<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SwXTextDefaults.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 03:41:33 $
 *
 *  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 _SW_XTEXT_DEFAULTS_HXX
#define _SW_XTEXT_DEFAULTS_HXX

#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_
#include <com/sun/star/beans/XPropertyState.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _SFX_ITEMPROP_HXX
#include <svtools/itemprop.hxx>
#endif

class SwXTextDefaults :  public cppu::WeakImplHelper3
                        <
                            com::sun::star::beans::XPropertyState,
                            com::sun::star::beans::XPropertySet,
                            com::sun::star::lang::XServiceInfo
                        >
{
    SfxItemPropertySet  aPropSet;
    SwDoc * pDoc;
public:
    SwXTextDefaults ( SwDoc * pNewDoc );
    ~SwXTextDefaults ();

    // XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  )
        throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Any& aValue )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& rPropertyName )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XPropertyState
    virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& rPropertyName )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState > SAL_CALL getPropertyStates( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& rPropertyNames )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& rPropertyName )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& rPropertyName )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw (::com::sun::star::uno::RuntimeException);
};
#endif
<commit_msg>INTEGRATION: CWS writercorehandoff (1.2.1284); FILE MERGED 2005/09/13 13:47:03 tra 1.2.1284.2: RESYNC: (1.2-1.3); FILE MERGED 2005/07/13 13:24:23 fme 1.2.1284.1: #i50348# Make SwDoc accessible via interfaces<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SwXTextDefaults.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-08-14 16:17:15 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SW_XTEXT_DEFAULTS_HXX
#define _SW_XTEXT_DEFAULTS_HXX
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_
#include <com/sun/star/beans/XPropertyState.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _SFX_ITEMPROP_HXX
#include <svtools/itemprop.hxx>
#endif

class SwDoc;

class SwXTextDefaults :  public cppu::WeakImplHelper3
                        <
                            com::sun::star::beans::XPropertyState,
                            com::sun::star::beans::XPropertySet,
                            com::sun::star::lang::XServiceInfo
                        >
{
    SfxItemPropertySet  aPropSet;
    SwDoc * pDoc;
public:
    SwXTextDefaults ( SwDoc * pNewDoc );
    ~SwXTextDefaults ();

    // XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  )
        throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Any& aValue )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& rPropertyName )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& rPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XPropertyState
    virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& rPropertyName )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState > SAL_CALL getPropertyStates( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& rPropertyNames )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& rPropertyName )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& rPropertyName )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw (::com::sun::star::uno::RuntimeException);
};
#endif
<|endoftext|>


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

#ifdef PRECOMPILED
#include "core_pch.hxx"
#endif

#pragma hdrstop

#ifndef _UNOEVTLSTNR_HXX
#include <unoevtlstnr.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _COM_SUN_STAR_LANG_EVENTOBJECT_HPP_
#include <com/sun/star/lang/EventObject.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif

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

/* -----------------22.04.99 11:24-------------------
 *
 * --------------------------------------------------*/
SV_IMPL_PTRARR(SwEvtLstnrArray, XEventListenerPtr);

/*-- 22.04.99 11:24:59---------------------------------------------------

  -----------------------------------------------------------------------*/
SwEventListenerContainer::SwEventListenerContainer( uno::XInterface* pxParent) :
    pListenerArr(0),
    pxParent(pxParent)
{
}
/*-- 22.04.99 11:24:59---------------------------------------------------

  -----------------------------------------------------------------------*/
SwEventListenerContainer::~SwEventListenerContainer()
{
    if(pListenerArr && pListenerArr->Count())
    {
        pListenerArr->DeleteAndDestroy(0, pListenerArr->Count());
    }
    delete pListenerArr;
}
/*-- 22.04.99 11:24:59---------------------------------------------------

  -----------------------------------------------------------------------*/
void    SwEventListenerContainer::AddListener(const uno::Reference< lang::XEventListener > & rxListener)
{
    if(!pListenerArr)
        pListenerArr = new SwEvtLstnrArray;
    uno::Reference< lang::XEventListener > * pInsert = new uno::Reference< lang::XEventListener > ;
    *pInsert = rxListener;
    pListenerArr->Insert(pInsert, pListenerArr->Count());
}
/*-- 22.04.99 11:25:00---------------------------------------------------

  -----------------------------------------------------------------------*/
sal_Bool    SwEventListenerContainer::RemoveListener(const uno::Reference< lang::XEventListener > & rxListener)
{
    if(!pListenerArr)
        return sal_False;
    else
    {
         lang::XEventListener* pLeft = rxListener.get();
        for(sal_uInt16 i = 0; i < pListenerArr->Count(); i++)
        {
            XEventListenerPtr pElem = pListenerArr->GetObject(i);
             lang::XEventListener* pRight = pElem->get();
            if(pLeft == pRight)
            {
                pListenerArr->Remove(i);
                delete pElem;
                return sal_True;
            }
        }
    }
    return sal_False;
}
/*-- 22.04.99 11:25:00---------------------------------------------------

  -----------------------------------------------------------------------*/
void    SwEventListenerContainer::Disposing()
{
    if(!pListenerArr)
        return;

    lang::EventObject aObj(pxParent);
    for(sal_uInt16 i = 0; i < pListenerArr->Count(); i++)
    {
        XEventListenerPtr pElem = pListenerArr->GetObject(i);
        (*pElem)->disposing(aObj);
    }
    pListenerArr->DeleteAndDestroy(0, pListenerArr->Count());
}

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

#pragma hdrstop

#ifndef _UNOEVTLSTNR_HXX
#include <unoevtlstnr.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _COM_SUN_STAR_LANG_EVENTOBJECT_HPP_
#include <com/sun/star/lang/EventObject.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif

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

/* -----------------22.04.99 11:24-------------------
 *
 * --------------------------------------------------*/
SV_IMPL_PTRARR(SwEvtLstnrArray, XEventListenerPtr);

/*-- 22.04.99 11:24:59---------------------------------------------------

  -----------------------------------------------------------------------*/
SwEventListenerContainer::SwEventListenerContainer( uno::XInterface* pxParent) :
    pListenerArr(0),
    pxParent(pxParent)
{
}
/*-- 22.04.99 11:24:59---------------------------------------------------

  -----------------------------------------------------------------------*/
SwEventListenerContainer::~SwEventListenerContainer()
{
    if(pListenerArr && pListenerArr->Count())
    {
        pListenerArr->DeleteAndDestroy(0, pListenerArr->Count());
    }
    delete pListenerArr;
}
/*-- 22.04.99 11:24:59---------------------------------------------------

  -----------------------------------------------------------------------*/
void    SwEventListenerContainer::AddListener(const uno::Reference< lang::XEventListener > & rxListener)
{
    if(!pListenerArr)
        pListenerArr = new SwEvtLstnrArray;
    uno::Reference< lang::XEventListener > * pInsert = new uno::Reference< lang::XEventListener > ;
    *pInsert = rxListener;
    pListenerArr->Insert(pInsert, pListenerArr->Count());
}
/*-- 22.04.99 11:25:00---------------------------------------------------

  -----------------------------------------------------------------------*/
sal_Bool    SwEventListenerContainer::RemoveListener(const uno::Reference< lang::XEventListener > & rxListener)
{
    if(!pListenerArr)
        return sal_False;
    else
    {
         lang::XEventListener* pLeft = rxListener.get();
        for(sal_uInt16 i = 0; i < pListenerArr->Count(); i++)
        {
            XEventListenerPtr pElem = pListenerArr->GetObject(i);
             lang::XEventListener* pRight = pElem->get();
            if(pLeft == pRight)
            {
                pListenerArr->Remove(i);
                delete pElem;
                return sal_True;
            }
        }
    }
    return sal_False;
}
/*-- 22.04.99 11:25:00---------------------------------------------------

  -----------------------------------------------------------------------*/
void    SwEventListenerContainer::Disposing()
{
    if(!pListenerArr)
        return;

    lang::EventObject aObj(pxParent);
    for(sal_uInt16 i = 0; i < pListenerArr->Count(); i++)
    {
        XEventListenerPtr pElem = pListenerArr->GetObject(i);
        (*pElem)->disposing(aObj);
    }
    pListenerArr->DeleteAndDestroy(0, pListenerArr->Count());
}

<|endoftext|>


<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld

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 <iconv.h>
#include <errno.h>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include "flusspferd/binary.hpp"
#include "flusspferd/encodings.hpp"
#include "flusspferd/create.hpp"

using namespace boost;
using namespace flusspferd;

void flusspferd::load_encodings_module(object container) {
  object exports = container.get_property_object("exports");

  // Load the binary module
  global().call("require", "binary");

  create_native_function(
    exports,
    "convertToString", &encodings::convert_to_string);

  create_native_function(
    exports,
    "convertFromString", &encodings::convert_from_string);

  create_native_function( exports, "convert", &encodings::convert);
}

// HELPER METHODS

// Actually do the conversion.
binary::vector_type do_convert(iconv_t conv, binary::element_type const* data,
                               size_t bytes);

// call iconv_open, or throw an error if it cant
iconv_t open_convert(std::string const &from, std::string const &to);

// If no direct conversion is possible, do it via utf8. Helper method
object convert_via_utf8(std::string toEnc, std::string fromEnc,
                        binary const &source);

static const char16_t b1 = *(char16_t*)"\xff\xfe",
                      b2 = 0xfffe;

static const char * native_charset = b1 == b2
                                   ? "utf-16be"
                                   : "utf-16le";

string
encodings::convert_to_string(std::string &enc, binary &source_binary) {

  // TODO: We probably need to strip an BOMs from the output (for all paths)
  binary::vector_type const &source = source_binary.get_const_data();

  to_lower(enc);
  if (enc == "utf-8") {
    binary::vector_type const &source = source_binary.get_const_data();
    return string( (char*)&source[0], source.size());
  }
  else if (enc == native_charset ) {
    // TODO: Assert on the possible alignment issue here
    binary::vector_type const &source = source_binary.get_const_data();
    return string( reinterpret_cast<char16_t const*>(&source[0]), source.size()/2);
  }
  else {
    // Not UTF-8 or UTF-16, so convert to utf-16
    iconv_t conv = open_convert(enc, native_charset);
    binary::vector_type utf16 = do_convert(conv, &source[0], source.size());
    iconv_close(conv);
    return string(reinterpret_cast<char16_t const*>(&utf16[0]), utf16.size()/2);
  }
  return string();
}

object
encodings::convert_from_string(std::string &enc, string const str) {
  binary::vector_type source;

  iconv_t conv = open_convert(native_charset, enc);
  const unsigned char *char_data = (const unsigned char*)str.data();

  binary::vector_type const &out = do_convert(conv, char_data, str.length()*2);
  iconv_close(conv);
  return create_native_object<byte_string>(object(), &out[0], out.size());
}

object encodings::convert(std::string &from, std::string &to,
    binary &source_binary)
{
  binary::vector_type const &source = source_binary.get_const_data();

  to_lower(from);
  to_lower(to);
  if ( from == to ) {
    // Encodings are the same, just return a copy of the binary
    return create_native_object<byte_string>(
      object(),
      &source[0],
      source.size()
    );
  }

  iconv_t conv = open_convert(from, to);

  binary::vector_type buf = do_convert(conv, &source[0], source.size());
  iconv_close(conv);
  return create_native_object<byte_string>(object(), &buf[0], buf.size());
}
// End JS methods

binary::vector_type
do_convert(iconv_t conv, binary::element_type const* data, size_t num_bytes) {
  binary::vector_type outbuf;

  size_t out_left,
         in_left = num_bytes;

  // Wikipedia says this:
  //   The chance of a random string of bytes being valid UTF-8 and not pure
  //   ASCII is 3.9% for a two-byte sequence, 0.41% for a three-byte sequence
  //   and 0.026% for a four-byte sequence.
  out_left = in_left + in_left/16 + 32; // GPSEE's Wild-assed guess.

  outbuf.resize(out_left);

  const unsigned char *inbytes  = data,
                      *outbytes = &outbuf[0];

  while (in_left) {
    size_t n = iconv(conv,
                     (char**)&inbytes, &in_left,
                     (char**)&outbytes, &out_left
                    );

    if (n == (size_t)(-1)) {
      switch (errno) {
        case E2BIG: {
          // Not enough space in output
          // Use GPSEE's WAG again. +32 assumes no encoding needs more than 32
          // bytes(!) per character. Probably a safe bet.
          size_t new_size = in_left + in_left/4 + 32,
                 old_size = outbytes - &outbuf[0];

          outbuf.resize(old_size + new_size);

          // The vector has probably realloced, so recalculate outbytes
          outbytes =  &outbuf[old_size];
          out_left += new_size;

          continue;
        }

        case EILSEQ:
          // An invalid multibyte sequence has been encountered in the input.
        case EINVAL:
          // An incomplete multibyte sequence has been encountered in the input.

          // Since we have provided the entire input, both these cases are the
          // same.
          size_t when = inbytes - data;
          std::stringstream ss;
          ss << "Convert Error: Invalid or incomplete multibyte"
                " sequence after " << when
             << (when == 1 ? " byte" : " bytes");
          throw flusspferd::exception(ss.str().c_str(), "TypeError");
          break;
      }
    }

    // Else all chars got converted
    in_left -= n;
  }
  outbuf.resize(outbytes - &outbuf[0]);
  return outbuf;
}

iconv_t open_convert(std::string const &from, std::string const &to) {
  iconv_t conv = iconv_open(to.c_str(), from.c_str());

  if (conv == (iconv_t)(-1)) {
    std::stringstream ss;
    ss << "Unable to convert from \"" << from
       << "\" to \"" << to << "\"";
    throw flusspferd::exception(ss.str().c_str());
  }
  return conv;
}

object
convert_via_utf8(std::string const &to, std::string const &from,
                 binary const &) {
  iconv_t to_utf   = iconv_open("utf-8", from.c_str()),
          from_utf = iconv_open(to.c_str(), "utf-8");

  if (to_utf == (iconv_t)(-1) || from_utf == (iconv_t)(-1)) {

    if (to_utf)
      iconv_close(to_utf);
    if (from_utf)
      iconv_close(from_utf);

    std::stringstream ss;
    ss << "Unable to convert from \"" << from
       << "\" to \"" << to << "\"";
    throw flusspferd::exception(ss.str().c_str());
  }
  return object();
}
<commit_msg>core/encodings: make constants actually constant<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld

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 <iconv.h>
#include <errno.h>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include "flusspferd/binary.hpp"
#include "flusspferd/encodings.hpp"
#include "flusspferd/create.hpp"

using namespace boost;
using namespace flusspferd;

void flusspferd::load_encodings_module(object container) {
  object exports = container.get_property_object("exports");

  // Load the binary module
  global().call("require", "binary");

  create_native_function(
    exports,
    "convertToString", &encodings::convert_to_string);

  create_native_function(
    exports,
    "convertFromString", &encodings::convert_from_string);

  create_native_function( exports, "convert", &encodings::convert);
}

// HELPER METHODS

// Actually do the conversion.
binary::vector_type do_convert(iconv_t conv, binary::element_type const* data,
                               size_t bytes);

// call iconv_open, or throw an error if it cant
iconv_t open_convert(std::string const &from, std::string const &to);

// If no direct conversion is possible, do it via utf8. Helper method
object convert_via_utf8(std::string toEnc, std::string fromEnc,
                        binary const &source);

static char16_t const b1 = *(char16_t*)"\xff\xfe";
static char16_t const b2 = 0xfffe;

static char const * const native_charset = b1 == b2 ? "utf-16be" : "utf-16le";

string
encodings::convert_to_string(std::string &enc, binary &source_binary) {

  // TODO: We probably need to strip an BOMs from the output (for all paths)
  binary::vector_type const &source = source_binary.get_const_data();

  to_lower(enc);
  if (enc == "utf-8") {
    binary::vector_type const &source = source_binary.get_const_data();
    return string( (char*)&source[0], source.size());
  }
  else if (enc == native_charset ) {
    // TODO: Assert on the possible alignment issue here
    binary::vector_type const &source = source_binary.get_const_data();
    return string( reinterpret_cast<char16_t const*>(&source[0]), source.size()/2);
  }
  else {
    // Not UTF-8 or UTF-16, so convert to utf-16
    iconv_t conv = open_convert(enc, native_charset);
    binary::vector_type utf16 = do_convert(conv, &source[0], source.size());
    iconv_close(conv);
    return string(reinterpret_cast<char16_t const*>(&utf16[0]), utf16.size()/2);
  }
  return string();
}

object
encodings::convert_from_string(std::string &enc, string const str) {
  binary::vector_type source;

  iconv_t conv = open_convert(native_charset, enc);
  const unsigned char *char_data = (const unsigned char*)str.data();

  binary::vector_type const &out = do_convert(conv, char_data, str.length()*2);
  iconv_close(conv);
  return create_native_object<byte_string>(object(), &out[0], out.size());
}

object encodings::convert(std::string &from, std::string &to,
    binary &source_binary)
{
  binary::vector_type const &source = source_binary.get_const_data();

  to_lower(from);
  to_lower(to);
  if ( from == to ) {
    // Encodings are the same, just return a copy of the binary
    return create_native_object<byte_string>(
      object(),
      &source[0],
      source.size()
    );
  }

  iconv_t conv = open_convert(from, to);

  binary::vector_type buf = do_convert(conv, &source[0], source.size());
  iconv_close(conv);
  return create_native_object<byte_string>(object(), &buf[0], buf.size());
}
// End JS methods

binary::vector_type
do_convert(iconv_t conv, binary::element_type const* data, size_t num_bytes) {
  binary::vector_type outbuf;

  size_t out_left,
         in_left = num_bytes;

  // Wikipedia says this:
  //   The chance of a random string of bytes being valid UTF-8 and not pure
  //   ASCII is 3.9% for a two-byte sequence, 0.41% for a three-byte sequence
  //   and 0.026% for a four-byte sequence.
  out_left = in_left + in_left/16 + 32; // GPSEE's Wild-assed guess.

  outbuf.resize(out_left);

  const unsigned char *inbytes  = data,
                      *outbytes = &outbuf[0];

  while (in_left) {
    size_t n = iconv(conv,
                     (char**)&inbytes, &in_left,
                     (char**)&outbytes, &out_left
                    );

    if (n == (size_t)(-1)) {
      switch (errno) {
        case E2BIG: {
          // Not enough space in output
          // Use GPSEE's WAG again. +32 assumes no encoding needs more than 32
          // bytes(!) per character. Probably a safe bet.
          size_t new_size = in_left + in_left/4 + 32,
                 old_size = outbytes - &outbuf[0];

          outbuf.resize(old_size + new_size);

          // The vector has probably realloced, so recalculate outbytes
          outbytes =  &outbuf[old_size];
          out_left += new_size;

          continue;
        }

        case EILSEQ:
          // An invalid multibyte sequence has been encountered in the input.
        case EINVAL:
          // An incomplete multibyte sequence has been encountered in the input.

          // Since we have provided the entire input, both these cases are the
          // same.
          size_t when = inbytes - data;
          std::stringstream ss;
          ss << "Convert Error: Invalid or incomplete multibyte"
                " sequence after " << when
             << (when == 1 ? " byte" : " bytes");
          throw flusspferd::exception(ss.str().c_str(), "TypeError");
          break;
      }
    }

    // Else all chars got converted
    in_left -= n;
  }
  outbuf.resize(outbytes - &outbuf[0]);
  return outbuf;
}

iconv_t open_convert(std::string const &from, std::string const &to) {
  iconv_t conv = iconv_open(to.c_str(), from.c_str());

  if (conv == (iconv_t)(-1)) {
    std::stringstream ss;
    ss << "Unable to convert from \"" << from
       << "\" to \"" << to << "\"";
    throw flusspferd::exception(ss.str().c_str());
  }
  return conv;
}

object
convert_via_utf8(std::string const &to, std::string const &from,
                 binary const &) {
  iconv_t to_utf   = iconv_open("utf-8", from.c_str()),
          from_utf = iconv_open(to.c_str(), "utf-8");

  if (to_utf == (iconv_t)(-1) || from_utf == (iconv_t)(-1)) {

    if (to_utf)
      iconv_close(to_utf);
    if (from_utf)
      iconv_close(from_utf);

    std::stringstream ss;
    ss << "Unable to convert from \"" << from
       << "\" to \"" << to << "\"";
    throw flusspferd::exception(ss.str().c_str());
  }
  return object();
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2009 Yahoo! Inc.  All rights reserved.  The copyrights
embodied in the content of this file are licensed under the BSD
(revised) open source license
 */
#include <stdio.h>
#include <float.h>

#include "cache.h"
#include "io.h"
#include "parse_regressor.h"
#include "parser.h"
#include "parse_args.h"
#include "sender.h"
#include "network.h"

const float default_decay = 1. / sqrt(2.);

po::variables_map parse_args(int argc, char *argv[], boost::program_options::options_description& desc,
			     gd_vars& vars, float& eta_decay_rate,
			     size_t &passes, regressor &r, parser* par,
			     string& final_regressor_name)
{
  vars.init();
  global.program_name = argv[0];
  // Declare the supported options.
  desc.add_options()
    ("audit,a", "print weights of features")
    ("bit_precision,b", po::value<size_t>(),
     "number of bits in the feature table")
    ("cache,c", "Use a cache.  The default is <data>.cache")
    ("cache_file", po::value< vector<string> >(), "The location(s) of cache_file.")
    ("data,d", po::value< string >()->default_value(""), "Example Set")
    ("daemon", "read data from port 39523")
    ("decay_learning_rate",    po::value<float>(&eta_decay_rate)->default_value(default_decay),
     "Set Decay factor for learning_rate between passes")
    ("final_regressor,f", po::value< string >(), "Final regressor")
    ("help,h","Output Arguments")
    ("initial_regressor,i", po::value< vector<string> >(), "Initial regressor(s)")
    ("initial_t", po::value<float>(&vars.t)->default_value(1.), "initial t value")
    ("min_prediction", po::value<double>(&global.min_label), "Smallest prediction to output")
    ("max_prediction", po::value<double>(&global.max_label), "Largest prediction to output")
    ("multisource", po::value<size_t>(), "multiple sources for daemon input")
    ("noop","do no learning")
    ("port", po::value<size_t>(),"port to listen on")
    ("power_t", po::value<float>(&vars.power_t)->default_value(0.), "t power value")
    ("predictto", po::value< string > (), "host to send predictions to")
    ("learning_rate,l", po::value<float>(&vars.eta)->default_value(0.1),
     "Set Learning Rate")
    ("passes", po::value<size_t>(&passes)->default_value(1),
     "Number of Training Passes")
    ("predictions,p", po::value< string >(), "File to output predictions to")
    ("quadratic,q", po::value< vector<string> > (),
     "Create and use quadratic features")
    ("quiet", "Don't output diagnostics")
    ("raw_predictions,r", po::value< string >(),
     "File to output unnormalized predictions to")
    ("sendto", po::value< vector<string> >(), "send example to <hosts>")
    ("testonly,t", "Ignore label information and just test")
    ("thread_bits", po::value<size_t>(&global.thread_bits)->default_value(0), "log_2 threads")
    ("loss_function", po::value<string>()->default_value("squared"), "Specify the loss function to be used, uses squared by default. Currently available ones are squared, hinge, logistic and quantile.")
    ("quantile_tau", po::value<double>()->default_value(0.5), "Parameter \\tau associated with Quantile loss. Defaults to 0.5")
    ("unique_id", po::value<size_t>(&global.unique_id)->default_value(0),"unique id used for cluster parallel")
    ("compressed", "use gzip format whenever appropriate. If a cache file is being created, this option creates a compressed cache file. A mixture of raw-text & compressed inputs are supported if this option is on");

  global.example_number = 0;
  global.weighted_examples = 0.;
  global.old_weighted_examples = 0.;
  global.weighted_labels = 0.;
  global.total_features = 0;
  global.sum_loss = 0.0;
  global.sum_loss_since_last_dump = 0.0;
  global.dump_interval = exp(1.);
  global.num_bits = 18;
  global.default_bits = true;
  global.final_prediction_sink = -1;
  global.raw_prediction = -1;
  global.local_prediction = -1;
  global.print = print_result;
  global.min_label = 0.;
  global.max_label = 1.;

  global.audit = false;
  global.reg = r;

  po::positional_options_description p;

  po::variables_map vm;

  po::store(po::command_line_parser(argc, argv).
	    options(desc).positional(p).run(), vm);
  po::notify(vm);

  if (vm.count("help") || argc == 1) {
    cerr << "\n" << desc << "\n";
    exit(1);
  }

  if (vm.count("bit_precision"))
    {
      global.default_bits = false;
      global.num_bits = vm["bit_precision"].as< size_t>();
    }

  if(vm.count("compressed")){
    set_compressed(par);
  }

  if (global.num_bits > 31) {
    cerr << "The system limits at 31 bits of precision!\n" << endl;
    exit(1);
  }
  if (vm.count("quiet"))
    global.quiet = true;
  else
    global.quiet = false;

  if (vm.count("quadratic"))
    {
      global.pairs = vm["quadratic"].as< vector<string> >();
      if (!global.quiet)
	{
	  cerr << "creating quadratic features for pairs: ";
	  for (vector<string>::iterator i = global.pairs.begin(); i != global.pairs.end();i++) {
	    cerr << *i << " ";
	    if (i->length() > 2)
	      cerr << endl << "warning, ignoring characters after the 2nd.\n";
	    if (i->length() < 2) {
	      cerr << endl << "error, quadratic features must involve two sets.\n";
	      exit(0);
	    }
	  }
	  cerr << endl;
	}
    }

  parse_regressor_args(vm, r, final_regressor_name, global.quiet);

  if (vm.count("min_prediction"))
    global.min_label = vm["min_prediction"].as<double>();
  if (vm.count("max_prediction"))
    global.max_label = vm["max_prediction"].as<double>();
  if (vm.count("min_prediction") || vm.count("max_prediction"))
    set_minmax = noop_mm;

  string loss_function;
  if(vm.count("loss_function"))
	  loss_function = vm["loss_function"].as<string>();
  else
	  loss_function = "squaredloss";

  double loss_parameter = 0.0;
  if(vm.count("quantile_tau"))
    loss_parameter = vm["quantile_tau"].as<double>();
  r.loss = getLossFunction(loss_function, loss_parameter);
  global.loss = r.loss;

  vars.eta *= pow(vars.t, vars.power_t);

  if (eta_decay_rate != default_decay && passes == 1)
    cerr << "Warning: decay_learning_rate has no effect when there is only one pass" << endl;

  if (pow(eta_decay_rate, passes) < 0.0001 )
    cerr << "Warning: the learning rate for the last pass is multiplied by: " << pow(eta_decay_rate, passes)
	 << " adjust to --decay_learning_rate larger to avoid this." << endl;

  parse_source_args(vm,par,global.quiet,passes);

  if (!global.quiet)
    {
      cerr << "Num weight bits = " << global.num_bits << endl;
      cerr << "learning rate = " << vars.eta << endl;
      cerr << "initial_t = " << vars.t << endl;
      cerr << "power_t = " << vars.power_t << endl;
      if (passes > 1)
	cerr << "decay_learning_rate = " << eta_decay_rate << endl;
    }

  if (vm.count("predictions")) {
    if (!global.quiet)
      cerr << "predictions = " <<  vm["predictions"].as< string >() << endl;
    if (strcmp(vm["predictions"].as< string >().c_str(), "stdout") == 0)
      global.final_prediction_sink = 1;//stdout
    else
      {
	const char* fstr = (vm["predictions"].as< string >().c_str());
	global.final_prediction_sink = fileno(fopen(fstr,"w"));
	if (global.final_prediction_sink < 0)
	  cerr << "Error opening the predictions file: " << fstr << endl;
      }
  }

  if (vm.count("raw_predictions")) {
    if (!global.quiet)
      cerr << "raw predictions = " <<  vm["raw_predictions"].as< string >() << endl;
    if (strcmp(vm["raw_predictions"].as< string >().c_str(), "stdout") == 0)
      global.raw_prediction = 1;//stdout
    else
      global.raw_prediction = fileno(fopen(vm["raw_predictions"].as< string >().c_str(), "w"));
  }

  if (vm.count("audit"))
    global.audit = true;

  parse_send_args(vm, global.pairs, global.thread_bits);

  if (vm.count("testonly"))
    {
      if (!global.quiet)
	cerr << "only testing" << endl;
      global.training = false;
    }
  else
    {
      global.training = true;
      if (!global.quiet)
	cerr << "learning_rate set to " << vars.eta << endl;
    }

  if (vm.count("predictto"))
    {
      if (!global.quiet)
	cerr << "predictto = " << vm["predictto"].as< string >() << endl;
      global.local_prediction = open_socket(vm["predictto"].as< string > ().c_str(), global.unique_id);
    }

  return vm;
}

<commit_msg>RF+ENH: --version  (new) and --help to print to stdout<commit_after>/*
Copyright (c) 2009 Yahoo! Inc.  All rights reserved.  The copyrights
embodied in the content of this file are licensed under the BSD
(revised) open source license
 */
#include <stdio.h>
#include <float.h>

#include "cache.h"
#include "io.h"
#include "parse_regressor.h"
#include "parser.h"
#include "parse_args.h"
#include "sender.h"
#include "network.h"
#include "global_data.h"

const float default_decay = 1. / sqrt(2.);

po::variables_map parse_args(int argc, char *argv[], boost::program_options::options_description& desc,
			     gd_vars& vars, float& eta_decay_rate,
			     size_t &passes, regressor &r, parser* par,
			     string& final_regressor_name)
{
  vars.init();
  global.program_name = argv[0];
  // Declare the supported options.
  desc.add_options()
    ("audit,a", "print weights of features")
    ("bit_precision,b", po::value<size_t>(),
     "number of bits in the feature table")
    ("cache,c", "Use a cache.  The default is <data>.cache")
    ("cache_file", po::value< vector<string> >(), "The location(s) of cache_file.")
    ("data,d", po::value< string >()->default_value(""), "Example Set")
    ("daemon", "read data from port 39523")
    ("decay_learning_rate",    po::value<float>(&eta_decay_rate)->default_value(default_decay),
     "Set Decay factor for learning_rate between passes")
    ("final_regressor,f", po::value< string >(), "Final regressor")
    ("help,h","Output Arguments")
    ("version","Version information")
    ("initial_regressor,i", po::value< vector<string> >(), "Initial regressor(s)")
    ("initial_t", po::value<float>(&vars.t)->default_value(1.), "initial t value")
    ("min_prediction", po::value<double>(&global.min_label), "Smallest prediction to output")
    ("max_prediction", po::value<double>(&global.max_label), "Largest prediction to output")
    ("multisource", po::value<size_t>(), "multiple sources for daemon input")
    ("noop","do no learning")
    ("port", po::value<size_t>(),"port to listen on")
    ("power_t", po::value<float>(&vars.power_t)->default_value(0.), "t power value")
    ("predictto", po::value< string > (), "host to send predictions to")
    ("learning_rate,l", po::value<float>(&vars.eta)->default_value(0.1),
     "Set Learning Rate")
    ("passes", po::value<size_t>(&passes)->default_value(1),
     "Number of Training Passes")
    ("predictions,p", po::value< string >(), "File to output predictions to")
    ("quadratic,q", po::value< vector<string> > (),
     "Create and use quadratic features")
    ("quiet", "Don't output diagnostics")
    ("raw_predictions,r", po::value< string >(),
     "File to output unnormalized predictions to")
    ("sendto", po::value< vector<string> >(), "send example to <hosts>")
    ("testonly,t", "Ignore label information and just test")
    ("thread_bits", po::value<size_t>(&global.thread_bits)->default_value(0), "log_2 threads")
    ("loss_function", po::value<string>()->default_value("squared"), "Specify the loss function to be used, uses squared by default. Currently available ones are squared, hinge, logistic and quantile.")
    ("quantile_tau", po::value<double>()->default_value(0.5), "Parameter \\tau associated with Quantile loss. Defaults to 0.5")
    ("unique_id", po::value<size_t>(&global.unique_id)->default_value(0),"unique id used for cluster parallel")
    ("compressed", "use gzip format whenever appropriate. If a cache file is being created, this option creates a compressed cache file. A mixture of raw-text & compressed inputs are supported if this option is on");

  global.example_number = 0;
  global.weighted_examples = 0.;
  global.old_weighted_examples = 0.;
  global.weighted_labels = 0.;
  global.total_features = 0;
  global.sum_loss = 0.0;
  global.sum_loss_since_last_dump = 0.0;
  global.dump_interval = exp(1.);
  global.num_bits = 18;
  global.default_bits = true;
  global.final_prediction_sink = -1;
  global.raw_prediction = -1;
  global.local_prediction = -1;
  global.print = print_result;
  global.min_label = 0.;
  global.max_label = 1.;

  global.audit = false;
  global.reg = r;

  po::positional_options_description p;

  po::variables_map vm;

  po::store(po::command_line_parser(argc, argv).
	    options(desc).positional(p).run(), vm);
  po::notify(vm);

  if (vm.count("help") || argc == 1) {
    /* upon direct query for help -- spit it out to stdout */
    cout << "\n" << desc << "\n";
    exit(0);
  }

  if (vm.count("version") || argc == 1) {
    /* upon direct query for version -- spit it out to stdout */
    cout << version << "\n";
    exit(0);
  }

  if (vm.count("bit_precision"))
    {
      global.default_bits = false;
      global.num_bits = vm["bit_precision"].as< size_t>();
    }

  if(vm.count("compressed")){
    set_compressed(par);
  }

  if (global.num_bits > 31) {
    cerr << "The system limits at 31 bits of precision!\n" << endl;
    exit(1);
  }
  if (vm.count("quiet"))
    global.quiet = true;
  else
    global.quiet = false;

  if (vm.count("quadratic"))
    {
      global.pairs = vm["quadratic"].as< vector<string> >();
      if (!global.quiet)
	{
	  cerr << "creating quadratic features for pairs: ";
	  for (vector<string>::iterator i = global.pairs.begin(); i != global.pairs.end();i++) {
	    cerr << *i << " ";
	    if (i->length() > 2)
	      cerr << endl << "warning, ignoring characters after the 2nd.\n";
	    if (i->length() < 2) {
	      cerr << endl << "error, quadratic features must involve two sets.\n";
	      exit(0);
	    }
	  }
	  cerr << endl;
	}
    }

  parse_regressor_args(vm, r, final_regressor_name, global.quiet);

  if (vm.count("min_prediction"))
    global.min_label = vm["min_prediction"].as<double>();
  if (vm.count("max_prediction"))
    global.max_label = vm["max_prediction"].as<double>();
  if (vm.count("min_prediction") || vm.count("max_prediction"))
    set_minmax = noop_mm;

  string loss_function;
  if(vm.count("loss_function"))
	  loss_function = vm["loss_function"].as<string>();
  else
	  loss_function = "squaredloss";

  double loss_parameter = 0.0;
  if(vm.count("quantile_tau"))
    loss_parameter = vm["quantile_tau"].as<double>();
  r.loss = getLossFunction(loss_function, loss_parameter);
  global.loss = r.loss;

  vars.eta *= pow(vars.t, vars.power_t);

  if (eta_decay_rate != default_decay && passes == 1)
    cerr << "Warning: decay_learning_rate has no effect when there is only one pass" << endl;

  if (pow(eta_decay_rate, passes) < 0.0001 )
    cerr << "Warning: the learning rate for the last pass is multiplied by: " << pow(eta_decay_rate, passes)
	 << " adjust to --decay_learning_rate larger to avoid this." << endl;

  parse_source_args(vm,par,global.quiet,passes);

  if (!global.quiet)
    {
      cerr << "Num weight bits = " << global.num_bits << endl;
      cerr << "learning rate = " << vars.eta << endl;
      cerr << "initial_t = " << vars.t << endl;
      cerr << "power_t = " << vars.power_t << endl;
      if (passes > 1)
	cerr << "decay_learning_rate = " << eta_decay_rate << endl;
    }

  if (vm.count("predictions")) {
    if (!global.quiet)
      cerr << "predictions = " <<  vm["predictions"].as< string >() << endl;
    if (strcmp(vm["predictions"].as< string >().c_str(), "stdout") == 0)
      global.final_prediction_sink = 1;//stdout
    else
      {
	const char* fstr = (vm["predictions"].as< string >().c_str());
	global.final_prediction_sink = fileno(fopen(fstr,"w"));
	if (global.final_prediction_sink < 0)
	  cerr << "Error opening the predictions file: " << fstr << endl;
      }
  }

  if (vm.count("raw_predictions")) {
    if (!global.quiet)
      cerr << "raw predictions = " <<  vm["raw_predictions"].as< string >() << endl;
    if (strcmp(vm["raw_predictions"].as< string >().c_str(), "stdout") == 0)
      global.raw_prediction = 1;//stdout
    else
      global.raw_prediction = fileno(fopen(vm["raw_predictions"].as< string >().c_str(), "w"));
  }

  if (vm.count("audit"))
    global.audit = true;

  parse_send_args(vm, global.pairs, global.thread_bits);

  if (vm.count("testonly"))
    {
      if (!global.quiet)
	cerr << "only testing" << endl;
      global.training = false;
    }
  else
    {
      global.training = true;
      if (!global.quiet)
	cerr << "learning_rate set to " << vars.eta << endl;
    }

  if (vm.count("predictto"))
    {
      if (!global.quiet)
	cerr << "predictto = " << vm["predictto"].as< string >() << endl;
      global.local_prediction = open_socket(vm["predictto"].as< string > ().c_str(), global.unique_id);
    }

  return vm;
}

<|endoftext|>


<commit_before>#include <openrave_ompl_bridge/RRTConnectParameters.h>

namespace openrave_ompl_bridge
{
  RRTConnectParameters::RRTConnectParameters() : is_processing(false)
  {
    _vXMLParameters.push_back("planning_timelimit");
    _vXMLParameters.push_back("smoothing_timelimit");

  }

  bool RRTConnectParameters::serialize(std::ostream& O, int options) const
  {
    if( !OpenRAVE::PlannerBase::PlannerParameters::serialize(O, options&~1) )
    {
      return false;
    }

    O << "<planning_timelimit>" << planning_timelimit << "</planning_timelimit>" << std::endl;
    O << "<smoothing_timelimit>" << smoothing_timelimit << "</smoothing_timelimit>" << std::endl;

    if( !(options & 1) )
    {
      O << _sExtraParameters << std::endl;
    }

    return !!O;
  }

  OpenRAVE::BaseXMLReader::ProcessElement RRTConnectParameters::startElement(const std::string& name, const OpenRAVE::AttributesList& atts)
  {
    if( is_processing )
    {
    return PE_Ignore;
    }

    switch( OpenRAVE::PlannerBase::PlannerParameters::startElement(name,atts) )
    {
      case PE_Pass: break;
      case PE_Support: return PE_Support;
      case PE_Ignore: return PE_Ignore;
    }

    is_processing = name=="planning_timelimit" || name=="smoothing_timelimit";

    return is_processing ? PE_Support : PE_Pass;
  }

  bool RRTConnectParameters::endElement(const std::string& name)
  {
    if( is_processing )
    {
      if( name == "planning_timelimit")
      {
        _ss >> planning_timelimit;
      }
      else if( name == "smoothing_timelimit")
      {
        _ss >> smoothing_timelimit;
      }
      else

      {
        RAVELOG_WARN(str(boost::format("unknown tag %s\n")%name));
      }
    is_processing = false;
    return false;
    }

    // give a chance for the default parameters to get processed
    return PlannerParameters::endElement(name);
  }

  std::vector<double> RRTConnectParameters::GetStartConfiguration()
  {
    return vinitialconfig;
  }

  std::vector<double> RRTConnectParameters::GetGoalConfiguration()
  {
    return vgoalconfig;
  }

  double RRTConnectParameters::GetPlanningTimeLimit()
  {
    return planning_timelimit;
  }

  double RRTConnectParameters::GetSmoothingTimeLimit()
  {
    return smoothing_timelimit;
  }
} /* namespace openrave_ompl_bridge */
<commit_msg>Corrected indention.<commit_after>#include <openrave_ompl_bridge/RRTConnectParameters.h>

namespace openrave_ompl_bridge
{
  RRTConnectParameters::RRTConnectParameters() : is_processing(false)
  {
    _vXMLParameters.push_back("planning_timelimit");
    _vXMLParameters.push_back("smoothing_timelimit");
  }

  bool RRTConnectParameters::serialize(std::ostream& O, int options) const
  {
    if( !OpenRAVE::PlannerBase::PlannerParameters::serialize(O, options&~1) )
    {
      return false;
    }

    O << "<planning_timelimit>" << planning_timelimit << "</planning_timelimit>" << std::endl;
    O << "<smoothing_timelimit>" << smoothing_timelimit << "</smoothing_timelimit>" << std::endl;

    if( !(options & 1) )
    {
      O << _sExtraParameters << std::endl;
    }

    return !!O;
  }

  OpenRAVE::BaseXMLReader::ProcessElement RRTConnectParameters::startElement(const std::string& name, const OpenRAVE::AttributesList& atts)
  {
    if( is_processing )
    {
    return PE_Ignore;
    }

    switch( OpenRAVE::PlannerBase::PlannerParameters::startElement(name,atts) )
    {
      case PE_Pass: break;
      case PE_Support: return PE_Support;
      case PE_Ignore: return PE_Ignore;
    }

    is_processing = name=="planning_timelimit" || name=="smoothing_timelimit";

    return is_processing ? PE_Support : PE_Pass;
  }

  bool RRTConnectParameters::endElement(const std::string& name)
  {
    if( is_processing )
    {
      if( name == "planning_timelimit")
      {
        _ss >> planning_timelimit;
      }
      else if( name == "smoothing_timelimit")
      {
        _ss >> smoothing_timelimit;
      }
      else

      {
        RAVELOG_WARN(str(boost::format("unknown tag %s\n")%name));
      }
    is_processing = false;
    return false;
    }

    // give a chance for the default parameters to get processed
    return PlannerParameters::endElement(name);
  }

  std::vector<double> RRTConnectParameters::GetStartConfiguration()
  {
    return vinitialconfig;
  }

  std::vector<double> RRTConnectParameters::GetGoalConfiguration()
  {
    return vgoalconfig;
  }

  double RRTConnectParameters::GetPlanningTimeLimit()
  {
    return planning_timelimit;
  }

  double RRTConnectParameters::GetSmoothingTimeLimit()
  {
    return smoothing_timelimit;
  }
} /* namespace openrave_ompl_bridge */
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2019 Intel Corporation                                    //
//                                                                          //
// 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 "common/Material.h"
#include "common/Data.h"
#include "texture/Texture2D.h"
#include "math/spectrum.h"
#include "Principled_ispc.h"

namespace ospray {
  namespace pathtracer {

    struct Principled : public ospray::Material
    {
      //! \brief common function to help printf-debugging
      /*! Every derived class should override this! */
      virtual std::string toString() const override
      { return "ospray::pathtracer::Principled"; }

      Principled()
      {
        ispcEquivalent = ispc::PathTracer_Principled_create();
      }

      //! \brief commit the material's parameters
      virtual void commit() override
      {
        MaterialParam3f baseColor = getMaterialParam3f("baseColor", vec3f(0.8f));
        MaterialParam3f edgeColor = getMaterialParam3f("edgeColor", vec3f(1.f));
        MaterialParam1f metallic = getMaterialParam1f("metallic", 0.f);
        MaterialParam1f diffuse = getMaterialParam1f("diffuse", 1.f);
        MaterialParam1f specular = getMaterialParam1f("specular", 1.f);
        MaterialParam1f ior = getMaterialParam1f("ior", 1.f);
        MaterialParam1f transmission = getMaterialParam1f("transmission", 0.f);
        MaterialParam3f transmissionColor = getMaterialParam3f("transmissionColor", vec3f(1.f));
        MaterialParam1f transmissionDepth = getMaterialParam1f("transmissionDepth", 1.f);
        MaterialParam1f roughness = getMaterialParam1f("roughness", 0.f);
        MaterialParam1f anisotropy = getMaterialParam1f("anisotropy", 0.f);
        MaterialParam1f rotation = getMaterialParam1f("rotation", 0.f);
        MaterialParam1f normal = getMaterialParam1f("normal", 1.f);
        MaterialParam1f baseNormal = getMaterialParam1f("baseNormal", 1.f);

        MaterialParam1f coat = getMaterialParam1f("coat", 0.f);
        MaterialParam1f coatIor = getMaterialParam1f("coatIor", 1.5f);
        MaterialParam3f coatColor = getMaterialParam3f("coatColor", vec3f(1.f));
        MaterialParam1f coatThickness = getMaterialParam1f("coatThickness", 1.f);
        MaterialParam1f coatRoughness = getMaterialParam1f("coatRoughness", 0.f);
        MaterialParam1f coatNormal = getMaterialParam1f("coatNormal", 1.f);

        MaterialParam1f sheen = getMaterialParam1f("sheen", 0.f);
        MaterialParam3f sheenColor = getMaterialParam3f("sheenColor", vec3f(1.f));
        MaterialParam1f sheenTint = getMaterialParam1f("sheenTint", 0.f);
        MaterialParam1f sheenRoughness = getMaterialParam1f("sheenRoughness", 0.2f);

        MaterialParam1f opacity = getMaterialParam1f("opacity", 1.f);

        bool thin = getParam1b("thin", false) || (getParam1f("thin", 0.f) > 0.f);
        MaterialParam1f backlight = getMaterialParam1f("backlight", 0.f);
        MaterialParam1f thickness = getMaterialParam1f("thickness", 1.f);

        float outsideIor = getParam1f("outsideIor", 1.f);
        vec3f outsideTransmissionColor = getParam3f("outsideTransmissionColor", vec3f(1.f));
        float outsideTransmissionDepth = getParam1f("outsideTransmissionDepth", 1.f);

        ispc::PathTracer_Principled_set(getIE(),
          (const ispc::vec3f&)baseColor.factor, baseColor.map ? baseColor.map->getIE() : nullptr, (const ispc::AffineSpace2f&)baseColor.xform,
          (const ispc::vec3f&)edgeColor.factor, edgeColor.map ? edgeColor.map->getIE() : nullptr, (const ispc::AffineSpace2f&)edgeColor.xform,
          metallic.factor, metallic.map ? metallic.map->getIE() : nullptr, (const ispc::AffineSpace2f&)metallic.xform,
          diffuse.factor, diffuse.map ? diffuse.map->getIE() : nullptr, (const ispc::AffineSpace2f&)diffuse.xform,
          specular.factor, specular.map ? specular.map->getIE() : nullptr, (const ispc::AffineSpace2f&)specular.xform,
          ior.factor, ior.map ? ior.map->getIE() : nullptr, (const ispc::AffineSpace2f&)ior.xform,
          transmission.factor, transmission.map ? transmission.map->getIE() : nullptr, (const ispc::AffineSpace2f&)transmission.xform,
          (const ispc::vec3f&)transmissionColor.factor, transmissionColor.map ? transmissionColor.map->getIE() : nullptr, (const ispc::AffineSpace2f&)transmissionColor.xform,
          transmissionDepth.factor, transmissionDepth.map ? transmissionDepth.map->getIE() : nullptr, (const ispc::AffineSpace2f&)transmissionDepth.xform,
          roughness.factor, roughness.map ? roughness.map->getIE() : nullptr, (const ispc::AffineSpace2f&)roughness.xform,
          anisotropy.factor, anisotropy.map ? anisotropy.map->getIE() : nullptr, (const ispc::AffineSpace2f&)anisotropy.xform,
          rotation.factor, rotation.map ? rotation.map->getIE() : nullptr, (const ispc::AffineSpace2f&)rotation.xform,
          normal.factor, normal.map ? normal.map->getIE() : nullptr, (const ispc::AffineSpace2f&)normal.xform, (const ispc::LinearSpace2f&)normal.rot,
          baseNormal.factor, baseNormal.map ? baseNormal.map->getIE() : nullptr, (const ispc::AffineSpace2f&)baseNormal.xform, (const ispc::LinearSpace2f&)baseNormal.rot,

          coat.factor, coat.map ? coat.map->getIE() : nullptr, (const ispc::AffineSpace2f&)coat.xform,
          coatIor.factor, coatIor.map ? coatIor.map->getIE() : nullptr, (const ispc::AffineSpace2f&)coatIor.xform,
          (const ispc::vec3f&)coatColor.factor, coatColor.map ? coatColor.map->getIE() : nullptr, (const ispc::AffineSpace2f&)coatColor.xform,
          coatThickness.factor, coatThickness.map ? coatThickness.map->getIE() : nullptr, (const ispc::AffineSpace2f&)coatThickness.xform,
          coatRoughness.factor, coatRoughness.map ? coatRoughness.map->getIE() : nullptr, (const ispc::AffineSpace2f&)coatRoughness.xform,
          coatNormal.factor, coatNormal.map ? coatNormal.map->getIE() : nullptr, (const ispc::AffineSpace2f&)coatNormal.xform, (const ispc::LinearSpace2f&)coatNormal.rot,

          sheen.factor, sheen.map ? sheen.map->getIE() : nullptr, (const ispc::AffineSpace2f&)sheen.xform,
          (const ispc::vec3f&)sheenColor.factor, sheenColor.map ? sheenColor.map->getIE() : nullptr, (const ispc::AffineSpace2f&)sheenColor.xform,
          sheenTint.factor, sheenTint.map ? sheenTint.map->getIE() : nullptr, (const ispc::AffineSpace2f&)sheenTint.xform,
          sheenRoughness.factor, sheenRoughness.map ? sheenRoughness.map->getIE() : nullptr, (const ispc::AffineSpace2f&)sheenRoughness.xform,

          opacity.factor, opacity.map ? opacity.map->getIE() : nullptr, (const ispc::AffineSpace2f&)opacity.xform,

          thin,
          backlight.factor, backlight.map ? backlight.map->getIE() : nullptr, (const ispc::AffineSpace2f&)backlight.xform,
          thickness.factor, thickness.map ? thickness.map->getIE() : nullptr, (const ispc::AffineSpace2f&)thickness.xform,

          outsideIor,
          (const ispc::vec3f&)outsideTransmissionColor,
          outsideTransmissionDepth);
      }
    };

    OSP_REGISTER_MATERIAL(pathtracer, Principled, Principled);
    OSP_REGISTER_MATERIAL(pt, Principled, Principled);
  }
}
<commit_msg>Principled material “thin” parameter only consumes booleans.<commit_after>// ======================================================================== //
// Copyright 2009-2019 Intel Corporation                                    //
//                                                                          //
// 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 "common/Material.h"
#include "common/Data.h"
#include "texture/Texture2D.h"
#include "math/spectrum.h"
#include "Principled_ispc.h"

namespace ospray {
  namespace pathtracer {

    struct Principled : public ospray::Material
    {
      //! \brief common function to help printf-debugging
      /*! Every derived class should override this! */
      virtual std::string toString() const override
      { return "ospray::pathtracer::Principled"; }

      Principled()
      {
        ispcEquivalent = ispc::PathTracer_Principled_create();
      }

      //! \brief commit the material's parameters
      virtual void commit() override
      {
        MaterialParam3f baseColor = getMaterialParam3f("baseColor", vec3f(0.8f));
        MaterialParam3f edgeColor = getMaterialParam3f("edgeColor", vec3f(1.f));
        MaterialParam1f metallic = getMaterialParam1f("metallic", 0.f);
        MaterialParam1f diffuse = getMaterialParam1f("diffuse", 1.f);
        MaterialParam1f specular = getMaterialParam1f("specular", 1.f);
        MaterialParam1f ior = getMaterialParam1f("ior", 1.f);
        MaterialParam1f transmission = getMaterialParam1f("transmission", 0.f);
        MaterialParam3f transmissionColor = getMaterialParam3f("transmissionColor", vec3f(1.f));
        MaterialParam1f transmissionDepth = getMaterialParam1f("transmissionDepth", 1.f);
        MaterialParam1f roughness = getMaterialParam1f("roughness", 0.f);
        MaterialParam1f anisotropy = getMaterialParam1f("anisotropy", 0.f);
        MaterialParam1f rotation = getMaterialParam1f("rotation", 0.f);
        MaterialParam1f normal = getMaterialParam1f("normal", 1.f);
        MaterialParam1f baseNormal = getMaterialParam1f("baseNormal", 1.f);

        MaterialParam1f coat = getMaterialParam1f("coat", 0.f);
        MaterialParam1f coatIor = getMaterialParam1f("coatIor", 1.5f);
        MaterialParam3f coatColor = getMaterialParam3f("coatColor", vec3f(1.f));
        MaterialParam1f coatThickness = getMaterialParam1f("coatThickness", 1.f);
        MaterialParam1f coatRoughness = getMaterialParam1f("coatRoughness", 0.f);
        MaterialParam1f coatNormal = getMaterialParam1f("coatNormal", 1.f);

        MaterialParam1f sheen = getMaterialParam1f("sheen", 0.f);
        MaterialParam3f sheenColor = getMaterialParam3f("sheenColor", vec3f(1.f));
        MaterialParam1f sheenTint = getMaterialParam1f("sheenTint", 0.f);
        MaterialParam1f sheenRoughness = getMaterialParam1f("sheenRoughness", 0.2f);

        MaterialParam1f opacity = getMaterialParam1f("opacity", 1.f);

        bool thin = getParam1b("thin", false);
        MaterialParam1f backlight = getMaterialParam1f("backlight", 0.f);
        MaterialParam1f thickness = getMaterialParam1f("thickness", 1.f);

        float outsideIor = getParam1f("outsideIor", 1.f);
        vec3f outsideTransmissionColor = getParam3f("outsideTransmissionColor", vec3f(1.f));
        float outsideTransmissionDepth = getParam1f("outsideTransmissionDepth", 1.f);

        ispc::PathTracer_Principled_set(getIE(),
          (const ispc::vec3f&)baseColor.factor, baseColor.map ? baseColor.map->getIE() : nullptr, (const ispc::AffineSpace2f&)baseColor.xform,
          (const ispc::vec3f&)edgeColor.factor, edgeColor.map ? edgeColor.map->getIE() : nullptr, (const ispc::AffineSpace2f&)edgeColor.xform,
          metallic.factor, metallic.map ? metallic.map->getIE() : nullptr, (const ispc::AffineSpace2f&)metallic.xform,
          diffuse.factor, diffuse.map ? diffuse.map->getIE() : nullptr, (const ispc::AffineSpace2f&)diffuse.xform,
          specular.factor, specular.map ? specular.map->getIE() : nullptr, (const ispc::AffineSpace2f&)specular.xform,
          ior.factor, ior.map ? ior.map->getIE() : nullptr, (const ispc::AffineSpace2f&)ior.xform,
          transmission.factor, transmission.map ? transmission.map->getIE() : nullptr, (const ispc::AffineSpace2f&)transmission.xform,
          (const ispc::vec3f&)transmissionColor.factor, transmissionColor.map ? transmissionColor.map->getIE() : nullptr, (const ispc::AffineSpace2f&)transmissionColor.xform,
          transmissionDepth.factor, transmissionDepth.map ? transmissionDepth.map->getIE() : nullptr, (const ispc::AffineSpace2f&)transmissionDepth.xform,
          roughness.factor, roughness.map ? roughness.map->getIE() : nullptr, (const ispc::AffineSpace2f&)roughness.xform,
          anisotropy.factor, anisotropy.map ? anisotropy.map->getIE() : nullptr, (const ispc::AffineSpace2f&)anisotropy.xform,
          rotation.factor, rotation.map ? rotation.map->getIE() : nullptr, (const ispc::AffineSpace2f&)rotation.xform,
          normal.factor, normal.map ? normal.map->getIE() : nullptr, (const ispc::AffineSpace2f&)normal.xform, (const ispc::LinearSpace2f&)normal.rot,
          baseNormal.factor, baseNormal.map ? baseNormal.map->getIE() : nullptr, (const ispc::AffineSpace2f&)baseNormal.xform, (const ispc::LinearSpace2f&)baseNormal.rot,

          coat.factor, coat.map ? coat.map->getIE() : nullptr, (const ispc::AffineSpace2f&)coat.xform,
          coatIor.factor, coatIor.map ? coatIor.map->getIE() : nullptr, (const ispc::AffineSpace2f&)coatIor.xform,
          (const ispc::vec3f&)coatColor.factor, coatColor.map ? coatColor.map->getIE() : nullptr, (const ispc::AffineSpace2f&)coatColor.xform,
          coatThickness.factor, coatThickness.map ? coatThickness.map->getIE() : nullptr, (const ispc::AffineSpace2f&)coatThickness.xform,
          coatRoughness.factor, coatRoughness.map ? coatRoughness.map->getIE() : nullptr, (const ispc::AffineSpace2f&)coatRoughness.xform,
          coatNormal.factor, coatNormal.map ? coatNormal.map->getIE() : nullptr, (const ispc::AffineSpace2f&)coatNormal.xform, (const ispc::LinearSpace2f&)coatNormal.rot,

          sheen.factor, sheen.map ? sheen.map->getIE() : nullptr, (const ispc::AffineSpace2f&)sheen.xform,
          (const ispc::vec3f&)sheenColor.factor, sheenColor.map ? sheenColor.map->getIE() : nullptr, (const ispc::AffineSpace2f&)sheenColor.xform,
          sheenTint.factor, sheenTint.map ? sheenTint.map->getIE() : nullptr, (const ispc::AffineSpace2f&)sheenTint.xform,
          sheenRoughness.factor, sheenRoughness.map ? sheenRoughness.map->getIE() : nullptr, (const ispc::AffineSpace2f&)sheenRoughness.xform,

          opacity.factor, opacity.map ? opacity.map->getIE() : nullptr, (const ispc::AffineSpace2f&)opacity.xform,

          thin,
          backlight.factor, backlight.map ? backlight.map->getIE() : nullptr, (const ispc::AffineSpace2f&)backlight.xform,
          thickness.factor, thickness.map ? thickness.map->getIE() : nullptr, (const ispc::AffineSpace2f&)thickness.xform,

          outsideIor,
          (const ispc::vec3f&)outsideTransmissionColor,
          outsideTransmissionDepth);
      }
    };

    OSP_REGISTER_MATERIAL(pathtracer, Principled, Principled);
    OSP_REGISTER_MATERIAL(pt, Principled, Principled);
  }
}
<|endoftext|>


<commit_before>#include <qcstring.h>
#include <qdatetime.h>
#include <qstring.h>
#include <qtimer.h>

#include <kiconloader.h>

#include "kapplication.h"       // kapp
#include "kdebug.h"

#include "event.h"

#include "karmutility.h"
#include "task.h"
#include "taskview.h"
#include "preferences.h"

const int gSecondsPerMinute = 60;

QPtrVector<QPixmap> *Task::icons = 0;

Task::Task( const QString& taskName, long minutes, long sessionTime,
            DesktopList desktops, TaskView *parent)
  : QObject(), QListViewItem(parent)
{
  init(taskName, minutes, sessionTime, desktops, 0);
}

Task::Task( const QString& taskName, long minutes, long sessionTime,
            DesktopList desktops, Task *parent)
  : QObject(), QListViewItem(parent)
{
  init(taskName, minutes, sessionTime, desktops, 0);
}

Task::Task( KCal::Todo* todo, TaskView* parent )
  : QObject(), QListViewItem( parent )
{
  long minutes = 0;
  QString name;
  long sessionTime = 0;
  int percent_complete = 0;
  DesktopList desktops;

  parseIncidence(todo, minutes, sessionTime, name, desktops, percent_complete);
  init(name, minutes, sessionTime, desktops, percent_complete);
}

void Task::init( const QString& taskName, long minutes, long sessionTime,
                 DesktopList desktops, int percent_complete)
{
  // If our parent is the taskview then connect our totalTimesChanged
  // signal to its receiver
  if ( ! parent() )
    connect( this, SIGNAL( totalTimesChanged ( long, long ) ),
             listView(), SLOT( taskTotalTimesChanged( long, long) ));

  connect( this, SIGNAL( deletingTask( Task* ) ),
           listView(), SLOT( deletingTask( Task* ) ));

  if (icons == 0) {
    icons = new QPtrVector<QPixmap>(8);
    for (int i=0; i<8; i++)
    {
      QPixmap *icon = new QPixmap();
      QString name;
      name.sprintf("watch-%d.xpm",i);
      *icon = UserIcon(name);
      icons->insert(i,icon);
    }
  }

  //kdDebug(5970) << "Task::init(" << taskName << ", " << minutes << ", "
  //  << sessionTime << ", desktops)" << endl;

  _name = taskName.stripWhiteSpace();
  _lastStart = QDateTime::currentDateTime();
  _totalTime = _time = minutes;
  _totalSessionTime = _sessionTime = sessionTime;
  noNegativeTimes();
  _timer = new QTimer(this);
  _desktops = desktops;
  connect(_timer, SIGNAL(timeout()), this, SLOT(updateActiveIcon()));
  setPixmap(1, UserIcon(QString::fromLatin1("empty-watch.xpm")));
  _currentPic = 0;
  _percentcomplete = percent_complete;

  update();
  changeParentTotalTimes( _sessionTime, _time);
}

Task::~Task() {
  emit deletingTask(this);
  delete _timer;
}

void Task::setRunning( bool on, KarmStorage* storage )
{
  if ( on ) {
    if (!_timer->isActive()) {
      _timer->start(1000);
      storage->startTimer(this);
      _currentPic=7;
      _lastStart = QDateTime::currentDateTime();
      updateActiveIcon();
    }
  }
  else {
    if (_timer->isActive()) {
      _timer->stop();
      storage->stopTimer(this);
      setPixmap(1, UserIcon(QString::fromLatin1("empty-watch.xpm")));
    }
  }
}

void Task::setUid(QString uid) {
  _uid = uid;
}

bool Task::isRunning() const
{
  return _timer->isActive();
}

void Task::setName( const QString& name, KarmStorage* storage )
{
  kdDebug(5970) << "Task:setName: " << name << endl;

  QString oldname = _name;
  if ( oldname != name ) {
    _name = name;
    storage->setName(this, oldname);
    update();
  }
}

void Task::setPercentComplete(const int percent, KarmStorage *storage)
{
  kdDebug(5970) << "Task::setPercentComplete(" << percent << ", storage): "
    << _uid << endl;

  if (isRunning()) setRunning(false, storage);

  setEnabled(false);
  setOpen(false);

  if (!percent)
    _percentcomplete = 0;
  else if (percent > 100)
    _percentcomplete = 100;
  else if (percent < 0)
    _percentcomplete = 0;
  else
    _percentcomplete = percent;

  // When parent marked as complete, mark all children as complete as well.
  // Complete tasks are not displayed in the task view, so if a parent is
  // marked as complete and some of the children are not, then we get an error
  // message.  KArm actually keep chugging along in this case and displays the
  // child tasks just fine, so an alternative solution is to remove that error
  // message (from KarmStorage::load).  But I think it makes more sense that
  // if you mark a parent task as complete, then all children should be
  // complete as well.
  //
  // This behavior is consistent with KOrganizer (as of 2003-09-24).
  if (_percentcomplete == 100)
  {
    for (Task* child= this->firstChild(); child; child = child->nextSibling())
      child->setPercentComplete(_percentcomplete, storage);
  }
}

bool Task::isComplete() { return _percentcomplete == 100; }

void Task::removeFromView()
{
  for (Task* child= this->firstChild(); child; child= child->nextSibling())
    child->removeFromView();
  delete this;
}

void Task::setDesktopList ( DesktopList desktopList )
{
  _desktops = desktopList;
}

void Task::changeTime( long minutes, KarmStorage* storage )
{
  changeTimes( minutes, minutes, storage);
}

void Task::changeTimes( long minutesSession, long minutes, KarmStorage* storage)
{
  if( minutesSession != 0 || minutes != 0)
  {
    _sessionTime += minutesSession;
    _time += minutes;
    if ( storage ) storage->changeTime(this, minutes * gSecondsPerMinute);
    noNegativeTimes();
    changeTotalTimes( minutesSession, minutes );
  }
}

void Task::changeTotalTimes( long minutesSession, long minutes )
{
  //kdDebug(5970)
  //  << "Task::changeTotalTimes(" << minutesSession << ", "
  //  << minutes << ") for " << name() << endl;

  _totalSessionTime += minutesSession;
  _totalTime += minutes;
  noNegativeTimes();
  update();
  changeParentTotalTimes( minutesSession, minutes );
}

void Task::resetTimes()
{
  _totalSessionTime -= _sessionTime;
  _totalTime -= _time;
  changeParentTotalTimes( -_sessionTime, -_time);
  _sessionTime = 0;
  _time = 0;
  update();
}

void Task::changeParentTotalTimes( long minutesSession, long minutes )
{
  //kdDebug(5970)
  //  << "Task::changeParentTotalTimes(" << minutesSession << ", "
  //  << minutes << ") for " << name() << endl;

  if ( isRoot() )
    emit totalTimesChanged( minutesSession, minutes );
  else
    parent()->changeTotalTimes( minutesSession, minutes );
}

bool Task::remove( QPtrList<Task>& activeTasks, KarmStorage* storage)
{
  kdDebug(5970) << "Task::remove: " << _name << endl;

  bool ok = true;

  storage->removeTask(this);

  if( isRunning() ) setRunning( false, storage );

  for (Task* child = this->firstChild(); child; child = child->nextSibling())
  {
    if (child->isRunning())
      child->setRunning(false, storage);
    child->remove(activeTasks, storage);
  }

  changeParentTotalTimes( -_sessionTime, -_time);

  return ok;
}

void Task::updateActiveIcon()
{
  _currentPic = (_currentPic+1) % 8;
  setPixmap(1, *(*icons)[_currentPic]);
}

void Task::noNegativeTimes()
{
  if ( _time < 0 )
      _time = 0;
  if ( _sessionTime < 0 )
      _sessionTime = 0;
}

QString Task::fullName() const
{
  if (isRoot())
    return name();
  else
    return parent()->fullName() + QString::fromLatin1("/") + name();
}

KCal::Todo* Task::asTodo(KCal::Todo* todo) const
{

  todo->setSummary( name() );

  // Note: if the date start is empty, the KOrganizer GUI will have the
  // checkbox blank, but will prefill the todo's starting datetime to the
  // time the file is opened.
  // todo->setDtStart( current );

  todo->setCustomProperty( kapp->instanceName(),
      QCString( "totalTaskTime" ), QString::number( _time ) );
  todo->setCustomProperty( kapp->instanceName(),
      QCString( "totalSessionTime" ), QString::number( _sessionTime) );

  if (getDesktopStr().isEmpty())
    todo->removeCustomProperty(kapp->instanceName(), QCString("desktopList"));
  else
    todo->setCustomProperty( kapp->instanceName(),
        QCString( "desktopList" ), getDesktopStr() );

  todo->setOrganizer( Preferences::instance()->userRealName() );

  todo->setPercentComplete(_percentcomplete);

  return todo;
}

bool Task::parseIncidence( KCal::Incidence* incident, long& minutes,
    long& sessionMinutes, QString& name, DesktopList& desktops,
    int& percent_complete )
{
  bool ok;

  name = incident->summary();
  _uid = incident->uid();

  _comment = incident->description();

  ok = false;
  minutes = incident->customProperty( kapp->instanceName(),
      QCString( "totalTaskTime" )).toInt( &ok );
  if ( !ok )
    minutes = 0;

  ok = false;
  sessionMinutes = incident->customProperty( kapp->instanceName(),
      QCString( "totalSessionTime" )).toInt( &ok );
  if ( !ok )
    sessionMinutes = 0;

  QString desktopList = incident->customProperty( kapp->instanceName(),
      QCString( "desktopList" ) );
  QStringList desktopStrList = QStringList::split( QString::fromLatin1(","),
      desktopList );
  desktops.clear();

  for ( QStringList::iterator iter = desktopStrList.begin();
        iter != desktopStrList.end();
        ++iter ) {
    int desktopInt = (*iter).toInt( &ok );
    if ( ok ) {
      desktops.push_back( desktopInt );
    }
  }

  percent_complete = static_cast<KCal::Todo*>(incident)->percentComplete();

  //kdDebug(5970) << "Task::parseIncidence: "
  //  << name << ", Minutes: " << minutes
  //  <<  ", desktop: " << desktopList << endl;

  return true;
}

QString Task::getDesktopStr() const
{
  if ( _desktops.empty() )
    return QString();

  QString desktopstr;
  for ( DesktopList::const_iterator iter = _desktops.begin();
        iter != _desktops.end();
        ++iter ) {
    desktopstr += QString::number( *iter ) + QString::fromLatin1( "," );
  }
  desktopstr.remove( desktopstr.length() - 1, 1 );
  return desktopstr;
}

void Task::cut()
{
  //kdDebug(5970) << "Task::cut - " << name() << endl;
  changeParentTotalTimes( -_totalSessionTime, -_totalTime);
  if ( ! parent())
    listView()->takeItem(this);
  else
    parent()->takeItem(this);
}

void Task::move(Task* destination)
{
  cut();
  paste(destination);
}

void Task::paste(Task* destination)
{
  destination->insertItem(this);
  changeParentTotalTimes( _totalSessionTime, _totalTime);
}

void Task::update()
{
  setText(0, _name);
  setText(1, formatTime(_sessionTime));
  setText(2, formatTime(_time));
  setText(3, formatTime(_totalSessionTime));
  setText(4, formatTime(_totalTime));
}

void Task::addComment( QString comment, KarmStorage* storage )
{
  _comment = _comment + QString::fromLatin1("\n") + comment;
  storage->addComment(this, comment);
}

QString Task::comment() const
{
  return _comment;
}

int Task::compare ( QListViewItem * i, int col, bool ascending ) const
{
  switch ( col )
  {
    case 1:
      if      ( _sessionTime < static_cast<Task*>(i)->sessionTime() ) return -1;
      else if ( _sessionTime > static_cast<Task*>(i)->sessionTime() ) return 1;
      else return 0;
      break;
    case 2:
      if      ( _time < static_cast<Task*>(i)->time() ) return -1;
      else if ( _time > static_cast<Task*>(i)->time() ) return 1;
      else return 0;
      break;
    case 3:
      if      ( _totalSessionTime < static_cast<Task*>(i)->totalSessionTime() )
        return -1;
      else if ( _totalSessionTime > static_cast<Task*>(i)->totalSessionTime() )
        return 1;
      else return 0;
      break;
    case 4:
      if      ( _totalTime < static_cast<Task*>(i)->totalTime() ) return -1;
      else if ( _totalTime > static_cast<Task*>(i)->totalTime() ) return 1;
      else return 0;
      break;
    default:
      return key(col, ascending).localeAwareCompare( i->key(col, ascending) );
  }
}

#include "task.moc"
<commit_msg>Improved compare routine, per F. Raabe's suggestion.<commit_after>#include <qcstring.h>
#include <qdatetime.h>
#include <qstring.h>
#include <qtimer.h>

#include <kiconloader.h>

#include "kapplication.h"       // kapp
#include "kdebug.h"

#include "event.h"

#include "karmutility.h"
#include "task.h"
#include "taskview.h"
#include "preferences.h"

const int gSecondsPerMinute = 60;

QPtrVector<QPixmap> *Task::icons = 0;

Task::Task( const QString& taskName, long minutes, long sessionTime,
            DesktopList desktops, TaskView *parent)
  : QObject(), QListViewItem(parent)
{
  init(taskName, minutes, sessionTime, desktops, 0);
}

Task::Task( const QString& taskName, long minutes, long sessionTime,
            DesktopList desktops, Task *parent)
  : QObject(), QListViewItem(parent)
{
  init(taskName, minutes, sessionTime, desktops, 0);
}

Task::Task( KCal::Todo* todo, TaskView* parent )
  : QObject(), QListViewItem( parent )
{
  long minutes = 0;
  QString name;
  long sessionTime = 0;
  int percent_complete = 0;
  DesktopList desktops;

  parseIncidence(todo, minutes, sessionTime, name, desktops, percent_complete);
  init(name, minutes, sessionTime, desktops, percent_complete);
}

void Task::init( const QString& taskName, long minutes, long sessionTime,
                 DesktopList desktops, int percent_complete)
{
  // If our parent is the taskview then connect our totalTimesChanged
  // signal to its receiver
  if ( ! parent() )
    connect( this, SIGNAL( totalTimesChanged ( long, long ) ),
             listView(), SLOT( taskTotalTimesChanged( long, long) ));

  connect( this, SIGNAL( deletingTask( Task* ) ),
           listView(), SLOT( deletingTask( Task* ) ));

  if (icons == 0) {
    icons = new QPtrVector<QPixmap>(8);
    for (int i=0; i<8; i++)
    {
      QPixmap *icon = new QPixmap();
      QString name;
      name.sprintf("watch-%d.xpm",i);
      *icon = UserIcon(name);
      icons->insert(i,icon);
    }
  }

  //kdDebug(5970) << "Task::init(" << taskName << ", " << minutes << ", "
  //  << sessionTime << ", desktops)" << endl;

  _name = taskName.stripWhiteSpace();
  _lastStart = QDateTime::currentDateTime();
  _totalTime = _time = minutes;
  _totalSessionTime = _sessionTime = sessionTime;
  noNegativeTimes();
  _timer = new QTimer(this);
  _desktops = desktops;
  connect(_timer, SIGNAL(timeout()), this, SLOT(updateActiveIcon()));
  setPixmap(1, UserIcon(QString::fromLatin1("empty-watch.xpm")));
  _currentPic = 0;
  _percentcomplete = percent_complete;

  update();
  changeParentTotalTimes( _sessionTime, _time);
}

Task::~Task() {
  emit deletingTask(this);
  delete _timer;
}

void Task::setRunning( bool on, KarmStorage* storage )
{
  if ( on ) {
    if (!_timer->isActive()) {
      _timer->start(1000);
      storage->startTimer(this);
      _currentPic=7;
      _lastStart = QDateTime::currentDateTime();
      updateActiveIcon();
    }
  }
  else {
    if (_timer->isActive()) {
      _timer->stop();
      storage->stopTimer(this);
      setPixmap(1, UserIcon(QString::fromLatin1("empty-watch.xpm")));
    }
  }
}

void Task::setUid(QString uid) {
  _uid = uid;
}

bool Task::isRunning() const
{
  return _timer->isActive();
}

void Task::setName( const QString& name, KarmStorage* storage )
{
  kdDebug(5970) << "Task:setName: " << name << endl;

  QString oldname = _name;
  if ( oldname != name ) {
    _name = name;
    storage->setName(this, oldname);
    update();
  }
}

void Task::setPercentComplete(const int percent, KarmStorage *storage)
{
  kdDebug(5970) << "Task::setPercentComplete(" << percent << ", storage): "
    << _uid << endl;

  if (isRunning()) setRunning(false, storage);

  setEnabled(false);
  setOpen(false);

  if (!percent)
    _percentcomplete = 0;
  else if (percent > 100)
    _percentcomplete = 100;
  else if (percent < 0)
    _percentcomplete = 0;
  else
    _percentcomplete = percent;

  // When parent marked as complete, mark all children as complete as well.
  // Complete tasks are not displayed in the task view, so if a parent is
  // marked as complete and some of the children are not, then we get an error
  // message.  KArm actually keep chugging along in this case and displays the
  // child tasks just fine, so an alternative solution is to remove that error
  // message (from KarmStorage::load).  But I think it makes more sense that
  // if you mark a parent task as complete, then all children should be
  // complete as well.
  //
  // This behavior is consistent with KOrganizer (as of 2003-09-24).
  if (_percentcomplete == 100)
  {
    for (Task* child= this->firstChild(); child; child = child->nextSibling())
      child->setPercentComplete(_percentcomplete, storage);
  }
}

bool Task::isComplete() { return _percentcomplete == 100; }

void Task::removeFromView()
{
  for (Task* child= this->firstChild(); child; child= child->nextSibling())
    child->removeFromView();
  delete this;
}

void Task::setDesktopList ( DesktopList desktopList )
{
  _desktops = desktopList;
}

void Task::changeTime( long minutes, KarmStorage* storage )
{
  changeTimes( minutes, minutes, storage);
}

void Task::changeTimes( long minutesSession, long minutes, KarmStorage* storage)
{
  if( minutesSession != 0 || minutes != 0)
  {
    _sessionTime += minutesSession;
    _time += minutes;
    if ( storage ) storage->changeTime(this, minutes * gSecondsPerMinute);
    noNegativeTimes();
    changeTotalTimes( minutesSession, minutes );
  }
}

void Task::changeTotalTimes( long minutesSession, long minutes )
{
  //kdDebug(5970)
  //  << "Task::changeTotalTimes(" << minutesSession << ", "
  //  << minutes << ") for " << name() << endl;

  _totalSessionTime += minutesSession;
  _totalTime += minutes;
  noNegativeTimes();
  update();
  changeParentTotalTimes( minutesSession, minutes );
}

void Task::resetTimes()
{
  _totalSessionTime -= _sessionTime;
  _totalTime -= _time;
  changeParentTotalTimes( -_sessionTime, -_time);
  _sessionTime = 0;
  _time = 0;
  update();
}

void Task::changeParentTotalTimes( long minutesSession, long minutes )
{
  //kdDebug(5970)
  //  << "Task::changeParentTotalTimes(" << minutesSession << ", "
  //  << minutes << ") for " << name() << endl;

  if ( isRoot() )
    emit totalTimesChanged( minutesSession, minutes );
  else
    parent()->changeTotalTimes( minutesSession, minutes );
}

bool Task::remove( QPtrList<Task>& activeTasks, KarmStorage* storage)
{
  kdDebug(5970) << "Task::remove: " << _name << endl;

  bool ok = true;

  storage->removeTask(this);

  if( isRunning() ) setRunning( false, storage );

  for (Task* child = this->firstChild(); child; child = child->nextSibling())
  {
    if (child->isRunning())
      child->setRunning(false, storage);
    child->remove(activeTasks, storage);
  }

  changeParentTotalTimes( -_sessionTime, -_time);

  return ok;
}

void Task::updateActiveIcon()
{
  _currentPic = (_currentPic+1) % 8;
  setPixmap(1, *(*icons)[_currentPic]);
}

void Task::noNegativeTimes()
{
  if ( _time < 0 )
      _time = 0;
  if ( _sessionTime < 0 )
      _sessionTime = 0;
}

QString Task::fullName() const
{
  if (isRoot())
    return name();
  else
    return parent()->fullName() + QString::fromLatin1("/") + name();
}

KCal::Todo* Task::asTodo(KCal::Todo* todo) const
{

  todo->setSummary( name() );

  // Note: if the date start is empty, the KOrganizer GUI will have the
  // checkbox blank, but will prefill the todo's starting datetime to the
  // time the file is opened.
  // todo->setDtStart( current );

  todo->setCustomProperty( kapp->instanceName(),
      QCString( "totalTaskTime" ), QString::number( _time ) );
  todo->setCustomProperty( kapp->instanceName(),
      QCString( "totalSessionTime" ), QString::number( _sessionTime) );

  if (getDesktopStr().isEmpty())
    todo->removeCustomProperty(kapp->instanceName(), QCString("desktopList"));
  else
    todo->setCustomProperty( kapp->instanceName(),
        QCString( "desktopList" ), getDesktopStr() );

  todo->setOrganizer( Preferences::instance()->userRealName() );

  todo->setPercentComplete(_percentcomplete);

  return todo;
}

bool Task::parseIncidence( KCal::Incidence* incident, long& minutes,
    long& sessionMinutes, QString& name, DesktopList& desktops,
    int& percent_complete )
{
  bool ok;

  name = incident->summary();
  _uid = incident->uid();

  _comment = incident->description();

  ok = false;
  minutes = incident->customProperty( kapp->instanceName(),
      QCString( "totalTaskTime" )).toInt( &ok );
  if ( !ok )
    minutes = 0;

  ok = false;
  sessionMinutes = incident->customProperty( kapp->instanceName(),
      QCString( "totalSessionTime" )).toInt( &ok );
  if ( !ok )
    sessionMinutes = 0;

  QString desktopList = incident->customProperty( kapp->instanceName(),
      QCString( "desktopList" ) );
  QStringList desktopStrList = QStringList::split( QString::fromLatin1(","),
      desktopList );
  desktops.clear();

  for ( QStringList::iterator iter = desktopStrList.begin();
        iter != desktopStrList.end();
        ++iter ) {
    int desktopInt = (*iter).toInt( &ok );
    if ( ok ) {
      desktops.push_back( desktopInt );
    }
  }

  percent_complete = static_cast<KCal::Todo*>(incident)->percentComplete();

  //kdDebug(5970) << "Task::parseIncidence: "
  //  << name << ", Minutes: " << minutes
  //  <<  ", desktop: " << desktopList << endl;

  return true;
}

QString Task::getDesktopStr() const
{
  if ( _desktops.empty() )
    return QString();

  QString desktopstr;
  for ( DesktopList::const_iterator iter = _desktops.begin();
        iter != _desktops.end();
        ++iter ) {
    desktopstr += QString::number( *iter ) + QString::fromLatin1( "," );
  }
  desktopstr.remove( desktopstr.length() - 1, 1 );
  return desktopstr;
}

void Task::cut()
{
  //kdDebug(5970) << "Task::cut - " << name() << endl;
  changeParentTotalTimes( -_totalSessionTime, -_totalTime);
  if ( ! parent())
    listView()->takeItem(this);
  else
    parent()->takeItem(this);
}

void Task::move(Task* destination)
{
  cut();
  paste(destination);
}

void Task::paste(Task* destination)
{
  destination->insertItem(this);
  changeParentTotalTimes( _totalSessionTime, _totalTime);
}

void Task::update()
{
  setText(0, _name);
  setText(1, formatTime(_sessionTime));
  setText(2, formatTime(_time));
  setText(3, formatTime(_totalSessionTime));
  setText(4, formatTime(_totalTime));
}

void Task::addComment( QString comment, KarmStorage* storage )
{
  _comment = _comment + QString::fromLatin1("\n") + comment;
  storage->addComment(this, comment);
}

QString Task::comment() const
{
  return _comment;
}

int Task::compare ( QListViewItem * i, int col, bool ascending ) const
{
  long thistime = 0;
  long thattime = 0;
  Task *task = static_cast<Task*>(i);

  switch ( col )
  {
    case 1:
      thistime = _sessionTime;
      thattime = task->sessionTime();
      break;
    case 2:
      thistime = _time;
      thattime = task->time();
      break;
    case 3:
      thistime = _totalSessionTime;
      thattime = task->totalSessionTime();
      break;
    case 4:
      thistime = _totalTime;
      thattime = task->totalTime();
      break;
    default:
      return key(col, ascending).localeAwareCompare( i->key(col, ascending) );
  }

  if ( thistime < thattime ) return -1;
  if ( thistime > thattime ) return 1;
  return 0;

}

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