<commit_before>/****************************************************************************
 *   Copyright (C) 2017-2018 Savoir-faire Linux                             *
 *   Author : Nicolas Jäger <nicolas.jager@savoirfairelinux.com>            *
 *   Author : Sébastien Blin <sebastien.blin@savoirfairelinux.com>          *
 *                                                                          *
 *   This library is free software; you can redistribute it and/or          *
 *   modify it under the terms of the GNU Lesser General Public             *
 *   License as published by the Free Software Foundation; either           *
 *   version 2.1 of the License, or (at your option) any later version.     *
 *                                                                          *
 *   This library is distributed in the hope that it will be useful,        *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of         *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU      *
 *   Lesser General Public License for more details.                        *
 *                                                                          *
 *   You should have received a copy of the GNU General Public License      *
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.  *
 ***************************************************************************/
#include "api/lrc.h"

// Models and database
#include "api/newaccountmodel.h"
#include "api/avmodel.h"
#include "api/datatransfermodel.h"
#include "api/behaviorcontroller.h"
#include "database.h"
#include "callbackshandler.h"
#include "dbus/configurationmanager.h"
#include "dbus/instancemanager.h"
#include "dbus/configurationmanager.h"

namespace lrc
{

using namespace api;

class LrcPimpl
{

public:
    LrcPimpl(Lrc& linked);

    const Lrc& linked;
    std::unique_ptr<BehaviorController> behaviorController;
    std::unique_ptr<CallbacksHandler> callbackHandler;
    std::unique_ptr<Database> database;
    std::unique_ptr<NewAccountModel> accountModel;
    std::unique_ptr<DataTransferModel> dataTransferModel;
    std::unique_ptr<AVModel> AVModel_;
};

Lrc::Lrc()
{
    // Ensure Daemon is running/loaded (especially on non-DBus platforms)
    // before instantiating LRC and its members
    InstanceManager::instance();
    lrcPimpl_ = std::make_unique<LrcPimpl>(*this);
}

Lrc::~Lrc()
{
}

const NewAccountModel&
Lrc::getAccountModel() const
{
    return *lrcPimpl_->accountModel;
}

BehaviorController&
Lrc::getBehaviorController() const
{
    return *lrcPimpl_->behaviorController;
}

DataTransferModel&
Lrc::getDataTransferModel() const
{
    return *lrcPimpl_->dataTransferModel;
}

AVModel&
Lrc::getAVModel() const
{
    return *lrcPimpl_->AVModel_;
}

void
Lrc::connectivityChanged() const
{
    ConfigurationManager::instance().connectivityChanged();
}

bool
Lrc::isConnected()
{
#ifdef ENABLE_LIBWRAP
    return true;
#else
    return ConfigurationManager::instance().connection().isConnected();
#endif
}

bool
Lrc::dbusIsValid()
{
#ifdef ENABLE_LIBWRAP
    return true;
#else
    return ConfigurationManager::instance().isValid();
#endif
}

LrcPimpl::LrcPimpl(Lrc& linked)
: linked(linked)
, behaviorController(std::make_unique<BehaviorController>())
, callbackHandler(std::make_unique<CallbacksHandler>(linked))
, database(std::make_unique<Database>())
, accountModel(std::make_unique<NewAccountModel>(linked, *database, *callbackHandler, *behaviorController))
, dataTransferModel {std::make_unique<DataTransferModel>()}
, AVModel_ {std::make_unique<AVModel>(*callbackHandler)}
{
}

} // namespace lrc
<commit_msg>lrc: disconnect form dbus when closing<commit_after>/****************************************************************************
 *   Copyright (C) 2017-2018 Savoir-faire Linux                             *
 *   Author : Nicolas Jäger <nicolas.jager@savoirfairelinux.com>            *
 *   Author : Sébastien Blin <sebastien.blin@savoirfairelinux.com>          *
 *                                                                          *
 *   This library is free software; you can redistribute it and/or          *
 *   modify it under the terms of the GNU Lesser General Public             *
 *   License as published by the Free Software Foundation; either           *
 *   version 2.1 of the License, or (at your option) any later version.     *
 *                                                                          *
 *   This library is distributed in the hope that it will be useful,        *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of         *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU      *
 *   Lesser General Public License for more details.                        *
 *                                                                          *
 *   You should have received a copy of the GNU General Public License      *
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.  *
 ***************************************************************************/
#include "api/lrc.h"

#ifndef _MSC_VER
#include <unistd.h>
#else
#include "../../daemon/MSVC/unistd.h"
#endif // !_MSC_VER

// Models and database
#include "api/newaccountmodel.h"
#include "api/avmodel.h"
#include "api/datatransfermodel.h"
#include "api/behaviorcontroller.h"
#include "database.h"
#include "callbackshandler.h"
#include "dbus/configurationmanager.h"
#include "dbus/instancemanager.h"
#include "dbus/configurationmanager.h"

namespace lrc
{

using namespace api;

class LrcPimpl
{

public:
    LrcPimpl(Lrc& linked);

    const Lrc& linked;
    std::unique_ptr<BehaviorController> behaviorController;
    std::unique_ptr<CallbacksHandler> callbackHandler;
    std::unique_ptr<Database> database;
    std::unique_ptr<NewAccountModel> accountModel;
    std::unique_ptr<DataTransferModel> dataTransferModel;
    std::unique_ptr<AVModel> AVModel_;
};

Lrc::Lrc()
{
    // Ensure Daemon is running/loaded (especially on non-DBus platforms)
    // before instantiating LRC and its members
    InstanceManager::instance();
    lrcPimpl_ = std::make_unique<LrcPimpl>(*this);
}

Lrc::~Lrc()
{
    //Unregister from the daemon
    InstanceManagerInterface& instance = InstanceManager::instance();
    Q_NOREPLY instance.Unregister(getpid());
#ifndef ENABLE_LIBWRAP
    instance.connection().disconnectFromBus(instance.connection().baseService());
#endif //ENABLE_LIBWRAP
}

const NewAccountModel&
Lrc::getAccountModel() const
{
    return *lrcPimpl_->accountModel;
}

BehaviorController&
Lrc::getBehaviorController() const
{
    return *lrcPimpl_->behaviorController;
}

DataTransferModel&
Lrc::getDataTransferModel() const
{
    return *lrcPimpl_->dataTransferModel;
}

AVModel&
Lrc::getAVModel() const
{
    return *lrcPimpl_->AVModel_;
}

void
Lrc::connectivityChanged() const
{
    ConfigurationManager::instance().connectivityChanged();
}

bool
Lrc::isConnected()
{
#ifdef ENABLE_LIBWRAP
    return true;
#else
    return ConfigurationManager::instance().connection().isConnected();
#endif
}

bool
Lrc::dbusIsValid()
{
#ifdef ENABLE_LIBWRAP
    return true;
#else
    return ConfigurationManager::instance().isValid();
#endif
}

LrcPimpl::LrcPimpl(Lrc& linked)
: linked(linked)
, behaviorController(std::make_unique<BehaviorController>())
, callbackHandler(std::make_unique<CallbacksHandler>(linked))
, database(std::make_unique<Database>())
, accountModel(std::make_unique<NewAccountModel>(linked, *database, *callbackHandler, *behaviorController))
, dataTransferModel {std::make_unique<DataTransferModel>()}
, AVModel_ {std::make_unique<AVModel>(*callbackHandler)}
{
}

} // namespace lrc
<|endoftext|>


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

#ifndef _FLBYTES_HXX
#define _FLBYTES_HXX

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif

//============================================================================
class SvFillLockBytes : public SvLockBytes
{
    SvLockBytesRef xLockBytes;
    ULONG nFilledSize;
    BOOL bTerminated;
    BOOL bSync;
public:
    TYPEINFO();

    SvFillLockBytes( SvLockBytes* pLockBytes );
    virtual ErrCode ReadAt(
        ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pRead ) const;
    virtual ErrCode WriteAt(
        ULONG nPos, const void* pBuffer, ULONG nCount, ULONG* pWritten );
    virtual ErrCode Flush() const;
    virtual ErrCode SetSize( ULONG nSize );
    virtual ErrCode LockRegion( ULONG nPos, ULONG nCount, LockType );
    virtual ErrCode UnlockRegion( ULONG nPos, ULONG nCount, LockType );
    virtual ErrCode Stat( SvLockBytesStat*, SvLockBytesStatFlag ) const;
    ErrCode FillAppend( const void* pBuffer, ULONG nCount, ULONG *pWritten );
    ULONG   Tell() const { return nFilledSize; }
    void    Seek( ULONG nPos ) { nFilledSize = nPos; }

    void Terminate();
};

SV_DECL_IMPL_REF( SvFillLockBytes )

//============================================================================
class SvSyncLockBytes: public SvOpenLockBytes
{
    SvAsyncLockBytesRef m_xAsyncLockBytes;

public:
    TYPEINFO();

    /// Create a synchronous wrapper around existing asynchronous lock bytes.
    ///
    /// @param pTheAsyncLockBytes  Must not be null.
    inline SvSyncLockBytes(SvAsyncLockBytes * pTheAsyncLockBytes);

    /// Create a synchronous wrapper around an existing stream.
    ///
    /// @descr  This is like first creating asynchronous lock bytes around the
    /// stream and than creating a synchronous wrapper around the asynchronous
    /// lock bytes.
    ///
    /// @param pStream  Must not be null.
    ///
    /// @param bOwner  True if these lock bytes own the stream (delete it on
    /// destruction).
    SvSyncLockBytes(SvStream * pStream, BOOL bOwner):
        m_xAsyncLockBytes(new SvAsyncLockBytes(pStream, bOwner)) {}

    virtual const SvStream * GetStream() const
    { return m_xAsyncLockBytes->GetStream(); }

    virtual void SetSynchronMode(BOOL bSync = TRUE)
    { m_xAsyncLockBytes->SetSynchronMode(bSync); }

    virtual BOOL IsSynchronMode() const
    { return m_xAsyncLockBytes->IsSynchronMode(); }

    virtual ErrCode ReadAt(ULONG nPos, void * pBuffer, ULONG nCount,
                           ULONG * pRead) const;

    virtual ErrCode WriteAt(ULONG nPos, const void * pBuffer, ULONG nCount,
                            ULONG * pWritten);

    virtual ErrCode Flush() const { return m_xAsyncLockBytes->Flush(); }

    virtual ErrCode SetSize(ULONG nSize)
    { return m_xAsyncLockBytes->SetSize(nSize); }

    virtual ErrCode LockRegion(ULONG nPos, ULONG nCount, LockType eType)
    { return m_xAsyncLockBytes->LockRegion(nPos, nCount, eType); }

    virtual ErrCode UnlockRegion(ULONG nPos, ULONG nCount, LockType eType)
    { return m_xAsyncLockBytes->UnlockRegion(nPos, nCount, eType); }

    virtual ErrCode Stat(SvLockBytesStat * pStat, SvLockBytesStatFlag eFlag)
        const
    { return m_xAsyncLockBytes->Stat(pStat, eFlag); }

    virtual ErrCode FillAppend(const void * pBuffer, ULONG nCount,
                               ULONG * pWritten)
    { return m_xAsyncLockBytes->FillAppend(pBuffer, nCount, pWritten); }

    virtual ULONG Tell() const { return m_xAsyncLockBytes->Tell(); }

    virtual ULONG Seek(ULONG nPos)
    { return m_xAsyncLockBytes->Seek(nPos); }

    virtual void Terminate() { m_xAsyncLockBytes->Terminate(); }
};

inline SvSyncLockBytes::SvSyncLockBytes(SvAsyncLockBytes *
                                         pTheAsyncLockBytes):
    m_xAsyncLockBytes(pTheAsyncLockBytes)
{
    DBG_ASSERT(m_xAsyncLockBytes.Is(),
               "SvSyncLockBytes::SvSyncLockBytes(): Null");
}

SV_DECL_IMPL_REF(SvSyncLockBytes);

//============================================================================
struct SvCompositeLockBytes_Impl;
class SvCompositeLockBytes : public SvLockBytes
{
    SvCompositeLockBytes_Impl* pImpl;
public:
    TYPEINFO();

    SvCompositeLockBytes( );
    ~SvCompositeLockBytes();

    void Append( SvLockBytes* pLockBytes, ULONG nPos, ULONG nOffset );
    ULONG RelativeOffset( ULONG nPos ) const;
    void  SetIsPending( BOOL bSet );
    SvLockBytes*    GetLastLockBytes() const;

    virtual ErrCode ReadAt(
        ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pRead ) const;
    virtual ErrCode WriteAt(
        ULONG nPos, const void* pBuffer, ULONG nCount, ULONG* pWritten );
    virtual ErrCode Flush() const;
    virtual ErrCode SetSize( ULONG nSize );
    virtual ErrCode LockRegion( ULONG nPos, ULONG nCount, LockType );
    virtual ErrCode UnlockRegion( ULONG nPos, ULONG nCount, LockType );
    virtual ErrCode Stat( SvLockBytesStat*, SvLockBytesStatFlag ) const;
};

SV_DECL_IMPL_REF( SvCompositeLockBytes )

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

#ifndef _FLBYTES_HXX
#define _FLBYTES_HXX

#include <tools/debug.hxx>
#include <tools/stream.hxx>

//============================================================================
class SvFillLockBytes : public SvLockBytes
{
    SvLockBytesRef xLockBytes;
    ULONG nFilledSize;
    BOOL bTerminated;
    BOOL bSync;
public:
    TYPEINFO();

    SvFillLockBytes( SvLockBytes* pLockBytes );
    virtual ErrCode ReadAt(
        ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pRead ) const;
    virtual ErrCode WriteAt(
        ULONG nPos, const void* pBuffer, ULONG nCount, ULONG* pWritten );
    virtual ErrCode Flush() const;
    virtual ErrCode SetSize( ULONG nSize );
    virtual ErrCode LockRegion( ULONG nPos, ULONG nCount, LockType );
    virtual ErrCode UnlockRegion( ULONG nPos, ULONG nCount, LockType );
    virtual ErrCode Stat( SvLockBytesStat*, SvLockBytesStatFlag ) const;
    ErrCode FillAppend( const void* pBuffer, ULONG nCount, ULONG *pWritten );
    ULONG   Tell() const { return nFilledSize; }
    void    Seek( ULONG nPos ) { nFilledSize = nPos; }

    void Terminate();
};

SV_DECL_IMPL_REF( SvFillLockBytes )

//============================================================================
class SvSyncLockBytes: public SvOpenLockBytes
{
    SvAsyncLockBytesRef m_xAsyncLockBytes;

public:
    TYPEINFO();

    /// Create a synchronous wrapper around existing asynchronous lock bytes.
    ///
    /// @param pTheAsyncLockBytes  Must not be null.
    inline SvSyncLockBytes(SvAsyncLockBytes * pTheAsyncLockBytes);

    /// Create a synchronous wrapper around an existing stream.
    ///
    /// @descr  This is like first creating asynchronous lock bytes around the
    /// stream and than creating a synchronous wrapper around the asynchronous
    /// lock bytes.
    ///
    /// @param pStream  Must not be null.
    ///
    /// @param bOwner  True if these lock bytes own the stream (delete it on
    /// destruction).
    SvSyncLockBytes(SvStream * pStream, BOOL bOwner):
        m_xAsyncLockBytes(new SvAsyncLockBytes(pStream, bOwner)) {}

    virtual const SvStream * GetStream() const
    { return m_xAsyncLockBytes->GetStream(); }

    virtual void SetSynchronMode(BOOL bSync = TRUE)
    { m_xAsyncLockBytes->SetSynchronMode(bSync); }

    virtual BOOL IsSynchronMode() const
    { return m_xAsyncLockBytes->IsSynchronMode(); }

    virtual ErrCode ReadAt(ULONG nPos, void * pBuffer, ULONG nCount,
                           ULONG * pRead) const;

    virtual ErrCode WriteAt(ULONG nPos, const void * pBuffer, ULONG nCount,
                            ULONG * pWritten);

    virtual ErrCode Flush() const { return m_xAsyncLockBytes->Flush(); }

    virtual ErrCode SetSize(ULONG nSize)
    { return m_xAsyncLockBytes->SetSize(nSize); }

    virtual ErrCode LockRegion(ULONG nPos, ULONG nCount, LockType eType)
    { return m_xAsyncLockBytes->LockRegion(nPos, nCount, eType); }

    virtual ErrCode UnlockRegion(ULONG nPos, ULONG nCount, LockType eType)
    { return m_xAsyncLockBytes->UnlockRegion(nPos, nCount, eType); }

    virtual ErrCode Stat(SvLockBytesStat * pStat, SvLockBytesStatFlag eFlag)
        const
    { return m_xAsyncLockBytes->Stat(pStat, eFlag); }

    virtual ErrCode FillAppend(const void * pBuffer, ULONG nCount,
                               ULONG * pWritten)
    { return m_xAsyncLockBytes->FillAppend(pBuffer, nCount, pWritten); }

    virtual ULONG Tell() const { return m_xAsyncLockBytes->Tell(); }

    virtual ULONG Seek(ULONG nPos)
    { return m_xAsyncLockBytes->Seek(nPos); }

    virtual void Terminate() { m_xAsyncLockBytes->Terminate(); }
};

inline SvSyncLockBytes::SvSyncLockBytes(SvAsyncLockBytes *
                                         pTheAsyncLockBytes):
    m_xAsyncLockBytes(pTheAsyncLockBytes)
{
    DBG_ASSERT(m_xAsyncLockBytes.Is(),
               "SvSyncLockBytes::SvSyncLockBytes(): Null");
}

SV_DECL_IMPL_REF(SvSyncLockBytes);

//============================================================================
struct SvCompositeLockBytes_Impl;
class SvCompositeLockBytes : public SvLockBytes
{
    SvCompositeLockBytes_Impl* pImpl;
public:
    TYPEINFO();

    SvCompositeLockBytes( );
    ~SvCompositeLockBytes();

    void Append( SvLockBytes* pLockBytes, ULONG nPos, ULONG nOffset );
    ULONG RelativeOffset( ULONG nPos ) const;
    void  SetIsPending( BOOL bSet );
    SvLockBytes*    GetLastLockBytes() const;

    virtual ErrCode ReadAt(
        ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pRead ) const;
    virtual ErrCode WriteAt(
        ULONG nPos, const void* pBuffer, ULONG nCount, ULONG* pWritten );
    virtual ErrCode Flush() const;
    virtual ErrCode SetSize( ULONG nSize );
    virtual ErrCode LockRegion( ULONG nPos, ULONG nCount, LockType );
    virtual ErrCode UnlockRegion( ULONG nPos, ULONG nCount, LockType );
    virtual ErrCode Stat( SvLockBytesStat*, SvLockBytesStatFlag ) const;
};

SV_DECL_IMPL_REF( SvCompositeLockBytes )

#endif
<|endoftext|>


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

// include ---------------------------------------------------------------

#ifndef _SVX_SIMPTABL_HXX
#include "simptabl.hxx"
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

namespace svx {

// class SvxRadioButtonListBox -------------------------------------------

class SVX_DLLPUBLIC SvxRadioButtonListBox : public SvxSimpleTable
{
private:
    Point               m_aCurMousePoint;

protected:
    virtual void        SetTabs();
    virtual void        MouseButtonUp( const MouseEvent& _rMEvt );
    virtual void        KeyInput( const KeyEvent& rKEvt );

public:
    SvxRadioButtonListBox( Window* _pParent, const ResId& _rId );
    ~SvxRadioButtonListBox();

    void                HandleEntryChecked( SvLBoxEntry* _pEntry );

    const Point&        GetCurMousePoint() const;
};

} // end of namespace ::svx

#endif // #ifndef _SVX_RADIOBTNBOX_HXX

<commit_msg>INTEGRATION: CWS sb59 (1.2.14); FILE MERGED 2006/08/03 13:47:05 cl 1.2.14.1: removed compiler warnings<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: radiobtnbox.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 11:48:06 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SVX_RADIOBTNBOX_HXX
#define _SVX_RADIOBTNBOX_HXX

// include ---------------------------------------------------------------

#ifndef _SVX_SIMPTABL_HXX
#include "simptabl.hxx"
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

namespace svx {

// class SvxRadioButtonListBox -------------------------------------------

class SVX_DLLPUBLIC SvxRadioButtonListBox : public SvxSimpleTable
{
    using SvxSimpleTable::SetTabs;

private:
    Point               m_aCurMousePoint;

protected:
    virtual void        SetTabs();
    virtual void        MouseButtonUp( const MouseEvent& _rMEvt );
    virtual void        KeyInput( const KeyEvent& rKEvt );

public:
    SvxRadioButtonListBox( Window* _pParent, const ResId& _rId );
    ~SvxRadioButtonListBox();

    void                HandleEntryChecked( SvLBoxEntry* _pEntry );

    const Point&        GetCurMousePoint() const;
};

} // end of namespace ::svx

#endif // #ifndef _SVX_RADIOBTNBOX_HXX

<|endoftext|>


<commit_before>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include "libtorrent/lsd.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include "libtorrent/buffer.hpp"
#include "libtorrent/http_parser.hpp"

#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <asio/ip/host_name.hpp>
#include <asio/ip/multicast.hpp>
#include <boost/thread/mutex.hpp>
#include <cstdlib>
#include <boost/config.hpp>

using boost::bind;
using namespace libtorrent;

namespace libtorrent
{
	// defined in broadcast_socket.cpp
	address guess_local_address(asio::io_service&);
}

lsd::lsd(io_service& ios, address const& listen_interface
	, peer_callback_t const& cb)
	: m_callback(cb)
	, m_retry_count(0)
	, m_socket(ios, udp::endpoint(address_v4::from_string("239.192.152.143"), 6771)
		, bind(&lsd::on_announce, self(), _1, _2, _3))
	, m_broadcast_timer(ios)
	, m_disabled(false)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc);
#endif
}

lsd::~lsd() {}

void lsd::announce(sha1_hash const& ih, int listen_port)
{
	if (m_disabled) return;

	std::stringstream btsearch;
	btsearch << "BT-SEARCH * HTTP/1.1\r\n"
		"Host: 239.192.152.143:6771\r\n"
		"Port: " << listen_port << "\r\n"
		"Infohash: " << ih << "\r\n"
		"\r\n\r\n";
	std::string const& msg = btsearch.str();

	m_retry_count = 0;
	asio::error_code ec;
	m_socket.send(msg.c_str(), int(msg.size()), ec);
	if (ec)
	{
		m_disabled = true;
		return;
	}

#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " ==> announce: ih: " << ih << " port: " << listen_port << std::endl;
#endif

	m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);
	m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));
}

void lsd::resend_announce(asio::error_code const& e, std::string msg)
{
	if (e) return;

	asio::error_code ec;
	m_socket.send(msg.c_str(), int(msg.size()), ec);

	++m_retry_count;
	if (m_retry_count >= 5)
		return;

	m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);
	m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));
}

void lsd::on_announce(udp::endpoint const& from, char* buffer
	, std::size_t bytes_transferred)
{
	using namespace libtorrent::detail;

	http_parser p;

	bool error = false;
	p.incoming(buffer::const_interval(buffer, buffer + bytes_transferred)
		, error);

	if (!p.header_finished() || error)
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " <== announce: incomplete HTTP message\n";
#endif
		return;
	}

	if (p.method() != "bt-search")
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " <== announce: invalid HTTP method: " << p.method() << std::endl;
#endif
		return;
	}

	std::string const& port_str = p.header("port");
	if (port_str.empty())
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " <== announce: invalid BT-SEARCH, missing port" << std::endl;
#endif
		return;
	}

	std::string const& ih_str = p.header("infohash");
	if (ih_str.empty())
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " <== announce: invalid BT-SEARCH, missing infohash" << std::endl;
#endif
		return;
	}

	sha1_hash ih(0);
	std::istringstream ih_sstr(ih_str);
	ih_sstr >> ih;
	int port = atoi(port_str.c_str());

	if (!ih.is_all_zeros() && port != 0)
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
		m_log << time_now_string()
			<< " *** incoming local announce " << from.address()
			<< ":" << port << " ih: " << ih << std::endl;
#endif
		// we got an announce, pass it on through the callback
#ifndef BOOST_NO_EXCEPTIONS
		try {
#endif
			m_callback(tcp::endpoint(from.address(), port), ih);
#ifndef BOOST_NO_EXCEPTIONS
		}
		catch (std::exception&) {}
#endif
	}
}

void lsd::close()
{
	m_socket.close();
	asio::error_code ec;
	m_broadcast_timer.cancel(ec);
	m_disabled = true;
	m_callback.clear();
}

<commit_msg>local service discovert resend fix<commit_after>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include "libtorrent/lsd.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include "libtorrent/buffer.hpp"
#include "libtorrent/http_parser.hpp"

#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <asio/ip/host_name.hpp>
#include <asio/ip/multicast.hpp>
#include <boost/thread/mutex.hpp>
#include <cstdlib>
#include <boost/config.hpp>

using boost::bind;
using namespace libtorrent;

namespace libtorrent
{
	// defined in broadcast_socket.cpp
	address guess_local_address(asio::io_service&);
}

lsd::lsd(io_service& ios, address const& listen_interface
	, peer_callback_t const& cb)
	: m_callback(cb)
	, m_retry_count(1)
	, m_socket(ios, udp::endpoint(address_v4::from_string("239.192.152.143"), 6771)
		, bind(&lsd::on_announce, self(), _1, _2, _3))
	, m_broadcast_timer(ios)
	, m_disabled(false)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc);
#endif
}

lsd::~lsd() {}

void lsd::announce(sha1_hash const& ih, int listen_port)
{
	if (m_disabled) return;

	std::stringstream btsearch;
	btsearch << "BT-SEARCH * HTTP/1.1\r\n"
		"Host: 239.192.152.143:6771\r\n"
		"Port: " << listen_port << "\r\n"
		"Infohash: " << ih << "\r\n"
		"\r\n\r\n";
	std::string const& msg = btsearch.str();

	m_retry_count = 1;
	asio::error_code ec;
	m_socket.send(msg.c_str(), int(msg.size()), ec);
	if (ec)
	{
		m_disabled = true;
		return;
	}

#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " ==> announce: ih: " << ih << " port: " << listen_port << std::endl;
#endif

	m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);
	m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));
}

void lsd::resend_announce(asio::error_code const& e, std::string msg)
{
	if (e) return;

	asio::error_code ec;
	m_socket.send(msg.c_str(), int(msg.size()), ec);

	++m_retry_count;
	if (m_retry_count >= 5)
		return;

	m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);
	m_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));
}

void lsd::on_announce(udp::endpoint const& from, char* buffer
	, std::size_t bytes_transferred)
{
	using namespace libtorrent::detail;

	http_parser p;

	bool error = false;
	p.incoming(buffer::const_interval(buffer, buffer + bytes_transferred)
		, error);

	if (!p.header_finished() || error)
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " <== announce: incomplete HTTP message\n";
#endif
		return;
	}

	if (p.method() != "bt-search")
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " <== announce: invalid HTTP method: " << p.method() << std::endl;
#endif
		return;
	}

	std::string const& port_str = p.header("port");
	if (port_str.empty())
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " <== announce: invalid BT-SEARCH, missing port" << std::endl;
#endif
		return;
	}

	std::string const& ih_str = p.header("infohash");
	if (ih_str.empty())
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
	m_log << time_now_string()
		<< " <== announce: invalid BT-SEARCH, missing infohash" << std::endl;
#endif
		return;
	}

	sha1_hash ih(0);
	std::istringstream ih_sstr(ih_str);
	ih_sstr >> ih;
	int port = atoi(port_str.c_str());

	if (!ih.is_all_zeros() && port != 0)
	{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
		m_log << time_now_string()
			<< " *** incoming local announce " << from.address()
			<< ":" << port << " ih: " << ih << std::endl;
#endif
		// we got an announce, pass it on through the callback
#ifndef BOOST_NO_EXCEPTIONS
		try {
#endif
			m_callback(tcp::endpoint(from.address(), port), ih);
#ifndef BOOST_NO_EXCEPTIONS
		}
		catch (std::exception&) {}
#endif
	}
}

void lsd::close()
{
	m_socket.close();
	asio::error_code ec;
	m_broadcast_timer.cancel(ec);
	m_disabled = true;
	m_callback.clear();
}

<|endoftext|>


<commit_before>
#include "ATEasySMS.h"

uint8_t ATEasySMS::initializeSMS()
{
    ////
    // set text mode
    strncpy_P(m_cmdBuffer, ATDEV_CMD_CMGF, ATDEV_BUFF_CMD_SIZE);

    if (this->sendATCmd() != ATDEV_OK) {
        return ATDEV_ERR_UNEXPECTED_RESULT;
    }

    ////
    // Set message storage
    strncpy_P(m_cmdBuffer, ATDEV_CMD_CPMS, ATDEV_BUFF_CMD_SIZE);

    if (this->sendATCmd() != ATDEV_OK) {
        return ATDEV_ERR_UNEXPECTED_RESULT;
    }

    // Ende
    return this->waitDevice(ATDEV_OK);
}

uint8_t ATEasySMS::sendSMS()
{
    snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CMGS, m_smsData.m_number);

    // Prepare answer
    m_endBuffer[0] = ATDEV_CH_AN;
    m_endBuffer[1] = 0x00;

    // Send command
    if (this->sendATCmd(true) == ATDEV_OK) {

        // Send SMS Data
        m_hwSerial->print(m_smsData.m_message);

        // generate SMS end
        m_cmdBuffer[0] = ATDEV_CH_END;

        // End of SMS
        m_timeOut = ATDEV_SMS_TIMEOUT_SEND;
        return this->sendATCmd();
    }

    return ATDEV_ERR_UNEXPECTED_RESULT;
}

uint8_t ATEasySMS::receiveSMS(uint16_t idx)
{
    snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CMGR, idx);

    // Prepare answer end
    memset(m_endBuffer, 0x00, ATDEV_BUFF_END_SIZE +1);
    strncpy_P(m_endBuffer, ATDEV_STR_CMGR, ATDEV_BUFF_END_SIZE);

    // Cleanup SMS buffers
    m_smsData.cleanUp();

    // Timeout
    m_timeOut       = ATDEV_SMS_TIMEOUT_READ;

    // Send command
    if (this->sendATCmd(true) == ATDEV_OK && this->readLine() == ATDEV_OK) {

        // header to smal / receive a error
        if (this->isCMSError() || this->parseInternalData() == 0) {
            return ATDEV_ERR_UNEXPECTED_RESULT;
        }

        // Timeout
        m_timeOut       = ATDEV_SMS_TIMEOUT_READ;

        // read sms text
        if (this->sendATCmd(false, m_smsData.m_message, ATDEV_SMS_TXT_SIZE) != ATDEV_OK) {
            return ATDEV_ERR_UNEXPECTED_RESULT;
        }

        // copy number to buffer
        strncpy(m_smsData.m_number, this->getParseElement(2), ATDEV_SMS_NUM_SIZE);

        // set stop
        m_smsData.m_message[m_readPtr-5] = 0x00;

        return ATDEV_OK;
    }

    return ATDEV_ERR_UNEXPECTED_RESULT;
}

void ATEasySMS::setCMGLEndBuffer()
{
    // Prepare answer end
    memset(m_endBuffer, 0x00, ATDEV_BUFF_END_SIZE +1);
    strncpy_P(m_endBuffer, ATDEV_STR_CMGL, ATDEV_BUFF_END_SIZE);

    // Timeout
    m_timeOut       = ATDEV_SMS_TIMEOUT_LIST;
}

uint16_t ATEasySMS::readNextIdxSMS(uint16_t lastIdx)
{
    int16_t nextIdx = -1;

    // AT cmd
    snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CMGL, ATDEV_OPT_CMGL_ALL);

    do {
        // Set +CMGL: as end
        this->setCMGLEndBuffer();

        // check answer / +CMGL:
        if (this->sendATCmd(true) == ATDEV_OK && this->readLine() == ATDEV_OK) {

            // is state not REC UNREAD or REC READ
            if (strstr_P(m_msgBuffer, ATDEV_OPT_CMGL_READ) == NULL &&
                strstr_P(m_msgBuffer, ATDEV_OPT_CMGL_UNREAD) == NULL) {
                continue;
            }

            // parse
            if (this->parseInternalData() >= 0) {
                nextIdx = atoi(this->getParseElement(0));
            }
            else {
                nextIdx = ATDEV_SMS_NO_MSG;
            }
        }
        // error
        else {
            nextIdx = ATDEV_SMS_NO_MSG;
        }

    } while (nextIdx < lastIdx && !(nextIdx == 0 && lastIdx == 0));

    // flush other
    this->flushInput();

    return static_cast<uint16_t>(nextIdx);
}

uint8_t ATEasySMS::doDeleteSMS(uint16_t idx, uint8_t flag)
{
    char numIdx[5];

    // clean buffer
    memset(numIdx, 0x00, 5);

    // if IDX a number in store?
    if (flag == ATDEV_OPT_CMGD_DEL_IDX) {
        snprintf_P(numIdx, 4, ATDEV_INT_CHAR, idx);
        m_timeOut = ATDEV_SMS_TIMEOUT_DEL;
    }
    // Delete all
    else {
        m_timeOut = ATDEV_SMS_TIMEOUT_DELALL;
    }

    // prepare AT+CMGD=%d,%d
    snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CMGD, numIdx, flag);
    return this->sendATCmd();
}

// vim: set sts=4 sw=4 ts=4 et:
<commit_msg>remove ugly code and cast so the function can handle full uint16_t message<commit_after>
#include "ATEasySMS.h"

uint8_t ATEasySMS::initializeSMS()
{
    ////
    // set text mode
    strncpy_P(m_cmdBuffer, ATDEV_CMD_CMGF, ATDEV_BUFF_CMD_SIZE);

    if (this->sendATCmd() != ATDEV_OK) {
        return ATDEV_ERR_UNEXPECTED_RESULT;
    }

    ////
    // Set message storage
    strncpy_P(m_cmdBuffer, ATDEV_CMD_CPMS, ATDEV_BUFF_CMD_SIZE);

    if (this->sendATCmd() != ATDEV_OK) {
        return ATDEV_ERR_UNEXPECTED_RESULT;
    }

    // Ende
    return this->waitDevice(ATDEV_OK);
}

uint8_t ATEasySMS::sendSMS()
{
    snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CMGS, m_smsData.m_number);

    // Prepare answer
    m_endBuffer[0] = ATDEV_CH_AN;
    m_endBuffer[1] = 0x00;

    // Send command
    if (this->sendATCmd(true) == ATDEV_OK) {

        // Send SMS Data
        m_hwSerial->print(m_smsData.m_message);

        // generate SMS end
        m_cmdBuffer[0] = ATDEV_CH_END;

        // End of SMS
        m_timeOut = ATDEV_SMS_TIMEOUT_SEND;
        return this->sendATCmd();
    }

    return ATDEV_ERR_UNEXPECTED_RESULT;
}

uint8_t ATEasySMS::receiveSMS(uint16_t idx)
{
    snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CMGR, idx);

    // Prepare answer end
    memset(m_endBuffer, 0x00, ATDEV_BUFF_END_SIZE +1);
    strncpy_P(m_endBuffer, ATDEV_STR_CMGR, ATDEV_BUFF_END_SIZE);

    // Cleanup SMS buffers
    m_smsData.cleanUp();

    // Timeout
    m_timeOut       = ATDEV_SMS_TIMEOUT_READ;

    // Send command
    if (this->sendATCmd(true) == ATDEV_OK && this->readLine() == ATDEV_OK) {

        // header to smal / receive a error
        if (this->isCMSError() || this->parseInternalData() == 0) {
            return ATDEV_ERR_UNEXPECTED_RESULT;
        }

        // Timeout
        m_timeOut       = ATDEV_SMS_TIMEOUT_READ;

        // read sms text
        if (this->sendATCmd(false, m_smsData.m_message, ATDEV_SMS_TXT_SIZE) != ATDEV_OK) {
            return ATDEV_ERR_UNEXPECTED_RESULT;
        }

        // copy number to buffer
        strncpy(m_smsData.m_number, this->getParseElement(2), ATDEV_SMS_NUM_SIZE);

        // set stop
        m_smsData.m_message[m_readPtr-5] = 0x00;

        return ATDEV_OK;
    }

    return ATDEV_ERR_UNEXPECTED_RESULT;
}

void ATEasySMS::setCMGLEndBuffer()
{
    // Prepare answer end
    memset(m_endBuffer, 0x00, ATDEV_BUFF_END_SIZE +1);
    strncpy_P(m_endBuffer, ATDEV_STR_CMGL, ATDEV_BUFF_END_SIZE);

    // Timeout
    m_timeOut       = ATDEV_SMS_TIMEOUT_LIST;
}

uint16_t ATEasySMS::readNextIdxSMS(uint16_t lastIdx)
{
    uint16_t nextIdx = ATDEV_SMS_NO_MSG;

    // AT cmd
    snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CMGL, ATDEV_OPT_CMGL_ALL);

    do {
        // Set +CMGL: as end
        this->setCMGLEndBuffer();

        // check answer / +CMGL:
        if (this->sendATCmd(true) == ATDEV_OK && this->readLine() == ATDEV_OK) {

            // is state not REC UNREAD or REC READ
            if (strstr_P(m_msgBuffer, ATDEV_OPT_CMGL_READ) == NULL &&
                strstr_P(m_msgBuffer, ATDEV_OPT_CMGL_UNREAD) == NULL) {
                continue;
            }

            // parse
            if (this->parseInternalData() >= 0) {
                nextIdx = atoi(this->getParseElement(0));
            }
            else {
                nextIdx = ATDEV_SMS_NO_MSG;
                break;
            }
        }
        // error
        else {
            nextIdx = ATDEV_SMS_NO_MSG;
            break;
        }

    } while ((nextIdx < lastIdx && !(nextIdx == 0 && lastIdx == 0)) || nextId == ATDEV_SMS_NO_MSG);

    // flush other
    this->flushInput();

    return nextIdx;
}

uint8_t ATEasySMS::doDeleteSMS(uint16_t idx, uint8_t flag)
{
    char numIdx[5];

    // clean buffer
    memset(numIdx, 0x00, 5);

    // if IDX a number in store?
    if (flag == ATDEV_OPT_CMGD_DEL_IDX) {
        snprintf_P(numIdx, 4, ATDEV_INT_CHAR, idx);
        m_timeOut = ATDEV_SMS_TIMEOUT_DEL;
    }
    // Delete all
    else {
        m_timeOut = ATDEV_SMS_TIMEOUT_DELALL;
    }

    // prepare AT+CMGD=%d,%d
    snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CMGD, numIdx, flag);
    return this->sendATCmd();
}

// vim: set sts=4 sw=4 ts=4 et:
<|endoftext|>


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

#include <avr/io.h>

#include "delay.h"

#define pbcl(port, b) do { port &= (uint8_t)~(_BV(b)); } while (0)
#define pbst(port, b) do { port |= _BV(b); } while (0)

// TLC5940 minimum pulse durations (16ns & 20ns) are smaller than the fastest a 16mHz AVR can do (125ns)
#define pulse(port, b) do { pbst(port, b); pbcl(port, b); } while (0);

#ifdef __led13_support
#  define LEDDDR DDRB
#  define LEDPORT PORTB
#  define LEDPIN 5

static void led13_init() {
	  pbst(LEDDDR, LEDPIN);
}

// useful for visual or logic analyzer identification
static void flashled(int count, int hdelay) {
  for (int i = 0; i < count; ++i) {
    pbst(LEDPORT, LEDPIN);
    delay_100us(hdelay);
    pbcl(LEDPORT, LEDPIN);
    delay_100us(hdelay);
  }
}

#else
#  define led13_init() while(0);
#  define flashled(count, delay) while(0);
#endif // __led13_support

#define TLC_PORT PORTA
#define TLC_DDR DDRA

#define TLC_0_SIN   0
#define TLC_1_SCLK  1
#define TLC_2_XLAT  2
#define TLC_3_BLANK 3
#define TLC_4_GSCLK 4
#define TLC_5_SOUT  xx
#define TLC_6_XERR  xx

#define ROWSEL_DDR DDRC
#define ROWSEL_PORT PORTC

#define GSBPP 12
#define GSPWMTOP 0xfff
#define ROWCOUNT 8
#define PIXELSPERROW 16

static int8_t pci = -1;
static int8_t btci = GSBPP-1;
static uint16_t pixel = 0;
static uint8_t rowi = 4;
static uint16_t pwmi = 0;

#define FACTOR 128

uint16_t gsdata[][16] = {

  {
    FACTOR*7, FACTOR*6, FACTOR*5, FACTOR*4, FACTOR*3, FACTOR*2, FACTOR*1, FACTOR*0,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  },

  {
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    FACTOR*0, FACTOR*1, FACTOR*2, FACTOR*3, FACTOR*4, FACTOR*5, FACTOR*6, FACTOR*7,
  }

};

void setup() {

	led13_init();

  // row selectors all outputs
  ROWSEL_DDR = 0xff;

  // row data controller (tlc5940) data loading serial interface
  TLC_DDR |= _BV(TLC_0_SIN) | _BV(TLC_1_SCLK) | _BV(TLC_2_XLAT);

  // row data controller (tlc5940) pwm controller
  TLC_DDR |= _BV(TLC_3_BLANK) | _BV(TLC_4_GSCLK);

  ROWSEL_PORT = 0xff; // active low, all disabled at start

  pbst(TLC_PORT, TLC_3_BLANK); // blank stuff until we setup

  // row data controller pins are active high
  TLC_PORT &= (uint8_t)~(_BV(TLC_0_SIN) | _BV(TLC_1_SCLK) | _BV(TLC_2_XLAT) | _BV(TLC_4_GSCLK));

  flashled(5, 20);

  for (int8_t i = PIXELSPERROW; i >= 0; --i) {

    uint16_t q = gsdata[0][i];

    for (uint8_t b = 0; b < GSBPP; ++b) {
      if ((q & (1<<(GSBPP-1))) != 0) {
        pbst(TLC_PORT, TLC_0_SIN);
      } else {
        pbcl(TLC_PORT, TLC_0_SIN);
      }

      pulse(TLC_PORT, TLC_1_SCLK);

      q<<=1;
    }
  }

  pulse(TLC_PORT, TLC_2_XLAT);

  pbcl(TLC_PORT, TLC_3_BLANK);

}

void loop() {

  // we never return from the 1st call to loop()

  pwmi = GSPWMTOP;

  while (1) {

    // TODO: offload this to SPI hardware
    if (pci >= 0) {

      if ((pixel & (1<<(GSBPP-1))) != 0) {
        pbst(TLC_PORT, TLC_0_SIN);
      } else {
        pbcl(TLC_PORT, TLC_0_SIN);
      }
      pulse(TLC_PORT, TLC_1_SCLK);

      pixel <<= 1;
      btci--;

      if (btci < 0) {
        pci--;
        pixel = gsdata[rowi%2][pci];
        btci = GSBPP-1;
      }
    }

    pulse(TLC_PORT, TLC_4_GSCLK);

    if (pwmi == 0) {
      pwmi = GSPWMTOP;

      // new GS data has been shifted, latch it
      pulse(TLC_PORT, TLC_2_XLAT);

      // reset GS counter
      pulse(TLC_PORT, TLC_3_BLANK);

      rowi = (rowi + 1) % ROWCOUNT;

      pci = PIXELSPERROW - 1;
      pixel = gsdata[rowi%2][pci];

      ROWSEL_PORT = ~(1<<rowi);

    } else {
      pwmi--;
    }
  }
}

int main(int argc, char** argv) {
	setup();
	loop();
}

<commit_msg>Adds preprocessor portability between devboard and Arduino target hw<commit_after>//
//   Copyright 2012 Dave Bacon
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//

#include <avr/io.h>

#define __devboard_mine__ 1

#if defined(ARDUINO)
#  define __led13_support
#  define delay_100us(x) delay(x)
#elif defined(__devboard_mine__)
# include "delay.h"
#else
#  warning "no target board defined"
#endif

#define pbcl(port, b) do { port &= (uint8_t)~(_BV(b)); } while (0)
#define pbst(port, b) do { port |= _BV(b); } while (0)

// TLC5940 minimum pulse durations (16ns & 20ns) are smaller than the fastest a 16mHz AVR can do (125ns)
#define pulse(port, b) do { pbst(port, b); pbcl(port, b); } while (0);

#ifdef __led13_support
#  define LEDDDR DDRB
#  define LEDPORT PORTB
#  define LEDPIN 5

static void led13_init() {
	  pbst(LEDDDR, LEDPIN);
}

// useful for visual or logic analyzer identification
static void flashled(int count, int hdelay) {
  for (int i = 0; i < count; ++i) {
    pbst(LEDPORT, LEDPIN);
    delay_100us(hdelay);
    pbcl(LEDPORT, LEDPIN);
    delay_100us(hdelay);
  }
}

#else
#  define led13_init() while(0);
#  define flashled(count, delay) while(0);
#endif // __led13_support

#if defined(ARDUINO)
#  define TLC_PORT PORTB
#  define TLC_DDR DDRB
#elif defined(__devboard_mine__)
#  define TLC_PORT PORTA
#  define TLC_DDR DDRA
#else
#  warning "no target board defined"
#endif

#define TLC_0_SIN   0
#define TLC_1_SCLK  1
#define TLC_2_XLAT  2
#define TLC_3_BLANK 3
#define TLC_4_GSCLK 4
#define TLC_5_SOUT  xx
#define TLC_6_XERR  xx

#if defined(ARDUINO)
#  define ROWSEL_DDR DDRD
#  define ROWSEL_PORT PORTD
#elif defined(__devboard_mine__)
#  define ROWSEL_DDR DDRC
#  define ROWSEL_PORT PORTC
#else
#  warning "no target board defined"
#endif

#define GSBPP 12
#define GSPWMTOP 0xfff
#define ROWCOUNT 8
#define PIXELSPERROW 16

static int8_t pci = -1;
static int8_t btci = GSBPP-1;
static uint16_t pixel = 0;
static uint8_t rowi = 4;
static uint16_t pwmi = 0;

#define FACTOR 128

uint16_t gsdata[][16] = {

  {
    FACTOR*7, FACTOR*6, FACTOR*5, FACTOR*4, FACTOR*3, FACTOR*2, FACTOR*1, FACTOR*0,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  },

  {
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    FACTOR*0, FACTOR*1, FACTOR*2, FACTOR*3, FACTOR*4, FACTOR*5, FACTOR*6, FACTOR*7,
  }

};

void setup() {

  led13_init();

  // row selectors all outputs
  ROWSEL_DDR = 0xff;

  // row data controller (tlc5940) data loading serial interface
  TLC_DDR |= _BV(TLC_0_SIN) | _BV(TLC_1_SCLK) | _BV(TLC_2_XLAT);

  // row data controller (tlc5940) pwm controller
  TLC_DDR |= _BV(TLC_3_BLANK) | _BV(TLC_4_GSCLK);

  ROWSEL_PORT = 0xff; // active low, all disabled at start

  pbst(TLC_PORT, TLC_3_BLANK); // blank stuff until we setup

  // row data controller pins are active high
  TLC_PORT &= (uint8_t)~(_BV(TLC_0_SIN) | _BV(TLC_1_SCLK) | _BV(TLC_2_XLAT) | _BV(TLC_4_GSCLK));

  flashled(5, 20);

  for (int8_t i = PIXELSPERROW; i >= 0; --i) {

    uint16_t q = gsdata[0][i];

    for (uint8_t b = 0; b < GSBPP; ++b) {
      if ((q & (1<<(GSBPP-1))) != 0) {
        pbst(TLC_PORT, TLC_0_SIN);
      } else {
        pbcl(TLC_PORT, TLC_0_SIN);
      }

      pulse(TLC_PORT, TLC_1_SCLK);

      q<<=1;
    }
  }

  pulse(TLC_PORT, TLC_2_XLAT);

  pbcl(TLC_PORT, TLC_3_BLANK);

}

void loop() {

  // we never return from the 1st call to loop()

  pwmi = GSPWMTOP;

  while (1) {

    // TODO: offload this to SPI hardware
    if (pci >= 0) {

      if ((pixel & (1<<(GSBPP-1))) != 0) {
        pbst(TLC_PORT, TLC_0_SIN);
      } else {
        pbcl(TLC_PORT, TLC_0_SIN);
      }
      pulse(TLC_PORT, TLC_1_SCLK);

      pixel <<= 1;
      btci--;

      if (btci < 0) {
        pci--;
        pixel = gsdata[rowi%2][pci];
        btci = GSBPP-1;
      }
    }

    pulse(TLC_PORT, TLC_4_GSCLK);

    if (pwmi == 0) {
      pwmi = GSPWMTOP;

      // new GS data has been shifted, latch it
      pulse(TLC_PORT, TLC_2_XLAT);

      // reset GS counter
      pulse(TLC_PORT, TLC_3_BLANK);

      rowi = (rowi + 1) % ROWCOUNT;

      pci = PIXELSPERROW - 1;
      pixel = gsdata[rowi%2][pci];

      ROWSEL_PORT = ~(1<<rowi);

    } else {
      pwmi--;
    }
  }
}

#if !defined(ARDUINO)

int main(int argc, char** argv) {
	setup();
	loop();
}

#endif
<|endoftext|>


<commit_before>#include "code_gen.h"
#include "cpp.h"
#include "error.h"
#include "parser.h"
#include "scanner.h"

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <list>
#include <string>
#include <vector>

#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>

std::string program;
std::string filename_in;
std::string filename_out;
bool debug = false;
static bool only_preprocess = false;
static bool only_compile = false;
static bool specified_out_name = false;
static std::list<std::string> filenames_in;
static std::list<std::string> gcc_filenames_in;
static std::list<std::string> gcc_args;
static std::list<std::string> defines;
static std::list<std::string> include_paths;

static void Usage() {
  printf("Usage: wgtcc [options] file...\n"
       "Options: \n"
       "  -h        Display this information\n"
       "  -D        Define object like macro\n"
       "  -I        Add search path\n"
       "  -E        Preprocess only; do not compile, assemble or link\n"
       "  -S        Compile only; do not assemble or link\n"
       "  -o        specify output file\n");

  exit(0);
}

static std::string GetExtension(const std::string& filename) {
  return filename.substr(filename.size() >= 2 ? filename.size() - 2 : 0);
}

static void ValidateFileName(const std::string& filename) {
  auto ext = GetExtension(filename);
  if (ext != ".c" && ext != ".s" && ext != ".o" && ext != ".a")
    Error("bad file name format:'%s'", filename.c_str());
}

static void DefineMacro(Preprocessor& cpp, const std::string& def) {
  auto pos = def.find('=');
  std::string macro;
  std::string* replace;
  if (pos == std::string::npos) {
    macro = def;
    replace = new std::string();
  } else {
    macro = def.substr(0, pos);
    replace = new std::string(def.substr(pos + 1));
  }
  cpp.AddMacro(macro, replace);
}

static std::string GetName(const std::string& path) {
  auto pos = path.rfind('/');
  if (pos == std::string::npos)
    return path;
  return path.substr(pos + 1);
}

static int RunWgtcc() {
  if (GetExtension(filename_in) != ".c")
    return -3;

  Preprocessor cpp(&filename_in);
  for (auto& def: defines)
    DefineMacro(cpp, def);
  for (auto& path: include_paths)
    cpp.AddSearchPath(path);

  FILE* fp = stdout;
  if (specified_out_name) {
    fp = fopen(filename_out.c_str(), "w");
  }
  TokenSequence ts;
  cpp.Process(ts);
  if (only_preprocess) {
    ts.Print(fp);
    return 0;
  }

  if (!only_compile || !specified_out_name) {
    filename_out = GetName(filename_in);
    filename_out.back() = 's';
  }
  fp = fopen(filename_out.c_str(), "w");

  Parser parser(ts);
  parser.Parse();
  Generator::SetInOut(&parser, fp);
  Generator().Gen();
  fclose(fp);
  return 0;
}

static int RunGcc() {
  // Froce C11
  bool spec_std = false;
  for (auto& arg: gcc_args) {
    if (arg.substr(0, 4) == "-std") {
      arg = "-std=c11";
      spec_std = true;
    }
  }
  if (!spec_std) {
    gcc_args.push_front("-std=c11");
  }

  std::string systemArg = "gcc";
  for (const auto& arg: gcc_args) {
    systemArg += " " + arg;
  }
  auto ret = system(systemArg.c_str());
  return ret;
}

static void ParseInclude(int argc, char* argv[], int& i) {
  if (argv[i][2]) {
    include_paths.push_front(&argv[i][2]);
    return;
  }

  if (i == argc - 1) {
    Error("missing argument to '%s'", argv[i]);
  }
  include_paths.push_front(argv[++i]);
  gcc_args.push_back(argv[i]);
}

static void ParseDefine(int argc, char* argv[], int& i) {
  if (argv[i][2]) {
    defines.push_back(&argv[i][2]);
    return;
  }

  if (i == argc - 1)
    Error("missing argument to '%s'", argv[i]);
  defines.push_back(argv[++i]);
  gcc_args.push_back(argv[i]);
}

static void ParseOut(int argc, char* argv[], int& i) {
  if (i == argc - 1)
    Error("missing argument to '%s'", argv[i]);
  filename_out = argv[++i];
  gcc_args.push_back(argv[i]);
}

/* Use:
 *   wgtcc: compile
 *   gcc: assemble and link
 * Allowing multi file may not be a good idea...
 */
int main(int argc, char* argv[]) {
  if (argc < 2)
    Usage();

  program = std::string(argv[0]);
  for (auto i = 1; i < argc; ++i) {
    if (argv[i][0] != '-') {
      filename_in = std::string(argv[i]);
      ValidateFileName(filename_in);
      filenames_in.push_back(filename_in);
      continue;
    }

    gcc_args.push_back(argv[i]);
    switch (argv[i][1]) {
    case 'h': Usage(); break;
    case 'E': only_preprocess = true; break;
    case 'S': only_compile = true; break;
    case 'I': ParseInclude(argc, argv, i); break;
    case 'D': ParseDefine(argc, argv, i); break;
    case 'o':
      specified_out_name = true;
      ParseOut(argc, argv, i); break;
    case 'g': gcc_args.pop_back(); debug = true; break;
    default:;
    }
  }

#ifdef DEBUG
  RunWgtcc();
#else
  for (const auto& filename: filenames_in) {
    filename_in = filename;
    pid_t pid = fork();
    if (pid < 0) {
      Error("fork error");
    } else if (pid == 0) {
      // Do work in child process
      return RunWgtcc();
    }
  }

  for (size_t i = 0; i < filenames_in.size(); ++i) {
      int stat;
      wait(&stat);
      // Child process terminate normaly if :
      // 1. terminate with `exit()`, that is, WIFEXITED(stat) if true.
      // 2. the status code is 0, that is, WEXITSTATUS(stat) == 0
      if (!WIFEXITED(stat) || WEXITSTATUS(stat))
        return 0;
  }
#endif

  if (only_preprocess || only_compile) {
    if (specified_out_name && filenames_in.size() > 1)
      Error("cannot specifier output filename with multiple input file");
    return 0;
  }

  std::list<std::string> filenames_out;
  for (auto& filename: filenames_in) {
    if (GetExtension(filename) == ".c") {
      gcc_args.push_back(GetName(filename));
      gcc_args.back().back() = 's';
    } else {
      gcc_args.clear();
      for (int i = 1; i < argc; ++i)
        gcc_args.push_back(argv[i]);
      break;
    }
  }
  auto ret = RunGcc();
  auto cmd = "rm -f " + filename_out;
  if (system(cmd.c_str())) {}
  return ret;
}
<commit_msg>Use standard function 'remove' (#58)<commit_after>#include "code_gen.h"
#include "cpp.h"
#include "error.h"
#include "parser.h"
#include "scanner.h"

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <list>
#include <string>
#include <vector>

#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>

std::string program;
std::string filename_in;
std::string filename_out;
bool debug = false;
static bool only_preprocess = false;
static bool only_compile = false;
static bool specified_out_name = false;
static std::list<std::string> filenames_in;
static std::list<std::string> gcc_filenames_in;
static std::list<std::string> gcc_args;
static std::list<std::string> defines;
static std::list<std::string> include_paths;

static void Usage() {
  printf("Usage: wgtcc [options] file...\n"
       "Options: \n"
       "  -h        Display this information\n"
       "  -D        Define object like macro\n"
       "  -I        Add search path\n"
       "  -E        Preprocess only; do not compile, assemble or link\n"
       "  -S        Compile only; do not assemble or link\n"
       "  -o        specify output file\n");

  exit(0);
}

static std::string GetExtension(const std::string& filename) {
  return filename.substr(filename.size() >= 2 ? filename.size() - 2 : 0);
}

static void ValidateFileName(const std::string& filename) {
  auto ext = GetExtension(filename);
  if (ext != ".c" && ext != ".s" && ext != ".o" && ext != ".a")
    Error("bad file name format:'%s'", filename.c_str());
}

static void DefineMacro(Preprocessor& cpp, const std::string& def) {
  auto pos = def.find('=');
  std::string macro;
  std::string* replace;
  if (pos == std::string::npos) {
    macro = def;
    replace = new std::string();
  } else {
    macro = def.substr(0, pos);
    replace = new std::string(def.substr(pos + 1));
  }
  cpp.AddMacro(macro, replace);
}

static std::string GetName(const std::string& path) {
  auto pos = path.rfind('/');
  if (pos == std::string::npos)
    return path;
  return path.substr(pos + 1);
}

static int RunWgtcc() {
  if (GetExtension(filename_in) != ".c")
    return -3;

  Preprocessor cpp(&filename_in);
  for (auto& def: defines)
    DefineMacro(cpp, def);
  for (auto& path: include_paths)
    cpp.AddSearchPath(path);

  FILE* fp = stdout;
  if (specified_out_name) {
    fp = fopen(filename_out.c_str(), "w");
  }
  TokenSequence ts;
  cpp.Process(ts);
  if (only_preprocess) {
    ts.Print(fp);
    return 0;
  }

  if (!only_compile || !specified_out_name) {
    filename_out = GetName(filename_in);
    filename_out.back() = 's';
  }
  fp = fopen(filename_out.c_str(), "w");

  Parser parser(ts);
  parser.Parse();
  Generator::SetInOut(&parser, fp);
  Generator().Gen();
  fclose(fp);
  return 0;
}

static int RunGcc() {
  // Froce C11
  bool spec_std = false;
  for (auto& arg: gcc_args) {
    if (arg.substr(0, 4) == "-std") {
      arg = "-std=c11";
      spec_std = true;
    }
  }
  if (!spec_std) {
    gcc_args.push_front("-std=c11");
  }

  std::string systemArg = "gcc";
  for (const auto& arg: gcc_args) {
    systemArg += " " + arg;
  }
  auto ret = system(systemArg.c_str());
  return ret;
}

static void ParseInclude(int argc, char* argv[], int& i) {
  if (argv[i][2]) {
    include_paths.push_front(&argv[i][2]);
    return;
  }

  if (i == argc - 1) {
    Error("missing argument to '%s'", argv[i]);
  }
  include_paths.push_front(argv[++i]);
  gcc_args.push_back(argv[i]);
}

static void ParseDefine(int argc, char* argv[], int& i) {
  if (argv[i][2]) {
    defines.push_back(&argv[i][2]);
    return;
  }

  if (i == argc - 1)
    Error("missing argument to '%s'", argv[i]);
  defines.push_back(argv[++i]);
  gcc_args.push_back(argv[i]);
}

static void ParseOut(int argc, char* argv[], int& i) {
  if (i == argc - 1)
    Error("missing argument to '%s'", argv[i]);
  filename_out = argv[++i];
  gcc_args.push_back(argv[i]);
}

/* Use:
 *   wgtcc: compile
 *   gcc: assemble and link
 * Allowing multi file may not be a good idea...
 */
int main(int argc, char* argv[]) {
  if (argc < 2)
    Usage();

  program = std::string(argv[0]);
  for (auto i = 1; i < argc; ++i) {
    if (argv[i][0] != '-') {
      filename_in = std::string(argv[i]);
      ValidateFileName(filename_in);
      filenames_in.push_back(filename_in);
      continue;
    }

    gcc_args.push_back(argv[i]);
    switch (argv[i][1]) {
    case 'h': Usage(); break;
    case 'E': only_preprocess = true; break;
    case 'S': only_compile = true; break;
    case 'I': ParseInclude(argc, argv, i); break;
    case 'D': ParseDefine(argc, argv, i); break;
    case 'o':
      specified_out_name = true;
      ParseOut(argc, argv, i); break;
    case 'g': gcc_args.pop_back(); debug = true; break;
    default:;
    }
  }

#ifdef DEBUG
  RunWgtcc();
#else
  for (const auto& filename: filenames_in) {
    filename_in = filename;
    pid_t pid = fork();
    if (pid < 0) {
      Error("fork error");
    } else if (pid == 0) {
      // Do work in child process
      return RunWgtcc();
    }
  }

  for (size_t i = 0; i < filenames_in.size(); ++i) {
      int stat;
      wait(&stat);
      // Child process terminate normaly if :
      // 1. terminate with `exit()`, that is, WIFEXITED(stat) if true.
      // 2. the status code is 0, that is, WEXITSTATUS(stat) == 0
      if (!WIFEXITED(stat) || WEXITSTATUS(stat))
        return 0;
  }
#endif

  if (only_preprocess || only_compile) {
    if (specified_out_name && filenames_in.size() > 1)
      Error("cannot specifier output filename with multiple input file");
    return 0;
  }

  std::list<std::string> filenames_out;
  for (auto& filename: filenames_in) {
    if (GetExtension(filename) == ".c") {
      gcc_args.push_back(GetName(filename));
      gcc_args.back().back() = 's';
    } else {
      gcc_args.clear();
      for (int i = 1; i < argc; ++i)
        gcc_args.push_back(argv[i]);
      break;
    }
  }
  auto ret = RunGcc();
  remove(filename_out.c_str());
  return ret;
}
<|endoftext|>


<commit_before>#include "AM2320.h"
#include <Wire.h>

// AM2320 Temperature & Humidity Sensor library for Arduino
// Modified by Timofeev E.N. from https://github.com/thakshak/AM2320/

unsigned int CRC16(byte * ptr, byte length) {
        unsigned int crc = 0xFFFF;
        uint8_t s = 0x00;

        while (length--) {
                crc ^ = * ptr++;
                for (s = 0; s < 8; s++) {
                        if ((crc & 0x01) ! = 0) {
                                crc >> = 1;
                                crc ^ = 0xA001;
                        } else crc >> = 1;
                }
        }
        return crc;
}

AM2320::AM2320() {}

int AM2320::Read() {
        byte buf[8];
        for (int s = 0; s < 8; s++) buf[s] = 0x00;

        Wire.beginTransmission(AM2320_address);
        Wire.endTransmission();
        // request 4 bytes (temperature and humidity)
        Wire.beginTransmission(AM2320_address);
        Wire.write(0x03); // request
        Wire.write(0x00); // from the 0th address
        Wire.write(0x04); // 4 bytes
        if (Wire.endTransmission(1) ! = 0) return 1;
        delayMicroseconds(1600); //>1.5ms
        // read the query results
        Wire.requestFrom(AM2320_address, 0x08);
        for (int i = 0; i < 0x08; i++) buf[i] = Wire.read();

        // CRC check
        unsigned int Rcrc = buf[7] << 8;
        Rcrc + = buf[6];
        if (Rcrc == CRC16(buf, 6)) {
                unsigned int temperature = ((buf[4] & 0x7F) << 8) + buf[5];
                t = temperature / 10.0;
                t = ((buf[4] & 0x80) >> 7) == 1 ? t * (-1) : t;

                unsigned int humidity = (buf[2] << 8) + buf[3];
                h = humidity / 10.0;
                return 0;
        }
        return 2;
}
<commit_msg>fixed operators<commit_after>#include "AM2320.h"
#include <Wire.h>

// AM2320 Temperature & Humidity Sensor library for Arduino
// Modified by Timofeev E.N. from https://github.com/thakshak/AM2320/

unsigned int CRC16(byte *ptr, byte length) {
        unsigned int crc = 0xFFFF;
        uint8_t s = 0x00;

        while (length--) {
                crc ^= *ptr++;
                for (s = 0; s < 8; s++) {
                        if ((crc & 0x01) != 0) {
                                crc >>= 1;
                                crc ^= 0xA001;
                        } else crc >>= 1;
                }
        }
        return crc;
}

AM2320::AM2320() {}

int AM2320::Read() {
        byte buf[8];
        for (int s = 0; s < 8; s++) buf[s] = 0x00;

        Wire.beginTransmission(AM2320_address);
        Wire.endTransmission();
        // request 4 bytes (temperature and humidity)
        Wire.beginTransmission(AM2320_address);
        Wire.write(0x03); // request
        Wire.write(0x00); // from the 0th address
        Wire.write(0x04); // 4 bytes
        if (Wire.endTransmission(1) != 0) return 1;
        delayMicroseconds(1600); //>1.5ms
        // read the query results
        Wire.requestFrom(AM2320_address, 0x08);
        for (int i = 0; i < 0x08; i++) buf[i] = Wire.read();

        // CRC check
        unsigned int Rcrc = buf[7] << 8;
        Rcrc += buf[6];
        if (Rcrc == CRC16(buf, 6)) {
                unsigned int temperature = ((buf[4] & 0x7F) << 8) + buf[5];
                t = temperature / 10.0;
                t = ((buf[4] & 0x80) >> 7) == 1 ? t * (-1) : t;

                unsigned int humidity = (buf[2] << 8) + buf[3];
                h = humidity / 10.0;
                return 0;
        }
        return 2;
}
<|endoftext|>


<commit_before>#pragma once

#include "Grappa.hpp"
#include "LocaleSharedMemory.hpp"

#include <stdlib.h>

namespace Grappa {

/// Vector that exposes its storage array as read-only.
/// increases in capacity as elements are added.
///
/// Only supports insertions. Insertions allowed only
/// while vector is in write only (OpMode::WO) mode and
/// getting the buffer pointer only allowed in read only mode
///
template < typename T >
class BufferVector {

  private:
    T * buf;
    size_t capacity;
    uint64_t nextIndex;

    enum class OpMode { RO, WO };
    OpMode mode;

  public:
    BufferVector( size_t capacity = 2 )
      : buf ( locale_alloc<T>(capacity) )
      , mode( OpMode::WO )
      , nextIndex( 0 )
      , capacity( capacity ) { }

    ~BufferVector() {
      locale_free(buf);
    }

    void setWriteMode() {
      CHECK( mode != OpMode::WO ) << "already in OpMode::WO mode";
      mode = OpMode::WO;
    }

    void setReadMode() {
      CHECK( mode != OpMode::RO ) << "already in OpMode::RO mode (" << this << ")";
      DVLOG(3) << "(" << this << ").setReadMode()";
      mode = OpMode::RO;
    }

    void insert( const T& v ) {
      CHECK( mode == OpMode::WO ) << "Must be in OpMode::WO mode to insert";

      if ( nextIndex == capacity ) {
        // expand the capacity of the buffer
        size_t newcapacity = capacity * 2;
        T * newbuf = locale_alloc<T>(newcapacity);
        memcpy( newbuf, buf, capacity*sizeof(T) );
        locale_free( buf );
        capacity = newcapacity;
        buf = newbuf;
      }

      // store element and increment index
      buf[nextIndex++] = v;
    }

    GlobalAddress<T> getReadBuffer() const {
      CHECK( mode == OpMode::RO ) << "Must be in OpMode::RO mode to see buffer";
      return make_global( /*static_cast<const T*>*/(buf) );
    }

    size_t size() const {
      return nextIndex;
    }

    /* to close the safety loop, OpMode::RO clients should release buffers,
     * allowing setWriteMode() to check that all buffers are released
     * but currently we will avoid this extra communication
     *
     * If we want more fine-grained concurrent R/W then it is better
     * not to expose this getBuffer type of interface
     */

    template < typename T1 >
    friend std::ostream& operator<<( std::ostream& o, const BufferVector<T1>& v );
};

template< typename T >
std::ostream& operator<<( std::ostream& o, const BufferVector<T>& v ) {
  o << "BV("
             << "capacity=" << v.capacity << ", "
             << "nextIndex=" << v.nextIndex << /*", "
             << "mode=" << v.mode==BufferVector<T>::OpMode::RO?"RO":"WO" <<*/ ")[";

  // print contents; ignores RO/WO functionality
  for (uint64_t i=0; i<v.nextIndex; i++) {
    int64_t r;
    o << v.buf[i] << ",";
  }
  o << "]";
  return o;
}

} // namespace Grappa
<commit_msg>Add RW option to BufferVector.<commit_after>#pragma once

#include "Grappa.hpp"
#include "LocaleSharedMemory.hpp"

#include <stdlib.h>

namespace Grappa {

/// Vector that exposes its storage array as read-only.
/// increases in capacity as elements are added.
///
/// Only supports insertions. Insertions allowed only
/// while vector is in write only (OpMode::WO) mode and
/// getting the buffer pointer only allowed in read only mode
///
template < typename T >
class BufferVector {

  private:
    T * buf;
    size_t capacity;
    uint64_t nextIndex;

    enum class OpMode { RO, WO, RW };
    OpMode mode;
    bool writeable() const { return mode == OpMode::WO || mode == OpMode::RW; }
    bool readable() const { return mode == OpMode::RO || mode == OpMode::RW; }

  public:
    BufferVector( size_t capacity = 2 )
      : buf ( locale_alloc<T>(capacity) )
      , mode( OpMode::WO )
      , nextIndex( 0 )
      , capacity( capacity ) { }

    ~BufferVector() {
      locale_free(buf);
    }

    void setWriteMode() {
      CHECK( mode != OpMode::WO ) << "already in OpMode::WO mode";
      mode = OpMode::WO;
    }

    void setReadMode() {
      CHECK( mode != OpMode::RO ) << "already in OpMode::RO mode (" << this << ")";
      DVLOG(3) << "(" << this << ").setReadMode()";
      mode = OpMode::RO;
    }

    void setReadWriteMode() { mode = OpMode::RW; }

    void insert( const T& v ) {
      CHECK( writeable() ) << "Must be in writable mode to insert";

      if ( nextIndex == capacity ) {
        // expand the capacity of the buffer
        size_t newcapacity = capacity * 2;
        T * newbuf = locale_alloc<T>(newcapacity);
        memcpy( newbuf, buf, capacity*sizeof(T) );
        locale_free( buf );
        capacity = newcapacity;
        buf = newbuf;
      }

      // store element and increment index
      buf[nextIndex++] = v;
    }

    GlobalAddress<T> getReadBuffer() const {
      CHECK( readable() ) << "Must be in readable mode to see buffer: " << (int)mode;
      return make_global( /*static_cast<const T*>*/(buf) );
    }

    size_t size() const {
      return nextIndex;
    }

    /* to close the safety loop, OpMode::RO clients should release buffers,
     * allowing setWriteMode() to check that all buffers are released
     * but currently we will avoid this extra communication
     *
     * If we want more fine-grained concurrent R/W then it is better
     * not to expose this getBuffer type of interface
     */

    template < typename T1 >
    friend std::ostream& operator<<( std::ostream& o, const BufferVector<T1>& v );
};

template< typename T >
std::ostream& operator<<( std::ostream& o, const BufferVector<T>& v ) {
  o << "BV("
             << "capacity=" << v.capacity << ", "
             << "nextIndex=" << v.nextIndex << /*", "
             << "mode=" << v.mode==BufferVector<T>::OpMode::RO?"RO":"WO" <<*/ ")[";

  // print contents; ignores RO/WO functionality
  for (uint64_t i=0; i<v.nextIndex; i++) {
    int64_t r;
    o << v.buf[i] << ",";
  }
  o << "]";
  return o;
}

} // namespace Grappa
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////
// This file is part of Grappa, a system for scaling irregular
// applications on commodity clusters.

// Copyright (C) 2010-2014 University of Washington and Battelle
// Memorial Institute. University of Washington authorizes use of this
// Grappa software.

// Grappa is free software: you can redistribute it and/or modify it
// under the terms of the Affero General Public License as published
// by Affero, Inc., either version 1 of the License, or (at your
// option) any later version.

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

// You should have received a copy of the Affero General Public
// License along with this program. If not, you may obtain one from
// http://www.affero.org/oagpl.html.
////////////////////////////////////////////////////////////////////////

#pragma once

#include "Message.hpp"
#include "Addressing.hpp"
#include "FullEmptyLocal.hpp"
#include "Metrics.hpp"

GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, delegate_short_circuits);

GRAPPA_DECLARE_METRIC(SummarizingMetric<double>, delegate_roundtrip_latency);
GRAPPA_DECLARE_METRIC(SummarizingMetric<double>, delegate_network_latency);
GRAPPA_DECLARE_METRIC(SummarizingMetric<double>, delegate_wakeup_latency);

GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, delegate_ops);
GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, delegate_targets);

namespace Grappa {

  namespace impl {

    inline void record_network_latency(int64_t start_time) {
      auto latency = Grappa::timestamp() - start_time;
      delegate_network_latency += latency;
    }

    inline void record_wakeup_latency(int64_t start_time, int64_t network_time) {
      auto current_time = Grappa::timestamp();
      auto blocked_time = current_time - start_time;
      auto wakeup_latency = current_time - network_time;
      delegate_roundtrip_latency += blocked_time;
      delegate_wakeup_latency += wakeup_latency;
    }

    // blocking call (void return type)
    template< typename F >
    void call(Core dest, F func, void (F::*mf)() const) {
      delegate_ops++;
      Core origin = Grappa::mycore();

      if (dest == origin) {
        // short-circuit if local
        delegate_short_circuits++;
        func();
      } else {
        int64_t network_time = 0;
        int64_t start_time = Grappa::timestamp();
        FullEmpty<bool> result;
        send_message(dest, [&result, origin, func, &network_time, start_time] {
          delegate_targets++;

          func();

          // TODO: replace with handler-safe send_message
          send_heap_message(origin, [&result, &network_time, start_time] {
            network_time = Grappa::timestamp();
            record_network_latency(start_time);
            result.writeXF(true);
          });
        }); // send message

        // ... and wait for the call to complete
        result.readFF();
        record_wakeup_latency(start_time, network_time);
      }
    }

    // blocking call (with return val)
    template< typename F, typename T >
    auto call(Core dest, F func, T (F::*mf)() const) -> T {
      static_assert(std::is_convertible< decltype(func()), T >(),
                    "lambda doesn't return the expected type");
      // Note: code below (calling call_async) could be used to avoid duplication of code,
      // but call_async adds some overhead (object creation overhead, especially for short
      // -circuit case and extra work in MessagePool)
      //   Promise<T> a;
      //   a.call_async(dest, func);
      //   return a.get();
      // TODO: find a way to implement using async version that doesn't introduce overhead

      delegate_ops++;
      Core origin = Grappa::mycore();

      if (dest == origin) {
        // short-circuit if local
        delegate_targets++;
        delegate_short_circuits++;
        return func();
      } else {
        FullEmpty<T> result;
        int64_t network_time = 0;
        int64_t start_time = Grappa::timestamp();

        send_message(dest, [&result, origin, func, &network_time, start_time] {
          delegate_targets++;
          T val = func();

          // TODO: replace with handler-safe send_message
          send_heap_message(origin, [&result, val, &network_time, start_time] {
            network_time = Grappa::timestamp();
            record_network_latency(start_time);
            result.writeXF(val); // can't block in message, assumption is that result is already empty
          });
        }); // send message
        // ... and wait for the result
        T r = result.readFE();
        record_wakeup_latency(start_time, network_time);
        return r;
      }
    }

    template< typename F >
    auto call(Core dest, F func) -> decltype(func()) {
      return call(dest, func, &F::operator());
    }

  } // namespace impl

} // namespace Grappa

<commit_msg>Fix size of delegate messages!<commit_after>////////////////////////////////////////////////////////////////////////
// This file is part of Grappa, a system for scaling irregular
// applications on commodity clusters.

// Copyright (C) 2010-2014 University of Washington and Battelle
// Memorial Institute. University of Washington authorizes use of this
// Grappa software.

// Grappa is free software: you can redistribute it and/or modify it
// under the terms of the Affero General Public License as published
// by Affero, Inc., either version 1 of the License, or (at your
// option) any later version.

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

// You should have received a copy of the Affero General Public
// License along with this program. If not, you may obtain one from
// http://www.affero.org/oagpl.html.
////////////////////////////////////////////////////////////////////////

#pragma once

#include "Message.hpp"
#include "Addressing.hpp"
#include "FullEmptyLocal.hpp"
#include "Metrics.hpp"

GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, delegate_short_circuits);

GRAPPA_DECLARE_METRIC(SummarizingMetric<double>, delegate_roundtrip_latency);
GRAPPA_DECLARE_METRIC(SummarizingMetric<double>, delegate_network_latency);
GRAPPA_DECLARE_METRIC(SummarizingMetric<double>, delegate_wakeup_latency);

GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, delegate_ops);
GRAPPA_DECLARE_METRIC(SimpleMetric<uint64_t>, delegate_targets);

namespace Grappa {

  namespace impl {

    inline void record_network_latency(int64_t start_time) {
      auto latency = Grappa::timestamp() - start_time;
      delegate_network_latency += latency;
    }

    inline void record_wakeup_latency(int64_t start_time, int64_t network_time) {
      auto current_time = Grappa::timestamp();
      auto blocked_time = current_time - start_time;
      auto wakeup_latency = current_time - network_time;
      delegate_roundtrip_latency += blocked_time;
      delegate_wakeup_latency += wakeup_latency;
    }

    // blocking call (void return type)
    template< typename F >
    void call(Core dest, F func, void (F::*mf)() const) {
      delegate_ops++;
      Core origin = Grappa::mycore();

      if (dest == origin) {
        // short-circuit if local
        delegate_short_circuits++;
        func();
      } else {

        struct Desc {
          int64_t network_time;
          int64_t start_time;
        } desc;

        desc.network_time = 0;
        desc.start_time = Grappa::timestamp();

        FullEmpty<Desc*> result(&desc);
        result.readFE();
        auto ra = make_global(&result);

        send_message(dest, [ra,func] {
          delegate_targets++;

          func();

          // TODO: replace with handler-safe send_message
          send_heap_message(ra.core(), [ra] {
            auto r = ra->readXX();
            r->network_time = Grappa::timestamp();
            record_network_latency(r->start_time);
            ra->writeXF(r);
          });
        }); // send message

        // ... and wait for the call to complete
        result.readFF();
        record_wakeup_latency(desc.start_time, desc.network_time);
      }
    }

    // blocking call (with return val)
    template< typename F, typename T >
    auto call(Core dest, F func, T (F::*mf)() const) -> T {
      static_assert(std::is_convertible< decltype(func()), T >(),
                    "lambda doesn't return the expected type");
      // Note: code below (calling call_async) could be used to avoid duplication of code,
      // but call_async adds some overhead (object creation overhead, especially for short
      // -circuit case and extra work in MessagePool)
      //   Promise<T> a;
      //   a.call_async(dest, func);
      //   return a.get();
      // TODO: find a way to implement using async version that doesn't introduce overhead

      delegate_ops++;
      Core origin = Grappa::mycore();

      if (dest == origin) {
        // short-circuit if local
        delegate_targets++;
        delegate_short_circuits++;
        return func();
      } else {

        struct Desc {
          T result;
          int64_t network_time;
          int64_t start_time;
        } desc;

        desc.network_time = 0;
        desc.start_time = Grappa::timestamp();

        FullEmpty<Desc*> dfe(&desc);
        dfe.readFE();
        auto da = make_global(&dfe);

        send_message(dest, [da,func] {
          delegate_targets++;

          auto val = func();

          // TODO: replace with handler-safe send_message
          send_heap_message(da.core(), [da,val] {
            auto d = da->readXX();
            d->result = val;
            d->network_time = Grappa::timestamp();
            record_network_latency(d->start_time);
            da->writeXF(d);
          });
        }); // send message

        // ... and wait for the call to complete
        dfe.readFF();
        record_wakeup_latency(desc.start_time, desc.network_time);
        return desc.result;
      }
    }

    template< typename F >
    auto call(Core dest, F func) -> decltype(func()) {
      return call(dest, func, &F::operator());
    }

  } // namespace impl

} // namespace Grappa

<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993-2011 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "common.h"

/* system headers */
#include <sstream>
#include <string>
#include <stdio.h>
#include <string.h>

// opaque version number increments on protocol incompatibility
#ifndef BZ_PROTO_VERSION
#  define BZ_PROTO_VERSION	"0207"
#endif

// version numbers - also update as needed:
//  ChangeLog
//  README
//  configure.ac
//  include/version.h
//  package/win32/nsis/BZFlag.nsi
//  tools/TextTool-W32/TextTool.rc
//  win32/VC6/installer.dsp
#ifndef BZ_MAJOR_VERSION
#  define BZ_MAJOR_VERSION	2
#endif

#ifndef BZ_MINOR_VERSION
#  define BZ_MINOR_VERSION	3
#endif

#ifndef BZ_REV
#  define BZ_REV		7
#endif

// DEVEL | RC# | STABLE | MAINT
#ifndef BZ_BUILD_TYPE
#  define BZ_BUILD_TYPE		"DEVEL"
#endif

const char *bzfcopyright = "Copyright (c) 1993-2011 Tim Riker";

//
//  Although the ./configure process will generate
//  -DBZ_BUILD_DATE for the build, here it's voided.
//
//  Could someone explain the reason for the
//  inconvenience caused by the ./configure method? This
//  way is simple, touch the *.cxx to get a new time
//  stamp (no big recompiles). If this file is updated,
//  you are also forced to get a new timestamp.
//
//  Using __DATE__ for all OSes is more consistent.
//
#undef BZ_BUILD_DATE

#ifndef BZ_BUILD_DATE
/* to get the version in the right format YYYYMMDD */
/* yes this is horible but it needs to be done to get it right */
/* windows should pull from a resouce */
/* *nix gets this from the passed from my the Makefile */
char buildDate[] = {__DATE__};

int getBuildDate()
{
  int year = 1900, month = 0, day = 0;
  char monthStr[512];
  sscanf(buildDate, "%s %d %d", monthStr, &day, &year);

  // we want it not as a name but a number
  if (strcmp(monthStr, "Jan") == 0)
    month = 1;
  else if (strcmp(monthStr, "Feb") == 0)
    month = 2;
  else if (strcmp(monthStr, "Mar") == 0)
    month = 3;
  else if (strcmp(monthStr, "Apr") == 0)
    month = 4;
  else if (strcmp(monthStr, "May") == 0)
    month = 5;
  else if (strcmp(monthStr, "Jun") == 0)
    month = 6;
  else if (strcmp(monthStr, "Jul") == 0)
    month = 7;
  else if (strcmp(monthStr, "Aug") == 0)
    month = 8;
  else if (strcmp(monthStr, "Sep") == 0)
    month = 9;
  else if (strcmp(monthStr, "Oct") == 0)
    month = 10;
  else if (strcmp(monthStr, "Nov") == 0)
    month = 11;
  else if (strcmp(monthStr, "Dec") == 0)
    month = 12;

  return (year*10000) + (month*100)+ day;
}
#endif
// down here so above gets created
#include "version.h"

const char*		getProtocolVersion()
{
  static std::string protVersion = BZ_PROTO_VERSION;
  return protVersion.c_str();
}

const char*		getServerVersion()
{
  static std::string serverVersion = std::string("BZFS") + getProtocolVersion();
  return serverVersion.c_str();
}

const char*		getMajorMinorVersion()
{
  static std::string	version = "";
  if (!version.size()){
    std::ostringstream	versionStream;
    versionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION;
    version = versionStream.str();
  }
  return version.c_str();
}

const char*		getMajorMinorRevVersion()
{
  static std::string	version = "";
  if (!version.size()){
    std::ostringstream	versionStream;
    versionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION << "." << BZ_REV;
    version = versionStream.str();
  }
  return version.c_str();
}

const char*		getAppVersion()
{
  static std::string	appVersion = "";
  if (!appVersion.size()){
    std::ostringstream	appVersionStream;
    // TODO add current platform, release, cpu, etc
    appVersionStream << getMajorMinorRevVersion() << "." << BZ_BUILD_DATE
	<< "-" << BZ_BUILD_TYPE << "-" << BZ_BUILD_OS;
#ifdef HAVE_SDL
    appVersionStream << "-SDL";
#endif
    appVersion = appVersionStream.str();
  }
  return appVersion.c_str();
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>increment revision and protocol to be sure everybody's wings acts the same<commit_after>/* bzflag
 * Copyright (c) 1993-2011 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "common.h"

/* system headers */
#include <sstream>
#include <string>
#include <stdio.h>
#include <string.h>

// opaque version number increments on protocol incompatibility
#ifndef BZ_PROTO_VERSION
#  define BZ_PROTO_VERSION	"0208"
#endif

// version numbers - also update as needed:
//  ChangeLog
//  README
//  configure.ac
//  include/version.h
//  package/win32/nsis/BZFlag.nsi
//  tools/TextTool-W32/TextTool.rc
//  win32/VC6/installer.dsp
#ifndef BZ_MAJOR_VERSION
#  define BZ_MAJOR_VERSION	2
#endif

#ifndef BZ_MINOR_VERSION
#  define BZ_MINOR_VERSION	3
#endif

#ifndef BZ_REV
#  define BZ_REV		8
#endif

// DEVEL | RC# | STABLE | MAINT
#ifndef BZ_BUILD_TYPE
#  define BZ_BUILD_TYPE		"DEVEL"
#endif

const char *bzfcopyright = "Copyright (c) 1993-2011 Tim Riker";

//
//  Although the ./configure process will generate
//  -DBZ_BUILD_DATE for the build, here it's voided.
//
//  Could someone explain the reason for the
//  inconvenience caused by the ./configure method? This
//  way is simple, touch the *.cxx to get a new time
//  stamp (no big recompiles). If this file is updated,
//  you are also forced to get a new timestamp.
//
//  Using __DATE__ for all OSes is more consistent.
//
#undef BZ_BUILD_DATE

#ifndef BZ_BUILD_DATE
/* to get the version in the right format YYYYMMDD */
/* yes this is horible but it needs to be done to get it right */
/* windows should pull from a resouce */
/* *nix gets this from the passed from my the Makefile */
char buildDate[] = {__DATE__};

int getBuildDate()
{
  int year = 1900, month = 0, day = 0;
  char monthStr[512];
  sscanf(buildDate, "%s %d %d", monthStr, &day, &year);

  // we want it not as a name but a number
  if (strcmp(monthStr, "Jan") == 0)
    month = 1;
  else if (strcmp(monthStr, "Feb") == 0)
    month = 2;
  else if (strcmp(monthStr, "Mar") == 0)
    month = 3;
  else if (strcmp(monthStr, "Apr") == 0)
    month = 4;
  else if (strcmp(monthStr, "May") == 0)
    month = 5;
  else if (strcmp(monthStr, "Jun") == 0)
    month = 6;
  else if (strcmp(monthStr, "Jul") == 0)
    month = 7;
  else if (strcmp(monthStr, "Aug") == 0)
    month = 8;
  else if (strcmp(monthStr, "Sep") == 0)
    month = 9;
  else if (strcmp(monthStr, "Oct") == 0)
    month = 10;
  else if (strcmp(monthStr, "Nov") == 0)
    month = 11;
  else if (strcmp(monthStr, "Dec") == 0)
    month = 12;

  return (year*10000) + (month*100)+ day;
}
#endif
// down here so above gets created
#include "version.h"

const char*		getProtocolVersion()
{
  static std::string protVersion = BZ_PROTO_VERSION;
  return protVersion.c_str();
}

const char*		getServerVersion()
{
  static std::string serverVersion = std::string("BZFS") + getProtocolVersion();
  return serverVersion.c_str();
}

const char*		getMajorMinorVersion()
{
  static std::string	version = "";
  if (!version.size()){
    std::ostringstream	versionStream;
    versionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION;
    version = versionStream.str();
  }
  return version.c_str();
}

const char*		getMajorMinorRevVersion()
{
  static std::string	version = "";
  if (!version.size()){
    std::ostringstream	versionStream;
    versionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION << "." << BZ_REV;
    version = versionStream.str();
  }
  return version.c_str();
}

const char*		getAppVersion()
{
  static std::string	appVersion = "";
  if (!appVersion.size()){
    std::ostringstream	appVersionStream;
    // TODO add current platform, release, cpu, etc
    appVersionStream << getMajorMinorRevVersion() << "." << BZ_BUILD_DATE
	<< "-" << BZ_BUILD_TYPE << "-" << BZ_BUILD_OS;
#ifdef HAVE_SDL
    appVersionStream << "-SDL";
#endif
    appVersion = appVersionStream.str();
  }
  return appVersion.c_str();
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include "stx/stdtypes.h"
#include "stx/application.h"
#include "stx/logging.h"
#include "stx/cli/flagparser.h"
#include "stx/io/fileutil.h"
#include "stx/http/httprouter.h"
#include "stx/http/httpserver.h"
#include "stx/thread/eventloop.h"
#include "stx/thread/threadpool.h"
#include "docdb/DocumentDB.h"
#include "docdb/DocumentDBServlet.h"
#include "common/AnalyticsAuth.h"

using namespace stx;
using namespace cm;

stx::thread::EventLoop ev;

int main(int argc, const char** argv) {
  stx::Application::init();
  stx::Application::logToStderr();

  stx::cli::FlagParser flags;

  flags.defineFlag(
      "http_port",
      stx::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "7003",
      "Start the public http server on this port",
      "<port>");

  flags.defineFlag(
      "datadir",
      cli::FlagParser::T_STRING,
      true,
      NULL,
      NULL,
      "datadir path",
      "<path>");

  flags.defineFlag(
      "loglevel",
      stx::cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  /* thread pools */
  stx::thread::ThreadPool tpool;

  /* http */
  stx::http::HTTPRouter http_router;
  stx::http::HTTPServer http_server(&http_router, &ev);
  http_server.listen(flags.getInt("http_port"));

  /* auth */
  AnalyticsAuth auth;

  /* DocumentDB */
  DocumentDB docdb(flags.getString("datadir"));
  DocumentDBServlet docdb_servlet(&docdb, &auth);

  http_router.addRouteByPrefixMatch(
      "/analytics/api/v1/documents",
      &docdb_servlet,
      &tpool);

  ev.run();
  stx::logInfo("dxa-docdb", "Exiting...");

  exit(0);
}

<commit_msg>use port 7005 for docdb<commit_after>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include "stx/stdtypes.h"
#include "stx/application.h"
#include "stx/logging.h"
#include "stx/cli/flagparser.h"
#include "stx/io/fileutil.h"
#include "stx/http/httprouter.h"
#include "stx/http/httpserver.h"
#include "stx/thread/eventloop.h"
#include "stx/thread/threadpool.h"
#include "docdb/DocumentDB.h"
#include "docdb/DocumentDBServlet.h"
#include "common/AnalyticsAuth.h"

using namespace stx;
using namespace cm;

stx::thread::EventLoop ev;

int main(int argc, const char** argv) {
  stx::Application::init();
  stx::Application::logToStderr();

  stx::cli::FlagParser flags;

  flags.defineFlag(
      "http_port",
      stx::cli::FlagParser::T_INTEGER,
      false,
      NULL,
      "7005",
      "Start the public http server on this port",
      "<port>");

  flags.defineFlag(
      "datadir",
      cli::FlagParser::T_STRING,
      true,
      NULL,
      NULL,
      "datadir path",
      "<path>");

  flags.defineFlag(
      "loglevel",
      stx::cli::FlagParser::T_STRING,
      false,
      NULL,
      "INFO",
      "loglevel",
      "<level>");

  flags.parseArgv(argc, argv);

  Logger::get()->setMinimumLogLevel(
      strToLogLevel(flags.getString("loglevel")));

  /* thread pools */
  stx::thread::ThreadPool tpool;

  /* http */
  stx::http::HTTPRouter http_router;
  stx::http::HTTPServer http_server(&http_router, &ev);
  http_server.listen(flags.getInt("http_port"));

  /* auth */
  AnalyticsAuth auth;

  /* DocumentDB */
  DocumentDB docdb(flags.getString("datadir"));
  DocumentDBServlet docdb_servlet(&docdb, &auth);

  http_router.addRouteByPrefixMatch(
      "/analytics/api/v1/documents",
      &docdb_servlet,
      &tpool);

  ev.run();
  stx::logInfo("dxa-docdb", "Exiting...");

  exit(0);
}

<|endoftext|>