<commit_before>/*************************************************************************
 *
 *  $RCSfile: languageoptions.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-23 12:37:40 $
 *
 *  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 _SVTOOLS_LANGUAGEOPTIONS_HXX
#include "languageoptions.hxx"
#endif
#ifndef _SVTOOLS_CJKOPTIONS_HXX
#include <cjkoptions.hxx>
#endif
#ifndef _SVTOOLS_CTLOPTIONS_HXX
#include <ctloptions.hxx>
#endif
#ifndef _LANG_HXX
#include <tools/lang.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef INCLUDED_RTL_INSTANCE_HXX
#include <rtl/instance.hxx>
#endif

// global ----------------------------------------------------------------------

namespace { struct ALMutex : public rtl::Static< ::osl::Mutex, ALMutex > {}; }

// class SvtLanguageOptions ----------------------------------------------------

SvtLanguageOptions::SvtLanguageOptions( sal_Bool _bDontLoad )
{
    // Global access, must be guarded (multithreading)
    ::osl::MutexGuard aGuard( ALMutex::get() );

    m_pCJKOptions = new SvtCJKOptions( _bDontLoad );
    m_pCTLOptions = new SvtCTLOptions( _bDontLoad );
    StartListening(*m_pCTLOptions);
}
//------------------------------------------------------------------------------
SvtLanguageOptions::~SvtLanguageOptions()
{
    // Global access, must be guarded (multithreading)
    ::osl::MutexGuard aGuard( ALMutex::get() );

    delete m_pCJKOptions;
    delete m_pCTLOptions;
}
//------------------------------------------------------------------------------
// CJK options -----------------------------------------------------------------
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsCJKFontEnabled() const
{
    return m_pCJKOptions->IsCJKFontEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsVerticalTextEnabled() const
{
    return m_pCJKOptions->IsVerticalTextEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsAsianTypographyEnabled() const
{
    return m_pCJKOptions->IsAsianTypographyEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsJapaneseFindEnabled() const
{
    return m_pCJKOptions->IsJapaneseFindEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsRubyEnabled() const
{
    return m_pCJKOptions->IsRubyEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsChangeCaseMapEnabled() const
{
    return m_pCJKOptions->IsChangeCaseMapEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsDoubleLinesEnabled() const
{
    return m_pCJKOptions->IsDoubleLinesEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsEmphasisMarksEnabled() const
{
    return m_pCJKOptions->IsEmphasisMarksEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsVerticalCallOutEnabled() const
{
    return m_pCJKOptions->IsVerticalCallOutEnabled();
}
//------------------------------------------------------------------------------
void SvtLanguageOptions::SetAll( sal_Bool _bSet )
{
    m_pCJKOptions->SetAll( _bSet );
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsAnyEnabled() const
{
    return m_pCJKOptions->IsAnyEnabled();
}
//------------------------------------------------------------------------------
// CTL options -----------------------------------------------------------------
//------------------------------------------------------------------------------
void SvtLanguageOptions::SetCTLFontEnabled( sal_Bool _bEnabled )
{
    m_pCTLOptions->SetCTLFontEnabled( _bEnabled );
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsCTLFontEnabled() const
{
    return m_pCTLOptions->IsCTLFontEnabled();
}
//------------------------------------------------------------------------------
void SvtLanguageOptions::SetCTLSequenceChecking( sal_Bool _bEnabled )
{
    m_pCTLOptions->SetCTLSequenceChecking( _bEnabled );
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsCTLSequenceChecking() const
{
    return m_pCTLOptions->IsCTLSequenceChecking();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsReadOnly(SvtLanguageOptions::EOption eOption) const
{
    sal_Bool bReadOnly = sal_False;
    switch(eOption)
    {
        // cjk options
        case SvtLanguageOptions::E_CJKFONT          : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_CJKFONT        ); break;
        case SvtLanguageOptions::E_VERTICALTEXT     : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_VERTICALTEXT   ); break;
        case SvtLanguageOptions::E_ASIANTYPOGRAPHY  : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_ASIANTYPOGRAPHY); break;
        case SvtLanguageOptions::E_JAPANESEFIND     : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_JAPANESEFIND   ); break;
        case SvtLanguageOptions::E_RUBY             : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_RUBY           ); break;
        case SvtLanguageOptions::E_CHANGECASEMAP    : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_CHANGECASEMAP  ); break;
        case SvtLanguageOptions::E_DOUBLELINES      : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_DOUBLELINES    ); break;
        case SvtLanguageOptions::E_EMPHASISMARKS    : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_EMPHASISMARKS  ); break;
        case SvtLanguageOptions::E_VERTICALCALLOUT  : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_VERTICALCALLOUT); break;
        case SvtLanguageOptions::E_ALLCJK           : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_ALL            ); break;
        // ctl options
        case SvtLanguageOptions::E_CTLFONT              : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLFONT            ); break;
        case SvtLanguageOptions::E_CTLSEQUENCECHECKING  : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLSEQUENCECHECKING); break;
        case SvtLanguageOptions::E_CTLCURSORMOVEMENT    : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLCURSORMOVEMENT  ); break;
        case SvtLanguageOptions::E_CTLTEXTNUMERALS      : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLTEXTNUMERALS    ); break;
    }
    return bReadOnly;
}
/* -----------------30.04.2003 11:03-----------------

 --------------------------------------------------*/
void SvtLanguageOptions::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    vos::OGuard aVclGuard( Application::GetSolarMutex() );
    Broadcast( rHint );
}

// -----------------------------------------------------------------------------
// returns for a language the scripttype
sal_uInt16 SvtLanguageOptions::GetScriptTypeOfLanguage( sal_uInt16 nLang )
{
    if( LANGUAGE_DONTKNOW == nLang )
        nLang = LANGUAGE_ENGLISH_US;
    else if( LANGUAGE_SYSTEM == nLang  )
        nLang = Application::GetSettings().GetLanguage();

    USHORT nScript;
    switch( nLang )
    {
        // CJK
        case LANGUAGE_CHINESE:
        case LANGUAGE_CHINESE_TRADITIONAL:
        case LANGUAGE_CHINESE_SIMPLIFIED:
        case LANGUAGE_CHINESE_HONGKONG:
        case LANGUAGE_CHINESE_SINGAPORE:
        case LANGUAGE_CHINESE_MACAU:
        case LANGUAGE_JAPANESE:
        case LANGUAGE_KOREAN:
        case LANGUAGE_KOREAN_JOHAB:
        case LANGUAGE_USER_KOREAN_NORTH:
            nScript = SCRIPTTYPE_ASIAN;
            break;

        // CTL
        case LANGUAGE_ARABIC:
        case LANGUAGE_ARABIC_SAUDI_ARABIA:
        case LANGUAGE_ARABIC_IRAQ:
        case LANGUAGE_ARABIC_EGYPT:
        case LANGUAGE_ARABIC_LIBYA:
        case LANGUAGE_ARABIC_ALGERIA:
        case LANGUAGE_ARABIC_MOROCCO:
        case LANGUAGE_ARABIC_TUNISIA:
        case LANGUAGE_ARABIC_OMAN:
        case LANGUAGE_ARABIC_YEMEN:
        case LANGUAGE_ARABIC_SYRIA:
        case LANGUAGE_ARABIC_JORDAN:
        case LANGUAGE_ARABIC_LEBANON:
        case LANGUAGE_ARABIC_KUWAIT:
        case LANGUAGE_ARABIC_UAE:
        case LANGUAGE_ARABIC_BAHRAIN:
        case LANGUAGE_ARABIC_QATAR:
        case LANGUAGE_HEBREW:
        case LANGUAGE_MARATHI:
        case LANGUAGE_PUNJABI:
        case LANGUAGE_GUJARATI:
        case LANGUAGE_HINDI:
        case LANGUAGE_KANNADA:
        case LANGUAGE_TAMIL:
        case LANGUAGE_TELUGU:
        case LANGUAGE_THAI:
        case LANGUAGE_URDU:
        case LANGUAGE_URDU_PAKISTAN:
        case LANGUAGE_URDU_INDIA:
        case LANGUAGE_VIETNAMESE: // not included in langtab.src?
            nScript = SCRIPTTYPE_COMPLEX;
            break;

// currently not knowing scripttype - defaultet to LATIN:
/*
#define LANGUAGE_AFRIKAANS                  0x0436
#define LANGUAGE_ARMENIAN                   0x042B
#define LANGUAGE_ASSAMESE                   0x044D
#define LANGUAGE_AZERI                      0x002C
#define LANGUAGE_AZERI_LATIN                0x042C
#define LANGUAGE_AZERI_CYRILLIC             0x082C
#define LANGUAGE_BASQUE                     0x042D
#define LANGUAGE_BELARUSIAN                 0x0423
#define LANGUAGE_BENGALI                    0x0445
#define LANGUAGE_INDONESIAN                 0x0421
#define LANGUAGE_KASHMIRI                   0x0460
#define LANGUAGE_KASHMIRI_INDIA             0x0860
#define LANGUAGE_KAZAK                      0x043F
#define LANGUAGE_KONKANI                    0x0457
#define LANGUAGE_LATVIAN                    0x0426
#define LANGUAGE_LITHUANIAN                 0x0427
#define LANGUAGE_LITHUANIAN_CLASSIC         0x0827
#define LANGUAGE_MACEDONIAN                 0x042F
#define LANGUAGE_MALAY                      0x003E
#define LANGUAGE_MALAY_MALAYSIA             0x043E
#define LANGUAGE_MALAY_BRUNEI_DARUSSALAM    0x083E
#define LANGUAGE_MALAYALAM                  0x044C
#define LANGUAGE_MANIPURI                   0x0458
#define LANGUAGE_NEPALI                     0x0461
#define LANGUAGE_NEPALI_INDIA               0x0861
#define LANGUAGE_ORIYA                      0x0448
#define LANGUAGE_SANSKRIT                   0x044F
#define LANGUAGE_SERBIAN                    0x041A
#define LANGUAGE_SERBIAN_LATIN              0x081A
#define LANGUAGE_SERBIAN_CYRILLIC           0x0C1A
#define LANGUAGE_SINDHI                     0x0459
#define LANGUAGE_SWAHILI                    0x5041
#define LANGUAGE_TATAR                      0x0444
#define LANGUAGE_TURKISH                    0x041F
#define LANGUAGE_UKRAINIAN                  0x0422
#define LANGUAGE_UZBEK                      0x0043
#define LANGUAGE_UZBEK_LATIN                0x0443
#define LANGUAGE_UZBEK_CYRILLIC             0x0843
*/

    default:
        nScript = SCRIPTTYPE_LATIN;
        break;
    }
    return nScript;
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS tleamisc (1.5.294); FILE MERGED 2004/07/16 13:25:18 tl 1.5.294.2: RESYNC: (1.5-1.6); FILE MERGED 2004/06/01 10:23:54 tl 1.5.294.1: #i23439# FARSI now CTL language<commit_after>/*************************************************************************
 *
 *  $RCSfile: languageoptions.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2004-08-11 15:30:02 $
 *
 *  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 _SVTOOLS_LANGUAGEOPTIONS_HXX
#include "languageoptions.hxx"
#endif
#ifndef _SVTOOLS_CJKOPTIONS_HXX
#include <cjkoptions.hxx>
#endif
#ifndef _SVTOOLS_CTLOPTIONS_HXX
#include <ctloptions.hxx>
#endif
#ifndef _LANG_HXX
#include <tools/lang.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef INCLUDED_RTL_INSTANCE_HXX
#include <rtl/instance.hxx>
#endif

// global ----------------------------------------------------------------------

namespace { struct ALMutex : public rtl::Static< ::osl::Mutex, ALMutex > {}; }

// class SvtLanguageOptions ----------------------------------------------------

SvtLanguageOptions::SvtLanguageOptions( sal_Bool _bDontLoad )
{
    // Global access, must be guarded (multithreading)
    ::osl::MutexGuard aGuard( ALMutex::get() );

    m_pCJKOptions = new SvtCJKOptions( _bDontLoad );
    m_pCTLOptions = new SvtCTLOptions( _bDontLoad );
    StartListening(*m_pCTLOptions);
}
//------------------------------------------------------------------------------
SvtLanguageOptions::~SvtLanguageOptions()
{
    // Global access, must be guarded (multithreading)
    ::osl::MutexGuard aGuard( ALMutex::get() );

    delete m_pCJKOptions;
    delete m_pCTLOptions;
}
//------------------------------------------------------------------------------
// CJK options -----------------------------------------------------------------
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsCJKFontEnabled() const
{
    return m_pCJKOptions->IsCJKFontEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsVerticalTextEnabled() const
{
    return m_pCJKOptions->IsVerticalTextEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsAsianTypographyEnabled() const
{
    return m_pCJKOptions->IsAsianTypographyEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsJapaneseFindEnabled() const
{
    return m_pCJKOptions->IsJapaneseFindEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsRubyEnabled() const
{
    return m_pCJKOptions->IsRubyEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsChangeCaseMapEnabled() const
{
    return m_pCJKOptions->IsChangeCaseMapEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsDoubleLinesEnabled() const
{
    return m_pCJKOptions->IsDoubleLinesEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsEmphasisMarksEnabled() const
{
    return m_pCJKOptions->IsEmphasisMarksEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsVerticalCallOutEnabled() const
{
    return m_pCJKOptions->IsVerticalCallOutEnabled();
}
//------------------------------------------------------------------------------
void SvtLanguageOptions::SetAll( sal_Bool _bSet )
{
    m_pCJKOptions->SetAll( _bSet );
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsAnyEnabled() const
{
    return m_pCJKOptions->IsAnyEnabled();
}
//------------------------------------------------------------------------------
// CTL options -----------------------------------------------------------------
//------------------------------------------------------------------------------
void SvtLanguageOptions::SetCTLFontEnabled( sal_Bool _bEnabled )
{
    m_pCTLOptions->SetCTLFontEnabled( _bEnabled );
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsCTLFontEnabled() const
{
    return m_pCTLOptions->IsCTLFontEnabled();
}
//------------------------------------------------------------------------------
void SvtLanguageOptions::SetCTLSequenceChecking( sal_Bool _bEnabled )
{
    m_pCTLOptions->SetCTLSequenceChecking( _bEnabled );
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsCTLSequenceChecking() const
{
    return m_pCTLOptions->IsCTLSequenceChecking();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsReadOnly(SvtLanguageOptions::EOption eOption) const
{
    sal_Bool bReadOnly = sal_False;
    switch(eOption)
    {
        // cjk options
        case SvtLanguageOptions::E_CJKFONT          : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_CJKFONT        ); break;
        case SvtLanguageOptions::E_VERTICALTEXT     : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_VERTICALTEXT   ); break;
        case SvtLanguageOptions::E_ASIANTYPOGRAPHY  : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_ASIANTYPOGRAPHY); break;
        case SvtLanguageOptions::E_JAPANESEFIND     : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_JAPANESEFIND   ); break;
        case SvtLanguageOptions::E_RUBY             : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_RUBY           ); break;
        case SvtLanguageOptions::E_CHANGECASEMAP    : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_CHANGECASEMAP  ); break;
        case SvtLanguageOptions::E_DOUBLELINES      : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_DOUBLELINES    ); break;
        case SvtLanguageOptions::E_EMPHASISMARKS    : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_EMPHASISMARKS  ); break;
        case SvtLanguageOptions::E_VERTICALCALLOUT  : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_VERTICALCALLOUT); break;
        case SvtLanguageOptions::E_ALLCJK           : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_ALL            ); break;
        // ctl options
        case SvtLanguageOptions::E_CTLFONT              : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLFONT            ); break;
        case SvtLanguageOptions::E_CTLSEQUENCECHECKING  : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLSEQUENCECHECKING); break;
        case SvtLanguageOptions::E_CTLCURSORMOVEMENT    : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLCURSORMOVEMENT  ); break;
        case SvtLanguageOptions::E_CTLTEXTNUMERALS      : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLTEXTNUMERALS    ); break;
    }
    return bReadOnly;
}
/* -----------------30.04.2003 11:03-----------------

 --------------------------------------------------*/
void SvtLanguageOptions::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    vos::OGuard aVclGuard( Application::GetSolarMutex() );
    Broadcast( rHint );
}

// -----------------------------------------------------------------------------
// returns for a language the scripttype
sal_uInt16 SvtLanguageOptions::GetScriptTypeOfLanguage( sal_uInt16 nLang )
{
    if( LANGUAGE_DONTKNOW == nLang )
        nLang = LANGUAGE_ENGLISH_US;
    else if( LANGUAGE_SYSTEM == nLang  )
        nLang = Application::GetSettings().GetLanguage();

    USHORT nScript;
    switch( nLang )
    {
        // CJK
        case LANGUAGE_CHINESE:
        case LANGUAGE_CHINESE_TRADITIONAL:
        case LANGUAGE_CHINESE_SIMPLIFIED:
        case LANGUAGE_CHINESE_HONGKONG:
        case LANGUAGE_CHINESE_SINGAPORE:
        case LANGUAGE_CHINESE_MACAU:
        case LANGUAGE_JAPANESE:
        case LANGUAGE_KOREAN:
        case LANGUAGE_KOREAN_JOHAB:
        case LANGUAGE_USER_KOREAN_NORTH:
            nScript = SCRIPTTYPE_ASIAN;
            break;

        // CTL
        case LANGUAGE_ARABIC:
        case LANGUAGE_ARABIC_SAUDI_ARABIA:
        case LANGUAGE_ARABIC_IRAQ:
        case LANGUAGE_ARABIC_EGYPT:
        case LANGUAGE_ARABIC_LIBYA:
        case LANGUAGE_ARABIC_ALGERIA:
        case LANGUAGE_ARABIC_MOROCCO:
        case LANGUAGE_ARABIC_TUNISIA:
        case LANGUAGE_ARABIC_OMAN:
        case LANGUAGE_ARABIC_YEMEN:
        case LANGUAGE_ARABIC_SYRIA:
        case LANGUAGE_ARABIC_JORDAN:
        case LANGUAGE_ARABIC_LEBANON:
        case LANGUAGE_ARABIC_KUWAIT:
        case LANGUAGE_ARABIC_UAE:
        case LANGUAGE_ARABIC_BAHRAIN:
        case LANGUAGE_ARABIC_QATAR:
        case LANGUAGE_FARSI:
        case LANGUAGE_HEBREW:
        case LANGUAGE_MARATHI:
        case LANGUAGE_PUNJABI:
        case LANGUAGE_GUJARATI:
        case LANGUAGE_HINDI:
        case LANGUAGE_KANNADA:
        case LANGUAGE_TAMIL:
        case LANGUAGE_TELUGU:
        case LANGUAGE_THAI:
        case LANGUAGE_URDU:
        case LANGUAGE_URDU_PAKISTAN:
        case LANGUAGE_URDU_INDIA:
        case LANGUAGE_VIETNAMESE: // not included in langtab.src?
            nScript = SCRIPTTYPE_COMPLEX;
            break;

// currently not knowing scripttype - defaultet to LATIN:
/*
#define LANGUAGE_AFRIKAANS                  0x0436
#define LANGUAGE_ARMENIAN                   0x042B
#define LANGUAGE_ASSAMESE                   0x044D
#define LANGUAGE_AZERI                      0x002C
#define LANGUAGE_AZERI_LATIN                0x042C
#define LANGUAGE_AZERI_CYRILLIC             0x082C
#define LANGUAGE_BASQUE                     0x042D
#define LANGUAGE_BELARUSIAN                 0x0423
#define LANGUAGE_BENGALI                    0x0445
#define LANGUAGE_INDONESIAN                 0x0421
#define LANGUAGE_KASHMIRI                   0x0460
#define LANGUAGE_KASHMIRI_INDIA             0x0860
#define LANGUAGE_KAZAK                      0x043F
#define LANGUAGE_KONKANI                    0x0457
#define LANGUAGE_LATVIAN                    0x0426
#define LANGUAGE_LITHUANIAN                 0x0427
#define LANGUAGE_LITHUANIAN_CLASSIC         0x0827
#define LANGUAGE_MACEDONIAN                 0x042F
#define LANGUAGE_MALAY                      0x003E
#define LANGUAGE_MALAY_MALAYSIA             0x043E
#define LANGUAGE_MALAY_BRUNEI_DARUSSALAM    0x083E
#define LANGUAGE_MALAYALAM                  0x044C
#define LANGUAGE_MANIPURI                   0x0458
#define LANGUAGE_NEPALI                     0x0461
#define LANGUAGE_NEPALI_INDIA               0x0861
#define LANGUAGE_ORIYA                      0x0448
#define LANGUAGE_SANSKRIT                   0x044F
#define LANGUAGE_SERBIAN                    0x041A
#define LANGUAGE_SERBIAN_LATIN              0x081A
#define LANGUAGE_SERBIAN_CYRILLIC           0x0C1A
#define LANGUAGE_SINDHI                     0x0459
#define LANGUAGE_SWAHILI                    0x5041
#define LANGUAGE_TATAR                      0x0444
#define LANGUAGE_TURKISH                    0x041F
#define LANGUAGE_UKRAINIAN                  0x0422
#define LANGUAGE_UZBEK                      0x0043
#define LANGUAGE_UZBEK_LATIN                0x0443
#define LANGUAGE_UZBEK_CYRILLIC             0x0843
*/

    default:
        nScript = SCRIPTTYPE_LATIN;
        break;
    }
    return nScript;
}
// -----------------------------------------------------------------------------
<|endoftext|>


<commit_before><commit_msg>coverity#708524 Uninitialized pointer field<commit_after><|endoftext|>


<commit_before>#ifndef BART_SRC_INSTRUMENTATION_OUTSTREAM_FACTORY_HPP_
#define BART_SRC_INSTRUMENTATION_OUTSTREAM_FACTORY_HPP_

#include "utility/factory/auto_registering_factory.hpp"

namespace bart::instrumentation::outstream {

template <typename DataType> class OutstreamI;

enum class OutstreamName {
  kToOstream,
  kToConditionalOstream,
  kVectorToVTU,
};

template <typename DataType, typename...ArgTypes>
class OutstreamIFactory : public utility::factory::AutoRegisteringFactory<
    OutstreamName,
    std::unique_ptr<OutstreamI<DataType>>(*)(ArgTypes...)> {};

// LCOV_EXCL_START
[[nodiscard]] inline auto to_string(OutstreamName to_convert) -> std::string {
  switch (to_convert) {
    case (OutstreamName::kToOstream):
      return std::string{"OutstreamName::kToOstream"};
    case (OutstreamName::kToConditionalOstream):
      return std::string{"OutstreamName::kToConditionalOstream"};
  }
  return std::string{"Unknown OutstreamName conversion to string requested."};
}
// LCOV_EXCL_STOP

} // namespace bart::instrumentation::outstream

#endif //BART_SRC_INSTRUMENTATION_OUTSTREAM_FACTORY_HPP_
<commit_msg>added kVectorToVTU option to to_string in outstream factory"<commit_after>#ifndef BART_SRC_INSTRUMENTATION_OUTSTREAM_FACTORY_HPP_
#define BART_SRC_INSTRUMENTATION_OUTSTREAM_FACTORY_HPP_

#include "utility/factory/auto_registering_factory.hpp"

namespace bart::instrumentation::outstream {

template <typename DataType> class OutstreamI;

enum class OutstreamName {
  kToOstream,
  kToConditionalOstream,
  kVectorToVTU,
};

template <typename DataType, typename...ArgTypes>
class OutstreamIFactory : public utility::factory::AutoRegisteringFactory<
    OutstreamName,
    std::unique_ptr<OutstreamI<DataType>>(*)(ArgTypes...)> {};

// LCOV_EXCL_START
[[nodiscard]] inline auto to_string(OutstreamName to_convert) -> std::string {
  switch (to_convert) {
    case (OutstreamName::kToOstream):
      return std::string{"OutstreamName::kToOstream"};
    case (OutstreamName::kToConditionalOstream):
      return std::string{"OutstreamName::kToConditionalOstream"};
    case (OutstreamName::kVectorToVTU):
      return std::string{"OutstreamName::kVectorToVTU"};
  }
  return std::string{"Unknown OutstreamName conversion to string requested."};
}
// LCOV_EXCL_STOP

} // namespace bart::instrumentation::outstream

#endif //BART_SRC_INSTRUMENTATION_OUTSTREAM_FACTORY_HPP_
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include "common/SessionSchema.h"

using namespace stx;

namespace cm {

RefPtr<msg::MessageSchema> SessionSchema::forCustomer(
    const CustomerConfig& cfg) {
  Vector<msg::MessageSchemaField> events;

  for (const auto& evschema : cfg.logjoin_config().session_event_schemas()) {
    events.emplace_back(
        msg::MessageSchemaField::mkObjectField(
            evschema.evid(),
            evschema.evtype(),
            true,
            false,
            msg::MessageSchema::decode(evschema.schema())));
  }

  return new msg::MessageSchema(
      "session",
      Vector<msg::MessageSchemaField> {
            msg::MessageSchemaField::mkObjectField(
                1,
                "attr",
                false,
                true,
                msg::MessageSchema::decode(
                    cfg.logjoin_config().session_attributes_schema())),
            msg::MessageSchemaField::mkObjectField(
                2,
                "event",
                false,
                true,
                new msg::MessageSchema("event", events)),
      });
}

Vector<TableDefinition> SessionSchema::tableDefinitionsForCustomer(
    const CustomerConfig& cfg) {
  Vector<TableDefinition> tbls;

  {
    TableDefinition td;
    td.set_customer(cfg.customer());
    td.set_table_name("sessions");
    td.set_type(TBL_LOGTABLE);
    td.set_schema_inline(SessionSchema::forCustomer(cfg)->encode().toString());
    tbls.emplace_back(td);
  }

  return tbls;
}

} // namespace cm
<commit_msg>sessione event tables<commit_after>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include "common/SessionSchema.h"

using namespace stx;

namespace cm {

RefPtr<msg::MessageSchema> SessionSchema::forCustomer(
    const CustomerConfig& cfg) {
  Vector<msg::MessageSchemaField> events;

  for (const auto& evschema : cfg.logjoin_config().session_event_schemas()) {
    events.emplace_back(
        msg::MessageSchemaField::mkObjectField(
            evschema.evid(),
            evschema.evtype(),
            true,
            false,
            msg::MessageSchema::decode(evschema.schema())));
  }

  return new msg::MessageSchema(
      "session",
      Vector<msg::MessageSchemaField> {
            msg::MessageSchemaField::mkObjectField(
                1,
                "attr",
                false,
                true,
                msg::MessageSchema::decode(
                    cfg.logjoin_config().session_attributes_schema())),
            msg::MessageSchemaField::mkObjectField(
                2,
                "event",
                false,
                true,
                new msg::MessageSchema("event", events)),
      });
}

Vector<TableDefinition> SessionSchema::tableDefinitionsForCustomer(
    const CustomerConfig& cfg) {
  Vector<TableDefinition> tbls;

  for (const auto& evschema : cfg.logjoin_config().session_event_schemas()) {
    TableDefinition td;
    td.set_customer(cfg.customer());
    td.set_table_name("sessions." + evschema.evtype());
    td.set_type(TBL_LOGTABLE);
    td.set_schema_inline(evschema.schema());
    tbls.emplace_back(td);
  }

  {
    TableDefinition td;
    td.set_customer(cfg.customer());
    td.set_table_name("sessions");
    td.set_type(TBL_LOGTABLE);
    td.set_schema_inline(SessionSchema::forCustomer(cfg)->encode().toString());
    tbls.emplace_back(td);
  }

  return tbls;
}

} // namespace cm
<|endoftext|>


<commit_before>//====== Copyright (c) 2012, Valve Corporation, All rights reserved. ========//
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//===========================================================================//

#include "demofiledump.h"
#include "win_stuff.h"

// these settings cause it to output nothing
bool g_bDumpJson = false;
bool g_bPrettyJson = false;
bool g_bDumpGameEvents = false;
bool g_bOnlyHsBoxEvents = false;
bool g_bSupressFootstepEvents = true;
bool g_bShowExtraPlayerInfoInGameEvents = false;
bool g_bDumpDeaths = false;
bool g_bSupressWarmupDeaths = true;
bool g_bDumpStringTables = false;
bool g_bDumpDataTables = false;
bool g_bDumpPacketEntities = false;
bool g_bDumpNetMessages = false;

int main(int argc, char *argv[]) {
    CDemoFileDump DemoFileDump;

    if (argc <= 1) {
        printf("demoinfogo filename.dem\n");
        printf("optional arguments:\n"
               " -json          Dump as json.\n"
               " -hsbox         Dump only headshotbox events.\n"
               " -gameevents    Dump out game events.\n"
               " -nofootsteps   Skip footstep events when dumping out game events.\n"
               "                Should be after -gameevents.\n"
               " -extrainfo     Show extra player info when dumping out game events.\n"
               "                Should be after -gameevents.\n"
               " -deathscsv     Dump out player death info in CSV form.\n"
               " -nowarmup      Skip deaths during warm up when dumping player deaths.\n"
               "                Should be after -deaths.\n"
               " -stringtables  Dump string tables.\n"
               " -datatables    Dump data tables. (send tables)\n"
               " -packetentites Dump Packet Entities messages.\n"
               " -netmessages   Dump net messages that are not one of the above.\n"
               "Note: by default everything is dumped out.\n");
        exit(1);
    }

    int nFileArgument = 1;
    if (argc > 2) {
        for (int i = 1; i < argc; i++) {
            // arguments start with - or /
            if (argv[i][0] == '-' || argv[i][0] == '/') {
                if (strcasecmp(&argv[i][1], "gameevents") == 0) {
                    g_bDumpGameEvents = true;
                    g_bSupressFootstepEvents = false;
                    g_bShowExtraPlayerInfoInGameEvents = false;
                } else if (strcasecmp(&argv[i][1], "nofootsteps") == 0) {
                    g_bSupressFootstepEvents = true;
                } else if (strcasecmp(&argv[i][1], "extrainfo") == 0) {
                    g_bShowExtraPlayerInfoInGameEvents = true;
                } else if (strcasecmp(&argv[i][1], "deathscsv") == 0) {
                    g_bDumpDeaths = true;
                    g_bSupressWarmupDeaths = false;
                } else if (strcasecmp(&argv[i][1], "nowarmup") == 0) {
                    g_bSupressWarmupDeaths = true;
                } else if (strcasecmp(&argv[i][1], "stringtables") == 0) {
                    g_bDumpStringTables = true;
                } else if (strcasecmp(&argv[i][1], "datatables") == 0) {
                    g_bDumpDataTables = true;
                } else if (strcasecmp(&argv[i][1], "packetentities") == 0) {
                    g_bDumpPacketEntities = true;
                } else if (strcasecmp(&argv[i][1], "netmessages") == 0) {
                    g_bDumpNetMessages = true;
                } else if (strcasecmp(&argv[i][1], "json") == 0) {
                    g_bDumpJson = true;
                } else if (strcasecmp(&argv[i][1], "pretty") == 0) {
                    g_bPrettyJson = true;
                } else if (strcasecmp(&argv[i][1], "hsbox") == 0) {
                    g_bDumpJson = g_bDumpGameEvents = g_bOnlyHsBoxEvents = true;
                }
            } else {
                nFileArgument = i;
            }
        }
    } else {
        // default is to dump out everything
        g_bDumpGameEvents = true;
        g_bSupressFootstepEvents = false;
        g_bShowExtraPlayerInfoInGameEvents = true;
        g_bDumpDeaths = true;
        g_bSupressWarmupDeaths = false;
        g_bDumpStringTables = true;
        g_bDumpDataTables = true;
        g_bDumpPacketEntities = true;
        g_bDumpNetMessages = true;
    }

    if (DemoFileDump.Open(argv[nFileArgument])) {
        DemoFileDump.DoDump();
    }

    return 0;
}
<commit_msg>Remove / as argument prefix.<commit_after>//====== Copyright (c) 2012, Valve Corporation, All rights reserved. ========//
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//===========================================================================//

#include "demofiledump.h"
#include "win_stuff.h"

// these settings cause it to output nothing
bool g_bDumpJson = false;
bool g_bPrettyJson = false;
bool g_bDumpGameEvents = false;
bool g_bOnlyHsBoxEvents = false;
bool g_bSupressFootstepEvents = true;
bool g_bShowExtraPlayerInfoInGameEvents = false;
bool g_bDumpDeaths = false;
bool g_bSupressWarmupDeaths = true;
bool g_bDumpStringTables = false;
bool g_bDumpDataTables = false;
bool g_bDumpPacketEntities = false;
bool g_bDumpNetMessages = false;

int main(int argc, char *argv[]) {
    CDemoFileDump DemoFileDump;

    if (argc <= 1) {
        printf("demoinfogo filename.dem\n");
        printf("optional arguments:\n"
               " -json          Dump as json.\n"
               " -hsbox         Dump only headshotbox events.\n"
               " -gameevents    Dump out game events.\n"
               " -nofootsteps   Skip footstep events when dumping out game events.\n"
               "                Should be after -gameevents.\n"
               " -extrainfo     Show extra player info when dumping out game events.\n"
               "                Should be after -gameevents.\n"
               " -deathscsv     Dump out player death info in CSV form.\n"
               " -nowarmup      Skip deaths during warm up when dumping player deaths.\n"
               "                Should be after -deaths.\n"
               " -stringtables  Dump string tables.\n"
               " -datatables    Dump data tables. (send tables)\n"
               " -packetentites Dump Packet Entities messages.\n"
               " -netmessages   Dump net messages that are not one of the above.\n"
               "Note: by default everything is dumped out.\n");
        exit(1);
    }

    int nFileArgument = 1;
    if (argc > 2) {
        for (int i = 1; i < argc; i++) {
            // arguments start with - or /
            if (argv[i][0] == '-') {
                if (strcasecmp(&argv[i][1], "gameevents") == 0) {
                    g_bDumpGameEvents = true;
                    g_bSupressFootstepEvents = false;
                    g_bShowExtraPlayerInfoInGameEvents = false;
                } else if (strcasecmp(&argv[i][1], "nofootsteps") == 0) {
                    g_bSupressFootstepEvents = true;
                } else if (strcasecmp(&argv[i][1], "extrainfo") == 0) {
                    g_bShowExtraPlayerInfoInGameEvents = true;
                } else if (strcasecmp(&argv[i][1], "deathscsv") == 0) {
                    g_bDumpDeaths = true;
                    g_bSupressWarmupDeaths = false;
                } else if (strcasecmp(&argv[i][1], "nowarmup") == 0) {
                    g_bSupressWarmupDeaths = true;
                } else if (strcasecmp(&argv[i][1], "stringtables") == 0) {
                    g_bDumpStringTables = true;
                } else if (strcasecmp(&argv[i][1], "datatables") == 0) {
                    g_bDumpDataTables = true;
                } else if (strcasecmp(&argv[i][1], "packetentities") == 0) {
                    g_bDumpPacketEntities = true;
                } else if (strcasecmp(&argv[i][1], "netmessages") == 0) {
                    g_bDumpNetMessages = true;
                } else if (strcasecmp(&argv[i][1], "json") == 0) {
                    g_bDumpJson = true;
                } else if (strcasecmp(&argv[i][1], "pretty") == 0) {
                    g_bPrettyJson = true;
                } else if (strcasecmp(&argv[i][1], "hsbox") == 0) {
                    g_bDumpJson = g_bDumpGameEvents = g_bOnlyHsBoxEvents = true;
                }
            } else {
                nFileArgument = i;
            }
        }
    } else {
        // default is to dump out everything
        g_bDumpGameEvents = true;
        g_bSupressFootstepEvents = false;
        g_bShowExtraPlayerInfoInGameEvents = true;
        g_bDumpDeaths = true;
        g_bSupressWarmupDeaths = false;
        g_bDumpStringTables = true;
        g_bDumpDataTables = true;
        g_bDumpPacketEntities = true;
        g_bDumpNetMessages = true;
    }

    if (DemoFileDump.Open(argv[nFileArgument])) {
        DemoFileDump.DoDump();
    }

    return 0;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "depscanner.h"
#include "artifact.h"
#include "projectbuilddata.h"
#include "buildgraph.h"

#include <tools/error.h>
#include <logging/translator.h>
#include <language/language.h>
#include <language/propertymapinternal.h>
#include <language/scriptengine.h>
#include <jsextensions/moduleproperties.h>
#include <plugins/scanner/scanner.h>
#include <tools/fileinfo.h>

#include <QtCore/qvariant.h>

#include <QtScript/qscriptcontext.h>

namespace qbs {
namespace Internal {

QString DependencyScanner::id() const
{
    if (m_id.isEmpty())
        m_id = createId();
    return m_id;
}

static QStringList collectCppIncludePaths(const QVariantMap &modules)
{
    QStringList result;
    const QVariantMap cpp = modules.value(QLatin1String("cpp")).toMap();
    if (cpp.isEmpty())
        return result;

    result << cpp.value(QLatin1String("includePaths")).toStringList();
    const bool useSystemHeaders
            = cpp.value(QLatin1String("treatSystemHeadersAsDependencies")).toBool();
    if (useSystemHeaders) {
        result
            << cpp.value(QLatin1String("systemIncludePaths")).toStringList()
            << cpp.value(QLatin1String("distributionIncludePaths")).toStringList()
            << cpp.value(QLatin1String("compilerIncludePaths")).toStringList();
    }
    result.removeDuplicates();
    return result;
}

PluginDependencyScanner::PluginDependencyScanner(ScannerPlugin *plugin)
    : m_plugin(plugin)
{
}

QStringList PluginDependencyScanner::collectSearchPaths(Artifact *artifact)
{
    if (m_plugin->flags & ScannerUsesCppIncludePaths) {
        QVariantMap modules = artifact->properties->value().value(QLatin1String("modules")).toMap();
        return collectCppIncludePaths(modules);
    } else {
        return QStringList();
    }
}

QStringList PluginDependencyScanner::collectDependencies(FileResourceBase *file,
                                                         const char *fileTags)
{
    Set<QString> result;
    QString baseDirOfInFilePath = file->dirPath();
    const QString &filepath = file->filePath();
    void *scannerHandle = m_plugin->open(filepath.utf16(), fileTags, ScanForDependenciesFlag);
    if (!scannerHandle)
        return QStringList();
    forever {
        int flags = 0;
        int length = 0;
        const char *szOutFilePath = m_plugin->next(scannerHandle, &length, &flags);
        if (szOutFilePath == 0)
            break;
        QString outFilePath = QString::fromLocal8Bit(szOutFilePath, length);
        if (outFilePath.isEmpty())
            continue;
        if (flags & SC_LOCAL_INCLUDE_FLAG) {
            QString localFilePath = FileInfo::resolvePath(baseDirOfInFilePath, outFilePath);
            if (FileInfo::exists(localFilePath))
                outFilePath = localFilePath;
        }
        result += outFilePath;
    }
    m_plugin->close(scannerHandle);
    return QStringList(result.toList());
}

bool PluginDependencyScanner::recursive() const
{
    return m_plugin->flags & ScannerRecursiveDependencies;
}

const void *PluginDependencyScanner::key() const
{
    return m_plugin;
}

QString PluginDependencyScanner::createId() const
{
    return QString::fromLatin1(m_plugin->name);
}

bool PluginDependencyScanner::areModulePropertiesCompatible(const PropertyMapConstPtr &m1,
                                                            const PropertyMapConstPtr &m2) const
{
    // This changes when our C++ scanner starts taking defines into account.
    Q_UNUSED(m1);
    Q_UNUSED(m2);
    return true;
}

UserDependencyScanner::UserDependencyScanner(const ResolvedScannerConstPtr &scanner,
        const Logger &logger, ScriptEngine *engine)
    : m_scanner(scanner),
      m_logger(logger),
      m_engine(engine),
      m_observer(m_engine),
      m_product(0)
{
    m_global = m_engine->newObject();
    m_global.setPrototype(m_engine->globalObject());
    setupScriptEngineForFile(m_engine, m_scanner->scanScript->fileContext, m_global);
}

QStringList UserDependencyScanner::collectSearchPaths(Artifact *artifact)
{
    return evaluate(artifact, m_scanner->searchPathsScript);
}

QStringList UserDependencyScanner::collectDependencies(FileResourceBase *file, const char *fileTags)
{
    Q_UNUSED(fileTags);
    // ### support user dependency scanners for file deps
    Artifact *artifact = dynamic_cast<Artifact *>(file);
    if (!artifact)
        return QStringList();
    return evaluate(artifact, m_scanner->scanScript);
}

bool UserDependencyScanner::recursive() const
{
    return m_scanner->recursive;
}

const void *UserDependencyScanner::key() const
{
    return m_scanner.data();
}

QString UserDependencyScanner::createId() const
{
    return m_scanner->scanScript->sourceCode;
}

bool UserDependencyScanner::areModulePropertiesCompatible(const PropertyMapConstPtr &m1,
                                                          const PropertyMapConstPtr &m2) const
{
    // TODO: This should probably be made more fine-grained. Perhaps the Scanner item
    //       could declare the relevant properties, or we could figure them out automatically
    //       somehow.
    return m1 == m2 || *m1 == *m2;
}

class ScriptEngineActiveFlagGuard
{
    ScriptEngine *m_engine;
public:
    ScriptEngineActiveFlagGuard(ScriptEngine *engine)
        : m_engine(engine)
    {
        m_engine->setActive(true);
    }

    ~ScriptEngineActiveFlagGuard()
    {
        m_engine->setActive(false);
    }
};

QStringList UserDependencyScanner::evaluate(Artifact *artifact, const ScriptFunctionPtr &script)
{
    ScriptEngineActiveFlagGuard guard(m_engine);

    if (artifact->product.data() != m_product) {
        m_product = artifact->product.data();
        setupScriptEngineForProduct(m_engine, artifact->product,
                                    m_scanner->module, m_global, &m_observer);
    }

    QScriptValue artifactConfig = m_engine->newObject();
    ModuleProperties::init(artifactConfig, artifact);
    artifactConfig.setProperty(QLatin1String("fileName"),
                               FileInfo::fileName(artifact->filePath()), 0);
    artifactConfig.setProperty(QLatin1String("filePath"), artifact->filePath(), 0);
    const QStringList fileTags = artifact->fileTags().toStringList();
    artifactConfig.setProperty(QLatin1String("fileTags"), m_engine->toScriptValue(fileTags));
    if (!m_scanner->module->name.isEmpty())
        artifactConfig.setProperty(QLatin1String("moduleName"), m_scanner->module->name);
    QScriptValueList args;
    args.reserve(3);
    args.append(m_global.property(QString::fromLatin1("project")));
    args.append(m_global.property(QString::fromLatin1("product")));
    args.append(artifactConfig);

    m_engine->setGlobalObject(m_global);
    QScriptValue &function = script->scriptFunction;
    if (!function.isValid() || function.engine() != m_engine) {
        function = m_engine->evaluate(script->sourceCode);
        if (Q_UNLIKELY(!function.isFunction()))
            throw ErrorInfo(Tr::tr("Invalid scan script."), script->location);
    }
    QScriptValue result = function.call(QScriptValue(), args);
    m_engine->setGlobalObject(m_global.prototype());
    m_engine->clearRequestedProperties();
    if (Q_UNLIKELY(m_engine->hasErrorOrException(result))) {
        QString msg = Tr::tr("evaluating scan script: ") + m_engine->lastErrorString(result);
        m_engine->clearExceptions();
        throw ErrorInfo(msg, script->location);
    }
    QStringList list;
    if (result.isArray()) {
        const int count = result.property(QLatin1String("length")).toInt32();
        list.reserve(count);
        for (qint32 i = 0; i < count; ++i) {
            QScriptValue item = result.property(i);
            if (item.isValid() && !item.isUndefined())
                list.append(item.toString());
        }
    }
    return list;
}

} // namespace Internal
} // namespace qbs
<commit_msg>Un-duplicate code in UserDependencyScanner::evaluate<commit_after>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "depscanner.h"
#include "artifact.h"
#include "projectbuilddata.h"
#include "buildgraph.h"
#include "transformer.h"

#include <tools/error.h>
#include <logging/translator.h>
#include <language/language.h>
#include <language/propertymapinternal.h>
#include <language/scriptengine.h>
#include <jsextensions/moduleproperties.h>
#include <plugins/scanner/scanner.h>
#include <tools/fileinfo.h>

#include <QtCore/qvariant.h>

#include <QtScript/qscriptcontext.h>

namespace qbs {
namespace Internal {

QString DependencyScanner::id() const
{
    if (m_id.isEmpty())
        m_id = createId();
    return m_id;
}

static QStringList collectCppIncludePaths(const QVariantMap &modules)
{
    QStringList result;
    const QVariantMap cpp = modules.value(QLatin1String("cpp")).toMap();
    if (cpp.isEmpty())
        return result;

    result << cpp.value(QLatin1String("includePaths")).toStringList();
    const bool useSystemHeaders
            = cpp.value(QLatin1String("treatSystemHeadersAsDependencies")).toBool();
    if (useSystemHeaders) {
        result
            << cpp.value(QLatin1String("systemIncludePaths")).toStringList()
            << cpp.value(QLatin1String("distributionIncludePaths")).toStringList()
            << cpp.value(QLatin1String("compilerIncludePaths")).toStringList();
    }
    result.removeDuplicates();
    return result;
}

PluginDependencyScanner::PluginDependencyScanner(ScannerPlugin *plugin)
    : m_plugin(plugin)
{
}

QStringList PluginDependencyScanner::collectSearchPaths(Artifact *artifact)
{
    if (m_plugin->flags & ScannerUsesCppIncludePaths) {
        QVariantMap modules = artifact->properties->value().value(QLatin1String("modules")).toMap();
        return collectCppIncludePaths(modules);
    } else {
        return QStringList();
    }
}

QStringList PluginDependencyScanner::collectDependencies(FileResourceBase *file,
                                                         const char *fileTags)
{
    Set<QString> result;
    QString baseDirOfInFilePath = file->dirPath();
    const QString &filepath = file->filePath();
    void *scannerHandle = m_plugin->open(filepath.utf16(), fileTags, ScanForDependenciesFlag);
    if (!scannerHandle)
        return QStringList();
    forever {
        int flags = 0;
        int length = 0;
        const char *szOutFilePath = m_plugin->next(scannerHandle, &length, &flags);
        if (szOutFilePath == 0)
            break;
        QString outFilePath = QString::fromLocal8Bit(szOutFilePath, length);
        if (outFilePath.isEmpty())
            continue;
        if (flags & SC_LOCAL_INCLUDE_FLAG) {
            QString localFilePath = FileInfo::resolvePath(baseDirOfInFilePath, outFilePath);
            if (FileInfo::exists(localFilePath))
                outFilePath = localFilePath;
        }
        result += outFilePath;
    }
    m_plugin->close(scannerHandle);
    return QStringList(result.toList());
}

bool PluginDependencyScanner::recursive() const
{
    return m_plugin->flags & ScannerRecursiveDependencies;
}

const void *PluginDependencyScanner::key() const
{
    return m_plugin;
}

QString PluginDependencyScanner::createId() const
{
    return QString::fromLatin1(m_plugin->name);
}

bool PluginDependencyScanner::areModulePropertiesCompatible(const PropertyMapConstPtr &m1,
                                                            const PropertyMapConstPtr &m2) const
{
    // This changes when our C++ scanner starts taking defines into account.
    Q_UNUSED(m1);
    Q_UNUSED(m2);
    return true;
}

UserDependencyScanner::UserDependencyScanner(const ResolvedScannerConstPtr &scanner,
        const Logger &logger, ScriptEngine *engine)
    : m_scanner(scanner),
      m_logger(logger),
      m_engine(engine),
      m_observer(m_engine),
      m_product(0)
{
    m_global = m_engine->newObject();
    m_global.setPrototype(m_engine->globalObject());
    setupScriptEngineForFile(m_engine, m_scanner->scanScript->fileContext, m_global);
}

QStringList UserDependencyScanner::collectSearchPaths(Artifact *artifact)
{
    return evaluate(artifact, m_scanner->searchPathsScript);
}

QStringList UserDependencyScanner::collectDependencies(FileResourceBase *file, const char *fileTags)
{
    Q_UNUSED(fileTags);
    // ### support user dependency scanners for file deps
    Artifact *artifact = dynamic_cast<Artifact *>(file);
    if (!artifact)
        return QStringList();
    return evaluate(artifact, m_scanner->scanScript);
}

bool UserDependencyScanner::recursive() const
{
    return m_scanner->recursive;
}

const void *UserDependencyScanner::key() const
{
    return m_scanner.data();
}

QString UserDependencyScanner::createId() const
{
    return m_scanner->scanScript->sourceCode;
}

bool UserDependencyScanner::areModulePropertiesCompatible(const PropertyMapConstPtr &m1,
                                                          const PropertyMapConstPtr &m2) const
{
    // TODO: This should probably be made more fine-grained. Perhaps the Scanner item
    //       could declare the relevant properties, or we could figure them out automatically
    //       somehow.
    return m1 == m2 || *m1 == *m2;
}

class ScriptEngineActiveFlagGuard
{
    ScriptEngine *m_engine;
public:
    ScriptEngineActiveFlagGuard(ScriptEngine *engine)
        : m_engine(engine)
    {
        m_engine->setActive(true);
    }

    ~ScriptEngineActiveFlagGuard()
    {
        m_engine->setActive(false);
    }
};

QStringList UserDependencyScanner::evaluate(Artifact *artifact, const ScriptFunctionPtr &script)
{
    ScriptEngineActiveFlagGuard guard(m_engine);

    if (artifact->product.data() != m_product) {
        m_product = artifact->product.data();
        setupScriptEngineForProduct(m_engine, artifact->product,
                                    m_scanner->module, m_global, &m_observer);
    }

    QScriptValueList args;
    args.reserve(3);
    args.append(m_global.property(QString::fromLatin1("project")));
    args.append(m_global.property(QString::fromLatin1("product")));
    args.append(Transformer::translateFileConfig(m_engine, artifact, m_scanner->module->name));

    m_engine->setGlobalObject(m_global);
    QScriptValue &function = script->scriptFunction;
    if (!function.isValid() || function.engine() != m_engine) {
        function = m_engine->evaluate(script->sourceCode);
        if (Q_UNLIKELY(!function.isFunction()))
            throw ErrorInfo(Tr::tr("Invalid scan script."), script->location);
    }
    QScriptValue result = function.call(QScriptValue(), args);
    m_engine->setGlobalObject(m_global.prototype());
    m_engine->clearRequestedProperties();
    if (Q_UNLIKELY(m_engine->hasErrorOrException(result))) {
        QString msg = Tr::tr("evaluating scan script: ") + m_engine->lastErrorString(result);
        m_engine->clearExceptions();
        throw ErrorInfo(msg, script->location);
    }
    QStringList list;
    if (result.isArray()) {
        const int count = result.property(QLatin1String("length")).toInt32();
        list.reserve(count);
        for (qint32 i = 0; i < count; ++i) {
            QScriptValue item = result.property(i);
            if (item.isValid() && !item.isUndefined())
                list.append(item.toString());
        }
    }
    return list;
}

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


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "buildablehelperlibrary.h"

#include <QtCore/QFileInfo>
#include <QtCore/QCoreApplication>
#include <QtCore/QHash>
#include <QtCore/QProcess>
#include <QtCore/QDir>
#include <QtCore/QDateTime>

#include <utils/environment.h>
#include <utils/synchronousprocess.h>

#include <QtGui/QDesktopServices>
#include <QtCore/QDebug>

namespace Utils {

QString BuildableHelperLibrary::findSystemQt(const Utils::Environment &env)
{
    QStringList paths = env.path();
    foreach (const QString &path, paths) {
        QString prefix = path;
        if (!prefix.endsWith(QLatin1Char('/')))
            prefix.append(QLatin1Char('/'));
        foreach (const QString &possibleCommand, possibleQMakeCommands()) {
            const QFileInfo qmake(prefix + possibleCommand);
            if (qmake.exists()) {
                if (!qtVersionForQMake(qmake.absoluteFilePath()).isNull()) {
                    return qmake.absoluteFilePath();
                }
            }
        }
    }
    return QString();
}

QString BuildableHelperLibrary::qtInstallDataDir(const QString &qmakePath)
{
    QProcess proc;
    proc.start(qmakePath, QStringList() << QLatin1String("-query") << QLatin1String("QT_INSTALL_DATA"));
    if (proc.waitForFinished())
        return QString(proc.readAll().trimmed());
    return QString();
}

QString BuildableHelperLibrary::qtVersionForQMake(const QString &qmakePath)
{
    if (qmakePath.isEmpty())
        return QString();

    QProcess qmake;
    qmake.start(qmakePath, QStringList(QLatin1String("--version")));
    if (!qmake.waitForStarted()) {
        qWarning("Cannot start '%s': %s", qPrintable(qmakePath), qPrintable(qmake.errorString()));
        return QString();
    }
    if (!qmake.waitForFinished())      {
        Utils::SynchronousProcess::stopProcess(qmake);
        qWarning("Timeout running '%s'.", qPrintable(qmakePath));
        return QString();
    }
    if (qmake.exitStatus() != QProcess::NormalExit) {
        qWarning("'%s' crashed.", qPrintable(qmakePath));
        return QString();
    }
    const QString output = QString::fromLocal8Bit(qmake.readAllStandardOutput());
    static QRegExp regexp(QLatin1String("(QMake version|QMake version:)[\\s]*([\\d.]*)"),
                          Qt::CaseInsensitive);
    regexp.indexIn(output);
    if (regexp.cap(2).startsWith(QLatin1String("2."))) {
        static QRegExp regexp2(QLatin1String("Using Qt version[\\s]*([\\d\\.]*)"),
                               Qt::CaseInsensitive);
        regexp2.indexIn(output);
        const QString version = regexp2.cap(1);
        return version;
    }
    return QString();
}

bool BuildableHelperLibrary::checkMinimumQtVersion(const QString &qtVersionString, int majorVersion, int minorVersion, int patchVersion)
{
    int major = -1;
    int minor = -1;
    int patch = -1;

    // check format
    static QRegExp qtVersionRegex(QLatin1String("^\\d+\\.\\d+\\.\\d+$"));
    if (!qtVersionRegex.exactMatch(qtVersionString))
        return false;

    QStringList parts = qtVersionString.split(QLatin1Char('.'));
    major = parts.at(0).toInt();
    minor = parts.at(1).toInt();
    patch = parts.at(2).toInt();

    if (major == majorVersion) {
        if (minor == minorVersion) {
            if (patch >= patchVersion)
                return true;
        } else if (minor > minorVersion)
            return true;
    }

    return false;
}

QStringList BuildableHelperLibrary::possibleQMakeCommands()
{
    // On windows no one has renamed qmake, right?
#ifdef Q_OS_WIN
    return QStringList(QLatin1String("qmake.exe"));
#else
    // On unix some distributions renamed qmake to avoid clashes
    QStringList result;
    result << QLatin1String("qmake-qt4") << QLatin1String("qmake4") << QLatin1String("qmake");
    return result;
#endif
}

// Copy helper source files to a target directory, replacing older files.
bool BuildableHelperLibrary::copyFiles(const QString &sourcePath,
                                     const QStringList &files,
                                     const QString &targetDirectory,
                                     QString *errorMessage)
{
    if (!QDir().mkpath(targetDirectory)) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::DebuggingHelperLibrary", "The target directory %1 could not be created.").arg(targetDirectory);
        return false;
    }
    foreach (const QString &file, files) {
        const QString source = sourcePath + file;
        const QString dest = targetDirectory + file;
        const QFileInfo destInfo(dest);
        if (destInfo.exists()) {
            if (destInfo.lastModified() >= QFileInfo(source).lastModified())
                continue;
            if (!QFile::remove(dest)) {
                *errorMessage = QCoreApplication::translate("ProjectExplorer::DebuggingHelperLibrary", "The existing file %1 could not be removed.").arg(destInfo.absoluteFilePath());
                return false;
            }
        }
        if (!destInfo.dir().exists()) {
            QDir().mkpath(destInfo.dir().absolutePath());
        }

        if (!QFile::copy(source, dest)) {
            *errorMessage = QCoreApplication::translate("ProjectExplorer::DebuggingHelperLibrary", "The file %1 could not be copied to %2.").arg(source, dest);
            return false;
        }
    }
    return true;
}

// Helper: Run a build process with merged stdout/stderr
static inline bool runBuildProcessI(QProcess &proc,
                                    const QString &binary,
                                    const QStringList &args,
                                    int timeoutMS,
                                    bool ignoreNonNullExitCode,
                                    QString *output, QString *errorMessage)
{
    proc.start(binary, args);
    if (!proc.waitForStarted()) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary",
                                                    "Cannot start process: %1").
                                                    arg(proc.errorString());
        return false;
    }
    // Read stdout/err and check for timeouts
    QByteArray stdOut;
    QByteArray stdErr;
    if (!SynchronousProcess::readDataFromProcess(proc, timeoutMS, &stdOut, &stdErr, false)) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary",
                                                    "Timeout after %1s.").
                                                    arg(timeoutMS / 1000);
        SynchronousProcess::stopProcess(proc);
        return false;
    }
    if (proc.exitStatus() != QProcess::NormalExit) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary",
                                                    "The process crashed.");
        return false;
    }
    const QString stdOutS = QString::fromLocal8Bit(stdOut);
    if (!ignoreNonNullExitCode && proc.exitCode() != 0) {
            *errorMessage = QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary",
                                                        "The process returned exit code %1:\n%2").
                                                         arg(proc.exitCode()).arg(stdOutS);
        return false;
    }
    output->append(stdOutS);
    return true;
}

// Run a build process with merged stdout/stderr and qWarn about errors.
static bool runBuildProcess(QProcess &proc,
                            const QString &binary,
                            const QStringList &args,
                            int timeoutMS,
                            bool ignoreNonNullExitCode,
                            QString *output, QString *errorMessage)
{
    const bool rc = runBuildProcessI(proc, binary, args, timeoutMS, ignoreNonNullExitCode, output, errorMessage);
    if (!rc) {
        // Fail - reformat error.
        QString cmd = binary;
        if (!args.isEmpty()) {
            cmd += QLatin1Char(' ');
            cmd += args.join(QString(QLatin1Char(' ')));
        }
        *errorMessage =
                QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary",
                                            "Error running '%1' in %2: %3").
                                            arg(cmd, proc.workingDirectory(), *errorMessage);
        qWarning("%s", qPrintable(*errorMessage));
    }
    return rc;
}

bool BuildableHelperLibrary::buildHelper(const QString &helperName, const QString &proFilename,
                                         const QString &directory, const QString &makeCommand,
                                         const QString &qmakeCommand, const QString &mkspec,
                                         const Utils::Environment &env, const QString &targetMode,
                                         const QStringList &qmakeArguments, QString *output,
                                         QString *errorMessage)
{
    const QChar newline = QLatin1Char('\n');
    // Setup process
    QProcess proc;
    proc.setEnvironment(env.toStringList());
    proc.setWorkingDirectory(directory);
    proc.setProcessChannelMode(QProcess::MergedChannels);

    output->append(QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary",
                                          "Building helper library '%1' in %2\n").arg(helperName, directory));
    output->append(newline);

    const QString makeFullPath = env.searchInPath(makeCommand);
    if (QFileInfo(directory + QLatin1String("/Makefile")).exists()) {
        if (makeFullPath.isEmpty()) {
            *errorMessage = QCoreApplication::translate("ProjectExplorer::DebuggingHelperLibrary",
                                                       "%1 not found in PATH\n").arg(makeCommand);
            return false;
        }
        const QString cleanTarget = QLatin1String("distclean");
        output->append(QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary",
                                                   "Running %1 %2...\n").arg(makeFullPath, cleanTarget));
        if (!runBuildProcess(proc, makeFullPath, QStringList(cleanTarget), 30000, true, output, errorMessage))
            return false;
    }
    output->append(newline);
    output->append(QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary", "Running %1 ...\n").arg(qmakeCommand));

    QStringList qmakeArgs;
    if (!targetMode.isEmpty())
        qmakeArgs << targetMode;
    if (!mkspec.isEmpty())
        qmakeArgs << QLatin1String("-spec") << mkspec;
    qmakeArgs << proFilename;
    qmakeArgs << qmakeArguments;
    if (!runBuildProcess(proc, qmakeCommand, qmakeArgs, 30000, false, output, errorMessage))
        return false;
    output->append(newline);
    if (makeFullPath.isEmpty()) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary", "%1 not found in PATH\n").arg(makeCommand);
        return false;
    }
    output->append(QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary", "Running %1 ...\n").arg(makeFullPath));
    if (!runBuildProcess(proc, makeFullPath, QStringList(), 120000, false, output, errorMessage))
        return false;
    return true;
}

bool BuildableHelperLibrary::getHelperFileInfoFor(const QStringList &validBinaryFilenames,
                                                  const QString &directory, QFileInfo* info)
{
    if (!info)
        return false;

    foreach(const QString &binaryFilename, validBinaryFilenames) {
        info->setFile(directory + binaryFilename);
        if (info->exists())
            return true;
    }

    return false;
}

QString BuildableHelperLibrary::byInstallDataHelper(const QString &mainFilename,
                                                    const QStringList &installDirectories,
                                                    const QStringList &validBinaryFilenames)
{
    QDateTime sourcesModified = QFileInfo(mainFilename).lastModified();
    // We pretend that the lastmodified of gdbmacros.cpp is 5 minutes before what the file system says
    // Because afer a installation from the package the modified dates of gdbmacros.cpp
    // and the actual library are close to each other, but not deterministic in one direction
    sourcesModified = sourcesModified.addSecs(-300);

    // look for the newest helper library in the different locations
    QString newestHelper;
    QDateTime newestHelperModified = sourcesModified; // prevent using one that's older than the sources
    QFileInfo fileInfo;
    foreach(const QString &installDirectory, installDirectories) {
        if (getHelperFileInfoFor(validBinaryFilenames, installDirectory, &fileInfo)) {
            if (fileInfo.lastModified() > newestHelperModified) {
                newestHelper = fileInfo.filePath();
                newestHelperModified = fileInfo.lastModified();
            }
        }
    }
    return newestHelper;
}

} // namespace Utils
<commit_msg>DebuggingHelpers: Improve log<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "buildablehelperlibrary.h"

#include <QtCore/QFileInfo>
#include <QtCore/QCoreApplication>
#include <QtCore/QHash>
#include <QtCore/QProcess>
#include <QtCore/QDir>
#include <QtCore/QDateTime>

#include <utils/environment.h>
#include <utils/synchronousprocess.h>

#include <QtGui/QDesktopServices>
#include <QtCore/QDebug>

namespace Utils {

QString BuildableHelperLibrary::findSystemQt(const Utils::Environment &env)
{
    QStringList paths = env.path();
    foreach (const QString &path, paths) {
        QString prefix = path;
        if (!prefix.endsWith(QLatin1Char('/')))
            prefix.append(QLatin1Char('/'));
        foreach (const QString &possibleCommand, possibleQMakeCommands()) {
            const QFileInfo qmake(prefix + possibleCommand);
            if (qmake.exists()) {
                if (!qtVersionForQMake(qmake.absoluteFilePath()).isNull()) {
                    return qmake.absoluteFilePath();
                }
            }
        }
    }
    return QString();
}

QString BuildableHelperLibrary::qtInstallDataDir(const QString &qmakePath)
{
    QProcess proc;
    proc.start(qmakePath, QStringList() << QLatin1String("-query") << QLatin1String("QT_INSTALL_DATA"));
    if (proc.waitForFinished())
        return QString(proc.readAll().trimmed());
    return QString();
}

QString BuildableHelperLibrary::qtVersionForQMake(const QString &qmakePath)
{
    if (qmakePath.isEmpty())
        return QString();

    QProcess qmake;
    qmake.start(qmakePath, QStringList(QLatin1String("--version")));
    if (!qmake.waitForStarted()) {
        qWarning("Cannot start '%s': %s", qPrintable(qmakePath), qPrintable(qmake.errorString()));
        return QString();
    }
    if (!qmake.waitForFinished())      {
        Utils::SynchronousProcess::stopProcess(qmake);
        qWarning("Timeout running '%s'.", qPrintable(qmakePath));
        return QString();
    }
    if (qmake.exitStatus() != QProcess::NormalExit) {
        qWarning("'%s' crashed.", qPrintable(qmakePath));
        return QString();
    }
    const QString output = QString::fromLocal8Bit(qmake.readAllStandardOutput());
    static QRegExp regexp(QLatin1String("(QMake version|QMake version:)[\\s]*([\\d.]*)"),
                          Qt::CaseInsensitive);
    regexp.indexIn(output);
    if (regexp.cap(2).startsWith(QLatin1String("2."))) {
        static QRegExp regexp2(QLatin1String("Using Qt version[\\s]*([\\d\\.]*)"),
                               Qt::CaseInsensitive);
        regexp2.indexIn(output);
        const QString version = regexp2.cap(1);
        return version;
    }
    return QString();
}

bool BuildableHelperLibrary::checkMinimumQtVersion(const QString &qtVersionString, int majorVersion, int minorVersion, int patchVersion)
{
    int major = -1;
    int minor = -1;
    int patch = -1;

    // check format
    static QRegExp qtVersionRegex(QLatin1String("^\\d+\\.\\d+\\.\\d+$"));
    if (!qtVersionRegex.exactMatch(qtVersionString))
        return false;

    QStringList parts = qtVersionString.split(QLatin1Char('.'));
    major = parts.at(0).toInt();
    minor = parts.at(1).toInt();
    patch = parts.at(2).toInt();

    if (major == majorVersion) {
        if (minor == minorVersion) {
            if (patch >= patchVersion)
                return true;
        } else if (minor > minorVersion)
            return true;
    }

    return false;
}

QStringList BuildableHelperLibrary::possibleQMakeCommands()
{
    // On windows no one has renamed qmake, right?
#ifdef Q_OS_WIN
    return QStringList(QLatin1String("qmake.exe"));
#else
    // On unix some distributions renamed qmake to avoid clashes
    QStringList result;
    result << QLatin1String("qmake-qt4") << QLatin1String("qmake4") << QLatin1String("qmake");
    return result;
#endif
}

// Copy helper source files to a target directory, replacing older files.
bool BuildableHelperLibrary::copyFiles(const QString &sourcePath,
                                     const QStringList &files,
                                     const QString &targetDirectory,
                                     QString *errorMessage)
{
    if (!QDir().mkpath(targetDirectory)) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::DebuggingHelperLibrary", "The target directory %1 could not be created.").arg(targetDirectory);
        return false;
    }
    foreach (const QString &file, files) {
        const QString source = sourcePath + file;
        const QString dest = targetDirectory + file;
        const QFileInfo destInfo(dest);
        if (destInfo.exists()) {
            if (destInfo.lastModified() >= QFileInfo(source).lastModified())
                continue;
            if (!QFile::remove(dest)) {
                *errorMessage = QCoreApplication::translate("ProjectExplorer::DebuggingHelperLibrary", "The existing file %1 could not be removed.").arg(destInfo.absoluteFilePath());
                return false;
            }
        }
        if (!destInfo.dir().exists()) {
            QDir().mkpath(destInfo.dir().absolutePath());
        }

        if (!QFile::copy(source, dest)) {
            *errorMessage = QCoreApplication::translate("ProjectExplorer::DebuggingHelperLibrary", "The file %1 could not be copied to %2.").arg(source, dest);
            return false;
        }
    }
    return true;
}

// Helper: Run a build process with merged stdout/stderr
static inline bool runBuildProcessI(QProcess &proc,
                                    const QString &binary,
                                    const QStringList &args,
                                    int timeoutMS,
                                    bool ignoreNonNullExitCode,
                                    QString *output, QString *errorMessage)
{
    proc.start(binary, args);
    if (!proc.waitForStarted()) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary",
                                                    "Cannot start process: %1").
                                                    arg(proc.errorString());
        return false;
    }
    // Read stdout/err and check for timeouts
    QByteArray stdOut;
    QByteArray stdErr;
    if (!SynchronousProcess::readDataFromProcess(proc, timeoutMS, &stdOut, &stdErr, false)) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary",
                                                    "Timeout after %1s.").
                                                    arg(timeoutMS / 1000);
        SynchronousProcess::stopProcess(proc);
        return false;
    }
    if (proc.exitStatus() != QProcess::NormalExit) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary",
                                                    "The process crashed.");
        return false;
    }
    const QString stdOutS = QString::fromLocal8Bit(stdOut);
    if (!ignoreNonNullExitCode && proc.exitCode() != 0) {
            *errorMessage = QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary",
                                                        "The process returned exit code %1:\n%2").
                                                         arg(proc.exitCode()).arg(stdOutS);
        return false;
    }
    output->append(stdOutS);
    return true;
}

// Run a build process with merged stdout/stderr and qWarn about errors.
static bool runBuildProcess(QProcess &proc,
                            const QString &binary,
                            const QStringList &args,
                            int timeoutMS,
                            bool ignoreNonNullExitCode,
                            QString *output, QString *errorMessage)
{
    const bool rc = runBuildProcessI(proc, binary, args, timeoutMS, ignoreNonNullExitCode, output, errorMessage);
    if (!rc) {
        // Fail - reformat error.
        QString cmd = binary;
        if (!args.isEmpty()) {
            cmd += QLatin1Char(' ');
            cmd += args.join(QString(QLatin1Char(' ')));
        }
        *errorMessage =
                QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary",
                                            "Error running '%1' in %2: %3").
                                            arg(cmd, proc.workingDirectory(), *errorMessage);
        qWarning("%s", qPrintable(*errorMessage));
    }
    return rc;
}

bool BuildableHelperLibrary::buildHelper(const QString &helperName, const QString &proFilename,
                                         const QString &directory, const QString &makeCommand,
                                         const QString &qmakeCommand, const QString &mkspec,
                                         const Utils::Environment &env, const QString &targetMode,
                                         const QStringList &qmakeArguments, QString *output,
                                         QString *errorMessage)
{
    const QChar newline = QLatin1Char('\n');
    // Setup process
    QProcess proc;
    proc.setEnvironment(env.toStringList());
    proc.setWorkingDirectory(directory);
    proc.setProcessChannelMode(QProcess::MergedChannels);

    output->append(QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary",
                                          "Building helper '%1' in %2\n").arg(helperName, directory));
    output->append(newline);

    const QString makeFullPath = env.searchInPath(makeCommand);
    if (QFileInfo(directory + QLatin1String("/Makefile")).exists()) {
        if (makeFullPath.isEmpty()) {
            *errorMessage = QCoreApplication::translate("ProjectExplorer::DebuggingHelperLibrary",
                                                       "%1 not found in PATH\n").arg(makeCommand);
            return false;
        }
        const QString cleanTarget = QLatin1String("distclean");
        output->append(QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary",
                                                   "Running %1 %2...\n").arg(makeFullPath, cleanTarget));
        if (!runBuildProcess(proc, makeFullPath, QStringList(cleanTarget), 30000, true, output, errorMessage))
            return false;
    }
    QStringList qmakeArgs;
    if (!targetMode.isEmpty())
        qmakeArgs << targetMode;
    if (!mkspec.isEmpty())
        qmakeArgs << QLatin1String("-spec") << mkspec;
    qmakeArgs << proFilename;
    qmakeArgs << qmakeArguments;

    output->append(newline);
    output->append(QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary", "Running %1 %2 ...\n").arg(qmakeCommand,
                                                                                qmakeArgs.join(" ")));

    if (!runBuildProcess(proc, qmakeCommand, qmakeArgs, 30000, false, output, errorMessage))
        return false;
    output->append(newline);
    if (makeFullPath.isEmpty()) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary", "%1 not found in PATH\n").arg(makeCommand);
        return false;
    }
    output->append(QCoreApplication::translate("ProjectExplorer::BuildableHelperLibrary", "Running %1 ...\n").arg(makeFullPath));
    if (!runBuildProcess(proc, makeFullPath, QStringList(), 120000, false, output, errorMessage))
        return false;
    return true;
}

bool BuildableHelperLibrary::getHelperFileInfoFor(const QStringList &validBinaryFilenames,
                                                  const QString &directory, QFileInfo* info)
{
    if (!info)
        return false;

    foreach(const QString &binaryFilename, validBinaryFilenames) {
        info->setFile(directory + binaryFilename);
        if (info->exists())
            return true;
    }

    return false;
}

QString BuildableHelperLibrary::byInstallDataHelper(const QString &mainFilename,
                                                    const QStringList &installDirectories,
                                                    const QStringList &validBinaryFilenames)
{
    QDateTime sourcesModified = QFileInfo(mainFilename).lastModified();
    // We pretend that the lastmodified of gdbmacros.cpp is 5 minutes before what the file system says
    // Because afer a installation from the package the modified dates of gdbmacros.cpp
    // and the actual library are close to each other, but not deterministic in one direction
    sourcesModified = sourcesModified.addSecs(-300);

    // look for the newest helper library in the different locations
    QString newestHelper;
    QDateTime newestHelperModified = sourcesModified; // prevent using one that's older than the sources
    QFileInfo fileInfo;
    foreach(const QString &installDirectory, installDirectories) {
        if (getHelperFileInfoFor(validBinaryFilenames, installDirectory, &fileInfo)) {
            if (fileInfo.lastModified() > newestHelperModified) {
                newestHelper = fileInfo.filePath();
                newestHelperModified = fileInfo.lastModified();
            }
        }
    }
    return newestHelper;
}

} // namespace Utils
<|endoftext|>


<commit_before>#include "utility\path.h"
#include <sstream>
#include <iostream>
#include "boost/property_tree/ptree.hpp"
#include "boost/property_tree/ini_parser.hpp"
#include <boost/algorithm/string.hpp>

namespace engine {

void Path::Initialize() {
  boost::property_tree::ptree pt;
  try {
    boost::property_tree::ini_parser::read_ini(root_ + "path_config.ini", pt);

    // Iterate over all keys in the paths section of path_config.ini and add
    // them to the map
    for (auto path : pt.get_child("paths"))
      directories_.insert(std::pair<std::string, std::string>(path.first, path.second.data()));

    const void* adress = static_cast<const void*>(this);
    std::stringstream init_message;
    init_message << "Path subsystem initialized at 0x" << adress;
    // Printing the error directly to the console as the Path subsystem is
    // initialized before the logger.
    std::cout << init_message.str() << std::endl;
  }
  catch (boost::property_tree::ini_parser_error err) {
    std::stringstream error_message;
    error_message << "Error reading path config, unable to access resources. File ("
      << err.filename()
      << " at line "
      << err.line()
      << "): "
      << err.message();
    // Printing the error directly to the console as the Path subsystem is
    // initialized before the logger.
    std::cout << error_message.str() << std::endl;
    // TODO(Jelle): Offer to create a test file to indicate what directory the
    // engine considers its root directory. Shut down the Engine afterwards as
    // this is a critical error.
  }
}

void Path::Terminate() {
  std::cout << "Logging subsystem terminated." << std::endl;
}

const std::string & Path::operator[](const std::string directory) const {
  if (directories_.count(directory) == 0) {
    std::stringstream error_message;
    std::string dir{ directory };
    boost::to_upper(dir);
    error_message << dir << "_DIRECTORY_NOT_FOUND";
    return error_message.str();
  }
  return directories_.at(directory);
}

} // namespace<commit_msg>Make the bracket operator of Path automatically concatenate the root path when requesting the path to a directory.<commit_after>#include "utility\path.h"
#include <sstream>
#include <iostream>
#include "boost/property_tree/ptree.hpp"
#include "boost/property_tree/ini_parser.hpp"
#include <boost/algorithm/string.hpp>

namespace engine {

void Path::Initialize() {
  boost::property_tree::ptree pt;
  try {
    boost::property_tree::ini_parser::read_ini(root_ + "path_config.ini", pt);

    // Iterate over all keys in the paths section of path_config.ini and add
    // them to the map
    for (auto path : pt.get_child("paths"))
      directories_.insert(std::pair<std::string, std::string>(path.first, path.second.data()));

    const void* adress = static_cast<const void*>(this);
    std::stringstream init_message;
    init_message << "Path subsystem initialized at 0x" << adress;
    // Printing the error directly to the console as the Path subsystem is
    // initialized before the logger.
    std::cout << init_message.str() << std::endl;
  }
  catch (boost::property_tree::ini_parser_error err) {
    std::stringstream error_message;
    error_message << "Error reading path config, unable to access resources. File ("
      << err.filename()
      << " at line "
      << err.line()
      << "): "
      << err.message();
    // Printing the error directly to the console as the Path subsystem is
    // initialized before the logger.
    std::cout << error_message.str() << std::endl;
    // TODO(Jelle): Offer to create a test file to indicate what directory the
    // engine considers its root directory. Shut down the Engine afterwards as
    // this is a critical error.
  }
}

void Path::Terminate() {
  std::cout << "Logging subsystem terminated." << std::endl;
}

const std::string & Path::operator[](const std::string directory) const {
  if (directories_.count(directory) == 0) {
    std::stringstream error_message;
    std::string dir{ directory };
    boost::to_upper(dir);
    error_message << dir << "_DIRECTORY_NOT_FOUND";
    return error_message.str();
  }
  return root_ + directories_.at(directory);
}

} // namespace<|endoftext|>