<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: privsplt.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2006-07-21 13:58:33 $
 *
 *  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_sc.hxx"

#include "privsplt.hxx"

/*************************************************************************
#*  Member:     ScPrivatSplit                               Datum:13.10.97
#*------------------------------------------------------------------------
#*
#*  Klasse:     MD_Test
#*
#*  Funktion:   Konstruktor der Klasse ScPrivatSplit
#*
#*  Input:      ---
#*
#*  Output:     ---
#*
#************************************************************************/

ScPrivatSplit::ScPrivatSplit( Window* pParent, const ResId& rResId,
                             SC_SPLIT_DIRECTION eSplit):
                        Control( pParent, rResId )
{
    Point aPos=GetPosPixel();
    nOldX=(short)aPos.X();
    nOldY=(short)aPos.Y();
    nNewX=(short)aPos.X();
    nNewY=(short)aPos.Y();
    eScSplit=eSplit;
    aXMovingRange.Min()=nNewX;
    aXMovingRange.Max()=nNewX;
    aYMovingRange.Min()=nNewY;
    aYMovingRange.Max()=nNewY;

    aWinPointer=GetPointer();

    aMovingFlag=FALSE;
    if(eScSplit==SC_SPLIT_HORZ)
    {
        aWinPointer=Pointer(POINTER_HSPLIT);
    }
    else
    {
        aWinPointer=Pointer(POINTER_VSPLIT);
    }
    SetPointer(aWinPointer);
}

/*************************************************************************
#*  Member:     MouseButtonDown                         Datum:13.10.97
#*------------------------------------------------------------------------
#*
#*  Klasse:     ScPrivatSplit
#*
#*  Funktion:   Reagiert auf einen einzelnen Mouse-Event. Nach Aufruf
#*              werden alle Mauseingaben an dieses Control weitergeleitet.
#*
#*  Input:      ---
#*
#*  Output:     ---
#*
#************************************************************************/

void ScPrivatSplit::MouseButtonDown( const MouseEvent& rMEvt )
{
    Point aPos=LogicToPixel(rMEvt.GetPosPixel());

    nOldX=(short)aPos.X();
    nOldY=(short)aPos.Y();

    CaptureMouse();
}

/*************************************************************************
#*  Member:     MouseButtonUp                           Datum:13.10.97
#*------------------------------------------------------------------------
#*
#*  Klasse:     ScPrivatSplit
#*
#*  Funktion:   Ende einer Benutzeraktion mit der Maus. Es werden
#*              die aktuelle Maus- Koordinaten ermittelt und fuer
#*              die Verschiebung des Fensters verwendet.
#*
#*  Input:      ---
#*
#*  Output:     ---
#*
#************************************************************************/

void ScPrivatSplit::MouseButtonUp( const MouseEvent& rMEvt )
{
    ReleaseMouse();

    Point aPos=LogicToPixel(rMEvt.GetPosPixel());
    Point a2Pos=GetPosPixel();
    Point a3Pos=a2Pos;

    if(eScSplit==SC_SPLIT_HORZ)
    {
        nNewX=(short)aPos.X();
        nDeltaX=nNewX-nOldX;
        a2Pos.X()+=nDeltaX;
        if(a2Pos.X()<aXMovingRange.Min())
        {
            nDeltaX=(short)(aXMovingRange.Min()-a3Pos.X());
            a2Pos.X()=aXMovingRange.Min();
        }
        else if(a2Pos.X()>aXMovingRange.Max())
        {
            nDeltaX=(short)(aXMovingRange.Max()-a3Pos.X());
            a2Pos.X()=aXMovingRange.Max();
        }
    }
    else
    {
        nNewY=(short)aPos.Y();
        nDeltaY=nNewY-nOldY;
        a2Pos.Y()+=nDeltaY;
        if(a2Pos.Y()<aYMovingRange.Min())
        {
            nDeltaY=(short)(aYMovingRange.Min()-a3Pos.Y());
            a2Pos.Y()=aYMovingRange.Min();
        }
        else if(a2Pos.Y()>aYMovingRange.Max())
        {
            nDeltaY=(short)(aYMovingRange.Max()-a3Pos.Y());
            a2Pos.Y()=aYMovingRange.Max();
        }
    }
    SetPosPixel(a2Pos);
    Invalidate();
    Update();
    CtrModified();
}

/*************************************************************************
#*  Member:     MouseMove                                   Datum:13.10.97
#*------------------------------------------------------------------------
#*
#*  Klasse:     ScPrivatSplit
#*
#*  Funktion:   Reagiert kontinuierlich auf Mausbewegungen. Es werden
#*              die aktuelle Maus- Koordinaten ermittelt und fuer
#*              die Verschiebung des Fensters verwendet.
#*
#*  Input:      ---
#*
#*  Output:     ---
#*
#************************************************************************/

void ScPrivatSplit::MouseMove( const MouseEvent& rMEvt )
{
    Point aPos=LogicToPixel(rMEvt.GetPosPixel());
    Point a2Pos=GetPosPixel();
    Point a3Pos=a2Pos;
    if(rMEvt.IsLeft())
    {
        if(eScSplit==SC_SPLIT_HORZ)
        {
            nNewX=(short)aPos.X();
            nDeltaX=nNewX-nOldX;
            a2Pos.X()+=nDeltaX;

            if(a2Pos.X()<aXMovingRange.Min())
            {
                nDeltaX=(short)(aXMovingRange.Min()-a3Pos.X());
                a2Pos.X()=aXMovingRange.Min();
            }
            else if(a2Pos.X()>aXMovingRange.Max())
            {
                nDeltaX=(short)(aXMovingRange.Max()-a3Pos.X());
                a2Pos.X()=aXMovingRange.Max();
            }
        }
        else
        {
            nNewY=(short)aPos.Y();
            nDeltaY=nNewY-nOldY;
            a2Pos.Y()+=nDeltaY;
            if(a2Pos.Y()<aYMovingRange.Min())
            {
                nDeltaY=(short)(aYMovingRange.Min()-a3Pos.Y());
                a2Pos.Y()=aYMovingRange.Min();
            }
            else if(a2Pos.Y()>aYMovingRange.Max())
            {
                nDeltaY=(short)(aYMovingRange.Max()-a3Pos.Y());
                a2Pos.Y()=aYMovingRange.Max();
            }
        }

        SetPosPixel(a2Pos);

        CtrModified();
        Invalidate();
        Update();
    }
}

/*************************************************************************
#*  Member:     SetXRange                                   Datum:14.10.97
#*------------------------------------------------------------------------
#*
#*  Klasse:     ScPrivatSplit
#*
#*  Funktion:   Setzt den Range fuer die X- Verschiebung
#*
#*  Input:      neuer Bereich
#*
#*  Output:     ---
#*
#************************************************************************/
void ScPrivatSplit::SetXRange(Range cRgeX)
{
    aXMovingRange=cRgeX;
}

/*************************************************************************
#*  Member:     SetYRange                                   Datum:14.10.97
#*------------------------------------------------------------------------
#*
#*  Klasse:     ScPrivatSplit
#*
#*  Funktion:   Setzt den Range fuer die Y- Verschiebung
#*
#*  Input:      neuer Bereich
#*
#*  Output:     ---
#*
#************************************************************************/
void ScPrivatSplit::SetYRange(Range cRgeY)
{
    aYMovingRange=cRgeY;
}

/*************************************************************************
#*  Member:     GetDeltaY                                   Datum:13.10.97
#*------------------------------------------------------------------------
#*
#*  Klasse:     ScPrivatSplit
#*
#*  Funktion:   Liefert die relative x-Verschiebung zurueck
#*
#*  Input:      ---
#*
#*  Output:     ---
#*
#************************************************************************/
short ScPrivatSplit::GetDeltaX()
{
    return nDeltaX;
}

/*************************************************************************
#*  Member:     GetDeltaY                                   Datum:13.10.97
#*------------------------------------------------------------------------
#*
#*  Klasse:     ScPrivatSplit
#*
#*  Funktion:   Liefert die relative y-Verschiebung zurueck
#*
#*  Input:      ---
#*
#*  Output:     ---
#*
#************************************************************************/
short ScPrivatSplit::GetDeltaY()
{
    return nDeltaY;
}

/*************************************************************************
#*  Member:     CtrModified                                 Datum:13.10.97
#*------------------------------------------------------------------------
#*
#*  Klasse:     ScPrivatSplit
#*
#*  Funktion:   Teilt einem installierten Handler mit, dass
#*              eine Veraenderung eingetreten ist.
#*
#*  Input:      ---
#*
#*  Output:     ---
#*
#************************************************************************/
void ScPrivatSplit::CtrModified()
{
    aCtrModifiedLink.Call( this );
}

void ScPrivatSplit::MoveSplitTo(Point aPos)
{
    Point a2Pos=GetPosPixel();
    nOldX=(short)a2Pos.X();
    nOldY=(short)a2Pos.Y();
    Point a3Pos=a2Pos;

    if(eScSplit==SC_SPLIT_HORZ)
    {
        nNewX=(short)aPos.X();
        nDeltaX=nNewX-nOldX;
        a2Pos.X()+=nDeltaX;
        if(a2Pos.X()<aXMovingRange.Min())
        {
            nDeltaX=(short)(aXMovingRange.Min()-a3Pos.X());
            a2Pos.X()=aXMovingRange.Min();
        }
        else if(a2Pos.X()>aXMovingRange.Max())
        {
            nDeltaX=(short)(aXMovingRange.Max()-a3Pos.X());
            a2Pos.X()=aXMovingRange.Max();
        }
    }
    else
    {
        nNewY=(short)aPos.Y();
        nDeltaY=nNewY-nOldY;
        a2Pos.Y()+=nDeltaY;
        if(a2Pos.Y()<aYMovingRange.Min())
        {
            nDeltaY=(short)(aYMovingRange.Min()-a3Pos.Y());
            a2Pos.Y()=aYMovingRange.Min();
        }
        else if(a2Pos.Y()>aYMovingRange.Max())
        {
            nDeltaY=(short)(aYMovingRange.Max()-a3Pos.Y());
            a2Pos.Y()=aYMovingRange.Max();
        }
    }
    SetPosPixel(a2Pos);
    Invalidate();
    Update();
    CtrModified();
}

void ScPrivatSplit::ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground )
{
    const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings();

    if ( bFont )
    {
        Font aFont = rStyleSettings.GetAppFont();
        if ( IsControlFont() )
            aFont.Merge( GetControlFont() );
        SetFont( aFont );
    }

    if ( bFont || bForeground )
    {
        Color aTextColor = rStyleSettings.GetButtonTextColor();
        if ( IsControlForeground() )
            aTextColor = GetControlForeground();
        SetTextColor( aTextColor );
    }

    if ( bBackground )
    {
        SetBackground( rStyleSettings.GetFaceColor());
    }
    if ( IsBackground() )
    {
        SetFillColor( GetBackground().GetColor() );
        SetBackground();
    }
    Invalidate();
}

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

void ScPrivatSplit::StateChanged( StateChangedType nType )
{
    if ( (nType == STATE_CHANGE_ZOOM) ||
         (nType == STATE_CHANGE_CONTROLFONT) )
    {
        ImplInitSettings( TRUE, FALSE, FALSE );
        Invalidate();
    }
    if ( nType == STATE_CHANGE_CONTROLFOREGROUND )
    {
        ImplInitSettings( FALSE, TRUE, FALSE );
        Invalidate();
    }
    else if ( nType == STATE_CHANGE_CONTROLBACKGROUND )
    {
        ImplInitSettings( FALSE, FALSE, TRUE );
        Invalidate();
    }

    Control::StateChanged( nType );
}

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

void ScPrivatSplit::DataChanged( const DataChangedEvent& rDCEvt )
{
    if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) &&
         (rDCEvt.GetFlags() & SETTINGS_STYLE) )
    {
        ImplInitSettings( TRUE, TRUE, TRUE );
        Invalidate();
    }
    else
        Window::DataChanged( rDCEvt );
}

<commit_msg>INTEGRATION: CWS changefileheader (1.3.492); FILE MERGED 2008/03/31 17:15:37 rt 1.3.492.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: privsplt.cxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "privsplt.hxx"

/*************************************************************************
#*  Member:     ScPrivatSplit                               Datum:13.10.97
#*------------------------------------------------------------------------
#*
#*  Klasse:     MD_Test
#*
#*  Funktion:   Konstruktor der Klasse ScPrivatSplit
#*
#*  Input:      ---
#*
#*  Output:     ---
#*
#************************************************************************/

ScPrivatSplit::ScPrivatSplit( Window* pParent, const ResId& rResId,
                             SC_SPLIT_DIRECTION eSplit):
                        Control( pParent, rResId )
{
    Point aPos=GetPosPixel();
    nOldX=(short)aPos.X();
    nOldY=(short)aPos.Y();
    nNewX=(short)aPos.X();
    nNewY=(short)aPos.Y();
    eScSplit=eSplit;
    aXMovingRange.Min()=nNewX;
    aXMovingRange.Max()=nNewX;
    aYMovingRange.Min()=nNewY;
    aYMovingRange.Max()=nNewY;

    aWinPointer=GetPointer();

    aMovingFlag=FALSE;
    if(eScSplit==SC_SPLIT_HORZ)
    {
        aWinPointer=Pointer(POINTER_HSPLIT);
    }
    else
    {
        aWinPointer=Pointer(POINTER_VSPLIT);
    }
    SetPointer(aWinPointer);
}

/*************************************************************************
#*  Member:     MouseButtonDown                         Datum:13.10.97
#*------------------------------------------------------------------------
#*
#*  Klasse:     ScPrivatSplit
#*
#*  Funktion:   Reagiert auf einen einzelnen Mouse-Event. Nach Aufruf
#*              werden alle Mauseingaben an dieses Control weitergeleitet.
#*
#*  Input:      ---
#*
#*  Output:     ---
#*
#************************************************************************/

void ScPrivatSplit::MouseButtonDown( const MouseEvent& rMEvt )
{
    Point aPos=LogicToPixel(rMEvt.GetPosPixel());

    nOldX=(short)aPos.X();
    nOldY=(short)aPos.Y();

    CaptureMouse();
}

/*************************************************************************
#*  Member:     MouseButtonUp                           Datum:13.10.97
#*------------------------------------------------------------------------
#*
#*  Klasse:     ScPrivatSplit
#*
#*  Funktion:   Ende einer Benutzeraktion mit der Maus. Es werden
#*              die aktuelle Maus- Koordinaten ermittelt und fuer
#*              die Verschiebung des Fensters verwendet.
#*
#*  Input:      ---
#*
#*  Output:     ---
#*
#************************************************************************/

void ScPrivatSplit::MouseButtonUp( const MouseEvent& rMEvt )
{
    ReleaseMouse();

    Point aPos=LogicToPixel(rMEvt.GetPosPixel());
    Point a2Pos=GetPosPixel();
    Point a3Pos=a2Pos;

    if(eScSplit==SC_SPLIT_HORZ)
    {
        nNewX=(short)aPos.X();
        nDeltaX=nNewX-nOldX;
        a2Pos.X()+=nDeltaX;
        if(a2Pos.X()<aXMovingRange.Min())
        {
            nDeltaX=(short)(aXMovingRange.Min()-a3Pos.X());
            a2Pos.X()=aXMovingRange.Min();
        }
        else if(a2Pos.X()>aXMovingRange.Max())
        {
            nDeltaX=(short)(aXMovingRange.Max()-a3Pos.X());
            a2Pos.X()=aXMovingRange.Max();
        }
    }
    else
    {
        nNewY=(short)aPos.Y();
        nDeltaY=nNewY-nOldY;
        a2Pos.Y()+=nDeltaY;
        if(a2Pos.Y()<aYMovingRange.Min())
        {
            nDeltaY=(short)(aYMovingRange.Min()-a3Pos.Y());
            a2Pos.Y()=aYMovingRange.Min();
        }
        else if(a2Pos.Y()>aYMovingRange.Max())
        {
            nDeltaY=(short)(aYMovingRange.Max()-a3Pos.Y());
            a2Pos.Y()=aYMovingRange.Max();
        }
    }
    SetPosPixel(a2Pos);
    Invalidate();
    Update();
    CtrModified();
}

/*************************************************************************
#*  Member:     MouseMove                                   Datum:13.10.97
#*------------------------------------------------------------------------
#*
#*  Klasse:     ScPrivatSplit
#*
#*  Funktion:   Reagiert kontinuierlich auf Mausbewegungen. Es werden
#*              die aktuelle Maus- Koordinaten ermittelt und fuer
#*              die Verschiebung des Fensters verwendet.
#*
#*  Input:      ---
#*
#*  Output:     ---
#*
#************************************************************************/

void ScPrivatSplit::MouseMove( const MouseEvent& rMEvt )
{
    Point aPos=LogicToPixel(rMEvt.GetPosPixel());
    Point a2Pos=GetPosPixel();
    Point a3Pos=a2Pos;
    if(rMEvt.IsLeft())
    {
        if(eScSplit==SC_SPLIT_HORZ)
        {
            nNewX=(short)aPos.X();
            nDeltaX=nNewX-nOldX;
            a2Pos.X()+=nDeltaX;

            if(a2Pos.X()<aXMovingRange.Min())
            {
                nDeltaX=(short)(aXMovingRange.Min()-a3Pos.X());
                a2Pos.X()=aXMovingRange.Min();
            }
            else if(a2Pos.X()>aXMovingRange.Max())
            {
                nDeltaX=(short)(aXMovingRange.Max()-a3Pos.X());
                a2Pos.X()=aXMovingRange.Max();
            }
        }
        else
        {
            nNewY=(short)aPos.Y();
            nDeltaY=nNewY-nOldY;
            a2Pos.Y()+=nDeltaY;
            if(a2Pos.Y()<aYMovingRange.Min())
            {
                nDeltaY=(short)(aYMovingRange.Min()-a3Pos.Y());
                a2Pos.Y()=aYMovingRange.Min();
            }
            else if(a2Pos.Y()>aYMovingRange.Max())
            {
                nDeltaY=(short)(aYMovingRange.Max()-a3Pos.Y());
                a2Pos.Y()=aYMovingRange.Max();
            }
        }

        SetPosPixel(a2Pos);

        CtrModified();
        Invalidate();
        Update();
    }
}

/*************************************************************************
#*  Member:     SetXRange                                   Datum:14.10.97
#*------------------------------------------------------------------------
#*
#*  Klasse:     ScPrivatSplit
#*
#*  Funktion:   Setzt den Range fuer die X- Verschiebung
#*
#*  Input:      neuer Bereich
#*
#*  Output:     ---
#*
#************************************************************************/
void ScPrivatSplit::SetXRange(Range cRgeX)
{
    aXMovingRange=cRgeX;
}

/*************************************************************************
#*  Member:     SetYRange                                   Datum:14.10.97
#*------------------------------------------------------------------------
#*
#*  Klasse:     ScPrivatSplit
#*
#*  Funktion:   Setzt den Range fuer die Y- Verschiebung
#*
#*  Input:      neuer Bereich
#*
#*  Output:     ---
#*
#************************************************************************/
void ScPrivatSplit::SetYRange(Range cRgeY)
{
    aYMovingRange=cRgeY;
}

/*************************************************************************
#*  Member:     GetDeltaY                                   Datum:13.10.97
#*------------------------------------------------------------------------
#*
#*  Klasse:     ScPrivatSplit
#*
#*  Funktion:   Liefert die relative x-Verschiebung zurueck
#*
#*  Input:      ---
#*
#*  Output:     ---
#*
#************************************************************************/
short ScPrivatSplit::GetDeltaX()
{
    return nDeltaX;
}

/*************************************************************************
#*  Member:     GetDeltaY                                   Datum:13.10.97
#*------------------------------------------------------------------------
#*
#*  Klasse:     ScPrivatSplit
#*
#*  Funktion:   Liefert die relative y-Verschiebung zurueck
#*
#*  Input:      ---
#*
#*  Output:     ---
#*
#************************************************************************/
short ScPrivatSplit::GetDeltaY()
{
    return nDeltaY;
}

/*************************************************************************
#*  Member:     CtrModified                                 Datum:13.10.97
#*------------------------------------------------------------------------
#*
#*  Klasse:     ScPrivatSplit
#*
#*  Funktion:   Teilt einem installierten Handler mit, dass
#*              eine Veraenderung eingetreten ist.
#*
#*  Input:      ---
#*
#*  Output:     ---
#*
#************************************************************************/
void ScPrivatSplit::CtrModified()
{
    aCtrModifiedLink.Call( this );
}

void ScPrivatSplit::MoveSplitTo(Point aPos)
{
    Point a2Pos=GetPosPixel();
    nOldX=(short)a2Pos.X();
    nOldY=(short)a2Pos.Y();
    Point a3Pos=a2Pos;

    if(eScSplit==SC_SPLIT_HORZ)
    {
        nNewX=(short)aPos.X();
        nDeltaX=nNewX-nOldX;
        a2Pos.X()+=nDeltaX;
        if(a2Pos.X()<aXMovingRange.Min())
        {
            nDeltaX=(short)(aXMovingRange.Min()-a3Pos.X());
            a2Pos.X()=aXMovingRange.Min();
        }
        else if(a2Pos.X()>aXMovingRange.Max())
        {
            nDeltaX=(short)(aXMovingRange.Max()-a3Pos.X());
            a2Pos.X()=aXMovingRange.Max();
        }
    }
    else
    {
        nNewY=(short)aPos.Y();
        nDeltaY=nNewY-nOldY;
        a2Pos.Y()+=nDeltaY;
        if(a2Pos.Y()<aYMovingRange.Min())
        {
            nDeltaY=(short)(aYMovingRange.Min()-a3Pos.Y());
            a2Pos.Y()=aYMovingRange.Min();
        }
        else if(a2Pos.Y()>aYMovingRange.Max())
        {
            nDeltaY=(short)(aYMovingRange.Max()-a3Pos.Y());
            a2Pos.Y()=aYMovingRange.Max();
        }
    }
    SetPosPixel(a2Pos);
    Invalidate();
    Update();
    CtrModified();
}

void ScPrivatSplit::ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground )
{
    const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings();

    if ( bFont )
    {
        Font aFont = rStyleSettings.GetAppFont();
        if ( IsControlFont() )
            aFont.Merge( GetControlFont() );
        SetFont( aFont );
    }

    if ( bFont || bForeground )
    {
        Color aTextColor = rStyleSettings.GetButtonTextColor();
        if ( IsControlForeground() )
            aTextColor = GetControlForeground();
        SetTextColor( aTextColor );
    }

    if ( bBackground )
    {
        SetBackground( rStyleSettings.GetFaceColor());
    }
    if ( IsBackground() )
    {
        SetFillColor( GetBackground().GetColor() );
        SetBackground();
    }
    Invalidate();
}

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

void ScPrivatSplit::StateChanged( StateChangedType nType )
{
    if ( (nType == STATE_CHANGE_ZOOM) ||
         (nType == STATE_CHANGE_CONTROLFONT) )
    {
        ImplInitSettings( TRUE, FALSE, FALSE );
        Invalidate();
    }
    if ( nType == STATE_CHANGE_CONTROLFOREGROUND )
    {
        ImplInitSettings( FALSE, TRUE, FALSE );
        Invalidate();
    }
    else if ( nType == STATE_CHANGE_CONTROLBACKGROUND )
    {
        ImplInitSettings( FALSE, FALSE, TRUE );
        Invalidate();
    }

    Control::StateChanged( nType );
}

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

void ScPrivatSplit::DataChanged( const DataChangedEvent& rDCEvt )
{
    if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) &&
         (rDCEvt.GetFlags() & SETTINGS_STYLE) )
    {
        ImplInitSettings( TRUE, TRUE, TRUE );
        Invalidate();
    }
    else
        Window::DataChanged( rDCEvt );
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: warnbox.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: dr $ $Date: 2002-10-23 14:52: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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SC_WARNBOX_HXX
#include "warnbox.hxx"
#endif

#include "scmod.hxx"
#include "inputopt.hxx"
#include "scresid.hxx"
#include "sc.hrc"

// ============================================================================

ScCbWarningBox::ScCbWarningBox( Window* pParent, const String& rMsgStr, bool bDefYes ) :
    WarningBox( pParent, WB_YES_NO | (bDefYes ? WB_DEF_YES : WB_DEF_NO), rMsgStr )
{
    SetDefaultCheckBoxText();
}

sal_Int16 ScCbWarningBox::Execute()
{
    sal_Int16 nRet = (GetStyle() & WB_DEF_YES) ? RET_YES : RET_NO;
    if( IsDialogEnabled() )
    {
        nRet = WarningBox::Execute();
        if( GetCheckBoxState() )
            DisableDialog();
    }
    return nRet;
}

bool ScCbWarningBox::IsDialogEnabled()
{
    return true;
}

void ScCbWarningBox::DisableDialog()
{
}

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

ScReplaceWarnBox::ScReplaceWarnBox( Window* pParent ) :
    ScCbWarningBox( pParent, String( ScResId( STR_REPLCELLSWARN ) ), true )
{
    SetHelpId( HID_SC_REPLCELLSWARN );
}

bool ScReplaceWarnBox::IsDialogEnabled()
{
    return SC_MOD()->GetInputOptions().GetReplaceCellsWarn() == TRUE;
}

void ScReplaceWarnBox::DisableDialog()
{
    ScModule* pScMod = SC_MOD();
    ScInputOptions aInputOpt( pScMod->GetInputOptions() );
    aInputOpt.SetReplaceCellsWarn( FALSE );
    pScMod->SetInputOptions( aInputOpt );
}

// ============================================================================

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

#ifndef SC_WARNBOX_HXX
#include "warnbox.hxx"
#endif

#include "scmod.hxx"
#include "inputopt.hxx"
#include "scresid.hxx"
#include "sc.hrc"

// ============================================================================

ScCbWarningBox::ScCbWarningBox( Window* pParent, const String& rMsgStr, bool bDefYes ) :
    WarningBox( pParent, WB_YES_NO | (bDefYes ? WB_DEF_YES : WB_DEF_NO), rMsgStr )
{
    SetDefaultCheckBoxText();
}

sal_Int16 ScCbWarningBox::Execute()
{
    sal_Int16 nRet = (GetStyle() & WB_DEF_YES) ? RET_YES : RET_NO;
    if( IsDialogEnabled() )
    {
        nRet = WarningBox::Execute();
        if( GetCheckBoxState() )
            DisableDialog();
    }
    return nRet;
}

bool ScCbWarningBox::IsDialogEnabled()
{
    return true;
}

void ScCbWarningBox::DisableDialog()
{
}

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

ScReplaceWarnBox::ScReplaceWarnBox( Window* pParent ) :
    ScCbWarningBox( pParent, String( ScResId( STR_REPLCELLSWARN ) ), true )
{
    SetHelpId( HID_SC_REPLCELLSWARN );
}

bool ScReplaceWarnBox::IsDialogEnabled()
{
    return SC_MOD()->GetInputOptions().GetReplaceCellsWarn() == TRUE;
}

void ScReplaceWarnBox::DisableDialog()
{
    ScModule* pScMod = SC_MOD();
    ScInputOptions aInputOpt( pScMod->GetInputOptions() );
    aInputOpt.SetReplaceCellsWarn( FALSE );
    pScMod->SetInputOptions( aInputOpt );
}

// ============================================================================

<|endoftext|>


<commit_before><commit_msg>Add awesome algorithm MO'.<commit_after><|endoftext|>


<commit_before>// netfortune session
// Copyright © 2017 Christian Rapp

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

// This program 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 General Public License for more details.

// You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.

#ifndef FSESSION_HPP
#define FSESSION_HPP

#include <cassert>
#include <iostream>
#include <memory>

#include <boost/asio.hpp>

#include "spdlog/spdlog.h"

#include "fproto.hpp"

/**
 * @brief FSession class represents one TCP Connection from server to client
 * @detail
 * A session handels reading and writing from/to the client.
 * 1. Reading the first 6 Bytes to get the actual message length. Then read
 *    the rest.
 * 2. Parse the message with a json encoder and see if this is valid json
 * 3. Get the information we need from the client and prepare the answer
 *    accordingly
 *
 */
class FSession : public std::enable_shared_from_this<FSession>
{
public:
    explicit FSession(boost::asio::ip::tcp::socket socket);
    virtual ~FSession() = default;

    /**
     * @brief Start the reading on FSession::socket
     */
    void start();

private:
    std::vector<unsigned char>
        data_buf; /**< buffer containing the request and later the answer */
    const size_t max_buf_size = 2048;    /**< maximum data buffer size */
    boost::asio::ip::tcp::socket socket; /**< Socket this session uses */

    std::shared_ptr<spdlog::logger> logger;
    std::unique_ptr<Fproto> nfprot;

    void do_read();
    void do_write();
};

#endif /* FSESSION_HPP */
<commit_msg>Add fsession had also the wrong license<commit_after>// netfortune brings fortunes for everyone, everywhere
// Copyright © 2017 Christian Rapp
// 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. Neither the name of the organization nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.

// THIS SOFTWARE IS PROVIDED BY  ''AS IS'' AND ANY
// EXPRESS 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  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.

#ifndef FSESSION_HPP
#define FSESSION_HPP

#include <cassert>
#include <iostream>
#include <memory>

#include <boost/asio.hpp>

#include "spdlog/spdlog.h"

#include "fproto.hpp"

/**
 * @brief FSession class represents one TCP Connection from server to client
 * @detail
 * A session handels reading and writing from/to the client.
 * 1. Reading the first 6 Bytes to get the actual message length. Then read
 *    the rest.
 * 2. Parse the message with a json encoder and see if this is valid json
 * 3. Get the information we need from the client and prepare the answer
 *    accordingly
 *
 */
class FSession : public std::enable_shared_from_this<FSession>
{
public:
    explicit FSession(boost::asio::ip::tcp::socket socket);
    virtual ~FSession() = default;

    /**
     * @brief Start the reading on FSession::socket
     */
    void start();

private:
    std::vector<unsigned char>
        data_buf; /**< buffer containing the request and later the answer */
    const size_t max_buf_size = 2048;    /**< maximum data buffer size */
    boost::asio::ip::tcp::socket socket; /**< Socket this session uses */

    std::shared_ptr<spdlog::logger> logger;
    std::unique_ptr<Fproto> nfprot;

    void do_read();
    void do_write();
};

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


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

#pragma once

#include <utility>
#include "ct_string.hpp"
#include "ct_array.hpp"
#include "hash/fnv1a.hpp"

namespace neam::ct
{
  namespace details
  {
    template<typename TID, size_t... Idxs>
    constexpr std::array<char, sizeof...(Idxs) + 1> id_make_array(std::index_sequence<Idxs...>&&) { return {{TID::str[Idxs]..., '\0'}}; }

    template<typename TID, size_t Count = TID::size>
    constexpr auto id_make_array() { return id_make_array<TID>(std::make_index_sequence<Count>{}); }

    template<typename T>
    struct tid
    {
      static constexpr string type_name() noexcept
      {
        constexpr string s = { __PRETTY_FUNCTION__ };
        constexpr string t = s.pad(s.find("= ") + 2, neam::ct::strlen("]"));
        return t;
      }

      static constexpr const char* str = type_name().str;
      static constexpr size_t size = type_name().size;
    };
    template<auto V>
    struct vid
    {
      static constexpr string type_name() noexcept
      {
        constexpr string s = { __PRETTY_FUNCTION__ };
        constexpr string t = s.pad(s.find("= ") + 2, neam::ct::strlen("]"));
        return t;
      }

      static constexpr const char* str = type_name().str;
      static constexpr size_t size = type_name().size;
    };

    /// This class has for effect to reduce the size of the executable:
    /// it holds the name for a given type T, and only that name (no other irrelevant data).
    /// It will generate some type-info (the name of the type will be stored in the binary), if rtti is enabled.
    template<typename T>
    struct tholder { static constexpr auto name = details::id_make_array<details::tid<T>>(); };
    template<auto V>
    struct vholder { static constexpr auto name = details::id_make_array<details::vid<V>>(); };
  } // namespace details

  /// \brief The name of the type, as a constexpr string.
  template<typename T>
  static constexpr string type_name = { details::tholder<T>::name.data(), details::tholder<T>::name.size() - 1 };
  /// \brief The name of the decayed type, as a constexpr string.
  template<typename T>
  static constexpr string decayed_type_name = type_name<std::decay_t<T>>;

  /// \brief A string for the corresponding value
  template<auto V>
  static constexpr string value_name = { details::vholder<V>::name.data(), details::vholder<V>::name.size() - 1 };

  /// \brief A hash for the type. No uniqueness guaranteed.
  template<typename T>
  static constexpr auto type_hash = hash::fnv1a<64>(details::tholder<T>::name.data(), details::tholder<T>::name.size() - 1);
  /// \brief A hash for the decayed type. No uniqueness guaranteed.
  template<typename T>
  static constexpr auto decayed_type_hash = type_hash<std::decay_t<T>>;

  /// \brief A (gratuitous) hash for the corresponding value. No uniqueness guaranteed.
  template<auto V>
  static constexpr auto value_hash = hash::fnv1a<64>(details::vholder<V>::name.data(), details::vholder<V>::name.size() - 1);
} // namespace neam::ct

#ifdef NCT_TESTS
    static_assert(neam::ct::type_name<int> == neam::ct::string{"int"});
    static_assert(neam::ct::type_name<double> == neam::ct::string{"double"});
    static_assert(neam::ct::type_name<double[]> == neam::ct::string{"double []"});
    static_assert(neam::ct::type_name<neam::ct::string> == neam::ct::string{"neam::ct::string"});
#endif

<commit_msg>Fix compilation issue with newer gcc<commit_after>//
// file : type_id.hpp
// in : file:///home/tim/projects/ntools/type_id.hpp
//
// created by : Timothée Feuillet
// date: sam. avr. 28 18:58:38 2018 GMT-0400
//
//
// Copyright (c) 2018 Timothée Feuillet
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

#pragma once

#include <utility>
#include <array>
#include "ct_string.hpp"
#include "ct_array.hpp"
#include "hash/fnv1a.hpp"

namespace neam::ct
{
  namespace details
  {
    template<typename TID, size_t... Idxs>
    constexpr std::array<char, sizeof...(Idxs) + 1> id_make_array(std::index_sequence<Idxs...>&&) { return {{TID::str[Idxs]..., '\0'}}; }

    template<typename TID, size_t Count = TID::size>
    constexpr auto id_make_array() { return id_make_array<TID>(std::make_index_sequence<Count>{}); }

    template<typename T>
    struct tid
    {
      static constexpr string type_name() noexcept
      {
        constexpr string s = { __PRETTY_FUNCTION__ };
        constexpr string t = s.pad(s.find("= ") + 2, neam::ct::strlen("]"));
        return t;
      }

      static constexpr const char* str = type_name().str;
      static constexpr size_t size = type_name().size;
    };
    template<auto V>
    struct vid
    {
      static constexpr string type_name() noexcept
      {
        constexpr string s = { __PRETTY_FUNCTION__ };
        constexpr string t = s.pad(s.find("= ") + 2, neam::ct::strlen("]"));
        return t;
      }

      static constexpr const char* str = type_name().str;
      static constexpr size_t size = type_name().size;
    };

    /// This class has for effect to reduce the size of the executable:
    /// it holds the name for a given type T, and only that name (no other irrelevant data).
    /// It will generate some type-info (the name of the type will be stored in the binary), if rtti is enabled.
    template<typename T>
    struct tholder { static constexpr auto name = details::id_make_array<details::tid<T>>(); };
    template<auto V>
    struct vholder { static constexpr auto name = details::id_make_array<details::vid<V>>(); };
  } // namespace details

  /// \brief The name of the type, as a constexpr string.
  template<typename T>
  static constexpr string type_name = { details::tholder<T>::name.data(), details::tholder<T>::name.size() - 1 };
  /// \brief The name of the decayed type, as a constexpr string.
  template<typename T>
  static constexpr string decayed_type_name = type_name<std::decay_t<T>>;

  /// \brief A string for the corresponding value
  template<auto V>
  static constexpr string value_name = { details::vholder<V>::name.data(), details::vholder<V>::name.size() - 1 };

  /// \brief A hash for the type. No uniqueness guaranteed.
  template<typename T>
  static constexpr auto type_hash = hash::fnv1a<64>(details::tholder<T>::name.data(), details::tholder<T>::name.size() - 1);
  /// \brief A hash for the decayed type. No uniqueness guaranteed.
  template<typename T>
  static constexpr auto decayed_type_hash = type_hash<std::decay_t<T>>;

  /// \brief A (gratuitous) hash for the corresponding value. No uniqueness guaranteed.
  template<auto V>
  static constexpr auto value_hash = hash::fnv1a<64>(details::vholder<V>::name.data(), details::vholder<V>::name.size() - 1);
} // namespace neam::ct

#ifdef NCT_TESTS
    static_assert(neam::ct::type_name<int> == neam::ct::string{"int"});
    static_assert(neam::ct::type_name<double> == neam::ct::string{"double"});
    static_assert(neam::ct::type_name<double[]> == neam::ct::string{"double []"});
    static_assert(neam::ct::type_name<neam::ct::string> == neam::ct::string{"neam::ct::string"});
#endif

<|endoftext|>


<commit_before>#include "Debugger.Process.h"

namespace GleeBug
{
    bool Process::SetBreakpoint(ptr address, bool singleshoot, SoftwareType type)
    {
        //check the address
        if(!MemIsValidPtr(address) ||
                breakpoints.find({ BreakpointType::Software, address }) != breakpoints.end())
            return false;

        //setup the breakpoint information struct
        BreakpointInfo info = {};
        info.address = address;
        info.singleshoot = singleshoot;
        info.type = BreakpointType::Software;

        //determine breakpoint byte and size from the type
        switch(type)
        {
        case SoftwareType::ShortInt3:
            info.internal.software.newbytes[0] = 0xCC;
            info.internal.software.size = 1;
            break;

        default:
            return false;
        }

        //read/write the breakpoint
        if(!MemReadUnsafe(address, info.internal.software.oldbytes, info.internal.software.size))
            return false;

        if(!MemWriteUnsafe(address, info.internal.software.newbytes, info.internal.software.size))
            return false;
        FlushInstructionCache(hProcess, nullptr, 0);

        //insert in the breakpoint map
        auto itr = breakpoints.insert({ { info.type, info.address }, info });
        softwareBreakpointReferences[info.address] = itr.first;

        return true;
    }

    bool Process::SetBreakpoint(ptr address, const BreakpointCallback & cbBreakpoint, bool singleshoot, SoftwareType type)
    {
        //check if a callback on this address was already found
        if(breakpointCallbacks.find({ BreakpointType::Software, address }) != breakpointCallbacks.end())
            return false;
        //set the breakpoint
        if(!SetBreakpoint(address, singleshoot, type))
            return false;
        //insert the callback
        breakpointCallbacks.insert({ { BreakpointType::Software, address }, cbBreakpoint });
        return true;
    }

    bool Process::DeleteBreakpoint(ptr address)
    {
        //find the breakpoint
        auto found = breakpoints.find({ BreakpointType::Software, address });
        if(found == breakpoints.end())
            return false;
        const auto & info = found->second;

        //restore the breakpoint bytes
        if(!MemWriteUnsafe(address, info.internal.software.oldbytes, info.internal.software.size))
            return false;
        FlushInstructionCache(hProcess, nullptr, 0);

        //remove the breakpoint from the maps
        softwareBreakpointReferences.erase(info.address);
        breakpoints.erase(found);
        breakpointCallbacks.erase({ BreakpointType::Software, address });
        return true;
    }

    bool Process::GetFreeHardwareBreakpointSlot(HardwareSlot & slot) const
    {
        //find a free hardware breakpoint slot
        for(int i = 0; i < HWBP_COUNT; i++)
        {
            if(!hardwareBreakpoints[i].internal.hardware.enabled)
            {
                slot = HardwareSlot(i);
                return true;
            }
        }
        return false;
    }

    bool Process::SetHardwareBreakpoint(ptr address, HardwareSlot slot, HardwareType type, HardwareSize size, bool singleshoot)
    {
        //check the address
        if(!MemIsValidPtr(address) ||
                breakpoints.find({ BreakpointType::Hardware, address }) != breakpoints.end())
            return false;

        //attempt to set the hardware breakpoint in every thread
        bool success = true;
        for(auto & thread : threads)
        {
            if(!thread.second->SetHardwareBreakpoint(address, slot, type, size))
            {
                success = false;
                break;
            }
        }

        //if setting failed, unset all
        if(!success)
        {
            for(auto & thread : threads)
                thread.second->DeleteHardwareBreakpoint(slot);
            return false;
        }

        //setup the breakpoint information struct
        BreakpointInfo info = {};
        info.address = address;
        info.singleshoot = singleshoot;
        info.type = BreakpointType::Hardware;
        info.internal.hardware.slot = slot;
        info.internal.hardware.type = type;
        info.internal.hardware.size = size;
        info.internal.hardware.enabled = true;

        //insert in the breakpoint map
        breakpoints.insert({ { info.type, info.address }, info });

        //insert in the hardware breakpoint cache
        hardwareBreakpoints[int(slot)] = info;

        return true;
    }

    bool Process::SetHardwareBreakpoint(ptr address, HardwareSlot slot, const BreakpointCallback & cbBreakpoint, HardwareType type, HardwareSize size, bool singleshoot)
    {
        //check if a callback on this address was already found
        if(breakpointCallbacks.find({ BreakpointType::Hardware, address }) != breakpointCallbacks.end())
            return false;
        //set the hardware breakpoint
        if(!SetHardwareBreakpoint(address, slot, type, size, singleshoot))
            return false;
        //insert the callback
        breakpointCallbacks.insert({ { BreakpointType::Hardware, address }, cbBreakpoint });
        return true;
    }

    bool Process::DeleteHardwareBreakpoint(ptr address)
    {
        //find the hardware breakpoint
        auto found = breakpoints.find({ BreakpointType::Hardware, address });
        if(found == breakpoints.end())
            return false;
        const auto & info = found->second;

        //delete the hardware breakpoint from the internal buffer
        hardwareBreakpoints[int(info.internal.hardware.slot)].internal.hardware.enabled = false;

        //delete the hardware breakpoint from the registers
        bool success = true;
        for(auto & thread : threads)
        {
            if(!thread.second->DeleteHardwareBreakpoint(info.internal.hardware.slot))
                success = false;
        }

        //delete the breakpoint from the maps
        breakpoints.erase(found);
        breakpointCallbacks.erase({ BreakpointType::Hardware, address });
        return success;
    }

#define PAGE_SHIFT              (12)
#define PAGE_ALIGN(Va)          ((ULONG_PTR)((ULONG_PTR)(Va) & ~(PAGE_SIZE - 1)))
#define BYTES_TO_PAGES(Size)    (((Size) >> PAGE_SHIFT) + (((Size) & (PAGE_SIZE - 1)) != 0))
#define ROUND_TO_PAGES(Size)    (((ULONG_PTR)(Size) + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1))

    /*
    #define PAGE_NOACCESS          0x01
    #define PAGE_READONLY          0x02
    #define PAGE_READWRITE         0x04
    #define PAGE_WRITECOPY         0x08 <- not supported

    #define PAGE_EXECUTE           0x10
    #define PAGE_EXECUTE_READ      0x20
    #define PAGE_EXECUTE_READWRITE 0x40
    #define PAGE_EXECUTE_WRITECOPY 0x80 <- not supported

    #define PAGE_GUARD            0x100 <- not supported with PAGE_NOACCESS
    #define PAGE_NOCACHE          0x200 <- not supported with PAGE_GUARD or PAGE_WRITECOMBINE
    #define PAGE_WRITECOMBINE     0x400 <- not supported with PAGE_GUARD or PAGE_NOCACHE
    */

    static DWORD RemoveExecuteAccess(DWORD dwAccess)
    {
        //These settings can trigger access violation.
        DWORD dwBase = dwAccess & 0xFF;
        DWORD dwHigh = dwAccess & 0xFFFFFF00;
        switch(dwBase)
        {
        case PAGE_EXECUTE:
            return dwHigh | PAGE_READONLY;
        case PAGE_EXECUTE_READ:
        case PAGE_EXECUTE_READWRITE:
        case PAGE_EXECUTE_WRITECOPY:
            return dwHigh | (dwBase >> 4); //This removes execute in deed; https://msdn.microsoft.com/en-us/library/windows/desktop/aa366786(v=vs.85).aspx - 0x1337 tricks
        default:
            return dwAccess;
        }
    }

    static DWORD RemoveWriteAccess(DWORD dwAccess)
    {
        DWORD dwBase = dwAccess & 0xFF;
        switch(dwBase)
        {
        case PAGE_READWRITE:
        case PAGE_EXECUTE_READWRITE:
            return (dwAccess & 0xFFFFFF00) | (dwBase >> 1);
        default:
            return dwAccess;
        }
    }

    bool Process::SetNewPageProtection(ptr page, MemoryBreakpointData & data, MemoryType type)
    {
        DPRINTF();
        //TODO: handle PAGE_NOACCESS and such correctly (since it cannot be combined with PAGE_GUARD)

        auto found = memoryBreakpointPages.find(page);
        if(found == memoryBreakpointPages.end())
        {
            data.Refcount = 1;
            switch(type)
            {
            case MemoryType::Access:
            case MemoryType::Read:
                data.NewProtect = data.OldProtect | PAGE_GUARD;
                break;
            case MemoryType::Write:
                data.NewProtect = RemoveWriteAccess(data.OldProtect);
                break;
            case MemoryType::Execute:
                data.NewProtect = permanentDep ? RemoveExecuteAccess(data.OldProtect) : data.OldProtect | PAGE_GUARD;
                break;
            }
        }
        else
        {
            auto & oldData = found->second;
            data.Type = oldData.Type | uint32(type); //combines new protection
            data.OldProtect = oldData.OldProtect; // old protection remains the same
            data.Refcount = oldData.Refcount + 1; //increment reference count
            if(oldData.Type == uint32(type))  // Edge case for when you need to set a mem bpx on a same page with the same type, you just leave newProtect = OldProtect.
            {
                data.NewProtect = data.OldProtect;
            }
            else if(data.Type & uint32(MemoryType::Access) || data.Type & uint32(MemoryType::Read))  // Access/Read always becomes PAGE_GUARD ; This page cannot access or Read?
                data.NewProtect = data.OldProtect | PAGE_GUARD; //as before
            else if(data.Type & (uint32(MemoryType::Write) | uint32(MemoryType::Execute)))  // Write + Execute becomes either PAGE_GUARD or both write and execute flags removed
                data.NewProtect = permanentDep ? RemoveExecuteAccess(RemoveWriteAccess(data.OldProtect)) : data.OldProtect | PAGE_GUARD;
        }

        dprintf("SetNewPageProtection(%p, %X)\n", page, data.NewProtect);
        return MemProtect(page, PAGE_SIZE, data.NewProtect);
    }

    bool Process::SetMemoryBreakpoint(ptr address, ptr size, MemoryType type, bool singleshoot)
    {
        DPRINTF();
        dprintf("SetMemoryBreakpoint(%p, %p, %d, %d)\n", address, size, type, singleshoot);
        //TODO: error reporting

        //basic checks
        if(!MemIsValidPtr(address) || !size)
            return false;

        //check if the range is unused for any previous memory breakpoints
        auto range = Range(address, address + size - 1);
        if(memoryBreakpointRanges.find(range) != memoryBreakpointRanges.end())
            return false;

        //change page protections
        bool success = true;
        struct TempMemoryBreakpointData
        {
            ptr addr;
            DWORD OldProtect;
            MemoryBreakpointData data;
        };
        std::vector<TempMemoryBreakpointData> breakpointData;
        {
            breakpointData.reserve(size / PAGE_SIZE);
            TempMemoryBreakpointData tempData;
            MemoryBreakpointData data;
            data.Type = uint32(type);
            auto alignedAddress = PAGE_ALIGN(address);
            for(auto page = alignedAddress; page < alignedAddress + ROUND_TO_PAGES(size); page += PAGE_SIZE)
            {
                MEMORY_BASIC_INFORMATION mbi;
                if(!VirtualQueryEx(hProcess, LPCVOID(page), &mbi, sizeof(mbi)))
                {
                    success = false;
                    dprintf("!VirtualQueryEx\n");
                    break;
                }
                data.OldProtect = mbi.Protect;
                if(!SetNewPageProtection(page, data, type))
                {
                    success = false;
                    dprintf("!SetNewPageProtection\n");
                    break;
                }
                tempData.addr = page;
                tempData.OldProtect = mbi.Protect;
                tempData.data = data;
                breakpointData.push_back(tempData);
            }
        }

        //if changing the page protections failed, attempt to revert all protection changes
        if(!success)
        {
            for(const auto & page : breakpointData)
                MemProtect(page.addr, PAGE_SIZE, page.OldProtect);
            return false;
        }

        //set the page data
        for(const auto & page : breakpointData)
            memoryBreakpointPages[page.addr] = page.data;

        //setup the breakpoint information struct
        BreakpointInfo info = {};
        info.address = address;
        info.singleshoot = singleshoot;
        info.type = BreakpointType::Memory;
        info.internal.memory.type = type;
        info.internal.memory.size = size;

        //insert in the breakpoint map
        breakpoints.insert({ { info.type, info.address }, info });
        memoryBreakpointRanges.insert(range);

        return true;
    }

    bool Process::SetMemoryBreakpoint(ptr address, ptr size, const BreakpointCallback & cbBreakpoint, MemoryType type, bool singleshoot)
    {
        //check if a callback on this address was already found
        if(breakpointCallbacks.find({ BreakpointType::Memory, address }) != breakpointCallbacks.end())
            return false;
        //set the memory breakpoint
        if(!SetMemoryBreakpoint(address, size, type, singleshoot))
            return false;
        //insert the callback
        breakpointCallbacks.insert({ { BreakpointType::Memory, address }, cbBreakpoint });
        return true;
    }

    bool Process::DeleteMemoryBreakpoint(ptr address)
    {
        //find the memory breakpoint range
        auto range = memoryBreakpointRanges.find(Range(address, address));
        if(range == memoryBreakpointRanges.end())
            return false;

        //find the memory breakpoint
        auto found = breakpoints.find({ BreakpointType::Memory, range->first });
        if(found == breakpoints.end())
            return false;
        const auto & info = found->second;

        //delete the memory breakpoint from the pages
        bool success = true;
        auto alignedAddress = PAGE_ALIGN(info.address);
        for(auto page = alignedAddress; page < alignedAddress + ROUND_TO_PAGES(info.internal.memory.size); page += PAGE_SIZE)
        {
            auto foundData = memoryBreakpointPages.find(page);
            if(foundData == memoryBreakpointPages.end())
                continue; //TODO: error reporting
            auto & data = foundData->second;
            DWORD Protect;
            data.Refcount--;
            if(data.Refcount)
            {
                //TODO: properly determine the new protection flag
                //Are there any other protections left?
                //If so add the guard
                if(data.Type & ~uint32(info.internal.memory.type))
                    data.NewProtect = data.OldProtect | PAGE_GUARD;
                Protect = data.NewProtect;
            }
            else
                Protect = data.OldProtect;
            if(!MemProtect(page, PAGE_SIZE, Protect))
                success = false;
            if(!data.Refcount)
                memoryBreakpointPages.erase(foundData);
        }

        //delete the breakpoint from the maps
        breakpoints.erase(found);
        breakpointCallbacks.erase({ BreakpointType::Hardware, address });
        memoryBreakpointRanges.erase(Range(address, address));
        return success;
    }

    bool Process::DeleteGenericBreakpoint(const BreakpointInfo & info)
    {
        switch(info.type)
        {
        case BreakpointType::Software:
            return DeleteBreakpoint(info.address);
        case BreakpointType::Hardware:
            return DeleteHardwareBreakpoint(info.address);
        case BreakpointType::Memory:
            return DeleteMemoryBreakpoint(info.address);
        default:
            return false;
        }
    }
};<commit_msg>Fix incorrect type<commit_after>#include "Debugger.Process.h"

namespace GleeBug
{
    bool Process::SetBreakpoint(ptr address, bool singleshoot, SoftwareType type)
    {
        //check the address
        if(!MemIsValidPtr(address) ||
                breakpoints.find({ BreakpointType::Software, address }) != breakpoints.end())
            return false;

        //setup the breakpoint information struct
        BreakpointInfo info = {};
        info.address = address;
        info.singleshoot = singleshoot;
        info.type = BreakpointType::Software;

        //determine breakpoint byte and size from the type
        switch(type)
        {
        case SoftwareType::ShortInt3:
            info.internal.software.newbytes[0] = 0xCC;
            info.internal.software.size = 1;
            break;

        default:
            return false;
        }

        //read/write the breakpoint
        if(!MemReadUnsafe(address, info.internal.software.oldbytes, info.internal.software.size))
            return false;

        if(!MemWriteUnsafe(address, info.internal.software.newbytes, info.internal.software.size))
            return false;
        FlushInstructionCache(hProcess, nullptr, 0);

        //insert in the breakpoint map
        auto itr = breakpoints.insert({ { info.type, info.address }, info });
        softwareBreakpointReferences[info.address] = itr.first;

        return true;
    }

    bool Process::SetBreakpoint(ptr address, const BreakpointCallback & cbBreakpoint, bool singleshoot, SoftwareType type)
    {
        //check if a callback on this address was already found
        if(breakpointCallbacks.find({ BreakpointType::Software, address }) != breakpointCallbacks.end())
            return false;
        //set the breakpoint
        if(!SetBreakpoint(address, singleshoot, type))
            return false;
        //insert the callback
        breakpointCallbacks.insert({ { BreakpointType::Software, address }, cbBreakpoint });
        return true;
    }

    bool Process::DeleteBreakpoint(ptr address)
    {
        //find the breakpoint
        auto found = breakpoints.find({ BreakpointType::Software, address });
        if(found == breakpoints.end())
            return false;
        const auto & info = found->second;

        //restore the breakpoint bytes
        if(!MemWriteUnsafe(address, info.internal.software.oldbytes, info.internal.software.size))
            return false;
        FlushInstructionCache(hProcess, nullptr, 0);

        //remove the breakpoint from the maps
        softwareBreakpointReferences.erase(info.address);
        breakpoints.erase(found);
        breakpointCallbacks.erase({ BreakpointType::Software, address });
        return true;
    }

    bool Process::GetFreeHardwareBreakpointSlot(HardwareSlot & slot) const
    {
        //find a free hardware breakpoint slot
        for(int i = 0; i < HWBP_COUNT; i++)
        {
            if(!hardwareBreakpoints[i].internal.hardware.enabled)
            {
                slot = HardwareSlot(i);
                return true;
            }
        }
        return false;
    }

    bool Process::SetHardwareBreakpoint(ptr address, HardwareSlot slot, HardwareType type, HardwareSize size, bool singleshoot)
    {
        //check the address
        if(!MemIsValidPtr(address) ||
                breakpoints.find({ BreakpointType::Hardware, address }) != breakpoints.end())
            return false;

        //attempt to set the hardware breakpoint in every thread
        bool success = true;
        for(auto & thread : threads)
        {
            if(!thread.second->SetHardwareBreakpoint(address, slot, type, size))
            {
                success = false;
                break;
            }
        }

        //if setting failed, unset all
        if(!success)
        {
            for(auto & thread : threads)
                thread.second->DeleteHardwareBreakpoint(slot);
            return false;
        }

        //setup the breakpoint information struct
        BreakpointInfo info = {};
        info.address = address;
        info.singleshoot = singleshoot;
        info.type = BreakpointType::Hardware;
        info.internal.hardware.slot = slot;
        info.internal.hardware.type = type;
        info.internal.hardware.size = size;
        info.internal.hardware.enabled = true;

        //insert in the breakpoint map
        breakpoints.insert({ { info.type, info.address }, info });

        //insert in the hardware breakpoint cache
        hardwareBreakpoints[int(slot)] = info;

        return true;
    }

    bool Process::SetHardwareBreakpoint(ptr address, HardwareSlot slot, const BreakpointCallback & cbBreakpoint, HardwareType type, HardwareSize size, bool singleshoot)
    {
        //check if a callback on this address was already found
        if(breakpointCallbacks.find({ BreakpointType::Hardware, address }) != breakpointCallbacks.end())
            return false;
        //set the hardware breakpoint
        if(!SetHardwareBreakpoint(address, slot, type, size, singleshoot))
            return false;
        //insert the callback
        breakpointCallbacks.insert({ { BreakpointType::Hardware, address }, cbBreakpoint });
        return true;
    }

    bool Process::DeleteHardwareBreakpoint(ptr address)
    {
        //find the hardware breakpoint
        auto found = breakpoints.find({ BreakpointType::Hardware, address });
        if(found == breakpoints.end())
            return false;
        const auto & info = found->second;

        //delete the hardware breakpoint from the internal buffer
        hardwareBreakpoints[int(info.internal.hardware.slot)].internal.hardware.enabled = false;

        //delete the hardware breakpoint from the registers
        bool success = true;
        for(auto & thread : threads)
        {
            if(!thread.second->DeleteHardwareBreakpoint(info.internal.hardware.slot))
                success = false;
        }

        //delete the breakpoint from the maps
        breakpoints.erase(found);
        breakpointCallbacks.erase({ BreakpointType::Hardware, address });
        return success;
    }

#define PAGE_SHIFT              (12)
#define PAGE_ALIGN(Va)          ((ULONG_PTR)((ULONG_PTR)(Va) & ~(PAGE_SIZE - 1)))
#define BYTES_TO_PAGES(Size)    (((Size) >> PAGE_SHIFT) + (((Size) & (PAGE_SIZE - 1)) != 0))
#define ROUND_TO_PAGES(Size)    (((ULONG_PTR)(Size) + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1))

    /*
    #define PAGE_NOACCESS          0x01
    #define PAGE_READONLY          0x02
    #define PAGE_READWRITE         0x04
    #define PAGE_WRITECOPY         0x08 <- not supported

    #define PAGE_EXECUTE           0x10
    #define PAGE_EXECUTE_READ      0x20
    #define PAGE_EXECUTE_READWRITE 0x40
    #define PAGE_EXECUTE_WRITECOPY 0x80 <- not supported

    #define PAGE_GUARD            0x100 <- not supported with PAGE_NOACCESS
    #define PAGE_NOCACHE          0x200 <- not supported with PAGE_GUARD or PAGE_WRITECOMBINE
    #define PAGE_WRITECOMBINE     0x400 <- not supported with PAGE_GUARD or PAGE_NOCACHE
    */

    static DWORD RemoveExecuteAccess(DWORD dwAccess)
    {
        //These settings can trigger access violation.
        DWORD dwBase = dwAccess & 0xFF;
        DWORD dwHigh = dwAccess & 0xFFFFFF00;
        switch(dwBase)
        {
        case PAGE_EXECUTE:
            return dwHigh | PAGE_READONLY;
        case PAGE_EXECUTE_READ:
        case PAGE_EXECUTE_READWRITE:
        case PAGE_EXECUTE_WRITECOPY:
            return dwHigh | (dwBase >> 4); //This removes execute in deed; https://msdn.microsoft.com/en-us/library/windows/desktop/aa366786(v=vs.85).aspx - 0x1337 tricks
        default:
            return dwAccess;
        }
    }

    static DWORD RemoveWriteAccess(DWORD dwAccess)
    {
        DWORD dwBase = dwAccess & 0xFF;
        switch(dwBase)
        {
        case PAGE_READWRITE:
        case PAGE_EXECUTE_READWRITE:
            return (dwAccess & 0xFFFFFF00) | (dwBase >> 1);
        default:
            return dwAccess;
        }
    }

    bool Process::SetNewPageProtection(ptr page, MemoryBreakpointData & data, MemoryType type)
    {
        DPRINTF();
        //TODO: handle PAGE_NOACCESS and such correctly (since it cannot be combined with PAGE_GUARD)

        auto found = memoryBreakpointPages.find(page);
        if(found == memoryBreakpointPages.end())
        {
            data.Refcount = 1;
            switch(type)
            {
            case MemoryType::Access:
            case MemoryType::Read:
                data.NewProtect = data.OldProtect | PAGE_GUARD;
                break;
            case MemoryType::Write:
                data.NewProtect = RemoveWriteAccess(data.OldProtect);
                break;
            case MemoryType::Execute:
                data.NewProtect = permanentDep ? RemoveExecuteAccess(data.OldProtect) : data.OldProtect | PAGE_GUARD;
                break;
            }
        }
        else
        {
            auto & oldData = found->second;
            data.Type = oldData.Type | uint32(type); //combines new protection
            data.OldProtect = oldData.OldProtect; // old protection remains the same
            data.Refcount = oldData.Refcount + 1; //increment reference count
            if(oldData.Type == uint32(type))  // Edge case for when you need to set a mem bpx on a same page with the same type, you just leave newProtect = OldProtect.
            {
                data.NewProtect = data.OldProtect;
            }
            else if(data.Type & uint32(MemoryType::Access) || data.Type & uint32(MemoryType::Read))  // Access/Read always becomes PAGE_GUARD ; This page cannot access or Read?
                data.NewProtect = data.OldProtect | PAGE_GUARD; //as before
            else if(data.Type & (uint32(MemoryType::Write) | uint32(MemoryType::Execute)))  // Write + Execute becomes either PAGE_GUARD or both write and execute flags removed
                data.NewProtect = permanentDep ? RemoveExecuteAccess(RemoveWriteAccess(data.OldProtect)) : data.OldProtect | PAGE_GUARD;
        }

        dprintf("SetNewPageProtection(%p, %X)\n", page, data.NewProtect);
        return MemProtect(page, PAGE_SIZE, data.NewProtect);
    }

    bool Process::SetMemoryBreakpoint(ptr address, ptr size, MemoryType type, bool singleshoot)
    {
        DPRINTF();
        dprintf("SetMemoryBreakpoint(%p, %p, %d, %d)\n", address, size, type, singleshoot);
        //TODO: error reporting

        //basic checks
        if(!MemIsValidPtr(address) || !size)
            return false;

        //check if the range is unused for any previous memory breakpoints
        auto range = Range(address, address + size - 1);
        if(memoryBreakpointRanges.find(range) != memoryBreakpointRanges.end())
            return false;

        //change page protections
        bool success = true;
        struct TempMemoryBreakpointData
        {
            ptr addr;
            DWORD OldProtect;
            MemoryBreakpointData data;
        };
        std::vector<TempMemoryBreakpointData> breakpointData;
        {
            breakpointData.reserve(size / PAGE_SIZE);
            TempMemoryBreakpointData tempData;
            MemoryBreakpointData data;
            data.Type = uint32(type);
            auto alignedAddress = PAGE_ALIGN(address);
            for(auto page = alignedAddress; page < alignedAddress + ROUND_TO_PAGES(size); page += PAGE_SIZE)
            {
                MEMORY_BASIC_INFORMATION mbi;
                if(!VirtualQueryEx(hProcess, LPCVOID(page), &mbi, sizeof(mbi)))
                {
                    success = false;
                    dprintf("!VirtualQueryEx\n");
                    break;
                }
                data.OldProtect = mbi.Protect;
                if(!SetNewPageProtection(page, data, type))
                {
                    success = false;
                    dprintf("!SetNewPageProtection\n");
                    break;
                }
                tempData.addr = page;
                tempData.OldProtect = mbi.Protect;
                tempData.data = data;
                breakpointData.push_back(tempData);
            }
        }

        //if changing the page protections failed, attempt to revert all protection changes
        if(!success)
        {
            for(const auto & page : breakpointData)
                MemProtect(page.addr, PAGE_SIZE, page.OldProtect);
            return false;
        }

        //set the page data
        for(const auto & page : breakpointData)
            memoryBreakpointPages[page.addr] = page.data;

        //setup the breakpoint information struct
        BreakpointInfo info = {};
        info.address = address;
        info.singleshoot = singleshoot;
        info.type = BreakpointType::Memory;
        info.internal.memory.type = type;
        info.internal.memory.size = size;

        //insert in the breakpoint map
        breakpoints.insert({ { info.type, info.address }, info });
        memoryBreakpointRanges.insert(range);

        return true;
    }

    bool Process::SetMemoryBreakpoint(ptr address, ptr size, const BreakpointCallback & cbBreakpoint, MemoryType type, bool singleshoot)
    {
        //check if a callback on this address was already found
        if(breakpointCallbacks.find({ BreakpointType::Memory, address }) != breakpointCallbacks.end())
            return false;
        //set the memory breakpoint
        if(!SetMemoryBreakpoint(address, size, type, singleshoot))
            return false;
        //insert the callback
        breakpointCallbacks.insert({ { BreakpointType::Memory, address }, cbBreakpoint });
        return true;
    }

    bool Process::DeleteMemoryBreakpoint(ptr address)
    {
        //find the memory breakpoint range
        auto range = memoryBreakpointRanges.find(Range(address, address));
        if(range == memoryBreakpointRanges.end())
            return false;

        //find the memory breakpoint
        auto found = breakpoints.find({ BreakpointType::Memory, range->first });
        if(found == breakpoints.end())
            return false;
        const auto & info = found->second;

        //delete the memory breakpoint from the pages
        bool success = true;
        auto alignedAddress = PAGE_ALIGN(info.address);
        for(auto page = alignedAddress; page < alignedAddress + ROUND_TO_PAGES(info.internal.memory.size); page += PAGE_SIZE)
        {
            auto foundData = memoryBreakpointPages.find(page);
            if(foundData == memoryBreakpointPages.end())
                continue; //TODO: error reporting
            auto & data = foundData->second;
            DWORD Protect;
            data.Refcount--;
            if(data.Refcount)
            {
                //TODO: properly determine the new protection flag
                //Are there any other protections left?
                //If so add the guard
                if(data.Type & ~uint32(info.internal.memory.type))
                    data.NewProtect = data.OldProtect | PAGE_GUARD;
                Protect = data.NewProtect;
            }
            else
                Protect = data.OldProtect;
            if(!MemProtect(page, PAGE_SIZE, Protect))
                success = false;
            if(!data.Refcount)
                memoryBreakpointPages.erase(foundData);
        }

        //delete the breakpoint from the maps
        breakpoints.erase(found);
        breakpointCallbacks.erase({ BreakpointType::Memory, address });
        memoryBreakpointRanges.erase(Range(address, address));
        return success;
    }

    bool Process::DeleteGenericBreakpoint(const BreakpointInfo & info)
    {
        switch(info.type)
        {
        case BreakpointType::Software:
            return DeleteBreakpoint(info.address);
        case BreakpointType::Hardware:
            return DeleteHardwareBreakpoint(info.address);
        case BreakpointType::Memory:
            return DeleteMemoryBreakpoint(info.address);
        default:
            return false;
        }
    }
};<|endoftext|>


<commit_before>#include "cute.h"
#include "ide_listener.h"
#include "xml_listener.h"
#include "cute_runner.h"

#include "MatVec.h"

void empty_double_initialisation() {
	MatVec<double, 3> vec;
	bool same{true};

	for (auto& el : vec)
		same &= el == 0;
	ASSERTM("somewhere not the same", same);
}

void test_norm2() {
	MatVec<double, 3> vec{-1,2,3};
	ASSERTM("", vec.norm2() == 14);
}

void test_norm() {
	MatVec<double, 2> vec{4,-3};
	ASSERTM("", vec.norm() == 5);
}

void scalar_product() {
	MatVec<double, 3> vec1{1,2,3};
	MatVec<double, 3> vec2{-1,-3,2};

	ASSERTM("",vec1*vec2 == -1);
}

void runAllTests(int argc, char const *argv[]){
	cute::suite s;
	s.push_back(CUTE(empty_double_initialisation));
	s.push_back(CUTE(scalar_product));
	s.push_back(CUTE(test_norm2));
	s.push_back(CUTE(test_norm));
	//TODO add your test here
	cute::xml_file_opener xmlfile(argc,argv);
	cute::xml_listener<cute::ide_listener<> >  lis(xmlfile.out);
	cute::makeRunner(lis,argc,argv)(s, "AllTests");
}

int main(int argc, char const *argv[]){
    runAllTests(argc,argv);
    return 0;
}

<commit_msg>Tests zu den Operationen<commit_after>#include "cute.h"
#include "ide_listener.h"
#include "xml_listener.h"
#include "cute_runner.h"

#include "MatVec.h"

void empty_double_initialisation() {
	MatVec<double, 3> vec { };
	bool same{true};

	for (auto& el : vec)
		same &= el == 0;
	ASSERTM("somewhere not the same", same);
}

void vektor_addition() {
	MatVec<double, 3> vec1{1,2,3};
	MatVec<double, 3> vec2{-1,-3,2};
	MatVec<double, 3> res{0,-1,5};

	ASSERTM("", vec1 + vec2 == res);
}

void vektor_subtraktion() {
	MatVec<double, 3> vec1{1,2,3};
	MatVec<double, 3> vec2{-1,-3,2};
	MatVec<double, 3> res{2,5,1};

	ASSERTM("", vec1 - vec2 == res);
}

void vektorElemente_SkalarAddition() {
	MatVec<double, 3> vec{-1,-3,2};
	MatVec<double, 3> res{1,-1,4};
	double s = 2;

	ASSERTM("", vec + s == res);
}

void vektorElemente_SkalarSubtraktion() {
	MatVec<double, 3> vec{1,-3,2};
	MatVec<double, 3> res{-1,-5,0};
	double s = 2;

	ASSERTM("", vec - s == res);
}

void test_norm2() {
	MatVec<double, 3> vec{-1,2,3};
	ASSERTM("", vec.norm2() == 14);
}

void test_norm() {
	MatVec<double, 2> vec{4,-3};
	ASSERTM("", vec.norm() == 5);
}

void scalar_product() {
	MatVec<double, 3> vec1{1,2,3};
	MatVec<double, 3> vec2{-1,-3,2};

	ASSERTM("",vec1*vec2 == -1);
}

void multiplikation_skalar() {
	MatVec<double, 3> vec{1,-2,3};
	MatVec<double, 3> res{-2,4,-6};
	double skalar{-2};

	ASSERTM("", vec * skalar == res);
}

void division_skalar() {
	MatVec<double, 3> vec{-2,4,-6};
	MatVec<double, 3> res{1,-2,3};
	double skalar{-2};

	ASSERTM("", vec / skalar == res);
}

void make_negative() {
	MatVec<double, 3> vec{-2,4,-6};
	MatVec<double, 3> res{2,-4,6};

	ASSERTM("", -vec == res);
}

void runAllTests(int argc, char const *argv[]){
	cute::suite s;
	s.push_back(CUTE(empty_double_initialisation));
	s.push_back(CUTE(scalar_product));
	s.push_back(CUTE(test_norm2));
	s.push_back(CUTE(test_norm));
	s.push_back(CUTE(multiplikation_skalar));
	s.push_back(CUTE(division_skalar));
	s.push_back(CUTE(make_negative));
	s.push_back(CUTE(vektor_addition));
	s.push_back(CUTE(vektor_subtraktion));
	s.push_back(CUTE(vektorElemente_SkalarAddition));
	s.push_back(CUTE(vektorElemente_SkalarSubtraktion));
	//TODO add your test here
	cute::xml_file_opener xmlfile(argc,argv);
	cute::xml_listener<cute::ide_listener<> >  lis(xmlfile.out);
	cute::makeRunner(lis,argc,argv)(s, "AllTests");
}

int main(int argc, char const *argv[]){
    runAllTests(argc,argv);
    return 0;
}

<|endoftext|>


<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2018 Intel Corporation. All Rights Reserved.

#include "software-device.h"
#include "stream.h"

namespace librealsense
{
    software_device::software_device()
        : device(std::make_shared<context>(backend_type::standard), {})
    {
        register_info(RS2_CAMERA_INFO_NAME, "Software-Device");
    }

    software_sensor& software_device::add_software_sensor(const std::string& name)
    {
        auto sensor = std::make_shared<software_sensor>(name, this);
        add_sensor(sensor);
        _software_sensors.push_back(sensor);

        return *sensor;
    }

    software_sensor& software_device::get_software_sensor(int index)
    {
        if (index >= _software_sensors.size())
        {
            throw rs2::error("Requested index is out of range!");
        }
        return *_software_sensors[index];
    }

    void software_device::set_matcher_type(rs2_matchers matcher)
    {
        _matcher = matcher;
    }

    software_sensor::software_sensor(std::string name, software_device* owner)
        : sensor_base(name, owner)
    {

    }

    std::shared_ptr<matcher> software_device::create_matcher(const frame_holder& frame) const
    {
        std::vector<stream_interface*> profiles;

        for (auto&& s : _software_sensors)
            for (auto&& p : s->get_stream_profiles())
                profiles.push_back(p.get());

        return matcher_factory::create(_matcher, profiles);
    }

    std::shared_ptr<stream_profile_interface> software_sensor::add_video_stream(rs2_video_stream video_stream)
    {
        auto exist = (std::find_if(_profiles.begin(), _profiles.end(), [&](std::shared_ptr<stream_profile_interface> profile)
        {
            if (profile->get_unique_id() == video_stream.uid)
            {
                return true;
            }
            return false;
        } ) != _profiles.end());

        if (exist)
        {
            LOG_WARNING("Stream unique ID already exist!");
            throw rs2::error("Stream unique ID already exist!");
        }

        auto profile = std::make_shared<video_stream_profile>(
            platform::stream_profile{ (uint32_t)video_stream.width, (uint32_t)video_stream.height, (uint32_t)video_stream.fps, 0 });
        profile->set_dims(video_stream.width, video_stream.height);
        profile->set_format(video_stream.fmt);
        profile->set_framerate(video_stream.fps);
        profile->set_stream_index(video_stream.index);
        profile->set_stream_type(video_stream.type);
        profile->set_unique_id(video_stream.uid);
        profile->set_intrinsics([=]() {return video_stream.intrinsics; });
        _profiles.push_back(profile);

        return profile;
    }

    stream_profiles software_sensor::init_stream_profiles()
    {
        return _profiles;
    }

    void software_sensor::open(const stream_profiles& requests)
    {

    }
    void software_sensor::close()
    {

    }

    void software_sensor::start(frame_callback_ptr callback)
    {
        _source.init(_metadata_parsers);
        _source.set_sensor(this->shared_from_this());
        _source.set_callback(callback);
    }

    void software_sensor::stop()
    {
        _source.flush();
        _source.reset();
    }

    void software_sensor::on_video_frame(rs2_software_video_frame software_frame)
    {
        frame_additional_data data;
        data.timestamp = software_frame.timestamp;
        data.timestamp_domain = software_frame.domain;
        data.frame_number = software_frame.frame_number;

        rs2_extension extension = software_frame.profile->profile->get_stream_type() == RS2_STREAM_DEPTH ?
            RS2_EXTENSION_DEPTH_FRAME : RS2_EXTENSION_VIDEO_FRAME;

        auto frame = _source.alloc_frame(extension, 0, data, false);

        auto vid_profile = dynamic_cast<video_stream_profile_interface*>(software_frame.profile->profile);
        auto vid_frame = dynamic_cast<video_frame*>(frame);
        vid_frame->assign(vid_profile->get_width(), vid_profile->get_height(), software_frame.stride, software_frame.bpp);

        frame->set_stream(std::dynamic_pointer_cast<stream_profile_interface>(software_frame.profile->profile->shared_from_this()));
        frame->attach_continuation(frame_continuation{ [=]() {
            software_frame.deleter(software_frame.pixels);
        }, software_frame.pixels });
        _source.invoke_callback(frame);
    }

    void software_sensor::add_read_only_option(rs2_option option, float val)
    {
        register_option(RS2_OPTION_DEPTH_UNITS, std::make_shared<const_value_option>("bypass sensor read only option",
            lazy<float>([=]() { return val; })));
    }

    void software_sensor::update_read_only_option(rs2_option option, float val)
    {
        get_option(option).set(val);
    }
}

<commit_msg>Fixes to the software device to enable recording into ROS-bag<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2018 Intel Corporation. All Rights Reserved.

#include "software-device.h"
#include "stream.h"

namespace librealsense
{
    software_device::software_device()
        : device(std::make_shared<context>(backend_type::standard), {})
    {
        register_info(RS2_CAMERA_INFO_NAME, "Software-Device");
    }

    software_sensor& software_device::add_software_sensor(const std::string& name)
    {
        auto sensor = std::make_shared<software_sensor>(name, this);
        add_sensor(sensor);
        _software_sensors.push_back(sensor);

        return *sensor;
    }

    software_sensor& software_device::get_software_sensor(int index)
    {
        if (index >= _software_sensors.size())
        {
            throw rs2::error("Requested index is out of range!");
        }
        return *_software_sensors[index];
    }

    void software_device::set_matcher_type(rs2_matchers matcher)
    {
        _matcher = matcher;
    }

    software_sensor::software_sensor(std::string name, software_device* owner)
        : sensor_base(name, owner)
    {

    }

    std::shared_ptr<matcher> software_device::create_matcher(const frame_holder& frame) const
    {
        std::vector<stream_interface*> profiles;

        for (auto&& s : _software_sensors)
            for (auto&& p : s->get_stream_profiles())
                profiles.push_back(p.get());

        return matcher_factory::create(_matcher, profiles);
    }

    std::shared_ptr<stream_profile_interface> software_sensor::add_video_stream(rs2_video_stream video_stream)
    {
        auto exist = (std::find_if(_profiles.begin(), _profiles.end(), [&](std::shared_ptr<stream_profile_interface> profile)
        {
            if (profile->get_unique_id() == video_stream.uid)
            {
                return true;
            }
            return false;
        } ) != _profiles.end());

        if (exist)
        {
            LOG_WARNING("Stream unique ID already exist!");
            throw rs2::error("Stream unique ID already exist!");
        }

        auto profile = std::make_shared<video_stream_profile>(
            platform::stream_profile{ (uint32_t)video_stream.width, (uint32_t)video_stream.height, (uint32_t)video_stream.fps, 0 });
        profile->set_dims(video_stream.width, video_stream.height);
        profile->set_format(video_stream.fmt);
        profile->set_framerate(video_stream.fps);
        profile->set_stream_index(video_stream.index);
        profile->set_stream_type(video_stream.type);
        profile->set_unique_id(video_stream.uid);
        profile->set_intrinsics([=]() {return video_stream.intrinsics; });
        _profiles.push_back(profile);

        return profile;
    }

    stream_profiles software_sensor::init_stream_profiles()
    {
        return _profiles;
    }

    void software_sensor::open(const stream_profiles& requests)
    {
        set_active_streams(requests);
    }

    void software_sensor::close(){}

    void software_sensor::start(frame_callback_ptr callback)
    {
        _source.init(_metadata_parsers);
        _source.set_sensor(this->shared_from_this());
        _source.set_callback(callback);
        raise_on_before_streaming_changes(true);
    }

    void software_sensor::stop()
    {
        raise_on_before_streaming_changes(false);
        _source.flush();
        _source.reset();
    }

    void software_sensor::on_video_frame(rs2_software_video_frame software_frame)
    {
        frame_additional_data data;
        data.timestamp = software_frame.timestamp;
        data.timestamp_domain = software_frame.domain;
        data.frame_number = software_frame.frame_number;

        rs2_extension extension = software_frame.profile->profile->get_stream_type() == RS2_STREAM_DEPTH ?
            RS2_EXTENSION_DEPTH_FRAME : RS2_EXTENSION_VIDEO_FRAME;

        auto frame = _source.alloc_frame(extension, 0, data, false);
        if (!frame) return;

        auto vid_profile = dynamic_cast<video_stream_profile_interface*>(software_frame.profile->profile);
        auto vid_frame = dynamic_cast<video_frame*>(frame);
        vid_frame->assign(vid_profile->get_width(), vid_profile->get_height(), software_frame.stride, software_frame.bpp);

        frame->set_stream(std::dynamic_pointer_cast<stream_profile_interface>(software_frame.profile->profile->shared_from_this()));
        frame->attach_continuation(frame_continuation{ [=]() {
            software_frame.deleter(software_frame.pixels);
        }, software_frame.pixels });
        _source.invoke_callback(frame);
    }

    void software_sensor::add_read_only_option(rs2_option option, float val)
    {
        register_option(RS2_OPTION_DEPTH_UNITS, std::make_shared<const_value_option>("bypass sensor read only option",
            lazy<float>([=]() { return val; })));
    }

    void software_sensor::update_read_only_option(rs2_option option, float val)
    {
        get_option(option).set(val);
    }
}

<|endoftext|>


<commit_before>/*
  Copyright (c) DataStax, Inc.

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

#ifndef DATASTAX_INTERNAL_SSL_NO_IMPL_HPP
#define DATASTAX_INTERNAL_SSL_NO_IMPL_HPP

namespace datastax { namespace internal { namespace core {

class NoSslSession : public SslSession {
public:
  NoSslSession(const Address& address, const String& hostname, const String& sni_server_name);

  virtual bool is_handshake_done() const { return false; }
  virtual void do_handshake() {}
  virtual void verify() {}

  virtual int encrypt(const char* buf, size_t size) { return -1; }
  virtual int decrypt(char* buf, size_t size) { return -1; }
};

class NoSslContext : public SslContext {
public:
  virtual SslSession* create_session(const Address& address, const String& hostname);

  virtual CassError add_trusted_cert(const char* cert, size_t cert_length);
  virtual CassError set_cert(const char* cert, size_t cert_length);
  virtual CassError set_private_key(const char* key, size_t key_length, const char* password,
                                    size_t password_length);
};

class NoSslContextFactory : public SslContextFactoryBase<NoSslContextFactory> {
public:
  static SslContext::Ptr create();
  static void internal_init() {}
  static void internal_thread_cleanup() {}
  static void internal_cleanup() {}
};

typedef SslContextFactoryBase<NoSslContextFactory> SslContextFactory;

}}} // namespace datastax::internal::core

#endif
<commit_msg>Fix silly error that made it to release<commit_after>/*
  Copyright (c) DataStax, Inc.

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

#ifndef DATASTAX_INTERNAL_SSL_NO_IMPL_HPP
#define DATASTAX_INTERNAL_SSL_NO_IMPL_HPP

namespace datastax { namespace internal { namespace core {

class NoSslSession : public SslSession {
public:
  NoSslSession(const Address& address, const String& hostname, const String& sni_server_name);

  virtual bool is_handshake_done() const { return false; }
  virtual void do_handshake() {}
  virtual void verify() {}

  virtual int encrypt(const char* buf, size_t size) { return -1; }
  virtual int decrypt(char* buf, size_t size) { return -1; }
};

class NoSslContext : public SslContext {
public:
  virtual SslSession* create_session(const Address& address, const String& hostname, const String& sni_server_name);

  virtual CassError add_trusted_cert(const char* cert, size_t cert_length);
  virtual CassError set_cert(const char* cert, size_t cert_length);
  virtual CassError set_private_key(const char* key, size_t key_length, const char* password,
                                    size_t password_length);
};

class NoSslContextFactory : public SslContextFactoryBase<NoSslContextFactory> {
public:
  static SslContext::Ptr create();
  static void internal_init() {}
  static void internal_thread_cleanup() {}
  static void internal_cleanup() {}
};

typedef SslContextFactoryBase<NoSslContextFactory> SslContextFactory;

}}} // namespace datastax::internal::core

#endif
<|endoftext|>