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

#ifndef _WEBDAV_UCP_PROVIDER_HXX
#define _WEBDAV_UCP_PROVIDER_HXX

#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_
#include <com/sun/star/beans/Property.hpp>
#endif

#ifndef _DAVSESSIONFACTORY_HXX_
#include "DAVSessionFactory.hxx"
#endif

#ifndef _UCBHELPER_PROVIDERHELPER_HXX
#include <ucbhelper/providerhelper.hxx>
#endif

#ifndef _WEBDAV_UCP_PROPERTYMAP_HXX
#include "PropertyMap.hxx"
#endif

namespace webdav_ucp {

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

// UNO service name for the provider. This name will be used by the UCB to
// create instances of the provider.
#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME \
                "com.sun.star.ucb.WebDAVContentProvider"
#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME_LENGTH 38

// URL scheme. This is the scheme the provider will be able to create
// contents for. The UCB will select the provider ( i.e. in order to create
// contents ) according to this scheme.
#define WEBDAV_URL_SCHEME \
                "vnd.sun.star.webdav"
#define WEBDAV_URL_SCHEME_LENGTH    19

#define HTTP_URL_SCHEME         "http"
#define HTTP_URL_SCHEME_LENGTH  4

#define HTTPS_URL_SCHEME        "https"
#define HTTPS_URL_SCHEME_LENGTH 5

#define FTP_URL_SCHEME "ftp"

#define HTTP_CONTENT_TYPE \
                "application/" HTTP_URL_SCHEME "-content"

#define WEBDAV_CONTENT_TYPE    HTTP_CONTENT_TYPE
#define WEBDAV_COLLECTION_TYPE \
                "application/" WEBDAV_URL_SCHEME "-collection"

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

class ContentProvider : public ::ucbhelper::ContentProviderImplHelper
{
    rtl::Reference< DAVSessionFactory > m_xDAVSessionFactory;
    PropertyMap * m_pProps;

public:
    ContentProvider( const ::com::sun::star::uno::Reference<
                        ::com::sun::star::lang::XMultiServiceFactory >& rSMgr );
    virtual ~ContentProvider();

    // XInterface
    XINTERFACE_DECL()

    // XTypeProvider
    XTYPEPROVIDER_DECL()

    // XServiceInfo
    XSERVICEINFO_DECL()

    // XContentProvider
    virtual ::com::sun::star::uno::Reference<
                ::com::sun::star::ucb::XContent > SAL_CALL
    queryContent( const ::com::sun::star::uno::Reference<
                    ::com::sun::star::ucb::XContentIdentifier >& Identifier )
        throw( ::com::sun::star::ucb::IllegalIdentifierException,
               ::com::sun::star::uno::RuntimeException );

    //////////////////////////////////////////////////////////////////////
    // Additional interfaces
    //////////////////////////////////////////////////////////////////////

    //////////////////////////////////////////////////////////////////////
    // Non-interface methods.
    //////////////////////////////////////////////////////////////////////

    rtl::Reference< DAVSessionFactory > getDAVSessionFactory()
    { return m_xDAVSessionFactory; }

    bool getProperty( const ::rtl::OUString & rPropName,
                      ::com::sun::star::beans::Property & rProp,
                      bool bStrict = false );
};

}

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.9.72); FILE MERGED 2008/04/01 16:02:29 thb 1.9.72.3: #i85898# Stripping all external header guards 2008/04/01 12:58:28 thb 1.9.72.2: #i85898# Stripping all external header guards 2008/03/31 15:30:32 rt 1.9.72.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: webdavprovider.hxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _WEBDAV_UCP_PROVIDER_HXX
#define _WEBDAV_UCP_PROVIDER_HXX

#include <rtl/ref.hxx>
#include <com/sun/star/beans/Property.hpp>
#include "DAVSessionFactory.hxx"
#include <ucbhelper/providerhelper.hxx>
#include "PropertyMap.hxx"

namespace webdav_ucp {

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

// UNO service name for the provider. This name will be used by the UCB to
// create instances of the provider.
#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME \
                "com.sun.star.ucb.WebDAVContentProvider"
#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME_LENGTH 38

// URL scheme. This is the scheme the provider will be able to create
// contents for. The UCB will select the provider ( i.e. in order to create
// contents ) according to this scheme.
#define WEBDAV_URL_SCHEME \
                "vnd.sun.star.webdav"
#define WEBDAV_URL_SCHEME_LENGTH    19

#define HTTP_URL_SCHEME         "http"
#define HTTP_URL_SCHEME_LENGTH  4

#define HTTPS_URL_SCHEME        "https"
#define HTTPS_URL_SCHEME_LENGTH 5

#define FTP_URL_SCHEME "ftp"

#define HTTP_CONTENT_TYPE \
                "application/" HTTP_URL_SCHEME "-content"

#define WEBDAV_CONTENT_TYPE    HTTP_CONTENT_TYPE
#define WEBDAV_COLLECTION_TYPE \
                "application/" WEBDAV_URL_SCHEME "-collection"

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

class ContentProvider : public ::ucbhelper::ContentProviderImplHelper
{
    rtl::Reference< DAVSessionFactory > m_xDAVSessionFactory;
    PropertyMap * m_pProps;

public:
    ContentProvider( const ::com::sun::star::uno::Reference<
                        ::com::sun::star::lang::XMultiServiceFactory >& rSMgr );
    virtual ~ContentProvider();

    // XInterface
    XINTERFACE_DECL()

    // XTypeProvider
    XTYPEPROVIDER_DECL()

    // XServiceInfo
    XSERVICEINFO_DECL()

    // XContentProvider
    virtual ::com::sun::star::uno::Reference<
                ::com::sun::star::ucb::XContent > SAL_CALL
    queryContent( const ::com::sun::star::uno::Reference<
                    ::com::sun::star::ucb::XContentIdentifier >& Identifier )
        throw( ::com::sun::star::ucb::IllegalIdentifierException,
               ::com::sun::star::uno::RuntimeException );

    //////////////////////////////////////////////////////////////////////
    // Additional interfaces
    //////////////////////////////////////////////////////////////////////

    //////////////////////////////////////////////////////////////////////
    // Non-interface methods.
    //////////////////////////////////////////////////////////////////////

    rtl::Reference< DAVSessionFactory > getDAVSessionFactory()
    { return m_xDAVSessionFactory; }

    bool getProperty( const ::rtl::OUString & rPropName,
                      ::com::sun::star::beans::Property & rProp,
                      bool bStrict = false );
};

}

#endif
<|endoftext|>


<commit_before>/*
    Copyright (c) 2006 Volker Krause <volker.krause@rwth-aachen.de>

    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 "collection.h"
#include "collectionlistjob.h"

#include <QDebug>
#include <QHash>
#include <QStringList>
#include <QTimer>

using namespace PIM;

class PIM::CollectionListJobPrivate
{
  public:
    bool recursive;
    QByteArray prefix;
    QByteArray tag;
    Collection::List collections;
};

PIM::CollectionListJob::CollectionListJob( const QByteArray &prefix, bool recursive, QObject *parent ) :
    Job( parent ),
    d( new CollectionListJobPrivate )
{
  d->prefix = prefix;
  d->recursive = recursive;
}

PIM::CollectionListJob::~CollectionListJob()
{
  delete d;
}

PIM::Collection::List PIM::CollectionListJob::collections() const
{
  return d->collections;
}

void PIM::CollectionListJob::doStart()
{
  d->tag = newTag();
  writeData( d->tag + " LIST \"" + d->prefix + "\" " + ( d->recursive ? '*' : '%' ) );
}

void PIM::CollectionListJob::handleResponse( const QByteArray & tag, const QByteArray & data )
{
  if ( tag == d->tag ) {
    if ( !data.startsWith( "OK" ) )
      setError( Unknown );
    emit done( this );
    return;
  }
  if ( tag == "*" && data.startsWith( "LIST" ) ) {
    int begin = data.indexOf( '(' );
    int end = data.indexOf( ')' );
    QList<QByteArray> attributes = data.mid( begin, end - begin - 1 ).split( ' ' );
    begin = data.indexOf( '"', end );
    char delim = data[begin + 1];
    begin = data.indexOf( ' ', begin + 2 );

    QByteArray folderName;
    if ( data[begin + 1] == '"' )
      folderName = data.mid( begin + 2, data.lastIndexOf( '"' ) - begin - 2 );
    else
      folderName = data.mid( begin + 1 ); // ### strip trailing newline?
    // add prefix
    if ( d->prefix.endsWith( Collection::delimiter() ) )
      folderName.prepend( d->prefix );
    else
      folderName.prepend( d->prefix + Collection::delimiter() );
    // strip trailing delimiters
    if ( folderName.endsWith( delim ) )
      folderName.truncate( data.length() - 1 );

    QByteArray parentName = folderName.mid( 0, folderName.lastIndexOf( delim ) + 1 );
    // strip trailing delimiter, but not if this is root
    if ( parentName.endsWith( Collection::delimiter() ) && parentName != Collection::root() )
      parentName.truncate( parentName.length() - 1 );
    Collection *col = new Collection( folderName );
    col->setParent( parentName );

    // determine collection type, TODO: search folder
    if ( parentName == Collection::root() ) {
      if ( folderName == Collection::searchFolder() )
        col->setType( Collection::VirtualParent );
      else
        col->setType( Collection::Resource );
    } else if ( parentName == Collection::searchFolder() )
      col->setType( Collection::Virtual );
    else
      col->setType( Collection::Folder );

    QStringList contentTypes;
    if ( !attributes.contains( "\Noinferiors" ) )
      contentTypes << "akonadi/folder";
    col->setContentTypes( contentTypes );

    d->collections.append( col );
    qDebug() << "received list response: delim: " << delim << " name: " << folderName << "attrs: " << attributes << " parent: " << parentName;
  }
  qDebug() << "unhandled server response in collection list job" << tag << data;
}

#include "collectionlistjob.moc"
<commit_msg>List returns an absolute path.<commit_after>/*
    Copyright (c) 2006 Volker Krause <volker.krause@rwth-aachen.de>

    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 "collection.h"
#include "collectionlistjob.h"

#include <QDebug>
#include <QHash>
#include <QStringList>
#include <QTimer>

using namespace PIM;

class PIM::CollectionListJobPrivate
{
  public:
    bool recursive;
    QByteArray prefix;
    QByteArray tag;
    Collection::List collections;
};

PIM::CollectionListJob::CollectionListJob( const QByteArray &prefix, bool recursive, QObject *parent ) :
    Job( parent ),
    d( new CollectionListJobPrivate )
{
  d->prefix = prefix;
  d->recursive = recursive;
}

PIM::CollectionListJob::~CollectionListJob()
{
  delete d;
}

PIM::Collection::List PIM::CollectionListJob::collections() const
{
  return d->collections;
}

void PIM::CollectionListJob::doStart()
{
  d->tag = newTag();
  writeData( d->tag + " LIST \"" + d->prefix + "\" " + ( d->recursive ? '*' : '%' ) );
}

void PIM::CollectionListJob::handleResponse( const QByteArray & tag, const QByteArray & data )
{
  if ( tag == d->tag ) {
    if ( !data.startsWith( "OK" ) )
      setError( Unknown );
    emit done( this );
    return;
  }
  if ( tag == "*" && data.startsWith( "LIST" ) ) {
    int begin = data.indexOf( '(' );
    int end = data.indexOf( ')' );
    QList<QByteArray> attributes = data.mid( begin, end - begin - 1 ).split( ' ' );
    begin = data.indexOf( '"', end );
    char delim = data[begin + 1];
    begin = data.indexOf( ' ', begin + 2 );

    QByteArray folderName;
    if ( data[begin + 1] == '"' )
      folderName = data.mid( begin + 2, data.lastIndexOf( '"' ) - begin - 2 );
    else
      folderName = data.mid( begin + 1 ); // ### strip trailing newline?
    // strip trailing delimiters
    if ( folderName.endsWith( delim ) )
      folderName.truncate( data.length() - 1 );

    QByteArray parentName = folderName.mid( 0, folderName.lastIndexOf( delim ) + 1 );
    // strip trailing delimiter, but not if this is root
    if ( parentName.endsWith( Collection::delimiter() ) && parentName != Collection::root() )
      parentName.truncate( parentName.length() - 1 );
    Collection *col = new Collection( folderName );
    col->setParent( parentName );

    // determine collection type, TODO: search folder
    if ( parentName == Collection::root() ) {
      if ( folderName == Collection::searchFolder() )
        col->setType( Collection::VirtualParent );
      else
        col->setType( Collection::Resource );
    } else if ( parentName == Collection::searchFolder() )
      col->setType( Collection::Virtual );
    else
      col->setType( Collection::Folder );

    QStringList contentTypes;
    if ( !attributes.contains( "\Noinferiors" ) )
      contentTypes << "akonadi/folder";
    col->setContentTypes( contentTypes );

    d->collections.append( col );
    qDebug() << "received list response: delim: " << delim << " name: " << folderName << "attrs: " << attributes << " parent: " << parentName;
  }
  qDebug() << "unhandled server response in collection list job" << tag << data;
}

#include "collectionlistjob.moc"
<|endoftext|>


<commit_before>// ------------------------------------------------------------------------
// jack-connections.cpp: Utility class to manage JACK port connections
// Copyright (C) 2008 Kai Vehmanen
//
// Attributes:
//     eca-style-version: 3 (see Ecasound Programmer's Guide)
//
// 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-1307  USA
// ------------------------------------------------------------------------

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <string>
#include <iostream>

#include <jack/jack.h>
#include <sys/types.h>
#include <unistd.h>

#include <kvu_numtostr.h>

#include "eca-logger.h"
#include "jack-connections.h"

using std::string;

JACK_CONNECTIONS::JACK_CONNECTIONS(void)
{
}

JACK_CONNECTIONS::~JACK_CONNECTIONS(void)
{
}

static jack_client_t *priv_prepare(void)
{
 int pid = getpid();
 std::string clntname = "libecasound-ctrl-" + kvu_numtostr(pid);
 jack_client_t *client = jack_client_new (clntname.c_str());
 return client;
}

static void priv_cleanup(jack_client_t *client)
{
  jack_client_close(client);
}

bool JACK_CONNECTIONS::connect(const char* src, const char* dest)
{

  int result = -1;
  jack_client_t *client = priv_prepare();
  if (client != 0) {
    result = jack_connect(client, src, dest);

    ECA_LOG_MSG(ECA_LOGGER::user_objects,
		std::string("Connected JACK ports ") +
		src +
		" and " +
		dest +
		" with result of " +
		kvu_numtostr(result));

    priv_cleanup(client);

  }

  return result == 0;
}

bool JACK_CONNECTIONS::disconnect(const char* src, const char* dest)
{
  int result = -1;
  jack_client_t *client = priv_prepare();
  if (client != 0) {
    result = jack_disconnect(client, src, dest);

    ECA_LOG_MSG(ECA_LOGGER::user_objects,
		std::string("Connected JACK ports ") +
		src +
		" and " +
		dest +
		" with result of " +
		kvu_numtostr(result));

    priv_cleanup(client);
  }

  return result == 0;
}

bool JACK_CONNECTIONS::list_connections(std::string* output)
{
  jack_client_t *client = priv_prepare();
  if (client != 0) {
    const char **next, **ports =
      jack_get_ports(client, NULL, NULL, 0);

    if (ports) {

      *output += "\n";

      for (next = ports; *next; next++) {
	jack_port_t *port;

	*output += string(*next);

	port = jack_port_by_name(client, *next);

	const char **nextconn, **conns =
	  jack_port_get_all_connections(client, port);

	if (conns) {
	  for(nextconn = conns; *nextconn; nextconn++) {
	    *output += string("\n\t") + string(*nextconn) + string("\n");
	  }
	  free(conns);
	}
	else {
	  *output += "\n";
	}
      }
      free(ports);
    }

    priv_cleanup(client);
  }

  return client != 0;
}
<commit_msg>Fixed a build error.<commit_after>// ------------------------------------------------------------------------
// jack-connections.cpp: Utility class to manage JACK port connections
// Copyright (C) 2008 Kai Vehmanen
//
// Attributes:
//     eca-style-version: 3 (see Ecasound Programmer's Guide)
//
// 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-1307  USA
// ------------------------------------------------------------------------

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <string>
#include <iostream>

#include <jack/jack.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

#include <kvu_numtostr.h>

#include "eca-logger.h"
#include "jack-connections.h"

using std::string;

JACK_CONNECTIONS::JACK_CONNECTIONS(void)
{
}

JACK_CONNECTIONS::~JACK_CONNECTIONS(void)
{
}

static jack_client_t *priv_prepare(void)
{
 int pid = getpid();
 std::string clntname = "libecasound-ctrl-" + kvu_numtostr(pid);
 jack_client_t *client = jack_client_new (clntname.c_str());
 return client;
}

static void priv_cleanup(jack_client_t *client)
{
  jack_client_close(client);
}

bool JACK_CONNECTIONS::connect(const char* src, const char* dest)
{

  int result = -1;
  jack_client_t *client = priv_prepare();
  if (client != 0) {
    result = jack_connect(client, src, dest);

    ECA_LOG_MSG(ECA_LOGGER::user_objects,
		std::string("Connected JACK ports ") +
		src +
		" and " +
		dest +
		" with result of " +
		kvu_numtostr(result));

    priv_cleanup(client);

  }

  return result == 0;
}

bool JACK_CONNECTIONS::disconnect(const char* src, const char* dest)
{
  int result = -1;
  jack_client_t *client = priv_prepare();
  if (client != 0) {
    result = jack_disconnect(client, src, dest);

    ECA_LOG_MSG(ECA_LOGGER::user_objects,
		std::string("Connected JACK ports ") +
		src +
		" and " +
		dest +
		" with result of " +
		kvu_numtostr(result));

    priv_cleanup(client);
  }

  return result == 0;
}

bool JACK_CONNECTIONS::list_connections(std::string* output)
{
  jack_client_t *client = priv_prepare();
  if (client != 0) {
    const char **next, **ports =
      jack_get_ports(client, NULL, NULL, 0);

    if (ports) {

      *output += "\n";

      for (next = ports; *next; next++) {
	jack_port_t *port;

	*output += string(*next);

	port = jack_port_by_name(client, *next);

	const char **nextconn, **conns =
	  jack_port_get_all_connections(client, port);

	if (conns) {
	  for(nextconn = conns; *nextconn; nextconn++) {
	    *output += string("\n\t") + string(*nextconn) + string("\n");
	  }
	  free(conns);
	}
	else {
	  *output += "\n";
	}
      }
      free(ports);
    }

    priv_cleanup(client);
  }

  return client != 0;
}
<|endoftext|>


<commit_before>/*******************************************************************************
 * pxgsettings - A helper binary to query gsettings
 * Copyright (C) 2006 Nathaniel McCallum <nathaniel@natemccallum.com>
 * Copyright (C) 2011 Dominique Leuenberger <dominique@leuenberger.net>
 *
 * 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.
 *
 * 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 <cstdio>
#include <unistd.h>
#include <signal.h>
#include <stdexcept>

#include <glib.h>
#include <glib-object.h>
#include <gio/gio.h>

using namespace std;

static GMainLoop* loop = NULL;

static int print_value(GVariant *value, const char *suffix) {

	if (!value) return 0;
	if (g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {
		return printf("%s%s", g_variant_get_string(value, NULL), suffix);
	}
	else if(g_variant_is_of_type(value, G_VARIANT_TYPE_INT32)) {
		return printf("%d%s", g_variant_get_int32(value), suffix);
	}
	else if(g_variant_is_of_type(value, G_VARIANT_TYPE_BOOLEAN)) {
		gboolean result;
		result = g_variant_get_boolean(value);
		return printf("%s%s", result ? "true" : "false",  suffix);
	}
	else if(g_variant_is_of_type(value, G_VARIANT_TYPE_ARRAY)) {
		int count;
		const gchar** items;
		items = g_variant_get_strv(value, NULL);
		for (count=0; items[count]; count++) {
			printf("%s%s", count < 2 ? "" : ",",  items[count]);
		}
		printf("%s", suffix);
		return count;
	}
	else {
		throw exception();
	}

	return 0;
}

static void on_value_change(GSettings *settings, const gchar *key, gpointer user_data) {
	printf("%s/%s\t", (gchar *)user_data, key);
	print_value(g_settings_get_value(settings, key), "\n");
}

static void on_sig(int /*signal*/) {
	g_main_loop_quit(loop);
}

static gboolean err(GIOChannel* /*source*/, GIOCondition /*condition*/, gpointer /*data*/) {
	g_main_loop_quit(loop);
	return false;
}

static gboolean in(GIOChannel *source, GIOCondition condition, gpointer data) {
	gchar *key, *val;
	GIOStatus st = g_io_channel_read_line(source, &key, NULL, NULL, NULL);

	// Remove the trailing '\n'
	for (int i=0 ; key && key[i] ; i++)
		if (key[i] == '\n')
			key[i] = '\0';

	// If we were successful
	if (key && st == G_IO_STATUS_NORMAL) {
		if (!g_strrstr(key, "\t"))
			goto exit;

		val = g_strrstr(key, "\t") + 1;
		*(val-1) = '\0';

		g_free(key);
		return true;
	}
	else if (key && st == G_IO_STATUS_AGAIN) {
		g_free(key);
		return in(source, condition, data);
	}

exit:
	g_free(key);
	return err(source, condition, data);
}

int main(int argc, char **argv) {
	if (argc < 2) return 1;

	// Register sighup handler
	if (signal(SIGHUP, on_sig) == SIG_ERR || signal(SIGPIPE, on_sig) == SIG_ERR || signal(SIGABRT, on_sig) == SIG_ERR) {
		fprintf(stderr, "Unable to trap signals!");
		return 2;
	}

	// Switch stdout to line buffering
	if (setvbuf(stdout, NULL, _IOLBF, 0)) {
		fprintf(stderr, "Unable to switch stdout to line buffering!");
		return 3;
	}

	// Switch stdin to line buffering
	if (setvbuf(stdin, NULL, _IOLBF, 0)) {
		fprintf(stderr, "Unable to switch stdin to line buffering!");
		return 4;
	}

	// Init
	g_type_init();

	// Get the main loop
	loop = g_main_loop_new(NULL, false);

	// Setup our GIO Channels
	GIOChannel* inchan  = g_io_channel_unix_new(fileno(stdin));
	GIOChannel* outchan = g_io_channel_unix_new(fileno(stdout));
	g_io_add_watch(inchan,  G_IO_IN,  in, NULL);
	g_io_add_watch(inchan,  G_IO_PRI, in, NULL);
	g_io_add_watch(inchan,  G_IO_ERR, err, NULL);
	g_io_add_watch(inchan,  G_IO_HUP, err, NULL);
	g_io_add_watch(outchan, G_IO_ERR, err, NULL);
	g_io_add_watch(outchan, G_IO_HUP, err, NULL);

	// Get GConf client
	GSettings* client;

	for (int i=1; i<argc; i++) {
		client = g_settings_new(argv[i]);
		gchar** keys = g_settings_list_keys(client);
		for (int j=0; keys[j]; on_value_change(client, keys[j++],argv[i] ));
		g_signal_connect(client, "changed::", (GCallback) on_value_change, argv[i]);
	}

	g_main_loop_run(loop);

	// Cleanup
	while (G_IS_OBJECT(client)) {
		g_object_unref(client);
	}
	g_io_channel_shutdown(inchan,  FALSE, NULL);
	g_io_channel_shutdown(outchan, FALSE, NULL);
	g_io_channel_unref(inchan);
	g_io_channel_unref(outchan);
	g_main_loop_unref(loop);
}
<commit_msg>pxgsettings: =/-1.. counting can be so hard<commit_after>/*******************************************************************************
 * pxgsettings - A helper binary to query gsettings
 * Copyright (C) 2006 Nathaniel McCallum <nathaniel@natemccallum.com>
 * Copyright (C) 2011 Dominique Leuenberger <dominique@leuenberger.net>
 *
 * 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.
 *
 * 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 <cstdio>
#include <unistd.h>
#include <signal.h>
#include <stdexcept>

#include <glib.h>
#include <glib-object.h>
#include <gio/gio.h>

using namespace std;

static GMainLoop* loop = NULL;

static int print_value(GVariant *value, const char *suffix) {

	if (!value) return 0;
	if (g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {
		return printf("%s%s", g_variant_get_string(value, NULL), suffix);
	}
	else if(g_variant_is_of_type(value, G_VARIANT_TYPE_INT32)) {
		return printf("%d%s", g_variant_get_int32(value), suffix);
	}
	else if(g_variant_is_of_type(value, G_VARIANT_TYPE_BOOLEAN)) {
		gboolean result;
		result = g_variant_get_boolean(value);
		return printf("%s%s", result ? "true" : "false",  suffix);
	}
	else if(g_variant_is_of_type(value, G_VARIANT_TYPE_ARRAY)) {
		int count;
		const gchar** items;
		items = g_variant_get_strv(value, NULL);
		for (count=0; items[count]; count++) {
			printf("%s%s", count < 1 ? "" : ",",  items[count]);
		}
		printf("%s", suffix);
		return count;
	}
	else {
		throw exception();
	}

	return 0;
}

static void on_value_change(GSettings *settings, const gchar *key, gpointer user_data) {
	printf("%s/%s\t", (gchar *)user_data, key);
	print_value(g_settings_get_value(settings, key), "\n");
}

static void on_sig(int /*signal*/) {
	g_main_loop_quit(loop);
}

static gboolean err(GIOChannel* /*source*/, GIOCondition /*condition*/, gpointer /*data*/) {
	g_main_loop_quit(loop);
	return false;
}

static gboolean in(GIOChannel *source, GIOCondition condition, gpointer data) {
	gchar *key, *val;
	GIOStatus st = g_io_channel_read_line(source, &key, NULL, NULL, NULL);

	// Remove the trailing '\n'
	for (int i=0 ; key && key[i] ; i++)
		if (key[i] == '\n')
			key[i] = '\0';

	// If we were successful
	if (key && st == G_IO_STATUS_NORMAL) {
		if (!g_strrstr(key, "\t"))
			goto exit;

		val = g_strrstr(key, "\t") + 1;
		*(val-1) = '\0';

		g_free(key);
		return true;
	}
	else if (key && st == G_IO_STATUS_AGAIN) {
		g_free(key);
		return in(source, condition, data);
	}

exit:
	g_free(key);
	return err(source, condition, data);
}

int main(int argc, char **argv) {
	if (argc < 2) return 1;

	// Register sighup handler
	if (signal(SIGHUP, on_sig) == SIG_ERR || signal(SIGPIPE, on_sig) == SIG_ERR || signal(SIGABRT, on_sig) == SIG_ERR) {
		fprintf(stderr, "Unable to trap signals!");
		return 2;
	}

	// Switch stdout to line buffering
	if (setvbuf(stdout, NULL, _IOLBF, 0)) {
		fprintf(stderr, "Unable to switch stdout to line buffering!");
		return 3;
	}

	// Switch stdin to line buffering
	if (setvbuf(stdin, NULL, _IOLBF, 0)) {
		fprintf(stderr, "Unable to switch stdin to line buffering!");
		return 4;
	}

	// Init
	g_type_init();

	// Get the main loop
	loop = g_main_loop_new(NULL, false);

	// Setup our GIO Channels
	GIOChannel* inchan  = g_io_channel_unix_new(fileno(stdin));
	GIOChannel* outchan = g_io_channel_unix_new(fileno(stdout));
	g_io_add_watch(inchan,  G_IO_IN,  in, NULL);
	g_io_add_watch(inchan,  G_IO_PRI, in, NULL);
	g_io_add_watch(inchan,  G_IO_ERR, err, NULL);
	g_io_add_watch(inchan,  G_IO_HUP, err, NULL);
	g_io_add_watch(outchan, G_IO_ERR, err, NULL);
	g_io_add_watch(outchan, G_IO_HUP, err, NULL);

	// Get GConf client
	GSettings* client;

	for (int i=1; i<argc; i++) {
		client = g_settings_new(argv[i]);
		gchar** keys = g_settings_list_keys(client);
		for (int j=0; keys[j]; on_value_change(client, keys[j++],argv[i] ));
		g_signal_connect(client, "changed::", (GCallback) on_value_change, argv[i]);
	}

	g_main_loop_run(loop);

	// Cleanup
	while (G_IS_OBJECT(client)) {
		g_object_unref(client);
	}
	g_io_channel_shutdown(inchan,  FALSE, NULL);
	g_io_channel_shutdown(outchan, FALSE, NULL);
	g_io_channel_unref(inchan);
	g_io_channel_unref(outchan);
	g_main_loop_unref(loop);
}
<|endoftext|>


<commit_before>/*--------------------------------------------------------------------------
 *--------------------------------------------------------------------------
 *
 * Copyright (C) 2008,2009 The PECOS Development Team
 *
 * Please see http://pecos.ices.utexas.edu for more information.
 *
 * This file is part of the QUESO Library (Quantification of Uncertainty
 * for Estimation, Simulation and Optimization).
 *
 * QUESO 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 3 of the License, or
 * (at your option) any later version.
 *
 * QUESO 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 QUESO. If not, see <http://www.gnu.org/licenses/>.
 *
 *--------------------------------------------------------------------------
 *
 * $Id$
 *
 * Basic API: Class member functions.
 *
 *--------------------------------------------------------------------------
 *-------------------------------------------------------------------------- */

using namespace std;

#include <basic_classes.h>
#include <basic_int.h>
#include <hpct.h>

namespace QUESO_Basic_API {

  void   QUESO_fatal        (const char *message);
  double Likelihood_Wrapper (const basicV &,const basicV *,const void *,basicV *,basicM *,basicV *);

  //------------------
  // Member Functions
  //------------------

  QUESO_Basic_Class::QUESO_Basic_Class()
  {
    m_initialized           = 0;
    m_silent                = 0;
    m_paramSpace            = NULL;
    m_paramDomain           = NULL;
    m_user_likelihood_func  = NULL;
  }

  void QUESO_Basic_Class::Initialize(const char *inputfile)
  {

    hpct_timer_init("QUESO");

    // Define new QUESO environment and store inputfile information

    m_env         = new uqFullEnvironmentClass(MPI_COMM_WORLD,inputfile,"");
    m_inputfile   = new string(inputfile);

    m_initialized = 1;

}

  void QUESO_Basic_Class:: DefineParameterSpace()
  {
    double *param_min;		// min value of each parameter
    double *param_max;		// max value of each parameter
    double *param_ini;		// initial value of each parameter

    int     ierr = 1;

    VerifyInit();

    // Verify presence of required input file

    ierr *= hpct_input_fopen(m_inputfile->c_str());

    if(ierr == 0)
      QUESO_fatal("Unable to access QUESO input file");

    // Derive the UQ parameters from input file and create QUESO parameter vector

    ierr *= hpct_input_fread_int("queso/parameters/num_params",&m_num_params);

    if(ierr == 0)
      QUESO_fatal("Unable to read num_params from input file.");

    printf("--> Setup parameter space variables/ranges...\n");
    m_paramSpace  = new uqVectorSpaceClass <basicV,basicM> (*m_env,"queso_basic_",m_num_params,NULL);

    param_min = (double *) calloc(m_num_params,sizeof(double));
    param_max = (double *) calloc(m_num_params,sizeof(double));
    param_ini = (double *) calloc(m_num_params,sizeof(double));

    if(param_min == NULL || param_max == NULL || param_ini == NULL)
      QUESO_fatal("Unable to allocate memory for desired parameter space");

    ierr *= hpct_input_fread_double_vec("queso/parameters/param_mins",  param_min, m_num_params);
    ierr *= hpct_input_fread_double_vec("queso/parameters/param_maxs",  param_max, m_num_params);
    ierr *= hpct_input_fread_double_vec("queso/parameters/param_inits", param_ini, m_num_params);

    if(ierr == 0)
      QUESO_fatal("Unable to read parameter min/max/init values");

    m_queso_var_min = new basicV ( m_paramSpace->zeroVector() );
    m_queso_var_max = new basicV ( m_paramSpace->zeroVector() );
    m_queso_var_ini = new basicV ( m_paramSpace->zeroVector() );

    for(int i = 0;i<m_num_params;i++)
      {
	(*m_queso_var_min)[i] = param_min[i];
	(*m_queso_var_max)[i] = param_max[i];
	(*m_queso_var_ini)[i] = param_ini[i];
      }

    printf("--> Setup parameter search box...\n");
    m_paramDomain = new uqBoxSubsetClass<basicV, basicM> ("queso_basic_",*m_paramSpace,
							  *m_queso_var_min,*m_queso_var_max);
    // un poquito de clean up.

    free(param_min);
    free(param_max);
    free(param_ini);

    hpct_input_fclose();

  }

  void QUESO_Basic_Class:: VerifyInit()
  {
    if(!m_initialized)
      QUESO_fatal("QUESO not initialized prior to use");
  }

  void QUESO_Basic_Class::Likelihood_Register(double (*fp)(double *) )
  {

    VerifyInit();

    printf("--> Setting prior and post vectors...\n");

    m_priorRV = new uqUniformVectorRVClass <basicV, basicM> ("prior_",*m_paramDomain);
    m_postRV  = new uqGenericVectorRVClass <basicV, basicM> ("post_" ,*m_paramSpace );

    m_likelihoodObj = new uqGenericScalarFunctionClass
      <basicV,basicM> ("like_",*m_paramDomain,Likelihood_Wrapper,NULL,true);

    m_user_likelihood_func = fp;

    // define the inverse (calibration) problem

    printf("--> Defining inverse problem...\n");

    m_ip = new uqStatisticalInverseProblemClass <basicV,basicM> ("",*m_priorRV,*m_likelihoodObj,*m_postRV);

    // Default covariance matrix for now - default assumption assumes
    // 6-sigma distribution range falls over 1/3 of the max parameter range.
    //
    // koomie TODO: store relevant constants regarding this default
    // assumption in input file and register as default values, but
    // allow the savvy user to override

    double cov_param = 1/(3.*6.);	// 6-sigma over 1/3 of the range
    double param_range = 0.0;

    printf("--> Defining default covariance matrix...\n");

    m_CovMatrix = m_postRV->imageSet().vectorSpace().newProposalMatrix(NULL,
								       m_queso_var_ini);

    for(int i=0;i<m_num_params;i++)
      {
	param_range = (*m_queso_var_max)[i] - (*m_queso_var_min)[i];
	(*m_CovMatrix)(i,i) = (cov_param*param_range)*(cov_param*param_range);
      }

  }

  void QUESO_Basic_Class::SolveInverseProblem()
  {
    VerifyInit();

    // Launch the Markov Chain

    m_ip->solveWithBayesMetropolisHastings(*m_queso_var_ini,m_CovMatrix);
  }

  //----------------------------------------------
  // Fatal error(): example only - to be replaced.
  //----------------------------------------------

  void QUESO_fatal(const char *message)
  {
    printf("%s\n",message);
    exit(1);

    // koomie note: likely need mpi_abort and better exception handling aqui.
    // koomie TODO: switch to queso error macro
  }

  //---------------------------------------------------------------------
  // Wrapper for user likelihood routine: culls data from QUESO uqVector
  // and passes to the user routine as an array of doubles.
  //---------------------------------------------------------------------

  double Likelihood_Wrapper(const basicV &paramValue,
			    const basicV *paramDirection,
			    const void *Data,basicV *gradV,basicM *hessianM,
			    basicV *hessianE)
  {
    // Logic just to avoid warnings from INTEL compiler: added by prudenci on 2009/Sep/06
    const uqGslVectorClass* aux1 = paramDirection;
    if (aux1) {};
    aux1 = gradV;
    aux1 = hessianE;
    uqGslMatrixClass* aux2 = hessianM;
    if (aux2) {};
    const void* aux3 = Data;
    if (aux3) {};

    // Actual code
    static int first_entry = 1;
    double *uqParams;
    int num_params;

    num_params = paramValue.sizeGlobal();

    if(first_entry)
      {
	if(num_params < 1)
	  QUESO_fatal("Invalid number of parameters");

	if(_QUESO_Basic->m_user_likelihood_func  == NULL )
	  QUESO_fatal("Invalid user-supplied likelihood function");

	uqParams = (double *)calloc(num_params,sizeof(double));
	if(uqParams == NULL)
	  QUESO_fatal("Unable to allocate emmory for uqParams");
      }

    for(int i=0;i<num_params;i++)
      uqParams[i] = paramValue[i];

    hpct_timer_begin("Likelihood Routine");

    double lhood_return = _QUESO_Basic->m_user_likelihood_func(uqParams);

    hpct_timer_end("Likelihood Routine");
    return(lhood_return);

    //      return( _QUESO_Basic->m_user_likelihood_func(uqParams) );

  }

}   //  QUESO_Basic_API namespace
<commit_msg>QUESO 0.42.0: removed compilation warning<commit_after>/*--------------------------------------------------------------------------
 *--------------------------------------------------------------------------
 *
 * Copyright (C) 2008,2009 The PECOS Development Team
 *
 * Please see http://pecos.ices.utexas.edu for more information.
 *
 * This file is part of the QUESO Library (Quantification of Uncertainty
 * for Estimation, Simulation and Optimization).
 *
 * QUESO 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 3 of the License, or
 * (at your option) any later version.
 *
 * QUESO 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 QUESO. If not, see <http://www.gnu.org/licenses/>.
 *
 *--------------------------------------------------------------------------
 *
 * $Id$
 *
 * Basic API: Class member functions.
 *
 *--------------------------------------------------------------------------
 *-------------------------------------------------------------------------- */

using namespace std;

#include <basic_classes.h>
#include <basic_int.h>
#include <hpct.h>

namespace QUESO_Basic_API {

  void   QUESO_fatal        (const char *message);
  double Likelihood_Wrapper (const basicV &,const basicV *,const void *,basicV *,basicM *,basicV *);

  //------------------
  // Member Functions
  //------------------

  QUESO_Basic_Class::QUESO_Basic_Class()
  {
    m_initialized           = 0;
    m_silent                = 0;
    m_paramSpace            = NULL;
    m_paramDomain           = NULL;
    m_user_likelihood_func  = NULL;
  }

  void QUESO_Basic_Class::Initialize(const char *inputfile)
  {

    hpct_timer_init("QUESO");

    // Define new QUESO environment and store inputfile information

    m_env         = new uqFullEnvironmentClass(MPI_COMM_WORLD,inputfile,"");
    m_inputfile   = new string(inputfile);

    m_initialized = 1;

}

  void QUESO_Basic_Class:: DefineParameterSpace()
  {
    double *param_min;		// min value of each parameter
    double *param_max;		// max value of each parameter
    double *param_ini;		// initial value of each parameter

    int     ierr = 1;

    VerifyInit();

    // Verify presence of required input file

    ierr *= hpct_input_fopen(m_inputfile->c_str());

    if(ierr == 0)
      QUESO_fatal("Unable to access QUESO input file");

    // Derive the UQ parameters from input file and create QUESO parameter vector

    ierr *= hpct_input_fread_int("queso/parameters/num_params",&m_num_params);

    if(ierr == 0)
      QUESO_fatal("Unable to read num_params from input file.");

    printf("--> Setup parameter space variables/ranges...\n");
    m_paramSpace  = new uqVectorSpaceClass <basicV,basicM> (*m_env,"queso_basic_",m_num_params,NULL);

    param_min = (double *) calloc(m_num_params,sizeof(double));
    param_max = (double *) calloc(m_num_params,sizeof(double));
    param_ini = (double *) calloc(m_num_params,sizeof(double));

    if(param_min == NULL || param_max == NULL || param_ini == NULL)
      QUESO_fatal("Unable to allocate memory for desired parameter space");

    ierr *= hpct_input_fread_double_vec("queso/parameters/param_mins",  param_min, m_num_params);
    ierr *= hpct_input_fread_double_vec("queso/parameters/param_maxs",  param_max, m_num_params);
    ierr *= hpct_input_fread_double_vec("queso/parameters/param_inits", param_ini, m_num_params);

    if(ierr == 0)
      QUESO_fatal("Unable to read parameter min/max/init values");

    m_queso_var_min = new basicV ( m_paramSpace->zeroVector() );
    m_queso_var_max = new basicV ( m_paramSpace->zeroVector() );
    m_queso_var_ini = new basicV ( m_paramSpace->zeroVector() );

    for(int i = 0;i<m_num_params;i++)
      {
	(*m_queso_var_min)[i] = param_min[i];
	(*m_queso_var_max)[i] = param_max[i];
	(*m_queso_var_ini)[i] = param_ini[i];
      }

    printf("--> Setup parameter search box...\n");
    m_paramDomain = new uqBoxSubsetClass<basicV, basicM> ("queso_basic_",*m_paramSpace,
							  *m_queso_var_min,*m_queso_var_max);
    // un poquito de clean up.

    free(param_min);
    free(param_max);
    free(param_ini);

    hpct_input_fclose();

  }

  void QUESO_Basic_Class:: VerifyInit()
  {
    if(!m_initialized)
      QUESO_fatal("QUESO not initialized prior to use");
  }

  void QUESO_Basic_Class::Likelihood_Register(double (*fp)(double *) )
  {

    VerifyInit();

    printf("--> Setting prior and post vectors...\n");

    m_priorRV = new uqUniformVectorRVClass <basicV, basicM> ("prior_",*m_paramDomain);
    m_postRV  = new uqGenericVectorRVClass <basicV, basicM> ("post_" ,*m_paramSpace );

    m_likelihoodObj = new uqGenericScalarFunctionClass
      <basicV,basicM> ("like_",*m_paramDomain,Likelihood_Wrapper,NULL,true);

    m_user_likelihood_func = fp;

    // define the inverse (calibration) problem

    printf("--> Defining inverse problem...\n");

    m_ip = new uqStatisticalInverseProblemClass <basicV,basicM> ("",*m_priorRV,*m_likelihoodObj,*m_postRV);

    // Default covariance matrix for now - default assumption assumes
    // 6-sigma distribution range falls over 1/3 of the max parameter range.
    //
    // koomie TODO: store relevant constants regarding this default
    // assumption in input file and register as default values, but
    // allow the savvy user to override

    double cov_param = 1/(3.*6.);	// 6-sigma over 1/3 of the range
    double param_range = 0.0;

    printf("--> Defining default covariance matrix...\n");

    m_CovMatrix = m_postRV->imageSet().vectorSpace().newProposalMatrix(NULL,
								       m_queso_var_ini);

    for(int i=0;i<m_num_params;i++)
      {
	param_range = (*m_queso_var_max)[i] - (*m_queso_var_min)[i];
	(*m_CovMatrix)(i,i) = (cov_param*param_range)*(cov_param*param_range);
      }

  }

  void QUESO_Basic_Class::SolveInverseProblem()
  {
    VerifyInit();

    // Launch the Markov Chain

    m_ip->solveWithBayesMetropolisHastings(*m_queso_var_ini,m_CovMatrix);
  }

  //----------------------------------------------
  // Fatal error(): example only - to be replaced.
  //----------------------------------------------

  void QUESO_fatal(const char *message)
  {
    printf("%s\n",message);
    exit(1);

    // koomie note: likely need mpi_abort and better exception handling aqui.
    // koomie TODO: switch to queso error macro
  }

  //---------------------------------------------------------------------
  // Wrapper for user likelihood routine: culls data from QUESO uqVector
  // and passes to the user routine as an array of doubles.
  //---------------------------------------------------------------------

  double Likelihood_Wrapper(const basicV &paramValue,
			    const basicV *paramDirection,
			    const void *Data,basicV *gradV,basicM *hessianM,
			    basicV *hessianE)
  {
    // Logic just to avoid warnings from INTEL compiler: added by prudenci on 2009/Sep/06
    const uqGslVectorClass* aux1 = paramDirection;
    if (aux1) {};
    aux1 = gradV;
    aux1 = hessianE;
    uqGslMatrixClass* aux2 = hessianM;
    if (aux2) {};
    const void* aux3 = Data;
    if (aux3) {};

    // Actual code
    static int first_entry = 1;
    double *uqParams = NULL;
    int num_params = paramValue.sizeGlobal();

    if(first_entry)
      {
	if(num_params < 1)
	  QUESO_fatal("Invalid number of parameters");

	if(_QUESO_Basic->m_user_likelihood_func  == NULL )
	  QUESO_fatal("Invalid user-supplied likelihood function");

	uqParams = (double *)calloc(num_params,sizeof(double));
	if(uqParams == NULL)
	  QUESO_fatal("Unable to allocate emmory for uqParams");
      }

    for(int i=0;i<num_params;i++)
      uqParams[i] = paramValue[i];

    hpct_timer_begin("Likelihood Routine");

    double lhood_return = _QUESO_Basic->m_user_likelihood_func(uqParams);

    hpct_timer_end("Likelihood Routine");
    return(lhood_return);

    //      return( _QUESO_Basic->m_user_likelihood_func(uqParams) );

  }

}   //  QUESO_Basic_API namespace
<|endoftext|>


<commit_before>/// @file tuple_tests.hpp
///
/// @brief Tests for Eigen librairy
///
/// @author Thomas Vanderbruggen <thomas@koheron.com>
/// @date 06/10/2015
///
/// (c) Koheron 2014-2015

#ifndef __EIGEN_TESTS_HPP__
#define __EIGEN_TESTS_HPP__

#include <Eigen/Dense>

#include "../drivers/core/dev_mem.hpp" // Unused but needed for now

//> \description Tests for tuple tranfers
class EigenTests
{
  public:
    EigenTests(Klib::DevMem& dvm_unused_) {}

    //> \io_type WRITE
    void small_vector()
    {
        Eigen::Vector2f v(1, 2);

        for(int i=0; i<v.size(); i++)
            printf("%i --> %f", i, v(i));

    }

    //> \io_type WRITE
    void dynamic_vector(unsigned int len)
    {
        Eigen::VectorXf v(len);

        for(int i=0; i<v.size(); i++)
            v(i) = i*i;

        for(int i=0; i<v.size(); i++)
            printf("%i --> %f", i, v(i));

    }
};

#endif // __TUPLE_TESTS_HPP__
<commit_msg>Update include path<commit_after>/// @file tuple_tests.hpp
///
/// @brief Tests for Eigen librairy
///
/// @author Thomas Vanderbruggen <thomas@koheron.com>
/// @date 06/10/2015
///
/// (c) Koheron 2014-2015

#ifndef __EIGEN_TESTS_HPP__
#define __EIGEN_TESTS_HPP__

#include <Eigen/Dense>

#include "../drivers/dev_mem.hpp" // Unused but needed for now

//> \description Tests for tuple tranfers
class EigenTests
{
  public:
    EigenTests(Klib::DevMem& dvm_unused_) {}

    //> \io_type WRITE
    void small_vector()
    {
        Eigen::Vector2f v(1, 2);

        for(int i=0; i<v.size(); i++)
            printf("%i --> %f", i, v(i));

    }

    //> \io_type WRITE
    void dynamic_vector(unsigned int len)
    {
        Eigen::VectorXf v(len);

        for(int i=0; i<v.size(); i++)
            v(i) = i*i;

        for(int i=0; i<v.size(); i++)
            printf("%i --> %f", i, v(i));

    }
};

#endif // __TUPLE_TESTS_HPP__
<|endoftext|>


<commit_before>#include <windows.h>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;

int main(int argc, char* argv[]) {
  try {
    if (argc < 2)
      throw exception("source path not specified");

    if (argc < 3)
      throw exception("platform not specified");

    string source_dir = argv[1];

    // determine Far version
    string plugin_hpp_path = source_dir + "\\PluginSDK\\Headers.c\\plugin.hpp";
    ifstream header_file;
    header_file.exceptions(ios_base::badbit | ios_base::failbit | ios_base::eofbit);
    header_file.open(plugin_hpp_path.c_str());
    string line;
    unsigned ver_major, ver_minor, ver_build;
    unsigned fount_cnt = 0;
    while (fount_cnt < 3) {
      header_file >> line;
      if (line == "FARMANAGERVERSION_MAJOR") {
        header_file >> ver_major;
        fount_cnt++;
      }
      if (line == "FARMANAGERVERSION_MINOR") {
        header_file >> ver_minor;
        fount_cnt++;
      }
      if (line == "FARMANAGERVERSION_BUILD") {
        header_file >> ver_build;
        fount_cnt++;
      }
    }

    // determine Far platform
    string platform_str = argv[2];
    unsigned platform_idx;
    if (platform_str == "x86") {
      platform_idx = 1;
    }
    else if (platform_str == "x64") {
      platform_str = "x64";
      platform_idx = 2;
    }
    else
      throw exception("unknown machine type");

    // generate makefile
    ostringstream fmt;
    fmt << ver_major << "." << ver_minor << "." << ver_build;
    string version = fmt.str();
    fmt.str(string());
    fmt << "Far" << ver_major << ver_minor << "b" << ver_build << "." << platform_str << ".msi";
    string msi_name = fmt.str();

    ofstream makefile;
    makefile.exceptions(ios_base::badbit | ios_base::failbit | ios_base::eofbit);
    makefile.open("makefile");
    makefile << "all:" << endl;
    makefile << "  cl -nologo -O1 -GS- -D_PLATFORM=" << platform_idx << " customact.cpp -link -dll -nodefaultlib -noentry -out:CustomActions.dll -export:UpdateFeatureState msi.lib" << endl;
    makefile << "  candle -nologo -dSourceDir=\"" << source_dir << "\" -dBranch=" << ver_major << " -dPlatform=" << platform_str << " -dVersion=" << version << " installer.wxs" << endl;
    makefile << "  light -nologo -ext"
#ifdef SPECIAL
    << " c:\\src\\WixUIExtension.dll"
#else
    << " WixUIExtension"
#endif
    << " -cultures:en-us -spdb -sval -sh -dcl:high -out " << msi_name << " installer.wixobj" << endl;

    return 0;
  }
  catch (const exception& e) {
    cerr << "genscript: error: " << typeid(e).name() << ": " << e.what() << endl;
  }
  catch (...) {
    cerr << "genscript: unknown error" << endl;
  }
  return 1;
}
<commit_msg>update for nightly<commit_after>#include <windows.h>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;

int main(int argc, char* argv[]) {
  try {
    if (argc < 2)
      throw exception("source path not specified");

    if (argc < 3)
      throw exception("platform not specified");

    string source_dir = argv[1];

    // determine Far version
    string plugin_hpp_path = source_dir + "\\PluginSDK\\Headers.c\\plugin.hpp";
    ifstream header_file;
    header_file.exceptions(ios_base::badbit | ios_base::failbit | ios_base::eofbit);
    header_file.open(plugin_hpp_path.c_str());
    string line;
    unsigned ver_major, ver_minor, ver_build;
    unsigned fount_cnt = 0;
    while (fount_cnt < 3) {
      header_file >> line;
      if (line == "FARMANAGERVERSION_MAJOR") {
        header_file >> ver_major;
        fount_cnt++;
      }
      if (line == "FARMANAGERVERSION_MINOR") {
        header_file >> ver_minor;
        fount_cnt++;
      }
      if (line == "FARMANAGERVERSION_BUILD") {
        header_file >> ver_build;
        fount_cnt++;
      }
    }

    // determine Far platform
    string platform_str = argv[2];
    unsigned platform_idx;
    if (platform_str == "x86") {
      platform_idx = 1;
    }
    else if (platform_str == "x64") {
      platform_str = "x64";
      platform_idx = 2;
    }
    else
      throw exception("unknown machine type");

    // generate makefile
    ostringstream fmt;
    fmt << ver_major << "." << ver_minor << "." << ver_build;
    string version = fmt.str();
    fmt.str(string());
    fmt << "Far" << ver_major << ver_minor << "b" << ver_build << "." << platform_str << ".msi";
    string msi_name = fmt.str();

#ifdef SPECIAL
    msi_name = source_dir + "\\final.msi";
#endif

    ofstream makefile;
    makefile.exceptions(ios_base::badbit | ios_base::failbit | ios_base::eofbit);
    makefile.open("makefile");
    makefile << "all:" << endl;
    makefile << "  cl -nologo -O1 -GS- -D_PLATFORM=" << platform_idx << " customact.cpp -link -dll -nodefaultlib -noentry -out:CustomActions.dll -export:UpdateFeatureState msi.lib" << endl;
    makefile << "  candle -nologo -dSourceDir=\"" << source_dir << "\" -dBranch=" << ver_major << " -dPlatform=" << platform_str << " -dVersion=" << version << " installer.wxs" << endl;
    makefile << "  light -nologo -ext"
#ifdef SPECIAL
    << " c:\\src\\WixUIExtension.dll"
#else
    << " WixUIExtension"
#endif
    << " -cultures:en-us -spdb -sval -sh -dcl:high -out " << msi_name << " installer.wixobj" << endl;

    return 0;
  }
  catch (const exception& e) {
    cerr << "genscript: error: " << typeid(e).name() << ": " << e.what() << endl;
  }
  catch (...) {
    cerr << "genscript: unknown error" << endl;
  }
  return 1;
}
<|endoftext|>


<commit_before>#ifndef MJOLNIR_LOCAL_FORCE_FIELD
#define MJOLNIR_LOCAL_FORCE_FIELD
#include "LocalInteractionBase.hpp"
#include <mjolnir/util/logger.hpp>
#include <utility>
#include <vector>
#include <array>
#include <memory>

namespace mjolnir
{

template<typename traitsT>
class LocalForceField
{
  public:
    typedef traitsT traits_type;
    typedef typename traits_type::time_type       time_type;
    typedef typename traits_type::real_type       real_type;
    typedef typename traits_type::coordinate_type coordinate_type;
    typedef Particle<coordinate_type>             particle_type;
    typedef ParticleContainer<traits_type>        particle_container_type;
    typedef LocalInteractionBase<traitsT>         interaction_type;
    typedef std::unique_ptr<interaction_type>     interaction_ptr;
    typedef std::vector<interaction_ptr>          container_type;

  public:

    LocalForceField() = default;
    ~LocalForceField() = default;
    LocalForceField(LocalForceField const&) = delete;
    LocalForceField(LocalForceField&&)      = default;
    LocalForceField& operator=(LocalForceField const&) = delete;
    LocalForceField& operator=(LocalForceField&&)      = default;

    void emplace(interaction_ptr&& interaction);

    void      calc_force(particle_container_type& pcon);
    real_type calc_energy(const particle_container_type& pcon) const;

    void reset_parameter(const std::string&, const real_type);

  private:

    container_type interactions_;
    static
    Logger& logger_;
};

template<typename traitsT>
Logger& LocalForceField<traitsT>::logger_ =
    LoggerManager<char>::get_logger("LocalForceField");

template<typename traitsT>
inline void LocalForceField<traitsT>::emplace(
        interaction_ptr&& interaction)
{
    interactions_.emplace_back(std::forward<interaction_ptr>(interaction));
    return;
}

template<typename traitsT>
void LocalForceField<traitsT>::calc_force(particle_container_type& pcon)
{
    for(auto iter = interactions_.cbegin(); iter != interactions_.cend(); ++iter)
        (*iter)->calc_force(pcon);
    return;
}

template<typename traitsT>
typename LocalForceField<traitsT>::real_type
LocalForceField<traitsT>::calc_energy(const particle_container_type& pcon) const
{
    real_type energy = 0.0;
    for(auto iter = interactions_.cbegin(); iter != interactions_.cend(); ++iter)
    {
        const real_type e = (*iter)->calc_energy(pcon);
        MJOLNIR_LOG_DEBUG("calculate energy", e);
        energy += e;
    }
    return energy;
}

template<typename traitsT>
void LocalForceField<traitsT>::reset_parameter(
        const std::string& name, const real_type val)
{
    for(auto iter = interactions_.begin(); iter != interactions_.end(); ++iter)
        (*iter)->reset_parameter(name, val);
    return;
}

} // mjolnir
#endif /* MJOLNIR_LOCAL_FORCE_FIELD */
<commit_msg>use System in LocalForceField<commit_after>#ifndef MJOLNIR_LOCAL_FORCE_FIELD
#define MJOLNIR_LOCAL_FORCE_FIELD
#include "LocalInteractionBase.hpp"
#include <mjolnir/util/logger.hpp>
#include <utility>
#include <vector>
#include <array>
#include <memory>

namespace mjolnir
{

template<typename traitsT>
class LocalForceField
{
  public:
    typedef traitsT traits_type;
    typedef typename traits_type::real_type       real_type;
    typedef typename traits_type::coordinate_type coordinate_type;
    typedef System<traits_type>                   system_type;
    typedef system_type::particle_type            particle_type;
    typedef LocalInteractionBase<traitsT>         interaction_type;
    typedef std::unique_ptr<interaction_type>     interaction_ptr;
    typedef std::vector<interaction_ptr>          container_type;

  public:

    LocalForceField()  = default;
    ~LocalForceField() = default;
    LocalForceField(LocalForceField const&) = delete;
    LocalForceField(LocalForceField&&)      = default;
    LocalForceField& operator=(LocalForceField const&) = delete;
    LocalForceField& operator=(LocalForceField&&)      = default;

    void emplace(interaction_ptr&& interaction)
    {
        interactions_.emplace_back(std::move(interaction));
    }

    void      calc_force (system_type& sys);
    real_type calc_energy(const system_type& sys) const;

  private:

    container_type interactions_;
};

template<typename traitsT>
inline void LocalForceField<traitsT>::calc_force(system_type& sys)
{
    for(const auto& item : this->interactions_)
        item->calc_force(sys);
    return;
}

template<typename traitsT>
inline typename LocalForceField<traitsT>::real_type
LocalForceField<traitsT>::calc_energy(const system_type& pcon) const
{
    real_type energy = 0.0;
    for(const auto& item : this->interactions_)
        energy += item->calc_energy(sys);
    return energy;
}

} // mjolnir
#endif /* MJOLNIR_LOCAL_FORCE_FIELD */
<|endoftext|>


<commit_before>
#include "common.h"

// interface header
#include "LuaPack.h"

// system headers
#include <string.h>
#include <string>
#include <vector>
using std::string;
using std::vector;
#include <algorithm>
using std::min;
using std::max;

// local headers
#include "LuaInclude.h"
#include "LuaHashString.h"
#include "LuaDouble.h"

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

bool LuaPack::PushEntries(lua_State* L)
{
	PUSH_LUA_CFUNC(L, PackU8);
	PUSH_LUA_CFUNC(L, PackU16);
	PUSH_LUA_CFUNC(L, PackU32);
	PUSH_LUA_CFUNC(L, PackU64);
	PUSH_LUA_CFUNC(L, PackI8);
	PUSH_LUA_CFUNC(L, PackI16);
	PUSH_LUA_CFUNC(L, PackI32);
	PUSH_LUA_CFUNC(L, PackI64);
	PUSH_LUA_CFUNC(L, PackF32);
	PUSH_LUA_CFUNC(L, PackF64); // LuaDouble

	PUSH_LUA_CFUNC(L, UnpackU8);
	PUSH_LUA_CFUNC(L, UnpackU16);
	PUSH_LUA_CFUNC(L, UnpackU32);
	PUSH_LUA_CFUNC(L, UnpackU64);
	PUSH_LUA_CFUNC(L, UnpackI8);
	PUSH_LUA_CFUNC(L, UnpackI16);
	PUSH_LUA_CFUNC(L, UnpackI32);
	PUSH_LUA_CFUNC(L, UnpackI64);
	PUSH_LUA_CFUNC(L, UnpackF32);
	PUSH_LUA_CFUNC(L, UnpackF64); // LuaDouble

	PUSH_LUA_CFUNC(L, SwapBy2);
	PUSH_LUA_CFUNC(L, SwapBy4);
	PUSH_LUA_CFUNC(L, SwapBy8);

	PUSH_LUA_CFUNC(L, GetEndian);

	return true;
}

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

template <typename T>
int PackType(lua_State* L)
{
	vector<T> vals;

	// collect the values
	if (lua_istable(L, 1)) {
		for (int i = 1; lua_checkgeti(L, 1, i); lua_pop(L, 1), i++) {
			if (lua_israwnumber(L, -1)) {
				vals.push_back((T)lua_tonumber(L, -1));
			}
			else {
				const double* dptr = LuaDouble::TestDouble(L, -1);
				if (dptr != NULL) {
					vals.push_back((T)(*dptr));
				} else {
					break; // not a lua_Number or a LuaDouble
				}
			}
		}
	}
	else {
		const int args = lua_gettop(L);
		for (int i = 1; i <= args; i++) {
			if (lua_israwnumber(L, i)) {
				vals.push_back((T)lua_tonumber(L, i));
			}
			else {
				const double* dptr = LuaDouble::TestDouble(L, i);
				if (dptr != NULL) {
					vals.push_back((T)(*dptr));
				} else {
					break; // not a lua_Number or a LuaDouble
				}
			}
		}
	}

	if (vals.empty()) {
		return 0;
	}

	// push the result
	const int bufSize = sizeof(T) * vals.size();
	char* buf = new char[bufSize];
	for (int i = 0; i < (int)vals.size(); i++) {
		memcpy(buf + (i * sizeof(T)), &vals[i], sizeof(T));
	}
	lua_pushlstring(L, buf, bufSize);
	delete[] buf;

	return 1;
}

int LuaPack::PackU8(lua_State*  L) { return PackType<uint8_t> (L); }
int LuaPack::PackU16(lua_State* L) { return PackType<uint16_t>(L); }
int LuaPack::PackU32(lua_State* L) { return PackType<uint32_t>(L); }
int LuaPack::PackU64(lua_State* L) { return PackType<uint64_t>(L); }
int LuaPack::PackI8(lua_State*  L) { return PackType<int8_t>  (L); }
int LuaPack::PackI16(lua_State* L) { return PackType<int16_t> (L); }
int LuaPack::PackI32(lua_State* L) { return PackType<int32_t> (L); }
int LuaPack::PackI64(lua_State* L) { return PackType<int64_t> (L); }
int LuaPack::PackF32(lua_State* L) { return PackType<float>   (L); }
int LuaPack::PackF64(lua_State* L) { return PackType<double>  (L); }

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

template <typename T>
int UnpackType(lua_State* L, bool defaultToDoubles = false)
{
	int index = 1;
	bool pushDoubles = defaultToDoubles;
	if (lua_isboolean(L, index)) {
		pushDoubles = lua_tobool(L, index);
		index++;
	}

	if (!lua_israwstring(L, index)) {
		return 0;
	}
	size_t len;
	const char* str = lua_tolstring(L, index, &len);

	// apply the offset
	if (lua_israwnumber(L, index + 1)) {
		const size_t offset = lua_toint(L, index + 1) - 1;
		if (offset >= len) {
			return 0;
		}
		str += offset;
		len -= offset;
	}

	const size_t eSize = sizeof(T);
	if (len < eSize) {
		return 0;
	}

	// return a single value
	if (!lua_israwnumber(L, index + 2)) {
		const T value = *((T*)str);
		if (pushDoubles) {
			LuaDouble::PushDouble(L, (double)(static_cast<lua_Number>(value)));
		} else {
			lua_pushnumber(L, static_cast<lua_Number>(value));
		}
		return 1;
	}

	// return a table
	const int maxCount = (len / eSize);
	int tableCount = lua_toint(L, 3);
	if (tableCount < 0) {
		tableCount = maxCount;
	}
	tableCount = min(maxCount, tableCount);
	lua_newtable(L);
	if (pushDoubles) {
		for (int i = 0; i < tableCount; i++) {
			const T value = *(((T*)str) + i);
			LuaDouble::PushDouble(L, (double)(static_cast<lua_Number>(value)));
			lua_rawseti(L, -2, (i + 1));
		}
	} else {
		for (int i = 0; i < tableCount; i++) {
			const T value = *(((T*)str) + i);
			lua_pushnumber(L, static_cast<lua_Number>(value));
			lua_rawseti(L, -2, (i + 1));
		}
	}
	return 1;
}

int LuaPack::UnpackU8(lua_State*  L) { return UnpackType<uint8_t> (L, false); }
int LuaPack::UnpackU16(lua_State* L) { return UnpackType<uint16_t>(L, false); }
int LuaPack::UnpackU32(lua_State* L) { return UnpackType<uint32_t>(L, true);  }
int LuaPack::UnpackU64(lua_State* L) { return UnpackType<uint64_t>(L, true);  }
int LuaPack::UnpackI8(lua_State*  L) { return UnpackType<int8_t>  (L, false); }
int LuaPack::UnpackI16(lua_State* L) { return UnpackType<int16_t> (L, false); }
int LuaPack::UnpackI32(lua_State* L) { return UnpackType<int32_t> (L, true);  }
int LuaPack::UnpackI64(lua_State* L) { return UnpackType<int64_t> (L, true);  }
int LuaPack::UnpackF32(lua_State* L) { return UnpackType<float>   (L, false); }
int LuaPack::UnpackF64(lua_State* L) { return UnpackType<double>  (L, true);  }

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

int LuaPack::SwapBy2(lua_State* L)
{
	size_t size;
	const char* data = lua_tolstring(L, 1, &size);
	if ((size % 2) != 0) {
		return 0;
	}
	char* output = new char[size];
	for (size_t i = 0; i < size; i += 2) {
		output[i + 0] = data[i + 1];
		output[i + 1] = data[i + 0];
	}
	lua_pushlstring(L, output, size);
	delete[] output;
	return 1;
}

int LuaPack::SwapBy4(lua_State* L)
{
	size_t size;
	const char* data = lua_tolstring(L, 1, &size);
	if ((size % 4) != 0) {
		return 0;
	}
	char* output = new char[size];
	for (size_t i = 0; i < size; i += 4) {
		output[i + 0] = data[i + 3];
		output[i + 1] = data[i + 2];
		output[i + 2] = data[i + 1];
		output[i + 3] = data[i + 0];
	}
	lua_pushlstring(L, output, size);
	delete[] output;
	return 1;
}

int LuaPack::SwapBy8(lua_State* L)
{
	size_t size;
	const char* data = lua_tolstring(L, 1, &size);
	if ((size % 8) != 0) {
		return 0;
	}
	char* output = new char[size];
	for (size_t i = 0; i < size; i += 8) {
		output[i + 0] = data[i + 7];
		output[i + 1] = data[i + 6];
		output[i + 2] = data[i + 5];
		output[i + 3] = data[i + 4];
		output[i + 4] = data[i + 3];
		output[i + 5] = data[i + 2];
		output[i + 6] = data[i + 1];
		output[i + 7] = data[i + 0];
	}
	lua_pushlstring(L, output, size);
	delete[] output;
	return 1;
}

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

int LuaPack::GetEndian(lua_State* L)
{
	static unsigned char endianArray[4] = { 0x11, 0x22, 0x33, 0x44 };
	static uint32_t& endian = *((uint32_t*)endianArray);

	switch (endian) {
		case 0x44332211: { HSTR_PUSH(L, "little");  break; }
		case 0x11223344: { HSTR_PUSH(L, "big");     break; }
		case 0x22114433: { HSTR_PUSH(L, "pdp");     break; }
		default:         { HSTR_PUSH(L, "unknown"); break; }
	}

	return 1;
}

//============================================================================//
//============================================================================//
<commit_msg>* fixed the LuaUnpackXXX table count parameter<commit_after>
#include "common.h"

// interface header
#include "LuaPack.h"

// system headers
#include <string.h>
#include <string>
#include <vector>
using std::string;
using std::vector;
#include <algorithm>
using std::min;
using std::max;

// local headers
#include "LuaInclude.h"
#include "LuaHashString.h"
#include "LuaDouble.h"

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

bool LuaPack::PushEntries(lua_State* L)
{
	PUSH_LUA_CFUNC(L, PackU8);
	PUSH_LUA_CFUNC(L, PackU16);
	PUSH_LUA_CFUNC(L, PackU32);
	PUSH_LUA_CFUNC(L, PackU64);
	PUSH_LUA_CFUNC(L, PackI8);
	PUSH_LUA_CFUNC(L, PackI16);
	PUSH_LUA_CFUNC(L, PackI32);
	PUSH_LUA_CFUNC(L, PackI64);
	PUSH_LUA_CFUNC(L, PackF32);
	PUSH_LUA_CFUNC(L, PackF64); // LuaDouble

	PUSH_LUA_CFUNC(L, UnpackU8);
	PUSH_LUA_CFUNC(L, UnpackU16);
	PUSH_LUA_CFUNC(L, UnpackU32);
	PUSH_LUA_CFUNC(L, UnpackU64);
	PUSH_LUA_CFUNC(L, UnpackI8);
	PUSH_LUA_CFUNC(L, UnpackI16);
	PUSH_LUA_CFUNC(L, UnpackI32);
	PUSH_LUA_CFUNC(L, UnpackI64);
	PUSH_LUA_CFUNC(L, UnpackF32);
	PUSH_LUA_CFUNC(L, UnpackF64); // LuaDouble

	PUSH_LUA_CFUNC(L, SwapBy2);
	PUSH_LUA_CFUNC(L, SwapBy4);
	PUSH_LUA_CFUNC(L, SwapBy8);

	PUSH_LUA_CFUNC(L, GetEndian);

	return true;
}

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

template <typename T>
int PackType(lua_State* L)
{
	vector<T> vals;

	// collect the values
	if (lua_istable(L, 1)) {
		for (int i = 1; lua_checkgeti(L, 1, i); lua_pop(L, 1), i++) {
			if (lua_israwnumber(L, -1)) {
				vals.push_back((T)lua_tonumber(L, -1));
			}
			else {
				const double* dptr = LuaDouble::TestDouble(L, -1);
				if (dptr != NULL) {
					vals.push_back((T)(*dptr));
				} else {
					break; // not a lua_Number or a LuaDouble
				}
			}
		}
	}
	else {
		const int args = lua_gettop(L);
		for (int i = 1; i <= args; i++) {
			if (lua_israwnumber(L, i)) {
				vals.push_back((T)lua_tonumber(L, i));
			}
			else {
				const double* dptr = LuaDouble::TestDouble(L, i);
				if (dptr != NULL) {
					vals.push_back((T)(*dptr));
				} else {
					break; // not a lua_Number or a LuaDouble
				}
			}
		}
	}

	if (vals.empty()) {
		return 0;
	}

	// push the result
	const int bufSize = sizeof(T) * vals.size();
	char* buf = new char[bufSize];
	for (int i = 0; i < (int)vals.size(); i++) {
		memcpy(buf + (i * sizeof(T)), &vals[i], sizeof(T));
	}
	lua_pushlstring(L, buf, bufSize);
	delete[] buf;

	return 1;
}

int LuaPack::PackU8(lua_State*  L) { return PackType<uint8_t> (L); }
int LuaPack::PackU16(lua_State* L) { return PackType<uint16_t>(L); }
int LuaPack::PackU32(lua_State* L) { return PackType<uint32_t>(L); }
int LuaPack::PackU64(lua_State* L) { return PackType<uint64_t>(L); }
int LuaPack::PackI8(lua_State*  L) { return PackType<int8_t>  (L); }
int LuaPack::PackI16(lua_State* L) { return PackType<int16_t> (L); }
int LuaPack::PackI32(lua_State* L) { return PackType<int32_t> (L); }
int LuaPack::PackI64(lua_State* L) { return PackType<int64_t> (L); }
int LuaPack::PackF32(lua_State* L) { return PackType<float>   (L); }
int LuaPack::PackF64(lua_State* L) { return PackType<double>  (L); }

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

template <typename T>
int UnpackType(lua_State* L, bool defaultToDoubles = false)
{
	int index = 1;
	bool pushDoubles = defaultToDoubles;
	if (lua_isboolean(L, index)) {
		pushDoubles = lua_tobool(L, index);
		index++;
	}

	if (!lua_israwstring(L, index)) {
		return 0;
	}
	size_t len;
	const char* str = lua_tolstring(L, index, &len);

	// apply the offset
	if (lua_israwnumber(L, index + 1)) {
		const size_t offset = lua_toint(L, index + 1) - 1;
		if (offset >= len) {
			return 0;
		}
		str += offset;
		len -= offset;
	}

	const size_t eSize = sizeof(T);
	if (len < eSize) {
		return 0;
	}

	// return a single value
	if (!lua_israwnumber(L, index + 2)) {
		const T value = *((T*)str);
		if (pushDoubles) {
			LuaDouble::PushDouble(L, (double)(static_cast<lua_Number>(value)));
		} else {
			lua_pushnumber(L, static_cast<lua_Number>(value));
		}
		return 1;
	}

	// return a table
	const int maxCount = (len / eSize);
	int tableCount = lua_toint(L, index + 2);
	if (tableCount < 0) {
		tableCount = maxCount;
	}
	tableCount = min(maxCount, tableCount);
	lua_newtable(L);
	if (pushDoubles) {
		for (int i = 0; i < tableCount; i++) {
			const T value = *(((T*)str) + i);
			LuaDouble::PushDouble(L, (double)(static_cast<lua_Number>(value)));
			lua_rawseti(L, -2, (i + 1));
		}
	} else {
		for (int i = 0; i < tableCount; i++) {
			const T value = *(((T*)str) + i);
			lua_pushnumber(L, static_cast<lua_Number>(value));
			lua_rawseti(L, -2, (i + 1));
		}
	}
	return 1;
}

int LuaPack::UnpackU8(lua_State*  L) { return UnpackType<uint8_t> (L, false); }
int LuaPack::UnpackU16(lua_State* L) { return UnpackType<uint16_t>(L, false); }
int LuaPack::UnpackU32(lua_State* L) { return UnpackType<uint32_t>(L, true);  }
int LuaPack::UnpackU64(lua_State* L) { return UnpackType<uint64_t>(L, true);  }
int LuaPack::UnpackI8(lua_State*  L) { return UnpackType<int8_t>  (L, false); }
int LuaPack::UnpackI16(lua_State* L) { return UnpackType<int16_t> (L, false); }
int LuaPack::UnpackI32(lua_State* L) { return UnpackType<int32_t> (L, true);  }
int LuaPack::UnpackI64(lua_State* L) { return UnpackType<int64_t> (L, true);  }
int LuaPack::UnpackF32(lua_State* L) { return UnpackType<float>   (L, false); }
int LuaPack::UnpackF64(lua_State* L) { return UnpackType<double>  (L, true);  }

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

int LuaPack::SwapBy2(lua_State* L)
{
	size_t size;
	const char* data = lua_tolstring(L, 1, &size);
	if ((size % 2) != 0) {
		return 0;
	}
	char* output = new char[size];
	for (size_t i = 0; i < size; i += 2) {
		output[i + 0] = data[i + 1];
		output[i + 1] = data[i + 0];
	}
	lua_pushlstring(L, output, size);
	delete[] output;
	return 1;
}

int LuaPack::SwapBy4(lua_State* L)
{
	size_t size;
	const char* data = lua_tolstring(L, 1, &size);
	if ((size % 4) != 0) {
		return 0;
	}
	char* output = new char[size];
	for (size_t i = 0; i < size; i += 4) {
		output[i + 0] = data[i + 3];
		output[i + 1] = data[i + 2];
		output[i + 2] = data[i + 1];
		output[i + 3] = data[i + 0];
	}
	lua_pushlstring(L, output, size);
	delete[] output;
	return 1;
}

int LuaPack::SwapBy8(lua_State* L)
{
	size_t size;
	const char* data = lua_tolstring(L, 1, &size);
	if ((size % 8) != 0) {
		return 0;
	}
	char* output = new char[size];
	for (size_t i = 0; i < size; i += 8) {
		output[i + 0] = data[i + 7];
		output[i + 1] = data[i + 6];
		output[i + 2] = data[i + 5];
		output[i + 3] = data[i + 4];
		output[i + 4] = data[i + 3];
		output[i + 5] = data[i + 2];
		output[i + 6] = data[i + 1];
		output[i + 7] = data[i + 0];
	}
	lua_pushlstring(L, output, size);
	delete[] output;
	return 1;
}

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

int LuaPack::GetEndian(lua_State* L)
{
	static unsigned char endianArray[4] = { 0x11, 0x22, 0x33, 0x44 };
	static uint32_t& endian = *((uint32_t*)endianArray);

	switch (endian) {
		case 0x44332211: { HSTR_PUSH(L, "little");  break; }
		case 0x11223344: { HSTR_PUSH(L, "big");     break; }
		case 0x22114433: { HSTR_PUSH(L, "pdp");     break; }
		default:         { HSTR_PUSH(L, "unknown"); break; }
	}

	return 1;
}

//============================================================================//
//============================================================================//
<|endoftext|>


<commit_before>#include "jsscript.h"
#include "factory.h"
#include "context.h"
#include <iostream>
namespace iv {
namespace lv5 {

JSScript::~JSScript() {
  // this container has ownership to factory
  if (type_ != kGlobal) {
    delete factory_;
    delete source_;
  }
}

JSScript* JSScript::NewGlobal(Context* ctx,
                              const FunctionLiteral* function,
                              AstFactory* factory,
                              core::BasicSource* source) {
  return new JSScript(kGlobal, function, factory, source);
}

JSScript* JSScript::NewEval(Context* ctx,
                            const FunctionLiteral* function,
                            AstFactory* factory,
                            core::BasicSource* source) {
  return new JSScript(kEval, function, factory, source);
}

JSScript* JSScript::NewFunction(Context* ctx,
                                const FunctionLiteral* function,
                                AstFactory* factory,
                                core::BasicSource* source) {
  return new JSScript(kFunction, function, factory, source);
}

} }  // namespace iv::lv5
<commit_msg>rm wasted iostream<commit_after>#include "jsscript.h"
#include "factory.h"
#include "context.h"
namespace iv {
namespace lv5 {

JSScript::~JSScript() {
  // this container has ownership to factory
  if (type_ != kGlobal) {
    delete factory_;
    delete source_;
  }
}

JSScript* JSScript::NewGlobal(Context* ctx,
                              const FunctionLiteral* function,
                              AstFactory* factory,
                              core::BasicSource* source) {
  return new JSScript(kGlobal, function, factory, source);
}

JSScript* JSScript::NewEval(Context* ctx,
                            const FunctionLiteral* function,
                            AstFactory* factory,
                            core::BasicSource* source) {
  return new JSScript(kEval, function, factory, source);
}

JSScript* JSScript::NewFunction(Context* ctx,
                                const FunctionLiteral* function,
                                AstFactory* factory,
                                core::BasicSource* source) {
  return new JSScript(kFunction, function, factory, source);
}

} }  // namespace iv::lv5
<|endoftext|>


<commit_before>/*
* (C) 2014,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "tests.h"

#if defined(BOTAN_HAS_ECC_GROUP)

#include "test_pubkey.h"

#include <botan/pubkey.h>
#include <botan/ecdsa.h>
#include <botan/oids.h>
#include <botan/hex.h>
#include <iostream>
#include <fstream>

using namespace Botan;

namespace {

size_t ecc_point_mul(const std::string& group_id,
                     const std::string& m_s,
                     const std::string& X_s,
                     const std::string& Y_s)
   {
   EC_Group group(OIDS::lookup(group_id));

   const BigInt m(m_s);
   const BigInt X(X_s);
   const BigInt Y(Y_s);

   PointGFp p = group.get_base_point() * m;

   size_t fails = 0;

   if(p.get_affine_x() != X)
      {
      std::cout << p.get_affine_x() << " != " << X << std::endl;
      ++fails;
      }

   if(p.get_affine_y() != Y)
      {
      std::cout << p.get_affine_y() << " != " << Y << std::endl;
      ++fails;
      }

   return fails;
   }

}

size_t test_ecc_pointmul()
   {
   size_t fails = 0;

   std::ifstream ecc_mul(PK_TEST_DATA_DIR "/ecc.vec");

   fails += run_tests_bb(ecc_mul, "ECC Point Mult", "Y", false,
             [](std::map<std::string, std::string> m) -> size_t
             {
             return ecc_point_mul(m["Group"], m["m"], m["X"], m["Y"]);
             });

   return fails;
   }

#else

SKIP_TEST(ecc_pointmul);

#endif // BOTAN_HAS_ECC_GROUP
<commit_msg>ECC pointmul test requires ECDSA<commit_after>/*
* (C) 2014,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "tests.h"

#if defined(BOTAN_HAS_ECC_GROUP)

#if defined(BOTAN_HAS_ECDSA)

#include "test_pubkey.h"

#include <botan/pubkey.h>
#include <botan/ecdsa.h>
#include <botan/oids.h>
#include <botan/hex.h>
#include <iostream>
#include <fstream>

using namespace Botan;

namespace {

size_t ecc_point_mul(const std::string& group_id,
                     const std::string& m_s,
                     const std::string& X_s,
                     const std::string& Y_s)
   {
   EC_Group group(OIDS::lookup(group_id));

   const BigInt m(m_s);
   const BigInt X(X_s);
   const BigInt Y(Y_s);

   PointGFp p = group.get_base_point() * m;

   size_t fails = 0;

   if(p.get_affine_x() != X)
      {
      std::cout << p.get_affine_x() << " != " << X << std::endl;
      ++fails;
      }

   if(p.get_affine_y() != Y)
      {
      std::cout << p.get_affine_y() << " != " << Y << std::endl;
      ++fails;
      }

   return fails;
   }

}

size_t test_ecc_pointmul()
   {
   size_t fails = 0;

   std::ifstream ecc_mul(PK_TEST_DATA_DIR "/ecc.vec");

   fails += run_tests_bb(ecc_mul, "ECC Point Mult", "Y", false,
             [](std::map<std::string, std::string> m) -> size_t
             {
             return ecc_point_mul(m["Group"], m["m"], m["X"], m["Y"]);
             });

   return fails;
   }

#else

UNTESTED_WARNING(ecc_pointmul);

#endif // BOTAN_HAS_ECDSA

#else

SKIP_TEST(ecc_pointmul);

#endif // BOTAN_HAS_ECC_GROUP
<|endoftext|>


<commit_before>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Nathan Osman
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 **/

#include <QPersistentModelIndex>
#include <QProgressBar>
#include <QPushButton>

#include "transferwindow.h"

#ifdef Qt5WinExtras_FOUND
#include <QSysInfo>
#include <QWinTaskbarProgress>
#endif

TransferWindow::TransferWindow(TransferModel *model)
    : mModel(model)
#ifdef Qt5WinExtras_FOUND
    , mTaskbarButton(nullptr)
#endif
#ifdef UNITY_FOUND
    , mLauncherEntry(nullptr),
#endif
{
    setupUi(this);

    transferView->setModel(mModel);
    transferView->setColumnWidth(TransferModel::DeviceNameColumn, 150);
    transferView->setColumnWidth(TransferModel::ProgressColumn, 150);
    transferView->setColumnWidth(TransferModel::StateColumn, 200);

    connect(sendDirectoryBtn, &QPushButton::clicked, this, &TransferWindow::sendDirectory);
    connect(sendFilesBtn, &QPushButton::clicked, this, &TransferWindow::sendFiles);
    connect(clear, &QPushButton::clicked, mModel, &TransferModel::clear);

    connect(mModel, &TransferModel::rowsInserted, this, &TransferWindow::onRowsInserted);
    connect(mModel, &TransferModel::dataChanged, this, &TransferWindow::onDataChanged);

#ifdef UNITY_FOUND
    mLauncherEntry = unity_launcher_entry_get_for_desktop_id("nitroshare.desktop");
#endif
}

void TransferWindow::onRowsInserted(const QModelIndex &, int first, int last)
{
    for(int row = first; row <= last; ++row) {

        // Create a progress box for (surprise!) displaying progress
        // It will remain in place as long as the row does
        QProgressBar *progressBar = new QProgressBar;
        progressBar->setMinimum(0);
        progressBar->setMaximum(100);
        progressBar->setAutoFillBackground(true);
        transferView->setIndexWidget(mModel->index(row, TransferModel::ProgressColumn), progressBar);

        // Update the button displayed in the action column
        updateButton(row);
    }
}

void TransferWindow::onDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight,  const QVector<int> &roles)
{
    for(int row = topLeft.row(); row <= bottomRight.row(); ++row) {

        // Update the progress box if its value has changed
        if(roles.contains(TransferModel::ProgressRole) || roles.empty()) {
            updateProgressBar(row);
        }

        // Update the button if the state has changed
        if(roles.contains(TransferModel::StateRole) || roles.isEmpty()) {
            updateButton(row);
        }
    }

#ifdef Qt5WinExtras_FOUND
    if(mTaskbarButton) {
        int progress = mModel->combinedProgress();
        mTaskbarButton->progress()->setValue(progress);
        mTaskbarButton->progress()->setVisible(progress > 0 && progress < 100);
    }
#endif

#ifdef UNITY_FOUND
    if(mLauncherEntry) {
        int progress = mModel->combinedProgress();
        unity_launcher_entry_set_progress(mLauncherEntry, static_cast<double>(progress) / 100.0f);
        unity_launcher_entry_set_progress_visible(mLauncherEntry, progress > 0 && progress < 100);
    }
#endif
}

#ifdef Qt5WinExtras_FOUND
void TransferWindow::showEvent(QShowEvent *)
{
    if(!mTaskbarButton && QSysInfo::windowsVersion() >= QSysInfo::WV_WINDOWS7) {
        mTaskbarButton = new QWinTaskbarButton(this);
        mTaskbarButton->setWindow(windowHandle());
    }
}

void TransferWindow::hideEvent(QHideEvent *)
{
    if(mTaskbarButton) {
        delete mTaskbarButton;
        mTaskbarButton = nullptr;
    }
}
#endif

void TransferWindow::updateProgressBar(int row)
{
    // Retrieve a pointer to the progress bar widget
    QModelIndex index = mModel->index(row, TransferModel::ProgressColumn);
    QProgressBar *progressBar = qobject_cast<QProgressBar*>(transferView->indexWidget(index));

    // Retrieve the value from the model and update the control
    int progress = index.data(TransferModel::ProgressRole).toInt();
    progressBar->setValue(progress);
}

void TransferWindow::updateButton(int row)
{
    // Create the button and persistent model index used to reference the row
    QPushButton *button = new QPushButton;
    QPersistentModelIndex index(mModel->index(row, 0));

    // The title and action for the button depend on the direction and state
    int direction = index.data(TransferModel::DirectionRole).toInt();
    int state = index.data(TransferModel::StateRole).toInt();

    // Display:
    // - a cancel button for transfers in progress
    // - a restart button for failed and canceled transfers being sent
    // - a dismiss button for everything else
    if(state == TransferModel::Connecting || state == TransferModel::InProgress) {

        button->setText(tr("Cancel"));
        connect(button, &QPushButton::clicked, [this, index]() {
            mModel->cancel(index.row());
        });

    } else if(direction == TransferModel::Send && state == TransferModel::Failed) {

        button->setText(tr("Restart"));
        connect(button, &QPushButton::clicked, [this, index]() {
            mModel->restart(index.row());
        });

    } else {

        button->setText(tr("Dismiss"));
        connect(button, &QPushButton::clicked, [this, index]() {
            mModel->dismiss(index.row());
        });
    }

    // Insert the button into the table
    transferView->setIndexWidget(mModel->index(row, TransferModel::ActionColumn), button);
}
<commit_msg>Fixed syntax error.<commit_after>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Nathan Osman
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 **/

#include <QPersistentModelIndex>
#include <QProgressBar>
#include <QPushButton>

#include "transferwindow.h"

#ifdef Qt5WinExtras_FOUND
#include <QSysInfo>
#include <QWinTaskbarProgress>
#endif

TransferWindow::TransferWindow(TransferModel *model)
    : mModel(model)
#ifdef Qt5WinExtras_FOUND
    , mTaskbarButton(nullptr)
#endif
#ifdef UNITY_FOUND
    , mLauncherEntry(nullptr)
#endif
{
    setupUi(this);

    transferView->setModel(mModel);
    transferView->setColumnWidth(TransferModel::DeviceNameColumn, 150);
    transferView->setColumnWidth(TransferModel::ProgressColumn, 150);
    transferView->setColumnWidth(TransferModel::StateColumn, 200);

    connect(sendDirectoryBtn, &QPushButton::clicked, this, &TransferWindow::sendDirectory);
    connect(sendFilesBtn, &QPushButton::clicked, this, &TransferWindow::sendFiles);
    connect(clear, &QPushButton::clicked, mModel, &TransferModel::clear);

    connect(mModel, &TransferModel::rowsInserted, this, &TransferWindow::onRowsInserted);
    connect(mModel, &TransferModel::dataChanged, this, &TransferWindow::onDataChanged);

#ifdef UNITY_FOUND
    mLauncherEntry = unity_launcher_entry_get_for_desktop_id("nitroshare.desktop");
#endif
}

void TransferWindow::onRowsInserted(const QModelIndex &, int first, int last)
{
    for(int row = first; row <= last; ++row) {

        // Create a progress box for (surprise!) displaying progress
        // It will remain in place as long as the row does
        QProgressBar *progressBar = new QProgressBar;
        progressBar->setMinimum(0);
        progressBar->setMaximum(100);
        progressBar->setAutoFillBackground(true);
        transferView->setIndexWidget(mModel->index(row, TransferModel::ProgressColumn), progressBar);

        // Update the button displayed in the action column
        updateButton(row);
    }
}

void TransferWindow::onDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight,  const QVector<int> &roles)
{
    for(int row = topLeft.row(); row <= bottomRight.row(); ++row) {

        // Update the progress box if its value has changed
        if(roles.contains(TransferModel::ProgressRole) || roles.empty()) {
            updateProgressBar(row);
        }

        // Update the button if the state has changed
        if(roles.contains(TransferModel::StateRole) || roles.isEmpty()) {
            updateButton(row);
        }
    }

#ifdef Qt5WinExtras_FOUND
    if(mTaskbarButton) {
        int progress = mModel->combinedProgress();
        mTaskbarButton->progress()->setValue(progress);
        mTaskbarButton->progress()->setVisible(progress > 0 && progress < 100);
    }
#endif

#ifdef UNITY_FOUND
    if(mLauncherEntry) {
        int progress = mModel->combinedProgress();
        unity_launcher_entry_set_progress(mLauncherEntry, static_cast<double>(progress) / 100.0f);
        unity_launcher_entry_set_progress_visible(mLauncherEntry, progress > 0 && progress < 100);
    }
#endif
}

#ifdef Qt5WinExtras_FOUND
void TransferWindow::showEvent(QShowEvent *)
{
    if(!mTaskbarButton && QSysInfo::windowsVersion() >= QSysInfo::WV_WINDOWS7) {
        mTaskbarButton = new QWinTaskbarButton(this);
        mTaskbarButton->setWindow(windowHandle());
    }
}

void TransferWindow::hideEvent(QHideEvent *)
{
    if(mTaskbarButton) {
        delete mTaskbarButton;
        mTaskbarButton = nullptr;
    }
}
#endif

void TransferWindow::updateProgressBar(int row)
{
    // Retrieve a pointer to the progress bar widget
    QModelIndex index = mModel->index(row, TransferModel::ProgressColumn);
    QProgressBar *progressBar = qobject_cast<QProgressBar*>(transferView->indexWidget(index));

    // Retrieve the value from the model and update the control
    int progress = index.data(TransferModel::ProgressRole).toInt();
    progressBar->setValue(progress);
}

void TransferWindow::updateButton(int row)
{
    // Create the button and persistent model index used to reference the row
    QPushButton *button = new QPushButton;
    QPersistentModelIndex index(mModel->index(row, 0));

    // The title and action for the button depend on the direction and state
    int direction = index.data(TransferModel::DirectionRole).toInt();
    int state = index.data(TransferModel::StateRole).toInt();

    // Display:
    // - a cancel button for transfers in progress
    // - a restart button for failed and canceled transfers being sent
    // - a dismiss button for everything else
    if(state == TransferModel::Connecting || state == TransferModel::InProgress) {

        button->setText(tr("Cancel"));
        connect(button, &QPushButton::clicked, [this, index]() {
            mModel->cancel(index.row());
        });

    } else if(direction == TransferModel::Send && state == TransferModel::Failed) {

        button->setText(tr("Restart"));
        connect(button, &QPushButton::clicked, [this, index]() {
            mModel->restart(index.row());
        });

    } else {

        button->setText(tr("Dismiss"));
        connect(button, &QPushButton::clicked, [this, index]() {
            mModel->dismiss(index.row());
        });
    }

    // Insert the button into the table
    transferView->setIndexWidget(mModel->index(row, TransferModel::ActionColumn), button);
}
<|endoftext|>