<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: webconninfo.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-26 16:40:29 $
 *
 *  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_svx.hxx"

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

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

#ifndef _SVX_DIALMGR_HXX
#include <svx/dialmgr.hxx>
#endif
#ifndef _SVX_DIALOGS_HRC
#include <svx/dialogs.hrc>
#endif

#include <com/sun/star/task/UrlRecord.hpp>
#include <com/sun/star/task/XPasswordContainer.hpp>
#include <com/sun/star/task/XMasterPasswordHandling.hpp>

#include <comphelper/processfactory.hxx>
#include <svtools/docpasswdrequest.hxx>

#include "webconninfo.hxx"
#include "webconninfo.hrc"

using namespace ::com::sun::star;

//........................................................................
namespace svx
{
//........................................................................

// class PasswordTable ---------------------------------------------------

PasswordTable::PasswordTable( Window* pParent, const ResId& rResId ) :
    SvxSimpleTable( pParent, rResId )
{
    SetWindowBits( GetStyle() | WB_NOINITIALSELECTION );
}

void PasswordTable::InsertHeaderItem( USHORT nColumn, const String& rText, HeaderBarItemBits nBits )
{
    GetTheHeaderBar()->InsertItem( nColumn, rText, 0, nBits );
}

void PasswordTable::ResetTabs()
{
    SetTabs();
}

void PasswordTable::Resort( bool bForced )
{
    USHORT nColumn = GetSelectedCol();
    if ( 0 == nColumn || bForced ) // only the first column is sorted
    {
        HeaderBarItemBits nBits = GetTheHeaderBar()->GetItemBits(1);
        BOOL bUp = ( ( nBits & HIB_UPARROW ) == HIB_UPARROW );
        SvSortMode eMode = SortAscending;

        if ( bUp )
        {
            nBits &= ~HIB_UPARROW;
            nBits |= HIB_DOWNARROW;
            eMode = SortDescending;
        }
        else
        {
            nBits &= ~HIB_DOWNARROW;
            nBits |= HIB_UPARROW;
        }
        GetTheHeaderBar()->SetItemBits( 1, nBits );
        SvTreeList* pListModel = GetModel();
        pListModel->SetSortMode( eMode );
        pListModel->Resort();
    }
}

// class WebConnectionInfoDialog -----------------------------------------

// -----------------------------------------------------------------------
WebConnectionInfoDialog::WebConnectionInfoDialog( Window* pParent ) :
     ModalDialog( pParent, SVX_RES( RID_SVXDLG_WEBCONNECTION_INFO ) )
    ,m_aNeverShownFI    ( this, SVX_RES( FI_NEVERSHOWN ) )
    ,m_aPasswordsLB     ( this, SVX_RES( LB_PASSWORDS ) )
    ,m_aRemoveBtn       ( this, SVX_RES( PB_REMOVE ) )
    ,m_aRemoveAllBtn    ( this, SVX_RES( PB_REMOVEALL ) )
    ,m_aChangeBtn       ( this, SVX_RES( PB_CHANGE ) )
    ,m_aButtonsFL       ( this, SVX_RES( FL_BUTTONS ) )
    ,m_aCloseBtn        ( this, SVX_RES( PB_CLOSE ) )
    ,m_aHelpBtn         ( this, SVX_RES( PB_HELP ) )

{
    static long aStaticTabs[]= { 3, 0, 150, 250 };
    m_aPasswordsLB.SetTabs( aStaticTabs );
    m_aPasswordsLB.InsertHeaderItem( 1, SVX_RESSTR( STR_WEBSITE ),
        HIB_LEFT | HIB_VCENTER | HIB_FIXEDPOS | HIB_CLICKABLE | HIB_UPARROW );
    m_aPasswordsLB.InsertHeaderItem( 2, SVX_RESSTR( STR_USERNAME ),
        HIB_LEFT | HIB_VCENTER | HIB_FIXEDPOS );
    m_aPasswordsLB.ResetTabs();

    FreeResource();

    m_aPasswordsLB.SetHeaderBarClickHdl( LINK( this, WebConnectionInfoDialog, HeaderBarClickedHdl ) );
    m_aRemoveBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, RemovePasswordHdl ) );
    m_aRemoveAllBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, RemoveAllPasswordsHdl ) );
    m_aChangeBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, ChangePasswordHdl ) );

    // one button too small for its text?
    sal_Int32 i = 0;
    long nBtnTextWidth = 0;
    Window* pButtons[] = { &m_aRemoveBtn, &m_aRemoveAllBtn, &m_aChangeBtn };
    Window** pButton = pButtons;
    const sal_Int32 nBCount = sizeof( pButtons ) / sizeof( pButtons[ 0 ] );
    for ( ; i < nBCount; ++i, ++pButton )
    {
        long nTemp = (*pButton)->GetCtrlTextWidth( (*pButton)->GetText() );
        if ( nTemp > nBtnTextWidth )
            nBtnTextWidth = nTemp;
    }
    nBtnTextWidth = nBtnTextWidth * 115 / 100; // a little offset
    long nButtonWidth = m_aRemoveBtn.GetSizePixel().Width();
    if ( nBtnTextWidth > nButtonWidth )
    {
        // so make the buttons broader and its control in front of it smaller
        long nDelta = nBtnTextWidth - nButtonWidth;
        pButton = pButtons;
        for ( i = 0; i < nBCount; ++i, ++pButton )
        {
            Point aNewPos = (*pButton)->GetPosPixel();
            if ( &m_aRemoveAllBtn == (*pButton) )
                aNewPos.X() += nDelta;
            else if ( &m_aChangeBtn == (*pButton) )
                aNewPos.X() -= nDelta;
            Size aNewSize = (*pButton)->GetSizePixel();
            aNewSize.Width() += nDelta;
            (*pButton)->SetPosSizePixel( aNewPos, aNewSize );
        }
    }

    FillPasswordList();

    m_aRemoveBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, RemovePasswordHdl ) );
    m_aRemoveAllBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, RemoveAllPasswordsHdl ) );
    m_aChangeBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, ChangePasswordHdl ) );
    m_aPasswordsLB.SetSelectHdl( LINK( this, WebConnectionInfoDialog, EntrySelectedHdl ) );

    m_aRemoveBtn.Enable( FALSE );
    m_aChangeBtn.Enable( FALSE );

    HeaderBarClickedHdl( NULL );
}

// -----------------------------------------------------------------------
WebConnectionInfoDialog::~WebConnectionInfoDialog()
{
}

// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, HeaderBarClickedHdl, SvxSimpleTable*, pTable )
{
    m_aPasswordsLB.Resort( NULL == pTable );
    return 0;
}

// -----------------------------------------------------------------------
void WebConnectionInfoDialog::FillPasswordList()
{
    try
    {
        uno::Reference< task::XMasterPasswordHandling > xMasterPasswd(
            comphelper::getProcessServiceFactory()->createInstance(
                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.PasswordContainer" ) ) ),
            uno::UNO_QUERY );

        if ( xMasterPasswd.is() && xMasterPasswd->isPersistentStoringAllowed() )
        {
            uno::Reference< task::XPasswordContainer > xPasswdContainer( xMasterPasswd, uno::UNO_QUERY_THROW );
            uno::Reference< task::XInteractionHandler > xInteractionHandler(
                comphelper::getProcessServiceFactory()->createInstance(
                    rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.InteractionHandler" ) ) ),
                uno::UNO_QUERY_THROW );

            uno::Sequence< task::UrlRecord > aURLEntries = xPasswdContainer->getAllPersistent( xInteractionHandler );
            sal_Int32 nCount = 0;
            for ( sal_Int32 nURLInd = 0; nURLInd < aURLEntries.getLength(); nURLInd++ )
                for ( sal_Int32 nUserInd = 0; nUserInd < aURLEntries[nURLInd].UserList.getLength(); nUserInd++ )
                {
                    ::rtl::OUString aUIEntry( aURLEntries[nURLInd].Url );
                    aUIEntry += ::rtl::OUString::valueOf( (sal_Unicode)'\t' );
                    aUIEntry += aURLEntries[nURLInd].UserList[nUserInd].UserName;
                    SvLBoxEntry* pEntry = m_aPasswordsLB.InsertEntry( aUIEntry );
                    pEntry->SetUserData( (void*)(nCount++) );
                }
        }
    }
    catch( uno::Exception& )
    {}
}

// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, RemovePasswordHdl, PushButton*, EMPTYARG )
{
    try
    {
        uno::Reference< task::XPasswordContainer > xPasswdContainer(
            comphelper::getProcessServiceFactory()->createInstance(
                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.PasswordContainer" ) ) ),
            uno::UNO_QUERY_THROW );

        uno::Reference< task::XInteractionHandler > xInteractionHandler(
            comphelper::getProcessServiceFactory()->createInstance(
                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.InteractionHandler" ) ) ),
            uno::UNO_QUERY_THROW );

        SvLBoxEntry* pEntry = m_aPasswordsLB.GetCurEntry();
        if ( pEntry )
        {
            ::rtl::OUString aURL = m_aPasswordsLB.GetEntryText( pEntry, 0 );
            ::rtl::OUString aUserName = m_aPasswordsLB.GetEntryText( pEntry, 1 );
            xPasswdContainer->removePersistent( aURL, aUserName );
            m_aPasswordsLB.RemoveEntry( pEntry );
        }
    }
    catch( uno::Exception& )
    {}

    return 0;
}

// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, RemoveAllPasswordsHdl, PushButton*, EMPTYARG )
{
    try
    {
        uno::Reference< task::XPasswordContainer > xPasswdContainer(
            comphelper::getProcessServiceFactory()->createInstance(
                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.PasswordContainer" ) ) ),
            uno::UNO_QUERY_THROW );

        // should the master password be requested before?
        xPasswdContainer->removeAllPersistent();
        m_aPasswordsLB.Clear();
    }
    catch( uno::Exception& )
    {}

    return 0;
}

// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, ChangePasswordHdl, PushButton*, EMPTYARG )
{
    try
    {
        uno::Reference< task::XPasswordContainer > xPasswdContainer(
            comphelper::getProcessServiceFactory()->createInstance(
                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.PasswordContainer" ) ) ),
            uno::UNO_QUERY_THROW );

        uno::Reference< task::XInteractionHandler > xInteractionHandler(
            comphelper::getProcessServiceFactory()->createInstance(
                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.InteractionHandler" ) ) ),
            uno::UNO_QUERY_THROW );

        SvLBoxEntry* pEntry = m_aPasswordsLB.GetCurEntry();
        if ( pEntry )
        {
            ::rtl::OUString aURL = m_aPasswordsLB.GetEntryText( pEntry, 0 );
            ::rtl::OUString aUserName = m_aPasswordsLB.GetEntryText( pEntry, 1 );

            RequestDocumentPassword* pPasswordRequest = new RequestDocumentPassword(
                                                               task::PasswordRequestMode_PASSWORD_CREATE,
                                                               aURL );

            uno::Reference< task::XInteractionRequest > rRequest( pPasswordRequest );
            xInteractionHandler->handle( rRequest );
            if ( pPasswordRequest->isPassword() )
            {
                String aNewPass = pPasswordRequest->getPassword();
                uno::Sequence< ::rtl::OUString > aPasswd( 1 );
                aPasswd[0] = aNewPass;
                xPasswdContainer->addPersistent( aURL, aUserName, aPasswd, xInteractionHandler );
            }
        }
    }
    catch( uno::Exception& )
    {}

    return 0;
}

// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, EntrySelectedHdl, void*, EMPTYARG )
{
    SvLBoxEntry* pEntry = m_aPasswordsLB.GetCurEntry();
    if ( !pEntry )
    {
        m_aRemoveBtn.Enable( FALSE );
        m_aChangeBtn.Enable( FALSE );
    }
    else
    {
        m_aRemoveBtn.Enable( TRUE );
        m_aChangeBtn.Enable( TRUE );
    }

    return 0;
}

//........................................................................
}   // namespace svx
//........................................................................

<commit_msg>INTEGRATION: CWS changefileheader (1.2.196); FILE MERGED 2008/04/01 12:48:24 thb 1.2.196.2: #i85898# Stripping all external header guards 2008/03/31 14:20:09 rt 1.2.196.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: webconninfo.cxx,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.
 *
 ************************************************************************/

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

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

// include ---------------------------------------------------------------
#include <svx/dialmgr.hxx>
#ifndef _SVX_DIALOGS_HRC
#include <svx/dialogs.hrc>
#endif

#include <com/sun/star/task/UrlRecord.hpp>
#include <com/sun/star/task/XPasswordContainer.hpp>
#include <com/sun/star/task/XMasterPasswordHandling.hpp>

#include <comphelper/processfactory.hxx>
#include <svtools/docpasswdrequest.hxx>

#include "webconninfo.hxx"
#include "webconninfo.hrc"

using namespace ::com::sun::star;

//........................................................................
namespace svx
{
//........................................................................

// class PasswordTable ---------------------------------------------------

PasswordTable::PasswordTable( Window* pParent, const ResId& rResId ) :
    SvxSimpleTable( pParent, rResId )
{
    SetWindowBits( GetStyle() | WB_NOINITIALSELECTION );
}

void PasswordTable::InsertHeaderItem( USHORT nColumn, const String& rText, HeaderBarItemBits nBits )
{
    GetTheHeaderBar()->InsertItem( nColumn, rText, 0, nBits );
}

void PasswordTable::ResetTabs()
{
    SetTabs();
}

void PasswordTable::Resort( bool bForced )
{
    USHORT nColumn = GetSelectedCol();
    if ( 0 == nColumn || bForced ) // only the first column is sorted
    {
        HeaderBarItemBits nBits = GetTheHeaderBar()->GetItemBits(1);
        BOOL bUp = ( ( nBits & HIB_UPARROW ) == HIB_UPARROW );
        SvSortMode eMode = SortAscending;

        if ( bUp )
        {
            nBits &= ~HIB_UPARROW;
            nBits |= HIB_DOWNARROW;
            eMode = SortDescending;
        }
        else
        {
            nBits &= ~HIB_DOWNARROW;
            nBits |= HIB_UPARROW;
        }
        GetTheHeaderBar()->SetItemBits( 1, nBits );
        SvTreeList* pListModel = GetModel();
        pListModel->SetSortMode( eMode );
        pListModel->Resort();
    }
}

// class WebConnectionInfoDialog -----------------------------------------

// -----------------------------------------------------------------------
WebConnectionInfoDialog::WebConnectionInfoDialog( Window* pParent ) :
     ModalDialog( pParent, SVX_RES( RID_SVXDLG_WEBCONNECTION_INFO ) )
    ,m_aNeverShownFI    ( this, SVX_RES( FI_NEVERSHOWN ) )
    ,m_aPasswordsLB     ( this, SVX_RES( LB_PASSWORDS ) )
    ,m_aRemoveBtn       ( this, SVX_RES( PB_REMOVE ) )
    ,m_aRemoveAllBtn    ( this, SVX_RES( PB_REMOVEALL ) )
    ,m_aChangeBtn       ( this, SVX_RES( PB_CHANGE ) )
    ,m_aButtonsFL       ( this, SVX_RES( FL_BUTTONS ) )
    ,m_aCloseBtn        ( this, SVX_RES( PB_CLOSE ) )
    ,m_aHelpBtn         ( this, SVX_RES( PB_HELP ) )

{
    static long aStaticTabs[]= { 3, 0, 150, 250 };
    m_aPasswordsLB.SetTabs( aStaticTabs );
    m_aPasswordsLB.InsertHeaderItem( 1, SVX_RESSTR( STR_WEBSITE ),
        HIB_LEFT | HIB_VCENTER | HIB_FIXEDPOS | HIB_CLICKABLE | HIB_UPARROW );
    m_aPasswordsLB.InsertHeaderItem( 2, SVX_RESSTR( STR_USERNAME ),
        HIB_LEFT | HIB_VCENTER | HIB_FIXEDPOS );
    m_aPasswordsLB.ResetTabs();

    FreeResource();

    m_aPasswordsLB.SetHeaderBarClickHdl( LINK( this, WebConnectionInfoDialog, HeaderBarClickedHdl ) );
    m_aRemoveBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, RemovePasswordHdl ) );
    m_aRemoveAllBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, RemoveAllPasswordsHdl ) );
    m_aChangeBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, ChangePasswordHdl ) );

    // one button too small for its text?
    sal_Int32 i = 0;
    long nBtnTextWidth = 0;
    Window* pButtons[] = { &m_aRemoveBtn, &m_aRemoveAllBtn, &m_aChangeBtn };
    Window** pButton = pButtons;
    const sal_Int32 nBCount = sizeof( pButtons ) / sizeof( pButtons[ 0 ] );
    for ( ; i < nBCount; ++i, ++pButton )
    {
        long nTemp = (*pButton)->GetCtrlTextWidth( (*pButton)->GetText() );
        if ( nTemp > nBtnTextWidth )
            nBtnTextWidth = nTemp;
    }
    nBtnTextWidth = nBtnTextWidth * 115 / 100; // a little offset
    long nButtonWidth = m_aRemoveBtn.GetSizePixel().Width();
    if ( nBtnTextWidth > nButtonWidth )
    {
        // so make the buttons broader and its control in front of it smaller
        long nDelta = nBtnTextWidth - nButtonWidth;
        pButton = pButtons;
        for ( i = 0; i < nBCount; ++i, ++pButton )
        {
            Point aNewPos = (*pButton)->GetPosPixel();
            if ( &m_aRemoveAllBtn == (*pButton) )
                aNewPos.X() += nDelta;
            else if ( &m_aChangeBtn == (*pButton) )
                aNewPos.X() -= nDelta;
            Size aNewSize = (*pButton)->GetSizePixel();
            aNewSize.Width() += nDelta;
            (*pButton)->SetPosSizePixel( aNewPos, aNewSize );
        }
    }

    FillPasswordList();

    m_aRemoveBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, RemovePasswordHdl ) );
    m_aRemoveAllBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, RemoveAllPasswordsHdl ) );
    m_aChangeBtn.SetClickHdl( LINK( this, WebConnectionInfoDialog, ChangePasswordHdl ) );
    m_aPasswordsLB.SetSelectHdl( LINK( this, WebConnectionInfoDialog, EntrySelectedHdl ) );

    m_aRemoveBtn.Enable( FALSE );
    m_aChangeBtn.Enable( FALSE );

    HeaderBarClickedHdl( NULL );
}

// -----------------------------------------------------------------------
WebConnectionInfoDialog::~WebConnectionInfoDialog()
{
}

// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, HeaderBarClickedHdl, SvxSimpleTable*, pTable )
{
    m_aPasswordsLB.Resort( NULL == pTable );
    return 0;
}

// -----------------------------------------------------------------------
void WebConnectionInfoDialog::FillPasswordList()
{
    try
    {
        uno::Reference< task::XMasterPasswordHandling > xMasterPasswd(
            comphelper::getProcessServiceFactory()->createInstance(
                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.PasswordContainer" ) ) ),
            uno::UNO_QUERY );

        if ( xMasterPasswd.is() && xMasterPasswd->isPersistentStoringAllowed() )
        {
            uno::Reference< task::XPasswordContainer > xPasswdContainer( xMasterPasswd, uno::UNO_QUERY_THROW );
            uno::Reference< task::XInteractionHandler > xInteractionHandler(
                comphelper::getProcessServiceFactory()->createInstance(
                    rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.InteractionHandler" ) ) ),
                uno::UNO_QUERY_THROW );

            uno::Sequence< task::UrlRecord > aURLEntries = xPasswdContainer->getAllPersistent( xInteractionHandler );
            sal_Int32 nCount = 0;
            for ( sal_Int32 nURLInd = 0; nURLInd < aURLEntries.getLength(); nURLInd++ )
                for ( sal_Int32 nUserInd = 0; nUserInd < aURLEntries[nURLInd].UserList.getLength(); nUserInd++ )
                {
                    ::rtl::OUString aUIEntry( aURLEntries[nURLInd].Url );
                    aUIEntry += ::rtl::OUString::valueOf( (sal_Unicode)'\t' );
                    aUIEntry += aURLEntries[nURLInd].UserList[nUserInd].UserName;
                    SvLBoxEntry* pEntry = m_aPasswordsLB.InsertEntry( aUIEntry );
                    pEntry->SetUserData( (void*)(nCount++) );
                }
        }
    }
    catch( uno::Exception& )
    {}
}

// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, RemovePasswordHdl, PushButton*, EMPTYARG )
{
    try
    {
        uno::Reference< task::XPasswordContainer > xPasswdContainer(
            comphelper::getProcessServiceFactory()->createInstance(
                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.PasswordContainer" ) ) ),
            uno::UNO_QUERY_THROW );

        uno::Reference< task::XInteractionHandler > xInteractionHandler(
            comphelper::getProcessServiceFactory()->createInstance(
                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.InteractionHandler" ) ) ),
            uno::UNO_QUERY_THROW );

        SvLBoxEntry* pEntry = m_aPasswordsLB.GetCurEntry();
        if ( pEntry )
        {
            ::rtl::OUString aURL = m_aPasswordsLB.GetEntryText( pEntry, 0 );
            ::rtl::OUString aUserName = m_aPasswordsLB.GetEntryText( pEntry, 1 );
            xPasswdContainer->removePersistent( aURL, aUserName );
            m_aPasswordsLB.RemoveEntry( pEntry );
        }
    }
    catch( uno::Exception& )
    {}

    return 0;
}

// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, RemoveAllPasswordsHdl, PushButton*, EMPTYARG )
{
    try
    {
        uno::Reference< task::XPasswordContainer > xPasswdContainer(
            comphelper::getProcessServiceFactory()->createInstance(
                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.PasswordContainer" ) ) ),
            uno::UNO_QUERY_THROW );

        // should the master password be requested before?
        xPasswdContainer->removeAllPersistent();
        m_aPasswordsLB.Clear();
    }
    catch( uno::Exception& )
    {}

    return 0;
}

// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, ChangePasswordHdl, PushButton*, EMPTYARG )
{
    try
    {
        uno::Reference< task::XPasswordContainer > xPasswdContainer(
            comphelper::getProcessServiceFactory()->createInstance(
                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.PasswordContainer" ) ) ),
            uno::UNO_QUERY_THROW );

        uno::Reference< task::XInteractionHandler > xInteractionHandler(
            comphelper::getProcessServiceFactory()->createInstance(
                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.task.InteractionHandler" ) ) ),
            uno::UNO_QUERY_THROW );

        SvLBoxEntry* pEntry = m_aPasswordsLB.GetCurEntry();
        if ( pEntry )
        {
            ::rtl::OUString aURL = m_aPasswordsLB.GetEntryText( pEntry, 0 );
            ::rtl::OUString aUserName = m_aPasswordsLB.GetEntryText( pEntry, 1 );

            RequestDocumentPassword* pPasswordRequest = new RequestDocumentPassword(
                                                               task::PasswordRequestMode_PASSWORD_CREATE,
                                                               aURL );

            uno::Reference< task::XInteractionRequest > rRequest( pPasswordRequest );
            xInteractionHandler->handle( rRequest );
            if ( pPasswordRequest->isPassword() )
            {
                String aNewPass = pPasswordRequest->getPassword();
                uno::Sequence< ::rtl::OUString > aPasswd( 1 );
                aPasswd[0] = aNewPass;
                xPasswdContainer->addPersistent( aURL, aUserName, aPasswd, xInteractionHandler );
            }
        }
    }
    catch( uno::Exception& )
    {}

    return 0;
}

// -----------------------------------------------------------------------
IMPL_LINK( WebConnectionInfoDialog, EntrySelectedHdl, void*, EMPTYARG )
{
    SvLBoxEntry* pEntry = m_aPasswordsLB.GetCurEntry();
    if ( !pEntry )
    {
        m_aRemoveBtn.Enable( FALSE );
        m_aChangeBtn.Enable( FALSE );
    }
    else
    {
        m_aRemoveBtn.Enable( TRUE );
        m_aChangeBtn.Enable( TRUE );
    }

    return 0;
}

//........................................................................
}   // namespace svx
//........................................................................

<|endoftext|>


<commit_before>#pragma once

#include <vector>
#include <algorithm>
#include <stdexcept>

namespace helene
{

namespace detail
{
}

template <class T, class Allocator = std::allocator<T>>
class stable_vector
{
    typedef std::vector<T, Allocator> vector_type;

public:
    typedef typename vector_type::size_type size_type;

public:
    size_type
    add(const T& value)
    {
        // check for vacant position
        if(erased_.size())
        {
            const auto vacant_index = erased_.back();
            erased_.pop_back();

            new(&data_[vacant_index]) T(value);

            return vacant_index;
        }

        const auto new_index = size();
        data_.push_back(value);

        return new_index;
    }

    // access with bounds checking
    T&
    at(size_type index)
    {
        if(std::find(erased_.begin(), erased_.end(), index) != erased_.end())
        {
            throw std::out_of_range("access of deleted element");
        }

        return data_.at(index);
    }

    // access with bounds checking
    const T&
    at(size_type index) const
    {
        if(std::find(erased_.cbegin(), erased_.cend(), index) != erased_.cend())
        {
            throw std::out_of_range("access of deleted element");
        }

        return data_.at(index);
    }

    void
    erase(size_type index)
    {
        (&data_[index])->~T();
        erased_.push_back(index);
    }

    T& operator[](size_type n)
    {
        return data_[n];
    }

    size_type
    size() const
    {
        return data_.size() - erased_.size();
    }

private:
    vector_type data_;
    std::vector<size_type, Allocator> erased_;
};
} // namespace helene
<commit_msg>Add const unchecked element access operator[]. 	modified:   include/stable_container.hpp<commit_after>#pragma once

#include <vector>
#include <algorithm>
#include <stdexcept>

namespace helene
{

namespace detail
{
}

template <class T, class Allocator = std::allocator<T>>
class stable_vector
{
    typedef std::vector<T, Allocator> vector_type;

public:
    typedef typename vector_type::size_type size_type;

public:
    size_type
    add(const T& value)
    {
        // check for vacant position
        if(erased_.size())
        {
            const auto vacant_index = erased_.back();
            erased_.pop_back();

            new(&data_[vacant_index]) T(value);

            return vacant_index;
        }

        const auto new_index = size();
        data_.push_back(value);

        return new_index;
    }

    // access with bounds checking
    T&
    at(size_type index)
    {
        if(std::find(erased_.begin(), erased_.end(), index) != erased_.end())
        {
            throw std::out_of_range("access of deleted element");
        }

        return data_.at(index);
    }

    // access with bounds checking
    const T&
    at(size_type index) const
    {
        if(std::find(erased_.cbegin(), erased_.cend(), index) != erased_.cend())
        {
            throw std::out_of_range("access of deleted element");
        }

        return data_.at(index);
    }

    void
    erase(size_type index)
    {
        (&data_[index])->~T();
        erased_.push_back(index);
    }

    T& operator[](size_type n)
    {
        return data_[n];
    }

    const T& operator[](size_type n) const
    {
        return data_[n];
    }

    size_type
    size() const
    {
        return data_.size() - erased_.size();
    }

private:
    vector_type data_;
    std::vector<size_type, Allocator> erased_;
};
} // namespace helene
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: dbaexchange.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: fs $ $Date: 2001-03-27 14:38:28 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SVX_DBAEXCHANGE_HXX_
#include "dbaexchange.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_SDB_COMMANDTYPE_HPP_
#include <com/sun/star/sdb/CommandType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _SOT_FORMATS_HXX
#include <sot/formats.hxx>
#endif
#ifndef _SOT_EXCHANGE_HXX
#include <sot/exchange.hxx>
#endif

//........................................................................
namespace svx
{
//........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::sdb;
    using namespace ::com::sun::star::sdbcx;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::datatransfer;
    using namespace ::svxform;

    //====================================================================
    //= OColumnTransferable
    //====================================================================
    //--------------------------------------------------------------------
    OColumnTransferable::OColumnTransferable(const ::rtl::OUString& _rDatasource, const sal_Int32 _nCommandType,
            const ::rtl::OUString& _rCommand, const ::rtl::OUString& _rFieldName, sal_Int32 _nFormats)
        :m_nFormatFlags(_nFormats)
    {
        implConstruct(_rDatasource, _nCommandType, _rCommand, _rFieldName);
    }

    //--------------------------------------------------------------------
    OColumnTransferable::OColumnTransferable(const Reference< XPropertySet >& _rxForm,
            const ::rtl::OUString& _rFieldName, sal_Int32 _nFormats)
        :m_nFormatFlags(_nFormats)
    {
        OSL_ENSURE(_rxForm.is(), "OColumnTransferable::OColumnTransferable: invalid form!");
        // collect the necessary information from the form
        ::rtl::OUString sCommand;
        sal_Int32       nCommandType = CommandType::TABLE;
        ::rtl::OUString sDatasource;

        sal_Bool        bTryToParse = sal_True;
        try
        {
            _rxForm->getPropertyValue(FM_PROP_COMMANDTYPE)  >>= nCommandType;
            _rxForm->getPropertyValue(FM_PROP_COMMAND)      >>= sCommand;
            _rxForm->getPropertyValue(FM_PROP_DATASOURCE)   >>= sDatasource;
            bTryToParse = ::cppu::any2bool(_rxForm->getPropertyValue(FM_PROP_ESCAPE_PROCESSING));
        }
        catch(Exception&)
        {
            OSL_ENSURE(sal_False, "OColumnTransferable::OColumnTransferable: could not collect essential data source attributes !");
        }

        // If the data source is an SQL-statement and simple enough (means "select <field list> from <table> where ....")
        // we are able to fake the drag information we are about to create.
        if (bTryToParse)
        {
            try
            {
                // need a query composer for this
                Reference< XSQLQueryComposerFactory > xComposerFac;
                _rxForm->getPropertyValue(FM_PROP_ACTIVE_CONNECTION) >>= xComposerFac;
                Reference< XSQLQueryComposer > xComposer;
                if (xComposerFac.is())
                    xComposer = xComposerFac->createQueryComposer();

                if (xComposer.is())
                {
                    ::rtl::OUString sActivaeCommand;
                    _rxForm->getPropertyValue(FM_PROP_ACTIVECOMMAND) >>= sActivaeCommand;
                    xComposer->setQuery(sActivaeCommand);
                    Reference< XTablesSupplier > xSupTab(xComposer, UNO_QUERY);
                    if(xSupTab.is())
                    {
                        Reference< XNameAccess > xNames = xSupTab->getTables();
                        if (xNames.is())
                        {
                            Sequence< ::rtl::OUString > aTables = xNames->getElementNames();
                            if (1 == aTables.getLength())
                            {
                                sCommand        = aTables[0];
                                nCommandType    = CommandType::TABLE;
                            }
                        }
                    }
                }
            }
            catch(Exception&)
            {
                OSL_ENSURE(sal_False, "OColumnTransferable::OColumnTransferable: could not collect essential data source attributes (part two) !");
            }
        }

        implConstruct(sDatasource, nCommandType, sCommand, _rFieldName);
    }

    //--------------------------------------------------------------------
    void OColumnTransferable::implConstruct(const ::rtl::OUString& _rDatasource, const sal_Int32 _nCommandType,
        const ::rtl::OUString& _rCommand, const ::rtl::OUString& _rFieldName)
    {
        const sal_Unicode       cSeparator = sal_Unicode(11);
        const ::rtl::OUString   sSeparator(&cSeparator, 1);

        m_sCompatibleFormat = ::rtl::OUString();
        m_sCompatibleFormat += _rDatasource;
        m_sCompatibleFormat += sSeparator;
        m_sCompatibleFormat += _rCommand;
        m_sCompatibleFormat += sSeparator;

        sal_Unicode cCommandType;
        switch (_nCommandType)
        {
            case CommandType::TABLE:
                cCommandType = '0';
                break;
            case CommandType::QUERY:
                cCommandType = '1';
                break;
            default:
                cCommandType = '2';
                break;
        }
        m_sCompatibleFormat += ::rtl::OUString(&cCommandType, 1);
        m_sCompatibleFormat += sSeparator;
        m_sCompatibleFormat += _rFieldName;
    }

    //--------------------------------------------------------------------
    void OColumnTransferable::AddSupportedFormats()
    {
        if (CTF_CONTROL_EXCHANGE & m_nFormatFlags)
            AddFormat(SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE);

        if (CTF_FIELD_DESCRIPTOR & m_nFormatFlags)
            AddFormat(SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE);
    }

    //--------------------------------------------------------------------
    sal_Bool OColumnTransferable::GetData( const DataFlavor& _rFlavor )
    {
        switch (SotExchange::GetFormat(_rFlavor))
        {
            case SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE:
            case SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE:
                return SetString(m_sCompatibleFormat, _rFlavor);
        }

        return sal_False;
    }

    //--------------------------------------------------------------------
    sal_Bool OColumnTransferable::canExtractColumnDescriptor(const DataFlavorExVector& _rFlavors, sal_Int32 _nFormats)
    {
        sal_Bool bFieldFormat   = 0 != (_nFormats & CTF_FIELD_DESCRIPTOR);
        sal_Bool bControlFormat = 0 != (_nFormats & CTF_CONTROL_EXCHANGE);
        for (   DataFlavorExVector::const_iterator aCheck = _rFlavors.begin();
                aCheck != _rFlavors.end();
                ++aCheck
            )
        {
            if (bFieldFormat && (SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE == aCheck->mnSotId))
                return sal_True;
            if (bControlFormat && (SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE == aCheck->mnSotId))
                return sal_True;
        }

        return sal_False;
    }

    //--------------------------------------------------------------------
    sal_Bool OColumnTransferable::extractColumnDescriptor(const TransferableDataHelper& _rData,
        ::rtl::OUString& _rDatasource, sal_Int32& _nCommandType, ::rtl::OUString& _rCommand, ::rtl::OUString& _rFieldName)
    {
        // check if we have a format we can use ....
        SotFormatStringId   nRecognizedFormat = 0;
        if (_rData.HasFormat(SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE))
            nRecognizedFormat = SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE;
        if (_rData.HasFormat(SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE))
            nRecognizedFormat = SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE;
        if (!nRecognizedFormat)
            return sal_False;

        String sFieldDescription;
        const_cast<TransferableDataHelper&>(_rData).GetString(nRecognizedFormat, sFieldDescription);

        const sal_Unicode cSeparator = sal_Unicode(11);
        _rDatasource    = sFieldDescription.GetToken(0, cSeparator);
        _rCommand       = sFieldDescription.GetToken(1, cSeparator);
        _nCommandType   = sFieldDescription.GetToken(2, cSeparator).ToInt32();
        _rFieldName     = sFieldDescription.GetToken(3, cSeparator);

        return sal_True;
    }

    //====================================================================
    //= ORowsetTransferable
    //====================================================================
    //--------------------------------------------------------------------
//  ORowsetTransferable::ORowsetTransferable(const String&  _rDatasource, const String& _rName,
//      ObjectType _eObject, const IntArray* _pSelectionList)
//  {
//  }

//........................................................................
}   // namespace svx
//........................................................................

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.1  2001/03/26 15:05:04  fs
 *  initial checkin - helper classes for data access related DnD
 *
 *
 *  Revision 1.0 23.03.01 12:59:54  fs
 ************************************************************************/

<commit_msg>added a data access descriptor format<commit_after>/*************************************************************************
 *
 *  $RCSfile: dbaexchange.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: fs $ $Date: 2001-04-11 12:40:59 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SVX_DBAEXCHANGE_HXX_
#include "dbaexchange.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_SDB_COMMANDTYPE_HPP_
#include <com/sun/star/sdb/CommandType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _SOT_FORMATS_HXX
#include <sot/formats.hxx>
#endif
#ifndef _SOT_EXCHANGE_HXX
#include <sot/exchange.hxx>
#endif
#ifndef _COMPHELPER_PROPERTSETINFO_HXX_
#include <comphelper/propertysetinfo.hxx>
#endif

//........................................................................
namespace svx
{
//........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::sdb;
    using namespace ::com::sun::star::sdbcx;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::datatransfer;
    using namespace ::svxform;
    using namespace ::comphelper;

    //====================================================================
    //= OColumnTransferable
    //====================================================================
    //--------------------------------------------------------------------
    OColumnTransferable::OColumnTransferable(const ::rtl::OUString& _rDatasource, const sal_Int32 _nCommandType,
            const ::rtl::OUString& _rCommand, const ::rtl::OUString& _rFieldName, sal_Int32 _nFormats)
        :m_nFormatFlags(_nFormats)
    {
        implConstruct(_rDatasource, _nCommandType, _rCommand, _rFieldName);
    }

    //--------------------------------------------------------------------
    OColumnTransferable::OColumnTransferable(const Reference< XPropertySet >& _rxForm,
            const ::rtl::OUString& _rFieldName, const Reference< XPropertySet >& _rxColumn, sal_Int32 _nFormats)
        :m_nFormatFlags(_nFormats)
    {
        OSL_ENSURE(_rxForm.is(), "OColumnTransferable::OColumnTransferable: invalid form!");
        // collect the necessary information from the form
        ::rtl::OUString sCommand;
        sal_Int32       nCommandType = CommandType::TABLE;
        ::rtl::OUString sDatasource;

        sal_Bool        bTryToParse = sal_True;
        try
        {
            _rxForm->getPropertyValue(FM_PROP_COMMANDTYPE)  >>= nCommandType;
            _rxForm->getPropertyValue(FM_PROP_COMMAND)      >>= sCommand;
            _rxForm->getPropertyValue(FM_PROP_DATASOURCE)   >>= sDatasource;
            bTryToParse = ::cppu::any2bool(_rxForm->getPropertyValue(FM_PROP_ESCAPE_PROCESSING));
        }
        catch(Exception&)
        {
            OSL_ENSURE(sal_False, "OColumnTransferable::OColumnTransferable: could not collect essential data source attributes !");
        }

        // If the data source is an SQL-statement and simple enough (means "select <field list> from <table> where ....")
        // we are able to fake the drag information we are about to create.
        if (bTryToParse)
        {
            try
            {
                // need a query composer for this
                Reference< XSQLQueryComposerFactory > xComposerFac;
                _rxForm->getPropertyValue(FM_PROP_ACTIVE_CONNECTION) >>= xComposerFac;
                Reference< XSQLQueryComposer > xComposer;
                if (xComposerFac.is())
                    xComposer = xComposerFac->createQueryComposer();

                if (xComposer.is())
                {
                    ::rtl::OUString sActivaeCommand;
                    _rxForm->getPropertyValue(FM_PROP_ACTIVECOMMAND) >>= sActivaeCommand;
                    xComposer->setQuery(sActivaeCommand);
                    Reference< XTablesSupplier > xSupTab(xComposer, UNO_QUERY);
                    if(xSupTab.is())
                    {
                        Reference< XNameAccess > xNames = xSupTab->getTables();
                        if (xNames.is())
                        {
                            Sequence< ::rtl::OUString > aTables = xNames->getElementNames();
                            if (1 == aTables.getLength())
                            {
                                sCommand        = aTables[0];
                                nCommandType    = CommandType::TABLE;
                            }
                        }
                    }
                }
            }
            catch(Exception&)
            {
                OSL_ENSURE(sal_False, "OColumnTransferable::OColumnTransferable: could not collect essential data source attributes (part two) !");
            }
        }

        implConstruct(sDatasource, nCommandType, sCommand, _rFieldName);

        if (_rxColumn.is() && ((m_nFormatFlags & CTF_COLUMN_DESCRIPTOR) == CTF_COLUMN_DESCRIPTOR))
            m_aDescriptor[daColumnObject] <<= _rxColumn;
    }

    //--------------------------------------------------------------------
    sal_uInt32 OColumnTransferable::getDescriptorFormatId()
    {
        static sal_uInt32 s_nFormat = (sal_uInt32)-1;
        if ((sal_uInt32)-1 == s_nFormat)
        {
            s_nFormat = SotExchange::RegisterFormatName(String::CreateFromAscii("svxform.ColumnDescriptorTransfer"));
            OSL_ENSURE((sal_uInt32)-1 != s_nFormat, "OColumnTransferable::getDescriptorFormatId: bad exchange id!");
        }
        return s_nFormat;
    }

    //--------------------------------------------------------------------
    void OColumnTransferable::implConstruct(const ::rtl::OUString& _rDatasource, const sal_Int32 _nCommandType,
        const ::rtl::OUString& _rCommand, const ::rtl::OUString& _rFieldName)
    {
        const sal_Unicode       cSeparator = sal_Unicode(11);
        const ::rtl::OUString   sSeparator(&cSeparator, 1);

        m_sCompatibleFormat = ::rtl::OUString();
        m_sCompatibleFormat += _rDatasource;
        m_sCompatibleFormat += sSeparator;
        m_sCompatibleFormat += _rCommand;
        m_sCompatibleFormat += sSeparator;

        sal_Unicode cCommandType;
        switch (_nCommandType)
        {
            case CommandType::TABLE:
                cCommandType = '0';
                break;
            case CommandType::QUERY:
                cCommandType = '1';
                break;
            default:
                cCommandType = '2';
                break;
        }
        m_sCompatibleFormat += ::rtl::OUString(&cCommandType, 1);
        m_sCompatibleFormat += sSeparator;
        m_sCompatibleFormat += _rFieldName;

        m_aDescriptor.clear();
        if ((m_nFormatFlags & CTF_COLUMN_DESCRIPTOR) == CTF_COLUMN_DESCRIPTOR)
        {
            m_aDescriptor[daDataSource]     <<= _rDatasource;
            m_aDescriptor[daCommand]        <<= _rCommand;
            m_aDescriptor[daCommandType]    <<= _nCommandType;
            m_aDescriptor[daColumnName]     <<= _rFieldName;
        }
    }

    //--------------------------------------------------------------------
    void OColumnTransferable::AddSupportedFormats()
    {
        if (CTF_CONTROL_EXCHANGE & m_nFormatFlags)
            AddFormat(SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE);

        if (CTF_FIELD_DESCRIPTOR & m_nFormatFlags)
            AddFormat(SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE);

        if (CTF_COLUMN_DESCRIPTOR & m_nFormatFlags)
            AddFormat(getDescriptorFormatId());
    }

    //--------------------------------------------------------------------
    sal_Bool OColumnTransferable::GetData( const DataFlavor& _rFlavor )
    {
        const sal_uInt32 nFormatId = SotExchange::GetFormat(_rFlavor);
        switch (nFormatId)
        {
            case SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE:
            case SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE:
                return SetString(m_sCompatibleFormat, _rFlavor);
        }
        if (nFormatId == getDescriptorFormatId())
            return SetAny( makeAny( m_aDescriptor.createPropertyValueSequence() ), _rFlavor );

        return sal_False;
    }

    //--------------------------------------------------------------------
    sal_Bool OColumnTransferable::canExtractColumnDescriptor(const DataFlavorExVector& _rFlavors, sal_Int32 _nFormats)
    {
        sal_Bool bFieldFormat       = 0 != (_nFormats & CTF_FIELD_DESCRIPTOR);
        sal_Bool bControlFormat     = 0 != (_nFormats & CTF_CONTROL_EXCHANGE);
        sal_Bool bDescriptorFormat  = 0 != (_nFormats & CTF_COLUMN_DESCRIPTOR);
        for (   DataFlavorExVector::const_iterator aCheck = _rFlavors.begin();
                aCheck != _rFlavors.end();
                ++aCheck
            )
        {
            if (bFieldFormat && (SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE == aCheck->mnSotId))
                return sal_True;
            if (bControlFormat && (SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE == aCheck->mnSotId))
                return sal_True;
            if (bDescriptorFormat && (getDescriptorFormatId() == aCheck->mnSotId))
                return sal_True;
        }

        return sal_False;
    }

    //--------------------------------------------------------------------
    ODataAccessDescriptor OColumnTransferable::extractColumnDescriptor(const TransferableDataHelper& _rData)
    {
        if (_rData.HasFormat(getDescriptorFormatId()))
        {
            // the object has a real descriptor object (not just the old compatible format)

            // extract the any from the transferable
            DataFlavor aFlavor;
#ifdef _DEBUG
            sal_Bool bSuccess =
#endif
            SotExchange::GetFormatDataFlavor(getDescriptorFormatId(), aFlavor);
            OSL_ENSURE(bSuccess, "OColumnTransferable::extractColumnDescriptor: invalid data format (no flavor)!");

            Any aDescriptor = _rData.GetAny(aFlavor);

            // extract the property value sequence
            Sequence< PropertyValue > aDescriptorProps;
#ifdef _DEBUG
            bSuccess =
#endif
            aDescriptor >>= aDescriptorProps;
            OSL_ENSURE(bSuccess, "OColumnTransferable::extractColumnDescriptor: invalid clipboard format!");

            // build the real descriptor
            return ODataAccessDescriptor(aDescriptorProps);
        }

        // only the old (compatible) format exists -> use the other extract method ...
        ::rtl::OUString sDatasource, sCommand, sFieldName;
        sal_Int32 nCommandType = CommandType::COMMAND;

        ODataAccessDescriptor aDescriptor;
        if (extractColumnDescriptor(_rData, sDatasource, nCommandType, sCommand, sFieldName))
        {
            // and build an own descriptor
            aDescriptor[daDataSource]   <<= sDatasource;
            aDescriptor[daCommand]      <<= sCommand;
            aDescriptor[daCommandType]  <<= nCommandType;
            aDescriptor[daColumnName]   <<= sFieldName;
        }
        return aDescriptor;
    }

    //--------------------------------------------------------------------
    sal_Bool OColumnTransferable::extractColumnDescriptor(const TransferableDataHelper& _rData,
        ::rtl::OUString& _rDatasource, sal_Int32& _nCommandType, ::rtl::OUString& _rCommand, ::rtl::OUString& _rFieldName)
    {
        if (_rData.HasFormat(getDescriptorFormatId()))
        {
            ODataAccessDescriptor aDescriptor = extractColumnDescriptor(_rData);
            aDescriptor[daDataSource]   >>= _rDatasource;
            aDescriptor[daCommand]      >>= _rCommand;
            aDescriptor[daCommandType]  >>= _nCommandType;
            aDescriptor[daColumnName]   >>= _rFieldName;
            return sal_True;
        }

        // check if we have a (string) format we can use ....
        SotFormatStringId   nRecognizedFormat = 0;
        if (_rData.HasFormat(SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE))
            nRecognizedFormat = SOT_FORMATSTR_ID_SBA_FIELDDATAEXCHANGE;
        if (_rData.HasFormat(SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE))
            nRecognizedFormat = SOT_FORMATSTR_ID_SBA_CTRLDATAEXCHANGE;
        if (!nRecognizedFormat)
            return sal_False;

        String sFieldDescription;
        const_cast<TransferableDataHelper&>(_rData).GetString(nRecognizedFormat, sFieldDescription);

        const sal_Unicode cSeparator = sal_Unicode(11);
        _rDatasource    = sFieldDescription.GetToken(0, cSeparator);
        _rCommand       = sFieldDescription.GetToken(1, cSeparator);
        _nCommandType   = sFieldDescription.GetToken(2, cSeparator).ToInt32();
        _rFieldName     = sFieldDescription.GetToken(3, cSeparator);

        return sal_True;
    }

    //====================================================================
    //= ORowsetTransferable
    //====================================================================
    //--------------------------------------------------------------------
//  ORowsetTransferable::ORowsetTransferable(const String&  _rDatasource, const String& _rName,
//      ObjectType _eObject, const IntArray* _pSelectionList)
//  {
//  }

//........................................................................
}   // namespace svx
//........................................................................

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.2  2001/03/27 14:38:28  fs
 *  swap the order in which the clipboard formats are added
 *
 *  Revision 1.1  2001/03/26 15:05:04  fs
 *  initial checkin - helper classes for data access related DnD
 *
 *
 *  Revision 1.0 23.03.01 12:59:54  fs
 ************************************************************************/

<|endoftext|>


<commit_before>#pragma once

#include <staticjson/error.hpp>

#include <cstddef>
#include <cstdint>
#include <memory>
#include <unordered_map>

namespace staticjson
{
struct NonMobile
{
    NonMobile() {}
    ~NonMobile() {}
    NonMobile(const NonMobile&) = delete;
    NonMobile(NonMobile&&) = delete;
    NonMobile& operator=(const NonMobile&) = delete;
    NonMobile& operator=(NonMobile&&) = delete;
};

typedef unsigned int SizeType;

class IHandler
{
public:
    IHandler() {}

    virtual ~IHandler();

    virtual bool Null() = 0;

    virtual bool Bool(bool) = 0;

    virtual bool Int(int) = 0;

    virtual bool Uint(unsigned) = 0;

    virtual bool Int64(std::int64_t) = 0;

    virtual bool Uint64(std::uint64_t) = 0;

    virtual bool Double(double) = 0;

    virtual bool String(const char*, SizeType, bool) = 0;

    virtual bool StartObject() = 0;

    virtual bool Key(const char*, SizeType, bool) = 0;

    virtual bool EndObject(SizeType) = 0;

    virtual bool StartArray() = 0;

    virtual bool EndArray(SizeType) = 0;

    virtual bool RawNumber() { return true; }

    virtual void prepare_for_reuse() = 0;
};

class NullableHandler;

class BaseHandler : public IHandler, private NonMobile
{
    friend class NullableHandler;

protected:
    std::unique_ptr<ErrorBase> the_error;
    bool parsed = false;

protected:
    bool set_out_of_range(const char* actual_type);
    bool set_type_mismatch(const char* actual_type);

    virtual void reset() {}

public:
    BaseHandler() {}

    virtual ~BaseHandler();

    virtual std::string type_name() const = 0;

    virtual bool Null() override { return set_type_mismatch("null"); }

    virtual bool Bool(bool) override { return set_type_mismatch("bool"); }

    virtual bool Int(int) override { return set_type_mismatch("int"); }

    virtual bool Uint(unsigned) override { return set_type_mismatch("unsigned"); }

    virtual bool Int64(std::int64_t) override { return set_type_mismatch("int64_t"); }

    virtual bool Uint64(std::uint64_t) override { return set_type_mismatch("uint64_t"); }

    virtual bool Double(double) override { return set_type_mismatch("double"); }

    virtual bool String(const char*, SizeType, bool) override
    {
        return set_type_mismatch("string");
    }

    virtual bool StartObject() override { return set_type_mismatch("object"); }

    virtual bool Key(const char*, SizeType, bool) override { return set_type_mismatch("object"); }

    virtual bool EndObject(SizeType) override { return set_type_mismatch("object"); }

    virtual bool StartArray() override { return set_type_mismatch("array"); }

    virtual bool EndArray(SizeType) override { return set_type_mismatch("array"); }

    virtual bool has_error() const { return bool(the_error); }

    virtual bool reap_error(ErrorStack& errs)
    {
        if (!the_error)
            return false;
        errs.push(the_error.release());
        return true;
    }

    bool is_parsed() const { return parsed; }

    void prepare_for_reuse() override
    {
        the_error.reset();
        parsed = false;
        reset();
    }

    virtual bool write(IHandler* output) const = 0;
};

struct Flags
{
    static const unsigned Default = 0x0, AllowDuplicateKey = 0x1, Optional = 0x2, IgnoreRead = 0x4,
                          IgnoreWrite = 0x8, DisallowUnknownKey = 0x16;
};

// Forward declaration
template <class T>
class Handler;

class ObjectHandler : public BaseHandler
{
protected:
    struct FlaggedHandler
    {
        std::unique_ptr<BaseHandler> handler;
        unsigned flags;
    };

protected:
    std::unordered_map<std::string, FlaggedHandler> internals;
    FlaggedHandler* current = nullptr;
    std::string current_name;
    int depth = 0;
    unsigned flags = Flags::Default;

protected:
    bool precheck(const char* type);
    bool postcheck(bool success);
    void set_missing_required(const std::string& name);
    void reset() override;

public:
    ObjectHandler();

    ~ObjectHandler();

    std::string type_name() const override;

    virtual bool Null() override;

    virtual bool Bool(bool) override;

    virtual bool Int(int) override;

    virtual bool Uint(unsigned) override;

    virtual bool Int64(std::int64_t) override;

    virtual bool Uint64(std::uint64_t) override;

    virtual bool Double(double) override;

    virtual bool String(const char*, SizeType, bool) override;

    virtual bool StartObject() override;

    virtual bool Key(const char*, SizeType, bool) override;

    virtual bool EndObject(SizeType) override;

    virtual bool StartArray() override;

    virtual bool EndArray(SizeType) override;

    virtual bool reap_error(ErrorStack&) override;

    virtual bool write(IHandler* output) const override;

    unsigned get_flags() const { return flags; }

    void set_flags(unsigned f) { flags = f; }

    template <class T>
    void add_property(const std::string& name, T* pointer, unsigned flags_ = Flags::Default)
    {
        FlaggedHandler fh;
        fh.handler.reset(new Handler<T>(pointer));
        fh.flags = flags_;
        internals.emplace(name, std::move(fh));
    }
};

template <class T>
class Handler : public ObjectHandler
{
public:
    explicit Handler(T* t) { t->staticjson_init(this); }
};
}<commit_msg>Use map instead of hash map<commit_after>#pragma once

#include <staticjson/error.hpp>

#include <cstddef>
#include <cstdint>
#include <map>
#include <memory>

namespace staticjson
{
struct NonMobile
{
    NonMobile() {}
    ~NonMobile() {}
    NonMobile(const NonMobile&) = delete;
    NonMobile(NonMobile&&) = delete;
    NonMobile& operator=(const NonMobile&) = delete;
    NonMobile& operator=(NonMobile&&) = delete;
};

typedef unsigned int SizeType;

class IHandler
{
public:
    IHandler() {}

    virtual ~IHandler();

    virtual bool Null() = 0;

    virtual bool Bool(bool) = 0;

    virtual bool Int(int) = 0;

    virtual bool Uint(unsigned) = 0;

    virtual bool Int64(std::int64_t) = 0;

    virtual bool Uint64(std::uint64_t) = 0;

    virtual bool Double(double) = 0;

    virtual bool String(const char*, SizeType, bool) = 0;

    virtual bool StartObject() = 0;

    virtual bool Key(const char*, SizeType, bool) = 0;

    virtual bool EndObject(SizeType) = 0;

    virtual bool StartArray() = 0;

    virtual bool EndArray(SizeType) = 0;

    virtual bool RawNumber() { return true; }

    virtual void prepare_for_reuse() = 0;
};

class NullableHandler;

class BaseHandler : public IHandler, private NonMobile
{
    friend class NullableHandler;

protected:
    std::unique_ptr<ErrorBase> the_error;
    bool parsed = false;

protected:
    bool set_out_of_range(const char* actual_type);
    bool set_type_mismatch(const char* actual_type);

    virtual void reset() {}

public:
    BaseHandler() {}

    virtual ~BaseHandler();

    virtual std::string type_name() const = 0;

    virtual bool Null() override { return set_type_mismatch("null"); }

    virtual bool Bool(bool) override { return set_type_mismatch("bool"); }

    virtual bool Int(int) override { return set_type_mismatch("int"); }

    virtual bool Uint(unsigned) override { return set_type_mismatch("unsigned"); }

    virtual bool Int64(std::int64_t) override { return set_type_mismatch("int64_t"); }

    virtual bool Uint64(std::uint64_t) override { return set_type_mismatch("uint64_t"); }

    virtual bool Double(double) override { return set_type_mismatch("double"); }

    virtual bool String(const char*, SizeType, bool) override
    {
        return set_type_mismatch("string");
    }

    virtual bool StartObject() override { return set_type_mismatch("object"); }

    virtual bool Key(const char*, SizeType, bool) override { return set_type_mismatch("object"); }

    virtual bool EndObject(SizeType) override { return set_type_mismatch("object"); }

    virtual bool StartArray() override { return set_type_mismatch("array"); }

    virtual bool EndArray(SizeType) override { return set_type_mismatch("array"); }

    virtual bool has_error() const { return bool(the_error); }

    virtual bool reap_error(ErrorStack& errs)
    {
        if (!the_error)
            return false;
        errs.push(the_error.release());
        return true;
    }

    bool is_parsed() const { return parsed; }

    void prepare_for_reuse() override
    {
        the_error.reset();
        parsed = false;
        reset();
    }

    virtual bool write(IHandler* output) const = 0;
};

struct Flags
{
    static const unsigned Default = 0x0, AllowDuplicateKey = 0x1, Optional = 0x2, IgnoreRead = 0x4,
                          IgnoreWrite = 0x8, DisallowUnknownKey = 0x16;
};

// Forward declaration
template <class T>
class Handler;

class ObjectHandler : public BaseHandler
{
protected:
    struct FlaggedHandler
    {
        std::unique_ptr<BaseHandler> handler;
        unsigned flags;
    };

protected:
    std::map<std::string, FlaggedHandler> internals;
    FlaggedHandler* current = nullptr;
    std::string current_name;
    int depth = 0;
    unsigned flags = Flags::Default;

protected:
    bool precheck(const char* type);
    bool postcheck(bool success);
    void set_missing_required(const std::string& name);
    void reset() override;

public:
    ObjectHandler();

    ~ObjectHandler();

    std::string type_name() const override;

    virtual bool Null() override;

    virtual bool Bool(bool) override;

    virtual bool Int(int) override;

    virtual bool Uint(unsigned) override;

    virtual bool Int64(std::int64_t) override;

    virtual bool Uint64(std::uint64_t) override;

    virtual bool Double(double) override;

    virtual bool String(const char*, SizeType, bool) override;

    virtual bool StartObject() override;

    virtual bool Key(const char*, SizeType, bool) override;

    virtual bool EndObject(SizeType) override;

    virtual bool StartArray() override;

    virtual bool EndArray(SizeType) override;

    virtual bool reap_error(ErrorStack&) override;

    virtual bool write(IHandler* output) const override;

    unsigned get_flags() const { return flags; }

    void set_flags(unsigned f) { flags = f; }

    template <class T>
    void add_property(const std::string& name, T* pointer, unsigned flags_ = Flags::Default)
    {
        FlaggedHandler fh;
        fh.handler.reset(new Handler<T>(pointer));
        fh.flags = flags_;
        internals.emplace(name, std::move(fh));
    }
};

template <class T>
class Handler : public ObjectHandler
{
public:
    explicit Handler(T* t) { t->staticjson_init(this); }
};
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: codegen.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-03-29 11:48:48 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <svtools/sbx.hxx>
#include "sbcomp.hxx"
#pragma hdrstop
#include "image.hxx"

// nInc ist die Inkrementgroesse der Puffer

SbiCodeGen::SbiCodeGen( SbModule& r, SbiParser* p, short nInc )
         : rMod( r ), aCode( p, nInc )
{
    pParser = p;
    bStmnt = FALSE;
    nLine = 0;
    nCol = 0;
    nForLevel = 0;
}

USHORT SbiCodeGen::GetPC()
{
    return aCode.GetSize();
}

// Statement merken

void SbiCodeGen::Statement()
{
    bStmnt = TRUE;

    nLine = pParser->GetLine();
    nCol  = pParser->GetCol1();

    // #29955 Information der for-Schleifen-Ebene
    // in oberen Byte der Spalte speichern
    nCol = (nCol & 0xff) + 0x100 * nForLevel;
}

// Anfang eines Statements markieren

void SbiCodeGen::GenStmnt()
{
    if( bStmnt )
    {
        bStmnt = FALSE;
        Gen( _STMNT, nLine, nCol );
    }
}

// Die Gen-Routinen returnen den Offset des 1. Operanden,
// damit Jumps dort ihr Backchain versenken koennen

USHORT SbiCodeGen::Gen( SbiOpcode eOpcode )
{
#ifndef PRODUCT
    if( eOpcode < SbOP0_START || eOpcode > SbOP0_END )
        pParser->Error( SbERR_INTERNAL_ERROR, "OPCODE1" );
#endif
    GenStmnt();
    aCode += (UINT8) eOpcode;
    return GetPC();
}

USHORT SbiCodeGen::Gen( SbiOpcode eOpcode, UINT16 nOpnd )
{
#ifndef PRODUCT
    if( eOpcode < SbOP1_START || eOpcode > SbOP1_END )
        pParser->Error( SbERR_INTERNAL_ERROR, "OPCODE2" );
#endif
    GenStmnt();
    aCode += (UINT8) eOpcode;
    USHORT n = GetPC();
    aCode += nOpnd;
    return n;
}

USHORT SbiCodeGen::Gen( SbiOpcode eOpcode, UINT16 nOpnd1, UINT16 nOpnd2 )
{
#ifndef PRODUCT
    if( eOpcode < SbOP2_START || eOpcode > SbOP2_END )
        pParser->Error( SbERR_INTERNAL_ERROR, "OPCODE3" );
#endif
    GenStmnt();
    aCode += (UINT8) eOpcode;
    USHORT n = GetPC();
    aCode += nOpnd1;
    aCode += nOpnd2;
    return n;
}

// Abspeichern des erzeugten Images im Modul

void SbiCodeGen::Save()
{
    SbiImage* p = new SbiImage;
    if( !p )
    {
        SbERR_NO_MEMORY; return;
    }
    rMod.StartDefinitions();
    // OPTION BASE-Wert:
    p->nDimBase = pParser->nBase;
    // OPTION EXPLICIT-Flag uebernehmen
    if( pParser->bExplicit )
        p->SetFlag( SBIMG_EXPLICIT );

    int nIfaceCount = 0;
    if( pParser->bClassModule )
    {
        p->SetFlag( SBIMG_CLASSMODULE );
        pCLASSFAC->AddClassModule( &rMod );

        nIfaceCount = pParser->aIfaceVector.size();
        if( nIfaceCount )
        {
            if( !rMod.pClassData )
                rMod.pClassData = new SbClassData;

            for( int i = 0 ; i < nIfaceCount ; i++ )
            {
                const String& rIfaceName = pParser->aIfaceVector[i];
                SbxVariable* pIfaceVar = new SbxVariable( SbxVARIANT );
                pIfaceVar->SetName( rIfaceName );
                SbxArray* pIfaces = rMod.pClassData->mxIfaces;
                pIfaces->Insert( pIfaceVar, pIfaces->Count() );
            }
        }
    }
    else
    {
        pCLASSFAC->RemoveClassModule( &rMod );
    }
    if( pParser->bText )
        p->SetFlag( SBIMG_COMPARETEXT );
    // GlobalCode-Flag
    if( pParser->HasGlobalCode() )
        p->SetFlag( SBIMG_INITCODE );
    // Die Entrypoints:
    for( SbiSymDef* pDef = pParser->aPublics.First(); pDef;
                   pDef = pParser->aPublics.Next() )
    {
        SbiProcDef* pProc = pDef->GetProcDef();
        if( pProc && pProc->IsDefined() )
        {
            String aProcName = pProc->GetName();
            String aIfaceProcName;
            String aIfaceName;
            USHORT nPassCount = 1;
            if( nIfaceCount )
            {
                int nPropPrefixFound =
                    aProcName.Search( String( RTL_CONSTASCII_USTRINGPARAM("Property ") ) );
                String aPureProcName = aProcName;
                String aPropPrefix;
                if( nPropPrefixFound == 0 )
                {
                    aPropPrefix = aProcName.Copy( 0, 13 );      // 13 == Len( "Property ?et " )
                    aPureProcName = aProcName.Copy( 13 );
                }
                for( int i = 0 ; i < nIfaceCount ; i++ )
                {
                    const String& rIfaceName = pParser->aIfaceVector[i];
                    int nFound = aPureProcName.Search( rIfaceName );
                    if( nFound == 0 && '_' == aPureProcName.GetChar( rIfaceName.Len() ) )
                    {
                        if( nPropPrefixFound == 0 )
                            aIfaceProcName += aPropPrefix;
                        aIfaceProcName += aPureProcName.Copy( rIfaceName.Len() + 1 );
                        aIfaceName = rIfaceName;
                        nPassCount = 2;
                        break;
                    }
                }
            }
            SbMethod* pMeth;
            for( USHORT nPass = 0 ; nPass < nPassCount ; nPass++ )
            {
                if( nPass == 1 )
                    aProcName = aIfaceProcName;

                PropertyMode ePropMode = pProc->getPropertyMode();
                if( ePropMode != PROPERTY_MODE_NONE )
                {
                    SbxDataType ePropType;
                    switch( ePropMode )
                    {
                        case PROPERTY_MODE_GET:
                            ePropType = pProc->GetType();
                            break;
                        case PROPERTY_MODE_LET:
                        {
                            // type == type of first parameter
                            ePropType = SbxVARIANT;     // Default
                            SbiSymPool* pPool = &pProc->GetParams();
                            if( pPool->GetSize() > 1 )
                            {
                                SbiSymDef* pPar = pPool->Get( 1 );
                                if( pPar )
                                    ePropType = pPar->GetType();
                            }
                            break;
                        }
                        case PROPERTY_MODE_SET:
                            ePropType = SbxOBJECT;
                            break;
                    }
                    String aPropName = pProc->GetPropName();
                    if( nPass == 1 )
                        aPropName = aPropName.Copy( aIfaceName.Len() + 1 );
                    SbProcedureProperty* pProcedureProperty =
                        rMod.GetProcedureProperty( aPropName, ePropType );
                        // rMod.GetProcedureProperty( pProc->GetPropName(), ePropType );
                }
                if( nPass == 1 )
                {
                    SbIfaceMapperMethod* pMapperMeth =
                        rMod.GetIfaceMapperMethod( aProcName, pMeth );
                }
                else
                {
                    pMeth = rMod.GetMethod( aProcName, pProc->GetType() );

                    // #110004
                    if( !pProc->IsPublic() )
                        pMeth->SetFlag( SBX_PRIVATE );

                    pMeth->nStart = pProc->GetAddr();
                    pMeth->nLine1 = pProc->GetLine1();
                    pMeth->nLine2 = pProc->GetLine2();
                    // Die Parameter:
                    SbxInfo* pInfo = pMeth->GetInfo();
                    String aHelpFile, aComment;
                    ULONG nHelpId = 0;
                    if( pInfo )
                    {
                        // Die Zusatzdaten retten
                        aHelpFile = pInfo->GetHelpFile();
                        aComment  = pInfo->GetComment();
                        nHelpId   = pInfo->GetHelpId();
                    }
                    // Und die Parameterliste neu aufbauen
                    pInfo = new SbxInfo( aHelpFile, nHelpId );
                    pInfo->SetComment( aComment );
                    SbiSymPool* pPool = &pProc->GetParams();
                    // Das erste Element ist immer der Funktionswert!
                    for( USHORT i = 1; i < pPool->GetSize(); i++ )
                    {
                        SbiSymDef* pPar = pPool->Get( i );
                        SbxDataType t = pPar->GetType();
                        if( !pPar->IsByVal() )
                            t = (SbxDataType) ( t | SbxBYREF );
                        if( pPar->GetDims() )
                            t = (SbxDataType) ( t | SbxARRAY );
                        // #33677 Optional-Info durchreichen
                        USHORT nFlags = SBX_READ;
                        if( pPar->IsOptional() )
                            nFlags |= SBX_OPTIONAL;

                        pInfo->AddParam( pPar->GetName(), t, nFlags );

                        UINT32 nUserData = 0;
                        USHORT nDefaultId = pPar->GetDefaultId();
                        if( nDefaultId )
                            nUserData |= nDefaultId;
                        if( pPar->IsParamArray() )
                            nUserData |= PARAM_INFO_PARAMARRAY;
                        if( nUserData )
                        {
                            SbxParamInfo* pParam = (SbxParamInfo*)pInfo->GetParam( i );
                            pParam->nUserData = nUserData;
                        }
                    }
                    pMeth->SetInfo( pInfo );
                }

            }   // for( iPass...
        }
    }
    // Der Code
    p->AddCode( aCode.GetBuffer(), aCode.GetSize() );

    // Der globale StringPool. 0 ist nicht belegt.
    SbiStringPool* pPool = &pParser->aGblStrings;
    USHORT nSize = pPool->GetSize();
    p->MakeStrings( nSize );
    USHORT i;
    for( i = 1; i <= nSize; i++ )
        p->AddString( pPool->Find( i ) );

    // Typen einfuegen
    USHORT nCount = pParser->rTypeArray->Count();
    for (i = 0; i < nCount; i++)
         p->AddType((SbxObject *)pParser->rTypeArray->Get(i));

    // Insert enum objects
    nCount = pParser->rEnumArray->Count();
    for (i = 0; i < nCount; i++)
         p->AddEnum((SbxObject *)pParser->rEnumArray->Get(i));

    if( !p->IsError() )
        rMod.pImage = p;
    else
        delete p;

    rMod.EndDefinitions();
}

<commit_msg>INTEGRATION: CWS visibility03 (1.6.8); FILE MERGED 2005/04/06 15:23:45 mhu 1.6.8.2: RESYNC: (1.6-1.7); FILE MERGED 2005/03/24 18:01:17 mhu 1.6.8.1: #i45006# Adapted to moved sbx headers.<commit_after>/*************************************************************************
 *
 *  $RCSfile: codegen.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2005-04-13 09:10:55 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <sbx.hxx>
#include "sbcomp.hxx"
#pragma hdrstop
#include "image.hxx"

// nInc ist die Inkrementgroesse der Puffer

SbiCodeGen::SbiCodeGen( SbModule& r, SbiParser* p, short nInc )
         : rMod( r ), aCode( p, nInc )
{
    pParser = p;
    bStmnt = FALSE;
    nLine = 0;
    nCol = 0;
    nForLevel = 0;
}

USHORT SbiCodeGen::GetPC()
{
    return aCode.GetSize();
}

// Statement merken

void SbiCodeGen::Statement()
{
    bStmnt = TRUE;

    nLine = pParser->GetLine();
    nCol  = pParser->GetCol1();

    // #29955 Information der for-Schleifen-Ebene
    // in oberen Byte der Spalte speichern
    nCol = (nCol & 0xff) + 0x100 * nForLevel;
}

// Anfang eines Statements markieren

void SbiCodeGen::GenStmnt()
{
    if( bStmnt )
    {
        bStmnt = FALSE;
        Gen( _STMNT, nLine, nCol );
    }
}

// Die Gen-Routinen returnen den Offset des 1. Operanden,
// damit Jumps dort ihr Backchain versenken koennen

USHORT SbiCodeGen::Gen( SbiOpcode eOpcode )
{
#ifndef PRODUCT
    if( eOpcode < SbOP0_START || eOpcode > SbOP0_END )
        pParser->Error( SbERR_INTERNAL_ERROR, "OPCODE1" );
#endif
    GenStmnt();
    aCode += (UINT8) eOpcode;
    return GetPC();
}

USHORT SbiCodeGen::Gen( SbiOpcode eOpcode, UINT16 nOpnd )
{
#ifndef PRODUCT
    if( eOpcode < SbOP1_START || eOpcode > SbOP1_END )
        pParser->Error( SbERR_INTERNAL_ERROR, "OPCODE2" );
#endif
    GenStmnt();
    aCode += (UINT8) eOpcode;
    USHORT n = GetPC();
    aCode += nOpnd;
    return n;
}

USHORT SbiCodeGen::Gen( SbiOpcode eOpcode, UINT16 nOpnd1, UINT16 nOpnd2 )
{
#ifndef PRODUCT
    if( eOpcode < SbOP2_START || eOpcode > SbOP2_END )
        pParser->Error( SbERR_INTERNAL_ERROR, "OPCODE3" );
#endif
    GenStmnt();
    aCode += (UINT8) eOpcode;
    USHORT n = GetPC();
    aCode += nOpnd1;
    aCode += nOpnd2;
    return n;
}

// Abspeichern des erzeugten Images im Modul

void SbiCodeGen::Save()
{
    SbiImage* p = new SbiImage;
    if( !p )
    {
        SbERR_NO_MEMORY; return;
    }
    rMod.StartDefinitions();
    // OPTION BASE-Wert:
    p->nDimBase = pParser->nBase;
    // OPTION EXPLICIT-Flag uebernehmen
    if( pParser->bExplicit )
        p->SetFlag( SBIMG_EXPLICIT );

    int nIfaceCount = 0;
    if( pParser->bClassModule )
    {
        p->SetFlag( SBIMG_CLASSMODULE );
        pCLASSFAC->AddClassModule( &rMod );

        nIfaceCount = pParser->aIfaceVector.size();
        if( nIfaceCount )
        {
            if( !rMod.pClassData )
                rMod.pClassData = new SbClassData;

            for( int i = 0 ; i < nIfaceCount ; i++ )
            {
                const String& rIfaceName = pParser->aIfaceVector[i];
                SbxVariable* pIfaceVar = new SbxVariable( SbxVARIANT );
                pIfaceVar->SetName( rIfaceName );
                SbxArray* pIfaces = rMod.pClassData->mxIfaces;
                pIfaces->Insert( pIfaceVar, pIfaces->Count() );
            }
        }
    }
    else
    {
        pCLASSFAC->RemoveClassModule( &rMod );
    }
    if( pParser->bText )
        p->SetFlag( SBIMG_COMPARETEXT );
    // GlobalCode-Flag
    if( pParser->HasGlobalCode() )
        p->SetFlag( SBIMG_INITCODE );
    // Die Entrypoints:
    for( SbiSymDef* pDef = pParser->aPublics.First(); pDef;
                   pDef = pParser->aPublics.Next() )
    {
        SbiProcDef* pProc = pDef->GetProcDef();
        if( pProc && pProc->IsDefined() )
        {
            String aProcName = pProc->GetName();
            String aIfaceProcName;
            String aIfaceName;
            USHORT nPassCount = 1;
            if( nIfaceCount )
            {
                int nPropPrefixFound =
                    aProcName.Search( String( RTL_CONSTASCII_USTRINGPARAM("Property ") ) );
                String aPureProcName = aProcName;
                String aPropPrefix;
                if( nPropPrefixFound == 0 )
                {
                    aPropPrefix = aProcName.Copy( 0, 13 );      // 13 == Len( "Property ?et " )
                    aPureProcName = aProcName.Copy( 13 );
                }
                for( int i = 0 ; i < nIfaceCount ; i++ )
                {
                    const String& rIfaceName = pParser->aIfaceVector[i];
                    int nFound = aPureProcName.Search( rIfaceName );
                    if( nFound == 0 && '_' == aPureProcName.GetChar( rIfaceName.Len() ) )
                    {
                        if( nPropPrefixFound == 0 )
                            aIfaceProcName += aPropPrefix;
                        aIfaceProcName += aPureProcName.Copy( rIfaceName.Len() + 1 );
                        aIfaceName = rIfaceName;
                        nPassCount = 2;
                        break;
                    }
                }
            }
            SbMethod* pMeth;
            for( USHORT nPass = 0 ; nPass < nPassCount ; nPass++ )
            {
                if( nPass == 1 )
                    aProcName = aIfaceProcName;

                PropertyMode ePropMode = pProc->getPropertyMode();
                if( ePropMode != PROPERTY_MODE_NONE )
                {
                    SbxDataType ePropType;
                    switch( ePropMode )
                    {
                        case PROPERTY_MODE_GET:
                            ePropType = pProc->GetType();
                            break;
                        case PROPERTY_MODE_LET:
                        {
                            // type == type of first parameter
                            ePropType = SbxVARIANT;     // Default
                            SbiSymPool* pPool = &pProc->GetParams();
                            if( pPool->GetSize() > 1 )
                            {
                                SbiSymDef* pPar = pPool->Get( 1 );
                                if( pPar )
                                    ePropType = pPar->GetType();
                            }
                            break;
                        }
                        case PROPERTY_MODE_SET:
                            ePropType = SbxOBJECT;
                            break;
                    }
                    String aPropName = pProc->GetPropName();
                    if( nPass == 1 )
                        aPropName = aPropName.Copy( aIfaceName.Len() + 1 );
                    SbProcedureProperty* pProcedureProperty =
                        rMod.GetProcedureProperty( aPropName, ePropType );
                        // rMod.GetProcedureProperty( pProc->GetPropName(), ePropType );
                }
                if( nPass == 1 )
                {
                    SbIfaceMapperMethod* pMapperMeth =
                        rMod.GetIfaceMapperMethod( aProcName, pMeth );
                }
                else
                {
                    pMeth = rMod.GetMethod( aProcName, pProc->GetType() );

                    // #110004
                    if( !pProc->IsPublic() )
                        pMeth->SetFlag( SBX_PRIVATE );

                    pMeth->nStart = pProc->GetAddr();
                    pMeth->nLine1 = pProc->GetLine1();
                    pMeth->nLine2 = pProc->GetLine2();
                    // Die Parameter:
                    SbxInfo* pInfo = pMeth->GetInfo();
                    String aHelpFile, aComment;
                    ULONG nHelpId = 0;
                    if( pInfo )
                    {
                        // Die Zusatzdaten retten
                        aHelpFile = pInfo->GetHelpFile();
                        aComment  = pInfo->GetComment();
                        nHelpId   = pInfo->GetHelpId();
                    }
                    // Und die Parameterliste neu aufbauen
                    pInfo = new SbxInfo( aHelpFile, nHelpId );
                    pInfo->SetComment( aComment );
                    SbiSymPool* pPool = &pProc->GetParams();
                    // Das erste Element ist immer der Funktionswert!
                    for( USHORT i = 1; i < pPool->GetSize(); i++ )
                    {
                        SbiSymDef* pPar = pPool->Get( i );
                        SbxDataType t = pPar->GetType();
                        if( !pPar->IsByVal() )
                            t = (SbxDataType) ( t | SbxBYREF );
                        if( pPar->GetDims() )
                            t = (SbxDataType) ( t | SbxARRAY );
                        // #33677 Optional-Info durchreichen
                        USHORT nFlags = SBX_READ;
                        if( pPar->IsOptional() )
                            nFlags |= SBX_OPTIONAL;

                        pInfo->AddParam( pPar->GetName(), t, nFlags );

                        UINT32 nUserData = 0;
                        USHORT nDefaultId = pPar->GetDefaultId();
                        if( nDefaultId )
                            nUserData |= nDefaultId;
                        if( pPar->IsParamArray() )
                            nUserData |= PARAM_INFO_PARAMARRAY;
                        if( nUserData )
                        {
                            SbxParamInfo* pParam = (SbxParamInfo*)pInfo->GetParam( i );
                            pParam->nUserData = nUserData;
                        }
                    }
                    pMeth->SetInfo( pInfo );
                }

            }   // for( iPass...
        }
    }
    // Der Code
    p->AddCode( aCode.GetBuffer(), aCode.GetSize() );

    // Der globale StringPool. 0 ist nicht belegt.
    SbiStringPool* pPool = &pParser->aGblStrings;
    USHORT nSize = pPool->GetSize();
    p->MakeStrings( nSize );
    USHORT i;
    for( i = 1; i <= nSize; i++ )
        p->AddString( pPool->Find( i ) );

    // Typen einfuegen
    USHORT nCount = pParser->rTypeArray->Count();
    for (i = 0; i < nCount; i++)
         p->AddType((SbxObject *)pParser->rTypeArray->Get(i));

    // Insert enum objects
    nCount = pParser->rEnumArray->Count();
    for (i = 0; i < nCount; i++)
         p->AddEnum((SbxObject *)pParser->rEnumArray->Get(i));

    if( !p->IsError() )
        rMod.pImage = p;
    else
        delete p;

    rMod.EndDefinitions();
}

<|endoftext|>


<commit_before>#pragma once

#include <cassert>
#include <tudocomp/def.hpp>
#include <tudocomp/util/View.hpp>

namespace tdc {

/// \brief Contains a literal and its location in the input.
///
/// This structure is used by encoders to get a glimpse at the literals it will
/// receive. The encoder is given a stream of literals and their occurences in
/// the compressed text. This information can be used to initialize data
/// structures that can be used for efficient encoding, e.g. a Huffman tree
/// or a k-mer dictionary.
struct Literal {
    /// The literal.
    uliteral_t c;

    /// The position of the literal in the input.
    len_t pos;
};

class LiteralIterator {
};

/// \brief An empty literal iterator that yields no literals whatsoever.
class NoLiterals : LiteralIterator {
public:
    /// \brief Constructor.
    inline NoLiterals() {}

    /// \brief Tests whether there are more literals in the stream.
    /// \return \e true if there are more literals in the stream, \e false
    ///         otherwise.
    inline bool has_next() const { return false; }

    /// \brief Yields the next literal from the stream.
    /// \return The next literal from the stream.
    inline Literal next() { assert(false); return Literal{0, 0}; }
};

/// \brief A literal iterator that yields every character from a \ref View.
class ViewLiterals : LiteralIterator {
private:
    View m_view;
    len_t m_index;

public:
    /// \brief Constructor.
    ///
    /// \param view The view to iterate over.
    inline ViewLiterals(View view) : m_view(view), m_index(0) {
    }

    /// \brief Tests whether there are more literals in the stream.
    /// \return \e true if there are more literals in the stream, \e false
    ///         otherwise.
    inline bool has_next() const {
        return m_index < m_view.size();
    }

    /// \brief Yields the next literal from the stream.
    /// \return The next literal from the stream.
    inline Literal next() {
        assert(has_next());

        auto i = m_index++;
        return Literal { uliteral_t(m_view[i]), i };
    }
};

}

<commit_msg>Move NoLiterals impl to LiteralIterator base so the functions are declared in it<commit_after>#pragma once

#include <cassert>
#include <tudocomp/def.hpp>
#include <tudocomp/util/View.hpp>

namespace tdc {

/// \brief Contains a literal and its location in the input.
///
/// This structure is used by encoders to get a glimpse at the literals it will
/// receive. The encoder is given a stream of literals and their occurences in
/// the compressed text. This information can be used to initialize data
/// structures that can be used for efficient encoding, e.g. a Huffman tree
/// or a k-mer dictionary.
struct Literal {
    /// The literal.
    uliteral_t c;

    /// The position of the literal in the input.
    len_t pos;
};

class LiteralIterator {
    /// \brief Tests whether there are more literals in the stream.
    /// \return \e true if there are more literals in the stream, \e false
    ///         otherwise.
    inline bool has_next() const { return false; }

    /// \brief Yields the next literal from the stream.
    /// \return The next literal from the stream.
    inline Literal next() { assert(false); return Literal{0, 0}; }
};

/// \brief An empty literal iterator that yields no literals whatsoever.
class NoLiterals : LiteralIterator {
};

/// \brief A literal iterator that yields every character from a \ref View.
class ViewLiterals : LiteralIterator {
private:
    View m_view;
    len_t m_index;

public:
    /// \brief Constructor.
    ///
    /// \param view The view to iterate over.
    inline ViewLiterals(View view) : m_view(view), m_index(0) {
    }

    /// \brief Tests whether there are more literals in the stream.
    /// \return \e true if there are more literals in the stream, \e false
    ///         otherwise.
    inline bool has_next() const {
        return m_index < m_view.size();
    }

    /// \brief Yields the next literal from the stream.
    /// \return The next literal from the stream.
    inline Literal next() {
        assert(has_next());

        auto i = m_index++;
        return Literal { uliteral_t(m_view[i]), i };
    }
};

}

<|endoftext|>