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

// include ---------------------------------------------------------------

#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

class SvXMLUnitConverter;
namespace rtl
{
    class OUString;
}

// class SvxOpaqueItem ---------------------------------------------------

/*
[Beschreibung]
Dieses Item beschreibt eine logische Variable "Undurchsichtig ja oder nein".
*/

class SVX_DLLPUBLIC SvxOpaqueItem : public SfxBoolItem
{
public:
    TYPEINFO();

    SvxOpaqueItem( const USHORT nId = ITEMID_OPAQUE, const BOOL bOpa = TRUE );
    inline SvxOpaqueItem &operator=( const SvxOpaqueItem &rCpy );

    // "pure virtual Methoden" vom SfxPoolItem
    virtual SfxPoolItem*    Clone( SfxItemPool *pPool = 0 ) const;
    virtual SfxPoolItem*    Create(SvStream &, USHORT) const;
    virtual SvStream&       Store(SvStream &, USHORT nItemVersion ) const;

    virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
                                    SfxMapUnit eCoreMetric,
                                    SfxMapUnit ePresMetric,
                                    String &rText, const IntlWrapper * = 0 ) const;
};

inline SvxOpaqueItem::SvxOpaqueItem( const USHORT nId, const BOOL bOpa )
    : SfxBoolItem( nId, bOpa )
{}

inline SvxOpaqueItem &SvxOpaqueItem::operator=( const SvxOpaqueItem &rCpy )
{
    SetValue( rCpy.GetValue() );
    return *this;
}

#endif

<commit_msg>INTEGRATION: CWS pchfix04 (1.7.256); FILE MERGED 2007/02/05 12:13:44 os 1.7.256.1: #i73604# usage of ITEMID_* removed<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: opaqitem.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 14:20:27 $
 *
 *  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 _SVX_OPAQITEM_HXX
#define _SVX_OPAQITEM_HXX

// include ---------------------------------------------------------------

#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

class SvXMLUnitConverter;
namespace rtl
{
    class OUString;
}

// class SvxOpaqueItem ---------------------------------------------------

/*
[Beschreibung]
Dieses Item beschreibt eine logische Variable "Undurchsichtig ja oder nein".
*/

class SVX_DLLPUBLIC SvxOpaqueItem : public SfxBoolItem
{
public:
    TYPEINFO();

    SvxOpaqueItem( const USHORT nId , const BOOL bOpa = TRUE );
    inline SvxOpaqueItem &operator=( const SvxOpaqueItem &rCpy );

    // "pure virtual Methoden" vom SfxPoolItem
    virtual SfxPoolItem*    Clone( SfxItemPool *pPool = 0 ) const;
    virtual SfxPoolItem*    Create(SvStream &, USHORT) const;
    virtual SvStream&       Store(SvStream &, USHORT nItemVersion ) const;

    virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
                                    SfxMapUnit eCoreMetric,
                                    SfxMapUnit ePresMetric,
                                    String &rText, const IntlWrapper * = 0 ) const;
};

inline SvxOpaqueItem::SvxOpaqueItem( const USHORT nId, const BOOL bOpa )
    : SfxBoolItem( nId, bOpa )
{}

inline SvxOpaqueItem &SvxOpaqueItem::operator=( const SvxOpaqueItem &rCpy )
{
    SetValue( rCpy.GetValue() );
    return *this;
}

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: srchitem.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 18:39:25 $
 *
 *  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 _SVX_SRCHITEM_HXX
#define _SVX_SRCHITEM_HXX

#include <sfx2/srchitem.hxx>

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.2.1256); FILE MERGED 2008/03/31 14:17:59 rt 1.2.1256.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: srchitem.hxx,v $
 * $Revision: 1.3 $
 *
 * 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 _SVX_SRCHITEM_HXX
#define _SVX_SRCHITEM_HXX

#include <sfx2/srchitem.hxx>

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: svdviter.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 18:57:44 $
 *
 *  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 _SVDVITER_HXX
#define _SVDVITER_HXX

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

////////////////////////////////////////////////////////////////////////////////////////////////////

class OutputDevice;
class Window;
class SdrView;
class SdrPageView;
class SdrModel;
class SdrPage;
class SdrObject;
class SetOfByte;

////////////////////////////////////////////////////////////////////////////////////////////////////

class SVX_DLLPUBLIC SdrViewIter {
    const SdrModel*  pModel;
    const SdrPage*   pPage;
    const SdrObject* pObject;
    SdrView*   pAktView;
    FASTBOOL   bNoMasterPage;
    USHORT     nListenerNum;
    USHORT     nPageViewNum;
    USHORT     nOutDevNum;
private:
    SVX_DLLPRIVATE void          ImpInitVars();
    SVX_DLLPRIVATE SdrView*      ImpFindView();
    SVX_DLLPRIVATE SdrPageView*  ImpFindPageView();
    SVX_DLLPRIVATE OutputDevice* ImpFindOutDev();
    SVX_DLLPRIVATE Window*       ImpFindWindow();
    SVX_DLLPRIVATE FASTBOOL      ImpCheckPageView(SdrPageView* pPV) const;
public:
    SdrViewIter(const SdrModel*  pModel);
    SdrViewIter(const SdrPage*   pPage, FASTBOOL bNoMasterPage=FALSE);
    SdrViewIter(const SdrObject* pObject, FASTBOOL bNoMasterPage=FALSE);
    SdrView*      FirstView();
    SdrView*      NextView();
    SdrPageView*  FirstPageView();
    SdrPageView*  NextPageView();
    OutputDevice* FirstOutDev();
    OutputDevice* NextOutDev();
    Window*       FirstWindow();
    Window*       NextWindow();
};

////////////////////////////////////////////////////////////////////////////////////////////////////

#ifdef _JUST_DESCRIPTION

Mit dieser Klasse kann man rausbekommen:
- SdrView* First/NextView()
  - Alle Views in denen ein Models dargestellt wird
  - Alle Views in denen eine bestimme Page sichtbar ist (ww. auch als MasterPage)
  - Alle Views in denen ein bestimmes Objekt sichtbar ist (ww. auch auf MasterPage)
- SdrPageView* First/NextPageView()
  - Alle PageViews in denen ein Models dargestellt wird
  - Alle PageViews in denen eine bestimme Page sichtbar ist (ww. auch als MasterPage)
  - Alle PageViews in denen ein bestimmes Objekt sichtbar ist (ww. auch auf MasterPage)
- OutputDevice* First/NextOutDev()
  - Alle OutputDevices in denen ein Models dargestellt wird
  - Alle OutputDevices in denen eine bestimme Page sichtbar ist (ww. auch als MasterPage)
  - Alle OutputDevices in denen ein bestimmes Objekt sichtbar ist (ww. auch auf MasterPage)
- Window* First/NextWindow()
  - Alle Windows in denen ein Models dargestellt wird
  - Alle Windows in denen eine bestimme Page sichtbar ist (auch als MasterPage)
  - Alle Windows in denen ein bestimmes Objekt sichtbar ist (auch auf MasterPage)
Ob die Auswahl auf ein(e) bestimmte(s) Page/Objekt beschraenkt wird, bestimmt man
durch die Wahl des Konstruktors.

Es werden u.a. auch berueksichtigt:
- Layer Sichtbarkeitsstatus
- Visible Layer von MasterPages
- Mehrfachlayer bei Gruppenobjekten

Es wird nicht berueksichtigt:
- Ob die Pages/Objekte wirklich schon gepaintet wurden oder noch ein Invalidate ansteht, ...
- Ob die Pages/Objekte in einem Window im sichtbaren Bereich liegen

#endif // _JUST_DESCRIPTION

////////////////////////////////////////////////////////////////////////////////////////////////////

#endif //_SVDVITER_HXX

<commit_msg>INTEGRATION: CWS aw024 (1.2.194); FILE MERGED 2005/09/18 00:53:27 aw 1.2.194.2: RESYNC: (1.2-1.3); FILE MERGED 2005/05/19 12:29:49 aw 1.2.194.1: #i39529#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: svdviter.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: ihi $ $Date: 2006-11-14 12:55:27 $
 *
 *  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 _SVDVITER_HXX
#define _SVDVITER_HXX

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

////////////////////////////////////////////////////////////////////////////////////////////////////

class OutputDevice;
class Window;
class SdrView;
class SdrPageView;
class SdrModel;
class SdrPage;
class SdrObject;
class SetOfByte;

////////////////////////////////////////////////////////////////////////////////////////////////////

class SVX_DLLPUBLIC SdrViewIter
{
    const SdrModel*                                     mpModel;
    const SdrPage*                                      mpPage;
    const SdrObject*                                    mpObject;
    SdrView*                                            mpAktView;

    sal_uInt32                                          mnListenerNum;
    sal_uInt32                                          mnPageViewNum;
    sal_uInt32                                          mnOutDevNum;

    // bitfield
    unsigned                                            mbNoMasterPage : 1;

private:
    SVX_DLLPRIVATE void          ImpInitVars();
    SVX_DLLPRIVATE SdrView*      ImpFindView();
    SVX_DLLPRIVATE SdrPageView*  ImpFindPageView();
    SVX_DLLPRIVATE OutputDevice* ImpFindOutDev();
    SVX_DLLPRIVATE Window*       ImpFindWindow();
    SVX_DLLPRIVATE sal_Bool      ImpCheckPageView(SdrPageView* pPV) const;

public:
    SdrViewIter(const SdrModel* pModel);
    SdrViewIter(const SdrPage* pPage, sal_Bool bNoMasterPage = sal_False);
    SdrViewIter(const SdrObject* pObject, sal_Bool bNoMasterPage = sal_False);

    SdrView* FirstView();
    SdrView* NextView();

    SdrPageView* FirstPageView();
    SdrPageView* NextPageView();

    OutputDevice* FirstOutDev();
    OutputDevice* NextOutDev();

    Window* FirstWindow();
    Window* NextWindow();
};

////////////////////////////////////////////////////////////////////////////////////////////////////

#ifdef _JUST_DESCRIPTION

Mit dieser Klasse kann man rausbekommen:
- SdrView* First/NextView()
  - Alle Views in denen ein Models dargestellt wird
  - Alle Views in denen eine bestimme Page sichtbar ist (ww. auch als MasterPage)
  - Alle Views in denen ein bestimmes Objekt sichtbar ist (ww. auch auf MasterPage)
- SdrPageView* First/NextPageView()
  - Alle PageViews in denen ein Models dargestellt wird
  - Alle PageViews in denen eine bestimme Page sichtbar ist (ww. auch als MasterPage)
  - Alle PageViews in denen ein bestimmes Objekt sichtbar ist (ww. auch auf MasterPage)
- OutputDevice* First/NextOutDev()
  - Alle OutputDevices in denen ein Models dargestellt wird
  - Alle OutputDevices in denen eine bestimme Page sichtbar ist (ww. auch als MasterPage)
  - Alle OutputDevices in denen ein bestimmes Objekt sichtbar ist (ww. auch auf MasterPage)
- Window* First/NextWindow()
  - Alle Windows in denen ein Models dargestellt wird
  - Alle Windows in denen eine bestimme Page sichtbar ist (auch als MasterPage)
  - Alle Windows in denen ein bestimmes Objekt sichtbar ist (auch auf MasterPage)
Ob die Auswahl auf ein(e) bestimmte(s) Page/Objekt beschraenkt wird, bestimmt man
durch die Wahl des Konstruktors.

Es werden u.a. auch berueksichtigt:
- Layer Sichtbarkeitsstatus
- Visible Layer von MasterPages
- Mehrfachlayer bei Gruppenobjekten

Es wird nicht berueksichtigt:
- Ob die Pages/Objekte wirklich schon gepaintet wurden oder noch ein Invalidate ansteht, ...
- Ob die Pages/Objekte in einem Window im sichtbaren Bereich liegen

#endif // _JUST_DESCRIPTION

////////////////////////////////////////////////////////////////////////////////////////////////////

#endif //_SVDVITER_HXX

<|endoftext|>


<commit_before>#include "shoppinglist.h"

ShoppingList::ShoppingList(QObject *parent) : QAbstractTableModel(parent)
{
}

void ShoppingList::newItem(QString itemName, double price, int amount)
{
	setItemPrice(itemName, price);
	setItemAmount(itemName, amount);
}

void ShoppingList::setItemPrice(QString itemName, double price)
{
	items[itemName].second = price;
}

void ShoppingList::setItemAmount(QString itemName, int amount)
{
	items[itemName].first = amount;
}

void ShoppingList::deleteItem(QString itemName)
{
	items.erase(items.find(itemName));
}

void ShoppingList::wipeList()
{
	items.clear();
}

/**
 * QAbstractTableModel subclassing convenience functions.
 **/

void ShoppingList::setItemAmount(const QModelIndex &parent, int amount)
{
	setItemAmount(getItem(parent).key(), amount);
}

void ShoppingList::deleteItem(const QModelIndex &parent)
{
	deleteItem(getItem(parent).key());
}

ShoppingListDB::const_iterator ShoppingList::getItem(const QModelIndex &parent) const
{
	return (items.begin() + parent.row());
}

ShoppingListDB::iterator ShoppingList::getItem(const QModelIndex &parent)
{
	return (items.begin() + parent.row());
}

/**
 * Neccessary functions for QAbstractTableModel subclassing.
 **/

int ShoppingList::rowCount(const QModelIndex &parent) const
{
	return items.size();
}

int ShoppingList::columnCount(const QModelIndex &parent) const
{
	return NUM_SHOPPINGLIST_PROPERTIES;
}

QVariant ShoppingList::data(const QModelIndex &index, int role) const
{
	ShoppingListDB::const_iterator item = getItem(index);
	int column = index.column();

	switch (column) {
		case ITEM_NAME_COL:
			return QVariant(item.key());
		case ITEM_PRICE_COL:
			return QVariant(item->second);
		case ITEM_AMOUNT_COL:
			return QVariant(item->first);
	}
}

<commit_msg>Rename contd.<commit_after>#include "shoppinglist.h"

ShoppingList::ShoppingList(QObject *parent) : QAbstractTableModel(parent)
{
}

void ShoppingList::newItem(QString itemName, double price, int amount)
{
	setItemPrice(itemName, price);
	setItemAmount(itemName, amount);
}

void ShoppingList::setItemPrice(QString itemName, double price)
{
	items[itemName].second = price;
}

void ShoppingList::setItemAmount(QString itemName, int amount)
{
	items[itemName].first = amount;
}

void ShoppingList::deleteItem(QString itemName)
{
	items.erase(items.find(itemName));
}

void ShoppingList::wipeList()
{
	items.clear();
}

/**
 * QAbstractTableModel subclassing convenience functions.
 **/

void ShoppingList::setItemAmount(const QModelIndex &parent, int amount)
{
	setItemAmount(getItem(parent).key(), amount);
}

void ShoppingList::deleteItem(const QModelIndex &parent)
{
	deleteItem(getItem(parent).key());
}

ShoppingListData::const_iterator ShoppingList::getItem(const QModelIndex &parent) const
{
	return (items.begin() + parent.row());
}

ShoppingListData::iterator ShoppingList::getItem(const QModelIndex &parent)
{
	return (items.begin() + parent.row());
}

/**
 * Neccessary functions for QAbstractTableModel subclassing.
 **/

int ShoppingList::rowCount(const QModelIndex &parent) const
{
	return items.size();
}

int ShoppingList::columnCount(const QModelIndex &parent) const
{
	return NUM_SHOPPINGLIST_PROPERTIES;
}

QVariant ShoppingList::data(const QModelIndex &index, int role) const
{
	ShoppingListData::const_iterator item = getItem(index);
	int column = index.column();

	switch (column) {
		case ITEM_NAME_COL:
			return QVariant(item.key());
		case ITEM_PRICE_COL:
			return QVariant(item->second);
		case ITEM_AMOUNT_COL:
			return QVariant(item->first);
	}
}

<|endoftext|>


<commit_before>#ifndef AL_OMNIAPP_H
#define AL_OMNIAPP_H

#include "allocore/al_Allocore.hpp"
#include "allocore/io/al_Window.hpp"
#include "allocore/protocol/al_OSC.hpp"
#include "alloutil/al_FPS.hpp"
#include "alloutil/al_OmniStereo.hpp"

#define PORT_TO_DEVICE_SERVER (12000)
#define PORT_FROM_DEVICE_SERVER (PORT_TO_DEVICE_SERVER+1)

// deprecated, do not use:
#define DEVICE_SERVER_SEND_PORT (PORT_FROM_DEVICE_SERVER)
#define DEVICE_SERVER_RECEIVE_PORT (PORT_TO_DEVICE_SERVER)

#define DEVICE_SERVER_IP_ADDRESS "BOSSANOVA"

namespace al {

class OmniApp : public Window, public osc::PacketHandler, public FPS, public OmniStereo::Drawable {
public:
	OmniApp(std::string name = "omniapp", bool slave=false);
	virtual ~OmniApp();

	void start();

	virtual void onDraw(Graphics& gl) {}
	virtual void onAnimate(al_sec dt) {}
	virtual void onSound(AudioIOData& io) {}
	virtual void onMessage(osc::Message& m);

	const AudioIO&		audioIO() const { return mAudioIO; }
	AudioIO&			audioIO(){ return mAudioIO; }

	const Lens&			lens() const { return mLens; }
	Lens&				lens() { return mLens; }

	const Graphics&		graphics() const { return mGraphics; }
	Graphics&			graphics(){ return mGraphics; }

	const Nav&			nav() const { return mNav; }
	Nav&				nav(){ return mNav; }

	ShaderProgram&		shader() { return mShader; }

	const std::string&	name() const { return mName; }
	OmniApp&			name(const std::string& v){ mName=v; return *this; }

	osc::Recv&			oscRecv(){ return mOSCRecv; }
	osc::Send&			oscSend(){ return mOSCSend; }

	OmniStereo&			omni() { return mOmni; }

	const std::string&	hostName() const { return mHostName; }

	bool				omniEnable() const { return bOmniEnable; }
	void				omniEnable(bool b) { bOmniEnable = b; }

	void initWindow(
		const Window::Dim& dims = Window::Dim(800, 400),
		const std::string title = "OmniApp",
		double fps = 60,
		Window::DisplayMode mode = Window::DEFAULT_BUF);

	void initAudio(
		double audioRate=44100, int audioBlockSize=256
	);

	void initAudio(
		std::string devicename,
    double audioRate, int audioBlockSize,
		int audioInputs, int audioOutputs
	);
	void initOmni(std::string path = "");

	void sendHandshake();
	void sendDisconnect();

	virtual bool onCreate();
	virtual bool onFrame();
	virtual void onDrawOmni(OmniStereo& omni);

	virtual std::string	vertexCode();
	virtual std::string	fragmentCode();

protected:

	AudioIO mAudioIO;
	OmniStereo mOmni;

	Lens mLens;
	Graphics mGraphics;

	ShaderProgram mShader;

	// control
	Nav mNav;
	NavInputControl mNavControl;
	StandardWindowKeyControls mStdControls;
	osc::Recv mOSCRecv;
	osc::Send mOSCSend;

	std::string mName;
	std::string mHostName;

	double mNavSpeed, mNavTurnSpeed;

	bool bOmniEnable, bSlave;

	static void AppAudioCB(AudioIOData& io);
};

// INLINE IMPLEMENTATION //

inline OmniApp::OmniApp(std::string name, bool slave)
:	mNavControl(mNav),
	mOSCRecv(PORT_FROM_DEVICE_SERVER),
	mOSCSend(PORT_TO_DEVICE_SERVER, DEVICE_SERVER_IP_ADDRESS),
	bSlave(slave)
{
	bOmniEnable = true;
	mHostName = Socket::hostName();
	mName = name;

	mNavSpeed = 1;
	mNavTurnSpeed = 0.02;

	lens().near(0.01).far(40).eyeSep(0.03);
	nav().smooth(0.8);

	Window::append(mStdControls);
	initWindow();
	initOmni();

	if (!bSlave) {
		Window::append(mNavControl);
		initAudio();

		oscRecv().bufferSize(32000);
		oscRecv().handler(*this);
		sendHandshake();
	}
}

inline OmniApp::~OmniApp() {
	if (!bSlave) sendDisconnect();
}

inline void OmniApp::initOmni(std::string path) {

	mOmni.configure(path, mHostName);
	if (mOmni.activeStereo()) {
		mOmni.mode(OmniStereo::ACTIVE).stereo(true);
	}
}

inline void OmniApp::initWindow(
	const Window::Dim& dims, const std::string title, double fps, Window::DisplayMode mode) {
	Window::dimensions(dims);
	Window::title(title);
	Window::fps(fps);
	Window::displayMode(mode);
}

inline void OmniApp::initAudio(
	double audioRate, int audioBlockSize
) {
	mAudioIO.callback = AppAudioCB;
	mAudioIO.user(this);
	mAudioIO.framesPerSecond(audioRate);
	mAudioIO.framesPerBuffer(audioBlockSize);
}

inline void OmniApp::initAudio(
	std::string devicename,
	double audioRate, int audioBlockSize,
	int audioInputs, int audioOutputs
) {
	AudioDevice indev(devicename, AudioDevice::INPUT);
	AudioDevice outdev(devicename, AudioDevice::OUTPUT);
	indev.print();
	outdev.print();
	mAudioIO.deviceIn(indev);
	mAudioIO.deviceOut(outdev);
	mAudioIO.channelsOut(audioOutputs);
	mAudioIO.channelsIn(audioInputs);
	initAudio(audioRate, audioBlockSize);
}

inline void OmniApp::sendHandshake(){
	oscSend().send("/handshake", name(), oscRecv().port());
}

inline void OmniApp::sendDisconnect(){
	oscSend().send("/disconnectApplication", name());
}

inline void OmniApp::start() {
	if (mOmni.activeStereo()) {
		Window::displayMode(Window::displayMode() | Window::STEREO_BUF);
	}

	create();

	if (mOmni.fullScreen()) {
		fullScreen(true);
		cursorHide(true);
	}

	if (!bSlave) {
		if(oscSend().opened()) sendHandshake();
		mAudioIO.start();
	}

	Main::get().start();
}

inline bool OmniApp::onCreate() {
	mOmni.onCreate();

	Shader vert, frag;
	vert.source(OmniStereo::glsl() + vertexCode(), Shader::VERTEX).compile();
	vert.printLog();
	frag.source(fragmentCode(), Shader::FRAGMENT).compile();
	frag.printLog();
	mShader.attach(vert).attach(frag).link();
	mShader.printLog();
	mShader.begin();
	mShader.uniform("lighting", 1.0);
	mShader.end();

	return true;
}

inline bool OmniApp::onFrame() {
	FPS::onFrame();

	while(oscRecv().recv()) {}

	nav().step();

	onAnimate(dt);

	Viewport vp(width(), height());

	if (bOmniEnable) {
		mOmni.onFrame(*this, lens(), nav(), vp);
	} else {
		mOmni.onFrameFront(*this, lens(), nav(), vp);
	}
	return true;
}

inline void OmniApp::onDrawOmni(OmniStereo& omni) {
	graphics().error("start onDraw");

	mShader.begin();
	mOmni.uniforms(mShader);

	onDraw(graphics());

	mShader.end();
}

inline void OmniApp::onMessage(osc::Message& m) {
	float x;
	if (m.addressPattern() == "/mx") {
		m >> x;
		nav().moveR(-x * mNavSpeed);

	} else if (m.addressPattern() == "/my") {
		m >> x;
		nav().moveU(x * mNavSpeed);

	} else if (m.addressPattern() == "/mz") {
		m >> x;
		nav().moveF(x * mNavSpeed);

	} else if (m.addressPattern() == "/tx") {
		m >> x;
		nav().spinR(x * -mNavTurnSpeed);

	} else if (m.addressPattern() == "/ty") {
		m >> x;
		nav().spinU(x * mNavTurnSpeed);

	} else if (m.addressPattern() == "/tz") {
		m >> x;
		nav().spinF(x * -mNavTurnSpeed);

	} else if (m.addressPattern() == "/home") {
		nav().home();

	} else if (m.addressPattern() == "/halt") {
		nav().halt();

	}
}

inline std::string	OmniApp::vertexCode() {
	return AL_STRINGIFY(
		varying vec4 color;
		varying vec3 normal, lightDir, eyeVec;
		void main(){
			color = gl_Color;
			vec4 vertex = gl_ModelViewMatrix * gl_Vertex;
			normal = gl_NormalMatrix * gl_Normal;
			vec3 V = vertex.xyz;
			eyeVec = normalize(-V);
			lightDir = normalize(vec3(gl_LightSource[0].position.xyz - V));
			gl_Position = omni_render(vertex);
		}
	);
}

inline std::string OmniApp::fragmentCode() {
	return AL_STRINGIFY(
		uniform float lighting;
		varying vec4 color;
		varying vec3 normal, lightDir, eyeVec;
    	void main() {
			vec4 final_color = color * gl_LightSource[0].ambient;
			vec3 N = normalize(normal);
			vec3 L = lightDir;
			float lambertTerm = max(dot(N, L), 0.0);
			final_color += gl_LightSource[0].diffuse * color * lambertTerm;
			vec3 E = eyeVec;
			vec3 R = reflect(-L, N);
			float spec = pow(max(dot(R, E), 0.0), 0.9 + 1e-20);
			final_color += gl_LightSource[0].specular * spec;
			gl_FragColor = mix(color, final_color, lighting);
		}
	);
}

inline void OmniApp::AppAudioCB(AudioIOData& io){
	OmniApp& app = io.user<OmniApp>();
	io.frame(0);
	app.onSound(io);
}

}

#endif
<commit_msg>added 2d texturing to OmniApp shader, uniform texture is a float from 0 to 1 specifying how much of the texture color to mix in<commit_after>#ifndef AL_OMNIAPP_H
#define AL_OMNIAPP_H

#include "allocore/al_Allocore.hpp"
#include "allocore/io/al_Window.hpp"
#include "allocore/protocol/al_OSC.hpp"
#include "alloutil/al_FPS.hpp"
#include "alloutil/al_OmniStereo.hpp"

#define PORT_TO_DEVICE_SERVER (12000)
#define PORT_FROM_DEVICE_SERVER (PORT_TO_DEVICE_SERVER+1)

// deprecated, do not use:
#define DEVICE_SERVER_SEND_PORT (PORT_FROM_DEVICE_SERVER)
#define DEVICE_SERVER_RECEIVE_PORT (PORT_TO_DEVICE_SERVER)

#define DEVICE_SERVER_IP_ADDRESS "BOSSANOVA"

namespace al {

class OmniApp : public Window, public osc::PacketHandler, public FPS, public OmniStereo::Drawable {
public:
	OmniApp(std::string name = "omniapp", bool slave=false);
	virtual ~OmniApp();

	void start();

	virtual void onDraw(Graphics& gl) {}
	virtual void onAnimate(al_sec dt) {}
	virtual void onSound(AudioIOData& io) {}
	virtual void onMessage(osc::Message& m);

	const AudioIO&		audioIO() const { return mAudioIO; }
	AudioIO&			audioIO(){ return mAudioIO; }

	const Lens&			lens() const { return mLens; }
	Lens&				lens() { return mLens; }

	const Graphics&		graphics() const { return mGraphics; }
	Graphics&			graphics(){ return mGraphics; }

	const Nav&			nav() const { return mNav; }
	Nav&				nav(){ return mNav; }

	ShaderProgram&		shader() { return mShader; }

	const std::string&	name() const { return mName; }
	OmniApp&			name(const std::string& v){ mName=v; return *this; }

	osc::Recv&			oscRecv(){ return mOSCRecv; }
	osc::Send&			oscSend(){ return mOSCSend; }

	OmniStereo&			omni() { return mOmni; }

	const std::string&	hostName() const { return mHostName; }

	bool				omniEnable() const { return bOmniEnable; }
	void				omniEnable(bool b) { bOmniEnable = b; }

	void initWindow(
		const Window::Dim& dims = Window::Dim(800, 400),
		const std::string title = "OmniApp",
		double fps = 60,
		Window::DisplayMode mode = Window::DEFAULT_BUF);

	void initAudio(
		double audioRate=44100, int audioBlockSize=256
	);

	void initAudio(
		std::string devicename,
    double audioRate, int audioBlockSize,
		int audioInputs, int audioOutputs
	);
	void initOmni(std::string path = "");

	void sendHandshake();
	void sendDisconnect();

	virtual bool onCreate();
	virtual bool onFrame();
	virtual void onDrawOmni(OmniStereo& omni);

	virtual std::string	vertexCode();
	virtual std::string	fragmentCode();

protected:

	AudioIO mAudioIO;
	OmniStereo mOmni;

	Lens mLens;
	Graphics mGraphics;

	ShaderProgram mShader;

	// control
	Nav mNav;
	NavInputControl mNavControl;
	StandardWindowKeyControls mStdControls;
	osc::Recv mOSCRecv;
	osc::Send mOSCSend;

	std::string mName;
	std::string mHostName;

	double mNavSpeed, mNavTurnSpeed;

	bool bOmniEnable, bSlave;

	static void AppAudioCB(AudioIOData& io);
};

// INLINE IMPLEMENTATION //

inline OmniApp::OmniApp(std::string name, bool slave)
:	mNavControl(mNav),
	mOSCRecv(PORT_FROM_DEVICE_SERVER),
	mOSCSend(PORT_TO_DEVICE_SERVER, DEVICE_SERVER_IP_ADDRESS),
	bSlave(slave)
{
	bOmniEnable = true;
	mHostName = Socket::hostName();
	mName = name;

	mNavSpeed = 1;
	mNavTurnSpeed = 0.02;

	lens().near(0.01).far(40).eyeSep(0.03);
	nav().smooth(0.8);

	Window::append(mStdControls);
	initWindow();
	initOmni();

	if (!bSlave) {
		Window::append(mNavControl);
		initAudio();

		oscRecv().bufferSize(32000);
		oscRecv().handler(*this);
		sendHandshake();
	}
}

inline OmniApp::~OmniApp() {
	if (!bSlave) sendDisconnect();
}

inline void OmniApp::initOmni(std::string path) {

	mOmni.configure(path, mHostName);
	if (mOmni.activeStereo()) {
		mOmni.mode(OmniStereo::ACTIVE).stereo(true);
	}
}

inline void OmniApp::initWindow(
	const Window::Dim& dims, const std::string title, double fps, Window::DisplayMode mode) {
	Window::dimensions(dims);
	Window::title(title);
	Window::fps(fps);
	Window::displayMode(mode);
}

inline void OmniApp::initAudio(
	double audioRate, int audioBlockSize
) {
	mAudioIO.callback = AppAudioCB;
	mAudioIO.user(this);
	mAudioIO.framesPerSecond(audioRate);
	mAudioIO.framesPerBuffer(audioBlockSize);
}

inline void OmniApp::initAudio(
	std::string devicename,
	double audioRate, int audioBlockSize,
	int audioInputs, int audioOutputs
) {
	AudioDevice indev(devicename, AudioDevice::INPUT);
	AudioDevice outdev(devicename, AudioDevice::OUTPUT);
	indev.print();
	outdev.print();
	mAudioIO.deviceIn(indev);
	mAudioIO.deviceOut(outdev);
	mAudioIO.channelsOut(audioOutputs);
	mAudioIO.channelsIn(audioInputs);
	initAudio(audioRate, audioBlockSize);
}

inline void OmniApp::sendHandshake(){
	oscSend().send("/handshake", name(), oscRecv().port());
}

inline void OmniApp::sendDisconnect(){
	oscSend().send("/disconnectApplication", name());
}

inline void OmniApp::start() {
	if (mOmni.activeStereo()) {
		Window::displayMode(Window::displayMode() | Window::STEREO_BUF);
	}

	create();

	if (mOmni.fullScreen()) {
		fullScreen(true);
		cursorHide(true);
	}

	if (!bSlave) {
		if(oscSend().opened()) sendHandshake();
		mAudioIO.start();
	}

	Main::get().start();
}

inline bool OmniApp::onCreate() {
	mOmni.onCreate();

	Shader vert, frag;
	vert.source(OmniStereo::glsl() + vertexCode(), Shader::VERTEX).compile();
	vert.printLog();
	frag.source(fragmentCode(), Shader::FRAGMENT).compile();
	frag.printLog();
	mShader.attach(vert).attach(frag).link();
	mShader.printLog();
	mShader.begin();
	mShader.uniform("lighting", 1.0);
	mShader.uniform("texture", 0.0);
	mShader.end();

	return true;
}

inline bool OmniApp::onFrame() {
	FPS::onFrame();

	while(oscRecv().recv()) {}

	nav().step();

	onAnimate(dt);

	Viewport vp(width(), height());

	if (bOmniEnable) {
		mOmni.onFrame(*this, lens(), nav(), vp);
	} else {
		mOmni.onFrameFront(*this, lens(), nav(), vp);
	}
	return true;
}

inline void OmniApp::onDrawOmni(OmniStereo& omni) {
	graphics().error("start onDraw");

	mShader.begin();
	mOmni.uniforms(mShader);

	onDraw(graphics());

	mShader.end();
}

inline void OmniApp::onMessage(osc::Message& m) {
	float x;
	if (m.addressPattern() == "/mx") {
		m >> x;
		nav().moveR(-x * mNavSpeed);

	} else if (m.addressPattern() == "/my") {
		m >> x;
		nav().moveU(x * mNavSpeed);

	} else if (m.addressPattern() == "/mz") {
		m >> x;
		nav().moveF(x * mNavSpeed);

	} else if (m.addressPattern() == "/tx") {
		m >> x;
		nav().spinR(x * -mNavTurnSpeed);

	} else if (m.addressPattern() == "/ty") {
		m >> x;
		nav().spinU(x * mNavTurnSpeed);

	} else if (m.addressPattern() == "/tz") {
		m >> x;
		nav().spinF(x * -mNavTurnSpeed);

	} else if (m.addressPattern() == "/home") {
		nav().home();

	} else if (m.addressPattern() == "/halt") {
		nav().halt();

	}
}

inline std::string	OmniApp::vertexCode() {
	return AL_STRINGIFY(
		varying vec4 color;
		varying vec3 normal, lightDir, eyeVec;

		void main(){
			color = gl_Color;
			vec4 vertex = gl_ModelViewMatrix * gl_Vertex;
			normal = gl_NormalMatrix * gl_Normal;
			vec3 V = vertex.xyz;
			eyeVec = normalize(-V);
			lightDir = normalize(vec3(gl_LightSource[0].position.xyz - V));
			gl_TexCoord[0] = gl_MultiTexCoord0;
			gl_Position = omni_render(vertex);
		}
	);
}

inline std::string OmniApp::fragmentCode() {
	return AL_STRINGIFY(
		uniform float lighting;
		uniform float texture;
		uniform sampler2D texture0;
		varying vec4 color;
		varying vec3 normal, lightDir, eyeVec;
    	void main() {

    		vec4 colorMixed;
    		if( texture > 0.0){
    			vec4 textureColor = texture2D(texture0, gl_TexCoord[0].st);
    			colorMixed = mix(color, textureColor, texture);
    		}else{
    			colorMixed = color;
    		}

			vec4 final_color = colorMixed * gl_LightSource[0].ambient;
			vec3 N = normalize(normal);
			vec3 L = lightDir;
			float lambertTerm = max(dot(N, L), 0.0);
			final_color += gl_LightSource[0].diffuse * colorMixed * lambertTerm;
			vec3 E = eyeVec;
			vec3 R = reflect(-L, N);
			float spec = pow(max(dot(R, E), 0.0), 0.9 + 1e-20);
			final_color += gl_LightSource[0].specular * spec;
			gl_FragColor = mix(colorMixed, final_color, lighting);
		}
	);
}

inline void OmniApp::AppAudioCB(AudioIOData& io){
	OmniApp& app = io.user<OmniApp>();
	io.frame(0);
	app.onSound(io);
}

}

#endif
<|endoftext|>


<commit_before>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

#include <exception>
#include <vector>
#include <string>

#include "itkImage.h"
#include "itkVectorImage.h"
#include "itkImageRegionIteratorWithIndex.h"

#include "LOCAL_antsImage.h"

namespace py = pybind11;

template< class ImageType, class VectorImageType >
py::capsule mergeChannels( std::vector<void *> imageList )
{
  typedef typename ImageType::Pointer       ImagePointerType;
  typedef typename VectorImageType::Pointer VectorImagePointerType;

  unsigned int nImages = imageList.size();

  std::vector<ImagePointerType> images;
  for ( unsigned int i=0; i<nImages; i++)
  {
    images.push_back( as<ImageType>( imageList[i] ) );
  }

  VectorImagePointerType vectorImage = VectorImageType::New();
  vectorImage->SetRegions( images[0]->GetLargestPossibleRegion() );
  vectorImage->SetSpacing( images[0]->GetSpacing() );
  vectorImage->SetOrigin( images[0]->GetOrigin() );
  vectorImage->SetDirection( images[0]->GetDirection() );
  vectorImage->SetNumberOfComponentsPerPixel( nImages );
  vectorImage->Allocate();

  // Fill image data
  itk::ImageRegionIteratorWithIndex<VectorImageType> it( vectorImage,
    vectorImage->GetLargestPossibleRegion() );

  while (!it.IsAtEnd() )
    {
    typename VectorImageType::PixelType pix;
    pix.SetSize( nImages );
    for (unsigned int i=0; i<nImages; i++)
      {
      pix[i] = images[i]->GetPixel(it.GetIndex());
      }
    vectorImage->SetPixel(it.GetIndex(), pix);
    ++it;
    }

  return wrap<VectorImageType>( vectorImage );
}

template< class ImageType, class VectorImageType >
py::capsule mergeChannels2( std::vector<py::capsule> imageList )
{
  typedef typename ImageType::Pointer       ImagePointerType;
  typedef typename VectorImageType::Pointer VectorImagePointerType;

  unsigned int nImages = imageList.size();

  std::vector<ImagePointerType> images;
  for ( unsigned int i=0; i<nImages; i++)
  {
    images.push_back( as<ImageType>( imageList[i] ) );
  }

  VectorImagePointerType vectorImage = VectorImageType::New();
  vectorImage->SetRegions( images[0]->GetLargestPossibleRegion() );
  vectorImage->SetSpacing( images[0]->GetSpacing() );
  vectorImage->SetOrigin( images[0]->GetOrigin() );
  vectorImage->SetDirection( images[0]->GetDirection() );
  vectorImage->SetNumberOfComponentsPerPixel( nImages );
  vectorImage->Allocate();

  // Fill image data
  itk::ImageRegionIteratorWithIndex<VectorImageType> it( vectorImage,
    vectorImage->GetLargestPossibleRegion() );

  while (!it.IsAtEnd() )
    {
    typename VectorImageType::PixelType pix;
    pix.SetSize( nImages );
    for (unsigned int i=0; i<nImages; i++)
      {
      pix[i] = images[i]->GetPixel(it.GetIndex());
      }
    vectorImage->SetPixel(it.GetIndex(), pix);
    ++it;
    }

  return wrap<VectorImageType>( vectorImage );
}

template< class ImageType, class VectorImageType >
py::capsule mergeChannels3( std::vector<py::capsule> imageList )
{
  typedef typename ImageType::Pointer       ImagePointerType;
  typedef typename VectorImageType::Pointer VectorImagePointerType;

  unsigned int nImages = imageList.size();

  std::vector<ImagePointerType> images;
  for ( unsigned int i=0; i<nImages; i++)
  {
    images.push_back( as<ImageType>( imageList[i] ) );
  }

  VectorImagePointerType vectorImage = VectorImageType::New();
  vectorImage->SetRegions( images[0]->GetLargestPossibleRegion() );
  vectorImage->SetSpacing( images[0]->GetSpacing() );
  vectorImage->SetOrigin( images[0]->GetOrigin() );
  vectorImage->SetDirection( images[0]->GetDirection() );
  //vectorImage->SetNumberOfComponentsPerPixel( nImages );
  vectorImage->Allocate();

  // Fill image data
  itk::ImageRegionIteratorWithIndex<VectorImageType> it( vectorImage,
    vectorImage->GetLargestPossibleRegion() );

  while (!it.IsAtEnd() )
    {

    typename VectorImageType::PixelType pix;
    //pix.SetSize( nImages );
    for (unsigned int i=0; i<nImages; i++)
      {
      pix[i] = images[i]->GetPixel(it.GetIndex());
      }
    vectorImage->SetPixel(it.GetIndex(), pix);
    ++it;
    }

  return wrap<VectorImageType>( vectorImage );
}

template< class VectorImageType, class ImageType>
std::vector<py::capsule > splitChannels( py::capsule & antsimage )
{
  typedef typename ImageType::Pointer       ImagePointerType;
  typedef typename VectorImageType::Pointer VectorImagePointerType;

  VectorImagePointerType input = as<VectorImageType>( antsimage );
  unsigned int nComponents = input->GetNumberOfComponentsPerPixel();

  // Create output images
  std::vector<ImagePointerType> images;
  for ( unsigned int i=0; i<nComponents; i++)
    {
    ImagePointerType image = ImageType::New();
    image->SetRegions( input->GetLargestPossibleRegion() );
    image->SetSpacing( input->GetSpacing() );
    image->SetOrigin( input->GetOrigin() );
    image->SetDirection( input->GetDirection() );
    image->Allocate();
    images.push_back( image );
    }

  // Fill image data
  itk::ImageRegionIteratorWithIndex<VectorImageType> it( input,
    input->GetLargestPossibleRegion() );

  while (!it.IsAtEnd() )
    {
    typename VectorImageType::PixelType pix = input->GetPixel(it.GetIndex());

    for (unsigned int i=0; i<nComponents; i++)
      {
      images[i]->SetPixel(it.GetIndex(), pix[i]);
      }
    ++it;
    }

  std::vector<py::capsule > outputList( nComponents );
  for (unsigned int i=0; i<nComponents; i++)
    {
    outputList[i] = wrap<ImageType>( images[i] );
    }

  return( outputList );

}

PYBIND11_MODULE(mergeChannels, m)
{
  m.def("mergeChannelsUC2", &mergeChannels<itk::Image<unsigned char, 2>, itk::VectorImage<unsigned char, 2> >);
  m.def("mergeChannelsUC3", &mergeChannels<itk::Image<unsigned char, 3>, itk::VectorImage<unsigned char, 3> >);
  m.def("mergeChannelsUC4", &mergeChannels<itk::Image<unsigned char, 4>, itk::VectorImage<unsigned char, 4> >);
  m.def("mergeChannelsUI2", &mergeChannels<itk::Image<unsigned int, 2>, itk::VectorImage<unsigned int, 2> >);
  m.def("mergeChannelsUI3", &mergeChannels<itk::Image<unsigned int, 3>, itk::VectorImage<unsigned int, 3> >);
  m.def("mergeChannelsUI4", &mergeChannels<itk::Image<unsigned int, 4>, itk::VectorImage<unsigned int, 4> >);
  m.def("mergeChannelsF2", &mergeChannels<itk::Image<float, 2>, itk::VectorImage<float, 2> >);
  m.def("mergeChannelsF3", &mergeChannels<itk::Image<float, 3>, itk::VectorImage<float, 3> >);
  m.def("mergeChannelsF4", &mergeChannels<itk::Image<float, 4>, itk::VectorImage<float, 4> >);

  m.def("splitChannelsVUC2", &splitChannels<itk::VectorImage<unsigned char, 2>, itk::Image<unsigned char, 2> >);
  m.def("splitChannelsVUC3", &splitChannels<itk::VectorImage<unsigned char, 3>, itk::Image<unsigned char, 3> >);
  m.def("splitChannelsVUC4", &splitChannels<itk::VectorImage<unsigned char, 4>, itk::Image<unsigned char, 4> >);
  m.def("splitChannelsVUI2", &splitChannels<itk::VectorImage<unsigned int, 2>, itk::Image<unsigned int, 2> >);
  m.def("splitChannelsVUI3", &splitChannels<itk::VectorImage<unsigned int, 3>, itk::Image<unsigned int, 3> >);
  m.def("splitChannelsVUI4", &splitChannels<itk::VectorImage<unsigned int, 4>, itk::Image<unsigned int, 4> >);
  m.def("splitChannelsVF2", &splitChannels<itk::VectorImage<float, 2>, itk::Image<float, 2> >);
  m.def("splitChannelsVF3", &splitChannels<itk::VectorImage<float, 3>, itk::Image<float, 3> >);
  m.def("splitChannelsVF4", &splitChannels<itk::VectorImage<float, 4>, itk::Image<float, 4> >);
  m.def("splitChannelsRGBF2", &splitChannels<  itk::Image<itk::RGBPixel<unsigned char>, 2>, itk::Image<float, 2> >);

}
<commit_msg>BUG: type<commit_after>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

#include <exception>
#include <vector>
#include <string>

#include "itkImage.h"
#include "itkVectorImage.h"
#include "itkImageRegionIteratorWithIndex.h"

#include "LOCAL_antsImage.h"

namespace py = pybind11;

template< class ImageType, class VectorImageType >
py::capsule mergeChannels( std::vector<void *> imageList )
{
  typedef typename ImageType::Pointer       ImagePointerType;
  typedef typename VectorImageType::Pointer VectorImagePointerType;

  unsigned int nImages = imageList.size();

  std::vector<ImagePointerType> images;
  for ( unsigned int i=0; i<nImages; i++)
  {
    images.push_back( as<ImageType>( imageList[i] ) );
  }

  VectorImagePointerType vectorImage = VectorImageType::New();
  vectorImage->SetRegions( images[0]->GetLargestPossibleRegion() );
  vectorImage->SetSpacing( images[0]->GetSpacing() );
  vectorImage->SetOrigin( images[0]->GetOrigin() );
  vectorImage->SetDirection( images[0]->GetDirection() );
  vectorImage->SetNumberOfComponentsPerPixel( nImages );
  vectorImage->Allocate();

  // Fill image data
  itk::ImageRegionIteratorWithIndex<VectorImageType> it( vectorImage,
    vectorImage->GetLargestPossibleRegion() );

  while (!it.IsAtEnd() )
    {
    typename VectorImageType::PixelType pix;
    pix.SetSize( nImages );
    for (unsigned int i=0; i<nImages; i++)
      {
      pix[i] = images[i]->GetPixel(it.GetIndex());
      }
    vectorImage->SetPixel(it.GetIndex(), pix);
    ++it;
    }

  return wrap<VectorImageType>( vectorImage );
}

template< class ImageType, class VectorImageType >
py::capsule mergeChannels2( std::vector<py::capsule> imageList )
{
  typedef typename ImageType::Pointer       ImagePointerType;
  typedef typename VectorImageType::Pointer VectorImagePointerType;

  unsigned int nImages = imageList.size();

  std::vector<ImagePointerType> images;
  for ( unsigned int i=0; i<nImages; i++)
  {
    images.push_back( as<ImageType>( imageList[i] ) );
  }

  VectorImagePointerType vectorImage = VectorImageType::New();
  vectorImage->SetRegions( images[0]->GetLargestPossibleRegion() );
  vectorImage->SetSpacing( images[0]->GetSpacing() );
  vectorImage->SetOrigin( images[0]->GetOrigin() );
  vectorImage->SetDirection( images[0]->GetDirection() );
  vectorImage->SetNumberOfComponentsPerPixel( nImages );
  vectorImage->Allocate();

  // Fill image data
  itk::ImageRegionIteratorWithIndex<VectorImageType> it( vectorImage,
    vectorImage->GetLargestPossibleRegion() );

  while (!it.IsAtEnd() )
    {
    typename VectorImageType::PixelType pix;
    pix.SetSize( nImages );
    for (unsigned int i=0; i<nImages; i++)
      {
      pix[i] = images[i]->GetPixel(it.GetIndex());
      }
    vectorImage->SetPixel(it.GetIndex(), pix);
    ++it;
    }

  return wrap<VectorImageType>( vectorImage );
}

template< class ImageType, class VectorImageType >
py::capsule mergeChannels3( std::vector<py::capsule> imageList )
{
  typedef typename ImageType::Pointer       ImagePointerType;
  typedef typename VectorImageType::Pointer VectorImagePointerType;

  unsigned int nImages = imageList.size();

  std::vector<ImagePointerType> images;
  for ( unsigned int i=0; i<nImages; i++)
  {
    images.push_back( as<ImageType>( imageList[i] ) );
  }

  VectorImagePointerType vectorImage = VectorImageType::New();
  vectorImage->SetRegions( images[0]->GetLargestPossibleRegion() );
  vectorImage->SetSpacing( images[0]->GetSpacing() );
  vectorImage->SetOrigin( images[0]->GetOrigin() );
  vectorImage->SetDirection( images[0]->GetDirection() );
  //vectorImage->SetNumberOfComponentsPerPixel( nImages );
  vectorImage->Allocate();

  // Fill image data
  itk::ImageRegionIteratorWithIndex<VectorImageType> it( vectorImage,
    vectorImage->GetLargestPossibleRegion() );

  while (!it.IsAtEnd() )
    {

    typename VectorImageType::PixelType pix;
    //pix.SetSize( nImages );
    for (unsigned int i=0; i<nImages; i++)
      {
      pix[i] = images[i]->GetPixel(it.GetIndex());
      }
    vectorImage->SetPixel(it.GetIndex(), pix);
    ++it;
    }

  return wrap<VectorImageType>( vectorImage );
}

template< class VectorImageType, class ImageType>
std::vector<py::capsule > splitChannels( py::capsule & antsimage )
{
  typedef typename ImageType::Pointer       ImagePointerType;
  typedef typename VectorImageType::Pointer VectorImagePointerType;

  VectorImagePointerType input = as<VectorImageType>( antsimage );
  unsigned int nComponents = input->GetNumberOfComponentsPerPixel();

  // Create output images
  std::vector<ImagePointerType> images;
  for ( unsigned int i=0; i<nComponents; i++)
    {
    ImagePointerType image = ImageType::New();
    image->SetRegions( input->GetLargestPossibleRegion() );
    image->SetSpacing( input->GetSpacing() );
    image->SetOrigin( input->GetOrigin() );
    image->SetDirection( input->GetDirection() );
    image->Allocate();
    images.push_back( image );
    }

  // Fill image data
  itk::ImageRegionIteratorWithIndex<VectorImageType> it( input,
    input->GetLargestPossibleRegion() );

  while (!it.IsAtEnd() )
    {
    typename VectorImageType::PixelType pix = input->GetPixel(it.GetIndex());

    for (unsigned int i=0; i<nComponents; i++)
      {
      images[i]->SetPixel(it.GetIndex(), pix[i]);
      }
    ++it;
    }

  std::vector<py::capsule > outputList( nComponents );
  for (unsigned int i=0; i<nComponents; i++)
    {
    outputList[i] = wrap<ImageType>( images[i] );
    }

  return( outputList );

}

PYBIND11_MODULE(mergeChannels, m)
{
  m.def("mergeChannelsUC2", &mergeChannels<itk::Image<unsigned char, 2>, itk::VectorImage<unsigned char, 2> >);
  m.def("mergeChannelsUC3", &mergeChannels<itk::Image<unsigned char, 3>, itk::VectorImage<unsigned char, 3> >);
  m.def("mergeChannelsUC4", &mergeChannels<itk::Image<unsigned char, 4>, itk::VectorImage<unsigned char, 4> >);
  m.def("mergeChannelsUI2", &mergeChannels<itk::Image<unsigned int, 2>, itk::VectorImage<unsigned int, 2> >);
  m.def("mergeChannelsUI3", &mergeChannels<itk::Image<unsigned int, 3>, itk::VectorImage<unsigned int, 3> >);
  m.def("mergeChannelsUI4", &mergeChannels<itk::Image<unsigned int, 4>, itk::VectorImage<unsigned int, 4> >);
  m.def("mergeChannelsF2", &mergeChannels<itk::Image<float, 2>, itk::VectorImage<float, 2> >);
  m.def("mergeChannelsF3", &mergeChannels<itk::Image<float, 3>, itk::VectorImage<float, 3> >);
  m.def("mergeChannelsF4", &mergeChannels<itk::Image<float, 4>, itk::VectorImage<float, 4> >);

  m.def("splitChannelsVUC2", &splitChannels<itk::VectorImage<unsigned char, 2>, itk::Image<unsigned char, 2> >);
  m.def("splitChannelsVUC3", &splitChannels<itk::VectorImage<unsigned char, 3>, itk::Image<unsigned char, 3> >);
  m.def("splitChannelsVUC4", &splitChannels<itk::VectorImage<unsigned char, 4>, itk::Image<unsigned char, 4> >);
  m.def("splitChannelsVUI2", &splitChannels<itk::VectorImage<unsigned int, 2>, itk::Image<unsigned int, 2> >);
  m.def("splitChannelsVUI3", &splitChannels<itk::VectorImage<unsigned int, 3>, itk::Image<unsigned int, 3> >);
  m.def("splitChannelsVUI4", &splitChannels<itk::VectorImage<unsigned int, 4>, itk::Image<unsigned int, 4> >);
  m.def("splitChannelsVF2", &splitChannels<itk::VectorImage<float, 2>, itk::Image<float, 2> >);
  m.def("splitChannelsVF3", &splitChannels<itk::VectorImage<float, 3>, itk::Image<float, 3> >);
  m.def("splitChannelsVF4", &splitChannels<itk::VectorImage<float, 4>, itk::Image<float, 4> >);
  m.def("splitChannelsRGBF2", &splitChannels<  itk::Image<itk::RGBPixel<unsigned char>, 2>, itk::Image<unsigned char, 2> >);

}
<|endoftext|>


<commit_before><commit_msg>libTidyEngine: Undo the last commit<commit_after><|endoftext|>


<commit_before>/*
 * This file is part of TelepathyQt4
 *
 * Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2009 Nokia Corporation
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "sender.h"
#include "_gen/sender.moc.hpp"

#include <TelepathyQt4/Debug>
#include <TelepathyQt4/Connection>
#include <TelepathyQt4/ConnectionManager>
#include <TelepathyQt4/Constants>
#include <TelepathyQt4/ContactManager>
#include <TelepathyQt4/FileTransferChannel>
#include <TelepathyQt4/OutgoingFileTransferChannel>
#include <TelepathyQt4/PendingChannel>
#include <TelepathyQt4/PendingConnection>
#include <TelepathyQt4/PendingContacts>
#include <TelepathyQt4/PendingOperation>
#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4/Presence>

#include <QDebug>
#include <QFile>
#include <QFileInfo>

Sender::Sender(const QString &username, const QString &password,
        const QString &receiver, const QString &fileName)
    : mUsername(username),
      mPassword(password),
      mReceiver(receiver),
      mFileName(fileName),
      mTransferStarted(false),
      mCompleted(false)
{
    mFile.setFileName(mFileName);
    if (!mFile.open(QIODevice::ReadOnly)) {
        qWarning() << "Unable to open file for reading";
        return;
    }

    mCM = ConnectionManager::create(QLatin1String("gabble"));
    connect(mCM->becomeReady(),
            SIGNAL(finished(Tp::PendingOperation *)),
            SLOT(onCMReady(Tp::PendingOperation *)));
}

Sender::~Sender()
{
    mFile.close();
}

void Sender::onCMReady(PendingOperation *op)
{
    if (op->isError()) {
        qWarning() << "CM cannot become ready -" <<
            op->errorName() << ": " << op->errorMessage();
        return;
    }

    qDebug() << "CM ready!";

    qDebug() << "Creating connection...";
    QVariantMap params;
    params.insert(QLatin1String("account"), QVariant(mUsername));
    params.insert(QLatin1String("password"), QVariant(mPassword));
    PendingConnection *pconn = mCM->requestConnection(QLatin1String("jabber"),
            params);
    connect(pconn,
            SIGNAL(finished(Tp::PendingOperation *)),
            SLOT(onConnectionCreated(Tp::PendingOperation *)));
}

void Sender::onConnectionCreated(PendingOperation *op)
{
    if (op->isError()) {
        qWarning() << "Unable to create connection -" <<
            op->errorName() << ": " << op->errorMessage();
        return;
    }

    qDebug() << "Connection ready!";

    qDebug() << "Connecting...";
    PendingConnection *pconn =
        qobject_cast<PendingConnection *>(op);
    mConn = pconn->connection();
    connect(mConn->requestConnect(),
            SIGNAL(finished(Tp::PendingOperation *)),
            SLOT(onConnectionConnected(Tp::PendingOperation *)));
    connect(mConn.data(),
            SIGNAL(invalidated(Tp::DBusProxy *, const QString &, const QString &)),
            SLOT(onInvalidated()));
}

void Sender::onConnectionConnected(PendingOperation *op)
{
    if (op->isError()) {
        qWarning() << "Connection cannot become connected -" <<
            op->errorName() << ": " << op->errorMessage();
        return;
    }

    qDebug() << "Connected!";

    qDebug() << "Creating contact object for receiver" << mReceiver;
    connect(mConn->contactManager()->contactsForIdentifiers(QStringList() << mReceiver,
                QSet<Contact::Feature>() << Contact::FeatureSimplePresence),
            SIGNAL(finished(Tp::PendingOperation *)),
            SLOT(onContactRetrieved(Tp::PendingOperation *)));
}

void Sender::onContactRetrieved(PendingOperation *op)
{
    if (op->isError()) {
        qWarning() << "Unable to create contact object for receiver" <<
            mReceiver << "-" << op->errorName() << ": " << op->errorMessage();
        return;
    }

    PendingContacts *pc = qobject_cast<PendingContacts *>(op);
    Q_ASSERT(pc->contacts().size() == 1);
    mContact = pc->contacts().first();

    qDebug() << "Checking contact presence...";
    connect(mContact.data(),
            SIGNAL(simplePresenceChanged(const QString &, uint, const QString &)),
            SLOT(onContactPresenceChanged()));
    onContactPresenceChanged();
}

void Sender::onContactPresenceChanged()
{
    if (mTransferStarted) {
        return;
    }

    if (mContact->presence().type() != ConnectionPresenceTypeUnset &&
        mContact->presence().type() != ConnectionPresenceTypeOffline &&
        mContact->presence().type() != ConnectionPresenceTypeUnknown &&
        mContact->presence().type() != ConnectionPresenceTypeError) {
        qDebug() << "Contact online!";

        // FIXME this is a workaround as we don't support contact capabilities yet
        sleep(5);
        createFileTransferChannel();

        /*
        connect(mConn->capabilitiesInterface(),
                SIGNAL(CapabilitiesChanged(const Tp::CapabilityChangeList &)),
                SLOT(onCapabilitiesChanged(const Tp::CapabilityChangeList &)));
        QDBusPendingCallWatcher *watcher =
            new QDBusPendingCallWatcher(
                    mConn->capabilitiesInterface()->GetCapabilities(
                        UIntList() << mContact->handle()[0]),
                    mConn.data());
        connect(watcher,
                SIGNAL(finished(QDBusPendingCallWatcher *)),
                SLOT(gotContactCapabilities(QDBusPendingCallWatcher *)));
        */
    }
}

/*
void Sender::onCapabilitiesChanged(const CapabilityChangeList &caps)
{
    if (mTransferStarted) {
        return;
    }

    qDebug() << "Capabilities changed";
    foreach (const CapabilityChange &cap, caps) {
        qDebug() << "Checking cap channel type" << cap.channelType;
        if (cap.handle == mContact->handle()[0] &&
            cap.channelType == TELEPATHY_INTERFACE_CHANNEL_TYPE_FILE_TRANSFER) {
            qDebug() << "Contact supports file transfer!";
            createFileTransferChannel();
            break;
        }
    }
}

void Sender::gotContactCapabilities(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<ContactCapabilityList> reply = *watcher;

    if (reply.isError()) {
        qWarning() << "Unable to get contact capabilities, trying "
            "anyway -" << reply.error().name() << ":" <<
            reply.error().message();
        createFileTransferChannel();
    } else {
        ContactCapabilityList caps = reply.value();
        qDebug() << "Got contact capabilities";
        foreach (const ContactCapability &cap, caps) {
            // no need to check the handle, as we only requested the caps for
            // one contact
            qDebug() << "Checking cap channel type" << cap.channelType;
            if (cap.channelType == TELEPATHY_INTERFACE_CHANNEL_TYPE_FILE_TRANSFER) {
                qDebug() << "Contact supports file transfer!";
                createFileTransferChannel();
                break;
            }
        }
    }
}
*/

void Sender::createFileTransferChannel()
{
    mTransferStarted = true;

    QFileInfo fileInfo(mFileName);
    qDebug() << "Creating file transfer channel...";
    QVariantMap request;
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"),
                   QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_FILE_TRANSFER));
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"),
                   (uint) Tp::HandleTypeContact);
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle"),
                   mContact->handle()[0]);
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_FILE_TRANSFER ".Filename"),
                   fileInfo.fileName());
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_FILE_TRANSFER ".Size"),
                   (qulonglong) fileInfo.size());
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_FILE_TRANSFER ".ContentType"),
                   QLatin1String("application/octet-stream"));
    qDebug() << "Request:" << request;
    connect(mConn->createChannel(request),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onFileTransferChannelCreated(Tp::PendingOperation*)));
}

void Sender::onFileTransferChannelCreated(PendingOperation *op)
{
    if (op->isError()) {
        qWarning() << "Unable to create file transfer channel -" <<
            op->errorName() << ": " << op->errorMessage();
        return;
    }

    qDebug() << "File transfer channel created!";
    PendingChannel *pc = qobject_cast<PendingChannel*>(op);
    mChan = OutgoingFileTransferChannelPtr::qObjectCast(pc->channel());
    connect(mChan.data(),
            SIGNAL(invalidated(Tp::DBusProxy *, const QString &, const QString &)),
            SLOT(onInvalidated()));
    connect(mChan->becomeReady(FileTransferChannel::FeatureCore),
            SIGNAL(finished(Tp::PendingOperation *)),
            SLOT(onFileTransferChannelReady(Tp::PendingOperation *)));
}

void Sender::onFileTransferChannelReady(PendingOperation *op)
{
    if (op->isError()) {
        qWarning() << "Unable to make file transfer channel ready -" <<
            op->errorName() << ": " << op->errorMessage();
        return;
    }

    qDebug() << "File transfer channel ready!";
    connect(mChan.data(),
            SIGNAL(stateChanged(Tp::FileTransferState, Tp::FileTransferStateChangeReason)),
            SLOT(onFileTransferChannelStateChanged(Tp::FileTransferState, Tp::FileTransferStateChangeReason)));
    connect(mChan.data(),
            SIGNAL(transferredBytesChanged(qulonglong)),
            SLOT(onFileTransferChannelTransferredBytesChanged(qulonglong)));
    mChan->provideFile(&mFile);
}

void Sender::onFileTransferChannelStateChanged(Tp::FileTransferState state,
    Tp::FileTransferStateChangeReason stateReason)
{
    qDebug() << "File transfer channel state changed to" << state <<
        "with reason" << stateReason;
    mCompleted = (state == FileTransferStateCompleted);
    if (mCompleted) {
        qDebug() << "Transfer completed!";
        QCoreApplication::exit(0);
    }
}

void Sender::onFileTransferChannelTransferredBytesChanged(qulonglong count)
{
    qDebug().nospace() << "Tranferred bytes " << count << " - " <<
        ((int) (((double) count / mChan->size()) * 100)) << "% done";
}

void Sender::onInvalidated()
{
    QCoreApplication::exit(!mCompleted);
}

int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);

    if (argc < 5) {
        qDebug() << "usage: sender username password receiver filename";
        return 1;
    }

    Tp::registerTypes();
    Tp::enableDebug(true);

    new Sender(QLatin1String(argv[1]), QLatin1String(argv[2]),
            QLatin1String(argv[3]), QLatin1String(argv[4]));

    return app.exec();
}
<commit_msg>file-transfer sender example: Properly build with contact changes.<commit_after>/*
 * This file is part of TelepathyQt4
 *
 * Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2009 Nokia Corporation
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "sender.h"
#include "_gen/sender.moc.hpp"

#include <TelepathyQt4/Debug>
#include <TelepathyQt4/Connection>
#include <TelepathyQt4/ConnectionManager>
#include <TelepathyQt4/Constants>
#include <TelepathyQt4/ContactManager>
#include <TelepathyQt4/FileTransferChannel>
#include <TelepathyQt4/OutgoingFileTransferChannel>
#include <TelepathyQt4/PendingChannel>
#include <TelepathyQt4/PendingConnection>
#include <TelepathyQt4/PendingContacts>
#include <TelepathyQt4/PendingOperation>
#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4/Presence>

#include <QDebug>
#include <QFile>
#include <QFileInfo>

Sender::Sender(const QString &username, const QString &password,
        const QString &receiver, const QString &fileName)
    : mUsername(username),
      mPassword(password),
      mReceiver(receiver),
      mFileName(fileName),
      mTransferStarted(false),
      mCompleted(false)
{
    mFile.setFileName(mFileName);
    if (!mFile.open(QIODevice::ReadOnly)) {
        qWarning() << "Unable to open file for reading";
        return;
    }

    mCM = ConnectionManager::create(QLatin1String("gabble"));
    connect(mCM->becomeReady(),
            SIGNAL(finished(Tp::PendingOperation *)),
            SLOT(onCMReady(Tp::PendingOperation *)));
}

Sender::~Sender()
{
    mFile.close();
}

void Sender::onCMReady(PendingOperation *op)
{
    if (op->isError()) {
        qWarning() << "CM cannot become ready -" <<
            op->errorName() << ": " << op->errorMessage();
        return;
    }

    qDebug() << "CM ready!";

    qDebug() << "Creating connection...";
    QVariantMap params;
    params.insert(QLatin1String("account"), QVariant(mUsername));
    params.insert(QLatin1String("password"), QVariant(mPassword));
    PendingConnection *pconn = mCM->requestConnection(QLatin1String("jabber"),
            params);
    connect(pconn,
            SIGNAL(finished(Tp::PendingOperation *)),
            SLOT(onConnectionCreated(Tp::PendingOperation *)));
}

void Sender::onConnectionCreated(PendingOperation *op)
{
    if (op->isError()) {
        qWarning() << "Unable to create connection -" <<
            op->errorName() << ": " << op->errorMessage();
        return;
    }

    qDebug() << "Connection ready!";

    qDebug() << "Connecting...";
    PendingConnection *pconn =
        qobject_cast<PendingConnection *>(op);
    mConn = pconn->connection();
    connect(mConn->requestConnect(),
            SIGNAL(finished(Tp::PendingOperation *)),
            SLOT(onConnectionConnected(Tp::PendingOperation *)));
    connect(mConn.data(),
            SIGNAL(invalidated(Tp::DBusProxy *, const QString &, const QString &)),
            SLOT(onInvalidated()));
}

void Sender::onConnectionConnected(PendingOperation *op)
{
    if (op->isError()) {
        qWarning() << "Connection cannot become connected -" <<
            op->errorName() << ": " << op->errorMessage();
        return;
    }

    qDebug() << "Connected!";

    qDebug() << "Creating contact object for receiver" << mReceiver;
    connect(mConn->contactManager()->contactsForIdentifiers(QStringList() << mReceiver,
                Features() << Contact::FeatureSimplePresence),
            SIGNAL(finished(Tp::PendingOperation *)),
            SLOT(onContactRetrieved(Tp::PendingOperation *)));
}

void Sender::onContactRetrieved(PendingOperation *op)
{
    if (op->isError()) {
        qWarning() << "Unable to create contact object for receiver" <<
            mReceiver << "-" << op->errorName() << ": " << op->errorMessage();
        return;
    }

    PendingContacts *pc = qobject_cast<PendingContacts *>(op);
    Q_ASSERT(pc->contacts().size() == 1);
    mContact = pc->contacts().first();

    qDebug() << "Checking contact presence...";
    connect(mContact.data(),
            SIGNAL(simplePresenceChanged(const QString &, uint, const QString &)),
            SLOT(onContactPresenceChanged()));
    onContactPresenceChanged();
}

void Sender::onContactPresenceChanged()
{
    if (mTransferStarted) {
        return;
    }

    if (mContact->presence().type() != ConnectionPresenceTypeUnset &&
        mContact->presence().type() != ConnectionPresenceTypeOffline &&
        mContact->presence().type() != ConnectionPresenceTypeUnknown &&
        mContact->presence().type() != ConnectionPresenceTypeError) {
        qDebug() << "Contact online!";

        // FIXME this is a workaround as we don't support contact capabilities yet
        sleep(5);
        createFileTransferChannel();

        /*
        connect(mConn->capabilitiesInterface(),
                SIGNAL(CapabilitiesChanged(const Tp::CapabilityChangeList &)),
                SLOT(onCapabilitiesChanged(const Tp::CapabilityChangeList &)));
        QDBusPendingCallWatcher *watcher =
            new QDBusPendingCallWatcher(
                    mConn->capabilitiesInterface()->GetCapabilities(
                        UIntList() << mContact->handle()[0]),
                    mConn.data());
        connect(watcher,
                SIGNAL(finished(QDBusPendingCallWatcher *)),
                SLOT(gotContactCapabilities(QDBusPendingCallWatcher *)));
        */
    }
}

/*
void Sender::onCapabilitiesChanged(const CapabilityChangeList &caps)
{
    if (mTransferStarted) {
        return;
    }

    qDebug() << "Capabilities changed";
    foreach (const CapabilityChange &cap, caps) {
        qDebug() << "Checking cap channel type" << cap.channelType;
        if (cap.handle == mContact->handle()[0] &&
            cap.channelType == TELEPATHY_INTERFACE_CHANNEL_TYPE_FILE_TRANSFER) {
            qDebug() << "Contact supports file transfer!";
            createFileTransferChannel();
            break;
        }
    }
}

void Sender::gotContactCapabilities(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<ContactCapabilityList> reply = *watcher;

    if (reply.isError()) {
        qWarning() << "Unable to get contact capabilities, trying "
            "anyway -" << reply.error().name() << ":" <<
            reply.error().message();
        createFileTransferChannel();
    } else {
        ContactCapabilityList caps = reply.value();
        qDebug() << "Got contact capabilities";
        foreach (const ContactCapability &cap, caps) {
            // no need to check the handle, as we only requested the caps for
            // one contact
            qDebug() << "Checking cap channel type" << cap.channelType;
            if (cap.channelType == TELEPATHY_INTERFACE_CHANNEL_TYPE_FILE_TRANSFER) {
                qDebug() << "Contact supports file transfer!";
                createFileTransferChannel();
                break;
            }
        }
    }
}
*/

void Sender::createFileTransferChannel()
{
    mTransferStarted = true;

    QFileInfo fileInfo(mFileName);
    qDebug() << "Creating file transfer channel...";
    QVariantMap request;
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"),
                   QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_FILE_TRANSFER));
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"),
                   (uint) Tp::HandleTypeContact);
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle"),
                   mContact->handle()[0]);
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_FILE_TRANSFER ".Filename"),
                   fileInfo.fileName());
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_FILE_TRANSFER ".Size"),
                   (qulonglong) fileInfo.size());
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_FILE_TRANSFER ".ContentType"),
                   QLatin1String("application/octet-stream"));
    qDebug() << "Request:" << request;
    connect(mConn->createChannel(request),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onFileTransferChannelCreated(Tp::PendingOperation*)));
}

void Sender::onFileTransferChannelCreated(PendingOperation *op)
{
    if (op->isError()) {
        qWarning() << "Unable to create file transfer channel -" <<
            op->errorName() << ": " << op->errorMessage();
        return;
    }

    qDebug() << "File transfer channel created!";
    PendingChannel *pc = qobject_cast<PendingChannel*>(op);
    mChan = OutgoingFileTransferChannelPtr::qObjectCast(pc->channel());
    connect(mChan.data(),
            SIGNAL(invalidated(Tp::DBusProxy *, const QString &, const QString &)),
            SLOT(onInvalidated()));
    connect(mChan->becomeReady(FileTransferChannel::FeatureCore),
            SIGNAL(finished(Tp::PendingOperation *)),
            SLOT(onFileTransferChannelReady(Tp::PendingOperation *)));
}

void Sender::onFileTransferChannelReady(PendingOperation *op)
{
    if (op->isError()) {
        qWarning() << "Unable to make file transfer channel ready -" <<
            op->errorName() << ": " << op->errorMessage();
        return;
    }

    qDebug() << "File transfer channel ready!";
    connect(mChan.data(),
            SIGNAL(stateChanged(Tp::FileTransferState, Tp::FileTransferStateChangeReason)),
            SLOT(onFileTransferChannelStateChanged(Tp::FileTransferState, Tp::FileTransferStateChangeReason)));
    connect(mChan.data(),
            SIGNAL(transferredBytesChanged(qulonglong)),
            SLOT(onFileTransferChannelTransferredBytesChanged(qulonglong)));
    mChan->provideFile(&mFile);
}

void Sender::onFileTransferChannelStateChanged(Tp::FileTransferState state,
    Tp::FileTransferStateChangeReason stateReason)
{
    qDebug() << "File transfer channel state changed to" << state <<
        "with reason" << stateReason;
    mCompleted = (state == FileTransferStateCompleted);
    if (mCompleted) {
        qDebug() << "Transfer completed!";
        QCoreApplication::exit(0);
    }
}

void Sender::onFileTransferChannelTransferredBytesChanged(qulonglong count)
{
    qDebug().nospace() << "Tranferred bytes " << count << " - " <<
        ((int) (((double) count / mChan->size()) * 100)) << "% done";
}

void Sender::onInvalidated()
{
    QCoreApplication::exit(!mCompleted);
}

int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);

    if (argc < 5) {
        qDebug() << "usage: sender username password receiver filename";
        return 1;
    }

    Tp::registerTypes();
    Tp::enableDebug(true);

    new Sender(QLatin1String(argv[1]), QLatin1String(argv[2]),
            QLatin1String(argv[3]), QLatin1String(argv[4]));

    return app.exec();
}
<|endoftext|>


<commit_before>/*
 * Fadecandy Firmware - USB Support
 *
 * Copyright (c) 2013 Micah Elizabeth Scott
 *
 * 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 "fc_usb.h"
#include <algorithm>

// USB protocol definitions

#define TYPE_BITS           0xC0
#define FINAL_BIT           0x20
#define INDEX_BITS          0x1F

#define TYPE_FRAMEBUFFER    0x00
#define TYPE_LUT            0x40
#define TYPE_CONFIG         0x80

void fcBuffers::handleUSB()
{
    /*
     * Look for incoming USB packets, and file them appropriately.
     * Our framebuffer and LUT buffers are arrays of references to USB packets
     * which we hold until a new packet arrives to replace them.
     */

    bool handledAnyPackets = false;

    while (1) {
        usb_packet_t *packet = usb_rx(FC_OUT_ENDPOINT);
        if (!packet) {
            break;
        }
        handledAnyPackets = true;

        unsigned control = packet->buf[0];
        unsigned type = control & TYPE_BITS;
        unsigned final = control & FINAL_BIT;
        unsigned index = control & INDEX_BITS;

        switch (type) {

            case TYPE_FRAMEBUFFER:
                fbNew->store(index, packet);
                if (final) {
                    finalizeFramebuffer();
                }
                break;

            case TYPE_LUT:
                lutNew.store(index, packet);
                if (final) {
                    finalizeLUT();
                }
                break;

            case TYPE_CONFIG:
                flags = packet->buf[1];
                usb_free(packet);
                break;

            default:
                usb_free(packet);
                break;
        }
    }

    if (flags & CFLAG_NO_ACTIVITY_LED) {
        // LED under manual control
        digitalWrite(LED_BUILTIN, flags & CFLAG_LED_CONTROL);
    } else {
        // Use the built-in LED as a USB activity indicator.
        digitalWrite(LED_BUILTIN, handledAnyPackets);
    }
}

void fcBuffers::finalizeFramebuffer()
{
    fcFramebuffer *recycle = fbPrev;
    fbNew->timestamp = millis();
    fbPrev = fbNext;
    fbNext = fbNew;
    fbNew = recycle;
}

void fcBuffers::finalizeLUT()
{
    /*
     * To keep LUT lookups super-fast, we copy the LUT into a linear array at this point.
     * LUT changes are intended to be infrequent (initialization or configuration-time only),
     * so this isn't a performance bottleneck.
     */

    for (unsigned i = 0; i < LUT_TOTAL_SIZE; ++i) {
        lutCurrent[i] = lutNew.entry(i);
    }
}
<commit_msg>Use digitalWriteFast() for LED control<commit_after>/*
 * Fadecandy Firmware - USB Support
 *
 * Copyright (c) 2013 Micah Elizabeth Scott
 *
 * 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 "fc_usb.h"
#include <algorithm>

// USB protocol definitions

#define TYPE_BITS           0xC0
#define FINAL_BIT           0x20
#define INDEX_BITS          0x1F

#define TYPE_FRAMEBUFFER    0x00
#define TYPE_LUT            0x40
#define TYPE_CONFIG         0x80

void fcBuffers::handleUSB()
{
    /*
     * Look for incoming USB packets, and file them appropriately.
     * Our framebuffer and LUT buffers are arrays of references to USB packets
     * which we hold until a new packet arrives to replace them.
     */

    bool handledAnyPackets = false;

    while (1) {
        usb_packet_t *packet = usb_rx(FC_OUT_ENDPOINT);
        if (!packet) {
            break;
        }
        handledAnyPackets = true;

        unsigned control = packet->buf[0];
        unsigned type = control & TYPE_BITS;
        unsigned final = control & FINAL_BIT;
        unsigned index = control & INDEX_BITS;

        switch (type) {

            case TYPE_FRAMEBUFFER:
                fbNew->store(index, packet);
                if (final) {
                    finalizeFramebuffer();
                }
                break;

            case TYPE_LUT:
                lutNew.store(index, packet);
                if (final) {
                    finalizeLUT();
                }
                break;

            case TYPE_CONFIG:
                flags = packet->buf[1];
                usb_free(packet);
                break;

            default:
                usb_free(packet);
                break;
        }
    }

    if (flags & CFLAG_NO_ACTIVITY_LED) {
        // LED under manual control
        digitalWriteFast(LED_BUILTIN, flags & CFLAG_LED_CONTROL);
    } else {
        // Use the built-in LED as a USB activity indicator.
        digitalWriteFast(LED_BUILTIN, handledAnyPackets);
    }
}

void fcBuffers::finalizeFramebuffer()
{
    fcFramebuffer *recycle = fbPrev;
    fbNew->timestamp = millis();
    fbPrev = fbNext;
    fbNext = fbNew;
    fbNew = recycle;
}

void fcBuffers::finalizeLUT()
{
    /*
     * To keep LUT lookups super-fast, we copy the LUT into a linear array at this point.
     * LUT changes are intended to be infrequent (initialization or configuration-time only),
     * so this isn't a performance bottleneck.
     */

    for (unsigned i = 0; i < LUT_TOTAL_SIZE; ++i) {
        lutCurrent[i] = lutNew.entry(i);
    }
}
<|endoftext|>


<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */

#include <gecode/driver.hh>
#include <gecode/int.hh>
#include <gecode/minimodel.hh>

using namespace Gecode;

//
// g++ -g simple_dependency.cpp -lgecodesupport -lgecodekernel -lgecodeint -lgecodesearch -lgecodedriver -lpthread -ldl   -lstdc++ -o simple_dependency
//

class SimpleDependency : public MinimizeScript {
protected:
  static const int PKG_COUNT = 11;

  IntVarArray package_versions;
  IntArgs disabled_package_weights;
  BoolVarArray disabled_package_variables;
  IntVar total_disabled;
public:
  /// Actual model
  SimpleDependency(const Options& opt) :
    package_versions(*this, PKG_COUNT, -1, 10),
    disabled_package_variables(*this, PKG_COUNT, 0, 1),
    total_disabled(*this, 0, 10*PKG_COUNT)
  {
    Problem1();

    branch(*this, package_versions, INT_VAR_SIZE_MIN, INT_VAL_MAX);
    branch(*this, disabled_package_variables, INT_VAR_SIZE_MIN, INT_VAL_MIN);
    branch(*this, total_disabled, INT_VAL_MIN);
  }

  void Problem1() {
    std::cout << "Setting up " << __FUNCTION__ << std::endl;
    // Add version constraints for pkg 0
    dom(*this, package_versions[0], -1, 0);
    dom(*this, package_versions[1], -1, 0);
    dom(*this, package_versions[2], -1, 0);
    dom(*this, package_versions[3], -1, 1);
    dom(*this, package_versions[4], -1, 0);
    dom(*this, package_versions[5], -1, 0);
    dom(*this, package_versions[6], -1, 2);
    dom(*this, package_versions[7], -1, 0);
    dom(*this, package_versions[8], -1, 0);
    dom(*this, package_versions[9], -1, -1);
    dom(*this, package_versions[10], 0, 0);

    AddVersionConstraint(0, 0, 1, 0, 1);
    AddVersionConstraint(2, 0, 1, 0, 0);
    AddVersionConstraint(1, 0, 3, 0, 1);
    AddVersionConstraint(1, 0, 4, 0, 0);
    AddVersionConstraint(1, 1, 3, 1, 1);
    AddVersionConstraint(1, 1, 5, 0, 0);
    AddVersionConstraint(7, 0, 3, -2, -2);
    AddVersionConstraint(8, 0, 9, -2, -2);
    AddVersionConstraint(10, 0, 7, 0, 0);

    IntArgs package_weights(PKG_COUNT, 10, 10, 10, 10, 10,  10, 10, 10, 10, 10 );

    std::cout << "Package versions:           " << package_versions << std::endl;
    std::cout << "Disabled package variables: " << disabled_package_variables << std::endl;
    std::cout << "Package weights             " << package_weights << std::endl;
    std::cout << "Total disabled:             " << total_disabled << std::endl;

    linear(*this, package_weights, disabled_package_variables, IRT_EQ, total_disabled);
  }

  void Problem2() {
    std::cout << "Setting up " << __FUNCTION__ << std::endl;
    // Add version constraints for pkg 0
    dom(*this, package_versions[0], -1, 0);
    dom(*this, package_versions[1], -1, 0);
    dom(*this, package_versions[2], -1, 0);
    dom(*this, package_versions[3], -1, 1);
    dom(*this, package_versions[4], -1, 0);
    dom(*this, package_versions[5], -1, 0);
    dom(*this, package_versions[6], -1, 2);
    dom(*this, package_versions[7], -1, 0);
    dom(*this, package_versions[8], -1, 0);
    dom(*this, package_versions[9], -1, -1);
    dom(*this, package_versions[10], 0, 0);

    AddVersionConstraint(0, 0, 1, 0, 1);
    AddVersionConstraint(2, 0, 1, 0, 0);
    AddVersionConstraint(1, 0, 3, 0, 1);
    AddVersionConstraint(1, 0, 4, 0, 0);
    AddVersionConstraint(1, 1, 3, 1, 1);
    AddVersionConstraint(1, 1, 5, 0, 0);
    AddVersionConstraint(7, 0, 3, -2, -2);
    AddVersionConstraint(8, 0, 9, -2, -2);
    AddVersionConstraint(10, 0, 7, 0, 0);

    IntArgs package_weights(PKG_COUNT, 10, 10, 10, 10, 10,  10, 10, 5, 10, 10 );

    std::cout << "Package versions:           " << package_versions << std::endl;
    std::cout << "Disabled package variables: " << disabled_package_variables << std::endl;
    std::cout << "Package weights             " << package_weights << std::endl;
    std::cout << "Total disabled:             " << total_disabled << std::endl;

    linear(*this, package_weights, disabled_package_variables, IRT_EQ, total_disabled);
  }

  bool AddVersionConstraint(int packageId, int version,
			    int dependentPackageId, int minDependentVersion, int maxDependentVersion)
  {
    BoolVar version_match(*this, 0, 1);
    BoolVar depend_match(*this, 0, 1);
    BoolVar predicated_depend_match(*this, 0, 1);

    std::cout << "Add VC for " << packageId << " @ " << version << " depPkg " << dependentPackageId;
    std::cout << " [ " << minDependentVersion << ", " << maxDependentVersion << " ]" << std::endl;
    std::cout.flush();

    //version_flags << version_match;
    // Constrain pred to reify package @ version
    rel(*this, package_versions[packageId], IRT_EQ, version, version_match);
    // Add the predicated version constraints imposed on dependent package
    dom(*this, package_versions[dependentPackageId], minDependentVersion, maxDependentVersion, depend_match);
    // disabled_package_variables[dependentPackageId] OR depend_match <=> version_match

    rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, predicated_depend_match);
    rel(*this, version_match, BOT_IMP, predicated_depend_match, 1);
  }

  /// Print solution
  virtual void
  print(std::ostream& os) const {
    os << "\t" << package_versions << std::endl;
    os << "\t" << disabled_package_variables << std::endl;
    os << "\t" << total_disabled << std::endl;
  }
  virtual IntVar cost() const {
    return total_disabled;
  }

  /// Constructor for cloning \a s
  SimpleDependency(bool share, SimpleDependency& s) :
    MinimizeScript(share,s),
    package_versions(s.package_versions),
    disabled_package_variables(s.disabled_package_variables),
    total_disabled(s.total_disabled)
  {
    package_versions.update(*this, share, s.package_versions);
    disabled_package_variables.update(*this, share, s.disabled_package_variables);
    total_disabled.update(*this, share, s.total_disabled);
  }
  /// Copy during cloning
  virtual Space*
  copy(bool share) {
    return new SimpleDependency(share,*this);
  }
};

/** \brief Main-function
 *  \relates Money
 */
int
main(int argc, char* argv[]) {
  Options opt("Solve dependency");
  opt.solutions(0);
  opt.iterations(20000);
  opt.parse(argc,argv);
  for (int i = 0; i < 1; i++)
    MinimizeScript::run<SimpleDependency,Restart,Options>(opt);
  return 0;
}

// STATISTICS: example-any

<commit_msg>Cleanup/reorder<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */

#include <gecode/driver.hh>
#include <gecode/int.hh>
#include <gecode/minimodel.hh>

using namespace Gecode;

//
// g++ -g simple_dependency.cpp -lgecodesupport -lgecodekernel -lgecodeint -lgecodesearch -lgecodedriver -lpthread -ldl   -lstdc++ -o simple_dependency
//

class SimpleDependency : public MinimizeScript {
protected:
  static const int PKG_COUNT = 11;

  IntVarArray package_versions;
  IntArgs disabled_package_weights;
  BoolVarArray disabled_package_variables;
  IntVar total_disabled;
public:
  /// Actual model
  SimpleDependency(const Options& opt) :
    package_versions(*this, PKG_COUNT, -1, 10),
    disabled_package_variables(*this, PKG_COUNT, 0, 1),
    total_disabled(*this, 0, 10*PKG_COUNT)
  {
    Problem2();

    branch(*this, package_versions, INT_VAR_SIZE_MIN, INT_VAL_MAX);
    branch(*this, disabled_package_variables, INT_VAR_SIZE_MIN, INT_VAL_MIN);
    branch(*this, total_disabled, INT_VAL_MIN);
  }

  void Problem1() {
    std::cout << "Setting up " << __FUNCTION__ << std::endl;
    // Add version constraints for pkg 0
    dom(*this, package_versions[0], -1, 0);
    dom(*this, package_versions[1], -1, 0);
    dom(*this, package_versions[2], -1, 0);
    dom(*this, package_versions[3], -1, 1);
    dom(*this, package_versions[4], -1, 0);
    dom(*this, package_versions[5], -1, 0);
    dom(*this, package_versions[6], -1, 2);
    dom(*this, package_versions[7], -1, 0);
    dom(*this, package_versions[8], -1, 0);
    dom(*this, package_versions[9], -1, -1);
    dom(*this, package_versions[10], 0, 0);

    AddVersionConstraint(0, 0, 1, 0, 1);
    AddVersionConstraint(2, 0, 1, 0, 0);
    AddVersionConstraint(1, 0, 3, 0, 1);
    AddVersionConstraint(1, 0, 4, 0, 0);
    AddVersionConstraint(1, 1, 3, 1, 1);
    AddVersionConstraint(1, 1, 5, 0, 0);
    AddVersionConstraint(7, 0, 3, -2, -2);
    AddVersionConstraint(8, 0, 9, -2, -2);
    AddVersionConstraint(10, 0, 7, 0, 0);

    IntArgs package_weights(PKG_COUNT, 10, 10, 10, 10, 10,  10, 10, 10, 10, 10 );
    linear(*this, package_weights, disabled_package_variables, IRT_EQ, total_disabled);

    std::cout << "Package versions:           " << package_versions << std::endl;
    std::cout << "Disabled package variables: " << disabled_package_variables << std::endl;
    std::cout << "Package weights             " << package_weights << std::endl;
    std::cout << "Total disabled:             " << total_disabled << std::endl;
  }

  void Problem2() {
    std::cout << "Setting up " << __FUNCTION__ << std::endl;
    // Add version constraints for pkg 0
    dom(*this, package_versions[0], -1, 0);
    dom(*this, package_versions[1], -1, 0);
    dom(*this, package_versions[2], -1, 0);
    dom(*this, package_versions[3], -1, 1);
    dom(*this, package_versions[4], -1, 0);
    dom(*this, package_versions[5], -1, 0);
    dom(*this, package_versions[6], -1, 2);
    dom(*this, package_versions[7], -1, 0);
    dom(*this, package_versions[8], -1, 0);
    dom(*this, package_versions[9], -1, -1);
    dom(*this, package_versions[10], 0, 0);

    AddVersionConstraint(0, 0, 1, 0, 1);
    AddVersionConstraint(2, 0, 1, 0, 0);
    AddVersionConstraint(1, 0, 3, 0, 1);
    AddVersionConstraint(1, 0, 4, 0, 0);
    AddVersionConstraint(1, 1, 3, 1, 1);
    AddVersionConstraint(1, 1, 5, 0, 0);
    AddVersionConstraint(7, 0, 3, -2, -2);
    AddVersionConstraint(8, 0, 9, -2, -2);
    AddVersionConstraint(10, 0, 7, 0, 0);

    IntArgs package_weights(PKG_COUNT, 10, 10, 10, 10, 10,  10, 10, 5, 10, 10 );
    linear(*this, package_weights, disabled_package_variables, IRT_EQ, total_disabled);

    std::cout << "Package versions:           " << package_versions << std::endl;
    std::cout << "Disabled package variables: " << disabled_package_variables << std::endl;
    std::cout << "Package weights             " << package_weights << std::endl;
    std::cout << "Total disabled:             " << total_disabled << std::endl;
  }

  bool AddVersionConstraint(int packageId, int version,
			    int dependentPackageId, int minDependentVersion, int maxDependentVersion)
  {
    BoolVar version_match(*this, 0, 1);
    BoolVar depend_match(*this, 0, 1);
    BoolVar predicated_depend_match(*this, 0, 1);

    std::cout << "Add VC for " << packageId << " @ " << version << " depPkg " << dependentPackageId;
    std::cout << " [ " << minDependentVersion << ", " << maxDependentVersion << " ]" << std::endl;
    std::cout.flush();

    //version_flags << version_match;
    // Constrain pred to reify package @ version
    rel(*this, package_versions[packageId], IRT_EQ, version, version_match);
    // Add the predicated version constraints imposed on dependent package
    dom(*this, package_versions[dependentPackageId], minDependentVersion, maxDependentVersion, depend_match);
    // disabled_package_variables[dependentPackageId] OR depend_match <=> version_match

    rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, predicated_depend_match);
    rel(*this, version_match, BOT_IMP, predicated_depend_match, 1);
  }

  /// Print solution
  virtual void
  print(std::ostream& os) const {
    os << "\t" << package_versions << std::endl;
    os << "\t" << disabled_package_variables << std::endl;
    os << "\t" << total_disabled << std::endl;
  }
  virtual IntVar cost() const {
    return total_disabled;
  }

  /// Constructor for cloning \a s
  SimpleDependency(bool share, SimpleDependency& s) :
    MinimizeScript(share,s),
    package_versions(s.package_versions),
    disabled_package_variables(s.disabled_package_variables),
    total_disabled(s.total_disabled)
  {
    package_versions.update(*this, share, s.package_versions);
    disabled_package_variables.update(*this, share, s.disabled_package_variables);
    total_disabled.update(*this, share, s.total_disabled);
  }
  /// Copy during cloning
  virtual Space*
  copy(bool share) {
    return new SimpleDependency(share,*this);
  }
};

/** \brief Main-function
 *  \relates Money
 */
int
main(int argc, char* argv[]) {
  Options opt("Solve dependency");
  opt.solutions(0);
  opt.iterations(20000);
  opt.parse(argc,argv);
  for (int i = 0; i < 1; i++)
    MinimizeScript::run<SimpleDependency,Restart,Options>(opt);
  return 0;
}

// STATISTICS: example-any

<|endoftext|>