<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pathoptions.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2007-04-11 19:31:05 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#define INCLUDED_SVTOOLS_PATHOPTIONS_HXX

#ifndef INCLUDED_SVLDLLAPI_H
#include "svtools/svldllapi.h"
#endif

#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#ifndef INCLUDED_SVTOOLS_OPTIONS_HXX
#include <svtools/options.hxx>
#endif

#define SVT_SEARCHPATH_DELIMITER      ';'

// class SvtPathOptions --------------------------------------------------

class SvtPathOptions_Impl;
class SVL_DLLPUBLIC SvtPathOptions: public svt::detail::Options
{
private:
    SvtPathOptions_Impl*    pImp;

public:
    enum Pathes
    {
        PATH_ADDIN,
        PATH_AUTOCORRECT,
        PATH_AUTOTEXT,
        PATH_BACKUP,
        PATH_BASIC,
        PATH_BITMAP,
        PATH_CONFIG,
        PATH_DICTIONARY,
        PATH_FAVORITES,
        PATH_FILTER,
        PATH_GALLERY,
        PATH_GRAPHIC,
        PATH_HELP,
        PATH_LINGUISTIC,
        PATH_MODULE,
        PATH_PALETTE,
        PATH_PLUGIN,
        PATH_STORAGE,
        PATH_TEMP,
        PATH_TEMPLATE,
        PATH_USERCONFIG,
        PATH_USERDICTIONARY,
        PATH_WORK,
        PATH_UICONFIG,
        PATH_COUNT // should always be the last element
    };

    SvtPathOptions();
    virtual ~SvtPathOptions();

    // get the pathes, not const because of using a mutex
    const String&   GetAddinPath() const;
    const String&   GetAutoCorrectPath() const;
    const String&   GetAutoTextPath() const;
    const String&   GetBackupPath() const;
    const String&   GetBasicPath() const;
    const String&   GetBitmapPath() const;
    const String&   GetConfigPath() const;
    const String&   GetDictionaryPath() const;
    const String&   GetFavoritesPath() const;
    const String&   GetFilterPath() const;
    const String&   GetGalleryPath() const;
    const String&   GetGraphicPath() const;
    const String&   GetHelpPath() const;
    const String&   GetLinguisticPath() const;
    const String&   GetModulePath() const;
    const String&   GetPalettePath() const;
    const String&   GetPluginPath() const;
    const String&   GetStoragePath() const;
    const String&   GetTempPath() const;
    const String&   GetTemplatePath() const;
    const String&   GetUserConfigPath() const;
    const String&   GetUserDictionaryPath() const;
    const String&   GetWorkPath() const;
    const String&   GetUIConfigPath() const;

    BOOL            IsPathReadonly(Pathes ePath)const;
    const String&   GetPath(Pathes ePath) const;

    // set the pathes
    void            SetAddinPath( const String& rPath );
    void            SetAutoCorrectPath( const String& rPath );
    void            SetAutoTextPath( const String& rPath );
    void            SetBackupPath( const String& rPath );
    void            SetBasicPath( const String& rPath );
    void            SetBitmapPath( const String& rPath );
    void            SetConfigPath( const String& rPath );
    void            SetDictionaryPath( const String& rPath );
    void            SetFavoritesPath( const String& rPath );
    void            SetFilterPath( const String& rPath );
    void            SetGalleryPath( const String& rPath );
    void            SetGraphicPath( const String& rPath );
    void            SetHelpPath( const String& rPath );
    void            SetLinguisticPath( const String& rPath );
    void            SetModulePath( const String& rPath );
    void            SetPalettePath( const String& rPath );
    void            SetPluginPath( const String& rPath );
    void            SetStoragePath( const String& rPath );
    void            SetTempPath( const String& rPath );
    void            SetTemplatePath( const String& rPath );
    void            SetUserConfigPath( const String& rPath );
    void            SetUserDictionaryPath( const String& rPath );
    void            SetWorkPath( const String& rPath );
    void            SetPath( SvtPathOptions::Pathes ePath, const String& rNewPath );

    String          SubstituteVariable( const String& rVar );
    String          UseVariable( const String& rVar );
    sal_Bool        SearchFile( String& rIniFile, Pathes ePath = PATH_USERCONFIG );
    ::com::sun::star::lang::Locale GetLocale() const;
    sal_Bool        IsReadonly() const;
};

#endif // #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX

<commit_msg>INTEGRATION: CWS languageguessing (1.2.6); FILE MERGED 2007/04/24 10:44:06 tl 1.2.6.1: #i73173# moved header file patched<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pathoptions.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2007-06-19 15:59:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#define INCLUDED_SVTOOLS_PATHOPTIONS_HXX

#ifndef INCLUDED_SVLDLLAPI_H
#include "svtools/svldllapi.h"
#endif

#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#ifndef INCLUDED_SVTOOLS_OPTIONS_HXX
#include <svtools/options.hxx>
#endif

#define SVT_SEARCHPATH_DELIMITER      ';'

// class SvtPathOptions --------------------------------------------------

class SvtPathOptions_Impl;
class SVL_DLLPUBLIC SvtPathOptions: public svt::detail::Options
{
private:
    SvtPathOptions_Impl*    pImp;

public:
    enum Pathes
    {
        PATH_ADDIN,
        PATH_AUTOCORRECT,
        PATH_AUTOTEXT,
        PATH_BACKUP,
        PATH_BASIC,
        PATH_BITMAP,
        PATH_CONFIG,
        PATH_DICTIONARY,
        PATH_FAVORITES,
        PATH_FILTER,
        PATH_GALLERY,
        PATH_GRAPHIC,
        PATH_HELP,
        PATH_LINGUISTIC,
        PATH_MODULE,
        PATH_PALETTE,
        PATH_PLUGIN,
        PATH_STORAGE,
        PATH_TEMP,
        PATH_TEMPLATE,
        PATH_USERCONFIG,
        PATH_USERDICTIONARY,
        PATH_WORK,
        PATH_UICONFIG,
        PATH_FINGERPRINT,
        PATH_COUNT // should always be the last element
    };

    SvtPathOptions();
    virtual ~SvtPathOptions();

    // get the pathes, not const because of using a mutex
    const String&   GetAddinPath() const;
    const String&   GetAutoCorrectPath() const;
    const String&   GetAutoTextPath() const;
    const String&   GetBackupPath() const;
    const String&   GetBasicPath() const;
    const String&   GetBitmapPath() const;
    const String&   GetConfigPath() const;
    const String&   GetDictionaryPath() const;
    const String&   GetFavoritesPath() const;
    const String&   GetFilterPath() const;
    const String&   GetGalleryPath() const;
    const String&   GetGraphicPath() const;
    const String&   GetHelpPath() const;
    const String&   GetLinguisticPath() const;
    const String&   GetModulePath() const;
    const String&   GetPalettePath() const;
    const String&   GetPluginPath() const;
    const String&   GetStoragePath() const;
    const String&   GetTempPath() const;
    const String&   GetTemplatePath() const;
    const String&   GetUserConfigPath() const;
    const String&   GetUserDictionaryPath() const;
    const String&   GetWorkPath() const;
    const String&   GetUIConfigPath() const;
    const String&   GetFingerprintPath() const;

    BOOL            IsPathReadonly(Pathes ePath)const;
    const String&   GetPath(Pathes ePath) const;

    // set the pathes
    void            SetAddinPath( const String& rPath );
    void            SetAutoCorrectPath( const String& rPath );
    void            SetAutoTextPath( const String& rPath );
    void            SetBackupPath( const String& rPath );
    void            SetBasicPath( const String& rPath );
    void            SetBitmapPath( const String& rPath );
    void            SetConfigPath( const String& rPath );
    void            SetDictionaryPath( const String& rPath );
    void            SetFavoritesPath( const String& rPath );
    void            SetFilterPath( const String& rPath );
    void            SetGalleryPath( const String& rPath );
    void            SetGraphicPath( const String& rPath );
    void            SetHelpPath( const String& rPath );
    void            SetLinguisticPath( const String& rPath );
    void            SetModulePath( const String& rPath );
    void            SetPalettePath( const String& rPath );
    void            SetPluginPath( const String& rPath );
    void            SetStoragePath( const String& rPath );
    void            SetTempPath( const String& rPath );
    void            SetTemplatePath( const String& rPath );
    void            SetUserConfigPath( const String& rPath );
    void            SetUserDictionaryPath( const String& rPath );
    void            SetWorkPath( const String& rPath );
    void            SetPath( SvtPathOptions::Pathes ePath, const String& rNewPath );

    String          SubstituteVariable( const String& rVar );
    String          UseVariable( const String& rVar );
    sal_Bool        SearchFile( String& rIniFile, Pathes ePath = PATH_USERCONFIG );
    ::com::sun::star::lang::Locale GetLocale() const;
    sal_Bool        IsReadonly() const;
};

#endif // #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX

<|endoftext|>


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

#ifndef _SVT_FILEDLG_HXX
#include <svtools/filedlg.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif

#ifndef _SVTOOLS_LOGINDLG_HXX_
#include "logindlg.hxx"
#endif

#ifndef _SVTOOLS_LOGINDLG_HRC_
#include "logindlg.hrc"
#endif
#ifndef _SVTOOLS_HRC
#include "svtools.hrc"
#endif

#ifndef _SVTOOLS_SVTDATA_HXX
#include "svtdata.hxx"
#endif

#ifdef UNX
#include <limits.h>
#define _MAX_PATH PATH_MAX
#endif

// LoginDialog -------------------------------------------------------

//............................................................................
namespace svt
{
//............................................................................

void LoginDialog::HideControls_Impl( USHORT nFlags )
{
    FASTBOOL bPathHide = FALSE;
    FASTBOOL bErrorHide = FALSE;
    FASTBOOL bAccountHide = FALSE;

    if ( ( nFlags & LF_NO_PATH ) == LF_NO_PATH )
    {
        aPathFT.Hide();
        aPathED.Hide();
        aPathBtn.Hide();
        bPathHide = TRUE;
    }
    else if ( ( nFlags & LF_PATH_READONLY ) == LF_PATH_READONLY )
    {
        aPathED.Hide();
        aPathInfo.Show();
        aPathBtn.Hide();
    }

    if ( ( nFlags & LF_NO_USERNAME ) == LF_NO_USERNAME )
    {
        aNameFT.Hide();
        aNameED.Hide();
    }
    else if ( ( nFlags & LF_USERNAME_READONLY ) == LF_USERNAME_READONLY )
    {
        aNameED.Hide();
        aNameInfo.Show();
    }

    if ( ( nFlags & LF_NO_PASSWORD ) == LF_NO_PASSWORD )
    {
        aPasswordFT.Hide();
        aPasswordED.Hide();
    }

    if ( ( nFlags & LF_NO_SAVEPASSWORD ) == LF_NO_SAVEPASSWORD )
        aSavePasswdBtn.Hide();

    if ( ( nFlags & LF_NO_ERRORTEXT ) == LF_NO_ERRORTEXT )
    {
        aErrorInfo.Hide();
        aErrorGB.Hide();
        bErrorHide = TRUE;
    }

    if ( ( nFlags & LF_NO_ACCOUNT ) == LF_NO_ACCOUNT )
    {
        aAccountFT.Hide();
        aAccountED.Hide();
        bAccountHide = TRUE;
    }

    if ( bErrorHide )
    {
        long nOffset = aLoginGB.GetPosPixel().Y() -
                       aErrorGB.GetPosPixel().Y();
        Point aNewPnt = aRequestInfo.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aRequestInfo.SetPosPixel( aNewPnt );
        aNewPnt = aPathFT.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aPathFT.SetPosPixel( aNewPnt );
        aNewPnt = aPathED.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aPathED.SetPosPixel( aNewPnt );
        aNewPnt = aPathInfo.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aPathInfo.SetPosPixel( aNewPnt );
        aNewPnt = aPathBtn.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aPathBtn.SetPosPixel( aNewPnt );
        aNewPnt = aNameFT.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aNameFT.SetPosPixel( aNewPnt );
        aNewPnt = aNameED.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aNameED.SetPosPixel( aNewPnt );
        aNewPnt = aNameInfo.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aNameInfo.SetPosPixel( aNewPnt );
        aNewPnt = aPasswordFT.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aPasswordFT.SetPosPixel( aNewPnt );
        aNewPnt = aPasswordED.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aPasswordED.SetPosPixel( aNewPnt );
        aNewPnt = aAccountFT.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aAccountFT.SetPosPixel( aNewPnt );
        aNewPnt = aAccountED.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aAccountED.SetPosPixel( aNewPnt );
        aNewPnt = aSavePasswdBtn.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aSavePasswdBtn.SetPosPixel( aNewPnt );
        aNewPnt = aLoginGB.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aLoginGB.SetPosPixel( aNewPnt );
        Size aNewSiz = GetSizePixel();
        aNewSiz.Height() -= nOffset;
        SetSizePixel( aNewSiz );
    }

    if ( bPathHide )
    {
        long nOffset = aNameED.GetPosPixel().Y() -
                       aPathED.GetPosPixel().Y();

        Point aTmpPnt1 = aNameFT.GetPosPixel();
        Point aTmpPnt2 = aPasswordFT.GetPosPixel();
        aNameFT.SetPosPixel( aPathFT.GetPosPixel() );
        aPasswordFT.SetPosPixel( aTmpPnt1 );
        aAccountFT.SetPosPixel( aTmpPnt2 );
        aTmpPnt1 = aNameED.GetPosPixel();
        aTmpPnt2 = aPasswordED.GetPosPixel();
        aNameED.SetPosPixel( aPathED.GetPosPixel() );
        aPasswordED.SetPosPixel( aTmpPnt1 );
        aAccountED.SetPosPixel( aTmpPnt2 );
        aNameInfo.SetPosPixel( aPathInfo.GetPosPixel() );
        aTmpPnt1 = aSavePasswdBtn.GetPosPixel();
        aTmpPnt1.Y() -= nOffset;
        aSavePasswdBtn.SetPosPixel( aTmpPnt1 );
        Size aNewSz = aLoginGB.GetSizePixel();
        aNewSz.Height() -= nOffset;
        aLoginGB.SetSizePixel( aNewSz );
        aNewSz = GetSizePixel();
        aNewSz.Height() -= nOffset;
        SetSizePixel( aNewSz );
    }

    if ( bAccountHide )
    {
        long nOffset = aAccountED.GetPosPixel().Y() - aPasswordED.GetPosPixel().Y();

        Point aTmpPnt = aSavePasswdBtn.GetPosPixel();
        aTmpPnt.Y() -= nOffset;
        aSavePasswdBtn.SetPosPixel( aTmpPnt );
        Size aNewSz = aLoginGB.GetSizePixel();
        aNewSz.Height() -= nOffset;
        aLoginGB.SetSizePixel( aNewSz );
        aNewSz = GetSizePixel();
        aNewSz.Height() -= nOffset;
        SetSizePixel( aNewSz );
    }
};

// -----------------------------------------------------------------------

IMPL_LINK( LoginDialog, OKHdl_Impl, OKButton *, EMPTYARG )
{
    // trim the strings
    aNameED.SetText( aNameED.GetText().EraseLeadingChars().
        EraseTrailingChars() );
    aPasswordED.SetText( aPasswordED.GetText().EraseLeadingChars().
        EraseTrailingChars() );
    EndDialog( RET_OK );
    return 1;
}

// -----------------------------------------------------------------------

IMPL_LINK( LoginDialog, PathHdl_Impl, PushButton *, EMPTYARG )
{
    PathDialog* pDlg = new PathDialog( this, WB_SVLOOK );
//  DirEntry aEntry;
//  aEntry.ToAbs();
//  pDlg->SetPath( aEntry.GetFull() );

    if ( pDlg->Execute() == RET_OK )
        aPathED.SetText( pDlg->GetPath() );

    delete pDlg;
    return 1;
}

// -----------------------------------------------------------------------

LoginDialog::LoginDialog
(
    Window* pParent,
    USHORT nFlags,
    const String& rServer,
    const String* pRealm
) :

    ModalDialog( pParent, SvtResId( DLG_LOGIN ) ),

    aErrorInfo      ( this, ResId( INFO_LOGIN_ERROR ) ),
    aErrorGB        ( this, ResId( GB_LOGIN_ERROR ) ),
    aRequestInfo    ( this, ResId( INFO_LOGIN_REQUEST ) ),
    aPathFT         ( this, ResId( FT_LOGIN_PATH ) ),
    aPathED         ( this, ResId( ED_LOGIN_PATH ) ),
    aPathInfo       ( this, ResId( INFO_LOGIN_PATH ) ),
    aPathBtn        ( this, ResId( BTN_LOGIN_PATH ) ),
    aNameFT         ( this, ResId( FT_LOGIN_USERNAME ) ),
    aNameED         ( this, ResId( ED_LOGIN_USERNAME ) ),
    aNameInfo       ( this, ResId( INFO_LOGIN_USERNAME ) ),
    aPasswordFT     ( this, ResId( FT_LOGIN_PASSWORD ) ),
    aPasswordED     ( this, ResId( ED_LOGIN_PASSWORD ) ),
    aAccountFT      ( this, ResId( FT_LOGIN_ACCOUNT ) ),
    aAccountED      ( this, ResId( ED_LOGIN_ACCOUNT ) ),
    aSavePasswdBtn  ( this, ResId( CB_LOGIN_SAVEPASSWORD ) ),
    aLoginGB        ( this, ResId( GB_LOGIN_LOGIN ) ),
    aOKBtn          ( this, ResId( BTN_LOGIN_OK ) ),
    aCancelBtn      ( this, ResId( BTN_LOGIN_CANCEL ) ),
    aHelpBtn        ( this, ResId( BTN_LOGIN_HELP ) )

{
    // Einlog-Ort eintragen
    String aServer;

    if ( ( ( nFlags & LF_NO_ACCOUNT ) == LF_NO_ACCOUNT ) && pRealm && pRealm->Len() )
    {
        aServer = *pRealm;
        ( ( aServer += ' ' ) += String( ResId( STR_LOGIN_AT ) ) ) += ' ';
    }
    aServer += rServer;
    String aTxt = aRequestInfo.GetText();
    aTxt.SearchAndReplaceAscii( "%1", aServer );
    aRequestInfo.SetText( aTxt );

    FreeResource();

    aPathED.SetMaxTextLen( _MAX_PATH );
    aNameED.SetMaxTextLen( _MAX_PATH );

    aOKBtn.SetClickHdl( LINK( this, LoginDialog, OKHdl_Impl ) );
    aPathBtn.SetClickHdl( LINK( this, LoginDialog, PathHdl_Impl ) );

    HideControls_Impl( nFlags );
};

// -----------------------------------------------------------------------

void LoginDialog::SetName( const String& rNewName )
{
    aNameED.SetText( rNewName );
    aNameInfo.SetText( rNewName );
}

// -----------------------------------------------------------------------

void LoginDialog::ClearPassword()
{
    aPasswordED.SetText( String() );

    if ( 0 == aNameED.GetText().Len() )
        aNameED.GrabFocus();
    else
        aPasswordED.GrabFocus();
};

// -----------------------------------------------------------------------

void LoginDialog::ClearAccount()
{
    aAccountED.SetText( String() );
    aAccountED.GrabFocus();
};

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

#ifndef _SVT_FILEDLG_HXX
#include <filedlg.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif

#ifndef _SVTOOLS_LOGINDLG_HXX_
#include "logindlg.hxx"
#endif

#ifndef _SVTOOLS_LOGINDLG_HRC_
#include "logindlg.hrc"
#endif
#ifndef _SVTOOLS_HRC
#include "svtools.hrc"
#endif

#ifndef _SVTOOLS_SVTDATA_HXX
#include "svtdata.hxx"
#endif

#ifdef UNX
#include <limits.h>
#define _MAX_PATH PATH_MAX
#endif

// LoginDialog -------------------------------------------------------

//............................................................................
namespace svt
{
//............................................................................

void LoginDialog::HideControls_Impl( USHORT nFlags )
{
    FASTBOOL bPathHide = FALSE;
    FASTBOOL bErrorHide = FALSE;
    FASTBOOL bAccountHide = FALSE;

    if ( ( nFlags & LF_NO_PATH ) == LF_NO_PATH )
    {
        aPathFT.Hide();
        aPathED.Hide();
        aPathBtn.Hide();
        bPathHide = TRUE;
    }
    else if ( ( nFlags & LF_PATH_READONLY ) == LF_PATH_READONLY )
    {
        aPathED.Hide();
        aPathInfo.Show();
        aPathBtn.Hide();
    }

    if ( ( nFlags & LF_NO_USERNAME ) == LF_NO_USERNAME )
    {
        aNameFT.Hide();
        aNameED.Hide();
    }
    else if ( ( nFlags & LF_USERNAME_READONLY ) == LF_USERNAME_READONLY )
    {
        aNameED.Hide();
        aNameInfo.Show();
    }

    if ( ( nFlags & LF_NO_PASSWORD ) == LF_NO_PASSWORD )
    {
        aPasswordFT.Hide();
        aPasswordED.Hide();
    }

    if ( ( nFlags & LF_NO_SAVEPASSWORD ) == LF_NO_SAVEPASSWORD )
        aSavePasswdBtn.Hide();

    if ( ( nFlags & LF_NO_ERRORTEXT ) == LF_NO_ERRORTEXT )
    {
        aErrorInfo.Hide();
        aErrorGB.Hide();
        bErrorHide = TRUE;
    }

    if ( ( nFlags & LF_NO_ACCOUNT ) == LF_NO_ACCOUNT )
    {
        aAccountFT.Hide();
        aAccountED.Hide();
        bAccountHide = TRUE;
    }

    if ( bErrorHide )
    {
        long nOffset = aLoginGB.GetPosPixel().Y() -
                       aErrorGB.GetPosPixel().Y();
        Point aNewPnt = aRequestInfo.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aRequestInfo.SetPosPixel( aNewPnt );
        aNewPnt = aPathFT.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aPathFT.SetPosPixel( aNewPnt );
        aNewPnt = aPathED.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aPathED.SetPosPixel( aNewPnt );
        aNewPnt = aPathInfo.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aPathInfo.SetPosPixel( aNewPnt );
        aNewPnt = aPathBtn.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aPathBtn.SetPosPixel( aNewPnt );
        aNewPnt = aNameFT.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aNameFT.SetPosPixel( aNewPnt );
        aNewPnt = aNameED.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aNameED.SetPosPixel( aNewPnt );
        aNewPnt = aNameInfo.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aNameInfo.SetPosPixel( aNewPnt );
        aNewPnt = aPasswordFT.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aPasswordFT.SetPosPixel( aNewPnt );
        aNewPnt = aPasswordED.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aPasswordED.SetPosPixel( aNewPnt );
        aNewPnt = aAccountFT.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aAccountFT.SetPosPixel( aNewPnt );
        aNewPnt = aAccountED.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aAccountED.SetPosPixel( aNewPnt );
        aNewPnt = aSavePasswdBtn.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aSavePasswdBtn.SetPosPixel( aNewPnt );
        aNewPnt = aLoginGB.GetPosPixel();
        aNewPnt.Y() -= nOffset;
        aLoginGB.SetPosPixel( aNewPnt );
        Size aNewSiz = GetSizePixel();
        aNewSiz.Height() -= nOffset;
        SetSizePixel( aNewSiz );
    }

    if ( bPathHide )
    {
        long nOffset = aNameED.GetPosPixel().Y() -
                       aPathED.GetPosPixel().Y();

        Point aTmpPnt1 = aNameFT.GetPosPixel();
        Point aTmpPnt2 = aPasswordFT.GetPosPixel();
        aNameFT.SetPosPixel( aPathFT.GetPosPixel() );
        aPasswordFT.SetPosPixel( aTmpPnt1 );
        aAccountFT.SetPosPixel( aTmpPnt2 );
        aTmpPnt1 = aNameED.GetPosPixel();
        aTmpPnt2 = aPasswordED.GetPosPixel();
        aNameED.SetPosPixel( aPathED.GetPosPixel() );
        aPasswordED.SetPosPixel( aTmpPnt1 );
        aAccountED.SetPosPixel( aTmpPnt2 );
        aNameInfo.SetPosPixel( aPathInfo.GetPosPixel() );
        aTmpPnt1 = aSavePasswdBtn.GetPosPixel();
        aTmpPnt1.Y() -= nOffset;
        aSavePasswdBtn.SetPosPixel( aTmpPnt1 );
        Size aNewSz = aLoginGB.GetSizePixel();
        aNewSz.Height() -= nOffset;
        aLoginGB.SetSizePixel( aNewSz );
        aNewSz = GetSizePixel();
        aNewSz.Height() -= nOffset;
        SetSizePixel( aNewSz );
    }

    if ( bAccountHide )
    {
        long nOffset = aAccountED.GetPosPixel().Y() - aPasswordED.GetPosPixel().Y();

        Point aTmpPnt = aSavePasswdBtn.GetPosPixel();
        aTmpPnt.Y() -= nOffset;
        aSavePasswdBtn.SetPosPixel( aTmpPnt );
        Size aNewSz = aLoginGB.GetSizePixel();
        aNewSz.Height() -= nOffset;
        aLoginGB.SetSizePixel( aNewSz );
        aNewSz = GetSizePixel();
        aNewSz.Height() -= nOffset;
        SetSizePixel( aNewSz );
    }
};

// -----------------------------------------------------------------------

IMPL_LINK( LoginDialog, OKHdl_Impl, OKButton *, EMPTYARG )
{
    // trim the strings
    aNameED.SetText( aNameED.GetText().EraseLeadingChars().
        EraseTrailingChars() );
    aPasswordED.SetText( aPasswordED.GetText().EraseLeadingChars().
        EraseTrailingChars() );
    EndDialog( RET_OK );
    return 1;
}

// -----------------------------------------------------------------------

IMPL_LINK( LoginDialog, PathHdl_Impl, PushButton *, EMPTYARG )
{
    PathDialog* pDlg = new PathDialog( this, WB_SVLOOK );
//  DirEntry aEntry;
//  aEntry.ToAbs();
//  pDlg->SetPath( aEntry.GetFull() );

    if ( pDlg->Execute() == RET_OK )
        aPathED.SetText( pDlg->GetPath() );

    delete pDlg;
    return 1;
}

// -----------------------------------------------------------------------

LoginDialog::LoginDialog
(
    Window* pParent,
    USHORT nFlags,
    const String& rServer,
    const String* pRealm
) :

    ModalDialog( pParent, SvtResId( DLG_LOGIN ) ),

    aErrorInfo      ( this, ResId( INFO_LOGIN_ERROR ) ),
    aErrorGB        ( this, ResId( GB_LOGIN_ERROR ) ),
    aRequestInfo    ( this, ResId( INFO_LOGIN_REQUEST ) ),
    aPathFT         ( this, ResId( FT_LOGIN_PATH ) ),
    aPathED         ( this, ResId( ED_LOGIN_PATH ) ),
    aPathInfo       ( this, ResId( INFO_LOGIN_PATH ) ),
    aPathBtn        ( this, ResId( BTN_LOGIN_PATH ) ),
    aNameFT         ( this, ResId( FT_LOGIN_USERNAME ) ),
    aNameED         ( this, ResId( ED_LOGIN_USERNAME ) ),
    aNameInfo       ( this, ResId( INFO_LOGIN_USERNAME ) ),
    aPasswordFT     ( this, ResId( FT_LOGIN_PASSWORD ) ),
    aPasswordED     ( this, ResId( ED_LOGIN_PASSWORD ) ),
    aAccountFT      ( this, ResId( FT_LOGIN_ACCOUNT ) ),
    aAccountED      ( this, ResId( ED_LOGIN_ACCOUNT ) ),
    aSavePasswdBtn  ( this, ResId( CB_LOGIN_SAVEPASSWORD ) ),
    aLoginGB        ( this, ResId( GB_LOGIN_LOGIN ) ),
    aOKBtn          ( this, ResId( BTN_LOGIN_OK ) ),
    aCancelBtn      ( this, ResId( BTN_LOGIN_CANCEL ) ),
    aHelpBtn        ( this, ResId( BTN_LOGIN_HELP ) )

{
    // Einlog-Ort eintragen
    String aServer;

    if ( ( ( nFlags & LF_NO_ACCOUNT ) == LF_NO_ACCOUNT ) && pRealm && pRealm->Len() )
    {
        aServer = *pRealm;
        ( ( aServer += ' ' ) += String( ResId( STR_LOGIN_AT ) ) ) += ' ';
    }
    aServer += rServer;
    String aTxt = aRequestInfo.GetText();
    aTxt.SearchAndReplaceAscii( "%1", aServer );
    aRequestInfo.SetText( aTxt );

    FreeResource();

    aPathED.SetMaxTextLen( _MAX_PATH );
    aNameED.SetMaxTextLen( _MAX_PATH );

    aOKBtn.SetClickHdl( LINK( this, LoginDialog, OKHdl_Impl ) );
    aPathBtn.SetClickHdl( LINK( this, LoginDialog, PathHdl_Impl ) );

    HideControls_Impl( nFlags );
};

// -----------------------------------------------------------------------

void LoginDialog::SetName( const String& rNewName )
{
    aNameED.SetText( rNewName );
    aNameInfo.SetText( rNewName );
}

// -----------------------------------------------------------------------

void LoginDialog::ClearPassword()
{
    aPasswordED.SetText( String() );

    if ( 0 == aNameED.GetText().Len() )
        aNameED.GrabFocus();
    else
        aPasswordED.GrabFocus();
};

// -----------------------------------------------------------------------

void LoginDialog::ClearAccount()
{
    aAccountED.SetText( String() );
    aAccountED.GrabFocus();
};

//............................................................................
}   // namespace svt
//............................................................................
<|endoftext|>


<commit_before><commit_msg>remove copypasta<commit_after><|endoftext|>


<commit_before>#include <log2plot/config_manager.h>
#include <math.h>

namespace log2plot
{

void ConfigManager::updateFrom(int argc, char **argv, bool warn)
{
  for(int i = 0; i < (argc-1)/2; i+=2)
  {
    const auto tags = toTags(argv[2*i+1]);
    if(has(tags))
      finalNode(tags, config) = std::string(argv[2*i+2]);
    else if(warn)
      std::cout << "log2plot: Passed argument '" << argv[2*i+1] << "' is not a configuration tag" << std::endl;
  }
}

std::vector<std::string> ConfigManager::toTags(std::string tag) const
{
  std::vector<std::string> tags;
  std::string out;
  std::istringstream iss(tag);
  while(std::getline(iss, out, ':'))
    tags.push_back(out);

  return tags;
}

void ConfigManager::addConditionalNameElement(std::string strTrue, bool condition, std::string strFalse)
{
  if(condition)
    addNameElement(strTrue);
  else
    addNameElement(strFalse);
}

void ConfigManager::addNameElement(std::string str)
{
  if(str.size())
  {
    if(base_name.size())
      base_name += "_";
    base_name += str;
  }
}

// print tag error
std::string ConfigManager::tagPathMessage(TagList tags, std::string msg) const
{
  std::string ret(msg + "\n  - file: " + config_file + "\n  -  tag: ");

  for(size_t idx = 0; idx < tags.size()-1; ++idx)
    ret += tags[idx] + ":";
  return ret + tags.back();
}

YAML::Node ConfigManager::finalNode(TagList tags, const YAML::Node &node, size_t idx) const
{
  const auto& tag = tags[idx];
  const auto &child = node[tag];
  if(!child)
    throw std::runtime_error(tagPathMessage(tags, "tag does not exist"));

  if(idx == tags.size()-1)
    return child;

  return finalNode(tags, child, idx+1);

}

double ConfigManager::str2double(std::string s)
{
  if(s.size() > 1)
  {
    // look for fractions of pi
    for(const auto denum: {2, 3, 4, 6, 1})
    {
      for(const auto sign: {1, -1})
      {
        for(const auto pi: {"PI", "pi"})
        {
          // build string to be searched
          std::stringstream ss;
          if(sign == -1)
            ss << "-";
          ss << pi;
          if(denum != 1)
            ss << "/" << denum;
          if(s == ss.str())
            return sign * M_PI/denum;
        }
      }
    }
  }
  return atof(s.c_str());
}

}

<commit_msg>offset bug in cmd line parser<commit_after>#include <log2plot/config_manager.h>
#include <math.h>

namespace log2plot
{

void ConfigManager::updateFrom(int argc, char **argv, bool warn)
{
  for(int i = 0; i < (argc-1)/2; i++)
  {
    const auto tags = toTags(argv[2*i+1]);
    if(has(tags))
      finalNode(tags, config) = std::string(argv[2*i+2]);
    else if(warn)
      std::cout << "log2plot: Passed argument '" << argv[2*i+1] << "' is not a configuration tag" << std::endl;
  }
}

std::vector<std::string> ConfigManager::toTags(std::string tag) const
{
  std::vector<std::string> tags;
  std::string out;
  std::istringstream iss(tag);
  while(std::getline(iss, out, ':'))
    tags.push_back(out);

  return tags;
}

void ConfigManager::addConditionalNameElement(std::string strTrue, bool condition, std::string strFalse)
{
  if(condition)
    addNameElement(strTrue);
  else
    addNameElement(strFalse);
}

void ConfigManager::addNameElement(std::string str)
{
  if(str.size())
  {
    if(base_name.size())
      base_name += "_";
    base_name += str;
  }
}

// print tag error
std::string ConfigManager::tagPathMessage(TagList tags, std::string msg) const
{
  std::string ret(msg + "\n  - file: " + config_file + "\n  -  tag: ");

  for(size_t idx = 0; idx < tags.size()-1; ++idx)
    ret += tags[idx] + ":";
  return ret + tags.back();
}

YAML::Node ConfigManager::finalNode(TagList tags, const YAML::Node &node, size_t idx) const
{
  const auto& tag = tags[idx];
  const auto &child = node[tag];
  if(!child)
    throw std::runtime_error(tagPathMessage(tags, "tag does not exist"));

  if(idx == tags.size()-1)
    return child;

  return finalNode(tags, child, idx+1);

}

double ConfigManager::str2double(std::string s)
{
  if(s.size() > 1)
  {
    // look for fractions of pi
    for(const auto denum: {2, 3, 4, 6, 1})
    {
      for(const auto sign: {1, -1})
      {
        for(const auto pi: {"PI", "pi"})
        {
          // build string to be searched
          std::stringstream ss;
          if(sign == -1)
            ss << "-";
          ss << pi;
          if(denum != 1)
            ss << "/" << denum;
          if(s == ss.str())
            return sign * M_PI/denum;
        }
      }
    }
  }
  return atof(s.c_str());
}

}

<|endoftext|>


<commit_before>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*
 * Copyright 2019 ScyllaDB
 */

#include <boost/intrusive/parent_from_member.hpp>
#include <seastar/core/fair_queue.hh>
#include <seastar/core/future.hh>
#include <seastar/core/shared_ptr.hh>
#include <seastar/core/circular_buffer.hh>
#include <seastar/util/noncopyable_function.hh>
#include <seastar/core/reactor.hh>
#include <queue>
#include <chrono>
#include <unordered_set>
#include <cmath>

#include "fmt/format.h"
#include "fmt/ostream.h"

namespace seastar {

static_assert(sizeof(fair_queue_ticket) == sizeof(uint64_t), "unexpected fair_queue_ticket size");
static_assert(sizeof(fair_queue_entry) <= 3 * sizeof(void*), "unexpected fair_queue_entry::_hook size");
static_assert(sizeof(fair_queue_entry::container_list_t) == 2 * sizeof(void*), "unexpected priority_class::_queue size");

fair_queue_ticket::fair_queue_ticket(uint32_t weight, uint32_t size) noexcept
    : _weight(weight)
    , _size(size)
{}

float fair_queue_ticket::normalize(fair_queue_ticket denominator) const noexcept {
    return float(_weight) / denominator._weight + float(_size) / denominator._size;
}

fair_queue_ticket fair_queue_ticket::operator+(fair_queue_ticket desc) const noexcept {
    return fair_queue_ticket(_weight + desc._weight, _size + desc._size);
}

fair_queue_ticket& fair_queue_ticket::operator+=(fair_queue_ticket desc) noexcept {
    _weight += desc._weight;
    _size += desc._size;
    return *this;
}

fair_queue_ticket fair_queue_ticket::operator-(fair_queue_ticket desc) const noexcept {
    return fair_queue_ticket(_weight - desc._weight, _size - desc._size);
}

fair_queue_ticket& fair_queue_ticket::operator-=(fair_queue_ticket desc) noexcept {
    _weight -= desc._weight;
    _size -= desc._size;
    return *this;
}

fair_queue_ticket::operator bool() const noexcept {
    return (_weight > 0) || (_size > 0);
}

bool fair_queue_ticket::operator==(const fair_queue_ticket& o) const noexcept {
    return _weight == o._weight && _size == o._size;
}

std::ostream& operator<<(std::ostream& os, fair_queue_ticket t) {
    return os << t._weight << ":" << t._size;
}

fair_group_rover::fair_group_rover(uint32_t weight, uint32_t size) noexcept
        : _weight(weight)
        , _size(size)
{}

fair_queue_ticket fair_group_rover::maybe_ahead_of(const fair_group_rover& other) const noexcept {
    return fair_queue_ticket(std::max<int32_t>(_weight - other._weight, 0),
            std::max<int32_t>(_size - other._size, 0));
}

fair_group_rover fair_group_rover::operator+(fair_queue_ticket t) const noexcept {
    return fair_group_rover(_weight + t._weight, _size + t._size);
}

fair_group_rover& fair_group_rover::operator+=(fair_queue_ticket t) noexcept {
    _weight += t._weight;
    _size += t._size;
    return *this;
}

std::ostream& operator<<(std::ostream& os, fair_group_rover r) {
    return os << r._weight << ":" << r._size;
}

fair_group::fair_group(config cfg) noexcept
        : _capacity_tail(fair_group_rover(0, 0))
        , _capacity_head(fair_group_rover(cfg.max_req_count, cfg.max_bytes_count))
        , _maximum_capacity(cfg.max_req_count, cfg.max_bytes_count)
{
    assert(!_capacity_tail.load(std::memory_order_relaxed)
                .maybe_ahead_of(_capacity_head.load(std::memory_order_relaxed)));
    seastar_logger.debug("Created fair group, capacity {}:{}", cfg.max_req_count, cfg.max_bytes_count);
}

fair_group_rover fair_group::grab_capacity(fair_queue_ticket cap) noexcept {
    fair_group_rover cur = _capacity_tail.load(std::memory_order_relaxed);
    while (!_capacity_tail.compare_exchange_weak(cur, cur + cap)) ;
    return cur;
}

void fair_group::release_capacity(fair_queue_ticket cap) noexcept {
    fair_group_rover cur = _capacity_head.load(std::memory_order_relaxed);
    while (!_capacity_head.compare_exchange_weak(cur, cur + cap)) ;
}

fair_queue::fair_queue(fair_group& group, config cfg)
    : _config(std::move(cfg))
    , _group(group)
    , _base(std::chrono::steady_clock::now())
{
    seastar_logger.debug("Created fair queue, ticket pace {}:{}", cfg.ticket_weight_pace, cfg.ticket_size_pace);
}

void fair_queue::push_priority_class(priority_class_ptr pc) {
    if (!pc->_queued) {
        _handles.push(pc);
        pc->_queued = true;
    }
}

priority_class_ptr fair_queue::peek_priority_class() {
    assert(!_handles.empty());
    return _handles.top();
}

void fair_queue::pop_priority_class(priority_class_ptr pc) {
    assert(pc->_queued);
    pc->_queued = false;
    _handles.pop();
}

priority_class::accumulator_t fair_queue::normalize_factor() const {
    return std::numeric_limits<priority_class::accumulator_t>::min();
}

void fair_queue::normalize_stats() {
    auto time_delta = std::log(normalize_factor()) * _config.tau;
    // time_delta is negative; and this may advance _base into the future
    _base -= std::chrono::duration_cast<clock_type::duration>(time_delta);
    for (auto& pc: _all_classes) {
        pc->_accumulated *= normalize_factor();
    }
}

std::chrono::microseconds fair_queue_ticket::duration_at_pace(float weight_pace, float size_pace) const noexcept {
    unsigned long dur = ((_weight * weight_pace) + (_size * size_pace));
    return std::chrono::microseconds(dur);
}

bool fair_queue::grab_pending_capacity(fair_queue_ticket cap) noexcept {
    fair_group_rover pending_head = _pending->orig_tail + cap;
    if (pending_head.maybe_ahead_of(_group.head())) {
        return false;
    }

    if (cap == _pending->cap) {
        _pending.reset();
    } else {
        /*
         * This branch is called when the fair queue decides to
         * submit not the same request that entered it into the
         * pending state and this new request crawls through the
         * expected head value.
         */
        _group.grab_capacity(cap);
        _pending->orig_tail += cap;
    }

    return true;
}

bool fair_queue::grab_capacity(fair_queue_ticket cap) noexcept {
    if (_pending) {
        return grab_pending_capacity(cap);
    }

    fair_group_rover orig_tail = _group.grab_capacity(cap);
    if ((orig_tail + cap).maybe_ahead_of(_group.head())) {
        _pending.emplace(orig_tail, cap);
        return false;
    }

    return true;
}

priority_class_ptr fair_queue::register_priority_class(uint32_t shares) {
    priority_class_ptr pclass = make_lw_shared<priority_class>(shares);
    _all_classes.insert(pclass);
    return pclass;
}

void fair_queue::unregister_priority_class(priority_class_ptr pclass) {
    assert(pclass->_queue.empty());
    _all_classes.erase(pclass);
}

size_t fair_queue::waiters() const {
    return _requests_queued;
}

size_t fair_queue::requests_currently_executing() const {
    return _requests_executing;
}

fair_queue_ticket fair_queue::resources_currently_waiting() const {
    return _resources_queued;
}

fair_queue_ticket fair_queue::resources_currently_executing() const {
    return _resources_executing;
}

void fair_queue::queue(priority_class_ptr pc, fair_queue_entry& ent) {
    // We need to return a future in this function on which the caller can wait.
    // Since we don't know which queue we will use to execute the next request - if ours or
    // someone else's, we need a separate promise at this point.
    push_priority_class(pc);
    pc->_queue.push_back(ent);
    _resources_queued += ent._ticket;
    _requests_queued++;
}

void fair_queue::notify_requests_finished(fair_queue_ticket desc, unsigned nr) noexcept {
    _resources_executing -= desc;
    _requests_executing -= nr;
    _group.release_capacity(desc);
}

void fair_queue::notify_request_cancelled(fair_queue_entry& ent) noexcept {
    _resources_queued -= ent._ticket;
    ent._ticket = fair_queue_ticket();
}

void fair_queue::dispatch_requests(std::function<void(fair_queue_entry&)> cb) {
    while (_requests_queued) {
        priority_class_ptr h;

        while (true) {
            h = peek_priority_class();
            if (!h->_queue.empty()) {
                break;
            }
            pop_priority_class(h);
        }

        auto& req = h->_queue.front();
        if (!grab_capacity(req._ticket)) {
            break;
        }

        pop_priority_class(h);
        h->_queue.pop_front();

        _resources_executing += req._ticket;
        _resources_queued -= req._ticket;
        _requests_executing++;
        _requests_queued--;

        auto delta = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - _base);
        auto req_cost  = req._ticket.normalize(_group.maximum_capacity()) / h->_shares;
        auto cost  = exp(priority_class::accumulator_t(1.0f/_config.tau.count() * delta.count())) * req_cost;
        priority_class::accumulator_t next_accumulated = h->_accumulated + cost;
        while (std::isinf(next_accumulated)) {
            normalize_stats();
            // If we have renormalized, our time base will have changed. This should happen very infrequently
            delta = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - _base);
            cost  = exp(priority_class::accumulator_t(1.0f/_config.tau.count() * delta.count())) * req_cost;
            next_accumulated = h->_accumulated + cost;
        }
        h->_accumulated = next_accumulated;

        if (!h->_queue.empty()) {
            push_priority_class(h);
        }

        cb(req);
    }
}

}
<commit_msg>fair_queue: Simplify base re-evaluation<commit_after>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*
 * Copyright 2019 ScyllaDB
 */

#include <boost/intrusive/parent_from_member.hpp>
#include <seastar/core/fair_queue.hh>
#include <seastar/core/future.hh>
#include <seastar/core/shared_ptr.hh>
#include <seastar/core/circular_buffer.hh>
#include <seastar/util/noncopyable_function.hh>
#include <seastar/core/reactor.hh>
#include <queue>
#include <chrono>
#include <unordered_set>
#include <cmath>

#include "fmt/format.h"
#include "fmt/ostream.h"

namespace seastar {

static_assert(sizeof(fair_queue_ticket) == sizeof(uint64_t), "unexpected fair_queue_ticket size");
static_assert(sizeof(fair_queue_entry) <= 3 * sizeof(void*), "unexpected fair_queue_entry::_hook size");
static_assert(sizeof(fair_queue_entry::container_list_t) == 2 * sizeof(void*), "unexpected priority_class::_queue size");

fair_queue_ticket::fair_queue_ticket(uint32_t weight, uint32_t size) noexcept
    : _weight(weight)
    , _size(size)
{}

float fair_queue_ticket::normalize(fair_queue_ticket denominator) const noexcept {
    return float(_weight) / denominator._weight + float(_size) / denominator._size;
}

fair_queue_ticket fair_queue_ticket::operator+(fair_queue_ticket desc) const noexcept {
    return fair_queue_ticket(_weight + desc._weight, _size + desc._size);
}

fair_queue_ticket& fair_queue_ticket::operator+=(fair_queue_ticket desc) noexcept {
    _weight += desc._weight;
    _size += desc._size;
    return *this;
}

fair_queue_ticket fair_queue_ticket::operator-(fair_queue_ticket desc) const noexcept {
    return fair_queue_ticket(_weight - desc._weight, _size - desc._size);
}

fair_queue_ticket& fair_queue_ticket::operator-=(fair_queue_ticket desc) noexcept {
    _weight -= desc._weight;
    _size -= desc._size;
    return *this;
}

fair_queue_ticket::operator bool() const noexcept {
    return (_weight > 0) || (_size > 0);
}

bool fair_queue_ticket::operator==(const fair_queue_ticket& o) const noexcept {
    return _weight == o._weight && _size == o._size;
}

std::ostream& operator<<(std::ostream& os, fair_queue_ticket t) {
    return os << t._weight << ":" << t._size;
}

fair_group_rover::fair_group_rover(uint32_t weight, uint32_t size) noexcept
        : _weight(weight)
        , _size(size)
{}

fair_queue_ticket fair_group_rover::maybe_ahead_of(const fair_group_rover& other) const noexcept {
    return fair_queue_ticket(std::max<int32_t>(_weight - other._weight, 0),
            std::max<int32_t>(_size - other._size, 0));
}

fair_group_rover fair_group_rover::operator+(fair_queue_ticket t) const noexcept {
    return fair_group_rover(_weight + t._weight, _size + t._size);
}

fair_group_rover& fair_group_rover::operator+=(fair_queue_ticket t) noexcept {
    _weight += t._weight;
    _size += t._size;
    return *this;
}

std::ostream& operator<<(std::ostream& os, fair_group_rover r) {
    return os << r._weight << ":" << r._size;
}

fair_group::fair_group(config cfg) noexcept
        : _capacity_tail(fair_group_rover(0, 0))
        , _capacity_head(fair_group_rover(cfg.max_req_count, cfg.max_bytes_count))
        , _maximum_capacity(cfg.max_req_count, cfg.max_bytes_count)
{
    assert(!_capacity_tail.load(std::memory_order_relaxed)
                .maybe_ahead_of(_capacity_head.load(std::memory_order_relaxed)));
    seastar_logger.debug("Created fair group, capacity {}:{}", cfg.max_req_count, cfg.max_bytes_count);
}

fair_group_rover fair_group::grab_capacity(fair_queue_ticket cap) noexcept {
    fair_group_rover cur = _capacity_tail.load(std::memory_order_relaxed);
    while (!_capacity_tail.compare_exchange_weak(cur, cur + cap)) ;
    return cur;
}

void fair_group::release_capacity(fair_queue_ticket cap) noexcept {
    fair_group_rover cur = _capacity_head.load(std::memory_order_relaxed);
    while (!_capacity_head.compare_exchange_weak(cur, cur + cap)) ;
}

fair_queue::fair_queue(fair_group& group, config cfg)
    : _config(std::move(cfg))
    , _group(group)
    , _base(std::chrono::steady_clock::now())
{
    seastar_logger.debug("Created fair queue, ticket pace {}:{}", cfg.ticket_weight_pace, cfg.ticket_size_pace);
}

void fair_queue::push_priority_class(priority_class_ptr pc) {
    if (!pc->_queued) {
        _handles.push(pc);
        pc->_queued = true;
    }
}

priority_class_ptr fair_queue::peek_priority_class() {
    assert(!_handles.empty());
    return _handles.top();
}

void fair_queue::pop_priority_class(priority_class_ptr pc) {
    assert(pc->_queued);
    pc->_queued = false;
    _handles.pop();
}

priority_class::accumulator_t fair_queue::normalize_factor() const {
    return std::numeric_limits<priority_class::accumulator_t>::min();
}

void fair_queue::normalize_stats() {
    _base = std::chrono::steady_clock::now() - _config.tau;
    for (auto& pc: _all_classes) {
        pc->_accumulated *= normalize_factor();
    }
}

std::chrono::microseconds fair_queue_ticket::duration_at_pace(float weight_pace, float size_pace) const noexcept {
    unsigned long dur = ((_weight * weight_pace) + (_size * size_pace));
    return std::chrono::microseconds(dur);
}

bool fair_queue::grab_pending_capacity(fair_queue_ticket cap) noexcept {
    fair_group_rover pending_head = _pending->orig_tail + cap;
    if (pending_head.maybe_ahead_of(_group.head())) {
        return false;
    }

    if (cap == _pending->cap) {
        _pending.reset();
    } else {
        /*
         * This branch is called when the fair queue decides to
         * submit not the same request that entered it into the
         * pending state and this new request crawls through the
         * expected head value.
         */
        _group.grab_capacity(cap);
        _pending->orig_tail += cap;
    }

    return true;
}

bool fair_queue::grab_capacity(fair_queue_ticket cap) noexcept {
    if (_pending) {
        return grab_pending_capacity(cap);
    }

    fair_group_rover orig_tail = _group.grab_capacity(cap);
    if ((orig_tail + cap).maybe_ahead_of(_group.head())) {
        _pending.emplace(orig_tail, cap);
        return false;
    }

    return true;
}

priority_class_ptr fair_queue::register_priority_class(uint32_t shares) {
    priority_class_ptr pclass = make_lw_shared<priority_class>(shares);
    _all_classes.insert(pclass);
    return pclass;
}

void fair_queue::unregister_priority_class(priority_class_ptr pclass) {
    assert(pclass->_queue.empty());
    _all_classes.erase(pclass);
}

size_t fair_queue::waiters() const {
    return _requests_queued;
}

size_t fair_queue::requests_currently_executing() const {
    return _requests_executing;
}

fair_queue_ticket fair_queue::resources_currently_waiting() const {
    return _resources_queued;
}

fair_queue_ticket fair_queue::resources_currently_executing() const {
    return _resources_executing;
}

void fair_queue::queue(priority_class_ptr pc, fair_queue_entry& ent) {
    // We need to return a future in this function on which the caller can wait.
    // Since we don't know which queue we will use to execute the next request - if ours or
    // someone else's, we need a separate promise at this point.
    push_priority_class(pc);
    pc->_queue.push_back(ent);
    _resources_queued += ent._ticket;
    _requests_queued++;
}

void fair_queue::notify_requests_finished(fair_queue_ticket desc, unsigned nr) noexcept {
    _resources_executing -= desc;
    _requests_executing -= nr;
    _group.release_capacity(desc);
}

void fair_queue::notify_request_cancelled(fair_queue_entry& ent) noexcept {
    _resources_queued -= ent._ticket;
    ent._ticket = fair_queue_ticket();
}

void fair_queue::dispatch_requests(std::function<void(fair_queue_entry&)> cb) {
    while (_requests_queued) {
        priority_class_ptr h;

        while (true) {
            h = peek_priority_class();
            if (!h->_queue.empty()) {
                break;
            }
            pop_priority_class(h);
        }

        auto& req = h->_queue.front();
        if (!grab_capacity(req._ticket)) {
            break;
        }

        pop_priority_class(h);
        h->_queue.pop_front();

        _resources_executing += req._ticket;
        _resources_queued -= req._ticket;
        _requests_executing++;
        _requests_queued--;

        auto delta = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - _base);
        auto req_cost  = req._ticket.normalize(_group.maximum_capacity()) / h->_shares;
        auto cost  = exp(priority_class::accumulator_t(1.0f/_config.tau.count() * delta.count())) * req_cost;
        priority_class::accumulator_t next_accumulated = h->_accumulated + cost;
        while (std::isinf(next_accumulated)) {
            normalize_stats();
            // If we have renormalized, our time base will have changed. This should happen very infrequently
            delta = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - _base);
            cost  = exp(priority_class::accumulator_t(1.0f/_config.tau.count() * delta.count())) * req_cost;
            next_accumulated = h->_accumulated + cost;
        }
        h->_accumulated = next_accumulated;

        if (!h->_queue.empty()) {
            push_priority_class(h);
        }

        cb(req);
    }
}

}
<|endoftext|>


<commit_before>/*
 * Illarionserver - server for the game Illarion
 * Copyright 2011 Illarion e.V.
 *
 * This file is part of Illarionserver.
 *
 * Illarionserver  is  free  software:  you can redistribute it and/or modify it
 * under the terms of the  GNU Affero General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 *
 * Illarionserver 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 Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along with
 * Illarionserver. If not, see <http://www.gnu.org/licenses/>.
 */

#include "RaceTable.hpp"

auto RaceTable::getTableName() -> std::string { return "race"; }

auto RaceTable::getColumnNames() -> std::vector<std::string> {
    return {"race_id",
            "race_name",
            "race_height_min",
            "race_height_max",
            "race_agility_min",
            "race_agility_max",
            "race_constitution_min",
            "race_constitution_max",
            "race_dexterity_min",
            "race_dexterity_max",
            "race_essence_min",
            "race_essence_max",
            "race_intelligence_min",
            "race_intelligence_max",
            "race_perception_min",
            "race_perception_max",
            "race_strength_min",
            "race_strength_max",
            "race_willpower_min",
            "race_willpower_max",
            "race_attribute_points_max"};
}

auto RaceTable::assignId(const Database::ResultTuple &row) -> TYPE_OF_ITEM_ID {
    return uint16_t(row["race_id"].as<int32_t>());
}

auto RaceTable::assignTable(const Database::ResultTuple &row) -> RaceStruct {
    RaceStruct race;
    race.serverName = row["race_name"].as<std::string>("unknown");
    race.minSize = uint16_t(row["race_height_min"].as<int32_t>(RaceStruct::defaultMinHeight));
    race.maxSize = uint16_t(row["race_height_max"].as<int32_t>(RaceStruct::defaultMaxHeight));
    race.minAgility = uint8_t(row["race_agility_min"].as<int32_t>(RaceStruct::defaultMinAttribute));
    race.maxAgility = uint8_t(row["race_agility_max"].as<int32_t>(RaceStruct::defaultMaxAttribute));
    race.minConstitution = uint8_t(row["race_constitution_min"].as<int32_t>(RaceStruct::defaultMinAttribute));
    race.maxConstitution = uint8_t(row["race_constitution_max"].as<int32_t>(RaceStruct::defaultMaxAttribute));
    race.minDexterity = uint8_t(row["race_dexterity_min"].as<int32_t>(RaceStruct::defaultMinAttribute));
    race.maxDexterity = uint8_t(row["race_dexterity_max"].as<int32_t>(RaceStruct::defaultMaxAttribute));
    race.minEssence = uint8_t(row["race_essence_min"].as<int32_t>(RaceStruct::defaultMinAttribute));
    race.maxEssence = uint8_t(row["race_essence_max"].as<int32_t>(RaceStruct::defaultMaxAttribute));
    race.minIntelligence = uint8_t(row["race_intelligence_min"].as<int32_t>(RaceStruct::defaultMinAttribute));
    race.maxIntelligence = uint8_t(row["race_intelligence_max"].as<int32_t>(RaceStruct::defaultMaxAttribute));
    race.minPerception = uint8_t(row["race_perception_min"].as<int32_t>(RaceStruct::defaultMinAttribute));
    race.maxPerception = uint8_t(row["race_perception_max"].as<int32_t>(RaceStruct::defaultMaxAttribute));
    race.minStrength = uint8_t(row["race_strength_min"].as<int32_t>(RaceStruct::defaultMinAttribute));
    race.maxStrength = uint8_t(row["race_strength_max"].as<int32_t>(RaceStruct::defaultMaxAttribute));
    race.minWillpower = uint8_t(row["race_willpower_min"].as<int32_t>(RaceStruct::defaultMinAttribute));
    race.maxWillpower = uint8_t(row["race_willpower_max"].as<int32_t>(RaceStruct::defaultMaxAttribute));
    race.maxAttribs = uint8_t(row["race_attribute_points_max"].as<int16_t>(RaceStruct::defaultMaxAttributePoints));
    return race;
}

auto RaceTable::getRelativeSize(TYPE_OF_RACE_ID race, uint16_t size) const -> uint8_t {
    // relative size is between 40 and 120 (in percent) and a linear interpolation between min and max size
    constexpr auto defaultRelativeSize = 100;

    if (!exists(race)) {
        return defaultRelativeSize;
    }

    const auto &sizes = this->get(race);

    const auto minSize = sizes.minSize;

    const auto maxSize = sizes.maxSize;

    constexpr auto minRelativeSize = 80;
    constexpr auto maxRelativeSize = 120;

    if (size < minSize) {
        return minRelativeSize;
    }

    if (size > maxSize) {
        return maxRelativeSize;
    }

    return uint8_t(((maxRelativeSize - minRelativeSize) * (size - minSize)) / (maxSize - minSize) + minRelativeSize);
}

auto RaceTable::isBaseAttributeInLimits(TYPE_OF_RACE_ID race, Character::attributeIndex attribute,
                                        Attribute::attribute_t value) const -> bool {
    if (!exists(race)) {
        return false;
    }

    const auto &attributes = this->get(race);

    switch (attribute) {
    case Character::agility:
        return value >= attributes.minAgility && value <= attributes.maxAgility;

    case Character::constitution:
        return value >= attributes.minConstitution && value <= attributes.maxConstitution;

    case Character::dexterity:
        return value >= attributes.minDexterity && value <= attributes.maxDexterity;

    case Character::essence:
        return value >= attributes.minEssence && value <= attributes.maxEssence;

    case Character::intelligence:
        return value >= attributes.minIntelligence && value <= attributes.maxIntelligence;

    case Character::perception:
        return value >= attributes.minPerception && value <= attributes.maxPerception;

    case Character::strength:
        return value >= attributes.minStrength && value <= attributes.maxStrength;

    case Character::willpower:
        return value >= attributes.minWillpower && value <= attributes.maxWillpower;

    default:
        return false;
    }
}

auto RaceTable::getMaxAttributePoints(TYPE_OF_RACE_ID race) const -> uint8_t {
    if (!exists(race)) {
        return 0;
    }

    const auto &attributes = this->get(race);
    return attributes.maxAttribs;
}
<commit_msg>Use default character height, if a character's height is not set<commit_after>/*
 * Illarionserver - server for the game Illarion
 * Copyright 2011 Illarion e.V.
 *
 * This file is part of Illarionserver.
 *
 * Illarionserver  is  free  software:  you can redistribute it and/or modify it
 * under the terms of the  GNU Affero General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 *
 * Illarionserver 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 Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along with
 * Illarionserver. If not, see <http://www.gnu.org/licenses/>.
 */

#include "RaceTable.hpp"

auto RaceTable::getTableName() -> std::string { return "race"; }

auto RaceTable::getColumnNames() -> std::vector<std::string> {
    return {"race_id",
            "race_name",
            "race_height_min",
            "race_height_max",
            "race_agility_min",
            "race_agility_max",
            "race_constitution_min",
            "race_constitution_max",
            "race_dexterity_min",
            "race_dexterity_max",
            "race_essence_min",
            "race_essence_max",
            "race_intelligence_min",
            "race_intelligence_max",
            "race_perception_min",
            "race_perception_max",
            "race_strength_min",
            "race_strength_max",
            "race_willpower_min",
            "race_willpower_max",
            "race_attribute_points_max"};
}

auto RaceTable::assignId(const Database::ResultTuple &row) -> TYPE_OF_ITEM_ID {
    return uint16_t(row["race_id"].as<int32_t>());
}

auto RaceTable::assignTable(const Database::ResultTuple &row) -> RaceStruct {
    RaceStruct race;
    race.serverName = row["race_name"].as<std::string>("unknown");
    race.minSize = uint16_t(row["race_height_min"].as<int32_t>(RaceStruct::defaultMinHeight));
    race.maxSize = uint16_t(row["race_height_max"].as<int32_t>(RaceStruct::defaultMaxHeight));
    race.minAgility = uint8_t(row["race_agility_min"].as<int32_t>(RaceStruct::defaultMinAttribute));
    race.maxAgility = uint8_t(row["race_agility_max"].as<int32_t>(RaceStruct::defaultMaxAttribute));
    race.minConstitution = uint8_t(row["race_constitution_min"].as<int32_t>(RaceStruct::defaultMinAttribute));
    race.maxConstitution = uint8_t(row["race_constitution_max"].as<int32_t>(RaceStruct::defaultMaxAttribute));
    race.minDexterity = uint8_t(row["race_dexterity_min"].as<int32_t>(RaceStruct::defaultMinAttribute));
    race.maxDexterity = uint8_t(row["race_dexterity_max"].as<int32_t>(RaceStruct::defaultMaxAttribute));
    race.minEssence = uint8_t(row["race_essence_min"].as<int32_t>(RaceStruct::defaultMinAttribute));
    race.maxEssence = uint8_t(row["race_essence_max"].as<int32_t>(RaceStruct::defaultMaxAttribute));
    race.minIntelligence = uint8_t(row["race_intelligence_min"].as<int32_t>(RaceStruct::defaultMinAttribute));
    race.maxIntelligence = uint8_t(row["race_intelligence_max"].as<int32_t>(RaceStruct::defaultMaxAttribute));
    race.minPerception = uint8_t(row["race_perception_min"].as<int32_t>(RaceStruct::defaultMinAttribute));
    race.maxPerception = uint8_t(row["race_perception_max"].as<int32_t>(RaceStruct::defaultMaxAttribute));
    race.minStrength = uint8_t(row["race_strength_min"].as<int32_t>(RaceStruct::defaultMinAttribute));
    race.maxStrength = uint8_t(row["race_strength_max"].as<int32_t>(RaceStruct::defaultMaxAttribute));
    race.minWillpower = uint8_t(row["race_willpower_min"].as<int32_t>(RaceStruct::defaultMinAttribute));
    race.maxWillpower = uint8_t(row["race_willpower_max"].as<int32_t>(RaceStruct::defaultMaxAttribute));
    race.maxAttribs = uint8_t(row["race_attribute_points_max"].as<int16_t>(RaceStruct::defaultMaxAttributePoints));
    return race;
}

auto RaceTable::getRelativeSize(TYPE_OF_RACE_ID race, uint16_t size) const -> uint8_t {
    // relative size is between 40 and 120 (in percent) and a linear interpolation between min and max size
    constexpr auto defaultRelativeSize = 100;

    if (size == 0) {
        // size not set
        return defaultRelativeSize;
    }

    if (!exists(race)) {
        return defaultRelativeSize;
    }

    const auto &sizes = this->get(race);

    const auto minSize = sizes.minSize;

    const auto maxSize = sizes.maxSize;

    constexpr auto minRelativeSize = 80;
    constexpr auto maxRelativeSize = 120;

    if (size < minSize) {
        return minRelativeSize;
    }

    if (size > maxSize) {
        return maxRelativeSize;
    }

    return uint8_t(((maxRelativeSize - minRelativeSize) * (size - minSize)) / (maxSize - minSize) + minRelativeSize);
}

auto RaceTable::isBaseAttributeInLimits(TYPE_OF_RACE_ID race, Character::attributeIndex attribute,
                                        Attribute::attribute_t value) const -> bool {
    if (!exists(race)) {
        return false;
    }

    const auto &attributes = this->get(race);

    switch (attribute) {
    case Character::agility:
        return value >= attributes.minAgility && value <= attributes.maxAgility;

    case Character::constitution:
        return value >= attributes.minConstitution && value <= attributes.maxConstitution;

    case Character::dexterity:
        return value >= attributes.minDexterity && value <= attributes.maxDexterity;

    case Character::essence:
        return value >= attributes.minEssence && value <= attributes.maxEssence;

    case Character::intelligence:
        return value >= attributes.minIntelligence && value <= attributes.maxIntelligence;

    case Character::perception:
        return value >= attributes.minPerception && value <= attributes.maxPerception;

    case Character::strength:
        return value >= attributes.minStrength && value <= attributes.maxStrength;

    case Character::willpower:
        return value >= attributes.minWillpower && value <= attributes.maxWillpower;

    default:
        return false;
    }
}

auto RaceTable::getMaxAttributePoints(TYPE_OF_RACE_ID race) const -> uint8_t {
    if (!exists(race)) {
        return 0;
    }

    const auto &attributes = this->get(race);
    return attributes.maxAttribs;
}
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef SERVER_RESPONSE_HPP
#define SERVER_RESPONSE_HPP

#include "http/inc/response.hpp"
#include "http/inc/mime_types.hpp"
#include "cookie.hpp"
#include <fs/filesystem.hpp>
#include <net/tcp/connection.hpp>
#include <utility/async.hpp>

#include <string>
#include <vector>
#include <time.h>
#include <chrono>

using namespace cookie;

struct File {

  File(fs::Disk_ptr dptr, const fs::Dirent& ent)
    : disk(dptr)
  {
    assert(ent.is_file());
    entry = ent;
  }

  fs::Dirent entry;
  fs::Disk_ptr disk;
};

namespace server {

class Response;
using Response_ptr = std::shared_ptr<Response>;

class Response : public http::Response {
private:
  using Code = http::status_t;
  using Connection_ptr = net::tcp::Connection_ptr;
  using OnSent = std::function<void(size_t)>;

public:

  struct Error {
    Code code;
    std::string type;
    std::string message;

    Error() : code{http::Bad_Request} {}

    Error(std::string&& type, std::string&& msg)
      : code{http::Bad_Request}, type{type}, message{msg}
    {}

    Error(const Code code, std::string&& type, std::string&& msg)
      : code{code}, type{type}, message{msg}
    {}

    // TODO: NotLikeThis
    std::string json() const {
      return "{ \"type\" : \"" + type + "\", \"message\" : \"" + message + "\" }";
    }
  };

  Response(Connection_ptr conn);

  /*
    Send only status code
  */
  void send_code(const Code, bool close = true);

  /*
    Send the Response
  */
  void send(bool close = false);

  /*
    Send a file
  */
  void send_file(const File&);

  void send_json(const std::string&);

  /* Cookie-support start */

  void cookie(const Cookie& c);

  void cookie(const std::string& name, const std::string& value);

  void cookie(const std::string& name, const std::string& value, const std::vector<std::string>& options);

  void update_cookie(const std::string& name, const std::string& old_path, const std::string& old_domain,
    const std::string& new_value);

  void update_cookie(const std::string& name, const std::string& old_path, const std::string& old_domain,
    const std::string& new_value, const std::vector<std::string>& new_options);

  void clear_cookie(const std::string& name, const std::string& path, const std::string& domain);

  /* Cookie-support end */

  /**
   * @brief Send an error response
   * @details Sends an error response together with the given status code.
   *
   * @param e Response::Error
   */
  void error(Error&&);

  /*
    "End" the response
  */
  void end() const;

  static void on_sent(OnSent cb)
  { on_sent_ = cb; }

  ~Response();

private:
  Connection_ptr conn_;

  static OnSent on_sent_;

  bool keep_alive = true;

  void write_to_conn(bool close_on_written = false);

}; // server::Response

} // < server

#endif
<commit_msg>Response: Refactored utility to util in IncludeOS<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef SERVER_RESPONSE_HPP
#define SERVER_RESPONSE_HPP

#include "http/inc/response.hpp"
#include "http/inc/mime_types.hpp"
#include "cookie.hpp"
#include <fs/filesystem.hpp>
#include <net/tcp/connection.hpp>
#include <util/async.hpp>

#include <string>
#include <vector>
#include <time.h>
#include <chrono>

using namespace cookie;

struct File {

  File(fs::Disk_ptr dptr, const fs::Dirent& ent)
    : disk(dptr)
  {
    assert(ent.is_file());
    entry = ent;
  }

  fs::Dirent entry;
  fs::Disk_ptr disk;
};

namespace server {

class Response;
using Response_ptr = std::shared_ptr<Response>;

class Response : public http::Response {
private:
  using Code = http::status_t;
  using Connection_ptr = net::tcp::Connection_ptr;
  using OnSent = std::function<void(size_t)>;

public:

  struct Error {
    Code code;
    std::string type;
    std::string message;

    Error() : code{http::Bad_Request} {}

    Error(std::string&& type, std::string&& msg)
      : code{http::Bad_Request}, type{type}, message{msg}
    {}

    Error(const Code code, std::string&& type, std::string&& msg)
      : code{code}, type{type}, message{msg}
    {}

    // TODO: NotLikeThis
    std::string json() const {
      return "{ \"type\" : \"" + type + "\", \"message\" : \"" + message + "\" }";
    }
  };

  Response(Connection_ptr conn);

  /*
    Send only status code
  */
  void send_code(const Code, bool close = true);

  /*
    Send the Response
  */
  void send(bool close = false);

  /*
    Send a file
  */
  void send_file(const File&);

  void send_json(const std::string&);

  /* Cookie-support start */

  void cookie(const Cookie& c);

  void cookie(const std::string& name, const std::string& value);

  void cookie(const std::string& name, const std::string& value, const std::vector<std::string>& options);

  void update_cookie(const std::string& name, const std::string& old_path, const std::string& old_domain,
    const std::string& new_value);

  void update_cookie(const std::string& name, const std::string& old_path, const std::string& old_domain,
    const std::string& new_value, const std::vector<std::string>& new_options);

  void clear_cookie(const std::string& name, const std::string& path, const std::string& domain);

  /* Cookie-support end */

  /**
   * @brief Send an error response
   * @details Sends an error response together with the given status code.
   *
   * @param e Response::Error
   */
  void error(Error&&);

  /*
    "End" the response
  */
  void end() const;

  static void on_sent(OnSent cb)
  { on_sent_ = cb; }

  ~Response();

private:
  Connection_ptr conn_;

  static OnSent on_sent_;

  bool keep_alive = true;

  void write_to_conn(bool close_on_written = false);

}; // server::Response

} // < server

#endif
<|endoftext|>