<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cuihyperdlg.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 20:52:04 $
 *
 *  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
 *
 ************************************************************************/

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

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

#ifndef _SV_SETTINGS_HXX
#include <vcl/settings.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_VIEWOPTIONS_HXX
#include <svtools/viewoptions.hxx>
#endif

#include "cuihyperdlg.hxx"

#include "hlinettp.hxx"
#include "hlmailtp.hxx"
#include "hldoctp.hxx"
#include "hldocntp.hxx"

#include "hyperdlg.hrc"

//########################################################################
//#                                                                      #
//# Childwindow-Wrapper-Class                                            #
//#                                                                      #
//########################################################################

SvxHlinkCtrl::SvxHlinkCtrl( USHORT nId, SfxBindings & rBindings, SvxHpLinkDlg* pDlg )
: SfxControllerItem ( nId, rBindings ),
  aRdOnlyForwarder  ( SID_READONLY_MODE, *this ),
  aOnlineForwarder  ( SID_INTERNET_ONLINE , *this )
{
    pParent = pDlg;
}

void SvxHlinkCtrl::StateChanged( USHORT nSID, SfxItemState eState,
                                 const SfxPoolItem* pState )
{
    if ( eState == SFX_ITEM_AVAILABLE )
    {
        switch ( nSID )
        {
            case SID_INTERNET_ONLINE :
            {
                pParent->EnableInetBrowse( !( (SfxBoolItem*)pState)->GetValue() );
            }
            break;
            case SID_HYPERLINK_GETLINK :
            {
                pParent->SetPage ( (SvxHyperlinkItem*)pState);
            }
            break;
            case SID_READONLY_MODE :
            {
                pParent->SetReadOnlyMode( ( (SfxBoolItem*)pState)->GetValue() == TRUE );
            }
            break;
        }
    }
}

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

//########################################################################
//#                                                                      #
//# Hyperlink - Dialog                                                   #
//#                                                                      #
//########################################################################

/*************************************************************************
|*
|* Contructor / Destructor
|*
|************************************************************************/

SvxHpLinkDlg::SvxHpLinkDlg (Window* pParent, SfxBindings* pBindings)
:   IconChoiceDialog( pParent, SVX_RES ( RID_SVXDLG_NEWHYPERLINK ) ),
    maCtrl          ( SID_HYPERLINK_GETLINK, *pBindings, this ),
    mpBindings      ( pBindings ),
    mbIsHTMLDoc     ( sal_False ),
    mbReadOnly      ( sal_False )
{
    mbGrabFocus = sal_True;
    // insert pages
    Image aImage;
    Image aImageHC;
    String aStrTitle;
    SvxIconChoiceCtrlEntry* pEntry = NULL;

    aStrTitle = SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLINETTP );
    aImage = Image( SVX_RES ( RID_SVXBMP_HLINETTP ) );
    aImageHC = Image( SVX_RES ( RID_SVXBMP_HLINETTP_H ) );
    pEntry = AddTabPage ( RID_SVXPAGE_HYPERLINK_INTERNET, aStrTitle, aImage, aImageHC, SvxHyperlinkInternetTp::Create );
    pEntry->SetQuickHelpText( SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLINETTP_HELP ) );
    aStrTitle = SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLMAILTP );
    aImage = Image( SVX_RES ( RID_SVXBMP_HLMAILTP ) );
    aImageHC = Image( SVX_RES ( RID_SVXBMP_HLMAILTP_H ) );
    pEntry = AddTabPage ( RID_SVXPAGE_HYPERLINK_MAIL, aStrTitle, aImage, aImageHC, SvxHyperlinkMailTp::Create );
    pEntry->SetQuickHelpText( SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLMAILTP_HELP ) );
    aStrTitle = SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLDOCTP );
    aImage = Image( SVX_RES ( RID_SVXBMP_HLDOCTP ) );
    aImageHC = Image( SVX_RES ( RID_SVXBMP_HLDOCTP_H ) );
    pEntry = AddTabPage ( RID_SVXPAGE_HYPERLINK_DOCUMENT, aStrTitle, aImage, aImageHC, SvxHyperlinkDocTp::Create );
    pEntry->SetQuickHelpText( SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLDOCTP_HELP ) );
    aStrTitle = SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLDOCNTP );
    aImage = Image( SVX_RES ( RID_SVXBMP_HLDOCNTP ) );
    aImageHC = Image( SVX_RES ( RID_SVXBMP_HLDOCNTP_H ) );
    pEntry = AddTabPage ( RID_SVXPAGE_HYPERLINK_NEWDOCUMENT, aStrTitle, aImage, aImageHC, SvxHyperlinkNewDocTp::Create );
    pEntry->SetQuickHelpText( SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLDOCNTP_HELP ) );

    // all tab pages set -> create mnemonics
    //  CreateIconTextAutoMnemonics();  #99671# not useful, because this is not what user expects when using mnemonics on the pages

    // create itemset for tabpages
    mpItemSet = new SfxItemSet( SFX_APP()->GetPool(), SID_HYPERLINK_GETLINK,
                               SID_HYPERLINK_SETLINK );

    SvxHyperlinkItem aItem;
    mpItemSet->Put (aItem, SID_HYPERLINK_GETLINK);

    SetInputSet (mpItemSet);

    // Init Dialog
    Start (FALSE);

    pBindings->Update( SID_READONLY_MODE );

    // set OK/Cancel - button
    GetOKButton().SetText ( SVX_RESSTR(RID_SVXSTR_HYPDLG_APPLYBUT) );
    GetCancelButton().SetText ( SVX_RESSTR(RID_SVXSTR_HYPDLG_CLOSEBUT) );

    GetOKButton().SetClickHdl    ( LINK ( this, SvxHpLinkDlg, ClickApplyHdl_Impl ) );
    GetCancelButton().SetClickHdl( LINK ( this, SvxHpLinkDlg, ClickCloseHdl_Impl ) );
}

SvxHpLinkDlg::~SvxHpLinkDlg ()
{
    // delete config item, so the base class (IconChoiceDialog) can not load it on the next start
    SvtViewOptions aViewOpt( E_TABDIALOG, String::CreateFromInt32( SID_HYPERLINK_DIALOG ) );
    aViewOpt.Delete();

    delete mpItemSet;
}

/*************************************************************************
|*
|* Close Dialog-Window
|*
|************************************************************************/

BOOL SvxHpLinkDlg::Close()
{
    GetDispatcher()->Execute( SID_HYPERLINK_DIALOG,
                              SFX_CALLMODE_ASYNCHRON |
                              SFX_CALLMODE_RECORD);
    return TRUE;
}

/*************************************************************************
|*
|* When extrawindow is visible and its never moved by user, then move that
|* window, too.
|*
|************************************************************************/

void SvxHpLinkDlg::Move()
{
    SvxHyperlinkTabPageBase* pCurrentPage = ( SvxHyperlinkTabPageBase* )
                                            GetTabPage ( GetCurPageId() );

    if( pCurrentPage->IsMarkWndVisible () )
    {
        // Pos&Size of this dialog-window
        Point aDlgPos ( GetPosPixel () );
        Size aDlgSize ( GetSizePixel () );

        // Size of Office-Main-Window
        Size aWindowSize( SFX_APP()->GetTopWindow()->GetSizePixel() );

        // Size of Extrawindow
        Size aExtraWndSize( pCurrentPage->GetSizeExtraWnd() );

        BOOL bDoInvalid ;
        if( aDlgPos.X()+(1.02*aDlgSize.Width())+aExtraWndSize.Width() > aWindowSize.Width() )
        {
            if( aDlgPos.X() - ( 0.02*aDlgSize.Width() ) - aExtraWndSize.Width() < 0 )
            {
                // Pos Extrawindow anywhere
                bDoInvalid = pCurrentPage->MoveToExtraWnd( Point( 1, long(1.1*aDlgPos.Y()) ), TRUE );
            }
            else
            {
                // Pos Extrawindow on the left side of Dialog
                bDoInvalid = pCurrentPage->MoveToExtraWnd( aDlgPos -
                                                           Point( long(0.02*aDlgSize.Width()), 0 ) -
                                                           Point( aExtraWndSize.Width(), 0 ) );
            }
        }
        else
        {
            // Pos Extrawindow on the right side of Dialog
            bDoInvalid = pCurrentPage->MoveToExtraWnd ( aDlgPos + Point( long(1.02*aDlgSize.Width()), 0 ) );
        }

        if ( bDoInvalid )
            Invalidate(INVALIDATE_BACKGROUND);
    }

    Window::Move();
}

/*long SvxHpLinkDlg::PreNotify( NotifyEvent& rNEvt )
{
    long nRet = 0;

    if( rNEvt.GetType() == EVENT_KEYINPUT )
    {
        DBG_ASSERT( rNEvt.GetKeyEvent(), "-SvxHpLinkDlg::PreNotify(): no KeyEvent for key event?!" );

        const KeyEvent* pKEvt = rNEvt.GetKeyEvent();

        if( KEY_MOD2 == pKEvt->GetKeyCode().GetModifier() && pKEvt->GetCharCode() && HandleShortCutKey( *pKEvt ) )
            nRet = 1;
    }

    if( !nRet )
        nRet = IconChoiceDialog::PreNotify( rNEvt );

    return nRet;
}*/

/*************************************************************************
|*
|* Click on Apply-button
|*
|************************************************************************/

IMPL_LINK ( SvxHpLinkDlg, ClickApplyHdl_Impl, void *, EMPTYARG )
{
    SfxItemSet aItemSet( SFX_APP()->GetPool(), SID_HYPERLINK_GETLINK,
                         SID_HYPERLINK_SETLINK );

    SvxHyperlinkTabPageBase* pCurrentPage = (SvxHyperlinkTabPageBase*)
                                            GetTabPage ( GetCurPageId() );

    if ( pCurrentPage->AskApply() )
    {
        pCurrentPage->FillItemSet( aItemSet );

        SvxHyperlinkItem *aItem = (SvxHyperlinkItem *)
                                  aItemSet.GetItem (SID_HYPERLINK_SETLINK);

        String aStrEmpty;
        if ( aItem->GetURL() != aStrEmpty )
            GetDispatcher()->Execute( SID_HYPERLINK_SETLINK, SFX_CALLMODE_ASYNCHRON |
                                      SFX_CALLMODE_RECORD, aItem, 0L);

        ( (SvxHyperlinkTabPageBase*)GetTabPage ( GetCurPageId() ) )->DoApply();
    }

    return( 0L );
}

/*************************************************************************
|*
|* Click on Close-button
|*
|************************************************************************/

IMPL_LINK ( SvxHpLinkDlg, ClickCloseHdl_Impl, void *, EMPTYARG )
{
    Close();

    return( 0L );
}

/*************************************************************************
|*
|* Set Page
|*
|************************************************************************/

USHORT SvxHpLinkDlg::SetPage ( SvxHyperlinkItem* pItem )
{
    USHORT nPageId = RID_SVXPAGE_HYPERLINK_INTERNET;

    String aStrURL ( pItem->GetURL() );
    INetURLObject aURL ( aStrURL );
    INetProtocol eProtocolTyp = aURL.GetProtocol();

    switch ( eProtocolTyp )
    {
        case INET_PROT_HTTP :
        case INET_PROT_FTP :
        case INET_PROT_TELNET :
            nPageId = RID_SVXPAGE_HYPERLINK_INTERNET;
            break;
        case INET_PROT_FILE :
        case INET_PROT_POP3 :
        case INET_PROT_IMAP :
            nPageId = RID_SVXPAGE_HYPERLINK_DOCUMENT;
            break;
        case INET_PROT_MAILTO :
        case INET_PROT_NEWS :
            nPageId = RID_SVXPAGE_HYPERLINK_MAIL;
            break;
        default :
            sal_Char const sNewsSrvScheme[] = "news://";
                // TODO news:// is nonsense

            if ( aStrURL.SearchAscii( sNewsSrvScheme ) == 0 )
                nPageId = RID_SVXPAGE_HYPERLINK_DOCUMENT;
            else
            {
                sal_Char const sHash[] = "#";
                if( aStrURL.SearchAscii( sHash ) == 0 )
                    nPageId = RID_SVXPAGE_HYPERLINK_DOCUMENT;
                else
                {
                    eProtocolTyp = INET_PROT_NOT_VALID;
                    nPageId = GetCurPageId();
                }
            }
            break;
    }

    ShowPage (nPageId);

    SvxHyperlinkTabPageBase* pCurrentPage = (SvxHyperlinkTabPageBase*)GetTabPage( nPageId );

    mbIsHTMLDoc = BOOL( pItem->GetInsertMode() & HLINK_HTMLMODE );

    SfxItemSet& aPageSet =  (SfxItemSet&)GetTabPage (nPageId)->GetItemSet ();
    aPageSet.Put ( *pItem );

    pCurrentPage->Reset( aPageSet );
    if ( mbGrabFocus )
    {
        pCurrentPage->SetInitFocus();   // #92535# grab the focus only once at initialization
        mbGrabFocus = sal_False;
    }
    return nPageId;
}

/*************************************************************************
|*
|* Enable/Disable to browse targets in a html-doc
|*
|************************************************************************/

void SvxHpLinkDlg::EnableInetBrowse( sal_Bool bEnable )
{
    SvxHyperlinkTabPageBase* pCurrentPage = ( SvxHyperlinkTabPageBase* )
                                            GetTabPage ( GetCurPageId() );
    pCurrentPage->SetOnlineMode( bEnable );
}

/*************************************************************************
|*
|* Enable/Disable ReadOnly mode
|*
|************************************************************************/

void SvxHpLinkDlg::SetReadOnlyMode( sal_Bool bRdOnly )
{
    mbReadOnly = bRdOnly;
    if ( bRdOnly )
        GetOKButton().Disable();
    else
        GetOKButton().Enable();
}

<commit_msg>INTEGRATION: CWS warnings01 (1.4.222); FILE MERGED 2006/05/04 14:46:50 os 1.4.222.1: warnings removed<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cuihyperdlg.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 15:04:47 $
 *
 *  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
 *
 ************************************************************************/

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

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

#ifndef _SV_SETTINGS_HXX
#include <vcl/settings.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_VIEWOPTIONS_HXX
#include <svtools/viewoptions.hxx>
#endif

#include "cuihyperdlg.hxx"

#include "hlinettp.hxx"
#include "hlmailtp.hxx"
#include "hldoctp.hxx"
#include "hldocntp.hxx"

#include "hyperdlg.hrc"

//########################################################################
//#                                                                      #
//# Childwindow-Wrapper-Class                                            #
//#                                                                      #
//########################################################################

SvxHlinkCtrl::SvxHlinkCtrl( USHORT _nId, SfxBindings & rBindings, SvxHpLinkDlg* pDlg )
: SfxControllerItem ( _nId, rBindings )
  ,aOnlineForwarder  ( SID_INTERNET_ONLINE , *this )
  ,aRdOnlyForwarder  ( SID_READONLY_MODE, *this )
{
    pParent = pDlg;
}

void SvxHlinkCtrl::StateChanged( USHORT nSID, SfxItemState eState,
                                 const SfxPoolItem* pState )
{
    if ( eState == SFX_ITEM_AVAILABLE )
    {
        switch ( nSID )
        {
            case SID_INTERNET_ONLINE :
            {
                pParent->EnableInetBrowse( !( (SfxBoolItem*)pState)->GetValue() );
            }
            break;
            case SID_HYPERLINK_GETLINK :
            {
                pParent->SetPage ( (SvxHyperlinkItem*)pState);
            }
            break;
            case SID_READONLY_MODE :
            {
                pParent->SetReadOnlyMode( ( (SfxBoolItem*)pState)->GetValue() == TRUE );
            }
            break;
        }
    }
}

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

//########################################################################
//#                                                                      #
//# Hyperlink - Dialog                                                   #
//#                                                                      #
//########################################################################

/*************************************************************************
|*
|* Contructor / Destructor
|*
|************************************************************************/

SvxHpLinkDlg::SvxHpLinkDlg (Window* pParent, SfxBindings* pBindings)
:   IconChoiceDialog( pParent, SVX_RES ( RID_SVXDLG_NEWHYPERLINK ) ),
    maCtrl          ( SID_HYPERLINK_GETLINK, *pBindings, this ),
    mpBindings      ( pBindings ),
    mbReadOnly      ( sal_False ),
    mbIsHTMLDoc     ( sal_False )
{
    mbGrabFocus = sal_True;
    // insert pages
    Image aImage;
    Image aImageHC;
    String aStrTitle;
    SvxIconChoiceCtrlEntry* pEntry = NULL;

    aStrTitle = SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLINETTP );
    aImage = Image( SVX_RES ( RID_SVXBMP_HLINETTP ) );
    aImageHC = Image( SVX_RES ( RID_SVXBMP_HLINETTP_H ) );
    pEntry = AddTabPage ( RID_SVXPAGE_HYPERLINK_INTERNET, aStrTitle, aImage, aImageHC, SvxHyperlinkInternetTp::Create );
    pEntry->SetQuickHelpText( SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLINETTP_HELP ) );
    aStrTitle = SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLMAILTP );
    aImage = Image( SVX_RES ( RID_SVXBMP_HLMAILTP ) );
    aImageHC = Image( SVX_RES ( RID_SVXBMP_HLMAILTP_H ) );
    pEntry = AddTabPage ( RID_SVXPAGE_HYPERLINK_MAIL, aStrTitle, aImage, aImageHC, SvxHyperlinkMailTp::Create );
    pEntry->SetQuickHelpText( SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLMAILTP_HELP ) );
    aStrTitle = SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLDOCTP );
    aImage = Image( SVX_RES ( RID_SVXBMP_HLDOCTP ) );
    aImageHC = Image( SVX_RES ( RID_SVXBMP_HLDOCTP_H ) );
    pEntry = AddTabPage ( RID_SVXPAGE_HYPERLINK_DOCUMENT, aStrTitle, aImage, aImageHC, SvxHyperlinkDocTp::Create );
    pEntry->SetQuickHelpText( SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLDOCTP_HELP ) );
    aStrTitle = SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLDOCNTP );
    aImage = Image( SVX_RES ( RID_SVXBMP_HLDOCNTP ) );
    aImageHC = Image( SVX_RES ( RID_SVXBMP_HLDOCNTP_H ) );
    pEntry = AddTabPage ( RID_SVXPAGE_HYPERLINK_NEWDOCUMENT, aStrTitle, aImage, aImageHC, SvxHyperlinkNewDocTp::Create );
    pEntry->SetQuickHelpText( SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLDOCNTP_HELP ) );

    // all tab pages set -> create mnemonics
    //  CreateIconTextAutoMnemonics();  #99671# not useful, because this is not what user expects when using mnemonics on the pages

    // create itemset for tabpages
    mpItemSet = new SfxItemSet( SFX_APP()->GetPool(), SID_HYPERLINK_GETLINK,
                               SID_HYPERLINK_SETLINK );

    SvxHyperlinkItem aItem;
    mpItemSet->Put (aItem, SID_HYPERLINK_GETLINK);

    SetInputSet (mpItemSet);

    // Init Dialog
    Start (FALSE);

    pBindings->Update( SID_READONLY_MODE );

    // set OK/Cancel - button
    GetOKButton().SetText ( SVX_RESSTR(RID_SVXSTR_HYPDLG_APPLYBUT) );
    GetCancelButton().SetText ( SVX_RESSTR(RID_SVXSTR_HYPDLG_CLOSEBUT) );

    GetOKButton().SetClickHdl    ( LINK ( this, SvxHpLinkDlg, ClickApplyHdl_Impl ) );
    GetCancelButton().SetClickHdl( LINK ( this, SvxHpLinkDlg, ClickCloseHdl_Impl ) );
}

SvxHpLinkDlg::~SvxHpLinkDlg ()
{
    // delete config item, so the base class (IconChoiceDialog) can not load it on the next start
    SvtViewOptions aViewOpt( E_TABDIALOG, String::CreateFromInt32( SID_HYPERLINK_DIALOG ) );
    aViewOpt.Delete();

    delete mpItemSet;
}

/*************************************************************************
|*
|* Close Dialog-Window
|*
|************************************************************************/

BOOL SvxHpLinkDlg::Close()
{
    GetDispatcher()->Execute( SID_HYPERLINK_DIALOG,
                              SFX_CALLMODE_ASYNCHRON |
                              SFX_CALLMODE_RECORD);
    return TRUE;
}

/*************************************************************************
|*
|* When extrawindow is visible and its never moved by user, then move that
|* window, too.
|*
|************************************************************************/

void SvxHpLinkDlg::Move()
{
    SvxHyperlinkTabPageBase* pCurrentPage = ( SvxHyperlinkTabPageBase* )
                                            GetTabPage ( GetCurPageId() );

    if( pCurrentPage->IsMarkWndVisible () )
    {
        // Pos&Size of this dialog-window
        Point aDlgPos ( GetPosPixel () );
        Size aDlgSize ( GetSizePixel () );

        // Size of Office-Main-Window
        Size aWindowSize( SFX_APP()->GetTopWindow()->GetSizePixel() );

        // Size of Extrawindow
        Size aExtraWndSize( pCurrentPage->GetSizeExtraWnd() );

        BOOL bDoInvalid ;
        if( aDlgPos.X()+(1.02*aDlgSize.Width())+aExtraWndSize.Width() > aWindowSize.Width() )
        {
            if( aDlgPos.X() - ( 0.02*aDlgSize.Width() ) - aExtraWndSize.Width() < 0 )
            {
                // Pos Extrawindow anywhere
                bDoInvalid = pCurrentPage->MoveToExtraWnd( Point( 1, long(1.1*aDlgPos.Y()) ), TRUE );
            }
            else
            {
                // Pos Extrawindow on the left side of Dialog
                bDoInvalid = pCurrentPage->MoveToExtraWnd( aDlgPos -
                                                           Point( long(0.02*aDlgSize.Width()), 0 ) -
                                                           Point( aExtraWndSize.Width(), 0 ) );
            }
        }
        else
        {
            // Pos Extrawindow on the right side of Dialog
            bDoInvalid = pCurrentPage->MoveToExtraWnd ( aDlgPos + Point( long(1.02*aDlgSize.Width()), 0 ) );
        }

        if ( bDoInvalid )
            Invalidate(INVALIDATE_BACKGROUND);
    }

    Window::Move();
}

/*long SvxHpLinkDlg::PreNotify( NotifyEvent& rNEvt )
{
    long nRet = 0;

    if( rNEvt.GetType() == EVENT_KEYINPUT )
    {
        DBG_ASSERT( rNEvt.GetKeyEvent(), "-SvxHpLinkDlg::PreNotify(): no KeyEvent for key event?!" );

        const KeyEvent* pKEvt = rNEvt.GetKeyEvent();

        if( KEY_MOD2 == pKEvt->GetKeyCode().GetModifier() && pKEvt->GetCharCode() && HandleShortCutKey( *pKEvt ) )
            nRet = 1;
    }

    if( !nRet )
        nRet = IconChoiceDialog::PreNotify( rNEvt );

    return nRet;
}*/

/*************************************************************************
|*
|* Click on Apply-button
|*
|************************************************************************/

IMPL_LINK ( SvxHpLinkDlg, ClickApplyHdl_Impl, void *, EMPTYARG )
{
    SfxItemSet aItemSet( SFX_APP()->GetPool(), SID_HYPERLINK_GETLINK,
                         SID_HYPERLINK_SETLINK );

    SvxHyperlinkTabPageBase* pCurrentPage = (SvxHyperlinkTabPageBase*)
                                            GetTabPage ( GetCurPageId() );

    if ( pCurrentPage->AskApply() )
    {
        pCurrentPage->FillItemSet( aItemSet );

        SvxHyperlinkItem *aItem = (SvxHyperlinkItem *)
                                  aItemSet.GetItem (SID_HYPERLINK_SETLINK);

        String aStrEmpty;
        if ( aItem->GetURL() != aStrEmpty )
            GetDispatcher()->Execute( SID_HYPERLINK_SETLINK, SFX_CALLMODE_ASYNCHRON |
                                      SFX_CALLMODE_RECORD, aItem, 0L);

        ( (SvxHyperlinkTabPageBase*)GetTabPage ( GetCurPageId() ) )->DoApply();
    }

    return( 0L );
}

/*************************************************************************
|*
|* Click on Close-button
|*
|************************************************************************/

IMPL_LINK ( SvxHpLinkDlg, ClickCloseHdl_Impl, void *, EMPTYARG )
{
    Close();

    return( 0L );
}

/*************************************************************************
|*
|* Set Page
|*
|************************************************************************/

USHORT SvxHpLinkDlg::SetPage ( SvxHyperlinkItem* pItem )
{
    USHORT nPageId = RID_SVXPAGE_HYPERLINK_INTERNET;

    String aStrURL ( pItem->GetURL() );
    INetURLObject aURL ( aStrURL );
    INetProtocol eProtocolTyp = aURL.GetProtocol();

    switch ( eProtocolTyp )
    {
        case INET_PROT_HTTP :
        case INET_PROT_FTP :
        case INET_PROT_TELNET :
            nPageId = RID_SVXPAGE_HYPERLINK_INTERNET;
            break;
        case INET_PROT_FILE :
        case INET_PROT_POP3 :
        case INET_PROT_IMAP :
            nPageId = RID_SVXPAGE_HYPERLINK_DOCUMENT;
            break;
        case INET_PROT_MAILTO :
        case INET_PROT_NEWS :
            nPageId = RID_SVXPAGE_HYPERLINK_MAIL;
            break;
        default :
            sal_Char const sNewsSrvScheme[] = "news://";
                // TODO news:// is nonsense

            if ( aStrURL.SearchAscii( sNewsSrvScheme ) == 0 )
                nPageId = RID_SVXPAGE_HYPERLINK_DOCUMENT;
            else
            {
                sal_Char const sHash[] = "#";
                if( aStrURL.SearchAscii( sHash ) == 0 )
                    nPageId = RID_SVXPAGE_HYPERLINK_DOCUMENT;
                else
                {
                    eProtocolTyp = INET_PROT_NOT_VALID;
                    nPageId = GetCurPageId();
                }
            }
            break;
    }

    ShowPage (nPageId);

    SvxHyperlinkTabPageBase* pCurrentPage = (SvxHyperlinkTabPageBase*)GetTabPage( nPageId );

    mbIsHTMLDoc = BOOL( pItem->GetInsertMode() & HLINK_HTMLMODE );

    SfxItemSet& aPageSet =  (SfxItemSet&)GetTabPage (nPageId)->GetItemSet ();
    aPageSet.Put ( *pItem );

    pCurrentPage->Reset( aPageSet );
    if ( mbGrabFocus )
    {
        pCurrentPage->SetInitFocus();   // #92535# grab the focus only once at initialization
        mbGrabFocus = sal_False;
    }
    return nPageId;
}

/*************************************************************************
|*
|* Enable/Disable to browse targets in a html-doc
|*
|************************************************************************/

void SvxHpLinkDlg::EnableInetBrowse( sal_Bool bEnable )
{
    SvxHyperlinkTabPageBase* pCurrentPage = ( SvxHyperlinkTabPageBase* )
                                            GetTabPage ( GetCurPageId() );
    pCurrentPage->SetOnlineMode( bEnable );
}

/*************************************************************************
|*
|* Enable/Disable ReadOnly mode
|*
|************************************************************************/

void SvxHpLinkDlg::SetReadOnlyMode( sal_Bool bRdOnly )
{
    mbReadOnly = bRdOnly;
    if ( bRdOnly )
        GetOKButton().Disable();
    else
        GetOKButton().Enable();
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: checkit.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-17 13:41:50 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _CHECKIT_HXX
#include <checkit.hxx>
#endif

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace drafts::com::sun::star::i18n;

SwCheckIt::SwCheckIt()
{
    Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();
    Reference < XInterface > xI = xMSF->createInstance(
        ::rtl::OUString::createFromAscii( "com.sun.star.i18n.InputSequenceChecker" ) );
    if ( xI.is() )
    {
        Any x = xI->queryInterface( ::getCppuType((const Reference< XInputSequenceChecker >*)0) );
        x >>= xCheck;
    }
}

<commit_msg>INTEGRATION: CWS i18napi (1.1.166); FILE MERGED 2003/04/19 20:27:00 er 1.1.166.1: #107686# move drafts.com.sun.star.i18n to com.sun.star.i18n<commit_after>/*************************************************************************
 *
 *  $RCSfile: checkit.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-24 10:53:20 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _CHECKIT_HXX
#include <checkit.hxx>
#endif

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::i18n;

SwCheckIt::SwCheckIt()
{
    Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();
    Reference < XInterface > xI = xMSF->createInstance(
        ::rtl::OUString::createFromAscii( "com.sun.star.i18n.InputSequenceChecker" ) );
    if ( xI.is() )
    {
        Any x = xI->queryInterface( ::getCppuType((const Reference< XInputSequenceChecker >*)0) );
        x >>= xCheck;
    }
}

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#ifndef INCLUDED_SW_SOURCE_CORE_LAYOUT_LAYHELP_HXX
#define INCLUDED_SW_SOURCE_CORE_LAYOUT_LAYHELP_HXX

#include <swrect.hxx>
#include <vector>
#include <deque>

class SwDoc;
class SwFrm;
class SwLayoutFrm;
class SwPageFrm;
class SwFlyFrm;
class SwSectionFrm;
class SwSectionNode;
class SvStream;

/*************************************************************************
 *                      class SwLayCacheImpl
 * contains the page break information and the text frame positions
 * of the document (after loading)
 * and is used inside the constructor of the layout rootframe to
 * insert content and text frames at the right pages.
 * For every page of the main text (body content, no footnotes, text frames etc.)
 * we have the nodeindex of the first content at the page,
 * the type of content ( table or paragraph )
 * and if it's not the first part of the table/paragraph,
 * the row/character-offset inside the table/paragraph.
 * The text frame positions are stored in the SwPageFlyCache array.
 *************************************************************************/

class SwFlyCache;
typedef boost::ptr_vector<SwFlyCache> SwPageFlyCache;

class SwLayCacheImpl : public std::vector<sal_uLong>
{
    std::deque<sal_Int32> aOffset;
    std::vector<sal_uInt16> aType;
    SwPageFlyCache aFlyCache;
    bool bUseFlyCache;
    void Insert( sal_uInt16 nType, sal_uLong nIndex, sal_Int32 nOffset );

public:
    SwLayCacheImpl() {}
    bool Read( SvStream& rStream );

    sal_uLong GetBreakIndex( sal_uInt16 nIdx ) const { return std::vector<sal_uLong>::operator[]( nIdx ); }
    sal_Int32 GetBreakOfst( size_t nIdx ) const { return aOffset[ nIdx ]; }
    sal_uInt16 GetBreakType( sal_uInt16 nIdx ) const { return aType[ nIdx ]; }

    sal_uInt16 GetFlyCount() const { return aFlyCache.size(); }
    SwFlyCache *GetFlyCache( sal_uInt16 nIdx ) { return &aFlyCache[ nIdx ]; }

    bool IsUseFlyCache() const { return bUseFlyCache; }
};

/*************************************************************************
 *                      class SwActualSection
 * helps to create the sectionframes during the _InsertCnt-function
 * by controlling nested sections.
 *************************************************************************/

class SwActualSection
{
    SwActualSection *pUpper;
    SwSectionFrm    *pSectFrm;
    SwSectionNode   *pSectNode;
public:
    SwActualSection( SwActualSection *pUpper,
                     SwSectionFrm    *pSect,
                     SwSectionNode   *pNd );

    SwSectionFrm    *GetSectionFrm()                    { return pSectFrm; }
    void             SetSectionFrm( SwSectionFrm *p )   { pSectFrm = p; }
    SwSectionNode   *GetSectionNode()                   { return pSectNode;}
    SwActualSection *GetUpper()                         { return pUpper; }
};

/*************************************************************************
 *                      class SwLayHelper
 * helps during the _InsertCnt-function to create new pages.
 * If there's a layoutcache available, this information is used.
 *************************************************************************/

class SwLayHelper
{
    SwFrm* &rpFrm;
    SwFrm* &rpPrv;
    SwPageFrm* &rpPage;
    SwLayoutFrm* &rpLay;
    SwActualSection* &rpActualSection;
    sal_Bool &rbBreakAfter;
    SwDoc* pDoc;
    SwLayCacheImpl* pImpl;
    sal_uLong nMaxParaPerPage;
    sal_uLong nParagraphCnt;
    sal_uLong nStartOfContent;
    sal_uInt16 nIndex;                      // the index in the page break array
    sal_uInt16 nFlyIdx;                     // the index in the fly cache array
    bool bFirst : 1;
    void _CheckFlyCache( SwPageFrm* pPage );
public:
    SwLayHelper( SwDoc *pD, SwFrm* &rpF, SwFrm* &rpP, SwPageFrm* &rpPg,
            SwLayoutFrm* &rpL, SwActualSection* &rpA, sal_Bool &rBrk,
            sal_uLong nNodeIndex, bool bCache );
    ~SwLayHelper();
    sal_uLong CalcPageCount();
    bool CheckInsert( sal_uLong nNodeIndex );

    bool CheckInsertPage();

    // Look for fresh text frames at this (new) page and set them to the right
    // position, if they are in the fly cache.
    void CheckFlyCache( SwPageFrm* pPage )
    { if( pImpl && nFlyIdx < pImpl->GetFlyCount() ) _CheckFlyCache( pPage ); }

    // Look for this text frame and set it to the right position,
    // if it's in the fly cache.
    static bool CheckPageFlyCache( SwPageFrm* &rpPage, SwFlyFrm* pFly );
};

/*************************************************************************
 *                      class SwLayCacheIoImpl
 * contains the data structures that are required to read and write a
 * layout cache.
 *************************************************************************/

#define SW_LAYCACHE_IO_REC_PAGES    'p'
#define SW_LAYCACHE_IO_REC_PARA     'P'
#define SW_LAYCACHE_IO_REC_TABLE    'T'
#define SW_LAYCACHE_IO_REC_FLY      'F'

#define SW_LAYCACHE_IO_VERSION_MAJOR    1
#define SW_LAYCACHE_IO_VERSION_MINOR    1

class SwLayCacheIoImpl
{
private:
    struct RecTypeSize {
        sal_uInt8 type;
        sal_uLong size;
        RecTypeSize(sal_uInt8 typ, sal_uLong siz) : type(typ), size(siz) {}
    };
    std::vector<RecTypeSize> aRecords;

    SvStream        *pStream;

    sal_uLong           nFlagRecEnd;

    sal_uInt16          nMajorVersion;
    sal_uInt16          nMinorVersion;

    bool            bWriteMode : 1;
    bool            bError : 1;

public:
    SwLayCacheIoImpl( SvStream& rStrm, bool bWrtMd );

    // Get input or output stream
    SvStream& GetStream() const { return *pStream; }

    // Open a record of type "nType"
    bool OpenRec( sal_uInt8 nType );

    // Close a record of type "nType". This skips any unread data that
    // remains in the record.
    bool CloseRec( sal_uInt8 nType );

    // Return the number of bytes contained in the current record that
    // haven't been read by now.
    sal_uInt32 BytesLeft();

    // Return the current record's type
    sal_uInt8 Peek();

    // Skip the current record
    void SkipRec();

    // Open a flag record for reading. The uppermost four bits are flags,
    // while the lowermost are the flag record's size. Flag records cannot
    // be nested.
    sal_uInt8 OpenFlagRec();

    // Open flag record for writing;
    void OpenFlagRec( sal_uInt8 nFlags, sal_uInt8 nLen );

    // Close a flag record. Any bytes left are skipped.
    void CloseFlagRec();

    bool HasError() const { return bError; }

    sal_uInt16 GetMajorVersion() const { return nMajorVersion; }
    sal_uInt16 GetMinorVersion() const { return nMinorVersion; }
};

// Stored information about text frames:
class SwFlyCache : public SwRect // position and size
{
public:
    sal_uLong nOrdNum;      // Id to recognize text frames
    sal_uInt16 nPageNum;    // page number
    SwFlyCache( sal_uInt16 nP, sal_uLong nO, long nXL, long nYL, long nWL, long nHL ) :
        SwRect( nXL, nYL, nWL, nHL ), nOrdNum( nO ), nPageNum( nP ){}
};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#708427 Unitialized scalar field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#ifndef INCLUDED_SW_SOURCE_CORE_LAYOUT_LAYHELP_HXX
#define INCLUDED_SW_SOURCE_CORE_LAYOUT_LAYHELP_HXX

#include <swrect.hxx>
#include <vector>
#include <deque>

class SwDoc;
class SwFrm;
class SwLayoutFrm;
class SwPageFrm;
class SwFlyFrm;
class SwSectionFrm;
class SwSectionNode;
class SvStream;

/*************************************************************************
 *                      class SwLayCacheImpl
 * contains the page break information and the text frame positions
 * of the document (after loading)
 * and is used inside the constructor of the layout rootframe to
 * insert content and text frames at the right pages.
 * For every page of the main text (body content, no footnotes, text frames etc.)
 * we have the nodeindex of the first content at the page,
 * the type of content ( table or paragraph )
 * and if it's not the first part of the table/paragraph,
 * the row/character-offset inside the table/paragraph.
 * The text frame positions are stored in the SwPageFlyCache array.
 *************************************************************************/

class SwFlyCache;
typedef boost::ptr_vector<SwFlyCache> SwPageFlyCache;

class SwLayCacheImpl : public std::vector<sal_uLong>
{
    std::deque<sal_Int32> aOffset;
    std::vector<sal_uInt16> aType;
    SwPageFlyCache aFlyCache;
    bool bUseFlyCache;
    void Insert( sal_uInt16 nType, sal_uLong nIndex, sal_Int32 nOffset );

public:
    SwLayCacheImpl() : bUseFlyCache(false) {}
    bool Read( SvStream& rStream );

    sal_uLong GetBreakIndex( sal_uInt16 nIdx ) const { return std::vector<sal_uLong>::operator[]( nIdx ); }
    sal_Int32 GetBreakOfst( size_t nIdx ) const { return aOffset[ nIdx ]; }
    sal_uInt16 GetBreakType( sal_uInt16 nIdx ) const { return aType[ nIdx ]; }

    sal_uInt16 GetFlyCount() const { return aFlyCache.size(); }
    SwFlyCache *GetFlyCache( sal_uInt16 nIdx ) { return &aFlyCache[ nIdx ]; }

    bool IsUseFlyCache() const { return bUseFlyCache; }
};

/*************************************************************************
 *                      class SwActualSection
 * helps to create the sectionframes during the _InsertCnt-function
 * by controlling nested sections.
 *************************************************************************/

class SwActualSection
{
    SwActualSection *pUpper;
    SwSectionFrm    *pSectFrm;
    SwSectionNode   *pSectNode;
public:
    SwActualSection( SwActualSection *pUpper,
                     SwSectionFrm    *pSect,
                     SwSectionNode   *pNd );

    SwSectionFrm    *GetSectionFrm()                    { return pSectFrm; }
    void             SetSectionFrm( SwSectionFrm *p )   { pSectFrm = p; }
    SwSectionNode   *GetSectionNode()                   { return pSectNode;}
    SwActualSection *GetUpper()                         { return pUpper; }
};

/*************************************************************************
 *                      class SwLayHelper
 * helps during the _InsertCnt-function to create new pages.
 * If there's a layoutcache available, this information is used.
 *************************************************************************/

class SwLayHelper
{
    SwFrm* &rpFrm;
    SwFrm* &rpPrv;
    SwPageFrm* &rpPage;
    SwLayoutFrm* &rpLay;
    SwActualSection* &rpActualSection;
    sal_Bool &rbBreakAfter;
    SwDoc* pDoc;
    SwLayCacheImpl* pImpl;
    sal_uLong nMaxParaPerPage;
    sal_uLong nParagraphCnt;
    sal_uLong nStartOfContent;
    sal_uInt16 nIndex;                      // the index in the page break array
    sal_uInt16 nFlyIdx;                     // the index in the fly cache array
    bool bFirst : 1;
    void _CheckFlyCache( SwPageFrm* pPage );
public:
    SwLayHelper( SwDoc *pD, SwFrm* &rpF, SwFrm* &rpP, SwPageFrm* &rpPg,
            SwLayoutFrm* &rpL, SwActualSection* &rpA, sal_Bool &rBrk,
            sal_uLong nNodeIndex, bool bCache );
    ~SwLayHelper();
    sal_uLong CalcPageCount();
    bool CheckInsert( sal_uLong nNodeIndex );

    bool CheckInsertPage();

    // Look for fresh text frames at this (new) page and set them to the right
    // position, if they are in the fly cache.
    void CheckFlyCache( SwPageFrm* pPage )
    { if( pImpl && nFlyIdx < pImpl->GetFlyCount() ) _CheckFlyCache( pPage ); }

    // Look for this text frame and set it to the right position,
    // if it's in the fly cache.
    static bool CheckPageFlyCache( SwPageFrm* &rpPage, SwFlyFrm* pFly );
};

/*************************************************************************
 *                      class SwLayCacheIoImpl
 * contains the data structures that are required to read and write a
 * layout cache.
 *************************************************************************/

#define SW_LAYCACHE_IO_REC_PAGES    'p'
#define SW_LAYCACHE_IO_REC_PARA     'P'
#define SW_LAYCACHE_IO_REC_TABLE    'T'
#define SW_LAYCACHE_IO_REC_FLY      'F'

#define SW_LAYCACHE_IO_VERSION_MAJOR    1
#define SW_LAYCACHE_IO_VERSION_MINOR    1

class SwLayCacheIoImpl
{
private:
    struct RecTypeSize {
        sal_uInt8 type;
        sal_uLong size;
        RecTypeSize(sal_uInt8 typ, sal_uLong siz) : type(typ), size(siz) {}
    };
    std::vector<RecTypeSize> aRecords;

    SvStream        *pStream;

    sal_uLong           nFlagRecEnd;

    sal_uInt16          nMajorVersion;
    sal_uInt16          nMinorVersion;

    bool            bWriteMode : 1;
    bool            bError : 1;

public:
    SwLayCacheIoImpl( SvStream& rStrm, bool bWrtMd );

    // Get input or output stream
    SvStream& GetStream() const { return *pStream; }

    // Open a record of type "nType"
    bool OpenRec( sal_uInt8 nType );

    // Close a record of type "nType". This skips any unread data that
    // remains in the record.
    bool CloseRec( sal_uInt8 nType );

    // Return the number of bytes contained in the current record that
    // haven't been read by now.
    sal_uInt32 BytesLeft();

    // Return the current record's type
    sal_uInt8 Peek();

    // Skip the current record
    void SkipRec();

    // Open a flag record for reading. The uppermost four bits are flags,
    // while the lowermost are the flag record's size. Flag records cannot
    // be nested.
    sal_uInt8 OpenFlagRec();

    // Open flag record for writing;
    void OpenFlagRec( sal_uInt8 nFlags, sal_uInt8 nLen );

    // Close a flag record. Any bytes left are skipped.
    void CloseFlagRec();

    bool HasError() const { return bError; }

    sal_uInt16 GetMajorVersion() const { return nMajorVersion; }
    sal_uInt16 GetMinorVersion() const { return nMinorVersion; }
};

// Stored information about text frames:
class SwFlyCache : public SwRect // position and size
{
public:
    sal_uLong nOrdNum;      // Id to recognize text frames
    sal_uInt16 nPageNum;    // page number
    SwFlyCache( sal_uInt16 nP, sal_uLong nO, long nXL, long nYL, long nWL, long nHL ) :
        SwRect( nXL, nYL, nWL, nHL ), nOrdNum( nO ), nPageNum( nP ){}
};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>// RUN: %clangxx_msan -m64 -O0 %s -o %t && not %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
// RUN: %clangxx_msan -m64 -O1 %s -o %t && not %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
// RUN: %clangxx_msan -m64 -O2 %s -o %t && not %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
// RUN: %clangxx_msan -m64 -O3 %s -o %t && not %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out

// RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O0 %s -o %t && not %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out
// RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O1 %s -o %t && not %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out
// RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O2 %s -o %t && not %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out
// RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O3 %s -o %t && not %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out

#include <stdlib.h>
int main(int argc, char **argv) {
  int x;
  int *volatile p = &x;
  if (*p)
    exit(0);
  // CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value
  // CHECK: {{#0 0x.* in main .*stack-origin.cc:}}[[@LINE-3]]

  // CHECK-ORIGINS: Uninitialized value was created by an allocation of 'x' in the stack frame of function 'main'

  // CHECK: SUMMARY: MemorySanitizer: use-of-uninitialized-value {{.*stack-origin.cc:.* main}}
  return 0;
}
<commit_msg>[msan] Add source file:line to stack origin reports.<commit_after>// RUN: %clangxx_msan -m64 -O0 %s -o %t && not %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
// RUN: %clangxx_msan -m64 -O1 %s -o %t && not %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
// RUN: %clangxx_msan -m64 -O2 %s -o %t && not %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out
// RUN: %clangxx_msan -m64 -O3 %s -o %t && not %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out

// RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O0 %s -o %t && not %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out
// RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O1 %s -o %t && not %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out
// RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O2 %s -o %t && not %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out
// RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O3 %s -o %t && not %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out

#include <stdlib.h>
int main(int argc, char **argv) {
  int x;
  int *volatile p = &x;
  if (*p)
    exit(0);
  // CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value
  // CHECK: {{#0 0x.* in main .*stack-origin.cc:}}[[@LINE-3]]

  // CHECK-ORIGINS: Uninitialized value was created by an allocation of 'x' in the stack frame of function 'main'
  // CHECK-ORIGINS: {{#0 0x.* in main .*stack-origin.cc:}}[[@LINE-9]]

  // CHECK: SUMMARY: MemorySanitizer: use-of-uninitialized-value {{.*stack-origin.cc:.* main}}
  return 0;
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2015 Advanced Micro Devices, Inc. All rights reserved.
//
#include "device/pal/palkernel.hpp"
#include "device/pal/palwavelimiter.hpp"
#include "os/os.hpp"
#include "utils/flags.hpp"

#include <cstdlib>
using namespace std;

namespace pal {

uint WaveLimiter::MaxWave;
uint WaveLimiter::RunCount;
uint WaveLimiter::AdaptCount;

WaveLimiter::WaveLimiter(WaveLimiterManager* manager, uint seqNum, bool enable, bool enableDump)
    : manager_(manager), dumper_(manager_->name() + "_" + std::to_string(seqNum), enableDump) {
  setIfNotDefault(SIMDPerSH_, GPU_WAVE_LIMIT_CU_PER_SH, manager->getSimdPerSH());
  MaxWave = GPU_WAVE_LIMIT_MAX_WAVE;
  RunCount = GPU_WAVE_LIMIT_RUN * MaxWave;
  AdaptCount = MaxContinuousSamples * 2 * (MaxWave + 1);

  state_ = WARMUP;
  if (!flagIsDefault(GPU_WAVE_LIMIT_TRACE)) {
    traceStream_.open(std::string(GPU_WAVE_LIMIT_TRACE) + manager_->name() + ".txt");
  }

  waves_ = MaxWave;
  enable_ = (SIMDPerSH_ == 0) ? false : enable;
  bestWave_ = (enable_) ? MaxWave : 0;
  sampleCount_ = 0;
  resultCount_ = 0;
  numContinuousSamples_ = 0;
}

WaveLimiter::~WaveLimiter() {
  if (traceStream_.is_open()) {
    traceStream_.close();
  }
}

uint WaveLimiter::getWavesPerSH() {
  // Generate different wave counts in the adaptation mode
  if ((state_ == ADAPT) && (sampleCount_ < AdaptCount)) {
    if (numContinuousSamples_ == 0) {
        waves_ = (++waves_) % (MaxWave + 1);
    }
    numContinuousSamples_ = (++numContinuousSamples_) % MaxContinuousSamples;
    ++sampleCount_;
  }
  else {
    waves_ = bestWave_;
  }
  return waves_ * SIMDPerSH_;
}

WLAlgorithmSmooth::WLAlgorithmSmooth(WaveLimiterManager* manager, uint seqNum, bool enable,
                                     bool enableDump)
    : WaveLimiter(manager, seqNum, enable, enableDump) {
  dynRunCount_ = RunCount;
  adpMeasure_.resize(MaxWave + 1);
  adpSampleCnt_.resize(MaxWave + 1);
  runMeasure_.resize(MaxWave + 1);
  runSampleCnt_.resize(MaxWave + 1);

  clearData();
}

WLAlgorithmSmooth::~WLAlgorithmSmooth() {}

void WLAlgorithmSmooth::clearData() {
  waves_ = MaxWave;
  countAll_ = 0;
  clear(adpMeasure_);
  clear(adpSampleCnt_);
  dataCount_ = 0;
}

void WLAlgorithmSmooth::updateData(ulong time) {

}

void WLAlgorithmSmooth::outputTrace() {
  if (!traceStream_.is_open()) {
    return;
  }

  traceStream_ << "[WaveLimiter] " << manager_->name() << " state=" << state_
               << " waves=" << waves_ << " bestWave=" << bestWave_ << '\n';
  output(traceStream_, "\n adaptive measure = ", adpMeasure_);
  output(traceStream_, "\n adaptive smaple count = ", adpSampleCnt_);
  output(traceStream_, "\n run measure = ", runMeasure_);
  output(traceStream_, "\n run smaple count = ", runSampleCnt_);
  traceStream_ << "\n % time from the previous runs to the best wave: ";
  float min = static_cast<float>(adpMeasure_[bestWave_]) / adpSampleCnt_[bestWave_];
  for (uint i = 0; i < (MaxWave + 1); ++i) {
    runSampleCnt_[i] = (runSampleCnt_[i] == 0) ? 1 : runSampleCnt_[i];
    float average = static_cast<float>(runMeasure_[i]) / runSampleCnt_[i];
    traceStream_ << (average * 100 / min) << " ";
  }
  traceStream_ << "\n run count = " << dynRunCount_;
  traceStream_ << "\n\n";
}

void WLAlgorithmSmooth::callback(ulong duration, uint32_t waves) {
  dumper_.addData(duration, waves, static_cast<char>(state_));

  if (!enable_ || (duration == 0)) {
    return;
  }

  countAll_++;

  waves /= SIMDPerSH_;
  // Collect the time for the current wave count
  runMeasure_[waves] += duration;
  runSampleCnt_[waves]++;

  switch (state_) {
    case ADAPT:
      assert(duration > 0);
      // Wave count 0 indicates the satrt of adaptation
      if ((waves == 0) || (resultCount_ > 0)) {
        // Scale time to us
        adpMeasure_[waves] += duration;
        adpSampleCnt_[waves]++;
        resultCount_++;
        // If the end of adaptation is reached, then analyze the results
        if (resultCount_ == AdaptCount) {
          // Reset the counters
          resultCount_ = sampleCount_ = 0;
          float min = std::numeric_limits<float>::max();
          uint32_t best = bestWave_;
          // Check performance for the previous run if it's available
          if (runSampleCnt_[bestWave_] > 0) {
            min = static_cast<float>(runMeasure_[bestWave_]) / runSampleCnt_[bestWave_];
          }
          else if (adpSampleCnt_[MaxWave] > 0) {
            min = static_cast<float>(adpMeasure_[MaxWave]) / adpSampleCnt_[MaxWave];
            bestWave_ = MaxWave;
          }
          // Find the fastest average time
          float reference = min;
          for (uint i = MaxWave; i > 0; --i) {
            float average;
            if (adpSampleCnt_[i] > 0) {
              average = static_cast<float>(adpMeasure_[i]) / adpSampleCnt_[i];
            }
            else {
              average = 0.0f;
            }
            if (average < min) {
              min = average;
              bestWave_ = i;
            }
          }
          // Check for 5% acceptance
          if ((min * 1.05f > reference) || (bestWave_ == best)) {
            bestWave_ = best;
            // Increase the run time if the same wave count is the best
            dynRunCount_ += RunCount;
            dynRunCount_++;
          }
          else {
            dynRunCount_ = RunCount;
          }
          state_ = RUN;
          outputTrace();
          // Start to collect the new data for the best wave
          countAll_ = 0;
          runMeasure_[bestWave_] = 0;
          runSampleCnt_[bestWave_] = 0;
        }
      }
      return;
    case WARMUP:
    case RUN:
      if (countAll_ < dynRunCount_) {
        return;
      }
      if (state_ == WARMUP) {
        runSampleCnt_[bestWave_] = 0;
      }
      state_ = ADAPT;
      clearData();
      return;
  }
}

WaveLimiter::DataDumper::DataDumper(const std::string& kernelName, bool enable) {
  enable_ = enable;
  if (enable_) {
    fileName_ = std::string(GPU_WAVE_LIMIT_DUMP) + kernelName + ".csv";
  }
}

WaveLimiter::DataDumper::~DataDumper() {
  if (!enable_) {
    return;
  }

  std::ofstream OFS(fileName_);
  for (size_t i = 0, e = time_.size(); i != e; ++i) {
    OFS << i << ',' << time_[i] << ',' << wavePerSIMD_[i] << ',' << static_cast<uint>(state_[i])
        << '\n';
  }
  OFS.close();
}

void WaveLimiter::DataDumper::addData(ulong time, uint wave, char state) {
  if (!enable_) {
    return;
  }

  time_.push_back(time);
  wavePerSIMD_.push_back(wave);
  state_.push_back(state);
}

WaveLimiterManager::WaveLimiterManager(device::Kernel* kernel, const uint simdPerSH)
    : owner_(kernel), enable_(false), enableDump_(!flagIsDefault(GPU_WAVE_LIMIT_DUMP)) {
  setIfNotDefault(simdPerSH_, GPU_WAVE_LIMIT_CU_PER_SH, simdPerSH);
  fixed_ = GPU_WAVES_PER_SIMD * simdPerSH_;
}

WaveLimiterManager::~WaveLimiterManager() {
  for (auto& I : limiters_) {
    delete I.second;
  }
}

uint WaveLimiterManager::getWavesPerSH(const device::VirtualDevice* vdev) const {
  if (fixed_ > 0) {
    return fixed_;
  }
  if (!enable_) {
    return 0;
  }
  auto loc = limiters_.find(vdev);
  if (loc == limiters_.end()) {
    return 0;
  }
  assert(loc->second != nullptr);
  return loc->second->getWavesPerSH();
}

amd::ProfilingCallback* WaveLimiterManager::getProfilingCallback(
    const device::VirtualDevice* vdev) {
  assert(vdev != nullptr);
  if (!enable_ && !enableDump_) {
    return nullptr;
  }

  amd::ScopedLock SL(monitor_);
  auto loc = limiters_.find(vdev);
  if (loc != limiters_.end()) {
    return loc->second;
  }

  auto limiter = new WLAlgorithmSmooth(this, limiters_.size(), enable_, enableDump_);
  if (limiter == nullptr) {
    enable_ = false;
    return nullptr;
  }
  limiters_[vdev] = limiter;
  return limiter;
}

void WaveLimiterManager::enable() {
  if (fixed_ > 0) {
    return;
  }

  // Enable it only for CI+, unless GPU_WAVE_LIMIT_ENABLE is set to 1
  // Disabled for SI due to bug #10817
  if (!flagIsDefault(GPU_WAVE_LIMIT_ENABLE)) {
    enable_ = GPU_WAVE_LIMIT_ENABLE;
  } else {
    if (owner_->workGroupInfo()->wavesPerSimdHint_ == 0) {
      enable_ = true;
    } else if (owner_->workGroupInfo()->wavesPerSimdHint_ <= GPU_WAVE_LIMIT_MAX_WAVE) {
      fixed_ = owner_->workGroupInfo()->wavesPerSimdHint_ * getSimdPerSH();
    }
  }
}

}  // namespace pal
<commit_msg>P4 to Git Change 1507894 by gandryey@gera-lnx-rcf on 2018/01/25 11:38:47<commit_after>//
// Copyright (c) 2015 Advanced Micro Devices, Inc. All rights reserved.
//
#include "device/pal/palkernel.hpp"
#include "device/pal/palwavelimiter.hpp"
#include "os/os.hpp"
#include "utils/flags.hpp"

#include <cstdlib>
using namespace std;

namespace pal {

uint WaveLimiter::MaxWave;
uint WaveLimiter::RunCount;
uint WaveLimiter::AdaptCount;

WaveLimiter::WaveLimiter(WaveLimiterManager* manager, uint seqNum, bool enable, bool enableDump)
    : manager_(manager), dumper_(manager_->name() + "_" + std::to_string(seqNum), enableDump) {
  setIfNotDefault(SIMDPerSH_, GPU_WAVE_LIMIT_CU_PER_SH, manager->getSimdPerSH());
  MaxWave = GPU_WAVE_LIMIT_MAX_WAVE;
  RunCount = GPU_WAVE_LIMIT_RUN * MaxWave;
  AdaptCount = MaxContinuousSamples * 2 * (MaxWave + 1);

  state_ = WARMUP;
  if (!flagIsDefault(GPU_WAVE_LIMIT_TRACE)) {
    traceStream_.open(std::string(GPU_WAVE_LIMIT_TRACE) + manager_->name() + ".txt");
  }

  waves_ = MaxWave;
  enable_ = (SIMDPerSH_ == 0) ? false : enable;
  bestWave_ = (enable_) ? MaxWave : 0;
  sampleCount_ = 0;
  resultCount_ = 0;
  numContinuousSamples_ = 0;
}

WaveLimiter::~WaveLimiter() {
  if (traceStream_.is_open()) {
    traceStream_.close();
  }
}

uint WaveLimiter::getWavesPerSH() {
  // Generate different wave counts in the adaptation mode
  if ((state_ == ADAPT) && (sampleCount_ < AdaptCount)) {
    if (numContinuousSamples_ == 0) {
        ++waves_;
        waves_ %= MaxWave + 1;
    }
    ++numContinuousSamples_;
    numContinuousSamples_ %= MaxContinuousSamples;
    ++sampleCount_;
  }
  else {
    waves_ = bestWave_;
  }
  return waves_ * SIMDPerSH_;
}

WLAlgorithmSmooth::WLAlgorithmSmooth(WaveLimiterManager* manager, uint seqNum, bool enable,
                                     bool enableDump)
    : WaveLimiter(manager, seqNum, enable, enableDump) {
  dynRunCount_ = RunCount;
  adpMeasure_.resize(MaxWave + 1);
  adpSampleCnt_.resize(MaxWave + 1);
  runMeasure_.resize(MaxWave + 1);
  runSampleCnt_.resize(MaxWave + 1);

  clearData();
}

WLAlgorithmSmooth::~WLAlgorithmSmooth() {}

void WLAlgorithmSmooth::clearData() {
  waves_ = MaxWave;
  countAll_ = 0;
  clear(adpMeasure_);
  clear(adpSampleCnt_);
  dataCount_ = 0;
}

void WLAlgorithmSmooth::updateData(ulong time) {

}

void WLAlgorithmSmooth::outputTrace() {
  if (!traceStream_.is_open()) {
    return;
  }

  traceStream_ << "[WaveLimiter] " << manager_->name() << " state=" << state_
               << " waves=" << waves_ << " bestWave=" << bestWave_ << '\n';
  output(traceStream_, "\n adaptive measure = ", adpMeasure_);
  output(traceStream_, "\n adaptive smaple count = ", adpSampleCnt_);
  output(traceStream_, "\n run measure = ", runMeasure_);
  output(traceStream_, "\n run smaple count = ", runSampleCnt_);
  traceStream_ << "\n % time from the previous runs to the best wave: ";
  float min = static_cast<float>(adpMeasure_[bestWave_]) / adpSampleCnt_[bestWave_];
  for (uint i = 0; i < (MaxWave + 1); ++i) {
    runSampleCnt_[i] = (runSampleCnt_[i] == 0) ? 1 : runSampleCnt_[i];
    float average = static_cast<float>(runMeasure_[i]) / runSampleCnt_[i];
    traceStream_ << (average * 100 / min) << " ";
  }
  traceStream_ << "\n run count = " << dynRunCount_;
  traceStream_ << "\n\n";
}

void WLAlgorithmSmooth::callback(ulong duration, uint32_t waves) {
  dumper_.addData(duration, waves, static_cast<char>(state_));

  if (!enable_ || (duration == 0)) {
    return;
  }

  countAll_++;

  waves /= SIMDPerSH_;
  // Collect the time for the current wave count
  runMeasure_[waves] += duration;
  runSampleCnt_[waves]++;

  switch (state_) {
    case ADAPT:
      assert(duration > 0);
      // Wave count 0 indicates the satrt of adaptation
      if ((waves == 0) || (resultCount_ > 0)) {
        // Scale time to us
        adpMeasure_[waves] += duration;
        adpSampleCnt_[waves]++;
        resultCount_++;
        // If the end of adaptation is reached, then analyze the results
        if (resultCount_ == AdaptCount) {
          // Reset the counters
          resultCount_ = sampleCount_ = 0;
          float min = std::numeric_limits<float>::max();
          uint32_t best = bestWave_;
          // Check performance for the previous run if it's available
          if (runSampleCnt_[bestWave_] > 0) {
            min = static_cast<float>(runMeasure_[bestWave_]) / runSampleCnt_[bestWave_];
          }
          else if (adpSampleCnt_[MaxWave] > 0) {
            min = static_cast<float>(adpMeasure_[MaxWave]) / adpSampleCnt_[MaxWave];
            bestWave_ = MaxWave;
          }
          // Find the fastest average time
          float reference = min;
          for (uint i = MaxWave; i > 0; --i) {
            float average;
            if (adpSampleCnt_[i] > 0) {
              average = static_cast<float>(adpMeasure_[i]) / adpSampleCnt_[i];
            }
            else {
              average = 0.0f;
            }
            if (average < min) {
              min = average;
              bestWave_ = i;
            }
          }
          // Check for 5% acceptance
          if ((min * 1.05f > reference) || (bestWave_ == best)) {
            bestWave_ = best;
            // Increase the run time if the same wave count is the best
            dynRunCount_ += RunCount;
            dynRunCount_++;
          }
          else {
            dynRunCount_ = RunCount;
          }
          state_ = RUN;
          outputTrace();
          // Start to collect the new data for the best wave
          countAll_ = 0;
          runMeasure_[bestWave_] = 0;
          runSampleCnt_[bestWave_] = 0;
        }
      }
      return;
    case WARMUP:
    case RUN:
      if (countAll_ < dynRunCount_) {
        return;
      }
      if (state_ == WARMUP) {
        runSampleCnt_[bestWave_] = 0;
      }
      state_ = ADAPT;
      clearData();
      return;
  }
}

WaveLimiter::DataDumper::DataDumper(const std::string& kernelName, bool enable) {
  enable_ = enable;
  if (enable_) {
    fileName_ = std::string(GPU_WAVE_LIMIT_DUMP) + kernelName + ".csv";
  }
}

WaveLimiter::DataDumper::~DataDumper() {
  if (!enable_) {
    return;
  }

  std::ofstream OFS(fileName_);
  for (size_t i = 0, e = time_.size(); i != e; ++i) {
    OFS << i << ',' << time_[i] << ',' << wavePerSIMD_[i] << ',' << static_cast<uint>(state_[i])
        << '\n';
  }
  OFS.close();
}

void WaveLimiter::DataDumper::addData(ulong time, uint wave, char state) {
  if (!enable_) {
    return;
  }

  time_.push_back(time);
  wavePerSIMD_.push_back(wave);
  state_.push_back(state);
}

WaveLimiterManager::WaveLimiterManager(device::Kernel* kernel, const uint simdPerSH)
    : owner_(kernel), enable_(false), enableDump_(!flagIsDefault(GPU_WAVE_LIMIT_DUMP)) {
  setIfNotDefault(simdPerSH_, GPU_WAVE_LIMIT_CU_PER_SH, simdPerSH);
  fixed_ = GPU_WAVES_PER_SIMD * simdPerSH_;
}

WaveLimiterManager::~WaveLimiterManager() {
  for (auto& I : limiters_) {
    delete I.second;
  }
}

uint WaveLimiterManager::getWavesPerSH(const device::VirtualDevice* vdev) const {
  if (fixed_ > 0) {
    return fixed_;
  }
  if (!enable_) {
    return 0;
  }
  auto loc = limiters_.find(vdev);
  if (loc == limiters_.end()) {
    return 0;
  }
  assert(loc->second != nullptr);
  return loc->second->getWavesPerSH();
}

amd::ProfilingCallback* WaveLimiterManager::getProfilingCallback(
    const device::VirtualDevice* vdev) {
  assert(vdev != nullptr);
  if (!enable_ && !enableDump_) {
    return nullptr;
  }

  amd::ScopedLock SL(monitor_);
  auto loc = limiters_.find(vdev);
  if (loc != limiters_.end()) {
    return loc->second;
  }

  auto limiter = new WLAlgorithmSmooth(this, limiters_.size(), enable_, enableDump_);
  if (limiter == nullptr) {
    enable_ = false;
    return nullptr;
  }
  limiters_[vdev] = limiter;
  return limiter;
}

void WaveLimiterManager::enable() {
  if (fixed_ > 0) {
    return;
  }

  // Enable it only for CI+, unless GPU_WAVE_LIMIT_ENABLE is set to 1
  // Disabled for SI due to bug #10817
  if (!flagIsDefault(GPU_WAVE_LIMIT_ENABLE)) {
    enable_ = GPU_WAVE_LIMIT_ENABLE;
  } else {
    if (owner_->workGroupInfo()->wavesPerSimdHint_ == 0) {
      enable_ = true;
    } else if (owner_->workGroupInfo()->wavesPerSimdHint_ <= GPU_WAVE_LIMIT_MAX_WAVE) {
      fixed_ = owner_->workGroupInfo()->wavesPerSimdHint_ * getSimdPerSH();
    }
  }
}

}  // namespace pal
<|endoftext|>


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

#ifndef DBAUI_DBTYPEWIZDLGSETUP_HXX
#define DBAUI_DBTYPEWIZDLGSETUP_HXX

#ifndef _DBAUI_UNOADMIN_
#include "unoadmin.hxx"
#endif

//.........................................................................
namespace dbaui
{
//.........................................................................
//=========================================================================
//= ODBTypeWizDialogSetup
//=========================================================================
class ODBTypeWizDialogSetup
        :public ODatabaseAdministrationDialog
        ,public ::comphelper::OPropertyArrayUsageHelper< ODBTypeWizDialogSetup >
{
    ::rtl::OUString m_sExistingDocToOpen;
    sal_Bool        m_bOpenDatabase;
    sal_Bool        m_bStartTableWizard;

protected:
    ODBTypeWizDialogSetup(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB);

public:
    // XTypeProvider
    virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL getImplementationId(  ) throw(::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
    virtual ::comphelper::StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);

    // XServiceInfo - static methods
    static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
    static ::rtl::OUString getImplementationName_Static(void) throw( ::com::sun::star::uno::RuntimeException );
    static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
            SAL_CALL Create(const ::com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >&);

    // XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo>  SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
    virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();

    // OPropertyArrayUsageHelper
    virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;
protected:
// OGenericUnoDialog overridables
    virtual Dialog* createDialog(Window* _pParent);
    virtual void executedDialog(sal_Int16 _nExecutionResult);
};

//.........................................................................
}   // namespace dbaui
//.........................................................................

#endif // DBAUI_DBTYPEWIZDLG_HXX

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

#ifndef DBAUI_DBTYPEWIZDLGSETUP_HXX
#define DBAUI_DBTYPEWIZDLGSETUP_HXX

#ifndef _DBAUI_UNOADMIN_
#include "unoadmin.hxx"
#endif

//.........................................................................
namespace dbaui
{
//.........................................................................
//=========================================================================
//= ODBTypeWizDialogSetup
//=========================================================================
class ODBTypeWizDialogSetup
        :public ODatabaseAdministrationDialog
        ,public ::comphelper::OPropertyArrayUsageHelper< ODBTypeWizDialogSetup >
{
    ::rtl::OUString m_sExistingDocToOpen;
    sal_Bool        m_bOpenDatabase;
    sal_Bool        m_bStartTableWizard;

protected:
    ODBTypeWizDialogSetup(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB);

public:
    // XTypeProvider
    virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL getImplementationId(  ) throw(::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
    virtual ::comphelper::StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);

    // XServiceInfo - static methods
    static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
    static ::rtl::OUString getImplementationName_Static(void) throw( ::com::sun::star::uno::RuntimeException );
    static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
            SAL_CALL Create(const ::com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >&);

    // XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo>  SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
    virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();

    // OPropertyArrayUsageHelper
    virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;
protected:
// OGenericUnoDialog overridables
    virtual Dialog* createDialog(Window* _pParent);
    virtual void executedDialog(sal_Int16 _nExecutionResult);
};

//.........................................................................
}   // namespace dbaui
//.........................................................................

#endif // DBAUI_DBTYPEWIZDLG_HXX

<|endoftext|>


<commit_before><commit_msg>CWS-TOOLING: integrate CWS calc33stopper3<commit_after><|endoftext|>


<commit_before>#include <openssl/evp.h>

#include <common/factory.h>

#include <crypto/crypto_encryption.h>

namespace {
	class SessionEVP : public CryptoEncryption::Session {
		LogHandle log_;
		const EVP_CIPHER *cipher_;
		EVP_CIPHER_CTX ctx_;
	public:
		SessionEVP(const EVP_CIPHER *xcipher)
		: log_("/crypto/encryption/session/openssl"),
		  cipher_(xcipher),
		  ctx_()
		{
			EVP_CIPHER_CTX_init(&ctx_);
		}

		~SessionEVP()
		{
			EVP_CIPHER_CTX_cleanup(&ctx_);
		}

		unsigned block_size(void) const
		{
			return (EVP_CIPHER_block_size(cipher_));
		}

		unsigned key_size(void) const
		{
			return (EVP_CIPHER_key_length(cipher_));
		}

		unsigned iv_size(void) const
		{
			return (EVP_CIPHER_iv_length(cipher_));
		}

		Session *clone(void) const
		{
			return (new SessionEVP(cipher_));
		}

		bool initialize(CryptoEncryption::Operation operation, const Buffer *key, const Buffer *iv)
		{
			if (key->length() < (size_t)EVP_CIPHER_key_length(cipher_))
				return (false);

			if (iv->length() < (size_t)EVP_CIPHER_iv_length(cipher_))
				return (false);

			int enc;
			switch (operation) {
			case CryptoEncryption::Encrypt:
				enc = 1;
				break;
			case CryptoEncryption::Decrypt:
				enc = 0;
				break;
			default:
				return (false);
			}

			uint8_t keydata[key->length()];
			key->copyout(keydata, sizeof keydata);

			uint8_t ivdata[iv->length()];
			iv->copyout(ivdata, sizeof ivdata);

			int rv = EVP_CipherInit(&ctx_, cipher_, keydata, ivdata, enc);
			if (rv == 0)
				return (false);

			return (true);
		}

		bool cipher(Buffer *out, const Buffer *in)
		{
			/*
			 * We process a single, large, linear byte buffer here rather
			 * than going a BufferSegment at a time, even though the byte
			 * buffer is less efficient than some alternatives, because
			 * there are padding and buffering implications if each
			 * BufferSegment's length is not modular to the block size.
			 */
			uint8_t indata[in->length()];
			in->copyout(indata, sizeof indata);

			uint8_t outdata[sizeof indata];
			int rv = EVP_Cipher(&ctx_, outdata, indata, sizeof indata);
			if (rv == 0)
				return (false);
			out->append(outdata, sizeof outdata);
			return (true);
		}

		Action *submit(Buffer *in, EventCallback *cb)
		{
			Buffer out;
			if (!cipher(&out, in)) {
				in->clear();
				cb->param(Event::Error);
				return (cb->schedule());
			}
			in->clear();
			cb->param(Event(Event::Done, out));
			return (cb->schedule());
		}
	};

	class MethodOpenSSL : public CryptoEncryption::Method {
		LogHandle log_;
		FactoryMap<CryptoEncryption::Cipher, CryptoEncryption::Session> cipher_map_;
	public:
		MethodOpenSSL(void)
		: CryptoEncryption::Method("OpenSSL"),
		  log_("/crypto/encryption/openssl"),
		  cipher_map_()
		{
			OpenSSL_add_all_algorithms();

			factory<SessionEVP> evp_factory;
			cipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::TripleDES, CryptoEncryption::CBC), evp_factory(EVP_des_ede3_cbc()));
			cipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES128, CryptoEncryption::CBC), evp_factory(EVP_aes_128_cbc()));
			cipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES192, CryptoEncryption::CBC), evp_factory(EVP_aes_192_cbc()));
			cipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES256, CryptoEncryption::CBC), evp_factory(EVP_aes_256_cbc()));
#if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x00907000L) && !defined(__APPLE__)
			cipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES128, CryptoEncryption::CTR), evp_factory(EVP_aes_128_ctr()));
			cipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES192, CryptoEncryption::CTR), evp_factory(EVP_aes_192_ctr()));
			cipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES256, CryptoEncryption::CTR), evp_factory(EVP_aes_256_ctr()));
#endif

			/* XXX Register.  */
		}

		~MethodOpenSSL()
		{
			/* XXX Unregister.  */
		}

		std::set<CryptoEncryption::Cipher> ciphers(void) const
		{
			return (cipher_map_.keys());
		}

		CryptoEncryption::Session *session(CryptoEncryption::Cipher cipher) const
		{
			return (cipher_map_.create(cipher));
		}
	};

	static MethodOpenSSL crypto_encryption_method_openssl;
}
<commit_msg>FreeBSD lies, too.  Bleh.<commit_after>#include <openssl/evp.h>

#include <common/factory.h>

#include <crypto/crypto_encryption.h>

namespace {
	class SessionEVP : public CryptoEncryption::Session {
		LogHandle log_;
		const EVP_CIPHER *cipher_;
		EVP_CIPHER_CTX ctx_;
	public:
		SessionEVP(const EVP_CIPHER *xcipher)
		: log_("/crypto/encryption/session/openssl"),
		  cipher_(xcipher),
		  ctx_()
		{
			EVP_CIPHER_CTX_init(&ctx_);
		}

		~SessionEVP()
		{
			EVP_CIPHER_CTX_cleanup(&ctx_);
		}

		unsigned block_size(void) const
		{
			return (EVP_CIPHER_block_size(cipher_));
		}

		unsigned key_size(void) const
		{
			return (EVP_CIPHER_key_length(cipher_));
		}

		unsigned iv_size(void) const
		{
			return (EVP_CIPHER_iv_length(cipher_));
		}

		Session *clone(void) const
		{
			return (new SessionEVP(cipher_));
		}

		bool initialize(CryptoEncryption::Operation operation, const Buffer *key, const Buffer *iv)
		{
			if (key->length() < (size_t)EVP_CIPHER_key_length(cipher_))
				return (false);

			if (iv->length() < (size_t)EVP_CIPHER_iv_length(cipher_))
				return (false);

			int enc;
			switch (operation) {
			case CryptoEncryption::Encrypt:
				enc = 1;
				break;
			case CryptoEncryption::Decrypt:
				enc = 0;
				break;
			default:
				return (false);
			}

			uint8_t keydata[key->length()];
			key->copyout(keydata, sizeof keydata);

			uint8_t ivdata[iv->length()];
			iv->copyout(ivdata, sizeof ivdata);

			int rv = EVP_CipherInit(&ctx_, cipher_, keydata, ivdata, enc);
			if (rv == 0)
				return (false);

			return (true);
		}

		bool cipher(Buffer *out, const Buffer *in)
		{
			/*
			 * We process a single, large, linear byte buffer here rather
			 * than going a BufferSegment at a time, even though the byte
			 * buffer is less efficient than some alternatives, because
			 * there are padding and buffering implications if each
			 * BufferSegment's length is not modular to the block size.
			 */
			uint8_t indata[in->length()];
			in->copyout(indata, sizeof indata);

			uint8_t outdata[sizeof indata];
			int rv = EVP_Cipher(&ctx_, outdata, indata, sizeof indata);
			if (rv == 0)
				return (false);
			out->append(outdata, sizeof outdata);
			return (true);
		}

		Action *submit(Buffer *in, EventCallback *cb)
		{
			Buffer out;
			if (!cipher(&out, in)) {
				in->clear();
				cb->param(Event::Error);
				return (cb->schedule());
			}
			in->clear();
			cb->param(Event(Event::Done, out));
			return (cb->schedule());
		}
	};

	class MethodOpenSSL : public CryptoEncryption::Method {
		LogHandle log_;
		FactoryMap<CryptoEncryption::Cipher, CryptoEncryption::Session> cipher_map_;
	public:
		MethodOpenSSL(void)
		: CryptoEncryption::Method("OpenSSL"),
		  log_("/crypto/encryption/openssl"),
		  cipher_map_()
		{
			OpenSSL_add_all_algorithms();

			factory<SessionEVP> evp_factory;
			cipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::TripleDES, CryptoEncryption::CBC), evp_factory(EVP_des_ede3_cbc()));
			cipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES128, CryptoEncryption::CBC), evp_factory(EVP_aes_128_cbc()));
			cipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES192, CryptoEncryption::CBC), evp_factory(EVP_aes_192_cbc()));
			cipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES256, CryptoEncryption::CBC), evp_factory(EVP_aes_256_cbc()));
#if 0
			cipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES128, CryptoEncryption::CTR), evp_factory(EVP_aes_128_ctr()));
			cipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES192, CryptoEncryption::CTR), evp_factory(EVP_aes_192_ctr()));
			cipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES256, CryptoEncryption::CTR), evp_factory(EVP_aes_256_ctr()));
#endif

			/* XXX Register.  */
		}

		~MethodOpenSSL()
		{
			/* XXX Unregister.  */
		}

		std::set<CryptoEncryption::Cipher> ciphers(void) const
		{
			return (cipher_map_.keys());
		}

		CryptoEncryption::Session *session(CryptoEncryption::Cipher cipher) const
		{
			return (cipher_map_.create(cipher));
		}
	};

	static MethodOpenSSL crypto_encryption_method_openssl;
}
<|endoftext|>