<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: apearcfg.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-11-11 08:46:25 $
 *
 *  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  SVL_DLLIMPLEMENTATION
#undef  SVL_DLLIMPLEMENTATION
#endif
#define SVT_DLLIMPLEMENTATION

#include "apearcfg.hxx"

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include "com/sun/star/uno/Any.hxx"
#endif

#include "tools/debug.hxx"
#include "vcl/settings.hxx"
#include "vcl/svapp.hxx"
#include <rtl/logfile.hxx>

#define DEFAULT_LOOKNFEEL   0
#define DEFAULT_DRAGMODE    2
#define DEFAULT_SNAPMODE    0
#define DEFAULT_SCALEFACTOR 100
#define DEFAULT_AAMINHEIGHT 8

using namespace ::rtl;
using namespace ::com::sun::star::uno;

sal_Bool SvtTabAppearanceCfg::bInitialized = sal_False;

/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/
SvtTabAppearanceCfg::SvtTabAppearanceCfg()
    :ConfigItem(OUString::createFromAscii("Office.Common/View"))
    ,nLookNFeel         ( DEFAULT_LOOKNFEEL )
    ,nDragMode          ( DEFAULT_DRAGMODE )
    ,nSnapMode          ( DEFAULT_SNAPMODE )
    ,nMiddleMouse       ( MOUSE_MIDDLE_AUTOSCROLL )
    ,nScaleFactor ( DEFAULT_SCALEFACTOR )
    ,bMenuMouseFollow(FALSE)
    ,bSingleLineTabCtrl(FALSE)
    ,bColoredTabCtrl(FALSE)
#if defined( UNX ) || defined ( FS_PRIV_DEBUG )
    ,nAAMinPixelHeight  ( DEFAULT_AAMINHEIGHT )
    ,bFontAntialiasing  ( TRUE )
#endif
{
    RTL_LOGFILE_CONTEXT(aLog, "svtools (???) SvtTabAppearanceCfg::SvtTabAppearanceCfg()");

    const Sequence<OUString>& rNames = GetPropertyNames();
    Sequence<Any> aValues = GetProperties(rNames);
    const Any* pValues = aValues.getConstArray();
    DBG_ASSERT(aValues.getLength() == rNames.getLength(), "GetProperties failed")

    if(aValues.getLength() == rNames.getLength())
    {
        for(int nProp = 0; nProp < rNames.getLength(); ++nProp, ++pValues)
        {
            if(pValues->hasValue())
            {
                switch(nProp)
                {
                    case  0: *pValues >>= nScaleFactor; break; //"FontScaling",
                    case  1: *pValues >>= nLookNFeel; break;  //"LookAndFeel",
                    case  2: *pValues >>= nDragMode; break;   //"Window/Drag",
                    case  3: bMenuMouseFollow = *(sal_Bool*)pValues->getValue(); break; //"Menu/FollowMouse",
                    case  4: bSingleLineTabCtrl      = *(sal_Bool*)pValues->getValue(); break; //"Dialog/SingleLineTab",
                    case  5: bColoredTabCtrl = *(sal_Bool*)pValues->getValue(); break; //"Dialog/ColoredTab",
                    case  6: *pValues >>= nSnapMode; break; //"Dialog/MousePositioning",
                    case  7: *pValues >>= nMiddleMouse; break; //"Dialog/MiddleMouseButton",
#if defined( UNX ) || defined ( FS_PRIV_DEBUG )
                    case  8: bFontAntialiasing = *(sal_Bool*)pValues->getValue(); break;    // "FontAntialising/Enabled",
                    case  9: *pValues >>= nAAMinPixelHeight; break;                         // "FontAntialising/MinPixelHeight",
#endif
                }
            }
        }
    }
}
/* -----------------------------22.05.01 11:53--------------------------------

 ---------------------------------------------------------------------------*/
SvtTabAppearanceCfg::~SvtTabAppearanceCfg( )
{
}
/* -----------------------------22.05.01 11:54--------------------------------

 ---------------------------------------------------------------------------*/
const Sequence<OUString>& SvtTabAppearanceCfg::GetPropertyNames()
{
    static Sequence<OUString> aNames;
    if(!aNames.getLength())
    {
        static const sal_Char* aPropNames[] =
        {
             "FontScaling"                       //  0
            ,"LookAndFeel"                       //  1
            ,"Window/Drag"                       //  2
            ,"Menu/FollowMouse"                  //  3
            ,"Dialog/SingleLineTab"              //  4
            ,"Dialog/ColoredTab"                 //  5
            ,"Dialog/MousePositioning"           //  6
            ,"Dialog/MiddleMouseButton"          //  7
#if defined( UNX ) || defined ( FS_PRIV_DEBUG )
            ,"FontAntiAliasing/Enabled"         //  8
            ,"FontAntiAliasing/MinPixelHeight"  //  9
#endif
        };
        const int nCount = sizeof( aPropNames ) / sizeof( aPropNames[0] );
        aNames.realloc(nCount);

        const sal_Char** pAsciiNames = aPropNames;
        OUString* pNames = aNames.getArray();
        for(int i = 0; i < nCount; ++i, ++pNames, ++pAsciiNames)
            *pNames = OUString::createFromAscii( *pAsciiNames );
    }
    return aNames;
}
/* -----------------------------22.05.01 11:54--------------------------------

 ---------------------------------------------------------------------------*/
void  SvtTabAppearanceCfg::Commit()
{
    const Sequence<OUString>& rNames = GetPropertyNames();
    const OUString* pNames = rNames.getConstArray();
    Sequence<Any> aValues(rNames.getLength());
    Any* pValues = aValues.getArray();

    const Type& rType = ::getBooleanCppuType();
    for(int nProp = 0; nProp < rNames.getLength(); nProp++)
    {
        switch(nProp)
        {
            case  0: pValues[nProp] <<= nScaleFactor; break;            // "FontScaling",
            case  1: pValues[nProp] <<= nLookNFeel; break;              //"LookAndFeel",
            case  2: pValues[nProp] <<= nDragMode; break;               //"Window/Drag",
            case  3: pValues[nProp].setValue(&bMenuMouseFollow, rType); break; //"Menu/FollowMouse",
            case  4: pValues[nProp].setValue(&bSingleLineTabCtrl, rType); break; //"Dialog/SingleLineTab",
            case  5: pValues[nProp].setValue(&bColoredTabCtrl, rType); break; //"Dialog/ColoredTab",
            case  6: pValues[nProp] <<= nSnapMode; break;               //"Dialog/MousePositioning",
            case  7: pValues[nProp] <<= nMiddleMouse; break;               //"Dialog/MiddleMouseButton",
#if defined( UNX ) || defined ( FS_PRIV_DEBUG )
            case  8: pValues[nProp].setValue(&bFontAntialiasing, rType); break; // "FontAntialising/Enabled",
            case  9: pValues[nProp] <<= nAAMinPixelHeight; break;               // "FontAntialising/MinPixelHeight",
#endif
        }
    }
    PutProperties(rNames, aValues);
}
/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/

void SvtTabAppearanceCfg::SetLookNFeel ( USHORT nSet )
{
    nLookNFeel = nSet;
    SetModified();
}

/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/

void SvtTabAppearanceCfg::SetDragMode  ( USHORT nSet )
{
    nDragMode = nSet;
    SetModified();
}

/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/

void SvtTabAppearanceCfg::SetScaleFactor ( USHORT nSet )
{
    nScaleFactor = nSet;
    SetModified();
}

/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/

void SvtTabAppearanceCfg::SetSnapMode ( USHORT nSet )
{
    nSnapMode = nSet;
    SetModified();
}
/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/
void SvtTabAppearanceCfg::SetMiddleMouseButton ( USHORT nSet )
{
    nMiddleMouse = nSet;
    SetModified();
}
/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/

void SvtTabAppearanceCfg::SetApplicationDefaults ( Application* pApp )
{
    AllSettings   hAppSettings = pApp->GetSettings();
    StyleSettings hAppStyle    = hAppSettings.GetStyleSettings();

    // Look & Feel

    // SetStandard...Styles() resets the UseSystemUIFonts flag,
    // but we don't want to change it now, so save the flag before ...
    BOOL bUseSystemUIFonts = hAppStyle.GetUseSystemUIFonts();

    switch ( nLookNFeel )
    {
        case LookMotif:
            hAppStyle.SetStandardUnixStyles();  break;

        case LookOSTwo:
            hAppStyle.SetStandardOS2Styles();   break;

        case LookMacintosh:
            hAppStyle.SetStandardMacStyles();   break;

        case LookWindows:
            hAppStyle.SetStandardWinStyles();   break;

        case LookStardivision:
        default:
            hAppStyle.SetStandardStyles();      break;
    }

    // and set it here
    hAppStyle.SetUseSystemUIFonts( bUseSystemUIFonts );

    // Screen and ScreenFont Scaling

    hAppStyle.SetScreenZoom( nScaleFactor );
    hAppStyle.SetScreenFontZoom( nScaleFactor );

#if defined( UNX ) || defined ( FS_PRIV_DEBUG )
    // font anti aliasing
    hAppStyle.SetAntialiasingMinPixelHeight( nAAMinPixelHeight );
    hAppStyle.SetDisplayOptions( bFontAntialiasing ? 0 : DISPLAY_OPTION_AA_DISABLE );
#endif

    // Mouse Snap

    MouseSettings hMouseSettings = hAppSettings.GetMouseSettings();
    ULONG         nMouseOptions  = hMouseSettings.GetOptions();

    nMouseOptions &=  ! (MOUSE_OPTION_AUTOCENTERPOS | MOUSE_OPTION_AUTODEFBTNPOS);

    switch ( nSnapMode )
    {
    case SnapToButton:
        nMouseOptions |= MOUSE_OPTION_AUTODEFBTNPOS;
        break;
    case SnapToMiddle:
        nMouseOptions |= MOUSE_OPTION_AUTOCENTERPOS;
        break;
    case NoSnap:
    default:
        break;
    }
    hMouseSettings.SetOptions(nMouseOptions);
    hMouseSettings.SetMiddleButtonAction(nMiddleMouse);

    // Merge and Publish Settings

    ULONG nFollow = hMouseSettings.GetFollow();
    if(bMenuMouseFollow)
        nFollow |= MOUSE_FOLLOW_MENU;
    else
        nFollow &= ~MOUSE_FOLLOW_MENU;
    hMouseSettings.SetFollow( nFollow );
    sal_uInt16 nTabStyle = 0;
    if(bSingleLineTabCtrl)
        nTabStyle |= STYLE_TABCONTROL_SINGLELINE;

    if(bColoredTabCtrl)
        nTabStyle |= STYLE_TABCONTROL_COLOR;
    hAppStyle.SetTabControlStyle(nTabStyle);

    hAppSettings.SetMouseSettings( hMouseSettings );

    hAppSettings.SetStyleSettings( hAppStyle );
    pApp->MergeSystemSettings    ( hAppSettings );      // Allow system-settings to apply
    pApp->SystemSettingsChanging ( hAppSettings, NULL );// Allow overruling of system-settings
                                                        //is concerned with window drag

    pApp->SetSettings ( hAppSettings );
}

<commit_msg>INTEGRATION: CWS warnings01 (1.4.62); FILE MERGED 2006/01/27 16:43:20 sb 1.4.62.3: #i53898# Made code warning-free. 2006/01/25 19:38:11 sb 1.4.62.2: RESYNC: (1.4-1.5); FILE MERGED 2005/10/25 12:44:00 pl 1.4.62.1: #i55991# removed warnings for linux platform<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: apearcfg.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 20:41:34 $
 *
 *  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  SVL_DLLIMPLEMENTATION
#undef  SVL_DLLIMPLEMENTATION
#endif
#define SVT_DLLIMPLEMENTATION

#include "apearcfg.hxx"

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include "com/sun/star/uno/Any.hxx"
#endif

#include "tools/debug.hxx"
#include "vcl/settings.hxx"
#include "vcl/svapp.hxx"
#include <rtl/logfile.hxx>

#define DEFAULT_LOOKNFEEL   0
#define DEFAULT_DRAGMODE    2
#define DEFAULT_SNAPMODE    0
#define DEFAULT_SCALEFACTOR 100
#define DEFAULT_AAMINHEIGHT 8

using namespace ::rtl;
using namespace ::com::sun::star::uno;

sal_Bool SvtTabAppearanceCfg::bInitialized = sal_False;

/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/
SvtTabAppearanceCfg::SvtTabAppearanceCfg()
    :ConfigItem(OUString::createFromAscii("Office.Common/View"))
    ,nLookNFeel         ( DEFAULT_LOOKNFEEL )
    ,nDragMode          ( DEFAULT_DRAGMODE )
    ,nScaleFactor       ( DEFAULT_SCALEFACTOR )
    ,nSnapMode          ( DEFAULT_SNAPMODE )
    ,nMiddleMouse       ( MOUSE_MIDDLE_AUTOSCROLL )
#if defined( UNX ) || defined ( FS_PRIV_DEBUG )
    ,nAAMinPixelHeight  ( DEFAULT_AAMINHEIGHT )
#endif
    ,bMenuMouseFollow(FALSE)
    ,bSingleLineTabCtrl(FALSE)
    ,bColoredTabCtrl(FALSE)
#if defined( UNX ) || defined ( FS_PRIV_DEBUG )
    ,bFontAntialiasing  ( TRUE )
#endif
{
    RTL_LOGFILE_CONTEXT(aLog, "svtools SvtTabAppearanceCfg::SvtTabAppearanceCfg()");

    const Sequence<OUString>& rNames = GetPropertyNames();
    Sequence<Any> aValues = GetProperties(rNames);
    const Any* pValues = aValues.getConstArray();
    DBG_ASSERT(aValues.getLength() == rNames.getLength(), "GetProperties failed")

    if(aValues.getLength() == rNames.getLength())
    {
        for(int nProp = 0; nProp < rNames.getLength(); ++nProp, ++pValues)
        {
            if(pValues->hasValue())
            {
                switch(nProp)
                {
                    case  0: *pValues >>= nScaleFactor; break; //"FontScaling",
                    case  1: *pValues >>= nLookNFeel; break;  //"LookAndFeel",
                    case  2: *pValues >>= nDragMode; break;   //"Window/Drag",
                    case  3: bMenuMouseFollow = *(sal_Bool*)pValues->getValue(); break; //"Menu/FollowMouse",
                    case  4: bSingleLineTabCtrl      = *(sal_Bool*)pValues->getValue(); break; //"Dialog/SingleLineTab",
                    case  5: bColoredTabCtrl = *(sal_Bool*)pValues->getValue(); break; //"Dialog/ColoredTab",
                    case  6: *pValues >>= nSnapMode; break; //"Dialog/MousePositioning",
                    case  7: *pValues >>= nMiddleMouse; break; //"Dialog/MiddleMouseButton",
#if defined( UNX ) || defined ( FS_PRIV_DEBUG )
                    case  8: bFontAntialiasing = *(sal_Bool*)pValues->getValue(); break;    // "FontAntialising/Enabled",
                    case  9: *pValues >>= nAAMinPixelHeight; break;                         // "FontAntialising/MinPixelHeight",
#endif
                }
            }
        }
    }
}
/* -----------------------------22.05.01 11:53--------------------------------

 ---------------------------------------------------------------------------*/
SvtTabAppearanceCfg::~SvtTabAppearanceCfg( )
{
}
/* -----------------------------22.05.01 11:54--------------------------------

 ---------------------------------------------------------------------------*/
const Sequence<OUString>& SvtTabAppearanceCfg::GetPropertyNames()
{
    static Sequence<OUString> aNames;
    if(!aNames.getLength())
    {
        static const sal_Char* aPropNames[] =
        {
             "FontScaling"                       //  0
            ,"LookAndFeel"                       //  1
            ,"Window/Drag"                       //  2
            ,"Menu/FollowMouse"                  //  3
            ,"Dialog/SingleLineTab"              //  4
            ,"Dialog/ColoredTab"                 //  5
            ,"Dialog/MousePositioning"           //  6
            ,"Dialog/MiddleMouseButton"          //  7
#if defined( UNX ) || defined ( FS_PRIV_DEBUG )
            ,"FontAntiAliasing/Enabled"         //  8
            ,"FontAntiAliasing/MinPixelHeight"  //  9
#endif
        };
        const int nCount = sizeof( aPropNames ) / sizeof( aPropNames[0] );
        aNames.realloc(nCount);

        const sal_Char** pAsciiNames = aPropNames;
        OUString* pNames = aNames.getArray();
        for(int i = 0; i < nCount; ++i, ++pNames, ++pAsciiNames)
            *pNames = OUString::createFromAscii( *pAsciiNames );
    }
    return aNames;
}
/* -----------------------------22.05.01 11:54--------------------------------

 ---------------------------------------------------------------------------*/
void  SvtTabAppearanceCfg::Commit()
{
    const Sequence<OUString>& rNames = GetPropertyNames();
    Sequence<Any> aValues(rNames.getLength());
    Any* pValues = aValues.getArray();

    const Type& rType = ::getBooleanCppuType();
    for(int nProp = 0; nProp < rNames.getLength(); nProp++)
    {
        switch(nProp)
        {
            case  0: pValues[nProp] <<= nScaleFactor; break;            // "FontScaling",
            case  1: pValues[nProp] <<= nLookNFeel; break;              //"LookAndFeel",
            case  2: pValues[nProp] <<= nDragMode; break;               //"Window/Drag",
            case  3: pValues[nProp].setValue(&bMenuMouseFollow, rType); break; //"Menu/FollowMouse",
            case  4: pValues[nProp].setValue(&bSingleLineTabCtrl, rType); break; //"Dialog/SingleLineTab",
            case  5: pValues[nProp].setValue(&bColoredTabCtrl, rType); break; //"Dialog/ColoredTab",
            case  6: pValues[nProp] <<= nSnapMode; break;               //"Dialog/MousePositioning",
            case  7: pValues[nProp] <<= nMiddleMouse; break;               //"Dialog/MiddleMouseButton",
#if defined( UNX ) || defined ( FS_PRIV_DEBUG )
            case  8: pValues[nProp].setValue(&bFontAntialiasing, rType); break; // "FontAntialising/Enabled",
            case  9: pValues[nProp] <<= nAAMinPixelHeight; break;               // "FontAntialising/MinPixelHeight",
#endif
        }
    }
    PutProperties(rNames, aValues);
}
/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/

void SvtTabAppearanceCfg::SetLookNFeel ( USHORT nSet )
{
    nLookNFeel = nSet;
    SetModified();
}

/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/

void SvtTabAppearanceCfg::SetDragMode  ( USHORT nSet )
{
    nDragMode = nSet;
    SetModified();
}

/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/

void SvtTabAppearanceCfg::SetScaleFactor ( USHORT nSet )
{
    nScaleFactor = nSet;
    SetModified();
}

/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/

void SvtTabAppearanceCfg::SetSnapMode ( USHORT nSet )
{
    nSnapMode = nSet;
    SetModified();
}
/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/
void SvtTabAppearanceCfg::SetMiddleMouseButton ( USHORT nSet )
{
    nMiddleMouse = nSet;
    SetModified();
}
/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/

void SvtTabAppearanceCfg::SetApplicationDefaults ( Application* pApp )
{
    AllSettings   hAppSettings = pApp->GetSettings();
    StyleSettings hAppStyle    = hAppSettings.GetStyleSettings();

    // Look & Feel

    // SetStandard...Styles() resets the UseSystemUIFonts flag,
    // but we don't want to change it now, so save the flag before ...
    BOOL bUseSystemUIFonts = hAppStyle.GetUseSystemUIFonts();

    switch ( nLookNFeel )
    {
        case LookMotif:
            hAppStyle.SetStandardUnixStyles();  break;

        case LookOSTwo:
            hAppStyle.SetStandardOS2Styles();   break;

        case LookMacintosh:
            hAppStyle.SetStandardMacStyles();   break;

        case LookWindows:
            hAppStyle.SetStandardWinStyles();   break;

        case LookStardivision:
        default:
            hAppStyle.SetStandardStyles();      break;
    }

    // and set it here
    hAppStyle.SetUseSystemUIFonts( bUseSystemUIFonts );

    // Screen and ScreenFont Scaling

    hAppStyle.SetScreenZoom( nScaleFactor );
    hAppStyle.SetScreenFontZoom( nScaleFactor );

#if defined( UNX ) || defined ( FS_PRIV_DEBUG )
    // font anti aliasing
    hAppStyle.SetAntialiasingMinPixelHeight( nAAMinPixelHeight );
    hAppStyle.SetDisplayOptions( bFontAntialiasing ? 0 : DISPLAY_OPTION_AA_DISABLE );
#endif

    // Mouse Snap

    MouseSettings hMouseSettings = hAppSettings.GetMouseSettings();
    ULONG         nMouseOptions  = hMouseSettings.GetOptions();

    nMouseOptions &=  ! (MOUSE_OPTION_AUTOCENTERPOS | MOUSE_OPTION_AUTODEFBTNPOS);

    switch ( nSnapMode )
    {
    case SnapToButton:
        nMouseOptions |= MOUSE_OPTION_AUTODEFBTNPOS;
        break;
    case SnapToMiddle:
        nMouseOptions |= MOUSE_OPTION_AUTOCENTERPOS;
        break;
    case NoSnap:
    default:
        break;
    }
    hMouseSettings.SetOptions(nMouseOptions);
    hMouseSettings.SetMiddleButtonAction(nMiddleMouse);

    // Merge and Publish Settings

    ULONG nFollow = hMouseSettings.GetFollow();
    if(bMenuMouseFollow)
        nFollow |= MOUSE_FOLLOW_MENU;
    else
        nFollow &= ~MOUSE_FOLLOW_MENU;
    hMouseSettings.SetFollow( nFollow );
    sal_uInt16 nTabStyle = 0;
    if(bSingleLineTabCtrl)
        nTabStyle |= STYLE_TABCONTROL_SINGLELINE;

    if(bColoredTabCtrl)
        nTabStyle |= STYLE_TABCONTROL_COLOR;
    hAppStyle.SetTabControlStyle(nTabStyle);

    hAppSettings.SetMouseSettings( hMouseSettings );

    hAppSettings.SetStyleSettings( hAppStyle );
    pApp->MergeSystemSettings    ( hAppSettings );      // Allow system-settings to apply
    pApp->SystemSettingsChanging ( hAppSettings, NULL );// Allow overruling of system-settings
                                                        //is concerned with window drag

    pApp->SetSettings ( hAppSettings );
}

<|endoftext|>


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

#include <log4cxx/logger.h>
#include <apr.h>
#include <apr_time.h>
#include <iostream>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/stream.h>
#include <log4cxx/appender.h>
#include <sstream>
#include "nullappender.h"
#include <log4cxx/consoleappender.h>
#include <log4cxx/patternlayout.h>
#include <log4cxx/helpers/pool.h>
#include <log4cxx/xml/domconfigurator.h>
#include <log4cxx/stream.h>

using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::performance;
using namespace log4cxx::xml;

/**
 * Logs in a loop a number of times and measure the elapsed time.
 *
 * @author Ceki Gülcü
 */
class Loop {
  static int runLength;
  static LoggerPtr logger;
  typedef long (*loopFunc)(long,LoggerPtr&);
  static loopFunc loop;
public:

  static int main(std::vector<LogString>& args)  {
    LoggerPtr j(Logger::getLogger("org.apache.log4j.joran"));
    j->setAdditivity(false);
    j->setLevel(Level::WARN);
    AppenderPtr a(new ConsoleAppender());
    a->setLayout(new PatternLayout(LOG4CXX_STR("%d %level %c - %m%n")));
    a->setName(LOG4CXX_STR("console"));
    Pool p;
    a->activateOptions(p);
    j->addAppender(a);

    if (args.size() >= 2) {
      init(args);
    } else {
      usage("Wrong number of arguments.");
    }

    //memPrint();
    (*loop)(1000, logger);
    //memPrint();

    long res = (*loop)(runLength, logger);
    double average = (res * 1000.0) / runLength;
    std::cout <<
      "Loop completed in [" << res << "] milliseconds, or [" << average
      << "] microseconds per log.";

    //memPrint();
    return 1;
  }

  static void usage(const char* msg) {
    std::cout << msg << '\n';
    std::cout <<
      "Usage: performance runLength configFile [char wide stream wide-stream bad-stream bad-wide-stream]\n";
    std::cout << "\trunLength (integer) is the length of test loop.";
    std::cout << "\tconfigFile is an XML configuration file";

    exit(1);
  }

  static void memPrint() {
  }

  static void init(std::vector<LogString>& args) {
    std::basic_istringstream<logchar> is(args[0]);
    is >> runLength;
    DOMConfigurator::configure(args[1]);
    if (args.size() == 3) {
      if(args[2] == LOG4CXX_STR("char")) {
        loop = Loop::loopChar;
      } else if (args[2] == LOG4CXX_STR("wide")) {
        loop = Loop::loopWide;
      } else if (args[2] == LOG4CXX_STR("stream")) {
        loop = Loop::loopStream;
      } else if (args[2] == LOG4CXX_STR("wide-stream")) {
        loop = Loop::loopWideStream;
      } else if (args[2] == LOG4CXX_STR("bad-stream")) {
        loop = Loop::loopBadStream;
      } else if (args[2] == LOG4CXX_STR("bad-wide-stream")) {
        loop = Loop::loopBadWideStream;
      } else {
        usage("Unrecognized loop type.");
      }
    }
  }

  static long loopChar(long len, LoggerPtr& logger) {
    const char* msg = "Some fix message of medium length.";
    apr_time_t before = apr_time_now();
    for (int i = 0; i < len; i++) {
      LOG4CXX_DEBUG(logger, msg);
    }
    return (apr_time_now() - before) / 1000;
  }

  static long loopWide(long len, LoggerPtr& logger) {
    const wchar_t* msg = L"Some fix message of medium length.";
    apr_time_t before = apr_time_now();
    for (int i = 0; i < len; i++) {
      LOG4CXX_DEBUG(logger, msg);
    }
    return (apr_time_now() - before) / 1000;
  }

  static long loopStream(long len, LoggerPtr& logger) {
    const char* msg = "Some fix message of medium length.";
    apr_time_t before = apr_time_now();
    logstream ls(logger, Level::DEBUG);
    for (int i = 0; i < len; i++) {
      ls << msg << LOG4CXX_ENDMSG;
    }
    return (apr_time_now() - before) / 1000;
  }

  static long loopWideStream(long len, LoggerPtr& logger) {
    const wchar_t* msg = L"Some fix message of medium length.";
    apr_time_t before = apr_time_now();
    logstream ls(logger, Level::DEBUG);
    for (int i = 0; i < len; i++) {
      ls << msg << LOG4CXX_ENDMSG;
    }
    return (apr_time_now() - before) / 1000;
  }

  static long loopBadStream(long len, LoggerPtr& logger) {
    const char* msg = "Some fix message of medium length.";
    apr_time_t before = apr_time_now();
    for (int i = 0; i < len; i++) {
      logstream ls(logger, Level::DEBUG);
      ls << msg << LOG4CXX_ENDMSG;
    }
    return (apr_time_now() - before) / 1000;
  }

  static long loopBadWideStream(long len, LoggerPtr& logger) {
    const wchar_t* msg = L"Some fix message of medium length.";
    apr_time_t before = apr_time_now();
    for (int i = 0; i < len; i++) {
      logstream ls(logger, Level::DEBUG);
      ls << msg << LOG4CXX_ENDMSG;
    }
    return (apr_time_now() - before) / 1000;
  }

};

LoggerPtr Loop::logger(Logger::getLogger("org.apache.log4j.performance.Loop"));
int Loop::runLength = 0;
Loop::loopFunc Loop::loop = Loop::loopChar;

int main(int argc, const char* const argv[])
{
        apr_app_initialize(&argc, &argv, NULL);
        std::vector<LogString> args(argc - 1);
        for (int i = 1; i < argc; i++) {
           Transcoder::decode(argv[i], args[i - 1]);
        }
        return Loop::main(args);
}
<commit_msg>LOGCXX-10: Skip wide perf test if no wchar_t type<commit_after>/*
 * Copyright 2003-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <log4cxx/logger.h>
#include <apr.h>
#include <apr_time.h>
#include <iostream>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/stream.h>
#include <log4cxx/appender.h>
#include <sstream>
#include "nullappender.h"
#include <log4cxx/consoleappender.h>
#include <log4cxx/patternlayout.h>
#include <log4cxx/helpers/pool.h>
#include <log4cxx/xml/domconfigurator.h>
#include <log4cxx/stream.h>

using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::performance;
using namespace log4cxx::xml;

/**
 * Logs in a loop a number of times and measure the elapsed time.
 *
 * @author Ceki Gülcü
 */
class Loop {
  static int runLength;
  static LoggerPtr logger;
  typedef long (*loopFunc)(long,LoggerPtr&);
  static loopFunc loop;
public:

  static int main(std::vector<LogString>& args)  {
    LoggerPtr j(Logger::getLogger("org.apache.log4j.joran"));
    j->setAdditivity(false);
    j->setLevel(Level::WARN);
    AppenderPtr a(new ConsoleAppender());
    a->setLayout(new PatternLayout(LOG4CXX_STR("%d %level %c - %m%n")));
    a->setName(LOG4CXX_STR("console"));
    Pool p;
    a->activateOptions(p);
    j->addAppender(a);

    if (args.size() >= 2) {
      init(args);
    } else {
      usage("Wrong number of arguments.");
    }

    //memPrint();
    (*loop)(1000, logger);
    //memPrint();

    long res = (*loop)(runLength, logger);
    double average = (res * 1000.0) / runLength;
    std::cout <<
      "Loop completed in [" << res << "] milliseconds, or [" << average
      << "] microseconds per log.";

    //memPrint();
    return 1;
  }

  static void usage(const char* msg) {
    std::cout << msg << '\n';
    std::cout <<
      "Usage: performance runLength configFile [char wide stream wide-stream bad-stream bad-wide-stream]\n";
    std::cout << "\trunLength (integer) is the length of test loop.";
    std::cout << "\tconfigFile is an XML configuration file";

    exit(1);
  }

  static void memPrint() {
  }

  static void init(std::vector<LogString>& args) {
    std::basic_istringstream<logchar> is(args[0]);
    is >> runLength;
    DOMConfigurator::configure(args[1]);
    if (args.size() == 3) {
      if(args[2] == LOG4CXX_STR("char")) {
        loop = Loop::loopChar;
      } else if (args[2] == LOG4CXX_STR("stream")) {
        loop = Loop::loopStream;
      } else if (args[2] == LOG4CXX_STR("bad-stream")) {
        loop = Loop::loopBadStream;
#if LOG4CXX_HAS_WCHAR_T
       } else if (args[2] == LOG4CXX_STR("wide")) {
        loop = Loop::loopWide;
      } else if (args[2] == LOG4CXX_STR("wide-stream")) {
        loop = Loop::loopWideStream;
      } else if (args[2] == LOG4CXX_STR("bad-wide-stream")) {
        loop = Loop::loopBadWideStream;
#endif
      } else {
        usage("Unrecognized loop type.");
      }
    }
  }

  static long loopChar(long len, LoggerPtr& logger) {
    const char* msg = "Some fix message of medium length.";
    apr_time_t before = apr_time_now();
    for (int i = 0; i < len; i++) {
      LOG4CXX_DEBUG(logger, msg);
    }
    return (apr_time_now() - before) / 1000;
  }

 #if LOG4CXX_HAS_WCHAR_T
  static long loopWide(long len, LoggerPtr& logger) {
    const wchar_t* msg = L"Some fix message of medium length.";
    apr_time_t before = apr_time_now();
    for (int i = 0; i < len; i++) {
      LOG4CXX_DEBUG(logger, msg);
    }
    return (apr_time_now() - before) / 1000;
  }
#endif

  static long loopStream(long len, LoggerPtr& logger) {
    const char* msg = "Some fix message of medium length.";
    apr_time_t before = apr_time_now();
    logstream ls(logger, Level::DEBUG);
    for (int i = 0; i < len; i++) {
      ls << msg << LOG4CXX_ENDMSG;
    }
    return (apr_time_now() - before) / 1000;
  }

#if LOG4CXX_HAS_WCHAR_T
   static long loopWideStream(long len, LoggerPtr& logger) {
    const wchar_t* msg = L"Some fix message of medium length.";
    apr_time_t before = apr_time_now();
    logstream ls(logger, Level::DEBUG);
    for (int i = 0; i < len; i++) {
      ls << msg << LOG4CXX_ENDMSG;
    }
    return (apr_time_now() - before) / 1000;
  }
#endif

  static long loopBadStream(long len, LoggerPtr& logger) {
    const char* msg = "Some fix message of medium length.";
    apr_time_t before = apr_time_now();
    for (int i = 0; i < len; i++) {
      logstream ls(logger, Level::DEBUG);
      ls << msg << LOG4CXX_ENDMSG;
    }
    return (apr_time_now() - before) / 1000;
  }

#if LOG4CXX_HAS_WCHAR_T
   static long loopBadWideStream(long len, LoggerPtr& logger) {
    const wchar_t* msg = L"Some fix message of medium length.";
    apr_time_t before = apr_time_now();
    for (int i = 0; i < len; i++) {
      logstream ls(logger, Level::DEBUG);
      ls << msg << LOG4CXX_ENDMSG;
    }
    return (apr_time_now() - before) / 1000;
  }
#endif

};

LoggerPtr Loop::logger(Logger::getLogger("org.apache.log4j.performance.Loop"));
int Loop::runLength = 0;
Loop::loopFunc Loop::loop = Loop::loopChar;

int main(int argc, const char* const argv[])
{
        apr_app_initialize(&argc, &argv, NULL);
        std::vector<LogString> args(argc - 1);
        for (int i = 1; i < argc; i++) {
           Transcoder::decode(argv[i], args[i - 1]);
        }
        return Loop::main(args);
}
<|endoftext|>


<commit_before><commit_msg>remove whitespace<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: converter.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 15:28:22 $
 *
 *  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_svtools.hxx"
#ifndef _SV_CONVERTER_HXX_
#include "converter.hxx"
#endif

INT32 SvDbaseConverter::ConvertPrecisionToDbase(INT32 _nLen, INT32 _nScale)
{
    return _nScale ? _nLen +2 : _nLen +1;
}
//------------------------------------------------------------------------
INT32 SvDbaseConverter::ConvertPrecisionToOdbc(INT32 _nLen, INT32 _nScale)
{
    return _nScale ? _nLen -2 : _nLen -1;
}

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

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

INT32 SvDbaseConverter::ConvertPrecisionToDbase(INT32 _nLen, INT32 _nScale)
{
    return _nScale ? _nLen +2 : _nLen +1;
}
//------------------------------------------------------------------------
INT32 SvDbaseConverter::ConvertPrecisionToOdbc(INT32 _nLen, INT32 _nScale)
{
    return _nScale ? _nLen -2 : _nLen -1;
}

<|endoftext|>


<commit_before><commit_msg>tdf#91382 UI: Crash after visiting Sidebar Properties Page<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: accframe.hxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:48:05 $
 *
 *  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 _ACCFRAME_HXX
#define _ACCFRAME_HXX

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#include <list>
#ifndef _FRAME_HXX
#include <frame.hxx>
#endif
#ifndef _ACCFRMOBJ_HXX
#include <accfrmobj.hxx>
#endif

// Any method of this class must be called with an acquired solar mutex!

class SwAccessibleMap;

class SwAccessibleFrame
{
    SwRect maVisArea;
    const SwFrm *mpFrm;
    const sal_Bool mbIsInPagePreview;

    static sal_Int32 GetChildCount( const SwRect& rVisArea,
                                    const SwFrm *pFrm,
                                    sal_Bool bInPagePreview );
    static SwFrmOrObj GetChild( const SwRect& rVisArea,
                                  const SwFrm *pFrm,
                                  sal_Int32& rPos,
                                sal_Bool bInPagePreview);
    static sal_Bool GetChildIndex( const SwRect& rVisArea,
                                    const SwFrm *pFrm,
                                    const SwFrmOrObj& rChild,
                                    sal_Int32& rPos,
                                    sal_Bool bInPagePreview );
    static SwFrmOrObj GetChildAtPixel( const SwRect& rVisArea,
                                    const SwFrm *pFrm,
                                    const Point& rPos,
                                    sal_Bool bInPagePreview,
                                    const SwAccessibleMap *pMap );
    static void GetChildren( const SwRect& rVisArea, const SwFrm *pFrm,
                             ::std::list< SwFrmOrObj >& rChildren,
                             sal_Bool bInPagePreview );

    static void MergeLowerBounds( SwRect& rBounds,
                                  const SwRect& rVisArea,
                                  const SwFrm *pFrm,
                                  sal_Bool bInPagePreview );
protected:

    sal_Bool IsEditable( ViewShell *pVSh ) const;

    sal_Bool IsOpaque( ViewShell *pVSh ) const;

    inline sal_Bool IsShowing( const SwRect& rFrm ) const;
    inline sal_Bool IsShowing( const SwFrmOrObj& rFrmOrObj ) const;
    inline sal_Bool IsShowing() const;

    inline sal_Bool IsInPagePreview() const { return mbIsInPagePreview; }

    void ClearFrm() { mpFrm = 0; }

    SwAccessibleFrame( const SwRect& rVisArea,
                       const SwFrm *pFrm,
                       sal_Bool bIsPagePreview );
    virtual ~SwAccessibleFrame();

public:
    // Return the SwFrm this context is attached to.
    const SwFrm *GetFrm() const { return mpFrm; };

    static const SwFrm *GetParent( const SwFrmOrObj& rFrmOrObj,
                                   sal_Bool bInPagePreview );

protected:

    // Return the bounding box of the frame clipped to the vis area. If
    // no frame is specified, use this' frame.
    SwRect GetBounds( const SwFrm *pFrm=0 );

    // Return the upper that has a context attached. This might be
    // another one than the immediate upper.
    inline const SwFrm *GetParent() const;

    // Return the lower count or the nth lower, there the lowers have a
    // not be same one as the SwFrm's lowers
    inline sal_Int32 GetChildCount() const;
    inline SwFrmOrObj GetChild( sal_Int32 nPos ) const;
    inline sal_Int32 GetChildIndex( const SwFrmOrObj& rChild ) const;
    inline SwFrmOrObj GetChildAtPixel( const Point& rPos,
                                    const SwAccessibleMap *pMap ) const;
    inline void GetChildren( ::std::list< SwFrmOrObj >& rChildren ) const;

    inline void SetVisArea( const SwRect& rNewVisArea );
    const SwRect& GetVisArea() const { return maVisArea; }

    String GetFormattedPageNumber() const;
};

inline sal_Bool SwAccessibleFrame::IsShowing( const SwRect& rFrm ) const
{
    return rFrm.IsOver( maVisArea );
}

inline sal_Bool SwAccessibleFrame::IsShowing( const SwFrmOrObj& rFrmOrObj ) const
{
    return IsShowing( rFrmOrObj.GetBox() );
}

inline sal_Bool SwAccessibleFrame::IsShowing() const
{
    SwFrmOrObj aFrmOrObj( GetFrm() );
    return IsShowing( aFrmOrObj );
}

inline const SwFrm *SwAccessibleFrame::GetParent() const
{
    SwFrmOrObj aFrmOrObj( GetFrm() );
    return GetParent( aFrmOrObj, IsInPagePreview()  );
}

inline sal_Int32 SwAccessibleFrame::GetChildCount() const
{
    return GetChildCount( maVisArea, mpFrm, IsInPagePreview() );
}

inline SwFrmOrObj SwAccessibleFrame::GetChild( sal_Int32 nPos ) const
{
    return GetChild( maVisArea, mpFrm, nPos, IsInPagePreview() );
}

inline sal_Int32 SwAccessibleFrame::GetChildIndex( const SwFrmOrObj& rChild ) const
{
    sal_Int32 nPos = 0;
    return GetChildIndex( maVisArea, mpFrm, rChild, nPos, IsInPagePreview() ) ? nPos : -1L;
}

inline SwFrmOrObj SwAccessibleFrame::GetChildAtPixel( const Point& rPos,
                                    const SwAccessibleMap *pMap ) const
{
    return GetChildAtPixel( maVisArea, mpFrm, rPos, IsInPagePreview(), pMap );
}

inline void SwAccessibleFrame::GetChildren(
        ::std::list< SwFrmOrObj >& rChildren ) const
{
    GetChildren( maVisArea, mpFrm, rChildren, IsInPagePreview() );
}

inline void SwAccessibleFrame::SetVisArea( const SwRect& rNewVisArea )
{
    maVisArea = rNewVisArea;
}
#endif

<commit_msg>INTEGRATION: CWS swqbf49 (1.15.132); FILE MERGED 2005/12/05 09:32:21 od 1.15.132.1: #i27138# - minor re-factoring of code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: accframe.hxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: kz $ $Date: 2006-02-01 14:20:43 $
 *
 *  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 _ACCFRAME_HXX
#define _ACCFRAME_HXX

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#include <list>
#ifndef _FRAME_HXX
#include <frame.hxx>
#endif
#ifndef _ACCFRMOBJ_HXX
#include <accfrmobj.hxx>
#endif

// Any method of this class must be called with an acquired solar mutex!

class SwAccessibleMap;

class SwAccessibleFrame
{
    SwRect maVisArea;
    const SwFrm* mpFrm;
    const sal_Bool mbIsInPagePreview;

    static sal_Int32 GetChildCount( const SwRect& rVisArea,
                                    const SwFrm *pFrm,
                                    sal_Bool bInPagePreview );
    static SwFrmOrObj GetChild( const SwRect& rVisArea,
                                  const SwFrm *pFrm,
                                  sal_Int32& rPos,
                                sal_Bool bInPagePreview);
    static sal_Bool GetChildIndex( const SwRect& rVisArea,
                                    const SwFrm *pFrm,
                                    const SwFrmOrObj& rChild,
                                    sal_Int32& rPos,
                                    sal_Bool bInPagePreview );
    static SwFrmOrObj GetChildAtPixel( const SwRect& rVisArea,
                                    const SwFrm *pFrm,
                                    const Point& rPos,
                                    sal_Bool bInPagePreview,
                                    const SwAccessibleMap *pMap );
    static void GetChildren( const SwRect& rVisArea, const SwFrm *pFrm,
                             ::std::list< SwFrmOrObj >& rChildren,
                             sal_Bool bInPagePreview );

protected:

    sal_Bool IsEditable( ViewShell *pVSh ) const;

    sal_Bool IsOpaque( ViewShell *pVSh ) const;

    inline sal_Bool IsShowing( const SwRect& rFrm ) const;
    inline sal_Bool IsShowing( const SwFrmOrObj& rFrmOrObj ) const;
    inline sal_Bool IsShowing() const;

    inline sal_Bool IsInPagePreview() const
    {
        return mbIsInPagePreview;
    }

    inline void ClearFrm()
    {
        mpFrm = 0;
    }

    SwAccessibleFrame( const SwRect& rVisArea,
                       const SwFrm *pFrm,
                       sal_Bool bIsPagePreview );
    virtual ~SwAccessibleFrame();

public:
    // Return the SwFrm this context is attached to.
    const SwFrm *GetFrm() const { return mpFrm; };

    static const SwFrm *GetParent( const SwFrmOrObj& rFrmOrObj,
                                   sal_Bool bInPagePreview );

protected:

    // Return the bounding box of the frame clipped to the vis area. If
    // no frame is specified, use this' frame.
    SwRect GetBounds( const SwFrm *pFrm=0 );

    // Return the upper that has a context attached. This might be
    // another one than the immediate upper.
    inline const SwFrm *GetParent() const;

    // Return the lower count or the nth lower, there the lowers have a
    // not be same one as the SwFrm's lowers
    inline sal_Int32 GetChildCount() const;
    inline SwFrmOrObj GetChild( sal_Int32 nPos ) const;
    inline sal_Int32 GetChildIndex( const SwFrmOrObj& rChild ) const;
    inline SwFrmOrObj GetChildAtPixel( const Point& rPos,
                                    const SwAccessibleMap *pMap ) const;
    inline void GetChildren( ::std::list< SwFrmOrObj >& rChildren ) const;

    inline void SetVisArea( const SwRect& rNewVisArea )
    {
        maVisArea = rNewVisArea;
    }

    inline const SwRect& GetVisArea() const
    {
        return maVisArea;
    }

    String GetFormattedPageNumber() const;
};

inline sal_Bool SwAccessibleFrame::IsShowing( const SwRect& rFrm ) const
{
    return rFrm.IsOver( maVisArea );
}

inline sal_Bool SwAccessibleFrame::IsShowing( const SwFrmOrObj& rFrmOrObj ) const
{
    return IsShowing( rFrmOrObj.GetBox() );
}

inline sal_Bool SwAccessibleFrame::IsShowing() const
{
    SwFrmOrObj aFrmOrObj( GetFrm() );
    return IsShowing( aFrmOrObj );
}

inline const SwFrm *SwAccessibleFrame::GetParent() const
{
    SwFrmOrObj aFrmOrObj( GetFrm() );
    return GetParent( aFrmOrObj, IsInPagePreview()  );
}

inline sal_Int32 SwAccessibleFrame::GetChildCount() const
{
    return GetChildCount( maVisArea, mpFrm, IsInPagePreview() );
}

inline SwFrmOrObj SwAccessibleFrame::GetChild( sal_Int32 nPos ) const
{
    return GetChild( maVisArea, mpFrm, nPos, IsInPagePreview() );
}

inline sal_Int32 SwAccessibleFrame::GetChildIndex( const SwFrmOrObj& rChild ) const
{
    sal_Int32 nPos = 0;
    return GetChildIndex( maVisArea, mpFrm, rChild, nPos, IsInPagePreview() ) ? nPos : -1L;
}

inline SwFrmOrObj SwAccessibleFrame::GetChildAtPixel( const Point& rPos,
                                    const SwAccessibleMap *pMap ) const
{
    return GetChildAtPixel( maVisArea, mpFrm, rPos, IsInPagePreview(), pMap );
}

inline void SwAccessibleFrame::GetChildren( ::std::list< SwFrmOrObj >& rChildren ) const
{
    GetChildren( maVisArea, mpFrm, rChildren, IsInPagePreview() );
}
#endif

<|endoftext|>


<commit_before>#include "FilesystemManager.h"
#include "../btrfs/btrfsplugin/IBtrfsFactory.h"
#include "DocanyMount.h"
#include "../stringtools.h"
#include "../fsimageplugin/IFSImageFactory.h"
#include "../fsimageplugin/IVHDFile.h"
#include "../clouddrive/IClouddriveFactory.h"
#include "../common/miniz.h"
#include "../urbackupcommon/backup_url_parser.h"
#include "../urbackupcommon/os_functions.h"

extern IBtrfsFactory* btrfs_fak;
extern IFSImageFactory* image_fak;
extern IClouddriveFactory* clouddrive_fak;

std::mutex FilesystemManager::mutex;
std::map<std::string, IBackupFileSystem*> FilesystemManager::filesystems;

bool FilesystemManager::openFilesystemImage(const std::string& url, const std::string& url_params,
	const str_map& secret_params)
{
	std::lock_guard<std::mutex> lock(mutex);

	if (filesystems.find(url) != filesystems.end())
		return true;

	IFile* img = nullptr;

	IClouddriveFactory::CloudSettings settings;

	if (next(url, 0, "file://"))
	{
		std::string fpath = url.substr(7);
		std::string ext = findextension(fpath);
		if (ext == "img" || ext == "raw")
		{
			img = Server->openFile(fpath, MODE_RW);
		}
		else if (ext == "vhdx")
		{
			IVHDFile* vhdfile = image_fak->createVHDFile(fpath, false, 0,
				2 * 1024 * 1024, false, IFSImageFactory::ImageFormat_VHDX);

			if (vhdfile == nullptr || !vhdfile->isOpen())
				return false;

			img = vhdfile;
		}
	}
	else if (parse_backup_url(url, url_params, secret_params, settings) )
	{
		if (!FileExists(settings.cache_img_path))
		{
			Server->Log("Creating new cache file system", LL_INFO);

			int64 cache_size = 1LL * 1024 * 1024 * 1024;
			std::unique_ptr<IVHDFile> dst_vhdx(image_fak->createVHDFile(settings.cache_img_path + ".new", false, cache_size,
				2 * 1024 * 1024, true, IFSImageFactory::ImageFormat_VHDX));

			if (!dst_vhdx || !dst_vhdx->isOpen())
			{
				Server->Log("Could not open cache vhdx to crate at " + settings.cache_img_path, LL_ERROR);
				return false;
			}

			if (!btrfs_fak->formatVolume(dst_vhdx.get()))
			{
				Server->Log("Could not btrfs format cache volume", LL_ERROR);
				return false;
			}

			dst_vhdx.reset();

			if (!os_rename_file(settings.cache_img_path + ".new",
				settings.cache_img_path))
			{
				Server->Log("Error renaming " + settings.cache_img_path + ". " + os_last_error_str(), LL_ERROR);
				return false;
			}
		}

		IVHDFile* cachevhdx = image_fak->createVHDFile(settings.cache_img_path, false, 0,
			2 * 1024 * 1024, false, IFSImageFactory::ImageFormat_VHDX);

		if (cachevhdx == nullptr || !cachevhdx->isOpen())
		{
			Server->Log("Could not open cache vhdx at " + settings.cache_img_path, LL_ERROR);
			return false;
		}

		IBackupFileSystem* cachefs = btrfs_fak->openBtrfsImage(cachevhdx);
		if (cachefs == nullptr)
		{
			Server->Log("Could not open cache btrfs at " + settings.cache_img_path, LL_ERROR);
			return false;
		}

		settings.size = 20LL * 1024 * 1024 * 1024; //20GB

		img = clouddrive_fak->createCloudFile(cachefs, settings);
	}

	if (img == nullptr)
		return false;

	if (img->RealSize() == 0)
	{
		if (!btrfs_fak->formatVolume(img))
		{
			Server->Log("Could not btrfs format volume", LL_ERROR);
			return false;
		}
	}

	IBackupFileSystem* fs = btrfs_fak->openBtrfsImage(img);
	if (fs == nullptr)
		return false;

	clouddrive_fak->setTopFs(img, fs);

	filesystems[url] = fs;

	return true;
}

bool FilesystemManager::mountFileSystem(const std::string& url, const std::string& url_params,
	const str_map& secret_params, const std::string& mount_path)
{
	if (!openFilesystemImage(url, url_params, secret_params))
		return false;

	std::lock_guard<std::mutex> lock(mutex);

	if (filesystems.find(url) == filesystems.end())
	{
		return false;
	}

	IBackupFileSystem* fs = filesystems[url];

	std::thread dm([url, fs, mount_path]() {
		if (!dokany_mount(fs, mount_path))
		{
			Server->Log("Mounting fs " + url + " at \"" + mount_path + "\" failed", LL_ERROR);
		}
		});

	dm.detach();

	return true;
}

IBackupFileSystem* FilesystemManager::getFileSystem(const std::string& path)
{
	std::lock_guard<std::mutex> lock(mutex);

	auto it = filesystems.find(path);
	if (it == filesystems.end())
		return nullptr;

	return it->second;
}

void FilesystemManager::startupMountFileSystems()
{
	std::vector<SFile> facet_dirs = getFiles("urbackup");

	for (SFile& fdir : facet_dirs)
	{
		if (!fdir.isdir || !next(fdir.name, 0, "data_"))
			continue;

		int facet_id = watoi(getafter("data_", fdir.name));

		std::vector<SFile> settings_files = getFiles("urbackup/" + fdir.name);

		for (SFile& sfn : settings_files)
		{
			if (sfn.isdir ||
				(sfn.name != "settings.cfg" &&
					!next(sfn.name, 0, "settings_")))
				continue;

			std::string clientsubname;
			if (sfn.name != "settings.cfg")
			{
				clientsubname = getbetween("settings_", ".cfg", sfn.name);

				if (clientsubname.empty())
					continue;
			}

			std::string dest, dest_params, computername;
			str_map dest_secret_params;
			size_t max_backups = 1;
			std::string perm_uid;
			if (!ClientConnector::getBackupDest(clientsubname, facet_id, dest,
				dest_params, dest_secret_params, computername, max_backups, perm_uid))
				continue;

			std::string backups_mpath;

			if (facet_id != 1)
				backups_mpath += std::to_string(facet_id);

			if (!clientsubname.empty())
			{
				if (!backups_mpath.empty())
					backups_mpath += "_";

				backups_mpath += clientsubname;
			}

			backups_mpath = "backups" + backups_mpath;

			if (!os_directory_exists(backups_mpath)
				&& !os_create_dir(backups_mpath))
				continue;

			std::string fmpath = os_get_final_path(backups_mpath);

			mountFileSystem(dest, dest_params, dest_secret_params,
				fmpath);
		}
	}
}
<commit_msg>Add cachefs layer to handle temp files<commit_after>#include "FilesystemManager.h"
#include "../btrfs/btrfsplugin/IBtrfsFactory.h"
#include "DocanyMount.h"
#include "../stringtools.h"
#include "../fsimageplugin/IFSImageFactory.h"
#include "../fsimageplugin/IVHDFile.h"
#include "../clouddrive/IClouddriveFactory.h"
#include "../common/miniz.h"
#include "../urbackupcommon/backup_url_parser.h"
#include "../urbackupcommon/os_functions.h"
#include "ClientService.h"
#include <chrono>
#include <atomic>
using namespace std::chrono_literals;

extern IBtrfsFactory* btrfs_fak;
extern IFSImageFactory* image_fak;
extern IClouddriveFactory* clouddrive_fak;

std::mutex FilesystemManager::mutex;
std::map<std::string, IBackupFileSystem*> FilesystemManager::filesystems;

namespace
{
	class TmpFileHandlingFileSystem : public IBackupFileSystem
	{
		std::unique_ptr<IBackupFileSystem> fs;
		bool do_stop = false;
		std::mutex flush_mutex;
		std::condition_variable flush_cond;
		std::thread flush_thread;
		std::atomic<bool> dirty = false;
	public:

		TmpFileHandlingFileSystem(IBackupFileSystem* fs)
			: fs(fs)
		{
			flush_thread = std::thread([this]() {
				this->regular_sync();
				});
		}

		~TmpFileHandlingFileSystem()
		{
			{
				std::unique_lock<std::mutex> lock(flush_mutex);
				do_stop = true;
				flush_cond.notify_all();
			}

			flush_thread.join();
		}

		virtual bool hasError() override
		{
			return fs->hasError();
		}

		bool isTmpFile(const std::string& path)
		{
			return next(path, 0, "tmp://");
		}

		std::string tmpFileName(const std::string& path)
		{
			return path.substr(6);
		}

		virtual IFsFile* openFile(const std::string& path, int mode) override
		{
			if (isTmpFile(path))
				return Server->openFile(tmpFileName(path), mode);

			if(mode!=MODE_READ && mode!=MODE_READ_DEVICE &&
				mode!=MODE_READ_SEQUENTIAL)
				dirty = true;

			return fs->openFile(path, mode);
		}

		virtual bool reflinkFile(const std::string& source, const std::string& dest) override
		{
			dirty = true;
			return fs->reflinkFile(source, dest);
		}

		virtual bool createDir(const std::string& path) override
		{
			dirty = true;
			return fs->createDir(path);
		}

		virtual bool deleteFile(const std::string& path) override
		{
			if (isTmpFile(path))
				return Server->deleteFile(tmpFileName(path));

			dirty = true;

			return fs->deleteFile(path);
		}

		virtual int getFileType(const std::string& path) override
		{
			if (isTmpFile(path))
				return os_get_file_type(tmpFileName(path));

			return fs->getFileType(path);
		}

		virtual bool sync(const std::string& path) override
		{
			bool ret = fs->sync(path);
			if (ret)
				dirty = false;
			return ret;
		}

		virtual std::vector<SFile> listFiles(const std::string& path) override
		{
			return fs->listFiles(path);
		}

		virtual bool createSubvol(const std::string& path) override
		{
			dirty = true;
			return fs->createSubvol(path);
		}

		virtual bool createSnapshot(const std::string& src_path, const std::string& dest_path) override
		{
			dirty = true;
			return fs->createSnapshot(src_path, dest_path);
		}

		virtual bool deleteSubvol(const std::string& path) override
		{
			dirty = true;
			return fs->deleteSubvol(path);
		}

		virtual bool rename(const std::string& src_name, const std::string& dest_name) override
		{
			dirty = true;
			return fs->rename(src_name, dest_name);
		}

		virtual bool removeDirRecursive(const std::string& path) override
		{
			dirty = true;
			return fs->removeDirRecursive(path);
		}

		virtual bool directoryExists(const std::string& path) override
		{
			return fs->directoryExists(path);
		}

		virtual bool linkSymbolic(const std::string& target, const std::string& lname) override
		{
			return fs->linkSymbolic(target, lname);
		}

		virtual bool copyFile(const std::string& src, const std::string& dst, bool flush = false, std::string* error_str = nullptr) override
		{
			return fs->copyFile(src, dst, flush, error_str);
		}

		virtual int64 totalSpace() override
		{
			return fs->totalSpace();
		}

		virtual int64 freeSpace() override
		{
			return fs->freeSpace();
		}
		virtual int64 freeMetadataSpace() override
		{
			return fs->freeMetadataSpace();
		}
		virtual int64 unallocatedSpace() override
		{
			return fs->unallocatedSpace();
		}
		virtual bool forceAllocMetadata() override
		{
			return fs->forceAllocMetadata();
		}
		virtual bool balance(int usage, size_t limit, bool metadata, bool& enospc, size_t& relocated) override
		{
			return fs->balance(usage, limit, metadata, enospc, relocated);
		}

		virtual std::string fileSep() override
		{
			return fs->fileSep();
		}

		virtual std::string filePath(IFile* f) override
		{
			return fs->filePath(f);
		}

		virtual bool getXAttr(const std::string& path, const std::string& key, std::string& value) override
		{
			return fs->getXAttr(path, key, value);
		}
		virtual bool setXAttr(const std::string& path, const std::string& key, const std::string& val) override
		{
			dirty = true;
			return fs->setXAttr(path, key, val);
		}
		virtual std::string getName() override
		{
			return fs->getName();
		}
		virtual IFile* getBackingFile() override
		{
			return fs->getBackingFile();
		}
		virtual std::string lastError() override
		{
			return fs->lastError();
		}
		virtual std::vector<SChunk> getChunks() override
		{
			return fs->getChunks();
		}

		void regular_sync()
		{
			std::unique_lock<std::mutex> lock(flush_mutex);
			while (!do_stop)
			{
				flush_cond.wait_for(lock, 10s);

				lock.unlock();

				if(dirty.exchange(false, std::memory_order_release))
				{
					if (!fs->sync(std::string()))
						break;
				}

				lock.lock();
			}
		}
};
}

bool FilesystemManager::openFilesystemImage(const std::string& url, const std::string& url_params,
	const str_map& secret_params)
{
	std::lock_guard<std::mutex> lock(mutex);

	if (filesystems.find(url) != filesystems.end())
		return true;

	IFile* img = nullptr;

	IClouddriveFactory::CloudSettings settings;
	std::unique_ptr<TmpFileHandlingFileSystem> tmpcachefs;

	if (next(url, 0, "file://"))
	{
		std::string fpath = url.substr(7);
		std::string ext = findextension(fpath);
		if (ext == "img" || ext == "raw")
		{
			img = Server->openFile(fpath, MODE_RW);
		}
		else if (ext == "vhdx")
		{
			IVHDFile* vhdfile = image_fak->createVHDFile(fpath, false, 0,
				2 * 1024 * 1024, false, IFSImageFactory::ImageFormat_VHDX);

			if (vhdfile == nullptr || !vhdfile->isOpen())
				return false;

			img = vhdfile;
		}
	}
	else if (parse_backup_url(url, url_params, secret_params, settings) )
	{
		if (!FileExists(settings.cache_img_path))
		{
			Server->Log("Creating new cache file system", LL_INFO);

			int64 cache_size = 1LL * 1024 * 1024 * 1024;
			std::unique_ptr<IVHDFile> dst_vhdx(image_fak->createVHDFile(settings.cache_img_path + ".new", false, cache_size,
				2 * 1024 * 1024, true, IFSImageFactory::ImageFormat_VHDX));

			if (!dst_vhdx || !dst_vhdx->isOpen())
			{
				Server->Log("Could not open cache vhdx to crate at " + settings.cache_img_path, LL_ERROR);
				return false;
			}

			if (!btrfs_fak->formatVolume(dst_vhdx.get()))
			{
				Server->Log("Could not btrfs format cache volume", LL_ERROR);
				return false;
			}

			dst_vhdx.reset();

			if (!os_rename_file(settings.cache_img_path + ".new",
				settings.cache_img_path))
			{
				Server->Log("Error renaming " + settings.cache_img_path + ". " + os_last_error_str(), LL_ERROR);
				return false;
			}
		}

		IVHDFile* cachevhdx = image_fak->createVHDFile(settings.cache_img_path, false, 0,
			2 * 1024 * 1024, false, IFSImageFactory::ImageFormat_VHDX);

		if (cachevhdx == nullptr || !cachevhdx->isOpen())
		{
			Server->Log("Could not open cache vhdx at " + settings.cache_img_path, LL_ERROR);
			return false;
		}

		IBackupFileSystem* cachefs = btrfs_fak->openBtrfsImage(cachevhdx);
		if (cachefs == nullptr)
		{
			Server->Log("Could not open cache btrfs at " + settings.cache_img_path, LL_ERROR);
			return false;
		}

		settings.size = 20LL * 1024 * 1024 * 1024; //20GB

		tmpcachefs = std::make_unique<TmpFileHandlingFileSystem>(cachefs);

		img = clouddrive_fak->createCloudFile(tmpcachefs.get(), settings);
	}

	if (img == nullptr)
		return false;

	if (img->RealSize() == 0)
	{
		if (!btrfs_fak->formatVolume(img))
		{
			Server->Log("Could not btrfs format volume", LL_ERROR);
			return false;
		}
	}

	IBackupFileSystem* fs = btrfs_fak->openBtrfsImage(img);
	if (fs == nullptr)
		return false;

	clouddrive_fak->setTopFs(img, fs);

	tmpcachefs.release();

	filesystems[url] = fs;

	return true;
}

bool FilesystemManager::mountFileSystem(const std::string& url, const std::string& url_params,
	const str_map& secret_params, const std::string& mount_path)
{
	if (!openFilesystemImage(url, url_params, secret_params))
		return false;

	std::lock_guard<std::mutex> lock(mutex);

	if (filesystems.find(url) == filesystems.end())
	{
		return false;
	}

	IBackupFileSystem* fs = filesystems[url];

	std::thread dm([url, fs, mount_path]() {
		if (!dokany_mount(fs, mount_path))
		{
			Server->Log("Mounting fs " + url + " at \"" + mount_path + "\" failed", LL_ERROR);
		}
		});

	dm.detach();

	return true;
}

IBackupFileSystem* FilesystemManager::getFileSystem(const std::string& path)
{
	std::lock_guard<std::mutex> lock(mutex);

	auto it = filesystems.find(path);
	if (it == filesystems.end())
		return nullptr;

	return it->second;
}

void FilesystemManager::startupMountFileSystems()
{
	std::vector<SFile> facet_dirs = getFiles("urbackup");

	for (SFile& fdir : facet_dirs)
	{
		if (!fdir.isdir || !next(fdir.name, 0, "data_"))
			continue;

		int facet_id = watoi(getafter("data_", fdir.name));

		std::vector<SFile> settings_files = getFiles("urbackup/" + fdir.name);

		for (SFile& sfn : settings_files)
		{
			if (sfn.isdir ||
				(sfn.name != "settings.cfg" &&
					!next(sfn.name, 0, "settings_")))
				continue;

			std::string clientsubname;
			if (sfn.name != "settings.cfg")
			{
				clientsubname = getbetween("settings_", ".cfg", sfn.name);

				if (clientsubname.empty())
					continue;
			}

			std::string dest, dest_params, computername;
			str_map dest_secret_params;
			size_t max_backups = 1;
			std::string perm_uid;
			if (!ClientConnector::getBackupDest(clientsubname, facet_id, dest,
				dest_params, dest_secret_params, computername, max_backups, perm_uid))
				continue;

			std::string backups_mpath;

			if (facet_id != 1)
				backups_mpath += std::to_string(facet_id);

			if (!clientsubname.empty())
			{
				if (!backups_mpath.empty())
					backups_mpath += "_";

				backups_mpath += clientsubname;
			}

			backups_mpath = "backups" + backups_mpath;

			if (!os_directory_exists(backups_mpath)
				&& !os_create_dir(backups_mpath))
				continue;

			std::string fmpath = os_get_final_path(backups_mpath);

			mountFileSystem(dest, dest_params, dest_secret_params,
				fmpath);
		}
	}
}
<|endoftext|>


<commit_before>#include <iostream>
#include <chrono>
#include <wiringPi.h>

#include <boost/lockfree/spsc_queue.hpp>

#include "../parser.hpp"

#define PIN_READ 27
#define PARSER_WAIT 200

#define ONE_BIT_LENGTH 200
#define MIN_SIGNAL_LENGTH (ONE_BIT_LENGTH / 2)

typedef int64_t duration_t;

struct Interrupt {
  std::chrono::high_resolution_clock::time_point timestamp;
  unsigned long long int duration;
  duration_t value;
};

typedef Interrupt *interrupt_t;
typedef boost::lockfree::spsc_queue<interrupt_t, boost::lockfree::capacity<500>> interrupt_list_t;

/*
 * interrupt_list_t is threadsafe as long as only one thread reads and only one
 * thread writes.
 */

// interrupt_list_t where our interrupt thread writes and main thread reads
interrupt_list_t interrupts;
// interrupt_list_t where our interrupt thread reads and main thread writes
interrupt_list_t empty;

void handleInterrupt(void) {
  interrupt_t interrupt;

  if (empty.read_available()) {
    interrupt = empty.front();
    empty.pop();
  } else {
    interrupt = new Interrupt();
  }

  interrupt->value = (unsigned int) (1 - ::digitalRead(PIN_READ));
  interrupt->timestamp = std::chrono::high_resolution_clock::now();

  if (!interrupts.push(interrupt)) {
    delete interrupt;
  }
}

void parse(void) {
  doorman::parser_t parser;
  interrupt_t current, previous;

  previous = new Interrupt();
  previous->value = 2; // doesn't exist
  previous->timestamp = std::chrono::high_resolution_clock::now();
  previous->duration = 0;

  while (true) {
    while (interrupts.read_available()) {
      current = interrupts.front();
      interrupts.pop();

      current->duration = std::chrono::duration_cast<std::chrono::microseconds>(
        current->timestamp - previous->timestamp
      ).count();

      if (current->duration < MIN_SIGNAL_LENGTH
          || current->value == previous->value) {
        previous->duration += current->duration;

        empty.push(current);
        continue;
      }

      unsigned int count = (unsigned int) round((1.0f * previous->duration) / ONE_BIT_LENGTH);

      if (count > 5) {
        count = 5;
      }

      // std::cout << current->value << ' ' << current->duration << ' ' << count << '\n';

      while (count-- > 0) {
        if (parser.consume(previous->value)) {
          if (parser.is_ready()) {
            std::cout << '\n' << parser.bits[0] << parser.bits[1] << parser.bits[2] << parser.bits[2] <<
                parser.bits[4] << parser.bits[5] << parser.bits[6] << parser.bits[7] << parser.bits[8] << parser.bits[9] << parser.bits[10] << parser.bits[11] << std::endl;
            parser.reset();
          }
        } else {
          parser.reset();
        }
      }

      empty.push(previous);
      previous = current;
    }

    // std::cout << std::endl;

    ::delayMicroseconds(PARSER_WAIT);
  }
}

int main(int argc, char ** argv) {
  ::wiringPiSetupGpio();
  ::pinMode(PIN_READ, INPUT);

  doorman::init();

  ::wiringPiISR(PIN_READ, INT_EDGE_BOTH, &handleInterrupt);

  parse();
}
<commit_msg>remove old logging<commit_after>#include <iostream>
#include <chrono>
#include <wiringPi.h>

#include <boost/lockfree/spsc_queue.hpp>

#include "../parser.hpp"

#define PIN_READ 27
#define PARSER_WAIT 200

#define ONE_BIT_LENGTH 200
#define MIN_SIGNAL_LENGTH (ONE_BIT_LENGTH / 2)

typedef int64_t duration_t;

struct Interrupt {
  std::chrono::high_resolution_clock::time_point timestamp;
  unsigned long long int duration;
  duration_t value;
};

typedef Interrupt *interrupt_t;
typedef boost::lockfree::spsc_queue<interrupt_t, boost::lockfree::capacity<500>> interrupt_list_t;

/*
 * interrupt_list_t is threadsafe as long as only one thread reads and only one
 * thread writes.
 */

// interrupt_list_t where our interrupt thread writes and main thread reads
interrupt_list_t interrupts;
// interrupt_list_t where our interrupt thread reads and main thread writes
interrupt_list_t empty;

void handleInterrupt(void) {
  interrupt_t interrupt;

  if (empty.read_available()) {
    interrupt = empty.front();
    empty.pop();
  } else {
    interrupt = new Interrupt();
  }

  interrupt->value = (unsigned int) (1 - ::digitalRead(PIN_READ));
  interrupt->timestamp = std::chrono::high_resolution_clock::now();

  if (!interrupts.push(interrupt)) {
    delete interrupt;
  }
}

void parse(void) {
  doorman::parser_t parser;
  interrupt_t current, previous;

  previous = new Interrupt();
  previous->value = 2; // doesn't exist
  previous->timestamp = std::chrono::high_resolution_clock::now();
  previous->duration = 0;

  while (true) {
    while (interrupts.read_available()) {
      current = interrupts.front();
      interrupts.pop();

      current->duration = std::chrono::duration_cast<std::chrono::microseconds>(
        current->timestamp - previous->timestamp
      ).count();

      if (current->duration < MIN_SIGNAL_LENGTH
          || current->value == previous->value) {
        previous->duration += current->duration;

        empty.push(current);
        continue;
      }

      unsigned int count = (unsigned int) round((1.0f * previous->duration) / ONE_BIT_LENGTH);

      if (count > 5) {
        count = 5;
      }

      while (count-- > 0) {
        if (parser.consume(previous->value)) {
          if (parser.is_ready()) {
            std::cout << '\n' << parser.bits[0] << parser.bits[1] << parser.bits[2] << parser.bits[2] <<
                parser.bits[4] << parser.bits[5] << parser.bits[6] << parser.bits[7] << parser.bits[8] << parser.bits[9] << parser.bits[10] << parser.bits[11] << std::endl;
            parser.reset();
          }
        } else {
          parser.reset();
        }
      }

      empty.push(previous);
      previous = current;
    }

    ::delayMicroseconds(PARSER_WAIT);
  }
}

int main(int argc, char ** argv) {
  ::wiringPiSetupGpio();
  ::pinMode(PIN_READ, INPUT);

  doorman::init();

  ::wiringPiISR(PIN_READ, INT_EDGE_BOTH, &handleInterrupt);

  parse();
}
<|endoftext|>


<commit_before><commit_msg>VCL: Cleanup headers in outdev/nativecontrols.cxx<commit_after><|endoftext|>


<commit_before>#include "aquila/global.h"
#include "aquila/transform/FftFactory.h"
#include "aquila/tools/TextPlot.h"
#include <algorithm>
#include <functional>
#include <memory>

int main() {

	FILE *fp;

	const std::size_t = 64;
	// etc.

	Aquila::SignalSource cmic; // control
	Aquila::SignalSource mic0, mic1, mic2, mic3;

	// GET FILE STUFF
	cmic.SignalSource(/*double vector*/, /*sample frequency rate -- check Arduino */);
			//  ^ fp needed here.
	//

	auto fft = Aquila::FftFactory::getFft(SIZE);
		// scope resolution w/ Function? ^

	int inverse(double amp) {
		return amp * -1;
	}

	Aquila::SpectrumType cspec = fft->fft(cmic.toArray());

	// TWO WAYS (PICK ONE!)

	std::for_each(cspec.begin(), cspec.end(), &inverse); // inverse noise spectrum.
	// ^ way 1: "for_each"

	for (double amp : cspec) {
		amp *= -1; } // <Michael-approved.

	// ^ way 2: range-based for loop
	// (does this work?)

	// SpectrumType is a vector of double-vectors.
	// why?
	// run example and print contents of an ex
	// frequency spectrum.
	// is *= -1 the best way to apply an operation
	// to all elements of a vector?

<commit_msg>update!<commit_after>#include "aquila/global.h"
#include "aquila/transform/FftFactory.h"
#include "aquila/tools/TextPlot.h"
#include <algorithm>
#include <functional>
#include <memory>

int main() {

	FILE *fp;

	const std::size_t = 64;
	// etc.

	Aquila::SignalSource cmic; // control
	Aquila::SignalSource mic0, mic1, mic2, mic3;

	// GET FILE STUFF
	cmic.SignalSource(/*double vector*/, /*sample frequency rate -- check Arduino */);
			//  ^ fp needed here.
	//

	auto fft = Aquila::FftFactory::getFft(SIZE);
		// scope resolution w/ Function? ^

	//int inverse(double amp) {
	//	return amp * -1;
	//}

	Aquila::SpectrumType cspec = fft->fft(cmic.toArray());

	// TWO WAYS (PICK ONE!)
	//std::for_each(cspec.begin(), cspec.end(), &inverse); // inverse noise spectrum.
	// ^ way 1: "for_each"
	for (double amp : cspec) {
		amp *= -1; } // <Michael-approved.
	// ^ way 2: range-based for loop
	// (does this work?)

	// SpectrumType is a vector of double-vectors.
	// why?
	// run example and print contents of an ex
	// frequency spectrum.
	// is *= -1 the best way to apply an operation
	// to all elements of a vector?

<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <MScalableImage>
#include <MImageWidget>
#include <MLabel>
#include <MWidgetController>
#include <MWidgetView>
#include <MSeparator>

#include <QGraphicsGridLayout>
#include <QGraphicsLinearLayout>
#include <QGraphicsSceneEvent>

#include "mbubbleitem.h"
#include "mbubbleitemview.h"
#include "mbubbleitemview_p.h"
#include "mbubbleitembackground_p.h"

MBubbleItemViewPrivate::MBubbleItemViewPrivate()
        : avatar(0),
        speechBubble(0),
        timeStampLabel(0),
        messageComposition(0),
        separator(0),
        currentCentralWidget(0)
{
    layout = new QGraphicsGridLayout;
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);

    informationWidgetsLayout = new QGraphicsLinearLayout(Qt::Horizontal);
    informationWidgetsLayout->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
    informationWidgetsLayout->setContentsMargins(0, 0, 0, 0);
    informationWidgetsLayout->setSpacing(0);

    informationWidgetsSpacer = new QGraphicsWidget;
    informationWidgetsSpacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);

    innerLayout = new QGraphicsLinearLayout(Qt::Vertical);
    innerLayout->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
    innerLayout->setContentsMargins(0, 0, 0, 0);
    innerLayout->setSpacing(0);

    timeStampLabel = new MLabel();
    timeStampLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);

    messageComposition = new MLabel();
    messageComposition->setWordWrap(true);
    messageComposition->setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
    messageComposition->setAlignment(Qt::AlignLeft);
}

MBubbleItemViewPrivate::~MBubbleItemViewPrivate()
{
    clearLayout();
}

void MBubbleItemViewPrivate::initLayout()
{
    clearLayout();

    replaceAvatar();

    if (controller->messageType() == MBubbleItem::Incoming) {
        if (controller->avatar()) {
            layout->addItem(controller->avatar(), 0, 0);
            layout->addItem(speechBubble, 0, 1);
        } else {
            layout->addItem(speechBubble, 0, 0);
        }
    } else if(controller->messageType() == MBubbleItem::Outgoing) {
        layout->addItem(speechBubble, 0, 0);
        if (controller->avatar())
            layout->addItem(controller->avatar(), 0, 1);
    }

    updateInformationWidgetsLayout();

    innerLayout->addItem(messageComposition);
    innerLayout->addItem(informationWidgetsLayout);

    setupCentralWidget();

    controller->connect(speechBubble, SIGNAL(clicked()), controller, SIGNAL(bubbleClicked()));
}

void MBubbleItemViewPrivate::clearLayout()
{
    while (layout->count())
        layout->removeAt(0);
    while (innerLayout->count())
        innerLayout->removeAt(0);
}

void MBubbleItemViewPrivate::replaceAvatar()
{
    Q_Q(MBubbleItemView);

    if (avatar) {
        for (int i = 0; i < layout->count(); i ++) {
            if (layout->itemAt(i) == avatar)
                layout->removeAt(i);
        }
        avatar = 0;
    }

    if (controller->avatar()) {
        if (controller->avatar()->objectName().isEmpty())
            controller->avatar()->setObjectName(q->style()->avatarObjectName());
        if (controller->messageType() == MBubbleItem::Incoming) {
            layout->addItem(controller->avatar(), 0, 0);
            layout->addItem(speechBubble, 0, 1);
        }
        else
            layout->addItem(controller->avatar(), 0, 1);
        avatar = controller->avatar();
    }
}

void MBubbleItemViewPrivate::setupCentralWidget()
{
    Q_Q(MBubbleItemView);

    if (q->model()->centralWidget() &&
        q->model()->centralWidget() != currentCentralWidget) {
        separator = new MSeparator;
        separator->setOrientation(Qt::Horizontal);
        innerLayout->addItem(separator);

        currentCentralWidget = q->model()->centralWidget();
        innerLayout->addItem(currentCentralWidget);
    } else {
        if (separator) {
            innerLayout->removeItem(separator);
            delete separator;
            separator = 0;
        }

        if (currentCentralWidget) {
            innerLayout->removeItem(currentCentralWidget);
            currentCentralWidget = 0;
        }
    }
}

void MBubbleItemViewPrivate::clearInformationWidgetsLayout()
{
    for (int i = 0; i < informationWidgetsLayout->count(); i++)
        informationWidgetsLayout->removeAt(0);
}

void MBubbleItemViewPrivate::updateInformationWidgetsLayout()
{
    Q_Q(MBubbleItemView);

    clearInformationWidgetsLayout();

    foreach (QGraphicsWidget *widget, q->model()->informationWidgets()) {
        informationWidgetsLayout->addItem(widget);
        informationWidgetsLayout->setAlignment(widget, Qt::AlignVCenter | Qt::AlignRight);
    }

    informationWidgetsLayout->addItem(informationWidgetsSpacer);
    informationWidgetsLayout->addItem(timeStampLabel);
}

void MBubbleItemViewPrivate::applyStyle()
{
    refreshStyleMode();
}

void MBubbleItemView::setGeometry(const QRectF &rect)
{
    MWidgetView::setGeometry(rect);

    Q_D(MBubbleItemView);
    d->updateMessageComposition();
}

void MBubbleItemViewPrivate::refreshStyleMode()
{
    Q_Q(MBubbleItemView);
    if (controller->messageType() == MBubbleItem::Incoming)
        q->style().setModeDefault();
    else
        q->style().setModeOutgoing();

    if (speechBubble)
        speechBubble->setObjectName(q->style()->bubbleObjectName());

    if (timeStampLabel) {
        timeStampLabel->setFont(q->style()->timestampFont());
        timeStampLabel->setColor(q->style()->timestampTextColor());
    }

    if (messageComposition) {
        messageComposition->setFont(q->style()->font());
        messageComposition->setColor(q->style()->textColor());
    }

    controller->setContentsMargins(q->style()->marginLeft(),
                                   q->style()->marginTop(),
                                   q->style()->marginRight(),
                                   q->style()->marginBottom());
}

void MBubbleItemViewPrivate::updateMessageComposition()
{
    Q_Q(MBubbleItemView);

    QString senderName = q->model()->senderName();
    QFont boldFontForSendername( messageComposition->font() );
    boldFontForSendername.setBold(true);
    QFontMetrics fontMetrics(boldFontForSendername);

    if (fontMetrics.width(senderName) > messageComposition->size().width())
        senderName = fontMetrics.elidedText(senderName, Qt::ElideRight,
                                            messageComposition->size().width()
                                            - fontMetrics.size( Qt::TextSingleLine, "...:" ).width()
                                            );

    if (controller->messageType() == MBubbleItem::Incoming)
        messageComposition->setText( "" + senderName + ": " + q->model()->message());
    else if (controller->messageType() == MBubbleItem::Outgoing)
        messageComposition->setText(q->model()->message() + "");

}
MBubbleItemView::MBubbleItemView(MBubbleItem *controller)
    : MWidgetView(* new MBubbleItemViewPrivate, controller)
{
    Q_D(MBubbleItemView);
    d->controller = controller;
    controller->setLayout(d->layout);
}

MBubbleItemView::MBubbleItemView(MBubbleItemViewPrivate &dd, MBubbleItem *controller)
    : MWidgetView(dd, controller)
{
    Q_D(MBubbleItemView);
    d->controller = controller;
    controller->setLayout(d->layout);
}

MBubbleItemView::~MBubbleItemView()
{
}

void MBubbleItemView::applyStyle()
{
    MWidgetView::applyStyle();

    Q_D(MBubbleItemView);
    d->applyStyle();
}

void MBubbleItemView::updateData(const QList<const char *> &modifications)
{
    Q_D(MBubbleItemView);

    MWidgetView::updateData(modifications);

    const char *member;
    for (int i = 0; i < modifications.count(); i++) {
        member = modifications[i];
        if (member == MBubbleItemModel::Avatar) {
            d->replaceAvatar();
        } else if (member == MBubbleItemModel::SenderName) {
            d->updateMessageComposition();
        } else if (member == MBubbleItemModel::TimeStamp) {
            d->timeStampLabel->setText(model()->timeStamp());
        } else if (member == MBubbleItemModel::Message) {
            d->updateMessageComposition();
        } else if (member == MBubbleItemModel::CentralWidget) {
            d->setupCentralWidget();
        } else if (member == MBubbleItemModel::MessageType) {
            d->speechBubble->setMessageType(static_cast<MBubbleItem::MessageType>(model()->messageType()));
            d->updateMessageComposition();
            d->initLayout();
            d->refreshStyleMode();
        } else if (member == MBubbleItemModel::InformationWidgets) {
            d->updateInformationWidgetsLayout();
        }
    }
}

void MBubbleItemView::setupModel()
{
    Q_D(MBubbleItemView);

    MWidgetView::setupModel();

    d->timeStampLabel->setText(model()->timeStamp());

    connect(d->messageComposition, SIGNAL(linkActivated(QString)), d->controller, SIGNAL(linkActivated(QString)));

    d->speechBubble = new MBubbleItemBackground(d->controller);
    d->speechBubble->setMessageType(static_cast<MBubbleItem::MessageType>(model()->messageType()));
    d->speechBubble->setObjectName(style()->bubbleObjectName());
    d->speechBubble->setLayout(d->innerLayout);
    d->speechBubble->setMinimumSize(0,0); //The background must always be smaller than our current geometry

    d->initLayout();
    d->refreshStyleMode();
}

void MBubbleItemView::setSelected(bool selected)
{
    Q_UNUSED(selected);
}

void MBubbleItemView::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    Q_UNUSED(event);
}

void MBubbleItemView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    Q_UNUSED(event);
}

M_REGISTER_VIEW_NEW(MBubbleItemView, MBubbleItem)

<commit_msg>Fixes: NB#190989 - Tap opens two message boxes in Speech Bubble widget<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <MScalableImage>
#include <MImageWidget>
#include <MLabel>
#include <MWidgetController>
#include <MWidgetView>
#include <MSeparator>

#include <QGraphicsGridLayout>
#include <QGraphicsLinearLayout>
#include <QGraphicsSceneEvent>

#include "mbubbleitem.h"
#include "mbubbleitemview.h"
#include "mbubbleitemview_p.h"
#include "mbubbleitembackground_p.h"

MBubbleItemViewPrivate::MBubbleItemViewPrivate()
        : avatar(0),
        speechBubble(0),
        timeStampLabel(0),
        messageComposition(0),
        separator(0),
        currentCentralWidget(0)
{
    layout = new QGraphicsGridLayout;
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);

    informationWidgetsLayout = new QGraphicsLinearLayout(Qt::Horizontal);
    informationWidgetsLayout->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);
    informationWidgetsLayout->setContentsMargins(0, 0, 0, 0);
    informationWidgetsLayout->setSpacing(0);

    informationWidgetsSpacer = new QGraphicsWidget;
    informationWidgetsSpacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum);

    innerLayout = new QGraphicsLinearLayout(Qt::Vertical);
    innerLayout->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
    innerLayout->setContentsMargins(0, 0, 0, 0);
    innerLayout->setSpacing(0);

    timeStampLabel = new MLabel();
    timeStampLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);

    messageComposition = new MLabel();
    messageComposition->setWordWrap(true);
    messageComposition->setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
    messageComposition->setAlignment(Qt::AlignLeft);
}

MBubbleItemViewPrivate::~MBubbleItemViewPrivate()
{
    clearLayout();
}

void MBubbleItemViewPrivate::initLayout()
{
    clearLayout();

    replaceAvatar();

    if (controller->messageType() == MBubbleItem::Incoming) {
        if (controller->avatar()) {
            layout->addItem(controller->avatar(), 0, 0);
            layout->addItem(speechBubble, 0, 1);
        } else {
            layout->addItem(speechBubble, 0, 0);
        }
    } else if(controller->messageType() == MBubbleItem::Outgoing) {
        layout->addItem(speechBubble, 0, 0);
        if (controller->avatar())
            layout->addItem(controller->avatar(), 0, 1);
    }

    updateInformationWidgetsLayout();

    innerLayout->addItem(messageComposition);
    innerLayout->addItem(informationWidgetsLayout);

    setupCentralWidget();

    controller->connect(speechBubble, SIGNAL(clicked()), controller, SIGNAL(bubbleClicked()), Qt::UniqueConnection);
}

void MBubbleItemViewPrivate::clearLayout()
{
    while (layout->count())
        layout->removeAt(0);
    while (innerLayout->count())
        innerLayout->removeAt(0);
}

void MBubbleItemViewPrivate::replaceAvatar()
{
    Q_Q(MBubbleItemView);

    if (avatar) {
        for (int i = 0; i < layout->count(); i ++) {
            if (layout->itemAt(i) == avatar)
                layout->removeAt(i);
        }
        avatar = 0;
    }

    if (controller->avatar()) {
        if (controller->avatar()->objectName().isEmpty())
            controller->avatar()->setObjectName(q->style()->avatarObjectName());
        if (controller->messageType() == MBubbleItem::Incoming) {
            layout->addItem(controller->avatar(), 0, 0);
            layout->addItem(speechBubble, 0, 1);
        }
        else
            layout->addItem(controller->avatar(), 0, 1);
        avatar = controller->avatar();
    }
}

void MBubbleItemViewPrivate::setupCentralWidget()
{
    Q_Q(MBubbleItemView);

    if (q->model()->centralWidget() &&
        q->model()->centralWidget() != currentCentralWidget) {
        separator = new MSeparator;
        separator->setOrientation(Qt::Horizontal);
        innerLayout->addItem(separator);

        currentCentralWidget = q->model()->centralWidget();
        innerLayout->addItem(currentCentralWidget);
    } else {
        if (separator) {
            innerLayout->removeItem(separator);
            delete separator;
            separator = 0;
        }

        if (currentCentralWidget) {
            innerLayout->removeItem(currentCentralWidget);
            currentCentralWidget = 0;
        }
    }
}

void MBubbleItemViewPrivate::clearInformationWidgetsLayout()
{
    for (int i = 0; i < informationWidgetsLayout->count(); i++)
        informationWidgetsLayout->removeAt(0);
}

void MBubbleItemViewPrivate::updateInformationWidgetsLayout()
{
    Q_Q(MBubbleItemView);

    clearInformationWidgetsLayout();

    foreach (QGraphicsWidget *widget, q->model()->informationWidgets()) {
        informationWidgetsLayout->addItem(widget);
        informationWidgetsLayout->setAlignment(widget, Qt::AlignVCenter | Qt::AlignRight);
    }

    informationWidgetsLayout->addItem(informationWidgetsSpacer);
    informationWidgetsLayout->addItem(timeStampLabel);
}

void MBubbleItemViewPrivate::applyStyle()
{
    refreshStyleMode();
}

void MBubbleItemView::setGeometry(const QRectF &rect)
{
    MWidgetView::setGeometry(rect);

    Q_D(MBubbleItemView);
    d->updateMessageComposition();
}

void MBubbleItemViewPrivate::refreshStyleMode()
{
    Q_Q(MBubbleItemView);
    if (controller->messageType() == MBubbleItem::Incoming)
        q->style().setModeDefault();
    else
        q->style().setModeOutgoing();

    if (speechBubble)
        speechBubble->setObjectName(q->style()->bubbleObjectName());

    if (timeStampLabel) {
        timeStampLabel->setFont(q->style()->timestampFont());
        timeStampLabel->setColor(q->style()->timestampTextColor());
    }

    if (messageComposition) {
        messageComposition->setFont(q->style()->font());
        messageComposition->setColor(q->style()->textColor());
    }

    controller->setContentsMargins(q->style()->marginLeft(),
                                   q->style()->marginTop(),
                                   q->style()->marginRight(),
                                   q->style()->marginBottom());
}

void MBubbleItemViewPrivate::updateMessageComposition()
{
    Q_Q(MBubbleItemView);

    QString senderName = q->model()->senderName();
    QFont boldFontForSendername( messageComposition->font() );
    boldFontForSendername.setBold(true);
    QFontMetrics fontMetrics(boldFontForSendername);

    if (fontMetrics.width(senderName) > messageComposition->size().width())
        senderName = fontMetrics.elidedText(senderName, Qt::ElideRight,
                                            messageComposition->size().width()
                                            - fontMetrics.size( Qt::TextSingleLine, "...:" ).width()
                                            );

    if (controller->messageType() == MBubbleItem::Incoming)
        messageComposition->setText( "" + senderName + ": " + q->model()->message());
    else if (controller->messageType() == MBubbleItem::Outgoing)
        messageComposition->setText(q->model()->message() + "");

}
MBubbleItemView::MBubbleItemView(MBubbleItem *controller)
    : MWidgetView(* new MBubbleItemViewPrivate, controller)
{
    Q_D(MBubbleItemView);
    d->controller = controller;
    controller->setLayout(d->layout);
}

MBubbleItemView::MBubbleItemView(MBubbleItemViewPrivate &dd, MBubbleItem *controller)
    : MWidgetView(dd, controller)
{
    Q_D(MBubbleItemView);
    d->controller = controller;
    controller->setLayout(d->layout);
}

MBubbleItemView::~MBubbleItemView()
{
}

void MBubbleItemView::applyStyle()
{
    MWidgetView::applyStyle();

    Q_D(MBubbleItemView);
    d->applyStyle();
}

void MBubbleItemView::updateData(const QList<const char *> &modifications)
{
    Q_D(MBubbleItemView);

    MWidgetView::updateData(modifications);

    const char *member;
    for (int i = 0; i < modifications.count(); i++) {
        member = modifications[i];
        if (member == MBubbleItemModel::Avatar) {
            d->replaceAvatar();
        } else if (member == MBubbleItemModel::SenderName) {
            d->updateMessageComposition();
        } else if (member == MBubbleItemModel::TimeStamp) {
            d->timeStampLabel->setText(model()->timeStamp());
        } else if (member == MBubbleItemModel::Message) {
            d->updateMessageComposition();
        } else if (member == MBubbleItemModel::CentralWidget) {
            d->setupCentralWidget();
        } else if (member == MBubbleItemModel::MessageType) {
            d->speechBubble->setMessageType(static_cast<MBubbleItem::MessageType>(model()->messageType()));
            d->updateMessageComposition();
            d->initLayout();
            d->refreshStyleMode();
        } else if (member == MBubbleItemModel::InformationWidgets) {
            d->updateInformationWidgetsLayout();
        }
    }
}

void MBubbleItemView::setupModel()
{
    Q_D(MBubbleItemView);

    MWidgetView::setupModel();

    d->timeStampLabel->setText(model()->timeStamp());

    connect(d->messageComposition, SIGNAL(linkActivated(QString)), d->controller, SIGNAL(linkActivated(QString)));

    d->speechBubble = new MBubbleItemBackground(d->controller);
    d->speechBubble->setMessageType(static_cast<MBubbleItem::MessageType>(model()->messageType()));
    d->speechBubble->setObjectName(style()->bubbleObjectName());
    d->speechBubble->setLayout(d->innerLayout);
    d->speechBubble->setMinimumSize(0,0); //The background must always be smaller than our current geometry

    d->initLayout();
    d->refreshStyleMode();
}

void MBubbleItemView::setSelected(bool selected)
{
    Q_UNUSED(selected);
}

void MBubbleItemView::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    Q_UNUSED(event);
}

void MBubbleItemView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    Q_UNUSED(event);
}

M_REGISTER_VIEW_NEW(MBubbleItemView, MBubbleItem)

<|endoftext|>