<commit_before>/*************************************************************************
 *
 *  $RCSfile: expftext.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2004-08-23 09:34:19 $
 *
 *  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_EXPFTEXT_HXX
#define _SC_EXPFTEXT_HXX

#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif

class SC_DLLPUBLIC ScExpandedFixedText: public FixedText
{
    protected:

        void RequestHelp( const HelpEvent& rHEvt );

    public:

        ScExpandedFixedText( Window* pParent,WinBits nWinStyle = 0);
        ScExpandedFixedText( Window* pWindow, const ResId& rResId);
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.346); FILE MERGED 2005/09/05 15:05:20 rt 1.2.346.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: expftext.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 21:24:30 $
 *
 *  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_EXPFTEXT_HXX
#define _SC_EXPFTEXT_HXX

#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif

class SC_DLLPUBLIC ScExpandedFixedText: public FixedText
{
    protected:

        void RequestHelp( const HelpEvent& rHEvt );

    public:

        ScExpandedFixedText( Window* pParent,WinBits nWinStyle = 0);
        ScExpandedFixedText( Window* pWindow, const ResId& rResId);
};

#endif
<|endoftext|>


<commit_before>#ifndef _FDSB_NID_
#define _FDSB_NID_

namespace fdsb
{

/**
 * Node Identifier Plain Old Data type.
 */
struct Nid
{
	enum struct Type : unsigned char
	{
		special,
		integer,
		real,
		character,
		allocated,
	};

	enum struct Special : unsigned long long
	{
		null,
		bool_true,
		bool_false,
	};

	Type t;
	union
	{
	unsigned long long v;
	double vd;
	};

	/** Generate a new unique node id. */
	static Nid unique();
};

constexpr Nid operator"" _nid(unsigned long long v)
{
	return {Nid::Type::integer, { .v = v }};
}

constexpr Nid operator"" _nid(long double v)
{
	return {Nid::Type::real, { .vd = v }};
}

constexpr Nid operator"" _nid(char v)
{
	return {Nid::Type::character, { .v = v }};
}

constexpr Nid null_nid = {Nid::Type::special,Nid::Special::null};
constexpr Nid true_nid = {Nid::Type::special,Nid::Special::bool_true};
constexpr Nid false_nid = {Nid::Type::special,Nid::Special::bool_false};

};

#endif
<commit_msg>Minor rename, attempting to fix compiler crash<commit_after>#ifndef _FDSB_NID_
#define _FDSB_NID_

namespace fdsb
{

/**
 * Node Identifier Plain Old Data type.
 */
struct Nid
{
	enum struct Type : unsigned char
	{
		special,
		integer,
		real,
		character,
		allocated,
	};

	enum struct Special : unsigned long long
	{
		null,
		bool_true,
		bool_false,
	};

	Type t;
	union
	{
	unsigned long long i;
	double d;
	};

	/** Generate a new unique node id. */
	static Nid unique();
};

constexpr Nid operator"" _nid(unsigned long long v)
{
	return Nid{Nid::Type::integer, { .i = v }};
}

constexpr Nid operator"" _nid(long double v)
{
	return Nid{Nid::Type::real, { .d = v }};
}

constexpr Nid operator"" _nid(char v)
{
	return Nid{Nid::Type::character, { .i = v }};
}

constexpr Nid null_nid = {Nid::Type::special,Nid::Special::null};
constexpr Nid true_nid = {Nid::Type::special,Nid::Special::bool_true};
constexpr Nid false_nid = {Nid::Type::special,Nid::Special::bool_false};

};

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: shtabdlg.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: dr $ $Date: 2002-10-02 14:59:25 $
 *
 *  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_SHTABDLG_HXX
#define SC_SHTABDLG_HXX

#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef SVTOOLS_TOOLTIPLBOX_HXX
#include <svtools/tooltiplbox.hxx>
#endif
#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif

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

class ScShowTabDlg : public ModalDialog
{
private:
    ::svtools::ToolTipMultiListBox  aLb;
    OKButton                        aBtnOk;
    CancelButton                    aBtnCancel;
    HelpButton                      aBtnHelp;
    FixedText                       aFtLbTitle;

    DECL_LINK( DblClkHdl, void * );

public:
            ScShowTabDlg( Window* pParent );
            ~ScShowTabDlg();

    /** Sets dialog title, fixed text for listbox and help IDs. */
    void    SetDescription(
                const String& rTitle, const String& rFixedText,
                ULONG nDlgHelpId, ULONG nLbHelpId );

    /** Inserts a string into the ListBox. */
    void    Insert( const String& rString, BOOL bSelected );

    USHORT  GetSelectEntryCount() const;
    String  GetSelectEntry(USHORT nPos) const;
    USHORT  GetSelectEntryPos(USHORT nPos) const;
};

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.3.898); FILE MERGED 2005/09/05 15:05:48 rt 1.3.898.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: shtabdlg.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 21:50:01 $
 *
 *  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_SHTABDLG_HXX
#define SC_SHTABDLG_HXX

#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef SVTOOLS_TOOLTIPLBOX_HXX
#include <svtools/tooltiplbox.hxx>
#endif
#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif

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

class ScShowTabDlg : public ModalDialog
{
private:
    ::svtools::ToolTipMultiListBox  aLb;
    OKButton                        aBtnOk;
    CancelButton                    aBtnCancel;
    HelpButton                      aBtnHelp;
    FixedText                       aFtLbTitle;

    DECL_LINK( DblClkHdl, void * );

public:
            ScShowTabDlg( Window* pParent );
            ~ScShowTabDlg();

    /** Sets dialog title, fixed text for listbox and help IDs. */
    void    SetDescription(
                const String& rTitle, const String& rFixedText,
                ULONG nDlgHelpId, ULONG nLbHelpId );

    /** Inserts a string into the ListBox. */
    void    Insert( const String& rString, BOOL bSelected );

    USHORT  GetSelectEntryCount() const;
    String  GetSelectEntry(USHORT nPos) const;
    USHORT  GetSelectEntryPos(USHORT nPos) const;
};

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: undobase.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: nn $ $Date: 2002-10-09 10:58:13 $
 *
 *  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_UNDOBASE_HXX
#define SC_UNDOBASE_HXX

#ifndef _UNDO_HXX //autogen
#include <svtools/undo.hxx>
#endif

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

class ScDocument;
class ScDocShell;
class SdrUndoAction;
class ScRefUndoData;

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

class ScSimpleUndo: public SfxUndoAction
{
public:
                    TYPEINFO();
                    ScSimpleUndo( ScDocShell* pDocSh );
    virtual         ~ScSimpleUndo();

    virtual BOOL    Merge( SfxUndoAction *pNextAction );

protected:
    ScDocShell*     pDocShell;
    SfxUndoAction*  pDetectiveUndo;

    void            BeginUndo();
    void            EndUndo();
    void            BeginRedo();
    void            EndRedo();

    static void     ShowTable( USHORT nTab );
    static void     ShowTable( const ScRange& rRange );
};

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

enum ScBlockUndoMode { SC_UNDO_SIMPLE, SC_UNDO_MANUALHEIGHT, SC_UNDO_AUTOHEIGHT };

class ScBlockUndo: public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScBlockUndo( ScDocShell* pDocSh, const ScRange& rRange,
                                 ScBlockUndoMode eBlockMode );
    virtual         ~ScBlockUndo();

protected:
    ScRange         aBlockRange;
    SdrUndoAction*  pDrawUndo;
    ScBlockUndoMode eMode;

    void            BeginUndo();
    void            EndUndo();
//  void            BeginRedo();
    void            EndRedo();

    BOOL            AdjustHeight();
    void            ShowBlock();
};

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

enum ScMoveUndoMode { SC_UNDO_REFFIRST, SC_UNDO_REFLAST };

class ScMoveUndo: public ScSimpleUndo               // mit Referenzen
{
public:
                    TYPEINFO();
                    ScMoveUndo( ScDocShell* pDocSh,
                                ScDocument* pRefDoc, ScRefUndoData* pRefData,
                                ScMoveUndoMode eRefMode );
    virtual         ~ScMoveUndo();

protected:
    SdrUndoAction*  pDrawUndo;
    ScDocument*     pRefUndoDoc;
    ScRefUndoData*  pRefUndoData;
    ScMoveUndoMode  eMode;

    void            BeginUndo();
    void            EndUndo();
//  void            BeginRedo();
//  void            EndRedo();

private:
    void            UndoRef();
};

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

class ScUndoWrapper: public SfxUndoAction           // for manual merging of actions
{
    SfxUndoAction*  pWrappedUndo;

public:
                            TYPEINFO();
                            ScUndoWrapper( SfxUndoAction* pUndo );
    virtual                 ~ScUndoWrapper();

    SfxUndoAction*          GetWrappedUndo()        { return pWrappedUndo; }
    void                    ForgetWrappedUndo();

    virtual BOOL            IsLinked();
    virtual void            SetLinked( BOOL bIsLinked );
    virtual void            Undo();
    virtual void            Redo();
    virtual void            Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL            CanRepeat(SfxRepeatTarget& rTarget) const;
    virtual BOOL            Merge( SfxUndoAction *pNextAction );
    virtual String          GetComment() const;
    virtual String          GetRepeatComment(SfxRepeatTarget&) const;
    virtual USHORT          GetId() const;
};

#endif

<commit_msg>INTEGRATION: CWS rowlimit (1.2.302); FILE MERGED 2004/01/13 20:04:46 er 1.2.302.2: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short 2003/11/28 19:48:03 er 1.2.302.1: #i1967# move ScAddress, ScRange from global.hxx to address.hxx<commit_after>/*************************************************************************
 *
 *  $RCSfile: undobase.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 11:43:57 $
 *
 *  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_UNDOBASE_HXX
#define SC_UNDOBASE_HXX

#ifndef _UNDO_HXX //autogen
#include <svtools/undo.hxx>
#endif

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

class ScDocument;
class ScDocShell;
class SdrUndoAction;
class ScRefUndoData;

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

class ScSimpleUndo: public SfxUndoAction
{
public:
                    TYPEINFO();
                    ScSimpleUndo( ScDocShell* pDocSh );
    virtual         ~ScSimpleUndo();

    virtual BOOL    Merge( SfxUndoAction *pNextAction );

protected:
    ScDocShell*     pDocShell;
    SfxUndoAction*  pDetectiveUndo;

    void            BeginUndo();
    void            EndUndo();
    void            BeginRedo();
    void            EndRedo();

    static void     ShowTable( SCTAB nTab );
    static void     ShowTable( const ScRange& rRange );
};

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

enum ScBlockUndoMode { SC_UNDO_SIMPLE, SC_UNDO_MANUALHEIGHT, SC_UNDO_AUTOHEIGHT };

class ScBlockUndo: public ScSimpleUndo
{
public:
                    TYPEINFO();
                    ScBlockUndo( ScDocShell* pDocSh, const ScRange& rRange,
                                 ScBlockUndoMode eBlockMode );
    virtual         ~ScBlockUndo();

protected:
    ScRange         aBlockRange;
    SdrUndoAction*  pDrawUndo;
    ScBlockUndoMode eMode;

    void            BeginUndo();
    void            EndUndo();
//  void            BeginRedo();
    void            EndRedo();

    BOOL            AdjustHeight();
    void            ShowBlock();
};

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

enum ScMoveUndoMode { SC_UNDO_REFFIRST, SC_UNDO_REFLAST };

class ScMoveUndo: public ScSimpleUndo               // mit Referenzen
{
public:
                    TYPEINFO();
                    ScMoveUndo( ScDocShell* pDocSh,
                                ScDocument* pRefDoc, ScRefUndoData* pRefData,
                                ScMoveUndoMode eRefMode );
    virtual         ~ScMoveUndo();

protected:
    SdrUndoAction*  pDrawUndo;
    ScDocument*     pRefUndoDoc;
    ScRefUndoData*  pRefUndoData;
    ScMoveUndoMode  eMode;

    void            BeginUndo();
    void            EndUndo();
//  void            BeginRedo();
//  void            EndRedo();

private:
    void            UndoRef();
};

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

class ScUndoWrapper: public SfxUndoAction           // for manual merging of actions
{
    SfxUndoAction*  pWrappedUndo;

public:
                            TYPEINFO();
                            ScUndoWrapper( SfxUndoAction* pUndo );
    virtual                 ~ScUndoWrapper();

    SfxUndoAction*          GetWrappedUndo()        { return pWrappedUndo; }
    void                    ForgetWrappedUndo();

    virtual BOOL            IsLinked();
    virtual void            SetLinked( BOOL bIsLinked );
    virtual void            Undo();
    virtual void            Redo();
    virtual void            Repeat(SfxRepeatTarget& rTarget);
    virtual BOOL            CanRepeat(SfxRepeatTarget& rTarget) const;
    virtual BOOL            Merge( SfxUndoAction *pNextAction );
    virtual String          GetComment() const;
    virtual String          GetRepeatComment(SfxRepeatTarget&) const;
    virtual USHORT          GetId() const;
};

#endif

<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/system_wrappers/source/event_win.h"

#include "Mmsystem.h"

namespace webrtc {

EventWindows::EventWindows()
    : event_(::CreateEvent(NULL,    // security attributes
                           FALSE,   // manual reset
                           FALSE,   // initial state
                           NULL)),  // name of event
    timerID_(NULL) {
}

EventWindows::~EventWindows() {
  CloseHandle(event_);
}

bool EventWindows::Set() {
  // Note: setting an event that is already set has no effect.
  return SetEvent(event_) == 1 ? true : false;
}

bool EventWindows::Reset() {
  return ResetEvent(event_) == 1 ? true : false;
}

EventTypeWrapper EventWindows::Wait(unsigned long max_time) {
  unsigned long res = WaitForSingleObject(event_, max_time);
  switch (res) {
    case WAIT_OBJECT_0:
      return kEventSignaled;
    case WAIT_TIMEOUT:
      return kEventTimeout;
    default:
      return kEventError;
  }
}

bool EventWindows::StartTimer(bool periodic, unsigned long time) {
  if (timerID_ != NULL) {
    timeKillEvent(timerID_);
    timerID_ = NULL;
  }
  if (periodic) {
    timerID_ = timeSetEvent(time, 0, (LPTIMECALLBACK)HANDLE(event_), 0,
                            TIME_PERIODIC | TIME_CALLBACK_EVENT_PULSE);
  } else {
    timerID_ = timeSetEvent(time, 0, (LPTIMECALLBACK)HANDLE(event_), 0,
                            TIME_ONESHOT | TIME_CALLBACK_EVENT_SET);
  }

  if (timerID_ == NULL) {
    return false;
  }
  return true;
}

bool EventWindows::StopTimer() {
  timeKillEvent(timerID_);
  timerID_ = NULL;
  return true;
}

}  // namespace webrtc
<commit_msg>Stop timer in ~EventWindows().<commit_after>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/system_wrappers/source/event_win.h"

#include "Mmsystem.h"

namespace webrtc {

EventWindows::EventWindows()
    : event_(::CreateEvent(NULL,    // security attributes
                           FALSE,   // manual reset
                           FALSE,   // initial state
                           NULL)),  // name of event
    timerID_(NULL) {
}

EventWindows::~EventWindows() {
  StopTimer();
  CloseHandle(event_);
}

bool EventWindows::Set() {
  // Note: setting an event that is already set has no effect.
  return SetEvent(event_) == 1;
}

bool EventWindows::Reset() {
  return ResetEvent(event_) == 1;
}

EventTypeWrapper EventWindows::Wait(unsigned long max_time) {
  unsigned long res = WaitForSingleObject(event_, max_time);
  switch (res) {
    case WAIT_OBJECT_0:
      return kEventSignaled;
    case WAIT_TIMEOUT:
      return kEventTimeout;
    default:
      return kEventError;
  }
}

bool EventWindows::StartTimer(bool periodic, unsigned long time) {
  if (timerID_ != NULL) {
    timeKillEvent(timerID_);
    timerID_ = NULL;
  }

  if (periodic) {
    timerID_ = timeSetEvent(time, 0, (LPTIMECALLBACK)HANDLE(event_), 0,
                            TIME_PERIODIC | TIME_CALLBACK_EVENT_PULSE);
  } else {
    timerID_ = timeSetEvent(time, 0, (LPTIMECALLBACK)HANDLE(event_), 0,
                            TIME_ONESHOT | TIME_CALLBACK_EVENT_SET);
  }

  return timerID_ != NULL;
}

bool EventWindows::StopTimer() {
  if (timerID_ != NULL) {
    timeKillEvent(timerID_);
    timerID_ = NULL;
  }

  return true;
}

}  // namespace webrtc
<|endoftext|>


<commit_before>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include <X11/cursorfont.h>
#include <X11/Xcursor/Xcursor.h>
#include "CursorResourceLinux.h"
#include "core/Engine.h"
#include "core/linux/WindowLinux.h"
#include "utils/Log.h"

namespace ouzel
{
    namespace input
    {
        CursorResourceLinux::~CursorResourceLinux()
        {
            if (sharedEngine)
            {
                WindowLinux* windowLinux = static_cast<WindowLinux*>(sharedEngine->getWindow());
                Display* display = windowLinux->getDisplay();
                if (cursor != None) XFreeCursor(display, cursor);
            }
        }

        bool CursorResourceLinux::upload()
        {
            std::lock_guard<std::mutex> lock(uploadMutex);

            if (dirty)
            {
                if (sharedEngine)
                {
                    WindowLinux* windowLinux = static_cast<WindowLinux*>(sharedEngine->getWindow());
                    Display* display = windowLinux->getDisplay();

                    if (cursor != None)
                    {
                        XFreeCursor(display, cursor);
                        cursor = None;
                    }

                    if (data.empty())
                    {
                        switch (systemCursor)
                        {
                            case SystemCursor::DEFAULT:
                                cursor = XcursorLibraryLoadCursor(display, "arrow");
                                break;
                            case SystemCursor::ARROW:
                                cursor = XcursorLibraryLoadCursor(display, "arrow");
                                break;
                            case SystemCursor::HAND:
                                cursor = XcursorLibraryLoadCursor(display, "hand1");
                                break;
                            case SystemCursor::HORIZONTAL_RESIZE:
                                cursor = XcursorLibraryLoadCursor(display, "sb_h_double_arrow");
                                break;
                            case SystemCursor::VERTICAL_RESIZE:
                                cursor = XcursorLibraryLoadCursor(display, "sb_v_double_arrow");
                                break;
                            case SystemCursor::CROSS:
                                cursor = XcursorLibraryLoadCursor(display, "crosshair");
                                break;
                            case SystemCursor::I_BEAM:
                                cursor = XcursorLibraryLoadCursor(display, "xterm");
                                break;
                        }
                    }
                    else
                    {
                        int width = static_cast<int>(size.v[0]);
                        int height = static_cast<int>(size.v[1]);

                        XcursorImage* cursorImage = XcursorImageCreate(width, height);

                        if (!cursorImage)
                        {
                            Log(Log::Level::ERR) << "Failed to create cursor image";
                            return false;
                        }

                        cursorImage->xhot = static_cast<int>(hotSpot.v[0]);
                        cursorImage->yhot = height - static_cast<int>(hotSpot.v[1]) - 1;
                        cursorImage->delay = 0;

                        unsigned char* target = reinterpret_cast<unsigned char*>(cursorImage->pixels);

                        for (int i = 0; i < width * height; ++i)
                        {
                            target[i * 4 + 0] = data[i * 4 + 3];
                            target[i * 4 + 1] = data[i * 4 + 0];
                            target[i * 4 + 2] = data[i * 4 + 1];
                            target[i * 4 + 3] = data[i * 4 + 2];
                        }

                        cursor = XcursorImageLoadCursor(display, cursorImage);

                        XcursorImageDestroy(cursorImage);
                    }
                }

                dirty = false;
            }

            return true;
        }
    } // namespace input
} // namespace ouzel
<commit_msg>Reverse pixel byte order<commit_after>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include <X11/cursorfont.h>
#include <X11/Xcursor/Xcursor.h>
#include "CursorResourceLinux.h"
#include "core/Engine.h"
#include "core/linux/WindowLinux.h"
#include "utils/Log.h"

namespace ouzel
{
    namespace input
    {
        CursorResourceLinux::~CursorResourceLinux()
        {
            if (sharedEngine)
            {
                WindowLinux* windowLinux = static_cast<WindowLinux*>(sharedEngine->getWindow());
                Display* display = windowLinux->getDisplay();
                if (cursor != None) XFreeCursor(display, cursor);
            }
        }

        bool CursorResourceLinux::upload()
        {
            std::lock_guard<std::mutex> lock(uploadMutex);

            if (dirty)
            {
                if (sharedEngine)
                {
                    WindowLinux* windowLinux = static_cast<WindowLinux*>(sharedEngine->getWindow());
                    Display* display = windowLinux->getDisplay();

                    if (cursor != None)
                    {
                        XFreeCursor(display, cursor);
                        cursor = None;
                    }

                    if (data.empty())
                    {
                        switch (systemCursor)
                        {
                            case SystemCursor::DEFAULT:
                                cursor = XcursorLibraryLoadCursor(display, "arrow");
                                break;
                            case SystemCursor::ARROW:
                                cursor = XcursorLibraryLoadCursor(display, "arrow");
                                break;
                            case SystemCursor::HAND:
                                cursor = XcursorLibraryLoadCursor(display, "hand1");
                                break;
                            case SystemCursor::HORIZONTAL_RESIZE:
                                cursor = XcursorLibraryLoadCursor(display, "sb_h_double_arrow");
                                break;
                            case SystemCursor::VERTICAL_RESIZE:
                                cursor = XcursorLibraryLoadCursor(display, "sb_v_double_arrow");
                                break;
                            case SystemCursor::CROSS:
                                cursor = XcursorLibraryLoadCursor(display, "crosshair");
                                break;
                            case SystemCursor::I_BEAM:
                                cursor = XcursorLibraryLoadCursor(display, "xterm");
                                break;
                        }
                    }
                    else
                    {
                        int width = static_cast<int>(size.v[0]);
                        int height = static_cast<int>(size.v[1]);

                        XcursorImage* cursorImage = XcursorImageCreate(width, height);

                        if (!cursorImage)
                        {
                            Log(Log::Level::ERR) << "Failed to create cursor image";
                            return false;
                        }

                        cursorImage->xhot = static_cast<int>(hotSpot.v[0]);
                        cursorImage->yhot = height - static_cast<int>(hotSpot.v[1]) - 1;
                        cursorImage->delay = 0;

                        unsigned char* target = reinterpret_cast<unsigned char*>(cursorImage->pixels);

                        for (int i = 0; i < width * height; ++i)
                        {
                            target[i * 4 + 0] = data[i * 4 + 2];
                            target[i * 4 + 1] = data[i * 4 + 1];
                            target[i * 4 + 2] = data[i * 4 + 0];
                            target[i * 4 + 3] = data[i * 4 + 3];
                        }

                        cursor = XcursorImageLoadCursor(display, cursorImage);

                        XcursorImageDestroy(cursorImage);
                    }
                }

                dirty = false;
            }

            return true;
        }
    } // namespace input
} // namespace ouzel
<|endoftext|>


<commit_before>// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS.  All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
//
// This sample application demonstrates how to use the matroska parser
// library, which allows clients to handle a matroska format file.

#include "mkvreader.hpp"
#include "mkvparser.hpp"

static const wchar_t* utf8towcs(const char* str)
{
    if (str == NULL)
        return NULL;

    //TODO: this probably requires that the locale be
    //configured somehow:

    const size_t size = mbstowcs(NULL, str, 0);

    if (size == 0)
        return NULL;

    wchar_t* const val = new wchar_t[size+1];

    mbstowcs(val, str, size);
    val[size] = L'\0';

    return val;
}

int main(int argc, char* argv[])
{
    if (argc == 1)
    {
        printf("\t\t\tMkv Parser Sample Application\n");
        printf("\t\t\tUsage: \n");
        printf("\t\t\t  ./sample [input file] \n");
        printf("\t\t\t  ./sample sample.mkv \n");
        return -1;
    }

    using namespace mkvparser;

    MkvReader reader;

    if (reader.Open(argv[1]))
    {
        printf("\n Filename is invalid or error while opening.\n");
        return -1;
    }

    int maj, min, build, rev;

    GetVersion(maj, min, build, rev);
    printf("\t\t libmkv verison: %d.%d.%d.%d\n", maj, min, build, rev);

    long long pos = 0;

    EBMLHeader ebmlHeader;

    ebmlHeader.Parse(&reader, pos);

    printf("\t\t\t    EBML Header\n");
    printf("\t\tEBML Version\t\t: %lld\n", ebmlHeader.m_version);
    printf("\t\tEBML MaxIDLength\t: %lld\n", ebmlHeader.m_maxIdLength);
    printf("\t\tEBML MaxSizeLength\t: %lld\n", ebmlHeader.m_maxSizeLength);
    printf("\t\tDoc Type\t\t: %s\n", ebmlHeader.m_docType);
    printf("\t\tPos\t\t\t: %lld\n", pos);

    mkvparser::Segment* pSegment;

    long long ret = mkvparser::Segment::CreateInstance(&reader, pos, pSegment);
    if (ret)
    {
        printf("\n Segment::CreateInstance() failed.");
        return -1;
    }

    ret  = pSegment->Load();
    if (ret < 0)
    {
        printf("\n Segment::Load() failed.");
        return -1;
    }

    const SegmentInfo* const pSegmentInfo = pSegment->GetInfo();

    const long long timeCodeScale = pSegmentInfo->GetTimeCodeScale();
    const long long duration_ns = pSegmentInfo->GetDuration();

    const char* const pTitle_ = pSegmentInfo->GetTitleAsUTF8();
    const wchar_t* const pTitle = utf8towcs(pTitle_);

    const char* const pMuxingApp_ = pSegmentInfo->GetMuxingAppAsUTF8();
    const wchar_t* const pMuxingApp = utf8towcs(pMuxingApp_);

    const char* const pWritingApp_ = pSegmentInfo->GetWritingAppAsUTF8();
    const wchar_t* const pWritingApp = utf8towcs(pWritingApp_);

    printf("\n");
    printf("\t\t\t   Segment Info\n");
    printf("\t\tTimeCodeScale\t\t: %lld \n", timeCodeScale);
    printf("\t\tDuration\t\t: %lld\n", duration_ns);

    const double duration_sec = double(duration_ns) / 1000000000;
    printf("\t\tDuration(secs)\t\t: %7.3lf\n", duration_sec);

    if (pTitle == NULL)
        printf("\t\tTrack Name\t\t: NULL\n");
    else
    {
        printf("\t\tTrack Name\t\t: %ls\n", pTitle);
        delete [] pTitle;
    }

    if (pMuxingApp == NULL)
        printf("\t\tMuxing App\t\t: NULL\n");
    else
    {
        printf("\t\tMuxing App\t\t: %ls\n", pMuxingApp);
        delete [] pMuxingApp;
    }

    if (pWritingApp == NULL)
        printf("\t\tWriting App\t\t: NULL\n");
    else
    {
        printf("\t\tWriting App\t\t: %ls\n", pWritingApp);
        delete [] pWritingApp;
    }

    // pos of segment payload
    printf("\t\tPosition(Segment)\t: %lld\n", pSegment->m_start);

    // size of segment payload
    printf("\t\tSize(Segment)\t\t: %lld\n", pSegment->m_size);

    mkvparser::Tracks* const pTracks = pSegment->GetTracks();

    unsigned long i = 0;
    const unsigned long j = pTracks->GetTracksCount();

    enum { VIDEO_TRACK = 1, AUDIO_TRACK = 2 };

    printf("\n\t\t\t   Track Info\n");

    while (i != j)
    {
        const Track* const pTrack = pTracks->GetTrackByIndex(i++);

        if (pTrack == NULL)
            continue;

        const long long trackType = pTrack->GetType();
        const long long trackNumber = pTrack->GetNumber();
        const unsigned long long trackUid = pTrack->GetUid();
        const wchar_t* const pTrackName = utf8towcs(pTrack->GetNameAsUTF8());

        printf("\t\tTrack Type\t\t: %lld\n", trackType);
        printf("\t\tTrack Number\t\t: %lld\n", trackNumber);
        printf("\t\tTrack Uid\t\t: %lld\n", trackUid);

        if (pTrackName == NULL)
            printf("\t\tTrack Name\t\t: NULL\n");
        else
        {
            printf("\t\tTrack Name\t\t: %ls \n", pTrackName);
            delete [] pTrackName;
        }

        const char* const pCodecId = pTrack->GetCodecId();

        if (pCodecId == NULL)
            printf("\t\tCodec Id\t\t: NULL\n");
        else
            printf("\t\tCodec Id\t\t: %s\n", pCodecId);

        const char* const pCodecName_ = pTrack->GetCodecNameAsUTF8();
        const wchar_t* const pCodecName = utf8towcs(pCodecName_);

        if (pCodecName == NULL)
            printf("\t\tCodec Name\t\t: NULL\n");
        else
        {
            printf("\t\tCodec Name\t\t: %ls\n", pCodecName);
            delete [] pCodecName;
        }

        if (trackType == VIDEO_TRACK)
        {
            const VideoTrack* const pVideoTrack =
                static_cast<const VideoTrack*>(pTrack);

            const long long width =  pVideoTrack->GetWidth();
            printf("\t\tVideo Width\t\t: %lld\n", width);

            const long long height = pVideoTrack->GetHeight();
            printf("\t\tVideo Height\t\t: %lld\n", height);

            const double rate = pVideoTrack->GetFrameRate();
            printf("\t\tVideo Rate\t\t: %f\n",rate);
        }

        if (trackType == AUDIO_TRACK)
        {
            const AudioTrack* const pAudioTrack =
                static_cast<const AudioTrack*>(pTrack);

            const long long channels =  pAudioTrack->GetChannels();
            printf("\t\tAudio Channels\t\t: %lld\n", channels);

            const long long bitDepth = pAudioTrack->GetBitDepth();
            printf("\t\tAudio BitDepth\t\t: %lld\n", bitDepth);

            const double sampleRate = pAudioTrack->GetSamplingRate();
            printf("\t\tAddio Sample Rate\t: %.3f\n", sampleRate);
        }
    }

    printf("\n\n\t\t\t   Cluster Info\n");
    const unsigned long clusterCount = pSegment->GetCount();

    printf("\t\tCluster Count\t: %ld\n\n", clusterCount);

    if (clusterCount == 0)
    {
        printf("\t\tSegment has no clusters.\n");
        delete pSegment;
        return -1;
    }

    const mkvparser::Cluster* pCluster = pSegment->GetFirst();

    while ((pCluster != NULL) && !pCluster->EOS())
    {
        const long long timeCode = pCluster->GetTimeCode();
        printf("\t\tCluster Time Code\t: %lld\n", timeCode);

        const long long time_ns = pCluster->GetTime();
        printf("\t\tCluster Time (ns)\t: %lld\n", time_ns);

        const BlockEntry* pBlockEntry = pCluster->GetFirst();

        while ((pBlockEntry != NULL) && !pBlockEntry->EOS())
        {
            const Block* const pBlock  = pBlockEntry->GetBlock();
            const long long trackNum = pBlock->GetTrackNumber();
            const unsigned long tn = static_cast<unsigned long>(trackNum);
            const Track* const pTrack = pTracks->GetTrackByNumber(tn);
            const long long trackType = pTrack->GetType();
            const int frameCount = pBlock->GetFrameCount();
            const long long time_ns = pBlock->GetTime(pCluster);

            printf("\t\t\tBlock\t\t:%s,%s,%15lld\n",
                   (trackType == VIDEO_TRACK) ? "V" : "A",
                   pBlock->IsKey() ? "I" : "P",
                   time_ns);

            for (int i = 0; i < frameCount; ++i)
            {
                const Block::Frame& theFrame = pBlock->GetFrame(i);
                const long size = theFrame.len;
                const long long offset = theFrame.pos;
                printf("\t\t\t %15ld,%15llx\n", size, offset);
            }

            pBlockEntry = pCluster->GetNext(pBlockEntry);
        }

        pCluster = pSegment->GetNext(pCluster);
    }

    delete pSegment;
    return 0;

}
<commit_msg>fixed build error in sample<commit_after>// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS.  All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
//
// This sample application demonstrates how to use the matroska parser
// library, which allows clients to handle a matroska format file.

#include "mkvreader.hpp"
#include "mkvparser.hpp"

static const wchar_t* utf8towcs(const char* str)
{
    if (str == NULL)
        return NULL;

    //TODO: this probably requires that the locale be
    //configured somehow:

    const size_t size = mbstowcs(NULL, str, 0);

    if (size == 0)
        return NULL;

    wchar_t* const val = new wchar_t[size+1];

    mbstowcs(val, str, size);
    val[size] = L'\0';

    return val;
}

int main(int argc, char* argv[])
{
    if (argc == 1)
    {
        printf("\t\t\tMkv Parser Sample Application\n");
        printf("\t\t\tUsage: \n");
        printf("\t\t\t  ./sample [input file] \n");
        printf("\t\t\t  ./sample sample.mkv \n");
        return -1;
    }

    using namespace mkvparser;

    MkvReader reader;

    if (reader.Open(argv[1]))
    {
        printf("\n Filename is invalid or error while opening.\n");
        return -1;
    }

    int maj, min, build, rev;

    GetVersion(maj, min, build, rev);
    printf("\t\t libmkv verison: %d.%d.%d.%d\n", maj, min, build, rev);

    long long pos = 0;

    EBMLHeader ebmlHeader;

    ebmlHeader.Parse(&reader, pos);

    printf("\t\t\t    EBML Header\n");
    printf("\t\tEBML Version\t\t: %lld\n", ebmlHeader.m_version);
    printf("\t\tEBML MaxIDLength\t: %lld\n", ebmlHeader.m_maxIdLength);
    printf("\t\tEBML MaxSizeLength\t: %lld\n", ebmlHeader.m_maxSizeLength);
    printf("\t\tDoc Type\t\t: %s\n", ebmlHeader.m_docType);
    printf("\t\tPos\t\t\t: %lld\n", pos);

    mkvparser::Segment* pSegment;

    long long ret = mkvparser::Segment::CreateInstance(&reader, pos, pSegment);
    if (ret)
    {
        printf("\n Segment::CreateInstance() failed.");
        return -1;
    }

    ret  = pSegment->Load();
    if (ret < 0)
    {
        printf("\n Segment::Load() failed.");
        return -1;
    }

    const SegmentInfo* const pSegmentInfo = pSegment->GetInfo();

    const long long timeCodeScale = pSegmentInfo->GetTimeCodeScale();
    const long long duration_ns = pSegmentInfo->GetDuration();

    const char* const pTitle_ = pSegmentInfo->GetTitleAsUTF8();
    const wchar_t* const pTitle = utf8towcs(pTitle_);

    const char* const pMuxingApp_ = pSegmentInfo->GetMuxingAppAsUTF8();
    const wchar_t* const pMuxingApp = utf8towcs(pMuxingApp_);

    const char* const pWritingApp_ = pSegmentInfo->GetWritingAppAsUTF8();
    const wchar_t* const pWritingApp = utf8towcs(pWritingApp_);

    printf("\n");
    printf("\t\t\t   Segment Info\n");
    printf("\t\tTimeCodeScale\t\t: %lld \n", timeCodeScale);
    printf("\t\tDuration\t\t: %lld\n", duration_ns);

    const double duration_sec = double(duration_ns) / 1000000000;
    printf("\t\tDuration(secs)\t\t: %7.3lf\n", duration_sec);

    if (pTitle == NULL)
        printf("\t\tTrack Name\t\t: NULL\n");
    else
    {
        printf("\t\tTrack Name\t\t: %ls\n", pTitle);
        delete [] pTitle;
    }

    if (pMuxingApp == NULL)
        printf("\t\tMuxing App\t\t: NULL\n");
    else
    {
        printf("\t\tMuxing App\t\t: %ls\n", pMuxingApp);
        delete [] pMuxingApp;
    }

    if (pWritingApp == NULL)
        printf("\t\tWriting App\t\t: NULL\n");
    else
    {
        printf("\t\tWriting App\t\t: %ls\n", pWritingApp);
        delete [] pWritingApp;
    }

    // pos of segment payload
    printf("\t\tPosition(Segment)\t: %lld\n", pSegment->m_start);

    // size of segment payload
    printf("\t\tSize(Segment)\t\t: %lld\n", pSegment->m_size);

    const mkvparser::Tracks* pTracks = pSegment->GetTracks();

    unsigned long i = 0;
    const unsigned long j = pTracks->GetTracksCount();

    enum { VIDEO_TRACK = 1, AUDIO_TRACK = 2 };

    printf("\n\t\t\t   Track Info\n");

    while (i != j)
    {
        const Track* const pTrack = pTracks->GetTrackByIndex(i++);

        if (pTrack == NULL)
            continue;

        const long long trackType = pTrack->GetType();
        const long long trackNumber = pTrack->GetNumber();
        const unsigned long long trackUid = pTrack->GetUid();
        const wchar_t* const pTrackName = utf8towcs(pTrack->GetNameAsUTF8());

        printf("\t\tTrack Type\t\t: %lld\n", trackType);
        printf("\t\tTrack Number\t\t: %lld\n", trackNumber);
        printf("\t\tTrack Uid\t\t: %lld\n", trackUid);

        if (pTrackName == NULL)
            printf("\t\tTrack Name\t\t: NULL\n");
        else
        {
            printf("\t\tTrack Name\t\t: %ls \n", pTrackName);
            delete [] pTrackName;
        }

        const char* const pCodecId = pTrack->GetCodecId();

        if (pCodecId == NULL)
            printf("\t\tCodec Id\t\t: NULL\n");
        else
            printf("\t\tCodec Id\t\t: %s\n", pCodecId);

        const char* const pCodecName_ = pTrack->GetCodecNameAsUTF8();
        const wchar_t* const pCodecName = utf8towcs(pCodecName_);

        if (pCodecName == NULL)
            printf("\t\tCodec Name\t\t: NULL\n");
        else
        {
            printf("\t\tCodec Name\t\t: %ls\n", pCodecName);
            delete [] pCodecName;
        }

        if (trackType == VIDEO_TRACK)
        {
            const VideoTrack* const pVideoTrack =
                static_cast<const VideoTrack*>(pTrack);

            const long long width =  pVideoTrack->GetWidth();
            printf("\t\tVideo Width\t\t: %lld\n", width);

            const long long height = pVideoTrack->GetHeight();
            printf("\t\tVideo Height\t\t: %lld\n", height);

            const double rate = pVideoTrack->GetFrameRate();
            printf("\t\tVideo Rate\t\t: %f\n",rate);
        }

        if (trackType == AUDIO_TRACK)
        {
            const AudioTrack* const pAudioTrack =
                static_cast<const AudioTrack*>(pTrack);

            const long long channels =  pAudioTrack->GetChannels();
            printf("\t\tAudio Channels\t\t: %lld\n", channels);

            const long long bitDepth = pAudioTrack->GetBitDepth();
            printf("\t\tAudio BitDepth\t\t: %lld\n", bitDepth);

            const double sampleRate = pAudioTrack->GetSamplingRate();
            printf("\t\tAddio Sample Rate\t: %.3f\n", sampleRate);
        }
    }

    printf("\n\n\t\t\t   Cluster Info\n");
    const unsigned long clusterCount = pSegment->GetCount();

    printf("\t\tCluster Count\t: %ld\n\n", clusterCount);

    if (clusterCount == 0)
    {
        printf("\t\tSegment has no clusters.\n");
        delete pSegment;
        return -1;
    }

    const mkvparser::Cluster* pCluster = pSegment->GetFirst();

    while ((pCluster != NULL) && !pCluster->EOS())
    {
        const long long timeCode = pCluster->GetTimeCode();
        printf("\t\tCluster Time Code\t: %lld\n", timeCode);

        const long long time_ns = pCluster->GetTime();
        printf("\t\tCluster Time (ns)\t: %lld\n", time_ns);

        const BlockEntry* pBlockEntry = pCluster->GetFirst();

        while ((pBlockEntry != NULL) && !pBlockEntry->EOS())
        {
            const Block* const pBlock  = pBlockEntry->GetBlock();
            const long long trackNum = pBlock->GetTrackNumber();
            const unsigned long tn = static_cast<unsigned long>(trackNum);
            const Track* const pTrack = pTracks->GetTrackByNumber(tn);
            const long long trackType = pTrack->GetType();
            const int frameCount = pBlock->GetFrameCount();
            const long long time_ns = pBlock->GetTime(pCluster);

            printf("\t\t\tBlock\t\t:%s,%s,%15lld\n",
                   (trackType == VIDEO_TRACK) ? "V" : "A",
                   pBlock->IsKey() ? "I" : "P",
                   time_ns);

            for (int i = 0; i < frameCount; ++i)
            {
                const Block::Frame& theFrame = pBlock->GetFrame(i);
                const long size = theFrame.len;
                const long long offset = theFrame.pos;
                printf("\t\t\t %15ld,%15llx\n", size, offset);
            }

            pBlockEntry = pCluster->GetNext(pBlockEntry);
        }

        pCluster = pSegment->GetNext(pCluster);
    }

    delete pSegment;
    return 0;

}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/glue/plugins/pepper_audio.h"

#include "base/logging.h"
#include "third_party/ppapi/c/dev/ppb_audio_dev.h"
#include "third_party/ppapi/c/dev/ppb_audio_trusted_dev.h"

namespace pepper {

namespace {

// PPB_AudioConfig -------------------------------------------------------------

uint32_t RecommendSampleFrameCount(uint32_t requested_sample_frame_count);

PP_Resource CreateStereo16bit(PP_Module module_id,
                              PP_AudioSampleRate_Dev sample_rate,
                              uint32_t sample_frame_count) {
  PluginModule* module = ResourceTracker::Get()->GetModule(module_id);
  if (!module)
    return 0;

  // TODO(brettw): Currently we don't actually check what the hardware
  // supports, so just allow sample rates of the "guaranteed working" ones.
  if (sample_rate != PP_AUDIOSAMPLERATE_44100 &&
      sample_rate != PP_AUDIOSAMPLERATE_48000)
    return 0;

  // TODO(brettw): Currently we don't actually query to get a value from the
  // hardware, so just validate the range.
  if (RecommendSampleFrameCount(sample_frame_count) != sample_frame_count)
    return 0;

  scoped_refptr<AudioConfig> config(new AudioConfig(module,
                                                    sample_rate,
                                                    sample_frame_count));
  return config->GetReference();
}

uint32_t RecommendSampleFrameCount(uint32_t requested_sample_frame_count) {
  // TODO(brettw) Currently we don't actually query to get a value from the
  // hardware, so we always return the input for in-range values.
  if (requested_sample_frame_count < PP_AUDIOMINSAMPLEFRAMECOUNT)
    return PP_AUDIOMINSAMPLEFRAMECOUNT;
  if (requested_sample_frame_count > PP_AUDIOMAXSAMPLEFRAMECOUNT)
    return PP_AUDIOMAXSAMPLEFRAMECOUNT;
  return requested_sample_frame_count;
}

bool IsAudioConfig(PP_Resource resource) {
  scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(resource);
  return config;
}

PP_AudioSampleRate_Dev GetSampleRate(PP_Resource config_id) {
  scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(config_id);
  return config ? config->sample_rate() : PP_AUDIOSAMPLERATE_NONE;
}

uint32_t GetSampleFrameCount(PP_Resource config_id) {
  scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(config_id);
  return config ? config->sample_frame_count() : 0;
}

const PPB_AudioConfig_Dev ppb_audioconfig = {
  &CreateStereo16bit,
  &RecommendSampleFrameCount,
  &IsAudioConfig,
  &GetSampleRate,
  &GetSampleFrameCount
};

// PPB_Audio -------------------------------------------------------------------

PP_Resource Create(PP_Instance instance_id, PP_Resource config_id,
                   PPB_Audio_Callback callback, void* user_data) {
  PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id);
  if (!instance)
    return 0;
  // TODO(neb): Require callback to be present for untrusted plugins.
  scoped_refptr<Audio> audio(new Audio(instance->module()));
  if (!audio->Init(instance->delegate(), config_id, callback, user_data))
    return 0;
  return audio->GetReference();
}

bool IsAudio(PP_Resource resource) {
  scoped_refptr<Audio> audio = Resource::GetAs<Audio>(resource);
  return audio;
}

PP_Resource GetCurrentConfiguration(PP_Resource audio_id) {
  scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id);
  return audio ? audio->GetCurrentConfiguration() : 0;
}

bool StartPlayback(PP_Resource audio_id) {
  scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id);
  return audio ? audio->StartPlayback() : false;
}

bool StopPlayback(PP_Resource audio_id) {
  scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id);
  return audio ? audio->StopPlayback() : false;
}

const PPB_Audio_Dev ppb_audio = {
  &Create,
  &IsAudio,
  &GetCurrentConfiguration,
  &StartPlayback,
  &StopPlayback,
};

// PPB_AudioTrusted ------------------------------------------------------------

PP_Resource GetBuffer(PP_Resource audio_id) {
  // TODO(neb): Implement me!
  return 0;
}

int GetOSDescriptor(PP_Resource audio_id) {
  // TODO(neb): Implement me!
  return -1;
}

const PPB_AudioTrusted_Dev ppb_audiotrusted = {
  &GetBuffer,
  &GetOSDescriptor
};

}  // namespace

// AudioConfig -----------------------------------------------------------------

AudioConfig::AudioConfig(PluginModule* module,
                         PP_AudioSampleRate_Dev sample_rate,
                         uint32_t sample_frame_count)
    : Resource(module),
      sample_rate_(sample_rate),
      sample_frame_count_(sample_frame_count) {
}

const PPB_AudioConfig_Dev* AudioConfig::GetInterface() {
  return &ppb_audioconfig;
}

size_t AudioConfig::BufferSize() {
  // TODO(audio): as more options become available, we'll need to
  // have additional code here to correctly calculate the size in
  // bytes of an audio buffer.  For now, only support two channel
  // int16_t sample buffers.
  const int kChannels = 2;
  const int kSizeOfSample = sizeof(int16_t);
  return static_cast<size_t>(sample_frame_count_ * kSizeOfSample * kChannels);
}

AudioConfig* AudioConfig::AsAudioConfig() {
  return this;
}

// Audio -----------------------------------------------------------------------

Audio::Audio(PluginModule* module)
    : Resource(module),
      playing_(false),
      socket_(NULL),
      shared_memory_(NULL),
      shared_memory_size_(0),
      callback_(NULL),
      user_data_(NULL) {
}

Audio::~Audio() {
  // Calling ShutDown() makes sure StreamCreated cannot be called anymore.
  audio_->ShutDown();
  // Closing the socket causes the thread to exit - wait for it.
  socket_->Close();
  if (audio_thread_.get()) {
    audio_thread_->Join();
    audio_thread_.reset();
  }
  // Shared memory destructor will unmap the memory automatically.
}

const PPB_Audio_Dev* Audio::GetInterface() {
  return &ppb_audio;
}

const PPB_AudioTrusted_Dev* Audio::GetTrustedInterface() {
  return &ppb_audiotrusted;
}

Audio* Audio::AsAudio() {
  return this;
}

bool Audio::Init(PluginDelegate* plugin_delegate, PP_Resource config_id,
                 PPB_Audio_Callback callback, void* user_data) {
  CHECK(!audio_.get());
  config_ = Resource::GetAs<AudioConfig>(config_id);
  if (!config_)
    return false;
  callback_ = callback;
  user_data_ = user_data;
  // When the stream is created, we'll get called back in StreamCreated().
  audio_.reset(plugin_delegate->CreateAudio(config_->sample_rate(),
                                            config_->sample_frame_count(),
                                            this));
  return audio_.get() != NULL;
}

bool Audio::StartPlayback() {
  if (playing_)
    return true;

  CHECK(!audio_thread_.get());
  if (callback_ && socket_.get()) {
    audio_thread_.reset(new base::DelegateSimpleThread(this,
                                                       "plugin_audio_thread"));
    audio_thread_->Start();
  }
  playing_ = true;
  return audio_->StartPlayback();
}

bool Audio::StopPlayback() {
  if (!playing_)
    return true;

  if (!audio_->StopPlayback())
    return false;

  if (audio_thread_.get()) {
    audio_thread_->Join();
    audio_thread_.reset();
  }
  playing_ = false;
  return true;
}

void Audio::StreamCreated(base::SharedMemoryHandle shared_memory_handle,
                          size_t shared_memory_size,
                          base::SyncSocket::Handle socket_handle) {
  socket_.reset(new base::SyncSocket(socket_handle));
  shared_memory_.reset(new base::SharedMemory(shared_memory_handle, false));
  shared_memory_size_ = shared_memory_size;

  if (callback_) {
    shared_memory_->Map(shared_memory_size_);
    // In common case StartPlayback() was called before StreamCreated().
    if (playing_) {
      audio_thread_.reset(new base::DelegateSimpleThread(this,
          "plugin_audio_thread"));
      audio_thread_->Start();
    }
  }
}

void Audio::Run() {
  int pending_data;
  void* buffer = shared_memory_->memory();
  size_t buffer_size_in_bytes = config_->BufferSize();

  while (sizeof(pending_data) ==
      socket_->Receive(&pending_data, sizeof(pending_data)) &&
      pending_data >= 0) {
    // Exit the thread on pause.
    if (pending_data < 0)
      return;
    callback_(buffer, buffer_size_in_bytes, user_data_);
  }
}

}  // namespace pepper

<commit_msg>Fix the build warnings about bool conversion.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/glue/plugins/pepper_audio.h"

#include "base/logging.h"
#include "third_party/ppapi/c/dev/ppb_audio_dev.h"
#include "third_party/ppapi/c/dev/ppb_audio_trusted_dev.h"

namespace pepper {

namespace {

// PPB_AudioConfig -------------------------------------------------------------

uint32_t RecommendSampleFrameCount(uint32_t requested_sample_frame_count);

PP_Resource CreateStereo16bit(PP_Module module_id,
                              PP_AudioSampleRate_Dev sample_rate,
                              uint32_t sample_frame_count) {
  PluginModule* module = ResourceTracker::Get()->GetModule(module_id);
  if (!module)
    return 0;

  // TODO(brettw): Currently we don't actually check what the hardware
  // supports, so just allow sample rates of the "guaranteed working" ones.
  if (sample_rate != PP_AUDIOSAMPLERATE_44100 &&
      sample_rate != PP_AUDIOSAMPLERATE_48000)
    return 0;

  // TODO(brettw): Currently we don't actually query to get a value from the
  // hardware, so just validate the range.
  if (RecommendSampleFrameCount(sample_frame_count) != sample_frame_count)
    return 0;

  scoped_refptr<AudioConfig> config(new AudioConfig(module,
                                                    sample_rate,
                                                    sample_frame_count));
  return config->GetReference();
}

uint32_t RecommendSampleFrameCount(uint32_t requested_sample_frame_count) {
  // TODO(brettw) Currently we don't actually query to get a value from the
  // hardware, so we always return the input for in-range values.
  if (requested_sample_frame_count < PP_AUDIOMINSAMPLEFRAMECOUNT)
    return PP_AUDIOMINSAMPLEFRAMECOUNT;
  if (requested_sample_frame_count > PP_AUDIOMAXSAMPLEFRAMECOUNT)
    return PP_AUDIOMAXSAMPLEFRAMECOUNT;
  return requested_sample_frame_count;
}

bool IsAudioConfig(PP_Resource resource) {
  scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(resource);
  return !!config;
}

PP_AudioSampleRate_Dev GetSampleRate(PP_Resource config_id) {
  scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(config_id);
  return config ? config->sample_rate() : PP_AUDIOSAMPLERATE_NONE;
}

uint32_t GetSampleFrameCount(PP_Resource config_id) {
  scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(config_id);
  return config ? config->sample_frame_count() : 0;
}

const PPB_AudioConfig_Dev ppb_audioconfig = {
  &CreateStereo16bit,
  &RecommendSampleFrameCount,
  &IsAudioConfig,
  &GetSampleRate,
  &GetSampleFrameCount
};

// PPB_Audio -------------------------------------------------------------------

PP_Resource Create(PP_Instance instance_id, PP_Resource config_id,
                   PPB_Audio_Callback callback, void* user_data) {
  PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id);
  if (!instance)
    return 0;
  // TODO(neb): Require callback to be present for untrusted plugins.
  scoped_refptr<Audio> audio(new Audio(instance->module()));
  if (!audio->Init(instance->delegate(), config_id, callback, user_data))
    return 0;
  return audio->GetReference();
}

bool IsAudio(PP_Resource resource) {
  scoped_refptr<Audio> audio = Resource::GetAs<Audio>(resource);
  return !!audio;
}

PP_Resource GetCurrentConfiguration(PP_Resource audio_id) {
  scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id);
  return audio ? audio->GetCurrentConfiguration() : 0;
}

bool StartPlayback(PP_Resource audio_id) {
  scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id);
  return audio ? audio->StartPlayback() : false;
}

bool StopPlayback(PP_Resource audio_id) {
  scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id);
  return audio ? audio->StopPlayback() : false;
}

const PPB_Audio_Dev ppb_audio = {
  &Create,
  &IsAudio,
  &GetCurrentConfiguration,
  &StartPlayback,
  &StopPlayback,
};

// PPB_AudioTrusted ------------------------------------------------------------

PP_Resource GetBuffer(PP_Resource audio_id) {
  // TODO(neb): Implement me!
  return 0;
}

int GetOSDescriptor(PP_Resource audio_id) {
  // TODO(neb): Implement me!
  return -1;
}

const PPB_AudioTrusted_Dev ppb_audiotrusted = {
  &GetBuffer,
  &GetOSDescriptor
};

}  // namespace

// AudioConfig -----------------------------------------------------------------

AudioConfig::AudioConfig(PluginModule* module,
                         PP_AudioSampleRate_Dev sample_rate,
                         uint32_t sample_frame_count)
    : Resource(module),
      sample_rate_(sample_rate),
      sample_frame_count_(sample_frame_count) {
}

const PPB_AudioConfig_Dev* AudioConfig::GetInterface() {
  return &ppb_audioconfig;
}

size_t AudioConfig::BufferSize() {
  // TODO(audio): as more options become available, we'll need to
  // have additional code here to correctly calculate the size in
  // bytes of an audio buffer.  For now, only support two channel
  // int16_t sample buffers.
  const int kChannels = 2;
  const int kSizeOfSample = sizeof(int16_t);
  return static_cast<size_t>(sample_frame_count_ * kSizeOfSample * kChannels);
}

AudioConfig* AudioConfig::AsAudioConfig() {
  return this;
}

// Audio -----------------------------------------------------------------------

Audio::Audio(PluginModule* module)
    : Resource(module),
      playing_(false),
      socket_(NULL),
      shared_memory_(NULL),
      shared_memory_size_(0),
      callback_(NULL),
      user_data_(NULL) {
}

Audio::~Audio() {
  // Calling ShutDown() makes sure StreamCreated cannot be called anymore.
  audio_->ShutDown();
  // Closing the socket causes the thread to exit - wait for it.
  socket_->Close();
  if (audio_thread_.get()) {
    audio_thread_->Join();
    audio_thread_.reset();
  }
  // Shared memory destructor will unmap the memory automatically.
}

const PPB_Audio_Dev* Audio::GetInterface() {
  return &ppb_audio;
}

const PPB_AudioTrusted_Dev* Audio::GetTrustedInterface() {
  return &ppb_audiotrusted;
}

Audio* Audio::AsAudio() {
  return this;
}

bool Audio::Init(PluginDelegate* plugin_delegate, PP_Resource config_id,
                 PPB_Audio_Callback callback, void* user_data) {
  CHECK(!audio_.get());
  config_ = Resource::GetAs<AudioConfig>(config_id);
  if (!config_)
    return false;
  callback_ = callback;
  user_data_ = user_data;
  // When the stream is created, we'll get called back in StreamCreated().
  audio_.reset(plugin_delegate->CreateAudio(config_->sample_rate(),
                                            config_->sample_frame_count(),
                                            this));
  return audio_.get() != NULL;
}

bool Audio::StartPlayback() {
  if (playing_)
    return true;

  CHECK(!audio_thread_.get());
  if (callback_ && socket_.get()) {
    audio_thread_.reset(new base::DelegateSimpleThread(this,
                                                       "plugin_audio_thread"));
    audio_thread_->Start();
  }
  playing_ = true;
  return audio_->StartPlayback();
}

bool Audio::StopPlayback() {
  if (!playing_)
    return true;

  if (!audio_->StopPlayback())
    return false;

  if (audio_thread_.get()) {
    audio_thread_->Join();
    audio_thread_.reset();
  }
  playing_ = false;
  return true;
}

void Audio::StreamCreated(base::SharedMemoryHandle shared_memory_handle,
                          size_t shared_memory_size,
                          base::SyncSocket::Handle socket_handle) {
  socket_.reset(new base::SyncSocket(socket_handle));
  shared_memory_.reset(new base::SharedMemory(shared_memory_handle, false));
  shared_memory_size_ = shared_memory_size;

  if (callback_) {
    shared_memory_->Map(shared_memory_size_);
    // In common case StartPlayback() was called before StreamCreated().
    if (playing_) {
      audio_thread_.reset(new base::DelegateSimpleThread(this,
          "plugin_audio_thread"));
      audio_thread_->Start();
    }
  }
}

void Audio::Run() {
  int pending_data;
  void* buffer = shared_memory_->memory();
  size_t buffer_size_in_bytes = config_->BufferSize();

  while (sizeof(pending_data) ==
      socket_->Receive(&pending_data, sizeof(pending_data)) &&
      pending_data >= 0) {
    // Exit the thread on pause.
    if (pending_data < 0)
      return;
    callback_(buffer, buffer_size_in_bytes, user_data_);
  }
}

}  // namespace pepper

<|endoftext|>


<commit_before>// Copyright (c) 2019 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list ofconditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "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 THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <iostream>

int main(int argc, char* argv[]) {
  (void)argc, (void)argv;

  std::cout << "Welcome to NYX !" << std::endl;

  return 0;
}
<commit_msg>:construction: chore(test) add test for nyx script<commit_after>// Copyright (c) 2019 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list ofconditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "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 THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <fstream>
#include <iostream>
#include <sstream>
#include "lexer.hh"

int main(int argc, char* argv[]) {
  (void)argc, (void)argv;

  std::cout << "Welcome to NYX !" << std::endl;

  if (argc < 2) {
    std::cerr << "USAGE: " << argv[0] << " {FILE_NAME}" << std::endl;
    return -1;
  }

  std::ifstream fp(argv[1]);
  if (!fp.is_open()) {
    std::cerr << "open file \"" << argv[1] << "\" failed" << std::endl;
    return -1;
  }
  std::stringstream ss;
  ss << fp.rdbuf();
  std::string source_bytes(ss.str());

  nyx::Lexer lex(source_bytes);
  while (true) {
    auto tok = lex.next_token();
    std::cout << tok << std::endl;

    if (tok.get_kind() == nyx::TokenKind::TK_EOF)
      break;
  }

  return 0;
}
<|endoftext|>


<commit_before>/**
 * This file is part of the CernVM File System.
 */

#include "dirtab.h"

#include <fstream>
#include <sstream>

#include "util.h"

using namespace catalog;

Dirtab::Dirtab() : valid_(true) {}

Dirtab::Dirtab(const std::string &dirtab_path) {
  if (! FileExists(dirtab_path)) {
    LogCvmfs(kLogCatalog, kLogStderr, "Cannot find dirtab at '%s'",
             dirtab_path.c_str());
    valid_ = false;
    return;
  }

  std::ifstream dirtab(dirtab_path.c_str());
  if (!dirtab) {
    LogCvmfs(kLogCatalog, kLogStderr, "Cannot open dirtab for reading at '%s'",
             dirtab_path.c_str());
    valid_ = false;
    return;
  }

  valid_ = Parse(dirtab);
  dirtab.close();
}

bool Dirtab::Parse(const std::string &dirtab) {
  std::istringstream iss(dirtab);
  const bool parse_success = Parse(iss);
  valid_ = parse_success;
  return parse_success;
}

bool Dirtab::Parse(std::istream &dirtab) {
  std::string line;
  bool all_valid = true;
  while (std::getline(dirtab, line)) {
    if (! ParseLine(line)) {
      all_valid = false;
    }
  }
  return all_valid && CheckRuleValidity();
}

bool Dirtab::ParseLine(const std::string &line) {
        std::string::const_iterator itr  = line.begin();
  const std::string::const_iterator iend = line.end();
  bool negation = false;

  // parse preamble
  SkipWhitespace(itr, iend);
  if (*itr == Dirtab::kCommentMarker) {
    return true;
  } else if (*itr == Dirtab::kNegationMarker) {
    negation = true;
    ++itr;
    SkipWhitespace(itr, iend);
  }

  // extract and parse pathspec
  std::string pathspec_str(itr, iend);
  if (pathspec_str.empty()) {
    return true;
  }
  Pathspec pathspec(pathspec_str);
  if (!pathspec.IsValid()) {
    return false;
  }

  // create a new dirtab rule
  const Rule rule(pathspec, negation);
  AddRule(rule);
  return true;
}

void Dirtab::AddRule(const Rule &rule) {
  if (rule.is_negation) {
    negative_rules_.push_back(rule);
  } else {
    positive_rules_.push_back(rule);
  }
}

bool Dirtab::CheckRuleValidity() const {
  // check if there are contradicting positive and negative rules
        Rules::const_iterator p    = positive_rules_.begin();
  const Rules::const_iterator pend = positive_rules_.end();
  for (; p != pend; ++p) {
    assert (! p->is_negation);
          Rules::const_iterator n    = negative_rules_.begin();
    const Rules::const_iterator nend = negative_rules_.end();
    for (; n != nend; ++n) {
      assert (n->is_negation);
      if (p->pathspec == n->pathspec) {
        return false;
      }
    }
  }

  return true;
}

bool Dirtab::IsMatching(const std::string &path) const {
  // check if path has a positive match
  bool has_positive_match = false;
        Rules::const_iterator p    = positive_rules_.begin();
  const Rules::const_iterator pend = positive_rules_.end();
  for (; p != pend; ++p) {
    assert (! p->is_negation);
    if (p->pathspec.IsMatching(path)) {
      has_positive_match = true;
      break;
    }
  }

  // no positive match, no match in general!
  if (! has_positive_match) {
    return false;
  }

  // check for negative matches (meaning no match in general)
        Rules::const_iterator n    = negative_rules_.begin();
  const Rules::const_iterator nend = negative_rules_.end();
  for (; n != nend; ++n) {
    assert (n->is_negation);
    if (n->pathspec.IsMatching(path)) {
      return false;
    }
  }

  // all good, path is matching dirtab
  return true;
}
<commit_msg>positive rules in dirtab must be absolute<commit_after>/**
 * This file is part of the CernVM File System.
 */

#include "dirtab.h"

#include <fstream>
#include <sstream>

#include "util.h"

using namespace catalog;

Dirtab::Dirtab() : valid_(true) {}

Dirtab::Dirtab(const std::string &dirtab_path) {
  if (! FileExists(dirtab_path)) {
    LogCvmfs(kLogCatalog, kLogStderr, "Cannot find dirtab at '%s'",
             dirtab_path.c_str());
    valid_ = false;
    return;
  }

  std::ifstream dirtab(dirtab_path.c_str());
  if (!dirtab) {
    LogCvmfs(kLogCatalog, kLogStderr, "Cannot open dirtab for reading at '%s'",
             dirtab_path.c_str());
    valid_ = false;
    return;
  }

  valid_ = Parse(dirtab);
  dirtab.close();
}

bool Dirtab::Parse(const std::string &dirtab) {
  std::istringstream iss(dirtab);
  const bool parse_success = Parse(iss);
  valid_ = parse_success;
  return parse_success;
}

bool Dirtab::Parse(std::istream &dirtab) {
  std::string line;
  bool all_valid = true;
  while (std::getline(dirtab, line)) {
    if (! ParseLine(line)) {
      all_valid = false;
    }
  }
  return all_valid && CheckRuleValidity();
}

bool Dirtab::ParseLine(const std::string &line) {
        std::string::const_iterator itr  = line.begin();
  const std::string::const_iterator iend = line.end();
  bool negation = false;

  // parse preamble
  SkipWhitespace(itr, iend);
  if (*itr == Dirtab::kCommentMarker) {
    return true;
  } else if (*itr == Dirtab::kNegationMarker) {
    negation = true;
    ++itr;
    SkipWhitespace(itr, iend);
  }

  // extract and parse pathspec
  std::string pathspec_str(itr, iend);
  if (pathspec_str.empty()) {
    return true;
  }
  Pathspec pathspec(pathspec_str);
  if ( !pathspec.IsValid() ||
      (!negation && !pathspec.IsAbsolute())) {
    return false;
  }

  // create a new dirtab rule
  const Rule rule(pathspec, negation);
  AddRule(rule);
  return true;
}

void Dirtab::AddRule(const Rule &rule) {
  if (rule.is_negation) {
    negative_rules_.push_back(rule);
  } else {
    positive_rules_.push_back(rule);
  }
}

bool Dirtab::CheckRuleValidity() const {
  // check if there are contradicting positive and negative rules
        Rules::const_iterator p    = positive_rules_.begin();
  const Rules::const_iterator pend = positive_rules_.end();
  for (; p != pend; ++p) {
    assert (! p->is_negation);
          Rules::const_iterator n    = negative_rules_.begin();
    const Rules::const_iterator nend = negative_rules_.end();
    for (; n != nend; ++n) {
      assert (n->is_negation);
      if (p->pathspec == n->pathspec) {
        return false;
      }
    }
  }

  return true;
}

bool Dirtab::IsMatching(const std::string &path) const {
  // check if path has a positive match
  bool has_positive_match = false;
        Rules::const_iterator p    = positive_rules_.begin();
  const Rules::const_iterator pend = positive_rules_.end();
  for (; p != pend; ++p) {
    assert (! p->is_negation);
    if (p->pathspec.IsMatching(path)) {
      has_positive_match = true;
      break;
    }
  }

  // no positive match, no match in general!
  if (! has_positive_match) {
    return false;
  }

  // check for negative matches (meaning no match in general)
        Rules::const_iterator n    = negative_rules_.begin();
  const Rules::const_iterator nend = negative_rules_.end();
  for (; n != nend; ++n) {
    assert (n->is_negation);
    if (n->pathspec.IsMatching(path)) {
      return false;
    }
  }

  // all good, path is matching dirtab
  return true;
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "TimerTaskHeap.h"

using namespace decaf;
using namespace decaf::internal;
using namespace decaf::internal::util;

////////////////////////////////////////////////////////////////////////////////
TimerTaskHeap::TimerTaskHeap() {
}

////////////////////////////////////////////////////////////////////////////////
TimerTaskHeap::~TimerTaskHeap() {
}

////////////////////////////////////////////////////////////////////////////////
Pointer<TimerTask> TimerTaskHeap::peek() {

    if( heap.empty() ) {
        return Pointer<TimerTask>();
    }

    return heap[0];
}

////////////////////////////////////////////////////////////////////////////////
bool TimerTaskHeap::isEmpty() const {
    return heap.empty();
}

////////////////////////////////////////////////////////////////////////////////
std::size_t TimerTaskHeap::size() const {
    return this->heap.size();
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::insert( const Pointer<TimerTask>& task ) {

    heap.push_back( task );
    upHeap();
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::remove( std::size_t pos ) {

    // possible to delete any position of the heap
    if( pos < heap.size() ) {
        heap[pos] = heap.back();
        heap.pop_back();
        downHeap( pos );
    }
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::upHeap() {

	std::size_t current = heap.size() - 1;
	std::size_t parent = ( current - 1 ) / 2;

    while( heap[current]->when < heap[parent]->when) {

        // swap the two
        Pointer<TimerTask> tmp = heap[current];
        heap[current] = heap[parent];
        heap[parent] = tmp;

        // update parent and current positions.
        current = parent;
        parent = ( current - 1 ) / 2;
    }
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::downHeap( std::size_t pos ) {

    std::size_t current = pos;
    std::size_t child = 2 * current + 1;

    while( child < heap.size() && !heap.empty() ) {

        // compare the children if they exist
        if( child + 1 < heap.size() && heap[child + 1]->when < heap[child]->when) {
            child++;
        }

        // compare selected child with parent
        if( heap[current]->when < heap[child]->when ) {
            break;
        }

        // swap the two
        Pointer<TimerTask> tmp = heap[current];
        heap[current] = heap[child];
        heap[child] = tmp;

        // update child and current positions
        current = child;
        child = 2 * current + 1;
    }
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::reset() {
    heap.clear();
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::adjustMinimum() {
    downHeap( 0 );
}

////////////////////////////////////////////////////////////////////////////////
std::size_t TimerTaskHeap::deleteIfCancelled() {

    std::size_t result = 0;

    for( std::size_t i = 0; i < heap.size(); ++i ) {
        if( heap[i]->cancelled ) {
            result++;
            remove( i );
            // re-try this point
            i--;
        }
    }

    return result;
}

////////////////////////////////////////////////////////////////////////////////
std::size_t TimerTaskHeap::find( const Pointer<TimerTask>& task ) const {

    for( std::size_t i = 0; i < heap.size(); ++i ) {
        if( heap[i] == task ) {
            return i;
        }
    }

    return -1;
}
<commit_msg>64bit OS fix<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "TimerTaskHeap.h"

using namespace decaf;
using namespace decaf::internal;
using namespace decaf::internal::util;

////////////////////////////////////////////////////////////////////////////////
TimerTaskHeap::TimerTaskHeap() {
}

////////////////////////////////////////////////////////////////////////////////
TimerTaskHeap::~TimerTaskHeap() {
}

////////////////////////////////////////////////////////////////////////////////
Pointer<TimerTask> TimerTaskHeap::peek() {

    if( heap.empty() ) {
        return Pointer<TimerTask>();
    }

    return heap[0];
}

////////////////////////////////////////////////////////////////////////////////
bool TimerTaskHeap::isEmpty() const {
    return heap.empty();
}

////////////////////////////////////////////////////////////////////////////////
std::size_t TimerTaskHeap::size() const {
    return this->heap.size();
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::insert( const Pointer<TimerTask>& task ) {

    heap.push_back( task );
    upHeap();
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::remove( std::size_t pos ) {

    // possible to delete any position of the heap
    if( pos < heap.size() ) {
        heap[pos] = heap.back();
        heap.pop_back();
        downHeap( pos );
    }
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::upHeap() {

    if( heap.size() <= 1 ) {
        return;  // Can't get any higher than the top.
    }

    std::size_t current = heap.size() - 1;
    std::size_t parent = ( current - 1 ) / 2;

    while( heap[current]->when < heap[parent]->when) {

        // swap the two
        Pointer<TimerTask> tmp = heap[current];
        heap[current] = heap[parent];
        heap[parent] = tmp;

        // update parent and current positions.
        current = parent;
        parent = ( current - 1 ) / 2;
    }
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::downHeap( std::size_t pos ) {

    std::size_t current = pos;
    std::size_t child = 2 * current + 1;

    while( child < heap.size() && !heap.empty() ) {

        // compare the children if they exist
        if( child + 1 < heap.size() && heap[child + 1]->when < heap[child]->when) {
            child++;
        }

        // compare selected child with parent
        if( heap[current]->when < heap[child]->when ) {
            break;
        }

        // swap the two
        Pointer<TimerTask> tmp = heap[current];
        heap[current] = heap[child];
        heap[child] = tmp;

        // update child and current positions
        current = child;
        child = 2 * current + 1;
    }
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::reset() {
    heap.clear();
}

////////////////////////////////////////////////////////////////////////////////
void TimerTaskHeap::adjustMinimum() {
    downHeap( 0 );
}

////////////////////////////////////////////////////////////////////////////////
std::size_t TimerTaskHeap::deleteIfCancelled() {

    std::size_t result = 0;

    for( std::size_t i = 0; i < heap.size(); ++i ) {
        if( heap[i]->cancelled ) {
            result++;
            remove( i );
            // re-try this point
            i--;
        }
    }

    return result;
}

////////////////////////////////////////////////////////////////////////////////
std::size_t TimerTaskHeap::find( const Pointer<TimerTask>& task ) const {

    for( std::size_t i = 0; i < heap.size(); ++i ) {
        if( heap[i] == task ) {
            return i;
        }
    }

    return -1;
}
<|endoftext|>


<commit_before>#include "commands.h"
#include "sim/except.h"
#include <iostream>

using namespace std;

void PrintException(Simulator::MGSystem *sys, ostream& out, const exception& e)
{
    out << endl << e.what() << endl;

    auto se = dynamic_cast<const Simulator::SimulationException*>(&e);
    if (se != NULL)
    {
        // SimulationExceptions hold more information, print it
        for (auto& p : se->GetDetails())
            out << p << endl;

        auto te = dynamic_cast<const Simulator::ProgramTerminationException*>(se);
        if (te == NULL && se->GetPC() != 0)
        {
            // We avoid printing the backtrace when receiving an exception
            // for normal program termination.
            assert(sys != NULL);
            sys->Disassemble(se->GetPC());
        }
    }
}

<commit_msg>Enable using PrintException even when no MGSystem is present.<commit_after>#include "commands.h"
#include "sim/except.h"
#include <iostream>

using namespace std;

void PrintException(Simulator::MGSystem *sys, ostream& out, const exception& e)
{
    out << endl << e.what() << endl;

    auto se = dynamic_cast<const Simulator::SimulationException*>(&e);
    if (se != NULL)
    {
        // SimulationExceptions hold more information, print it
        for (auto& p : se->GetDetails())
            out << p << endl;

        auto te = dynamic_cast<const Simulator::ProgramTerminationException*>(se);
        if (te == NULL && se->GetPC() != 0)
        {
            // We avoid printing the backtrace when receiving an exception
            // for normal program termination.
            if (sys != NULL)
                // Only disassemble if there is a system to do so.
                sys->Disassemble(se->GetPC());
        }
    }
}
<|endoftext|>


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

#include "uv.h"
#include "Core.h"

#ifdef WIN32
#include "webrtc/base/win32socketinit.h"
#endif

using namespace WebRTC;

rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> _factory;
rtc::scoped_ptr<cricket::DeviceManagerInterface> _manager;
uv_check_t _msg;

static void ProcessMessages(uv_check_t* handle) {
  rtc::Thread::Current()->ProcessMessages(0);
}

void Core::Init() {
#ifdef WIN32
  rtc::EnsureWinsockInit();
#endif
  uv_check_init(uv_default_loop(), &_msg);
  uv_check_start(&_msg, ProcessMessages);
  uv_unref(reinterpret_cast<uv_handle_t*>(&_msg));

  rtc::InitializeSSL();
  _factory = webrtc::CreatePeerConnectionFactory();
  _manager.reset(cricket::DeviceManagerFactory::Create());

  if (!_manager->Init()) {
    _manager.release();
  }
}

void Core::Dispose() {
  uv_check_stop(&_msg);
  _factory.release();
  _manager.release();
}

webrtc::PeerConnectionFactoryInterface* Core::GetFactory() {
  return _factory.get();
}

cricket::DeviceManagerInterface* Core::GetManager() {
  return _manager.get();
}<commit_msg>Terminate Manager<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 vmolsa <ville.molsa@gmail.com> (http://github.com/vmolsa)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/

#include "uv.h"
#include "Core.h"

#ifdef WIN32
#include "webrtc/base/win32socketinit.h"
#endif

using namespace WebRTC;

rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> _factory;
rtc::scoped_ptr<cricket::DeviceManagerInterface> _manager;
uv_check_t _msg;

static void ProcessMessages(uv_check_t* handle) {
  rtc::Thread::Current()->ProcessMessages(0);
}

void Core::Init() {
#ifdef WIN32
  rtc::EnsureWinsockInit();
#endif
  uv_check_init(uv_default_loop(), &_msg);
  uv_check_start(&_msg, ProcessMessages);
  uv_unref(reinterpret_cast<uv_handle_t*>(&_msg));

  rtc::InitializeSSL();
  _factory = webrtc::CreatePeerConnectionFactory();
  _manager.reset(cricket::DeviceManagerFactory::Create());

  if (!_manager->Init()) {
    _manager.release();
  }
}

void Core::Dispose() {
  uv_check_stop(&_msg);
  _factory.release();

  if (_manager.get()) {
    _manager->Terminate();
  }

  _manager.release();
}

webrtc::PeerConnectionFactoryInterface* Core::GetFactory() {
  return _factory.get();
}

cricket::DeviceManagerInterface* Core::GetManager() {
  return _manager.get();
}<|endoftext|>