<commit_before>/*****************************************************************************
 * preferences.cpp: preferences window for the kde gui
 *****************************************************************************
 * Copyright (C) 2001 VideoLAN
 * $Id: preferences.cpp,v 1.15 2003/04/09 12:03:44 sam Exp $
 *
 * Authors: Sigmund Augdal <sigmunau@idi.ntnu.no> Mon Aug 12 2002
 *
 * 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., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
 *****************************************************************************/
#include <kdialogbase.h>
#include <qmap.h>
#include <qcheckbox.h>
#include <qframe.h>
#include <qgroupbox.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qlistview.h>
#include <qnamespace.h>
#include <qobjectlist.h>
#include <qslider.h>
#include <qspinbox.h>
#include <qtooltip.h>
#include <qvbox.h>

#include <kbuttonbox.h>
#include <klineedit.h>
#include <klocale.h>
#include <knuminput.h>
#include <kurlrequester.h>
#include <kcombobox.h>

#include "QConfigItem.h"
#include "pluginsbox.h"
#include "preferences.h"

/*
  construct a new configuration window for the given module
*/
KPreferences::KPreferences(intf_thread_t *p_intf, const char *psz_module_name,
                           QWidget *parent, const QString &caption) :
    KDialogBase ( TreeList, caption, Ok| Apply|Cancel|User1, Ok, parent,
                  "vlc preferences", true, false, i18n("&Save") )
{
    module_t *p_parser = NULL;
    vlc_list_t *p_list;
    module_config_t *p_item;
    int i_index;
    QVBox *category_table = NULL;
    QString *category_label;

    this->p_intf = p_intf;

    /* List all modules */
    p_list = vlc_list_find( p_intf, VLC_OBJECT_MODULE, FIND_ANYWHERE );

    for( i_index = 0; i_index < p_list->i_count; i_index++ )
    {
        p_parser = (module_t *)p_list->p_values[i_index].p_object ;
        p_item = p_parser->p_config;
        while( p_item && p_item->i_type != CONFIG_HINT_END )
        {
            switch( p_item->i_type )
            {
            case CONFIG_HINT_CATEGORY:
                /* force the content to the top of the page */
                if ( category_table )
                {
                    QWidget *space = new QWidget( category_table );
                    category_table->setStretchFactor( space, 10 );
                    category_table = NULL;
                }

                /*
                 * Now we can start taking care of the new category
                 */
                if( p_item->i_type == CONFIG_HINT_CATEGORY )
                {
                    category_label = new QString( p_item->psz_text );
                    QStringList path;
                    if ( strcmp( p_parser->psz_object_name, "main" ) )
                    {
                        path += _( "Plugins" );
                        path += p_parser->psz_capability;
                        path += p_parser->psz_object_name;
                    }
                    path += *category_label;
                    QFrame *page = addPage( path );
                    QVBoxLayout *toplayout = new QVBoxLayout( page);
                    QScrollView *sv = new QScrollView(page);
                    sv->setResizePolicy(QScrollView::AutoOneFit);
                    sv->setFrameStyle(QScrollView::NoFrame);
                    toplayout->addWidget(sv);
                    category_table = new QVBox(sv->viewport());
                    sv->addChild(category_table);
                    category_table->setSpacing(spacingHint());
                }

                break;

            case CONFIG_ITEM_MODULE:

            {
                vlc_mutex_lock( p_item->p_lock );
                KPluginsBox *item_frame =
                    new KPluginsBox( p_intf, p_item->psz_text,
                                     p_item->psz_value ? p_item->psz_value :"",
                                     category_table,
                                     spacingHint(),
                                     this );
                QConfigItem *ci = new QConfigItem(this,
                                                  p_item->psz_name,
                                                  p_item->i_type,
                                                  p_item->psz_value);
                connect(item_frame, SIGNAL(selectionChanged(const QString &)),
                        ci, SLOT(setValue(const QString &)));

                /* build a list of available plugins */
                for( int i_index = 0; i_index < p_list->i_count; i_index++ )
                {
                    module_t *p_parser = (module_t *)p_list->p_values[i_index].p_object ;

                    if( !strcmp( p_parser->psz_capability,
                                 p_item->psz_type ) )
                    {
                        new QListViewItem(item_frame->getListView(),
                                          p_parser->psz_object_name,
                                          p_parser->psz_longname);
                    }
                }

                vlc_mutex_unlock( p_item->p_lock );
            }
            break;

            case CONFIG_ITEM_STRING:
            {
                QHBox *hb = new QHBox(category_table);
                hb->setSpacing(spacingHint());
                new QLabel(p_item->psz_text, hb);
                /* add input box with default value */
                vlc_mutex_lock( p_item->p_lock );
                QConfigItem *ci = new QConfigItem(this, p_item->psz_name,
                                                  p_item->i_type,
                                                  p_item->psz_value ?
                                                  p_item->psz_value : "");
                if ( p_item->ppsz_list )
                {
                    char **ppsz_list = p_item->ppsz_list;
                    KComboBox *p_combobox = new KComboBox( true, hb );
                    QToolTip::add(p_combobox, p_item->psz_longtext);
                    connect(p_combobox, SIGNAL(activated ( const QString & )),
                            ci, SLOT(setValue( const QString &)));
                    while ( *ppsz_list )
                    {
                        p_combobox->insertItem( *ppsz_list );
                        if ( !strcmp( *ppsz_list, p_item->psz_value ?
                                                  p_item->psz_value : "" ) )
                        {
#if KDE_VERSION_MAJOR >= 3
                            p_combobox->setCurrentText( *ppsz_list );
#else
                            p_combobox->setCurrentItem( p_combobox->count() );
#endif
                        }
                        ppsz_list++;
                    }
                }
                else
                {
                    KLineEdit *kl = new KLineEdit( p_item->psz_value ?
                                                   p_item->psz_value : "", hb);
                    connect(kl, SIGNAL(textChanged ( const QString & )),
                            ci, SLOT(setValue( const QString &)));
                    QToolTip::add(kl, p_item->psz_longtext);
                    kl->setMaxLength(40);
                }

                vlc_mutex_unlock( p_item->p_lock );
            }
            break;

            case CONFIG_ITEM_FILE:
            {
                QHBox *hb = new QHBox(category_table);
                hb->setSpacing(spacingHint());
                new QLabel(p_item->psz_text, hb);
                /* add input box with default value */
                vlc_mutex_lock( p_item->p_lock );

//            KLineEdit *kl = new KLineEdit( p_item->psz_value ?
//                                           p_item->psz_value : "", hb);
                QConfigItem *ci = new QConfigItem(this, p_item->psz_name,
                                                  p_item->i_type,
                                                  p_item->psz_value ?
                                                  p_item->psz_value : "");
//            QPushButton *bbrowse = new QPushButton( _("Browse"), hb );
                KURLRequester *kfile = new KURLRequester( p_item->psz_value ?
                                                          p_item->psz_value : "",
                                                          hb );
                connect(kfile, SIGNAL(textChanged ( const QString & )),
                        ci, SLOT(setValue( const QString &)));
                QToolTip::add(kfile, p_item->psz_longtext);
                vlc_mutex_unlock( p_item->p_lock );
            }
            break;

            case CONFIG_ITEM_INTEGER:
                /* add input box with default value */
            {
                QHBox *hb = new QHBox(category_table);
                hb->setSpacing(spacingHint());
                new QLabel(p_item->psz_text, hb);
                QConfigItem *ci = new QConfigItem(this, p_item->psz_name,
                                                  p_item->i_type,
                                                  p_item->i_value);
                if ( p_item->i_min == 0 && p_item->i_max == 0 )
                {
                    QSpinBox *item_adj = new QSpinBox(-1, 99999, 1, hb);
                    item_adj->setValue( p_item->i_value );
                    connect(item_adj, SIGNAL(valueChanged( int)),
                            ci, SLOT(setValue(int)));
                    QToolTip::add(item_adj, p_item->psz_longtext);
                }
                else
                {
                    KIntNumInput *p_ii = new KIntNumInput( p_item->i_value, hb );
                    p_ii->setRange( p_item->i_min, p_item->i_max, 1, true );
                    connect( p_ii, SIGNAL( valueChanged( int ) ),
                             ci, SLOT( setValue( int ) ) );
                    QToolTip::add( p_ii, p_item->psz_longtext );
                }
            }
            break;

            case CONFIG_ITEM_FLOAT:
            {
                QHBox *hb = new QHBox(category_table);
                hb->setSpacing(spacingHint());
                new QLabel(p_item->psz_text, hb);
                KDoubleNumInput *kdi= new KDoubleNumInput(p_item->f_value, hb);
                if ( p_item->f_min == 0 && p_item->f_max == 0 )
                {
                    kdi->setRange(-1, 99999, 0.01, false);
                }
                else
                {
                    kdi->setRange( p_item->f_min, p_item->f_max, 0.01, true );
                }
                QConfigItem *ci = new QConfigItem(this, p_item->psz_name,
                                                  p_item->i_type,
                                                  p_item->f_value);
                connect(kdi, SIGNAL(valueChanged(double)),
                        ci, SLOT(setValue(double)));
                QToolTip::add(kdi, p_item->psz_longtext);
            }
            break;

            case CONFIG_ITEM_BOOL:

                /* add check button */
            {
                QCheckBox *bool_checkbutton =
                    new QCheckBox(QString(p_item->psz_text), category_table);
                QConfigItem *ci = new QConfigItem(this, p_item->psz_name,
                                                  p_item->i_type,
                                                  p_item->i_value);
                bool_checkbutton->setChecked(p_item->i_value);
                connect(bool_checkbutton, SIGNAL(stateChanged( int)),
                        ci, SLOT(setValue(int)));
                QToolTip::add(bool_checkbutton, p_item->psz_longtext);

            }
            break;

            }

            p_item++;
        }
    }
    /* force the content to the top of the page, even on the last page */
    if ( category_table )
    {
        QWidget *space = new QWidget( category_table );
        category_table->setStretchFactor( space, 10 );
        category_table = NULL;
    }

    vlc_list_release( p_list );

    exec();
}

/*
  empty destructor, qt takes care of this (I think)
*/
KPreferences::~KPreferences()
{
}

/*
  return true if the give module is configureable
*/
bool KPreferences::isConfigureable(QString module)
{
    module_t *p_parser;
    vlc_list_t *p_list;
    int i_index;

    p_list = vlc_list_find( this->p_intf, VLC_OBJECT_MODULE, FIND_ANYWHERE );

    for( i_index = 0; i_index < p_list->i_count; i_index++ )
    {
        p_parser = (module_t *)p_list->p_values[i_index].p_object ;

        if( !module.compare( p_parser->psz_object_name ) )
        {
            bool ret = p_parser->i_config_items != 0;
            vlc_list_release( p_list );
            return ret;
        }
    }

    vlc_list_release( p_list );
    return false;
}

/*
  run when the Apply button is pressed, and by the methods for the ok
  and save buttons
*/
void KPreferences::slotApply()
{
    QObjectList * l = queryList( "QConfigItem" );
    QObjectListIt it( *l );             // iterate over the config items
    QObject * obj;
    while ( (obj=it.current()) != 0 ) {
        ++it;
        QConfigItem *p_config = (QConfigItem *)obj;
        if ( p_config->changed() )
        {
            msg_Dbg( p_intf, const_cast<char *>(p_config->name()));
            msg_Dbg( p_intf, "%d", p_config->getType());

            switch( p_config->getType() ) {

            case CONFIG_ITEM_STRING:
            case CONFIG_ITEM_FILE:
            case CONFIG_ITEM_MODULE:
                if (p_config->sValue()) {
                    config_PutPsz( p_intf, p_config->name(),
                                   strdup(p_config->sValue().latin1()));
                }
                else {
                    config_PutPsz( p_intf, p_config->name(), NULL );
                }
                break;
            case CONFIG_ITEM_INTEGER:
            case CONFIG_ITEM_BOOL:
                config_PutInt( p_intf, p_config->name(), p_config->iValue() );
                break;
            case CONFIG_ITEM_FLOAT:
                config_PutFloat( p_intf, p_config->name(), p_config->fValue() );
                break;
            }
            p_config->resetChanged();
        }
    }
    delete l;
}

/*
  run when the Ok button is pressed
*/
void KPreferences::slotOk()
{
    slotApply();
    accept();
}

/*
  run when the save button is pressed
*/
void KPreferences::slotUser1()
{
    slotApply();
    config_SaveConfigFile( p_intf, NULL );
}
<commit_msg>Implemented support for CONFIG_ITEM_DIRECTORY<commit_after>/*****************************************************************************
 * preferences.cpp: preferences window for the kde gui
 *****************************************************************************
 * Copyright (C) 2001 VideoLAN
 * $Id: preferences.cpp,v 1.16 2003/05/05 14:58:45 sigmunau Exp $
 *
 * Authors: Sigmund Augdal <sigmunau@idi.ntnu.no> Mon Aug 12 2002
 *
 * 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., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
 *****************************************************************************/
#include <kdialogbase.h>
#include <qmap.h>
#include <qcheckbox.h>
#include <qframe.h>
#include <qgroupbox.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qlistview.h>
#include <qnamespace.h>
#include <qobjectlist.h>
#include <qslider.h>
#include <qspinbox.h>
#include <qtooltip.h>
#include <qvbox.h>

#include <kbuttonbox.h>
#include <klineedit.h>
#include <klocale.h>
#include <knuminput.h>
#include <kurlrequester.h>
#include <kcombobox.h>

#include "QConfigItem.h"
#include "pluginsbox.h"
#include "preferences.h"

/*
  construct a new configuration window for the given module
*/
KPreferences::KPreferences(intf_thread_t *p_intf, const char *psz_module_name,
                           QWidget *parent, const QString &caption) :
    KDialogBase ( TreeList, caption, Ok| Apply|Cancel|User1, Ok, parent,
                  "vlc preferences", true, false, i18n("&Save") )
{
    module_t *p_parser = NULL;
    vlc_list_t *p_list;
    module_config_t *p_item;
    int i_index;
    QVBox *category_table = NULL;
    QString *category_label;

    this->p_intf = p_intf;

    /* List all modules */
    p_list = vlc_list_find( p_intf, VLC_OBJECT_MODULE, FIND_ANYWHERE );

    for( i_index = 0; i_index < p_list->i_count; i_index++ )
    {
        p_parser = (module_t *)p_list->p_values[i_index].p_object ;
        p_item = p_parser->p_config;
        while( p_item && p_item->i_type != CONFIG_HINT_END )
        {
            switch( p_item->i_type )
            {
            case CONFIG_HINT_CATEGORY:
                /* force the content to the top of the page */
                if ( category_table )
                {
                    QWidget *space = new QWidget( category_table );
                    category_table->setStretchFactor( space, 10 );
                    category_table = NULL;
                }

                /*
                 * Now we can start taking care of the new category
                 */
                if( p_item->i_type == CONFIG_HINT_CATEGORY )
                {
                    category_label = new QString( p_item->psz_text );
                    QStringList path;
                    if ( strcmp( p_parser->psz_object_name, "main" ) )
                    {
                        path += _( "Plugins" );
                        path += p_parser->psz_capability;
                        path += p_parser->psz_object_name;
                    }
                    path += *category_label;
                    QFrame *page = addPage( path );
                    QVBoxLayout *toplayout = new QVBoxLayout( page);
                    QScrollView *sv = new QScrollView(page);
                    sv->setResizePolicy(QScrollView::AutoOneFit);
                    sv->setFrameStyle(QScrollView::NoFrame);
                    toplayout->addWidget(sv);
                    category_table = new QVBox(sv->viewport());
                    sv->addChild(category_table);
                    category_table->setSpacing(spacingHint());
                }

                break;

            case CONFIG_ITEM_MODULE:

            {
                vlc_mutex_lock( p_item->p_lock );
                KPluginsBox *item_frame =
                    new KPluginsBox( p_intf, p_item->psz_text,
                                     p_item->psz_value ? p_item->psz_value :"",
                                     category_table,
                                     spacingHint(),
                                     this );
                QConfigItem *ci = new QConfigItem(this,
                                                  p_item->psz_name,
                                                  p_item->i_type,
                                                  p_item->psz_value);
                connect(item_frame, SIGNAL(selectionChanged(const QString &)),
                        ci, SLOT(setValue(const QString &)));

                /* build a list of available plugins */
                for( int i_index = 0; i_index < p_list->i_count; i_index++ )
                {
                    module_t *p_parser = (module_t *)p_list->p_values[i_index].p_object ;

                    if( !strcmp( p_parser->psz_capability,
                                 p_item->psz_type ) )
                    {
                        new QListViewItem(item_frame->getListView(),
                                          p_parser->psz_object_name,
                                          p_parser->psz_longname);
                    }
                }

                vlc_mutex_unlock( p_item->p_lock );
            }
            break;

            case CONFIG_ITEM_STRING:
            {
                QHBox *hb = new QHBox(category_table);
                hb->setSpacing(spacingHint());
                new QLabel(p_item->psz_text, hb);
                /* add input box with default value */
                vlc_mutex_lock( p_item->p_lock );
                QConfigItem *ci = new QConfigItem(this, p_item->psz_name,
                                                  p_item->i_type,
                                                  p_item->psz_value ?
                                                  p_item->psz_value : "");
                if ( p_item->ppsz_list )
                {
                    char **ppsz_list = p_item->ppsz_list;
                    KComboBox *p_combobox = new KComboBox( true, hb );
                    QToolTip::add(p_combobox, p_item->psz_longtext);
                    connect(p_combobox, SIGNAL(activated ( const QString & )),
                            ci, SLOT(setValue( const QString &)));
                    while ( *ppsz_list )
                    {
                        p_combobox->insertItem( *ppsz_list );
                        if ( !strcmp( *ppsz_list, p_item->psz_value ?
                                                  p_item->psz_value : "" ) )
                        {
#if KDE_VERSION_MAJOR >= 3
                            p_combobox->setCurrentText( *ppsz_list );
#else
                            p_combobox->setCurrentItem( p_combobox->count() );
#endif
                        }
                        ppsz_list++;
                    }
                }
                else
                {
                    KLineEdit *kl = new KLineEdit( p_item->psz_value ?
                                                   p_item->psz_value : "", hb);
                    connect(kl, SIGNAL(textChanged ( const QString & )),
                            ci, SLOT(setValue( const QString &)));
                    QToolTip::add(kl, p_item->psz_longtext);
                    kl->setMaxLength(40);
                }

                vlc_mutex_unlock( p_item->p_lock );
            }
            break;

            case CONFIG_ITEM_FILE:
            case CONFIG_ITEM_DIRECTORY:
            {
                QHBox *hb = new QHBox(category_table);
                hb->setSpacing(spacingHint());
                new QLabel(p_item->psz_text, hb);
                /* add input box with default value */
                vlc_mutex_lock( p_item->p_lock );

//            KLineEdit *kl = new KLineEdit( p_item->psz_value ?
//                                           p_item->psz_value : "", hb);
                QConfigItem *ci = new QConfigItem(this, p_item->psz_name,
                                                  p_item->i_type,
                                                  p_item->psz_value ?
                                                  p_item->psz_value : "");
//            QPushButton *bbrowse = new QPushButton( _("Browse"), hb );
                KURLRequester *kfile = new KURLRequester( p_item->psz_value ?
                                                          p_item->psz_value : "",
                                                          hb );
                if ( p_item->i_type == CONFIG_ITEM_DIRECTORY )
                {
                    kfile->setMode(KFile::Directory|KFile::ExistingOnly|KFile::LocalOnly);
                }
                connect(kfile, SIGNAL(textChanged ( const QString & )),
                        ci, SLOT(setValue( const QString &)));
                QToolTip::add(kfile, p_item->psz_longtext);
                vlc_mutex_unlock( p_item->p_lock );
            }
            break;

            case CONFIG_ITEM_INTEGER:
                /* add input box with default value */
            {
                QHBox *hb = new QHBox(category_table);
                hb->setSpacing(spacingHint());
                new QLabel(p_item->psz_text, hb);
                QConfigItem *ci = new QConfigItem(this, p_item->psz_name,
                                                  p_item->i_type,
                                                  p_item->i_value);
                if ( p_item->i_min == 0 && p_item->i_max == 0 )
                {
                    QSpinBox *item_adj = new QSpinBox(-1, 99999, 1, hb);
                    item_adj->setValue( p_item->i_value );
                    connect(item_adj, SIGNAL(valueChanged( int)),
                            ci, SLOT(setValue(int)));
                    QToolTip::add(item_adj, p_item->psz_longtext);
                }
                else
                {
                    KIntNumInput *p_ii = new KIntNumInput( p_item->i_value, hb );
                    p_ii->setRange( p_item->i_min, p_item->i_max, 1, true );
                    connect( p_ii, SIGNAL( valueChanged( int ) ),
                             ci, SLOT( setValue( int ) ) );
                    QToolTip::add( p_ii, p_item->psz_longtext );
                }
            }
            break;

            case CONFIG_ITEM_FLOAT:
            {
                QHBox *hb = new QHBox(category_table);
                hb->setSpacing(spacingHint());
                new QLabel(p_item->psz_text, hb);
                KDoubleNumInput *kdi= new KDoubleNumInput(p_item->f_value, hb);
                if ( p_item->f_min == 0 && p_item->f_max == 0 )
                {
                    kdi->setRange(-1, 99999, 0.01, false);
                }
                else
                {
                    kdi->setRange( p_item->f_min, p_item->f_max, 0.01, true );
                }
                QConfigItem *ci = new QConfigItem(this, p_item->psz_name,
                                                  p_item->i_type,
                                                  p_item->f_value);
                connect(kdi, SIGNAL(valueChanged(double)),
                        ci, SLOT(setValue(double)));
                QToolTip::add(kdi, p_item->psz_longtext);
            }
            break;

            case CONFIG_ITEM_BOOL:

                /* add check button */
            {
                QCheckBox *bool_checkbutton =
                    new QCheckBox(QString(p_item->psz_text), category_table);
                QConfigItem *ci = new QConfigItem(this, p_item->psz_name,
                                                  p_item->i_type,
                                                  p_item->i_value);
                bool_checkbutton->setChecked(p_item->i_value);
                connect(bool_checkbutton, SIGNAL(stateChanged( int)),
                        ci, SLOT(setValue(int)));
                QToolTip::add(bool_checkbutton, p_item->psz_longtext);

            }
            break;

            }

            p_item++;
        }
    }
    /* force the content to the top of the page, even on the last page */
    if ( category_table )
    {
        QWidget *space = new QWidget( category_table );
        category_table->setStretchFactor( space, 10 );
        category_table = NULL;
    }

    vlc_list_release( p_list );

    exec();
}

/*
  empty destructor, qt takes care of this (I think)
*/
KPreferences::~KPreferences()
{
}

/*
  return true if the give module is configureable
*/
bool KPreferences::isConfigureable(QString module)
{
    module_t *p_parser;
    vlc_list_t *p_list;
    int i_index;

    p_list = vlc_list_find( this->p_intf, VLC_OBJECT_MODULE, FIND_ANYWHERE );

    for( i_index = 0; i_index < p_list->i_count; i_index++ )
    {
        p_parser = (module_t *)p_list->p_values[i_index].p_object ;

        if( !module.compare( p_parser->psz_object_name ) )
        {
            bool ret = p_parser->i_config_items != 0;
            vlc_list_release( p_list );
            return ret;
        }
    }

    vlc_list_release( p_list );
    return false;
}

/*
  run when the Apply button is pressed, and by the methods for the ok
  and save buttons
*/
void KPreferences::slotApply()
{
    QObjectList * l = queryList( "QConfigItem" );
    QObjectListIt it( *l );             // iterate over the config items
    QObject * obj;
    while ( (obj=it.current()) != 0 ) {
        ++it;
        QConfigItem *p_config = (QConfigItem *)obj;
        if ( p_config->changed() )
        {
            msg_Dbg( p_intf, const_cast<char *>(p_config->name()));
            msg_Dbg( p_intf, "%d", p_config->getType());

            switch( p_config->getType() ) {

            case CONFIG_ITEM_DIRECTORY:
            case CONFIG_ITEM_STRING:
            case CONFIG_ITEM_FILE:
            case CONFIG_ITEM_MODULE:
                if (p_config->sValue()) {
                    config_PutPsz( p_intf, p_config->name(),
                                   strdup(p_config->sValue().latin1()));
                }
                else {
                    config_PutPsz( p_intf, p_config->name(), NULL );
                }
                break;
            case CONFIG_ITEM_INTEGER:
            case CONFIG_ITEM_BOOL:
                config_PutInt( p_intf, p_config->name(), p_config->iValue() );
                break;
            case CONFIG_ITEM_FLOAT:
                config_PutFloat( p_intf, p_config->name(), p_config->fValue() );
                break;
            }
            p_config->resetChanged();
        }
    }
    delete l;
}

/*
  run when the Ok button is pressed
*/
void KPreferences::slotOk()
{
    slotApply();
    accept();
}

/*
  run when the save button is pressed
*/
void KPreferences::slotUser1()
{
    slotApply();
    config_SaveConfigFile( p_intf, NULL );
}
<|endoftext|>


<commit_before>#include <julia.h>
#include "Values.h"
#include "lvalue.h"

#include <iostream>

using namespace std;

template <typename V,typename E> static shared_ptr<nj::Value> reboxArray(jl_value_t *jlarray)
{
   shared_ptr<nj::Value> value;
   V *p = (V*)jl_array_data(jlarray);
   int ndims = jl_array_ndims(jlarray);
   vector<int> dims;

   for(int dim = 0;dim < ndims;dim++) dims.push_back(jl_array_dim(jlarray,dim));

   nj::Array<V,E> *array = new nj::Array<V,E>(dims);

   value.reset(array);
   memcpy(array->ptr(),p,array->size()*sizeof(double));
   return value;
}

static shared_ptr<nj::Value> getArrayValue(jl_value_t *jlarray)
{
   shared_ptr<nj::Value> value;
   jl_value_t *elementType = jl_tparam0(jl_typeof(jlarray));

   if(jl_is_int64(elementType)) value = reboxArray<int64_t,nj::Int64_t>(jlarray);
   else if(jl_is_int32(elementType)) value = reboxArray<int,nj::Int32_t>(jlarray);
   else if(jl_is_float64(elementType)) value = reboxArray<double,nj::Float64_t>(jlarray);
   else if(jl_is_float32(elementType)) value = reboxArray<float,nj::Float32_t>(jlarray);
   else if(jl_is_uint64(elementType)) value = reboxArray<uint64_t,nj::UInt64_t>(jlarray);
   else if(jl_is_uint32(elementType)) value = reboxArray<unsigned int,nj::UInt32_t>(jlarray);
   else if(jl_is_int8(elementType)) value = reboxArray<char,nj::Char_t>(jlarray);
   else if(jl_is_int16(elementType)) value = reboxArray<short,nj::Int16_t>(jlarray);
   else if(jl_is_uint8(elementType)) value = reboxArray<unsigned char,nj::UChar_t>(jlarray);
   else if(jl_is_uint16(elementType)) value = reboxArray<unsigned short,nj::UInt16_t>(jlarray);

   return value;
}

vector<shared_ptr<nj::Value>> nj::lvalue(jl_value_t *jlvalue)
{
   vector<shared_ptr<nj::Value>> res;

   if(jl_is_null(jlvalue))
   {
      shared_ptr<nj::Value>  value(new nj::Null);
      res.push_back(value);
   }
   else if(jl_is_array(jlvalue))
   {
      res.push_back(getArrayValue(jlvalue));
   }
   else
   {
      shared_ptr<nj::Value> value;

      if(jl_is_int64(jlvalue)) value.reset(new nj::Int64(jl_unbox_int64(jlvalue)));
      else if(jl_is_int32(jlvalue)) value.reset(new nj::Int32(jl_unbox_int32(jlvalue)));
      else if(jl_is_float64(jlvalue)) value.reset(new nj::Float64(jl_unbox_float64(jlvalue)));
      else if(jl_is_float32(jlvalue)) value.reset(new nj::Float32(jl_unbox_float32(jlvalue)));
      else if(jl_is_uint64(jlvalue)) value.reset(new nj::UInt64(jl_unbox_uint64(jlvalue)));
      else if(jl_is_uint32(jlvalue)) value.reset(new nj::UInt32(jl_unbox_uint32(jlvalue)));
      else if(jl_is_int8(jlvalue)) value.reset(new nj::Char(jl_unbox_int8(jlvalue)));
      else if(jl_is_int16(jlvalue)) value.reset(new nj::Int16(jl_unbox_int16(jlvalue)));
      else if(jl_is_uint8(jlvalue)) value.reset(new nj::UChar(jl_unbox_uint8(jlvalue)));
      else if(jl_is_uint16(jlvalue)) value.reset(new nj::UInt16(jl_unbox_uint16(jlvalue)));
      else if(jl_is_ascii_string(jlvalue)) value.reset(new nj::String((char*)jl_unbox_voidpointer(jlvalue)));

      if(value.get()) res.push_back(value);
   }
   return res;
}
<commit_msg>Debugging<commit_after>#include <julia.h>
#include "Values.h"
#include "lvalue.h"

#include <iostream>

using namespace std;

template <typename V,typename E> static shared_ptr<nj::Value> reboxArray(jl_value_t *jlarray)
{
   shared_ptr<nj::Value> value;
   V *p = (V*)jl_array_data(jlarray);
   int ndims = jl_array_ndims(jlarray);
   vector<int> dims;

   for(int dim = 0;dim < ndims;dim++) dims.push_back(jl_array_dim(jlarray,dim));

   nj::Array<V,E> *array = new nj::Array<V,E>(dims);

printf("In rebox array: dim = %lu\n",dims.size());

   value.reset(array);
   memcpy(array->ptr(),p,array->size()*sizeof(V));
   return value;
}

static shared_ptr<nj::Value> getArrayValue(jl_value_t *jlarray)
{
   shared_ptr<nj::Value> value;
   jl_value_t *elementType = jl_tparam0(jl_typeof(jlarray));

printf("In getArray Value\n");

   if(jl_is_int64(elementType)) value = reboxArray<int64_t,nj::Int64_t>(jlarray);
   else if(jl_is_int32(elementType)) value = reboxArray<int,nj::Int32_t>(jlarray);
   else if(jl_is_float64(elementType)) value = reboxArray<double,nj::Float64_t>(jlarray);
   else if(jl_is_float32(elementType)) value = reboxArray<float,nj::Float32_t>(jlarray);
   else if(jl_is_uint64(elementType)) value = reboxArray<uint64_t,nj::UInt64_t>(jlarray);
   else if(jl_is_uint32(elementType)) value = reboxArray<unsigned int,nj::UInt32_t>(jlarray);
   else if(jl_is_int8(elementType)) value = reboxArray<char,nj::Char_t>(jlarray);
   else if(jl_is_int16(elementType)) value = reboxArray<short,nj::Int16_t>(jlarray);
   else if(jl_is_uint8(elementType)) value = reboxArray<unsigned char,nj::UChar_t>(jlarray);
   else if(jl_is_uint16(elementType)) value = reboxArray<unsigned short,nj::UInt16_t>(jlarray);

   return value;
}

vector<shared_ptr<nj::Value>> nj::lvalue(jl_value_t *jlvalue)
{
   vector<shared_ptr<nj::Value>> res;

   if(jl_is_null(jlvalue))
   {
      shared_ptr<nj::Value>  value(new nj::Null);
      res.push_back(value);
   }
   else if(jl_is_array(jlvalue))
   {
      res.push_back(getArrayValue(jlvalue));
   }
   else
   {
      shared_ptr<nj::Value> value;

      if(jl_is_int64(jlvalue)) value.reset(new nj::Int64(jl_unbox_int64(jlvalue)));
      else if(jl_is_int32(jlvalue)) value.reset(new nj::Int32(jl_unbox_int32(jlvalue)));
      else if(jl_is_float64(jlvalue)) value.reset(new nj::Float64(jl_unbox_float64(jlvalue)));
      else if(jl_is_float32(jlvalue)) value.reset(new nj::Float32(jl_unbox_float32(jlvalue)));
      else if(jl_is_uint64(jlvalue)) value.reset(new nj::UInt64(jl_unbox_uint64(jlvalue)));
      else if(jl_is_uint32(jlvalue)) value.reset(new nj::UInt32(jl_unbox_uint32(jlvalue)));
      else if(jl_is_int8(jlvalue)) value.reset(new nj::Char(jl_unbox_int8(jlvalue)));
      else if(jl_is_int16(jlvalue)) value.reset(new nj::Int16(jl_unbox_int16(jlvalue)));
      else if(jl_is_uint8(jlvalue)) value.reset(new nj::UChar(jl_unbox_uint8(jlvalue)));
      else if(jl_is_uint16(jlvalue)) value.reset(new nj::UInt16(jl_unbox_uint16(jlvalue)));
      else if(jl_is_ascii_string(jlvalue)) value.reset(new nj::String((char*)jl_unbox_voidpointer(jlvalue)));

      if(value.get()) res.push_back(value);
   }
   return res;
}
<|endoftext|>


<commit_before>/*
* TLS Record Writing
* (C) 2004-2011 Jack Lloyd
*
* Released under the terms of the Botan license
*/

#include <botan/tls_record.h>
#include <botan/internal/tls_session_key.h>
#include <botan/internal/tls_handshake_hash.h>
#include <botan/lookup.h>
#include <botan/internal/rounding.h>
#include <botan/internal/assert.h>
#include <botan/loadstor.h>
#include <botan/libstate.h>

namespace Botan {

/*
* Record_Writer Constructor
*/
Record_Writer::Record_Writer(std::tr1::function<void (const byte[], size_t)> out,
                             size_t max_fragment) :
   output_fn(out),
   max_fragment(clamp(max_fragment, 128, MAX_PLAINTEXT_SIZE))
   {
   mac = 0;
   reset();
   }

/*
* Reset the state
*/
void Record_Writer::reset()
   {
   cipher.reset();

   delete mac;
   mac = 0;

   major = minor = 0;
   block_size = 0;
   mac_size = 0;
   iv_size = 0;

   seq_no = 0;
   }

/*
* Set the version to use
*/
void Record_Writer::set_version(Version_Code version)
   {
   if(version != SSL_V3 && version != TLS_V10 && version != TLS_V11)
      throw Invalid_Argument("Record_Writer: Invalid protocol version");

   major = (version >> 8) & 0xFF;
   minor = (version & 0xFF);
   }

/*
* Set the keys for writing
*/
void Record_Writer::set_keys(const CipherSuite& suite,
                             const SessionKeys& keys,
                             Connection_Side side)
   {
   cipher.reset();
   delete mac;
   mac = 0;

   SymmetricKey mac_key, cipher_key;
   InitializationVector iv;

   if(side == CLIENT)
      {
      cipher_key = keys.client_cipher_key();
      iv = keys.client_iv();
      mac_key = keys.client_mac_key();
      }
   else
      {
      cipher_key = keys.server_cipher_key();
      iv = keys.server_iv();
      mac_key = keys.server_mac_key();
      }

   const std::string cipher_algo = suite.cipher_algo();
   const std::string mac_algo = suite.mac_algo();

   if(have_block_cipher(cipher_algo))
      {
      cipher.append(get_cipher(
                       cipher_algo + "/CBC/NoPadding",
                       cipher_key, iv, ENCRYPTION)
         );
      block_size = block_size_of(cipher_algo);

      if(major > 3 || (major == 3 && minor >= 2))
         iv_size = block_size;
      else
         iv_size = 0;
      }
   else if(have_stream_cipher(cipher_algo))
      {
      cipher.append(get_cipher(cipher_algo, cipher_key, ENCRYPTION));
      block_size = 0;
      iv_size = 0;
      }
   else
      throw Invalid_Argument("Record_Writer: Unknown cipher " + cipher_algo);

   if(have_hash(mac_algo))
      {
      Algorithm_Factory& af = global_state().algorithm_factory();

      if(major == 3 && minor == 0)
         mac = af.make_mac("SSL3-MAC(" + mac_algo + ")");
      else
         mac = af.make_mac("HMAC(" + mac_algo + ")");

      mac->set_key(mac_key);
      mac_size = mac->output_length();
      }
   else
      throw Invalid_Argument("Record_Writer: Unknown hash " + mac_algo);
   }

/*
* Send one or more records to the other side
*/
void Record_Writer::send(byte type, const byte input[], size_t length)
   {
   if(length == 0)
      return;

   /*
   * If using CBC mode in SSLv3/TLS1.0, send a single byte of
   * plaintext to randomize the (implicit) IV of the following main
   * block. If using a stream cipher, or TLS v1.1, this isn't
   * necessary.
   *
   * An empty record also works but apparently some implementations do
   * not like this.
   *
   * See http://www.openssl.org/~bodo/tls-cbc.txt for background.
   */
   if((block_size > 0) && (iv_size == 0))
      {
      send_record(type, &input[0], 1);
      input += 1;
      length -= 1;
      }

   while(length)
      {
      const size_t sending = std::min(length, max_fragment);
      send_record(type, &input[0], sending);

      input += sending;
      length -= sending;
      }
   }

/*
* Encrypt and send the record
*/
void Record_Writer::send_record(byte type, const byte input[], size_t length)
   {
   if(length >= MAX_PLAINTEXT_SIZE)
      throw TLS_Exception(INTERNAL_ERROR,
                          "Record_Writer: Compressed packet is too big");

   if(mac_size == 0)
      {
      const byte header[5] = {
         type,
         major,
         minor,
         get_byte<u16bit>(0, length),
         get_byte<u16bit>(1, length)
      };

      output_fn(header, 5);
      output_fn(input, length);
      }
   else
      {
      mac->update_be(seq_no);
      mac->update(type);

      if(major > 3 || (major == 3 && minor != 0))
         {
         mac->update(major);
         mac->update(minor);
         }

      mac->update(get_byte<u16bit>(0, length));
      mac->update(get_byte<u16bit>(1, length));
      mac->update(input, length);

      const size_t buf_size = round_up(iv_size + length +
                                       mac->output_length() +
                                       (block_size ? 1 : 0),
                                       block_size);

      if(buf_size >= MAX_CIPHERTEXT_SIZE)
         throw TLS_Exception(INTERNAL_ERROR,
                             "Record_Writer: Record is too big");

      MemoryVector<byte> buf(5 + buf_size);

      // TLS record header
      buf[0] = type;
      buf[1] = major;
      buf[2] = minor;
      buf[3] = get_byte<u16bit>(0, buf_size);
      buf[4] = get_byte<u16bit>(1, buf_size);

      byte* buf_write_ptr = &buf[5];

      if(iv_size)
         {
         RandomNumberGenerator& rng = global_state().global_rng();
         rng.randomize(buf_write_ptr, iv_size);
         buf_write_ptr += iv_size;
         }

      copy_mem(buf_write_ptr, input, length);
      buf_write_ptr += length;

      mac->final(buf_write_ptr);
      buf_write_ptr += mac->output_length();

      if(block_size)
         {
         const size_t pad_val =
            buf_size - (iv_size + length + mac->output_length() + 1);

         for(size_t i = 0; i != pad_val + 1; ++i)
            {
            *buf_write_ptr = pad_val;
            buf_write_ptr += 1;
            }
         }

      // FIXME: this could be done in-place without copying
      cipher.process_msg(&buf[5], buf.size() - 5);
      size_t got_back = cipher.read(&buf[5], buf.size() - 5, Pipe::LAST_MESSAGE);
      BOTAN_ASSERT_EQUAL(got_back, buf.size()-5, "CBC didn't encrypt full blocks");

      output_fn(&buf[0], buf.size());

      seq_no++;
      }
   }

/*
* Send an alert
*/
void Record_Writer::alert(Alert_Level level, Alert_Type type)
   {
   byte alert[2] = { level, type };
   send(ALERT, alert, sizeof(alert));
   }

}
<commit_msg>Only insert small fragments for application records. Handshakes would only be affected if the attacker can modify the handshake messages, which seems fairly unlikely, and some implementations are known to be unhappy with fragmented handshakes.<commit_after>/*
* TLS Record Writing
* (C) 2004-2011 Jack Lloyd
*
* Released under the terms of the Botan license
*/

#include <botan/tls_record.h>
#include <botan/internal/tls_session_key.h>
#include <botan/internal/tls_handshake_hash.h>
#include <botan/lookup.h>
#include <botan/internal/rounding.h>
#include <botan/internal/assert.h>
#include <botan/loadstor.h>
#include <botan/libstate.h>

namespace Botan {

/*
* Record_Writer Constructor
*/
Record_Writer::Record_Writer(std::tr1::function<void (const byte[], size_t)> out,
                             size_t max_fragment) :
   output_fn(out),
   max_fragment(clamp(max_fragment, 128, MAX_PLAINTEXT_SIZE))
   {
   mac = 0;
   reset();
   }

/*
* Reset the state
*/
void Record_Writer::reset()
   {
   cipher.reset();

   delete mac;
   mac = 0;

   major = minor = 0;
   block_size = 0;
   mac_size = 0;
   iv_size = 0;

   seq_no = 0;
   }

/*
* Set the version to use
*/
void Record_Writer::set_version(Version_Code version)
   {
   if(version != SSL_V3 && version != TLS_V10 && version != TLS_V11)
      throw Invalid_Argument("Record_Writer: Invalid protocol version");

   major = (version >> 8) & 0xFF;
   minor = (version & 0xFF);
   }

/*
* Set the keys for writing
*/
void Record_Writer::set_keys(const CipherSuite& suite,
                             const SessionKeys& keys,
                             Connection_Side side)
   {
   cipher.reset();
   delete mac;
   mac = 0;

   SymmetricKey mac_key, cipher_key;
   InitializationVector iv;

   if(side == CLIENT)
      {
      cipher_key = keys.client_cipher_key();
      iv = keys.client_iv();
      mac_key = keys.client_mac_key();
      }
   else
      {
      cipher_key = keys.server_cipher_key();
      iv = keys.server_iv();
      mac_key = keys.server_mac_key();
      }

   const std::string cipher_algo = suite.cipher_algo();
   const std::string mac_algo = suite.mac_algo();

   if(have_block_cipher(cipher_algo))
      {
      cipher.append(get_cipher(
                       cipher_algo + "/CBC/NoPadding",
                       cipher_key, iv, ENCRYPTION)
         );
      block_size = block_size_of(cipher_algo);

      if(major > 3 || (major == 3 && minor >= 2))
         iv_size = block_size;
      else
         iv_size = 0;
      }
   else if(have_stream_cipher(cipher_algo))
      {
      cipher.append(get_cipher(cipher_algo, cipher_key, ENCRYPTION));
      block_size = 0;
      iv_size = 0;
      }
   else
      throw Invalid_Argument("Record_Writer: Unknown cipher " + cipher_algo);

   if(have_hash(mac_algo))
      {
      Algorithm_Factory& af = global_state().algorithm_factory();

      if(major == 3 && minor == 0)
         mac = af.make_mac("SSL3-MAC(" + mac_algo + ")");
      else
         mac = af.make_mac("HMAC(" + mac_algo + ")");

      mac->set_key(mac_key);
      mac_size = mac->output_length();
      }
   else
      throw Invalid_Argument("Record_Writer: Unknown hash " + mac_algo);
   }

/*
* Send one or more records to the other side
*/
void Record_Writer::send(byte type, const byte input[], size_t length)
   {
   if(length == 0)
      return;

   /*
   * If using CBC mode in SSLv3/TLS1.0, send a single byte of
   * plaintext to randomize the (implicit) IV of the following main
   * block. If using a stream cipher, or TLS v1.1, this isn't
   * necessary.
   *
   * An empty record also works but apparently some implementations do
   * not like this.
   *
   * See http://www.openssl.org/~bodo/tls-cbc.txt for background.
   */
   if((type == APPLICATION) && (block_size > 0) && (iv_size == 0))
      {
      send_record(type, &input[0], 1);
      input += 1;
      length -= 1;
      }

   while(length)
      {
      const size_t sending = std::min(length, max_fragment);
      send_record(type, &input[0], sending);

      input += sending;
      length -= sending;
      }
   }

/*
* Encrypt and send the record
*/
void Record_Writer::send_record(byte type, const byte input[], size_t length)
   {
   if(length >= MAX_PLAINTEXT_SIZE)
      throw TLS_Exception(INTERNAL_ERROR,
                          "Record_Writer: Compressed packet is too big");

   if(mac_size == 0)
      {
      const byte header[5] = {
         type,
         major,
         minor,
         get_byte<u16bit>(0, length),
         get_byte<u16bit>(1, length)
      };

      output_fn(header, 5);
      output_fn(input, length);
      }
   else
      {
      mac->update_be(seq_no);
      mac->update(type);

      if(major > 3 || (major == 3 && minor != 0))
         {
         mac->update(major);
         mac->update(minor);
         }

      mac->update(get_byte<u16bit>(0, length));
      mac->update(get_byte<u16bit>(1, length));
      mac->update(input, length);

      const size_t buf_size = round_up(iv_size + length +
                                       mac->output_length() +
                                       (block_size ? 1 : 0),
                                       block_size);

      if(buf_size >= MAX_CIPHERTEXT_SIZE)
         throw TLS_Exception(INTERNAL_ERROR,
                             "Record_Writer: Record is too big");

      MemoryVector<byte> buf(5 + buf_size);

      // TLS record header
      buf[0] = type;
      buf[1] = major;
      buf[2] = minor;
      buf[3] = get_byte<u16bit>(0, buf_size);
      buf[4] = get_byte<u16bit>(1, buf_size);

      byte* buf_write_ptr = &buf[5];

      if(iv_size)
         {
         RandomNumberGenerator& rng = global_state().global_rng();
         rng.randomize(buf_write_ptr, iv_size);
         buf_write_ptr += iv_size;
         }

      copy_mem(buf_write_ptr, input, length);
      buf_write_ptr += length;

      mac->final(buf_write_ptr);
      buf_write_ptr += mac->output_length();

      if(block_size)
         {
         const size_t pad_val =
            buf_size - (iv_size + length + mac->output_length() + 1);

         for(size_t i = 0; i != pad_val + 1; ++i)
            {
            *buf_write_ptr = pad_val;
            buf_write_ptr += 1;
            }
         }

      // FIXME: this could be done in-place without copying
      cipher.process_msg(&buf[5], buf.size() - 5);
      size_t got_back = cipher.read(&buf[5], buf.size() - 5, Pipe::LAST_MESSAGE);
      BOTAN_ASSERT_EQUAL(got_back, buf.size()-5, "CBC didn't encrypt full blocks");

      output_fn(&buf[0], buf.size());

      seq_no++;
      }
   }

/*
* Send an alert
*/
void Record_Writer::alert(Alert_Level level, Alert_Type type)
   {
   byte alert[2] = { level, type };
   send(ALERT, alert, sizeof(alert));
   }

}
<|endoftext|>


<commit_before>#include "layers/layerfactory.h"

#include <boost/assign/list_of.hpp>

#include "core/registor.h"

/** Whenever a new layer is imeplemented:
 *  1. include its header below
 *  2. Add it to the initialization of g_layerRegistry map.
 */
#include "layers/attentionwindow.h"
#include "layers/icp.h"
#include "layers/layer_y.h"
#include "layers/layer_z.h"
#include "encoding/populationcode.h"
#include "layers/saliencyitti.h"
#include "layers/weightedsum.h"

using boost::assign::map_list_of;

typedef Registor_<base_Layer> LayerRegistor;
typedef Registor_<base_Layer>::Registry LayerRegistry;

/** Macros for creating individual registry pair items
 *  credit: J. Turcot, T. Senechal, http://stackoverflow.com/questions/138600/initializing-a-static-stdmapint-int-in-c
 */
#define REGISTRY_PAIR(Registor, NewInstance) (#NewInstance, &Registor::DerivedInstance<NewInstance>)
#define LAYER_REGISTRY_PAIR(NewInstance) REGISTRY_PAIR(LayerRegistor, NewInstance)

LayerRegistry g_layerRegistry = map_list_of
        LAYER_REGISTRY_PAIR( AttentionWindow )
        LAYER_REGISTRY_PAIR( ICP )
        LAYER_REGISTRY_PAIR( LayerY )
        LAYER_REGISTRY_PAIR( LayerZ )
        LAYER_REGISTRY_PAIR( MutexPopulationCode )
        LAYER_REGISTRY_PAIR( SaliencyItti )
        LAYER_REGISTRY_PAIR( WeightedSum )
        ; ///< <-- add new layer to registry here

LayerFactory::LayerFactory()
{
}

LayerRegistor::RegisteredTypeSharedPtr LayerFactory::CreateShared(const LayerType &type)
{
    return LayerRegistor::CreatePtrShared(g_layerRegistry, type);
}

LayerRegistor::RegisteredTypeSharedPtr LayerFactory::CreateShared(const LayerType &type,
                                                                          const LayerConfig &config,
                                                                          const LayerIONames &io)
{
    LayerRegistor::RegisteredTypeSharedPtr ptr = LayerFactory::CreateShared(type);
    ptr->Reset(config);
    ptr->IONames(io);
    return ptr;
}
<commit_msg>reigster Triangulation layer<commit_after>#include "layers/layerfactory.h"

#include <boost/assign/list_of.hpp>

#include "core/registor.h"

/** Whenever a new layer is imeplemented:
 *  1. include its header below
 *  2. Add it to the initialization of g_layerRegistry map.
 */
#include "layers/attentionwindow.h"
#include "layers/icp.h"
#include "layers/layer_y.h"
#include "layers/layer_z.h"
#include "encoding/populationcode.h"
#include "layers/saliencyitti.h"
#include "layers/triangulation.h"
#include "layers/weightedsum.h"

using boost::assign::map_list_of;

typedef Registor_<base_Layer> LayerRegistor;
typedef Registor_<base_Layer>::Registry LayerRegistry;

/** Macros for creating individual registry pair items
 *  credit: J. Turcot, T. Senechal, http://stackoverflow.com/questions/138600/initializing-a-static-stdmapint-int-in-c
 */
#define REGISTRY_PAIR(Registor, NewInstance) (#NewInstance, &Registor::DerivedInstance<NewInstance>)
#define LAYER_REGISTRY_PAIR(NewInstance) REGISTRY_PAIR(LayerRegistor, NewInstance)

LayerRegistry g_layerRegistry = map_list_of
        LAYER_REGISTRY_PAIR( AttentionWindow )
        LAYER_REGISTRY_PAIR( ICP )
        LAYER_REGISTRY_PAIR( LayerY )
        LAYER_REGISTRY_PAIR( LayerZ )
        LAYER_REGISTRY_PAIR( MutexPopulationCode )
        LAYER_REGISTRY_PAIR( SaliencyItti )
        LAYER_REGISTRY_PAIR( Triangulation )
        LAYER_REGISTRY_PAIR( WeightedSum )
        ; ///< <-- add new layer to registry here

LayerFactory::LayerFactory()
{
}

LayerRegistor::RegisteredTypeSharedPtr LayerFactory::CreateShared(const LayerType &type)
{
    return LayerRegistor::CreatePtrShared(g_layerRegistry, type);
}

LayerRegistor::RegisteredTypeSharedPtr LayerFactory::CreateShared(const LayerType &type,
                                                                          const LayerConfig &config,
                                                                          const LayerIONames &io)
{
    LayerRegistor::RegisteredTypeSharedPtr ptr = LayerFactory::CreateShared(type);
    ptr->Reset(config);
    ptr->IONames(io);
    return ptr;
}
<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <cstdlib>
#include <cpprest/http_client.h>

using namespace web::http;

using namespace std;

void fatal(const char* msg) {
  cerr << msg << "\n";
  abort();
}

int main() {
  ifstream f("~/.stockfighter");
  if (!f) fatal("error: ifstream()");
  string apikey;
  if (!getline(f, apikey)) fatal("error: getline()");

  printf("Hello, world!\n");
  return 0;
}
<commit_msg>Basic request working<commit_after>#include <fstream>
#include <iostream>
#include <cstdlib>
#include <cpprest/http_client.h>

using namespace web::http;
using namespace client;

using namespace std;

void fatal(const char* msg) {
  cerr << msg << "\n";
  abort();
}

int main(int argc, const char** argv) {
  if (argc < 2) fatal("usage: main <apikeyfile>");
  ifstream f(argv[1]);
  if (!f) fatal("error: ifstream()");
  string apikey;
  if (!getline(f, apikey)) fatal("error: getline()");

  cout << "API Key: '" << apikey << "'\n";

  http_client client("https://api.stockfighter.io");

  auto res = client.request("GET", "/ob/api/venues").get();

  auto body = res.extract_utf8string(true).get();

  cout << body << "\n===END OF MESSAGE===\n";

  return 0;
}
<|endoftext|>


<commit_before>/*
 * This file is part of the QPackageKit project
 * Copyright (C) 2008 Adrien Bustany <madcat@mymadcat.com>
 * Copyright (C) 2010-2018 Daniel Nicoletti <dantti12@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB. If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "transaction.h"
#include "transactionprivate.h"
#include "transactionproxy.h"

#include "daemon.h"
#include "common.h"

#include <QDBusError>

Q_LOGGING_CATEGORY(PACKAGEKITQT_TRANSACTION, "packagekitqt.transaction")

using namespace PackageKit;

Transaction::Transaction()
    : d_ptr(new TransactionPrivate(this))
{
    Q_D(Transaction);

    connect(Daemon::global(), SIGNAL(daemonQuit()), SLOT(daemonQuit()));

    QDBusPendingReply<QDBusObjectPath> reply = Daemon::global()->createTransaction();
    auto watcher = new QDBusPendingCallWatcher(reply, this);
    connect(watcher, &QDBusPendingCallWatcher::finished,
            this, [this, d] (QDBusPendingCallWatcher *call)
    {
        QDBusPendingReply<QDBusObjectPath> reply = *call;
        if (reply.isError()) {
            errorCode(Transaction::ErrorInternalError, reply.error().message());
            d->finished(Transaction::ExitFailed, 0);
            d->destroy();
        } else {
            // Setup our new Transaction ID
            d->setup(reply.argumentAt<0>());
        }
        call->deleteLater();
    });
}

Transaction::Transaction(const QDBusObjectPath &tid)
    : d_ptr(new TransactionPrivate(this))
{
    Q_D(Transaction);

    connect(Daemon::global(), SIGNAL(daemonQuit()), SLOT(daemonQuit()));
    d->setup(tid);
}

void Transaction::connectNotify(const QMetaMethod &signal)
{
    Q_D(Transaction);
    if (!d->connectedSignals.contains(signal)) {
        d->connectedSignals << signal;

        if (d->p) {
            d->setupSignal(signal);
        }
    }
}

void Transaction::disconnectNotify(const QMetaMethod &signal)
{
    QObject::disconnectNotify(signal);
}

Transaction::Transaction(TransactionPrivate *d)
    : d_ptr(d)
{
}

void TransactionPrivate::setupSignal(const QMetaMethod &signal)
{
    Q_Q(Transaction);

    const char *signalToConnect = 0;
    const char *memberToConnect = 0;

    if (signal == QMetaMethod::fromSignal(&Transaction::category)) {
        signalToConnect = SIGNAL(Category(QString,QString,QString,QString,QString));
        memberToConnect = SIGNAL(category(QString,QString,QString,QString,QString));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::details)) {
        signalToConnect = SIGNAL(Details(QVariantMap));
        memberToConnect = SLOT(details(QVariantMap));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::distroUpgrade)) {
        signalToConnect = SIGNAL(DistroUpgrade(uint,QString,QString));
        memberToConnect = SLOT(distroUpgrade(uint,QString,QString));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::errorCode)) {
        signalToConnect = SIGNAL(ErrorCode(uint,QString));
        memberToConnect = SLOT(errorCode(uint,QString));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::files)) {
        signalToConnect = SIGNAL(Files(QString,QStringList));
        memberToConnect = SIGNAL(files(QString,QStringList));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::finished)) {
        signalToConnect = SIGNAL(Finished(uint,uint));
        memberToConnect = SLOT(finished(uint,uint));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::package)) {
        signalToConnect = SIGNAL(Package(uint,QString,QString));
        memberToConnect = SLOT(Package(uint,QString,QString));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::repoDetail)) {
        signalToConnect = SIGNAL(RepoDetail(QString,QString,bool));
        memberToConnect = SIGNAL(repoDetail(QString,QString,bool));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::repoSignatureRequired)) {
        signalToConnect = SIGNAL(RepoSignatureRequired(QString,QString,QString,QString,QString,QString,QString,uint));
        memberToConnect = SLOT(RepoSignatureRequired(QString,QString,QString,QString,QString,QString,QString,uint));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::eulaRequired)) {
        signalToConnect = SIGNAL(EulaRequired(QString,QString,QString,QString));
        memberToConnect = SIGNAL(eulaRequired(QString,QString,QString,QString));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::mediaChangeRequired)) {
        signalToConnect = SIGNAL(MediaChangeRequired(uint,QString,QString));
        memberToConnect = SLOT(mediaChangeRequired(uint,QString,QString));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::itemProgress)) {
        signalToConnect = SIGNAL(ItemProgress(QString,uint,uint));
        memberToConnect = SLOT(ItemProgress(QString,uint,uint));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::requireRestart)) {
        signalToConnect = SIGNAL(RequireRestart(uint,QString));
        memberToConnect = SLOT(requireRestart(uint,QString));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::transaction)) {
        signalToConnect = SIGNAL(Transaction(QDBusObjectPath,QString,bool,uint,uint,QString,uint,QString));
        memberToConnect = SLOT(transaction(QDBusObjectPath,QString,bool,uint,uint,QString,uint,QString));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::updateDetail)) {
        signalToConnect = SIGNAL(UpdateDetail(QString,QStringList,QStringList,QStringList,QStringList,QStringList,uint,QString,QString,uint,QString,QString));
        memberToConnect = SLOT(UpdateDetail(QString,QStringList,QStringList,QStringList,QStringList,QStringList,uint,QString,QString,uint,QString,QString));
    }

    if (signalToConnect && memberToConnect) {
        QObject::connect(p, signalToConnect, q, memberToConnect);
    }
}

Transaction::~Transaction()
{
//    qDebug() << "Destroying transaction with tid" << d_ptr->tid.path();
    delete d_ptr;
}

QDBusObjectPath Transaction::tid() const
{
    Q_D(const Transaction);
    return d->tid;
}

bool Transaction::allowCancel() const
{
    Q_D(const Transaction);
    return d->allowCancel;
}

bool Transaction::isCallerActive() const
{
    Q_D(const Transaction);
    return d->callerActive;
}

QDBusPendingReply<> Transaction::cancel()
{
    Q_D(const Transaction);
    if (d->p) {
        return d->p->Cancel();
    }
    return QDBusPendingReply<>();
}

QString Transaction::packageName(const QString &packageID)
{
    return packageID.section(QLatin1Char(';'), 0, 0);
}

QString Transaction::packageVersion(const QString &packageID)
{
    return packageID.section(QLatin1Char(';'), 1, 1);
}

QString Transaction::packageArch(const QString &packageID)
{
    return packageID.section(QLatin1Char(';'), 2, 2);
}

QString Transaction::packageData(const QString &packageID)
{
    return packageID.section(QLatin1Char(';'), 3, 3);
}

QString Transaction::lastPackage() const
{
    Q_D(const Transaction);
    return d->lastPackage;
}

uint Transaction::percentage() const
{
    Q_D(const Transaction);
    return d->percentage;
}

uint Transaction::elapsedTime() const
{
    Q_D(const Transaction);
    return d->elapsedTime;
}

uint Transaction::remainingTime() const
{
    Q_D(const Transaction);
    return d->remainingTime;
}

uint Transaction::speed() const
{
    Q_D(const Transaction);
    return d->speed;
}

qulonglong Transaction::downloadSizeRemaining() const
{
    Q_D(const Transaction);
    return d->downloadSizeRemaining;
}

Transaction::Role Transaction::role() const
{
    Q_D(const Transaction);
    return d->role;
}

QDBusPendingReply<> Transaction::setHints(const QStringList &hints)
{
    Q_D(Transaction);
    if (d->p) {
        return d->p->SetHints(hints);
    }
    return QDBusPendingReply<>();
}

QDBusPendingReply<> Transaction::setHints(const QString &hints)
{
    return setHints(QStringList{ hints });
}

Transaction::Status Transaction::status() const
{
    Q_D(const Transaction);
    return d->status;
}

Transaction::TransactionFlags Transaction::transactionFlags() const
{
    Q_D(const Transaction);
    return d->transactionFlags;
}

QDateTime Transaction::timespec() const
{
    Q_D(const Transaction);
    return d->timespec;
}

bool Transaction::succeeded() const
{
    Q_D(const Transaction);
    return d->succeeded;
}

uint Transaction::duration() const
{
    Q_D(const Transaction);
    return d->duration;
}

QString Transaction::data() const
{
    Q_D(const Transaction);
    return d->data;
}

uint Transaction::uid() const
{
    Q_D(const Transaction);
    return d->uid;
}

QString Transaction::cmdline() const
{
    Q_D(const Transaction);
    return d->cmdline;
}

Transaction::InternalError Transaction::parseError(const QString &errorName)
{
    QString error = errorName;
    if (error.startsWith(QLatin1String("org.freedesktop.packagekit."))) {
        return Transaction::InternalErrorFailedAuth;
    }

    error.remove(QLatin1String("org.freedesktop.PackageKit.Transaction."));

    if (error.startsWith(QLatin1String("PermissionDenied")) ||
        error.startsWith(QLatin1String("RefusedByPolicy"))) {
        return Transaction::InternalErrorFailedAuth;
    }

    if (error.startsWith(QLatin1String("PackageIdInvalid")) ||
        error.startsWith(QLatin1String("SearchInvalid")) ||
        error.startsWith(QLatin1String("FilterInvalid")) ||
        error.startsWith(QLatin1String("InvalidProvide")) ||
        error.startsWith(QLatin1String("InputInvalid"))) {
        return Transaction::InternalErrorInvalidInput;
    }

    if (error.startsWith(QLatin1String("PackInvalid")) ||
        error.startsWith(QLatin1String("NoSuchFile")) ||
        error.startsWith(QLatin1String("NoSuchDirectory"))) {
        return Transaction::InternalErrorInvalidFile;
    }

    if (error.startsWith(QLatin1String("NotSupported"))) {
        return Transaction::InternalErrorFunctionNotSupported;
    }

    qCWarning(PACKAGEKITQT_TRANSACTION) << "Transaction::parseError: unknown error" << errorName;
    return Transaction::InternalErrorFailed;
}

#include "moc_transaction.cpp"
<commit_msg>Also optimize PackageName & friends on Transaction class<commit_after>/*
 * This file is part of the QPackageKit project
 * Copyright (C) 2008 Adrien Bustany <madcat@mymadcat.com>
 * Copyright (C) 2010-2018 Daniel Nicoletti <dantti12@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB. If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "transaction.h"
#include "transactionprivate.h"
#include "transactionproxy.h"

#include "daemon.h"
#include "common.h"

#include <QDBusError>

Q_LOGGING_CATEGORY(PACKAGEKITQT_TRANSACTION, "packagekitqt.transaction")

using namespace PackageKit;

Transaction::Transaction()
    : d_ptr(new TransactionPrivate(this))
{
    Q_D(Transaction);

    connect(Daemon::global(), SIGNAL(daemonQuit()), SLOT(daemonQuit()));

    QDBusPendingReply<QDBusObjectPath> reply = Daemon::global()->createTransaction();
    auto watcher = new QDBusPendingCallWatcher(reply, this);
    connect(watcher, &QDBusPendingCallWatcher::finished,
            this, [this, d] (QDBusPendingCallWatcher *call)
    {
        QDBusPendingReply<QDBusObjectPath> reply = *call;
        if (reply.isError()) {
            errorCode(Transaction::ErrorInternalError, reply.error().message());
            d->finished(Transaction::ExitFailed, 0);
            d->destroy();
        } else {
            // Setup our new Transaction ID
            d->setup(reply.argumentAt<0>());
        }
        call->deleteLater();
    });
}

Transaction::Transaction(const QDBusObjectPath &tid)
    : d_ptr(new TransactionPrivate(this))
{
    Q_D(Transaction);

    connect(Daemon::global(), SIGNAL(daemonQuit()), SLOT(daemonQuit()));
    d->setup(tid);
}

void Transaction::connectNotify(const QMetaMethod &signal)
{
    Q_D(Transaction);
    if (!d->connectedSignals.contains(signal)) {
        d->connectedSignals << signal;

        if (d->p) {
            d->setupSignal(signal);
        }
    }
}

void Transaction::disconnectNotify(const QMetaMethod &signal)
{
    QObject::disconnectNotify(signal);
}

Transaction::Transaction(TransactionPrivate *d)
    : d_ptr(d)
{
}

void TransactionPrivate::setupSignal(const QMetaMethod &signal)
{
    Q_Q(Transaction);

    const char *signalToConnect = 0;
    const char *memberToConnect = 0;

    if (signal == QMetaMethod::fromSignal(&Transaction::category)) {
        signalToConnect = SIGNAL(Category(QString,QString,QString,QString,QString));
        memberToConnect = SIGNAL(category(QString,QString,QString,QString,QString));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::details)) {
        signalToConnect = SIGNAL(Details(QVariantMap));
        memberToConnect = SLOT(details(QVariantMap));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::distroUpgrade)) {
        signalToConnect = SIGNAL(DistroUpgrade(uint,QString,QString));
        memberToConnect = SLOT(distroUpgrade(uint,QString,QString));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::errorCode)) {
        signalToConnect = SIGNAL(ErrorCode(uint,QString));
        memberToConnect = SLOT(errorCode(uint,QString));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::files)) {
        signalToConnect = SIGNAL(Files(QString,QStringList));
        memberToConnect = SIGNAL(files(QString,QStringList));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::finished)) {
        signalToConnect = SIGNAL(Finished(uint,uint));
        memberToConnect = SLOT(finished(uint,uint));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::package)) {
        signalToConnect = SIGNAL(Package(uint,QString,QString));
        memberToConnect = SLOT(Package(uint,QString,QString));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::repoDetail)) {
        signalToConnect = SIGNAL(RepoDetail(QString,QString,bool));
        memberToConnect = SIGNAL(repoDetail(QString,QString,bool));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::repoSignatureRequired)) {
        signalToConnect = SIGNAL(RepoSignatureRequired(QString,QString,QString,QString,QString,QString,QString,uint));
        memberToConnect = SLOT(RepoSignatureRequired(QString,QString,QString,QString,QString,QString,QString,uint));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::eulaRequired)) {
        signalToConnect = SIGNAL(EulaRequired(QString,QString,QString,QString));
        memberToConnect = SIGNAL(eulaRequired(QString,QString,QString,QString));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::mediaChangeRequired)) {
        signalToConnect = SIGNAL(MediaChangeRequired(uint,QString,QString));
        memberToConnect = SLOT(mediaChangeRequired(uint,QString,QString));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::itemProgress)) {
        signalToConnect = SIGNAL(ItemProgress(QString,uint,uint));
        memberToConnect = SLOT(ItemProgress(QString,uint,uint));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::requireRestart)) {
        signalToConnect = SIGNAL(RequireRestart(uint,QString));
        memberToConnect = SLOT(requireRestart(uint,QString));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::transaction)) {
        signalToConnect = SIGNAL(Transaction(QDBusObjectPath,QString,bool,uint,uint,QString,uint,QString));
        memberToConnect = SLOT(transaction(QDBusObjectPath,QString,bool,uint,uint,QString,uint,QString));
    } else if (signal == QMetaMethod::fromSignal(&Transaction::updateDetail)) {
        signalToConnect = SIGNAL(UpdateDetail(QString,QStringList,QStringList,QStringList,QStringList,QStringList,uint,QString,QString,uint,QString,QString));
        memberToConnect = SLOT(UpdateDetail(QString,QStringList,QStringList,QStringList,QStringList,QStringList,uint,QString,QString,uint,QString,QString));
    }

    if (signalToConnect && memberToConnect) {
        QObject::connect(p, signalToConnect, q, memberToConnect);
    }
}

Transaction::~Transaction()
{
//    qDebug() << "Destroying transaction with tid" << d_ptr->tid.path();
    delete d_ptr;
}

QDBusObjectPath Transaction::tid() const
{
    Q_D(const Transaction);
    return d->tid;
}

bool Transaction::allowCancel() const
{
    Q_D(const Transaction);
    return d->allowCancel;
}

bool Transaction::isCallerActive() const
{
    Q_D(const Transaction);
    return d->callerActive;
}

QDBusPendingReply<> Transaction::cancel()
{
    Q_D(const Transaction);
    if (d->p) {
        return d->p->Cancel();
    }
    return QDBusPendingReply<>();
}

QString Transaction::packageName(const QString &packageID)
{
    QString ret;
    ret = packageID.left(packageID.indexOf(QLatin1Char(';')));
    return ret;
}

QString Transaction::packageVersion(const QString &packageID)
{
    QString ret;
    int start = packageID.indexOf(QLatin1Char(';'));
    if (start == -1) {
        return ret;
    }
    int end = packageID.indexOf(QLatin1Char(';'), start);
    if (end == -1) {
        return ret;
    }
    ret = packageID.mid(start, end - start);
    return ret;
}

QString Transaction::packageArch(const QString &packageID)
{
    QString ret;
    int start = packageID.indexOf(QLatin1Char(';'));
    if (start == -1) {
        return ret;
    }
    start = packageID.indexOf(QLatin1Char(';'), start);
    if (start == -1) {
        return ret;
    }
    int end = packageID.indexOf(QLatin1Char(';'), start);
    if (end == -1) {
        return ret;
    }
    ret = packageID.mid(start, end - start);
    return ret;
}

QString Transaction::packageData(const QString &packageID)
{
    QString ret;
    int start = packageID.indexOf(QLatin1Char(';'));
    if (start == -1) {
        return ret;
    }
    start = packageID.indexOf(QLatin1Char(';'), start);
    if (start == -1) {
        return ret;
    }
    start = packageID.indexOf(QLatin1Char(';'), start);
    if (start == -1) {
        return ret;
    }
    int end = packageID.indexOf(QLatin1Char(';'), start);
    if (end == -1) {
        return ret;
    }
    ret = packageID.mid(start, end - start);
    return ret;
}

QString Transaction::lastPackage() const
{
    Q_D(const Transaction);
    return d->lastPackage;
}

uint Transaction::percentage() const
{
    Q_D(const Transaction);
    return d->percentage;
}

uint Transaction::elapsedTime() const
{
    Q_D(const Transaction);
    return d->elapsedTime;
}

uint Transaction::remainingTime() const
{
    Q_D(const Transaction);
    return d->remainingTime;
}

uint Transaction::speed() const
{
    Q_D(const Transaction);
    return d->speed;
}

qulonglong Transaction::downloadSizeRemaining() const
{
    Q_D(const Transaction);
    return d->downloadSizeRemaining;
}

Transaction::Role Transaction::role() const
{
    Q_D(const Transaction);
    return d->role;
}

QDBusPendingReply<> Transaction::setHints(const QStringList &hints)
{
    Q_D(Transaction);
    if (d->p) {
        return d->p->SetHints(hints);
    }
    return QDBusPendingReply<>();
}

QDBusPendingReply<> Transaction::setHints(const QString &hints)
{
    return setHints(QStringList{ hints });
}

Transaction::Status Transaction::status() const
{
    Q_D(const Transaction);
    return d->status;
}

Transaction::TransactionFlags Transaction::transactionFlags() const
{
    Q_D(const Transaction);
    return d->transactionFlags;
}

QDateTime Transaction::timespec() const
{
    Q_D(const Transaction);
    return d->timespec;
}

bool Transaction::succeeded() const
{
    Q_D(const Transaction);
    return d->succeeded;
}

uint Transaction::duration() const
{
    Q_D(const Transaction);
    return d->duration;
}

QString Transaction::data() const
{
    Q_D(const Transaction);
    return d->data;
}

uint Transaction::uid() const
{
    Q_D(const Transaction);
    return d->uid;
}

QString Transaction::cmdline() const
{
    Q_D(const Transaction);
    return d->cmdline;
}

Transaction::InternalError Transaction::parseError(const QString &errorName)
{
    QString error = errorName;
    if (error.startsWith(QLatin1String("org.freedesktop.packagekit."))) {
        return Transaction::InternalErrorFailedAuth;
    }

    error.remove(QLatin1String("org.freedesktop.PackageKit.Transaction."));

    if (error.startsWith(QLatin1String("PermissionDenied")) ||
        error.startsWith(QLatin1String("RefusedByPolicy"))) {
        return Transaction::InternalErrorFailedAuth;
    }

    if (error.startsWith(QLatin1String("PackageIdInvalid")) ||
        error.startsWith(QLatin1String("SearchInvalid")) ||
        error.startsWith(QLatin1String("FilterInvalid")) ||
        error.startsWith(QLatin1String("InvalidProvide")) ||
        error.startsWith(QLatin1String("InputInvalid"))) {
        return Transaction::InternalErrorInvalidInput;
    }

    if (error.startsWith(QLatin1String("PackInvalid")) ||
        error.startsWith(QLatin1String("NoSuchFile")) ||
        error.startsWith(QLatin1String("NoSuchDirectory"))) {
        return Transaction::InternalErrorInvalidFile;
    }

    if (error.startsWith(QLatin1String("NotSupported"))) {
        return Transaction::InternalErrorFunctionNotSupported;
    }

    qCWarning(PACKAGEKITQT_TRANSACTION) << "Transaction::parseError: unknown error" << errorName;
    return Transaction::InternalErrorFailed;
}

#include "moc_transaction.cpp"
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef AST_RETURN_H
#define AST_RETURN_H

#include <memory>

#include <boost/intrusive_ptr.hpp>
#include <boost/fusion/include/adapt_struct.hpp>

#include "ast/Deferred.hpp"
#include "ast/Value.hpp"

namespace eddic {

class Context;

namespace ast {

struct ASTReturn {
    Value value;

    mutable long references;
    ASTReturn() : references(0) {}
};

typedef Deferred<ASTReturn, boost::intrusive_ptr<ASTReturn>> Return;

} //end of ast

} //end of eddic

//Adapt the struct for the AST
BOOST_FUSION_ADAPT_STRUCT(
    eddic::ast::Return,
    (eddic::ast::Value, Content->value)
)

#endif
<commit_msg>Remove useless forward declaration<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef AST_RETURN_H
#define AST_RETURN_H

#include <memory>

#include <boost/intrusive_ptr.hpp>
#include <boost/fusion/include/adapt_struct.hpp>

#include "ast/Deferred.hpp"
#include "ast/Value.hpp"

namespace eddic {

namespace ast {

struct ASTReturn {
    Value value;

    mutable long references;
    ASTReturn() : references(0) {}
};

typedef Deferred<ASTReturn, boost::intrusive_ptr<ASTReturn>> Return;

} //end of ast

} //end of eddic

//Adapt the struct for the AST
BOOST_FUSION_ADAPT_STRUCT(
    eddic::ast::Return,
    (eddic::ast::Value, Content->value)
)

#endif
<|endoftext|>


<commit_before>#pragma once

template <typename T> inline bool binarynode_t<T>::empty() const
{
	return this->_data == 0 || this->_tree == 0 || this->_ring < 0 || this->_branch < 0;
}

template <typename T> inline size_t binarynode_t<T>::index() const
{
	return tree_index(this->_ring, this->_branch, 2);
}

template <typename T> inline binaryiterator_t<T> binaryiterator_t<T>::left() const
{
	return this->_node != 0 && this->_node->_left != 0 ? binaryiterator_t<T>(this->_node->_left) : binaryiterator_t<T>();
}
template <typename T> inline binaryiterator_t<T> binaryiterator_t<T>::left(const T& item)
{
	if (this->_node != 0 && this->_node->_tree != 0)
	{
		int32_t ring = this->_node->_ring + 1;
		int32_t branch = (this->_node->_branch * 2) + 1;
		int32_t index = (((int32_t)pow(2.0f, (float)ring)) - 1) + branch;
		binarynode_t<T>& node = (this->_node->_tree->_registry[index] = binarynode_t<T>(*(this->_node->_tree), ring, branch, item));
		node._up = this->_node;
		this->_node->_left = treereference_t<binarynode_t<T> >(this->_node->_tree->_registry, index);
		return binaryiterator_t<T>(this->_node->_left);
	}

	return binaryiterator_t<T>();
}
template <typename T> inline binaryiterator_t<T> binaryiterator_t<T>::right() const
{
	return this->_node != 0 && this->_node->_right != 0 ? binaryiterator_t<T>(this->_node->_right) : binaryiterator_t<T>();
}
template <typename T> inline binaryiterator_t<T> binaryiterator_t<T>::right(const T& item)
{
	if (this->_node != 0)
	{
		int32_t ring = this->_node->_ring + 1;
		int32_t branch = this->_node->_branch * 2;
		int32_t index = (((int32_t)pow(2.0f, (float)ring)) - 1) + branch;
		binarynode_t<T>& node = (this->_node->_tree->_registry[index] = binarynode_t<T>(*(this->_node->_tree), ring, branch, item));
		node._up = this->_node;
		this->_node->_right = treereference_t<binarynode_t<T> >(this->_node->_tree->_registry, index);
		return binaryiterator_t<T>(this->_node->_right);
	}

	return binaryiterator_t<T>();
}
template <typename T> inline binaryiterator_t<T> binaryiterator_t<T>::parent()
{
    return this->_up != 0 ? binaryiterator_t<T>(this->_up) : binaryiterator_t<T>();
}

template <typename T> inline binaryiterator_t<T> binaryiterator_t<T>::remove()
{
	if (this->_node != 0)
	{
		treereference_t<binarynode_t<T> > prev = this->_node;
		if (prev->_up != 0)
		{
			if (prev->_up->_left == prev) { prev->_up->_left = -1; }
			else if (prev->_up->_right == prev) { prev->_up->_right = -1; }
		}

		this->_node = prev->_up;
		prev->_tree->_registry.remove(prev->index());
		if (this->_node != 0)
		{
			return binaryiterator_t<T>(this->_node);
		}
	}

	return binaryiterator_t<T>();
}

template <typename T> inline bool binaryiterator_t<T>::has_left() const
{
	return this->_node != 0 && this->_node->_left != 0;
}
template <typename T> inline bool binaryiterator_t<T>::has_right() const
{
	return this->_node != 0 && this->_node->_right != 0;
}
template <typename T> inline bool binaryiterator_t<T>::root() const
{
	return this->_node != 0 && this->_node->_parent == 0;
}
template <typename T> inline bool binaryiterator_t<T>::leaf() const
{
	return this->_node != 0 && this->_node->_left == 0 && this->_node->_right == 0;
}

template <typename T> inline bool binaryiterator_t<T>::empty() const
{
	return this->_node == 0;
}

template <typename T> inline binaryiterator_t<T>& binaryiterator_t<T>::operator++()
{
	if (this->_node != 0)
	{
		this->_node = this->_node->_left;
	}

	return *this;
}
template <typename T> inline binaryiterator_t<T>& binaryiterator_t<T>::operator--()
{
	if (this->_node != 0)
	{
		this->_node = this->_node->_right;
	}

	return *this;
}
template <typename T> inline T& binaryiterator_t<T>::operator*() const
{
	return *(this->_node->_data);
}
template <typename T> inline bool binaryiterator_t<T>::operator==(const binaryiterator_t<T>& other) const
{
	return this->_node == other._node;
}
template <typename T> inline bool binaryiterator_t<T>::operator!=(const binaryiterator_t<T>& other) const
{
	return this->_node != other._node;
}

template <typename T> inline binaryiterator_t<T> binarytree_t<T>::set_root(const T& item)
{
	this->_registry.zero();
	this->_registry[0] = binarynode_t<T>(*this, 0, 0, item);
	return iterator(treereference_t<binarynode_t<T> >(this->_registry, 0));
}

template <typename T> inline binaryiterator_t<T> binarytree_t<T>::search(const T& item)
{
	for (size_t i = 0; i < this->_registry.capacity(); i++)
	{
		treereference_t<binarynode_t<T> > node(this->_registry, i);
		if (!node.empty() && !node->empty() && memcmp(&(node->_data), &item, sizeof(T)) == 0)
		{
			return binaryiterator_t<T>(node);
		}
	}

	return binaryiterator_t<T>();
}

template <typename T> inline void binarytree_t<T>::each(iterationfunc callback)
{
	execute_each(treereference_t<binarynode_t<T> >(this->_registry, 0), callback);
}
template <typename T> inline void binarytree_t<T>::path(iterationfunc callback)
{
	execute_path(treereference_t<binarynode_t<T> >(this->_registry, 0), callback);
}

template <typename T> inline void binarytree_t<T>::clear()
{
	this->_registry.clear();
}

template <typename T> int32_t binarytree_t<T>::execute_each(const treereference_t<binarynode_t<T> >& node, iterationfunc callback)
{
	int32_t result = 1;
	if (node != 0 && !node.empty() && !node->empty() && callback != 0)
	{
		result = callback(node, node->_data);
		if (result != 0)
		{
			result = execute_each(node->_left, callback);
			if (result != 0)
			{
				result = execute_each(node->_right, callback);
			}
		}
	}

	return result;
}
template <typename T> int32_t binarytree_t<T>::execute_path(const treereference_t<binarynode_t<T> >& node, iterationfunc callback)
{
	int32_t result = 0;
	if (node != 0 && !node.empty() && !node->empty() && callback != 0)
	{
		result = callback(node, node->_data);
		if (result != 0)
		{
			if (result > 0)
			{
				return execute_path(node->_left, callback);
			}
			else
			{
				return execute_path(node->_right, callback);
			}
		}
	}

	return result;
}<commit_msg>binary fixes<commit_after>#pragma once

template <typename T> inline bool binarynode_t<T>::empty() const
{
	return this->_tree == 0 || this->_ring < 0 || this->_branch < 0;
}

template <typename T> inline size_t binarynode_t<T>::index() const
{
	return tree_index(this->_ring, this->_branch, 2);
}

template <typename T> inline binaryiterator_t<T> binaryiterator_t<T>::left() const
{
	return this->_node != 0 && this->_node->_left != 0 ? binaryiterator_t<T>(this->_node->_left) : binaryiterator_t<T>();
}
template <typename T> inline binaryiterator_t<T> binaryiterator_t<T>::left(const T& item)
{
	if (this->_node != 0 && this->_node->_tree != 0)
	{
		int32_t ring = this->_node->_ring + 1;
		int32_t branch = (this->_node->_branch * 2) + 1;
		int32_t index = tree_index(ring, branch, 2);
		binarynode_t<T>& node = (this->_node->_tree->_registry[index] = binarynode_t<T>(*(this->_node->_tree), ring, branch, item));
		node._up = this->_node;
		this->_node->_left = treereference_t<binarynode_t<T> >(this->_node->_tree->_registry, index);
		return binaryiterator_t<T>(this->_node->_left);
	}

	return binaryiterator_t<T>();
}
template <typename T> inline binaryiterator_t<T> binaryiterator_t<T>::right() const
{
	return this->_node != 0 && this->_node->_right != 0 ? binaryiterator_t<T>(this->_node->_right) : binaryiterator_t<T>();
}
template <typename T> inline binaryiterator_t<T> binaryiterator_t<T>::right(const T& item)
{
	if (this->_node != 0)
	{
		int32_t ring = this->_node->_ring + 1;
		int32_t branch = this->_node->_branch * 2;
		int32_t index = tree_index(ring, branch, 2);
		binarynode_t<T>& node = (this->_node->_tree->_registry[index] = binarynode_t<T>(*(this->_node->_tree), ring, branch, item));
		node._up = this->_node;
		this->_node->_right = treereference_t<binarynode_t<T> >(this->_node->_tree->_registry, index);
		return binaryiterator_t<T>(this->_node->_right);
	}

	return binaryiterator_t<T>();
}
template <typename T> inline binaryiterator_t<T> binaryiterator_t<T>::parent()
{
    return this->_up != 0 ? binaryiterator_t<T>(this->_up) : binaryiterator_t<T>();
}

template <typename T> inline binaryiterator_t<T> binaryiterator_t<T>::remove()
{
	if (this->_node != 0)
	{
		treereference_t<binarynode_t<T> > prev = this->_node;
		if (prev->_up != 0)
		{
			if (prev->_up->_left == prev) { prev->_up->_left = -1; }
			else if (prev->_up->_right == prev) { prev->_up->_right = -1; }
		}

		this->_node = prev->_up;
		prev->_tree->_registry.remove(prev->index());
		if (this->_node != 0)
		{
			return binaryiterator_t<T>(this->_node);
		}
	}

	return binaryiterator_t<T>();
}

template <typename T> inline bool binaryiterator_t<T>::has_left() const
{
	return this->_node != 0 && this->_node->_left != 0;
}
template <typename T> inline bool binaryiterator_t<T>::has_right() const
{
	return this->_node != 0 && this->_node->_right != 0;
}
template <typename T> inline bool binaryiterator_t<T>::root() const
{
	return this->_node != 0 && this->_node->_parent == 0;
}
template <typename T> inline bool binaryiterator_t<T>::leaf() const
{
	return this->_node != 0 && this->_node->_left == 0 && this->_node->_right == 0;
}

template <typename T> inline bool binaryiterator_t<T>::empty() const
{
	return this->_node == 0;
}

template <typename T> inline binaryiterator_t<T>& binaryiterator_t<T>::operator++()
{
	if (this->_node != 0)
	{
		this->_node = this->_node->_left;
	}

	return *this;
}
template <typename T> inline binaryiterator_t<T>& binaryiterator_t<T>::operator--()
{
	if (this->_node != 0)
	{
		this->_node = this->_node->_right;
	}

	return *this;
}
template <typename T> inline T& binaryiterator_t<T>::operator*() const
{
	return *(this->_node->_data);
}
template <typename T> inline bool binaryiterator_t<T>::operator==(const binaryiterator_t<T>& other) const
{
	return this->_node == other._node;
}
template <typename T> inline bool binaryiterator_t<T>::operator!=(const binaryiterator_t<T>& other) const
{
	return this->_node != other._node;
}

template <typename T> inline binaryiterator_t<T> binarytree_t<T>::set_root(const T& item)
{
	this->_registry.zero();
	this->_registry[0] = binarynode_t<T>(*this, 0, 0, item);
	return iterator(treereference_t<binarynode_t<T> >(this->_registry, 0));
}

template <typename T> inline binaryiterator_t<T> binarytree_t<T>::search(const T& item)
{
	for (size_t i = 0; i < this->_registry.capacity(); i++)
	{
		treereference_t<binarynode_t<T> > node(this->_registry, i);
		if (!node.empty() && !node->empty() && memcmp(&(node->_data), &item, sizeof(T)) == 0)
		{
			return binaryiterator_t<T>(node);
		}
	}

	return binaryiterator_t<T>();
}

template <typename T> inline void binarytree_t<T>::each(iterationfunc callback)
{
	execute_each(treereference_t<binarynode_t<T> >(this->_registry, 0), callback);
}
template <typename T> inline void binarytree_t<T>::path(iterationfunc callback)
{
	execute_path(treereference_t<binarynode_t<T> >(this->_registry, 0), callback);
}

template <typename T> inline void binarytree_t<T>::clear()
{
	this->_registry.clear();
}

template <typename T> int32_t binarytree_t<T>::execute_each(const treereference_t<binarynode_t<T> >& node, iterationfunc callback)
{
	int32_t result = 1;
	if (node != 0 && !node.empty() && !node->empty() && callback != 0)
	{
		result = callback(node, node->_data);
		if (result != 0)
		{
			result = execute_each(node->_left, callback);
			if (result != 0)
			{
				result = execute_each(node->_right, callback);
			}
		}
	}

	return result;
}
template <typename T> int32_t binarytree_t<T>::execute_path(const treereference_t<binarynode_t<T> >& node, iterationfunc callback)
{
	int32_t result = 0;
	if (node != 0 && !node.empty() && !node->empty() && callback != 0)
	{
		result = callback(node, node->_data);
		if (result != 0)
		{
			if (result > 0)
			{
				return execute_path(node->_left, callback);
			}
			else
			{
				return execute_path(node->_right, callback);
			}
		}
	}

	return result;
}<|endoftext|>