<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: salframe.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2007-04-11 18:06:15 $
 *
 *  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 _SV_SALFRAME_HXX
#define _SV_SALFRAME_HXX

#ifndef _SV_SV_H
#include <vcl/sv.h>
#endif

#ifndef _VCL_DLLAPI_H
#include <vcl/dllapi.h>
#endif

#ifdef __cplusplus

#ifndef _SV_PTRSTYLE_HXX
#include <vcl/ptrstyle.hxx>
#endif
#ifndef _SV_SNDSTYLE_HXX
#include <vcl/sndstyle.hxx>
#endif

#endif // __cplusplus

#ifndef _SV_SALWTYPE_HXX
#include <vcl/salwtype.hxx>
#endif
#ifndef _SV_SALGEOM_HXX
#include <vcl/salgeom.hxx>
#endif

#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif

#ifndef _SV_REGION_HXX
#include <vcl/region.hxx>
#endif

#ifndef _VCL_IMPDEL_HXX
#include <vcl/impdel.hxx>
#endif

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

#ifndef _SV_KEYCODE_HXX
#include <vcl/keycod.hxx>
#endif

#ifdef __cplusplus

class AllSettings;
class SalGraphics;
class SalBitmap;
class SalMenu;

#else

#define AllSettings void
#define SalGraphics void

#endif // __cplusplus

struct SalFrameState;
struct SalInputContext;
struct SystemEnvData;

// -----------------
// - SalFrameTypes -
// -----------------

#define SAL_FRAME_TOTOP_RESTOREWHENMIN      ((USHORT)0x0001)
#define SAL_FRAME_TOTOP_FOREGROUNDTASK      ((USHORT)0x0002)
#define SAL_FRAME_TOTOP_GRABFOCUS           ((USHORT)0x0004)
#define SAL_FRAME_TOTOP_GRABFOCUS_ONLY       ((USHORT)0x0008)

#define SAL_FRAME_ENDEXTTEXTINPUT_COMPLETE  ((USHORT)0x0001)
#define SAL_FRAME_ENDEXTTEXTINPUT_CANCEL    ((USHORT)0x0002)

// -----------------
// - SalFrameStyle -
// -----------------

#define SAL_FRAME_STYLE_DEFAULT             ((ULONG)0x00000001)
#define SAL_FRAME_STYLE_MOVEABLE            ((ULONG)0x00000002)
#define SAL_FRAME_STYLE_SIZEABLE            ((ULONG)0x00000004)
#define SAL_FRAME_STYLE_CLOSEABLE           ((ULONG)0x00000008)

// no shadow effect on WindowsXP
#define SAL_FRAME_STYLE_NOSHADOW            ((ULONG)0x00000010)
// indicate tooltip windows, so they can always be topmost
#define SAL_FRAME_STYLE_TOOLTIP             ((ULONG)0x00000020)
// windows without windowmanager decoration, this typically only applies to floating windows
#define SAL_FRAME_STYLE_OWNERDRAWDECORATION ((ULONG)0x00000040)
// dialogs
#define SAL_FRAME_STYLE_DIALOG              ((ULONG)0x00000080)
// partial fullscreen: fullscreen on one monitor of a multimonitor display
#define SAL_FRAME_STYLE_PARTIAL_FULLSCREEN  ((ULONG)0x08000000)
// system child window
#define SAL_FRAME_STYLE_CHILD               ((ULONG)0x10000000)
// floating window
#define SAL_FRAME_STYLE_FLOAT               ((ULONG)0x20000000)
// toolwindows should be painted with a smaller decoration
#define SAL_FRAME_STYLE_TOOLWINDOW          ((ULONG)0x40000000)
// the window containing the intro bitmap, aka splashscreen
#define SAL_FRAME_STYLE_INTRO               ((ULONG)0x80000000)

/*
#define SAL_FRAME_STYLE_MINABLE             ((ULONG)0x00000008)
#define SAL_FRAME_STYLE_MAXABLE             ((ULONG)0x00000010)
#define SAL_FRAME_STYLE_BORDER              ((ULONG)0x00000040)
#define SAL_FRAME_STYLE_DOC                 ((ULONG)0x00004000)
#define SAL_FRAME_STYLE_DIALOG              ((ULONG)0x00008000)
#define SAL_FRAME_STYLE_TOOL                ((ULONG)0x00010000)
#define SAL_FRAME_STYLE_FULLSIZE            ((ULONG)0x00020000)
*/

// ----------------------------------------
// - extended frame style                 -
// - (sal equivalent to extended WinBits) -
// ----------------------------------------
typedef sal_uInt64 SalExtStyle;
#define SAL_FRAME_EXT_STYLE_DOCUMENT        SalExtStyle(0x00000001)

// ------------------------
// - Flags for SetPosSize -
// ------------------------

#define SAL_FRAME_POSSIZE_X                 ((USHORT)0x0001)
#define SAL_FRAME_POSSIZE_Y                 ((USHORT)0x0002)
#define SAL_FRAME_POSSIZE_WIDTH             ((USHORT)0x0004)
#define SAL_FRAME_POSSIZE_HEIGHT            ((USHORT)0x0008)

#ifdef __cplusplus

using namespace rtl;

// ------------
// - SalFrame -
// ------------

struct SystemParentData;

class VCL_DLLPUBLIC SalFrame : public vcl::DeletionNotifier
{
    void*                   m_pInst;
    SALFRAMEPROC            m_pProc;
public:                     // public for Sal Implementation
    SalFrame() : m_pInst( NULL ), m_pProc( NULL ) {}
    virtual ~SalFrame();

public:                     // public for Sal Implementation
    SalFrameGeometry        maGeometry;

public:
    // SalGraphics or NULL, but two Graphics for all SalFrames
    // must be returned
    virtual SalGraphics*        GetGraphics() = 0;
    virtual void                ReleaseGraphics( SalGraphics* pGraphics ) = 0;

    // Event must be destroyed, when Frame is destroyed
    // When Event is called, SalInstance::Yield() must be returned
    virtual BOOL                PostEvent( void* pData ) = 0;

    virtual void                SetTitle( const XubString& rTitle ) = 0;
    virtual void                SetIcon( USHORT nIcon ) = 0;
    virtual void                    SetMenu( SalMenu *pSalMenu ) = 0;
    virtual void                    DrawMenuBar() = 0;

    virtual void                SetExtendedFrameStyle( SalExtStyle nExtStyle ) = 0;

    // Before the window is visible, a resize event
    // must be sent with the correct size
    virtual void                Show( BOOL bVisible, BOOL bNoActivate = FALSE ) = 0;
    virtual void                Enable( BOOL bEnable ) = 0;
    // Set ClientSize and Center the Window to the desktop
    // and send/post a resize message
    virtual void                SetMinClientSize( long nWidth, long nHeight ) = 0;
    virtual void                SetMaxClientSize( long nWidth, long nHeight ) = 0;
    virtual void                SetPosSize( long nX, long nY, long nWidth, long nHeight, USHORT nFlags ) = 0;
    virtual void                GetClientSize( long& rWidth, long& rHeight ) = 0;
    virtual void                GetWorkArea( Rectangle& rRect ) = 0;
    virtual SalFrame*           GetParent() const = 0;
    // Note: x will be mirrored at parent if UI mirroring is active
    SalFrameGeometry            GetGeometry();
    const SalFrameGeometry&     GetUnmirroredGeometry() const { return maGeometry; }
    virtual void                SetWindowState( const SalFrameState* pState ) = 0;
    virtual BOOL                GetWindowState( SalFrameState* pState ) = 0;
    virtual void                ShowFullScreen( BOOL bFullScreen, sal_Int32 nDisplay ) = 0;
    // Enable/Disable ScreenSaver, SystemAgents, ...
    virtual void                StartPresentation( BOOL bStart ) = 0;
    // Show Window over all other Windows
    virtual void                SetAlwaysOnTop( BOOL bOnTop ) = 0;

    // Window to top and grab focus
    virtual void                ToTop( USHORT nFlags ) = 0;

    // this function can call with the same
    // pointer style
    virtual void                SetPointer( PointerStyle ePointerStyle ) = 0;
    virtual void                CaptureMouse( BOOL bMouse ) = 0;
    virtual void                SetPointerPos( long nX, long nY ) = 0;

    // flush output buffer
    virtual void                Flush() = 0;
    // flush output buffer, wait till outstanding operations are done
    virtual void                Sync() = 0;

    virtual void                SetInputContext( SalInputContext* pContext ) = 0;
    virtual void                EndExtTextInput( USHORT nFlags ) = 0;

    virtual String              GetKeyName( USHORT nKeyCode ) = 0;
    virtual String              GetSymbolKeyName( const XubString& rFontName, USHORT nKeyCode ) = 0;

    // returns in 'rKeyCode' the single keycode that translates to the given unicode when using a keyboard layout of language 'aLangType'
    // returns FALSE if no mapping exists or function not supported
    // this is required for advanced menu support
    virtual BOOL                MapUnicodeToKeyCode( sal_Unicode aUnicode, LanguageType aLangType, KeyCode& rKeyCode ) = 0;

    // returns the input language used for the last key stroke
    // may be LANGUAGE_DONTKNOW if not supported by the OS
    virtual LanguageType        GetInputLanguage() = 0;

    virtual SalBitmap*          SnapShot() = 0;

    virtual void                UpdateSettings( AllSettings& rSettings ) = 0;

    virtual void                Beep( SoundType eSoundType ) = 0;

    // returns system data (most prominent: window handle)
    virtual const SystemEnvData*    GetSystemData() const = 0;

    // sets a background bitmap on the frame; the implementation
    // must not make assumptions about the lifetime of the passed SalBitmap
    // but should copy its contents to an own buffer
    virtual void                SetBackgroundBitmap( SalBitmap* ) = 0;

    // get current modifier, button mask and mouse position
    struct SalPointerState
    {
        ULONG   mnState;
        Point   maPos;      // in frame coordinates
    };

    virtual SalPointerState     GetPointerState() = 0;

    // set new parent window
    virtual void                SetParent( SalFrame* pNewParent ) = 0;
    // reparent window to act as a plugin; implementation
    // may choose to use a new system window inetrnally
    // return false to indicate failure
    virtual bool                SetPluginParent( SystemParentData* pNewParent ) = 0;

    // shaped system windows
    // set clip region to none (-> rectangular windows, normal state)
    virtual void                    ResetClipRegion() = 0;
    // start setting the clipregion consisting of nRects rectangles
    virtual void                    BeginSetClipRegion( ULONG nRects ) = 0;
    // add a rectangle to the clip region
    virtual void                    UnionClipRegion( long nX, long nY, long nWidth, long nHeight ) = 0;
    // done setting up the clipregion
    virtual void                    EndSetClipRegion() = 0;

    // Callbacks (indepent part in vcl/source/window/winproc.cxx)
    // for default message handling return 0
    void                        SetCallback( void* pInst, SALFRAMEPROC pProc )
    { m_pInst = pInst; m_pProc = pProc; }

    // returns the instance set
    void*                       GetInstance() const { return m_pInst; }

    // Call the callback set; this sometimes necessary for implementation classes
    // that should not now more than necessary about the SalFrame implementation
    // (e.g. input methods, printer update handlers).
    long                        CallCallback( USHORT nEvent, const void* pEvent ) const
    { return m_pProc ? m_pProc( m_pInst, const_cast<SalFrame*>(this), nEvent, pEvent ) : 0; }
};

#endif // __cplusplus

#endif // _SV_SALFRAME_HXX
<commit_msg>INTEGRATION: CWS aquavcl03 (1.2.106); FILE MERGED 2007/09/06 15:42:39 pl 1.2.106.1: #i80230# make instance pointer of SalFrameProc a Window ptr explicitly<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: salframe.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2007-10-09 15:17:45 $
 *
 *  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 _SV_SALFRAME_HXX
#define _SV_SALFRAME_HXX

#ifndef _SV_SV_H
#include <vcl/sv.h>
#endif

#ifndef _VCL_DLLAPI_H
#include <vcl/dllapi.h>
#endif

#ifdef __cplusplus

#ifndef _SV_PTRSTYLE_HXX
#include <vcl/ptrstyle.hxx>
#endif
#ifndef _SV_SNDSTYLE_HXX
#include <vcl/sndstyle.hxx>
#endif

#endif // __cplusplus

#ifndef _SV_SALWTYPE_HXX
#include <vcl/salwtype.hxx>
#endif
#ifndef _SV_SALGEOM_HXX
#include <vcl/salgeom.hxx>
#endif

#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif

#ifndef _SV_REGION_HXX
#include <vcl/region.hxx>
#endif

#ifndef _VCL_IMPDEL_HXX
#include <vcl/impdel.hxx>
#endif

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

#ifndef _SV_KEYCODE_HXX
#include <vcl/keycod.hxx>
#endif

class AllSettings;
class SalGraphics;
class SalBitmap;
class SalMenu;
class Window;

struct SalFrameState;
struct SalInputContext;
struct SystemEnvData;

// -----------------
// - SalFrameTypes -
// -----------------

#define SAL_FRAME_TOTOP_RESTOREWHENMIN      ((USHORT)0x0001)
#define SAL_FRAME_TOTOP_FOREGROUNDTASK      ((USHORT)0x0002)
#define SAL_FRAME_TOTOP_GRABFOCUS           ((USHORT)0x0004)
#define SAL_FRAME_TOTOP_GRABFOCUS_ONLY       ((USHORT)0x0008)

#define SAL_FRAME_ENDEXTTEXTINPUT_COMPLETE  ((USHORT)0x0001)
#define SAL_FRAME_ENDEXTTEXTINPUT_CANCEL    ((USHORT)0x0002)

// -----------------
// - SalFrameStyle -
// -----------------

#define SAL_FRAME_STYLE_DEFAULT             ((ULONG)0x00000001)
#define SAL_FRAME_STYLE_MOVEABLE            ((ULONG)0x00000002)
#define SAL_FRAME_STYLE_SIZEABLE            ((ULONG)0x00000004)
#define SAL_FRAME_STYLE_CLOSEABLE           ((ULONG)0x00000008)

// no shadow effect on WindowsXP
#define SAL_FRAME_STYLE_NOSHADOW            ((ULONG)0x00000010)
// indicate tooltip windows, so they can always be topmost
#define SAL_FRAME_STYLE_TOOLTIP             ((ULONG)0x00000020)
// windows without windowmanager decoration, this typically only applies to floating windows
#define SAL_FRAME_STYLE_OWNERDRAWDECORATION ((ULONG)0x00000040)
// dialogs
#define SAL_FRAME_STYLE_DIALOG              ((ULONG)0x00000080)
// partial fullscreen: fullscreen on one monitor of a multimonitor display
#define SAL_FRAME_STYLE_PARTIAL_FULLSCREEN  ((ULONG)0x08000000)
// system child window
#define SAL_FRAME_STYLE_CHILD               ((ULONG)0x10000000)
// floating window
#define SAL_FRAME_STYLE_FLOAT               ((ULONG)0x20000000)
// toolwindows should be painted with a smaller decoration
#define SAL_FRAME_STYLE_TOOLWINDOW          ((ULONG)0x40000000)
// the window containing the intro bitmap, aka splashscreen
#define SAL_FRAME_STYLE_INTRO               ((ULONG)0x80000000)

/*
#define SAL_FRAME_STYLE_MINABLE             ((ULONG)0x00000008)
#define SAL_FRAME_STYLE_MAXABLE             ((ULONG)0x00000010)
#define SAL_FRAME_STYLE_BORDER              ((ULONG)0x00000040)
#define SAL_FRAME_STYLE_DOC                 ((ULONG)0x00004000)
#define SAL_FRAME_STYLE_DIALOG              ((ULONG)0x00008000)
#define SAL_FRAME_STYLE_TOOL                ((ULONG)0x00010000)
#define SAL_FRAME_STYLE_FULLSIZE            ((ULONG)0x00020000)
*/

// ----------------------------------------
// - extended frame style                 -
// - (sal equivalent to extended WinBits) -
// ----------------------------------------
typedef sal_uInt64 SalExtStyle;
#define SAL_FRAME_EXT_STYLE_DOCUMENT        SalExtStyle(0x00000001)

// ------------------------
// - Flags for SetPosSize -
// ------------------------

#define SAL_FRAME_POSSIZE_X                 ((USHORT)0x0001)
#define SAL_FRAME_POSSIZE_Y                 ((USHORT)0x0002)
#define SAL_FRAME_POSSIZE_WIDTH             ((USHORT)0x0004)
#define SAL_FRAME_POSSIZE_HEIGHT            ((USHORT)0x0008)

#ifdef __cplusplus

using namespace rtl;

// ------------
// - SalFrame -
// ------------

struct SystemParentData;

class VCL_DLLPUBLIC SalFrame : public vcl::DeletionNotifier
{
    // the VCL window corresponding to this frame
    Window*                 m_pWindow;
    SALFRAMEPROC            m_pProc;
public:                     // public for Sal Implementation
    SalFrame() : m_pWindow( NULL ), m_pProc( NULL ) {}
    virtual ~SalFrame();

public:                     // public for Sal Implementation
    SalFrameGeometry        maGeometry;

public:
    // SalGraphics or NULL, but two Graphics for all SalFrames
    // must be returned
    virtual SalGraphics*        GetGraphics() = 0;
    virtual void                ReleaseGraphics( SalGraphics* pGraphics ) = 0;

    // Event must be destroyed, when Frame is destroyed
    // When Event is called, SalInstance::Yield() must be returned
    virtual BOOL                PostEvent( void* pData ) = 0;

    virtual void                SetTitle( const XubString& rTitle ) = 0;
    virtual void                SetIcon( USHORT nIcon ) = 0;
    virtual void                    SetMenu( SalMenu *pSalMenu ) = 0;
    virtual void                    DrawMenuBar() = 0;

    virtual void                SetExtendedFrameStyle( SalExtStyle nExtStyle ) = 0;

    // Before the window is visible, a resize event
    // must be sent with the correct size
    virtual void                Show( BOOL bVisible, BOOL bNoActivate = FALSE ) = 0;
    virtual void                Enable( BOOL bEnable ) = 0;
    // Set ClientSize and Center the Window to the desktop
    // and send/post a resize message
    virtual void                SetMinClientSize( long nWidth, long nHeight ) = 0;
    virtual void                SetMaxClientSize( long nWidth, long nHeight ) = 0;
    virtual void                SetPosSize( long nX, long nY, long nWidth, long nHeight, USHORT nFlags ) = 0;
    virtual void                GetClientSize( long& rWidth, long& rHeight ) = 0;
    virtual void                GetWorkArea( Rectangle& rRect ) = 0;
    virtual SalFrame*           GetParent() const = 0;
    // Note: x will be mirrored at parent if UI mirroring is active
    SalFrameGeometry            GetGeometry();
    const SalFrameGeometry&     GetUnmirroredGeometry() const { return maGeometry; }
    virtual void                SetWindowState( const SalFrameState* pState ) = 0;
    virtual BOOL                GetWindowState( SalFrameState* pState ) = 0;
    virtual void                ShowFullScreen( BOOL bFullScreen, sal_Int32 nDisplay ) = 0;
    // Enable/Disable ScreenSaver, SystemAgents, ...
    virtual void                StartPresentation( BOOL bStart ) = 0;
    // Show Window over all other Windows
    virtual void                SetAlwaysOnTop( BOOL bOnTop ) = 0;

    // Window to top and grab focus
    virtual void                ToTop( USHORT nFlags ) = 0;

    // this function can call with the same
    // pointer style
    virtual void                SetPointer( PointerStyle ePointerStyle ) = 0;
    virtual void                CaptureMouse( BOOL bMouse ) = 0;
    virtual void                SetPointerPos( long nX, long nY ) = 0;

    // flush output buffer
    virtual void                Flush() = 0;
    // flush output buffer, wait till outstanding operations are done
    virtual void                Sync() = 0;

    virtual void                SetInputContext( SalInputContext* pContext ) = 0;
    virtual void                EndExtTextInput( USHORT nFlags ) = 0;

    virtual String              GetKeyName( USHORT nKeyCode ) = 0;
    virtual String              GetSymbolKeyName( const XubString& rFontName, USHORT nKeyCode ) = 0;

    // returns in 'rKeyCode' the single keycode that translates to the given unicode when using a keyboard layout of language 'aLangType'
    // returns FALSE if no mapping exists or function not supported
    // this is required for advanced menu support
    virtual BOOL                MapUnicodeToKeyCode( sal_Unicode aUnicode, LanguageType aLangType, KeyCode& rKeyCode ) = 0;

    // returns the input language used for the last key stroke
    // may be LANGUAGE_DONTKNOW if not supported by the OS
    virtual LanguageType        GetInputLanguage() = 0;

    virtual SalBitmap*          SnapShot() = 0;

    virtual void                UpdateSettings( AllSettings& rSettings ) = 0;

    virtual void                Beep( SoundType eSoundType ) = 0;

    // returns system data (most prominent: window handle)
    virtual const SystemEnvData*    GetSystemData() const = 0;

    // sets a background bitmap on the frame; the implementation
    // must not make assumptions about the lifetime of the passed SalBitmap
    // but should copy its contents to an own buffer
    virtual void                SetBackgroundBitmap( SalBitmap* ) = 0;

    // get current modifier, button mask and mouse position
    struct SalPointerState
    {
        ULONG   mnState;
        Point   maPos;      // in frame coordinates
    };

    virtual SalPointerState     GetPointerState() = 0;

    // set new parent window
    virtual void                SetParent( SalFrame* pNewParent ) = 0;
    // reparent window to act as a plugin; implementation
    // may choose to use a new system window inetrnally
    // return false to indicate failure
    virtual bool                SetPluginParent( SystemParentData* pNewParent ) = 0;

    // shaped system windows
    // set clip region to none (-> rectangular windows, normal state)
    virtual void                    ResetClipRegion() = 0;
    // start setting the clipregion consisting of nRects rectangles
    virtual void                    BeginSetClipRegion( ULONG nRects ) = 0;
    // add a rectangle to the clip region
    virtual void                    UnionClipRegion( long nX, long nY, long nWidth, long nHeight ) = 0;
    // done setting up the clipregion
    virtual void                    EndSetClipRegion() = 0;

    // Callbacks (indepent part in vcl/source/window/winproc.cxx)
    // for default message handling return 0
    void                        SetCallback( Window* pWindow, SALFRAMEPROC pProc )
    { m_pWindow = pWindow; m_pProc = pProc; }

    // returns the instance set
    Window*                       GetWindow() const { return m_pWindow; }

    // Call the callback set; this sometimes necessary for implementation classes
    // that should not now more than necessary about the SalFrame implementation
    // (e.g. input methods, printer update handlers).
    long                        CallCallback( USHORT nEvent, const void* pEvent ) const
    { return m_pProc ? m_pProc( m_pWindow, const_cast<SalFrame*>(this), nEvent, pEvent ) : 0; }
};

#endif // __cplusplus

#endif // _SV_SALFRAME_HXX
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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.
 *
 ************************************************************************/

#include "VCLKDEApplication.hxx"

#define Region QtXRegion

#include <kapplication.h>
#include <klocale.h>
#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <kstartupinfo.h>
#include <qabstracteventdispatcher.h>
#include <qclipboard.h>
#include <qthread.h>

#undef Region

#include "KDEXLib.hxx"

#include <i18n_im.hxx>
#include <i18n_xkb.hxx>

#include <saldata.hxx>
#include <vos/process.hxx>

#include "KDESalDisplay.hxx"

#if OSL_DEBUG_LEVEL > 1
#include <stdio.h>
#endif

#include <stdio.h>

#ifdef KDE_HAVE_GLIB
#if QT_VERSION >= QT_VERSION_CHECK( 4, 8, 0 )
#if 0 // wait until fixed in Qt
#define GLIB_EVENT_LOOP_SUPPORT
#endif
#endif
#endif

#ifdef GLIB_EVENT_LOOP_SUPPORT
#include <glib-2.0/glib.h>
#endif

KDEXLib::KDEXLib() :
    SalXLib(),  m_bStartupDone(false), m_pApplication(0),
    m_pFreeCmdLineArgs(0), m_pAppCmdLineArgs(0), m_nFakeCmdLineArgs( 0 ),
    eventLoopType( LibreOfficeEventLoop )
{
    // the timers created here means they belong to the main thread
    connect( &timeoutTimer, SIGNAL( timeout()), this, SLOT( timeoutActivated()));
    connect( &userEventTimer, SIGNAL( timeout()), this, SLOT( userEventActivated()));
    // QTimer::start() can be called only in its (here main) thread, so this will
    // forward between threads if needed
    connect( this, SIGNAL( startTimeoutTimerSignal()), this, SLOT( startTimeoutTimer()), Qt::QueuedConnection );
    connect( this, SIGNAL( startUserEventTimerSignal()), this, SLOT( startUserEventTimer()), Qt::QueuedConnection );
    // this one needs to be blocking, so that the handling in main thread is processed before
    // the thread emitting the signal continues
    connect( this, SIGNAL( processYieldSignal( bool, bool )), this, SLOT( processYield( bool, bool )),
        Qt::BlockingQueuedConnection );
}

KDEXLib::~KDEXLib()
{
    delete m_pApplication;

    // free the faked cmdline arguments no longer needed by KApplication
    for( int i = 0; i < m_nFakeCmdLineArgs; i++ )
    {
        free( m_pFreeCmdLineArgs[i] );
    }

    delete [] m_pFreeCmdLineArgs;
    delete [] m_pAppCmdLineArgs;
}

void KDEXLib::Init()
{
    SalI18N_InputMethod* pInputMethod = new SalI18N_InputMethod;
    pInputMethod->SetLocale();
    XrmInitialize();

    KAboutData *kAboutData = new KAboutData("OpenOffice.org",
            "kdelibs4",
            ki18n( "OpenOffice.org" ),
            "3.0.0",
            ki18n( "OpenOffice.org with KDE Native Widget Support." ),
            KAboutData::License_LGPL,
            ki18n( "Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009 Novell, Inc"),
            ki18n( "OpenOffice.org is an office suite.\n" ),
            "http://kde.openoffice.org/index.html",
            "dev@kde.openoffice.org" );

    kAboutData->addAuthor( ki18n( "Jan Holesovsky" ),
            ki18n( "Original author and maintainer of the KDE NWF." ),
            "kendy@artax.karlin.mff.cuni.cz",
            "http://artax.karlin.mff.cuni.cz/~kendy" );
    kAboutData->addAuthor( ki18n("Roman Shtylman"),
            ki18n( "Porting to KDE 4." ),
            "shtylman@gmail.com", "http://shtylman.com" );
    kAboutData->addAuthor( ki18n("Eric Bischoff"),
            ki18n( "Accessibility fixes, porting to KDE 4." ),
            "bischoff@kde.org" );

    //kAboutData->setProgramIconName("OpenOffice");

    m_nFakeCmdLineArgs = 1;
    USHORT nIdx;
    vos::OExtCommandLine aCommandLine;
    int nParams = aCommandLine.getCommandArgCount();
    rtl::OString aDisplay;
    rtl::OUString aParam, aBin;

    for ( nIdx = 0; nIdx < nParams; ++nIdx )
    {
        aCommandLine.getCommandArg( nIdx, aParam );
        if ( !m_pFreeCmdLineArgs && aParam.equalsAscii( "-display" ) && nIdx + 1 < nParams )
        {
            aCommandLine.getCommandArg( nIdx + 1, aParam );
            aDisplay = rtl::OUStringToOString( aParam, osl_getThreadTextEncoding() );

            m_nFakeCmdLineArgs = 3;
            m_pFreeCmdLineArgs = new char*[ m_nFakeCmdLineArgs ];
            m_pFreeCmdLineArgs[ 1 ] = strdup( "-display" );
            m_pFreeCmdLineArgs[ 2 ] = strdup( aDisplay.getStr() );
        }
    }
    if ( !m_pFreeCmdLineArgs )
        m_pFreeCmdLineArgs = new char*[ m_nFakeCmdLineArgs ];

    osl_getExecutableFile( &aParam.pData );
    osl_getSystemPathFromFileURL( aParam.pData, &aBin.pData );
    rtl::OString aExec = rtl::OUStringToOString( aBin, osl_getThreadTextEncoding() );
    m_pFreeCmdLineArgs[0] = strdup( aExec.getStr() );

    // make a copy of the string list for freeing it since
    // KApplication manipulates the pointers inside the argument vector
    // note: KApplication bad !
    m_pAppCmdLineArgs = new char*[ m_nFakeCmdLineArgs ];
    for( int i = 0; i < m_nFakeCmdLineArgs; i++ )
        m_pAppCmdLineArgs[i] = m_pFreeCmdLineArgs[i];

    KCmdLineArgs::init( m_nFakeCmdLineArgs, m_pAppCmdLineArgs, kAboutData );

    m_pApplication = new VCLKDEApplication();
    kapp->disableSessionManagement();
    KApplication::setQuitOnLastWindowClosed(false);
    setupEventLoop();

    Display* pDisp = QX11Info::display();
    SalKDEDisplay *pSalDisplay = new SalKDEDisplay(pDisp);

    pInputMethod->CreateMethod( pDisp );
    pInputMethod->AddConnectionWatch( pDisp, (void*)this );
    pSalDisplay->SetInputMethod( pInputMethod );

    PushXErrorLevel( true );
    SalI18N_KeyboardExtension *pKbdExtension = new SalI18N_KeyboardExtension( pDisp );
    XSync( pDisp, False );

    pKbdExtension->UseExtension( ! HasXErrorOccured() );
    PopXErrorLevel();

    pSalDisplay->SetKbdExtension( pKbdExtension );
}

// When we use Qt event loop, it can actually use its own event loop handling, or wrap
// the Glib event loop (the latter is the default is Qt is built with Glib support
// and $QT_NO_GLIB is not set). We mostly do not care which one it is, as QSocketNotifier's
// and QTimer's can handle it transparently, but it matters for the SolarMutex, which
// needs to be unlocked shortly before entering the main sleep (e.g. select()) and locked
// immediatelly after. So we need to know which event loop implementation is used and
// hook accordingly.
#ifdef GLIB_EVENT_LOOP_SUPPORT
static GPollFunc old_gpoll = NULL;
static gint gpoll_wrapper( GPollFD*, guint, gint );
#endif

void KDEXLib::setupEventLoop()
{
#ifdef GLIB_EVENT_LOOP_SUPPORT
// Glib is simple, it has g_main_context_set_poll_func() for wrapping the sleep call.
// The catch is that Qt has a bug that allows triggering timers even when they should
// not be, leading to crashes caused by QClipboard re-entering the event loop.
// (http://bugreports.qt.nokia.com/browse/QTBUG-14461), so enable only with Qt>=4.8.0,
// where it is(?) fixed.
    if( QAbstractEventDispatcher::instance()->inherits( "QEventDispatcherGlib" ))
    {
        eventLoopType = GlibEventLoop;
        old_gpoll = g_main_context_get_poll_func( NULL );
        g_main_context_set_poll_func( NULL, gpoll_wrapper );
        // set QClipboard to use event loop, otherwise the main thread will hold
        // SolarMutex locked, which will prevent the clipboard thread from answering
        m_pApplication->clipboard()->setProperty( "useEventLoopWhenWaiting", true );
        return;
    }
#endif
    // TODO handle also Qt's own event loop (requires fixing Qt too)
}

#ifdef GLIB_EVENT_LOOP_SUPPORT
gint gpoll_wrapper( GPollFD* ufds, guint nfds, gint timeout )
{
    YieldMutexReleaser release; // release YieldMutex (and re-acquire at block end)
    return old_gpoll( ufds, nfds, timeout );
}
#endif

void KDEXLib::Insert( int fd, void* data, YieldFunc pending, YieldFunc queued, YieldFunc handle )
{
    if( eventLoopType == LibreOfficeEventLoop )
        return SalXLib::Insert( fd, data, pending, queued, handle );
    SocketData sdata;
    sdata.data = data;
    sdata.pending = pending;
    sdata.queued = queued;
    sdata.handle = handle;
    // qApp as parent to make sure it uses the main thread event loop
    sdata.notifier = new QSocketNotifier( fd, QSocketNotifier::Read, qApp );
    connect( sdata.notifier, SIGNAL( activated( int )), this, SLOT( socketNotifierActivated( int )));
    socketData[ fd ] = sdata;
}

void KDEXLib::Remove( int fd )
{
    if( eventLoopType == LibreOfficeEventLoop )
        return SalXLib::Remove( fd );
    SocketData sdata = socketData.take( fd );// according to SalXLib::Remove() this should be safe
    delete sdata.notifier;
}

void KDEXLib::socketNotifierActivated( int fd )
{
    const SocketData& sdata = socketData[ fd ];
    sdata.handle( fd, sdata.data );
}

void KDEXLib::Yield( bool bWait, bool bHandleAllCurrentEvents )
{
    if( eventLoopType == LibreOfficeEventLoop )
        return SalXLib::Yield( bWait, bHandleAllCurrentEvents );
    // if we are the main thread (which is where the event processing is done),
    // good, just do it
    if( qApp->thread() == QThread::currentThread())
        processYield( bWait, bHandleAllCurrentEvents );
    else
    { // if this deadlocks, event processing needs to go into a separate thread
      // or some other solution needs to be found
        emit processYieldSignal( bWait, bHandleAllCurrentEvents );
    }
}

void KDEXLib::processYield( bool bWait, bool bHandleAllCurrentEvents )
{
    QAbstractEventDispatcher* dispatcher = QAbstractEventDispatcher::instance( qApp->thread());
    bool wasEvent = false;
    for( int cnt = bHandleAllCurrentEvents ? 100 : 1;
         cnt > 0;
         --cnt )
    {
        if( !dispatcher->processEvents( QEventLoop::AllEvents ))
            break;
        wasEvent = true;
    }
    if( bWait && !wasEvent )
        dispatcher->processEvents( QEventLoop::WaitForMoreEvents );
}

void KDEXLib::StartTimer( ULONG nMS )
{
    if( eventLoopType == LibreOfficeEventLoop )
        return SalXLib::StartTimer( nMS );
    timeoutTimer.setInterval( nMS );
    // QTimer's can be started only in their thread (main thread here)
    if( qApp->thread() == QThread::currentThread())
        startTimeoutTimer();
    else
        emit startTimeoutTimerSignal();
}

void KDEXLib::startTimeoutTimer()
{
    timeoutTimer.start();
}

void KDEXLib::StopTimer()
{
    if( eventLoopType == LibreOfficeEventLoop )
        return SalXLib::StopTimer();
    timeoutTimer.stop();
}

void KDEXLib::timeoutActivated()
{
    GetX11SalData()->Timeout();
    // QTimer is not single shot, so will be restarted immediatelly
}

void KDEXLib::Wakeup()
{
    if( eventLoopType == LibreOfficeEventLoop )
        return SalXLib::Wakeup();
    QAbstractEventDispatcher::instance( qApp->thread())->wakeUp(); // main thread event loop
}

void KDEXLib::PostUserEvent()
{
    if( eventLoopType == LibreOfficeEventLoop )
        return SalXLib::PostUserEvent();
    if( qApp->thread() == QThread::currentThread())
        startUserEventTimer();
    else
        emit startUserEventTimerSignal();
}

void KDEXLib::startUserEventTimer()
{
    userEventTimer.start( 0 );
}

void KDEXLib::userEventActivated()
{
    SalKDEDisplay::self()->EventGuardAcquire();
    if( SalKDEDisplay::self()->userEventsCount() <= 1 )
        userEventTimer.stop();
    SalKDEDisplay::self()->EventGuardRelease();
    SalKDEDisplay::self()->DispatchInternalEvent();
    // QTimer is not single shot, so will be restarted immediatelly
}

void KDEXLib::doStartup()
{
    if( ! m_bStartupDone )
    {
        KStartupInfo::appStarted();
        m_bStartupDone = true;
        #if OSL_DEBUG_LEVEL > 1
        fprintf( stderr, "called KStartupInfo::appStarted()\n" );
        #endif
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>disable KDE's crash handler<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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.
 *
 ************************************************************************/

#include "VCLKDEApplication.hxx"

#define Region QtXRegion

#include <kapplication.h>
#include <klocale.h>
#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <kstartupinfo.h>
#include <qabstracteventdispatcher.h>
#include <qclipboard.h>
#include <qthread.h>

#undef Region

#include "KDEXLib.hxx"

#include <i18n_im.hxx>
#include <i18n_xkb.hxx>

#include <saldata.hxx>
#include <vos/process.hxx>

#include "KDESalDisplay.hxx"

#if OSL_DEBUG_LEVEL > 1
#include <stdio.h>
#endif

#include <stdio.h>

#ifdef KDE_HAVE_GLIB
#if QT_VERSION >= QT_VERSION_CHECK( 4, 8, 0 )
#if 0 // wait until fixed in Qt
#define GLIB_EVENT_LOOP_SUPPORT
#endif
#endif
#endif

#ifdef GLIB_EVENT_LOOP_SUPPORT
#include <glib-2.0/glib.h>
#endif

KDEXLib::KDEXLib() :
    SalXLib(),  m_bStartupDone(false), m_pApplication(0),
    m_pFreeCmdLineArgs(0), m_pAppCmdLineArgs(0), m_nFakeCmdLineArgs( 0 ),
    eventLoopType( LibreOfficeEventLoop )
{
    // the timers created here means they belong to the main thread
    connect( &timeoutTimer, SIGNAL( timeout()), this, SLOT( timeoutActivated()));
    connect( &userEventTimer, SIGNAL( timeout()), this, SLOT( userEventActivated()));
    // QTimer::start() can be called only in its (here main) thread, so this will
    // forward between threads if needed
    connect( this, SIGNAL( startTimeoutTimerSignal()), this, SLOT( startTimeoutTimer()), Qt::QueuedConnection );
    connect( this, SIGNAL( startUserEventTimerSignal()), this, SLOT( startUserEventTimer()), Qt::QueuedConnection );
    // this one needs to be blocking, so that the handling in main thread is processed before
    // the thread emitting the signal continues
    connect( this, SIGNAL( processYieldSignal( bool, bool )), this, SLOT( processYield( bool, bool )),
        Qt::BlockingQueuedConnection );
}

KDEXLib::~KDEXLib()
{
    delete m_pApplication;

    // free the faked cmdline arguments no longer needed by KApplication
    for( int i = 0; i < m_nFakeCmdLineArgs; i++ )
    {
        free( m_pFreeCmdLineArgs[i] );
    }

    delete [] m_pFreeCmdLineArgs;
    delete [] m_pAppCmdLineArgs;
}

void KDEXLib::Init()
{
    SalI18N_InputMethod* pInputMethod = new SalI18N_InputMethod;
    pInputMethod->SetLocale();
    XrmInitialize();

    KAboutData *kAboutData = new KAboutData("OpenOffice.org",
            "kdelibs4",
            ki18n( "OpenOffice.org" ),
            "3.0.0",
            ki18n( "OpenOffice.org with KDE Native Widget Support." ),
            KAboutData::License_LGPL,
            ki18n( "Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008, 2009 Novell, Inc"),
            ki18n( "OpenOffice.org is an office suite.\n" ),
            "http://kde.openoffice.org/index.html",
            "dev@kde.openoffice.org" );

    kAboutData->addAuthor( ki18n( "Jan Holesovsky" ),
            ki18n( "Original author and maintainer of the KDE NWF." ),
            "kendy@artax.karlin.mff.cuni.cz",
            "http://artax.karlin.mff.cuni.cz/~kendy" );
    kAboutData->addAuthor( ki18n("Roman Shtylman"),
            ki18n( "Porting to KDE 4." ),
            "shtylman@gmail.com", "http://shtylman.com" );
    kAboutData->addAuthor( ki18n("Eric Bischoff"),
            ki18n( "Accessibility fixes, porting to KDE 4." ),
            "bischoff@kde.org" );

    //kAboutData->setProgramIconName("OpenOffice");

    m_nFakeCmdLineArgs = 2;
    USHORT nIdx;
    vos::OExtCommandLine aCommandLine;
    int nParams = aCommandLine.getCommandArgCount();
    rtl::OString aDisplay;
    rtl::OUString aParam, aBin;

    for ( nIdx = 0; nIdx < nParams; ++nIdx )
    {
        aCommandLine.getCommandArg( nIdx, aParam );
        if ( !m_pFreeCmdLineArgs && aParam.equalsAscii( "-display" ) && nIdx + 1 < nParams )
        {
            aCommandLine.getCommandArg( nIdx + 1, aParam );
            aDisplay = rtl::OUStringToOString( aParam, osl_getThreadTextEncoding() );

            m_pFreeCmdLineArgs = new char*[ m_nFakeCmdLineArgs + 2 ];
            m_pFreeCmdLineArgs[ m_nFakeCmdLineArgs + 0 ] = strdup( "-display" );
            m_pFreeCmdLineArgs[ m_nFakeCmdLineArgs + 1 ] = strdup( aDisplay.getStr() );
            m_nFakeCmdLineArgs += 2;
        }
    }
    if ( !m_pFreeCmdLineArgs )
        m_pFreeCmdLineArgs = new char*[ m_nFakeCmdLineArgs ];

    osl_getExecutableFile( &aParam.pData );
    osl_getSystemPathFromFileURL( aParam.pData, &aBin.pData );
    rtl::OString aExec = rtl::OUStringToOString( aBin, osl_getThreadTextEncoding() );
    m_pFreeCmdLineArgs[0] = strdup( aExec.getStr() );
    m_pFreeCmdLineArgs[1] = strdup( "--nocrashhandler" );

    // make a copy of the string list for freeing it since
    // KApplication manipulates the pointers inside the argument vector
    // note: KApplication bad !
    m_pAppCmdLineArgs = new char*[ m_nFakeCmdLineArgs ];
    for( int i = 0; i < m_nFakeCmdLineArgs; i++ )
        m_pAppCmdLineArgs[i] = m_pFreeCmdLineArgs[i];

    KCmdLineArgs::init( m_nFakeCmdLineArgs, m_pAppCmdLineArgs, kAboutData );

    m_pApplication = new VCLKDEApplication();
    kapp->disableSessionManagement();
    KApplication::setQuitOnLastWindowClosed(false);
    setupEventLoop();

    Display* pDisp = QX11Info::display();
    SalKDEDisplay *pSalDisplay = new SalKDEDisplay(pDisp);

    pInputMethod->CreateMethod( pDisp );
    pInputMethod->AddConnectionWatch( pDisp, (void*)this );
    pSalDisplay->SetInputMethod( pInputMethod );

    PushXErrorLevel( true );
    SalI18N_KeyboardExtension *pKbdExtension = new SalI18N_KeyboardExtension( pDisp );
    XSync( pDisp, False );

    pKbdExtension->UseExtension( ! HasXErrorOccured() );
    PopXErrorLevel();

    pSalDisplay->SetKbdExtension( pKbdExtension );
}

// When we use Qt event loop, it can actually use its own event loop handling, or wrap
// the Glib event loop (the latter is the default is Qt is built with Glib support
// and $QT_NO_GLIB is not set). We mostly do not care which one it is, as QSocketNotifier's
// and QTimer's can handle it transparently, but it matters for the SolarMutex, which
// needs to be unlocked shortly before entering the main sleep (e.g. select()) and locked
// immediatelly after. So we need to know which event loop implementation is used and
// hook accordingly.
#ifdef GLIB_EVENT_LOOP_SUPPORT
static GPollFunc old_gpoll = NULL;
static gint gpoll_wrapper( GPollFD*, guint, gint );
#endif

void KDEXLib::setupEventLoop()
{
#ifdef GLIB_EVENT_LOOP_SUPPORT
// Glib is simple, it has g_main_context_set_poll_func() for wrapping the sleep call.
// The catch is that Qt has a bug that allows triggering timers even when they should
// not be, leading to crashes caused by QClipboard re-entering the event loop.
// (http://bugreports.qt.nokia.com/browse/QTBUG-14461), so enable only with Qt>=4.8.0,
// where it is(?) fixed.
    if( QAbstractEventDispatcher::instance()->inherits( "QEventDispatcherGlib" ))
    {
        eventLoopType = GlibEventLoop;
        old_gpoll = g_main_context_get_poll_func( NULL );
        g_main_context_set_poll_func( NULL, gpoll_wrapper );
        // set QClipboard to use event loop, otherwise the main thread will hold
        // SolarMutex locked, which will prevent the clipboard thread from answering
        m_pApplication->clipboard()->setProperty( "useEventLoopWhenWaiting", true );
        return;
    }
#endif
    // TODO handle also Qt's own event loop (requires fixing Qt too)
}

#ifdef GLIB_EVENT_LOOP_SUPPORT
gint gpoll_wrapper( GPollFD* ufds, guint nfds, gint timeout )
{
    YieldMutexReleaser release; // release YieldMutex (and re-acquire at block end)
    return old_gpoll( ufds, nfds, timeout );
}
#endif

void KDEXLib::Insert( int fd, void* data, YieldFunc pending, YieldFunc queued, YieldFunc handle )
{
    if( eventLoopType == LibreOfficeEventLoop )
        return SalXLib::Insert( fd, data, pending, queued, handle );
    SocketData sdata;
    sdata.data = data;
    sdata.pending = pending;
    sdata.queued = queued;
    sdata.handle = handle;
    // qApp as parent to make sure it uses the main thread event loop
    sdata.notifier = new QSocketNotifier( fd, QSocketNotifier::Read, qApp );
    connect( sdata.notifier, SIGNAL( activated( int )), this, SLOT( socketNotifierActivated( int )));
    socketData[ fd ] = sdata;
}

void KDEXLib::Remove( int fd )
{
    if( eventLoopType == LibreOfficeEventLoop )
        return SalXLib::Remove( fd );
    SocketData sdata = socketData.take( fd );// according to SalXLib::Remove() this should be safe
    delete sdata.notifier;
}

void KDEXLib::socketNotifierActivated( int fd )
{
    const SocketData& sdata = socketData[ fd ];
    sdata.handle( fd, sdata.data );
}

void KDEXLib::Yield( bool bWait, bool bHandleAllCurrentEvents )
{
    if( eventLoopType == LibreOfficeEventLoop )
        return SalXLib::Yield( bWait, bHandleAllCurrentEvents );
    // if we are the main thread (which is where the event processing is done),
    // good, just do it
    if( qApp->thread() == QThread::currentThread())
        processYield( bWait, bHandleAllCurrentEvents );
    else
    { // if this deadlocks, event processing needs to go into a separate thread
      // or some other solution needs to be found
        emit processYieldSignal( bWait, bHandleAllCurrentEvents );
    }
}

void KDEXLib::processYield( bool bWait, bool bHandleAllCurrentEvents )
{
    QAbstractEventDispatcher* dispatcher = QAbstractEventDispatcher::instance( qApp->thread());
    bool wasEvent = false;
    for( int cnt = bHandleAllCurrentEvents ? 100 : 1;
         cnt > 0;
         --cnt )
    {
        if( !dispatcher->processEvents( QEventLoop::AllEvents ))
            break;
        wasEvent = true;
    }
    if( bWait && !wasEvent )
        dispatcher->processEvents( QEventLoop::WaitForMoreEvents );
}

void KDEXLib::StartTimer( ULONG nMS )
{
    if( eventLoopType == LibreOfficeEventLoop )
        return SalXLib::StartTimer( nMS );
    timeoutTimer.setInterval( nMS );
    // QTimer's can be started only in their thread (main thread here)
    if( qApp->thread() == QThread::currentThread())
        startTimeoutTimer();
    else
        emit startTimeoutTimerSignal();
}

void KDEXLib::startTimeoutTimer()
{
    timeoutTimer.start();
}

void KDEXLib::StopTimer()
{
    if( eventLoopType == LibreOfficeEventLoop )
        return SalXLib::StopTimer();
    timeoutTimer.stop();
}

void KDEXLib::timeoutActivated()
{
    GetX11SalData()->Timeout();
    // QTimer is not single shot, so will be restarted immediatelly
}

void KDEXLib::Wakeup()
{
    if( eventLoopType == LibreOfficeEventLoop )
        return SalXLib::Wakeup();
    QAbstractEventDispatcher::instance( qApp->thread())->wakeUp(); // main thread event loop
}

void KDEXLib::PostUserEvent()
{
    if( eventLoopType == LibreOfficeEventLoop )
        return SalXLib::PostUserEvent();
    if( qApp->thread() == QThread::currentThread())
        startUserEventTimer();
    else
        emit startUserEventTimerSignal();
}

void KDEXLib::startUserEventTimer()
{
    userEventTimer.start( 0 );
}

void KDEXLib::userEventActivated()
{
    SalKDEDisplay::self()->EventGuardAcquire();
    if( SalKDEDisplay::self()->userEventsCount() <= 1 )
        userEventTimer.stop();
    SalKDEDisplay::self()->EventGuardRelease();
    SalKDEDisplay::self()->DispatchInternalEvent();
    // QTimer is not single shot, so will be restarted immediatelly
}

void KDEXLib::doStartup()
{
    if( ! m_bStartupDone )
    {
        KStartupInfo::appStarted();
        m_bStartupDone = true;
        #if OSL_DEBUG_LEVEL > 1
        fprintf( stderr, "called KStartupInfo::appStarted()\n" );
        #endif
    }
}

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


<commit_before>#include "TChain.h"
#include "TTree.h"
#include "TH1D.h"
#include "TF1.h"
#include "TCanvas.h"
#include "TObjArray.h"

#include "AliAnalysisTask.h"
#include "AliAnalysisManager.h"

#include "AliESDEvent.h"
#include "AliESDInputHandler.h"

#include "AliT0CalibOffsetChannelsTask.h"

//#include "AliCDBMetaData.h"
//#include "AliCDBId.h"
//#include "AliCDBEntry.h"
//#include "AliCDBManager.h"
//#include "AliCDBStorage.h"

// Task should calculate channels offset
// Authors: Alla

ClassImp(AliT0CalibOffsetChannelsTask)
//________________________________________________________________________
AliT0CalibOffsetChannelsTask::AliT0CalibOffsetChannelsTask()
  : AliAnalysisTaskSE(),  fESD(0x0), fTzeroObject(0x0),
  fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0),
  fRunNumber(0)
{
  // Constructor

  for( int ip=0; ip < 24; ip++){
    fTimeDiff[ip] = 0;
    fCFD[ip]      = 0;
  }

  // Define input and output slots here
  // Input slot #0 works with a TChain
  //  DefineInput(0,  TChain::Class());
  //  DefineOutput(1, TObjArray::Class());
}

//________________________________________________________________________
AliT0CalibOffsetChannelsTask::AliT0CalibOffsetChannelsTask(const char *name)
  : AliAnalysisTaskSE(name), fESD(0), fTzeroObject(0),
  fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0),
  fRunNumber(0)
{
  // Constructor

  for( int ip=0; ip < 24; ip++){
    fTimeDiff[ip] = 0;
    fCFD[ip]      = 0;
  }

  // Define input and output slots here
  // Input slot #0 works with a TChain
  DefineInput(0, TChain::Class());
  DefineOutput(1, TObjArray::Class());
  // Output slot #0 id reserved by the base class for AOD
  // Output slot #1 writes into a TH1 container
}

//________________________________________________________________________
AliT0CalibOffsetChannelsTask::~AliT0CalibOffsetChannelsTask()
{
  // Destructor
  // printf("AliT0CalibOffsetChannels~AliT0CalibOffsetChannels() ");
  delete fTzeroORA;
  delete fTzeroORC;
  delete fResolution;
  delete fTzeroORAplusORC;
  for( Int_t  ip=0; ip < 24; ip++){
    delete fTimeDiff[ip];
    delete fCFD[ip];
  }

  delete fTzeroObject;
}

//________________________________________________________________________
/*void AliT0CalibOffsetChannelsTaskX::ConnectInputData(Option_t *) {
  //
  //
  //
  TTree* tree=dynamic_cast<TTree*>(GetInputData(0));
  if (!tree) {
    printf("ERROR: Could not read chain from input slot 0");
  }
  else {
    AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
    if (!esdH) {
      printf ("ERROR: Could not get ESDInputHandler");
    }
    else {
      fESD = esdH->GetEvent();
      printf ("*** CONNECTED NEW EVENT ****");
    }
  }
}
*/
//________________________________________________________________________
void AliT0CalibOffsetChannelsTask::UserCreateOutputObjects()
{
  // Create histograms
  for (Int_t i=0; i<24; i++) {
    fTimeDiff[i]   = new TH1F (Form("CFD1minCFD%d",i+1),"fTimeDiff",300, -300, 300);
    fCFD[i]        = new TH1F(Form("CFD%d",i+1),"CFD",500, 2000, 3000);//6000, 7000);
    // fCFD[i]        = new TH1F(Form("CFD%d",i+1),"CFD",500, -1000, 1000);//6000, 7000);
  }

  fTzeroORAplusORC = new TH1F("fTzeroORAplusORC","ORA+ORC /2",400,-2000,2000);   //or A plus or C
  fResolution      = new TH1F("fResolution","fResolution",400,-2000,2000);// or A minus or C spectrum
  fTzeroORA        = new TH1F("fTzeroORA","fTzeroORA",400,-2000,2000);// or A spectrum
  fTzeroORC        = new TH1F("fTzeroORC","fTzeroORC",400,-2000,2000);// or C spectrum

  fTzeroObject     = new TObjArray(0);
  fTzeroObject->SetOwner(kTRUE);

  for (Int_t i=0; i<24; i++)
    fTzeroObject->AddAtAndExpand(fTimeDiff[i],i);

  for (Int_t i=0; i<24; i++)
    fTzeroObject->AddAtAndExpand(fCFD[i],i+24); //24 - 48

  fTzeroObject->AddAtAndExpand(fTzeroORAplusORC, 48);
  fTzeroObject->AddAtAndExpand(fResolution, 49);
  fTzeroObject->AddAtAndExpand(fTzeroORA, 50);
  fTzeroObject->AddAtAndExpand(fTzeroORC, 51);

  PostData(1, fTzeroObject);
  // Called once
}

//________________________________________________________________________
void AliT0CalibOffsetChannelsTask::UserExec(Option_t *)
{
  // Main loop
  // Called for each event

  // Post output data.
  fESD = dynamic_cast<AliESDEvent*>(InputEvent());
  if (!fESD) {
    printf("ERROR: fESD not available\n");
    return;
  }

  fRunNumber =  fESD->GetRunNumber() ;

  const Double32_t* time = fESD->GetT0time();
  for (Int_t i=0; i<12; i++) {
     if( time[i] != 0 ){
     printf(" %i time %f \n", i, time[i] );
    fCFD[i]->Fill( time[i]);
      if(  time[0] != 0 )
	fTimeDiff[i]->Fill( time[i]-time[0]);
    }
  }
  for (Int_t i=12; i<24; i++) {
    if( time[i] != 0) {
      fCFD[i]->Fill( time[i]);
      if( time[12] != 0 )
	fTimeDiff[i]->Fill( time[i]-time[12]);
    }
  }
  const Double32_t* mean = fESD->GetT0TOF();
  Double32_t meanTOF = mean[0] ;
  Double32_t orA = mean[1] ;
  Double32_t orC = mean[2];

  if(orA<99999) fTzeroORA->Fill(orA);
  if(orC<99999) fTzeroORC->Fill(orC);
  if(orA<99999 && orC<99999) fResolution->Fill((orA-orC)/2.);
  if(orA<99999 && orC<99999) fTzeroORAplusORC->Fill(meanTOF);

  //  printf("%f   %f  %f\n",orA,orC,meanTOF);
  PostData(1, fTzeroObject);
}
 //________________________________________________________________________
void AliT0CalibOffsetChannelsTask::Terminate(Option_t *)
{

   // Called once at the end of the query
}

<commit_msg> printout removed<commit_after>#include "TChain.h"
#include "TTree.h"
#include "TH1D.h"
#include "TF1.h"
#include "TCanvas.h"
#include "TObjArray.h"

#include "AliAnalysisTask.h"
#include "AliAnalysisManager.h"

#include "AliESDEvent.h"
#include "AliESDInputHandler.h"

#include "AliT0CalibOffsetChannelsTask.h"

//#include "AliCDBMetaData.h"
//#include "AliCDBId.h"
//#include "AliCDBEntry.h"
//#include "AliCDBManager.h"
//#include "AliCDBStorage.h"

// Task should calculate channels offset
// Authors: Alla

ClassImp(AliT0CalibOffsetChannelsTask)
//________________________________________________________________________
AliT0CalibOffsetChannelsTask::AliT0CalibOffsetChannelsTask()
  : AliAnalysisTaskSE(),  fESD(0x0), fTzeroObject(0x0),
  fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0),
  fRunNumber(0)
{
  // Constructor

  for( int ip=0; ip < 24; ip++){
    fTimeDiff[ip] = 0;
    fCFD[ip]      = 0;
  }

  // Define input and output slots here
  // Input slot #0 works with a TChain
  //  DefineInput(0,  TChain::Class());
  //  DefineOutput(1, TObjArray::Class());
}

//________________________________________________________________________
AliT0CalibOffsetChannelsTask::AliT0CalibOffsetChannelsTask(const char *name)
  : AliAnalysisTaskSE(name), fESD(0), fTzeroObject(0),
  fTzeroORA(0x0), fTzeroORC(0x0), fResolution(0x0), fTzeroORAplusORC(0x0),
  fRunNumber(0)
{
  // Constructor

  for( int ip=0; ip < 24; ip++){
    fTimeDiff[ip] = 0;
    fCFD[ip]      = 0;
  }

  // Define input and output slots here
  // Input slot #0 works with a TChain
  DefineInput(0, TChain::Class());
  DefineOutput(1, TObjArray::Class());
  // Output slot #0 id reserved by the base class for AOD
  // Output slot #1 writes into a TH1 container
}

//________________________________________________________________________
AliT0CalibOffsetChannelsTask::~AliT0CalibOffsetChannelsTask()
{
  // Destructor
  // printf("AliT0CalibOffsetChannels~AliT0CalibOffsetChannels() ");
  delete fTzeroORA;
  delete fTzeroORC;
  delete fResolution;
  delete fTzeroORAplusORC;
  for( Int_t  ip=0; ip < 24; ip++){
    delete fTimeDiff[ip];
    delete fCFD[ip];
  }

  delete fTzeroObject;
}

//________________________________________________________________________
/*void AliT0CalibOffsetChannelsTaskX::ConnectInputData(Option_t *) {
  //
  //
  //
  TTree* tree=dynamic_cast<TTree*>(GetInputData(0));
  if (!tree) {
    printf("ERROR: Could not read chain from input slot 0");
  }
  else {
    AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
    if (!esdH) {
      printf ("ERROR: Could not get ESDInputHandler");
    }
    else {
      fESD = esdH->GetEvent();
      printf ("*** CONNECTED NEW EVENT ****");
    }
  }
}
*/
//________________________________________________________________________
void AliT0CalibOffsetChannelsTask::UserCreateOutputObjects()
{
  // Create histograms
  for (Int_t i=0; i<24; i++) {
    fTimeDiff[i]   = new TH1F (Form("CFD1minCFD%d",i+1),"fTimeDiff",300, -300, 300);
    fCFD[i]        = new TH1F(Form("CFD%d",i+1),"CFD",500, 2000, 3000);//6000, 7000);
    // fCFD[i]        = new TH1F(Form("CFD%d",i+1),"CFD",500, -1000, 1000);//6000, 7000);
  }

  fTzeroORAplusORC = new TH1F("fTzeroORAplusORC","ORA+ORC /2",400,-2000,2000);   //or A plus or C
  fResolution      = new TH1F("fResolution","fResolution",400,-2000,2000);// or A minus or C spectrum
  fTzeroORA        = new TH1F("fTzeroORA","fTzeroORA",400,-2000,2000);// or A spectrum
  fTzeroORC        = new TH1F("fTzeroORC","fTzeroORC",400,-2000,2000);// or C spectrum

  fTzeroObject     = new TObjArray(0);
  fTzeroObject->SetOwner(kTRUE);

  for (Int_t i=0; i<24; i++)
    fTzeroObject->AddAtAndExpand(fTimeDiff[i],i);

  for (Int_t i=0; i<24; i++)
    fTzeroObject->AddAtAndExpand(fCFD[i],i+24); //24 - 48

  fTzeroObject->AddAtAndExpand(fTzeroORAplusORC, 48);
  fTzeroObject->AddAtAndExpand(fResolution, 49);
  fTzeroObject->AddAtAndExpand(fTzeroORA, 50);
  fTzeroObject->AddAtAndExpand(fTzeroORC, 51);

  PostData(1, fTzeroObject);
  // Called once
}

//________________________________________________________________________
void AliT0CalibOffsetChannelsTask::UserExec(Option_t *)
{
  // Main loop
  // Called for each event

  // Post output data.
  fESD = dynamic_cast<AliESDEvent*>(InputEvent());
  if (!fESD) {
    printf("ERROR: fESD not available\n");
    return;
  }

  fRunNumber =  fESD->GetRunNumber() ;

  const Double32_t* time = fESD->GetT0time();
  for (Int_t i=0; i<12; i++) {
    if( time[i] != 0 ){
      fCFD[i]->Fill( time[i]);
      if(  time[0] != 0 )
	fTimeDiff[i]->Fill( time[i]-time[0]);
    }
  }
  for (Int_t i=12; i<24; i++) {
    if( time[i] != 0) {
      fCFD[i]->Fill( time[i]);
      if( time[12] != 0 )
	fTimeDiff[i]->Fill( time[i]-time[12]);
    }
  }
  const Double32_t* mean = fESD->GetT0TOF();
  Double32_t meanTOF = mean[0] ;
  Double32_t orA = mean[1] ;
  Double32_t orC = mean[2];

  if(orA<99999) fTzeroORA->Fill(orA);
  if(orC<99999) fTzeroORC->Fill(orC);
  if(orA<99999 && orC<99999) fResolution->Fill((orA-orC)/2.);
  if(orA<99999 && orC<99999) fTzeroORAplusORC->Fill(meanTOF);

  //  printf("%f   %f  %f\n",orA,orC,meanTOF);
  PostData(1, fTzeroObject);
}
 //________________________________________________________________________
void AliT0CalibOffsetChannelsTask::Terminate(Option_t *)
{

   // Called once at the end of the query
}

<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/bookmarks/recently_used_folders_combo_model.h"

#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/bookmarks/bookmark_model_factory.h"
#include "chrome/test/base/testing_profile.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/bookmarks/test/bookmark_test_helpers.h"
#include "content/public/test/test_browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/models/combobox_model_observer.h"

using bookmarks::BookmarkModel;
using bookmarks::BookmarkNode;
using content::BrowserThread;

// Implementation of ComboboxModelObserver that records when
// OnComboboxModelChanged() is invoked.
class TestComboboxModelObserver : public ui::ComboboxModelObserver {
 public:
  TestComboboxModelObserver() : changed_(false) {}
  ~TestComboboxModelObserver() override {}

  // Returns whether the model changed and clears changed state.
  bool GetAndClearChanged() {
    const bool changed = changed_;
    changed_ = false;
    return changed;
  }

  // ui::ComboboxModelObserver:
  void OnComboboxModelChanged(ui::ComboboxModel* model) override {
    changed_ = true;
  }

 private:
  bool changed_;

  DISALLOW_COPY_AND_ASSIGN(TestComboboxModelObserver);
};

class RecentlyUsedFoldersComboModelTest : public testing::Test {
 public:
  RecentlyUsedFoldersComboModelTest();

  void SetUp() override;
  void TearDown() override;

 protected:
  BookmarkModel* GetModel();

 private:
  base::MessageLoopForUI message_loop_;
  content::TestBrowserThread ui_thread_;
  content::TestBrowserThread file_thread_;
  scoped_ptr<TestingProfile> profile_;

  DISALLOW_COPY_AND_ASSIGN(RecentlyUsedFoldersComboModelTest);
};

RecentlyUsedFoldersComboModelTest::RecentlyUsedFoldersComboModelTest()
    : ui_thread_(BrowserThread::UI, &message_loop_),
      file_thread_(BrowserThread::FILE, &message_loop_) {
}

void RecentlyUsedFoldersComboModelTest::SetUp() {
  profile_.reset(new TestingProfile());
  profile_->CreateBookmarkModel(true);
  bookmarks::test::WaitForBookmarkModelToLoad(GetModel());
}

void RecentlyUsedFoldersComboModelTest::TearDown() {
  // Flush the message loop to make application verifiers happy.
  message_loop_.RunUntilIdle();
}

BookmarkModel* RecentlyUsedFoldersComboModelTest::GetModel() {
  return BookmarkModelFactory::GetForProfile(profile_.get());
}

// Verifies there are no duplicate nodes in the model.
TEST_F(RecentlyUsedFoldersComboModelTest, NoDups) {
  const BookmarkNode* new_node = GetModel()->AddURL(
      GetModel()->bookmark_bar_node(), 0, base::ASCIIToUTF16("a"),
      GURL("http://a"));
  RecentlyUsedFoldersComboModel model(GetModel(), new_node);
  std::set<base::string16> items;
  for (int i = 0; i < model.GetItemCount(); ++i) {
    if (!model.IsItemSeparatorAt(i))
      EXPECT_EQ(0u, items.count(model.GetItemAt(i)));
  }
}

// Verifies that observers are notified on changes.
TEST_F(RecentlyUsedFoldersComboModelTest, NotifyObserver) {
  const BookmarkNode* folder = GetModel()->AddFolder(
      GetModel()->bookmark_bar_node(), 0, base::ASCIIToUTF16("a"));
  const BookmarkNode* sub_folder = GetModel()->AddFolder(
      folder, 0, base::ASCIIToUTF16("b"));
  const BookmarkNode* new_node = GetModel()->AddURL(
      sub_folder, 0, base::ASCIIToUTF16("a"), GURL("http://a"));
  RecentlyUsedFoldersComboModel model(GetModel(), new_node);
  TestComboboxModelObserver observer;
  model.AddObserver(&observer);

  const int initial_count = model.GetItemCount();
  // Remove a folder, it should remove an item from the model too.
  GetModel()->Remove(sub_folder);
  EXPECT_TRUE(observer.GetAndClearChanged());
  const int updated_count = model.GetItemCount();
  EXPECT_LT(updated_count, initial_count);

  // Remove all, which should remove a folder too.
  GetModel()->RemoveAllUserBookmarks();
  EXPECT_TRUE(observer.GetAndClearChanged());
  EXPECT_LT(model.GetItemCount(), updated_count);

  model.RemoveObserver(&observer);
}
<commit_msg>chrome: Simplify the initialization of BookmarkModel in RecentlyUsedFoldersComboModelTest.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/bookmarks/recently_used_folders_combo_model.h"

#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/bookmarks/test/bookmark_test_helpers.h"
#include "components/bookmarks/test/test_bookmark_client.h"
#include "content/public/test/test_browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/models/combobox_model_observer.h"

using bookmarks::BookmarkModel;
using bookmarks::BookmarkNode;
using bookmarks::TestBookmarkClient;
using content::BrowserThread;

// Implementation of ComboboxModelObserver that records when
// OnComboboxModelChanged() is invoked.
class TestComboboxModelObserver : public ui::ComboboxModelObserver {
 public:
  TestComboboxModelObserver() : changed_(false) {}
  ~TestComboboxModelObserver() override {}

  // Returns whether the model changed and clears changed state.
  bool GetAndClearChanged() {
    const bool changed = changed_;
    changed_ = false;
    return changed;
  }

  // ui::ComboboxModelObserver:
  void OnComboboxModelChanged(ui::ComboboxModel* model) override {
    changed_ = true;
  }

 private:
  bool changed_;

  DISALLOW_COPY_AND_ASSIGN(TestComboboxModelObserver);
};

class RecentlyUsedFoldersComboModelTest : public testing::Test {
 public:
  RecentlyUsedFoldersComboModelTest();

 private:
  base::MessageLoopForUI message_loop_;
  content::TestBrowserThread ui_thread_;
  content::TestBrowserThread file_thread_;

  DISALLOW_COPY_AND_ASSIGN(RecentlyUsedFoldersComboModelTest);
};

RecentlyUsedFoldersComboModelTest::RecentlyUsedFoldersComboModelTest()
    : ui_thread_(BrowserThread::UI, &message_loop_),
      file_thread_(BrowserThread::FILE, &message_loop_) {
}

// Verifies there are no duplicate nodes in the model.
TEST_F(RecentlyUsedFoldersComboModelTest, NoDups) {
  TestBookmarkClient client;
  scoped_ptr<BookmarkModel> bookmark_model(client.CreateModel());
  const BookmarkNode* new_node = bookmark_model->AddURL(
      bookmark_model->bookmark_bar_node(), 0, base::ASCIIToUTF16("a"),
      GURL("http://a"));
  RecentlyUsedFoldersComboModel model(bookmark_model.get(), new_node);
  std::set<base::string16> items;
  for (int i = 0; i < model.GetItemCount(); ++i) {
    if (!model.IsItemSeparatorAt(i))
      EXPECT_EQ(0u, items.count(model.GetItemAt(i)));
  }
}

// Verifies that observers are notified on changes.
TEST_F(RecentlyUsedFoldersComboModelTest, NotifyObserver) {
  TestBookmarkClient client;
  scoped_ptr<BookmarkModel> bookmark_model(client.CreateModel());
  const BookmarkNode* folder = bookmark_model->AddFolder(
      bookmark_model->bookmark_bar_node(), 0, base::ASCIIToUTF16("a"));
  const BookmarkNode* sub_folder = bookmark_model->AddFolder(
      folder, 0, base::ASCIIToUTF16("b"));
  const BookmarkNode* new_node = bookmark_model->AddURL(
      sub_folder, 0, base::ASCIIToUTF16("a"), GURL("http://a"));
  RecentlyUsedFoldersComboModel model(bookmark_model.get(), new_node);
  TestComboboxModelObserver observer;
  model.AddObserver(&observer);

  const int initial_count = model.GetItemCount();
  // Remove a folder, it should remove an item from the model too.
  bookmark_model->Remove(sub_folder);
  EXPECT_TRUE(observer.GetAndClearChanged());
  const int updated_count = model.GetItemCount();
  EXPECT_LT(updated_count, initial_count);

  // Remove all, which should remove a folder too.
  bookmark_model->RemoveAllUserBookmarks();
  EXPECT_TRUE(observer.GetAndClearChanged());
  EXPECT_LT(model.GetItemCount(), updated_count);

  model.RemoveObserver(&observer);
}
<|endoftext|>


<commit_before>// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/feature_engagement/new_tab/new_tab_tracker.h"

namespace {

const int kTwoHoursInMinutes = 120;

}  // namespace

namespace feature_engagement {

NewTabTracker::NewTabTracker(Profile* profile,
                             SessionDurationUpdater* session_duration_updater)
    : FeatureTracker(profile, session_duration_updater) {}

NewTabTracker::~NewTabTracker() = default;

void NewTabTracker::OnNewTabOpened() {}

void NewTabTracker::OnSessionTimeMet() {}

int NewTabTracker::GetSessionTimeRequiredToShowInMinutes() {
  NOTREACHED();
  return kTwoHoursInMinutes;
}

}  // namespace feature_engagement
<commit_msg>Changes on the FeatureTracker constructor<commit_after>// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/feature_engagement/new_tab/new_tab_tracker.h"

#include "components/feature_engagement/public/feature_constants.h"

namespace {

const int kDefaultPromoShowTimeInHours = 2;

}  // namespace

namespace feature_engagement {

NewTabTracker::NewTabTracker(Profile* profile,
                             SessionDurationUpdater* session_duration_updater)
    : FeatureTracker(profile,
                     session_duration_updater,
                     &kIPHNewTabFeature,
                     base::TimeDelta::FromHours(kDefaultPromoShowTimeInHours)) {
}

NewTabTracker::~NewTabTracker() = default;

void NewTabTracker::OnNewTabOpened() {}

void NewTabTracker::OnSessionTimeMet() {}

}  // namespace feature_engagement
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: stgole.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 16:10:14 $
 *
 *  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_sot.hxx"

#include "rtl/string.h"
#include "rtl/string.h"
#include "stgole.hxx"
#include "storinfo.hxx"     // Read/WriteClipboardFormat()

#include <tools/debug.hxx>

///////////////////////// class StgInternalStream ////////////////////////

StgInternalStream::StgInternalStream
    ( BaseStorage& rStg, const String& rName, BOOL bWr )
{
    bIsWritable = TRUE;
    USHORT nMode = bWr
                 ? STREAM_WRITE | STREAM_SHARE_DENYALL
                 : STREAM_READ | STREAM_SHARE_DENYWRITE | STREAM_NOCREATE;
    pStrm = rStg.OpenStream( rName, nMode );

    // set the error code right here in the stream
    SetError( rStg.GetError() );
    SetBufferSize( 1024 );
}

StgInternalStream::~StgInternalStream()
{
    delete pStrm;
}

ULONG StgInternalStream::GetData( void* pData, ULONG nSize )
{
    if( pStrm )
    {
        nSize = pStrm->Read( pData, nSize );
        SetError( pStrm->GetError() );
        return nSize;
    }
    else
        return 0;
}

ULONG StgInternalStream::PutData( const void* pData, ULONG nSize )
{
    if( pStrm )
    {
        nSize = pStrm->Write( pData, nSize );
        SetError( pStrm->GetError() );
        return nSize;
    }
    else
        return 0;
}

ULONG StgInternalStream::SeekPos( ULONG nPos )
{
    return pStrm ? pStrm->Seek( nPos ) : 0;
}

void StgInternalStream::FlushData()
{
    if( pStrm )
    {
        pStrm->Flush();
        SetError( pStrm->GetError() );
    }
}

void StgInternalStream::Commit()
{
    Flush();
    pStrm->Commit();
}

///////////////////////// class StgCompObjStream /////////////////////////

StgCompObjStream::StgCompObjStream( BaseStorage& rStg, BOOL bWr )
            : StgInternalStream( rStg, String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "\1CompObj" ) ), bWr )
{
    memset( &aClsId, 0, sizeof( ClsId ) );
    nCbFormat = 0;
}

BOOL StgCompObjStream::Load()
{
    memset( &aClsId, 0, sizeof( ClsId ) );
    nCbFormat = 0;
    aUserName.Erase();
    if( GetError() != SVSTREAM_OK )
        return FALSE;
    Seek( 8L );     // skip the first part
    INT32 nMarker = 0;
    *this >> nMarker;
    if( nMarker == -1L )
    {
        *this >> aClsId;
        INT32 nLen1 = 0;
        *this >> nLen1;
        // higher bits are ignored
        nLen1 &= 0xFFFF;
        sal_Char* p = new sal_Char[ (USHORT) nLen1 ];
        if( Read( p, nLen1 ) == (ULONG) nLen1 )
        {
            aUserName = nLen1 ? String( p, gsl_getSystemTextEncoding() ) : String();
/*          // Now we can read the CB format
            INT32 nLen2 = 0;
            *this >> nLen2;
            if( nLen2 > 0 )
            {
                // get a string name
                if( nLen2 > nLen1 )
                    delete p, p = new char[ nLen2 ];
                if( Read( p, nLen2 ) == (ULONG) nLen2 && nLen2 )
                    nCbFormat = Exchange::RegisterFormatName( String( p ) );
                else
                    SetError( SVSTREAM_GENERALERROR );
            }
            else if( nLen2 == -1L )
                // Windows clipboard format
                *this >> nCbFormat;
            else
                // unknown identifier
                SetError( SVSTREAM_GENERALERROR );
*/
            nCbFormat = ReadClipboardFormat( *this );
        }
        else
            SetError( SVSTREAM_GENERALERROR );
        delete [] p;
    }
    return BOOL( GetError() == SVSTREAM_OK );
}

BOOL StgCompObjStream::Store()
{
    if( GetError() != SVSTREAM_OK )
        return FALSE;
    Seek( 0L );
    ByteString aAsciiUserName( aUserName, RTL_TEXTENCODING_ASCII_US );
    *this << (INT16) 1          // Version?
              << (INT16) -2                     // 0xFFFE = Byte Order Indicator
              << (INT32) 0x0A03         // Windows 3.10
              << (INT32) -1L
              << aClsId             // Class ID
              << (INT32) (aAsciiUserName.Len() + 1)
              << (const char *)aAsciiUserName.GetBuffer()
              << (UINT8) 0;             // string terminator
/*  // determine the clipboard format string
    String aCbFmt;
    if( nCbFormat > FORMAT_GDIMETAFILE )
    aCbFmt = Exchange::GetFormatName( nCbFormat );
    if( aCbFmt.Len() )
        *this << (INT32) aCbFmt.Len() + 1
               << (const char*) aCbFmt
               << (UINT8) 0;
    else if( nCbFormat )
         *this << (INT32) -1            // for Windows
                << (INT32) nCbFormat;
    else
        *this << (INT32) 0;         // no clipboard format
*/
    WriteClipboardFormat( *this, nCbFormat );
    *this << (INT32) 0;             // terminator
    Commit();
    return BOOL( GetError() == SVSTREAM_OK );
}

/////////////////////////// class StgOleStream ///////////////////////////

StgOleStream::StgOleStream( BaseStorage& rStg, BOOL bWr )
            : StgInternalStream( rStg, String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "\1Ole" ) ), bWr )
{
    nFlags = 0;
}

BOOL StgOleStream::Load()
{
    nFlags = 0;
    if( GetError() != SVSTREAM_OK )
        return FALSE;
    INT32 version = 0;
    Seek( 0L );
    *this >> version >> nFlags;
    return BOOL( GetError() == SVSTREAM_OK );
}

BOOL StgOleStream::Store()
{
    if( GetError() != SVSTREAM_OK )
        return FALSE;
    Seek( 0L );
    *this << (INT32) 0x02000001         // OLE version, format
          << (INT32) nFlags             // Object flags
          << (INT32) 0                  // Update Options
          << (INT32) 0                  // reserved
          << (INT32) 0;                 // Moniker 1
    Commit();
    return BOOL( GetError() == SVSTREAM_OK );
}

<commit_msg>INTEGRATION: CWS obo05 (1.8.4); FILE MERGED 2006/09/08 09:23:54 obo 1.8.4.2: pragma only for .net 2005 2006/07/03 15:43:10 obo 1.8.4.1: #i53611# disable warning C4342<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: stgole.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: vg $ $Date: 2006-09-25 13:35:41 $
 *
 *  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_sot.hxx"

#include "rtl/string.h"
#include "rtl/string.h"
#include "stgole.hxx"
#include "storinfo.hxx"     // Read/WriteClipboardFormat()

#include <tools/debug.hxx>
#if defined(_MSC_VER) && (_MSC_VER>=1400)
#pragma warning(disable: 4342)
#endif
///////////////////////// class StgInternalStream ////////////////////////

StgInternalStream::StgInternalStream
    ( BaseStorage& rStg, const String& rName, BOOL bWr )
{
    bIsWritable = TRUE;
    USHORT nMode = bWr
                 ? STREAM_WRITE | STREAM_SHARE_DENYALL
                 : STREAM_READ | STREAM_SHARE_DENYWRITE | STREAM_NOCREATE;
    pStrm = rStg.OpenStream( rName, nMode );

    // set the error code right here in the stream
    SetError( rStg.GetError() );
    SetBufferSize( 1024 );
}

StgInternalStream::~StgInternalStream()
{
    delete pStrm;
}

ULONG StgInternalStream::GetData( void* pData, ULONG nSize )
{
    if( pStrm )
    {
        nSize = pStrm->Read( pData, nSize );
        SetError( pStrm->GetError() );
        return nSize;
    }
    else
        return 0;
}

ULONG StgInternalStream::PutData( const void* pData, ULONG nSize )
{
    if( pStrm )
    {
        nSize = pStrm->Write( pData, nSize );
        SetError( pStrm->GetError() );
        return nSize;
    }
    else
        return 0;
}

ULONG StgInternalStream::SeekPos( ULONG nPos )
{
    return pStrm ? pStrm->Seek( nPos ) : 0;
}

void StgInternalStream::FlushData()
{
    if( pStrm )
    {
        pStrm->Flush();
        SetError( pStrm->GetError() );
    }
}

void StgInternalStream::Commit()
{
    Flush();
    pStrm->Commit();
}

///////////////////////// class StgCompObjStream /////////////////////////

StgCompObjStream::StgCompObjStream( BaseStorage& rStg, BOOL bWr )
            : StgInternalStream( rStg, String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "\1CompObj" ) ), bWr )
{
    memset( &aClsId, 0, sizeof( ClsId ) );
    nCbFormat = 0;
}

BOOL StgCompObjStream::Load()
{
    memset( &aClsId, 0, sizeof( ClsId ) );
    nCbFormat = 0;
    aUserName.Erase();
    if( GetError() != SVSTREAM_OK )
        return FALSE;
    Seek( 8L );     // skip the first part
    INT32 nMarker = 0;
    *this >> nMarker;
    if( nMarker == -1L )
    {
        *this >> aClsId;
        INT32 nLen1 = 0;
        *this >> nLen1;
        // higher bits are ignored
        nLen1 &= 0xFFFF;
        sal_Char* p = new sal_Char[ (USHORT) nLen1 ];
        if( Read( p, nLen1 ) == (ULONG) nLen1 )
        {
            aUserName = nLen1 ? String( p, gsl_getSystemTextEncoding() ) : String();
/*          // Now we can read the CB format
            INT32 nLen2 = 0;
            *this >> nLen2;
            if( nLen2 > 0 )
            {
                // get a string name
                if( nLen2 > nLen1 )
                    delete p, p = new char[ nLen2 ];
                if( Read( p, nLen2 ) == (ULONG) nLen2 && nLen2 )
                    nCbFormat = Exchange::RegisterFormatName( String( p ) );
                else
                    SetError( SVSTREAM_GENERALERROR );
            }
            else if( nLen2 == -1L )
                // Windows clipboard format
                *this >> nCbFormat;
            else
                // unknown identifier
                SetError( SVSTREAM_GENERALERROR );
*/
            nCbFormat = ReadClipboardFormat( *this );
        }
        else
            SetError( SVSTREAM_GENERALERROR );
        delete [] p;
    }
    return BOOL( GetError() == SVSTREAM_OK );
}

BOOL StgCompObjStream::Store()
{
    if( GetError() != SVSTREAM_OK )
        return FALSE;
    Seek( 0L );
    ByteString aAsciiUserName( aUserName, RTL_TEXTENCODING_ASCII_US );
    *this << (INT16) 1          // Version?
              << (INT16) -2                     // 0xFFFE = Byte Order Indicator
              << (INT32) 0x0A03         // Windows 3.10
              << (INT32) -1L
              << aClsId             // Class ID
              << (INT32) (aAsciiUserName.Len() + 1)
              << (const char *)aAsciiUserName.GetBuffer()
              << (UINT8) 0;             // string terminator
/*  // determine the clipboard format string
    String aCbFmt;
    if( nCbFormat > FORMAT_GDIMETAFILE )
    aCbFmt = Exchange::GetFormatName( nCbFormat );
    if( aCbFmt.Len() )
        *this << (INT32) aCbFmt.Len() + 1
               << (const char*) aCbFmt
               << (UINT8) 0;
    else if( nCbFormat )
         *this << (INT32) -1            // for Windows
                << (INT32) nCbFormat;
    else
        *this << (INT32) 0;         // no clipboard format
*/
    WriteClipboardFormat( *this, nCbFormat );
    *this << (INT32) 0;             // terminator
    Commit();
    return BOOL( GetError() == SVSTREAM_OK );
}

/////////////////////////// class StgOleStream ///////////////////////////

StgOleStream::StgOleStream( BaseStorage& rStg, BOOL bWr )
            : StgInternalStream( rStg, String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "\1Ole" ) ), bWr )
{
    nFlags = 0;
}

BOOL StgOleStream::Load()
{
    nFlags = 0;
    if( GetError() != SVSTREAM_OK )
        return FALSE;
    INT32 version = 0;
    Seek( 0L );
    *this >> version >> nFlags;
    return BOOL( GetError() == SVSTREAM_OK );
}

BOOL StgOleStream::Store()
{
    if( GetError() != SVSTREAM_OK )
        return FALSE;
    Seek( 0L );
    *this << (INT32) 0x02000001         // OLE version, format
          << (INT32) nFlags             // Object flags
          << (INT32) 0                  // Update Options
          << (INT32) 0                  // reserved
          << (INT32) 0;                 // Moniker 1
    Commit();
    return BOOL( GetError() == SVSTREAM_OK );
}

<|endoftext|>