<commit_before>//  Author Amoriello Hutti - 2015

#include <token/commands.h>

#include <Arduino.h>
#include <USBAPI.h>

#include <token/token.h>
#include <token/password.h>
#include <token/crypto.h>
#include <token/communication/channel.h>
#include <token/log.h>

CmdProcessor g_cmd_registrer[cmdid::kNbCmd];

void Pair(const Command& cmd) {
  Response resp;

  g_token.Pair();

  TLOG2("Pair");

  const SymKey& pass_key = g_token.PassKey();
  const SymKey& cr_key = g_token.CRKey();
  const SymKey& req_key = g_token.ReqKey();

  resp.hdr.id = respid::kOk;
  uint8_t key_size = sizeof(pass_key.data);
  resp.hdr.arg_size = 3 * key_size;

  for (int i = 0; i < key_size; ++i) {
    resp.arg[i] = pass_key.data[i];
    resp.arg[16 + i] = cr_key.data[i];
    resp.arg[32 + i] = req_key.data[i];
  }

  g_chan.WriteResponse(resp);
}

void CreateChallenge(const Command& cmd) {
  Response resp;

  TLOG2("Challenge");

  resp.hdr.id = respid::kOk;
  resp.hdr.arg_size = sizeof(Challenge);

  Challenge* p_challenge = (Challenge*)(&resp.arg);
  CreateChallenge(p_challenge);

  g_chan.WriteResponse(resp);
}

void CreatePassword(const Command& cmd) {
  Response resp;
  Password pass;

  TLOG2("CreatePassword");

  uint8_t size = cmd.arg[0];
  if (size > Password::kMaxSize) {
    resp.hdr.id = respid::kInvalidArgument;
    resp.hdr.arg_size = 0;
    g_chan.WriteResponse(resp);
    return;
  }

  CreatePassword(&pass, size);

  CipherPassword(pass, g_token.PassKey(), resp.arg);

  resp.hdr.id = respid::kOk;
  // IV + 4 * 16 bytes
  resp.hdr.arg_size = 80;

  g_chan.WriteResponse(resp);
}

void TypePassword(const Command& cmd) {
  Response resp;

  TLOG2("TypePassword");

  if (cmd.hdr.arg_size < 80 || cmd.hdr.arg_size > 85) {
    TLOG2("No Way");
    TLOG2(cmd.hdr.arg_size, DEC);
    resp.hdr.id = respid::kInvalidArgument;
    resp.hdr.arg_size = 0;
    g_chan.WriteResponse(resp);
    return;
  }

  DecipherPassword(cmd.arg, g_token.PassKey(), (Password*)&resp.arg);

  char* p_password = (char*)&resp.arg[1];
  TLOG2(p_password);

#ifndef TEST_NO_KEYBOARD
  Keyboard.print(p_password);
#endif  // TEST_NO_KEYBOARD
  TLOG("ArgSize:");
  TLOG(cmd.hdr.arg_size, DEC);
  uint8_t nbAdditionnalKeyPress = cmd.hdr.arg_size - 80;
  for (uint8_t i = 0; i < nbAdditionnalKeyPress; ++i) {
    TLOG2("More keys");
    TLOG2(cmd.arg[80 + i], HEX);
    #ifndef TEST_NO_KEYBOARD
    Keyboard.press(cmd.arg[80 + i]);
    Keyboard.releaseAll();
    #endif  // TEST_NO_KEYBOARD
  }

  resp.hdr.id = respid::kOk;
  resp.hdr.arg_size = 0;
  g_chan.WriteResponse(resp);
}

void LockComputer(const Command& cmd) {
  Response resp;

  Keyboard.press(KEY_LEFT_GUI);
  Keyboard.release('l');

  resp.hdr.id = respid::kOk;
  resp.hdr.arg_size = 0;
  g_chan.WriteResponse(resp);
}

void TypeString(const Command& cmd) {
  Response resp;

  if (cmd.hdr.arg_size >= 100) {
    resp.hdr.id = respid::kInvalidArgument;
    resp.hdr.arg_size = 0;
    g_chan.WriteResponse(resp);
    return;
  }

  char* string = (char*)cmd.arg;

  //length will contains string length + 1
  uint8_t length = 0;
  while (string[length++]);

  // Special characters
  if (cmd.hdr.arg_size > length) {
    uint8_t nbAdditionnalKeyPress = cmd.hdr.arg_size - length;
    uint8_t beginKeyIndex = cmd.hdr.arg_size - nbAdditionnalKeyPress;
    for (uint8_t i = 0; i < nbAdditionnalKeyPress; ++i) {
      #ifndef TEST_NO_KEYBOARD
      Keyboard.press(cmd.arg[beginKeyIndex + i]);
      Keyboard.releaseAll();
      #endif  // TEST_NO_KEYBOARD
    }
  }

  Keyboard.print(string);

  resp.hdr.id = respid::kOk;
  resp.hdr.arg_size = 0;
  g_chan.WriteResponse(resp);
}

void ReturnPassword(const Command& cmd) {
  Response resp;
  Password pass;
  TLOG2("ReturnPassword");

  if (cmd.hdr.arg_size != 80) {
    resp.hdr.id = respid::kInvalidArgument;
    resp.hdr.arg_size = 0;
    g_chan.WriteResponse(resp);
  }

  DecipherPassword(cmd.arg, g_token.PassKey(), &pass);

  CipherPassword(pass, g_token.ReqKey(), resp.arg);

  resp.hdr.id = respid::kOk;
  // IV + 4 * 16 bytes
  resp.hdr.arg_size = 80;

  g_chan.WriteResponse(resp);
}

void Reset(const Command& cmd) {
  Response resp;

  g_token.Reset();

  resp.hdr.id = respid::kOk;
  resp.hdr.arg_size = 0;

  g_chan.WriteResponse(resp);
}

namespace /* anonymous */ {

void RegistrerCommands() {
  g_cmd_registrer[cmdid::kPair] = &Pair;
  g_cmd_registrer[cmdid::kCreateChallenge] = &CreateChallenge;
  g_cmd_registrer[cmdid::kReset] = &Reset;

  g_cmd_registrer[cmdid::kCreatePassword] = &CreatePassword;
  g_cmd_registrer[cmdid::kTypePassword] = &TypePassword;
  g_cmd_registrer[cmdid::kReturnPassword] = &ReturnPassword;
  g_cmd_registrer[cmdid::kLockComputer] = &LockComputer;
  g_cmd_registrer[cmdid::kTypeString] = &TypeString;
  g_cmd_registrer[cmdid::kNbCmd] = 0;  // kNbCmd == nb registrered cmd
}

struct AutoCmdRegistrer {
  AutoCmdRegistrer() {
    RegistrerCommands();
  }
};

static AutoCmdRegistrer registrer2;

}  // namespace anonymous<commit_msg>Fix: Index out of range<commit_after>//  Author Amoriello Hutti - 2015

#include <token/commands.h>

#include <Arduino.h>
#include <USBAPI.h>

#include <token/token.h>
#include <token/password.h>
#include <token/crypto.h>
#include <token/communication/channel.h>
#include <token/log.h>

CmdProcessor g_cmd_registrer[cmdid::kNbCmd];

void Pair(const Command& cmd) {
  Response resp;

  g_token.Pair();

  TLOG2("Pair");

  const SymKey& pass_key = g_token.PassKey();
  const SymKey& cr_key = g_token.CRKey();
  const SymKey& req_key = g_token.ReqKey();

  resp.hdr.id = respid::kOk;
  uint8_t key_size = sizeof(pass_key.data);
  resp.hdr.arg_size = 3 * key_size;

  for (int i = 0; i < key_size; ++i) {
    resp.arg[i] = pass_key.data[i];
    resp.arg[16 + i] = cr_key.data[i];
    resp.arg[32 + i] = req_key.data[i];
  }

  g_chan.WriteResponse(resp);
}

void CreateChallenge(const Command& cmd) {
  Response resp;

  TLOG2("Challenge");

  resp.hdr.id = respid::kOk;
  resp.hdr.arg_size = sizeof(Challenge);

  Challenge* p_challenge = (Challenge*)(&resp.arg);
  CreateChallenge(p_challenge);

  g_chan.WriteResponse(resp);
}

void CreatePassword(const Command& cmd) {
  Response resp;
  Password pass;

  TLOG2("CreatePassword");

  uint8_t size = cmd.arg[0];
  if (size > Password::kMaxSize) {
    resp.hdr.id = respid::kInvalidArgument;
    resp.hdr.arg_size = 0;
    g_chan.WriteResponse(resp);
    return;
  }

  CreatePassword(&pass, size);

  CipherPassword(pass, g_token.PassKey(), resp.arg);

  resp.hdr.id = respid::kOk;
  // IV + 4 * 16 bytes
  resp.hdr.arg_size = 80;

  g_chan.WriteResponse(resp);
}

void TypePassword(const Command& cmd) {
  Response resp;

  TLOG2("TypePassword");

  if (cmd.hdr.arg_size < 80 || cmd.hdr.arg_size > 85) {
    TLOG2("No Way");
    TLOG2(cmd.hdr.arg_size, DEC);
    resp.hdr.id = respid::kInvalidArgument;
    resp.hdr.arg_size = 0;
    g_chan.WriteResponse(resp);
    return;
  }

  DecipherPassword(cmd.arg, g_token.PassKey(), (Password*)&resp.arg);

  char* p_password = (char*)&resp.arg[1];
  TLOG2(p_password);

#ifndef TEST_NO_KEYBOARD
  Keyboard.print(p_password);
#endif  // TEST_NO_KEYBOARD
  TLOG("ArgSize:");
  TLOG(cmd.hdr.arg_size, DEC);
  uint8_t nbAdditionnalKeyPress = cmd.hdr.arg_size - 80;
  for (uint8_t i = 0; i < nbAdditionnalKeyPress; ++i) {
    TLOG2("More keys");
    TLOG2(cmd.arg[80 + i], HEX);
    #ifndef TEST_NO_KEYBOARD
    Keyboard.press(cmd.arg[80 + i]);
    Keyboard.releaseAll();
    #endif  // TEST_NO_KEYBOARD
  }

  resp.hdr.id = respid::kOk;
  resp.hdr.arg_size = 0;
  g_chan.WriteResponse(resp);
}

void LockComputer(const Command& cmd) {
  Response resp;

  Keyboard.press(KEY_LEFT_GUI);
  Keyboard.release('l');

  resp.hdr.id = respid::kOk;
  resp.hdr.arg_size = 0;
  g_chan.WriteResponse(resp);
}

void TypeString(const Command& cmd) {
  Response resp;

  if (cmd.hdr.arg_size >= 100) {
    resp.hdr.id = respid::kInvalidArgument;
    resp.hdr.arg_size = 0;
    g_chan.WriteResponse(resp);
    return;
  }

  char* string = (char*)cmd.arg;

  //length will contains string length + 1
  uint8_t length = 0;
  while (string[length++]);

  // Special characters
  if (cmd.hdr.arg_size > length) {
    uint8_t nbAdditionnalKeyPress = cmd.hdr.arg_size - length;
    uint8_t beginKeyIndex = cmd.hdr.arg_size - nbAdditionnalKeyPress;
    for (uint8_t i = 0; i < nbAdditionnalKeyPress; ++i) {
      #ifndef TEST_NO_KEYBOARD
      Keyboard.press(cmd.arg[beginKeyIndex + i]);
      Keyboard.releaseAll();
      #endif  // TEST_NO_KEYBOARD
    }
  }

  Keyboard.print(string);

  resp.hdr.id = respid::kOk;
  resp.hdr.arg_size = 0;
  g_chan.WriteResponse(resp);
}

void ReturnPassword(const Command& cmd) {
  Response resp;
  Password pass;
  TLOG2("ReturnPassword");

  if (cmd.hdr.arg_size != 80) {
    resp.hdr.id = respid::kInvalidArgument;
    resp.hdr.arg_size = 0;
    g_chan.WriteResponse(resp);
  }

  DecipherPassword(cmd.arg, g_token.PassKey(), &pass);

  CipherPassword(pass, g_token.ReqKey(), resp.arg);

  resp.hdr.id = respid::kOk;
  // IV + 4 * 16 bytes
  resp.hdr.arg_size = 80;

  g_chan.WriteResponse(resp);
}

void Reset(const Command& cmd) {
  Response resp;

  g_token.Reset();

  resp.hdr.id = respid::kOk;
  resp.hdr.arg_size = 0;

  g_chan.WriteResponse(resp);
}

namespace /* anonymous */ {

void RegistrerCommands() {
  g_cmd_registrer[cmdid::kPair] = &Pair;
  g_cmd_registrer[cmdid::kCreateChallenge] = &CreateChallenge;
  g_cmd_registrer[cmdid::kReset] = &Reset;

  g_cmd_registrer[cmdid::kCreatePassword] = &CreatePassword;
  g_cmd_registrer[cmdid::kTypePassword] = &TypePassword;
  g_cmd_registrer[cmdid::kReturnPassword] = &ReturnPassword;
  g_cmd_registrer[cmdid::kLockComputer] = &LockComputer;
  g_cmd_registrer[cmdid::kTypeString] = &TypeString;
}

struct AutoCmdRegistrer {
  AutoCmdRegistrer() {
    RegistrerCommands();
  }
};

static AutoCmdRegistrer registrer2;

}  // namespace anonymous<|endoftext|>


<commit_before>/*
    nowlisteningplugin.cpp

    Kopete Now Listening To plugin

    Copyright (c) 2002 by Will Stephenson <will@stevello.free-online.co.uk>

    Kopete    (c) 2002 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <qtimer.h>
#include <qdict.h>
#if QT_VERSION < 0x030100
#include <qregexp.h>
#endif

#include <kdebug.h>
#include <kgenericfactory.h>
#include <kapplication.h>
#include <dcopclient.h>
#include <kaction.h>
#include <kstdguiitem.h>

//#include "kopete.h"
#include "kopetemessagemanagerfactory.h"
#include "kopetemetacontact.h"
#include "nowlisteningpreferences.h"
#include "nowlisteningplugin.h"
#include "nlmediaplayer.h"
#include "nlkscd.h"
#include "nlnoatun.h"

#ifdef HAVE_XMMS
#include "nlxmms.h"
#endif

#define NL_DATA_KEY "sendNowListening"

K_EXPORT_COMPONENT_FACTORY(  kopete_nowlistening, KGenericFactory<NowListeningPlugin> );

NowListeningPlugin::NowListeningPlugin( QObject *parent, const char *name, const QStringList & /*args*/ )
	: KopetePlugin( parent, name )
{
	kdDebug(14307) << "NowListeningPlugin::NowListeningPlugin()" << endl;
	// make these pointers safe until init'd
	m_actionCollection = 0L;
	m_actionWantsAdvert = 0L;
	m_currentMetaContact = 0L;
	m_currentMessageManager = 0L;

	// initialise preferences

	m_prefs = new NowListeningPreferences( "", this );
	connect ( m_prefs, SIGNAL( saved() ), this, SLOT( slotSettingsChanged() ) );
	// get a pointer to the dcop client

	m_client = kapp->dcopClient();
	m_client->attach();

	// set up known media players
	m_mediaPlayer = new QPtrList<NLMediaPlayer>;
	m_mediaPlayer->setAutoDelete( true );
	m_mediaPlayer->append( new NLKscd( m_client ) );
	m_mediaPlayer->append( new NLNoatun( m_client ) );
#ifdef HAVE_XMMS
	m_mediaPlayer->append( new NLXmms() );
#endif

	// set up poll timers
	m_pollTimer = new QTimer();

	// connect timer signals to dcop poll methods
	connect( m_pollTimer, SIGNAL( timeout() ),
			this, SLOT( slotChangesToAllChats() ) );
	m_pollTimer->start( m_prefs->pollFrequency() * 1000 );

	// watch for '/media' getting typed
	connect(  KopeteMessageManagerFactory::factory(),
			SIGNAL(  aboutToSend(  KopeteMessage & ) ),
			SLOT(  slotOutgoingMessage(  KopeteMessage & ) ) );
}

NowListeningPlugin::~NowListeningPlugin()
{
	kdDebug(14307) << "NowListeningPlugin::~NowListeningPlugin()" << endl;

	delete m_mediaPlayer;

	// cleanly end DCOP
	m_client->detach();
}

KActionCollection *NowListeningPlugin::customContextMenuActions( KopeteMetaContact *m )
{
	kdDebug(14307) << "NowListeningPlugin::customContextMenuActions() - for " <<
		m->displayName() << endl;
	delete m_actionCollection;
	m_actionCollection = new KActionCollection( this );
	m_actionWantsAdvert = new KToggleAction( "Now Listening", 0, this,
			SLOT( slotContactWantsToggled() ), m_actionCollection, "actionWantsAdvert" );
	m_actionWantsAdvert->setChecked( m->pluginData( this, NL_DATA_KEY ) == "true" );
	m_actionCollection->insert( m_actionWantsAdvert );
	m_currentMetaContact = m;
	return m_actionCollection;
}

KActionCollection *NowListeningPlugin::customChatActions(  KopeteMessageManager* kmm )
{
	kdDebug(14307) << "NowListeningPlugin::customChatActions()" << endl;
	delete m_actionCollection;
	m_actionCollection = new KActionCollection( this );
	KAction *actionSendAdvert = new KAction( "Send Media Info", 0, this,
			SLOT( slotAdvertToCurrentChat() ), m_actionCollection, "actionSendAdvert" );
	m_actionCollection->insert( actionSendAdvert );
	m_currentMessageManager = kmm;
	return m_actionCollection;
}

void NowListeningPlugin::slotContactWantsToggled()
{
	kdDebug(14307) << "NowListeningPlugin::slotContactsWantsToggled()" << endl;
	if ( m_actionWantsAdvert && m_currentMetaContact )
	{
		m_currentMetaContact->setPluginData( this, NL_DATA_KEY,
				( m_actionWantsAdvert->isChecked() ? "true" : "false" ) );
	}
	return;
}

void NowListeningPlugin::slotAdvertToCurrentChat()
{
	//advertise  to a single chat
	if ( m_currentMessageManager )
		advertiseToChat( m_currentMessageManager, allPlayerAdvert() );
	return;
}

void NowListeningPlugin::slotChangesToAllChats()
{
	kdDebug(14307) << "NowListeningPlugin::slotChangesToAllChats()" << endl;
	//bool sthToAdvertise = false;
	QString message = changesOnlyAdvert();
	// tell each active chat about the new tracks
	if ( !message.isEmpty() )
	{
		// get the list of active chats
		KopeteMessageManagerDict allsessions =
			KopeteMessageManagerFactory::factory()->sessions();
		// for each active chat
		for ( QIntDictIterator<KopeteMessageManager> it( allsessions );
				it.current();
				++it )
		{
			advertiseToChat( it.current(), message );
		}
	}
	return;
}

void NowListeningPlugin::slotOutgoingMessage( KopeteMessage& msg )
{
	//NB DOESN'T RESPECT USER PREFS"!!!
	QString originalBody = msg.plainBody();
	// look for messages that we've generated and ignore them
	if ( !originalBody.startsWith( m_prefs->header() ) )
	{
		// look for the string '/media'
		if ( originalBody.startsWith( "/media" ) )
		{
			// replace it with media advert
			QString newBody = allPlayerAdvert() + originalBody.right(
					originalBody.length() - 6 );
			msg.setBody( newBody, KopeteMessage::RichText );
		}
		return;
	}
}

QString NowListeningPlugin::allPlayerAdvert() const
{
	// generate message for all players
	QString message = m_prefs->header();
	QString perTrack = m_prefs->perTrack();

	for ( NLMediaPlayer* i = m_mediaPlayer->first(); i; i = m_mediaPlayer->next() )
	{
		i->update();
		if ( i->playing() )
		{
			if (  message != m_prefs->header() ) // > 1 track playing!
				message = message + m_prefs->conjunction();
			message = message + substDepthFirst( i, perTrack, false );
		}
	}
	return message;
}

QString NowListeningPlugin::changesOnlyAdvert() const
{
	QString message = "";
	QString perTrack = m_prefs->perTrack();

	// see if there is something new
	for ( NLMediaPlayer* i = m_mediaPlayer->first(); i; i = m_mediaPlayer->next() )
	{
		i->update();
		if ( i->playing() && i->newTrack() )
		{
			if ( message.isEmpty() )
				message = m_prefs->header();
			// generate a message
			//kdDebug(14307) << m_mediaPlayer[ i ]->name() << " says it's playing "
			//	<< "a " << ( m_mediaPlayer[ i ]->newTrack() ? "new" : "old" )  << " track" << endl;
			// CLEVER SUBSTITUTION WITH DEPTH FIRST SEARCH FOR
			// INCLUSION CONDITIONAL ON SUBSTITUTION BEING MADE
			if (  message != m_prefs->header() ) // > 1 track playing!
				message = message + m_prefs->conjunction();
			//kdDebug(14307) << i->track() << i->artist() << i->album() << i->name() << endl;
			message = message + substDepthFirst( i, perTrack, false );
		}
	}
	return message;
}

QString NowListeningPlugin::substDepthFirst( NLMediaPlayer *player,
		QString in, bool inBrackets ) const
{
	QString track = player->track();
	QString artist = player->artist();
	QString album = player->album();
	QString playerName = player->name();

	for ( unsigned int i = 0; i < in.length(); i++ )
	{
		QChar c = in.at( i );
		//kdDebug(14307) << "Now working on:" << in << " char is: " << c << endl;
		if ( c == '(' )
		{
			// find matching bracket
			int depth = 0;
			//kdDebug(14307) << "Looking for ')'" << endl;
			for ( unsigned int j = i + 1; j < in.length(); j++ )
			{
				QChar d = in.at( j );
				//kdDebug(14307) << "Got " << d << endl;
				if ( d == '(' )
					depth++;
				if ( d == ')' )
				{
					// have we found the match?
					if ( depth == 0 )
					{
						// recursively replace contents of matching ()
						QString substitution = substDepthFirst( player,
								in.mid( i + 1, j - i - 1), true ) ;
						in.replace ( i, j - i + 1, substitution );
						// perform substitution and return the result
						i = i + substitution.length() - 1;
						break;
					}
					else
						depth--;
				}
			}
		}
	}
	// no () found, perform substitution!
	// get each string (to) to substitute for (from)
	bool done = false;
	if ( in.contains ( "%track" ) && !track.isEmpty() )
	{
#if QT_VERSION < 0x030100
		in.replace( QRegExp( "%track" ), track );
#else
		in.replace( "%track", track );
#endif
		done = true;
	}
	if ( in.contains ( "%artist" ) && !artist.isEmpty() )
	{
#if QT_VERSION < 0x030100
		in.replace( QRegExp( "%artist" ), artist );
#else
		in.replace( "%artist", artist );
#endif
		done = true;
	}
	if ( in.contains ( "%album" ) && !album.isEmpty() )
	{
#if QT_VERSION < 0x030100
		in.replace( QRegExp( "%album" ), album );
#else
		in.replace( "%album", album );
#endif
		done = true;
	}
	if ( in.contains ( "%player" ) && !playerName.isEmpty() )
	{
#if QT_VERSION < 0x030100
		in.replace( QRegExp( "%player" ), playerName );
#else
		in.replace( "%player", playerName );
#endif
		done = true;
	}
	//kdDebug(14307) << "Result is: " << in << endl;
	// make whether we return anything dependent on whether we
	// were in brackets and if we were, if a substitution was made.
	if ( inBrackets && !done )
		return "";
	else
		return in;
}

void NowListeningPlugin::advertiseToChat( KopeteMessageManager *theChat, QString message )
{
	if ( theChat->widget() != 0L )
	{
		// then we have a live session?

		// reduce the recipients to the set of members who are interested
		// in our output
		KopeteContactPtrList pl = theChat->members();
		QStringList myData;
		// avoid skipping one member when removing
		// (old version's pl.remove(); pl.next() skipped because
		// remove() moves on to next for you.
		pl.first();
		while ( pl.current() )
		{
			myData = pl.current()->metaContact()->pluginData( this, NL_DATA_KEY );
			if ( myData.isEmpty() || myData.first() != "true" )
				pl.remove();
			else
				pl.next();
		}
		// get on with it
		kdDebug(14307) << "NowListeningPlugin::advertiseNewTracks() - " <<
			( pl.isEmpty() ? "has no " : "has " ) << "interested recipients: " << endl;
		for ( pl.first(); pl.current(); pl.next() )
			kdDebug(14307) << "NowListeningPlugin::advertiseNewTracks() " << pl.current()->displayName() << endl;
		// if no-one in this KMM wants to be advertised to, don't send
		// any message
		if ( pl.isEmpty() )
			return;
		KopeteMessage msg( theChat->user(),
				pl,
				message,
				KopeteMessage::Outbound,
				KopeteMessage::RichText );
		theChat->slotMessageSent( msg );
	}
	return;
}
void NowListeningPlugin::slotSettingsChanged()
{
	m_pollTimer->start( m_prefs->pollFrequency() * 1000 );
}

#include "nowlisteningplugin.moc"

// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>Fix to make nowlistning build again<commit_after>/*
    nowlisteningplugin.cpp

    Kopete Now Listening To plugin

    Copyright (c) 2002 by Will Stephenson <will@stevello.free-online.co.uk>

    Kopete    (c) 2002 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <qtimer.h>
#include <qdict.h>
#if QT_VERSION < 0x030100
#include <qregexp.h>
#endif

#include <kdebug.h>
#include <kgenericfactory.h>
#include <kapplication.h>
#include <dcopclient.h>
#include <kaction.h>
#include <kstdguiitem.h>

//#include "kopete.h"
#include "kopetemessagemanagerfactory.h"
#include "kopetemetacontact.h"
#include "nowlisteningpreferences.h"
#include "nowlisteningplugin.h"
#include "nlmediaplayer.h"
#include "nlkscd.h"
#include "nlnoatun.h"

#ifdef HAVE_XMMS
#include "nlxmms.h"
#endif

#define NL_DATA_KEY "sendNowListening"

K_EXPORT_COMPONENT_FACTORY(  kopete_nowlistening, KGenericFactory<NowListeningPlugin> );

NowListeningPlugin::NowListeningPlugin( QObject *parent, const char *name, const QStringList & /*args*/ )
	: KopetePlugin( parent, name )
{
	kdDebug(14307) << "NowListeningPlugin::NowListeningPlugin()" << endl;
	// make these pointers safe until init'd
	m_actionCollection = 0L;
	m_actionWantsAdvert = 0L;
	m_currentMetaContact = 0L;
	m_currentMessageManager = 0L;

	// initialise preferences

	m_prefs = new NowListeningPreferences( "", this );
	connect ( m_prefs, SIGNAL( saved() ), this, SLOT( slotSettingsChanged() ) );
	// get a pointer to the dcop client

	m_client = kapp->dcopClient();
	m_client->attach();

	// set up known media players
	m_mediaPlayer = new QPtrList<NLMediaPlayer>;
	m_mediaPlayer->setAutoDelete( true );
	m_mediaPlayer->append( new NLKscd( m_client ) );
	m_mediaPlayer->append( new NLNoatun( m_client ) );
#ifdef HAVE_XMMS
	m_mediaPlayer->append( new NLXmms() );
#endif

	// set up poll timers
	m_pollTimer = new QTimer();

	// connect timer signals to dcop poll methods
	connect( m_pollTimer, SIGNAL( timeout() ),
			this, SLOT( slotChangesToAllChats() ) );
	m_pollTimer->start( m_prefs->pollFrequency() * 1000 );

	// watch for '/media' getting typed
	connect(  KopeteMessageManagerFactory::factory(),
			SIGNAL(  aboutToSend(  KopeteMessage & ) ),
			SLOT(  slotOutgoingMessage(  KopeteMessage & ) ) );
}

NowListeningPlugin::~NowListeningPlugin()
{
	kdDebug(14307) << "NowListeningPlugin::~NowListeningPlugin()" << endl;

	delete m_mediaPlayer;

	// cleanly end DCOP
	m_client->detach();
}

KActionCollection *NowListeningPlugin::customContextMenuActions( KopeteMetaContact *m )
{
	kdDebug(14307) << "NowListeningPlugin::customContextMenuActions() - for " <<
		m->displayName() << endl;
	delete m_actionCollection;
	m_actionCollection = new KActionCollection( this );
	m_actionWantsAdvert = new KToggleAction( "Now Listening", 0, this,
			SLOT( slotContactWantsToggled() ), m_actionCollection, "actionWantsAdvert" );
	m_actionWantsAdvert->setChecked( m->pluginData( this, NL_DATA_KEY ) == "true" );
	m_actionCollection->insert( m_actionWantsAdvert );
	m_currentMetaContact = m;
	return m_actionCollection;
}

KActionCollection *NowListeningPlugin::customChatActions(  KopeteMessageManager* kmm )
{
	kdDebug(14307) << "NowListeningPlugin::customChatActions()" << endl;
	delete m_actionCollection;
	m_actionCollection = new KActionCollection( this );
	KAction *actionSendAdvert = new KAction( "Send Media Info", 0, this,
			SLOT( slotAdvertToCurrentChat() ), m_actionCollection, "actionSendAdvert" );
	m_actionCollection->insert( actionSendAdvert );
	m_currentMessageManager = kmm;
	return m_actionCollection;
}

void NowListeningPlugin::slotContactWantsToggled()
{
	kdDebug(14307) << "NowListeningPlugin::slotContactsWantsToggled()" << endl;
	if ( m_actionWantsAdvert && m_currentMetaContact )
	{
		m_currentMetaContact->setPluginData( this, NL_DATA_KEY,
				( m_actionWantsAdvert->isChecked() ? "true" : "false" ) );
	}
	return;
}

void NowListeningPlugin::slotAdvertToCurrentChat()
{
	//advertise  to a single chat
	if ( m_currentMessageManager )
		advertiseToChat( m_currentMessageManager, allPlayerAdvert() );
	return;
}

void NowListeningPlugin::slotChangesToAllChats()
{
	kdDebug(14307) << "NowListeningPlugin::slotChangesToAllChats()" << endl;
	//bool sthToAdvertise = false;
	QString message = changesOnlyAdvert();
	// tell each active chat about the new tracks
	if ( !message.isEmpty() )
	{
		// get the list of active chats
		KopeteMessageManagerDict allsessions =
			KopeteMessageManagerFactory::factory()->sessions();
		// for each active chat
		for ( QIntDictIterator<KopeteMessageManager> it( allsessions );
				it.current();
				++it )
		{
			advertiseToChat( it.current(), message );
		}
	}
	return;
}

void NowListeningPlugin::slotOutgoingMessage( KopeteMessage& msg )
{
	//NB DOESN'T RESPECT USER PREFS"!!!
	QString originalBody = msg.plainBody();
	// look for messages that we've generated and ignore them
	if ( !originalBody.startsWith( m_prefs->header() ) )
	{
		// look for the string '/media'
		if ( originalBody.startsWith( "/media" ) )
		{
			// replace it with media advert
			QString newBody = allPlayerAdvert() + originalBody.right(
					originalBody.length() - 6 );
			msg.setBody( newBody, KopeteMessage::RichText );
		}
		return;
	}
}

QString NowListeningPlugin::allPlayerAdvert() const
{
	// generate message for all players
	QString message = m_prefs->header();
	QString perTrack = m_prefs->perTrack();

	for ( NLMediaPlayer* i = m_mediaPlayer->first(); i; i = m_mediaPlayer->next() )
	{
		i->update();
		if ( i->playing() )
		{
			if (  message != m_prefs->header() ) // > 1 track playing!
				message = message + m_prefs->conjunction();
			message = message + substDepthFirst( i, perTrack, false );
		}
	}
	return message;
}

QString NowListeningPlugin::changesOnlyAdvert() const
{
	QString message = "";
	QString perTrack = m_prefs->perTrack();

	// see if there is something new
	for ( NLMediaPlayer* i = m_mediaPlayer->first(); i; i = m_mediaPlayer->next() )
	{
		i->update();
		if ( i->playing() && i->newTrack() )
		{
			if ( message.isEmpty() )
				message = m_prefs->header();
			// generate a message
			//kdDebug(14307) << m_mediaPlayer[ i ]->name() << " says it's playing "
			//	<< "a " << ( m_mediaPlayer[ i ]->newTrack() ? "new" : "old" )  << " track" << endl;
			// CLEVER SUBSTITUTION WITH DEPTH FIRST SEARCH FOR
			// INCLUSION CONDITIONAL ON SUBSTITUTION BEING MADE
			if (  message != m_prefs->header() ) // > 1 track playing!
				message = message + m_prefs->conjunction();
			//kdDebug(14307) << i->track() << i->artist() << i->album() << i->name() << endl;
			message = message + substDepthFirst( i, perTrack, false );
		}
	}
	return message;
}

QString NowListeningPlugin::substDepthFirst( NLMediaPlayer *player,
		QString in, bool inBrackets ) const
{
	QString track = player->track();
	QString artist = player->artist();
	QString album = player->album();
	QString playerName = player->name();

	for ( unsigned int i = 0; i < in.length(); i++ )
	{
		QChar c = in.at( i );
		//kdDebug(14307) << "Now working on:" << in << " char is: " << c << endl;
		if ( c == '(' )
		{
			// find matching bracket
			int depth = 0;
			//kdDebug(14307) << "Looking for ')'" << endl;
			for ( unsigned int j = i + 1; j < in.length(); j++ )
			{
				QChar d = in.at( j );
				//kdDebug(14307) << "Got " << d << endl;
				if ( d == '(' )
					depth++;
				if ( d == ')' )
				{
					// have we found the match?
					if ( depth == 0 )
					{
						// recursively replace contents of matching ()
						QString substitution = substDepthFirst( player,
								in.mid( i + 1, j - i - 1), true ) ;
						in.replace ( i, j - i + 1, substitution );
						// perform substitution and return the result
						i = i + substitution.length() - 1;
						break;
					}
					else
						depth--;
				}
			}
		}
	}
	// no () found, perform substitution!
	// get each string (to) to substitute for (from)
	bool done = false;
	if ( in.contains ( "%track" ) && !track.isEmpty() )
	{
#if QT_VERSION < 0x030100
		in.replace( QRegExp( "%track" ), track );
#else
		in.replace( "%track", track );
#endif
		done = true;
	}
	if ( in.contains ( "%artist" ) && !artist.isEmpty() )
	{
#if QT_VERSION < 0x030100
		in.replace( QRegExp( "%artist" ), artist );
#else
		in.replace( "%artist", artist );
#endif
		done = true;
	}
	if ( in.contains ( "%album" ) && !album.isEmpty() )
	{
#if QT_VERSION < 0x030100
		in.replace( QRegExp( "%album" ), album );
#else
		in.replace( "%album", album );
#endif
		done = true;
	}
	if ( in.contains ( "%player" ) && !playerName.isEmpty() )
	{
#if QT_VERSION < 0x030100
		in.replace( QRegExp( "%player" ), playerName );
#else
		in.replace( "%player", playerName );
#endif
		done = true;
	}
	//kdDebug(14307) << "Result is: " << in << endl;
	// make whether we return anything dependent on whether we
	// were in brackets and if we were, if a substitution was made.
	if ( inBrackets && !done )
		return "";
	else
		return in;
}

void NowListeningPlugin::advertiseToChat( KopeteMessageManager *theChat, QString message )
{
	// reduce the recipients to the set of members who are interested
	// in our output
	KopeteContactPtrList pl = theChat->members();
	QStringList myData;
	// avoid skipping one member when removing
	// (old version's pl.remove(); pl.next() skipped because
	// remove() moves on to next for you.
	pl.first();
	while ( pl.current() )
	{
		myData = pl.current()->metaContact()->pluginData( this, NL_DATA_KEY );
		if ( myData.isEmpty() || myData.first() != "true" )
			pl.remove();
		else
			pl.next();
	}
	// get on with it
	kdDebug(14307) << "NowListeningPlugin::advertiseNewTracks() - " <<
		( pl.isEmpty() ? "has no " : "has " ) << "interested recipients: " << endl;
	for ( pl.first(); pl.current(); pl.next() )
		kdDebug(14307) << "NowListeningPlugin::advertiseNewTracks() " << pl.current()->displayName() << endl;
	// if no-one in this KMM wants to be advertised to, don't send
	// any message
	if ( pl.isEmpty() )
		return;
	KopeteMessage msg( theChat->user(),
			pl,
			message,
			KopeteMessage::Outbound,
			KopeteMessage::RichText );
	theChat->messageSent( msg );
}
void NowListeningPlugin::slotSettingsChanged()
{
	m_pollTimer->start( m_prefs->pollFrequency() * 1000 );
}

#include "nowlisteningplugin.moc"

// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|>


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

#ifndef _TOOLKIT_HELPER_UNOPROPERTYARRAYHELPER_HXX_
#define _TOOLKIT_HELPER_UNOPROPERTYARRAYHELPER_HXX_

#include <cppuhelper/propshlp.hxx>

#include <tools/table.hxx>

//  ----------------------------------------------------
//  class UnoPropertyArrayHelper
//  ----------------------------------------------------
class UnoPropertyArrayHelper : public ::cppu::IPropertyArrayHelper
{
private:
    Table       maIDs;

protected:
    sal_Bool    ImplHasProperty( sal_uInt16 nPropId ) const;

public:
                UnoPropertyArrayHelper( const ::com::sun::star::uno::Sequence<sal_Int32>& rIDs );

    // ::cppu::IPropertyArrayHelper
    sal_Bool SAL_CALL fillPropertyMembersByHandle( ::rtl::OUString * pPropName, sal_Int16 * pAttributes, sal_Int32 nHandle );
    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > SAL_CALL getProperties();
    ::com::sun::star::beans::Property SAL_CALL getPropertyByName(const ::rtl::OUString& rPropertyName) throw (::com::sun::star::beans::UnknownPropertyException);
    sal_Bool SAL_CALL hasPropertyByName(const ::rtl::OUString& rPropertyName);
    sal_Int32 SAL_CALL getHandleByName( const ::rtl::OUString & rPropertyName );
    sal_Int32 SAL_CALL fillHandles( sal_Int32* pHandles, const ::com::sun::star::uno::Sequence< ::rtl::OUString > & rPropNames );
};

#endif // _TOOLKIT_HELPER_UNOPROPERTYARRAYHELPER_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.208); FILE MERGED 2005/09/05 16:57:51 rt 1.2.208.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: unopropertyarrayhelper.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 12:59:45 $
 *
 *  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 _TOOLKIT_HELPER_UNOPROPERTYARRAYHELPER_HXX_
#define _TOOLKIT_HELPER_UNOPROPERTYARRAYHELPER_HXX_

#include <cppuhelper/propshlp.hxx>

#include <tools/table.hxx>

//  ----------------------------------------------------
//  class UnoPropertyArrayHelper
//  ----------------------------------------------------
class UnoPropertyArrayHelper : public ::cppu::IPropertyArrayHelper
{
private:
    Table       maIDs;

protected:
    sal_Bool    ImplHasProperty( sal_uInt16 nPropId ) const;

public:
                UnoPropertyArrayHelper( const ::com::sun::star::uno::Sequence<sal_Int32>& rIDs );

    // ::cppu::IPropertyArrayHelper
    sal_Bool SAL_CALL fillPropertyMembersByHandle( ::rtl::OUString * pPropName, sal_Int16 * pAttributes, sal_Int32 nHandle );
    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > SAL_CALL getProperties();
    ::com::sun::star::beans::Property SAL_CALL getPropertyByName(const ::rtl::OUString& rPropertyName) throw (::com::sun::star::beans::UnknownPropertyException);
    sal_Bool SAL_CALL hasPropertyByName(const ::rtl::OUString& rPropertyName);
    sal_Int32 SAL_CALL getHandleByName( const ::rtl::OUString & rPropertyName );
    sal_Int32 SAL_CALL fillHandles( sal_Int32* pHandles, const ::com::sun::star::uno::Sequence< ::rtl::OUString > & rPropNames );
};

#endif // _TOOLKIT_HELPER_UNOPROPERTYARRAYHELPER_HXX_

<|endoftext|>


<commit_before>/*
 * Copyright © 2011 Intel Corporation
 *
 * 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 (including the next
 * paragraph) 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 "brw_vec4.h"
#include "../glsl/ir_print_visitor.h"

using namespace brw;

namespace brw {

static void
assign(int *reg_hw_locations, reg *reg)
{
   if (reg->file == GRF) {
      reg->reg = reg_hw_locations[reg->reg];
   }
}

void
vec4_visitor::reg_allocate_trivial()
{
   int hw_reg_mapping[this->virtual_grf_count];
   bool virtual_grf_used[this->virtual_grf_count];
   int i;
   int next;

   /* Calculate which virtual GRFs are actually in use after whatever
    * optimization passes have occurred.
    */
   for (int i = 0; i < this->virtual_grf_count; i++) {
      virtual_grf_used[i] = false;
   }

   foreach_iter(exec_list_iterator, iter, this->instructions) {
      vec4_instruction *inst = (vec4_instruction *)iter.get();

      if (inst->dst.file == GRF)
	 virtual_grf_used[inst->dst.reg] = true;

      for (int i = 0; i < 3; i++) {
	 if (inst->src[i].file == GRF)
	    virtual_grf_used[inst->src[i].reg] = true;
      }
   }

   /* Note that compressed instructions require alignment to 2 registers. */
   hw_reg_mapping[0] = this->first_non_payload_grf;
   next = hw_reg_mapping[0] + this->virtual_grf_sizes[0];
   for (i = 1; i < this->virtual_grf_count; i++) {
      if (virtual_grf_used[i]) {
	 hw_reg_mapping[i] = next;
	 next += this->virtual_grf_sizes[i];
      }
   }
   prog_data->total_grf = next;

   foreach_iter(exec_list_iterator, iter, this->instructions) {
      vec4_instruction *inst = (vec4_instruction *)iter.get();

      assign(hw_reg_mapping, &inst->dst);
      assign(hw_reg_mapping, &inst->src[0]);
      assign(hw_reg_mapping, &inst->src[1]);
      assign(hw_reg_mapping, &inst->src[2]);
   }

   if (prog_data->total_grf > BRW_MAX_GRF) {
      fail("Ran out of regs on trivial allocator (%d/%d)\n",
	   prog_data->total_grf, BRW_MAX_GRF);
   }
}

void
vec4_visitor::reg_allocate()
{
   reg_allocate_trivial();
}

} /* namespace brw */
<commit_msg>i965/vs: Remove stale comment about compressed instructions.<commit_after>/*
 * Copyright © 2011 Intel Corporation
 *
 * 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 (including the next
 * paragraph) 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 "brw_vec4.h"
#include "../glsl/ir_print_visitor.h"

using namespace brw;

namespace brw {

static void
assign(int *reg_hw_locations, reg *reg)
{
   if (reg->file == GRF) {
      reg->reg = reg_hw_locations[reg->reg];
   }
}

void
vec4_visitor::reg_allocate_trivial()
{
   int hw_reg_mapping[this->virtual_grf_count];
   bool virtual_grf_used[this->virtual_grf_count];
   int i;
   int next;

   /* Calculate which virtual GRFs are actually in use after whatever
    * optimization passes have occurred.
    */
   for (int i = 0; i < this->virtual_grf_count; i++) {
      virtual_grf_used[i] = false;
   }

   foreach_iter(exec_list_iterator, iter, this->instructions) {
      vec4_instruction *inst = (vec4_instruction *)iter.get();

      if (inst->dst.file == GRF)
	 virtual_grf_used[inst->dst.reg] = true;

      for (int i = 0; i < 3; i++) {
	 if (inst->src[i].file == GRF)
	    virtual_grf_used[inst->src[i].reg] = true;
      }
   }

   hw_reg_mapping[0] = this->first_non_payload_grf;
   next = hw_reg_mapping[0] + this->virtual_grf_sizes[0];
   for (i = 1; i < this->virtual_grf_count; i++) {
      if (virtual_grf_used[i]) {
	 hw_reg_mapping[i] = next;
	 next += this->virtual_grf_sizes[i];
      }
   }
   prog_data->total_grf = next;

   foreach_iter(exec_list_iterator, iter, this->instructions) {
      vec4_instruction *inst = (vec4_instruction *)iter.get();

      assign(hw_reg_mapping, &inst->dst);
      assign(hw_reg_mapping, &inst->src[0]);
      assign(hw_reg_mapping, &inst->src[1]);
      assign(hw_reg_mapping, &inst->src[2]);
   }

   if (prog_data->total_grf > BRW_MAX_GRF) {
      fail("Ran out of regs on trivial allocator (%d/%d)\n",
	   prog_data->total_grf, BRW_MAX_GRF);
   }
}

void
vec4_visitor::reg_allocate()
{
   reg_allocate_trivial();
}

} /* namespace brw */
<|endoftext|>


<commit_before>#include <QToolButton>
#include <QLabel>

#include "search-bar.h"

namespace {

const int kMarginRightSearchBar = 16;
const int kMarginBottom = 5;
const int kHMargin = 10;

} // namespace

SearchBar::SearchBar(QWidget *parent)
    : QLineEdit(parent)
{
    setObjectName("mSearchBar");

    // This property was introduced in Qt 5.2.
#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))
    setClearButtonEnabled(false);
#endif
#ifdef Q_OS_MAC
    setAttribute(Qt::WA_MacShowFocusRect, 0);
#endif

    placeholder_label_ = new QLabel(this);

    clear_button_ = new QToolButton(this);
    QIcon icon(":/images/cancel.png");
    clear_button_size_ = 12;
    clear_button_->setIcon(icon);
    clear_button_->setIconSize(QSize(clear_button_size_, clear_button_size_));
    clear_button_->setCursor(Qt::ArrowCursor);
    clear_button_->setStyleSheet("QToolButton { border: 0px; }");
    clear_button_->hide();
    connect(clear_button_, SIGNAL(clicked()),
            this, SLOT(clear()));

    connect(this, SIGNAL(textChanged(const QString&)),
            this, SLOT(onTextChanged(const QString&)));

    const QString style = QString(" QLineEdit#mSearchBar { "
                                      " padding-right: %1px; "
                                      " padding-left: %2px; } " )
                                  .arg(clear_button_size_ + kHMargin)
                                  .arg(kHMargin);
    setStyleSheet(style);
}

void SearchBar::paintEvent(QPaintEvent* event)
{
    QLineEdit::paintEvent(event);
}

void SearchBar::resizeEvent(QResizeEvent* event)
{
    clear_button_->move(rect().right() - kMarginRightSearchBar
                        - kHMargin - clear_button_size_ - 2,
                        (rect().bottom() - clear_button_size_) / 2);
    int label_height = placeholder_label_->height();
    int label_width = placeholder_label_->width();
    placeholder_label_->move((rect().right() - label_width) / 2,
                             (rect().bottom()  -  label_height) / 2);
}

void SearchBar::onTextChanged(const QString& text)
{
    clear_button_->setVisible(!text.isEmpty());
    placeholder_label_->setVisible(text.isEmpty());
}

void SearchBar::setPlaceholderText(const QString& text)
{
    placeholder_label_->setText(text);
    placeholder_label_->setStyleSheet("QLabel { font-size: 13px;"
                                              " color: #AAAAAA; }");
    placeholder_label_->show();
}
<commit_msg>Adjust the search bar view (#1070)<commit_after>#include <QToolButton>
#include <QLabel>

#include "search-bar.h"

namespace {

const int kMarginRightSearchBar = 16;
const int kMarginBottom = 5;
const int kHMargin = 10;

} // namespace

SearchBar::SearchBar(QWidget *parent)
    : QLineEdit(parent)
{
    setObjectName("mSearchBar");

    // This property was introduced in Qt 5.2.
#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))
    setClearButtonEnabled(false);
#endif
#ifdef Q_OS_MAC
    setAttribute(Qt::WA_MacShowFocusRect, 0);
#endif

    placeholder_label_ = new QLabel(this);

    clear_button_ = new QToolButton(this);
    QIcon icon(":/images/cancel.png");
    clear_button_size_ = 12;
    clear_button_->setIcon(icon);
    clear_button_->setIconSize(QSize(clear_button_size_, clear_button_size_));
    clear_button_->setCursor(Qt::ArrowCursor);
    clear_button_->setStyleSheet("QToolButton { border: 0px; }");
    clear_button_->hide();
    connect(clear_button_, SIGNAL(clicked()),
            this, SLOT(clear()));

    connect(this, SIGNAL(textChanged(const QString&)),
            this, SLOT(onTextChanged(const QString&)));

    const QString style = QString(" QLineEdit#mSearchBar { "
                                      " padding-right: %1px; "
                                      " padding-left: %2px; } " )
                                  .arg(clear_button_size_ + kHMargin)
                                  .arg(kHMargin);
    setStyleSheet(style);
}

void SearchBar::paintEvent(QPaintEvent* event)
{
    QLineEdit::paintEvent(event);
}

void SearchBar::resizeEvent(QResizeEvent* event)
{
    clear_button_->move(rect().right() - kMarginRightSearchBar
                        - kHMargin - clear_button_size_ - 12,
                        (rect().bottom() - clear_button_size_) / 2);
    int label_height = placeholder_label_->height();
    int label_width = placeholder_label_->width();
    placeholder_label_->move((rect().right() - label_width) / 2,
                             (rect().bottom()  -  label_height) / 2);
}

void SearchBar::onTextChanged(const QString& text)
{
    clear_button_->setVisible(!text.isEmpty());
    placeholder_label_->setVisible(text.isEmpty());
}

void SearchBar::setPlaceholderText(const QString& text)
{
    placeholder_label_->setText(text);
    placeholder_label_->setStyleSheet("QLabel { font-size: 13px;"
                                              " color: #AAAAAA; }");
    placeholder_label_->show();
}
<|endoftext|>


<commit_before>/****************************************************************
    2次元、30×30のライフゲーム

    フィールドの上下左右はつながっている(ドラクエふう)
*****************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include <unistd.h>
#include <iostream>
using namespace std;

int field[32][32];        /*0-死 1-生*/
int next_field[32][32];
//int old_field[32][32]; いらない疑惑
//char command,line[10];

int get_random(int min,int max); /*minからmaxまでの乱数を返す関数*/
int get_sum(int x,int y); /*周囲8セルの合計を返す関数*/
void init_field(int init_living_pct); /*フィールドの初期化*/
void print_field(void); /*フィールドの初期化*/
void copy_border_cells(void); /*左右と上下のデータをコピー*/
int count_changes(void); /*変わったセルの数*/
int sweep(void); /*生き死にを変える*/
void update(void); /*バッファをコピー*/

int get_random(int min,int max) /*minからmaxまでの乱数を返す関数*/
{
	static bool flag;
	if(flag){
		srand( (unsigned int) time (NULL) );
		flag = false;
	}

	return min + (int)( rand()*(max - min + 1.0)/(1.0 + RAND_MAX) );
}

int get_sum(int x,int y)/*周囲8セルの合計を返す関数*/
{
	return field[x-1][y-1] + field[x-1][y] + field[x-1][y+1]
		+field[x][y-1] + field[x][y+1]
		+ field[x+1][y-1] + field[x+1][y] + field[x+1][y+1];
}

void init_field(int init_living_pct)
{
	for(int i=1;i<31;++i){
		for(int ii=1;ii<31;++ii){
			if(get_random(1,100) <= init_living_pct)
				field[i][ii] = 1;
			else
				field[i][ii] = 0;
		}
	}
}

void print_field(int generation)
{
	system("clear");
	for(int i=1;i<31;++i){
		for(int ii=1;ii<31;++ii){
			if(field[ii][i] == 1)
				cout << " O";
			else
				cout << "  ";
		}
		cout << endl;
	}
	cout << generation << "世代" << endl;
}

void copy_border_cells(void)
{
	for(int i=1;i<31;++i){
		field[0][i]=field[30][i];
		field[31][i]=field[1][i];

		field[i][0]=field[i][30];
		field[i][31]=field[i][1];
	}
	field[0][0]=field[30][30];
	field[0][31]=field[30][1];
	field[31][0]=field[1][30];
	field[31][31]=field[1][1];
}

int count_changes(void)
{
	int c = 0;
	for(int i=1;i<31;++i)
		for(int ii=1;ii<31;++ii)
			//if(old_field[i][ii] != next_field[i][ii])
			if(field[i][ii] != next_field[i][ii])
				++c;

	return c;
}

int sweep(void)
{
	for(int i=1;i<31;++i){
		for(int ii=1;ii<31;++ii){
			if(field[i][ii] == 0){/*セルが死んでいる場合*/
				if( get_sum(i,ii) == 3)
    					next_field[i][ii] = 1;
				else
					next_field[i][ii] = 0;
			}else{ /*セルが生きている場合*/
				if( get_sum(i,ii) == 2 || get_sum(i,ii) == 3)
					next_field[i][ii] = 1;
				else
					next_field[i][ii] = 0;
			}
		}
	}

	return count_changes();
}

void update(void)
{
	/*fieldをnext_fieldで更新*/
	for(int i=1;i<31;++i)
		for(int ii=1;ii<31;++ii)
			field[i][ii] = next_field[i][ii];
}

int main(int argc, char const* argv[])
{
	int generation = 0;
	/*初期配置の決定*/
	int init_living_percentage; /*初期配置における生きたセルのパーセンテージ*/
	cout << "生きたセルは何パーセント? (整数で):" << endl;
	cin >> init_living_percentage;
	init_field(init_living_percentage);

	/*以下を繰り返す*/
	//int change = 0;
	while(1){
		/*現在のfieldを画面に出力*/
		usleep(200*1000);
		print_field(generation);

		copy_border_cells();
		if (sweep() == 0)
			break;

		++generation;
		update();

/* ここら辺、来ないような気がするのでコメントアウト（by 上田）
		change = count_changes();

		if (change == 0){
			++cnt;
			cout << "loop" << endl;
		}
		if (cnt >= 10)
			break;

		change = 0;
*/
	}
	exit(0);
}
<commit_msg>Refactor some parts<commit_after>/****************************************************************
    2次元、30×30のライフゲーム

    フィールドの上下左右はつながっている(ドラクエふう)
*****************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include <unistd.h>
#include <iostream>
using namespace std;

int field[32][32];        /*0-死 1-生*/
int next_field[32][32];
//int old_field[32][32]; いらない疑惑
//char command,line[10];

int get_random(int min,int max); /*minからmaxまでの乱数を返す関数*/
int get_sum(int x,int y); /*周囲8セルの合計を返す関数*/
void init_field(int init_living_pct); /*フィールドの初期化*/
void print_field(void); /*フィールドの初期化*/
void copy_border_cells(void); /*左右と上下のデータをコピー*/
int count_changes(void); /*変わったセルの数*/
int sweep(void); /*生き死にを変える*/
void update(void); /*バッファをコピー*/

int get_random(int min,int max) /*minからmaxまでの乱数を返す関数*/
{
	static bool flag;
	if(flag){
		srand( (unsigned int) time (NULL) );
		flag = false;
	}

	return min + (int)( rand()*(max - min + 1.0)/(1.0 + RAND_MAX) );
}

int get_sum(int x,int y)/*周囲8セルの合計を返す関数*/
{
	return field[x-1][y-1] + field[x-1][y] + field[x-1][y+1]
		+field[x][y-1] + field[x][y+1]
		+ field[x+1][y-1] + field[x+1][y] + field[x+1][y+1];
}

void init_field(int init_living_pct)
{
	for(int i=1;i<31;++i){
		for(int ii=1;ii<31;++ii){
			if(get_random(1,100) <= init_living_pct)
				field[i][ii] = 1;
			else
				field[i][ii] = 0;
		}
	}
	copy_border_cells();
}

void print_field(int generation)
{
	system("clear");
	for(int i=1;i<31;++i){
		for(int ii=1;ii<31;++ii){
			if(field[ii][i] == 1)
				cout << " O";
			else
				cout << "  ";
		}
		cout << endl;
	}
	cout << generation << "世代" << endl;
}

void copy_border_cells(void)
{
	for(int i=1;i<31;++i){
		field[0][i]=field[30][i];
		field[31][i]=field[1][i];

		field[i][0]=field[i][30];
		field[i][31]=field[i][1];
	}
	field[0][0]=field[30][30];
	field[0][31]=field[30][1];
	field[31][0]=field[1][30];
	field[31][31]=field[1][1];
}

int count_changes(void)
{
	int c = 0;
	for(int i=1;i<31;++i)
		for(int ii=1;ii<31;++ii)
			//if(old_field[i][ii] != next_field[i][ii])
			if(field[i][ii] != next_field[i][ii])
				++c;

	return c;
}

int sweep(void)
{
	for(int i=1;i<31;++i){
		for(int ii=1;ii<31;++ii){
			if(field[i][ii] == 0){/*セルが死んでいる場合*/
				if( get_sum(i,ii) == 3)
    					next_field[i][ii] = 1;
				else
					next_field[i][ii] = 0;
			}else{ /*セルが生きている場合*/
				if( get_sum(i,ii) == 2 || get_sum(i,ii) == 3)
					next_field[i][ii] = 1;
				else
					next_field[i][ii] = 0;
			}
		}
	}

	return count_changes();
}

void update(void)
{
	/*fieldをnext_fieldで更新*/
	for(int i=1;i<31;++i)
		for(int ii=1;ii<31;++ii)
			field[i][ii] = next_field[i][ii];

	copy_border_cells();
}

int main(int argc, char const* argv[])
{
	int p; /*初期配置における生きたセルのパーセンテージ*/
	cout << "生きたセルは何パーセント? (整数で):" << endl;
	cin >> p;
	init_field(p);

	int generation = 0;
	print_field(generation);

	while(sweep()){
		++generation;

		update();
		print_field(generation);
		usleep(200*1000);

/* ここら辺、来ないような気がするのでコメントアウト（by 上田）
		change = count_changes();

		if (change == 0){
			++cnt;
			cout << "loop" << endl;
		}
		if (cnt >= 10)
			break;

		change = 0;
*/
	}
	exit(0);
}
<|endoftext|>


<commit_before>#pragma once
#ifndef LIGHTPTR_HPP
# define LIGHTPTR_HPP

#include <cassert>

#include <atomic>

#include <memory>

#include <type_traits>

namespace detail
{
  template <typename T>
  struct remove_array
  {
    using type = T;
  };

  template <typename T>
  struct remove_array<T[]>
  {
    using type = T;
  };
}

template <typename T,
  class D = typename std::default_delete<T> >
struct light_ptr
{
  using counter_type = std::size_t;

  light_ptr() = default;

  explicit light_ptr(typename ::detail::remove_array<T>::type* const p) :
    counter_ptr_(new atomic_type(counter_type(1))),
    ptr_(p)
  {
  }

  ~light_ptr() { dec_ref(); }

  light_ptr(light_ptr const& other) noexcept { *this = other; }

  light_ptr(light_ptr&& other) noexcept { *this = std::move(other); }

  light_ptr& operator=(light_ptr const& other)
  {
    if (*this != other)
    {
      dec_ref();

      if ((counter_ptr_ = other.counter_ptr_))
      {
        ptr_ = other.ptr_;

        inc_ref();
      }
      // else do nothing
    }
    // else do nothing

    return *this;
  }

  light_ptr& operator=(light_ptr&& rhs) noexcept
  {
    counter_ptr_ = rhs.counter_ptr_;
    ptr_ = rhs.ptr_;

    rhs.counter_ptr_ = nullptr;

    return *this;
  }

  bool operator==(light_ptr const& rhs) const noexcept
  {
    return counter_ptr_ == rhs.counter_ptr_;
  }

  bool operator!=(light_ptr const& rhs) const noexcept
  {
    return !operator==(rhs);
  }

  explicit operator bool() const noexcept { return counter_ptr_; }

  T& operator*() const noexcept { return *ptr_; }

  T* operator->() const noexcept { return ptr_; }

  T* get() const noexcept { return counter_ptr_ ? ptr_ : nullptr; }

  void reset(T* const p = nullptr)
  {
    dec_ref();

    if (p)
    {
      counter_ptr_ = new atomic_type(counter_type(1));

      ptr_ = p;
    }
    else
    {
      counter_ptr_ = nullptr;
    }
    // else do nothing
  }

  bool unique() const noexcept { return counter_type(1) == use_count(); }

  counter_type use_count() const noexcept
  {
    return counter_ptr_ ? counter_ptr_->load() : counter_type{};
  }

private:
  void dec_ref()
  {
    using deleter_type = D;

    if (counter_ptr_ && *counter_ptr_ && !--*counter_ptr_)
    {
      deleter_type()(ptr_);

      delete counter_ptr_;
    }
    // else do nothing
  }

  void inc_ref() noexcept
  {
    assert(ptr_);
    assert(counter_ptr_);
    ++*counter_ptr_;
  }

private:
  using atomic_type = std::atomic<counter_type>;

  atomic_type* counter_ptr_{};

  typename ::detail::remove_array<T>::type* ptr_;
};

#endif // LIGHTPTR_HPP
<commit_msg>shared ptr added<commit_after>#pragma once
#ifndef LIGHTPTR_HPP
# define LIGHTPTR_HPP

#include <cassert>

#include <atomic>

#include <memory>

#include <type_traits>

namespace detail
{
  template <typename T>
  struct remove_array
  {
    using type = T;
  };

  template <typename T>
  struct remove_array<T[]>
  {
    using type = T;
  };
}

template <typename T,
  class D = typename std::default_delete<T> >
struct light_ptr
{
  using counter_type = std::size_t;

  light_ptr() = default;

  explicit light_ptr(typename ::detail::remove_array<T>::type* const p) :
    counter_ptr_(new atomic_type(counter_type(1))),
    ptr_(p)
  {
  }

  ~light_ptr() { dec_ref(); }

  light_ptr(light_ptr const& other) { *this = other; }

  light_ptr(light_ptr&& other) noexcept { *this = std::move(other); }

  light_ptr& operator=(light_ptr const& other)
  {
    if (*this != other)
    {
      dec_ref();

      if ((counter_ptr_ = other.counter_ptr_))
      {
        ptr_ = other.ptr_;

        inc_ref();
      }
      // else do nothing
    }
    // else do nothing

    return *this;
  }

  light_ptr& operator=(light_ptr&& rhs) noexcept
  {
    counter_ptr_ = rhs.counter_ptr_;
    ptr_ = rhs.ptr_;

    rhs.counter_ptr_ = nullptr;

    return *this;
  }

  bool operator==(light_ptr const& rhs) const noexcept
  {
    return counter_ptr_ == rhs.counter_ptr_;
  }

  bool operator!=(light_ptr const& rhs) const noexcept
  {
    return !operator==(rhs);
  }

  explicit operator bool() const noexcept { return counter_ptr_; }

  T& operator*() const noexcept { return *ptr_; }

  T* operator->() const noexcept { return ptr_; }

  T* get() const noexcept { return counter_ptr_ ? ptr_ : nullptr; }

  void reset(T* const p = nullptr)
  {
    dec_ref();

    if (p)
    {
      counter_ptr_ = new atomic_type(counter_type(1));

      ptr_ = p;
    }
    else
    {
      counter_ptr_ = nullptr;
    }
    // else do nothing
  }

  bool unique() const noexcept { return counter_type(1) == use_count(); }

  counter_type use_count() const noexcept
  {
    return counter_ptr_ ? counter_ptr_->load() : counter_type{};
  }

private:
  void dec_ref()
  {
    using deleter_type = D;

    if (counter_ptr_ && *counter_ptr_ && !--*counter_ptr_)
    {
      deleter_type()(ptr_);

      delete counter_ptr_;
    }
    // else do nothing
  }

  void inc_ref() noexcept
  {
    assert(ptr_);
    assert(counter_ptr_);
    ++*counter_ptr_;
  }

private:
  using atomic_type = std::atomic<counter_type>;

  atomic_type* counter_ptr_{};

  typename ::detail::remove_array<T>::type* ptr_;
};

#endif // LIGHTPTR_HPP
<|endoftext|>


<commit_before>#pragma once
#ifndef LIGHTPTR_HPP
# define LIGHTPTR_HPP

#include <cassert>

#include <atomic>

#include <memory>

#include <utility>

#include <type_traits>

namespace generic
{

namespace detail
{
  using counter_type = unsigned;

  using atomic_type = ::std::atomic<counter_type>;

  template <typename T>
  using deleter_type = void (*)(T*);

  template <typename U>
  struct ref_type
  {
    using type = U&;
  };

  template <>
  struct ref_type<void>
  {
    using type = void;
  };
}

template <typename T>
struct light_ptr
{
  template <typename U, typename V>
  struct deletion_type
  {
    using type = V;
  };

  template <typename U, typename V>
  struct deletion_type<U[], V>
  {
    using type = V[];
  };

  template <typename U, typename V, ::std::size_t N>
  struct deletion_type<U[N], V>
  {
    using type = V[];
  };

  template <typename U>
  struct remove_array
  {
    using type = U;
  };

  template <typename U>
  struct remove_array<U[]>
  {
    using type = U;
  };

  template <typename U, ::std::size_t N>
  struct remove_array<U[N]>
  {
    using type = U;
  };

  using element_type = typename remove_array<T>::type;

  using deleter_type = detail::deleter_type<element_type>;

  struct counter_base
  {
    using invoker_type = void (*)(counter_base*, element_type*);

    explicit counter_base(detail::counter_type c,
      invoker_type invoker) noexcept :
      counter_(c),
      invoker_(invoker)
    {
    }

    template <typename U>
    typename ::std::enable_if<!::std::is_void<U>{}>::type
    dec_ref(U* const ptr)
    {
      if (detail::counter_type(1) ==
        counter_.fetch_sub(detail::counter_type(1),
          ::std::memory_order_relaxed))
      {
        typedef char type_must_be_complete[sizeof(U) ? 1 : -1];
        (void)sizeof(type_must_be_complete);
        invoker_(this, ptr);
      }
      // else do nothing
    }

    template <typename U>
    typename ::std::enable_if<::std::is_void<U>{}>::type
    dec_ref(U* const ptr)
    {
      if (detail::counter_type(1) ==
        counter_.fetch_sub(detail::counter_type(1),
          ::std::memory_order_relaxed))
      {
        invoker_(this, ptr);
      }
      // else do nothing
    }

    void inc_ref() noexcept
    {
      //assert(counter_ptr);
      counter_.fetch_add(detail::counter_type(1),
        ::std::memory_order_relaxed);
    }

    detail::atomic_type counter_{};

    invoker_type invoker_;
  };

  template <typename U>
  struct counter : counter_base
  {
    explicit counter(detail::counter_type const c, U&& d) noexcept :
      counter_base(c, invoker),
      d_(::std::forward<U>(d))
    {
    }

  private:
    static void invoker(counter_base* const ptr, element_type* e)
    {
      auto const c(static_cast<counter<U>*>(ptr));

      typename ::std::decay<U>::type const d(::std::move(c->d_));

      delete c;

      d(e);
    }

  private:
    typename ::std::decay<U>::type d_;
  };

  light_ptr() = default;

  template <typename U>
  static void default_deleter(element_type* const p)
  {
    ::std::default_delete<typename deletion_type<T, U>::type>()(
      static_cast<U*>(p));
  }

  template <typename U, typename D = decltype(&default_deleter<U>)>
  explicit light_ptr(U* p, D&& d = default_deleter<U>)
  {
    reset(p, ::std::forward<D>(d));
  }

  ~light_ptr()
  {
    if (counter_)
    {
      counter_->dec_ref(ptr_);
    }
    // else do nothing
  }

  light_ptr(light_ptr const& other) { *this = other; }

  light_ptr(light_ptr&& other) noexcept { *this = ::std::move(other); }

  light_ptr& operator=(light_ptr const& rhs)
  {
    if (*this != rhs)
    {
      if (counter_)
      {
        counter_->dec_ref(ptr_);
      }
      // else do nothing

      counter_ = rhs.counter_;
      ptr_ = rhs.ptr_;

      if (counter_)
      {
        counter_->inc_ref();
      }
      // else do nothing
    }
    // else do nothing

    return *this;
  }

  light_ptr& operator=(light_ptr&& rhs) noexcept
  {
    counter_ = rhs.counter_;
    ptr_ = rhs.ptr_;

    rhs.counter_ = nullptr;
    rhs.ptr_ = nullptr;

    return *this;
  }

  light_ptr& operator=(::std::nullptr_t const) noexcept { reset(); }

  bool operator<(light_ptr const& rhs) const noexcept
  {
    return get() < rhs.get();
  }

  bool operator==(light_ptr const& rhs) const noexcept
  {
    return counter_ == rhs.counter_;
  }

  bool operator!=(light_ptr const& rhs) const noexcept
  {
    return !operator==(rhs);
  }

  bool operator==(::std::nullptr_t const) const noexcept
  {
    return !ptr_;
  }

  bool operator!=(::std::nullptr_t const) const noexcept
  {
    return ptr_;
  }

  explicit operator bool() const noexcept { return ptr_; }

  typename detail::ref_type<T>::type
  operator*() const noexcept
  {
    return *static_cast<T*>(static_cast<void*>(ptr_));
  }

  T* operator->() const noexcept
  {
    return static_cast<T*>(static_cast<void*>(ptr_));
  }

  element_type* get() const noexcept { return ptr_; }

  void reset() { reset(nullptr); }

  void reset(::std::nullptr_t const)
  {
    if (counter_)
    {
      counter_->dec_ref(ptr_);

      counter_ = {};
    }
    // else do nothing

    ptr_ = {};
  }

  template <typename U, typename D = decltype(&default_deleter<U>)>
  void reset(U* const p, D&& d = default_deleter<U>)
  {
    if (counter_)
    {
      counter_->dec_ref(ptr_);
    }
    // else do nothing

    counter_ = new counter<D>(detail::counter_type(1), ::std::forward<D>(d));

    ptr_ = p;
  }

  void swap(light_ptr& other) noexcept
  {
    ::std::swap(counter_, other.counter_);
    ::std::swap(ptr_, other.ptr_);
  }

  bool unique() const noexcept
  {
    return detail::counter_type(1) == use_count();
  }

  detail::counter_type use_count() const noexcept
  {
    return counter_ ?
      counter_->counter_.load(::std::memory_order_relaxed) :
      detail::counter_type{};
  }

private:
  counter_base* counter_{};

  element_type* ptr_{};
};

template<class T, class ...Args>
inline light_ptr<T> make_light(Args&& ...args)
{
  return light_ptr<T>(new T(::std::forward<Args>(args)...));
}

}

namespace std
{
  template <typename T>
  struct hash<::generic::light_ptr<T> >
  {
    size_t operator()(::generic::light_ptr<T> const& l) const noexcept
    {
      return hash<typename ::generic::light_ptr<T>::element_type*>()(l.get());
    }
  };
}

#endif // LIGHTPTR_HPP
<commit_msg>some fixes<commit_after>#pragma once
#ifndef LIGHTPTR_HPP
# define LIGHTPTR_HPP

#include <cassert>

#include <atomic>

#include <memory>

#include <utility>

#include <type_traits>

namespace generic
{

namespace detail
{
  using counter_type = unsigned;

  using atomic_type = ::std::atomic<counter_type>;

  template <typename T>
  using deleter_type = void (*)(T*);

  template <typename U>
  struct ref_type
  {
    using type = U&;
  };

  template <>
  struct ref_type<void>
  {
    using type = void;
  };
}

template <typename T>
struct light_ptr
{
  template <typename U, typename V>
  struct deletion_type
  {
    using type = V;
  };

  template <typename U, typename V>
  struct deletion_type<U[], V>
  {
    using type = V[];
  };

  template <typename U, typename V, ::std::size_t N>
  struct deletion_type<U[N], V>
  {
    using type = V[];
  };

  template <typename U>
  struct remove_array
  {
    using type = U;
  };

  template <typename U>
  struct remove_array<U[]>
  {
    using type = U;
  };

  template <typename U, ::std::size_t N>
  struct remove_array<U[N]>
  {
    using type = U;
  };

  using element_type = typename remove_array<T>::type;

  using deleter_type = detail::deleter_type<element_type>;

  struct counter_base
  {
    using invoker_type = void (*)(counter_base*, element_type*);

    explicit counter_base(detail::counter_type c,
      invoker_type invoker) noexcept :
      counter_(c),
      invoker_(invoker)
    {
    }

    template <typename U>
    typename ::std::enable_if<!::std::is_void<U>{}>::type
    dec_ref(U* const ptr)
    {
      if (detail::counter_type(1) ==
        counter_.fetch_sub(detail::counter_type(1),
          ::std::memory_order_relaxed))
      {
        typedef char type_must_be_complete[sizeof(U) ? 1 : -1];
        (void)sizeof(type_must_be_complete);
        invoker_(this, ptr);
      }
      // else do nothing
    }

    template <typename U>
    typename ::std::enable_if<::std::is_void<U>{}>::type
    dec_ref(U* const ptr)
    {
      if (detail::counter_type(1) ==
        counter_.fetch_sub(detail::counter_type(1),
          ::std::memory_order_relaxed))
      {
        invoker_(this, ptr);
      }
      // else do nothing
    }

    void inc_ref() noexcept
    {
      //assert(counter_ptr);
      counter_.fetch_add(detail::counter_type(1),
        ::std::memory_order_relaxed);
    }

    detail::atomic_type counter_{};

    invoker_type invoker_;
  };

  template <typename U>
  struct counter : counter_base
  {
    explicit counter(detail::counter_type const c, U&& d) noexcept :
      counter_base(c, invoker),
      d_(::std::forward<U>(d))
    {
    }

  private:
    static void invoker(counter_base* const ptr, element_type* e)
    {
      auto const c(static_cast<counter<U>*>(ptr));

      typename ::std::decay<U>::type const d(::std::move(c->d_));

      delete c;

      d(e);
    }

  private:
    typename ::std::decay<U>::type d_;
  };

  light_ptr() = default;

  template <typename U>
  explicit light_ptr(U* p)
  {
    reset(p, [](element_type* const p)
      {
        ::std::default_delete<typename deletion_type<T, U>::type>()(
          static_cast<U*>(p));
      });
  }

  template <typename U, typename D>
  explicit light_ptr(U* p, D&& d)
  {
    reset(p, ::std::forward<D>(d));
  }

  ~light_ptr()
  {
    if (counter_)
    {
      counter_->dec_ref(ptr_);
    }
    // else do nothing
  }

  light_ptr(light_ptr const& other) { *this = other; }

  light_ptr(light_ptr&& other) noexcept { *this = ::std::move(other); }

  light_ptr& operator=(light_ptr const& rhs)
  {
    if (*this != rhs)
    {
      if (counter_)
      {
        counter_->dec_ref(ptr_);
      }
      // else do nothing

      counter_ = rhs.counter_;
      ptr_ = rhs.ptr_;

      if (counter_)
      {
        counter_->inc_ref();
      }
      // else do nothing
    }
    // else do nothing

    return *this;
  }

  light_ptr& operator=(light_ptr&& rhs) noexcept
  {
    counter_ = rhs.counter_;
    ptr_ = rhs.ptr_;

    rhs.counter_ = nullptr;
    rhs.ptr_ = nullptr;

    return *this;
  }

  light_ptr& operator=(::std::nullptr_t const) noexcept { reset(); }

  bool operator<(light_ptr const& rhs) const noexcept
  {
    return get() < rhs.get();
  }

  bool operator==(light_ptr const& rhs) const noexcept
  {
    return counter_ == rhs.counter_;
  }

  bool operator!=(light_ptr const& rhs) const noexcept
  {
    return !operator==(rhs);
  }

  bool operator==(::std::nullptr_t const) const noexcept
  {
    return !ptr_;
  }

  bool operator!=(::std::nullptr_t const) const noexcept
  {
    return ptr_;
  }

  explicit operator bool() const noexcept { return ptr_; }

  typename detail::ref_type<T>::type
  operator*() const noexcept
  {
    return *static_cast<T*>(static_cast<void*>(ptr_));
  }

  T* operator->() const noexcept
  {
    return static_cast<T*>(static_cast<void*>(ptr_));
  }

  element_type* get() const noexcept { return ptr_; }

  void reset() { reset(nullptr); }

  void reset(::std::nullptr_t const)
  {
    if (counter_)
    {
      counter_->dec_ref(ptr_);

      counter_ = {};
    }
    // else do nothing

    ptr_ = {};
  }

  template <typename U>
  void reset(U* const p)
  {
    reset(detail::counter_type(1),
      [](element_type* const p) {
        ::std::default_delete<typename deletion_type<T, U>::type>()(
          static_cast<U*>(p));
      });
  }

  template <typename U, typename D>
  void reset(U* const p, D&& d)
  {
    if (counter_)
    {
      counter_->dec_ref(ptr_);
    }
    // else do nothing

    counter_ = new counter<D>(detail::counter_type(1), ::std::forward<D>(d));

    ptr_ = p;
  }

  void swap(light_ptr& other) noexcept
  {
    ::std::swap(counter_, other.counter_);
    ::std::swap(ptr_, other.ptr_);
  }

  bool unique() const noexcept
  {
    return detail::counter_type(1) == use_count();
  }

  detail::counter_type use_count() const noexcept
  {
    return counter_ ?
      counter_->counter_.load(::std::memory_order_relaxed) :
      detail::counter_type{};
  }

private:
  counter_base* counter_{};

  element_type* ptr_{};
};

template<class T, class ...Args>
inline light_ptr<T> make_light(Args&& ...args)
{
  return light_ptr<T>(new T(::std::forward<Args>(args)...));
}

}

namespace std
{
  template <typename T>
  struct hash<::generic::light_ptr<T> >
  {
    size_t operator()(::generic::light_ptr<T> const& l) const noexcept
    {
      return hash<typename ::generic::light_ptr<T>::element_type*>()(l.get());
    }
  };
}

#endif // LIGHTPTR_HPP
<|endoftext|>


<commit_before>#ifndef __V_RAPID_MEDIA_HPP__
#define __V_RAPID_MEDIA_HPP__
#include "cppkit/os/ck_exports.h"
#include "utility/type.hpp"
#include "utility/videotype.hpp"

using namespace std;

typedef BOOL (*RMDataHandler)(void* pContext, VideoFrame& packet);
typedef BOOL (*RMRawVideoHandler)(void* pContext, RawFrame& packet);

class RapidMediaData;
class VE_LIBRARY_API RapidMedia
{
public:
	RapidMedia();
	~RapidMedia();
public:
	BOOL Init(BOOL bRealStream, string strUrl, string strUser,
				string strPass, BOOL bHWAccel = FALSE);
	BOOL PutData(VideoFrame& packet);
	void	SetDataHandler(RMDataHandler handle, void *pContext);
	void	SetRawDataHandler(RMRawVideoHandler handle, void *pContext);

	BOOL Start();
	BOOL Stop();

public:
	RapidMediaData * m_data;
};
#endif /* __V_RAPID_MEDIA_HPP__ */
<commit_msg>add raw interface<commit_after>#ifndef __V_RAPID_MEDIA_HPP__
#define __V_RAPID_MEDIA_HPP__
#include "cppkit/os/ck_exports.h"
#include "utility/type.hpp"
#include "utility/videotype.hpp"

using namespace std;

typedef BOOL (*RMDataHandler)(void* pContext, VideoFrame& packet);
typedef BOOL (*RMRawVideoHandler)(void* pContext, RawFrame& packet);

class RapidMediaData;
class VE_LIBRARY_API RapidMedia
{
public:
	RapidMedia();
	~RapidMedia();
public:
	BOOL Init(BOOL bRealStream, string strUrl, string strUser,
				string strPass, BOOL bHWAccel = FALSE);
	BOOL PutData(VideoFrame& packet);
	void	SetDataHandler(RMDataHandler handle, void *pContext);
	void	SetRawDataHandler(RMRawVideoHandler handle, void *pContext);

	BOOL Start();
	BOOL Stop();
	BOOL StartRaw();
	BOOL StopRaw();

public:
	RapidMediaData * m_data;
};
#endif /* __V_RAPID_MEDIA_HPP__ */
<|endoftext|>


<commit_before>/***************************************************************************
                          cryptographyplugin.cpp  -  description
                             -------------------
    begin                : jeu nov 14 2002
    copyright            : (C) 2002 by Olivier Goffart
    email                : ogoffart@tiscalinet.be
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include <kdebug.h>
#include <kaction.h>
#include <klocale.h>
#include <kgenericfactory.h>

#include "kopete.h"
#include "kopetemessage.h"
#include "kopetemetacontact.h"
#include "kopetemessagemanager.h"

#include "cryptographyplugin.h"
#include "cryptographypreferences.h"

#include "kgpginterface.h"

K_EXPORT_COMPONENT_FACTORY( kopete_cryptography, KGenericFactory<CryptographyPlugin> );

CryptographyPlugin::CryptographyPlugin( QObject *parent, const char *name,
	const QStringList &/*args*/ )
: KopetePlugin( parent, name ) ,
		m_cachedPass()
{
	if( !pluginStatic_ )
		pluginStatic_=this;

	//TODO: found a pixmap
	m_prefs = new CryptographyPreferences ( "kgpg", this );

	connect( kopeteapp, SIGNAL(aboutToDisplay(KopeteMessage&)),
		 SLOT(slotIncomingMessage(KopeteMessage&)) );
	connect( kopeteapp, SIGNAL(aboutToSend(KopeteMessage&)),
		 SLOT(slotOutgoingMessage(KopeteMessage&)) );

	m_collection=0l;
	m_currentMetaContact=0L;

}

CryptographyPlugin::~CryptographyPlugin()
{
	pluginStatic_ = 0L;
	delete m_collection;
}

CryptographyPlugin* CryptographyPlugin::plugin()
{
	return pluginStatic_ ;
}

CryptographyPlugin* CryptographyPlugin::pluginStatic_ = 0L;

QCString CryptographyPlugin::cachedPass()
{
	return pluginStatic_->m_cachedPass;
}

void CryptographyPlugin::setCachedPass(const QCString& p)
{
	pluginStatic_->m_cachedPass=p;
}

void CryptographyPlugin::init()
{
}

bool CryptographyPlugin::unload()
{
	return true;
}

bool CryptographyPlugin::serialize( KopeteMetaContact *metaContact,
			  QStringList &strList  ) const
{
	if ( !m_keyMap.contains( metaContact ) )
		return false;

	strList<<  m_keyMap[ metaContact ] ;
	return true;
}

void CryptographyPlugin::deserialize( KopeteMetaContact *metaContact, const QStringList& data )
{
	m_keyMap[ metaContact ] = data.first();
}

KActionCollection *CryptographyPlugin::customContextMenuActions(KopeteMetaContact *m)
{
	delete m_collection;

	m_collection = new KActionCollection(this);

	KAction *action=new KAction( i18n("&Select Cryptography public key"), "kgpg", 0, this, SLOT (slotSelectContactKey()), m_collection);

	m_collection->insert(action);
	m_currentMetaContact=m;
	return m_collection;
}

/*KActionCollection *CryptographyPlugin::customChatActions(KopeteMessageManager *KMM)
{
	delete m_actionCollection;

	m_actionCollection = new KActionCollection(this);
	KAction *actionTranslate = new KAction( i18n ("Translate"), 0,
		this, SLOT( slotTranslateChat() ), m_actionCollection, "actionTranslate" );
	m_actionCollection->insert( actionTranslate );

	m_currentMessageManager=KMM;
	return m_actionCollection;
}*/

void CryptographyPlugin::slotIncomingMessage( KopeteMessage& msg )
{
	if(msg.direction() != KopeteMessage::Inbound)
		return;
	QString body=msg.plainBody();
	if(!body.startsWith("-----BEGIN Cryptography MESSAGE----"))
		return;

	body=KgpgInterface::KgpgDecryptText(body, m_prefs->privateKey());

	if (body!="")
		msg.setBody(body,KopeteMessage::PlainText);
}

void CryptographyPlugin::slotOutgoingMessage( KopeteMessage& msg )
{
	if(msg.direction() != KopeteMessage::Outbound)
		return;
	if(msg.to().count()!=1)
	{
		kdDebug() << "CryptographyPlugin::slotOutgoingMessage: TODO: group chat not yet implemented" <<endl;
		return;
	}
	KopeteMetaContact *m=msg.to().first()->metaContact();

	if(!m_keyMap.contains(m))
	{
		kdDebug() << "CryptographyPlugin::slotOutgoingMessage: no key selected for this contact" <<endl;
		return;
	}

	/* Code From KGPG */

  //////////////////              encode from editor
  QString encryptOptions="";

  //if (utrust==true)
		encryptOptions+=" --always-trust ";
  //if (arm==true)
		encryptOptions+=" --armor ";

 /* if (pubcryptography==true)
   {
      if (gpgversion<120) encryptOptions+=" --compress-algo 1 --cipher-algo cast5 ";
      else encryptOptions+=" --cryptography6 ";
    }*/

// if (selec==NULL) {KMessageBox::sorry(0,i18n("You have not choosen an encryption key..."));return;}

	QString resultat=KgpgInterface::KgpgEncryptText(msg.plainBody(),m_keyMap[m],encryptOptions);
	if (resultat!="")
		msg.setBody(resultat,KopeteMessage::PlainText);
}

#include "popuppublic.h"

void CryptographyPlugin::slotSelectContactKey()
{
	popupPublic *dialogue=new popupPublic(0L/*this*/, "public_keys", 0,false);
	connect(dialogue,SIGNAL(selectedKey(QString &,bool,bool,bool,bool)),this,SLOT(setKey(QString &)));
	dialogue->exec();
	delete dialogue;
}

void CryptographyPlugin::setKey(QString &keyId)
{
	if(  m_currentMetaContact)
	{
		m_keyMap[ m_currentMetaContact ]= keyId;
	}
}

#include "cryptographyplugin.moc"

<commit_msg>oups, i commited to quickly<commit_after>/***************************************************************************
                          cryptographyplugin.cpp  -  description
                             -------------------
    begin                : jeu nov 14 2002
    copyright            : (C) 2002 by Olivier Goffart
    email                : ogoffart@tiscalinet.be
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include <kdebug.h>
#include <kaction.h>
#include <klocale.h>
#include <kgenericfactory.h>

#include "kopete.h"
#include "kopetemessage.h"
#include "kopetemetacontact.h"
#include "kopetemessagemanager.h"

#include "cryptographyplugin.h"
#include "cryptographypreferences.h"

#include "kgpginterface.h"

K_EXPORT_COMPONENT_FACTORY( kopete_cryptography, KGenericFactory<CryptographyPlugin> );

CryptographyPlugin::CryptographyPlugin( QObject *parent, const char *name,
	const QStringList &/*args*/ )
: KopetePlugin( parent, name ) ,
		m_cachedPass()
{
	if( !pluginStatic_ )
		pluginStatic_=this;

	//TODO: found a pixmap
	m_prefs = new CryptographyPreferences ( "kgpg", this );

	connect( kopeteapp, SIGNAL(aboutToDisplay(KopeteMessage&)),
		 SLOT(slotIncomingMessage(KopeteMessage&)) );
	connect( kopeteapp, SIGNAL(aboutToSend(KopeteMessage&)),
		 SLOT(slotOutgoingMessage(KopeteMessage&)) );

	m_collection=0l;
	m_currentMetaContact=0L;

}

CryptographyPlugin::~CryptographyPlugin()
{
	pluginStatic_ = 0L;
	delete m_collection;
}

CryptographyPlugin* CryptographyPlugin::plugin()
{
	return pluginStatic_ ;
}

CryptographyPlugin* CryptographyPlugin::pluginStatic_ = 0L;

QCString CryptographyPlugin::cachedPass()
{
	return pluginStatic_->m_cachedPass;
}

void CryptographyPlugin::setCachedPass(const QCString& p)
{
	pluginStatic_->m_cachedPass=p;
}

void CryptographyPlugin::init()
{
}

bool CryptographyPlugin::unload()
{
	return true;
}

bool CryptographyPlugin::serialize( KopeteMetaContact *metaContact,
			  QStringList &strList  ) const
{
	if ( !m_keyMap.contains( metaContact ) )
		return false;

	strList<<  m_keyMap[ metaContact ] ;
	return true;
}

void CryptographyPlugin::deserialize( KopeteMetaContact *metaContact, const QStringList& data )
{
	m_keyMap[ metaContact ] = data.first();
}

KActionCollection *CryptographyPlugin::customContextMenuActions(KopeteMetaContact *m)
{
	delete m_collection;

	m_collection = new KActionCollection(this);

	KAction *action=new KAction( i18n("&Select Cryptography public key"), "kgpg", 0, this, SLOT (slotSelectContactKey()), m_collection);

	m_collection->insert(action);
	m_currentMetaContact=m;
	return m_collection;
}

/*KActionCollection *CryptographyPlugin::customChatActions(KopeteMessageManager *KMM)
{
	delete m_actionCollection;

	m_actionCollection = new KActionCollection(this);
	KAction *actionTranslate = new KAction( i18n ("Translate"), 0,
		this, SLOT( slotTranslateChat() ), m_actionCollection, "actionTranslate" );
	m_actionCollection->insert( actionTranslate );

	m_currentMessageManager=KMM;
	return m_actionCollection;
}*/

void CryptographyPlugin::slotIncomingMessage( KopeteMessage& msg )
{
	if(msg.direction() != KopeteMessage::Inbound)
		return;
	QString body=msg.plainBody();
	if(!body.startsWith("-----BEGIN PGP MESSAGE----"))
		return;

	body=KgpgInterface::KgpgDecryptText(body, m_prefs->privateKey());

	if (body!="")
		msg.setBody(body,KopeteMessage::PlainText);
}

void CryptographyPlugin::slotOutgoingMessage( KopeteMessage& msg )
{
	if(msg.direction() != KopeteMessage::Outbound)
		return;
	if(msg.to().count()!=1)
	{
		kdDebug() << "CryptographyPlugin::slotOutgoingMessage: TODO: group chat not yet implemented" <<endl;
		return;
	}
	KopeteMetaContact *m=msg.to().first()->metaContact();

	if(!m_keyMap.contains(m))
	{
		kdDebug() << "CryptographyPlugin::slotOutgoingMessage: no key selected for this contact" <<endl;
		return;
	}

	/* Code From KGPG */

  //////////////////              encode from editor
  QString encryptOptions="";

  //if (utrust==true)
		encryptOptions+=" --always-trust ";
  //if (arm==true)
		encryptOptions+=" --armor ";

 /* if (pubcryptography==true)
   {
      if (gpgversion<120) encryptOptions+=" --compress-algo 1 --cipher-algo cast5 ";
      else encryptOptions+=" --cryptography6 ";
    }*/

// if (selec==NULL) {KMessageBox::sorry(0,i18n("You have not choosen an encryption key..."));return;}

	QString resultat=KgpgInterface::KgpgEncryptText(msg.plainBody(),m_keyMap[m],encryptOptions);
	if (resultat!="")
		msg.setBody(resultat,KopeteMessage::PlainText);
}

#include "popuppublic.h"

void CryptographyPlugin::slotSelectContactKey()
{
	popupPublic *dialogue=new popupPublic(0L/*this*/, "public_keys", 0,false);
	connect(dialogue,SIGNAL(selectedKey(QString &,bool,bool,bool,bool)),this,SLOT(setKey(QString &)));
	dialogue->exec();
	delete dialogue;
}

void CryptographyPlugin::setKey(QString &keyId)
{
	if(  m_currentMetaContact)
	{
		m_keyMap[ m_currentMetaContact ]= keyId;
	}
}

#include "cryptographyplugin.moc"

<|endoftext|>


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

#ifndef SC_ACCESSIBILITYHINTS_HXX
#define SC_ACCESSIBILITYHINTS_HXX

#ifndef SC_VIEWDATA_HXX
#include "viewdata.hxx"
#endif

#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif

#ifndef _SFXSMPLHINT_HXX
#include <svtools/smplhint.hxx>
#endif
#ifndef _SFXHINT_HXX //autogen
#include <svtools/hint.hxx>
#endif

#define SC_HINT_ACC_SIMPLE_START    SFX_HINT_USER00
#define SC_HINT_ACC_TABLECHANGED    SC_HINT_ACC_SIMPLE_START + 1
#define SC_HINT_ACC_CURSORCHANGED   SC_HINT_ACC_SIMPLE_START + 2
#define SC_HINT_ACC_VISAREACHANGED  SC_HINT_ACC_SIMPLE_START + 3

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

class ScAccGridViewChangeHint : public SfxHint
{
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                xOldAccessible;
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                xNewAccessible;
    ScSplitPos  eOldGridWin;
    ScSplitPos  eNewGridWin;
public:
                TYPEINFO();
                ScAccGridViewChangeHint( ScSplitPos eOldGridWin, ScSplitPos eNewGridWin,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xOld,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xNew );
                ~ScAccGridViewChangeHint();

    ScSplitPos  GetOldGridWin() const { return eOldGridWin; }
    ScSplitPos  GetNewGridWin() const { return eNewGridWin; }
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                GetOldAccessible() const { return xOldAccessible; }
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                GetNewAccessible() const { return xOldAccessible; }
};

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

#ifndef SC_ACCESSIBILITYHINTS_HXX
#define SC_ACCESSIBILITYHINTS_HXX

#ifndef SC_VIEWDATA_HXX
#include "viewdata.hxx"
#endif

#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif

#ifndef _SFXSMPLHINT_HXX
#include <svtools/smplhint.hxx>
#endif
#ifndef _SFXHINT_HXX //autogen
#include <svtools/hint.hxx>
#endif

#define SC_HINT_ACC_SIMPLE_START    SFX_HINT_USER00
#define SC_HINT_ACC_TABLECHANGED    SC_HINT_ACC_SIMPLE_START + 1
#define SC_HINT_ACC_CURSORCHANGED   SC_HINT_ACC_SIMPLE_START + 2
#define SC_HINT_ACC_VISAREACHANGED  SC_HINT_ACC_SIMPLE_START + 3
#define SC_HINT_ACC_EDITMODE        SC_HINT_ACC_SIMPLE_START + 4
#define SC_HINT_ACC_MAKEDRAWLAYER   SC_HINT_ACC_SIMPLE_START + 5

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

class ScAccGridViewChangeHint : public SfxHint
{
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                xOldAccessible;
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                xNewAccessible;
    ScSplitPos  eOldGridWin;
    ScSplitPos  eNewGridWin;
public:
                TYPEINFO();
                ScAccGridViewChangeHint( ScSplitPos eOldGridWin, ScSplitPos eNewGridWin,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xOld,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xNew );
                ~ScAccGridViewChangeHint();

    ScSplitPos  GetOldGridWin() const { return eOldGridWin; }
    ScSplitPos  GetNewGridWin() const { return eNewGridWin; }
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                GetOldAccessible() const { return xOldAccessible; }
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                GetNewAccessible() const { return xOldAccessible; }
};

#endif
<|endoftext|>