<commit_before>/*************************************************************************
 *
 *  $RCSfile: editable.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 11:33:11 $
 *
 *  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_EDITABLE_HXX
#define SC_EDITABLE_HXX

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

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif

class ScDocument;
class ScViewFunc;
class ScMarkData;
class ScRange;

class ScEditableTester
{
    BOOL    bIsEditable;
    BOOL    bOnlyMatrix;

public:
            // no test in ctor
            ScEditableTester();

            // calls TestBlock
            ScEditableTester( ScDocument* pDoc, SCTAB nTab,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow );

            // calls TestSelectedBlock
            ScEditableTester( ScDocument* pDoc,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow,
                        const ScMarkData& rMark );

            // calls TestRange
            ScEditableTester( ScDocument* pDoc, const ScRange& rRange );

            // calls TestSelection
            ScEditableTester( ScDocument* pDoc, const ScMarkData& rMark );

            // calls TestView
            ScEditableTester( ScViewFunc* pView );

            ~ScEditableTester() {}

            // Several calls to the Test... methods check if *all* of the ranges
            // are editable. For several independent checks, Reset() has to be used.
    void    TestBlock( ScDocument* pDoc, SCTAB nTab,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow );
    void    TestSelectedBlock( ScDocument* pDoc,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow,
                        const ScMarkData& rMark );
    void    TestRange( ScDocument* pDoc, const ScRange& rRange );
    void    TestSelection( ScDocument* pDoc, const ScMarkData& rMark );
    void    TestView( ScViewFunc* pView );

    void    Reset();

    BOOL    IsEditable() const          { return bIsEditable; }
    BOOL    IsFormatEditable() const    { return bIsEditable || bOnlyMatrix; }
    USHORT  GetMessageId() const;
};

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.452); FILE MERGED 2005/09/05 15:05:19 rt 1.2.452.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: editable.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 21:23:46 $
 *
 *  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_EDITABLE_HXX
#define SC_EDITABLE_HXX

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

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif

class ScDocument;
class ScViewFunc;
class ScMarkData;
class ScRange;

class ScEditableTester
{
    BOOL    bIsEditable;
    BOOL    bOnlyMatrix;

public:
            // no test in ctor
            ScEditableTester();

            // calls TestBlock
            ScEditableTester( ScDocument* pDoc, SCTAB nTab,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow );

            // calls TestSelectedBlock
            ScEditableTester( ScDocument* pDoc,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow,
                        const ScMarkData& rMark );

            // calls TestRange
            ScEditableTester( ScDocument* pDoc, const ScRange& rRange );

            // calls TestSelection
            ScEditableTester( ScDocument* pDoc, const ScMarkData& rMark );

            // calls TestView
            ScEditableTester( ScViewFunc* pView );

            ~ScEditableTester() {}

            // Several calls to the Test... methods check if *all* of the ranges
            // are editable. For several independent checks, Reset() has to be used.
    void    TestBlock( ScDocument* pDoc, SCTAB nTab,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow );
    void    TestSelectedBlock( ScDocument* pDoc,
                        SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow,
                        const ScMarkData& rMark );
    void    TestRange( ScDocument* pDoc, const ScRange& rRange );
    void    TestSelection( ScDocument* pDoc, const ScMarkData& rMark );
    void    TestView( ScViewFunc* pView );

    void    Reset();

    BOOL    IsEditable() const          { return bIsEditable; }
    BOOL    IsFormatEditable() const    { return bIsEditable || bOnlyMatrix; }
    USHORT  GetMessageId() const;
};

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: expftext.hxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:44:58 $
 *
 *  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

class 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 tune03 (1.1.1.1.530); FILE MERGED 2004/07/08 16:45:10 mhu 1.1.1.1.530.1: #i29979# Added SC_DLLPUBLIC/PRIVATE (see scdllapi.h) to exported symbols/classes.<commit_after>/*************************************************************************
 *
 *  $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
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: validate.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: dr $ $Date: 2001-05-22 13:16:10 $
 *
 *  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_VALIDATE_HXX
#define SC_VALIDATE_HXX

#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif

#ifndef _SV_EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif

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

#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _SVEDIT_HXX //autogen
#include <svtools/svmedit.hxx>
#endif

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

class ScValidationDlg : public SfxTabDialog
{
public:
                ScValidationDlg( Window* pParent, const SfxItemSet* pArgSet );
                ~ScValidationDlg();

};

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

class ScTPValidationValue : public SfxTabPage
{
private:
    FixedText   aFtAllow;
    ListBox     aLbAllow;
    TriStateBox aTsbAllow;
    FixedText   aFtValue;
    ListBox     aLbValue;
    FixedText   aFtMin;
    Edit        aEdtMin;
    FixedText   aFtMax;
    Edit        aEdtMax;

    String      aStrMin;
    String      aStrMax;
    String      aStrValue;

    const SfxItemSet& rSet;

#ifdef _VALIDATE_CXX
    void    Init();

    // Handler ------------------------
    DECL_LINK( SelectAllowHdl, ListBox * );
    DECL_LINK( SelectValueHdl, ListBox * );
#endif

public:
            ScTPValidationValue( Window* pParent, const SfxItemSet& rArgSet );
            ~ScTPValidationValue();

    static  SfxTabPage* Create      ( Window* pParent, const SfxItemSet& rArgSet );
    static  USHORT*     GetRanges   ();
    virtual BOOL        FillItemSet ( SfxItemSet& rArgSet );
    virtual void        Reset       ( const SfxItemSet& rArgSet );
};

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

class ScTPValidationHelp : public SfxTabPage
{
private:
    TriStateBox     aTsbHelp;
    FixedLine       aFlContent;
    FixedText       aFtTitle;
    Edit            aEdtTitle;
    FixedText       aFtInputHelp;
    MultiLineEdit   aEdInputHelp;

    const SfxItemSet& rSet;

#ifdef _VALIDATE_CXX
    void    Init();

    // Handler ------------------------
    // DECL_LINK( SelectHdl, ListBox * );
#endif

public:
            ScTPValidationHelp( Window* pParent, const SfxItemSet& rArgSet );
            ~ScTPValidationHelp();

    static  SfxTabPage* Create      ( Window* pParent, const SfxItemSet& rArgSet );
    static  USHORT*     GetRanges   ();
    virtual BOOL        FillItemSet ( SfxItemSet& rArgSet );
    virtual void        Reset       ( const SfxItemSet& rArgSet );
};

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

class ScTPValidationError : public SfxTabPage
{
private:
    TriStateBox     aTsbShow;
    FixedLine       aFlContent;
    FixedText       aFtAction;
    ListBox         aLbAction;
    PushButton      aBtnSearch;
    FixedText       aFtTitle;
    Edit            aEdtTitle;
    FixedText       aFtError;
    MultiLineEdit   aEdError;

    const SfxItemSet& rSet;

#ifdef _VALIDATE_CXX
    void    Init();

    // Handler ------------------------
    DECL_LINK( SelectActionHdl, ListBox * );
    DECL_LINK( ClickSearchHdl, PushButton * );
#endif

public:
            ScTPValidationError( Window* pParent, const SfxItemSet& rArgSet );
            ~ScTPValidationError();

    static  SfxTabPage* Create      ( Window* pParent, const SfxItemSet& rArgSet );
    static  USHORT*     GetRanges   ();
    virtual BOOL        FillItemSet ( SfxItemSet& rArgSet );
    virtual void        Reset       ( const SfxItemSet& rArgSet );
};

#endif // SC_VALIDATE_HXX

<commit_msg>INTEGRATION: CWS dr6 (1.2.30); FILE MERGED 2003/07/10 06:40:26 dr 1.2.30.2: #i3653# list validity 2003/07/04 12:36:58 dr 1.2.30.1: #i3653# additions for list validation<commit_after>/*************************************************************************
 *
 *  $RCSfile: validate.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hjs $ $Date: 2003-08-19 11:40:15 $
 *
 *  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_VALIDATE_HXX
#define SC_VALIDATE_HXX

#ifndef _SFXTABDLG_HXX
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _SV_EDIT_HXX
#include <vcl/edit.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SVEDIT_HXX
#include <svtools/svmedit.hxx>
#endif

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

/** The "Validity" tab dialog. */
class ScValidationDlg : public SfxTabDialog
{
public:
    explicit                    ScValidationDlg( Window* pParent, const SfxItemSet* pArgSet );
    virtual                     ~ScValidationDlg();
};

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

/** The tab page "Criteria" from the Validation dialog. */
class ScTPValidationValue : public SfxTabPage
{
public:
    explicit                    ScTPValidationValue( Window* pParent, const SfxItemSet& rArgSet );
    virtual                     ~ScTPValidationValue();

    static SfxTabPage*          Create( Window* pParent, const SfxItemSet& rArgSet );
    static USHORT*              GetRanges();

    virtual BOOL                FillItemSet( SfxItemSet& rArgSet );
    virtual void                Reset( const SfxItemSet& rArgSet );

private:
    void                        Init();

    String                      GetFirstFormula() const;
    String                      GetSecondFormula() const;

    void                        SetFirstFormula( const String& rFmlaStr );
    void                        SetSecondFormula( const String& rFmlaStr );

                                DECL_LINK( SelectHdl, ListBox* );
                                DECL_LINK( CheckHdl, CheckBox* );

    FixedText                   maFtAllow;
    ListBox                     maLbAllow;
    CheckBox                    maCbAllow;      /// Allow blank cells.
    CheckBox                    maCbShow;       /// Show selection list in cell.
    CheckBox                    maCbSort;       /// Sort selection list in cell.
    FixedText                   maFtValue;
    ListBox                     maLbValue;
    FixedText                   maFtMin;
    Edit                        maEdMin;
    MultiLineEdit               maEdList;       /// Entries for explicit list
    FixedText                   maFtMax;
    Edit                        maEdMax;
    FixedText                   maFtHint;       /// Hint text for cell range validity.

    String                      maStrMin;
    String                      maStrMax;
    String                      maStrValue;
    String                      maStrRange;
    String                      maStrList;
    sal_Unicode                 mcFmlaSep;      /// List separator in formulas.
};

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

class ScTPValidationHelp : public SfxTabPage
{
private:
    TriStateBox     aTsbHelp;
    FixedLine       aFlContent;
    FixedText       aFtTitle;
    Edit            aEdtTitle;
    FixedText       aFtInputHelp;
    MultiLineEdit   aEdInputHelp;

    const SfxItemSet& mrArgSet;

    void    Init();

    // Handler ------------------------
    // DECL_LINK( SelectHdl, ListBox * );

public:
            ScTPValidationHelp( Window* pParent, const SfxItemSet& rArgSet );
            ~ScTPValidationHelp();

    static  SfxTabPage* Create      ( Window* pParent, const SfxItemSet& rArgSet );
    static  USHORT*     GetRanges   ();
    virtual BOOL        FillItemSet ( SfxItemSet& rArgSet );
    virtual void        Reset       ( const SfxItemSet& rArgSet );
};

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

class ScTPValidationError : public SfxTabPage
{
private:
    TriStateBox     aTsbShow;
    FixedLine       aFlContent;
    FixedText       aFtAction;
    ListBox         aLbAction;
    PushButton      aBtnSearch;
    FixedText       aFtTitle;
    Edit            aEdtTitle;
    FixedText       aFtError;
    MultiLineEdit   aEdError;

    const SfxItemSet& mrArgSet;

    void    Init();

    // Handler ------------------------
    DECL_LINK( SelectActionHdl, ListBox * );
    DECL_LINK( ClickSearchHdl, PushButton * );

public:
            ScTPValidationError( Window* pParent, const SfxItemSet& rArgSet );
            ~ScTPValidationError();

    static  SfxTabPage* Create      ( Window* pParent, const SfxItemSet& rArgSet );
    static  USHORT*     GetRanges   ();
    virtual BOOL        FillItemSet ( SfxItemSet& rArgSet );
    virtual void        Reset       ( const SfxItemSet& rArgSet );
};

#endif // SC_VALIDATE_HXX

<|endoftext|>


<commit_before>#include "iCubProprioception/CADSuperimposer.h"

#include <exception>
#include <utility>

#include <iCub/ctrl/math.h>
#include <yarp/math/Math.h>
#include <yarp/os/Bottle.h>
#include <yarp/os/LogStream.h>
#include <yarp/os/ResourceFinder.h>

using namespace yarp::dev;
using namespace yarp::math;
using namespace yarp::os;
using namespace yarp::sig;
using namespace iCub::ctrl;
using namespace iCub::iKin;

CADSuperimposer::CADSuperimposer(const ConstString& port_prefix, const ConstString& robot, const ConstString& camera,
                                 const SICAD::ModelPathContainer& cad_hand, const ConstString& shader_path) :
    ID_(port_prefix), log_ID_("[" + ID_ + "]"),
    robot_(robot), camera_(camera),
    cad_hand_(cad_hand), shader_path_(shader_path)
{
    yInfo() << log_ID_ << "Invoked CADSuperimposer (base class) ctor...";

    /* Port for the CAD superimposer to work */
    yInfo() << log_ID_ << "Opening ports for CAD images.";

    if (!inport_renderer_img_.open("/" + ID_ + "/cam/" + camera_ + ":i"))
    {
        yError() << log_ID_ << "Cannot open input image port for " + camera_ + " camera!";
        throw std::runtime_error("Cannot open input image port for " + camera_ + " camera!");
    }

    if (!outport_renderer_img_.open("/" + ID_ + "/cam/" + camera_ + ":o"))
    {
        yError() << log_ID_ << "Cannot open output image port for " + camera_ + " camera!";
        throw std::runtime_error("Cannot open output image port for " + camera_ + " camera!");
    }

    /* Setting up common gaze controller and camera parameters */
    if (openGazeController())
    {
        Bottle cam_info;
        itf_gaze_->getInfo(cam_info);
        yInfo() << log_ID_ << "[CAM PARAMS]" << cam_info.toString();
        Bottle* cam_sel_intrinsic  = cam_info.findGroup("camera_intrinsics_" + camera_).get(1).asList();
        cam_width_  = cam_info.findGroup("camera_width_" + camera_).get(1).asInt();
        cam_height_ = cam_info.findGroup("camera_height_" + camera_).get(1).asInt();
        cam_fx_     = static_cast<float>(cam_sel_intrinsic->get(0).asDouble());
        cam_cx_     = static_cast<float>(cam_sel_intrinsic->get(2).asDouble());
        cam_fy_     = static_cast<float>(cam_sel_intrinsic->get(5).asDouble());
        cam_cy_     = static_cast<float>(cam_sel_intrinsic->get(6).asDouble());
    }
    else
    {
        yWarning() << log_ID_ << "[CAM PARAMS]" << "No intrinisc camera information could be found by the ctor. Looking for fallback values in parameters.ini.";

        ResourceFinder rf;
        rf.setVerbose(true);
        rf.setDefaultConfigFile("parameters.ini");
        rf.setDefaultContext("iCubProprioception");
        rf.configure(0, YARP_NULLPTR);

        Bottle* fallback_intrinsic = rf.findGroup("FALLBACK").find("intrinsic_" + camera_).asList();
        if (fallback_intrinsic)
        {
            yInfo() << log_ID_ << "[FALLBACK][CAM PARAMS]" << fallback_intrinsic->toString();

            cam_width_  = fallback_intrinsic->get(0).asDouble();
            cam_height_ = fallback_intrinsic->get(1).asDouble();
            cam_fx_     = fallback_intrinsic->get(2).asDouble();
            cam_cx_     = fallback_intrinsic->get(3).asDouble();
            cam_fy_     = fallback_intrinsic->get(4).asDouble();
            cam_cy_     = fallback_intrinsic->get(5).asDouble();
        }
        else
        {
            yWarning() << log_ID_ << "[CAM PARAMS]" << "No fallback values could be found in parameters.ini by the ctor for the intrinisc camera parameters. Falling (even more) back to iCub_SIM values.";
            cam_width_  = 320;
            cam_height_ = 240;
            cam_fx_     = 257.34;
            cam_cx_     = 160;
            cam_fy_     = 257.34;
            cam_cy_     = 120;
        }
    }
    yInfo() << log_ID_ << "[CAM]" << "Running with:";
    yInfo() << log_ID_ << "[CAM]" << " - width:"  << cam_width_;
    yInfo() << log_ID_ << "[CAM]" << " - height:" << cam_height_;
    yInfo() << log_ID_ << "[CAM]" << " - fx:"     << cam_fx_;
    yInfo() << log_ID_ << "[CAM]" << " - fy:"     << cam_fy_;
    yInfo() << log_ID_ << "[CAM]" << " - cx:"     << cam_cx_;
    yInfo() << log_ID_ << "[CAM]" << " - cy:"     << cam_cy_;

    /* Initiliaze left eye interface */
    yInfo() << log_ID_ << "Setting" + camera_ + "eye.";

    eye_ = iCubEye(camera_ + "_v2");
    eye_.setAllConstraints(false);
    eye_.releaseLink(0);
    eye_.releaseLink(1);
    eye_.releaseLink(2);

    /* Initialize right hand finger interfaces */
    yInfo() << log_ID_ << "Setting right hand fingers.";

    right_finger_[0] = iCubFinger("right_thumb");
    right_finger_[1] = iCubFinger("right_index");
    right_finger_[2] = iCubFinger("right_middle");

    right_finger_[0].setAllConstraints(false);
    right_finger_[1].setAllConstraints(false);
    right_finger_[2].setAllConstraints(false);

    /* Initialize CAD superimposer */
    yInfo() << log_ID_ << "Setting up OpenGL drawer.";

    drawer_ = new SICAD(cad_hand_,
                        cam_width_, cam_height_, cam_fx_, cam_fy_, cam_cx_, cam_cy_,
                        1,
                        {1.0, 0.0, 0.0, M_PI},
                        shader_path_);

    drawer_->setBackgroundOpt(true);
    drawer_->setWireframeOpt(true);

    /* Open command port */
    if (!setCommandPort()) throw std::runtime_error("Cannot attach the command port.");

    yInfo() << log_ID_ << "...CADSuperimposer ctor completed!";
}

CADSuperimposer::~CADSuperimposer() noexcept
{
    delete drawer_;
}

void CADSuperimposer::run()
{
    ImageOf<PixelRgb>* tmp_imgin = YARP_NULLPTR;
    Vector tmp_root_eye_enc(8);
    Vector tmp_cam_pose(7);
    Vector tmp_ee_pose(7);
    Vector tmp_encs_arm(16);

    while (!isStopping())
    {
        tmp_imgin = inport_renderer_img_.read(false);
        if (tmp_imgin != YARP_NULLPTR)
            imgin_ = tmp_imgin;

        tmp_root_eye_enc = readRootToEye(camera_);
        if (!(tmp_root_eye_enc == zeros(tmp_root_eye_enc.size())))
            root_eye_enc_ = tmp_root_eye_enc;

        tmp_ee_pose = getEndEffectorPose();
        if (!(tmp_ee_pose == zeros(tmp_ee_pose.size())))
            ee_pose_ = tmp_ee_pose;

        tmp_encs_arm = getRightArmEncoders();
        if (!(tmp_encs_arm == zeros(tmp_encs_arm.size())))
            encs_arm_ = tmp_encs_arm;

        if (  imgin_        != YARP_NULLPTR                 &&
            !(root_eye_enc_ == zeros(root_eye_enc_.size())) &&
            !(ee_pose_      == zeros(ee_pose_.size()))      &&
            !(encs_arm_     == zeros(encs_arm_.size())))
        {
            eye_.setAng(CTRL_DEG2RAD * root_eye_enc_);
            Vector cam_pose = eye_.EndEffPose();

            if (ee_pose_.size() == 6)
            {
                double ang =  norm(ee_pose_.subVector(3, 5));
                ee_pose_(3) /= ang;
                ee_pose_(4) /= ang;
                ee_pose_(5) /= ang;
                ee_pose_.push_back(ang);
            }

#if ICP_USE_ANALOGS == 1
            Vector analogs;
            itf_right_hand_analog_->read(analogs);
            yAssert(analogs.size() >= 15);
#endif

            Vector chainjoints;
            for (unsigned int i = 0; i < 3; ++i)
            {
#if ICP_USE_ANALOGS == 1
                right_finger_[i].getChainJoints(encs_arm_, analogs, chainjoints);
#else
                right_finger_[i].getChainJoints(encs_arm_, chainjoints);
#endif

                right_finger_[i].setAng(CTRL_DEG2RAD * chainjoints);
            }

            Superimpose::ModelPoseContainer hand_pose;
            getRightHandObjPoseMap(ee_pose_, hand_pose);
            getExtraObjPoseMap(hand_pose);

            ImageOf<PixelRgb>& imgout = outport_renderer_img_.prepare();
            imgout = *imgin_;

            cv::Mat img = cv::cvarrToMat(imgout.getIplImage());
            drawer_->superimpose(hand_pose, cam_pose.data(), cam_pose.data()+3, img);

            outport_renderer_img_.write();
        }
    }
}

void CADSuperimposer::onStop()
{
    inport_renderer_img_.interrupt();
}

void CADSuperimposer::threadRelease()
{
    yInfo() << log_ID_ << "Deallocating resource...";

    if (!inport_renderer_img_.isClosed())  inport_renderer_img_.close();
    if (!outport_renderer_img_.isClosed()) outport_renderer_img_.close();

    if (port_command_.isOpen()) port_command_.close();

    yInfo() << log_ID_ << "...deallocation completed!";
}

void CADSuperimposer::getRightHandObjPoseMap(const Vector& ee_pose, Superimpose::ModelPoseContainer& hand_pose)
{
    Superimpose::ModelPose pose;

    Matrix Ha = axis2dcm(ee_pose.subVector(3, 6));
    Ha.setSubcol(ee_pose.subVector(0, 2), 0, 3);
    Ha(3, 3) = 1.0;

    pose.assign(ee_pose.data(), ee_pose.data()+7);
    hand_pose.emplace("palm", pose);
    for (size_t fng = 1; fng < 3; ++fng)
    {
        std::string finger_s;
        pose.clear();
        if (fng != 0)
        {
            Vector j_x = (Ha * (right_finger_[fng].getH0().getCol(3))).subVector(0, 2);
            Vector j_o = dcm2axis(Ha * right_finger_[fng].getH0());

            if      (fng == 1) { finger_s = "index0";  }
            else if (fng == 2) { finger_s = "medium0"; }

            pose.assign(j_x.data(), j_x.data()+3);
            pose.insert(pose.end(), j_o.data(), j_o.data()+4);
            hand_pose.emplace(finger_s, pose);
        }

        for (size_t i = 0; i < right_finger_[fng].getN(); ++i)
        {
            Vector j_x = (Ha * (right_finger_[fng].getH(i, true).getCol(3))).subVector(0, 2);
            Vector j_o = dcm2axis(Ha * right_finger_[fng].getH(i, true));

            if      (fng == 0) { finger_s = "thumb"  + std::to_string(i+1); }
            else if (fng == 1) { finger_s = "index"  + std::to_string(i+1); }
            else if (fng == 2) { finger_s = "medium" + std::to_string(i+1); }

            pose.assign(j_x.data(), j_x.data()+3);
            pose.insert(pose.end(), j_o.data(), j_o.data()+4);
            hand_pose.emplace(finger_s, pose);
        }
    }
}

bool CADSuperimposer::mesh_background(const bool status)
{
    yInfo() << log_ID_ << ConstString((status ? "Enable" : "Disable")) + " background of the mesh window.";

    drawer_->setBackgroundOpt(status);

    return true;
}

bool CADSuperimposer::mesh_wireframe(const bool status)
{
    yInfo() << log_ID_ << ConstString((status ? "Enable" : "Disable")) + " wireframe rendering.";

    drawer_->setWireframeOpt(status);

    return true;
}

bool CADSuperimposer::openGazeController()
{
    Property opt_gaze;
    opt_gaze.put("device", "gazecontrollerclient");
    opt_gaze.put("local",  "/" + ID_ + "/cam/" + camera_ + "/gaze");
    opt_gaze.put("remote", "/iKinGazeCtrl");

    if (drv_gaze_.open(opt_gaze))
    {
        drv_gaze_.view(itf_gaze_);
        if (!itf_gaze_)
        {
            yError() << log_ID_ << "Cannot get head gazecontrollerclient interface!";
            drv_gaze_.close();
            return false;
        }
    }
    else
    {
        yError() << log_ID_ << "Cannot open head gazecontrollerclient!";
        return false;
    }

    return true;
}

bool CADSuperimposer::setCommandPort()
{
    yInfo() << log_ID_ << "Opening command port.";
    if (!port_command_.open("/" + ID_ + "/cam/" + camera_ + "/render/cmd:i"))
    {
        yError() << log_ID_ << "Cannot open /" + ID_ + "/render/cmd:i port.";
        return false;
    }
    if (!this->yarp().attachAsServer(port_command_))
    {
        yError() << log_ID_ << "Cannot attach the renderer RPC port.";
        return false;
    }
    yInfo() << log_ID_ << "Renderer RPC port succesfully opened and attached. Ready to recieve commands.";

    return true;
}

Vector CADSuperimposer::readRootToEye(const ConstString& camera)
{
    Vector root_eye_enc = zeros(8);

    Vector root_torso_enc = getTorsoEncoders();
    if (root_torso_enc == zeros(root_torso_enc.size()))
        return root_eye_enc;

    Vector enc_head = getHeadEncoders();
    if (enc_head == zeros(enc_head.size()))
        return root_eye_enc;

    root_eye_enc.setSubvector(0, root_torso_enc);

    for (size_t i = 0; i < 4; ++i)
        root_eye_enc(3+i) = enc_head(i);

    if      (camera == "left")
        root_eye_enc(7) = enc_head(4) + enc_head(5) / 2.0;
    else if (camera == "right")
        root_eye_enc(7) = enc_head(4) - enc_head(5) / 2.0;
    else
        yError() << "Wrong 'camera' argument for CADSuperimposer::readRootToEye(). Shall be 'left' or 'right'.";

    return root_eye_enc;
}
<commit_msg>Update SICAD constructor<commit_after>#include "iCubProprioception/CADSuperimposer.h"

#include <exception>
#include <utility>

#include <iCub/ctrl/math.h>
#include <yarp/math/Math.h>
#include <yarp/os/Bottle.h>
#include <yarp/os/LogStream.h>
#include <yarp/os/ResourceFinder.h>

using namespace yarp::dev;
using namespace yarp::math;
using namespace yarp::os;
using namespace yarp::sig;
using namespace iCub::ctrl;
using namespace iCub::iKin;

CADSuperimposer::CADSuperimposer(const ConstString& port_prefix, const ConstString& robot, const ConstString& camera,
                                 const SICAD::ModelPathContainer& cad_hand, const ConstString& shader_path) :
    ID_(port_prefix), log_ID_("[" + ID_ + "]"),
    robot_(robot), camera_(camera),
    cad_hand_(cad_hand), shader_path_(shader_path)
{
    yInfo() << log_ID_ << "Invoked CADSuperimposer (base class) ctor...";

    /* Port for the CAD superimposer to work */
    yInfo() << log_ID_ << "Opening ports for CAD images.";

    if (!inport_renderer_img_.open("/" + ID_ + "/cam/" + camera_ + ":i"))
    {
        yError() << log_ID_ << "Cannot open input image port for " + camera_ + " camera!";
        throw std::runtime_error("Cannot open input image port for " + camera_ + " camera!");
    }

    if (!outport_renderer_img_.open("/" + ID_ + "/cam/" + camera_ + ":o"))
    {
        yError() << log_ID_ << "Cannot open output image port for " + camera_ + " camera!";
        throw std::runtime_error("Cannot open output image port for " + camera_ + " camera!");
    }

    /* Setting up common gaze controller and camera parameters */
    if (openGazeController())
    {
        Bottle cam_info;
        itf_gaze_->getInfo(cam_info);
        yInfo() << log_ID_ << "[CAM PARAMS]" << cam_info.toString();
        Bottle* cam_sel_intrinsic  = cam_info.findGroup("camera_intrinsics_" + camera_).get(1).asList();
        cam_width_  = cam_info.findGroup("camera_width_" + camera_).get(1).asInt();
        cam_height_ = cam_info.findGroup("camera_height_" + camera_).get(1).asInt();
        cam_fx_     = static_cast<float>(cam_sel_intrinsic->get(0).asDouble());
        cam_cx_     = static_cast<float>(cam_sel_intrinsic->get(2).asDouble());
        cam_fy_     = static_cast<float>(cam_sel_intrinsic->get(5).asDouble());
        cam_cy_     = static_cast<float>(cam_sel_intrinsic->get(6).asDouble());
    }
    else
    {
        yWarning() << log_ID_ << "[CAM PARAMS]" << "No intrinisc camera information could be found by the ctor. Looking for fallback values in parameters.ini.";

        ResourceFinder rf;
        rf.setVerbose(true);
        rf.setDefaultConfigFile("parameters.ini");
        rf.setDefaultContext("iCubProprioception");
        rf.configure(0, YARP_NULLPTR);

        Bottle* fallback_intrinsic = rf.findGroup("FALLBACK").find("intrinsic_" + camera_).asList();
        if (fallback_intrinsic)
        {
            yInfo() << log_ID_ << "[FALLBACK][CAM PARAMS]" << fallback_intrinsic->toString();

            cam_width_  = fallback_intrinsic->get(0).asDouble();
            cam_height_ = fallback_intrinsic->get(1).asDouble();
            cam_fx_     = fallback_intrinsic->get(2).asDouble();
            cam_cx_     = fallback_intrinsic->get(3).asDouble();
            cam_fy_     = fallback_intrinsic->get(4).asDouble();
            cam_cy_     = fallback_intrinsic->get(5).asDouble();
        }
        else
        {
            yWarning() << log_ID_ << "[CAM PARAMS]" << "No fallback values could be found in parameters.ini by the ctor for the intrinisc camera parameters. Falling (even more) back to iCub_SIM values.";
            cam_width_  = 320;
            cam_height_ = 240;
            cam_fx_     = 257.34;
            cam_cx_     = 160;
            cam_fy_     = 257.34;
            cam_cy_     = 120;
        }
    }
    yInfo() << log_ID_ << "[CAM]" << "Running with:";
    yInfo() << log_ID_ << "[CAM]" << " - width:"  << cam_width_;
    yInfo() << log_ID_ << "[CAM]" << " - height:" << cam_height_;
    yInfo() << log_ID_ << "[CAM]" << " - fx:"     << cam_fx_;
    yInfo() << log_ID_ << "[CAM]" << " - fy:"     << cam_fy_;
    yInfo() << log_ID_ << "[CAM]" << " - cx:"     << cam_cx_;
    yInfo() << log_ID_ << "[CAM]" << " - cy:"     << cam_cy_;

    /* Initiliaze left eye interface */
    yInfo() << log_ID_ << "Setting" + camera_ + "eye.";

    eye_ = iCubEye(camera_ + "_v2");
    eye_.setAllConstraints(false);
    eye_.releaseLink(0);
    eye_.releaseLink(1);
    eye_.releaseLink(2);

    /* Initialize right hand finger interfaces */
    yInfo() << log_ID_ << "Setting right hand fingers.";

    right_finger_[0] = iCubFinger("right_thumb");
    right_finger_[1] = iCubFinger("right_index");
    right_finger_[2] = iCubFinger("right_middle");

    right_finger_[0].setAllConstraints(false);
    right_finger_[1].setAllConstraints(false);
    right_finger_[2].setAllConstraints(false);

    /* Initialize CAD superimposer */
    yInfo() << log_ID_ << "Setting up OpenGL drawer.";

    drawer_ = new SICAD(cad_hand_,
                        cam_width_, cam_height_, cam_fx_, cam_fy_, cam_cx_, cam_cy_,
                        1,
                        {1.0, 0.0, 0.0, M_PI},
                        shader_path_,
                        false);

    drawer_->setBackgroundOpt(true);
    drawer_->setWireframeOpt(true);

    /* Open command port */
    if (!setCommandPort()) throw std::runtime_error("Cannot attach the command port.");

    yInfo() << log_ID_ << "...CADSuperimposer ctor completed!";
}

CADSuperimposer::~CADSuperimposer() noexcept
{
    delete drawer_;
}

void CADSuperimposer::run()
{
    ImageOf<PixelRgb>* tmp_imgin = YARP_NULLPTR;
    Vector tmp_root_eye_enc(8);
    Vector tmp_cam_pose(7);
    Vector tmp_ee_pose(7);
    Vector tmp_encs_arm(16);

    while (!isStopping())
    {
        tmp_imgin = inport_renderer_img_.read(false);
        if (tmp_imgin != YARP_NULLPTR)
            imgin_ = tmp_imgin;

        tmp_root_eye_enc = readRootToEye(camera_);
        if (!(tmp_root_eye_enc == zeros(tmp_root_eye_enc.size())))
            root_eye_enc_ = tmp_root_eye_enc;

        tmp_ee_pose = getEndEffectorPose();
        if (!(tmp_ee_pose == zeros(tmp_ee_pose.size())))
            ee_pose_ = tmp_ee_pose;

        tmp_encs_arm = getRightArmEncoders();
        if (!(tmp_encs_arm == zeros(tmp_encs_arm.size())))
            encs_arm_ = tmp_encs_arm;

        if (  imgin_        != YARP_NULLPTR                 &&
            !(root_eye_enc_ == zeros(root_eye_enc_.size())) &&
            !(ee_pose_      == zeros(ee_pose_.size()))      &&
            !(encs_arm_     == zeros(encs_arm_.size())))
        {
            eye_.setAng(CTRL_DEG2RAD * root_eye_enc_);
            Vector cam_pose = eye_.EndEffPose();

            if (ee_pose_.size() == 6)
            {
                double ang =  norm(ee_pose_.subVector(3, 5));
                ee_pose_(3) /= ang;
                ee_pose_(4) /= ang;
                ee_pose_(5) /= ang;
                ee_pose_.push_back(ang);
            }

#if ICP_USE_ANALOGS == 1
            Vector analogs;
            itf_right_hand_analog_->read(analogs);
            yAssert(analogs.size() >= 15);
#endif

            Vector chainjoints;
            for (unsigned int i = 0; i < 3; ++i)
            {
#if ICP_USE_ANALOGS == 1
                right_finger_[i].getChainJoints(encs_arm_, analogs, chainjoints);
#else
                right_finger_[i].getChainJoints(encs_arm_, chainjoints);
#endif

                right_finger_[i].setAng(CTRL_DEG2RAD * chainjoints);
            }

            Superimpose::ModelPoseContainer hand_pose;
            getRightHandObjPoseMap(ee_pose_, hand_pose);
            getExtraObjPoseMap(hand_pose);

            ImageOf<PixelRgb>& imgout = outport_renderer_img_.prepare();
            imgout = *imgin_;

            cv::Mat img = cv::cvarrToMat(imgout.getIplImage());
            drawer_->superimpose(hand_pose, cam_pose.data(), cam_pose.data()+3, img);

            outport_renderer_img_.write();
        }
    }
}

void CADSuperimposer::onStop()
{
    inport_renderer_img_.interrupt();
}

void CADSuperimposer::threadRelease()
{
    yInfo() << log_ID_ << "Deallocating resource...";

    if (!inport_renderer_img_.isClosed())  inport_renderer_img_.close();
    if (!outport_renderer_img_.isClosed()) outport_renderer_img_.close();

    if (port_command_.isOpen()) port_command_.close();

    yInfo() << log_ID_ << "...deallocation completed!";
}

void CADSuperimposer::getRightHandObjPoseMap(const Vector& ee_pose, Superimpose::ModelPoseContainer& hand_pose)
{
    Superimpose::ModelPose pose;

    Matrix Ha = axis2dcm(ee_pose.subVector(3, 6));
    Ha.setSubcol(ee_pose.subVector(0, 2), 0, 3);
    Ha(3, 3) = 1.0;

    pose.assign(ee_pose.data(), ee_pose.data()+7);
    hand_pose.emplace("palm", pose);
    for (size_t fng = 1; fng < 3; ++fng)
    {
        std::string finger_s;
        pose.clear();
        if (fng != 0)
        {
            Vector j_x = (Ha * (right_finger_[fng].getH0().getCol(3))).subVector(0, 2);
            Vector j_o = dcm2axis(Ha * right_finger_[fng].getH0());

            if      (fng == 1) { finger_s = "index0";  }
            else if (fng == 2) { finger_s = "medium0"; }

            pose.assign(j_x.data(), j_x.data()+3);
            pose.insert(pose.end(), j_o.data(), j_o.data()+4);
            hand_pose.emplace(finger_s, pose);
        }

        for (size_t i = 0; i < right_finger_[fng].getN(); ++i)
        {
            Vector j_x = (Ha * (right_finger_[fng].getH(i, true).getCol(3))).subVector(0, 2);
            Vector j_o = dcm2axis(Ha * right_finger_[fng].getH(i, true));

            if      (fng == 0) { finger_s = "thumb"  + std::to_string(i+1); }
            else if (fng == 1) { finger_s = "index"  + std::to_string(i+1); }
            else if (fng == 2) { finger_s = "medium" + std::to_string(i+1); }

            pose.assign(j_x.data(), j_x.data()+3);
            pose.insert(pose.end(), j_o.data(), j_o.data()+4);
            hand_pose.emplace(finger_s, pose);
        }
    }
}

bool CADSuperimposer::mesh_background(const bool status)
{
    yInfo() << log_ID_ << ConstString((status ? "Enable" : "Disable")) + " background of the mesh window.";

    drawer_->setBackgroundOpt(status);

    return true;
}

bool CADSuperimposer::mesh_wireframe(const bool status)
{
    yInfo() << log_ID_ << ConstString((status ? "Enable" : "Disable")) + " wireframe rendering.";

    drawer_->setWireframeOpt(status);

    return true;
}

bool CADSuperimposer::openGazeController()
{
    Property opt_gaze;
    opt_gaze.put("device", "gazecontrollerclient");
    opt_gaze.put("local",  "/" + ID_ + "/cam/" + camera_ + "/gaze");
    opt_gaze.put("remote", "/iKinGazeCtrl");

    if (drv_gaze_.open(opt_gaze))
    {
        drv_gaze_.view(itf_gaze_);
        if (!itf_gaze_)
        {
            yError() << log_ID_ << "Cannot get head gazecontrollerclient interface!";
            drv_gaze_.close();
            return false;
        }
    }
    else
    {
        yError() << log_ID_ << "Cannot open head gazecontrollerclient!";
        return false;
    }

    return true;
}

bool CADSuperimposer::setCommandPort()
{
    yInfo() << log_ID_ << "Opening command port.";
    if (!port_command_.open("/" + ID_ + "/cam/" + camera_ + "/render/cmd:i"))
    {
        yError() << log_ID_ << "Cannot open /" + ID_ + "/render/cmd:i port.";
        return false;
    }
    if (!this->yarp().attachAsServer(port_command_))
    {
        yError() << log_ID_ << "Cannot attach the renderer RPC port.";
        return false;
    }
    yInfo() << log_ID_ << "Renderer RPC port succesfully opened and attached. Ready to recieve commands.";

    return true;
}

Vector CADSuperimposer::readRootToEye(const ConstString& camera)
{
    Vector root_eye_enc = zeros(8);

    Vector root_torso_enc = getTorsoEncoders();
    if (root_torso_enc == zeros(root_torso_enc.size()))
        return root_eye_enc;

    Vector enc_head = getHeadEncoders();
    if (enc_head == zeros(enc_head.size()))
        return root_eye_enc;

    root_eye_enc.setSubvector(0, root_torso_enc);

    for (size_t i = 0; i < 4; ++i)
        root_eye_enc(3+i) = enc_head(i);

    if      (camera == "left")
        root_eye_enc(7) = enc_head(4) + enc_head(5) / 2.0;
    else if (camera == "right")
        root_eye_enc(7) = enc_head(4) - enc_head(5) / 2.0;
    else
        yError() << "Wrong 'camera' argument for CADSuperimposer::readRootToEye(). Shall be 'left' or 'right'.";

    return root_eye_enc;
}
<|endoftext|>


<commit_before>/*  This file is part of the KDE project.

    Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).

    This library is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 2.1 or 3 of the License.

    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, see <http://www.gnu.org/licenses/>.
*/

#include "common.h"
#include "backend.h"
#include "audiooutput.h"
#include "audioeffect.h"
#include "mediaobject.h"
#include "videowidget.h"
#include "devicemanager.h"
#include "effectmanager.h"
#include "message.h"
#include "volumefadereffect.h"
#include <gst/interfaces/propertyprobe.h>

#include <QtCore/QSet>
#include <QtCore/QVariant>
#include <QtCore/QtPlugin>

QT_BEGIN_NAMESPACE

Q_EXPORT_PLUGIN2(phonon_gstreamer, Phonon::Gstreamer::Backend)

namespace Phonon
{
namespace Gstreamer
{

class MediaNode;

Backend::Backend(QObject *parent, const QVariantList &)
        : QObject(parent)
        , m_deviceManager(0)
        , m_effectManager(0)
        , m_debugLevel(Warning)
        , m_isValid(false)
{
    GError *err = 0;
    bool wasInit = gst_init_check(0, 0, &err);  //init gstreamer: must be called before any gst-related functions
    if (err)
        g_error_free(err);

    qRegisterMetaType<Message>("Message");
#ifndef QT_NO_PROPERTIES
    setProperty("identifier",     QLatin1String("phonon_gstreamer"));
    setProperty("backendName",    QLatin1String("Gstreamer"));
    setProperty("backendComment", QLatin1String("Gstreamer plugin for Phonon"));
    setProperty("backendVersion", QLatin1String("0.2"));
    setProperty("backendWebsite", QLatin1String("http://qt.nokia.com/"));
#endif //QT_NO_PROPERTIES

    //check if we should enable debug output
    QString debugLevelString = qgetenv("PHONON_GST_DEBUG");
    int debugLevel = debugLevelString.toInt();
    if (debugLevel > 3) //3 is maximum
        debugLevel = 3;
    m_debugLevel = (DebugLevel)debugLevel;

    if (wasInit) {
        m_isValid = checkDependencies();
        gchar *versionString = gst_version_string();
        logMessage(QString("Using %0").arg(versionString));
        g_free(versionString);
    }
    if (!m_isValid)
        qWarning("Phonon::GStreamer::Backend: Failed to initialize GStreamer");

    m_deviceManager = new DeviceManager(this);
    m_effectManager = new EffectManager(this);
}

Backend::~Backend()
{
}

gboolean Backend::busCall(GstBus *bus, GstMessage *msg, gpointer data)
{
    Q_UNUSED(bus);
    Q_ASSERT(msg);

    MediaObject *mediaObject = static_cast<MediaObject*>(data);
    Q_ASSERT(mediaObject);

    Message message(msg, mediaObject);
    QMetaObject::invokeMethod(mediaObject->backend(), "handleBusMessage", Qt::QueuedConnection, Q_ARG(Message, message));

    return true;
}

/***
 * !reimp
 */
QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &args)
{
    // Return nothing if dependencies are not met

    switch (c) {
    case MediaObjectClass:
        return new MediaObject(this, parent);

    case AudioOutputClass: {
            AudioOutput *ao = new AudioOutput(this, parent);
            m_audioOutputs.append(ao);
            return ao;
        }
#ifndef QT_NO_PHONON_EFFECT
    case EffectClass:
        return new AudioEffect(this, args[0].toInt(), parent);
#endif //QT_NO_PHONON_EFFECT
    case AudioDataOutputClass:
        logMessage("createObject() : AudioDataOutput not implemented");
        break;

#ifndef QT_NO_PHONON_VIDEO
    case VideoDataOutputClass:
        logMessage("createObject() : VideoDataOutput not implemented");
        break;

    case VideoWidgetClass: {
            QWidget *widget =  qobject_cast<QWidget*>(parent);
            return new VideoWidget(this, widget);
        }
#endif //QT_NO_PHONON_VIDEO
#ifndef QT_NO_PHONON_VOLUMEFADEREFFECT
    case VolumeFaderEffectClass:
        return new VolumeFaderEffect(this, parent);
#endif //QT_NO_PHONON_VOLUMEFADEREFFECT

    case VisualizationClass:  //Fall through
    default:
        logMessage("createObject() : Backend object not available");
    }
    return 0;
}

// Returns true if all dependencies are met
// and gstreamer is usable, otherwise false
bool Backend::isValid() const
{
    return m_isValid;
}

bool Backend::supportsVideo() const
{
    return isValid();
}

bool Backend::checkDependencies() const
{
    bool success = false;
    // Verify that gst-plugins-base is installed
    GstElementFactory *acFactory = gst_element_factory_find ("audioconvert");
    if (acFactory) {
        gst_object_unref(acFactory);
        success = true;
        // Check if gst-plugins-good is installed
        GstElementFactory *csFactory = gst_element_factory_find ("videobalance");
        if (csFactory) {
            gst_object_unref(csFactory);
        } else {
            QString message = tr("Warning: You do not seem to have the package gstreamer0.10-plugins-good installed.\n"
                                 "          Some video features have been disabled.");
            qDebug() << message;
        }
    } else {
        qWarning() << tr("Warning: You do not seem to have the base GStreamer plugins installed.\n"
                         "          All audio and video support has been disabled");
    }
    return success;
}

/***
 * !reimp
 */
QStringList Backend::availableMimeTypes() const
{
    QStringList availableMimeTypes;

    if (!isValid())
        return availableMimeTypes;

    GstElementFactory *mpegFactory;
    // Add mp3 as a separate mime type as people are likely to look for it.
    if ((mpegFactory = gst_element_factory_find ("ffmpeg")) ||
        (mpegFactory = gst_element_factory_find ("mad"))) {
        availableMimeTypes << QLatin1String("audio/x-mp3");
        gst_object_unref(GST_OBJECT(mpegFactory));
    }

    // Iterate over all audio and video decoders and extract mime types from sink caps
    GList* factoryList = gst_registry_get_feature_list(gst_registry_get_default (), GST_TYPE_ELEMENT_FACTORY);
    for (GList* iter = g_list_first(factoryList) ; iter != NULL ; iter = g_list_next(iter)) {
        GstPluginFeature *feature = GST_PLUGIN_FEATURE(iter->data);
        QString klass = gst_element_factory_get_klass(GST_ELEMENT_FACTORY(feature));

        if (klass == QLatin1String("Codec/Decoder/Audio") ||
            klass == QLatin1String("Codec/Decoder/Video")) {

            const GList *static_templates;
            GstElementFactory *factory = GST_ELEMENT_FACTORY(feature);
            static_templates = gst_element_factory_get_static_pad_templates(factory);

            for (; static_templates != NULL ; static_templates = static_templates->next) {
                GstStaticPadTemplate *padTemplate = (GstStaticPadTemplate *) static_templates->data;
                if (padTemplate && padTemplate->direction == GST_PAD_SINK) {
                    GstCaps *caps = gst_static_pad_template_get_caps (padTemplate);

                    if (caps) {
                        const GstStructure* capsStruct = gst_caps_get_structure (caps, 0);
                        QString mime = QString::fromUtf8(gst_structure_get_name (capsStruct));
                        if (!availableMimeTypes.contains(mime))
                              availableMimeTypes.append(mime);
                    }
                }
            }
        }
    }
    g_list_free(factoryList);
    availableMimeTypes.sort();
    return availableMimeTypes;
}

/***
 * !reimp
 */
QList<int> Backend::objectDescriptionIndexes(ObjectDescriptionType type) const
{
    QList<int> list;

    if (!isValid())
        return list;

    switch (type) {
    case Phonon::AudioOutputDeviceType: {
            QList<AudioDevice> deviceList = deviceManager()->audioOutputDevices();
            for (int dev = 0 ; dev < deviceList.size() ; ++dev)
                list.append(deviceList[dev].id);
            break;
        }
        break;

    case Phonon::EffectType: {
            QList<EffectInfo*> effectList = effectManager()->audioEffects();
            for (int eff = 0 ; eff < effectList.size() ; ++eff)
                list.append(eff);
            break;
        }
        break;
    default:
        break;
    }
    return list;
}

/***
 * !reimp
 */
QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(ObjectDescriptionType type, int index) const
{

    QHash<QByteArray, QVariant> ret;

    if (!isValid())
        return ret;

    switch (type) {
    case Phonon::AudioOutputDeviceType: {
            QList<AudioDevice> audioDevices = deviceManager()->audioOutputDevices();
            if (index >= 0 && index < audioDevices.size()) {
                ret.insert("name", audioDevices[index].gstId);
                ret.insert("description", audioDevices[index].description);
                ret.insert("icon", QLatin1String("audio-card"));
            }
        }
        break;

    case Phonon::EffectType: {
            QList<EffectInfo*> effectList = effectManager()->audioEffects();
            if (index >= 0 && index <= effectList.size()) {
                const EffectInfo *effect = effectList[index];
                ret.insert("name", effect->name());
                ret.insert("description", effect->description());
                ret.insert("author", effect->author());
            } else
                Q_ASSERT(1); // Since we use list position as ID, this should not happen
        }
    default:
        break;
    }
    return ret;
}

/***
 * !reimp
 */
bool Backend::startConnectionChange(QSet<QObject *> objects)
{
    foreach (QObject *object, objects) {
        MediaNode *sourceNode = qobject_cast<MediaNode *>(object);
        MediaObject *media = sourceNode->root();
        if (media) {
            media->saveState();
            return true;
        }
    }
    return true;
}

/***
 * !reimp
 */
bool Backend::connectNodes(QObject *source, QObject *sink)
{
    if (isValid()) {
        MediaNode *sourceNode = qobject_cast<MediaNode *>(source);
        MediaNode *sinkNode = qobject_cast<MediaNode *>(sink);
        if (sourceNode && sinkNode) {
            if (sourceNode->connectNode(sink)) {
                sourceNode->root()->invalidateGraph();
                logMessage(QString("Backend connected %0 to %1").arg(source->metaObject()->className()).arg(sink->metaObject()->className()));
                return true;
            }
        }
    }
    logMessage(QString("Linking %0 to %1 failed").arg(source->metaObject()->className()).arg(sink->metaObject()->className()), Warning);
    return false;
}

/***
 * !reimp
 */
bool Backend::disconnectNodes(QObject *source, QObject *sink)
{
    MediaNode *sourceNode = qobject_cast<MediaNode *>(source);
    MediaNode *sinkNode = qobject_cast<MediaNode *>(sink);

    if (sourceNode && sinkNode)
        return sourceNode->disconnectNode(sink);
    else
        return false;
}

/***
 * !reimp
 */
bool Backend::endConnectionChange(QSet<QObject *> objects)
{
    foreach (QObject *object, objects) {
        MediaNode *sourceNode = qobject_cast<MediaNode *>(object);
        MediaObject *media = sourceNode->root();
        if (media) {
            media->resumeState();
            return true;
        }
    }
    return true;
}

/***
 * Request bus messages for this mediaobject
 */
void Backend::addBusWatcher(MediaObject* node)
{
    Q_ASSERT(node);
    GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE(node->pipeline()));
    gst_bus_add_watch (bus, busCall, node);
    gst_object_unref(bus);
}

/***
 * Ignore bus messages for this mediaobject
 */
void Backend::removeBusWatcher(MediaObject* node)
{
    Q_ASSERT(node);
    g_source_remove_by_user_data(node);
}

/***
 * Polls each mediaobject's pipeline and delivers
 * pending any pending messages
 */
void Backend::handleBusMessage(Message message)
{
    MediaObject *mediaObject = message.source();
    mediaObject->handleBusMessage(message);
}

DeviceManager* Backend::deviceManager() const
{
    return m_deviceManager;
}

EffectManager* Backend::effectManager() const
{
    return m_effectManager;
}

/**
 * Returns a debuglevel that is determined by the
 * PHONON_GSTREAMER_DEBUG environment variable.
 *
 *  Warning - important warnings
 *  Info    - general info
 *  Debug   - gives extra info
 */
Backend::DebugLevel Backend::debugLevel() const
{
    return m_debugLevel;
}

/***
 * Prints a conditional debug message based on the current debug level
 * If obj is provided, classname and objectname will be printed as well
 *
 * see debugLevel()
 */
void Backend::logMessage(const QString &message, int priority, QObject *obj) const
{
    if (debugLevel() > 0) {
        QString output;
        if (obj) {
            // Strip away namespace from className
            QString className(obj->metaObject()->className());
            int nameLength = className.length() - className.lastIndexOf(':') - 1;
            className = className.right(nameLength);
            output.sprintf("%s %s (%s %p)", message.toLatin1().constData(),
                                          obj->objectName().toLatin1().constData(),
                                          className.toLatin1().constData(), obj);
        }
        else {
            output = message;
        }
        if (priority <= (int)debugLevel()) {
            qDebug() << QString("PGST(%1): %2").arg(priority).arg(output);
        }
    }
}

}
}

QT_END_NAMESPACE

#include "moc_backend.cpp"
<commit_msg>Gstreamer: Detect more mimetypes<commit_after>/*  This file is part of the KDE project.

    Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).

    This library is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 2.1 or 3 of the License.

    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, see <http://www.gnu.org/licenses/>.
*/

#include "common.h"
#include "backend.h"
#include "audiooutput.h"
#include "audioeffect.h"
#include "mediaobject.h"
#include "videowidget.h"
#include "devicemanager.h"
#include "effectmanager.h"
#include "message.h"
#include "volumefadereffect.h"
#include <gst/interfaces/propertyprobe.h>

#include <QtCore/QSet>
#include <QtCore/QVariant>
#include <QtCore/QtPlugin>

QT_BEGIN_NAMESPACE

Q_EXPORT_PLUGIN2(phonon_gstreamer, Phonon::Gstreamer::Backend)

namespace Phonon
{
namespace Gstreamer
{

class MediaNode;

Backend::Backend(QObject *parent, const QVariantList &)
        : QObject(parent)
        , m_deviceManager(0)
        , m_effectManager(0)
        , m_debugLevel(Warning)
        , m_isValid(false)
{
    GError *err = 0;
    bool wasInit = gst_init_check(0, 0, &err);  //init gstreamer: must be called before any gst-related functions
    if (err)
        g_error_free(err);

    qRegisterMetaType<Message>("Message");
#ifndef QT_NO_PROPERTIES
    setProperty("identifier",     QLatin1String("phonon_gstreamer"));
    setProperty("backendName",    QLatin1String("Gstreamer"));
    setProperty("backendComment", QLatin1String("Gstreamer plugin for Phonon"));
    setProperty("backendVersion", QLatin1String("0.2"));
    setProperty("backendWebsite", QLatin1String("http://qt.nokia.com/"));
#endif //QT_NO_PROPERTIES

    //check if we should enable debug output
    QString debugLevelString = qgetenv("PHONON_GST_DEBUG");
    int debugLevel = debugLevelString.toInt();
    if (debugLevel > 3) //3 is maximum
        debugLevel = 3;
    m_debugLevel = (DebugLevel)debugLevel;

    if (wasInit) {
        m_isValid = checkDependencies();
        gchar *versionString = gst_version_string();
        logMessage(QString("Using %0").arg(versionString));
        g_free(versionString);
    }
    if (!m_isValid)
        qWarning("Phonon::GStreamer::Backend: Failed to initialize GStreamer");

    m_deviceManager = new DeviceManager(this);
    m_effectManager = new EffectManager(this);
}

Backend::~Backend()
{
}

gboolean Backend::busCall(GstBus *bus, GstMessage *msg, gpointer data)
{
    Q_UNUSED(bus);
    Q_ASSERT(msg);

    MediaObject *mediaObject = static_cast<MediaObject*>(data);
    Q_ASSERT(mediaObject);

    Message message(msg, mediaObject);
    QMetaObject::invokeMethod(mediaObject->backend(), "handleBusMessage", Qt::QueuedConnection, Q_ARG(Message, message));

    return true;
}

/***
 * !reimp
 */
QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &args)
{
    // Return nothing if dependencies are not met

    switch (c) {
    case MediaObjectClass:
        return new MediaObject(this, parent);

    case AudioOutputClass: {
            AudioOutput *ao = new AudioOutput(this, parent);
            m_audioOutputs.append(ao);
            return ao;
        }
#ifndef QT_NO_PHONON_EFFECT
    case EffectClass:
        return new AudioEffect(this, args[0].toInt(), parent);
#endif //QT_NO_PHONON_EFFECT
    case AudioDataOutputClass:
        logMessage("createObject() : AudioDataOutput not implemented");
        break;

#ifndef QT_NO_PHONON_VIDEO
    case VideoDataOutputClass:
        logMessage("createObject() : VideoDataOutput not implemented");
        break;

    case VideoWidgetClass: {
            QWidget *widget =  qobject_cast<QWidget*>(parent);
            return new VideoWidget(this, widget);
        }
#endif //QT_NO_PHONON_VIDEO
#ifndef QT_NO_PHONON_VOLUMEFADEREFFECT
    case VolumeFaderEffectClass:
        return new VolumeFaderEffect(this, parent);
#endif //QT_NO_PHONON_VOLUMEFADEREFFECT

    case VisualizationClass:  //Fall through
    default:
        logMessage("createObject() : Backend object not available");
    }
    return 0;
}

// Returns true if all dependencies are met
// and gstreamer is usable, otherwise false
bool Backend::isValid() const
{
    return m_isValid;
}

bool Backend::supportsVideo() const
{
    return isValid();
}

bool Backend::checkDependencies() const
{
    bool success = false;
    // Verify that gst-plugins-base is installed
    GstElementFactory *acFactory = gst_element_factory_find ("audioconvert");
    if (acFactory) {
        gst_object_unref(acFactory);
        success = true;
        // Check if gst-plugins-good is installed
        GstElementFactory *csFactory = gst_element_factory_find ("videobalance");
        if (csFactory) {
            gst_object_unref(csFactory);
        } else {
            QString message = tr("Warning: You do not seem to have the package gstreamer0.10-plugins-good installed.\n"
                                 "          Some video features have been disabled.");
            qDebug() << message;
        }
    } else {
        qWarning() << tr("Warning: You do not seem to have the base GStreamer plugins installed.\n"
                         "          All audio and video support has been disabled");
    }
    return success;
}

/***
 * !reimp
 */
QStringList Backend::availableMimeTypes() const
{
    QStringList availableMimeTypes;

    if (!isValid())
        return availableMimeTypes;

    GstElementFactory *mpegFactory;
    // Add mp3 as a separate mime type as people are likely to look for it.
    if ((mpegFactory = gst_element_factory_find ("ffmpeg")) ||
        (mpegFactory = gst_element_factory_find ("mad"))) {
        availableMimeTypes << QLatin1String("audio/x-mp3");
        gst_object_unref(GST_OBJECT(mpegFactory));
    }

    // Iterate over all audio and video decoders and extract mime types from sink caps
    GList* factoryList = gst_registry_get_feature_list(gst_registry_get_default (), GST_TYPE_ELEMENT_FACTORY);
    for (GList* iter = g_list_first(factoryList) ; iter != NULL ; iter = g_list_next(iter)) {
        GstPluginFeature *feature = GST_PLUGIN_FEATURE(iter->data);
        QString klass = gst_element_factory_get_klass(GST_ELEMENT_FACTORY(feature));

        if (klass == QLatin1String("Codec/Decoder") ||
            klass == QLatin1String("Codec/Decoder/Audio") ||
            klass == QLatin1String("Codec/Decoder/Video") ||
            klass == QLatin1String("Codec/Demuxer") ||
            klass == QLatin1String("Codec/Demuxer/Audio") ||
            klass == QLatin1String("Codec/Demuxer/Video") ||
            klass == QLatin1String("Codec/Parser") ||
            klass == QLatin1String("Codec/Parser/Audio") ||
            klass == QLatin1String("Codec/Parser/Video")) {

            const GList *static_templates;
            GstElementFactory *factory = GST_ELEMENT_FACTORY(feature);
            static_templates = gst_element_factory_get_static_pad_templates(factory);

            for (; static_templates != NULL ; static_templates = static_templates->next) {
                GstStaticPadTemplate *padTemplate = (GstStaticPadTemplate *) static_templates->data;
                if (padTemplate && padTemplate->direction == GST_PAD_SINK) {
                    GstCaps *caps = gst_static_pad_template_get_caps (padTemplate);

                    if (caps) {
                        const GstStructure* capsStruct = gst_caps_get_structure (caps, 0);
                        QString mime = QString::fromUtf8(gst_structure_get_name (capsStruct));
                        if (!availableMimeTypes.contains(mime))
                              availableMimeTypes.append(mime);
                    }
                }
            }
        }
    }
    g_list_free(factoryList);
    availableMimeTypes.sort();
    return availableMimeTypes;
}

/***
 * !reimp
 */
QList<int> Backend::objectDescriptionIndexes(ObjectDescriptionType type) const
{
    QList<int> list;

    if (!isValid())
        return list;

    switch (type) {
    case Phonon::AudioOutputDeviceType: {
            QList<AudioDevice> deviceList = deviceManager()->audioOutputDevices();
            for (int dev = 0 ; dev < deviceList.size() ; ++dev)
                list.append(deviceList[dev].id);
            break;
        }
        break;

    case Phonon::EffectType: {
            QList<EffectInfo*> effectList = effectManager()->audioEffects();
            for (int eff = 0 ; eff < effectList.size() ; ++eff)
                list.append(eff);
            break;
        }
        break;
    default:
        break;
    }
    return list;
}

/***
 * !reimp
 */
QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(ObjectDescriptionType type, int index) const
{

    QHash<QByteArray, QVariant> ret;

    if (!isValid())
        return ret;

    switch (type) {
    case Phonon::AudioOutputDeviceType: {
            QList<AudioDevice> audioDevices = deviceManager()->audioOutputDevices();
            if (index >= 0 && index < audioDevices.size()) {
                ret.insert("name", audioDevices[index].gstId);
                ret.insert("description", audioDevices[index].description);
                ret.insert("icon", QLatin1String("audio-card"));
            }
        }
        break;

    case Phonon::EffectType: {
            QList<EffectInfo*> effectList = effectManager()->audioEffects();
            if (index >= 0 && index <= effectList.size()) {
                const EffectInfo *effect = effectList[index];
                ret.insert("name", effect->name());
                ret.insert("description", effect->description());
                ret.insert("author", effect->author());
            } else
                Q_ASSERT(1); // Since we use list position as ID, this should not happen
        }
    default:
        break;
    }
    return ret;
}

/***
 * !reimp
 */
bool Backend::startConnectionChange(QSet<QObject *> objects)
{
    foreach (QObject *object, objects) {
        MediaNode *sourceNode = qobject_cast<MediaNode *>(object);
        MediaObject *media = sourceNode->root();
        if (media) {
            media->saveState();
            return true;
        }
    }
    return true;
}

/***
 * !reimp
 */
bool Backend::connectNodes(QObject *source, QObject *sink)
{
    if (isValid()) {
        MediaNode *sourceNode = qobject_cast<MediaNode *>(source);
        MediaNode *sinkNode = qobject_cast<MediaNode *>(sink);
        if (sourceNode && sinkNode) {
            if (sourceNode->connectNode(sink)) {
                sourceNode->root()->invalidateGraph();
                logMessage(QString("Backend connected %0 to %1").arg(source->metaObject()->className()).arg(sink->metaObject()->className()));
                return true;
            }
        }
    }
    logMessage(QString("Linking %0 to %1 failed").arg(source->metaObject()->className()).arg(sink->metaObject()->className()), Warning);
    return false;
}

/***
 * !reimp
 */
bool Backend::disconnectNodes(QObject *source, QObject *sink)
{
    MediaNode *sourceNode = qobject_cast<MediaNode *>(source);
    MediaNode *sinkNode = qobject_cast<MediaNode *>(sink);

    if (sourceNode && sinkNode)
        return sourceNode->disconnectNode(sink);
    else
        return false;
}

/***
 * !reimp
 */
bool Backend::endConnectionChange(QSet<QObject *> objects)
{
    foreach (QObject *object, objects) {
        MediaNode *sourceNode = qobject_cast<MediaNode *>(object);
        MediaObject *media = sourceNode->root();
        if (media) {
            media->resumeState();
            return true;
        }
    }
    return true;
}

/***
 * Request bus messages for this mediaobject
 */
void Backend::addBusWatcher(MediaObject* node)
{
    Q_ASSERT(node);
    GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE(node->pipeline()));
    gst_bus_add_watch (bus, busCall, node);
    gst_object_unref(bus);
}

/***
 * Ignore bus messages for this mediaobject
 */
void Backend::removeBusWatcher(MediaObject* node)
{
    Q_ASSERT(node);
    g_source_remove_by_user_data(node);
}

/***
 * Polls each mediaobject's pipeline and delivers
 * pending any pending messages
 */
void Backend::handleBusMessage(Message message)
{
    MediaObject *mediaObject = message.source();
    mediaObject->handleBusMessage(message);
}

DeviceManager* Backend::deviceManager() const
{
    return m_deviceManager;
}

EffectManager* Backend::effectManager() const
{
    return m_effectManager;
}

/**
 * Returns a debuglevel that is determined by the
 * PHONON_GSTREAMER_DEBUG environment variable.
 *
 *  Warning - important warnings
 *  Info    - general info
 *  Debug   - gives extra info
 */
Backend::DebugLevel Backend::debugLevel() const
{
    return m_debugLevel;
}

/***
 * Prints a conditional debug message based on the current debug level
 * If obj is provided, classname and objectname will be printed as well
 *
 * see debugLevel()
 */
void Backend::logMessage(const QString &message, int priority, QObject *obj) const
{
    if (debugLevel() > 0) {
        QString output;
        if (obj) {
            // Strip away namespace from className
            QString className(obj->metaObject()->className());
            int nameLength = className.length() - className.lastIndexOf(':') - 1;
            className = className.right(nameLength);
            output.sprintf("%s %s (%s %p)", message.toLatin1().constData(),
                                          obj->objectName().toLatin1().constData(),
                                          className.toLatin1().constData(), obj);
        }
        else {
            output = message;
        }
        if (priority <= (int)debugLevel()) {
            qDebug() << QString("PGST(%1): %2").arg(priority).arg(output);
        }
    }
}

}
}

QT_END_NAMESPACE

#include "moc_backend.cpp"
<|endoftext|>


<commit_before>#include <Core/Animation/Pose/PoseOperation.hpp>
#include <Eigen/Geometry>

namespace Ra {
namespace Core {
namespace Animation {

bool compatible( const Pose& p0, const Pose& p1 ) {
    return ( p0.size() == p1.size() );
}

Pose relativePose( const Pose& modelPose, const RestPose& restPose )  {
    CORE_ASSERT( compatible( modelPose, restPose ), " Poses with different size " );
    Pose T( restPose.size() );
    for( uint i = 0; i < T.size(); ++i ) {
        T[i] = modelPose[i] * restPose[i].inverse( Eigen::Affine );
    }
    return T;
}

Pose applyTransformation(const Pose& pose, const AlignedStdVector<Transform> &transform ) {
    Pose T( std::min( pose.size(), transform.size() ) );
    for( uint i = 0; i < T.size(); ++i ) {
        T[i] = transform[i] * pose[i];
    }
    return T;
}

Pose applyTransformation( const Pose& pose, const Transform& transform ) {
    Pose T( pose.size() );
    for( uint i = 0; i < T.size(); ++i ) {
        T[i] = transform * pose[i];
    }
    return T;
}

bool areEqual( const Pose &p0, const Pose &p1 ) {
    CORE_ASSERT( compatible( p0, p1 ), " Poses with different size " );
    const uint n = p0.size();
    for( uint i = 0; i < n; ++i ) {
        if( !p0[i].isApprox( p1[i]) ) {
            return false;
        }
    }
    return true;
}

Pose interpolatePoses(const Pose& a, const Pose& b, const Scalar t ) {
    CORE_ASSERT( ( a.size() == b.size() ), "Poses are wrong");
    CORE_ASSERT( ( ( t >= 0.0 ) && ( t <= 1.0 ) ), "T is wrong");

    const uint size = a.size();
    Pose interpolatedPose( size );

#pragma omp parallel for
    for ( uint i = 0; i < size; ++i ) {
        // interpolate between the transforms
        Ra::Core::Transform aTransform = a[i];
        Ra::Core::Transform bTransform = b[i];

        Ra::Core::Quaternion aRot = Ra::Core::Quaternion( aTransform.rotation() );
        Ra::Core::Quaternion bRot = Ra::Core::Quaternion( bTransform.rotation() );
        Ra::Core::Quaternion interpRot = aRot.slerp(t, bRot);

        Ra::Core::Vector3 interpTranslation = ( 1.0 - t ) * aTransform.translation() + t * bTransform.translation();

        Ra::Core::Transform interpolatedTransform;
        interpolatedTransform.linear() = interpRot.toRotationMatrix();
        interpolatedTransform.translation() = interpTranslation;

        interpolatedPose[i] = interpolatedTransform;
    }

    return interpolatedPose;
}

void interpolateTransforms( const Ra::Core::Transform& a, const Ra::Core::Transform& b, const Scalar t, Ra::Core::Transform& interpolated ) {
    Ra::Core::Quaternion aRot = Ra::Core::Quaternion( a.rotation() );
    Ra::Core::Quaternion bRot = Ra::Core::Quaternion( b.rotation() );
    Ra::Core::Quaternion interpRot = aRot.slerp( t, bRot );

    Ra::Core::Vector3 interpTranslation = ( 1.0 - t) * a.translation() + t * b.translation();

    interpolated.linear() = interpRot.toRotationMatrix();
    interpolated.translation() = interpTranslation;
}

} // namespace Animation
} // namespace Core
} // namespace Ra
<commit_msg>Added OpenMP pragmas to all the functions in PoseOperation<commit_after>#include <Core/Animation/Pose/PoseOperation.hpp>
#include <Eigen/Geometry>

namespace Ra {
namespace Core {
namespace Animation {

bool compatible( const Pose& p0, const Pose& p1 ) {
    return ( p0.size() == p1.size() );
}

Pose relativePose( const Pose& modelPose, const RestPose& restPose )  {
    CORE_ASSERT( compatible( modelPose, restPose ), " Poses with different size " );
    Pose T( restPose.size() );
    #pragma omp parallel for
    for( uint i = 0; i < T.size(); ++i ) {
        T[i] = modelPose[i] * restPose[i].inverse( Eigen::Affine );
    }
    return T;
}

Pose applyTransformation(const Pose& pose, const AlignedStdVector<Transform> &transform ) {
    Pose T( std::min( pose.size(), transform.size() ) );
    #pragma omp parallel for
    for( uint i = 0; i < T.size(); ++i ) {
        T[i] = transform[i] * pose[i];
    }
    return T;
}

Pose applyTransformation( const Pose& pose, const Transform& transform ) {
    Pose T( pose.size() );
    #pragma omp parallel for
    for( uint i = 0; i < T.size(); ++i ) {
        T[i] = transform * pose[i];
    }
    return T;
}

bool areEqual( const Pose &p0, const Pose &p1 ) {
    CORE_ASSERT( compatible( p0, p1 ), " Poses with different size " );
    const uint n = p0.size();
    for( uint i = 0; i < n; ++i ) {
        if( !p0[i].isApprox( p1[i]) ) {
            return false;
        }
    }
    return true;
}

Pose interpolatePoses(const Pose& a, const Pose& b, const Scalar t ) {
    CORE_ASSERT( ( a.size() == b.size() ), "Poses are wrong");
    CORE_ASSERT( ( ( t >= 0.0 ) && ( t <= 1.0 ) ), "T is wrong");

    const uint size = a.size();
    Pose interpolatedPose( size );

#pragma omp parallel for
    for ( uint i = 0; i < size; ++i ) {
        // interpolate between the transforms
        Ra::Core::Transform aTransform = a[i];
        Ra::Core::Transform bTransform = b[i];

        Ra::Core::Quaternion aRot = Ra::Core::Quaternion( aTransform.rotation() );
        Ra::Core::Quaternion bRot = Ra::Core::Quaternion( bTransform.rotation() );
        Ra::Core::Quaternion interpRot = aRot.slerp(t, bRot);

        Ra::Core::Vector3 interpTranslation = ( 1.0 - t ) * aTransform.translation() + t * bTransform.translation();

        Ra::Core::Transform interpolatedTransform;
        interpolatedTransform.linear() = interpRot.toRotationMatrix();
        interpolatedTransform.translation() = interpTranslation;

        interpolatedPose[i] = interpolatedTransform;
    }

    return interpolatedPose;
}

void interpolateTransforms( const Ra::Core::Transform& a, const Ra::Core::Transform& b, const Scalar t, Ra::Core::Transform& interpolated ) {
    Ra::Core::Quaternion aRot = Ra::Core::Quaternion( a.rotation() );
    Ra::Core::Quaternion bRot = Ra::Core::Quaternion( b.rotation() );
    Ra::Core::Quaternion interpRot = aRot.slerp( t, bRot );

    Ra::Core::Vector3 interpTranslation = ( 1.0 - t) * a.translation() + t * b.translation();

    interpolated.linear() = interpRot.toRotationMatrix();
    interpolated.translation() = interpTranslation;
}

} // namespace Animation
} // namespace Core
} // namespace Ra
<|endoftext|>