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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#ifndef _CACHESTR_HXX //autogen
#include <tools/cachestr.hxx>
#endif
#ifndef _CONFIG_HXX
#include <tools/config.hxx>
#endif
#ifndef _INETSTRM_HXX //autogen
#include <svtools/inetstrm.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif

#define _SVSTDARR_STRINGS
#include <svtools/svstdarr.hxx>
#include <vos/mutex.hxx>

#include <vcl/menu.hxx>

#ifndef _LOGINERR_HXX
#include <svtools/loginerr.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DATETIMEITEM_HXX //autogen
#include <svtools/dateitem.hxx>
#endif
#ifndef _SV_MENU_HXX
#include <vcl/menu.hxx>
#endif
#ifndef _SV_WRKWIN_HXX
#include <vcl/wrkwin.hxx>
#endif
#include "comphelper/processfactory.hxx"

#include "viewfrm.hxx"
#include "appdata.hxx"
#include "dispatch.hxx"
#include "event.hxx"
#include "sfxtypes.hxx"
#include "doctempl.hxx"
#include "arrdecl.hxx"
#include "docfac.hxx"
#include "docfile.hxx"
#include "request.hxx"
#include "referers.hxx"
#include "app.hrc"
#include "sfxresid.hxx"
#include "objshimp.hxx"
#include "appuno.hxx"
#include "imestatuswindow.hxx"

SfxAppData_Impl::SfxAppData_Impl( SfxApplication* pApp ) :
        pDdeService( 0 ),
        pDocTopics( 0 ),
        pTriggerTopic(0),
        pDdeService2(0),
        pFactArr(0),
        pTopFrames( new SfxFrameArr_Impl ),
        pInitLinkList(0),
        pMatcher( 0 ),
        pCancelMgr( 0 ),
        pLabelResMgr( 0 ),
        pAppDispatch(NULL),
        pTemplates( 0 ),
        pPool(0),
        pEventConfig(0),
        pDisabledSlotList( 0 ),
        pSecureURLs(0),
        pMiscConfig(0),
        pSaveOptions( 0 ),
        pUndoOptions( 0 ),
        pHelpOptions( 0 ),
        pThisDocument(0),
        pProgress(0),
        pTemplateCommon( 0 ),
        nDocModalMode(0),
        nAutoTabPageId(0),
        nBasicCallLevel(0),
        nRescheduleLocks(0),
        nInReschedule(0),
        nAsynchronCalls(0),
        m_xImeStatusWindow(new sfx2::appl::ImeStatusWindow(
                               *pApp, comphelper::getProcessServiceFactory()))
    , pTbxCtrlFac(0)
    , pStbCtrlFac(0)
    , pViewFrames(0)
    , pObjShells(0)
    , pSfxResManager(0)
    , pOfaResMgr(0)
    , pSimpleResManager(0)
    , pBasicLibContainer(0)
    , pDialogLibContainer(0)
    , pViewFrame( 0 )
    , pSlotPool( 0 )
    , pResMgr( 0 )
    , pAppDispat( 0 )
    , pInterfaces( 0 )
    , nDocNo(0)
    , nInterfaces( 0 )
    , bDowning( sal_True ),
        bInQuit(sal_False),
        bInvalidateOnUnlock(sal_False)
{
}

SfxAppData_Impl::~SfxAppData_Impl()
{
    DeInitDDE();
    delete pTopFrames;
    delete pCancelMgr;
    delete pSecureURLs;
}

IMPL_STATIC_LINK( SfxAppData_Impl, CreateDocumentTemplates, void*, EMPTYARG)
{
    pThis->GetDocumentTemplates();
    return 0;
}

void SfxAppData_Impl::UpdateApplicationSettings( sal_Bool bDontHide )
{
    AllSettings aAllSet = Application::GetSettings();
    StyleSettings aStyleSet = aAllSet.GetStyleSettings();
    sal_uInt32 nStyleOptions = aStyleSet.GetOptions();
    if ( bDontHide )
        nStyleOptions &= ~STYLE_OPTION_HIDEDISABLED;
    else
        nStyleOptions |= STYLE_OPTION_HIDEDISABLED;
    aStyleSet.SetOptions( nStyleOptions );
    aAllSet.SetStyleSettings( aStyleSet );
    Application::SetSettings( aAllSet );
}

SfxDocumentTemplates* SfxAppData_Impl::GetDocumentTemplates()
{
    if ( !pTemplates )
        pTemplates = new SfxDocumentTemplates;
    else
        pTemplates->ReInitFromComponent();
    return pTemplates;
}
<commit_msg>INTEGRATION: CWS basmgr01 (1.23.8); FILE MERGED 2006/09/28 20:25:45 fs 1.23.8.1: #i69957#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: appdata.cxx,v $
 *
 *  $Revision: 1.24 $
 *
 *  last change: $Author: kz $ $Date: 2006-11-08 11:57: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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#ifndef _CACHESTR_HXX //autogen
#include <tools/cachestr.hxx>
#endif
#ifndef _CONFIG_HXX
#include <tools/config.hxx>
#endif
#ifndef _INETSTRM_HXX //autogen
#include <svtools/inetstrm.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif

#define _SVSTDARR_STRINGS
#include <svtools/svstdarr.hxx>
#include <vos/mutex.hxx>

#include <vcl/menu.hxx>

#ifndef _LOGINERR_HXX
#include <svtools/loginerr.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DATETIMEITEM_HXX //autogen
#include <svtools/dateitem.hxx>
#endif
#ifndef _SV_MENU_HXX
#include <vcl/menu.hxx>
#endif
#ifndef _SV_WRKWIN_HXX
#include <vcl/wrkwin.hxx>
#endif
#include "comphelper/processfactory.hxx"

#include "viewfrm.hxx"
#include "appdata.hxx"
#include "dispatch.hxx"
#include "event.hxx"
#include "sfxtypes.hxx"
#include "doctempl.hxx"
#include "arrdecl.hxx"
#include "docfac.hxx"
#include "docfile.hxx"
#include "request.hxx"
#include "referers.hxx"
#include "app.hrc"
#include "sfxresid.hxx"
#include "objshimp.hxx"
#include "appuno.hxx"
#include "imestatuswindow.hxx"
#include "appbaslib.hxx"

#include <basic/basicmanagerrepository.hxx>
#include <basic/basmgr.hxx>

using ::basic::BasicManagerRepository;
using ::basic::BasicManagerCreationListener;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::frame::XModel;

class SfxBasicManagerCreationListener : public ::basic::BasicManagerCreationListener
{
private:
    SfxAppData_Impl& m_rAppData;

public:
    SfxBasicManagerCreationListener( SfxAppData_Impl& _rAppData ) :m_rAppData( _rAppData ) { }

    virtual void onBasicManagerCreated( const Reference< XModel >& _rxForDocument, BasicManager& _rBasicManager );
};

void SfxBasicManagerCreationListener::onBasicManagerCreated( const Reference< XModel >& _rxForDocument, BasicManager& _rBasicManager )
{
    if ( _rxForDocument == NULL )
        m_rAppData.OnApplicationBasicManagerCreated( _rBasicManager );
}

SfxAppData_Impl::SfxAppData_Impl( SfxApplication* pApp ) :
        pDdeService( 0 ),
        pDocTopics( 0 ),
        pTriggerTopic(0),
        pDdeService2(0),
        pFactArr(0),
        pTopFrames( new SfxFrameArr_Impl ),
        pInitLinkList(0),
        pMatcher( 0 ),
        pCancelMgr( 0 ),
        pLabelResMgr( 0 ),
        pAppDispatch(NULL),
        pTemplates( 0 ),
        pPool(0),
        pEventConfig(0),
        pDisabledSlotList( 0 ),
        pSecureURLs(0),
        pMiscConfig(0),
        pSaveOptions( 0 ),
        pUndoOptions( 0 ),
        pHelpOptions( 0 ),
        pThisDocument(0),
        pProgress(0),
        pTemplateCommon( 0 ),
        nDocModalMode(0),
        nAutoTabPageId(0),
        nBasicCallLevel(0),
        nRescheduleLocks(0),
        nInReschedule(0),
        nAsynchronCalls(0),
        m_xImeStatusWindow(new sfx2::appl::ImeStatusWindow(
                               *pApp, comphelper::getProcessServiceFactory()))
    , pTbxCtrlFac(0)
    , pStbCtrlFac(0)
    , pViewFrames(0)
    , pObjShells(0)
    , pSfxResManager(0)
    , pOfaResMgr(0)
    , pSimpleResManager(0)
    , pBasicManager( new SfxBasicManagerHolder )
    , pBasMgrListener( new SfxBasicManagerCreationListener( *this ) )
    , pViewFrame( 0 )
    , pSlotPool( 0 )
    , pResMgr( 0 )
    , pAppDispat( 0 )
    , pInterfaces( 0 )
    , nDocNo(0)
    , nInterfaces( 0 )
    , bDowning( sal_True ),
        bInQuit(sal_False),
        bInvalidateOnUnlock(sal_False)
{
    BasicManagerRepository::registerCreationListener( *pBasMgrListener );
}

SfxAppData_Impl::~SfxAppData_Impl()
{
    DeInitDDE();
    delete pTopFrames;
    delete pCancelMgr;
    delete pSecureURLs;
    delete pBasicManager;

    BasicManagerRepository::revokeCreationListener( *pBasMgrListener );
    delete pBasMgrListener;
}

IMPL_STATIC_LINK( SfxAppData_Impl, CreateDocumentTemplates, void*, EMPTYARG)
{
    pThis->GetDocumentTemplates();
    return 0;
}

void SfxAppData_Impl::UpdateApplicationSettings( sal_Bool bDontHide )
{
    AllSettings aAllSet = Application::GetSettings();
    StyleSettings aStyleSet = aAllSet.GetStyleSettings();
    sal_uInt32 nStyleOptions = aStyleSet.GetOptions();
    if ( bDontHide )
        nStyleOptions &= ~STYLE_OPTION_HIDEDISABLED;
    else
        nStyleOptions |= STYLE_OPTION_HIDEDISABLED;
    aStyleSet.SetOptions( nStyleOptions );
    aAllSet.SetStyleSettings( aStyleSet );
    Application::SetSettings( aAllSet );
}

SfxDocumentTemplates* SfxAppData_Impl::GetDocumentTemplates()
{
    if ( !pTemplates )
        pTemplates = new SfxDocumentTemplates;
    else
        pTemplates->ReInitFromComponent();
    return pTemplates;
}

void SfxAppData_Impl::OnApplicationBasicManagerCreated( BasicManager& _rBasicManager )
{
    pBasicManager->reset( &_rBasicManager );

    // global constants, additionally to the ones already added by createApplicationBasicManager:
    // ThisComponent
    Reference< XModel > xThisComponent;
    SfxObjectShell* pDoc = SfxObjectShell::Current();
    if ( pDoc )
        xThisComponent = pDoc->GetModel();
    _rBasicManager.InsertGlobalUNOConstant( "ThisComponent", makeAny( xThisComponent ) );
    pThisDocument = pDoc;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: newhelp.hxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: pb $ $Date: 2001-07-09 11:36:59 $
 *
 *  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 INCLUDED_SFX_NEWHELP_HXX
#define INCLUDED_SFX_NEWHELP_HXX

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif

namespace com { namespace sun { namespace star { namespace frame { class XFrame; } } } };
namespace com { namespace sun { namespace star { namespace awt { class XWindow; } } } };

#include <vcl/window.hxx>
#include <vcl/toolbox.hxx>
#include <vcl/tabpage.hxx>
#include <vcl/splitwin.hxx>
#include <vcl/tabctrl.hxx>
#include <vcl/combobox.hxx>
#include <vcl/fixed.hxx>
#include <vcl/button.hxx>
#include <vcl/lstbox.hxx>
#include <vcl/dialog.hxx>

// class OpenStatusListener_Impl -----------------------------------------

class OpenStatusListener_Impl : public ::cppu::WeakImplHelper1< ::com::sun::star::frame::XStatusListener >
{
private:
    sal_Bool    m_bFinished;
    sal_Bool    m_bSuccess;
    String      m_aURL;
    Link        m_aOpenLink;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >
                m_xDispatch;

public:
    OpenStatusListener_Impl() : m_bFinished( FALSE ),   m_bSuccess( FALSE ) {}

    virtual void SAL_CALL
                statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL
                disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);

    void        AddListener( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >& xDispatch,
                             const ::com::sun::star::util::URL& aURL );

    sal_Bool    IsFinished() const { return m_bFinished; }
    sal_Bool    IsSuccessful() const { return m_bSuccess; }
    const String& GetURL() const { return m_aURL; }
    void        SetOpenHdl( const Link& rLink ) { m_aOpenLink = rLink; }
};

// class ContentTabPage_Impl ---------------------------------------------

class ContentTabPage_Impl : public TabPage
{
private:
    Window          aContentWin;

public:
    ContentTabPage_Impl( Window* pParent );

    virtual void    Resize();
};

// class IndexTabPage_Impl -----------------------------------------------

class IndexTabPage_Impl : public TabPage
{
private:
    FixedText           aExpressionFT;
    ComboBox            aIndexCB;
    PushButton          aOpenBtn;
    Timer               aFactoryTimer;

    long                nMinWidth;
    String              aFactory;

    void                InitializeIndex();
    void                ClearIndex();

    DECL_LINK(          OpenHdl, PushButton* );
    DECL_LINK(          FactoryHdl, Timer* );

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

    virtual void        Resize();

    void                SetDoubleClickHdl( const Link& rLink );
    void                SetFactory( const String& rFactory );
    String              GetFactory() const { return aFactory; }
    String              GetSelectEntry() const;
};

// class SearchTabPage_Impl ----------------------------------------------

class SearchBox_Impl : public ComboBox
{
private:
    Link                aSearchLink;

public:
    SearchBox_Impl( Window* pParent, const ResId& rResId ) :
        ComboBox( pParent, rResId ) { SetDropDownLineCount( 5 ); }

    virtual long        PreNotify( NotifyEvent& rNEvt );
    virtual void        Select();

    void                SetSearchLink( const Link& rLink ) { aSearchLink = rLink; }
};

class SearchTabPage_Impl : public TabPage
{
private:
    FixedText           aSearchFT;
    SearchBox_Impl      aSearchED;
    PushButton          aSearchBtn;
    ListBox             aResultsLB;
    PushButton          aOpenBtn;
    CheckBox            aScopeCB;

    Size                aMinSize;
    String              aFactory;

    void                ClearSearchResults();
    void                RememberSearchText( const String& rSearchText );

    DECL_LINK(          SearchHdl, PushButton* );
    DECL_LINK(          OpenHdl, PushButton* );

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

    virtual void        Resize();

    void                SetDoubleClickHdl( const Link& rLink );
    void                SetFactory( const String& rFactory ) { aFactory = rFactory; }
    String              GetSelectEntry() const;
};

// class BookmarksTabPage_Impl -------------------------------------------

class BookmarksBox_Impl : public ListBox
{
private:
    void                DoAction( USHORT nAction );

public:
    BookmarksBox_Impl( Window* pParent, const ResId& rResId );
    ~BookmarksBox_Impl();

    virtual long        Notify( NotifyEvent& rNEvt );
};

class BookmarksTabPage_Impl : public TabPage
{
private:
    FixedText           aBookmarksFT;
    BookmarksBox_Impl   aBookmarksBox;
    PushButton          aBookmarksPB;

    long                nMinWidth;

public:
    BookmarksTabPage_Impl( Window* pParent );

    virtual void        Resize();

    void                SetDoubleClickHdl( const Link& rLink );
    String              GetSelectEntry() const;
    void                AddBookmarks( const String& rTitle, const String& rURL );
};

// class SfxHelpIndexWindow_Impl -----------------------------------------

class SfxHelpIndexWindow_Impl : public Window
{
private:
    ListBox             aActiveLB;
    FixedLine           aActiveLine;

    TabControl          aTabCtrl;
    Timer               aInitTimer;

    ContentTabPage_Impl*    pCPage;
    IndexTabPage_Impl*      pIPage;
    SearchTabPage_Impl*     pSPage;
    BookmarksTabPage_Impl*  pFPage;

    long                nMinWidth;

    void                Initialize();
    void                SetActiveFactory();

    DECL_LINK(          ActivatePageHdl, TabControl* );
    DECL_LINK(          SelectHdl, ListBox* );
    DECL_LINK(          InitHdl, Timer* );

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

    virtual void        Resize();

    void                SetDoubleClickHdl( const Link& rLink );
    void                SetFactory( const String& rFactory, sal_Bool bActive );
    String              GetFactory() const { return pIPage->GetFactory(); }
    String              GetSelectEntry() const;
    void                AddBookmarks( const String& rTitle, const String& rURL );
};

// class SfxHelpTextWindow_Impl ------------------------------------------

class SfxHelpWindow_Impl;
class SfxHelpTextWindow_Impl : public Window
{
private:
    ToolBox                 aToolBox;
    SfxHelpWindow_Impl*     pHelpWin;
    Window*                 pTextWin;
    ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame >
                            xFrame;
    sal_Bool                bIsDebug;

public:
    SfxHelpTextWindow_Impl( SfxHelpWindow_Impl* pParent );
    ~SfxHelpTextWindow_Impl();

    virtual void            Resize();
    virtual long            PreNotify( NotifyEvent& rNEvt );

    void                    SetSelectHdl( const Link& rLink ) { aToolBox.SetSelectHdl( rLink ); }

    ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame >
                            getFrame() const { return xFrame; }
};

// class SfxHelpWindow_Impl ----------------------------------------------

class HelpInterceptor_Impl;
class HelpListener_Impl;
class SfxHelpWindow_Impl : public SplitWindow
{
private:
    ::com::sun::star::uno::Reference < ::com::sun::star::awt::XWindow >
                                xWindow;
    ::com::sun::star::uno::Reference < ::com::sun::star::frame::XStatusListener >
                                xOpenListener;

    SfxHelpIndexWindow_Impl*    pIndexWin;
    SfxHelpTextWindow_Impl*     pTextWin;
    HelpInterceptor_Impl*       pHelpInterceptor;
    HelpListener_Impl*          pHelpListener;

    sal_Int32           nExpandWidth;
    sal_Int32           nCollapseWidth;
    sal_Int32           nHeight;
    long                nIndexSize;
    long                nTextSize;

    sal_Bool            bIndex;

    virtual void        Resize();
    virtual void        Split();

    void                MakeLayout();
    void                InitSizes();
    void                LoadConfig();
    void                SaveConfig();

    DECL_LINK(          SelectHdl, ToolBox* );
    DECL_LINK(          OpenHdl, SfxHelpIndexWindow_Impl* );
    DECL_LINK(          ChangeHdl, HelpListener_Impl* );
    DECL_LINK(          OpenDoneHdl, OpenStatusListener_Impl* );

public:
    SfxHelpWindow_Impl( const ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame >& rFrame,
                        Window* pParent, WinBits nBits );
    ~SfxHelpWindow_Impl();

    void                setContainerWindow(
                            ::com::sun::star::uno::Reference < ::com::sun::star::awt::XWindow > xWin );
    void                SetFactory( const String& rFactory, sal_Bool bStart );
    void                SetHelpURL( const String& rURL );
    void                DoAction( USHORT nActionId );
};

class SfxAddHelpBookmarkDialog_Impl : public ModalDialog
{
private:
    FixedText       aTitleFT;
    Edit            aTitleED;
    OKButton        aOKBtn;
    CancelButton    aEscBtn;
    HelpButton      aHelpBtn;

public:
    SfxAddHelpBookmarkDialog_Impl( Window* pParent, sal_Bool bRename = sal_True );
    ~SfxAddHelpBookmarkDialog_Impl();

    void            SetTitle( const String& rTitle );
    String          GetTitle() const { return aTitleED.GetText(); }
};

#endif // #ifndef INCLUDED_SFX_NEWHELP_HXX

<commit_msg>fix: #89087# #87761# index on/off images/strings added, SelectFactory handler added<commit_after>/*************************************************************************
 *
 *  $RCSfile: newhelp.hxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: pb $ $Date: 2001-07-12 10:27: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 INCLUDED_SFX_NEWHELP_HXX
#define INCLUDED_SFX_NEWHELP_HXX

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif

namespace com { namespace sun { namespace star { namespace frame { class XFrame; } } } };
namespace com { namespace sun { namespace star { namespace awt { class XWindow; } } } };

#include <vcl/window.hxx>
#include <vcl/toolbox.hxx>
#include <vcl/tabpage.hxx>
#include <vcl/splitwin.hxx>
#include <vcl/tabctrl.hxx>
#include <vcl/combobox.hxx>
#include <vcl/fixed.hxx>
#include <vcl/button.hxx>
#include <vcl/lstbox.hxx>
#include <vcl/dialog.hxx>

// class OpenStatusListener_Impl -----------------------------------------

class OpenStatusListener_Impl : public ::cppu::WeakImplHelper1< ::com::sun::star::frame::XStatusListener >
{
private:
    sal_Bool    m_bFinished;
    sal_Bool    m_bSuccess;
    String      m_aURL;
    Link        m_aOpenLink;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >
                m_xDispatch;

public:
    OpenStatusListener_Impl() : m_bFinished( FALSE ),   m_bSuccess( FALSE ) {}

    virtual void SAL_CALL
                statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL
                disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);

    void        AddListener( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >& xDispatch,
                             const ::com::sun::star::util::URL& aURL );

    sal_Bool    IsFinished() const { return m_bFinished; }
    sal_Bool    IsSuccessful() const { return m_bSuccess; }
    const String& GetURL() const { return m_aURL; }
    void        SetOpenHdl( const Link& rLink ) { m_aOpenLink = rLink; }
};

// class ContentTabPage_Impl ---------------------------------------------

class ContentTabPage_Impl : public TabPage
{
private:
    Window          aContentWin;

public:
    ContentTabPage_Impl( Window* pParent );

    virtual void    Resize();
};

// class IndexTabPage_Impl -----------------------------------------------

class IndexTabPage_Impl : public TabPage
{
private:
    FixedText           aExpressionFT;
    ComboBox            aIndexCB;
    PushButton          aOpenBtn;
    Timer               aFactoryTimer;

    long                nMinWidth;
    String              aFactory;

    void                InitializeIndex();
    void                ClearIndex();

    DECL_LINK(          OpenHdl, PushButton* );
    DECL_LINK(          FactoryHdl, Timer* );

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

    virtual void        Resize();

    void                SetDoubleClickHdl( const Link& rLink );
    void                SetFactory( const String& rFactory );
    String              GetFactory() const { return aFactory; }
    String              GetSelectEntry() const;
};

// class SearchTabPage_Impl ----------------------------------------------

class SearchBox_Impl : public ComboBox
{
private:
    Link                aSearchLink;

public:
    SearchBox_Impl( Window* pParent, const ResId& rResId ) :
        ComboBox( pParent, rResId ) { SetDropDownLineCount( 5 ); }

    virtual long        PreNotify( NotifyEvent& rNEvt );
    virtual void        Select();

    void                SetSearchLink( const Link& rLink ) { aSearchLink = rLink; }
};

class SearchTabPage_Impl : public TabPage
{
private:
    FixedText           aSearchFT;
    SearchBox_Impl      aSearchED;
    PushButton          aSearchBtn;
    ListBox             aResultsLB;
    PushButton          aOpenBtn;
    CheckBox            aScopeCB;

    Size                aMinSize;
    String              aFactory;

    void                ClearSearchResults();
    void                RememberSearchText( const String& rSearchText );

    DECL_LINK(          SearchHdl, PushButton* );
    DECL_LINK(          OpenHdl, PushButton* );

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

    virtual void        Resize();

    void                SetDoubleClickHdl( const Link& rLink );
    void                SetFactory( const String& rFactory ) { aFactory = rFactory; }
    String              GetSelectEntry() const;
};

// class BookmarksTabPage_Impl -------------------------------------------

class BookmarksBox_Impl : public ListBox
{
private:
    void                DoAction( USHORT nAction );

public:
    BookmarksBox_Impl( Window* pParent, const ResId& rResId );
    ~BookmarksBox_Impl();

    virtual long        Notify( NotifyEvent& rNEvt );
};

class BookmarksTabPage_Impl : public TabPage
{
private:
    FixedText           aBookmarksFT;
    BookmarksBox_Impl   aBookmarksBox;
    PushButton          aBookmarksPB;

    long                nMinWidth;

public:
    BookmarksTabPage_Impl( Window* pParent );

    virtual void        Resize();

    void                SetDoubleClickHdl( const Link& rLink );
    String              GetSelectEntry() const;
    void                AddBookmarks( const String& rTitle, const String& rURL );
};

// class SfxHelpIndexWindow_Impl -----------------------------------------

class SfxHelpIndexWindow_Impl : public Window
{
private:
    ListBox             aActiveLB;
    FixedLine           aActiveLine;

    TabControl          aTabCtrl;
    Timer               aInitTimer;

    Link                aSelectFactoryLink;

    ContentTabPage_Impl*    pCPage;
    IndexTabPage_Impl*      pIPage;
    SearchTabPage_Impl*     pSPage;
    BookmarksTabPage_Impl*  pFPage;

    long                nMinWidth;

    void                Initialize();
    void                SetActiveFactory();

    DECL_LINK(          ActivatePageHdl, TabControl* );
    DECL_LINK(          SelectHdl, ListBox* );
    DECL_LINK(          InitHdl, Timer* );

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

    virtual void        Resize();

    void                SetDoubleClickHdl( const Link& rLink );
    void                SetSelectFactoryHdl( const Link& rLink ) { aSelectFactoryLink = rLink; }
    void                SetFactory( const String& rFactory, sal_Bool bActive );
    String              GetFactory() const { return pIPage->GetFactory(); }
    String              GetSelectEntry() const;
    void                AddBookmarks( const String& rTitle, const String& rURL );
    String              GetActiveFactoryTitle() const { return aActiveLB.GetSelectEntry(); }
};

// class SfxHelpTextWindow_Impl ------------------------------------------

class SfxHelpWindow_Impl;
class SfxHelpTextWindow_Impl : public Window
{
private:
    ToolBox                 aToolBox;
    SfxHelpWindow_Impl*     pHelpWin;
    Window*                 pTextWin;
    ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame >
                            xFrame;
    sal_Bool                bIsDebug;
    sal_Bool                bIsIndexOn;

    String                  aIndexOnText;
    String                  aIndexOffText;
    Image                   aIndexOnImage;
    Image                   aIndexOffImage;

public:
    SfxHelpTextWindow_Impl( SfxHelpWindow_Impl* pParent );
    ~SfxHelpTextWindow_Impl();

    virtual void            Resize();
    virtual long            PreNotify( NotifyEvent& rNEvt );

    void                    SetSelectHdl( const Link& rLink ) { aToolBox.SetSelectHdl( rLink ); }

    ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame >
                            getFrame() const { return xFrame; }
    void                    ToggleIndex( sal_Bool bOn );
};

// class SfxHelpWindow_Impl ----------------------------------------------

class HelpInterceptor_Impl;
class HelpListener_Impl;
class SfxHelpWindow_Impl : public SplitWindow
{
private:
    ::com::sun::star::uno::Reference < ::com::sun::star::awt::XWindow >
                                xWindow;
    ::com::sun::star::uno::Reference < ::com::sun::star::frame::XStatusListener >
                                xOpenListener;

    SfxHelpIndexWindow_Impl*    pIndexWin;
    SfxHelpTextWindow_Impl*     pTextWin;
    HelpInterceptor_Impl*       pHelpInterceptor;
    HelpListener_Impl*          pHelpListener;

    sal_Int32           nExpandWidth;
    sal_Int32           nCollapseWidth;
    sal_Int32           nHeight;
    long                nIndexSize;
    long                nTextSize;
    sal_Bool            bIndex;

    String              aTitle;

    virtual void        Resize();
    virtual void        Split();

    void                MakeLayout();
    void                InitSizes();
    void                LoadConfig();
    void                SaveConfig();
    void                ShowStartPage();

    DECL_LINK(          SelectHdl, ToolBox* );
    DECL_LINK(          OpenHdl, SfxHelpIndexWindow_Impl* );
    DECL_LINK(          SelectFactoryHdl, SfxHelpIndexWindow_Impl* );
    DECL_LINK(          ChangeHdl, HelpListener_Impl* );
    DECL_LINK(          OpenDoneHdl, OpenStatusListener_Impl* );

public:
    SfxHelpWindow_Impl( const ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame >& rFrame,
                        Window* pParent, WinBits nBits );
    ~SfxHelpWindow_Impl();

    void                setContainerWindow(
                            ::com::sun::star::uno::Reference < ::com::sun::star::awt::XWindow > xWin );
    void                SetFactory( const String& rFactory, sal_Bool bStart );
    void                SetHelpURL( const String& rURL );
    void                DoAction( USHORT nActionId );
};

class SfxAddHelpBookmarkDialog_Impl : public ModalDialog
{
private:
    FixedText       aTitleFT;
    Edit            aTitleED;
    OKButton        aOKBtn;
    CancelButton    aEscBtn;
    HelpButton      aHelpBtn;

public:
    SfxAddHelpBookmarkDialog_Impl( Window* pParent, sal_Bool bRename = sal_True );
    ~SfxAddHelpBookmarkDialog_Impl();

    void            SetTitle( const String& rTitle );
    String          GetTitle() const { return aTitleED.GetText(); }
};

#endif // #ifndef INCLUDED_SFX_NEWHELP_HXX

<|endoftext|>


<commit_before>#include "Halide.h"
#include <cstdlib>
#include <chrono>
#include <iostream>
#include "configure.h"
#include "generated_conv_layer.o.h"
#include <tiramisu/utils.h>

int main(int, char**)
{
	srand(1);
	std::vector<double> duration_vector;
	double start, end;

	Halide::Buffer<float> input(FIN_BLOCKING, N + 2, N + 2, FIN_NB_BLOCKS, BATCH_SIZE);
	Halide::Buffer<float> filter(FOUT_BLOCKING, FIN_BLOCKING, K, K, FIN_NB_BLOCKS, FOUT_NB_BLOCKS);
	Halide::Buffer<float> bias(FOut);
	Halide::Buffer<float> conv(FOUT_BLOCKING, N, N, FOUT_NB_BLOCKS, BATCH_SIZE);

	// Initialize buffers
	for (int n = 0; n < BATCH_SIZE; ++n)
		for (int fin = 0; fin < FIn; ++fin)
			for (int y = 0; y < N + 2; ++y)
				for (int x = 0; x < N + 2; ++x)
					input(fin%FIN_BLOCKING, x, y, fin/FIN_BLOCKING, n) = ((float)(rand()%256 - 128)) / 127.f;

	for (int fout = 0; fout < FOut; ++fout)
	{
		int zero_weights = 0;
		for (int fin = 0; fin < FIn; ++fin)
		{
			for (int k_y = 0; k_y < K; ++k_y)
				for (int k_x = 0; k_x < K; ++k_x)
				{
					if (zero_weights < ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL)
					    filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = 0;
					else
					    filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = ((float)(rand()%256 - 128)) / 127.f;
				}

		        zero_weights++;
		}
	}

	for (int fout = 0; fout < FOut; ++fout)
		bias(fout) = ((float)(rand()%256 - 128)) / 127.f;

	std::cout << "\t\tBuffers initialized" << std::endl;

	// Execute Tiramisu code
	for (int i = 0; i < NB_TESTS; i++) {
		start = rtclock();

		conv_tiramisu(
			input.raw_buffer(),
			filter.raw_buffer(),
			bias.raw_buffer(),
			conv.raw_buffer()
		);

		end = rtclock();
		duration_vector.push_back((end - start) * 1000);
	}

	std::cout << "\t\tN = " << N << "; BATCH_SIZE = " << BATCH_SIZE << "; FIn = " << FIn << "; FOut = " << FOut << ";" << std::endl;
	std::cout << "\t\tTiramisu conv" << ": " << median(duration_vector) << "; " << std::endl;

	// Write results to file
	FILE* f = fopen("tiramisu_result.txt", "w");
	if (f == NULL) {
		printf("Error creating tiramisu_result.txt.\n");
		return 0;
	}

	for (int n = 0; n < BATCH_SIZE; ++n)
		for (int fout = 0; fout < FOut; ++fout)
			for (int y = 0; y < N; ++y)
				for (int x = 0; x < N; ++x)
					fprintf(f, "%.10g\n", conv(fout%FOUT_BLOCKING, x, y, fout/FOUT_BLOCKING, n));

	fclose(f);

    // Compare results with Intel MKL
    std::ifstream mkl_result("mkl_result.txt");
    float tmp;
    float file_count = 0, corr = 0;

    for (int n = 0; n < BATCH_SIZE; ++n)
        for (int fout = 0; fout < FOut; ++fout)
            for (int y = 0; y < N; ++y)
                for (int x = 0; x < N; ++x) {
                    mkl_result >> tmp;

                    file_count++;
                    if (std::abs(conv(fout%FOUT_BLOCKING, x, y, fout/FOUT_BLOCKING, n) - tmp) <= 0.0001)
                        corr++;
                }

    std::cout << "\t\tResult"
              << ":\n\n";

    std::cout << "\t\tPercentage of correctness " << corr / file_count * 100 << "%" << std::endl << std::endl;

    return 0;
}
<commit_msg>Add pattern 0, 1 and 2 to data generation in Tiramisu code<commit_after>#include "Halide.h"
#include <cstdlib>
#include <chrono>
#include <iostream>
#include "configure.h"
#include "generated_conv_layer.o.h"
#include <tiramisu/utils.h>

int main(int, char**)
{
	srand(1);
	std::vector<double> duration_vector;
	double start, end;

	Halide::Buffer<float> input(FIN_BLOCKING, N + 2, N + 2, FIN_NB_BLOCKS, BATCH_SIZE);
	Halide::Buffer<float> filter(FOUT_BLOCKING, FIN_BLOCKING, K, K, FIN_NB_BLOCKS, FOUT_NB_BLOCKS);
	Halide::Buffer<float> bias(FOut);
	Halide::Buffer<float> conv(FOUT_BLOCKING, N, N, FOUT_NB_BLOCKS, BATCH_SIZE);

	// Initialize buffers
	for (int n = 0; n < BATCH_SIZE; ++n)
		for (int fin = 0; fin < FIn; ++fin)
			for (int y = 0; y < N + 2; ++y)
				for (int x = 0; x < N + 2; ++x)
					input(fin%FIN_BLOCKING, x, y, fin/FIN_BLOCKING, n) = ((float)(rand()%256 - 128)) / 127.f;

    	for (int fout = 0; fout < FOut; ++fout)
        {
		int zero_weights = 0;
		for (int fin = 0; fin < FIn; ++fin)
		{
			for (int k_y = 0; k_y < K; ++k_y)
				for (int k_x = 0; k_x < K; ++k_x)
				{
					if (zero_weights < ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL)
					{
	 				        filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = 0;
					}
					else if (zero_weights < ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL +
								PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL)
					{
						if (k_y == 0)
						    filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = 1;
						else
					    	    filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = 0;
					}
					else if (zero_weights < ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL +
								PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL +
								PATTERN_1_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL)
					{
						if (k_y == 1)
							filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = 1;
						else
							filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = 0;

					}
					else if (zero_weights < ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL +
								PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL +
								PATTERN_1_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL +
								PATTERN_2_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL)
					{
						if (k_y == 2)
					    		filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = 1;
						else
					    		filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = 0;

					}
					else
						filter(fout%FOUT_BLOCKING, fin%FIN_BLOCKING, k_x, k_y, fin/FIN_BLOCKING, fout/FOUT_BLOCKING) = ((float)(rand()%256 - 128)) / 127.f;
				}

			zero_weights++;
		}
    	}

	for (int fout = 0; fout < FOut; ++fout)
		bias(fout) = ((float)(rand()%256 - 128)) / 127.f;

	std::cout << "\t\tBuffers initialized" << std::endl;

	// Execute Tiramisu code
	for (int i = 0; i < NB_TESTS; i++) {
		start = rtclock();

		conv_tiramisu(
			input.raw_buffer(),
			filter.raw_buffer(),
			bias.raw_buffer(),
			conv.raw_buffer()
		);

		end = rtclock();
		duration_vector.push_back((end - start) * 1000);
	}

	std::cout << "\t\tN = " << N << "; BATCH_SIZE = " << BATCH_SIZE << "; FIn = " << FIn << "; FOut = " << FOut << ";" << std::endl;
	std::cout << "\t\tTiramisu conv" << ": " << median(duration_vector) << "; " << std::endl;

	// Write results to file
	FILE* f = fopen("tiramisu_result.txt", "w");
	if (f == NULL) {
		printf("Error creating tiramisu_result.txt.\n");
		return 0;
	}

	for (int n = 0; n < BATCH_SIZE; ++n)
		for (int fout = 0; fout < FOut; ++fout)
			for (int y = 0; y < N; ++y)
				for (int x = 0; x < N; ++x)
					fprintf(f, "%.10g\n", conv(fout%FOUT_BLOCKING, x, y, fout/FOUT_BLOCKING, n));

	fclose(f);

    // Compare results with Intel MKL
    std::ifstream mkl_result("mkl_result.txt");
    float tmp;
    float file_count = 0, corr = 0;

    for (int n = 0; n < BATCH_SIZE; ++n)
        for (int fout = 0; fout < FOut; ++fout)
            for (int y = 0; y < N; ++y)
                for (int x = 0; x < N; ++x) {
                    mkl_result >> tmp;

                    file_count++;
                    if (std::abs(conv(fout%FOUT_BLOCKING, x, y, fout/FOUT_BLOCKING, n) - tmp) <= 0.0001)
                        corr++;
                }

    std::cout << "\t\tResult"
              << ":\n\n";

    std::cout << "\t\tPercentage of correctness " << corr / file_count * 100 << "%" << std::endl << std::endl;

    return 0;
}
<|endoftext|>


<commit_before>// RUN: %clangxx -O1 %s -o %t && TSAN_OPTIONS="flush_memory_ms=1 memory_limit_mb=1" ASAN_OPTIONS="handle_segv=0 allow_user_segv_handler=1" %run %t 2>&1 | FileCheck %s

// JVM uses SEGV to preempt threads. All threads do a load from a known address
// periodically. When runtime needs to preempt threads, it unmaps the page.
// Threads start triggering SEGV one by one. The signal handler blocks
// threads while runtime does its thing. Then runtime maps the page again
// and resumes the threads.
// Previously this pattern conflicted with stop-the-world machinery,
// because it briefly reset SEGV handler to SIG_DFL.
// As the consequence JVM just silently died.

// This test sets memory flushing rate to maximum, then does series of
// "benign" SEGVs that are handled by signal handler, and ensures that
// the process survive.

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/mman.h>
#include <string.h>

void *guard;

void handler(int signo, siginfo_t *info, void *uctx) {
  mprotect(guard, 4096, PROT_READ | PROT_WRITE);
}

int main() {
  struct sigaction a, old;
  memset(&a, 0, sizeof(a));
  memset(&old, 0, sizeof(old));
  a.sa_sigaction = handler;
  a.sa_flags = SA_SIGINFO;
  sigaction(SIGSEGV, &a, &old);
  guard = (char *)mmap(0, 3 * 4096, PROT_NONE, MAP_ANON | MAP_PRIVATE, -1, 0) +
          4096;
  for (int i = 0; i < 1000000; i++) {
    mprotect(guard, 4096, PROT_NONE);
    *(int*)guard = 1;
  }
  sigaction(SIGSEGV, &old, 0);
  fprintf(stderr, "DONE\n");
}

// CHECK: DONE
<commit_msg>asan: fix a test<commit_after>// RUN: %clangxx -O1 %s -o %t && TSAN_OPTIONS="flush_memory_ms=1 memory_limit_mb=1" ASAN_OPTIONS="handle_segv=0 allow_user_segv_handler=1" %run %t 2>&1 | FileCheck %s

// JVM uses SEGV to preempt threads. All threads do a load from a known address
// periodically. When runtime needs to preempt threads, it unmaps the page.
// Threads start triggering SEGV one by one. The signal handler blocks
// threads while runtime does its thing. Then runtime maps the page again
// and resumes the threads.
// Previously this pattern conflicted with stop-the-world machinery,
// because it briefly reset SEGV handler to SIG_DFL.
// As the consequence JVM just silently died.

// This test sets memory flushing rate to maximum, then does series of
// "benign" SEGVs that are handled by signal handler, and ensures that
// the process survive.

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/mman.h>
#include <string.h>
#include <unistd.h>

unsigned long page_size;
void *guard;

void handler(int signo, siginfo_t *info, void *uctx) {
  mprotect(guard, page_size, PROT_READ | PROT_WRITE);
}

int main() {
  page_size = sysconf(_SC_PAGESIZE);
  struct sigaction a, old;
  memset(&a, 0, sizeof(a));
  memset(&old, 0, sizeof(old));
  a.sa_sigaction = handler;
  a.sa_flags = SA_SIGINFO;
  sigaction(SIGSEGV, &a, &old);
  guard = mmap(0, 3 * page_size, PROT_NONE, MAP_ANON | MAP_PRIVATE, -1, 0);
  guard = (char*)guard + page_size;  // work around a kernel bug
  for (int i = 0; i < 1000000; i++) {
    mprotect(guard, page_size, PROT_NONE);
    *(int*)guard = 1;
  }
  sigaction(SIGSEGV, &old, 0);
  fprintf(stderr, "DONE\n");
}

// CHECK: DONE
<|endoftext|>


<commit_before>//===- Chunks.cpp ---------------------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "Chunks.h"
#include "InputFiles.h"
#include "Writer.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/COFF.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;
using namespace llvm::object;
using namespace llvm::support::endian;
using namespace llvm::COFF;
using llvm::RoundUpToAlignment;

namespace lld {
namespace coff {

SectionChunk::SectionChunk(ObjectFile *F, const coff_section *H, uint32_t SI)
    : File(F), Header(H), SectionIndex(SI) {
  // Initialize SectionName.
  File->getCOFFObj()->getSectionName(Header, SectionName);
  // Bit [20:24] contains section alignment.
  unsigned Shift = ((Header->Characteristics & 0xF00000) >> 20) - 1;
  Align = uint32_t(1) << Shift;
}

void SectionChunk::writeTo(uint8_t *Buf) {
  if (!hasData())
    return;
  // Copy section contents from source object file to output file.
  ArrayRef<uint8_t> Data;
  File->getCOFFObj()->getSectionContents(Header, Data);
  memcpy(Buf + FileOff, Data.data(), Data.size());

  // Apply relocations.
  for (const auto &I : getSectionRef().relocations()) {
    const coff_relocation *Rel = File->getCOFFObj()->getCOFFRelocation(I);
    applyReloc(Buf, Rel);
  }
}

// Returns true if this chunk should be considered as a GC root.
bool SectionChunk::isRoot() {
  // COMDAT sections are live only when they are referenced by something else.
  if (isCOMDAT())
    return false;

  // Associative sections are live if their parent COMDATs are live,
  // and vice versa, so they are not considered live by themselves.
  if (IsAssocChild)
    return false;

  // Only code is subject of dead-stripping.
  return !(Header->Characteristics & IMAGE_SCN_CNT_CODE);
}

void SectionChunk::markLive() {
  if (Live)
    return;
  Live = true;

  // Mark all symbols listed in the relocation table for this section.
  for (const auto &I : getSectionRef().relocations()) {
    const coff_relocation *Rel = File->getCOFFObj()->getCOFFRelocation(I);
    SymbolBody *B = File->getSymbolBody(Rel->SymbolTableIndex);
    if (auto *Def = dyn_cast<Defined>(B))
      Def->markLive();
  }

  // Mark associative sections if any.
  for (Chunk *C : AssocChildren)
    C->markLive();
}

void SectionChunk::addAssociative(SectionChunk *Child) {
  Child->IsAssocChild = true;
  AssocChildren.push_back(Child);
}

static void add16(uint8_t *P, int32_t V) { write16le(P, read16le(P) + V); }
static void add32(uint8_t *P, int32_t V) { write32le(P, read32le(P) + V); }
static void add64(uint8_t *P, int64_t V) { write64le(P, read64le(P) + V); }

// Implements x64 PE/COFF relocations.
void SectionChunk::applyReloc(uint8_t *Buf, const coff_relocation *Rel) {
  uint8_t *Off = Buf + FileOff + Rel->VirtualAddress;
  SymbolBody *Body = File->getSymbolBody(Rel->SymbolTableIndex);
  uint64_t S = cast<Defined>(Body)->getRVA();
  uint64_t P = RVA + Rel->VirtualAddress;
  switch (Rel->Type) {
  case IMAGE_REL_AMD64_ADDR32:   add32(Off, S + Config->ImageBase); break;
  case IMAGE_REL_AMD64_ADDR64:   add64(Off, S + Config->ImageBase); break;
  case IMAGE_REL_AMD64_ADDR32NB: add32(Off, S); break;
  case IMAGE_REL_AMD64_REL32:    add32(Off, S - P - 4); break;
  case IMAGE_REL_AMD64_REL32_1:  add32(Off, S - P - 5); break;
  case IMAGE_REL_AMD64_REL32_2:  add32(Off, S - P - 6); break;
  case IMAGE_REL_AMD64_REL32_3:  add32(Off, S - P - 7); break;
  case IMAGE_REL_AMD64_REL32_4:  add32(Off, S - P - 8); break;
  case IMAGE_REL_AMD64_REL32_5:  add32(Off, S - P - 9); break;
  case IMAGE_REL_AMD64_SECTION:  add16(Off, Out->getSectionIndex()); break;
  case IMAGE_REL_AMD64_SECREL:   add32(Off, S - Out->getRVA()); break;
  default:
    llvm::report_fatal_error("Unsupported relocation type");
  }
}

bool SectionChunk::hasData() const {
  return !(Header->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA);
}

uint32_t SectionChunk::getPermissions() const {
  return Header->Characteristics & PermMask;
}

bool SectionChunk::isCOMDAT() const {
  return Header->Characteristics & IMAGE_SCN_LNK_COMDAT;
}

// Prints "Discarded <symbol>" for all external function symbols.
void SectionChunk::printDiscardedMessage() {
  uint32_t E = File->getCOFFObj()->getNumberOfSymbols();
  for (uint32_t I = 0; I < E; ++I) {
    auto SrefOrErr = File->getCOFFObj()->getSymbol(I);
    COFFSymbolRef Sym = SrefOrErr.get();
    if (uint32_t(Sym.getSectionNumber()) != SectionIndex)
      continue;
    if (!Sym.isFunctionDefinition())
      continue;
    StringRef SymbolName;
    File->getCOFFObj()->getSymbolName(Sym, SymbolName);
    llvm::dbgs() << "Discarded " << SymbolName << " from "
                 << File->getShortName() << "\n";
    I += Sym.getNumberOfAuxSymbols();
  }
}

SectionRef SectionChunk::getSectionRef() {
  DataRefImpl Ref;
  Ref.p = uintptr_t(Header);
  return SectionRef(Ref, File->getCOFFObj());
}

uint32_t CommonChunk::getPermissions() const {
  return IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ |
         IMAGE_SCN_MEM_WRITE;
}

void StringChunk::writeTo(uint8_t *Buf) {
  memcpy(Buf + FileOff, Str.data(), Str.size());
}

void ImportThunkChunk::writeTo(uint8_t *Buf) {
  memcpy(Buf + FileOff, ImportThunkData, sizeof(ImportThunkData));
  // The first two bytes is a JMP instruction. Fill its operand.
  uint32_t Operand = ImpSymbol->getRVA() - RVA - getSize();
  write32le(Buf + FileOff + 2, Operand);
}

} // namespace coff
} // namespace lld
<commit_msg>COFF: Fix typo.<commit_after>//===- Chunks.cpp ---------------------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "Chunks.h"
#include "InputFiles.h"
#include "Writer.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/COFF.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;
using namespace llvm::object;
using namespace llvm::support::endian;
using namespace llvm::COFF;
using llvm::RoundUpToAlignment;

namespace lld {
namespace coff {

SectionChunk::SectionChunk(ObjectFile *F, const coff_section *H, uint32_t SI)
    : File(F), Header(H), SectionIndex(SI) {
  // Initialize SectionName.
  File->getCOFFObj()->getSectionName(Header, SectionName);
  // Bit [20:24] contains section alignment.
  unsigned Shift = ((Header->Characteristics & 0xF00000) >> 20) - 1;
  Align = uint32_t(1) << Shift;
}

void SectionChunk::writeTo(uint8_t *Buf) {
  if (!hasData())
    return;
  // Copy section contents from source object file to output file.
  ArrayRef<uint8_t> Data;
  File->getCOFFObj()->getSectionContents(Header, Data);
  memcpy(Buf + FileOff, Data.data(), Data.size());

  // Apply relocations.
  for (const auto &I : getSectionRef().relocations()) {
    const coff_relocation *Rel = File->getCOFFObj()->getCOFFRelocation(I);
    applyReloc(Buf, Rel);
  }
}

// Returns true if this chunk should be considered as a GC root.
bool SectionChunk::isRoot() {
  // COMDAT sections are live only when they are referenced by something else.
  if (isCOMDAT())
    return false;

  // Associative sections are live if their parent COMDATs are live,
  // and vice versa, so they are not considered live by themselves.
  if (IsAssocChild)
    return false;

  // Only code is subject of dead-stripping.
  return !(Header->Characteristics & IMAGE_SCN_CNT_CODE);
}

void SectionChunk::markLive() {
  if (Live)
    return;
  Live = true;

  // Mark all symbols listed in the relocation table for this section.
  for (const auto &I : getSectionRef().relocations()) {
    const coff_relocation *Rel = File->getCOFFObj()->getCOFFRelocation(I);
    SymbolBody *B = File->getSymbolBody(Rel->SymbolTableIndex);
    if (auto *Def = dyn_cast<Defined>(B))
      Def->markLive();
  }

  // Mark associative sections if any.
  for (Chunk *C : AssocChildren)
    C->markLive();
}

void SectionChunk::addAssociative(SectionChunk *Child) {
  Child->IsAssocChild = true;
  AssocChildren.push_back(Child);
}

static void add16(uint8_t *P, int16_t V) { write16le(P, read16le(P) + V); }
static void add32(uint8_t *P, int32_t V) { write32le(P, read32le(P) + V); }
static void add64(uint8_t *P, int64_t V) { write64le(P, read64le(P) + V); }

// Implements x64 PE/COFF relocations.
void SectionChunk::applyReloc(uint8_t *Buf, const coff_relocation *Rel) {
  uint8_t *Off = Buf + FileOff + Rel->VirtualAddress;
  SymbolBody *Body = File->getSymbolBody(Rel->SymbolTableIndex);
  uint64_t S = cast<Defined>(Body)->getRVA();
  uint64_t P = RVA + Rel->VirtualAddress;
  switch (Rel->Type) {
  case IMAGE_REL_AMD64_ADDR32:   add32(Off, S + Config->ImageBase); break;
  case IMAGE_REL_AMD64_ADDR64:   add64(Off, S + Config->ImageBase); break;
  case IMAGE_REL_AMD64_ADDR32NB: add32(Off, S); break;
  case IMAGE_REL_AMD64_REL32:    add32(Off, S - P - 4); break;
  case IMAGE_REL_AMD64_REL32_1:  add32(Off, S - P - 5); break;
  case IMAGE_REL_AMD64_REL32_2:  add32(Off, S - P - 6); break;
  case IMAGE_REL_AMD64_REL32_3:  add32(Off, S - P - 7); break;
  case IMAGE_REL_AMD64_REL32_4:  add32(Off, S - P - 8); break;
  case IMAGE_REL_AMD64_REL32_5:  add32(Off, S - P - 9); break;
  case IMAGE_REL_AMD64_SECTION:  add16(Off, Out->getSectionIndex()); break;
  case IMAGE_REL_AMD64_SECREL:   add32(Off, S - Out->getRVA()); break;
  default:
    llvm::report_fatal_error("Unsupported relocation type");
  }
}

bool SectionChunk::hasData() const {
  return !(Header->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA);
}

uint32_t SectionChunk::getPermissions() const {
  return Header->Characteristics & PermMask;
}

bool SectionChunk::isCOMDAT() const {
  return Header->Characteristics & IMAGE_SCN_LNK_COMDAT;
}

// Prints "Discarded <symbol>" for all external function symbols.
void SectionChunk::printDiscardedMessage() {
  uint32_t E = File->getCOFFObj()->getNumberOfSymbols();
  for (uint32_t I = 0; I < E; ++I) {
    auto SrefOrErr = File->getCOFFObj()->getSymbol(I);
    COFFSymbolRef Sym = SrefOrErr.get();
    if (uint32_t(Sym.getSectionNumber()) != SectionIndex)
      continue;
    if (!Sym.isFunctionDefinition())
      continue;
    StringRef SymbolName;
    File->getCOFFObj()->getSymbolName(Sym, SymbolName);
    llvm::dbgs() << "Discarded " << SymbolName << " from "
                 << File->getShortName() << "\n";
    I += Sym.getNumberOfAuxSymbols();
  }
}

SectionRef SectionChunk::getSectionRef() {
  DataRefImpl Ref;
  Ref.p = uintptr_t(Header);
  return SectionRef(Ref, File->getCOFFObj());
}

uint32_t CommonChunk::getPermissions() const {
  return IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ |
         IMAGE_SCN_MEM_WRITE;
}

void StringChunk::writeTo(uint8_t *Buf) {
  memcpy(Buf + FileOff, Str.data(), Str.size());
}

void ImportThunkChunk::writeTo(uint8_t *Buf) {
  memcpy(Buf + FileOff, ImportThunkData, sizeof(ImportThunkData));
  // The first two bytes is a JMP instruction. Fill its operand.
  uint32_t Operand = ImpSymbol->getRVA() - RVA - getSize();
  write32le(Buf + FileOff + 2, Operand);
}

} // namespace coff
} // namespace lld
<|endoftext|>


<commit_before>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB

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

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#include "manager.h"

#include <my_global.h>
#include <signal.h>

#include "thread_repository.h"
#include "listener.h"
#include "log.h"

void manager(const char *socket_file_name)
{
  Thread_repository thread_repository;
  Listener_thread_args listener_args(thread_repository, socket_file_name);

  /* write pid file */

  /* block signals */
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGINT);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGHUP);

  /* all new threads will inherite this signal mask */
  pthread_sigmask(SIG_BLOCK, &mask, NULL);
  {
    /* create the listener */
    pthread_t listener_thd_id;
    pthread_attr_t listener_thd_attr;

    pthread_attr_init(&listener_thd_attr);
    pthread_attr_setdetachstate(&listener_thd_attr, PTHREAD_CREATE_DETACHED);
    if (pthread_create(&listener_thd_id, &listener_thd_attr, listener,
                       &listener_args))
      die("manager(): pthread_create(listener) failed");
  }
  /*
    To work nicely with LinuxThreads, the signal thread is the first thread
    in the process.
  */
  int signo;
  sigwait(&mask, &signo);
  thread_repository.deliver_shutdown();
  /* don't pthread_exit to kill all threads who did not shut down in time */
}
<commit_msg>Fix for the unixware: non-posix sigwait<commit_after>/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB

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

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#include "manager.h"

#include <my_global.h>
#include <signal.h>

#include "thread_repository.h"
#include "listener.h"
#include "log.h"

void manager(const char *socket_file_name)
{
  Thread_repository thread_repository;
  Listener_thread_args listener_args(thread_repository, socket_file_name);

  /* write pid file */

  /* block signals */
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGINT);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGHUP);

  /* all new threads will inherite this signal mask */
  pthread_sigmask(SIG_BLOCK, &mask, NULL);
  {
    /* create the listener */
    pthread_t listener_thd_id;
    pthread_attr_t listener_thd_attr;

    pthread_attr_init(&listener_thd_attr);
    pthread_attr_setdetachstate(&listener_thd_attr, PTHREAD_CREATE_DETACHED);
    if (pthread_create(&listener_thd_id, &listener_thd_attr, listener,
                       &listener_args))
      die("manager(): pthread_create(listener) failed");
  }
  /*
    To work nicely with LinuxThreads, the signal thread is the first thread
    in the process.
  */
  int signo;
  my_sigwait(&mask, &signo);
  thread_repository.deliver_shutdown();
  /* don't pthread_exit to kill all threads who did not shut down in time */
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008, 2009 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>
#include <QtCore>
#include "fileutils.h"
#include "infocdbbackend.h"
#include "cdbwriter.h"

class InfoCdbBackendUnitTest : public QObject
{
    Q_OBJECT
    InfoCdbBackend *backend;

private slots:
    void initTestCase();
    void listKeys();
    void listPlugins();
    void listKeysForPlugin();
};

void InfoCdbBackendUnitTest::initTestCase()
{
    // FIXME: LOCAL_DIR
    CDBWriter writer("cache.cdb");
    writer.add("KEYS", "Battery.Charging");
    writer.add("KEYS", "Internet.BytesOut");
    writer.add("PLUGINS", "contextkit-dbus");
    writer.add("contextkit-dbus:KEYS", "Battery.Charging");
    writer.add("contextkit-dbus:KEYS", "Battery.BytesOut");
    writer.close();

    utilSetEnv("CONTEXT_PROVIDERS", LOCAL_DIR);
    utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null");
    backend = new InfoCdbBackend();
}

void InfoCdbBackendUnitTest::listKeys()
{
    QStringList keys = backend->listKeys();
    QCOMPARE(keys.count(), 2);
    QVERIFY(keys.contains("Battery.Charging"));
    QVERIFY(keys.contains("Internet.BytesOut"));
}

void InfoCdbBackendUnitTest::listPlugins()
{
    QStringList plugins = backend->listPlugins();
    QCOMPARE(plugins.count(), 1);
    QVERIFY(plugins.contains("contextkit-dbus"));
}

void InfoCdbBackendUnitTest::listKeysForPlugin()
{
    QStringList keys1 = backend->listKeysForPlugin("contextkit-dbus");
    QCOMPARE(keys1.count(), 2);
    QVERIFY(keys1.contains("Battery.Charging"));
    QVERIFY(keys1.contains("Internet.BytesOut"));

    QStringList keys2 = backend->listKeysForPlugin("non-existant");
    QCOMPARE(keys2.count(), 1);
}

#include "infocdbbackendunittest.moc"
QTEST_MAIN(InfoCdbBackendUnitTest);
<commit_msg>typeForKey.<commit_after>/*
 * Copyright (C) 2008, 2009 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>
#include <QtCore>
#include "fileutils.h"
#include "infocdbbackend.h"
#include "cdbwriter.h"

class InfoCdbBackendUnitTest : public QObject
{
    Q_OBJECT
    InfoCdbBackend *backend;

private slots:
    void initTestCase();
    void listKeys();
    void listPlugins();
    void listKeysForPlugin();
    void typeForKey();
};

void InfoCdbBackendUnitTest::initTestCase()
{
    // FIXME: LOCAL_DIR
    CDBWriter writer("cache.cdb");
    writer.add("KEYS", "Battery.Charging");
    writer.add("KEYS", "Internet.BytesOut");
    writer.add("PLUGINS", "contextkit-dbus");
    writer.add("contextkit-dbus:KEYS", "Battery.Charging");
    writer.add("contextkit-dbus:KEYS", "Internet.BytesOut");
    writer.add("Battery.Charging:TYPE", "TRUTH");
    writer.add("Internet.BytesOut:TYPE", "INTEGER");
    writer.close();

    utilSetEnv("CONTEXT_PROVIDERS", LOCAL_DIR);
    utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null");
    backend = new InfoCdbBackend();
}

void InfoCdbBackendUnitTest::listKeys()
{
    QStringList keys = backend->listKeys();
    QCOMPARE(keys.count(), 2);
    QVERIFY(keys.contains("Battery.Charging"));
    QVERIFY(keys.contains("Internet.BytesOut"));
}

void InfoCdbBackendUnitTest::listPlugins()
{
    QStringList plugins = backend->listPlugins();
    QCOMPARE(plugins.count(), 1);
    QVERIFY(plugins.contains("contextkit-dbus"));
}

void InfoCdbBackendUnitTest::listKeysForPlugin()
{
    QStringList keys1 = backend->listKeysForPlugin("contextkit-dbus");
    QCOMPARE(keys1.count(), 2);
    QVERIFY(keys1.contains("Battery.Charging"));
    QVERIFY(keys1.contains("Internet.BytesOut"));

    QStringList keys2 = backend->listKeysForPlugin("non-existant");
    QCOMPARE(keys2.count(), 1);
}

void InfoCdbBackendUnitTest::typeForKey()
{
    QCOMPARE(backend->typeForKey("Internet.BytesOut"), QString("INTEGER"));
    QCOMPARE(backend->typeForKey("Battery.Charging"), QString("TRUTH"));
    QCOMPARE(backend->typeForKey("Does.Not.Exist"), QString());
}

#include "infocdbbackendunittest.moc"
QTEST_MAIN(InfoCdbBackendUnitTest);
<|endoftext|>


<commit_before>/***************************************************************************************[System.cc]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson

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 "utils/System.h"

#if defined(__linux__)

#include <stdio.h>
#include <stdlib.h>

using namespace Minisat;

// TODO: split the memory reading functions into two: one for reading high-watermark of RSS, and
// one for reading the current virtual memory size.

static inline int memReadStat(int field)
{
    char  name[256];
    pid_t pid = getpid();
    int   value;

    sprintf(name, "/proc/%d/statm", pid);
    FILE* in = fopen(name, "rb");
    if (in == NULL) return 0;

    for (; field >= 0; field--)
        if (fscanf(in, "%d", &value) != 1)
            printf("ERROR! Failed to parse memory statistics from \"/proc\".\n"), exit(1);
    fclose(in);
    return value;
}

static inline int memReadPeak(void)
{
    char  name[256];
    pid_t pid = getpid();

    sprintf(name, "/proc/%d/status", pid);
    FILE* in = fopen(name, "rb");
    if (in == NULL) return 0;

    // Find the correct line, beginning with "VmPeak:":
    int peak_kb = 0;
    while (!feof(in) && fscanf(in, "VmPeak: %d kB", &peak_kb) != 1)
        while (!feof(in) && fgetc(in) != '\n')
            ;
    fclose(in);

    return peak_kb;
}

double Minisat::memUsed() { return (double)memReadStat(0) * (double)getpagesize() / (1024*1024); }
double Minisat::memUsedPeak() {
    double peak = memReadPeak() / 1024;
    return peak == 0 ? memUsed() : peak; }

#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__gnu_hurd__)

double Minisat::memUsed(void) {
    struct rusage ru;
    getrusage(RUSAGE_SELF, &ru);
    return (double)ru.ru_maxrss / 1024; }
double Minisat::memUsedPeak(void) { return memUsed(); }

#elif defined(__APPLE__)
#include <malloc/malloc.h>

double Minisat::memUsed(void) {
    malloc_statistics_t t;
    malloc_zone_statistics(NULL, &t);
    return (double)t.max_size_in_use / (1024*1024); }

#else
double Minisat::memUsed() {
    return 0; }
#endif
<commit_msg>Fix build and minor cleanup of System module.<commit_after>/***************************************************************************************[System.cc]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson

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 "utils/System.h"

#if defined(__linux__)

#include <stdio.h>
#include <stdlib.h>

using namespace Minisat;

static inline int memReadStat(int field)
{
    char  name[256];
    pid_t pid = getpid();
    int   value;

    sprintf(name, "/proc/%d/statm", pid);
    FILE* in = fopen(name, "rb");
    if (in == NULL) return 0;

    for (; field >= 0; field--)
        if (fscanf(in, "%d", &value) != 1)
            printf("ERROR! Failed to parse memory statistics from \"/proc\".\n"), exit(1);
    fclose(in);
    return value;
}

static inline int memReadPeak(void)
{
    char  name[256];
    pid_t pid = getpid();

    sprintf(name, "/proc/%d/status", pid);
    FILE* in = fopen(name, "rb");
    if (in == NULL) return 0;

    // Find the correct line, beginning with "VmPeak:":
    int peak_kb = 0;
    while (!feof(in) && fscanf(in, "VmPeak: %d kB", &peak_kb) != 1)
        while (!feof(in) && fgetc(in) != '\n')
            ;
    fclose(in);

    return peak_kb;
}

double Minisat::memUsed() { return (double)memReadStat(0) * (double)getpagesize() / (1024*1024); }
double Minisat::memUsedPeak() {
    double peak = memReadPeak() / 1024;
    return peak == 0 ? memUsed() : peak; }

#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__gnu_hurd__)

double Minisat::memUsed() {
    struct rusage ru;
    getrusage(RUSAGE_SELF, &ru);
    return (double)ru.ru_maxrss / 1024; }
double Minisat::memUsedPeak() { return memUsed(); }

#elif defined(__APPLE__)
#include <malloc/malloc.h>

double Minisat::memUsed() {
    malloc_statistics_t t;
    malloc_zone_statistics(NULL, &t);
    return (double)t.max_size_in_use / (1024*1024); }
double Minisat::memUsedPeak() { return memUsed(); }

#else
double Minisat::memUsed()     { return 0; }
double Minisat::memUsedPeak() { return 0; }
#endif
<|endoftext|>


<commit_before>/*!
 *  \file       ak47_HardwareSerial.hpp
 *  \author     Francois Best
 *  \date       16/06/2012
 *  \license    GPL v3.0 - Copyright Forty Seven Effects 2012
 *
 *	This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details: http://www.gnu.org/licenses
 */

#pragma once

BEGIN_AK47_NAMESPACE

// -----------------------------------------------------------------------------
// Macros

#define UBBR_VALUE(baud)    (( (F_CPU) / 16 + (baud) / 2) / (baud) - 1)

#define UART_OPEN_IMPL(uart, baud)                                              \
template<>                                                                      \
template<>                                                                      \
inline void Uart<uart>::open<baud>()                                            \
{                                                                               \
    /* Compute baud rate */                                                     \
    UBRR##uart##H = UBBR_VALUE(baud) >> 8;                                      \
    UBRR##uart##L = UBBR_VALUE(baud) & 0xFF;                                    \
                                                                                \
    UCSR##uart##A   = 0x00;                                                     \
    UCSR##uart##B   = (1 << RXEN##uart)    /* Enable RX */                      \
                    | (1 << TXEN##uart)    /* Enable TX */                      \
                    | (1 << RXCIE##uart);  /* Enable RX Interrupt */            \
    /* TX Interrupt will be enabled when data needs sending. */                 \
                                                                                \
    /* Defaults to 8-bit, no parity, 1 stop bit */                              \
    UCSR##uart##C   = (1 << UCSZ##uart##1) | (1 << UCSZ##uart##0);              \
}

#define UART_IMPLEMENT_OPEN(uart)                                               \
    UART_OPEN_IMPL(uart, 4800)                                                  \
    UART_OPEN_IMPL(uart, 9600)                                                  \
    UART_OPEN_IMPL(uart, 14400)                                                 \
    UART_OPEN_IMPL(uart, 19200)                                                 \
    UART_OPEN_IMPL(uart, 28800)                                                 \
    UART_OPEN_IMPL(uart, 31250)                                                 \
    UART_OPEN_IMPL(uart, 38400)                                                 \
    UART_OPEN_IMPL(uart, 57600)                                                 \
    UART_OPEN_IMPL(uart, 76800)                                                 \
    UART_OPEN_IMPL(uart, 115200)                                                \
    UART_OPEN_IMPL(uart, 230400)                                                \
    UART_OPEN_IMPL(uart, 250000)                                                \
    UART_OPEN_IMPL(uart, 500000)                                                \
    UART_OPEN_IMPL(uart, 1000000)

#define UART_ENABLE_TX_INT(uart)    UCSR##uart##B |=  (1 << UDRIE##uart)
#define UART_DISABLE_TX_INT(uart)   UCSR##uart##B &= ~(1 << UDRIE##uart)

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

template<byte UartNumber>
inline Uart<UartNumber>::Uart()
{
}

template<byte UartNumber>
inline Uart<UartNumber>::~Uart()
{
}

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

#ifdef UART0
UART_IMPLEMENT_OPEN(0);
#endif

#ifdef UART1
UART_IMPLEMENT_OPEN(1);
#endif

#ifdef UART2
UART_IMPLEMENT_OPEN(2);
#endif

#ifdef UART3
UART_IMPLEMENT_OPEN(3);
#endif

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

#ifdef UART0
template<>
inline void Uart<0>::close()
{
    UCSR0B = 0x00;
}
#endif

#ifdef UART1
template<>
inline void Uart<1>::close()
{
    UCSR1B = 0x00;
}
#endif

#ifdef UART2
template<>
inline void Uart<2>::close()
{
    UCSR2B = 0x00;
}
#endif

#ifdef UART3
template<>
inline void Uart<3>::close()
{
    UCSR3B = 0x00;
}
#endif

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

template<byte UartNumber>
inline bool Uart<UartNumber>::available() const
{
    return !(mRxBuffer.empty());
}

template<byte UartNumber>
inline byte Uart<UartNumber>::read()
{
    if (!mRxBuffer.empty())
        return mRxBuffer.pop();
    return 0xFF;
}

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

#ifdef UART0
template<>
inline void Uart<0>::write(byte inData)
{
    UART_DISABLE_TX_INT(0);
    mTxBuffer.push(inData);
    UART_ENABLE_TX_INT(0);
}
#endif

#ifdef UART1
template<>
inline void Uart<1>::write(byte inData)
{
    UART_DISABLE_TX_INT(1);
    mTxBuffer.push(inData);
    UART_ENABLE_TX_INT(1);
}
#endif

#ifdef UART2
template<>
inline void Uart<2>::write(byte inData)
{
    UART_DISABLE_TX_INT(2);
    mTxBuffer.push(inData);
    UART_ENABLE_TX_INT(2);
}
#endif

#ifdef UART3
template<>
inline void Uart<3>::write(byte inData)
{
    UART_DISABLE_TX_INT(3);
    mTxBuffer.push(inData);
    UART_ENABLE_TX_INT(3);
}
#endif

template<byte UartNumber>
inline void Uart<UartNumber>::write(const byte* inData,
                                    unsigned inSize)
{
    for (unsigned i = 0; i < inSize; ++i)
    {
        write(inData[i]);
    }
}

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

#ifdef UART0
template<>
inline void Uart<0>::busyWrite(byte inData)
{
    UDR0 = inData;
    while (!(UCSR0A & (1 << UDRE0)));
}
#endif

#ifdef UART1
template<>
inline void Uart<1>::busyWrite(byte inData)
{
    UDR1 = inData;
    while (!(UCSR1A & (1 << UDRE1)));
}
#endif

#ifdef UART2
template<>
inline void Uart<2>::busyWrite(byte inData)
{
    UDR2 = inData;
    while (!(UCSR2A & (1 << UDRE2)));
}
#endif

#ifdef UART3
template<>
inline void Uart<3>::busyWrite(byte inData)
{
    UDR3 = inData;
    while (!(UCSR3A & (1 << UDRE3)));
}
#endif

/*! \brief Write data and wait until end of transmission.

 Unlike write, this method will wait for each byte to be transmitted to send
 the next one. It does not use the TX buffer, allowing large amounts of data
 to be sent without the need of a big TX buffer size.
 */
template<byte UartNumber>
inline void Uart<UartNumber>::busyWrite(const byte* inData,
                                        unsigned inSize)
{
    for (unsigned i = 0; i < inSize; ++i)
    {
        busyWrite(inData[i]);
    }
}

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

template<byte UartNumber>
inline void Uart<UartNumber>::clearRxBuffer()
{
    mRxBuffer.clear();
}

template<byte UartNumber>
inline void Uart<UartNumber>::clearTxBuffer()
{
    mTxBuffer.clear();
}

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

template<byte UartNumber>
inline void Uart<UartNumber>::handleByteReceived(byte inData)
{
    mRxBuffer.push(inData);
}

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

#ifdef UART0
template<>
inline void Uart<0>::handleTxReady()
{
    if (!mTxBuffer.empty())
    {
        UDR0 = mTxBuffer.pop();
    }
    else
    {
        // No more data to be sent, disable TX interrupt.
        UART_DISABLE_TX_INT(0);
    }
}
#endif

#ifdef UART1
template<>
inline void Uart<1>::handleTxReady()
{
    if (!mTxBuffer.empty())
    {
        UDR1 = mTxBuffer.pop();
    }
    else
    {
        // No more data to be sent, disable TX interrupt.
        UART_DISABLE_TX_INT(1);
    }
}
#endif

#ifdef UART2
template<>
inline void Uart<2>::handleTxReady()
{
    if (!mTxBuffer.empty())
    {
        UDR2 = mTxBuffer.pop();
    }
    else
    {
        // No more data to be sent, disable TX interrupt.
        UART_DISABLE_TX_INT(2);
    }
}
#endif

#ifdef UART3
template<>
inline void Uart<3>::handleTxReady()
{
    if (!mTxBuffer.empty())
    {
        UDR3 = mTxBuffer.pop();
    }
    else
    {
        // No more data to be sent, disable TX interrupt.
        UART_DISABLE_TX_INT(3);
    }
}
#endif

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

#undef UART_OPEN_IMPL
#undef UART_IMPLEMENT_OPEN
#undef UBBR_VALUE
#undef UART_ENABLE_TX_INT
#undef UART_DISABLE_TX_INT

END_AK47_NAMESPACE
<commit_msg>Some UARTs need interrupts to be off when initializing.<commit_after>/*!
 *  \file       ak47_HardwareSerial.hpp
 *  \author     Francois Best
 *  \date       16/06/2012
 *  \license    GPL v3.0 - Copyright Forty Seven Effects 2012
 *
 *	This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details: http://www.gnu.org/licenses
 */

#pragma once

BEGIN_AK47_NAMESPACE

// -----------------------------------------------------------------------------
// Macros

#define UBBR_VALUE(baud)    (( (F_CPU) / 16 + (baud) / 2) / (baud) - 1)

#define UART_OPEN_IMPL(uart, baud)                                              \
template<>                                                                      \
template<>                                                                      \
inline void Uart<uart>::open<baud>()                                            \
{                                                                               \
    cli();                                                                      \
    /* Compute baud rate */                                                     \
    UBRR##uart##H = UBBR_VALUE(baud) >> 8;                                      \
    UBRR##uart##L = UBBR_VALUE(baud) & 0xFF;                                    \
                                                                                \
    UCSR##uart##A   = 0x00;                                                     \
    UCSR##uart##B   = (1 << RXEN##uart)    /* Enable RX */                      \
                    | (1 << TXEN##uart)    /* Enable TX */                      \
                    | (1 << RXCIE##uart);  /* Enable RX Interrupt */            \
    /* TX Interrupt will be enabled when data needs sending. */                 \
                                                                                \
    /* Defaults to 8-bit, no parity, 1 stop bit */                              \
    UCSR##uart##C   = (1 << UCSZ##uart##1) | (1 << UCSZ##uart##0);              \
    sei();                                                                      \
}

#define UART_IMPLEMENT_OPEN(uart)                                               \
    UART_OPEN_IMPL(uart, 4800)                                                  \
    UART_OPEN_IMPL(uart, 9600)                                                  \
    UART_OPEN_IMPL(uart, 14400)                                                 \
    UART_OPEN_IMPL(uart, 19200)                                                 \
    UART_OPEN_IMPL(uart, 28800)                                                 \
    UART_OPEN_IMPL(uart, 31250)                                                 \
    UART_OPEN_IMPL(uart, 38400)                                                 \
    UART_OPEN_IMPL(uart, 57600)                                                 \
    UART_OPEN_IMPL(uart, 76800)                                                 \
    UART_OPEN_IMPL(uart, 115200)                                                \
    UART_OPEN_IMPL(uart, 230400)                                                \
    UART_OPEN_IMPL(uart, 250000)                                                \
    UART_OPEN_IMPL(uart, 500000)                                                \
    UART_OPEN_IMPL(uart, 1000000)

#define UART_ENABLE_TX_INT(uart)    UCSR##uart##B |=  (1 << UDRIE##uart)
#define UART_DISABLE_TX_INT(uart)   UCSR##uart##B &= ~(1 << UDRIE##uart)

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

template<byte UartNumber>
inline Uart<UartNumber>::Uart()
{
}

template<byte UartNumber>
inline Uart<UartNumber>::~Uart()
{
}

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

#ifdef UART0
UART_IMPLEMENT_OPEN(0);
#endif

#ifdef UART1
UART_IMPLEMENT_OPEN(1);
#endif

#ifdef UART2
UART_IMPLEMENT_OPEN(2);
#endif

#ifdef UART3
UART_IMPLEMENT_OPEN(3);
#endif

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

#ifdef UART0
template<>
inline void Uart<0>::close()
{
    UCSR0B = 0x00;
}
#endif

#ifdef UART1
template<>
inline void Uart<1>::close()
{
    UCSR1B = 0x00;
}
#endif

#ifdef UART2
template<>
inline void Uart<2>::close()
{
    UCSR2B = 0x00;
}
#endif

#ifdef UART3
template<>
inline void Uart<3>::close()
{
    UCSR3B = 0x00;
}
#endif

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

template<byte UartNumber>
inline bool Uart<UartNumber>::available() const
{
    return !(mRxBuffer.empty());
}

template<byte UartNumber>
inline byte Uart<UartNumber>::read()
{
    if (!mRxBuffer.empty())
        return mRxBuffer.pop();
    return 0xFF;
}

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

#ifdef UART0
template<>
inline void Uart<0>::write(byte inData)
{
    UART_DISABLE_TX_INT(0);
    mTxBuffer.push(inData);
    UART_ENABLE_TX_INT(0);
}
#endif

#ifdef UART1
template<>
inline void Uart<1>::write(byte inData)
{
    UART_DISABLE_TX_INT(1);
    mTxBuffer.push(inData);
    UART_ENABLE_TX_INT(1);
}
#endif

#ifdef UART2
template<>
inline void Uart<2>::write(byte inData)
{
    UART_DISABLE_TX_INT(2);
    mTxBuffer.push(inData);
    UART_ENABLE_TX_INT(2);
}
#endif

#ifdef UART3
template<>
inline void Uart<3>::write(byte inData)
{
    UART_DISABLE_TX_INT(3);
    mTxBuffer.push(inData);
    UART_ENABLE_TX_INT(3);
}
#endif

template<byte UartNumber>
inline void Uart<UartNumber>::write(const byte* inData,
                                    unsigned inSize)
{
    for (unsigned i = 0; i < inSize; ++i)
    {
        write(inData[i]);
    }
}

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

#ifdef UART0
template<>
inline void Uart<0>::busyWrite(byte inData)
{
    UDR0 = inData;
    while (!(UCSR0A & (1 << UDRE0)));
}
#endif

#ifdef UART1
template<>
inline void Uart<1>::busyWrite(byte inData)
{
    UDR1 = inData;
    while (!(UCSR1A & (1 << UDRE1)));
}
#endif

#ifdef UART2
template<>
inline void Uart<2>::busyWrite(byte inData)
{
    UDR2 = inData;
    while (!(UCSR2A & (1 << UDRE2)));
}
#endif

#ifdef UART3
template<>
inline void Uart<3>::busyWrite(byte inData)
{
    UDR3 = inData;
    while (!(UCSR3A & (1 << UDRE3)));
}
#endif

/*! \brief Write data and wait until end of transmission.

 Unlike write, this method will wait for each byte to be transmitted to send
 the next one. It does not use the TX buffer, allowing large amounts of data
 to be sent without the need of a big TX buffer size.
 */
template<byte UartNumber>
inline void Uart<UartNumber>::busyWrite(const byte* inData,
                                        unsigned inSize)
{
    for (unsigned i = 0; i < inSize; ++i)
    {
        busyWrite(inData[i]);
    }
}

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

template<byte UartNumber>
inline void Uart<UartNumber>::clearRxBuffer()
{
    mRxBuffer.clear();
}

template<byte UartNumber>
inline void Uart<UartNumber>::clearTxBuffer()
{
    mTxBuffer.clear();
}

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

template<byte UartNumber>
inline void Uart<UartNumber>::handleByteReceived(byte inData)
{
    mRxBuffer.push(inData);
}

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

#ifdef UART0
template<>
inline void Uart<0>::handleTxReady()
{
    if (!mTxBuffer.empty())
    {
        UDR0 = mTxBuffer.pop();
    }
    else
    {
        // No more data to be sent, disable TX interrupt.
        UART_DISABLE_TX_INT(0);
    }
}
#endif

#ifdef UART1
template<>
inline void Uart<1>::handleTxReady()
{
    if (!mTxBuffer.empty())
    {
        UDR1 = mTxBuffer.pop();
    }
    else
    {
        // No more data to be sent, disable TX interrupt.
        UART_DISABLE_TX_INT(1);
    }
}
#endif

#ifdef UART2
template<>
inline void Uart<2>::handleTxReady()
{
    if (!mTxBuffer.empty())
    {
        UDR2 = mTxBuffer.pop();
    }
    else
    {
        // No more data to be sent, disable TX interrupt.
        UART_DISABLE_TX_INT(2);
    }
}
#endif

#ifdef UART3
template<>
inline void Uart<3>::handleTxReady()
{
    if (!mTxBuffer.empty())
    {
        UDR3 = mTxBuffer.pop();
    }
    else
    {
        // No more data to be sent, disable TX interrupt.
        UART_DISABLE_TX_INT(3);
    }
}
#endif

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

#undef UART_OPEN_IMPL
#undef UART_IMPLEMENT_OPEN
#undef UBBR_VALUE
#undef UART_ENABLE_TX_INT
#undef UART_DISABLE_TX_INT

END_AK47_NAMESPACE
<|endoftext|>