<commit_before>/*****************************************************************************
 * recents.cpp : Recents MRL (menu)
 *****************************************************************************
 * Copyright © 2008-2014 VideoLAN and VLC authors
 * $Id$
 *
 * Authors: Ludovic Fauvet <etix@l0cal.com>
 *          Jean-baptiste Kempf <jb@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * ( at your option ) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#include "qt4.hpp"
#include "recents.hpp"
#include "dialogs_provider.hpp"
#include "menus.hpp"
#include "util/qt_dirs.hpp"

#include <QStringList>
#include <QRegExp>
#include <QSignalMapper>

#ifdef _WIN32
    #include <shlobj.h>
    /* typedef enum  {
        SHARD_PIDL              = 0x00000001,
        SHARD_PATHA             = 0x00000002,
        SHARD_PATHW             = 0x00000003,
        SHARD_APPIDINFO         = 0x00000004,
        SHARD_APPIDINFOIDLIST   = 0x00000005,
        SHARD_LINK              = 0x00000006,
        SHARD_APPIDINFOLINK     = 0x00000007,
        SHARD_SHELLITEM         = 0x00000008
    } SHARD; */
    #define SHARD_PATHW 0x00000003

    #include <vlc_charset.h>
#endif

RecentsMRL::RecentsMRL( intf_thread_t *_p_intf ) : p_intf( _p_intf )
{
    recents = QStringList();
    times = QStringList();

    signalMapper = new QSignalMapper( this );
    CONNECT( signalMapper,
            mapped(const QString & ),
            this,
            playMRL( const QString & ) );

    /* Load the filter psz */
    char* psz_tmp = var_InheritString( p_intf, "qt-recentplay-filter" );
    if( psz_tmp && *psz_tmp )
        filter = new QRegExp( psz_tmp, Qt::CaseInsensitive );
    else
        filter = NULL;
    free( psz_tmp );

    load();
    isActive = var_InheritBool( p_intf, "qt-recentplay" );
    if( !isActive ) clear();
}

RecentsMRL::~RecentsMRL()
{
    save();
    delete filter;
}

void RecentsMRL::addRecent( const QString &mrl )
{
    if ( !isActive || ( filter && filter->indexIn( mrl ) >= 0 ) )
        return;

#ifdef _WIN32
    /* Add to the Windows 7 default list in taskbar */
    char* path = make_path( qtu( mrl ) );
    if( path )
    {
        wchar_t *wmrl = ToWide( path );
        SHAddToRecentDocs( SHARD_PATHW, wmrl );
        free( wmrl );
        free( path );
    }
#endif

    int i_index = recents.indexOf( mrl );
    if( 0 <= i_index )
    {
        /* move to the front */
        recents.move( i_index, 0 );
        times.move( i_index, 0 );
    }
    else
    {
        recents.prepend( mrl );
        times.prepend( "-1" );
        if( recents.count() > RECENTS_LIST_SIZE ) {
            recents.takeLast();
            times.takeLast();
        }
    }
    VLCMenuBar::updateRecents( p_intf );
    save();
}

void RecentsMRL::clear()
{
    if ( recents.isEmpty() )
        return;

    recents.clear();
    times.clear();
    if( isActive ) VLCMenuBar::updateRecents( p_intf );
    save();
}

QStringList RecentsMRL::recentList()
{
    return recents;
}

void RecentsMRL::load()
{
    /* Load from the settings */
    QStringList list = getSettings()->value( "RecentsMRL/list" ).toStringList();
    QStringList list2 = getSettings()->value( "RecentsMRL/times" ).toStringList();

    /* And filter the regexp on the list */
    for( int i = 0; i < list.count(); ++i )
    {
        if ( !filter || filter->indexIn( list.at(i) ) == -1 ) {
            recents.append( list.at(i) );
            times.append( list2.value(i, "-1" ) );
        }
    }
}

void RecentsMRL::save()
{
    getSettings()->setValue( "RecentsMRL/list", recents );
    getSettings()->setValue( "RecentsMRL/times", times );
}

playlist_item_t *RecentsMRL::toPlaylist(int length)
{
    playlist_item_t *p_node_recent = playlist_NodeCreate(THEPL, _("Recently Played"), THEPL->p_root, PLAYLIST_END, PLAYLIST_RO_FLAG, NULL);

    if ( p_node_recent == NULL )  return NULL;

    if (length == 0 || recents.count() < length)
        length = recents.count();

    for (int i = 0; i < length; i++)
    {
        input_item_t *p_input = input_item_New(qtu(recents.at(i)), NULL);
        playlist_NodeAddInput(THEPL, p_input, p_node_recent, PLAYLIST_APPEND, PLAYLIST_END, false);
    }

    return p_node_recent;
}

void RecentsMRL::playMRL( const QString &mrl )
{
    Open::openMRL( p_intf, mrl );
}

int RecentsMRL::time( const QString &mrl )
{
    if( !isActive )
        return -1;

    int i_index = recents.indexOf( mrl );
    if( i_index != -1 )
        return times.value(i_index, "-1").toInt();
    else
        return -1;
}

void RecentsMRL::setTime( const QString &mrl, const int64_t time )
{
    int i_index = recents.indexOf( mrl );
    if( i_index != -1 )
        times[i_index] = QString::number( time / 1000 );
}

int Open::openMRL( intf_thread_t *p_intf,
                    const QString &mrl,
                    bool b_start,
                    bool b_playlist)
{
    return openMRLwithOptions( p_intf, mrl, NULL, b_start, b_playlist );
}

int Open::openMRLwithOptions( intf_thread_t* p_intf,
                     const QString &mrl,
                     QStringList *options,
                     bool b_start,
                     bool b_playlist,
                     const char *title)
{
    /* Options */
    const char **ppsz_options = NULL;
    int i_options = 0;

    if( options != NULL && options->count() > 0 )
    {
        ppsz_options = (const char **)malloc( options->count() );
        if( ppsz_options ) {
            for( int j = 0; j < options->count(); j++ ) {
                QString option = colon_unescape( options->at(j) );
                if( !option.isEmpty() ) {
                    ppsz_options[j] = qtu(option);
                    i_options++;
                }
            }
        }
    }

    /* Add to playlist */
    int i_ret = playlist_AddExt( THEPL,
                  qtu(mrl), title,
                  PLAYLIST_APPEND | (b_start ? PLAYLIST_GO : PLAYLIST_PREPARSE),
                  PLAYLIST_END,
                  -1,
                  i_options, ppsz_options, VLC_INPUT_OPTION_TRUSTED,
                  b_playlist,
                  pl_Unlocked );

    /* Add to recent items, only if played */
    if( i_ret == VLC_SUCCESS && b_start && b_playlist )
        RecentsMRL::getInstance( p_intf )->addRecent( mrl );

    return i_ret;
}

<commit_msg>qt4: fix memory leak<commit_after>/*****************************************************************************
 * recents.cpp : Recents MRL (menu)
 *****************************************************************************
 * Copyright © 2008-2014 VideoLAN and VLC authors
 * $Id$
 *
 * Authors: Ludovic Fauvet <etix@l0cal.com>
 *          Jean-baptiste Kempf <jb@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * ( at your option ) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#include "qt4.hpp"
#include "recents.hpp"
#include "dialogs_provider.hpp"
#include "menus.hpp"
#include "util/qt_dirs.hpp"

#include <QStringList>
#include <QRegExp>
#include <QSignalMapper>

#ifdef _WIN32
    #include <shlobj.h>
    /* typedef enum  {
        SHARD_PIDL              = 0x00000001,
        SHARD_PATHA             = 0x00000002,
        SHARD_PATHW             = 0x00000003,
        SHARD_APPIDINFO         = 0x00000004,
        SHARD_APPIDINFOIDLIST   = 0x00000005,
        SHARD_LINK              = 0x00000006,
        SHARD_APPIDINFOLINK     = 0x00000007,
        SHARD_SHELLITEM         = 0x00000008
    } SHARD; */
    #define SHARD_PATHW 0x00000003

    #include <vlc_charset.h>
#endif

RecentsMRL::RecentsMRL( intf_thread_t *_p_intf ) : p_intf( _p_intf )
{
    recents = QStringList();
    times = QStringList();

    signalMapper = new QSignalMapper( this );
    CONNECT( signalMapper,
            mapped(const QString & ),
            this,
            playMRL( const QString & ) );

    /* Load the filter psz */
    char* psz_tmp = var_InheritString( p_intf, "qt-recentplay-filter" );
    if( psz_tmp && *psz_tmp )
        filter = new QRegExp( psz_tmp, Qt::CaseInsensitive );
    else
        filter = NULL;
    free( psz_tmp );

    load();
    isActive = var_InheritBool( p_intf, "qt-recentplay" );
    if( !isActive ) clear();
}

RecentsMRL::~RecentsMRL()
{
    save();
    delete filter;
}

void RecentsMRL::addRecent( const QString &mrl )
{
    if ( !isActive || ( filter && filter->indexIn( mrl ) >= 0 ) )
        return;

#ifdef _WIN32
    /* Add to the Windows 7 default list in taskbar */
    char* path = make_path( qtu( mrl ) );
    if( path )
    {
        wchar_t *wmrl = ToWide( path );
        SHAddToRecentDocs( SHARD_PATHW, wmrl );
        free( wmrl );
        free( path );
    }
#endif

    int i_index = recents.indexOf( mrl );
    if( 0 <= i_index )
    {
        /* move to the front */
        recents.move( i_index, 0 );
        times.move( i_index, 0 );
    }
    else
    {
        recents.prepend( mrl );
        times.prepend( "-1" );
        if( recents.count() > RECENTS_LIST_SIZE ) {
            recents.takeLast();
            times.takeLast();
        }
    }
    VLCMenuBar::updateRecents( p_intf );
    save();
}

void RecentsMRL::clear()
{
    if ( recents.isEmpty() )
        return;

    recents.clear();
    times.clear();
    if( isActive ) VLCMenuBar::updateRecents( p_intf );
    save();
}

QStringList RecentsMRL::recentList()
{
    return recents;
}

void RecentsMRL::load()
{
    /* Load from the settings */
    QStringList list = getSettings()->value( "RecentsMRL/list" ).toStringList();
    QStringList list2 = getSettings()->value( "RecentsMRL/times" ).toStringList();

    /* And filter the regexp on the list */
    for( int i = 0; i < list.count(); ++i )
    {
        if ( !filter || filter->indexIn( list.at(i) ) == -1 ) {
            recents.append( list.at(i) );
            times.append( list2.value(i, "-1" ) );
        }
    }
}

void RecentsMRL::save()
{
    getSettings()->setValue( "RecentsMRL/list", recents );
    getSettings()->setValue( "RecentsMRL/times", times );
}

playlist_item_t *RecentsMRL::toPlaylist(int length)
{
    playlist_item_t *p_node_recent = playlist_NodeCreate(THEPL, _("Recently Played"), THEPL->p_root, PLAYLIST_END, PLAYLIST_RO_FLAG, NULL);

    if ( p_node_recent == NULL )  return NULL;

    if (length == 0 || recents.count() < length)
        length = recents.count();

    for (int i = 0; i < length; i++)
    {
        input_item_t *p_input = input_item_New(qtu(recents.at(i)), NULL);
        playlist_NodeAddInput(THEPL, p_input, p_node_recent, PLAYLIST_APPEND, PLAYLIST_END, false);
    }

    return p_node_recent;
}

void RecentsMRL::playMRL( const QString &mrl )
{
    Open::openMRL( p_intf, mrl );
}

int RecentsMRL::time( const QString &mrl )
{
    if( !isActive )
        return -1;

    int i_index = recents.indexOf( mrl );
    if( i_index != -1 )
        return times.value(i_index, "-1").toInt();
    else
        return -1;
}

void RecentsMRL::setTime( const QString &mrl, const int64_t time )
{
    int i_index = recents.indexOf( mrl );
    if( i_index != -1 )
        times[i_index] = QString::number( time / 1000 );
}

int Open::openMRL( intf_thread_t *p_intf,
                    const QString &mrl,
                    bool b_start,
                    bool b_playlist)
{
    return openMRLwithOptions( p_intf, mrl, NULL, b_start, b_playlist );
}

int Open::openMRLwithOptions( intf_thread_t* p_intf,
                     const QString &mrl,
                     QStringList *options,
                     bool b_start,
                     bool b_playlist,
                     const char *title)
{
    /* Options */
    const char **ppsz_options = NULL;
    int i_options = 0;

    if( options != NULL && options->count() > 0 )
    {
        ppsz_options = new const char *[options->count()];
        for( int j = 0; j < options->count(); j++ ) {
            QString option = colon_unescape( options->at(j) );
            if( !option.isEmpty() ) {
                ppsz_options[j] = qtu(option);
                i_options++;
            }
        }
    }

    /* Add to playlist */
    int i_ret = playlist_AddExt( THEPL,
                  qtu(mrl), title,
                  PLAYLIST_APPEND | (b_start ? PLAYLIST_GO : PLAYLIST_PREPARSE),
                  PLAYLIST_END,
                  -1,
                  i_options, ppsz_options, VLC_INPUT_OPTION_TRUSTED,
                  b_playlist,
                  pl_Unlocked );

    /* Add to recent items, only if played */
    if( i_ret == VLC_SUCCESS && b_start && b_playlist )
        RecentsMRL::getInstance( p_intf )->addRecent( mrl );

    delete[] options;
    return i_ret;
}

<|endoftext|>


<commit_before>/*****************************************************************************
 * recents.cpp : Recents MRL (menu)
 *****************************************************************************
 * Copyright © 2008-2014 VideoLAN and VLC authors
 * $Id$
 *
 * Authors: Ludovic Fauvet <etix@l0cal.com>
 *          Jean-baptiste Kempf <jb@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * ( at your option ) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#include "qt4.hpp"
#include "recents.hpp"
#include "dialogs_provider.hpp"
#include "menus.hpp"
#include "util/qt_dirs.hpp"

#include <QStringList>
#include <QRegExp>
#include <QSignalMapper>

#ifdef _WIN32
    #include <shlobj.h>
    /* typedef enum  {
        SHARD_PIDL              = 0x00000001,
        SHARD_PATHA             = 0x00000002,
        SHARD_PATHW             = 0x00000003,
        SHARD_APPIDINFO         = 0x00000004,
        SHARD_APPIDINFOIDLIST   = 0x00000005,
        SHARD_LINK              = 0x00000006,
        SHARD_APPIDINFOLINK     = 0x00000007,
        SHARD_SHELLITEM         = 0x00000008
    } SHARD; */
    #define SHARD_PATHW 0x00000003

    #include <vlc_charset.h>
#endif

RecentsMRL::RecentsMRL( intf_thread_t *_p_intf ) : p_intf( _p_intf )
{
    recents = QStringList();
    times = QStringList();

    signalMapper = new QSignalMapper( this );
    CONNECT( signalMapper,
            mapped(const QString & ),
            this,
            playMRL( const QString & ) );

    /* Load the filter psz */
    char* psz_tmp = var_InheritString( p_intf, "qt-recentplay-filter" );
    if( psz_tmp && *psz_tmp )
        filter = new QRegExp( psz_tmp, Qt::CaseInsensitive );
    else
        filter = NULL;
    free( psz_tmp );

    load();
    isActive = var_InheritBool( p_intf, "qt-recentplay" );
    if( !isActive ) clear();
}

RecentsMRL::~RecentsMRL()
{
    save();
    delete filter;
}

void RecentsMRL::addRecent( const QString &mrl )
{
    if ( !isActive || ( filter && filter->indexIn( mrl ) >= 0 ) )
        return;

#ifdef _WIN32
    /* Add to the Windows 7 default list in taskbar */
    char* path = make_path( qtu( mrl ) );
    if( path )
    {
        wchar_t *wmrl = ToWide( path );
        SHAddToRecentDocs( SHARD_PATHW, wmrl );
        free( wmrl );
        free( path );
    }
#endif

    int i_index = recents.indexOf( mrl );
    if( 0 <= i_index )
    {
        /* move to the front */
        recents.move( i_index, 0 );
        times.move( i_index, 0 );
    }
    else
    {
        recents.prepend( mrl );
        times.prepend( "-1" );
        if( recents.count() > RECENTS_LIST_SIZE ) {
            recents.takeLast();
            times.takeLast();
        }
    }
    VLCMenuBar::updateRecents( p_intf );
    save();
}

void RecentsMRL::clear()
{
    if ( recents.isEmpty() )
        return;

    recents.clear();
    times.clear();
    if( isActive ) VLCMenuBar::updateRecents( p_intf );
    save();
}

QStringList RecentsMRL::recentList()
{
    return recents;
}

void RecentsMRL::load()
{
    /* Load from the settings */
    QStringList list = getSettings()->value( "RecentsMRL/list" ).toStringList();
    QStringList list2 = getSettings()->value( "RecentsMRL/times" ).toStringList();

    /* And filter the regexp on the list */
    for( int i = 0; i < list.count(); ++i )
    {
        if ( !filter || filter->indexIn( list.at(i) ) == -1 ) {
            recents.append( list.at(i) );
            times.append( list2.value(i, "-1" ) );
        }
    }
}

void RecentsMRL::save()
{
    getSettings()->setValue( "RecentsMRL/list", recents );
    getSettings()->setValue( "RecentsMRL/times", times );
}

playlist_item_t *RecentsMRL::toPlaylist(int length)
{
    playlist_item_t *p_node_recent = playlist_NodeCreate(THEPL, _("Recently Played"), THEPL->p_root, PLAYLIST_END, PLAYLIST_RO_FLAG, NULL);

    if ( p_node_recent == NULL )  return NULL;

    if (length == 0 || recents.count() < length)
        length = recents.count();

    for (int i = 0; i < length; i++)
    {
        input_item_t *p_input = input_item_New(qtu(recents.at(i)), NULL);
        playlist_NodeAddInput(THEPL, p_input, p_node_recent, PLAYLIST_APPEND, PLAYLIST_END, false);
    }

    return p_node_recent;
}

void RecentsMRL::playMRL( const QString &mrl )
{
    Open::openMRL( p_intf, mrl );
}

int RecentsMRL::time( const QString &mrl )
{
    if( !isActive )
        return -1;

    int i_index = recents.indexOf( mrl );
    if( i_index != -1 )
        return times.value(i_index, "-1").toInt();
    else
        return -1;
}

void RecentsMRL::setTime( const QString &mrl, const int64_t time )
{
    int i_index = recents.indexOf( mrl );
    if( i_index != -1 )
        times[i_index] = QString::number( time / 1000 );
}

int Open::openMRL( intf_thread_t *p_intf,
                    const QString &mrl,
                    bool b_start,
                    bool b_playlist)
{
    return openMRLwithOptions( p_intf, mrl, NULL, b_start, b_playlist );
}

int Open::openMRLwithOptions( intf_thread_t* p_intf,
                     const QString &mrl,
                     QStringList *options,
                     bool b_start,
                     bool b_playlist,
                     const char *title)
{
    /* Options */
    const char **ppsz_options = NULL;
    int i_options = 0;

    if( options != NULL && options->count() > 0 )
    {
        ppsz_options = new const char *[options->count()];
        for( int j = 0; j < options->count(); j++ ) {
            QString option = colon_unescape( options->at(j) );
            if( !option.isEmpty() ) {
                ppsz_options[j] = qtu(option);
                i_options++;
            }
        }
    }

    /* Add to playlist */
    int i_ret = playlist_AddExt( THEPL,
                  qtu(mrl), title,
                  PLAYLIST_APPEND | (b_start ? PLAYLIST_GO : PLAYLIST_PREPARSE),
                  PLAYLIST_END,
                  -1,
                  i_options, ppsz_options, VLC_INPUT_OPTION_TRUSTED,
                  b_playlist,
                  pl_Unlocked );

    /* Add to recent items, only if played */
    if( i_ret == VLC_SUCCESS && b_start && b_playlist )
        RecentsMRL::getInstance( p_intf )->addRecent( mrl );

    delete[] options;
    return i_ret;
}

<commit_msg>Qt: Fix crash introduced by 798ee1ab<commit_after>/*****************************************************************************
 * recents.cpp : Recents MRL (menu)
 *****************************************************************************
 * Copyright © 2008-2014 VideoLAN and VLC authors
 * $Id$
 *
 * Authors: Ludovic Fauvet <etix@l0cal.com>
 *          Jean-baptiste Kempf <jb@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * ( at your option ) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#include "qt4.hpp"
#include "recents.hpp"
#include "dialogs_provider.hpp"
#include "menus.hpp"
#include "util/qt_dirs.hpp"

#include <QStringList>
#include <QRegExp>
#include <QSignalMapper>

#ifdef _WIN32
    #include <shlobj.h>
    /* typedef enum  {
        SHARD_PIDL              = 0x00000001,
        SHARD_PATHA             = 0x00000002,
        SHARD_PATHW             = 0x00000003,
        SHARD_APPIDINFO         = 0x00000004,
        SHARD_APPIDINFOIDLIST   = 0x00000005,
        SHARD_LINK              = 0x00000006,
        SHARD_APPIDINFOLINK     = 0x00000007,
        SHARD_SHELLITEM         = 0x00000008
    } SHARD; */
    #define SHARD_PATHW 0x00000003

    #include <vlc_charset.h>
#endif

RecentsMRL::RecentsMRL( intf_thread_t *_p_intf ) : p_intf( _p_intf )
{
    recents = QStringList();
    times = QStringList();

    signalMapper = new QSignalMapper( this );
    CONNECT( signalMapper,
            mapped(const QString & ),
            this,
            playMRL( const QString & ) );

    /* Load the filter psz */
    char* psz_tmp = var_InheritString( p_intf, "qt-recentplay-filter" );
    if( psz_tmp && *psz_tmp )
        filter = new QRegExp( psz_tmp, Qt::CaseInsensitive );
    else
        filter = NULL;
    free( psz_tmp );

    load();
    isActive = var_InheritBool( p_intf, "qt-recentplay" );
    if( !isActive ) clear();
}

RecentsMRL::~RecentsMRL()
{
    save();
    delete filter;
}

void RecentsMRL::addRecent( const QString &mrl )
{
    if ( !isActive || ( filter && filter->indexIn( mrl ) >= 0 ) )
        return;

#ifdef _WIN32
    /* Add to the Windows 7 default list in taskbar */
    char* path = make_path( qtu( mrl ) );
    if( path )
    {
        wchar_t *wmrl = ToWide( path );
        SHAddToRecentDocs( SHARD_PATHW, wmrl );
        free( wmrl );
        free( path );
    }
#endif

    int i_index = recents.indexOf( mrl );
    if( 0 <= i_index )
    {
        /* move to the front */
        recents.move( i_index, 0 );
        times.move( i_index, 0 );
    }
    else
    {
        recents.prepend( mrl );
        times.prepend( "-1" );
        if( recents.count() > RECENTS_LIST_SIZE ) {
            recents.takeLast();
            times.takeLast();
        }
    }
    VLCMenuBar::updateRecents( p_intf );
    save();
}

void RecentsMRL::clear()
{
    if ( recents.isEmpty() )
        return;

    recents.clear();
    times.clear();
    if( isActive ) VLCMenuBar::updateRecents( p_intf );
    save();
}

QStringList RecentsMRL::recentList()
{
    return recents;
}

void RecentsMRL::load()
{
    /* Load from the settings */
    QStringList list = getSettings()->value( "RecentsMRL/list" ).toStringList();
    QStringList list2 = getSettings()->value( "RecentsMRL/times" ).toStringList();

    /* And filter the regexp on the list */
    for( int i = 0; i < list.count(); ++i )
    {
        if ( !filter || filter->indexIn( list.at(i) ) == -1 ) {
            recents.append( list.at(i) );
            times.append( list2.value(i, "-1" ) );
        }
    }
}

void RecentsMRL::save()
{
    getSettings()->setValue( "RecentsMRL/list", recents );
    getSettings()->setValue( "RecentsMRL/times", times );
}

playlist_item_t *RecentsMRL::toPlaylist(int length)
{
    playlist_item_t *p_node_recent = playlist_NodeCreate(THEPL, _("Recently Played"), THEPL->p_root, PLAYLIST_END, PLAYLIST_RO_FLAG, NULL);

    if ( p_node_recent == NULL )  return NULL;

    if (length == 0 || recents.count() < length)
        length = recents.count();

    for (int i = 0; i < length; i++)
    {
        input_item_t *p_input = input_item_New(qtu(recents.at(i)), NULL);
        playlist_NodeAddInput(THEPL, p_input, p_node_recent, PLAYLIST_APPEND, PLAYLIST_END, false);
    }

    return p_node_recent;
}

void RecentsMRL::playMRL( const QString &mrl )
{
    Open::openMRL( p_intf, mrl );
}

int RecentsMRL::time( const QString &mrl )
{
    if( !isActive )
        return -1;

    int i_index = recents.indexOf( mrl );
    if( i_index != -1 )
        return times.value(i_index, "-1").toInt();
    else
        return -1;
}

void RecentsMRL::setTime( const QString &mrl, const int64_t time )
{
    int i_index = recents.indexOf( mrl );
    if( i_index != -1 )
        times[i_index] = QString::number( time / 1000 );
}

int Open::openMRL( intf_thread_t *p_intf,
                    const QString &mrl,
                    bool b_start,
                    bool b_playlist)
{
    return openMRLwithOptions( p_intf, mrl, NULL, b_start, b_playlist );
}

int Open::openMRLwithOptions( intf_thread_t* p_intf,
                     const QString &mrl,
                     QStringList *options,
                     bool b_start,
                     bool b_playlist,
                     const char *title)
{
    /* Options */
    const char **ppsz_options = NULL;
    int i_options = 0;

    if( options != NULL && options->count() > 0 )
    {
        ppsz_options = new const char *[options->count()];
        for( int j = 0; j < options->count(); j++ ) {
            QString option = colon_unescape( options->at(j) );
            if( !option.isEmpty() ) {
                ppsz_options[j] = qtu(option);
                i_options++;
            }
        }
    }

    /* Add to playlist */
    int i_ret = playlist_AddExt( THEPL,
                  qtu(mrl), title,
                  PLAYLIST_APPEND | (b_start ? PLAYLIST_GO : PLAYLIST_PREPARSE),
                  PLAYLIST_END,
                  -1,
                  i_options, ppsz_options, VLC_INPUT_OPTION_TRUSTED,
                  b_playlist,
                  pl_Unlocked );

    /* Add to recent items, only if played */
    if( i_ret == VLC_SUCCESS && b_start && b_playlist )
        RecentsMRL::getInstance( p_intf )->addRecent( mrl );

    return i_ret;
}

<|endoftext|>


<commit_before>#include "LBP.h"

LBP::LBP(unsigned int windowHeight, unsigned int windowWidth, unsigned int numberOfChannels, unsigned int *radius, unsigned int *samples, unsigned int numberOfRadiusSamplesCombinations) {
	unsigned int descriptorLengthPerWindow = numberOfRadiusSamplesCombinations * numberOfChannels;
    this->radius = radius;
    this->samples = samples;
    this->numberOfRadiusSamplesCombinations = numberOfRadiusSamplesCombinations;
    this->descriptorLengthPerWindow = descriptorLengthPerWindow;
    this->windowHeight = windowHeight;
    this->windowWidth = windowWidth;
    this->numberOfChannels = numberOfChannels;
}

LBP::~LBP() {
}

void LBP::apply(double *windowImage, double *descriptorVector) {
    LBPdescriptor(windowImage, this->radius, this->samples, this->numberOfRadiusSamplesCombinations, this->windowHeight, this->windowWidth, this->numberOfChannels, descriptorVector);
}

void LBPdescriptor(double *inputImage, unsigned int *radius, unsigned int *samples, unsigned int numberOfRadiusSamplesCombinations, unsigned int imageHeight, unsigned int imageWidth, unsigned int numberOfChannels, double *descriptorVector) {
    unsigned int i, s, ch;
    int centre_y, centre_x, rx, ry, fx, fy, cx, cy;
    double angle_step, min_x, min_y, sample_x, sample_y, centre_val, sample_val;
    double *samples_coords_x;
    double *samples_coords_y;
    double tx, ty, w1, w2, w3, w4;
    int lbp_code;

    for (i=0; i<numberOfRadiusSamplesCombinations; i++) {
        // find coordinates of sampling points with the axes origin (0,0) on the window centre
        samples_coords_x = new double[samples[i]];
        samples_coords_y = new double[samples[i]];
        angle_step = 2*PI/samples[i];
        for (s=0; s<samples[i]; s++) {
            samples_coords_x[s] = radius[i] * cos(s * angle_step);
            samples_coords_y[s] = - (radius[i] * sin(s * angle_step));
        }

        // find min coordinates of sampling points with the axes origin (0,0) on the window centre
        min_x = samples_coords_x[0];
        min_y = samples_coords_y[0];
        for (s=1; s<samples[i]; s++) {
            if (samples_coords_x[s] < min_x)
                min_x = samples_coords_x[s];
            if (samples_coords_y[s] < min_y)
                min_y = samples_coords_y[s];
        }

        // find coordinates of the window centre in the window reference frame (axes origin in bottom left corner)
        centre_y = (int)-floor(min(min_y,0.0));
        centre_x = (int)-floor(min(min_x,0.0));

        // value of centre
        centre_val = inputImage[centre_y + centre_x*imageHeight + ch*imageHeight*imageWidth];

        // for each channel, compute the lbp code
        for (ch=0; ch<numberOfChannels; ch++) {
            lbp_code = 0;
            for (s=0; s<samples[i]; s++) {
                // coordinates of sampling point in the window reference frame (axes origin in bottom left corner)
                sample_x = centre_x + samples_coords_x[s];
                sample_y = centre_y + samples_coords_y[s];

                // check if interpolation is needed
                rx = (int)round(sample_x);
                ry = (int)round(sample_y);
                if ( (fabs(sample_x - rx) < small_val) && (fabs(sample_y - ry) < small_val) )
                    sample_val = inputImage[ry + rx*imageHeight + ch*imageHeight*imageWidth];
                else {
                    fx = (int)floor(sample_x);
                    fy = (int)floor(sample_y);
                    cx = (int)ceil(sample_x);
                    cy = (int)ceil(sample_y);
                    tx = sample_x - fx;
                    ty = sample_y - fy;
                    w1 = roundn((1 - tx) * (1 - ty), -6);
                    w2 = roundn(tx * (1 - ty), -6);
                    w3 = roundn((1 - tx) * ty, -6);
                    // w4 = roundn(tx * ty, -6);
                    w4 = roundn(1 - w1 - w2 - w3, -6);
                    sample_val = w1*inputImage[fy + fx*imageHeight + ch*imageHeight*imageWidth] + w2*inputImage[fy + cx*imageHeight + ch*imageHeight*imageWidth] + w3*inputImage[cy + fx*imageHeight + ch*imageHeight*imageWidth] + w4*inputImage[cy + cx*imageHeight + ch*imageHeight*imageWidth];
                    sample_val = roundn(sample_val, -4);
                }

                // update the lbp code
                if (sample_val >= centre_val)
                    lbp_code = lbp_code + 2^s;
            }
            descriptorVector[i + ch*numberOfRadiusSamplesCombinations] = lbp_code;
        }
    }
    // Empty memory
    delete [] samples_coords_x;
    delete [] samples_coords_y;
}

double roundn(double x, int n) {
    if (n < 0) {
        double p = 10 ^ -n;
        x = round(p * x) / p;
    }
    else if (n > 0) {
        double p = 10 ^ n;
        x = p * round(x / p);
    }
    else
        x = round(x);
    return x;
}
<commit_msg>fixed cpp logic bug<commit_after>#include "LBP.h"

LBP::LBP(unsigned int windowHeight, unsigned int windowWidth, unsigned int numberOfChannels, unsigned int *radius, unsigned int *samples, unsigned int numberOfRadiusSamplesCombinations) {
	unsigned int descriptorLengthPerWindow = numberOfRadiusSamplesCombinations * numberOfChannels;
    this->radius = radius;
    this->samples = samples;
    this->numberOfRadiusSamplesCombinations = numberOfRadiusSamplesCombinations;
    this->descriptorLengthPerWindow = descriptorLengthPerWindow;
    this->windowHeight = windowHeight;
    this->windowWidth = windowWidth;
    this->numberOfChannels = numberOfChannels;
}

LBP::~LBP() {
}

void LBP::apply(double *windowImage, double *descriptorVector) {
    LBPdescriptor(windowImage, this->radius, this->samples, this->numberOfRadiusSamplesCombinations, this->windowHeight, this->windowWidth, this->numberOfChannels, descriptorVector);
}

void LBPdescriptor(double *inputImage, unsigned int *radius, unsigned int *samples, unsigned int numberOfRadiusSamplesCombinations, unsigned int imageHeight, unsigned int imageWidth, unsigned int numberOfChannels, double *descriptorVector) {
    unsigned int i, s, ch;
    int centre_y, centre_x, rx, ry, fx, fy, cx, cy;
    double angle_step, centre_val, sample_val;
    double *samples_x;
    double *samples_y;
    double tx, ty, w1, w2, w3, w4;
    int lbp_code;

    // find coordinates of the window centre in the window reference frame (axes origin in bottom left corner)
    centre_y = (int)((imageHeight-1)/2);
    centre_x = (int)((imageWidth-1)/2);

    for (i=0; i<numberOfRadiusSamplesCombinations; i++) {
        // find coordinates of sampling point in the window reference frame (axes origin in bottom left corner)
        samples_x = new double[samples[i]];
        samples_y = new double[samples[i]];
        angle_step = 2*PI/samples[i];
        for (s=0; s<samples[i]; s++) {
            samples_x[s] = centre_x + radius[i] * cos(s * angle_step);
            samples_y[s] = centre_y - radius[i] * sin(s * angle_step);
        }

        // for each channel, compute the lbp code
        for (ch=0; ch<numberOfChannels; ch++) {
            // value of centre
            centre_val = inputImage[centre_y + centre_x*imageHeight + ch*imageHeight*imageWidth];
            lbp_code = 0;
            for (s=0; s<samples[i]; s++) {
                // check if interpolation is needed
                rx = (int)round(samples_x[s]);
                ry = (int)round(samples_y[s]);
                if ( (fabs(samples_x[s] - rx) < small_val) && (fabs(samples_y[s] - ry) < small_val) )
                    sample_val = inputImage[ry + rx*imageHeight + ch*imageHeight*imageWidth];
                else {
                    fx = (int)floor(samples_x[s]);
                    fy = (int)floor(samples_y[s]);
                    cx = (int)ceil(samples_x[s]);
                    cy = (int)ceil(samples_y[s]);
                    tx = samples_x[s] - fx;
                    ty = samples_y[s] - fy;
                    w1 = roundn((1 - tx) * (1 - ty), -6);
                    w2 = roundn(tx * (1 - ty), -6);
                    w3 = roundn((1 - tx) * ty, -6);
                    // w4 = roundn(tx * ty, -6);
                    w4 = roundn(1 - w1 - w2 - w3, -6);
                    sample_val = w1*inputImage[fy + fx*imageHeight + ch*imageHeight*imageWidth] + w2*inputImage[fy + cx*imageHeight + ch*imageHeight*imageWidth] + w3*inputImage[cy + fx*imageHeight + ch*imageHeight*imageWidth] + w4*inputImage[cy + cx*imageHeight + ch*imageHeight*imageWidth];
                    sample_val = roundn(sample_val, -4);
                }

                // update the lbp code
                if (sample_val >= centre_val)
                    lbp_code = lbp_code + 2^s;
            }
            descriptorVector[i + ch*numberOfRadiusSamplesCombinations] = lbp_code;
        }
    }
    // Empty memory
    delete [] samples_x;
    delete [] samples_y;
}

double roundn(double x, int n) {
    if (n < 0) {
        double p = 10 ^ -n;
        x = round(p * x) / p;
    }
    else if (n > 0) {
        double p = 10 ^ n;
        x = p * round(x / p);
    }
    else
        x = round(x);
    return x;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "debuggerkitconfigwidget.h"
#include "debuggerkitinformation.h"

#include <projectexplorer/abi.h>
#include <projectexplorer/kitinformation.h>

#include <utils/pathchooser.h>
#include <utils/qtcassert.h>

#ifdef Q_OS_WIN
#include <utils/winutils.h>
#endif

#include <QUrl>

#include <QDesktopServices>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QFormLayout>
#include <QLabel>
#include <QComboBox>
#include <QMenu>
#include <QAction>
#include <QPushButton>
#include <QDialogButtonBox>

namespace Debugger {
namespace Internal {

static const char dgbToolsDownloadLink32C[] = "http://www.microsoft.com/whdc/devtools/debugging/installx86.Mspx";
static const char dgbToolsDownloadLink64C[] = "http://www.microsoft.com/whdc/devtools/debugging/install64bit.Mspx";

// -----------------------------------------------------------------------
// DebuggerKitConfigWidget:
// -----------------------------------------------------------------------

DebuggerKitConfigWidget::DebuggerKitConfigWidget(ProjectExplorer::Kit *workingCopy,
                                                 const DebuggerKitInformation *ki,
                                                 QWidget *parent) :
    ProjectExplorer::KitConfigWidget(parent),
    m_kit(workingCopy),
    m_info(ki),
    m_label(new QLabel(this)),
    m_button(new QPushButton(tr("Manage..."), this))
{
    setToolTip(tr("The debugger to use for this kit."));

    QHBoxLayout *layout = new QHBoxLayout(this);
    layout->setMargin(0);
    layout->addWidget(m_label);

    // ToolButton with Menu, defaulting to 'Autodetect'.
    QMenu *buttonMenu = new QMenu(m_button);
    QAction *autoDetectAction = buttonMenu->addAction(tr("Auto-detect"));
    connect(autoDetectAction, SIGNAL(triggered()), this, SLOT(autoDetectDebugger()));
    QAction *changeAction = buttonMenu->addAction(tr("Edit..."));
    connect(changeAction, SIGNAL(triggered()), this, SLOT(showDialog()));
    m_button->setMenu(buttonMenu);

    refresh();
}

QWidget *DebuggerKitConfigWidget::buttonWidget() const
{
       return m_button;
}

QString DebuggerKitConfigWidget::displayName() const
{
    return tr("Debugger:");
}

void DebuggerKitConfigWidget::makeReadOnly()
{
    m_button->setEnabled(false);
}

void DebuggerKitConfigWidget::refresh()
{
    m_label->setText(DebuggerKitInformation::userOutput(DebuggerKitInformation::debuggerItem(m_kit)));
}

void DebuggerKitConfigWidget::autoDetectDebugger()
{
    DebuggerKitInformation::setDebuggerItem(m_kit, DebuggerKitInformation::autoDetectItem(m_kit));
}

void DebuggerKitConfigWidget::showDialog()
{
    DebuggerKitConfigDialog dialog;
    dialog.setWindowTitle(tr("Debugger for \"%1\"").arg(m_kit->displayName()));
    dialog.setDebuggerItem(DebuggerKitInformation::debuggerItem(m_kit));
    if (dialog.exec() == QDialog::Accepted)
        DebuggerKitInformation::setDebuggerItem(m_kit, dialog.item());
}

// -----------------------------------------------------------------------
// DebuggerKitConfigDialog:
// -----------------------------------------------------------------------

DebuggerKitConfigDialog::DebuggerKitConfigDialog(QWidget *parent)
    : QDialog(parent)
    , m_comboBox(new QComboBox(this))
    , m_label(new QLabel(this))
    , m_chooser(new Utils::PathChooser(this))
{
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    QVBoxLayout *layout = new QVBoxLayout(this);
    QFormLayout *formLayout = new QFormLayout;
    formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);

    m_comboBox->addItem(DebuggerKitInformation::debuggerEngineName(GdbEngineType), QVariant(int(GdbEngineType)));
    if (ProjectExplorer::Abi::hostAbi().os() == ProjectExplorer::Abi::WindowsOS) {
        m_comboBox->addItem(DebuggerKitInformation::debuggerEngineName(CdbEngineType), QVariant(int(CdbEngineType)));
    } else {
        m_comboBox->addItem(DebuggerKitInformation::debuggerEngineName(LldbEngineType), QVariant(int(LldbEngineType)));
    }
    connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(refreshLabel()));
    QLabel *engineTypeLabel = new QLabel(tr("&Engine:"));
    engineTypeLabel->setBuddy(m_comboBox);
    formLayout->addRow(engineTypeLabel, m_comboBox);

    m_label->setTextInteractionFlags(Qt::TextBrowserInteraction);
    m_label->setOpenExternalLinks(true);
    formLayout->addRow(m_label);

    QLabel *binaryLabel = new QLabel(tr("&Binary:"));
    m_chooser->setExpectedKind(Utils::PathChooser::ExistingCommand);
    binaryLabel->setBuddy(m_chooser);
    formLayout->addRow(binaryLabel, m_chooser);
    layout->addLayout(formLayout);

    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this);
    connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
    connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
    layout->addWidget(buttonBox);
}

DebuggerEngineType DebuggerKitConfigDialog::engineType() const
{
    const int index = m_comboBox->currentIndex();
    return static_cast<DebuggerEngineType>(m_comboBox->itemData(index).toInt());
}

void DebuggerKitConfigDialog::setEngineType(DebuggerEngineType et)
{
    const int size = m_comboBox->count();
    for (int i = 0; i < size; ++i) {
        if (m_comboBox->itemData(i).toInt() == et) {
            m_comboBox->setCurrentIndex(i);
            refreshLabel();
            break;
        }
    }
}

Utils::FileName DebuggerKitConfigDialog::fileName() const
{
    return m_chooser->fileName();
}

void DebuggerKitConfigDialog::setFileName(const Utils::FileName &fn)
{
    m_chooser->setFileName(fn);
}

void DebuggerKitConfigDialog::refreshLabel()
{
    QString text;
    const DebuggerEngineType type = engineType();
    switch (type) {
    case CdbEngineType: {
#ifdef Q_OS_WIN
        const bool is64bit = Utils::winIs64BitSystem();
#else
        const bool is64bit = false;
#endif
        const QString link = is64bit ? QLatin1String(dgbToolsDownloadLink64C) : QLatin1String(dgbToolsDownloadLink32C);
        const QString versionString = is64bit ? tr("64-bit version") : tr("32-bit version");
        //: Label text for path configuration. %2 is "x-bit version".
        text = tr("
Specify the path to the "
                  "Windows Console Debugger executable"
                  " (%2) here.
""").arg(link, versionString);
    }
        break;
    default:
        break;
    }
    m_label->setText(text);
    m_label->setVisible(!text.isEmpty());
    m_chooser->setCommandVersionArguments(type == CdbEngineType ?
                                          QStringList(QLatin1String("-version")) :
                                          QStringList(QLatin1String("--version")));
}

void DebuggerKitConfigDialog::setDebuggerItem(const DebuggerKitInformation::DebuggerItem &item)
{
    setEngineType(item.engineType);
    setFileName(item.binary);
}

} // namespace Internal
} // namespace Debugger
<commit_msg>Replace dead link to Debugging Tools download by Wiki link.<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "debuggerkitconfigwidget.h"
#include "debuggerkitinformation.h"

#include <projectexplorer/abi.h>
#include <projectexplorer/kitinformation.h>

#include <utils/pathchooser.h>
#include <utils/qtcassert.h>

#ifdef Q_OS_WIN
#include <utils/winutils.h>
#endif

#include <QUrl>

#include <QDesktopServices>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QFormLayout>
#include <QLabel>
#include <QComboBox>
#include <QMenu>
#include <QAction>
#include <QPushButton>
#include <QDialogButtonBox>

namespace Debugger {
namespace Internal {

static const char debuggingToolsWikiLinkC[] = "http://qt-project.org/wiki/Qt_Creator_Windows_Debugging";

// -----------------------------------------------------------------------
// DebuggerKitConfigWidget:
// -----------------------------------------------------------------------

DebuggerKitConfigWidget::DebuggerKitConfigWidget(ProjectExplorer::Kit *workingCopy,
                                                 const DebuggerKitInformation *ki,
                                                 QWidget *parent) :
    ProjectExplorer::KitConfigWidget(parent),
    m_kit(workingCopy),
    m_info(ki),
    m_label(new QLabel(this)),
    m_button(new QPushButton(tr("Manage..."), this))
{
    setToolTip(tr("The debugger to use for this kit."));

    QHBoxLayout *layout = new QHBoxLayout(this);
    layout->setMargin(0);
    layout->addWidget(m_label);

    // ToolButton with Menu, defaulting to 'Autodetect'.
    QMenu *buttonMenu = new QMenu(m_button);
    QAction *autoDetectAction = buttonMenu->addAction(tr("Auto-detect"));
    connect(autoDetectAction, SIGNAL(triggered()), this, SLOT(autoDetectDebugger()));
    QAction *changeAction = buttonMenu->addAction(tr("Edit..."));
    connect(changeAction, SIGNAL(triggered()), this, SLOT(showDialog()));
    m_button->setMenu(buttonMenu);

    refresh();
}

QWidget *DebuggerKitConfigWidget::buttonWidget() const
{
       return m_button;
}

QString DebuggerKitConfigWidget::displayName() const
{
    return tr("Debugger:");
}

void DebuggerKitConfigWidget::makeReadOnly()
{
    m_button->setEnabled(false);
}

void DebuggerKitConfigWidget::refresh()
{
    m_label->setText(DebuggerKitInformation::userOutput(DebuggerKitInformation::debuggerItem(m_kit)));
}

void DebuggerKitConfigWidget::autoDetectDebugger()
{
    DebuggerKitInformation::setDebuggerItem(m_kit, DebuggerKitInformation::autoDetectItem(m_kit));
}

void DebuggerKitConfigWidget::showDialog()
{
    DebuggerKitConfigDialog dialog;
    dialog.setWindowTitle(tr("Debugger for \"%1\"").arg(m_kit->displayName()));
    dialog.setDebuggerItem(DebuggerKitInformation::debuggerItem(m_kit));
    if (dialog.exec() == QDialog::Accepted)
        DebuggerKitInformation::setDebuggerItem(m_kit, dialog.item());
}

// -----------------------------------------------------------------------
// DebuggerKitConfigDialog:
// -----------------------------------------------------------------------

DebuggerKitConfigDialog::DebuggerKitConfigDialog(QWidget *parent)
    : QDialog(parent)
    , m_comboBox(new QComboBox(this))
    , m_label(new QLabel(this))
    , m_chooser(new Utils::PathChooser(this))
{
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    QVBoxLayout *layout = new QVBoxLayout(this);
    QFormLayout *formLayout = new QFormLayout;
    formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);

    m_comboBox->addItem(DebuggerKitInformation::debuggerEngineName(GdbEngineType), QVariant(int(GdbEngineType)));
    if (ProjectExplorer::Abi::hostAbi().os() == ProjectExplorer::Abi::WindowsOS) {
        m_comboBox->addItem(DebuggerKitInformation::debuggerEngineName(CdbEngineType), QVariant(int(CdbEngineType)));
    } else {
        m_comboBox->addItem(DebuggerKitInformation::debuggerEngineName(LldbEngineType), QVariant(int(LldbEngineType)));
    }
    connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(refreshLabel()));
    QLabel *engineTypeLabel = new QLabel(tr("&Engine:"));
    engineTypeLabel->setBuddy(m_comboBox);
    formLayout->addRow(engineTypeLabel, m_comboBox);

    m_label->setTextInteractionFlags(Qt::TextBrowserInteraction);
    m_label->setOpenExternalLinks(true);
    formLayout->addRow(m_label);

    QLabel *binaryLabel = new QLabel(tr("&Binary:"));
    m_chooser->setExpectedKind(Utils::PathChooser::ExistingCommand);
    binaryLabel->setBuddy(m_chooser);
    formLayout->addRow(binaryLabel, m_chooser);
    layout->addLayout(formLayout);

    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this);
    connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
    connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
    layout->addWidget(buttonBox);
}

DebuggerEngineType DebuggerKitConfigDialog::engineType() const
{
    const int index = m_comboBox->currentIndex();
    return static_cast<DebuggerEngineType>(m_comboBox->itemData(index).toInt());
}

void DebuggerKitConfigDialog::setEngineType(DebuggerEngineType et)
{
    const int size = m_comboBox->count();
    for (int i = 0; i < size; ++i) {
        if (m_comboBox->itemData(i).toInt() == et) {
            m_comboBox->setCurrentIndex(i);
            refreshLabel();
            break;
        }
    }
}

Utils::FileName DebuggerKitConfigDialog::fileName() const
{
    return m_chooser->fileName();
}

void DebuggerKitConfigDialog::setFileName(const Utils::FileName &fn)
{
    m_chooser->setFileName(fn);
}

void DebuggerKitConfigDialog::refreshLabel()
{
    QString text;
    const DebuggerEngineType type = engineType();
    switch (type) {
    case CdbEngineType: {
#ifdef Q_OS_WIN
        const bool is64bit = Utils::winIs64BitSystem();
#else
        const bool is64bit = false;
#endif
        const QString versionString = is64bit ? tr("64-bit version") : tr("32-bit version");
        //: Label text for path configuration. %2 is "x-bit version".
        text = tr("
Specify the path to the "
                  "Windows Console Debugger executable"
                  " (%2) here.
""").
                arg(QLatin1String(debuggingToolsWikiLinkC), versionString);
    }
        break;
    default:
        break;
    }
    m_label->setText(text);
    m_label->setVisible(!text.isEmpty());
    m_chooser->setCommandVersionArguments(type == CdbEngineType ?
                                          QStringList(QLatin1String("-version")) :
                                          QStringList(QLatin1String("--version")));
}

void DebuggerKitConfigDialog::setDebuggerItem(const DebuggerKitInformation::DebuggerItem &item)
{
    setEngineType(item.engineType);
    setFileName(item.binary);
}

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


<commit_before>//==============================================================================
// Compiler plugin
//==============================================================================

#include "compilerplugin.h"

//==============================================================================

namespace OpenCOR {
namespace Compiler {

//==============================================================================

PLUGININFO_FUNC CompilerPluginInfo()
{
    Descriptions descriptions;

    descriptions.insert("en", "A plugin to support code compilation");
    descriptions.insert("fr", "Une extension pour supporter la compilation de code");

    return new PluginInfo(PluginInfo::V001,
                          PluginInfo::General,
                          PluginInfo::Miscellaneous,
                          false,
                          QStringList() << "LLVM",
                          descriptions);
}

//==============================================================================

Q_EXPORT_PLUGIN2(Compiler, CompilerPlugin)

//==============================================================================

}   // namespace Compiler
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some work towards supporting KINSOL (#108).<commit_after>//==============================================================================
// Compiler plugin
//==============================================================================

#include "compilerplugin.h"

//==============================================================================

namespace OpenCOR {
namespace Compiler {

//==============================================================================

PLUGININFO_FUNC CompilerPluginInfo()
{
    Descriptions descriptions;

    descriptions.insert("en", "A plugin to support code compilation");
    descriptions.insert("fr", "Une extension pour supporter la compilation de code");

    return new PluginInfo(PluginInfo::V001,
                          PluginInfo::General,
                          PluginInfo::Miscellaneous,
                          false,
/*---GRY---
                          QStringList() << "LLVM",
*/
//---GRY--- BEGIN
                          QStringList() << "CoreSolver" << "SUNDIALS" << "LLVM",
//---GRY--- END
                          descriptions);
}

//==============================================================================

Q_EXPORT_PLUGIN2(Compiler, CompilerPlugin)

//==============================================================================

}   // namespace Compiler
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/testapp.h>
#include <vbench/test/all.h>
#include <vespa/vespalib/util/slaveproc.h>
#include <vespa/vespalib/net/crypto_engine.h>
#include <vespa/vespalib/net/tls/tls_crypto_engine.h>
#include <vespa/vespalib/test/make_tls_options_for_testing.h>
#include <vespa/vespalib/portal/portal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

using namespace vbench;
using vespalib::SlaveProc;

using InputReader = vespalib::InputReader;
using OutputWriter = vespalib::OutputWriter;
using Portal = vespalib::Portal;

auto null_crypto = std::make_shared<vespalib::NullCryptoEngine>();
auto tls_opts = vespalib::test::make_tls_options_for_testing();
auto tls_crypto = std::make_shared<vespalib::TlsCryptoEngine>(tls_opts);

void write_file(const vespalib::string &file_name, const vespalib::string &content) {
    int fd = creat(file_name.c_str(), 0600);
    ASSERT_TRUE(fd >= 0);
    ssize_t res = write(fd, content.data(), content.size());
    ASSERT_EQUAL(res, ssize_t(content.size()));
    int res2 = close(fd);
    ASSERT_EQUAL(res2, 0);
}

TEST("vbench usage") {
    std::string out;
    EXPECT_FALSE(SlaveProc::run("../../apps/vbench/vbench_app", out));
    fprintf(stderr, "%s\n", out.c_str());
}

struct MyGet : vespalib::Portal::GetHandler {
    std::atomic<size_t> cnt;
    void get(vespalib::Portal::GetRequest request) override {
        ++cnt;
        request.respond_with_content("text/plain", "data");
    };
};

struct Servers {
    MyGet my_get;
    MyGet my_tls_get;
    Portal::SP portal;
    Portal::SP tls_portal;
    Portal::Token::UP root;
    Portal::Token::UP tls_root;
    Servers() : my_get(), my_tls_get(),
                portal(Portal::create(null_crypto, 0)),
                tls_portal(Portal::create(tls_crypto, 0)),
                root(portal->bind("/", my_get)),
                tls_root(tls_portal->bind("/", my_tls_get))
    {
        write_file("ca_certs.pem", tls_opts.ca_certs_pem());
        write_file("certs.pem", tls_opts.cert_chain_pem());
        write_file("test.key", tls_opts.private_key_pem());
    }
};

TEST_MT_F("run vbench", 2, Servers()) {
    if (thread_id == 0) {
        std::string out;
        EXPECT_TRUE(SlaveProc::run(strfmt("sed 's/_LOCAL_PORT_/%d/' vbench.cfg.template > vbench.cfg", f1.portal->listen_port()).c_str()));
        EXPECT_TRUE(SlaveProc::run("../../apps/vbench/vbench_app run vbench.cfg 2> vbench.out", out));
        fprintf(stderr, "null crypto: %s\n", out.c_str());
        EXPECT_EQUAL(f1.my_get.cnt, 144u);
    } else {
        std::string tls_out;
        EXPECT_TRUE(SlaveProc::run(strfmt("sed 's/_LOCAL_PORT_/%d/' vbench.tls.cfg.template > vbench.tls.cfg", f1.tls_portal->listen_port()).c_str()));
        EXPECT_TRUE(SlaveProc::run("../../apps/vbench/vbench_app run vbench.tls.cfg 2> vbench.tls.out", tls_out));
        fprintf(stderr, "tls crypto: %s\n", tls_out.c_str());
        EXPECT_EQUAL(f1.my_tls_get.cnt, 144u);
    }
}

TEST_MAIN_WITH_PROCESS_PROXY() { TEST_RUN_ALL(); }
<commit_msg>require fewer GET requests<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/testapp.h>
#include <vbench/test/all.h>
#include <vespa/vespalib/util/slaveproc.h>
#include <vespa/vespalib/net/crypto_engine.h>
#include <vespa/vespalib/net/tls/tls_crypto_engine.h>
#include <vespa/vespalib/test/make_tls_options_for_testing.h>
#include <vespa/vespalib/portal/portal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

using namespace vbench;
using vespalib::SlaveProc;

using InputReader = vespalib::InputReader;
using OutputWriter = vespalib::OutputWriter;
using Portal = vespalib::Portal;

auto null_crypto = std::make_shared<vespalib::NullCryptoEngine>();
auto tls_opts = vespalib::test::make_tls_options_for_testing();
auto tls_crypto = std::make_shared<vespalib::TlsCryptoEngine>(tls_opts);

void write_file(const vespalib::string &file_name, const vespalib::string &content) {
    int fd = creat(file_name.c_str(), 0600);
    ASSERT_TRUE(fd >= 0);
    ssize_t res = write(fd, content.data(), content.size());
    ASSERT_EQUAL(res, ssize_t(content.size()));
    int res2 = close(fd);
    ASSERT_EQUAL(res2, 0);
}

TEST("vbench usage") {
    std::string out;
    EXPECT_FALSE(SlaveProc::run("../../apps/vbench/vbench_app", out));
    fprintf(stderr, "%s\n", out.c_str());
}

struct MyGet : vespalib::Portal::GetHandler {
    std::atomic<size_t> cnt;
    void get(vespalib::Portal::GetRequest request) override {
        ++cnt;
        request.respond_with_content("text/plain", "data");
    };
};

struct Servers {
    MyGet my_get;
    MyGet my_tls_get;
    Portal::SP portal;
    Portal::SP tls_portal;
    Portal::Token::UP root;
    Portal::Token::UP tls_root;
    Servers() : my_get(), my_tls_get(),
                portal(Portal::create(null_crypto, 0)),
                tls_portal(Portal::create(tls_crypto, 0)),
                root(portal->bind("/", my_get)),
                tls_root(tls_portal->bind("/", my_tls_get))
    {
        write_file("ca_certs.pem", tls_opts.ca_certs_pem());
        write_file("certs.pem", tls_opts.cert_chain_pem());
        write_file("test.key", tls_opts.private_key_pem());
    }
};

TEST_MT_F("run vbench", 2, Servers()) {
    if (thread_id == 0) {
        std::string out;
        EXPECT_TRUE(SlaveProc::run(strfmt("sed 's/_LOCAL_PORT_/%d/' vbench.cfg.template > vbench.cfg", f1.portal->listen_port()).c_str()));
        EXPECT_TRUE(SlaveProc::run("../../apps/vbench/vbench_app run vbench.cfg 2> vbench.out", out));
        fprintf(stderr, "null crypto: %s\n", out.c_str());
        EXPECT_GREATER(f1.my_get.cnt, 10u);
    } else {
        std::string tls_out;
        EXPECT_TRUE(SlaveProc::run(strfmt("sed 's/_LOCAL_PORT_/%d/' vbench.tls.cfg.template > vbench.tls.cfg", f1.tls_portal->listen_port()).c_str()));
        EXPECT_TRUE(SlaveProc::run("../../apps/vbench/vbench_app run vbench.tls.cfg 2> vbench.tls.out", tls_out));
        fprintf(stderr, "tls crypto: %s\n", tls_out.c_str());
        EXPECT_GREATER(f1.my_tls_get.cnt, 10u);
    }
}

TEST_MAIN_WITH_PROCESS_PROXY() { TEST_RUN_ALL(); }
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2004-2007 Marc Boris Duerner
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * As a special exception, you may use this file as part of a free
 * software library without restriction. Specifically, if other files
 * instantiate templates or use macros or inline functions from this
 * file, or you compile this file and link it with other files to
 * produce an executable, this file does not by itself cause the
 * resulting executable to be covered by the GNU General Public
 * License. This exception does not however invalidate any other
 * reasons why the executable file might be covered by the GNU Library
 * General Public License.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <cxxtools/facets.h>

locale::id numpunct<cxxtools::Char>::id;

numpunct<cxxtools::Char>::numpunct(size_t refs)
: locale::facet(refs)
{ }

numpunct<cxxtools::Char>::~numpunct()
{ }

cxxtools::Char numpunct<cxxtools::Char>::decimal_point() const
{ return this->do_decimal_point(); }

cxxtools::Char numpunct<cxxtools::Char>::thousands_sep() const
{ return this->do_thousands_sep(); }

string numpunct<cxxtools::Char>::grouping() const
{ return this->do_grouping(); }

cxxtools::String numpunct<cxxtools::Char>::truename() const
{ return this->do_truename(); }

cxxtools::String numpunct<cxxtools::Char>::falsename() const
{ return this->do_falsename(); }

cxxtools::Char numpunct<cxxtools::Char>::do_decimal_point() const
{ return '.'; }

cxxtools::Char numpunct<cxxtools::Char>::do_thousands_sep() const
{ return ','; }

std::string numpunct<cxxtools::Char>::do_grouping() const
{ return ""; }

cxxtools::String numpunct<cxxtools::Char>::do_truename() const
{
    static const cxxtools::Char truename[] = {'t', 'r', 'u', 'e', '\0'};
    return truename;
}

cxxtools::String numpunct<cxxtools::Char>::do_falsename() const
{
    static const cxxtools::Char falsename[] = {'f', 'a', 'l', 's', 'e', '\0'};
    return falsename;
}

}
<commit_msg>revert to 1252<commit_after>/*
 * Copyright (C) 2004-2007 Marc Boris Duerner
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * As a special exception, you may use this file as part of a free
 * software library without restriction. Specifically, if other files
 * instantiate templates or use macros or inline functions from this
 * file, or you compile this file and link it with other files to
 * produce an executable, this file does not by itself cause the
 * resulting executable to be covered by the GNU General Public
 * License. This exception does not however invalidate any other
 * reasons why the executable file might be covered by the GNU Library
 * General Public License.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

namespace std {

locale::id numpunct<cxxtools::Char>::id;

numpunct<cxxtools::Char>::numpunct(size_t refs)
: locale::facet(refs)
{ }

numpunct<cxxtools::Char>::~numpunct()
{ }

cxxtools::Char numpunct<cxxtools::Char>::decimal_point() const
{ return this->do_decimal_point(); }

cxxtools::Char numpunct<cxxtools::Char>::thousands_sep() const
{ return this->do_thousands_sep(); }

string numpunct<cxxtools::Char>::grouping() const
{ return this->do_grouping(); }

cxxtools::String numpunct<cxxtools::Char>::truename() const
{ return this->do_truename(); }

cxxtools::String numpunct<cxxtools::Char>::falsename() const
{ return this->do_falsename(); }

cxxtools::Char numpunct<cxxtools::Char>::do_decimal_point() const
{ return '.'; }

cxxtools::Char numpunct<cxxtools::Char>::do_thousands_sep() const
{ return ','; }

std::string numpunct<cxxtools::Char>::do_grouping() const
{ return ""; }

cxxtools::String numpunct<cxxtools::Char>::do_truename() const
{
    static const cxxtools::Char truename[] = {'t', 'r', 'u', 'e', '\0'};
    return truename;
}

cxxtools::String numpunct<cxxtools::Char>::do_falsename() const
{
    static const cxxtools::Char falsename[] = {'f', 'a', 'l', 's', 'e', '\0'};
    return falsename;
}

}
<|endoftext|>


<commit_before>#include "single_checker_l1_norm.h"

namespace bart {

namespace convergence {

namespace flux {

bool SingleCheckerL1Norm::CheckIfConverged(data::Flux &current_iteration,
                                                data::Flux &previous_iteration) {
  data::Flux difference{current_iteration};
  difference -= previous_iteration;
  delta_ = difference.l1_norm()/current_iteration.l1_norm();
  is_converged_ = delta_ <= max_delta_;
  return is_converged_;
}

} // namespace flux

} // namespace convergence

} // namespace bart
<commit_msg>fixed indentation<commit_after>#include "single_checker_l1_norm.h"

namespace bart {

namespace convergence {

namespace flux {

bool SingleCheckerL1Norm::CheckIfConverged(data::Flux &current_iteration,
                                           data::Flux &previous_iteration) {
  data::Flux difference{current_iteration};
  difference -= previous_iteration;
  delta_ = difference.l1_norm()/current_iteration.l1_norm();
  is_converged_ = delta_ <= max_delta_;
  return is_converged_;
}

} // namespace flux

} // namespace convergence

} // namespace bart
<|endoftext|>


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

#include <inviwo/core/network/processornetworkevaluator.h>
#include <inviwo/core/processors/canvasprocessor.h>
#include <inviwo/core/processors/progressbarowner.h>
#include <inviwo/core/util/assertion.h>
#include <inviwo/core/util/canvas.h>
#include <inviwo/core/util/rendercontext.h>

namespace inviwo {

std::map<ProcessorNetwork*, ProcessorNetworkEvaluator*>
    ProcessorNetworkEvaluator::processorNetworkEvaluators_;

ProcessorNetworkEvaluator::ProcessorNetworkEvaluator(ProcessorNetwork* processorNetwork)
    : processorNetwork_(processorNetwork)
    , evaulationQueued_(false)
    , evaluationDisabled_(false)
    , exceptionHandler_(StandardExceptionHandler()) {
    ivwAssert(
        processorNetworkEvaluators_.find(processorNetwork) == processorNetworkEvaluators_.end(),
        "A ProcessorNetworkEvaluator for the given ProcessorNetwork is already created");

    processorNetworkEvaluators_[processorNetwork] = this;
    processorNetwork_->addObserver(this);
}

ProcessorNetworkEvaluator::~ProcessorNetworkEvaluator() {
    std::map<ProcessorNetwork*, ProcessorNetworkEvaluator*>::iterator it =
        processorNetworkEvaluators_.find(processorNetwork_);

    if (it != processorNetworkEvaluators_.end()) processorNetworkEvaluators_.erase(it);
}

void ProcessorNetworkEvaluator::setProcessorVisited(Processor* processor, bool visited) {
    ProcMapIt it = processorStates_.find(processor);
    if (it != processorStates_.end()) it->second.visited = visited;
}

bool ProcessorNetworkEvaluator::hasBeenVisited(Processor* processor) const {
    const_ProcMapIt it = processorStates_.find(processor);
    if (it != processorStates_.end())
        return it->second.visited;
    else
        return false;
}

void ProcessorNetworkEvaluator::setPropertyVisited(Property* property, bool visited) {
    PropertyMapIt it = propertiesVisited_.find(property);
    if (it != propertiesVisited_.end()) it->second.visited = visited;
}

bool ProcessorNetworkEvaluator::hasBeenVisited(Property* property) const {
    const_PropertyMapIt it = propertiesVisited_.find(property);
    if (it != propertiesVisited_.end())
        return it->second.visited;
    else
        return false;
}

const ProcessorNetworkEvaluator::ProcessorList& ProcessorNetworkEvaluator::getStoredPredecessors(
    Processor* processor) const {
    const_ProcMapIt it = processorStates_.find(processor);
    if (it != processorStates_.end()) {
        return it->second.pred;
    } else {
        // processor not found, return reference to empty list of dummy element
        return processorStates_.find(nullptr)->second.pred;
    }
}

ProcessorNetworkEvaluator::ProcessorList ProcessorNetworkEvaluator::getDirectPredecessors(
    Processor* processor) const {
    ProcessorList predecessors;

    for (auto port : processor->getInports()) {
        if (!port->isConnected()) continue;

        for (auto connectedPort : port->getConnectedOutports()) {
            if (connectedPort) predecessors.insert(connectedPort->getProcessor());
        }
    }

    return predecessors;
}

void ProcessorNetworkEvaluator::traversePredecessors(Processor* processor) {
    if (!hasBeenVisited(processor)) {
        setProcessorVisited(processor);

        for (auto p : getStoredPredecessors(processor)) traversePredecessors(p);

        processorsSorted_.push_back(processor);
    }
}

void ProcessorNetworkEvaluator::determineProcessingOrder() {
    std::vector<Processor*> endProcessors;

    for (auto processor : processorNetwork_->getProcessors()) {
        if (processor->isEndProcessor()) endProcessors.push_back(processor);
    }

    // perform topological sorting and store processor order
    // in processorsSorted_
    processorsSorted_.clear();
    resetProcessorVisitedStates();

    for (auto processor : endProcessors) traversePredecessors(processor);
}

void ProcessorNetworkEvaluator::updateProcessorStates() {
    std::vector<Processor*> endProcessors;

    processorStates_.clear();
    // insert dummy processor to be able to return a reference to an
    // empty predecessor list, if a processor does not exist (getStoredPredecessors())
    processorStates_.insert(ProcMapPair(nullptr, ProcessorState()));

    // update all processor states, i.e. collecting predecessors
    for (auto processor : processorNetwork_->getProcessors()) {
        // register processor in global state map
        if (!processorStates_.insert(ProcMapPair(processor, ProcessorState(getDirectPredecessors(
                                                                processor)))).second)
            LogError("Processor State was already registered.");

        if (processor->isEndProcessor()) endProcessors.push_back(processor);
    }

    // perform topological sorting and store processor order in processorsSorted_
    processorsSorted_.clear();

    for (auto processor : endProcessors) traversePredecessors(processor);
}

void ProcessorNetworkEvaluator::resetProcessorVisitedStates() {
    for (auto& state : processorStates_) state.second.visited = false;
}

void ProcessorNetworkEvaluator::setExceptionHandler(ExceptionHandler handler) {
    exceptionHandler_ = handler;
}

void ProcessorNetworkEvaluator::onProcessorInvalidationEnd(Processor* p) {
    processorNetwork_->onProcessorInvalidationEnd(p);
    p->ProcessorObservable::removeObserver(this);

    if (evaulationQueued_) {
        evaulationQueued_ = false;
        requestEvaluate();
    }
}

void ProcessorNetworkEvaluator::onProcessorNetworkEvaluateRequest() {
    // Direct request, thus we don't want to queue the evaluation anymore
    if (evaulationQueued_) evaulationQueued_ = false;

    requestEvaluate();
}

void ProcessorNetworkEvaluator::onProcessorNetworkUnlocked() {
    // Only evaluate if an evaluation is queued or the network is modified
    if (evaulationQueued_ || processorNetwork_->isModified()) {
        evaulationQueued_ = false;
        requestEvaluate();
    }
}

void ProcessorNetworkEvaluator::disableEvaluation() { evaluationDisabled_ = true; }

void ProcessorNetworkEvaluator::enableEvaluation() {
    evaluationDisabled_ = false;

    if (evaulationQueued_) {
        evaulationQueued_ = false;
        requestEvaluate();
    }
}

ProcessorNetworkEvaluator*
ProcessorNetworkEvaluator::getProcessorNetworkEvaluatorForProcessorNetwork(
    ProcessorNetwork* network) {
    std::map<ProcessorNetwork*, ProcessorNetworkEvaluator*>::iterator it =
        processorNetworkEvaluators_.find(network);

    if (it == processorNetworkEvaluators_.end()) return new ProcessorNetworkEvaluator(network);

    return it->second;
}

void ProcessorNetworkEvaluator::requestEvaluate() {
    // evaluation has been triggered but is currently queued
    // requestEvaluate needs to be called with evaulationQueued_ false to continue.
    if (evaulationQueued_) return;

    // wait for linking to finish
    if (processorNetwork_->isLinking()) {
        evaulationQueued_ = true;
        return;
    }

    // evaluation disabled
    if (processorNetwork_->islocked() || evaluationDisabled_) {
        evaulationQueued_ = true;
        return;
    }

    // wait for invalidation to finish before evaluating
    if (processorNetwork_->isInvalidating()) {
        evaulationQueued_ = true;
        return;
    }

    evaulationQueued_ = false;
    // if we haven't returned yet, perform evaluation of the network
    evaluate();
}

void ProcessorNetworkEvaluator::evaluate() {
    // lock processor network to avoid concurrent evaluation
    NetworkLock lock(processorNetwork_);

    RenderContext::getPtr()->activateDefaultRenderContext();

    // if the processor network has changed determine the new processor order
    if (processorNetwork_->isModified()) {
        // make sure all processor are initialized
        for (auto p : processorNetwork_->getProcessors()) {
            try {
                if (!p->isInitialized()) p->initialize();
            } catch (Exception& e) {
                exceptionHandler_(IvwContext);
            }
        }
        processorNetwork_->setModified(false);

        // network topology has changed, update internal processor states
        updateProcessorStates();
    }

    for (auto processor : processorsSorted_) {
        if (!processor->isValid()) {
            if (processor->isReady()) {
                try {
                    // re-initialize resources (e.g., shaders) if necessary
                    if (processor->getInvalidationLevel() >= INVALID_RESOURCES) {
                        processor->initializeResources();
                    }
                    // call onChange for all invalid inports
                    for (auto inport : processor->getInports()) {
                        inport->callOnChangeIfChanged();
                    }
                } catch (Exception& e) {
                    exceptionHandler_(IvwContext);
                    processor->setValid();
                    continue;
                }

                #if IVW_PROFILING
                processor->notifyObserversAboutToProcess(processor);
                #endif

                try {
                    // do the actual processing
                    processor->process();
                } catch (Exception& e) {
                    exceptionHandler_(IvwContext);
                }
                // set processor as valid
                processor->setValid();

                #if IVW_PROFILING
                processor->notifyObserversFinishedProcess(processor);
                #endif
            } else {
                processor->doIfNotReady();
            }
        }
    }

    resetProcessorVisitedStates();
}

}  // namespace
<commit_msg>Core: Processor Network Evaluator Should behave much better when throwing out if the evaluate function now. closes inviwo/inviwo-dev#865<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2012-2015 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <inviwo/core/network/processornetworkevaluator.h>
#include <inviwo/core/processors/canvasprocessor.h>
#include <inviwo/core/processors/progressbarowner.h>
#include <inviwo/core/util/assertion.h>
#include <inviwo/core/util/canvas.h>
#include <inviwo/core/util/rendercontext.h>
#include <inviwo/core/util/raiiutils.h>

namespace inviwo {

std::map<ProcessorNetwork*, ProcessorNetworkEvaluator*>
    ProcessorNetworkEvaluator::processorNetworkEvaluators_;

ProcessorNetworkEvaluator::ProcessorNetworkEvaluator(ProcessorNetwork* processorNetwork)
    : processorNetwork_(processorNetwork)
    , evaulationQueued_(false)
    , evaluationDisabled_(false)
    , exceptionHandler_(StandardExceptionHandler()) {
    ivwAssert(
        processorNetworkEvaluators_.find(processorNetwork) == processorNetworkEvaluators_.end(),
        "A ProcessorNetworkEvaluator for the given ProcessorNetwork is already created");

    processorNetworkEvaluators_[processorNetwork] = this;
    processorNetwork_->addObserver(this);
}

ProcessorNetworkEvaluator::~ProcessorNetworkEvaluator() {
    std::map<ProcessorNetwork*, ProcessorNetworkEvaluator*>::iterator it =
        processorNetworkEvaluators_.find(processorNetwork_);

    if (it != processorNetworkEvaluators_.end()) processorNetworkEvaluators_.erase(it);
}

void ProcessorNetworkEvaluator::setProcessorVisited(Processor* processor, bool visited) {
    ProcMapIt it = processorStates_.find(processor);
    if (it != processorStates_.end()) it->second.visited = visited;
}

bool ProcessorNetworkEvaluator::hasBeenVisited(Processor* processor) const {
    const_ProcMapIt it = processorStates_.find(processor);
    if (it != processorStates_.end())
        return it->second.visited;
    else
        return false;
}

void ProcessorNetworkEvaluator::setPropertyVisited(Property* property, bool visited) {
    PropertyMapIt it = propertiesVisited_.find(property);
    if (it != propertiesVisited_.end()) it->second.visited = visited;
}

bool ProcessorNetworkEvaluator::hasBeenVisited(Property* property) const {
    const_PropertyMapIt it = propertiesVisited_.find(property);
    if (it != propertiesVisited_.end())
        return it->second.visited;
    else
        return false;
}

const ProcessorNetworkEvaluator::ProcessorList& ProcessorNetworkEvaluator::getStoredPredecessors(
    Processor* processor) const {
    const_ProcMapIt it = processorStates_.find(processor);
    if (it != processorStates_.end()) {
        return it->second.pred;
    } else {
        // processor not found, return reference to empty list of dummy element
        return processorStates_.find(nullptr)->second.pred;
    }
}

ProcessorNetworkEvaluator::ProcessorList ProcessorNetworkEvaluator::getDirectPredecessors(
    Processor* processor) const {
    ProcessorList predecessors;

    for (auto port : processor->getInports()) {
        if (!port->isConnected()) continue;

        for (auto connectedPort : port->getConnectedOutports()) {
            if (connectedPort) predecessors.insert(connectedPort->getProcessor());
        }
    }

    return predecessors;
}

void ProcessorNetworkEvaluator::traversePredecessors(Processor* processor) {
    if (!hasBeenVisited(processor)) {
        setProcessorVisited(processor);

        for (auto p : getStoredPredecessors(processor)) traversePredecessors(p);

        processorsSorted_.push_back(processor);
    }
}

void ProcessorNetworkEvaluator::determineProcessingOrder() {
    std::vector<Processor*> endProcessors;

    for (auto processor : processorNetwork_->getProcessors()) {
        if (processor->isEndProcessor()) endProcessors.push_back(processor);
    }

    // perform topological sorting and store processor order
    // in processorsSorted_
    processorsSorted_.clear();
    resetProcessorVisitedStates();

    for (auto processor : endProcessors) traversePredecessors(processor);
}

void ProcessorNetworkEvaluator::updateProcessorStates() {
    std::vector<Processor*> endProcessors;

    processorStates_.clear();
    // insert dummy processor to be able to return a reference to an
    // empty predecessor list, if a processor does not exist (getStoredPredecessors())
    processorStates_.insert(ProcMapPair(nullptr, ProcessorState()));

    // update all processor states, i.e. collecting predecessors
    for (auto processor : processorNetwork_->getProcessors()) {
        // register processor in global state map
        if (!processorStates_.insert(ProcMapPair(processor, ProcessorState(getDirectPredecessors(
                                                                processor)))).second)
            LogError("Processor State was already registered.");

        if (processor->isEndProcessor()) endProcessors.push_back(processor);
    }

    // perform topological sorting and store processor order in processorsSorted_
    processorsSorted_.clear();

    for (auto processor : endProcessors) traversePredecessors(processor);
}

void ProcessorNetworkEvaluator::resetProcessorVisitedStates() {
    for (auto& state : processorStates_) state.second.visited = false;
}

void ProcessorNetworkEvaluator::setExceptionHandler(ExceptionHandler handler) {
    exceptionHandler_ = handler;
}

void ProcessorNetworkEvaluator::onProcessorInvalidationEnd(Processor* p) {
    processorNetwork_->onProcessorInvalidationEnd(p);
    p->ProcessorObservable::removeObserver(this);

    if (evaulationQueued_) {
        evaulationQueued_ = false;
        requestEvaluate();
    }
}

void ProcessorNetworkEvaluator::onProcessorNetworkEvaluateRequest() {
    // Direct request, thus we don't want to queue the evaluation anymore
    if (evaulationQueued_) evaulationQueued_ = false;

    requestEvaluate();
}

void ProcessorNetworkEvaluator::onProcessorNetworkUnlocked() {
    // Only evaluate if an evaluation is queued or the network is modified
    if (evaulationQueued_ || processorNetwork_->isModified()) {
        evaulationQueued_ = false;
        requestEvaluate();
    }
}

void ProcessorNetworkEvaluator::disableEvaluation() { evaluationDisabled_ = true; }

void ProcessorNetworkEvaluator::enableEvaluation() {
    evaluationDisabled_ = false;

    if (evaulationQueued_) {
        evaulationQueued_ = false;
        requestEvaluate();
    }
}

ProcessorNetworkEvaluator*
ProcessorNetworkEvaluator::getProcessorNetworkEvaluatorForProcessorNetwork(
    ProcessorNetwork* network) {
    std::map<ProcessorNetwork*, ProcessorNetworkEvaluator*>::iterator it =
        processorNetworkEvaluators_.find(network);

    if (it == processorNetworkEvaluators_.end()) return new ProcessorNetworkEvaluator(network);

    return it->second;
}

void ProcessorNetworkEvaluator::requestEvaluate() {
    // evaluation has been triggered but is currently queued
    // requestEvaluate needs to be called with evaulationQueued_ false to continue.
    if (evaulationQueued_) return;

    // wait for linking to finish
    if (processorNetwork_->isLinking()) {
        evaulationQueued_ = true;
        return;
    }

    // evaluation disabled
    if (processorNetwork_->islocked() || evaluationDisabled_) {
        evaulationQueued_ = true;
        return;
    }

    // wait for invalidation to finish before evaluating
    if (processorNetwork_->isInvalidating()) {
        evaulationQueued_ = true;
        return;
    }

    evaulationQueued_ = false;
    // if we haven't returned yet, perform evaluation of the network
    evaluate();
}

void ProcessorNetworkEvaluator::evaluate() {
    // lock processor network to avoid concurrent evaluation
    NetworkLock lock(processorNetwork_);
    util::OnScopeExit reset([this](){resetProcessorVisitedStates();});

    RenderContext::getPtr()->activateDefaultRenderContext();

    // if the processor network has changed determine the new processor order
    if (processorNetwork_->isModified()) {
        // make sure all processor are initialized
        for (auto p : processorNetwork_->getProcessors()) {
            try {
                if (!p->isInitialized()) p->initialize();
            } catch (Exception& e) {
                exceptionHandler_(IvwContext);
            }
        }
        processorNetwork_->setModified(false);

        // network topology has changed, update internal processor states
        updateProcessorStates();
    }

    for (auto processor : processorsSorted_) {
        if (!processor->isValid()) {
            if (processor->isReady()) {
                try {
                    // re-initialize resources (e.g., shaders) if necessary
                    if (processor->getInvalidationLevel() >= INVALID_RESOURCES) {
                        processor->initializeResources();
                    }
                    // call onChange for all invalid inports
                    for (auto inport : processor->getInports()) {
                        inport->callOnChangeIfChanged();
                    }
                } catch (Exception& e) {
                    exceptionHandler_(IvwContext);
                    processor->setValid();
                    continue;
                }

                #if IVW_PROFILING
                processor->notifyObserversAboutToProcess(processor);
                #endif

                try {
                    // do the actual processing
                    processor->process();
                } catch (Exception& e) {
                    exceptionHandler_(IvwContext);
                }
                // set processor as valid
                processor->setValid();

                #if IVW_PROFILING
                processor->notifyObserversFinishedProcess(processor);
                #endif
            } else {
                processor->doIfNotReady();
            }
        }
    }
}

}  // namespace
<|endoftext|>


<commit_before>/*
* OctetString
* (C) 1999-2007 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/symkey.h>
#include <botan/rng.h>
#include <botan/hex.h>
#include <algorithm>

namespace Botan {

/*
* Create an OctetString from RNG output
*/
OctetString::OctetString(RandomNumberGenerator& rng,
                         size_t len)
   {
   rng.random_vec(m_data, len);
   }

/*
* Create an OctetString from a hex string
*/
OctetString::OctetString(const std::string& hex_string)
   {
   if(!hex_string.empty())
      {
      m_data.resize(1 + hex_string.length() / 2);
      m_data.resize(hex_decode(m_data.data(), hex_string));
      }
   }

/*
* Create an OctetString from a byte string
*/
OctetString::OctetString(const uint8_t in[], size_t n)
   {
   m_data.assign(in, in + n);
   }

namespace {

alignas(64) const uint8_t ODD_PARITY[256] = {
   0x01, 0x01, 0x02, 0x02, 0x04, 0x04, 0x07, 0x07, 0x08, 0x08, 0x0B, 0x0B,
   0x0D, 0x0D, 0x0E, 0x0E, 0x10, 0x10, 0x13, 0x13, 0x15, 0x15, 0x16, 0x16,
   0x19, 0x19, 0x1A, 0x1A, 0x1C, 0x1C, 0x1F, 0x1F, 0x20, 0x20, 0x23, 0x23,
   0x25, 0x25, 0x26, 0x26, 0x29, 0x29, 0x2A, 0x2A, 0x2C, 0x2C, 0x2F, 0x2F,
   0x31, 0x31, 0x32, 0x32, 0x34, 0x34, 0x37, 0x37, 0x38, 0x38, 0x3B, 0x3B,
   0x3D, 0x3D, 0x3E, 0x3E, 0x40, 0x40, 0x43, 0x43, 0x45, 0x45, 0x46, 0x46,
   0x49, 0x49, 0x4A, 0x4A, 0x4C, 0x4C, 0x4F, 0x4F, 0x51, 0x51, 0x52, 0x52,
   0x54, 0x54, 0x57, 0x57, 0x58, 0x58, 0x5B, 0x5B, 0x5D, 0x5D, 0x5E, 0x5E,
   0x61, 0x61, 0x62, 0x62, 0x64, 0x64, 0x67, 0x67, 0x68, 0x68, 0x6B, 0x6B,
   0x6D, 0x6D, 0x6E, 0x6E, 0x70, 0x70, 0x73, 0x73, 0x75, 0x75, 0x76, 0x76,
   0x79, 0x79, 0x7A, 0x7A, 0x7C, 0x7C, 0x7F, 0x7F, 0x80, 0x80, 0x83, 0x83,
   0x85, 0x85, 0x86, 0x86, 0x89, 0x89, 0x8A, 0x8A, 0x8C, 0x8C, 0x8F, 0x8F,
   0x91, 0x91, 0x92, 0x92, 0x94, 0x94, 0x97, 0x97, 0x98, 0x98, 0x9B, 0x9B,
   0x9D, 0x9D, 0x9E, 0x9E, 0xA1, 0xA1, 0xA2, 0xA2, 0xA4, 0xA4, 0xA7, 0xA7,
   0xA8, 0xA8, 0xAB, 0xAB, 0xAD, 0xAD, 0xAE, 0xAE, 0xB0, 0xB0, 0xB3, 0xB3,
   0xB5, 0xB5, 0xB6, 0xB6, 0xB9, 0xB9, 0xBA, 0xBA, 0xBC, 0xBC, 0xBF, 0xBF,
   0xC1, 0xC1, 0xC2, 0xC2, 0xC4, 0xC4, 0xC7, 0xC7, 0xC8, 0xC8, 0xCB, 0xCB,
   0xCD, 0xCD, 0xCE, 0xCE, 0xD0, 0xD0, 0xD3, 0xD3, 0xD5, 0xD5, 0xD6, 0xD6,
   0xD9, 0xD9, 0xDA, 0xDA, 0xDC, 0xDC, 0xDF, 0xDF, 0xE0, 0xE0, 0xE3, 0xE3,
   0xE5, 0xE5, 0xE6, 0xE6, 0xE9, 0xE9, 0xEA, 0xEA, 0xEC, 0xEC, 0xEF, 0xEF,
   0xF1, 0xF1, 0xF2, 0xF2, 0xF4, 0xF4, 0xF7, 0xF7, 0xF8, 0xF8, 0xFB, 0xFB,
   0xFD, 0xFD, 0xFE, 0xFE };

}

/*
* Set the parity of each key byte to odd
*/
void OctetString::set_odd_parity()
   {
   for(size_t j = 0; j != m_data.size(); ++j)
      m_data[j] = ODD_PARITY[m_data[j]];
   }

/*
* Hex encode an OctetString
*/
std::string OctetString::to_string() const
   {
   return hex_encode(m_data.data(), m_data.size());
   }

/*
* XOR Operation for OctetStrings
*/
OctetString& OctetString::operator^=(const OctetString& k)
   {
   if(&k == this) { zeroise(m_data); return (*this); }
   xor_buf(m_data.data(), k.begin(), std::min(length(), k.length()));
   return (*this);
   }

/*
* Equality Operation for OctetStrings
*/
bool operator==(const OctetString& s1, const OctetString& s2)
   {
   return (s1.bits_of() == s2.bits_of());
   }

/*
* Unequality Operation for OctetStrings
*/
bool operator!=(const OctetString& s1, const OctetString& s2)
   {
   return !(s1 == s2);
   }

/*
* Append Operation for OctetStrings
*/
OctetString operator+(const OctetString& k1, const OctetString& k2)
   {
   secure_vector<uint8_t> out;
   out += k1.bits_of();
   out += k2.bits_of();
   return OctetString(out);
   }

/*
* XOR Operation for OctetStrings
*/
OctetString operator^(const OctetString& k1, const OctetString& k2)
   {
   secure_vector<uint8_t> out(std::max(k1.length(), k2.length()));

   copy_mem(out.data(), k1.begin(), k1.length());
   xor_buf(out.data(), k2.begin(), k2.length());
   return OctetString(out);
   }

}
<commit_msg>Don't use a lookup table for parity calculations<commit_after>/*
* OctetString
* (C) 1999-2007 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/symkey.h>
#include <botan/rng.h>
#include <botan/hex.h>
#include <algorithm>

namespace Botan {

/*
* Create an OctetString from RNG output
*/
OctetString::OctetString(RandomNumberGenerator& rng,
                         size_t len)
   {
   rng.random_vec(m_data, len);
   }

/*
* Create an OctetString from a hex string
*/
OctetString::OctetString(const std::string& hex_string)
   {
   if(!hex_string.empty())
      {
      m_data.resize(1 + hex_string.length() / 2);
      m_data.resize(hex_decode(m_data.data(), hex_string));
      }
   }

/*
* Create an OctetString from a byte string
*/
OctetString::OctetString(const uint8_t in[], size_t n)
   {
   m_data.assign(in, in + n);
   }

namespace {

uint8_t odd_parity_of(uint8_t x)
   {
   x &= 0xFE;
   uint8_t parity = 1;
   for(size_t i = 1; i != 8; ++i)
      parity ^= (x >> i) & 1;
   return x ^ parity;
   }

}

/*
* Set the parity of each key byte to odd
*/
void OctetString::set_odd_parity()
   {
   for(size_t j = 0; j != m_data.size(); ++j)
      m_data[j] = odd_parity_of(m_data[j]);
   }

/*
* Hex encode an OctetString
*/
std::string OctetString::to_string() const
   {
   return hex_encode(m_data.data(), m_data.size());
   }

/*
* XOR Operation for OctetStrings
*/
OctetString& OctetString::operator^=(const OctetString& k)
   {
   if(&k == this) { zeroise(m_data); return (*this); }
   xor_buf(m_data.data(), k.begin(), std::min(length(), k.length()));
   return (*this);
   }

/*
* Equality Operation for OctetStrings
*/
bool operator==(const OctetString& s1, const OctetString& s2)
   {
   return (s1.bits_of() == s2.bits_of());
   }

/*
* Unequality Operation for OctetStrings
*/
bool operator!=(const OctetString& s1, const OctetString& s2)
   {
   return !(s1 == s2);
   }

/*
* Append Operation for OctetStrings
*/
OctetString operator+(const OctetString& k1, const OctetString& k2)
   {
   secure_vector<uint8_t> out;
   out += k1.bits_of();
   out += k2.bits_of();
   return OctetString(out);
   }

/*
* XOR Operation for OctetStrings
*/
OctetString operator^(const OctetString& k1, const OctetString& k2)
   {
   secure_vector<uint8_t> out(std::max(k1.length(), k2.length()));

   copy_mem(out.data(), k1.begin(), k1.length());
   xor_buf(out.data(), k2.begin(), k2.length());
   return OctetString(out);
   }

}
<|endoftext|>