<commit_before>/*
    This file is part of libkpimexchange.
    Copyright (c) 2002 Tobias Koenig <tokoe@kde.org>
    Copyright (c) 2002 Jan-Pascal van Best <janpascal@vanbest.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include <qlabel.h>
#include <qlayout.h>

#include <klocale.h>
#include <kdebug.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>

#include "exchangeaccount.h"
#include "resourceexchangeconfig.h"
#include "resourceexchange.h"

using namespace KCal;

ResourceExchangeConfig::ResourceExchangeConfig( QWidget* parent,  const char* name )
    : KRES::ResourceConfigWidget( parent, name )
{
  resize( 245, 115 );
  QGridLayout *mainLayout = new QGridLayout( this, 7, 3 );

  QLabel *label = new QLabel( i18n( "Host:" ), this );
  mHostEdit = new KLineEdit( this );
  mainLayout->addWidget( label, 1, 0 );
  mainLayout->addWidget( mHostEdit, 1, 1 );

  label = new QLabel( i18n( "Account:" ), this );
  mAccountEdit = new KLineEdit( this );
  mainLayout->addWidget( label, 2, 0 );
  mainLayout->addWidget( mAccountEdit, 2, 1 );

  label = new QLabel( i18n( "Password:" ), this );
  mPasswordEdit = new KLineEdit( this );
  mPasswordEdit->setEchoMode( QLineEdit::Password );
  mainLayout->addWidget( label, 3, 0 );
  mainLayout->addWidget( mPasswordEdit, 3, 1 );

  mMailboxEqualsUser = new QCheckBox( i18n( "Exchange Mailbox is &equal to User" ), this );
  mainLayout->addMultiCellWidget( mMailboxEqualsUser, 4, 4, 0, 1 );
  connect( mMailboxEqualsUser, SIGNAL(toggled(bool)), this, SLOT(slotToggleEquals(bool)) );

  mMailboxEdit = new KLineEdit( this );
  mainLayout->addWidget( new QLabel( i18n( "Mailbox URL:" ), this ), 5, 0 );
  mainLayout->addWidget( mMailboxEdit, 5, 1 );

  mTryFindMailbox = new QPushButton( "&Find", this );
  mainLayout->addWidget( mTryFindMailbox, 5, 2 );
  connect( mTryFindMailbox, SIGNAL(clicked()), this, SLOT(slotFindClicked()) );

  label = new QLabel( i18n( "Cache timeout:" ), this );
  mCacheEdit = new KIntNumInput( this );
  mCacheEdit->setMinValue( 0 );
  mCacheEdit->setSuffix( i18n(" seconds") );
  mainLayout->addWidget( label, 6, 0 );
  mainLayout->addWidget( mCacheEdit, 6, 1 );
}

void ResourceExchangeConfig::loadSettings( KRES::Resource *resource )
{
  ResourceExchange* res = dynamic_cast<ResourceExchange*>( resource );
  if (res) {
    mHostEdit->setText( res->mAccount->host() );
    mAccountEdit->setText( res->mAccount->account() );
    mPasswordEdit->setText( res->mAccount->password() );
    mMailboxEqualsUser->setChecked( res->mAccount->mailbox() == ("webdav://"+res->mAccount->host()+"/exchange/"+res->mAccount->account() ) );
    mMailboxEdit->setText( res->mAccount->mailbox() );
    mCacheEdit->setValue( res->mCachedSeconds );
  } else
    kdDebug(5700) << "ERROR: ResourceExchangeConfig::loadSettings(): no ResourceExchange, cast failed" << endl;
}

void ResourceExchangeConfig::saveSettings( KRES::Resource *resource )
{
  ResourceExchange* res = dynamic_cast<ResourceExchange*>( resource );
  if (res) {
    res->mAccount->setHost(mHostEdit->text());
    res->mAccount->setAccount(mAccountEdit->text());
    res->mAccount->setPassword(mPasswordEdit->text());
    if ( mMailboxEqualsUser->isChecked() ) {
      res->mAccount->setMailbox( "webdav://" + mHostEdit->text() + "/exchange/" + mAccountEdit->text() );
    } else {
      res->mAccount->setMailbox( mAccountEdit->text() );
    }
    res->mCachedSeconds = mCacheEdit->value();
  } else
    kdDebug(5700) << "ERROR: ResourceExchangeConfig::saveSettings(): no ResourceExchange, cast failed" << endl;
}

void ResourceExchangeConfig::slotToggleEquals( bool on )
{
  mMailboxEdit->setEnabled( ! on );
  mTryFindMailbox->setEnabled( ! on );
  if ( on ) {
    mMailboxEdit->setText( "webdav://" + mHostEdit->text() + "/exchange/" + mAccountEdit->text() );
  }
}

void ResourceExchangeConfig::slotUserChanged( const QString& text )
{
  if ( mMailboxEqualsUser->isChecked() ) {
    mMailboxEdit->setText( "webdav://" + mHostEdit->text() + "/exchange/" + text );
  }
}

void ResourceExchangeConfig::slotFindClicked()
{
  QString mailbox = KPIM::ExchangeAccount::tryFindMailbox( mHostEdit->text(), mAccountEdit->text(), mPasswordEdit->text() );
  if ( mailbox.isNull() ) {
    KMessageBox::sorry( this, "Could not determine mailbox URL" );
  } else {
    mMailboxEdit->setText( mailbox );
  }
}

#include "resourceexchangeconfig.moc"
<commit_msg>Fix buglet: retain edited mailbox url<commit_after>/*
    This file is part of libkpimexchange.
    Copyright (c) 2002 Tobias Koenig <tokoe@kde.org>
    Copyright (c) 2002 Jan-Pascal van Best <janpascal@vanbest.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include <qlabel.h>
#include <qlayout.h>

#include <klocale.h>
#include <kdebug.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>

#include "exchangeaccount.h"
#include "resourceexchangeconfig.h"
#include "resourceexchange.h"

using namespace KCal;

ResourceExchangeConfig::ResourceExchangeConfig( QWidget* parent,  const char* name )
    : KRES::ResourceConfigWidget( parent, name )
{
  resize( 245, 115 );
  QGridLayout *mainLayout = new QGridLayout( this, 7, 3 );

  QLabel *label = new QLabel( i18n( "Host:" ), this );
  mHostEdit = new KLineEdit( this );
  mainLayout->addWidget( label, 1, 0 );
  mainLayout->addWidget( mHostEdit, 1, 1 );

  label = new QLabel( i18n( "Account:" ), this );
  mAccountEdit = new KLineEdit( this );
  mainLayout->addWidget( label, 2, 0 );
  mainLayout->addWidget( mAccountEdit, 2, 1 );

  label = new QLabel( i18n( "Password:" ), this );
  mPasswordEdit = new KLineEdit( this );
  mPasswordEdit->setEchoMode( QLineEdit::Password );
  mainLayout->addWidget( label, 3, 0 );
  mainLayout->addWidget( mPasswordEdit, 3, 1 );

  mMailboxEqualsUser = new QCheckBox( i18n( "Exchange Mailbox is &equal to User" ), this );
  mainLayout->addMultiCellWidget( mMailboxEqualsUser, 4, 4, 0, 1 );
  connect( mMailboxEqualsUser, SIGNAL(toggled(bool)), this, SLOT(slotToggleEquals(bool)) );

  mMailboxEdit = new KLineEdit( this );
  mainLayout->addWidget( new QLabel( i18n( "Mailbox URL:" ), this ), 5, 0 );
  mainLayout->addWidget( mMailboxEdit, 5, 1 );

  mTryFindMailbox = new QPushButton( "&Find", this );
  mainLayout->addWidget( mTryFindMailbox, 5, 2 );
  connect( mTryFindMailbox, SIGNAL(clicked()), this, SLOT(slotFindClicked()) );

  label = new QLabel( i18n( "Cache timeout:" ), this );
  mCacheEdit = new KIntNumInput( this );
  mCacheEdit->setMinValue( 0 );
  mCacheEdit->setSuffix( i18n(" seconds") );
  mainLayout->addWidget( label, 6, 0 );
  mainLayout->addWidget( mCacheEdit, 6, 1 );
}

void ResourceExchangeConfig::loadSettings( KRES::Resource *resource )
{
  ResourceExchange* res = dynamic_cast<ResourceExchange*>( resource );
  if (res) {
    mHostEdit->setText( res->mAccount->host() );
    mAccountEdit->setText( res->mAccount->account() );
    mPasswordEdit->setText( res->mAccount->password() );
    mMailboxEqualsUser->setChecked( res->mAccount->mailbox() == ("webdav://"+res->mAccount->host()+"/exchange/"+res->mAccount->account() ) );
    mMailboxEdit->setText( res->mAccount->mailbox() );
    mCacheEdit->setValue( res->mCachedSeconds );
  } else
    kdDebug(5700) << "ERROR: ResourceExchangeConfig::loadSettings(): no ResourceExchange, cast failed" << endl;
}

void ResourceExchangeConfig::saveSettings( KRES::Resource *resource )
{
  ResourceExchange* res = dynamic_cast<ResourceExchange*>( resource );
  if (res) {
    res->mAccount->setHost(mHostEdit->text());
    res->mAccount->setAccount(mAccountEdit->text());
    res->mAccount->setPassword(mPasswordEdit->text());
    if ( mMailboxEqualsUser->isChecked() ) {
      res->mAccount->setMailbox( "webdav://" + mHostEdit->text() + "/exchange/" + mAccountEdit->text() );
    } else {
      res->mAccount->setMailbox( mMailboxEdit->text() );
    }
    res->mCachedSeconds = mCacheEdit->value();
  } else
    kdDebug(5700) << "ERROR: ResourceExchangeConfig::saveSettings(): no ResourceExchange, cast failed" << endl;
}

void ResourceExchangeConfig::slotToggleEquals( bool on )
{
  mMailboxEdit->setEnabled( ! on );
  mTryFindMailbox->setEnabled( ! on );
  if ( on ) {
    mMailboxEdit->setText( "webdav://" + mHostEdit->text() + "/exchange/" + mAccountEdit->text() );
  }
}

void ResourceExchangeConfig::slotUserChanged( const QString& text )
{
  if ( mMailboxEqualsUser->isChecked() ) {
    mMailboxEdit->setText( "webdav://" + mHostEdit->text() + "/exchange/" + text );
  }
}

void ResourceExchangeConfig::slotFindClicked()
{
  QString mailbox = KPIM::ExchangeAccount::tryFindMailbox( mHostEdit->text(), mAccountEdit->text(), mPasswordEdit->text() );
  if ( mailbox.isNull() ) {
    KMessageBox::sorry( this, "Could not determine mailbox URL" );
  } else {
    mMailboxEdit->setText( mailbox );
  }
}

#include "resourceexchangeconfig.moc"
<|endoftext|>


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

#ifndef _EXTENSIONS_PROPCTRLR_USERCONTROL_HXX_
#include "usercontrol.hxx"
#endif

#ifndef _NUMUNO_HXX
#include <svtools/numuno.hxx>
#endif
#ifndef _TOOLS_SOLMATH_HXX
#include <tools/solmath.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _ZFORMAT_HXX
#include <svtools/zformat.hxx>
#endif

//............................................................................
namespace pcr
{
//............................................................................

    //==================================================================
    // class OFormatDescriptionControl
    //==================================================================
    //------------------------------------------------------------------
    OFormatDescriptionControl::OFormatDescriptionControl( Window* pParent, WinBits nWinStyle)
            :OCommonBehaviourControl(this)
            ,FormattedField(pParent, nWinStyle)
    {
        SetModifyHdl(LINK( this, OCommonBehaviourControl, ModifiedHdl ));
        SetGetFocusHdl(LINK( this, OCommonBehaviourControl, GetFocusHdl));
        SetLoseFocusHdl(LINK( this, OCommonBehaviourControl, LoseFocusHdl));

        autoSizeWindow();
    }

    //------------------------------------------------------------------
    long OFormatDescriptionControl::PreNotify( NotifyEvent& rNEvt )
    {
        // want to handle two keys myself : Del/Backspace should empty the window (setting my prop to "standard" this way)
        if (EVENT_KEYINPUT == rNEvt.GetType())
        {
            sal_uInt16 nKey = rNEvt.GetKeyEvent()->GetKeyCode().GetCode();

            if ((KEY_DELETE == nKey) || (KEY_BACKSPACE == nKey))
            {
                SetText(String());
                ModifiedHdl(this);
                return sal_True;
            }
        }

        if (OCommonBehaviourControl::handlePreNotify(rNEvt))
            return sal_True;

        // it wasn't a PropCommonControl event => let our window handle it
        return FormattedField::PreNotify(rNEvt);
    }

    //------------------------------------------------------------------
    void OFormatDescriptionControl::SetProperty(const ::rtl::OUString& rString, sal_Bool bIsUnknown)
    {
        if (bIsUnknown || (rString == m_sStandardString) || !rString.getLength())
            // unknown or standard -> no text
            SetText(String());
        else
        {
            // else set the new format key, the text will be reformatted
            SetValue(1234.56789);
            SetFormatKey(String(rString).ToInt32());
        }
    }

    //------------------------------------------------------------------
    ::rtl::OUString OFormatDescriptionControl::GetProperty() const
    {
        if (!GetText().Len())
            return m_sStandardString;
        else
            return String::CreateFromInt32(GetFormatKey());
    }

    //------------------------------------------------------------------
    void OFormatDescriptionControl::SetFormatSupplier(const SvNumberFormatsSupplierObj* pSupplier)
    {
        if (pSupplier)
        {
            TreatAsNumber(sal_True);

            SvNumberFormatter* pFormatter = pSupplier->GetNumberFormatter();
            SetFormatter(pFormatter, sal_True);
            SetValue(1234.56789);
        }
        else
        {
            TreatAsNumber(sal_False);
            SetFormatter(NULL, sal_True);
            SetText(String());
        }
    }

    //==================================================================
    // class OFormattedNumericControl
    //==================================================================
    DBG_NAME(OFormattedNumericControl);
    //------------------------------------------------------------------
    OFormattedNumericControl::OFormattedNumericControl( Window* pParent, WinBits nWinStyle)
            :OCommonBehaviourControl(this)
            ,FormattedField(pParent, nWinStyle)
    {
        DBG_CTOR(OFormattedNumericControl,NULL);

        SetModifyHdl(LINK( this, OFormattedNumericControl, ModifiedHdl ));
        SetGetFocusHdl(LINK( this, OFormattedNumericControl, GetFocusHdl));
        SetLoseFocusHdl(LINK( this, OFormattedNumericControl, LoseFocusHdl));

        autoSizeWindow();

        TreatAsNumber(sal_True);

        m_nLastDecimalDigits = GetDecimalDigits();
    }

    //------------------------------------------------------------------
    OFormattedNumericControl::~OFormattedNumericControl()
    {
        DBG_DTOR(OFormattedNumericControl,NULL);
    }

    //------------------------------------------------------------------
    long OFormattedNumericControl::PreNotify( NotifyEvent& rNEvt )
    {
        if (OCommonBehaviourControl::handlePreNotify(rNEvt))
            return sal_True;

        // it wasn't a PropCommonControl event => let our window handle it
        return FormattedField::PreNotify(rNEvt);
    }

    //------------------------------------------------------------------
    void OFormattedNumericControl::SetProperty(const ::rtl::OUString& rString, sal_Bool bIsUnknown)
    {
        if (bIsUnknown || (rString == m_sStandardString) || !rString.getLength())
            // unknown or standard -> no text
            SetText(String());
        else
        {
            SetValue(String(rString).ToDouble());
        }
    }

    //------------------------------------------------------------------
    ::rtl::OUString OFormattedNumericControl::GetProperty() const
    {
        if (!GetText().Len())
            return m_sStandardString;
        else
        {
            String sReturn;
            SolarMath::DoubleToString(
                sReturn, const_cast<OFormattedNumericControl*>(this)->GetValue(), 'F', m_nLastDecimalDigits,
                '.', sal_True);
                // always use a '.' (instead of the decimal separator given by m_aUsedInternational) :
                // when the returned string is interpreted nobody knows about this control or the used
                // international, so by convention we always use '.' for describing floating point numbers
                // 27.07.99 - 67901 - FS
            return sReturn;
        }
    }

    //------------------------------------------------------------------
    void OFormattedNumericControl::SetFormatDescription(const FormatDescription& rDesc)
    {
        if (rDesc.pSupplier)
        {
            TreatAsNumber(sal_True);

            SvNumberFormatter* pFormatter = rDesc.pSupplier->GetNumberFormatter();
            if (pFormatter != GetFormatter())
                SetFormatter(pFormatter, sal_True);
            SetFormatKey(rDesc.nKey);

            const SvNumberformat* pEntry = GetFormatter()->GetEntry(GetFormatKey());
            switch (pEntry->GetType() & ~NUMBERFORMAT_DEFINED)
            {
                case NUMBERFORMAT_NUMBER:
                case NUMBERFORMAT_CURRENCY:
                case NUMBERFORMAT_SCIENTIFIC:
                case NUMBERFORMAT_FRACTION:
                case NUMBERFORMAT_PERCENT:
                    m_nLastDecimalDigits = GetDecimalDigits();
                    break;
                case NUMBERFORMAT_DATETIME:
                case NUMBERFORMAT_DATE:
                case NUMBERFORMAT_TIME:
                    m_nLastDecimalDigits = 7;
                    break;
                default:
                    m_nLastDecimalDigits = 0;
                    break;
            }

        }
        else
        {
            TreatAsNumber(sal_False);
            SetFormatter(NULL, sal_True);
            SetText(String());
            m_nLastDecimalDigits = 0;
        }
    }

//............................................................................
} // namespace pcr
//............................................................................

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.1  2001/01/12 11:34:02  fs
 *  initial checkin - outsourced the form property browser
 *
 *
 *  Revision 1.0 09.01.01 10:23:42  fs
 ************************************************************************/

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

#ifndef _EXTENSIONS_PROPCTRLR_USERCONTROL_HXX_
#include "usercontrol.hxx"
#endif

#ifndef _NUMUNO_HXX
#include <svtools/numuno.hxx>
#endif
#ifndef _TOOLS_SOLMATH_HXX
#include <tools/solmath.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _ZFORMAT_HXX
#include <svtools/zformat.hxx>
#endif

//............................................................................
namespace pcr
{
//............................................................................

    //==================================================================
    // class OFormatDescriptionControl
    //==================================================================
    //------------------------------------------------------------------
    OFormatDescriptionControl::OFormatDescriptionControl( Window* pParent, WinBits nWinStyle)
            :OCommonBehaviourControl(this)
            ,FormattedField(pParent, nWinStyle)
    {
        SetModifyHdl(LINK( this, OCommonBehaviourControl, ModifiedHdl ));
        SetGetFocusHdl(LINK( this, OCommonBehaviourControl, GetFocusHdl));
        SetLoseFocusHdl(LINK( this, OCommonBehaviourControl, LoseFocusHdl));

        autoSizeWindow();
    }

    //------------------------------------------------------------------
    long OFormatDescriptionControl::PreNotify( NotifyEvent& rNEvt )
    {
        // want to handle two keys myself : Del/Backspace should empty the window (setting my prop to "standard" this way)
        if (EVENT_KEYINPUT == rNEvt.GetType())
        {
            sal_uInt16 nKey = rNEvt.GetKeyEvent()->GetKeyCode().GetCode();

            if ((KEY_DELETE == nKey) || (KEY_BACKSPACE == nKey))
            {
                SetText(String());
                ModifiedHdl(this);
                return sal_True;
            }
        }

        if (OCommonBehaviourControl::handlePreNotify(rNEvt))
            return sal_True;

        // it wasn't a PropCommonControl event => let our window handle it
        return FormattedField::PreNotify(rNEvt);
    }

    //------------------------------------------------------------------
    void OFormatDescriptionControl::SetProperty(const ::rtl::OUString& rString, sal_Bool bIsUnknown)
    {
        if (bIsUnknown || (rString == m_sStandardString) || !rString.getLength())
            // unknown or standard -> no text
            SetText(String());
        else
        {
            // else set the new format key, the text will be reformatted
            SetValue(1234.56789);
            SetFormatKey(String(rString).ToInt32());
        }
    }

    //------------------------------------------------------------------
    ::rtl::OUString OFormatDescriptionControl::GetProperty() const
    {
        if (!GetText().Len())
            return m_sStandardString;
        else
            return String::CreateFromInt32(GetFormatKey());
    }

    //------------------------------------------------------------------
    void OFormatDescriptionControl::SetFormatSupplier(const SvNumberFormatsSupplierObj* pSupplier)
    {
        if (pSupplier)
        {
            TreatAsNumber(sal_True);

            SvNumberFormatter* pFormatter = pSupplier->GetNumberFormatter();
            SetFormatter(pFormatter, sal_True);
            SetValue(1234.56789);
        }
        else
        {
            TreatAsNumber(sal_False);
            SetFormatter(NULL, sal_True);
            SetText(String());
        }
    }

    //==================================================================
    // class OFormattedNumericControl
    //==================================================================
    DBG_NAME(OFormattedNumericControl);
    //------------------------------------------------------------------
    OFormattedNumericControl::OFormattedNumericControl( Window* pParent, WinBits nWinStyle)
            :OCommonBehaviourControl(this)
            ,FormattedField(pParent, nWinStyle)
    {
        DBG_CTOR(OFormattedNumericControl,NULL);

        SetModifyHdl(LINK( this, OFormattedNumericControl, ModifiedHdl ));
        SetGetFocusHdl(LINK( this, OFormattedNumericControl, GetFocusHdl));
        SetLoseFocusHdl(LINK( this, OFormattedNumericControl, LoseFocusHdl));

        autoSizeWindow();

        TreatAsNumber(sal_True);

        m_nLastDecimalDigits = GetDecimalDigits();
    }

    //------------------------------------------------------------------
    OFormattedNumericControl::~OFormattedNumericControl()
    {
        DBG_DTOR(OFormattedNumericControl,NULL);
    }

    //------------------------------------------------------------------
    long OFormattedNumericControl::PreNotify( NotifyEvent& rNEvt )
    {
        if (OCommonBehaviourControl::handlePreNotify(rNEvt))
            return sal_True;

        // it wasn't a PropCommonControl event => let our window handle it
        return FormattedField::PreNotify(rNEvt);
    }

    //------------------------------------------------------------------
    void OFormattedNumericControl::SetProperty(const ::rtl::OUString& rString, sal_Bool bIsUnknown)
    {
        if (bIsUnknown || (rString == m_sStandardString) || !rString.getLength())
            // unknown or standard -> no text
            SetText(String());
        else
        {
            SetValue(String(rString).ToDouble());
        }
    }

    //------------------------------------------------------------------
    ::rtl::OUString OFormattedNumericControl::GetProperty() const
    {
        if (!GetText().Len())
            return m_sStandardString;
        else
        {
            String sReturn;
            SolarMath::DoubleToString(
                sReturn, const_cast<OFormattedNumericControl*>(this)->GetValue(), 'F', m_nLastDecimalDigits,
                '.', sal_True);
                // always use a '.' (instead of the decimal separator given by m_aUsedInternational) :
                // when the returned string is interpreted nobody knows about this control or the used
                // international, so by convention we always use '.' for describing floating point numbers
                // 27.07.99 - 67901 - FS
            return sReturn;
        }
    }

    //------------------------------------------------------------------
    void OFormattedNumericControl::SetFormatDescription(const FormatDescription& rDesc)
    {
        sal_Bool bFallback = sal_True;

        if (rDesc.pSupplier)
        {
            TreatAsNumber(sal_True);

            SvNumberFormatter* pFormatter = rDesc.pSupplier->GetNumberFormatter();
            if (pFormatter != GetFormatter())
                SetFormatter(pFormatter, sal_True);
            SetFormatKey(rDesc.nKey);

            const SvNumberformat* pEntry = GetFormatter()->GetEntry(GetFormatKey());
            DBG_ASSERT( pEntry, "OFormattedNumericControl::SetFormatDescription: invalid format key!" );
            if ( pEntry )
            {
                switch (pEntry->GetType() & ~NUMBERFORMAT_DEFINED)
                {
                    case NUMBERFORMAT_NUMBER:
                    case NUMBERFORMAT_CURRENCY:
                    case NUMBERFORMAT_SCIENTIFIC:
                    case NUMBERFORMAT_FRACTION:
                    case NUMBERFORMAT_PERCENT:
                        m_nLastDecimalDigits = GetDecimalDigits();
                        break;
                    case NUMBERFORMAT_DATETIME:
                    case NUMBERFORMAT_DATE:
                    case NUMBERFORMAT_TIME:
                        m_nLastDecimalDigits = 7;
                        break;
                    default:
                        m_nLastDecimalDigits = 0;
                        break;
                }
                bFallback = sal_False;
            }

        }

        if ( bFallback )
        {
            TreatAsNumber(sal_False);
            SetFormatter(NULL, sal_True);
            SetText(String());
            m_nLastDecimalDigits = 0;
        }
    }

//............................................................................
} // namespace pcr
//............................................................................

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.2  2001/02/13 15:36:13  fs
 *  #83843# SetFormatDescription: correctly calculate m_nLastDecimalDigits
 *
 *  Revision 1.1  2001/01/12 11:34:02  fs
 *  initial checkin - outsourced the form property browser
 *
 *
 *  Revision 1.0 09.01.01 10:23:42  fs
 ************************************************************************/

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: download.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-06 14:36: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 _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif

#include <rtl/ref.hxx>
#include <rtl/ustring.hxx>
#include <osl/conditn.hxx>
#include <osl/file.h>

struct DownloadInteractionHandler : public rtl::IReference
{
    // called if the destination file already exists, but resume is false
    virtual bool downloadTargetExists(const rtl::OUString& rFileName) = 0;

    // called when curl reports an error
    virtual void downloadStalled(const rtl::OUString& rErrorMessage) = 0;

    // progress handler
    virtual void downloadProgressAt(sal_Int8 nPercent) = 0;

    // called on first progress notification
    virtual void downloadStarted(const rtl::OUString& rFileName) = 0;

    // called when download has been finished
    virtual void downloadFinished(const rtl::OUString& rFileName) = 0;
};

class Download
{
public:
    Download(const com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext >& xContext,
             const rtl::Reference< DownloadInteractionHandler >& rHandler) : m_xContext(xContext), m_aHandler(rHandler) {};

    // returns true when the content of rURL was successfully written to rLocalFile
    bool start(const rtl::OUString& rURL, const rtl::OUString& rLocalFile, bool resume);

    // stops the download after the next write operation
    void stop();

    // returns true if the stop condition is set
    bool isStopped() const
        { return sal_True == const_cast <Download *> (this)->m_aCondition.check(); };

protected:

    // Determines the appropriate proxy settings for the given URL. Returns true if a proxy should be used
    void getProxyForURL(const rtl::OUString& rURL, rtl::OString& rHost, sal_Int32& rPort) const;

private:
    osl::Condition m_aCondition;
    const com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext >& m_xContext;
    const rtl::Reference< DownloadInteractionHandler > m_aHandler;
};

<commit_msg>INTEGRATION: CWS updchk07 (1.2.2); FILE MERGED 2007/07/18 14:23:29 obr 1.2.2.2: #i79252# store total download size to be able to reconstruct progress after restart 2007/07/09 10:46:55 obr 1.2.2.1: #i79134# split file name of started download from default target dir<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: download.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2007-07-31 15:56:04 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif

#include <rtl/ref.hxx>
#include <rtl/ustring.hxx>
#include <osl/conditn.hxx>
#include <osl/file.h>

struct DownloadInteractionHandler : public rtl::IReference
{
    // called if the destination file already exists, but resume is false
    virtual bool downloadTargetExists(const rtl::OUString& rFileName) = 0;

    // called when curl reports an error
    virtual void downloadStalled(const rtl::OUString& rErrorMessage) = 0;

    // progress handler
    virtual void downloadProgressAt(sal_Int8 nPercent) = 0;

    // called on first progress notification
    virtual void downloadStarted(const rtl::OUString& rFileName, sal_Int64 nFileSize) = 0;

    // called when download has been finished
    virtual void downloadFinished(const rtl::OUString& rFileName) = 0;
};

class Download
{
public:
    Download(const com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext >& xContext,
             const rtl::Reference< DownloadInteractionHandler >& rHandler) : m_xContext(xContext), m_aHandler(rHandler) {};

    // returns true when the content of rURL was successfully written to rLocalFile
    bool start(const rtl::OUString& rURL, const rtl::OUString& rFile, const rtl::OUString& rDestinationDir);

    // stops the download after the next write operation
    void stop();

    // returns true if the stop condition is set
    bool isStopped() const
        { return sal_True == const_cast <Download *> (this)->m_aCondition.check(); };

protected:

    // Determines the appropriate proxy settings for the given URL. Returns true if a proxy should be used
    void getProxyForURL(const rtl::OUString& rURL, rtl::OString& rHost, sal_Int32& rPort) const;

private:
    osl::Condition m_aCondition;
    const com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext >& m_xContext;
    const rtl::Reference< DownloadInteractionHandler > m_aHandler;
};

<|endoftext|>


<commit_before>/*
 * This file is part of the Sqloxx project and is distributed under the
 * terms of the license contained in the file LICENSE.txt distributed
 * with this package.
 *
 * Author: Matthew Harvey <matthew@matthewharvey.net>
 *
 * Copyright (c) 2012-2013, Matthew Harvey.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "derived_po.hpp"
#include "handle.hpp"
#include "identity_map.hpp"
#include "sqloxx_exceptions.hpp"
#include "sqloxx_tests_common.hpp"
#include <UnitTest++/UnitTest++.h>

namespace sqloxx
{
namespace tests
{

// Note many of the functions of IdentityMap can only be tested
// indirectly via the database connection, as they are
// private.

// TODO Uncomment the commented-out tests and adjust them to
// reflect that those functions are now private.

TEST_FIXTURE(DerivedPOFixture, identity_map_after_object_removal)
{
	DerivedDatabaseConnection& dbc = *pdbc;
	Handle<DerivedPO> dpo1(dbc);
	dpo1->set_x(10);
	dpo1->set_y(-1298);
	dpo1->save();
	Handle<DerivedPO> dpo1b(dbc, 1);  // OK
	dpo1->remove();
	bool ok = false;
	try
	{
		Handle<DerivedPO> dpo1c(*pdbc, 1);
	}
	catch (BadIdentifier&)
	{
		ok = true;
	}
	CHECK(ok);
	// But this doesn't throw
	Handle<DerivedPO> dpo1d
	(	Handle<DerivedPO>::create_unchecked(dbc, 1)
	);
}

TEST_FIXTURE(DerivedPOFixture, identity_map_connection)
{
	DerivedDatabaseConnection& dbc = *pdbc;
	IdentityMap<DerivedPO> idm(dbc);
	CHECK_EQUAL(&(idm.connection()), &dbc);
}

}  // namespace tests
}  // namespace sqloxx
<commit_msg>Deleted an obolete TODO.<commit_after>/*
 * This file is part of the Sqloxx project and is distributed under the
 * terms of the license contained in the file LICENSE.txt distributed
 * with this package.
 *
 * Author: Matthew Harvey <matthew@matthewharvey.net>
 *
 * Copyright (c) 2012-2013, Matthew Harvey.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "derived_po.hpp"
#include "handle.hpp"
#include "identity_map.hpp"
#include "sqloxx_exceptions.hpp"
#include "sqloxx_tests_common.hpp"
#include <UnitTest++/UnitTest++.h>

namespace sqloxx
{
namespace tests
{

// Note many of the functions of IdentityMap can only be tested
// indirectly via the database connection, as they are
// private.

TEST_FIXTURE(DerivedPOFixture, identity_map_after_object_removal)
{
	DerivedDatabaseConnection& dbc = *pdbc;
	Handle<DerivedPO> dpo1(dbc);
	dpo1->set_x(10);
	dpo1->set_y(-1298);
	dpo1->save();
	Handle<DerivedPO> dpo1b(dbc, 1);  // OK
	dpo1->remove();
	bool ok = false;
	try
	{
		Handle<DerivedPO> dpo1c(*pdbc, 1);
	}
	catch (BadIdentifier&)
	{
		ok = true;
	}
	CHECK(ok);
	// But this doesn't throw
	Handle<DerivedPO> dpo1d
	(	Handle<DerivedPO>::create_unchecked(dbc, 1)
	);
}

TEST_FIXTURE(DerivedPOFixture, identity_map_connection)
{
	DerivedDatabaseConnection& dbc = *pdbc;
	IdentityMap<DerivedPO> idm(dbc);
	CHECK_EQUAL(&(idm.connection()), &dbc);
}

}  // namespace tests
}  // namespace sqloxx
<|endoftext|>


<commit_before>//===========================================
//  Lumina-DE source code
//  Copyright (c) 2014, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "SysMenuQuick.h"
#include "ui_SysMenuQuick.h"

#include "../../LSession.h"
#include <LuminaX11.h>

LSysMenuQuick::LSysMenuQuick(QWidget *parent) : QWidget(parent), ui(new Ui::LSysMenuQuick){
  ui->setupUi(this);
  settings = new QSettings("panel-plugins","systemdashboard");
  brighttimer = new QTimer(this);
    brighttimer->setSingleShot(true);
    brighttimer->setInterval(100); //100ms delay in setting the new value
  //Now reset the initial saved settings (if any)
  LOS::setScreenBrightness( settings->value("screenbrightness",100).toInt() ); //default to 100%
  LOS::setAudioVolume( settings->value("audiovolume", 100).toInt() ); //default to 100%
  //Now setup the connections
  connect(ui->slider_volume, SIGNAL(valueChanged(int)), this, SLOT(volSliderChanged()) );
  connect(ui->slider_brightness, SIGNAL(valueChanged(int)), this, SLOT(brightSliderChanged()) );
  connect(ui->tool_wk_prev, SIGNAL(clicked()), this, SLOT(prevWorkspace()) );
  connect(ui->tool_wk_next, SIGNAL(clicked()), this, SLOT(nextWorkspace()) );
  connect(ui->tool_logout, SIGNAL(clicked()), this, SLOT(startLogout()) );
  connect(ui->tool_vol_mixer, SIGNAL(clicked()), this, SLOT(startMixer()) );
  connect(brighttimer, SIGNAL(timeout()), this, SLOT(setCurrentBrightness()) );
  //And setup the default icons
  ui->label_bright_icon->setPixmap( LXDG::findIcon("preferences-system-power-management","").pixmap(ui->label_bright_icon->maximumSize()) );
  ui->tool_wk_prev->setIcon( LXDG::findIcon("go-previous-view",""));
  ui->tool_wk_next->setIcon( LXDG::findIcon("go-next-view","") );
  ui->tool_logout->setIcon( LXDG::findIcon("system-log-out","") );
}

LSysMenuQuick::~LSysMenuQuick(){

}

void LSysMenuQuick::UpdateMenu(){
  //Audio Volume
  int val = LOS::audioVolume();
  QIcon ico;
  if(val > 66){ ico= LXDG::findIcon("audio-volume-high",""); }
  else if(val > 33){ ico= LXDG::findIcon("audio-volume-medium",""); }
  else if(val > 0){ ico= LXDG::findIcon("audio-volume-low",""); }
  else{ ico= LXDG::findIcon("audio-volume-muted",""); }
  bool hasMixer = LOS::hasMixerUtility();
  ui->label_vol_icon->setVisible(!hasMixer);
  ui->tool_vol_mixer->setVisible(hasMixer);
  if(!hasMixer){ ui->label_vol_icon->setPixmap( ico.pixmap(ui->label_vol_icon->maximumSize()) ); }
  else{ ui->tool_vol_mixer->setIcon(ico); }
  QString txt = QString::number(val)+"%";
  if(val<100){ txt.prepend(" "); } //make sure no widget resizing
  ui->label_vol_text->setText(txt);
  if(ui->slider_volume->value()!= val){ ui->slider_volume->setValue(val); }
  //Screen Brightness
  val = LOS::ScreenBrightness();
  if(val < 0){
    //No brightness control - hide it
    ui->group_brightness->setVisible(false);
  }else{
    ui->group_brightness->setVisible(true);
    txt = QString::number(val)+"%";
    if(val<100){ txt.prepend(" "); } //make sure no widget resizing
    ui->label_bright_text->setText(txt);
    if(ui->slider_brightness->value()!=val){ ui->slider_brightness->setValue(val); }
  }
  //Battery Status
  if(LOS::hasBattery()){
    ui->group_battery->setVisible(true);
    val = LOS::batteryCharge();
    if(LOS::batteryIsCharging()){
      if(val < 15){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-low","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 30){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-caution","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 50){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-040","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 70){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-060","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 90){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-080","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else{ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      ui->label_bat_text->setText( QString("%1%\n(%2)").arg(QString::number(val), tr("connected")) );
    }else{
      if(val < 1){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-missing","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 15){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-low","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 30){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-caution","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 50){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-040","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 70){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-060","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 90){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-080","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else{ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-100","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      ui->label_bat_text->setText( QString("%1%\n(%2)").arg(QString::number(val), getRemainingTime()) );
    }
  }else{
    ui->group_battery->setVisible(false);
  }
  //Workspace
  val = LX11::GetCurrentDesktop();
  int tot = LX11::GetNumberOfDesktops();
  ui->group_workspace->setVisible(val>=0 && tot>1);
  ui->label_wk_text->setText( QString(tr("%1 of %2")).arg(QString::number(val+1), QString::number(tot)) );
}

void LSysMenuQuick::volSliderChanged(){
  int val = ui->slider_volume->value();
  LOS::setAudioVolume(val);
  settings->setValue("audiovolume",val);
  QString txt = QString::number(val)+"%";
  if(val<100){ txt.prepend(" "); } //make sure no widget resizing
  ui->label_vol_text->setText( txt );
  if(val > 66){ ui->label_vol_icon->setPixmap( LXDG::findIcon("audio-volume-high","").pixmap(ui->label_vol_icon->maximumSize()) ); }
  else if(val > 33){ ui->label_vol_icon->setPixmap( LXDG::findIcon("audio-volume-medium","").pixmap(ui->label_vol_icon->maximumSize()) ); }
  else if(val > 0){ ui->label_vol_icon->setPixmap( LXDG::findIcon("audio-volume-low","").pixmap(ui->label_vol_icon->maximumSize()) ); }
  else{ ui->label_vol_icon->setPixmap( LXDG::findIcon("audio-volume-muted","").pixmap(ui->label_vol_icon->maximumSize()) ); }
}

void LSysMenuQuick::startMixer(){
  emit CloseMenu();
  LOS::startMixerUtility();
}

void LSysMenuQuick::brightSliderChanged(){
  //Brightness controls cannot operate extremely quickly - combine calls as necessary
  if(brighttimer->isActive()){ brighttimer->stop(); }
  brighttimer->start();
}

void LSysMenuQuick::setCurrentBrightness(){
  int val = ui->slider_brightness->value();
  LOS::setScreenBrightness(val);
  settings->setValue("screenbrightness",val);
  QString txt = QString::number(val)+"%";
  if(val<100){ txt.prepend(" "); } //make sure no widget resizing
  ui->label_bright_text->setText( txt );
}

void LSysMenuQuick::nextWorkspace(){
  int cur = LX11::GetCurrentDesktop();
  int tot = LX11::GetNumberOfDesktops();
  cur++;
  if(cur>=tot){ cur = 0; } //back to beginning
  LX11::SetCurrentDesktop(cur);
ui->label_wk_text->setText( QString(tr("%1 of %2")).arg(QString::number(cur+1), QString::number(tot)) );
}

void LSysMenuQuick::prevWorkspace(){
  int cur = LX11::GetCurrentDesktop();
  int tot = LX11::GetNumberOfDesktops();
  cur--;
  if(cur<0){ cur = tot-1; } //back to last
  LX11::SetCurrentDesktop(cur);
  ui->label_wk_text->setText( QString(tr("%1 of %2")).arg(QString::number(cur+1), QString::number(tot)) );
}

QString LSysMenuQuick::getRemainingTime(){
  int secs = LOS::batterySecondsLeft();
  if(secs < 0){ return "??"; }
  QString rem; //remaining
  if(secs > 3600){
    int hours = secs/3600;
    rem.append( QString::number(hours)+"h ");
    secs = secs - (hours*3600);
  }
  if(secs > 60){
    int min = secs/60;
    rem.append( QString::number(min)+"m ");
    secs = secs - (min*60);
  }
  if(secs > 0){
    rem.append( QString::number(secs)+"s");
  }else{
    rem.append( "0s" );
  }
  return rem;
}

void LSysMenuQuick::startLogout(){
  emit CloseMenu();
  LSession::handle()->systemWindow();
}
<commit_msg>Adjust te brightness control labelling a bit in the sytem dashboard. Now the label will always stay in sync with the slider (no delay), it is only the backend setting routine which is on a slight (50ms) delay.<commit_after>//===========================================
//  Lumina-DE source code
//  Copyright (c) 2014, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "SysMenuQuick.h"
#include "ui_SysMenuQuick.h"

#include "../../LSession.h"
#include <LuminaX11.h>

LSysMenuQuick::LSysMenuQuick(QWidget *parent) : QWidget(parent), ui(new Ui::LSysMenuQuick){
  ui->setupUi(this);
  settings = new QSettings("panel-plugins","systemdashboard");
  brighttimer = new QTimer(this);
    brighttimer->setSingleShot(true);
    brighttimer->setInterval(50); //50ms delay in setting the new value
  //Now reset the initial saved settings (if any)
  LOS::setScreenBrightness( settings->value("screenbrightness",100).toInt() ); //default to 100%
  LOS::setAudioVolume( settings->value("audiovolume", 100).toInt() ); //default to 100%
  //Now setup the connections
  connect(ui->slider_volume, SIGNAL(valueChanged(int)), this, SLOT(volSliderChanged()) );
  connect(ui->slider_brightness, SIGNAL(valueChanged(int)), this, SLOT(brightSliderChanged()) );
  connect(ui->tool_wk_prev, SIGNAL(clicked()), this, SLOT(prevWorkspace()) );
  connect(ui->tool_wk_next, SIGNAL(clicked()), this, SLOT(nextWorkspace()) );
  connect(ui->tool_logout, SIGNAL(clicked()), this, SLOT(startLogout()) );
  connect(ui->tool_vol_mixer, SIGNAL(clicked()), this, SLOT(startMixer()) );
  connect(brighttimer, SIGNAL(timeout()), this, SLOT(setCurrentBrightness()) );
  //And setup the default icons
  ui->label_bright_icon->setPixmap( LXDG::findIcon("preferences-system-power-management","").pixmap(ui->label_bright_icon->maximumSize()) );
  ui->tool_wk_prev->setIcon( LXDG::findIcon("go-previous-view",""));
  ui->tool_wk_next->setIcon( LXDG::findIcon("go-next-view","") );
  ui->tool_logout->setIcon( LXDG::findIcon("system-log-out","") );
}

LSysMenuQuick::~LSysMenuQuick(){

}

void LSysMenuQuick::UpdateMenu(){
  //Audio Volume
  int val = LOS::audioVolume();
  QIcon ico;
  if(val > 66){ ico= LXDG::findIcon("audio-volume-high",""); }
  else if(val > 33){ ico= LXDG::findIcon("audio-volume-medium",""); }
  else if(val > 0){ ico= LXDG::findIcon("audio-volume-low",""); }
  else{ ico= LXDG::findIcon("audio-volume-muted",""); }
  bool hasMixer = LOS::hasMixerUtility();
  ui->label_vol_icon->setVisible(!hasMixer);
  ui->tool_vol_mixer->setVisible(hasMixer);
  if(!hasMixer){ ui->label_vol_icon->setPixmap( ico.pixmap(ui->label_vol_icon->maximumSize()) ); }
  else{ ui->tool_vol_mixer->setIcon(ico); }
  QString txt = QString::number(val)+"%";
  if(val<100){ txt.prepend(" "); } //make sure no widget resizing
  ui->label_vol_text->setText(txt);
  if(ui->slider_volume->value()!= val){ ui->slider_volume->setValue(val); }
  //Screen Brightness
  val = LOS::ScreenBrightness();
  if(val < 0){
    //No brightness control - hide it
    ui->group_brightness->setVisible(false);
  }else{
    ui->group_brightness->setVisible(true);
    txt = QString::number(val)+"%";
    if(val<100){ txt.prepend(" "); } //make sure no widget resizing
    ui->label_bright_text->setText(txt);
    if(ui->slider_brightness->value()!=val){ ui->slider_brightness->setValue(val); }
  }
  //Battery Status
  if(LOS::hasBattery()){
    ui->group_battery->setVisible(true);
    val = LOS::batteryCharge();
    if(LOS::batteryIsCharging()){
      if(val < 15){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-low","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 30){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-caution","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 50){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-040","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 70){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-060","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 90){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging-080","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else{ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-charging","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      ui->label_bat_text->setText( QString("%1%\n(%2)").arg(QString::number(val), tr("connected")) );
    }else{
      if(val < 1){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-missing","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 15){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-low","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 30){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-caution","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 50){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-040","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 70){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-060","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else if(val < 90){ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-080","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      else{ ui->label_bat_icon->setPixmap( LXDG::findIcon("battery-100","").pixmap(ui->label_bat_icon->maximumSize()) ); }
      ui->label_bat_text->setText( QString("%1%\n(%2)").arg(QString::number(val), getRemainingTime()) );
    }
  }else{
    ui->group_battery->setVisible(false);
  }
  //Workspace
  val = LX11::GetCurrentDesktop();
  int tot = LX11::GetNumberOfDesktops();
  ui->group_workspace->setVisible(val>=0 && tot>1);
  ui->label_wk_text->setText( QString(tr("%1 of %2")).arg(QString::number(val+1), QString::number(tot)) );
}

void LSysMenuQuick::volSliderChanged(){
  int val = ui->slider_volume->value();
  LOS::setAudioVolume(val);
  settings->setValue("audiovolume",val);
  QString txt = QString::number(val)+"%";
  if(val<100){ txt.prepend(" "); } //make sure no widget resizing
  ui->label_vol_text->setText( txt );
  if(val > 66){ ui->label_vol_icon->setPixmap( LXDG::findIcon("audio-volume-high","").pixmap(ui->label_vol_icon->maximumSize()) ); }
  else if(val > 33){ ui->label_vol_icon->setPixmap( LXDG::findIcon("audio-volume-medium","").pixmap(ui->label_vol_icon->maximumSize()) ); }
  else if(val > 0){ ui->label_vol_icon->setPixmap( LXDG::findIcon("audio-volume-low","").pixmap(ui->label_vol_icon->maximumSize()) ); }
  else{ ui->label_vol_icon->setPixmap( LXDG::findIcon("audio-volume-muted","").pixmap(ui->label_vol_icon->maximumSize()) ); }
}

void LSysMenuQuick::startMixer(){
  emit CloseMenu();
  LOS::startMixerUtility();
}

void LSysMenuQuick::brightSliderChanged(){
  //Brightness controls cannot operate extremely quickly - combine calls as necessary
  if(brighttimer->isActive()){ brighttimer->stop(); }
  brighttimer->start();
  //*DO* update the label right away
  int val = ui->slider_brightness->value();
  QString txt = QString::number(val)+"%";
  if(val<100){ txt.prepend(" "); } //make sure no widget resizing
  ui->label_bright_text->setText( txt );
}

void LSysMenuQuick::setCurrentBrightness(){
  int val = ui->slider_brightness->value();
  LOS::setScreenBrightness(val);
  settings->setValue("screenbrightness",val);
  QString txt = QString::number(val)+"%";
  if(val<100){ txt.prepend(" "); } //make sure no widget resizing
  ui->label_bright_text->setText( txt );
}

void LSysMenuQuick::nextWorkspace(){
  int cur = LX11::GetCurrentDesktop();
  int tot = LX11::GetNumberOfDesktops();
  cur++;
  if(cur>=tot){ cur = 0; } //back to beginning
  LX11::SetCurrentDesktop(cur);
ui->label_wk_text->setText( QString(tr("%1 of %2")).arg(QString::number(cur+1), QString::number(tot)) );
}

void LSysMenuQuick::prevWorkspace(){
  int cur = LX11::GetCurrentDesktop();
  int tot = LX11::GetNumberOfDesktops();
  cur--;
  if(cur<0){ cur = tot-1; } //back to last
  LX11::SetCurrentDesktop(cur);
  ui->label_wk_text->setText( QString(tr("%1 of %2")).arg(QString::number(cur+1), QString::number(tot)) );
}

QString LSysMenuQuick::getRemainingTime(){
  int secs = LOS::batterySecondsLeft();
  if(secs < 0){ return "??"; }
  QString rem; //remaining
  if(secs > 3600){
    int hours = secs/3600;
    rem.append( QString::number(hours)+"h ");
    secs = secs - (hours*3600);
  }
  if(secs > 60){
    int min = secs/60;
    rem.append( QString::number(min)+"m ");
    secs = secs - (min*60);
  }
  if(secs > 0){
    rem.append( QString::number(secs)+"s");
  }else{
    rem.append( "0s" );
  }
  return rem;
}

void LSysMenuQuick::startLogout(){
  emit CloseMenu();
  LSession::handle()->systemWindow();
}
<|endoftext|>


<commit_before>/*
 * Copyright 2011 Simon A. F. Lund <safl@safl.dk>
 *
 * This file is part of cphVB.
 *
 * cphVB is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * cphVB 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with cphVB. If not, see <http://www.gnu.org/licenses/>.
 */
#include <cphvb.h>
#include "cphvb_ve_score.h"
#include <iostream>
#include <cphvb_mcache.h>

static cphvb_component *myself = NULL;
static cphvb_userfunc_impl reduce_impl = NULL;
static cphvb_intp reduce_impl_id = 0;
static cphvb_userfunc_impl random_impl = NULL;
static cphvb_intp random_impl_id = 0;
static cphvb_userfunc_impl matmul_impl = NULL;
static cphvb_intp matmul_impl_id = 0;

static cphvb_intp cphvb_ve_score_buffersizes = 0;
static computeloop* cphvb_ve_score_compute_loops = NULL;
static cphvb_tstate* cphvb_ve_score_tstates = NULL;

static cphvb_intp block_size = 1000;

cphvb_error cphvb_ve_score_init(cphvb_component *self)
{
    myself = self;                              // Assign config container.

    char *env = getenv("CPHVB_VE_BLOCKSIZE");   // Override block_size from environment-variable.
    if(env != NULL)
    {
        block_size = atoi(env);
    }
    if(block_size <= 0)                         // Verify it
    {
        fprintf(stderr, "CPHVB_VE_BLOCKSIZE (%ld) should be greater than zero!\n", block_size);
        return CPHVB_ERROR;
    }

    cphvb_mcache_init( 10 );
    return CPHVB_SUCCESS;
}

inline cphvb_error block_execute( cphvb_instruction* instr, cphvb_intp start, cphvb_intp end) {

    cphvb_intp i, k;

    //Make sure we have enough space
    if ((end - start + 1) > cphvb_ve_score_buffersizes)
    {
    	cphvb_intp mcount = (end - start + 1);

    	//We only work in multiples of 1000
    	if (mcount % 1000 != 0)
    		mcount = (mcount + 1000) - (mcount % 1000);

    	//Make sure we re-allocate on error
    	cphvb_ve_score_buffersizes = 0;

    	if (cphvb_ve_score_compute_loops != NULL) {
    		free(cphvb_ve_score_compute_loops);
    		free(cphvb_ve_score_tstates);
    		cphvb_ve_score_compute_loops = NULL;
    		cphvb_ve_score_tstates = NULL;
    	}

    	cphvb_ve_score_compute_loops = (computeloop*)malloc(sizeof(computeloop) * mcount);
        cphvb_ve_score_tstates = (cphvb_tstate*)malloc(sizeof(cphvb_tstate)*mcount);

    	if (cphvb_ve_score_compute_loops == NULL)
    		return CPHVB_OUT_OF_MEMORY;
    	if (cphvb_ve_score_tstates == NULL)
    		return CPHVB_OUT_OF_MEMORY;

    	cphvb_ve_score_buffersizes = mcount;
    }

    computeloop* compute_loops = cphvb_ve_score_compute_loops;
    cphvb_tstate* states = cphvb_ve_score_tstates;
    cphvb_intp  nelements, trav_end=0;

    for(i=0; i<=end-start;i++)                      // Reset traversal coordinates
        cphvb_tstate_reset( &states[i] );

    for(i=start, k=0; i <= end; i++,k++)            // Get the compute-loops
    {
        compute_loops[k] = cphvb_compute_get( &instr[i] );
    }
                                                    // Block-size split
    nelements = cphvb_nelements( instr[start].operand[0]->ndim, instr[start].operand[0]->shape );
    while(nelements>trav_end)
    {
        trav_end    += block_size;
        if (trav_end > nelements)
            trav_end = nelements;

        for(i=start, k=0; i <= end; i++, k++)
        {
            compute_loops[k]( &instr[i], &states[k], trav_end );
        }
    }

    for(i=start; i <= end; i++)                     // Set instruction status
    {
        instr[i].status = CPHVB_SUCCESS;
    }

    return CPHVB_SUCCESS;

}

cphvb_error cphvb_ve_score_execute( cphvb_intp instruction_count, cphvb_instruction* instruction_list )
{
    cphvb_intp cur_index,  j;
    cphvb_instruction *inst, *binst;

    cphvb_intp bin_start, bin_end, bin_size;
    cphvb_intp bundle_start, bundle_end, bundle_size;
    cphvb_error res;

    for(cur_index=0; cur_index < instruction_count; cur_index++)
    {
        inst = &instruction_list[cur_index];

        if(inst->status == CPHVB_SUCCESS)       // SKIP instruction
        {
            continue;
        }

        res = cphvb_mcache_malloc( inst );      // Allocate memory for operands
        if ( res != CPHVB_SUCCESS ) {
            return res;
        }

        switch(inst->opcode)                    // Dispatch instruction
        {
            case CPHVB_NONE:                    // NOOP.
            case CPHVB_DISCARD:
            case CPHVB_SYNC:
                inst->status = CPHVB_SUCCESS;
                break;

            case CPHVB_FREE:                        // Store data-pointer in malloc-cache
                inst->status = cphvb_mcache_free( inst );
                break;

            case CPHVB_USERFUNC:                // External libraries

                if(inst->userfunc->id == reduce_impl_id)
                {
                    inst->status = reduce_impl(inst->userfunc, NULL);
                }
                else if(inst->userfunc->id == random_impl_id)
                {
                    inst->status = random_impl(inst->userfunc, NULL);
                }
                else if(inst->userfunc->id == matmul_impl_id)
                {
                    inst->status = matmul_impl(inst->userfunc, NULL);
                }
                else                            // Unsupported userfunc
                {
                    inst->status = CPHVB_USERFUNC_NOT_SUPPORTED;
                }

                break;

            default:                                            // Built-in operations
                                                                // -={[ BINNING ]}=-
                bin_start   = cur_index;                        // Count built-ins and their start/end indexes and allocate memory for them.
                bin_end     = cur_index;
                for(j=bin_start+1; j<instruction_count; j++)
                {
                    binst = &instruction_list[j];               // EXIT: Stop if instruction is NOT built-in
                    if ((binst->opcode == CPHVB_NONE) || \
                        (binst->opcode == CPHVB_DISCARD) || \
                        (binst->opcode == CPHVB_SYNC) || \
                        (binst->opcode == CPHVB_USERFUNC) || \
                        (binst->opcode == CPHVB_FREE) ) {
                        break;
                    }

                    bin_end++;                                  // The "end" index
                    res = cphvb_mcache_malloc( binst );         // Allocate memory for operands
                    if ( res != CPHVB_SUCCESS ) {
                        return res;
                    }

                }
                bin_size = bin_end - bin_start +1;              // The counting part

                                                                // -={[ BUNDLING ]}=-
                bundle_size     = (bin_size > 1) ? cphvb_inst_bundle( instruction_list, bin_start, bin_end ) : 1;
                bundle_start    = bin_start;
                bundle_end      = bundle_start + bundle_size-1;

                block_execute( instruction_list, bundle_start, bundle_end );
                cur_index += bundle_size-1;
        }

        if (inst->status != CPHVB_SUCCESS)    // Instruction failed
        {
            break;
        }

    }

    if (cur_index == instruction_count) {
        return CPHVB_SUCCESS;
    } else {
        return CPHVB_PARTIAL_SUCCESS;
    }

}

cphvb_error cphvb_ve_score_shutdown( void )
{
    cphvb_mcache_clear();
    cphvb_mcache_delete();

    return CPHVB_SUCCESS;
}

cphvb_error cphvb_ve_score_reg_func(char *fun, cphvb_intp *id) {

    if(strcmp("cphvb_reduce", fun) == 0)
    {
    	if (reduce_impl == NULL)
    	{
			cphvb_component_get_func(myself, fun, &reduce_impl);
			if (reduce_impl == NULL)
				return CPHVB_USERFUNC_NOT_SUPPORTED;

			reduce_impl_id = *id;
			return CPHVB_SUCCESS;
        }
        else
        {
        	*id = reduce_impl_id;
        	return CPHVB_SUCCESS;
        }
    }
    else if(strcmp("cphvb_random", fun) == 0)
    {
    	if (random_impl == NULL)
    	{
			cphvb_component_get_func(myself, fun, &random_impl);
			if (random_impl == NULL)
				return CPHVB_USERFUNC_NOT_SUPPORTED;

			random_impl_id = *id;
			return CPHVB_SUCCESS;
        }
        else
        {
        	*id = random_impl_id;
        	return CPHVB_SUCCESS;
        }
    }
    else if(strcmp("cphvb_matmul", fun) == 0)
    {
    	if (matmul_impl == NULL)
    	{
			cphvb_component_get_func(myself, fun, &matmul_impl);
			if (matmul_impl == NULL)
				return CPHVB_USERFUNC_NOT_SUPPORTED;

			matmul_impl_id = *id;
			return CPHVB_SUCCESS;
        }
        else
        {
        	*id = matmul_impl_id;
        	return CPHVB_SUCCESS;
        }
    }

    return CPHVB_USERFUNC_NOT_SUPPORTED;
}

cphvb_error cphvb_reduce( cphvb_userfunc *arg, void* ve_arg)
{
    return cphvb_compute_reduce( arg, ve_arg );
}

cphvb_error cphvb_random( cphvb_userfunc *arg, void* ve_arg)
{
    return cphvb_compute_random( arg, ve_arg );
}

cphvb_error cphvb_matmul( cphvb_userfunc *arg, void* ve_arg)
{
    return cphvb_compute_matmul( arg, ve_arg );

}
<commit_msg>Fixed a compile warning in score<commit_after>/*
 * Copyright 2011 Simon A. F. Lund <safl@safl.dk>
 *
 * This file is part of cphVB.
 *
 * cphVB is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * cphVB 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with cphVB. If not, see <http://www.gnu.org/licenses/>.
 */
#include <cphvb.h>
#include "cphvb_ve_score.h"
#include <iostream>
#include <cphvb_mcache.h>

static cphvb_component *myself = NULL;
static cphvb_userfunc_impl reduce_impl = NULL;
static cphvb_intp reduce_impl_id = 0;
static cphvb_userfunc_impl random_impl = NULL;
static cphvb_intp random_impl_id = 0;
static cphvb_userfunc_impl matmul_impl = NULL;
static cphvb_intp matmul_impl_id = 0;

static cphvb_intp cphvb_ve_score_buffersizes = 0;
static computeloop* cphvb_ve_score_compute_loops = NULL;
static cphvb_tstate* cphvb_ve_score_tstates = NULL;

static cphvb_intp block_size = 1000;

cphvb_error cphvb_ve_score_init(cphvb_component *self)
{
    myself = self;                              // Assign config container.

    char *env = getenv("CPHVB_VE_BLOCKSIZE");   // Override block_size from environment-variable.
    if(env != NULL)
    {
        block_size = atoi(env);
    }
    if(block_size <= 0)                         // Verify it
    {
        fprintf(stderr, "CPHVB_VE_BLOCKSIZE (%lld) should be greater than zero!\n", (cphvb_int64)block_size);
        return CPHVB_ERROR;
    }

    cphvb_mcache_init( 10 );
    return CPHVB_SUCCESS;
}

inline cphvb_error block_execute( cphvb_instruction* instr, cphvb_intp start, cphvb_intp end) {

    cphvb_intp i, k;

    //Make sure we have enough space
    if ((end - start + 1) > cphvb_ve_score_buffersizes)
    {
    	cphvb_intp mcount = (end - start + 1);

    	//We only work in multiples of 1000
    	if (mcount % 1000 != 0)
    		mcount = (mcount + 1000) - (mcount % 1000);

    	//Make sure we re-allocate on error
    	cphvb_ve_score_buffersizes = 0;

    	if (cphvb_ve_score_compute_loops != NULL) {
    		free(cphvb_ve_score_compute_loops);
    		free(cphvb_ve_score_tstates);
    		cphvb_ve_score_compute_loops = NULL;
    		cphvb_ve_score_tstates = NULL;
    	}

    	cphvb_ve_score_compute_loops = (computeloop*)malloc(sizeof(computeloop) * mcount);
        cphvb_ve_score_tstates = (cphvb_tstate*)malloc(sizeof(cphvb_tstate)*mcount);

    	if (cphvb_ve_score_compute_loops == NULL)
    		return CPHVB_OUT_OF_MEMORY;
    	if (cphvb_ve_score_tstates == NULL)
    		return CPHVB_OUT_OF_MEMORY;

    	cphvb_ve_score_buffersizes = mcount;
    }

    computeloop* compute_loops = cphvb_ve_score_compute_loops;
    cphvb_tstate* states = cphvb_ve_score_tstates;
    cphvb_intp  nelements, trav_end=0;

    for(i=0; i<=end-start;i++)                      // Reset traversal coordinates
        cphvb_tstate_reset( &states[i] );

    for(i=start, k=0; i <= end; i++,k++)            // Get the compute-loops
    {
        compute_loops[k] = cphvb_compute_get( &instr[i] );
    }
                                                    // Block-size split
    nelements = cphvb_nelements( instr[start].operand[0]->ndim, instr[start].operand[0]->shape );
    while(nelements>trav_end)
    {
        trav_end    += block_size;
        if (trav_end > nelements)
            trav_end = nelements;

        for(i=start, k=0; i <= end; i++, k++)
        {
            compute_loops[k]( &instr[i], &states[k], trav_end );
        }
    }

    for(i=start; i <= end; i++)                     // Set instruction status
    {
        instr[i].status = CPHVB_SUCCESS;
    }

    return CPHVB_SUCCESS;

}

cphvb_error cphvb_ve_score_execute( cphvb_intp instruction_count, cphvb_instruction* instruction_list )
{
    cphvb_intp cur_index,  j;
    cphvb_instruction *inst, *binst;

    cphvb_intp bin_start, bin_end, bin_size;
    cphvb_intp bundle_start, bundle_end, bundle_size;
    cphvb_error res;

    for(cur_index=0; cur_index < instruction_count; cur_index++)
    {
        inst = &instruction_list[cur_index];

        if(inst->status == CPHVB_SUCCESS)       // SKIP instruction
        {
            continue;
        }

        res = cphvb_mcache_malloc( inst );      // Allocate memory for operands
        if ( res != CPHVB_SUCCESS ) {
            return res;
        }

        switch(inst->opcode)                    // Dispatch instruction
        {
            case CPHVB_NONE:                    // NOOP.
            case CPHVB_DISCARD:
            case CPHVB_SYNC:
                inst->status = CPHVB_SUCCESS;
                break;

            case CPHVB_FREE:                        // Store data-pointer in malloc-cache
                inst->status = cphvb_mcache_free( inst );
                break;

            case CPHVB_USERFUNC:                // External libraries

                if(inst->userfunc->id == reduce_impl_id)
                {
                    inst->status = reduce_impl(inst->userfunc, NULL);
                }
                else if(inst->userfunc->id == random_impl_id)
                {
                    inst->status = random_impl(inst->userfunc, NULL);
                }
                else if(inst->userfunc->id == matmul_impl_id)
                {
                    inst->status = matmul_impl(inst->userfunc, NULL);
                }
                else                            // Unsupported userfunc
                {
                    inst->status = CPHVB_USERFUNC_NOT_SUPPORTED;
                }

                break;

            default:                                            // Built-in operations
                                                                // -={[ BINNING ]}=-
                bin_start   = cur_index;                        // Count built-ins and their start/end indexes and allocate memory for them.
                bin_end     = cur_index;
                for(j=bin_start+1; j<instruction_count; j++)
                {
                    binst = &instruction_list[j];               // EXIT: Stop if instruction is NOT built-in
                    if ((binst->opcode == CPHVB_NONE) || \
                        (binst->opcode == CPHVB_DISCARD) || \
                        (binst->opcode == CPHVB_SYNC) || \
                        (binst->opcode == CPHVB_USERFUNC) || \
                        (binst->opcode == CPHVB_FREE) ) {
                        break;
                    }

                    bin_end++;                                  // The "end" index
                    res = cphvb_mcache_malloc( binst );         // Allocate memory for operands
                    if ( res != CPHVB_SUCCESS ) {
                        return res;
                    }

                }
                bin_size = bin_end - bin_start +1;              // The counting part

                                                                // -={[ BUNDLING ]}=-
                bundle_size     = (bin_size > 1) ? cphvb_inst_bundle( instruction_list, bin_start, bin_end ) : 1;
                bundle_start    = bin_start;
                bundle_end      = bundle_start + bundle_size-1;

                block_execute( instruction_list, bundle_start, bundle_end );
                cur_index += bundle_size-1;
        }

        if (inst->status != CPHVB_SUCCESS)    // Instruction failed
        {
            break;
        }

    }

    if (cur_index == instruction_count) {
        return CPHVB_SUCCESS;
    } else {
        return CPHVB_PARTIAL_SUCCESS;
    }

}

cphvb_error cphvb_ve_score_shutdown( void )
{
    cphvb_mcache_clear();
    cphvb_mcache_delete();

    return CPHVB_SUCCESS;
}

cphvb_error cphvb_ve_score_reg_func(char *fun, cphvb_intp *id) {

    if(strcmp("cphvb_reduce", fun) == 0)
    {
    	if (reduce_impl == NULL)
    	{
			cphvb_component_get_func(myself, fun, &reduce_impl);
			if (reduce_impl == NULL)
				return CPHVB_USERFUNC_NOT_SUPPORTED;

			reduce_impl_id = *id;
			return CPHVB_SUCCESS;
        }
        else
        {
        	*id = reduce_impl_id;
        	return CPHVB_SUCCESS;
        }
    }
    else if(strcmp("cphvb_random", fun) == 0)
    {
    	if (random_impl == NULL)
    	{
			cphvb_component_get_func(myself, fun, &random_impl);
			if (random_impl == NULL)
				return CPHVB_USERFUNC_NOT_SUPPORTED;

			random_impl_id = *id;
			return CPHVB_SUCCESS;
        }
        else
        {
        	*id = random_impl_id;
        	return CPHVB_SUCCESS;
        }
    }
    else if(strcmp("cphvb_matmul", fun) == 0)
    {
    	if (matmul_impl == NULL)
    	{
			cphvb_component_get_func(myself, fun, &matmul_impl);
			if (matmul_impl == NULL)
				return CPHVB_USERFUNC_NOT_SUPPORTED;

			matmul_impl_id = *id;
			return CPHVB_SUCCESS;
        }
        else
        {
        	*id = matmul_impl_id;
        	return CPHVB_SUCCESS;
        }
    }

    return CPHVB_USERFUNC_NOT_SUPPORTED;
}

cphvb_error cphvb_reduce( cphvb_userfunc *arg, void* ve_arg)
{
    return cphvb_compute_reduce( arg, ve_arg );
}

cphvb_error cphvb_random( cphvb_userfunc *arg, void* ve_arg)
{
    return cphvb_compute_random( arg, ve_arg );
}

cphvb_error cphvb_matmul( cphvb_userfunc *arg, void* ve_arg)
{
    return cphvb_compute_matmul( arg, ve_arg );

}
<|endoftext|>


<commit_before>/*
This file is part of cphVB and copyright (c) 2012 the cphVB team:
http://cphvb.bitbucket.org

cphVB is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.

cphVB 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 General Public License for more details.

You should have received a copy of the
GNU Lesser General Public License along with cphVB.

If not, see <http://www.gnu.org/licenses/>.
*/

#include <cassert>
#include <cstring>
#include <iostream>
#include <cphvb.h>

#include "cphvb_vem_node.h"

//Function pointers to the VE.
static cphvb_init ve_init;
static cphvb_execute ve_execute;
static cphvb_shutdown ve_shutdown;
static cphvb_reg_func ve_reg_func;

//The VE components
static cphvb_component **vem_node_components;

//Our self
static cphvb_component *vem_node_myself;

//Number of user-defined functions registered.
static cphvb_intp vem_userfunc_count = 0;

/* Initialize the VEM
 *
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_init(cphvb_component *self)
{
    cphvb_intp children_count;
    cphvb_error err;
    vem_node_myself = self;

    err = cphvb_component_children(self, &children_count, &vem_node_components);
    if (children_count != 1)
    {
		std::cerr << "Unexpected number of child nodes for VEM, must be 1" << std::endl;
		return CPHVB_ERROR;
    }

    if (err != CPHVB_SUCCESS)
	    return err;

    ve_init = vem_node_components[0]->init;
    ve_execute = vem_node_components[0]->execute;
    ve_shutdown = vem_node_components[0]->shutdown;
    ve_reg_func = vem_node_components[0]->reg_func;

    //Let us initiate the simple VE and register what it supports.
    if((err = ve_init(vem_node_components[0])) != 0)
        return err;

    return CPHVB_SUCCESS;
}

/* Shutdown the VEM, which include a instruction flush
 *
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_shutdown(void)
{
    cphvb_error err;
    err = ve_shutdown();
    cphvb_component_free(vem_node_components[0]);//Only got one child.
    ve_init     = NULL;
    ve_execute  = NULL;
    ve_shutdown = NULL;
    ve_reg_func = NULL;
    cphvb_component_free_ptr(vem_node_components);
    vem_node_components = NULL;
    return err;
}

/* Register a new user-defined function.
 *
 * @lib Name of the shared library e.g. libmyfunc.so
 *      When NULL the default library is used.
 * @fun Name of the function e.g. myfunc
 * @id Identifier for the new function. The bridge should set the
 *     initial value to Zero. (in/out-put)
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_reg_func(char *fun, cphvb_intp *id)
{
	cphvb_error e;
	cphvb_intp tmpid;

    if(*id == 0)//Only if parent didn't set the ID.
        tmpid = vem_userfunc_count + 1;

    e = ve_reg_func(fun, &tmpid);

    //If the call succeeded, register the id as taken and return it
    if (e == CPHVB_SUCCESS)
    {
	    if (tmpid > vem_userfunc_count)
	    	vem_userfunc_count = tmpid;
    	*id = tmpid;
    }

    return e;
}

/* Execute a list of instructions (blocking, for the time being).
 * It is required that the VEM supports all instructions in the list.
 *
 * @instruction A list of instructions to execute
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_execute(cphvb_intp count,
                                   cphvb_instruction inst_list[])
{
    if (count <= 0)
        return CPHVB_SUCCESS;

    #ifdef CPHVB_TRACE
        cphvb_intp i;
        for(i=0; i<count; ++i)
        {
            cphvb_instruction* inst = &inst_list[i];
            cphvb_component_trace_inst(vem_node_myself, inst);
        }
    #endif

    return ve_execute(count, inst_list);
}
<commit_msg>minor cleanup of cphvb_vem_node_reg_func()<commit_after>/*
This file is part of cphVB and copyright (c) 2012 the cphVB team:
http://cphvb.bitbucket.org

cphVB is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.

cphVB 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 General Public License for more details.

You should have received a copy of the
GNU Lesser General Public License along with cphVB.

If not, see <http://www.gnu.org/licenses/>.
*/

#include <cassert>
#include <cstring>
#include <iostream>
#include <cphvb.h>

#include "cphvb_vem_node.h"

//Function pointers to the VE.
static cphvb_init ve_init;
static cphvb_execute ve_execute;
static cphvb_shutdown ve_shutdown;
static cphvb_reg_func ve_reg_func;

//The VE components
static cphvb_component **vem_node_components;

//Our self
static cphvb_component *vem_node_myself;

//Number of user-defined functions registered.
static cphvb_intp vem_userfunc_count = 0;

/* Initialize the VEM
 *
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_init(cphvb_component *self)
{
    cphvb_intp children_count;
    cphvb_error err;
    vem_node_myself = self;

    err = cphvb_component_children(self, &children_count, &vem_node_components);
    if (children_count != 1)
    {
		std::cerr << "Unexpected number of child nodes for VEM, must be 1" << std::endl;
		return CPHVB_ERROR;
    }

    if (err != CPHVB_SUCCESS)
	    return err;

    ve_init = vem_node_components[0]->init;
    ve_execute = vem_node_components[0]->execute;
    ve_shutdown = vem_node_components[0]->shutdown;
    ve_reg_func = vem_node_components[0]->reg_func;

    //Let us initiate the simple VE and register what it supports.
    if((err = ve_init(vem_node_components[0])) != 0)
        return err;

    return CPHVB_SUCCESS;
}

/* Shutdown the VEM, which include a instruction flush
 *
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_shutdown(void)
{
    cphvb_error err;
    err = ve_shutdown();
    cphvb_component_free(vem_node_components[0]);//Only got one child.
    ve_init     = NULL;
    ve_execute  = NULL;
    ve_shutdown = NULL;
    ve_reg_func = NULL;
    cphvb_component_free_ptr(vem_node_components);
    vem_node_components = NULL;
    return err;
}

/* Register a new user-defined function.
 *
 * @lib Name of the shared library e.g. libmyfunc.so
 *      When NULL the default library is used.
 * @fun Name of the function e.g. myfunc
 * @id Identifier for the new function. The bridge should set the
 *     initial value to Zero. (in/out-put)
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_reg_func(char *fun, cphvb_intp *id)
{
	cphvb_error e;

    if(*id == 0)//Only if parent didn't set the ID.
        *id = ++vem_userfunc_count;

    if((e = ve_reg_func(fun, id)) != CPHVB_SUCCESS)
    {
        *id = 0;
        return e;
    }
    return e;
}

/* Execute a list of instructions (blocking, for the time being).
 * It is required that the VEM supports all instructions in the list.
 *
 * @instruction A list of instructions to execute
 * @return Error codes (CPHVB_SUCCESS)
 */
cphvb_error cphvb_vem_node_execute(cphvb_intp count,
                                   cphvb_instruction inst_list[])
{
    if (count <= 0)
        return CPHVB_SUCCESS;

    #ifdef CPHVB_TRACE
        cphvb_intp i;
        for(i=0; i<count; ++i)
        {
            cphvb_instruction* inst = &inst_list[i];
            cphvb_component_trace_inst(vem_node_myself, inst);
        }
    #endif

    return ve_execute(count, inst_list);
}
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "OgreArchive.h"
#include "OgreException.h"

namespace Ogre {
    //---------------------------------------------------------------------
    DataStreamPtr Archive::create(const String&) const
    {
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
                    "This archive does not support creation of files.",
                    "Archive::create");
    }
    //---------------------------------------------------------------------
    void Archive::remove(const String&) const
    {
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
                    "This archive does not support removal of files.",
                    "Archive::remove");
    }
    //---------------------------------------------------------------------
}
<commit_msg>fixed PCH issue caused by new OgreArchive.cpp file (OGRE-433)<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "OgreStableHeaders.h"

#include "OgreArchive.h"
#include "OgreException.h"

namespace Ogre {
    //---------------------------------------------------------------------
    DataStreamPtr Archive::create(const String&) const
    {
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
                    "This archive does not support creation of files.",
                    "Archive::create");
    }
    //---------------------------------------------------------------------
    void Archive::remove(const String&) const
    {
        OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED,
                    "This archive does not support removal of files.",
                    "Archive::remove");
    }
    //---------------------------------------------------------------------
}
<|endoftext|>