<commit_before>#ifndef LIMONP_LOCAL_VECTOR_HPP
#define LIMONP_LOCAL_VECTOR_HPP

#include <iostream>
#include <stdlib.h>
#include <assert.h>
#include <string.h>

namespace Limonp
{
    using namespace std;
    const size_t LOCAL_VECTOR_BUFFER_SIZE = 16;
    template <class T>
        class LocalVector
        {
            public:
                typedef const T* const_iterator ;
                typedef T value_type;
                typedef size_t size_type;
            private:
                T _buffer[LOCAL_VECTOR_BUFFER_SIZE];
                T * _ptr;
                size_t _size;
                size_t _capacity;
            public:
                LocalVector()
                {
                    _init();
                };
                LocalVector(const LocalVector<T>& vec)
                {
                    _init();
                    *this = vec;
                }
                LocalVector(const_iterator  begin, const_iterator end) // TODO: make it faster
                {
                    _init();
                    while(begin != end)
                    {
                        push_back(*begin++);
                    }
                }
                LocalVector(size_t size, const T& t) // TODO: make it faster
                {
                    _init();
                    while(size--)
                    {
                        push_back(t);
                    }
                }
                ~LocalVector()
                {
                    if(_ptr != _buffer)
                    {
                        free(_ptr);
                    }
                };
            public:
                LocalVector<T>& operator = (const LocalVector<T>& vec)
                {
                    clear();
                    _size = vec.size();
                    _capacity = vec.capacity();
                    if(vec._buffer == vec._ptr)
                    {
                        memcpy(_buffer, vec._buffer, sizeof(T) * _size);
                        _ptr = _buffer;
                    }
                    else
                    {
                        _ptr = (T*) malloc(vec.capacity() * sizeof(T));
                        assert(_ptr);
                        memcpy(_ptr, vec._ptr, vec.size() * sizeof(T));
                    }
                    return *this;
                }
            private:
                void _init()
                {
                    _ptr = _buffer;
                    _size = 0;
                    _capacity = LOCAL_VECTOR_BUFFER_SIZE;
                }
            public:
                T& operator [] (size_t i)
                {
                    return _ptr[i];
                }
                const T& operator [] (size_t i) const
                {
                    return _ptr[i];
                }
                void push_back(const T& t)
                {
                    if(!full())
                    {
                        _ptr[_size++] = t;
                        return ;
                    }
                    assert(_capacity);
                    reserve(_capacity * 2);
                    _ptr[_size ++ ] = t;
                }
                void reserve(size_t size)
                {
                    if(size <= _capacity)
                    {
                        return;
                    }
                    T * next =  (T*)malloc(sizeof(T) * size);
                    assert(next);
                    T * old = _ptr;
                    _ptr = next;
                    memcpy(_ptr, old, sizeof(T) * _capacity);
                    _capacity = size;
                    if(old != _buffer)
                    {
                        free(old);
                    }
                }
                bool full() const
                {
                    return size() == capacity();
                }
                bool empty() const
                {
                    return 0 == size();
                }
                size_t size() const
                {
                    return _size;
                }
                size_t capacity() const
                {
                    return _capacity;
                }
                const_iterator begin() const
                {
                    return _ptr;
                }
                const_iterator end() const
                {
                    return _ptr + _size;
                }
                void clear()
                {
                    if(_ptr != _buffer)
                    {
                        free(_ptr);
                    }
                    _init();
                }
        };

    template <class T>
        ostream & operator << (ostream& os, const LocalVector<T>& vec)
        {
            if(vec.empty())
            {
                return os << "[]";
            }
            os<<"[\""<<vec[0];
            for(size_t i = 1; i < vec.size(); i++)
            {
                os<<"\", \""<<vec[i];
            }
            os<<"\"]";
            return os;
        }

}

#endif
<commit_msg>update localvector<commit_after>#ifndef LIMONP_LOCAL_VECTOR_HPP
#define LIMONP_LOCAL_VECTOR_HPP

#include <iostream>
#include <stdlib.h>
#include <assert.h>
#include <string.h>

namespace Limonp
{
    using namespace std;
    /*
     * LocalVector<T> : T must be primitive type (char , int, size_t), if T is struct or class, LocalVector<T> may be dangerous..
     * LocalVector<T> is simple and not well-tested.
     */
    const size_t LOCAL_VECTOR_BUFFER_SIZE = 16;
    template <class T>
        class LocalVector
        {
            public:
                typedef const T* const_iterator ;
                typedef T value_type;
                typedef size_t size_type;
            private:
                T _buffer[LOCAL_VECTOR_BUFFER_SIZE];
                T * _ptr;
                size_t _size;
                size_t _capacity;
            public:
                LocalVector()
                {
                    _init();
                };
                LocalVector(const LocalVector<T>& vec)
                {
                    _init();
                    *this = vec;
                }
                LocalVector(const_iterator  begin, const_iterator end) // TODO: make it faster
                {
                    _init();
                    while(begin != end)
                    {
                        push_back(*begin++);
                    }
                }
                LocalVector(size_t size, const T& t) // TODO: make it faster
                {
                    _init();
                    while(size--)
                    {
                        push_back(t);
                    }
                }
                ~LocalVector()
                {
                    if(_ptr != _buffer)
                    {
                        free(_ptr);
                    }
                };
            public:
                LocalVector<T>& operator = (const LocalVector<T>& vec)
                {
                    clear();
                    _size = vec.size();
                    _capacity = vec.capacity();
                    if(vec._buffer == vec._ptr)
                    {
                        memcpy(_buffer, vec._buffer, sizeof(T) * _size);
                        _ptr = _buffer;
                    }
                    else
                    {
                        _ptr = (T*) malloc(vec.capacity() * sizeof(T));
                        assert(_ptr);
                        memcpy(_ptr, vec._ptr, vec.size() * sizeof(T));
                    }
                    return *this;
                }
            private:
                void _init()
                {
                    _ptr = _buffer;
                    _size = 0;
                    _capacity = LOCAL_VECTOR_BUFFER_SIZE;
                }
            public:
                T& operator [] (size_t i)
                {
                    return _ptr[i];
                }
                const T& operator [] (size_t i) const
                {
                    return _ptr[i];
                }
                void push_back(const T& t)
                {
                    if(_size == _capacity)
                    {
                        assert(_capacity);
                        reserve(_capacity * 2);
                    }
                    _ptr[_size ++ ] = t;
                }
                void reserve(size_t size)
                {
                    if(size <= _capacity)
                    {
                        return;
                    }
                    T * next =  (T*)malloc(sizeof(T) * size);
                    assert(next);
                    T * old = _ptr;
                    _ptr = next;
                    memcpy(_ptr, old, sizeof(T) * _capacity);
                    _capacity = size;
                    if(old != _buffer)
                    {
                        free(old);
                    }
                }
                bool empty() const
                {
                    return 0 == size();
                }
                size_t size() const
                {
                    return _size;
                }
                size_t capacity() const
                {
                    return _capacity;
                }
                const_iterator begin() const
                {
                    return _ptr;
                }
                const_iterator end() const
                {
                    return _ptr + _size;
                }
                void clear()
                {
                    if(_ptr != _buffer)
                    {
                        free(_ptr);
                    }
                    _init();
                }
        };

    template <class T>
        ostream & operator << (ostream& os, const LocalVector<T>& vec)
        {
            if(vec.empty())
            {
                return os << "[]";
            }
            os<<"[\""<<vec[0];
            for(size_t i = 1; i < vec.size(); i++)
            {
                os<<"\", \""<<vec[i];
            }
            os<<"\"]";
            return os;
        }

}

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: helper.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: rt $ $Date: 2004-03-30 13:46:06 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include <unistd.h>

#ifndef _PAD_HELPER_HXX_
#include <helper.hxx>
#endif
#ifndef _PAD_PADIALOG_HRC_
#include <padialog.hrc>
#endif

#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _INTN_HXX
#include <tools/intn.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _CONFIG_HXX
#include <tools/config.hxx>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFOLDERPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFolderPicker.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XCONTROLACCESS_HPP_
#include <com/sun/star/ui/dialogs/XControlAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _UNOTOOLS_CONFIGNODE_HXX_
#include <unotools/confignode.hxx>
#endif
#ifndef _VCL_UNOHELP_HXX
#include <vcl/unohelp.hxx>
#endif
#ifndef _ISOLANG_HXX
#include <tools/isolang.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

using namespace osl;
using namespace rtl;
using namespace padmin;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::ui::dialogs;

#define MAX_PATH 1024

/*
 *  PaResId
 */

ResId padmin::PaResId( ULONG nId )
{
    static ResMgr* pPaResMgr = NULL;
    if( ! pPaResMgr )
    {
        LanguageType nLang = LANGUAGE_SYSTEM;

        utl::OConfigurationNode aNode =
            utl::OConfigurationTreeRoot::tryCreateWithServiceFactory(
                    vcl::unohelper::GetMultiServiceFactory(),
                    OUString::createFromAscii( "org.openoffice.Setup/L10N" ) );
        if ( aNode.isValid() )
        {
            rtl::OUString aLoc;
            Any aValue = aNode.getNodeValue( OUString::createFromAscii( "ooLocale" ) );
            if( aValue >>= aLoc )
            {
                LanguageType nTmpLang = ConvertIsoStringToLanguage( aLoc );
                if( nTmpLang != LANGUAGE_DONTKNOW )
                    nLang = nTmpLang;
            }
        }
        pPaResMgr = ResMgr::SearchCreateResMgr( "spa" MAKE_NUMSTR(SUPD), nLang );
        AllSettings aSettings = Application::GetSettings();
        aSettings.SetUILanguage( nLang );
        Application::SetSettings( aSettings );
    }
    return ResId( nId, pPaResMgr );
}

/*
 *  FindFiles
 */

void padmin::FindFiles( const String& rDirectory, ::std::list< String >& rResult, const String& rSuffixes, bool bRecursive )
{
    rResult.clear();

    OUString aDirPath;
    ::osl::FileBase::getFileURLFromSystemPath( rDirectory, aDirPath );
    Directory aDir( aDirPath );
    if( aDir.open() != FileBase::E_None )
        return;
    DirectoryItem aItem;
    while( aDir.getNextItem( aItem ) == FileBase::E_None )
    {
        FileStatus aStatus( FileStatusMask_FileName         |
                            FileStatusMask_Type
                            );
        if( aItem.getFileStatus( aStatus ) == FileBase::E_None &&
            ( aStatus.getFileType() == FileStatus::Regular ||
              aStatus.getFileType() == FileStatus::Link ) )
        {
            String aFileName = aStatus.getFileName();
            int nToken = rSuffixes.GetTokenCount( ';' );
            while( nToken-- )
            {
                String aSuffix = rSuffixes.GetToken( nToken, ';' );
                if( aFileName.Len() > aSuffix.Len()+1 )
                {
                    String aExtension = aFileName.Copy( aFileName.Len()-aSuffix.Len() );
                    if( aFileName.GetChar( aFileName.Len()-aSuffix.Len()-1 ) == '.' &&
                        aExtension.EqualsIgnoreCaseAscii( aSuffix ) )
                    {
                        rResult.push_back( aFileName );
                        break;
                    }
                }
            }
        }
        else if( bRecursive &&
                 ( aStatus.getFileType() == FileStatus::Directory ||
                   aStatus.getFileType() == FileStatus::Link ) )
        {
            OUStringBuffer aSubDir( rDirectory );
            aSubDir.appendAscii( "/", 1 );
            aSubDir.append( aStatus.getFileName() );
            std::list< String > subfiles;
            FindFiles( aSubDir.makeStringAndClear(), subfiles, rSuffixes, bRecursive );
            for( std::list< String >::const_iterator it = subfiles.begin(); it != subfiles.end(); ++it )
            {
                OUStringBuffer aSubFile( aStatus.getFileName() );
                aSubFile.appendAscii( "/", 1 );
                aSubFile.append( *it );
                rResult.push_back( aSubFile.makeStringAndClear() );
            }
        }
    }
    aDir.close();
}

/*
 *  DelMultiListBox
 */

long DelMultiListBox::Notify( NotifyEvent& rEvent )
{
    long nRet = 0;

    if( rEvent.GetType() == EVENT_KEYINPUT &&
        rEvent.GetKeyEvent()->GetKeyCode().GetCode() == KEY_DELETE )
    {
        m_aDelPressedLink.Call( this );
        nRet = 1;
    }
    else
        nRet = MultiListBox::Notify( rEvent );

    return nRet;
}

/*
 *  DelListBox
 */

long DelListBox::Notify( NotifyEvent& rEvent )
{
    long nRet = 0;

    if( rEvent.GetType() == EVENT_KEYINPUT &&
        rEvent.GetKeyEvent()->GetKeyCode().GetCode() == KEY_DELETE )
    {
        m_aDelPressedLink.Call( this );
        nRet = 1;
    }
    else
        nRet = ListBox::Notify( rEvent );

    return nRet;
}

/*
 *  QueryString
 */

QueryString::QueryString( Window* pParent, String& rQuery, String& rRet, const ::std::list< String >& rChoices ) :
        ModalDialog( pParent, PaResId( RID_STRINGQUERYDLG ) ),
        m_aOKButton( this, PaResId( RID_STRQRY_BTN_OK ) ),
        m_aCancelButton( this, PaResId( RID_STRQRY_BTN_CANCEL ) ),
        m_aFixedText( this, PaResId( RID_STRQRY_TXT_RENAME ) ),
        m_aEdit( this, PaResId( RID_STRQRY_EDT_NEWNAME ) ),
        m_aComboBox( this, PaResId( RID_STRQRY_BOX_NEWNAME ) ),
        m_rReturnValue( rRet )
{
    m_aOKButton.SetClickHdl( LINK( this, QueryString, ClickBtnHdl ) );
    m_aFixedText.SetText( rQuery );
    if( rChoices.begin() != rChoices.end() )
    {
        m_aComboBox.SetText( m_rReturnValue );
        m_aComboBox.InsertEntry( m_rReturnValue );
        for( ::std::list<String>::const_iterator it = rChoices.begin(); it != rChoices.end(); ++it )
            m_aComboBox.InsertEntry( *it );
        m_aEdit.Show( FALSE );
        m_bUseEdit = false;
    }
    else
    {
        m_aEdit.SetText( m_rReturnValue );
        m_aComboBox.Show( FALSE );
        m_bUseEdit = true;
    }
    SetText( Application::GetDisplayName() );
    FreeResource();
}

QueryString::~QueryString()
{
}

IMPL_LINK( QueryString, ClickBtnHdl, Button*, pButton )
{
    if( pButton == &m_aOKButton )
    {
        m_rReturnValue = m_bUseEdit ? m_aEdit.GetText() : m_aComboBox.GetText();
        EndDialog( 1 );
    }
    else
        EndDialog(0);
    return 0;
}

/*
 *  AreYouSure
 */

BOOL padmin::AreYouSure( Window* pParent, int nRid )
{
    if( nRid == -1 )
        nRid = RID_YOU_SURE;
    QueryBox aQueryBox( pParent, WB_YES_NO | WB_DEF_NO,
                        String( PaResId( nRid ) ) );
    return aQueryBox.Execute() == RET_NO ? FALSE : TRUE;
}

/*
 *  getPadminRC
 */

static Config* pRC = NULL;

Config& padmin::getPadminRC()
{
    if( ! pRC )
    {
        static const char* pEnv = getenv( "HOME" );
        String aFileName( pEnv ? pEnv : "", osl_getThreadTextEncoding() );
        aFileName.AppendAscii( "/.padminrc" );
        pRC = new Config( aFileName );
    }
    return *pRC;
}

void padmin::freePadminRC()
{
    if( pRC )
        delete pRC, pRC = NULL;
}

bool padmin::chooseDirectory( Window* pParent, String& rInOutPath )
{
    bool bRet = false;
    Reference< XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
    if( xFactory.is() )
    {
        Reference< XFolderPicker > xFolderPicker( xFactory->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.ui.dialogs.FolderPicker" ) ) ), UNO_QUERY );
        if( xFolderPicker.is() )
        {
            Reference< XControlAccess > xCA( xFolderPicker, UNO_QUERY );
            if( xCA.is() )
            {
                try
                {
                    Any aState;
                    aState <<= sal_False;
                    xCA->setControlProperty( OUString( RTL_CONSTASCII_USTRINGPARAM( "HelpButton" ) ),
                                             OUString( RTL_CONSTASCII_USTRINGPARAM( "Visible" ) ),
                                             aState );

                }
                catch( ... )
                {
                }
            }
            INetURLObject aObj( rInOutPath, INET_PROT_FILE, INetURLObject::ENCODE_ALL );
            xFolderPicker->setDisplayDirectory( aObj.GetMainURL(INetURLObject::DECODE_TO_IURI) );
            if( xFolderPicker->execute() == ExecutableDialogResults::OK )
            {
                aObj = INetURLObject( xFolderPicker->getDirectory() );
                rInOutPath = aObj.PathToFileName();
                bRet = true;
            }
        }
#if OSL_DEBUG_LEVEL > 1
        else
            fprintf( stderr, "could not get FolderPicker service\n" );
#endif
    }
    return bRet;
}
<commit_msg>INTEGRATION: CWS mergebuild (1.12.32); FILE MERGED 2004/05/18 15:47:10 hjs 1.12.32.3: RESYNC: (1.13-1.14); FILE MERGED 2004/04/20 19:29:10 hjs 1.12.32.2: RESYNC: (1.12-1.13); FILE MERGED 2004/02/20 18:40:04 ihi 1.12.32.1: Merge-While-Build update<commit_after>/*************************************************************************
 *
 *  $RCSfile: helper.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: hjs $ $Date: 2004-06-26 03:11:23 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include <unistd.h>

#ifndef _PAD_HELPER_HXX_
#include <helper.hxx>
#endif
#ifndef _PAD_PADIALOG_HRC_
#include <padialog.hrc>
#endif

#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _INTN_HXX
#include <tools/intn.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _CONFIG_HXX
#include <tools/config.hxx>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFOLDERPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFolderPicker.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XCONTROLACCESS_HPP_
#include <com/sun/star/ui/dialogs/XControlAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _UNOTOOLS_CONFIGNODE_HXX_
#include <unotools/confignode.hxx>
#endif
#ifndef _VCL_UNOHELP_HXX
#include <vcl/unohelp.hxx>
#endif
#ifndef _ISOLANG_HXX
#include <tools/isolang.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

using namespace osl;
using namespace rtl;
using namespace padmin;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::ui::dialogs;

#define MAX_PATH 1024

/*
 *  PaResId
 */

ResId padmin::PaResId( ULONG nId )
{
    static ResMgr* pPaResMgr = NULL;
    if( ! pPaResMgr )
    {
        ::com::sun::star::lang::Locale aLocale;
//      LanguageType nLang = LANGUAGE_SYSTEM;

        utl::OConfigurationNode aNode =
            utl::OConfigurationTreeRoot::tryCreateWithServiceFactory(
                    vcl::unohelper::GetMultiServiceFactory(),
                    OUString::createFromAscii( "org.openoffice.Setup/L10N" ) );
        if ( aNode.isValid() )
        {
            rtl::OUString aLoc;
            Any aValue = aNode.getNodeValue( OUString::createFromAscii( "ooLocale" ) );
            if( aValue >>= aLoc )
            {
//                LanguageType nTmpLang = ConvertIsoStringToLanguage( aLoc );
//                if( nTmpLang != LANGUAGE_DONTKNOW )
//                    nLang = nTmpLang;
                sal_Int32 nIndex = 0;
                aLocale.Language = aLoc.getToken( 0, '-', nIndex );
                aLocale.Country = aLoc.getToken( 0, '-', nIndex );
                aLocale.Variant = aLoc.getToken( 0, '-', nIndex );
            }
        }
//      pPaResMgr = ResMgr::SearchCreateResMgr( "spa" MAKE_NUMSTR(SUPD), nLang );
        pPaResMgr = ResMgr::SearchCreateResMgr( "spa" MAKE_NUMSTR(SUPD), aLocale );
        AllSettings aSettings = Application::GetSettings();
//        aSettings.SetUILanguage( nLang );
        aSettings.SetUILocale( aLocale );
        Application::SetSettings( aSettings );
    }
    return ResId( nId, pPaResMgr );
}

/*
 *  FindFiles
 */

void padmin::FindFiles( const String& rDirectory, ::std::list< String >& rResult, const String& rSuffixes, bool bRecursive )
{
    rResult.clear();

    OUString aDirPath;
    ::osl::FileBase::getFileURLFromSystemPath( rDirectory, aDirPath );
    Directory aDir( aDirPath );
    if( aDir.open() != FileBase::E_None )
        return;
    DirectoryItem aItem;
    while( aDir.getNextItem( aItem ) == FileBase::E_None )
    {
        FileStatus aStatus( FileStatusMask_FileName         |
                            FileStatusMask_Type
                            );
        if( aItem.getFileStatus( aStatus ) == FileBase::E_None &&
            ( aStatus.getFileType() == FileStatus::Regular ||
              aStatus.getFileType() == FileStatus::Link ) )
        {
            String aFileName = aStatus.getFileName();
            int nToken = rSuffixes.GetTokenCount( ';' );
            while( nToken-- )
            {
                String aSuffix = rSuffixes.GetToken( nToken, ';' );
                if( aFileName.Len() > aSuffix.Len()+1 )
                {
                    String aExtension = aFileName.Copy( aFileName.Len()-aSuffix.Len() );
                    if( aFileName.GetChar( aFileName.Len()-aSuffix.Len()-1 ) == '.' &&
                        aExtension.EqualsIgnoreCaseAscii( aSuffix ) )
                    {
                        rResult.push_back( aFileName );
                        break;
                    }
                }
            }
        }
        else if( bRecursive &&
                 ( aStatus.getFileType() == FileStatus::Directory ||
                   aStatus.getFileType() == FileStatus::Link ) )
        {
            OUStringBuffer aSubDir( rDirectory );
            aSubDir.appendAscii( "/", 1 );
            aSubDir.append( aStatus.getFileName() );
            std::list< String > subfiles;
            FindFiles( aSubDir.makeStringAndClear(), subfiles, rSuffixes, bRecursive );
            for( std::list< String >::const_iterator it = subfiles.begin(); it != subfiles.end(); ++it )
            {
                OUStringBuffer aSubFile( aStatus.getFileName() );
                aSubFile.appendAscii( "/", 1 );
                aSubFile.append( *it );
                rResult.push_back( aSubFile.makeStringAndClear() );
            }
        }
    }
    aDir.close();
}

/*
 *  DelMultiListBox
 */

long DelMultiListBox::Notify( NotifyEvent& rEvent )
{
    long nRet = 0;

    if( rEvent.GetType() == EVENT_KEYINPUT &&
        rEvent.GetKeyEvent()->GetKeyCode().GetCode() == KEY_DELETE )
    {
        m_aDelPressedLink.Call( this );
        nRet = 1;
    }
    else
        nRet = MultiListBox::Notify( rEvent );

    return nRet;
}

/*
 *  DelListBox
 */

long DelListBox::Notify( NotifyEvent& rEvent )
{
    long nRet = 0;

    if( rEvent.GetType() == EVENT_KEYINPUT &&
        rEvent.GetKeyEvent()->GetKeyCode().GetCode() == KEY_DELETE )
    {
        m_aDelPressedLink.Call( this );
        nRet = 1;
    }
    else
        nRet = ListBox::Notify( rEvent );

    return nRet;
}

/*
 *  QueryString
 */

QueryString::QueryString( Window* pParent, String& rQuery, String& rRet, const ::std::list< String >& rChoices ) :
        ModalDialog( pParent, PaResId( RID_STRINGQUERYDLG ) ),
        m_aOKButton( this, PaResId( RID_STRQRY_BTN_OK ) ),
        m_aCancelButton( this, PaResId( RID_STRQRY_BTN_CANCEL ) ),
        m_aFixedText( this, PaResId( RID_STRQRY_TXT_RENAME ) ),
        m_aEdit( this, PaResId( RID_STRQRY_EDT_NEWNAME ) ),
        m_aComboBox( this, PaResId( RID_STRQRY_BOX_NEWNAME ) ),
        m_rReturnValue( rRet )
{
    m_aOKButton.SetClickHdl( LINK( this, QueryString, ClickBtnHdl ) );
    m_aFixedText.SetText( rQuery );
    if( rChoices.begin() != rChoices.end() )
    {
        m_aComboBox.SetText( m_rReturnValue );
        m_aComboBox.InsertEntry( m_rReturnValue );
        for( ::std::list<String>::const_iterator it = rChoices.begin(); it != rChoices.end(); ++it )
            m_aComboBox.InsertEntry( *it );
        m_aEdit.Show( FALSE );
        m_bUseEdit = false;
    }
    else
    {
        m_aEdit.SetText( m_rReturnValue );
        m_aComboBox.Show( FALSE );
        m_bUseEdit = true;
    }
    SetText( Application::GetDisplayName() );
    FreeResource();
}

QueryString::~QueryString()
{
}

IMPL_LINK( QueryString, ClickBtnHdl, Button*, pButton )
{
    if( pButton == &m_aOKButton )
    {
        m_rReturnValue = m_bUseEdit ? m_aEdit.GetText() : m_aComboBox.GetText();
        EndDialog( 1 );
    }
    else
        EndDialog(0);
    return 0;
}

/*
 *  AreYouSure
 */

BOOL padmin::AreYouSure( Window* pParent, int nRid )
{
    if( nRid == -1 )
        nRid = RID_YOU_SURE;
    QueryBox aQueryBox( pParent, WB_YES_NO | WB_DEF_NO,
                        String( PaResId( nRid ) ) );
    return aQueryBox.Execute() == RET_NO ? FALSE : TRUE;
}

/*
 *  getPadminRC
 */

static Config* pRC = NULL;

Config& padmin::getPadminRC()
{
    if( ! pRC )
    {
        static const char* pEnv = getenv( "HOME" );
        String aFileName( pEnv ? pEnv : "", osl_getThreadTextEncoding() );
        aFileName.AppendAscii( "/.padminrc" );
        pRC = new Config( aFileName );
    }
    return *pRC;
}

void padmin::freePadminRC()
{
    if( pRC )
        delete pRC, pRC = NULL;
}

bool padmin::chooseDirectory( Window* pParent, String& rInOutPath )
{
    bool bRet = false;
    Reference< XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
    if( xFactory.is() )
    {
        Reference< XFolderPicker > xFolderPicker( xFactory->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.ui.dialogs.FolderPicker" ) ) ), UNO_QUERY );
        if( xFolderPicker.is() )
        {
            Reference< XControlAccess > xCA( xFolderPicker, UNO_QUERY );
            if( xCA.is() )
            {
                try
                {
                    Any aState;
                    aState <<= sal_False;
                    xCA->setControlProperty( OUString( RTL_CONSTASCII_USTRINGPARAM( "HelpButton" ) ),
                                             OUString( RTL_CONSTASCII_USTRINGPARAM( "Visible" ) ),
                                             aState );

                }
                catch( ... )
                {
                }
            }
            INetURLObject aObj( rInOutPath, INET_PROT_FILE, INetURLObject::ENCODE_ALL );
            xFolderPicker->setDisplayDirectory( aObj.GetMainURL(INetURLObject::DECODE_TO_IURI) );
            if( xFolderPicker->execute() == ExecutableDialogResults::OK )
            {
                aObj = INetURLObject( xFolderPicker->getDirectory() );
                rInOutPath = aObj.PathToFileName();
                bRet = true;
            }
        }
#if OSL_DEBUG_LEVEL > 1
        else
            fprintf( stderr, "could not get FolderPicker service\n" );
#endif
    }
    return bRet;
}
<|endoftext|>


<commit_before>//
// Copyright (C) 2013 Mateusz Łoskot <mateusz@loskot.net>
// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
//
// This file is part of Qt Creator Boost.Build plugin project.
//
// This is free software; you can redistribute and/or modify it under
// the terms of the  GNU Lesser General Public License, Version 2.1
// as published by the Free Software Foundation.
// See accompanying file LICENSE.txt or copy at
// http://www.gnu.org/licenses/lgpl-2.1-standalone.html.
//
#include "bbbuildconfiguration.hpp"
#include "bbbuildstep.hpp"
#include "bbopenprojectwizard.hpp"
#include "bbproject.hpp"
#include "bbprojectfile.hpp"
#include "bbprojectmanager.hpp"
#include "bbprojectmanagerconstants.hpp"
#include "bbprojectnode.hpp"
#include "bbutility.hpp"
// Qt Creator
#include <app/app_version.h>
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <coreplugin/generatedfile.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <cpptools/cppmodelmanager.h>
#include <cpptools/cppprojects.h>
#include <cpptools/cpptoolsconstants.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectnodes.h>
#include <projectexplorer/target.h>
#include <qtsupport/customexecutablerunconfiguration.h>
#include <utils/fileutils.h>
#include <utils/QtConcurrentTools>
// Qt
#include <QDir>
#include <QFileInfo>
#include <QMessageBox>

namespace BoostBuildProjectManager {
namespace Internal {

Project::Project(ProjectManager* manager, QString const& fileName)
    : manager_(manager)
    , filePath_(fileName)
    , projectFile_(new ProjectFile(this, filePath_)) // enables projectDirectory()
    , projectNode_(new ProjectNode(this, projectFile_))
{
    Q_ASSERT(manager_);
    Q_ASSERT(!filePath_.isEmpty());

    setProjectContext(Core::Context(Constants::PROJECT_CONTEXT));
    setProjectLanguages(Core::Context(ProjectExplorer::Constants::LANG_CXX));
#if defined(IDE_VERSION_MAJOR) && (IDE_VERSION_MAJOR == 3 && IDE_VERSION_MINOR > 0)
    setId(Constants::PROJECT_ID);
#endif

    QFileInfo const projectFileInfo(filePath_);
    QDir const projectDir(projectFileInfo.dir());
    projectName_ = defaultProjectName(filePath_);
    filesFilePath_ = QFileInfo(projectDir
        , filePath_ + QLatin1String(Constants::EXT_JAMFILE_FILES)).absoluteFilePath();
    includesFilePath_ = QFileInfo(projectDir
        , filePath_ + QLatin1String(Constants::EXT_JAMFILE_INCLUDES)).absoluteFilePath();

    projectNode_->setDisplayName(displayName());

    manager_->registerProject(this);

    // TODO: Add file watchers
    //projectFileWatcher_->addPath(projectFilePath);
    //connect(projectFileWatcher_, SIGNAL(fileChanged(QString)), this, SLOT(refresh()));

    BBPM_QDEBUG("created project: " << displayName() << " in " << projectDirectory());
}

Project::~Project()
{
    manager_->unregisterProject(this);
    delete projectNode_;
}

QString Project::displayName() const
{
    return projectName_;
}

#if defined(IDE_VERSION_MAJOR) && (IDE_VERSION_MAJOR == 3 && IDE_VERSION_MINOR == 0)
Core::Id Project::id() const
{
    return Core::Id(Constants::PROJECT_ID);
}
#endif

Core::IDocument* Project::document() const
{
    return projectFile_;
}

ProjectExplorer::IProjectManager* Project::projectManager() const
{
    return manager_;
}

ProjectExplorer::ProjectNode* Project::rootProjectNode() const
{
    return projectNode_;
}

QStringList Project::files(FilesMode fileMode) const
{
    // TODO: handle ExcludeGeneratedFiles, but what files exactly?
    //       *.qtcreator.files, *.qtcreator.includes and *.user?
    Q_UNUSED(fileMode);
    return files_;
}

QStringList Project::files() const
{
    return files(FilesMode::AllFiles);
}

QString Project::filesFilePath() const
{
    Q_ASSERT(!filesFilePath_.isEmpty());
    return filesFilePath_;
}

QString Project::includesFilePath() const
{
    Q_ASSERT(!includesFilePath_.isEmpty());
    return includesFilePath_;
}

bool Project::needsConfiguration() const
{
    // TODO: Does Boost.Build project require any configuration on loading?
    // - Kit selection
    // - build/stage directory
    // - targets listing
    // CMakeProjectManager seems to request configuration in fromMap()

    return false;
}

/*static*/
QString Project::defaultProjectName(QString const& fileName)
{
    QFileInfo const fileInfo(fileName);
    return fileInfo.absoluteDir().dirName();
}

/*static*/
QString Project::defaultBuildDirectory(QString const& top)
{
    Utils::FileName fn(Utils::FileName::fromString(defaultWorkingDirectory(top)));
    fn.appendPath(BBPM_C(BUILD_DIR_NAME));
    return fn.toString();
}

/*static*/
QString Project::defaultWorkingDirectory(QString const& top)
{
    // Accepts both, project file or project directory, as top.
    return ProjectExplorer::Project::projectDirectory(Utils::FileName::fromString(top)).toString();
}

void Project::setProjectName(QString const& name)
{
    if (projectName_ != name)
    {
        projectName_ = name;
        projectNode_->setDisplayName(projectName_);
        // TODO: signal?
    }
}

QVariantMap Project::toMap() const
{
    QVariantMap map(ProjectExplorer::Project::toMap());
    map.insert(QLatin1String(Constants::P_KEY_PROJECTNAME), projectName_);
    return map;
}

// This function is called at the very beginning to restore the settings
// from .user file, if there is any with previous settings stored.
bool Project::fromMap(QVariantMap const& map)
{
    BBPM_QDEBUG(displayName());
    QTC_ASSERT(projectNode_, return false);

    if (!ProjectExplorer::Project::fromMap(map))
        return false;

    QVariantMap extraValues(map);
    if (!extraValues.contains(BBPM_C(P_KEY_PROJECTNAME)))
        extraValues.insert(BBPM_C(P_KEY_PROJECTNAME), projectName_);
    setProjectName(map.value(BBPM_C(P_KEY_PROJECTNAME)).toString());

    // Check required auxiliary files, run wizard of necessary
    if (!QFileInfo(filesFilePath()).exists() || !QFileInfo(includesFilePath()).exists())
    {
        ProjectExplorer::Kit* defaultKit = ProjectExplorer::KitManager::defaultKit();
        Q_ASSERT(defaultKit);

        OpenProjectWizard wizard(this);
        if (!wizard.run(defaultKit->displayName(), extraValues))
            return false;

        QVariantMap outputValues = wizard.outputValues();
        setProjectName(outputValues.value(BBPM_C(P_KEY_PROJECTNAME)).toString());
    }

    // Set up active ProjectConfiguration (aka Target).
    // NOTE: Call setActiveBuildConfiguration when creating new build configurations.
    if (!activeTarget())
    {
        // Create project configuration from scratch

        // TODO: Map the Kit to Boost.Build toolset option value
        ProjectExplorer::Kit* defaultKit = ProjectExplorer::KitManager::defaultKit();
        Q_ASSERT(defaultKit);

        // Creates as many {Build|Run|Deploy}Configurations for as corresponding
        // factories report as available.
        // For example, BuildConfigurationFactory::availableBuilds => Debug and Release
        ProjectExplorer::Target* target = createTarget(defaultKit);
        QTC_ASSERT(target, return false);

        addTarget(target);
    }
    else
    {
        // Configure project from settings sorced from .user file
        // TODO: Do we need to handle anything from .user here? Do we need this case?
        BBPM_QDEBUG(displayName() << "has user file");
    }

    // Sanity check (taken from GenericProjectManager):
    // We need both a BuildConfiguration and a RunConfiguration!
    QList<ProjectExplorer::Target*> targetList = targets();
    foreach (ProjectExplorer::Target* t, targetList)
    {
        if (!t->activeBuildConfiguration())
        {
            removeTarget(t);
            continue;
        }
        if (!t->activeRunConfiguration())
            t->addRunConfiguration(new QtSupport::CustomExecutableRunConfiguration(t));
    }

    QTC_ASSERT(hasActiveBuildSettings(), return false);
    QTC_ASSERT(activeTarget() != 0, return false);

    // Trigger loading project tree and parsing sources
    refresh();

    return true;
}

void Project::refresh()
{
    QTC_ASSERT(QFileInfo(filesFilePath()).exists(), return);
    QTC_ASSERT(QFileInfo(includesFilePath()).exists(), return);

    QSet<QString> oldFileList;
    oldFileList = files_.toSet();

    // Parse project:
    // The manager does not parse Jamfile files.
    // Only generates and parses list of source files in Jamfile.${JAMFILE_FILES_EXT}
    QString const projectPath(projectDirectory().toString());
    filesRaw_ = Utility::readLines(filesFilePath());
    files_ = Utility::makeAbsolutePaths(projectPath, filesRaw_);

    QStringList includePaths =
        Utility::makeAbsolutePaths(projectPath,
            Utility::readLines(includesFilePath()));

    emit fileListChanged();

    projectNode_->refresh(oldFileList);

    // TODO: Does it make sense to move this to separate asynchronous task?
    // TODO: extract updateCppCodeModel
    CppTools::CppModelManager *modelmanager =
        CppTools::CppModelManager::instance();
    if (modelmanager) {
        CppTools::ProjectInfo pinfo = modelmanager->projectInfo(this);

        CppTools::ProjectPartBuilder builder(pinfo);
        builder.setDisplayName(displayName());
        builder.setProjectFile(projectFilePath().toString());
        //builder.setDefines();	// TODO: waiting for Jamfile parser
        builder.setIncludePaths(QStringList() << projectDirectory().toString() << includePaths);

        const QList<Core::Id> languages = builder.createProjectPartsForFiles(files_);
        foreach (Core::Id language, languages)
            setProjectLanguage(language, true);

        cppModelFuture_.cancel();
        pinfo.finish();
        cppModelFuture_ = modelmanager->updateProjectInfo(pinfo);
    }
}

} // namespace Internal
} // namespace BoostBuildProjectManager
<commit_msg>Create a new ProjectInfo as we do not have one<commit_after>//
// Copyright (C) 2013 Mateusz Łoskot <mateusz@loskot.net>
// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
//
// This file is part of Qt Creator Boost.Build plugin project.
//
// This is free software; you can redistribute and/or modify it under
// the terms of the  GNU Lesser General Public License, Version 2.1
// as published by the Free Software Foundation.
// See accompanying file LICENSE.txt or copy at
// http://www.gnu.org/licenses/lgpl-2.1-standalone.html.
//
#include "bbbuildconfiguration.hpp"
#include "bbbuildstep.hpp"
#include "bbopenprojectwizard.hpp"
#include "bbproject.hpp"
#include "bbprojectfile.hpp"
#include "bbprojectmanager.hpp"
#include "bbprojectmanagerconstants.hpp"
#include "bbprojectnode.hpp"
#include "bbutility.hpp"
// Qt Creator
#include <app/app_version.h>
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <coreplugin/generatedfile.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <cpptools/cppmodelmanager.h>
#include <cpptools/cppprojects.h>
#include <cpptools/cpptoolsconstants.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectnodes.h>
#include <projectexplorer/target.h>
#include <qtsupport/customexecutablerunconfiguration.h>
#include <utils/fileutils.h>
#include <utils/QtConcurrentTools>
// Qt
#include <QDir>
#include <QFileInfo>
#include <QMessageBox>

namespace BoostBuildProjectManager {
namespace Internal {

Project::Project(ProjectManager* manager, QString const& fileName)
    : manager_(manager)
    , filePath_(fileName)
    , projectFile_(new ProjectFile(this, filePath_)) // enables projectDirectory()
    , projectNode_(new ProjectNode(this, projectFile_))
{
    Q_ASSERT(manager_);
    Q_ASSERT(!filePath_.isEmpty());

    setProjectContext(Core::Context(Constants::PROJECT_CONTEXT));
    setProjectLanguages(Core::Context(ProjectExplorer::Constants::LANG_CXX));
#if defined(IDE_VERSION_MAJOR) && (IDE_VERSION_MAJOR == 3 && IDE_VERSION_MINOR > 0)
    setId(Constants::PROJECT_ID);
#endif

    QFileInfo const projectFileInfo(filePath_);
    QDir const projectDir(projectFileInfo.dir());
    projectName_ = defaultProjectName(filePath_);
    filesFilePath_ = QFileInfo(projectDir
        , filePath_ + QLatin1String(Constants::EXT_JAMFILE_FILES)).absoluteFilePath();
    includesFilePath_ = QFileInfo(projectDir
        , filePath_ + QLatin1String(Constants::EXT_JAMFILE_INCLUDES)).absoluteFilePath();

    projectNode_->setDisplayName(displayName());

    manager_->registerProject(this);

    // TODO: Add file watchers
    //projectFileWatcher_->addPath(projectFilePath);
    //connect(projectFileWatcher_, SIGNAL(fileChanged(QString)), this, SLOT(refresh()));

    BBPM_QDEBUG("created project: " << displayName() << " in " << projectDirectory());
}

Project::~Project()
{
    manager_->unregisterProject(this);
    delete projectNode_;
}

QString Project::displayName() const
{
    return projectName_;
}

#if defined(IDE_VERSION_MAJOR) && (IDE_VERSION_MAJOR == 3 && IDE_VERSION_MINOR == 0)
Core::Id Project::id() const
{
    return Core::Id(Constants::PROJECT_ID);
}
#endif

Core::IDocument* Project::document() const
{
    return projectFile_;
}

ProjectExplorer::IProjectManager* Project::projectManager() const
{
    return manager_;
}

ProjectExplorer::ProjectNode* Project::rootProjectNode() const
{
    return projectNode_;
}

QStringList Project::files(FilesMode fileMode) const
{
    // TODO: handle ExcludeGeneratedFiles, but what files exactly?
    //       *.qtcreator.files, *.qtcreator.includes and *.user?
    Q_UNUSED(fileMode);
    return files_;
}

QStringList Project::files() const
{
    return files(FilesMode::AllFiles);
}

QString Project::filesFilePath() const
{
    Q_ASSERT(!filesFilePath_.isEmpty());
    return filesFilePath_;
}

QString Project::includesFilePath() const
{
    Q_ASSERT(!includesFilePath_.isEmpty());
    return includesFilePath_;
}

bool Project::needsConfiguration() const
{
    // TODO: Does Boost.Build project require any configuration on loading?
    // - Kit selection
    // - build/stage directory
    // - targets listing
    // CMakeProjectManager seems to request configuration in fromMap()

    return false;
}

/*static*/
QString Project::defaultProjectName(QString const& fileName)
{
    QFileInfo const fileInfo(fileName);
    return fileInfo.absoluteDir().dirName();
}

/*static*/
QString Project::defaultBuildDirectory(QString const& top)
{
    Utils::FileName fn(Utils::FileName::fromString(defaultWorkingDirectory(top)));
    fn.appendPath(BBPM_C(BUILD_DIR_NAME));
    return fn.toString();
}

/*static*/
QString Project::defaultWorkingDirectory(QString const& top)
{
    // Accepts both, project file or project directory, as top.
    return ProjectExplorer::Project::projectDirectory(Utils::FileName::fromString(top)).toString();
}

void Project::setProjectName(QString const& name)
{
    if (projectName_ != name)
    {
        projectName_ = name;
        projectNode_->setDisplayName(projectName_);
        // TODO: signal?
    }
}

QVariantMap Project::toMap() const
{
    QVariantMap map(ProjectExplorer::Project::toMap());
    map.insert(QLatin1String(Constants::P_KEY_PROJECTNAME), projectName_);
    return map;
}

// This function is called at the very beginning to restore the settings
// from .user file, if there is any with previous settings stored.
bool Project::fromMap(QVariantMap const& map)
{
    BBPM_QDEBUG(displayName());
    QTC_ASSERT(projectNode_, return false);

    if (!ProjectExplorer::Project::fromMap(map))
        return false;

    QVariantMap extraValues(map);
    if (!extraValues.contains(BBPM_C(P_KEY_PROJECTNAME)))
        extraValues.insert(BBPM_C(P_KEY_PROJECTNAME), projectName_);
    setProjectName(map.value(BBPM_C(P_KEY_PROJECTNAME)).toString());

    // Check required auxiliary files, run wizard of necessary
    if (!QFileInfo(filesFilePath()).exists() || !QFileInfo(includesFilePath()).exists())
    {
        ProjectExplorer::Kit* defaultKit = ProjectExplorer::KitManager::defaultKit();
        Q_ASSERT(defaultKit);

        OpenProjectWizard wizard(this);
        if (!wizard.run(defaultKit->displayName(), extraValues))
            return false;

        QVariantMap outputValues = wizard.outputValues();
        setProjectName(outputValues.value(BBPM_C(P_KEY_PROJECTNAME)).toString());
    }

    // Set up active ProjectConfiguration (aka Target).
    // NOTE: Call setActiveBuildConfiguration when creating new build configurations.
    if (!activeTarget())
    {
        // Create project configuration from scratch

        // TODO: Map the Kit to Boost.Build toolset option value
        ProjectExplorer::Kit* defaultKit = ProjectExplorer::KitManager::defaultKit();
        Q_ASSERT(defaultKit);

        // Creates as many {Build|Run|Deploy}Configurations for as corresponding
        // factories report as available.
        // For example, BuildConfigurationFactory::availableBuilds => Debug and Release
        ProjectExplorer::Target* target = createTarget(defaultKit);
        QTC_ASSERT(target, return false);

        addTarget(target);
    }
    else
    {
        // Configure project from settings sorced from .user file
        // TODO: Do we need to handle anything from .user here? Do we need this case?
        BBPM_QDEBUG(displayName() << "has user file");
    }

    // Sanity check (taken from GenericProjectManager):
    // We need both a BuildConfiguration and a RunConfiguration!
    QList<ProjectExplorer::Target*> targetList = targets();
    foreach (ProjectExplorer::Target* t, targetList)
    {
        if (!t->activeBuildConfiguration())
        {
            removeTarget(t);
            continue;
        }
        if (!t->activeRunConfiguration())
            t->addRunConfiguration(new QtSupport::CustomExecutableRunConfiguration(t));
    }

    QTC_ASSERT(hasActiveBuildSettings(), return false);
    QTC_ASSERT(activeTarget() != 0, return false);

    // Trigger loading project tree and parsing sources
    refresh();

    return true;
}

void Project::refresh()
{
    QTC_ASSERT(QFileInfo(filesFilePath()).exists(), return);
    QTC_ASSERT(QFileInfo(includesFilePath()).exists(), return);

    QSet<QString> oldFileList;
    oldFileList = files_.toSet();

    // Parse project:
    // The manager does not parse Jamfile files.
    // Only generates and parses list of source files in Jamfile.${JAMFILE_FILES_EXT}
    QString const projectPath(projectDirectory().toString());
    filesRaw_ = Utility::readLines(filesFilePath());
    files_ = Utility::makeAbsolutePaths(projectPath, filesRaw_);

    QStringList includePaths =
        Utility::makeAbsolutePaths(projectPath,
            Utility::readLines(includesFilePath()));

    emit fileListChanged();

    projectNode_->refresh(oldFileList);

    // TODO: Does it make sense to move this to separate asynchronous task?
    // TODO: extract updateCppCodeModel
    CppTools::CppModelManager *modelmanager =
        CppTools::CppModelManager::instance();
    if (modelmanager) {
        CppTools::ProjectInfo pinfo(this);

        CppTools::ProjectPartBuilder builder(pinfo);
        builder.setDisplayName(displayName());
        builder.setProjectFile(projectFilePath().toString());
        //builder.setDefines();	// TODO: waiting for Jamfile parser
        builder.setIncludePaths(QStringList() << projectDirectory().toString() << includePaths);

        const QList<Core::Id> languages = builder.createProjectPartsForFiles(files_);
        foreach (Core::Id language, languages)
            setProjectLanguage(language, true);

        cppModelFuture_.cancel();
        pinfo.finish();
        cppModelFuture_ = modelmanager->updateProjectInfo(pinfo);
    }
}

} // namespace Internal
} // namespace BoostBuildProjectManager
<|endoftext|>


<commit_before>#ifndef CPP_UNIT_TEST_H_
#define CPP_UNIT_TEST_H_

///////////////////////////////////////////////////////////////////////////////
///
/// \brief    A light-weight and easy to use unit testing framework for C++
/// \details  Header-only unit testing framework that makes unit testing easy
///           and quick to set up.
/// \version  0.1.0
/// \date     December 2011
/// \author   Tommy Back
///
///
/// Simply include this header file to get started.
///
/// \code
/// #include <cpput/TestHarness.h>
/// #include <Foo.h>
///
/// TEST(Foo, some_descriptive_name)
/// {
///   // Arrange
///   Foo foo;
///   // Act
///   bool result = foo.isBar();
///   // Assert
///   ASSERT_TRUE(result);
/// }
/// \endcode
///
/// In case you want to keep a single file with tests that compile to an
/// executable you can also add the main function to the end of the file.
/// This is simple to do with the provided macro:
///
/// \code
/// DECLARE_TEST_MAIN_FUNCTION;
/// \endcode
///
/// For larger test suits, it's recommended to group the tests per class
/// in separate files and let the compiler combine them into a single
/// executable which has a main.cpp file that only has the main function
/// declared.
///
/// \example
/// [Test_Foo.cpp]
///
/// \code
/// #include <cpput/TestHarness.h>
/// #include <Foo.h>
///
/// TEST(Foo, foo_bar_z)
/// {
///   ...
/// \endcode
///
/// [main.cpp]
///
/// \code
/// #include <cpput/TestHarness.h>
///
/// DECLARE_TEST_MAIN_FUNCTION;
/// \endcode
///
///

#include <ctime>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <sstream>

namespace test
{
namespace unit
{

struct Failure
{
  Failure(const std::string& filename, std::size_t line, const std::string& message)
    : type_("Failure") // TODO: type of failure?
    , filename_(filename)
    , line_(line)
    , message_(message)
  {
  }

  friend std::ostream& operator<<(std::ostream& os, const Failure& f)
  {
    os << f.filename_ << ", line " << f.line_ << ": " << f.message_;
    return os;
  }

  std::string type_;
  std::string filename_;
  std::size_t line_;
  std::string message_;
};

/////////////////////////////////////////////////////////////////////////////

struct IOutputter
{
  virtual ~IOutputter() {}

  virtual void startTest(const std::string& className, const std::string& name) = 0;
  virtual void endTest(bool success) = 0;

  virtual void failure(const Failure& failure) = 0;
  virtual int getNumberOfFailures() const = 0;
};

/////////////////////////////////////////////////////////////////////////////

class TextOutputter : public IOutputter
{
public:
  TextOutputter()
    : testCount_(0)
  {
  }

  virtual ~TextOutputter()
  {
    std::cout << "\n";
    if (failures_.empty())
    {
      std::cout << "All tests pass.\n";
      return;
    }
    // print details of all failures
    std::cout << "\n";
    for (std::size_t i=0; i<failures_.size(); ++i)
    {
      std::cout << failures_[i] << "\n";
    }
    std::cout << "\n" << failures_.size() << " out of " << testCount_ << " tests failed.\n";
  }

  virtual void startTest(const std::string& className, const std::string& name)
  {
    testCount_++;
  }

  virtual void endTest(bool success)
  {
    if (success)
      std::cout << '.';
    else
      std::cout << 'F';
  }

  virtual void failure(const Failure& failure)
  {
    failures_.push_back(failure);
  }

  virtual int getNumberOfFailures() const { return failures_.size(); }

private:
  int                  testCount_;
  std::vector<Failure> failures_;
};

/////////////////////////////////////////////////////////////////////////////

class XmlOutputter : public IOutputter
{
public:
  XmlOutputter()
    : startTime_(0)
  {
    std::cout << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    std::cout << "<testsuite>\n";
  }

  virtual ~XmlOutputter()
  {
    std::cout << "</testsuite>\n";
  }

  virtual void startTest(const std::string& className, const std::string& name)
  {
    startTime_ = std::clock();
    std::cout << "  <testcase classname=\""
              << className
              << "\" name=\""
              << name
              << "\" time=\"";
  }

  virtual void endTest(bool success)
  {
    if (success)
    {
      std::cout << static_cast<float>(std::clock()-startTime_)/CLOCKS_PER_SEC << "\"";
      std::cout << "/>\n";
    }
    else
      std::cout << "  </testcase>\n";
  }

  virtual void failure(const Failure& failure)
  {
    std::cout << static_cast<float>(std::clock()-startTime_)/CLOCKS_PER_SEC << "\"";
    std::cout << ">\n"
              << "    <failure type=\""
              << failure.type_
              << "\">"
              << failure.message_
              << " in "
              << failure.filename_
              << ", line "
              << failure.line_
              << "</failure>\n";
    failureCount_++;
  }

  virtual int getNumberOfFailures() const
  {
    return failureCount_;
  }

private:
  std::clock_t startTime_;
  int          failureCount_;
};

/////////////////////////////////////////////////////////////////////////////

struct Result
{
  Result(const std::string& testClassName,
         const std::string& testName,
         IOutputter& out)
    : out_(out)
    , pass_(true)
  {
    out_.startTest(testClassName, testName);
  }

  ~Result()
  {
    out_.endTest(pass_);
  }

  template <typename T, typename U>
  void addFailure(const char* filename,
                  std::size_t line,
                  T expected,
                  U actual)
  {
    pass_ = false;
    std::stringstream ss;
    ss << std::setprecision(20)
       << "failed comparison, expected " << expected
       << " got " << actual << "\n";
    Failure f(filename, line, ss.str());
    out_.failure(f);
  }

  void addFailure(const char* filename,
                  std::size_t line,
                  const char* message)
  {
    pass_ = false;
    Failure f(filename, line, message);
    out_.failure(f);
  }

  IOutputter& out_;
  bool        pass_;
};

/////////////////////////////////////////////////////////////////////////////

class Repository;

class Case
{
  friend class Repository;

public:
  Case(const char* className, const char* name);
  virtual ~Case() {}

  void run(IOutputter& out)
  {
    Result result(test_unit_class_name_, test_unit_name_, out);
    try
    {
      do_run(result);
    }
    catch (const std::exception& e)
    {
      result.addFailure(__FILE__, __LINE__, std::string("Unexpected exception: ").append(e.what()).c_str());
    }
    catch (...)
    {
      result.addFailure(__FILE__, __LINE__, "Unspecified exception!");
    }
  }

  Case* next() { return test_unit_next_; }

private:
  virtual void do_run(Result& testResult_) = 0;

private:
  std::string test_unit_class_name_;
  std::string test_unit_name_;
  Case*       test_unit_next_;
};

/////////////////////////////////////////////////////////////////////////////

class Repository
{
public:
  static Repository& instance()
  {
    static Repository repo;
    return repo;
  }

  void add(Case* tc)
  {
    if (!cases_)
    {
      cases_ = tc;
      return;
    }

    // add as last
    Case* tmp = cases_;
    while (tmp->test_unit_next_)
      tmp = tmp->test_unit_next_;
    tmp->test_unit_next_ = tc;
  }

  Case* getCases() { return cases_; }

private:
  Repository() : cases_(0) {}
  Repository(const Repository& other);
  Repository& operator=(const Repository& rhs) const;

private:
  Case* cases_;
};

inline Case::Case(const char* className, const char* name)
  : test_unit_class_name_(className)
  , test_unit_name_(name)
  , test_unit_next_(0)
{
  Repository::instance().add(this);
}

/////////////////////////////////////////////////////////////////////////////

struct Runner
{
  static int run(bool xmlOutput=false)
  {
    if (xmlOutput)
    {
      XmlOutputter out;
      return do_run(out);
    }
    TextOutputter out;
    return do_run(out);
  }

private:
  static int do_run(IOutputter& out)
  {
    Case* c = Repository::instance().getCases();
    while (c)
    {
      c->run(out);
      c = c->next();
    }
    return out.getNumberOfFailures();
  }

private:
  Runner();
  Runner(const Runner& other);
  Runner& operator=(const Runner& rhs) const;
};

} // namespace unit
} // namespace test

// Convenience macro to get main function.
// TODO: check properly for -xmloutput
#define DECLARE_TEST_MAIN_FUNCTION \
int main(int argc, char* argv[]) { \
  return test::unit::Runner::run(argc > 1); \
}

///////////////////////////////////////////////////////////////////////////////
// Test Case Macros
///////////////////////////////////////////////////////////////////////////////

/// Stand-alone test case.
///
#define TEST(group,name) \
class group##name##Test : public test::unit::Case \
{ \
public: \
  group##name##Test() : test::unit::Case(#group,#name) {} \
  virtual ~group##name##Test() {} \
private: \
  virtual void do_run(test::unit::Result& testResult_); \
} group##name##TestInstance; \
inline void group##name##Test::do_run(test::unit::Result& testResult_)

/// Test case with fixture.
///
#define TEST_F(group,name) \
class group##name##FixtureTest : public group { \
public: \
    void do_run(test::unit::Result& testResult_); \
}; \
class group##name##Test : public test::unit::Case { \
public: \
    group##name##Test() : Case(#group,#name) {} \
    virtual void do_run(test::unit::Result& testResult_); \
} group##name##TestInstance; \
inline void group##name##Test::do_run(test::unit::Result& testResult_) { \
  group##name##FixtureTest test; \
  test.do_run(testResult_); \
} \
inline void group##name##FixtureTest::do_run(test::unit::Result& testResult_)

///////////////////////////////////////////////////////////////////////////////
// Assertion Macros
///////////////////////////////////////////////////////////////////////////////

#define ASSERT_TRUE(expression) \
{ \
  if (!(expression)) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, #expression); \
    return; \
  } \
}

#define ASSERT_FALSE(expression) \
{ \
  if ((expression)) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, #expression); \
    return; \
  } \
}

#define ASSERT_EQ(expected,actual) \
{ \
  if (!((expected) == (actual))) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, expected, actual); \
    return; \
  } \
}

#define ASSERT_NEQ(expected,actual) \
{ \
  if (((expected) == (actual))) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, expected, actual); \
    return; \
  } \
}

#define ASSERT_STREQ(expected,actual) { \
  if (!(std::string(expected) == std::string(actual))) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, expected, actual); \
    return; \
  } \
}

#define ASSERT_NEAR(expected,actual,epsilon) \
{ \
  double actualTmp = actual; \
  double expectedTmp = expected; \
  double diff = expectedTmp - actualTmp; \
  if ((diff > epsilon) || (-diff > epsilon)) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, expectedTmp, actualTmp); \
    return; \
  } \
}

#endif // CPP_UNIT_TEST_H_
<commit_msg>Changed namespace to cpput.<commit_after>#ifndef CPP_UNIT_TEST_H_
#define CPP_UNIT_TEST_H_

///////////////////////////////////////////////////////////////////////////////
///
/// \brief    A light-weight and easy to use unit testing framework for C++
/// \details  Header-only unit testing framework that makes unit testing easy
///           and quick to set up.
/// \version  0.1.0
/// \date     December 2011
/// \author   Tommy Back
///
///
/// Simply include this header file to get started.
///
/// \code
/// #include <cpput/TestHarness.h>
/// #include <Foo.h>
///
/// TEST(Foo, some_descriptive_name)
/// {
///   // Arrange
///   Foo foo;
///   // Act
///   bool result = foo.isBar();
///   // Assert
///   ASSERT_TRUE(result);
/// }
/// \endcode
///
/// In case you want to keep a single file with tests that compile to an
/// executable you can also add the main function to the end of the file.
/// This is simple to do with the provided macro:
///
/// \code
/// DECLARE_TEST_MAIN_FUNCTION;
/// \endcode
///
/// For larger test suits, it's recommended to group the tests per class
/// in separate files and let the compiler combine them into a single
/// executable which has a main.cpp file that only has the main function
/// declared.
///
/// \example
/// [Test_Foo.cpp]
///
/// \code
/// #include <cpput/TestHarness.h>
/// #include <Foo.h>
///
/// TEST(Foo, foo_bar_z)
/// {
///   ...
/// \endcode
///
/// [main.cpp]
///
/// \code
/// #include <cpput/TestHarness.h>
///
/// DECLARE_TEST_MAIN_FUNCTION;
/// \endcode
///
///

#include <ctime>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <sstream>

namespace cpput
{

struct Failure
{
  Failure(const std::string& filename, std::size_t line, const std::string& message)
    : type_("Failure") // TODO: type of failure?
    , filename_(filename)
    , line_(line)
    , message_(message)
  {
  }

  friend std::ostream& operator<<(std::ostream& os, const Failure& f)
  {
    os << f.filename_ << ", line " << f.line_ << ": " << f.message_;
    return os;
  }

  std::string type_;
  std::string filename_;
  std::size_t line_;
  std::string message_;
};

/////////////////////////////////////////////////////////////////////////////

struct IOutputter
{
  virtual ~IOutputter() {}

  virtual void startTest(const std::string& className, const std::string& name) = 0;
  virtual void endTest(bool success) = 0;

  virtual void failure(const Failure& failure) = 0;
  virtual int getNumberOfFailures() const = 0;
};

/////////////////////////////////////////////////////////////////////////////

class TextOutputter : public IOutputter
{
public:
  TextOutputter()
    : testCount_(0)
  {
  }

  virtual ~TextOutputter()
  {
    std::cout << "\n";
    if (failures_.empty())
    {
      std::cout << "All tests pass.\n";
      return;
    }
    // print details of all failures
    std::cout << "\n";
    for (std::size_t i=0; i<failures_.size(); ++i)
    {
      std::cout << failures_[i] << "\n";
    }
    std::cout << "\n" << failures_.size() << " out of " << testCount_ << " tests failed.\n";
  }

  virtual void startTest(const std::string& className, const std::string& name)
  {
    testCount_++;
  }

  virtual void endTest(bool success)
  {
    if (success)
      std::cout << '.';
    else
      std::cout << 'F';
  }

  virtual void failure(const Failure& failure)
  {
    failures_.push_back(failure);
  }

  virtual int getNumberOfFailures() const { return failures_.size(); }

private:
  int                  testCount_;
  std::vector<Failure> failures_;
};

/////////////////////////////////////////////////////////////////////////////

class XmlOutputter : public IOutputter
{
public:
  XmlOutputter()
    : startTime_(0)
  {
    std::cout << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    std::cout << "<testsuite>\n";
  }

  virtual ~XmlOutputter()
  {
    std::cout << "</testsuite>\n";
  }

  virtual void startTest(const std::string& className, const std::string& name)
  {
    startTime_ = std::clock();
    std::cout << "  <testcase classname=\""
              << className
              << "\" name=\""
              << name
              << "\" time=\"";
  }

  virtual void endTest(bool success)
  {
    if (success)
    {
      std::cout << static_cast<float>(std::clock()-startTime_)/CLOCKS_PER_SEC << "\"";
      std::cout << "/>\n";
    }
    else
      std::cout << "  </testcase>\n";
  }

  virtual void failure(const Failure& failure)
  {
    std::cout << static_cast<float>(std::clock()-startTime_)/CLOCKS_PER_SEC << "\"";
    std::cout << ">\n"
              << "    <failure type=\""
              << failure.type_
              << "\">"
              << failure.message_
              << " in "
              << failure.filename_
              << ", line "
              << failure.line_
              << "</failure>\n";
    failureCount_++;
  }

  virtual int getNumberOfFailures() const
  {
    return failureCount_;
  }

private:
  std::clock_t startTime_;
  int          failureCount_;
};

/////////////////////////////////////////////////////////////////////////////

struct Result
{
  Result(const std::string& testClassName,
         const std::string& testName,
         IOutputter& out)
    : out_(out)
    , pass_(true)
  {
    out_.startTest(testClassName, testName);
  }

  ~Result()
  {
    out_.endTest(pass_);
  }

  template <typename T, typename U>
  void addFailure(const char* filename,
                  std::size_t line,
                  T expected,
                  U actual)
  {
    pass_ = false;
    std::stringstream ss;
    ss << std::setprecision(20)
       << "failed comparison, expected " << expected
       << " got " << actual << "\n";
    Failure f(filename, line, ss.str());
    out_.failure(f);
  }

  void addFailure(const char* filename,
                  std::size_t line,
                  const char* message)
  {
    pass_ = false;
    Failure f(filename, line, message);
    out_.failure(f);
  }

  IOutputter& out_;
  bool        pass_;
};

/////////////////////////////////////////////////////////////////////////////

class Repository;

class Case
{
  friend class Repository;

public:
  Case(const char* className, const char* name);
  virtual ~Case() {}

  void run(IOutputter& out)
  {
    Result result(test_unit_class_name_, test_unit_name_, out);
    try
    {
      do_run(result);
    }
    catch (const std::exception& e)
    {
      result.addFailure(__FILE__, __LINE__, std::string("Unexpected exception: ").append(e.what()).c_str());
    }
    catch (...)
    {
      result.addFailure(__FILE__, __LINE__, "Unspecified exception!");
    }
  }

  Case* next() { return test_unit_next_; }

private:
  virtual void do_run(Result& testResult_) = 0;

private:
  std::string test_unit_class_name_;
  std::string test_unit_name_;
  Case*       test_unit_next_;
};

/////////////////////////////////////////////////////////////////////////////

class Repository
{
public:
  static Repository& instance()
  {
    static Repository repo;
    return repo;
  }

  void add(Case* tc)
  {
    if (!cases_)
    {
      cases_ = tc;
      return;
    }

    // add as last
    Case* tmp = cases_;
    while (tmp->test_unit_next_)
      tmp = tmp->test_unit_next_;
    tmp->test_unit_next_ = tc;
  }

  Case* getCases() { return cases_; }

private:
  Repository() : cases_(0) {}
  Repository(const Repository& other);
  Repository& operator=(const Repository& rhs) const;

private:
  Case* cases_;
};

inline Case::Case(const char* className, const char* name)
  : test_unit_class_name_(className)
  , test_unit_name_(name)
  , test_unit_next_(0)
{
  Repository::instance().add(this);
}

/////////////////////////////////////////////////////////////////////////////

struct Runner
{
  static int run(bool xmlOutput=false)
  {
    if (xmlOutput)
    {
      XmlOutputter out;
      return do_run(out);
    }
    TextOutputter out;
    return do_run(out);
  }

private:
  static int do_run(IOutputter& out)
  {
    Case* c = Repository::instance().getCases();
    while (c)
    {
      c->run(out);
      c = c->next();
    }
    return out.getNumberOfFailures();
  }

private:
  Runner();
  Runner(const Runner& other);
  Runner& operator=(const Runner& rhs) const;
};

} // namespace cpput

// Convenience macro to get main function.
// TODO: check properly for -xmloutput
#define DECLARE_TEST_MAIN_FUNCTION \
int main(int argc, char* argv[]) { \
  return ::cpput::Runner::run(argc > 1); \
}

///////////////////////////////////////////////////////////////////////////////
// Test Case Macros
///////////////////////////////////////////////////////////////////////////////

/// Stand-alone test case.
///
#define TEST(group,name) \
class group##name##Test : public cpput::Case \
{ \
public: \
  group##name##Test() : cpput::Case(#group,#name) {} \
  virtual ~group##name##Test() {} \
private: \
  virtual void do_run(cpput::Result& testResult_); \
} group##name##TestInstance; \
inline void group##name##Test::do_run(cpput::Result& testResult_)

/// Test case with fixture.
///
#define TEST_F(group,name) \
class group##name##FixtureTest : public group { \
public: \
    void do_run(cpput::Result& testResult_); \
}; \
class group##name##Test : public cpput::Case { \
public: \
    group##name##Test() : Case(#group,#name) {} \
    virtual void do_run(cpput::Result& testResult_); \
} group##name##TestInstance; \
inline void group##name##Test::do_run(cpput::Result& testResult_) { \
  group##name##FixtureTest test; \
  test.do_run(testResult_); \
} \
inline void group##name##FixtureTest::do_run(cpput::Result& testResult_)

///////////////////////////////////////////////////////////////////////////////
// Assertion Macros
///////////////////////////////////////////////////////////////////////////////

#define ASSERT_TRUE(expression) \
{ \
  if (!(expression)) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, #expression); \
    return; \
  } \
}

#define ASSERT_FALSE(expression) \
{ \
  if ((expression)) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, #expression); \
    return; \
  } \
}

#define ASSERT_EQ(expected,actual) \
{ \
  if (!((expected) == (actual))) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, expected, actual); \
    return; \
  } \
}

#define ASSERT_NEQ(expected,actual) \
{ \
  if (((expected) == (actual))) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, expected, actual); \
    return; \
  } \
}

#define ASSERT_STREQ(expected,actual) { \
  if (!(std::string(expected) == std::string(actual))) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, expected, actual); \
    return; \
  } \
}

#define ASSERT_NEAR(expected,actual,epsilon) \
{ \
  double actualTmp = actual; \
  double expectedTmp = expected; \
  double diff = expectedTmp - actualTmp; \
  if ((diff > epsilon) || (-diff > epsilon)) \
  { \
    testResult_.addFailure(__FILE__, __LINE__, expectedTmp, actualTmp); \
    return; \
  } \
}

#endif // CPP_UNIT_TEST_H_
<|endoftext|>


<commit_before>#include "app.h"

App::App(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
	connect(ui.parAutoWrite, SIGNAL(triggered(bool)), this, SLOT(parAutoWrite_checked()));
	connect(ui.parHandWrite, SIGNAL(triggered(bool)), this, SLOT(parHandWrite_checked()));
}

App::~App()
{

}

void App::on_getFileButton_clicked()
{
	filePath = QFileDialog::getOpenFileName(0, "Select file", "*.csv");

	fw = new FileWorker();
	if (fw->loadFile(filePath))
	{
		ui.filePathLine->clear();
		ui.filePathLine->insert(filePath);
		dataForParams = fw->getTable();
		ui.getParametersButton->setEnabled(true);
	}
	fw->~FileWorker();

	ui.getParametersButton->setEnabled(true);
}

void App::on_getParametersButton_clicked()
{
	ui.getCostButton->setEnabled(true);

	ui.v0_Line->setReadOnly(false);
	ui.theta_Line->setReadOnly(false);
	ui.kappa_Line->setReadOnly(false);
	ui.sigma_Line->setReadOnly(false);
	ui.rho_Line->setReadOnly(false);

	// Все данные для расчета находятся в dataForParam (это QVector<optionParams>, typedef лежит в file_worker.h)
}

void App::on_getCostButton_clicked()
{
	/***********************
	double N = 18;
	double S = 95;
	double K = 100;
	double T = 1;
	double r = 0;
	double v0 = 0.04;
	double theta = 0.04;
	double kappa = 0.25;
	double sigma = 0.5;
	double rho = -0.6;
	***********************/

	if (ui.parHandWrite->isChecked())
	{
		bool *b = new bool[10];

		//data.N = ui.N_Line->text().toInt(&b[0]);
		data.S = ui.S_Line->text().toDouble(&b[1]);
		data.K = ui.K_Line->text().toDouble(&b[2]);
		data.T = ui.T_Line->text().toDouble(&b[3]);
		data.r = ui.r_Line->text().toDouble(&b[4]);
		data.v0 = ui.v0_Line->text().toDouble(&b[5]);
		data.theta = ui.theta_Line->text().toDouble(&b[6]);
		data.kappa = ui.kappa_Line->text().toDouble(&b[7]);
		data.sigma = ui.sigma_Line->text().toDouble(&b[8]);
		data.rho = ui.rho_Line->text().toDouble(&b[9]);

		if (!(b[0] && b[1] && b[2] && b[3] && b[4] && b[5] && b[6] && b[7] && b[8] && b[9]))
		{
			QMessageBox::StandardButton Load;
			Load = QMessageBox::critical(this, "Error", "The parameters must be a number", QMessageBox::Ok);
		}
		else
		{
			double price = callPriceFFT(18, data.S, data.K, data.T, data.r, data.v0, data.theta, data.kappa, data.sigma, data.rho);
			ui.Opt_Line->setText(QString::number(price));
		}
	}

}

void App::parAutoWrite_checked()
{
	ui.parHandWrite->setChecked(false);
	ui.filePathLine->setEnabled(true);
	ui.getFileButton->setEnabled(true);
	ui.getParametersButton->setEnabled(false);

	ui.v0_Line->clear();
	ui.theta_Line->clear();
	ui.kappa_Line->clear();
	ui.sigma_Line->clear();
	ui.rho_Line->clear();
	ui.v0_Line->setReadOnly(true);
	ui.theta_Line->setReadOnly(true);
	ui.kappa_Line->setReadOnly(true);
	ui.sigma_Line->setReadOnly(true);
	ui.rho_Line->setReadOnly(true);

	ui.getCostButton->setEnabled(false);
	ui.Opt_Line->clear();
}

void App::parHandWrite_checked()
{
	ui.parAutoWrite->setChecked(false);

	ui.filePathLine->clear();
	ui.filePathLine->setEnabled(false);
	if (!dataForParams.isEmpty())
	{
		dataForParams.clear();
	}

	ui.getFileButton->setEnabled(false);
	ui.getParametersButton->setEnabled(false);

	ui.v0_Line->clear();
	ui.theta_Line->clear();
	ui.kappa_Line->clear();
	ui.sigma_Line->clear();
	ui.rho_Line->clear();

	ui.Opt_Line->clear();
}<commit_msg>Поправил режим<commit_after>#include "app.h"

App::App(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
	connect(ui.parAutoWrite, SIGNAL(triggered(bool)), this, SLOT(parAutoWrite_checked()));
	connect(ui.parHandWrite, SIGNAL(triggered(bool)), this, SLOT(parHandWrite_checked()));
}

App::~App()
{

}

void App::on_getFileButton_clicked()
{
	filePath = QFileDialog::getOpenFileName(0, "Select file", "*.csv");

	fw = new FileWorker();
	if (fw->loadFile(filePath))
	{
		ui.filePathLine->clear();
		ui.filePathLine->insert(filePath);
		dataForParams = fw->getTable();
		ui.getParametersButton->setEnabled(true);
	}
	fw->~FileWorker();

	ui.getParametersButton->setEnabled(true);
}

void App::on_getParametersButton_clicked()
{
	ui.getCostButton->setEnabled(true);

	ui.v0_Line->setReadOnly(false);
	ui.theta_Line->setReadOnly(false);
	ui.kappa_Line->setReadOnly(false);
	ui.sigma_Line->setReadOnly(false);
	ui.rho_Line->setReadOnly(false);

	// Все данные для расчета находятся в dataForParam (это QVector<optionParams>, typedef лежит в file_worker.h)
}

void App::on_getCostButton_clicked()
{
	/***********************
	double N = 18;
	double S = 95;
	double K = 100;
	double T = 1;
	double r = 0;
	double v0 = 0.04;
	double theta = 0.04;
	double kappa = 0.25;
	double sigma = 0.5;
	double rho = -0.6;
	***********************/

	if (ui.parHandWrite->isChecked())
	{
		bool *b = new bool[10];

		//data.N = ui.N_Line->text().toInt(&b[0]);
		data.S = ui.S_Line->text().toDouble(&b[1]);
		data.K = ui.K_Line->text().toDouble(&b[2]);
		data.T = ui.T_Line->text().toDouble(&b[3]);
		data.r = ui.r_Line->text().toDouble(&b[4]);
		data.v0 = ui.v0_Line->text().toDouble(&b[5]);
		data.theta = ui.theta_Line->text().toDouble(&b[6]);
		data.kappa = ui.kappa_Line->text().toDouble(&b[7]);
		data.sigma = ui.sigma_Line->text().toDouble(&b[8]);
		data.rho = ui.rho_Line->text().toDouble(&b[9]);

		if (!(b[0] && b[1] && b[2] && b[3] && b[4] && b[5] && b[6] && b[7] && b[8] && b[9]))
		{
			QMessageBox::StandardButton Load;
			Load = QMessageBox::critical(this, "Error", "The parameters must be a number", QMessageBox::Ok);
		}
		else
		{
			double price = callPriceFFT(18, data.S, data.K, data.T, data.r, data.v0, data.theta, data.kappa, data.sigma, data.rho);
			ui.Opt_Line->setText(QString::number(price));
		}
	}

}

void App::parAutoWrite_checked()
{
	ui.parHandWrite->setChecked(false);
	ui.filePathLine->setEnabled(true);
	ui.getFileButton->setEnabled(true);
	ui.getParametersButton->setEnabled(false);

	ui.v0_Line->clear();
	ui.theta_Line->clear();
	ui.kappa_Line->clear();
	ui.sigma_Line->clear();
	ui.rho_Line->clear();
	ui.v0_Line->setReadOnly(true);
	ui.theta_Line->setReadOnly(true);
	ui.kappa_Line->setReadOnly(true);
	ui.sigma_Line->setReadOnly(true);
	ui.rho_Line->setReadOnly(true);

	ui.getCostButton->setEnabled(false);
	ui.Opt_Line->clear();
}

void App::parHandWrite_checked()
{
	ui.parAutoWrite->setChecked(false);

	ui.filePathLine->clear();
	ui.filePathLine->setEnabled(false);
	if (!dataForParams.isEmpty())
	{
		dataForParams.clear();
	}

	ui.getFileButton->setEnabled(false);
	ui.getParametersButton->setEnabled(false);

	ui.v0_Line->clear();
	ui.theta_Line->clear();
	ui.kappa_Line->clear();
	ui.sigma_Line->clear();
	ui.rho_Line->clear();
	ui.v0_Line->setReadOnly(false);
	ui.theta_Line->setReadOnly(false);
	ui.kappa_Line->setReadOnly(false);
	ui.sigma_Line->setReadOnly(false);
	ui.rho_Line->setReadOnly(false);

	ui.Opt_Line->clear();
}<|endoftext|>


<commit_before>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016
              Vladimír Vondruš <mosra@centrum.cz>

    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 <type_traits>
#include <al.h>

#include "Corrade/configure.h"
#include "Magnum/Types.h"

namespace Magnum { namespace Audio {

/* Verify types */
static_assert(std::is_same<ALubyte, UnsignedByte>::value, "ALubyte is not the same as UnsignedByte");
/* ALbyte is defined as `signed char` in OpenAL Soft and `char` in the official
   SDK from Creative and on Apple. Both are okay. */
static_assert(std::is_same<ALbyte, Byte>::value || std::is_signed<ALbyte>::value && sizeof(ALbyte) == 1, "ALbyte does not have the characteristics as Byte");
static_assert(std::is_same<ALushort, UnsignedShort>::value, "ALushort is not the same as UnsignedShort");
static_assert(std::is_same<ALshort, Short>::value, "ALshort is not the same as Short");
static_assert(std::is_same<ALuint, UnsignedInt>::value, "ALuint is not the same as UnsignedInt");
static_assert(std::is_same<ALint, Int>::value, "ALint is not the same as Int");
static_assert(std::is_same<ALsizei, Int>::value, "ALsizei is not the same as Int");
static_assert(std::is_same<ALfloat, Float>::value, "ALfloat is not the same as Float");
#ifndef MAGNUM_TARGET_GLES
static_assert(std::is_same<ALdouble, Double>::value, "ALdouble is not the same as Double");
#endif

/* Verify boolean values */
static_assert(AL_FALSE == false, "AL_FALSE is not the same as false");
static_assert(AL_TRUE == true, "AL_TRUE is not the same as true");

}}
<commit_msg>Audio: fix compiler warning.<commit_after>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016
              Vladimír Vondruš <mosra@centrum.cz>

    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 <type_traits>
#include <al.h>

#include "Corrade/configure.h"
#include "Magnum/Types.h"

namespace Magnum { namespace Audio {

/* Verify types */
static_assert(std::is_same<ALubyte, UnsignedByte>::value, "ALubyte is not the same as UnsignedByte");
/* ALbyte is defined as `signed char` in OpenAL Soft and `char` in the official
   SDK from Creative and on Apple. Both are okay. */
static_assert(std::is_same<ALbyte, Byte>::value || (std::is_signed<ALbyte>::value && sizeof(ALbyte) == 1), "ALbyte does not have the characteristics as Byte");
static_assert(std::is_same<ALushort, UnsignedShort>::value, "ALushort is not the same as UnsignedShort");
static_assert(std::is_same<ALshort, Short>::value, "ALshort is not the same as Short");
static_assert(std::is_same<ALuint, UnsignedInt>::value, "ALuint is not the same as UnsignedInt");
static_assert(std::is_same<ALint, Int>::value, "ALint is not the same as Int");
static_assert(std::is_same<ALsizei, Int>::value, "ALsizei is not the same as Int");
static_assert(std::is_same<ALfloat, Float>::value, "ALfloat is not the same as Float");
#ifndef MAGNUM_TARGET_GLES
static_assert(std::is_same<ALdouble, Double>::value, "ALdouble is not the same as Double");
#endif

/* Verify boolean values */
static_assert(AL_FALSE == false, "AL_FALSE is not the same as false");
static_assert(AL_TRUE == true, "AL_TRUE is not the same as true");

}}
<|endoftext|>