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

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

//_________________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________________

#include "..\misc\ImplHelper.hxx"

//_________________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________________

#ifndef _CPPUHELPER_SERVICEFACTORY_HXX_
#include <cppuhelper/servicefactory.hxx>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_
#include <com/sun/star/datatransfer/XTransferable.hpp>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDOWNER_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardOwner.hpp>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDNOTIFIER_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardNotifier.hpp>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDEX_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardEx.hpp>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XFLUSHABLECLIPBOARD_HPP_
#include <com/sun/star/datatransfer/clipboard/XFlushableClipboard.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#include <stdio.h>
#if defined _MSC_VER
#pragma warning(push,1)
#endif
#include <windows.h>
#include <objbase.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif

#include <memory>

#include <process.h>

//-------------------------------------------------------------
// my defines
//-------------------------------------------------------------

#define TEST_CLIPBOARD
#define RDB_SYSPATH  "d:\\projects\\src623\\dtrans\\wntmsci7\\bin\\applicat.rdb"
#define WINCLIPBOARD_SERVICE_NAME L"com.sun.star.datatransfer.clipboard.SystemClipboard"
#define  WRITE_CB
#define EVT_MANUAL_RESET     TRUE
#define EVT_INIT_NONSIGNALED FALSE
#define EVT_NONAME           ""

//------------------------------------------------------------
//  namesapces
//------------------------------------------------------------

using namespace ::rtl;
using namespace ::std;
using namespace ::cppu;
using namespace ::com::sun::star::datatransfer;
using namespace ::com::sun::star::datatransfer::clipboard;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;

//------------------------------------------------------------
//  globales
//------------------------------------------------------------

Reference< XTransferable > rXTransfRead;
HANDLE  g_hEvtThreadWakeup;

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

class CClipboardListener : public WeakImplHelper1 < XClipboardListener >
{
public:
    ~CClipboardListener( );

    //-------------------------------------------------
    // XClipboardListener
    //-------------------------------------------------

    virtual void SAL_CALL disposing( const EventObject& Source ) throw(RuntimeException);
    virtual void SAL_CALL changedContents( const ClipboardEvent& event ) throw( RuntimeException );
};

CClipboardListener::~CClipboardListener( )
{
}

void SAL_CALL CClipboardListener::disposing( const EventObject& Source ) throw(RuntimeException)
{

}

void SAL_CALL CClipboardListener::changedContents( const ClipboardEvent& event ) throw( RuntimeException )
{
    //MessageBox( NULL, TEXT("Clipboard content changed"), TEXT("Info"), MB_OK | MB_ICONINFORMATION );
}

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

class CTransferable : public WeakImplHelper2< XClipboardOwner, XTransferable >
{
public:
    CTransferable( );

    //-------------------------------------------------
    // XTransferable
    //-------------------------------------------------

    virtual Any SAL_CALL getTransferData( const DataFlavor& aFlavor )
        throw(UnsupportedFlavorException, IOException, RuntimeException);

    virtual Sequence< DataFlavor > SAL_CALL getTransferDataFlavors(  ) throw(RuntimeException);

    virtual sal_Bool SAL_CALL isDataFlavorSupported( const DataFlavor& aFlavor ) throw(RuntimeException);

    //-------------------------------------------------
    // XClipboardOwner
    //-------------------------------------------------

    virtual void SAL_CALL lostOwnership( const Reference< XClipboard >& xClipboard, const Reference< XTransferable >& xTrans )
        throw(RuntimeException);

private:
    Sequence< DataFlavor > m_FlavorList;
    OUString               m_Data;
};

//----------------------------------------------------------------
//  ctor
//----------------------------------------------------------------

CTransferable::CTransferable( ) :
    m_FlavorList( 1 ),
    m_Data( OUString::createFromAscii( "Ich habe mir ein neues Fahrrad gekauft!" ) )
{
    DataFlavor df;

    //df.MimeType = L"text/plain;charset=utf-16";
    //df.DataType = getCppuType( ( OUString* )0 );

    df.MimeType = L"text/plain;charset=Windows1252";
    df.DataType = getCppuType( (Sequence< sal_Int8 >*)0 );

    m_FlavorList[0] = df;
}

//----------------------------------------------------------------
//  getTransferData
//----------------------------------------------------------------

Any SAL_CALL CTransferable::getTransferData( const DataFlavor& aFlavor )
    throw(UnsupportedFlavorException, IOException, RuntimeException)
{
    Any anyData;

    /*
    if ( aFlavor.MimeType == m_FlavorList[0].MimeType )
        anyData = makeAny( m_Data );
    */
    if ( aFlavor.MimeType.equalsIgnoreCase( m_FlavorList[0].MimeType ) )
    {
        OString text(
            m_Data.getStr( ),
            m_Data.getLength( ),
            RTL_TEXTENCODING_ASCII_US );

        Sequence< sal_Int8 > textStream( text.getLength( ) + 1 );

        rtl_copyMemory( textStream.getArray( ), text.getStr( ), textStream.getLength( ) );

        anyData = makeAny( textStream );
    }
    else
        throw UnsupportedFlavorException( );

    return anyData;
}

//----------------------------------------------------------------
//  getTransferDataFlavors
//----------------------------------------------------------------

Sequence< DataFlavor > SAL_CALL CTransferable::getTransferDataFlavors(  )
    throw(RuntimeException)
{
    return m_FlavorList;
}

//----------------------------------------------------------------
//  isDataFlavorSupported
//----------------------------------------------------------------

sal_Bool SAL_CALL CTransferable::isDataFlavorSupported( const DataFlavor& aFlavor )
    throw(RuntimeException)
{
    sal_Int32 nLength = m_FlavorList.getLength( );

    for ( sal_Int32 i = 0; i < nLength; ++i )
        if ( m_FlavorList[i].MimeType == aFlavor.MimeType )
            return sal_True;

    return sal_False;
}

//----------------------------------------------------------------
//  lostOwnership
//----------------------------------------------------------------

void SAL_CALL CTransferable::lostOwnership(
    const Reference< XClipboard >& xClipboard, const Reference< XTransferable >& xTrans )
    throw(RuntimeException)
{
    //MessageBox( NULL, TEXT("No longer clipboard owner"), TEXT("Info"), MB_OK | MB_ICONINFORMATION );
}

//----------------------------------------------------------------
//  main
//----------------------------------------------------------------

int SAL_CALL main( int nArgc, char* Argv[] )
{
    // create a multi-threaded apartment; we can test only
    // with a multithreaded apartment because for a single
    // threaded apartment we need a message loop to deliver
    // messages to our XTDataObject
    //HRESULT hr = CoInitializeEx( NULL, COINIT_MULTITHREADED );
    HRESULT hr = CoInitialize( NULL );

    char buff[6];

    LCID lcid = MAKELCID( MAKELANGID( LANG_GERMAN, SUBLANG_GERMAN ), SORT_DEFAULT );

    BOOL bValid = IsValidLocale( lcid, LCID_SUPPORTED );
    GetLocaleInfoA( lcid, LOCALE_IDEFAULTANSICODEPAGE, buff, sizeof( buff ) );

    //-------------------------------------------------
    // get the global service-manager
    //-------------------------------------------------

    OUString rdbName = OUString( RTL_CONSTASCII_USTRINGPARAM( RDB_SYSPATH ) );
    Reference< XMultiServiceFactory > g_xFactory( createRegistryServiceFactory( rdbName ) );

    // Print a message if an error occured.
    if ( !g_xFactory.is( ) )
    {
        OSL_ENSURE(sal_False, "Can't create RegistryServiceFactory");
        return(-1);
    }

    //-------------------------------------------------
    // try to get an Interface to a XFilePicker Service
    //-------------------------------------------------

    Reference< XTransferable > rXTransf( static_cast< XTransferable* >( new CTransferable ) );

    Reference< XClipboard >
        xClipboard( g_xFactory->createInstance( OUString( WINCLIPBOARD_SERVICE_NAME ) ), UNO_QUERY );
    if ( !xClipboard.is( ) )
    {
        OSL_ENSURE( sal_False, "Error creating Clipboard Service" );
        return(-1);
    }

    Reference< XClipboardNotifier > xClipNotifier( xClipboard, UNO_QUERY );
    Reference< XClipboardListener > rXClipListener( static_cast< XClipboardListener* >( new CClipboardListener() ) );
    xClipNotifier->addClipboardListener( rXClipListener );

    MessageBox( NULL, TEXT("Go"), TEXT("INFO"), MB_OK|MB_ICONINFORMATION);

    // set new clipboard content
    xClipboard->setContents( rXTransf, Reference< XClipboardOwner >( rXTransf, UNO_QUERY )  );

    /*
    MessageBox( NULL, TEXT("Clear content"), TEXT("INFO"), MB_OK|MB_ICONINFORMATION);

    Reference< XClipboardOwner > rXClipOwner;
    Reference< XTransferable >   rXEmptyTransf;
    xClipboard->setContents( rXEmptyTransf, rXClipOwner );
    */

    MessageBox( NULL, TEXT("Stop"), TEXT("INFO"), MB_OK|MB_ICONINFORMATION);

    // flush the clipboard content
    Reference< XFlushableClipboard > rXFlushableClip( xClipboard, UNO_QUERY );
    rXFlushableClip->flushClipboard( );
    rXFlushableClip = Reference< XFlushableClipboard >( );

    xClipNotifier->removeClipboardListener( rXClipListener );
    rXClipListener = Reference< XClipboardListener >( );
    xClipNotifier  = Reference< XClipboardNotifier >( );

    //--------------------------------------------------
    // shutdown the service manager
    //--------------------------------------------------

    // Cast factory to XComponent
    Reference< XComponent > xComponent( g_xFactory, UNO_QUERY );

    if ( !xComponent.is() )
        OSL_ENSURE(sal_False, "Error shuting down");

    // Dispose and clear factory
    xComponent->dispose();
    xComponent = Reference< XComponent >( );

    g_xFactory.clear();
    g_xFactory = Reference< XMultiServiceFactory >();

    CoUninitialize( );

    return 0;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.11.48); FILE MERGED 2008/04/01 15:13:37 thb 1.11.48.3: #i85898# Stripping all external header guards 2008/04/01 12:28:35 thb 1.11.48.2: #i85898# Stripping all external header guards 2008/03/31 13:09:04 rt 1.11.48.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: test_wincb.cxx,v $
 * $Revision: 1.12 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

//_________________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________________

#include "..\misc\ImplHelper.hxx"

//_________________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________________
#include <cppuhelper/servicefactory.hxx>
#include <com/sun/star/datatransfer/XTransferable.hpp>
#include <com/sun/star/datatransfer/clipboard/XClipboardOwner.hpp>
#include <com/sun/star/datatransfer/clipboard/XClipboardNotifier.hpp>
#include <com/sun/star/datatransfer/clipboard/XClipboardEx.hpp>
#include <com/sun/star/datatransfer/clipboard/XFlushableClipboard.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <cppuhelper/implbase1.hxx>
#include <cppuhelper/implbase2.hxx>
#include <rtl/ustring.hxx>
#include <sal/types.h>
#include <osl/diagnose.h>

#include <stdio.h>
#if defined _MSC_VER
#pragma warning(push,1)
#endif
#include <windows.h>
#include <objbase.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif

#include <memory>

#include <process.h>

//-------------------------------------------------------------
// my defines
//-------------------------------------------------------------

#define TEST_CLIPBOARD
#define RDB_SYSPATH  "d:\\projects\\src623\\dtrans\\wntmsci7\\bin\\applicat.rdb"
#define WINCLIPBOARD_SERVICE_NAME L"com.sun.star.datatransfer.clipboard.SystemClipboard"
#define  WRITE_CB
#define EVT_MANUAL_RESET     TRUE
#define EVT_INIT_NONSIGNALED FALSE
#define EVT_NONAME           ""

//------------------------------------------------------------
//  namesapces
//------------------------------------------------------------

using namespace ::rtl;
using namespace ::std;
using namespace ::cppu;
using namespace ::com::sun::star::datatransfer;
using namespace ::com::sun::star::datatransfer::clipboard;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;

//------------------------------------------------------------
//  globales
//------------------------------------------------------------

Reference< XTransferable > rXTransfRead;
HANDLE  g_hEvtThreadWakeup;

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

class CClipboardListener : public WeakImplHelper1 < XClipboardListener >
{
public:
    ~CClipboardListener( );

    //-------------------------------------------------
    // XClipboardListener
    //-------------------------------------------------

    virtual void SAL_CALL disposing( const EventObject& Source ) throw(RuntimeException);
    virtual void SAL_CALL changedContents( const ClipboardEvent& event ) throw( RuntimeException );
};

CClipboardListener::~CClipboardListener( )
{
}

void SAL_CALL CClipboardListener::disposing( const EventObject& Source ) throw(RuntimeException)
{

}

void SAL_CALL CClipboardListener::changedContents( const ClipboardEvent& event ) throw( RuntimeException )
{
    //MessageBox( NULL, TEXT("Clipboard content changed"), TEXT("Info"), MB_OK | MB_ICONINFORMATION );
}

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

class CTransferable : public WeakImplHelper2< XClipboardOwner, XTransferable >
{
public:
    CTransferable( );

    //-------------------------------------------------
    // XTransferable
    //-------------------------------------------------

    virtual Any SAL_CALL getTransferData( const DataFlavor& aFlavor )
        throw(UnsupportedFlavorException, IOException, RuntimeException);

    virtual Sequence< DataFlavor > SAL_CALL getTransferDataFlavors(  ) throw(RuntimeException);

    virtual sal_Bool SAL_CALL isDataFlavorSupported( const DataFlavor& aFlavor ) throw(RuntimeException);

    //-------------------------------------------------
    // XClipboardOwner
    //-------------------------------------------------

    virtual void SAL_CALL lostOwnership( const Reference< XClipboard >& xClipboard, const Reference< XTransferable >& xTrans )
        throw(RuntimeException);

private:
    Sequence< DataFlavor > m_FlavorList;
    OUString               m_Data;
};

//----------------------------------------------------------------
//  ctor
//----------------------------------------------------------------

CTransferable::CTransferable( ) :
    m_FlavorList( 1 ),
    m_Data( OUString::createFromAscii( "Ich habe mir ein neues Fahrrad gekauft!" ) )
{
    DataFlavor df;

    //df.MimeType = L"text/plain;charset=utf-16";
    //df.DataType = getCppuType( ( OUString* )0 );

    df.MimeType = L"text/plain;charset=Windows1252";
    df.DataType = getCppuType( (Sequence< sal_Int8 >*)0 );

    m_FlavorList[0] = df;
}

//----------------------------------------------------------------
//  getTransferData
//----------------------------------------------------------------

Any SAL_CALL CTransferable::getTransferData( const DataFlavor& aFlavor )
    throw(UnsupportedFlavorException, IOException, RuntimeException)
{
    Any anyData;

    /*
    if ( aFlavor.MimeType == m_FlavorList[0].MimeType )
        anyData = makeAny( m_Data );
    */
    if ( aFlavor.MimeType.equalsIgnoreCase( m_FlavorList[0].MimeType ) )
    {
        OString text(
            m_Data.getStr( ),
            m_Data.getLength( ),
            RTL_TEXTENCODING_ASCII_US );

        Sequence< sal_Int8 > textStream( text.getLength( ) + 1 );

        rtl_copyMemory( textStream.getArray( ), text.getStr( ), textStream.getLength( ) );

        anyData = makeAny( textStream );
    }
    else
        throw UnsupportedFlavorException( );

    return anyData;
}

//----------------------------------------------------------------
//  getTransferDataFlavors
//----------------------------------------------------------------

Sequence< DataFlavor > SAL_CALL CTransferable::getTransferDataFlavors(  )
    throw(RuntimeException)
{
    return m_FlavorList;
}

//----------------------------------------------------------------
//  isDataFlavorSupported
//----------------------------------------------------------------

sal_Bool SAL_CALL CTransferable::isDataFlavorSupported( const DataFlavor& aFlavor )
    throw(RuntimeException)
{
    sal_Int32 nLength = m_FlavorList.getLength( );

    for ( sal_Int32 i = 0; i < nLength; ++i )
        if ( m_FlavorList[i].MimeType == aFlavor.MimeType )
            return sal_True;

    return sal_False;
}

//----------------------------------------------------------------
//  lostOwnership
//----------------------------------------------------------------

void SAL_CALL CTransferable::lostOwnership(
    const Reference< XClipboard >& xClipboard, const Reference< XTransferable >& xTrans )
    throw(RuntimeException)
{
    //MessageBox( NULL, TEXT("No longer clipboard owner"), TEXT("Info"), MB_OK | MB_ICONINFORMATION );
}

//----------------------------------------------------------------
//  main
//----------------------------------------------------------------

int SAL_CALL main( int nArgc, char* Argv[] )
{
    // create a multi-threaded apartment; we can test only
    // with a multithreaded apartment because for a single
    // threaded apartment we need a message loop to deliver
    // messages to our XTDataObject
    //HRESULT hr = CoInitializeEx( NULL, COINIT_MULTITHREADED );
    HRESULT hr = CoInitialize( NULL );

    char buff[6];

    LCID lcid = MAKELCID( MAKELANGID( LANG_GERMAN, SUBLANG_GERMAN ), SORT_DEFAULT );

    BOOL bValid = IsValidLocale( lcid, LCID_SUPPORTED );
    GetLocaleInfoA( lcid, LOCALE_IDEFAULTANSICODEPAGE, buff, sizeof( buff ) );

    //-------------------------------------------------
    // get the global service-manager
    //-------------------------------------------------

    OUString rdbName = OUString( RTL_CONSTASCII_USTRINGPARAM( RDB_SYSPATH ) );
    Reference< XMultiServiceFactory > g_xFactory( createRegistryServiceFactory( rdbName ) );

    // Print a message if an error occured.
    if ( !g_xFactory.is( ) )
    {
        OSL_ENSURE(sal_False, "Can't create RegistryServiceFactory");
        return(-1);
    }

    //-------------------------------------------------
    // try to get an Interface to a XFilePicker Service
    //-------------------------------------------------

    Reference< XTransferable > rXTransf( static_cast< XTransferable* >( new CTransferable ) );

    Reference< XClipboard >
        xClipboard( g_xFactory->createInstance( OUString( WINCLIPBOARD_SERVICE_NAME ) ), UNO_QUERY );
    if ( !xClipboard.is( ) )
    {
        OSL_ENSURE( sal_False, "Error creating Clipboard Service" );
        return(-1);
    }

    Reference< XClipboardNotifier > xClipNotifier( xClipboard, UNO_QUERY );
    Reference< XClipboardListener > rXClipListener( static_cast< XClipboardListener* >( new CClipboardListener() ) );
    xClipNotifier->addClipboardListener( rXClipListener );

    MessageBox( NULL, TEXT("Go"), TEXT("INFO"), MB_OK|MB_ICONINFORMATION);

    // set new clipboard content
    xClipboard->setContents( rXTransf, Reference< XClipboardOwner >( rXTransf, UNO_QUERY )  );

    /*
    MessageBox( NULL, TEXT("Clear content"), TEXT("INFO"), MB_OK|MB_ICONINFORMATION);

    Reference< XClipboardOwner > rXClipOwner;
    Reference< XTransferable >   rXEmptyTransf;
    xClipboard->setContents( rXEmptyTransf, rXClipOwner );
    */

    MessageBox( NULL, TEXT("Stop"), TEXT("INFO"), MB_OK|MB_ICONINFORMATION);

    // flush the clipboard content
    Reference< XFlushableClipboard > rXFlushableClip( xClipboard, UNO_QUERY );
    rXFlushableClip->flushClipboard( );
    rXFlushableClip = Reference< XFlushableClipboard >( );

    xClipNotifier->removeClipboardListener( rXClipListener );
    rXClipListener = Reference< XClipboardListener >( );
    xClipNotifier  = Reference< XClipboardNotifier >( );

    //--------------------------------------------------
    // shutdown the service manager
    //--------------------------------------------------

    // Cast factory to XComponent
    Reference< XComponent > xComponent( g_xFactory, UNO_QUERY );

    if ( !xComponent.is() )
        OSL_ENSURE(sal_False, "Error shuting down");

    // Dispose and clear factory
    xComponent->dispose();
    xComponent = Reference< XComponent >( );

    g_xFactory.clear();
    g_xFactory = Reference< XMultiServiceFactory >();

    CoUninitialize( );

    return 0;
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <string>
#include <regex>
#include <fstream>
#include <sys/stat.h>
#include <unistd.h>
#include <execinfo.h>
// http://tclap.sourceforge.net/manual.html
#include "tclap/CmdLine.h"
#include "HCIDumpParser.h"
#include "MsgPublisherTypeConstraint.h"
#include "LcdDisplayTypeConstraint.h"
#include "MockScannerView.h"
#include "BeaconMapper.h"
#include "../lcd/AbstractLcdView.h"
#include "PropertiesMapper.h"

static HCIDumpParser parserLogic;

#define STOP_MARKER_FILE "/var/run/scannerd.STOP"

inline bool stopMarkerExists() {
    struct stat buffer;
    bool stop = (stat (STOP_MARKER_FILE, &buffer) == 0);
    if(stop) {
        printf("Found STOP marker file, will exit...\n");
        fflush(stdout);
    }
    return stop;
}
static long eventCount = 0;
static long maxEventCount = 0;
static int64_t lastMarkerCheckTime = 0;

/**
* Callback invoked by the hdidumpinternal.c code when a LE_ADVERTISING_REPORT event is seen on the stack
*/
extern "C" bool beacon_event_callback(beacon_info * info) {
#if PRINT_DEBUG
    printf("beacon_event_callback(%ld: %s, code=%d, time=%lld)\n", eventCount, info->uuid, info->code, info->time);
#endif
    parserLogic.beaconEvent(*info);
    eventCount ++;
    // Check for a termination marker every 1000 events or 5 seconds
    bool stop = false;
    int64_t elapsed = info->time - lastMarkerCheckTime;
    if((eventCount % 1000) == 0 || elapsed > 5000) {
        lastMarkerCheckTime = info->time;
        stop = stopMarkerExists();
        printf("beacon_event_callback, status eventCount=%ld, stop=%d\n", eventCount, stop);
        fflush(stdout);
    }
    // Check max event count limit
    if(maxEventCount > 0 && eventCount >= maxEventCount)
        stop = true;
    return stop;
}

using namespace std;

static ScannerView *getDisplayInstance(LcdDisplayType type) {
    ScannerView *view = nullptr;
#ifdef HAVE_LCD_DISPLAY
    AbstractLcdView *lcd = AbstractLcdView::getLcdDisplayInstance(type);
    lcd->init();
    lcd->clear();
    view = lcd;
#else
    view = new MockScannerView();
#endif
    return view;
}

void printStacktrace() {
    void *array[20];
    int size = backtrace(array, sizeof(array) / sizeof(array[0]));
    backtrace_symbols_fd(array, size, STDERR_FILENO);
}

static void terminateHandler() {
    std::exception_ptr exptr = std::current_exception();
    if (exptr != nullptr) {
        // the only useful feature of std::exception_ptr is that it can be rethrown...
        try {
            std::rethrow_exception(exptr);
        } catch (std::exception &ex) {
            std::fprintf(stderr, "Terminated due to exception: %s\n", ex.what());
        }
        catch (...) {
            std::fprintf(stderr, "Terminated due to unknown exception\n");
        }
    }
    else {
        std::fprintf(stderr, "Terminated due to unknown reason :(\n");
    }
    printStacktrace();
    exit(100);
}

/**
* A version of the native scanner that directly integrates with the bluez stack hcidump command rather than parsing
* the hcidump output.
*/
int main(int argc, const char **argv) {

    printf("NativeScanner starting up...\n");
    for(int n = 0; n < argc; n ++) {
        printf("    argv[%d] = %s\n", n, argv[n]);
    }
    fflush(stdout);
    TCLAP::CmdLine cmd("NativeScanner command line options", ' ', "0.1");
    //
    TCLAP::ValueArg<std::string> scannerID("s", "scannerID",
            "Specify the ID of the scanner reading the beacon events. If this is a string with a comma separated list of names, the scanner will cycle through them.",
            true, "DEFAULT", "string", cmd);
    TCLAP::ValueArg<std::string> heartbeatUUID("H", "heartbeatUUID",
            "Specify the UUID of the beacon used to signal the scanner heartbeat event",
            false, "DEFAULT", "string", cmd);
    TCLAP::ValueArg<std::string> rawDumpFile("d", "rawDumpFile",
            "Specify a path to an hcidump file to parse for testing",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> clientID("c", "clientID",
            "Specify the clientID to connect to the MQTT broker with",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> username("u", "username",
            "Specify the username to connect to the MQTT broker with",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> password("p", "password",
            "Specify the password to connect to the MQTT broker with",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> brokerURL("b", "brokerURL",
            "Specify the brokerURL to connect to the message broker with; default tcp://localhost:5672",
            false, "tcp://localhost:5672", "string", cmd);
    TCLAP::ValueArg<std::string> destinationName("t", "destinationName",
            "Specify the name of the destination on the message broker to publish to; default beaconEvents",
            false, "beaconEvents", "string", cmd);
    TCLAP::ValueArg<int> analyzeWindow("W", "analyzeWindow",
            "Specify the number of seconds in the analyzeMode time window",
            false, 1, "int", cmd);
    TCLAP::ValueArg<std::string> hciDev("D", "hciDev",
            "Specify the name of the host controller interface to use; default hci0",
            false, "hci0", "string", cmd);
    TCLAP::ValueArg<std::string> bcastAddress("", "bcastAddress",
                                              "Address to broadcast scanner status to as backup to statusQueue if non-empty; default empty",
                                              false, "", "string", cmd);
    TCLAP::ValueArg<int> bcastPort("", "bcastPort",
                                              "Port to broadcast scanner status to as backup to statusQueue if non-empty; default empty",
                                              false, 12345, "int", cmd);
    MsgPublisherTypeConstraint pubTypeConstraint;
    TCLAP::ValueArg<std::string> pubType("P", "pubType",
            "Specify the MsgPublisherType enum for the publisher implementation to use; default AMQP_QPID",
            false, "AMQP_QPID", &pubTypeConstraint, cmd, nullptr);
    LcdDisplayTypeConstraint lcdTypeConstraint;
    TCLAP::ValueArg<std::string> lcdType("", "lcdType",
             "Specify the LcdDisplayType enum for the LCD implementation to use; default PCD8544",
             false, "PCD8544", &lcdTypeConstraint, cmd, nullptr);

    TCLAP::ValueArg<int> maxCount("C", "maxCount",
            "Specify a maxium number of events the scanner should process before exiting; default 0 means no limit",
            false, 0, "int", cmd);
    TCLAP::ValueArg<int> batchCount("B", "batchCount",
            "Specify a maxium number of events the scanner should combine before sending to broker; default 0 means no batching",
            false, 0, "int", cmd);
    TCLAP::ValueArg<int> statusInterval("I", "statusInterval",
            "Specify the interval in seconds between health status messages, <= 0 means no messages; default 30",
            false, 30, "int", cmd);
    TCLAP::ValueArg<int> rebootAfterNoReply("r", "rebootAfterNoReply",
            "Specify the interval in seconds after which a failure to hear our own heartbeat triggers a reboot, <= 0 means no reboot; default -1",
            false, -1, "int", cmd);
    TCLAP::ValueArg<std::string> statusQueue("q", "statusQueue",
            "Specify the name of the status health queue destination; default scannerHealth",
            false, "scannerHealth", "string", cmd);
    TCLAP::ValueArg<std::string> beaconMapping("", "beaconMapping",
                                             "Specify the source of the beacon id to user name mapping. The following formats are understood:",
                                             false, "", "string", cmd);
    TCLAP::SwitchArg skipPublish("S", "skipPublish",
            "Indicate that the parsed beacons should not be published",
            false);
    TCLAP::SwitchArg asyncMode("A", "asyncMode",
            "Indicate that the parsed beacons should be published using async delivery mode",
            false);
    TCLAP::SwitchArg useQueues("Q", "useQueues",
            "Indicate that the destination type is a queue. If not given the default type is a topic.",
            false);
    TCLAP::SwitchArg skipHeartbeat("K", "skipHeartbeat",
            "Don't publish the heartbeat messages. Useful to limit the noise when testing the scanner.",
            false);
    TCLAP::SwitchArg analzyeMode("", "analzyeMode",
            "Run the scanner in a mode that simply collects beacon readings and reports unique beacons seen in a time window",
             false);
    TCLAP::SwitchArg generateTestData("T", "generateTestData",
             "Indicate that test data should be generated",
             false);
    TCLAP::SwitchArg noBrokerReconnect("", "noBrokerReconnect",
             "Don't try to reconnect to the broker on failure, just exit",
             false);
    TCLAP::SwitchArg skipScannerView("", "skipScannerView",
              "Skip the scanner view display of closest beacon",
              false);
    TCLAP::SwitchArg  batteryTestMode("", "batteryTestMode",
                                     "Simply monitor the raw heartbeat beacon events and publish them to the destinationName",
                                     false);
    try {
        // Add the flag arguments
        cmd.add(skipPublish);
        cmd.add(asyncMode);
        cmd.add(useQueues);
        cmd.add(skipHeartbeat);
        cmd.add(analzyeMode);
        cmd.add(generateTestData);
        cmd.add(noBrokerReconnect);
        cmd.add(batteryTestMode);
        cmd.add(skipScannerView);
        // Parse the argv array.
        printf("Parsing command line...\n");
        cmd.parse( argc, argv );
        printf("done\n");
    }
    catch (TCLAP::ArgException &e) {
        fprintf(stderr, "error: %s for arg: %s\n", e.error().c_str(), e.argId().c_str());
    }

    // Remove any stop marker file
    if(remove(STOP_MARKER_FILE) == 0) {
        printf("Removed existing %s marker file\n", STOP_MARKER_FILE);
    }

    // Validate the system time as unless the network time has syncd, just exit to wait for it to happen
    int64_t nowMS = EventsWindow::currentMilliseconds();
    // 1434954728562 = 2015-06-21 23:32:08.562
    if(nowMS < 1434954728562) {
        fprintf(stderr, "currentMilliseconds(%ld) < 1434954728562 = 2015-06-21 23:32:08.562", nowMS);
        exit(1);
    }

    // If scannerID is the string {IP}, replace it with the host IP address
    string scannerIDValue = scannerID.getValue();
    if(scannerIDValue.compare("{IP}") == 0) {
        char hostIPAddress[128];
        char macaddr[32];
        HealthStatus::getHostInfo(hostIPAddress, macaddr);
        scannerIDValue = hostIPAddress;
    }
    HCIDumpCommand command(scannerIDValue, brokerURL.getValue(), clientID.getValue(), destinationName.getValue());
    command.setUseQueues(useQueues.getValue());
    command.setSkipPublish(skipPublish.getValue());
    command.setSkipHeartbeat(skipHeartbeat.getValue());
    command.setHciDev(hciDev.getValue());
    command.setAsyncMode(asyncMode.getValue());
    command.setAnalyzeMode(analzyeMode.getValue());
    command.setAnalyzeWindow(analyzeWindow.getValue());
    command.setPubType(pubTypeConstraint.toType(pubType.getValue()));
    command.setStatusInterval(statusInterval.getValue());
    command.setStatusQueue(statusQueue.getValue());
    command.setGenerateTestData(generateTestData.getValue());
    command.setBatteryTestMode(batteryTestMode.getValue());
    command.setUsername(username.getValue());
    command.setPassword(password.getValue());
    command.setBcastAddress(bcastAddress.getValue());
    command.setBcastPort(bcastPort.getValue());
    if(maxCount.getValue() > 0) {
        maxEventCount = maxCount.getValue();
        printf("Set maxEventCount: %ld\n", maxEventCount);
    }
    parserLogic.setBatchCount(batchCount.getValue());
    if(heartbeatUUID.isSet()) {
        parserLogic.setScannerUUID(heartbeatUUID.getValue());
        printf("Set heartbeatUUID: %s\n", heartbeatUUID.getValue().c_str());
    }

    // Install default terminate handler to make sure we exit with non-zero status
    std::set_terminate(terminateHandler);

    // Create a beacon mapping instance
    shared_ptr<AbstractBeaconMapper> beaconMapper(new AbstractBeaconMapper());
    if(beaconMapping.isSet()) {
        const string& mapping = beaconMapping.getValue();
        string filePrefix("file:");
        if(!mapping.compare(0, filePrefix.size(), filePrefix)) {
            // TODO
            printf("file: beaconMapper not implemented yet\n");
        } else {
            // The value is a series of id1=userid1,id2=userid2,... values
            beaconMapper.reset(new PropertiesMapper(mapping));
            printf("Loaded beacon mappings: \n", mapping.c_str());
        }
    }

    if(!skipScannerView.getValue()) {
        // Get the scanner view implementation
        LcdDisplayType type = lcdTypeConstraint.toType(lcdType.getValue());
        if(type == LcdDisplayType::INVALID_LCD_TYPE) {
            fprintf(stderr, "Skipping scanner view due to invalid LcdDisplayType. No mapping for: %s\n", lcdType.getValue().c_str());
        } else {
            printf("Using LCD type=%s\n",  lcdType.getValue().c_str());
            shared_ptr<ScannerView> lcd(getDisplayInstance(type));
            // Set the scanner view display's beacon mapper to display the minorID to name correctly
            lcd->setBeaconMapper(beaconMapper);
            parserLogic.setScannerView(lcd);
        }
    }

    char cwd[256];
    getcwd(cwd, sizeof(cwd));
    printf("Begin scanning, cwd=%s...\n", cwd);
    fflush(stdout);
    parserLogic.processHCI(command);
    parserLogic.cleanup();
    printf("End scanning\n");
    fflush(stdout);
    return 0;
}
<commit_msg>log the mapping string<commit_after>#include <cstdio>
#include <string>
#include <regex>
#include <fstream>
#include <sys/stat.h>
#include <unistd.h>
#include <execinfo.h>
// http://tclap.sourceforge.net/manual.html
#include "tclap/CmdLine.h"
#include "HCIDumpParser.h"
#include "MsgPublisherTypeConstraint.h"
#include "LcdDisplayTypeConstraint.h"
#include "MockScannerView.h"
#include "BeaconMapper.h"
#include "../lcd/AbstractLcdView.h"
#include "PropertiesMapper.h"

static HCIDumpParser parserLogic;

#define STOP_MARKER_FILE "/var/run/scannerd.STOP"

inline bool stopMarkerExists() {
    struct stat buffer;
    bool stop = (stat (STOP_MARKER_FILE, &buffer) == 0);
    if(stop) {
        printf("Found STOP marker file, will exit...\n");
        fflush(stdout);
    }
    return stop;
}
static long eventCount = 0;
static long maxEventCount = 0;
static int64_t lastMarkerCheckTime = 0;

/**
* Callback invoked by the hdidumpinternal.c code when a LE_ADVERTISING_REPORT event is seen on the stack
*/
extern "C" bool beacon_event_callback(beacon_info * info) {
#if PRINT_DEBUG
    printf("beacon_event_callback(%ld: %s, code=%d, time=%lld)\n", eventCount, info->uuid, info->code, info->time);
#endif
    parserLogic.beaconEvent(*info);
    eventCount ++;
    // Check for a termination marker every 1000 events or 5 seconds
    bool stop = false;
    int64_t elapsed = info->time - lastMarkerCheckTime;
    if((eventCount % 1000) == 0 || elapsed > 5000) {
        lastMarkerCheckTime = info->time;
        stop = stopMarkerExists();
        printf("beacon_event_callback, status eventCount=%ld, stop=%d\n", eventCount, stop);
        fflush(stdout);
    }
    // Check max event count limit
    if(maxEventCount > 0 && eventCount >= maxEventCount)
        stop = true;
    return stop;
}

using namespace std;

static ScannerView *getDisplayInstance(LcdDisplayType type) {
    ScannerView *view = nullptr;
#ifdef HAVE_LCD_DISPLAY
    AbstractLcdView *lcd = AbstractLcdView::getLcdDisplayInstance(type);
    lcd->init();
    lcd->clear();
    view = lcd;
#else
    view = new MockScannerView();
#endif
    return view;
}

void printStacktrace() {
    void *array[20];
    int size = backtrace(array, sizeof(array) / sizeof(array[0]));
    backtrace_symbols_fd(array, size, STDERR_FILENO);
}

static void terminateHandler() {
    std::exception_ptr exptr = std::current_exception();
    if (exptr != nullptr) {
        // the only useful feature of std::exception_ptr is that it can be rethrown...
        try {
            std::rethrow_exception(exptr);
        } catch (std::exception &ex) {
            std::fprintf(stderr, "Terminated due to exception: %s\n", ex.what());
        }
        catch (...) {
            std::fprintf(stderr, "Terminated due to unknown exception\n");
        }
    }
    else {
        std::fprintf(stderr, "Terminated due to unknown reason :(\n");
    }
    printStacktrace();
    exit(100);
}

/**
* A version of the native scanner that directly integrates with the bluez stack hcidump command rather than parsing
* the hcidump output.
*/
int main(int argc, const char **argv) {

    printf("NativeScanner starting up...\n");
    for(int n = 0; n < argc; n ++) {
        printf("    argv[%d] = %s\n", n, argv[n]);
    }
    fflush(stdout);
    TCLAP::CmdLine cmd("NativeScanner command line options", ' ', "0.1");
    //
    TCLAP::ValueArg<std::string> scannerID("s", "scannerID",
            "Specify the ID of the scanner reading the beacon events. If this is a string with a comma separated list of names, the scanner will cycle through them.",
            true, "DEFAULT", "string", cmd);
    TCLAP::ValueArg<std::string> heartbeatUUID("H", "heartbeatUUID",
            "Specify the UUID of the beacon used to signal the scanner heartbeat event",
            false, "DEFAULT", "string", cmd);
    TCLAP::ValueArg<std::string> rawDumpFile("d", "rawDumpFile",
            "Specify a path to an hcidump file to parse for testing",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> clientID("c", "clientID",
            "Specify the clientID to connect to the MQTT broker with",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> username("u", "username",
            "Specify the username to connect to the MQTT broker with",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> password("p", "password",
            "Specify the password to connect to the MQTT broker with",
            false, "", "string", cmd);
    TCLAP::ValueArg<std::string> brokerURL("b", "brokerURL",
            "Specify the brokerURL to connect to the message broker with; default tcp://localhost:5672",
            false, "tcp://localhost:5672", "string", cmd);
    TCLAP::ValueArg<std::string> destinationName("t", "destinationName",
            "Specify the name of the destination on the message broker to publish to; default beaconEvents",
            false, "beaconEvents", "string", cmd);
    TCLAP::ValueArg<int> analyzeWindow("W", "analyzeWindow",
            "Specify the number of seconds in the analyzeMode time window",
            false, 1, "int", cmd);
    TCLAP::ValueArg<std::string> hciDev("D", "hciDev",
            "Specify the name of the host controller interface to use; default hci0",
            false, "hci0", "string", cmd);
    TCLAP::ValueArg<std::string> bcastAddress("", "bcastAddress",
                                              "Address to broadcast scanner status to as backup to statusQueue if non-empty; default empty",
                                              false, "", "string", cmd);
    TCLAP::ValueArg<int> bcastPort("", "bcastPort",
                                              "Port to broadcast scanner status to as backup to statusQueue if non-empty; default empty",
                                              false, 12345, "int", cmd);
    MsgPublisherTypeConstraint pubTypeConstraint;
    TCLAP::ValueArg<std::string> pubType("P", "pubType",
            "Specify the MsgPublisherType enum for the publisher implementation to use; default AMQP_QPID",
            false, "AMQP_QPID", &pubTypeConstraint, cmd, nullptr);
    LcdDisplayTypeConstraint lcdTypeConstraint;
    TCLAP::ValueArg<std::string> lcdType("", "lcdType",
             "Specify the LcdDisplayType enum for the LCD implementation to use; default PCD8544",
             false, "PCD8544", &lcdTypeConstraint, cmd, nullptr);

    TCLAP::ValueArg<int> maxCount("C", "maxCount",
            "Specify a maxium number of events the scanner should process before exiting; default 0 means no limit",
            false, 0, "int", cmd);
    TCLAP::ValueArg<int> batchCount("B", "batchCount",
            "Specify a maxium number of events the scanner should combine before sending to broker; default 0 means no batching",
            false, 0, "int", cmd);
    TCLAP::ValueArg<int> statusInterval("I", "statusInterval",
            "Specify the interval in seconds between health status messages, <= 0 means no messages; default 30",
            false, 30, "int", cmd);
    TCLAP::ValueArg<int> rebootAfterNoReply("r", "rebootAfterNoReply",
            "Specify the interval in seconds after which a failure to hear our own heartbeat triggers a reboot, <= 0 means no reboot; default -1",
            false, -1, "int", cmd);
    TCLAP::ValueArg<std::string> statusQueue("q", "statusQueue",
            "Specify the name of the status health queue destination; default scannerHealth",
            false, "scannerHealth", "string", cmd);
    TCLAP::ValueArg<std::string> beaconMapping("", "beaconMapping",
                                             "Specify the source of the beacon id to user name mapping. The following formats are understood:",
                                             false, "", "string", cmd);
    TCLAP::SwitchArg skipPublish("S", "skipPublish",
            "Indicate that the parsed beacons should not be published",
            false);
    TCLAP::SwitchArg asyncMode("A", "asyncMode",
            "Indicate that the parsed beacons should be published using async delivery mode",
            false);
    TCLAP::SwitchArg useQueues("Q", "useQueues",
            "Indicate that the destination type is a queue. If not given the default type is a topic.",
            false);
    TCLAP::SwitchArg skipHeartbeat("K", "skipHeartbeat",
            "Don't publish the heartbeat messages. Useful to limit the noise when testing the scanner.",
            false);
    TCLAP::SwitchArg analzyeMode("", "analzyeMode",
            "Run the scanner in a mode that simply collects beacon readings and reports unique beacons seen in a time window",
             false);
    TCLAP::SwitchArg generateTestData("T", "generateTestData",
             "Indicate that test data should be generated",
             false);
    TCLAP::SwitchArg noBrokerReconnect("", "noBrokerReconnect",
             "Don't try to reconnect to the broker on failure, just exit",
             false);
    TCLAP::SwitchArg skipScannerView("", "skipScannerView",
              "Skip the scanner view display of closest beacon",
              false);
    TCLAP::SwitchArg  batteryTestMode("", "batteryTestMode",
                                     "Simply monitor the raw heartbeat beacon events and publish them to the destinationName",
                                     false);
    try {
        // Add the flag arguments
        cmd.add(skipPublish);
        cmd.add(asyncMode);
        cmd.add(useQueues);
        cmd.add(skipHeartbeat);
        cmd.add(analzyeMode);
        cmd.add(generateTestData);
        cmd.add(noBrokerReconnect);
        cmd.add(batteryTestMode);
        cmd.add(skipScannerView);
        // Parse the argv array.
        printf("Parsing command line...\n");
        cmd.parse( argc, argv );
        printf("done\n");
    }
    catch (TCLAP::ArgException &e) {
        fprintf(stderr, "error: %s for arg: %s\n", e.error().c_str(), e.argId().c_str());
    }

    // Remove any stop marker file
    if(remove(STOP_MARKER_FILE) == 0) {
        printf("Removed existing %s marker file\n", STOP_MARKER_FILE);
    }

    // Validate the system time as unless the network time has syncd, just exit to wait for it to happen
    int64_t nowMS = EventsWindow::currentMilliseconds();
    // 1434954728562 = 2015-06-21 23:32:08.562
    if(nowMS < 1434954728562) {
        fprintf(stderr, "currentMilliseconds(%ld) < 1434954728562 = 2015-06-21 23:32:08.562", nowMS);
        exit(1);
    }

    // If scannerID is the string {IP}, replace it with the host IP address
    string scannerIDValue = scannerID.getValue();
    if(scannerIDValue.compare("{IP}") == 0) {
        char hostIPAddress[128];
        char macaddr[32];
        HealthStatus::getHostInfo(hostIPAddress, macaddr);
        scannerIDValue = hostIPAddress;
    }
    HCIDumpCommand command(scannerIDValue, brokerURL.getValue(), clientID.getValue(), destinationName.getValue());
    command.setUseQueues(useQueues.getValue());
    command.setSkipPublish(skipPublish.getValue());
    command.setSkipHeartbeat(skipHeartbeat.getValue());
    command.setHciDev(hciDev.getValue());
    command.setAsyncMode(asyncMode.getValue());
    command.setAnalyzeMode(analzyeMode.getValue());
    command.setAnalyzeWindow(analyzeWindow.getValue());
    command.setPubType(pubTypeConstraint.toType(pubType.getValue()));
    command.setStatusInterval(statusInterval.getValue());
    command.setStatusQueue(statusQueue.getValue());
    command.setGenerateTestData(generateTestData.getValue());
    command.setBatteryTestMode(batteryTestMode.getValue());
    command.setUsername(username.getValue());
    command.setPassword(password.getValue());
    command.setBcastAddress(bcastAddress.getValue());
    command.setBcastPort(bcastPort.getValue());
    if(maxCount.getValue() > 0) {
        maxEventCount = maxCount.getValue();
        printf("Set maxEventCount: %ld\n", maxEventCount);
    }
    parserLogic.setBatchCount(batchCount.getValue());
    if(heartbeatUUID.isSet()) {
        parserLogic.setScannerUUID(heartbeatUUID.getValue());
        printf("Set heartbeatUUID: %s\n", heartbeatUUID.getValue().c_str());
    }

    // Install default terminate handler to make sure we exit with non-zero status
    std::set_terminate(terminateHandler);

    // Create a beacon mapping instance
    shared_ptr<AbstractBeaconMapper> beaconMapper(new AbstractBeaconMapper());
    if(beaconMapping.isSet()) {
        const string& mapping = beaconMapping.getValue();
        string filePrefix("file:");
        if(!mapping.compare(0, filePrefix.size(), filePrefix)) {
            // TODO
            printf("file: beaconMapper not implemented yet\n");
        } else {
            // The value is a series of id1=userid1,id2=userid2,... values
            beaconMapper.reset(new PropertiesMapper(mapping));
            printf("Loaded beacon mappings: %s\n", mapping.c_str());
        }
    }

    if(!skipScannerView.getValue()) {
        // Get the scanner view implementation
        LcdDisplayType type = lcdTypeConstraint.toType(lcdType.getValue());
        if(type == LcdDisplayType::INVALID_LCD_TYPE) {
            fprintf(stderr, "Skipping scanner view due to invalid LcdDisplayType. No mapping for: %s\n", lcdType.getValue().c_str());
        } else {
            printf("Using LCD type=%s\n",  lcdType.getValue().c_str());
            shared_ptr<ScannerView> lcd(getDisplayInstance(type));
            // Set the scanner view display's beacon mapper to display the minorID to name correctly
            lcd->setBeaconMapper(beaconMapper);
            parserLogic.setScannerView(lcd);
        }
    }

    char cwd[256];
    getcwd(cwd, sizeof(cwd));
    printf("Begin scanning, cwd=%s...\n", cwd);
    fflush(stdout);
    parserLogic.processHCI(command);
    parserLogic.cleanup();
    printf("End scanning\n");
    fflush(stdout);
    return 0;
}
<|endoftext|>


<commit_before>#include <bitcoin/bitcoin.hpp>
#include <obelisk/client/interface.hpp>
#include "config.hpp"
#include "util.hpp"

using namespace bc;

bool stopped = false;

void history_fetched(const std::error_code& ec,
    const blockchain::history_list& history)
{
    if (ec)
    {
        std::cerr << "balance: Failed to fetch history: "
            << ec.message() << std::endl;
        return;
    }
    uint64_t total_recv = 0, balance = 0, pending_balance = 0;
    for (const auto& row: history)
    {
        uint64_t value = row.value;
        BITCOIN_ASSERT(value >= 0);
        total_recv += value;
        // Unconfirmed balance.
        if (row.spend.hash == null_hash)
        {
            pending_balance += value;
        }
        // Confirmed balance.
        if (row.output_height &&
            (row.spend.hash == null_hash || !row.spend_height))
        {
            balance += value;
        }
    }
    std::cout << "Paid balance:    " << balance << std::endl;
    std::cout << "Pending balance: " << pending_balance << std::endl;
    std::cout << "Total received:  " << total_recv << std::endl;
    stopped = true;
}

int main()
{
    config_map_type config;
    load_config(config);
    payment_address payaddr;
    if (!payaddr.set_encoded(read_stdin()))
    {
        std::cerr << "balance: Invalid address." << std::endl;
        return -1;
    }
    fullnode_interface fullnode(config["service"]);
    fullnode.fetch_history(payaddr, history_fetched);
    while (!stopped)
    {
        fullnode.update();
        sleep(0.1);
    }
    return 0;
}

<commit_msg>balance can now also read addr from command line too.<commit_after>#include <bitcoin/bitcoin.hpp>
#include <obelisk/client/interface.hpp>
#include "config.hpp"
#include "util.hpp"

using namespace bc;

bool stopped = false;

void history_fetched(const std::error_code& ec,
    const blockchain::history_list& history)
{
    if (ec)
    {
        std::cerr << "balance: Failed to fetch history: "
            << ec.message() << std::endl;
        return;
    }
    uint64_t total_recv = 0, balance = 0, pending_balance = 0;
    for (const auto& row: history)
    {
        uint64_t value = row.value;
        BITCOIN_ASSERT(value >= 0);
        total_recv += value;
        // Unconfirmed balance.
        if (row.spend.hash == null_hash)
        {
            pending_balance += value;
        }
        // Confirmed balance.
        if (row.output_height &&
            (row.spend.hash == null_hash || !row.spend_height))
        {
            balance += value;
        }
    }
    BITCOIN_ASSERT(pending_balance > balance);
    BITCOIN_ASSERT(total_recv > pending_balance);
    std::cout << "Paid balance:    " << balance << std::endl;
    std::cout << "Pending balance: " << pending_balance << std::endl;
    std::cout << "Total received:  " << total_recv << std::endl;
    stopped = true;
}

int main(int argc, char** argv)
{
    std::string addr_str;
    if (argc == 2)
        addr_str = argv[1];
    else
        addr_str = read_stdin();
    config_map_type config;
    load_config(config);
    payment_address payaddr;
    if (!payaddr.set_encoded(addr_str))
    {
        std::cerr << "balance: Invalid address." << std::endl;
        return -1;
    }
    fullnode_interface fullnode(config["service"]);
    fullnode.fetch_history(payaddr, history_fetched);
    while (!stopped)
    {
        fullnode.update();
        sleep(0.1);
    }
    return 0;
}

<|endoftext|>


<commit_before>#include "mainwindow.hpp"
#include "draw_widget.hpp"
#include "slider_ctrl.hpp"
#include "about.hpp"

#include "../defines.hpp"

#include "../map/settings.hpp"

#include <QtGui/QDockWidget>
#include <QtGui/QToolBar>
#include <QtGui/QAction>
#include <QtGui/QMenuBar>
#include <QtGui/QMenu>

#define IDM_ABOUT_DIALOG        1001

namespace qt
{

MainWindow::MainWindow()
#ifdef DEBUG // code removed for desktop releases
  : m_updateDialog(0)
#endif // DEBUG
{
  m_pDrawWidget = new DrawWidget(this, m_storage);

  CreateNavigationBar();

#ifdef DEBUG // code removed for desktop releases
  CreateClassifPanel();
  CreateGuidePanel();
#endif // DEBUG
  setCentralWidget(m_pDrawWidget);

  setWindowTitle(tr("MapsWithMe"));
  setWindowIcon(QIcon(":logo.png"));

#ifndef OMIM_OS_WINDOWS
  QMenu * helpMenu = new QMenu(tr("Help"), this);
  menuBar()->addMenu(helpMenu);
  helpMenu->addAction(tr("About"), this, SLOT(OnAbout()));
#ifdef DEBUG // code removed for desktop releases
  helpMenu->addAction(tr("Preferences"), this, SLOT(OnPreferences()));
#endif // DEBUG
#else
  {
    // create items in the system menu
    HMENU menu = ::GetSystemMenu(winId(), FALSE);
    MENUITEMINFOA item;
    item.cbSize = sizeof(MENUITEMINFOA);
    item.fMask = MIIM_FTYPE | MIIM_ID | MIIM_STRING;
    item.fType = MFT_STRING;
 #ifdef DEBUG // code removed for desktop releases
    item.wID = IDM_PREFERENCES_DIALOG;
    QByteArray const prefsStr = tr("Preferences...").toLocal8Bit();
    item.dwTypeData = const_cast<char *>(prefsStr.data());
    item.cch = prefsStr.size();
    ::InsertMenuItemA(menu, ::GetMenuItemCount(menu) - 1, TRUE, &item);
 #endif DEBUG
    item.wID = IDM_ABOUT_DIALOG;
    QByteArray const aboutStr = tr("About MapsWithMe...").toLocal8Bit();
    item.dwTypeData = const_cast<char *>(aboutStr.data());
    item.cch = aboutStr.size();
    ::InsertMenuItemA(menu, ::GetMenuItemCount(menu) - 1, TRUE, &item);
    item.fType = MFT_SEPARATOR;
    ::InsertMenuItemA(menu, ::GetMenuItemCount(menu) - 1, TRUE, &item);
  }
#endif

  LoadState();

#ifdef DEBUG // code removed for desktop releases
  // Show intro dialog if necessary
  bool bShow = true;
  (void)Settings::Get("ShowWelcome", bShow);

  if (bShow)
  {
    QFile welcomeTextFile(GetPlatform().ReadPathForFile("welcome.html").c_str());

    bool bShowUpdateDialog = true;

    if (welcomeTextFile.open(QIODevice::ReadOnly))
    {
      QByteArray text = welcomeTextFile.readAll();
      welcomeTextFile.close();

      InfoDialog welcomeDlg(tr("Welcome to MapsWithMe!"), text, this, QStringList(tr("Download Maps")));
      if (welcomeDlg.exec() == QDialog::Rejected)
        bShowUpdateDialog = false;
    }
    Settings::Set("ShowWelcome", false);

    if (bShowUpdateDialog)
      ShowUpdateDialog();
  }
#endif // DEBUG
}

#if defined(Q_WS_WIN)
bool MainWindow::winEvent(MSG * msg, long * result)
{
  if (msg->message == WM_SYSCOMMAND)
  {
    if (msg->wParam == IDM_PREFERENCES_DIALOG)
    {
      OnPreferences();
      *result = 0;
      return true;
    }
    else if (msg->wParam == IDM_ABOUT_DIALOG)
    {
      OnAbout();
      *result = 0;
      return true;
    }
  }
  return false;
}
#endif

MainWindow::~MainWindow()
{
  SaveState();
#ifdef DEBUG // code removed for desktop releases
  GetDownloadManager().CancelAllDownloads();
#endif
}

void MainWindow::SaveState()
{
  pair<uint32_t, uint32_t> xAndY(x(), y());
  pair<uint32_t, uint32_t> widthAndHeight(width(), height());
  Settings::Set("MainWindowXY", xAndY);
  Settings::Set("MainWindowSize", widthAndHeight);

  m_pDrawWidget->SaveState();
}

void MainWindow::LoadState()
{
  pair<uint32_t, uint32_t> xAndY;
  pair<uint32_t, uint32_t> widthAndHeight;
  bool loaded = Settings::Get("MainWindowXY", xAndY) &&
                Settings::Get("MainWindowSize", widthAndHeight);
  if (loaded)
  {
    move(xAndY.first, xAndY.second);
    resize(widthAndHeight.first, widthAndHeight.second);

    loaded = m_pDrawWidget->LoadState();
  }

  if (!loaded)
  {
    showMaximized();
    m_pDrawWidget->ShowAll();
  }
  else
    m_pDrawWidget->UpdateNow();
}

namespace
{
  struct button_t
  {
    QString name;
    char const * icon;
    char const * slot;
  };

  void add_buttons(QToolBar * pBar, button_t buttons[], size_t count, QWidget * pReceiver)
  {
    for (size_t i = 0; i < count; ++i)
    {
      if (buttons[i].icon)
        pBar->addAction(QIcon(buttons[i].icon), buttons[i].name, pReceiver, buttons[i].slot);
      else
        pBar->addSeparator();
    }
  }
}

void MainWindow::CreateNavigationBar()
{
  QToolBar * pBar = new QToolBar(tr("Navigation Bar"), this);
  pBar->setOrientation(Qt::Vertical);
  pBar->setIconSize(QSize(32, 32));

  {
    // add my position button with "checked" behavior
    m_pMyPosition = pBar->addAction(QIcon(":/navig64/location.png"),
                                           tr("My Position"),
                                           this,
                                           SLOT(OnMyPosition()));
    m_pMyPosition->setCheckable(true);
    m_pMyPosition->setToolTip(tr("My Position"));

    // add view actions 1
    button_t arr[] = {
//      { tr("Left"), ":/navig64/left.png", SLOT(MoveLeft()) },
//      { tr("Right"), ":/navig64/right.png", SLOT(MoveRight()) },
//      { tr("Up"), ":/navig64/up.png", SLOT(MoveUp()) },
//      { tr("Down"), ":/navig64/down.png", SLOT(MoveDown()) },
//      { tr("Show all"), ":/navig64/world.png", SLOT(ShowAll()) },
//      { QString(), 0, 0 },
      { tr("Scale +"), ":/navig64/plus.png", SLOT(ScalePlus()) }
    };
    add_buttons(pBar, arr, ARRAY_SIZE(arr), m_pDrawWidget);
  }

  // add scale slider
  QClickSlider * pScale = new QClickSlider(Qt::Vertical, this);
  pScale->setRange(0, scales::GetUpperScale());
  pScale->setTickPosition(QSlider::TicksRight);

  pBar->addWidget(pScale);
  m_pDrawWidget->SetScaleControl(pScale);

  {
    // add view actions 2
    button_t arr[] = {
      { tr("Scale -"), ":/navig64/minus.png", SLOT(ScaleMinus()) }
    };
    add_buttons(pBar, arr, ARRAY_SIZE(arr), m_pDrawWidget);
  }
#ifdef DEBUG // code removed for desktop releases
  {
    // add mainframe actions
    button_t arr[] = {
      { QString(), 0, 0 },
      { tr("Download Maps"), ":/navig64/download.png", SLOT(ShowUpdateDialog()) }
    };
    add_buttons(pBar, arr, ARRAY_SIZE(arr), this);
  }
#endif // DEBUG
  addToolBar(Qt::RightToolBarArea, pBar);
}

//void MainWindow::CreateFindTable(QLayout * pLayout)
//{
//  // find widget
//  FindEditorWnd * pEditor = new FindEditorWnd(0);
//  pLayout->addWidget(pEditor);
//
//  // find table result
//  m_pFindTable = new FindTableWnd(0, pEditor, m_pDrawWidget->GetModel());
//  pLayout->addWidget(m_pFindTable);
//  connect(m_pFindTable, SIGNAL(cellClicked(int, int)), this, SLOT(OnFeatureClicked(int, int)));
//  connect(m_pFindTable, SIGNAL(cellEntered(int, int)), this, SLOT(OnFeatureEntered(int, int)));
//}
//
//void MainWindow::OnFeatureEntered(int /*row*/, int /*col*/)
//{
//  //Feature const & p = m_pFindTable->GetFeature(row);
//
//  /// @todo highlight the feature
//}
//
//void MainWindow::OnFeatureClicked(int row, int /*col*/)
//{
//  Feature const & p = m_pFindTable->GetFeature(row);
//  m_pDrawWidget->ShowFeature(p);
//}
void MainWindow::OnAbout()
{
  AboutDialog dlg(this);
  dlg.exec();
}

void MainWindow::OnLocationFound()
{
  m_pMyPosition->setIcon(QIcon(":/navig64/location.png"));
  m_pMyPosition->setToolTip(tr("My Position"));
}

void MainWindow::OnMyPosition()
{
  if (m_pMyPosition->isChecked())
  {
    m_pMyPosition->setIcon(QIcon(":/navig64/location-search.png"));
    m_pMyPosition->setToolTip(tr("Looking for position..."));
    m_pDrawWidget->OnEnableMyPosition(boost::bind(&MainWindow::OnLocationFound, this));
  }
  else
  {
    m_pMyPosition->setIcon(QIcon(":/navig64/location.png"));
    m_pMyPosition->setToolTip(tr("My Position"));
    m_pDrawWidget->OnDisableMyPosition();
  }
}

#ifdef DEBUG // code removed for desktop releases
void MainWindow::ShowUpdateDialog()
{
  if (!m_updateDialog)
    m_updateDialog = new UpdateDialog(this, m_storage);
  m_updateDialog->ShowDialog();
}

void MainWindow::ShowClassifPanel()
{
  m_Docks[0]->show();
}

void MainWindow::ShowGuidePanel()
{
  m_Docks[1]->show();
}

void MainWindow::OnPreferences()
{
  bool autoUpdatesEnabled = DEFAULT_AUTO_UPDATES_ENABLED;
  Settings::Get("AutomaticUpdateCheck", autoUpdatesEnabled);

  PreferencesDialog dlg(this, autoUpdatesEnabled);
  dlg.exec();

  Settings::Set("AutomaticUpdateCheck", autoUpdatesEnabled);
}

void MainWindow::CreateClassifPanel()
{
  CreatePanelImpl(0, tr("Classificator Bar"),
                  QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_C), SLOT(ShowClassifPanel()));

  ClassifTreeHolder * pCTree = new ClassifTreeHolder(m_Docks[0], m_pDrawWidget, SLOT(Repaint()));
  pCTree->SetRoot(classif().GetMutableRoot());

  m_Docks[0]->setWidget(pCTree);
}

void MainWindow::CreateGuidePanel()
{
  CreatePanelImpl(1, tr("Guide Bar"),
                  QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_G), SLOT(ShowGuidePanel()));

  qt::GuidePageHolder * pGPage = new qt::GuidePageHolder(m_Docks[1]);

  m_Docks[1]->setWidget(pGPage);
}

void MainWindow::CreatePanelImpl(size_t i, QString const & name,
                                 QKeySequence const & hotkey, char const * slot)
{
  m_Docks[i] = new QDockWidget(name, this);

  addDockWidget(Qt::LeftDockWidgetArea, m_Docks[i]);

  // hide by default
  m_Docks[i]->hide();

  // register a hotkey to show classificator panel
  QAction * pAct = new QAction(this);
  pAct->setShortcut(hotkey);
  connect(pAct, SIGNAL(triggered()), this, slot);
  addAction(pAct);
}
#endif // DEBUG
}
<commit_msg>- Fix debug compilation errors. - Restore Show All button.<commit_after>#include "mainwindow.hpp"
#include "draw_widget.hpp"
#include "slider_ctrl.hpp"
#include "about.hpp"

#ifdef DEBUG
#include "info_dialog.hpp"
#include "update_dialog.hpp"
#include "preferences_dialog.hpp"
#include "classificator_tree.hpp"
#include "guide_page.hpp"

#include "../indexer/classificator.hpp"
#endif

#include "../defines.hpp"

#include "../map/settings.hpp"

#include <QtGui/QDockWidget>
#include <QtGui/QToolBar>
#include <QtGui/QAction>
#include <QtGui/QMenuBar>
#include <QtGui/QMenu>

#ifdef DEBUG
#include <QtCore/QFile>
#endif

#define IDM_ABOUT_DIALOG        1001

namespace qt
{

MainWindow::MainWindow()
#ifdef DEBUG // code removed for desktop releases
  : m_updateDialog(0)
#endif // DEBUG
{
  m_pDrawWidget = new DrawWidget(this, m_storage);

  CreateNavigationBar();

#ifdef DEBUG // code removed for desktop releases
  CreateClassifPanel();
  CreateGuidePanel();
#endif // DEBUG
  setCentralWidget(m_pDrawWidget);

  setWindowTitle(tr("MapsWithMe"));
  setWindowIcon(QIcon(":logo.png"));

#ifndef OMIM_OS_WINDOWS
  QMenu * helpMenu = new QMenu(tr("Help"), this);
  menuBar()->addMenu(helpMenu);
  helpMenu->addAction(tr("About"), this, SLOT(OnAbout()));
#ifdef DEBUG // code removed for desktop releases
  helpMenu->addAction(tr("Preferences"), this, SLOT(OnPreferences()));
#endif // DEBUG
#else
  {
    // create items in the system menu
    HMENU menu = ::GetSystemMenu(winId(), FALSE);
    MENUITEMINFOA item;
    item.cbSize = sizeof(MENUITEMINFOA);
    item.fMask = MIIM_FTYPE | MIIM_ID | MIIM_STRING;
    item.fType = MFT_STRING;
 #ifdef DEBUG // code removed for desktop releases
    item.wID = IDM_PREFERENCES_DIALOG;
    QByteArray const prefsStr = tr("Preferences...").toLocal8Bit();
    item.dwTypeData = const_cast<char *>(prefsStr.data());
    item.cch = prefsStr.size();
    ::InsertMenuItemA(menu, ::GetMenuItemCount(menu) - 1, TRUE, &item);
 #endif DEBUG
    item.wID = IDM_ABOUT_DIALOG;
    QByteArray const aboutStr = tr("About MapsWithMe...").toLocal8Bit();
    item.dwTypeData = const_cast<char *>(aboutStr.data());
    item.cch = aboutStr.size();
    ::InsertMenuItemA(menu, ::GetMenuItemCount(menu) - 1, TRUE, &item);
    item.fType = MFT_SEPARATOR;
    ::InsertMenuItemA(menu, ::GetMenuItemCount(menu) - 1, TRUE, &item);
  }
#endif

  LoadState();

#ifdef DEBUG // code removed for desktop releases
  // Show intro dialog if necessary
  bool bShow = true;
  (void)Settings::Get("ShowWelcome", bShow);

  if (bShow)
  {
    QFile welcomeTextFile(GetPlatform().ReadPathForFile("welcome.html").c_str());

    bool bShowUpdateDialog = true;

    if (welcomeTextFile.open(QIODevice::ReadOnly))
    {
      QByteArray text = welcomeTextFile.readAll();
      welcomeTextFile.close();

      InfoDialog welcomeDlg(tr("Welcome to MapsWithMe!"), text, this, QStringList(tr("Download Maps")));
      if (welcomeDlg.exec() == QDialog::Rejected)
        bShowUpdateDialog = false;
    }
    Settings::Set("ShowWelcome", false);

    if (bShowUpdateDialog)
      ShowUpdateDialog();
  }
#endif // DEBUG
}

#if defined(Q_WS_WIN)
bool MainWindow::winEvent(MSG * msg, long * result)
{
  if (msg->message == WM_SYSCOMMAND)
  {
    if (msg->wParam == IDM_PREFERENCES_DIALOG)
    {
      OnPreferences();
      *result = 0;
      return true;
    }
    else if (msg->wParam == IDM_ABOUT_DIALOG)
    {
      OnAbout();
      *result = 0;
      return true;
    }
  }
  return false;
}
#endif

MainWindow::~MainWindow()
{
  SaveState();
#ifdef DEBUG // code removed for desktop releases
  GetDownloadManager().CancelAllDownloads();
#endif
}

void MainWindow::SaveState()
{
  pair<uint32_t, uint32_t> xAndY(x(), y());
  pair<uint32_t, uint32_t> widthAndHeight(width(), height());
  Settings::Set("MainWindowXY", xAndY);
  Settings::Set("MainWindowSize", widthAndHeight);

  m_pDrawWidget->SaveState();
}

void MainWindow::LoadState()
{
  pair<uint32_t, uint32_t> xAndY;
  pair<uint32_t, uint32_t> widthAndHeight;
  bool loaded = Settings::Get("MainWindowXY", xAndY) &&
                Settings::Get("MainWindowSize", widthAndHeight);
  if (loaded)
  {
    move(xAndY.first, xAndY.second);
    resize(widthAndHeight.first, widthAndHeight.second);

    loaded = m_pDrawWidget->LoadState();
  }

  if (!loaded)
  {
    showMaximized();
    m_pDrawWidget->ShowAll();
  }
  else
    m_pDrawWidget->UpdateNow();
}

namespace
{
  struct button_t
  {
    QString name;
    char const * icon;
    char const * slot;
  };

  void add_buttons(QToolBar * pBar, button_t buttons[], size_t count, QWidget * pReceiver)
  {
    for (size_t i = 0; i < count; ++i)
    {
      if (buttons[i].icon)
        pBar->addAction(QIcon(buttons[i].icon), buttons[i].name, pReceiver, buttons[i].slot);
      else
        pBar->addSeparator();
    }
  }
}

void MainWindow::CreateNavigationBar()
{
  QToolBar * pBar = new QToolBar(tr("Navigation Bar"), this);
  pBar->setOrientation(Qt::Vertical);
  pBar->setIconSize(QSize(32, 32));

  {
    // add my position button with "checked" behavior
    m_pMyPosition = pBar->addAction(QIcon(":/navig64/location.png"),
                                           tr("My Position"),
                                           this,
                                           SLOT(OnMyPosition()));
    m_pMyPosition->setCheckable(true);
    m_pMyPosition->setToolTip(tr("My Position"));

    // add view actions 1
    button_t arr[] = {
//      { tr("Left"), ":/navig64/left.png", SLOT(MoveLeft()) },
//      { tr("Right"), ":/navig64/right.png", SLOT(MoveRight()) },
//      { tr("Up"), ":/navig64/up.png", SLOT(MoveUp()) },
//      { tr("Down"), ":/navig64/down.png", SLOT(MoveDown()) },
      { QString(), 0, 0 },
      { tr("Show all"), ":/navig64/world.png", SLOT(ShowAll()) },
      { tr("Scale +"), ":/navig64/plus.png", SLOT(ScalePlus()) }
    };
    add_buttons(pBar, arr, ARRAY_SIZE(arr), m_pDrawWidget);
  }

  // add scale slider
  QClickSlider * pScale = new QClickSlider(Qt::Vertical, this);
  pScale->setRange(0, scales::GetUpperScale());
  pScale->setTickPosition(QSlider::TicksRight);

  pBar->addWidget(pScale);
  m_pDrawWidget->SetScaleControl(pScale);

  {
    // add view actions 2
    button_t arr[] = {
      { tr("Scale -"), ":/navig64/minus.png", SLOT(ScaleMinus()) }
    };
    add_buttons(pBar, arr, ARRAY_SIZE(arr), m_pDrawWidget);
  }
#ifdef DEBUG // code removed for desktop releases
  {
    // add mainframe actions
    button_t arr[] = {
      { QString(), 0, 0 },
      { tr("Download Maps"), ":/navig64/download.png", SLOT(ShowUpdateDialog()) }
    };
    add_buttons(pBar, arr, ARRAY_SIZE(arr), this);
  }
#endif // DEBUG
  addToolBar(Qt::RightToolBarArea, pBar);
}

//void MainWindow::CreateFindTable(QLayout * pLayout)
//{
//  // find widget
//  FindEditorWnd * pEditor = new FindEditorWnd(0);
//  pLayout->addWidget(pEditor);
//
//  // find table result
//  m_pFindTable = new FindTableWnd(0, pEditor, m_pDrawWidget->GetModel());
//  pLayout->addWidget(m_pFindTable);
//  connect(m_pFindTable, SIGNAL(cellClicked(int, int)), this, SLOT(OnFeatureClicked(int, int)));
//  connect(m_pFindTable, SIGNAL(cellEntered(int, int)), this, SLOT(OnFeatureEntered(int, int)));
//}
//
//void MainWindow::OnFeatureEntered(int /*row*/, int /*col*/)
//{
//  //Feature const & p = m_pFindTable->GetFeature(row);
//
//  /// @todo highlight the feature
//}
//
//void MainWindow::OnFeatureClicked(int row, int /*col*/)
//{
//  Feature const & p = m_pFindTable->GetFeature(row);
//  m_pDrawWidget->ShowFeature(p);
//}
void MainWindow::OnAbout()
{
  AboutDialog dlg(this);
  dlg.exec();
}

void MainWindow::OnLocationFound()
{
  m_pMyPosition->setIcon(QIcon(":/navig64/location.png"));
  m_pMyPosition->setToolTip(tr("My Position"));
}

void MainWindow::OnMyPosition()
{
  if (m_pMyPosition->isChecked())
  {
    m_pMyPosition->setIcon(QIcon(":/navig64/location-search.png"));
    m_pMyPosition->setToolTip(tr("Looking for position..."));
    m_pDrawWidget->OnEnableMyPosition(boost::bind(&MainWindow::OnLocationFound, this));
  }
  else
  {
    m_pMyPosition->setIcon(QIcon(":/navig64/location.png"));
    m_pMyPosition->setToolTip(tr("My Position"));
    m_pDrawWidget->OnDisableMyPosition();
  }
}

#ifdef DEBUG // code removed for desktop releases
void MainWindow::ShowUpdateDialog()
{
  if (!m_updateDialog)
    m_updateDialog = new UpdateDialog(this, m_storage);
  m_updateDialog->ShowDialog();
}

void MainWindow::ShowClassifPanel()
{
  m_Docks[0]->show();
}

void MainWindow::ShowGuidePanel()
{
  m_Docks[1]->show();
}

void MainWindow::OnPreferences()
{
  bool autoUpdatesEnabled = DEFAULT_AUTO_UPDATES_ENABLED;
  Settings::Get("AutomaticUpdateCheck", autoUpdatesEnabled);

  PreferencesDialog dlg(this, autoUpdatesEnabled);
  dlg.exec();

  Settings::Set("AutomaticUpdateCheck", autoUpdatesEnabled);
}

void MainWindow::CreateClassifPanel()
{
  CreatePanelImpl(0, tr("Classificator Bar"),
                  QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_C), SLOT(ShowClassifPanel()));

  ClassifTreeHolder * pCTree = new ClassifTreeHolder(m_Docks[0], m_pDrawWidget, SLOT(Repaint()));
  pCTree->SetRoot(classif().GetMutableRoot());

  m_Docks[0]->setWidget(pCTree);
}

void MainWindow::CreateGuidePanel()
{
  CreatePanelImpl(1, tr("Guide Bar"),
                  QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_G), SLOT(ShowGuidePanel()));

  qt::GuidePageHolder * pGPage = new qt::GuidePageHolder(m_Docks[1]);

  m_Docks[1]->setWidget(pGPage);
}

void MainWindow::CreatePanelImpl(size_t i, QString const & name,
                                 QKeySequence const & hotkey, char const * slot)
{
  m_Docks[i] = new QDockWidget(name, this);

  addDockWidget(Qt::LeftDockWidgetArea, m_Docks[i]);

  // hide by default
  m_Docks[i]->hide();

  // register a hotkey to show classificator panel
  QAction * pAct = new QAction(this);
  pAct->setShortcut(hotkey);
  connect(pAct, SIGNAL(triggered()), this, slot);
  addAction(pAct);
}
#endif // DEBUG
}
<|endoftext|>