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

#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_USER_KURDISH_IRAQ:
        case LANGUAGE_USER_KURDISH_IRAN:
        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 dzongkha (1.9.20); FILE MERGED 2004/10/25 11:15:09 er 1.9.20.2: #i34007# Swahili is not CTL 2004/09/30 18:02:20 er 1.9.20.1: #i34007# classify some languages as CTL instead of Western<commit_after>/*************************************************************************
 *
 *  $RCSfile: languageoptions.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: pjunck $ $Date: 2004-10-28 07:56:42 $
 *
 *  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_ASSAMESE:
        case LANGUAGE_BENGALI:
        case LANGUAGE_FARSI:
        case LANGUAGE_HEBREW:
        case LANGUAGE_MARATHI:
        case LANGUAGE_PUNJABI:
        case LANGUAGE_GUJARATI:
        case LANGUAGE_HINDI:
        case LANGUAGE_KANNADA:
        case LANGUAGE_KASHMIRI:
        case LANGUAGE_KASHMIRI_INDIA:
        case LANGUAGE_KHMER:
        case LANGUAGE_LAO:
        case LANGUAGE_MALAYALAM:
        case LANGUAGE_MANIPURI:
        case LANGUAGE_MONGOLIAN_MONGOLIAN:
        case LANGUAGE_NEPALI:
        case LANGUAGE_NEPALI_INDIA:
        case LANGUAGE_ORIYA:
        case LANGUAGE_SANSKRIT:
        case LANGUAGE_SINDHI:
        case LANGUAGE_SINDHI_PAKISTAN:
        case LANGUAGE_SINHALESE_SRI_LANKA:
        case LANGUAGE_SYRIAC:
        case LANGUAGE_TAMIL:
        case LANGUAGE_TELUGU:
        case LANGUAGE_THAI:
        case LANGUAGE_TIBETAN:
        case LANGUAGE_URDU:
        case LANGUAGE_URDU_PAKISTAN:
        case LANGUAGE_URDU_INDIA:
        case LANGUAGE_USER_KURDISH_IRAQ:
        case LANGUAGE_USER_KURDISH_IRAN:
        case LANGUAGE_VIETNAMESE: // not included in langtab.src?
            nScript = SCRIPTTYPE_COMPLEX;
            break;

// currently not knowing scripttype - defaultet to LATIN:
/*
#define LANGUAGE_ARMENIAN                   0x042B
#define LANGUAGE_INDONESIAN                 0x0421
#define LANGUAGE_KAZAK                      0x043F
#define LANGUAGE_KONKANI                    0x0457
#define LANGUAGE_MACEDONIAN                 0x042F
#define LANGUAGE_TATAR                      0x0444
*/

    default:
        switch ( nLang & LANGUAGE_MASK_PRIMARY )
        {
            // CJK catcher
            case LANGUAGE_CHINESE & LANGUAGE_MASK_PRIMARY:
                nScript = SCRIPTTYPE_ASIAN;
                break;
            // CTL catcher
            case LANGUAGE_ARABIC & LANGUAGE_MASK_PRIMARY:
                nScript = SCRIPTTYPE_COMPLEX;
                break;
            // Western (actually not necessarily Latin but also Cyrillic, for example)
            default:
                nScript = SCRIPTTYPE_LATIN;
        }
        break;
    }
    return nScript;
}
// -----------------------------------------------------------------------------
<|endoftext|>


<commit_before>#include "generator/transit_generator_experimental.hpp"

#include "generator/utils.hpp"

#include "routing/index_router.hpp"
#include "routing/road_graph.hpp"
#include "routing/routing_exceptions.hpp"
#include "routing/vehicle_mask.hpp"

#include "storage/country_info_getter.hpp"
#include "storage/routing_helpers.hpp"

#include "transit/experimental/transit_types_experimental.hpp"

#include "indexer/mwm_set.hpp"

#include "platform/country_file.hpp"
#include "platform/platform.hpp"

#include "coding/file_writer.hpp"

#include "geometry/point2d.hpp"
#include "geometry/mercator.hpp"

#include "base/assert.hpp"
#include "base/exception.hpp"
#include "base/file_name_utils.hpp"
#include "base/logging.hpp"

#include "defines.hpp"

#include <algorithm>
#include <memory>
#include <vector>

using namespace generator;
using namespace platform;
using namespace routing;
using namespace routing::transit;
using namespace storage;

namespace transit
{
namespace experimental
{
void FillOsmIdToFeatureIdsMap(std::string const & osmIdToFeatureIdsPath,
                              OsmIdToFeatureIdsMap & mapping)
{
  bool const mappedIds = ForEachOsmId2FeatureId(
      osmIdToFeatureIdsPath, [&mapping](auto const & compositeId, auto featureId) {
        mapping[compositeId.m_mainId].push_back(featureId);
      });
  CHECK(mappedIds, (osmIdToFeatureIdsPath));
}

std::string GetMwmPath(std::string const & mwmDir, CountryId const & countryId)
{
  return base::JoinPath(mwmDir, countryId + DATA_FILE_EXTENSION);
}

std::vector<SingleMwmSegment> GetSegmentsFromEdges(std::vector<routing::Edge> && edges)
{
  std::vector<SingleMwmSegment> segments;
  segments.reserve(edges.size());

  for (auto const & edge : edges)
    segments.emplace_back(edge.GetFeatureId().m_index, edge.GetSegId(), edge.IsForward());

  return segments;
}

template <class D, class C>
std::vector<routing::Edge> GetBestPedestrianEdges(D const & destination, C && countryFileGetter,
                                                  IndexRouter & indexRouter,
                                                  std::unique_ptr<WorldGraph> & worldGraph,
                                                  CountryId const & countryId)
{
  std::vector<routing::Edge> edges;

  if (countryFileGetter(destination.GetPoint()) != countryId)
    return edges;

  // For pedestrian routing all the segments are considered as two-way segments so
  // IndexRouter::FindBestSegments() finds the same segments for |isOutgoing| == true
  // and |isOutgoing| == false.
  try
  {
    if (countryFileGetter(destination.GetPoint()) != countryId)
      return edges;

    bool dummy = false;
    indexRouter.FindBestEdges(destination.GetPoint(), platform::CountryFile(countryId),
                              m2::PointD::Zero() /* direction */, true /* isOutgoing */,
                              FeaturesRoadGraph::kClosestEdgesRadiusM, *worldGraph, edges, dummy);
    return edges;
  }
  catch (MwmIsNotAliveException const & e)
  {
    LOG(LCRITICAL, ("Destination point", mercator::ToLatLon(destination.GetPoint()), "belongs to the mwm", countryId,
                    "but it's not alive:", e.what()));
  }
  catch (RootException const & e)
  {
    LOG(LCRITICAL, ("Exception while looking for the best segment in mwm", countryId,
                    "Destination", mercator::ToLatLon(destination.GetPoint()), e.what()));
  }

  return edges;
}

/// \brief Calculates best pedestrians segments for gates and stops which are imported from GTFS.
void CalculateBestPedestrianSegments(std::string const & mwmPath, CountryId const & countryId,
                                     TransitData & transitData)
{
  // Creating IndexRouter.
  SingleMwmDataSource dataSource(mwmPath);

  auto infoGetter = storage::CountryInfoReader::CreateCountryInfoGetter(GetPlatform());
  CHECK(infoGetter, ());

  auto const countryFileGetter = [&infoGetter](m2::PointD const & pt) {
    return infoGetter->GetRegionCountryId(pt);
  };

  auto const getMwmRectByName = [&](std::string const & c) {
    CHECK_EQUAL(countryId, c, ());
    return infoGetter->GetLimitRectForLeaf(c);
  };

  CHECK_EQUAL(dataSource.GetMwmId().GetInfo()->GetType(), MwmInfo::COUNTRY, ());
  auto numMwmIds = std::make_shared<NumMwmIds>();
  numMwmIds->RegisterFile(CountryFile(countryId));

  // |indexRouter| is valid while |dataSource| is valid.
  IndexRouter indexRouter(VehicleType::Pedestrian, false /* load altitudes */,
                          CountryParentNameGetterFn(), countryFileGetter, getMwmRectByName,
                          numMwmIds, MakeNumMwmTree(*numMwmIds, *infoGetter),
                          traffic::TrafficCache(), dataSource.GetDataSource());
  auto worldGraph = indexRouter.MakeSingleMwmWorldGraph();

  auto const & gates = transitData.GetGates();
  for (size_t i = 0; i < gates.size(); ++i)
  {
    auto edges =
        GetBestPedestrianEdges(gates[i], countryFileGetter, indexRouter, worldGraph, countryId);
    transitData.SetGatePedestrianSegments(i, GetSegmentsFromEdges(std::move(edges)));
  }

  auto const & stops = transitData.GetStops();
  for (size_t i = 0; i < stops.size(); ++i)
  {
    auto edges =
        GetBestPedestrianEdges(stops[i], countryFileGetter, indexRouter, worldGraph, countryId);
    transitData.SetStopPedestrianSegments(i, GetSegmentsFromEdges(std::move(edges)));
  }
}

void DeserializeFromJson(OsmIdToFeatureIdsMap const & mapping, std::string const & transitJsonsPath,
                         TransitData & data)
{
  data.DeserializeFromJson(transitJsonsPath, mapping);
}

EdgeIdToFeatureId BuildTransit(std::string const & mwmDir, CountryId const & countryId,
                               std::string const & osmIdToFeatureIdsPath,
                               std::string const & transitDir)
{
  LOG(LINFO, ("Building experimental transit section for", countryId, "mwmDir:", mwmDir));
  std::string const mwmPath = GetMwmPath(mwmDir, countryId);

  OsmIdToFeatureIdsMap mapping;
  FillOsmIdToFeatureIdsMap(osmIdToFeatureIdsPath, mapping);

  std::string const transitPath = base::JoinPath(transitDir, countryId);
  if (!Platform::IsFileExistsByFullPath(transitPath))
  {
    LOG(LWARNING, ("Path to experimental transit files doesn't exist:", transitPath));
    return {};
  }

  TransitData data;
  DeserializeFromJson(mapping, transitPath, data);

  // Transit section can be empty.
  if (data.IsEmpty())
  {
    LOG(LWARNING, ("Experimental transit data deserialized from jsons is empty:", transitPath));
    return {};
  }

  CalculateBestPedestrianSegments(mwmPath, countryId, data);

  data.Sort();

  data.CheckSorted();
  data.CheckValid();
  data.CheckUnique();

  FilesContainerW container(mwmPath, FileWriter::OP_WRITE_EXISTING);
  auto writer = container.GetWriter(TRANSIT_FILE_TAG);
  data.Serialize(*writer);
  CHECK_EQUAL(data.GetEdgeIdToFeatureId().size(), data.GetEdges().size(), ());
  return data.GetEdgeIdToFeatureId();
}
}  // namespace experimental
}  // namespace transit
<commit_msg>[transit][generator] Fix cross mwm features numeration for experimental transit.<commit_after>#include "generator/transit_generator_experimental.hpp"

#include "generator/utils.hpp"

#include "routing/index_router.hpp"
#include "routing/road_graph.hpp"
#include "routing/routing_exceptions.hpp"
#include "routing/vehicle_mask.hpp"

#include "storage/country_info_getter.hpp"
#include "storage/routing_helpers.hpp"

#include "transit/experimental/transit_types_experimental.hpp"

#include "indexer/mwm_set.hpp"

#include "platform/country_file.hpp"
#include "platform/platform.hpp"

#include "coding/file_writer.hpp"

#include "geometry/point2d.hpp"
#include "geometry/mercator.hpp"

#include "base/assert.hpp"
#include "base/exception.hpp"
#include "base/file_name_utils.hpp"
#include "base/logging.hpp"

#include "defines.hpp"

#include <algorithm>
#include <memory>
#include <vector>

using namespace generator;
using namespace platform;
using namespace routing;
using namespace routing::transit;
using namespace storage;

namespace transit
{
namespace experimental
{
void FillOsmIdToFeatureIdsMap(std::string const & osmIdToFeatureIdsPath,
                              OsmIdToFeatureIdsMap & mapping)
{
  bool const mappedIds = ForEachOsmId2FeatureId(
      osmIdToFeatureIdsPath, [&mapping](auto const & compositeId, auto featureId) {
        mapping[compositeId.m_mainId].push_back(featureId);
      });
  CHECK(mappedIds, (osmIdToFeatureIdsPath));
}

std::string GetMwmPath(std::string const & mwmDir, CountryId const & countryId)
{
  return base::JoinPath(mwmDir, countryId + DATA_FILE_EXTENSION);
}

std::vector<SingleMwmSegment> GetSegmentsFromEdges(std::vector<routing::Edge> && edges)
{
  std::vector<SingleMwmSegment> segments;
  segments.reserve(edges.size());

  for (auto const & edge : edges)
    segments.emplace_back(edge.GetFeatureId().m_index, edge.GetSegId(), edge.IsForward());

  return segments;
}

template <class D, class C>
std::vector<routing::Edge> GetBestPedestrianEdges(D const & destination, C && countryFileGetter,
                                                  IndexRouter & indexRouter,
                                                  std::unique_ptr<WorldGraph> & worldGraph,
                                                  CountryId const & countryId)
{
  std::vector<routing::Edge> edges;

  if (countryFileGetter(destination.GetPoint()) != countryId)
    return edges;

  // For pedestrian routing all the segments are considered as two-way segments so
  // IndexRouter::FindBestSegments() finds the same segments for |isOutgoing| == true
  // and |isOutgoing| == false.
  try
  {
    if (countryFileGetter(destination.GetPoint()) != countryId)
      return edges;

    bool dummy = false;
    indexRouter.FindBestEdges(destination.GetPoint(), platform::CountryFile(countryId),
                              m2::PointD::Zero() /* direction */, true /* isOutgoing */,
                              FeaturesRoadGraph::kClosestEdgesRadiusM, *worldGraph, edges, dummy);
    return edges;
  }
  catch (MwmIsNotAliveException const & e)
  {
    LOG(LCRITICAL, ("Destination point", mercator::ToLatLon(destination.GetPoint()), "belongs to the mwm", countryId,
                    "but it's not alive:", e.what()));
  }
  catch (RootException const & e)
  {
    LOG(LCRITICAL, ("Exception while looking for the best segment in mwm", countryId,
                    "Destination", mercator::ToLatLon(destination.GetPoint()), e.what()));
  }

  return edges;
}

/// \brief Calculates best pedestrians segments for gates and stops which are imported from GTFS.
void CalculateBestPedestrianSegments(std::string const & mwmPath, CountryId const & countryId,
                                     TransitData & transitData)
{
  // Creating IndexRouter.
  SingleMwmDataSource dataSource(mwmPath);

  auto infoGetter = storage::CountryInfoReader::CreateCountryInfoGetter(GetPlatform());
  CHECK(infoGetter, ());

  auto const countryFileGetter = [&infoGetter](m2::PointD const & pt) {
    return infoGetter->GetRegionCountryId(pt);
  };

  auto const getMwmRectByName = [&](std::string const & c) {
    CHECK_EQUAL(countryId, c, ());
    return infoGetter->GetLimitRectForLeaf(c);
  };

  CHECK_EQUAL(dataSource.GetMwmId().GetInfo()->GetType(), MwmInfo::COUNTRY, ());
  auto numMwmIds = std::make_shared<NumMwmIds>();
  numMwmIds->RegisterFile(CountryFile(countryId));

  // |indexRouter| is valid while |dataSource| is valid.
  IndexRouter indexRouter(VehicleType::Pedestrian, false /* load altitudes */,
                          CountryParentNameGetterFn(), countryFileGetter, getMwmRectByName,
                          numMwmIds, MakeNumMwmTree(*numMwmIds, *infoGetter),
                          traffic::TrafficCache(), dataSource.GetDataSource());
  auto worldGraph = indexRouter.MakeSingleMwmWorldGraph();

  auto const & gates = transitData.GetGates();
  for (size_t i = 0; i < gates.size(); ++i)
  {
    auto edges =
        GetBestPedestrianEdges(gates[i], countryFileGetter, indexRouter, worldGraph, countryId);
    transitData.SetGatePedestrianSegments(i, GetSegmentsFromEdges(std::move(edges)));
  }

  auto const & stops = transitData.GetStops();
  for (size_t i = 0; i < stops.size(); ++i)
  {
    auto edges =
        GetBestPedestrianEdges(stops[i], countryFileGetter, indexRouter, worldGraph, countryId);
    transitData.SetStopPedestrianSegments(i, GetSegmentsFromEdges(std::move(edges)));
  }
}

void DeserializeFromJson(OsmIdToFeatureIdsMap const & mapping, std::string const & transitJsonsPath,
                         TransitData & data)
{
  data.DeserializeFromJson(transitJsonsPath, mapping);
}

EdgeIdToFeatureId BuildTransit(std::string const & mwmDir, CountryId const & countryId,
                               std::string const & osmIdToFeatureIdsPath,
                               std::string const & transitDir)
{
  LOG(LINFO, ("Building experimental transit section for", countryId, "mwmDir:", mwmDir));
  std::string const mwmPath = GetMwmPath(mwmDir, countryId);

  OsmIdToFeatureIdsMap mapping;
  FillOsmIdToFeatureIdsMap(osmIdToFeatureIdsPath, mapping);

  std::string const transitPath = base::JoinPath(transitDir, countryId);
  if (!Platform::IsFileExistsByFullPath(transitPath))
  {
    LOG(LWARNING, ("Path to experimental transit files doesn't exist:", transitPath));
    return {};
  }

  TransitData data;
  DeserializeFromJson(mapping, transitPath, data);

  // Transit section can be empty.
  if (data.IsEmpty())
  {
    LOG(LWARNING, ("Experimental transit data deserialized from jsons is empty:", transitPath));
    return {};
  }

  CalculateBestPedestrianSegments(mwmPath, countryId, data);

  data.Sort();

  data.CheckSorted();
  data.CheckValid();
  data.CheckUnique();

  // Transit graph numerates features according to their orderto their order..
  EdgeIdToFeatureId edgeToFeature;
  for (size_t i = 0; i < data.GetEdges().size(); ++i)
  {
    auto const & e = data.GetEdges()[i];
    EdgeId id(e.GetStop1Id(), e.GetStop2Id(), e.GetLineId());
    edgeToFeature[id] = i;
  }

  FilesContainerW container(mwmPath, FileWriter::OP_WRITE_EXISTING);
  auto writer = container.GetWriter(TRANSIT_FILE_TAG);
  data.Serialize(*writer);
  return edgeToFeature;
}
}  // namespace experimental
}  // namespace transit
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This utility can dump the contents of CRL set, optionally augmented with a
// delta CRL set.

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

#include <string>

#include "base/at_exit.h"
#include "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/string_number_conversions.h"
#include "net/base/crl_set.h"

static int Usage(const char* argv0) {
  fprintf(stderr, "Usage: %s <crl-set file> [<delta file>]\n", argv0);
  return 1;
}

int main(int argc, char** argv) {
  base::AtExitManager at_exit_manager;

  if (argc < 2)
    return Usage(argv[0]);

  FilePath crl_set_filename, delta_filename;

  if (argc != 2 && argc != 3)
    return Usage(argv[0]);

  crl_set_filename = FilePath::FromUTF8Unsafe(argv[1]);
  if (argc == 3)
    delta_filename = FilePath::FromUTF8Unsafe(argv[2]);

  std::string crl_set_bytes, delta_bytes;
  if (!file_util::ReadFileToString(crl_set_filename, &crl_set_bytes))
    return 1;
  if (!delta_filename.empty() &&
      !file_util::ReadFileToString(delta_filename, &delta_bytes)) {
    return 1;
  }

  scoped_refptr<net::CRLSet> crl_set, final_crl_set;
  if (!net::CRLSet::Parse(crl_set_bytes, &crl_set)) {
    fprintf(stderr, "Failed to parse CRLSet\n");
    return 1;
  }

  if (!delta_bytes.empty()) {
    if (!crl_set->ApplyDelta(delta_bytes, &final_crl_set)) {
      fprintf(stderr, "Failed to apply delta to CRLSet\n");
      return 1;
    }
  } else {
    final_crl_set = crl_set;
  }

  const net::CRLSet::CRLList& crls = crl_set->crls();
  for (net::CRLSet::CRLList::const_iterator i = crls.begin(); i != crls.end();
       i++) {
    printf("%s\n", base::HexEncode(i->first.data(), i->first.size()).c_str());
    for (std::vector<std::string>::const_iterator j = i->second.begin();
         j != i->second.end(); j++) {
      printf("  %s\n", base::HexEncode(j->data(), j->size()).c_str());
    }
  }

  return 0;
}
<commit_msg>net: fix crl_set_dump to print the delta-updated CRL.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This utility can dump the contents of CRL set, optionally augmented with a
// delta CRL set.

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

#include <string>

#include "base/at_exit.h"
#include "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/string_number_conversions.h"
#include "net/base/crl_set.h"

static int Usage(const char* argv0) {
  fprintf(stderr, "Usage: %s <crl-set file> [<delta file>]\n", argv0);
  return 1;
}

int main(int argc, char** argv) {
  base::AtExitManager at_exit_manager;

  if (argc < 2)
    return Usage(argv[0]);

  FilePath crl_set_filename, delta_filename;

  if (argc != 2 && argc != 3)
    return Usage(argv[0]);

  crl_set_filename = FilePath::FromUTF8Unsafe(argv[1]);
  if (argc == 3)
    delta_filename = FilePath::FromUTF8Unsafe(argv[2]);

  std::string crl_set_bytes, delta_bytes;
  if (!file_util::ReadFileToString(crl_set_filename, &crl_set_bytes))
    return 1;
  if (!delta_filename.empty() &&
      !file_util::ReadFileToString(delta_filename, &delta_bytes)) {
    return 1;
  }

  scoped_refptr<net::CRLSet> crl_set, final_crl_set;
  if (!net::CRLSet::Parse(crl_set_bytes, &crl_set)) {
    fprintf(stderr, "Failed to parse CRLSet\n");
    return 1;
  }

  if (!delta_bytes.empty()) {
    if (!crl_set->ApplyDelta(delta_bytes, &final_crl_set)) {
      fprintf(stderr, "Failed to apply delta to CRLSet\n");
      return 1;
    }
  } else {
    final_crl_set = crl_set;
  }

  const net::CRLSet::CRLList& crls = final_crl_set->crls();
  for (net::CRLSet::CRLList::const_iterator i = crls.begin(); i != crls.end();
       i++) {
    printf("%s\n", base::HexEncode(i->first.data(), i->first.size()).c_str());
    for (std::vector<std::string>::const_iterator j = i->second.begin();
         j != i->second.end(); j++) {
      printf("  %s\n", base::HexEncode(j->data(), j->size()).c_str());
    }
  }

  return 0;
}
<|endoftext|>


<commit_before>//
//  server.cpp
//  fibio
//
//  Created by Chen Xu on 14-3-13.
//  Copyright (c) 2014 0d0a.com. All rights reserved.
//

#include <boost/asio/basic_waitable_timer.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/iostreams/restrict.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/algorithm/string/case_conv.hpp>
#include <fibio/future.hpp>
#include <fibio/http/server/server.hpp>

namespace fibio { namespace http {
    namespace detail {
        typedef fibio::http::server_request request;
        typedef fibio::http::server_response response;
        typedef boost::asio::basic_waitable_timer<std::chrono::steady_clock> watchdog_timer_t;

        template<typename Stream>
        struct stream_traits {};

        template<>
        struct stream_traits<tcp_stream> {
            typedef tcp_stream stream_type;
            typedef tcp_stream_acceptor acceptor_type;
            // HACK:
            typedef int *arg_type;
            static constexpr uint16_t default_port=80;
            static stream_type *construct(arg_type) {
                return new stream_type;
            }
        };

#ifdef HAVE_SSL
        template<>
        struct stream_traits<ssl::tcp_stream> {
            typedef ssl::tcp_stream stream_type;
            typedef ssl::tcp_stream_acceptor acceptor_type;
            // HACK:
            typedef ssl::context *arg_type;
            static constexpr uint16_t default_port=443;
            static stream_type *construct(arg_type arg) {
                return new stream_type(*arg);
            }
        };
#endif

        template<typename Stream>
        struct connection {
            typedef stream_traits<Stream> traits_type;
            typedef typename traits_type::stream_type stream_type;
            typedef typename traits_type::arg_type arg_type;

            connection(const std::string &host,
                       timeout_type read_timeout,
                       timeout_type write_timeout,
                       arg_type arg)
            : host_(host)
            , read_timeout_(read_timeout)
            , write_timeout_(write_timeout)
            , stream_(traits_type::construct(arg))
            {}

            connection(connection &&other)=default;
            connection(const connection &)=delete;
            ~connection() {
                close();
            }

            void start_watchdog() {
                watchdog_timer_.reset(new watchdog_timer_t(asio::get_io_service()));
                watchdog_fiber_.reset(new fiber(fiber::attributes(fiber::attributes::stick_with_parent),
                                                &connection::watchdog_fiber,
                                                this));
            }

            void watchdog_fiber() {
                boost::system::error_code ignore_ec;
                while (is_open()) {
                    watchdog_timer_->async_wait(asio::yield[ignore_ec]);
                    // close the stream if timeout
                    auto dur=watchdog_timer_->expires_from_now();
                    std::chrono::seconds s=std::chrono::duration_cast<std::chrono::seconds>(dur);
                    if (s <= std::chrono::seconds(0)) {
                        stream().close();
                    }
                }
            }

            bool recv(request &req) {
                bool ret=false;
                if (bad()) return false;
                if(read_timeout_>NO_TIMEOUT) {
                    // Set read timeout
                    watchdog_timer_->expires_from_now(read_timeout_);
                }
                ret=req.read(stream());
                return ret;
            }

            bool send(response &resp) {
                bool ret=false;
                if (bad()) return false;
                if(write_timeout_>NO_TIMEOUT) {
                    // Set write timeout
                    watchdog_timer_->expires_from_now(write_timeout_);
                }
                ret=resp.write(stream());
                if (!resp.keep_alive()) {
                    stream().close();
                    return false;
                }
                return ret;
            }

            bool is_open() const { return stream_ && stream().is_open(); }

            void close() {
                if (stream_) {
                    stream_->close();
                    stream_.reset();
                }
                if (watchdog_timer_) {
                    watchdog_timer_->cancel();
                }
                if (watchdog_fiber_) {
                    watchdog_fiber_->join();
                    watchdog_fiber_.reset();
                }
                watchdog_timer_.reset();
            }

            stream_type &stream() { return *stream_; };
            const stream_type &stream() const { return *stream_; };

            bool bad() const {
                if(!stream_) return true;
                return !stream().is_open() || stream().eof() || stream().fail() || stream().bad();
            }

            bool good() const {
                return !bad();
            }

            const std::string &host_;
            timeout_type read_timeout_;
            timeout_type write_timeout_;

            std::unique_ptr<stream_type> stream_;
            std::unique_ptr<watchdog_timer_t> watchdog_timer_;
            std::unique_ptr<fiber> watchdog_fiber_;
        };

        template<typename Stream>
        struct server_engine {
            typedef stream_traits<Stream> traits_type;
            typedef typename traits_type::stream_type stream_type;
            typedef typename traits_type::acceptor_type acceptor_type;
            typedef typename traits_type::arg_type arg_type;
            typedef connection<Stream> connection_type;

            server_engine(arg_type arg,
                          const std::string &addr,
                          unsigned short port,
                          const std::string &host,
                          server::request_handler default_request_handler)
            : host_(host)
            , acceptor_(addr.c_str(), port)
            , default_request_handler_(std::move(default_request_handler))
            , arg_(arg)
            , active_connection_(0)
            {}

            server_engine(unsigned short port, const std::string &host)
            : host_(host)
            , acceptor_(port)
            {}

            void start() {
                watchdog_.reset(new fiber(fiber::attributes(fiber::attributes::stick_with_parent),
                                          &server_engine::watchdog,
                                          this));
                boost::system::error_code ec;
                // Loop until accept closed
                while (true) {
                    connection_type sc(host_, read_timeout_, write_timeout_, arg_);
                    ec=accept(sc);
                    if(ec) break;
                    sc.read_timeout_=read_timeout_;
                    sc.write_timeout_=write_timeout_;
                    fiber(&server_engine::servant, this, std::move(sc)).detach();
                }
                watchdog_->join();
            }

            void close() {
                exit_signal_.set_value();
                if(watchdog_)
                    watchdog_->join();
                // Wait until all connections are closed
                std::unique_lock<mutex> l(connection_counter_mtx_);
                while(active_connection_) {
                    connection_close_.wait(l);
                }
            }

            boost::system::error_code accept(connection_type &sc) {
                boost::system::error_code ec;
                acceptor_(sc.stream(), ec);
                if (!ec) {
                    active_connection_++;
                }
                return ec;
            }

            void watchdog() {
                exit_signal_.get_future().wait();
                acceptor_.close();
            }

            void servant(connection_type c) {
                if (read_timeout_>NO_TIMEOUT || write_timeout_>NO_TIMEOUT) {
                    c.start_watchdog();
                }
                request req;
                int count=0;
                while(c.recv(req)) {
                    response resp;
                    req.raw_stream_=&(c.stream());
                    resp.raw_stream_=&(c.stream());
                    // Set default attributes for response
                    resp.status_code(http_status_code::OK);
                    resp.version(req.version);
                    resp.keep_alive(req.keep_alive);
                    if(count>=max_keep_alive_) resp.keep_alive(false);
                    try {
                        if(!default_request_handler_(req, resp)) break;
                    } catch(boost::bad_lexical_cast &e) {
                        resp.status_code(http_status_code::BAD_REQUEST);
                    } catch(server_error &e) {
                        resp.status_code(e.code);
                        resp.body(e.what());
                    } catch(std::exception &e) {
                        resp.status_code(http_status_code::INTERNAL_SERVER_ERROR);
                        resp.keep_alive(false);
                    }
                    resp.body_stream().flush();
                    c.send(resp);
                    // Make sure we consumed all parts of the request
                    req.drop_body();
                    // Make sure all data are received and sent
                    c.stream().flush();
                    // Keepalive counter
                    count++;
                    if (!resp.keep_alive()) break;
                }
                c.close();

                active_connection_--;
                connection_close_.notify_one();
            }

            std::string host_;
            acceptor_type acceptor_;
            server::request_handler default_request_handler_;
            promise<void> exit_signal_;
            timeout_type read_timeout_=DEFAULT_TIMEOUT;
            timeout_type write_timeout_=DEFAULT_TIMEOUT;
            unsigned max_keep_alive_=DEFAULT_MAX_KEEP_ALIVE;
            arg_type arg_;

            std::unique_ptr<fiber> watchdog_;

            // connection uses vhost info in server
            // make sure server exists if there is living connection
            std::atomic<uint32_t> active_connection_;
            mutex connection_counter_mtx_;
            condition_variable connection_close_;
        };
    }   // End of namespace detail

    //////////////////////////////////////////////////////////////////////////////////////////
    // server_request
    //////////////////////////////////////////////////////////////////////////////////////////

    void server_request::clear() {
        // Make sure there is no pending data in the last request
        drop_body();
        params.clear();
        common::request::clear();
    }

    bool server_request::accept_compressed() const {
        // TODO: Kinda buggy
        return strcasestr(request::header("Accept-Encoding").c_str(), "gzip")!=NULL;
    }

    bool server_request::read(std::istream &is) {
        clear();
        if (!common::request::read_header(is)) return false;
        if (content_length>0) {
            // Setup body stream
            namespace bio = boost::iostreams;
            restriction_.reset(new bio::restriction<std::istream>(is, 0, content_length));
            bio::filtering_istream *in=new bio::filtering_istream;
            in->push(*restriction_);
            body_stream_.reset(in);
        }
        return true;
    }

    const common::cookie_map &server_request::cookies() {
        if (!cookies_) {
            cookies_.reset(new common::cookie_map);
            common::parse_cookie(headers, *cookies_, false);
        }
        return *cookies_;
    }

    void server_request::drop_body() {
        // Discard body content iff body stream exists
        if (body_stream_) {
            while (!body_stream().eof()) {
                char buf[1024];
                body_stream().read(buf, sizeof(buf));
            }
            body_stream_.reset();
            restriction_.reset();
        }
    }

    //////////////////////////////////////////////////////////////////////////////////////////
    // server_response
    //////////////////////////////////////////////////////////////////////////////////////////

    void server_response::clear() {
        common::response::clear();
        std::string e;
        if (!raw_body_stream_.vector().empty())
            raw_body_stream_.swap_vector(e);
    }

    const std::string &server_response::body() const {
        return raw_body_stream_.vector();
    }

    std::ostream &server_response::body_stream() {
        return raw_body_stream_;
    }

    server_response &server_response::header(const std::string &key, const std::string &value) {
        headers.insert({key, value});
        return *this;
    }

    server_response &server_response::cookie(const common::cookie &c) {
        headers.insert({"Set-Cookie", c.to_string()});
        return *this;
    }

    size_t server_response::content_length() const {
        return raw_body_stream_.vector().size();
    }

    server_response &server_response::content_type(const std::string &ct) {
        if(ct.empty()) {
            headers.erase("Content-Type");
        } else {
            set_header("Content-Type", ct);
        }
        return *this;
    }

    bool server_response::write_header(std::ostream &os) {
        response::set_header("Connection", keep_alive() ? "keep-alive" : "close");
        if (!common::response::write_header(os)) return false;
        return !os.eof() && !os.fail() && !os.bad();
    }

    bool server_response::write(std::ostream &os) {
        response::set_header("Content-Length", boost::lexical_cast<std::string>(content_length()));
        // Write headers
        if (!write_header(os)) return false;
        // Write body
        os.write(&(raw_body_stream_.vector()[0]), raw_body_stream_.vector().size());
        os.flush();
        return !os.eof() && !os.fail() && !os.bad();
    }

    //////////////////////////////////////////////////////////////////////////////////////////
    // server
    //////////////////////////////////////////////////////////////////////////////////////////

    typedef detail::server_engine<tcp_stream> server_engine;
#ifdef HAVE_SSL
    typedef detail::server_engine<ssl::tcp_stream> ssl_server_engine;
#endif

    static inline server_engine *get_engine(server::impl *impl) {
        return reinterpret_cast<server_engine *>(impl);
    }

#ifdef HAVE_SSL
    static inline ssl_server_engine *get_ssl_engine(server::impl *impl) {
        return reinterpret_cast<ssl_server_engine *>(impl);
    }
#endif

    template<typename Stream>
    static std::string get_default_host_name(uint16_t port) {
        std::string ret="127.0.0.1";
        if(detail::stream_traits<Stream>::default_port!=port) {
            ret+=':';
            ret+=boost::lexical_cast<std::string>(port);
        }
        return ret;
    }

    server::~server() {
        stop();
#ifdef HAVE_SSL
        if (ssl())
        {
            delete get_ssl_engine(engine_);
        }
        else
#endif
        {
            delete get_engine(engine_);
        }
    }

    void server::init_engine() {
#ifdef HAVE_SSL
        if(ssl())
        {
            engine_=reinterpret_cast<impl *>(new ssl_server_engine(s_.ctx_,
                                                                   s_.address_,
                                                                   s_.port_,
                                                                   get_default_host_name<ssl::tcp_stream>(s_.port_),
                                                                   std::move(s_.default_request_handler_)));
            get_ssl_engine(engine_)->read_timeout_=s_.read_timeout_;
            get_ssl_engine(engine_)->write_timeout_=s_.write_timeout_;
            get_ssl_engine(engine_)->max_keep_alive_=s_.max_keep_alive_;
        }
        else
#endif
        {
            engine_=reinterpret_cast<impl *>(new server_engine(0,
                                                               s_.address_,
                                                               s_.port_,
                                                               get_default_host_name<tcp_stream>(s_.port_),
                                                               std::move(s_.default_request_handler_)));
            get_engine(engine_)->read_timeout_=s_.read_timeout_;
            get_engine(engine_)->write_timeout_=s_.write_timeout_;
            get_engine(engine_)->max_keep_alive_=s_.max_keep_alive_;
        }
    }

    server &server::start() {
        init_engine();
#ifdef HAVE_SSL
        if (ssl())
        {
            servant_.reset(new fiber(&ssl_server_engine::start, get_ssl_engine(engine_)));
        }
        else
#endif
        {
            servant_.reset(new fiber(&server_engine::start, get_engine(engine_)));
        }
        return *this;
    }

    void server::stop() {
        if (servant_) {
#ifdef HAVE_SSL
            if (ssl())
            {
                get_ssl_engine(engine_)->close();
            }
            else
#endif
            {
                get_engine(engine_)->close();
            }
        }
    }

    boost::system::error_code server::join() {
        try {
            if (servant_) {
                servant_->join(true);
                servant_.reset();
            }
        } catch(boost::system::system_error &e) {
            return e.code();
        }
        return boost::system::error_code();
    }
}}  // End of namespace fibio::http
<commit_msg>Don't use strcasestr<commit_after>//
//  server.cpp
//  fibio
//
//  Created by Chen Xu on 14-3-13.
//  Copyright (c) 2014 0d0a.com. All rights reserved.
//

#include <boost/asio/basic_waitable_timer.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/iostreams/restrict.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/algorithm/string/find.hpp>
#include <fibio/future.hpp>
#include <fibio/http/server/server.hpp>

namespace fibio { namespace http {
    namespace detail {
        typedef fibio::http::server_request request;
        typedef fibio::http::server_response response;
        typedef boost::asio::basic_waitable_timer<std::chrono::steady_clock> watchdog_timer_t;

        template<typename Stream>
        struct stream_traits {};

        template<>
        struct stream_traits<tcp_stream> {
            typedef tcp_stream stream_type;
            typedef tcp_stream_acceptor acceptor_type;
            // HACK:
            typedef int *arg_type;
            static constexpr uint16_t default_port=80;
            static stream_type *construct(arg_type) {
                return new stream_type;
            }
        };

#ifdef HAVE_SSL
        template<>
        struct stream_traits<ssl::tcp_stream> {
            typedef ssl::tcp_stream stream_type;
            typedef ssl::tcp_stream_acceptor acceptor_type;
            // HACK:
            typedef ssl::context *arg_type;
            static constexpr uint16_t default_port=443;
            static stream_type *construct(arg_type arg) {
                return new stream_type(*arg);
            }
        };
#endif

        template<typename Stream>
        struct connection {
            typedef stream_traits<Stream> traits_type;
            typedef typename traits_type::stream_type stream_type;
            typedef typename traits_type::arg_type arg_type;

            connection(const std::string &host,
                       timeout_type read_timeout,
                       timeout_type write_timeout,
                       arg_type arg)
            : host_(host)
            , read_timeout_(read_timeout)
            , write_timeout_(write_timeout)
            , stream_(traits_type::construct(arg))
            {}

            connection(connection &&other)=default;
            connection(const connection &)=delete;
            ~connection() {
                close();
            }

            void start_watchdog() {
                watchdog_timer_.reset(new watchdog_timer_t(asio::get_io_service()));
                watchdog_fiber_.reset(new fiber(fiber::attributes(fiber::attributes::stick_with_parent),
                                                &connection::watchdog_fiber,
                                                this));
            }

            void watchdog_fiber() {
                boost::system::error_code ignore_ec;
                while (is_open()) {
                    watchdog_timer_->async_wait(asio::yield[ignore_ec]);
                    // close the stream if timeout
                    auto dur=watchdog_timer_->expires_from_now();
                    std::chrono::seconds s=std::chrono::duration_cast<std::chrono::seconds>(dur);
                    if (s <= std::chrono::seconds(0)) {
                        stream().close();
                    }
                }
            }

            bool recv(request &req) {
                bool ret=false;
                if (bad()) return false;
                if(read_timeout_>NO_TIMEOUT) {
                    // Set read timeout
                    watchdog_timer_->expires_from_now(read_timeout_);
                }
                ret=req.read(stream());
                return ret;
            }

            bool send(response &resp) {
                bool ret=false;
                if (bad()) return false;
                if(write_timeout_>NO_TIMEOUT) {
                    // Set write timeout
                    watchdog_timer_->expires_from_now(write_timeout_);
                }
                ret=resp.write(stream());
                if (!resp.keep_alive()) {
                    stream().close();
                    return false;
                }
                return ret;
            }

            bool is_open() const { return stream_ && stream().is_open(); }

            void close() {
                if (stream_) {
                    stream_->close();
                    stream_.reset();
                }
                if (watchdog_timer_) {
                    watchdog_timer_->cancel();
                }
                if (watchdog_fiber_) {
                    watchdog_fiber_->join();
                    watchdog_fiber_.reset();
                }
                watchdog_timer_.reset();
            }

            stream_type &stream() { return *stream_; };
            const stream_type &stream() const { return *stream_; };

            bool bad() const {
                if(!stream_) return true;
                return !stream().is_open() || stream().eof() || stream().fail() || stream().bad();
            }

            bool good() const {
                return !bad();
            }

            const std::string &host_;
            timeout_type read_timeout_;
            timeout_type write_timeout_;

            std::unique_ptr<stream_type> stream_;
            std::unique_ptr<watchdog_timer_t> watchdog_timer_;
            std::unique_ptr<fiber> watchdog_fiber_;
        };

        template<typename Stream>
        struct server_engine {
            typedef stream_traits<Stream> traits_type;
            typedef typename traits_type::stream_type stream_type;
            typedef typename traits_type::acceptor_type acceptor_type;
            typedef typename traits_type::arg_type arg_type;
            typedef connection<Stream> connection_type;

            server_engine(arg_type arg,
                          const std::string &addr,
                          unsigned short port,
                          const std::string &host,
                          server::request_handler default_request_handler)
            : host_(host)
            , acceptor_(addr.c_str(), port)
            , default_request_handler_(std::move(default_request_handler))
            , arg_(arg)
            , active_connection_(0)
            {}

            server_engine(unsigned short port, const std::string &host)
            : host_(host)
            , acceptor_(port)
            {}

            void start() {
                watchdog_.reset(new fiber(fiber::attributes(fiber::attributes::stick_with_parent),
                                          &server_engine::watchdog,
                                          this));
                boost::system::error_code ec;
                // Loop until accept closed
                while (true) {
                    connection_type sc(host_, read_timeout_, write_timeout_, arg_);
                    ec=accept(sc);
                    if(ec) break;
                    sc.read_timeout_=read_timeout_;
                    sc.write_timeout_=write_timeout_;
                    fiber(&server_engine::servant, this, std::move(sc)).detach();
                }
                watchdog_->join();
            }

            void close() {
                exit_signal_.set_value();
                if(watchdog_)
                    watchdog_->join();
                // Wait until all connections are closed
                std::unique_lock<mutex> l(connection_counter_mtx_);
                while(active_connection_) {
                    connection_close_.wait(l);
                }
            }

            boost::system::error_code accept(connection_type &sc) {
                boost::system::error_code ec;
                acceptor_(sc.stream(), ec);
                if (!ec) {
                    active_connection_++;
                }
                return ec;
            }

            void watchdog() {
                exit_signal_.get_future().wait();
                acceptor_.close();
            }

            void servant(connection_type c) {
                if (read_timeout_>NO_TIMEOUT || write_timeout_>NO_TIMEOUT) {
                    c.start_watchdog();
                }
                request req;
                int count=0;
                while(c.recv(req)) {
                    response resp;
                    req.raw_stream_=&(c.stream());
                    resp.raw_stream_=&(c.stream());
                    // Set default attributes for response
                    resp.status_code(http_status_code::OK);
                    resp.version(req.version);
                    resp.keep_alive(req.keep_alive);
                    if(count>=max_keep_alive_) resp.keep_alive(false);
                    try {
                        if(!default_request_handler_(req, resp)) break;
                    } catch(boost::bad_lexical_cast &e) {
                        resp.status_code(http_status_code::BAD_REQUEST);
                    } catch(server_error &e) {
                        resp.status_code(e.code);
                        resp.body(e.what());
                    } catch(std::exception &e) {
                        resp.status_code(http_status_code::INTERNAL_SERVER_ERROR);
                        resp.keep_alive(false);
                    }
                    resp.body_stream().flush();
                    c.send(resp);
                    // Make sure we consumed all parts of the request
                    req.drop_body();
                    // Make sure all data are received and sent
                    c.stream().flush();
                    // Keepalive counter
                    count++;
                    if (!resp.keep_alive()) break;
                }
                c.close();

                active_connection_--;
                connection_close_.notify_one();
            }

            std::string host_;
            acceptor_type acceptor_;
            server::request_handler default_request_handler_;
            promise<void> exit_signal_;
            timeout_type read_timeout_=DEFAULT_TIMEOUT;
            timeout_type write_timeout_=DEFAULT_TIMEOUT;
            unsigned max_keep_alive_=DEFAULT_MAX_KEEP_ALIVE;
            arg_type arg_;

            std::unique_ptr<fiber> watchdog_;

            // connection uses vhost info in server
            // make sure server exists if there is living connection
            std::atomic<uint32_t> active_connection_;
            mutex connection_counter_mtx_;
            condition_variable connection_close_;
        };
    }   // End of namespace detail

    //////////////////////////////////////////////////////////////////////////////////////////
    // server_request
    //////////////////////////////////////////////////////////////////////////////////////////

    void server_request::clear() {
        // Make sure there is no pending data in the last request
        drop_body();
        params.clear();
        common::request::clear();
    }

    bool server_request::accept_compressed() const {
        // TODO: Kinda buggy
        return !(boost::algorithm::ifind_first(request::header("Accept-Encoding"), "gzip").empty());
    }

    bool server_request::read(std::istream &is) {
        clear();
        if (!common::request::read_header(is)) return false;
        if (content_length>0) {
            // Setup body stream
            namespace bio = boost::iostreams;
            restriction_.reset(new bio::restriction<std::istream>(is, 0, content_length));
            bio::filtering_istream *in=new bio::filtering_istream;
            in->push(*restriction_);
            body_stream_.reset(in);
        }
        return true;
    }

    const common::cookie_map &server_request::cookies() {
        if (!cookies_) {
            cookies_.reset(new common::cookie_map);
            common::parse_cookie(headers, *cookies_, false);
        }
        return *cookies_;
    }

    void server_request::drop_body() {
        // Discard body content iff body stream exists
        if (body_stream_) {
            while (!body_stream().eof()) {
                char buf[1024];
                body_stream().read(buf, sizeof(buf));
            }
            body_stream_.reset();
            restriction_.reset();
        }
    }

    //////////////////////////////////////////////////////////////////////////////////////////
    // server_response
    //////////////////////////////////////////////////////////////////////////////////////////

    void server_response::clear() {
        common::response::clear();
        std::string e;
        if (!raw_body_stream_.vector().empty())
            raw_body_stream_.swap_vector(e);
    }

    const std::string &server_response::body() const {
        return raw_body_stream_.vector();
    }

    std::ostream &server_response::body_stream() {
        return raw_body_stream_;
    }

    server_response &server_response::header(const std::string &key, const std::string &value) {
        headers.insert({key, value});
        return *this;
    }

    server_response &server_response::cookie(const common::cookie &c) {
        headers.insert({"Set-Cookie", c.to_string()});
        return *this;
    }

    size_t server_response::content_length() const {
        return raw_body_stream_.vector().size();
    }

    server_response &server_response::content_type(const std::string &ct) {
        if(ct.empty()) {
            headers.erase("Content-Type");
        } else {
            set_header("Content-Type", ct);
        }
        return *this;
    }

    bool server_response::write_header(std::ostream &os) {
        response::set_header("Connection", keep_alive() ? "keep-alive" : "close");
        if (!common::response::write_header(os)) return false;
        return !os.eof() && !os.fail() && !os.bad();
    }

    bool server_response::write(std::ostream &os) {
        response::set_header("Content-Length", boost::lexical_cast<std::string>(content_length()));
        // Write headers
        if (!write_header(os)) return false;
        // Write body
        os.write(&(raw_body_stream_.vector()[0]), raw_body_stream_.vector().size());
        os.flush();
        return !os.eof() && !os.fail() && !os.bad();
    }

    //////////////////////////////////////////////////////////////////////////////////////////
    // server
    //////////////////////////////////////////////////////////////////////////////////////////

    typedef detail::server_engine<tcp_stream> server_engine;
#ifdef HAVE_SSL
    typedef detail::server_engine<ssl::tcp_stream> ssl_server_engine;
#endif

    static inline server_engine *get_engine(server::impl *impl) {
        return reinterpret_cast<server_engine *>(impl);
    }

#ifdef HAVE_SSL
    static inline ssl_server_engine *get_ssl_engine(server::impl *impl) {
        return reinterpret_cast<ssl_server_engine *>(impl);
    }
#endif

    template<typename Stream>
    static std::string get_default_host_name(uint16_t port) {
        std::string ret="127.0.0.1";
        if(detail::stream_traits<Stream>::default_port!=port) {
            ret+=':';
            ret+=boost::lexical_cast<std::string>(port);
        }
        return ret;
    }

    server::~server() {
        stop();
#ifdef HAVE_SSL
        if (ssl())
        {
            delete get_ssl_engine(engine_);
        }
        else
#endif
        {
            delete get_engine(engine_);
        }
    }

    void server::init_engine() {
#ifdef HAVE_SSL
        if(ssl())
        {
            engine_=reinterpret_cast<impl *>(new ssl_server_engine(s_.ctx_,
                                                                   s_.address_,
                                                                   s_.port_,
                                                                   get_default_host_name<ssl::tcp_stream>(s_.port_),
                                                                   std::move(s_.default_request_handler_)));
            get_ssl_engine(engine_)->read_timeout_=s_.read_timeout_;
            get_ssl_engine(engine_)->write_timeout_=s_.write_timeout_;
            get_ssl_engine(engine_)->max_keep_alive_=s_.max_keep_alive_;
        }
        else
#endif
        {
            engine_=reinterpret_cast<impl *>(new server_engine(0,
                                                               s_.address_,
                                                               s_.port_,
                                                               get_default_host_name<tcp_stream>(s_.port_),
                                                               std::move(s_.default_request_handler_)));
            get_engine(engine_)->read_timeout_=s_.read_timeout_;
            get_engine(engine_)->write_timeout_=s_.write_timeout_;
            get_engine(engine_)->max_keep_alive_=s_.max_keep_alive_;
        }
    }

    server &server::start() {
        init_engine();
#ifdef HAVE_SSL
        if (ssl())
        {
            servant_.reset(new fiber(&ssl_server_engine::start, get_ssl_engine(engine_)));
        }
        else
#endif
        {
            servant_.reset(new fiber(&server_engine::start, get_engine(engine_)));
        }
        return *this;
    }

    void server::stop() {
        if (servant_) {
#ifdef HAVE_SSL
            if (ssl())
            {
                get_ssl_engine(engine_)->close();
            }
            else
#endif
            {
                get_engine(engine_)->close();
            }
        }
    }

    boost::system::error_code server::join() {
        try {
            if (servant_) {
                servant_->join(true);
                servant_.reset();
            }
        } catch(boost::system::system_error &e) {
            return e.code();
        }
        return boost::system::error_code();
    }
}}  // End of namespace fibio::http
<|endoftext|>


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

// no include protection. This file is included from elementimport.hxx only.

#ifndef _INCLUDING_FROM_ELEMENTIMPORT_HXX_
#error "do not include this file directly!"
#endif

// no namespace. Same as above: this file is included from elementimport.hxx only,
// and this is done inside the namespace

//=========================================================================
//= OContainerImport
//=========================================================================
//-------------------------------------------------------------------------
template <class BASE>
SvXMLImportContext* OContainerImport< BASE >::CreateChildContext(
    sal_uInt16 _nPrefix, const ::rtl::OUString& _rLocalName,
    const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rxAttrList)
{
    // maybe it's a sub control
    if (_rLocalName == m_sWrapperElementName)
        if (m_xMeAsContainer.is())
            return implCreateControlWrapper(_nPrefix, _rLocalName);
        else
        {
            OSL_ENSURE(sal_False, "OContainerImport::CreateChildContext: don't have an element!");
            return NULL;
        }

    return BASE::CreateChildContext(_nPrefix, _rLocalName, _rxAttrList);
}

//-------------------------------------------------------------------------
template <class BASE>
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
    OContainerImport< BASE >::createElement()
{
    // let the base class create the object
    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > xReturn = BASE::createElement();
    if (!xReturn.is())
        return xReturn;

    // ensure that the object is a XNameContainer (we strongly need this for inserting child elements)
    m_xMeAsContainer = ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer >(xReturn, ::com::sun::star::uno::UNO_QUERY);
    if (!m_xMeAsContainer.is())
    {
        OSL_ENSURE(sal_False, "OContainerImport::createElement: invalid element (no XNameContainer) created!");
        xReturn.clear();
    }

    return xReturn;
}

//-------------------------------------------------------------------------
template <class BASE>
void OContainerImport< BASE >::EndElement()
{
    BASE::EndElement();

    // now that we have all children, attach the events
    ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > xIndexContainer(m_xMeAsContainer, ::com::sun::star::uno::UNO_QUERY);
    if (xIndexContainer.is())
        ODefaultEventAttacherManager::setEvents(xIndexContainer);
}

//=========================================================================
//= OColumnImport
//=========================================================================
//-------------------------------------------------------------------------
template <class BASE>
OColumnImport< BASE >::OColumnImport(IFormsImportContext& _rImport, IEventAttacherManager& _rEventManager, sal_uInt16 _nPrefix, const ::rtl::OUString& _rName,
        const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer >& _rxParentContainer,
        OControlElement::ElementType _eType,
        const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rxOuterAttribs)
    :BASE(_rImport, _rEventManager, _nPrefix, _rName, _rxParentContainer, _eType)
    ,m_xColumnFactory(_rxParentContainer, ::com::sun::star::uno::UNO_QUERY)
{
    OSL_ENSURE(m_xColumnFactory.is(), "OColumnImport::OColumnImport: invalid parent container (no factory)!");
}

//-------------------------------------------------------------------------
// OElementImport overridables
template <class BASE>
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > OColumnImport< BASE >::createElement()
{
    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > xReturn;
    // no call to the base class' method. We have to use the grid column factory
    if (m_xColumnFactory.is())
    {
        // create the column
        xReturn = m_xColumnFactory->createColumn(this->m_sServiceName);
        OSL_ENSURE(xReturn.is(), "OColumnImport::createElement: the factory returned an invalid object!");
    }
    return xReturn;
}

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.4.334.1  2004/07/13 20:28:08  fa
 *  #i31445# explicitly scope data member to satisfy gcc 3.4
 *
 *  Revision 1.4  2001/01/03 16:25:34  fs
 *  file format change (extra wrapper element for controls, similar to columns)
 *
 *  Revision 1.3  2001/01/02 15:58:21  fs
 *  event ex- & import
 *
 *  Revision 1.2  2000/12/13 10:40:15  fs
 *  new import related implementations - at this version, we should be able to import everything we export (which is all except events and styles)
 *
 *  Revision 1.1  2000/12/12 12:02:53  fs
 *  initial checkin - implementations for the template classes in elementimport
 *
 *
 *  Revision 1.0 12.12.00 08:33:20  fs
 ************************************************************************/

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

// no include protection. This file is included from elementimport.hxx only.

#ifndef _INCLUDING_FROM_ELEMENTIMPORT_HXX_
#error "do not include this file directly!"
#endif

// no namespace. Same as above: this file is included from elementimport.hxx only,
// and this is done inside the namespace

//=========================================================================
//= OContainerImport
//=========================================================================
//-------------------------------------------------------------------------
template <class BASE>
SvXMLImportContext* OContainerImport< BASE >::CreateChildContext(
    sal_uInt16 _nPrefix, const ::rtl::OUString& _rLocalName,
    const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& _rxAttrList)
{
    // maybe it's a sub control
    if (_rLocalName == m_sWrapperElementName)
        if (m_xMeAsContainer.is())
            return implCreateControlWrapper(_nPrefix, _rLocalName);
        else
        {
            OSL_ENSURE(sal_False, "OContainerImport::CreateChildContext: don't have an element!");
            return NULL;
        }

    return BASE::CreateChildContext(_nPrefix, _rLocalName, _rxAttrList);
}

//-------------------------------------------------------------------------
template <class BASE>
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
    OContainerImport< BASE >::createElement()
{
    // let the base class create the object
    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > xReturn = BASE::createElement();
    if (!xReturn.is())
        return xReturn;

    // ensure that the object is a XNameContainer (we strongly need this for inserting child elements)
    m_xMeAsContainer = ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer >(xReturn, ::com::sun::star::uno::UNO_QUERY);
    if (!m_xMeAsContainer.is())
    {
        OSL_ENSURE(sal_False, "OContainerImport::createElement: invalid element (no XNameContainer) created!");
        xReturn.clear();
    }

    return xReturn;
}

//-------------------------------------------------------------------------
template <class BASE>
void OContainerImport< BASE >::EndElement()
{
    BASE::EndElement();

    // now that we have all children, attach the events
    ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > xIndexContainer(m_xMeAsContainer, ::com::sun::star::uno::UNO_QUERY);
    if (xIndexContainer.is())
        ODefaultEventAttacherManager::setEvents(xIndexContainer);
}

//=========================================================================
//= OColumnImport
//=========================================================================
//-------------------------------------------------------------------------
template <class BASE>
OColumnImport< BASE >::OColumnImport(IFormsImportContext& _rImport, IEventAttacherManager& _rEventManager, sal_uInt16 _nPrefix, const ::rtl::OUString& _rName,
        const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer >& _rxParentContainer,
        OControlElement::ElementType _eType)
    :BASE(_rImport, _rEventManager, _nPrefix, _rName, _rxParentContainer, _eType)
    ,m_xColumnFactory(_rxParentContainer, ::com::sun::star::uno::UNO_QUERY)
{
    OSL_ENSURE(m_xColumnFactory.is(), "OColumnImport::OColumnImport: invalid parent container (no factory)!");
}

//-------------------------------------------------------------------------
// OElementImport overridables
template <class BASE>
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > OColumnImport< BASE >::createElement()
{
    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > xReturn;
    // no call to the base class' method. We have to use the grid column factory
    if (m_xColumnFactory.is())
    {
        // create the column
        xReturn = m_xColumnFactory->createColumn(this->m_sServiceName);
        OSL_ENSURE(xReturn.is(), "OColumnImport::createElement: the factory returned an invalid object!");
    }
    return xReturn;
}

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.5.2.1  2004/10/15 13:54:39  fs
 *  #i30706# removed obsolete parameter from OColumnWrapper
 *
 *  Revision 1.5  2004/07/30 15:04:34  kz
 *  INTEGRATION: CWS gcc340fixes01 (1.4.334); FILE MERGED
 *  2004/07/13 20:28:08 fa 1.4.334.1: #i31445# explicitly scope data member to satisfy gcc 3.4
 *
 *  Revision 1.4.334.1  2004/07/13 20:28:08  fa
 *  #i31445# explicitly scope data member to satisfy gcc 3.4
 *
 *  Revision 1.4  2001/01/03 16:25:34  fs
 *  file format change (extra wrapper element for controls, similar to columns)
 *
 *  Revision 1.3  2001/01/02 15:58:21  fs
 *  event ex- & import
 *
 *  Revision 1.2  2000/12/13 10:40:15  fs
 *  new import related implementations - at this version, we should be able to import everything we export (which is all except events and styles)
 *
 *  Revision 1.1  2000/12/12 12:02:53  fs
 *  initial checkin - implementations for the template classes in elementimport
 *
 *
 *  Revision 1.0 12.12.00 08:33:20  fs
 ************************************************************************/

<|endoftext|>