<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Copyright (c) 2017-2018 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "script/sigencoding.h"

#include "pubkey.h"
#include "script/script_flags.h"

#include <vector>

typedef std::vector<unsigned char> valtype;

bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
    if (vchPubKey.size() < 33) {
        //  Non-canonical public key: too short
        return false;
    }
    if (vchPubKey[0] == 0x04) {
        if (vchPubKey.size() != 65) {
            //  Non-canonical public key: invalid length for uncompressed key
            return false;
        }
    } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
        if (vchPubKey.size() != 33) {
            //  Non-canonical public key: invalid length for compressed key
            return false;
        }
    } else {
          //  Non-canonical public key: neither compressed nor uncompressed
          return false;
    }
    return true;
}

static bool IsCompressedPubKey(const valtype &vchPubKey)
{
    if (vchPubKey.size() != 33)
    {
        //  Non-canonical public key: invalid length for compressed key
        return false;
    }
    if (vchPubKey[0] != 0x02 && vchPubKey[0] != 0x03)
    {
        //  Non-canonical public key: invalid prefix for compressed key
        return false;
    }
    return true;
}

/**
 * A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
 * Where R and S are not negative (their first byte has its highest bit not set), and not
 * excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
 * in which case a single 0 byte is necessary and even required).
 *
 * See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
 *
 * This function is consensus-critical since BIP66.
 */
bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) {
    // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
    // * total-length: 1-byte length descriptor of everything that follows,
    //   excluding the sighash byte.
    // * R-length: 1-byte length descriptor of the R value that follows.
    // * R: arbitrary-length big-endian encoded R value. It must use the shortest
    //   possible encoding for a positive integers (which means no null bytes at
    //   the start, except a single one when the next byte has its highest bit set).
    // * S-length: 1-byte length descriptor of the S value that follows.
    // * S: arbitrary-length big-endian encoded S value. The same rules apply.
    // * sighash: 1-byte value indicating what data is hashed (not part of the DER
    //   signature)

    // Minimum and maximum size constraints.
    if (sig.size() < 9 || sig.size() > 73) {
        return false;
    }

    //
    // Check that the signature is a coumpound structure of proper size.
    //

    // A signature is of type 0x30 (compound).
    if (sig[0] != 0x30) {
        return false;
    }

    // Make sure the length covers the entire signature.
    // Remove:
    // * 1 byte for the coupound type.
    // * 1 byte for the length of the signature.
    // * 1 byte for the sighash type.
    if (sig[1] != sig.size() - 3) {
        return false;
    }

    //
    // Check that R is an positive integer of sensible size.
    //

    // Check whether the R element is an integer.
    if (sig[2] != 0x02) {
        return false;
    }

    // Extract the length of the R element.
    const uint32_t lenR = sig[3];

    // Zero-length integers are not allowed for R.
    if (lenR == 0) {
        return false;
    }

    // Negative numbers are not allowed for R.
    if (sig[4] & 0x80) {
        return false;
    }

    // Make sure the length of the R element is consistent with the signature
    // size.
    // Remove:
    // * 1 byte for the coumpound type.
    // * 1 byte for the length of the signature.
    // * 2 bytes for the integer type of R and S.
    // * 2 bytes for the size of R and S.
    // * 1 byte for S itself.
    // * 1 byte for the sighash type.
    if (lenR > (sig.size() - 8)) {
        return false;
    }

    // Null bytes at the start of R are not allowed, unless R would otherwise be
    // interpreted as a negative number.
    //
    // /!\ This check can only be performed after we checked that lenR is
    //     consistent with the size of the signature or we risk to access out of
    //     bound elements.
    if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) {
        return false;
    }

    //
    // Check that S is an positive integer of sensible size.
    //

    // S's definition starts after R's definition:
    // * 1 byte for the coumpound type.
    // * 1 byte for the length of the signature.
    // * 1 byte for the size of R.
    // * lenR bytes for R itself.
    // * 1 byte to get to S.
    const uint32_t startS = lenR + 4;

    // Check whether the S element is an integer.
    if (sig[startS] != 0x02) {
        return false;
    }

    // Extract the length of the S element.
    const uint32_t lenS = sig[startS + 1];

    // Zero-length integers are not allowed for S.
    if (lenS == 0) {
        return false;
    }

    // Negative numbers are not allowed for S.
    if (sig[startS + 2] & 0x80) {
        return false;
    }

    // Verify that the length of S is consistent with the size of the signature
    // including metadatas:
    // * 1 byte for the integer type of S.
    // * 1 byte for the size of S.
    // * 1 byte for the sighash type.
    if (size_t(startS + lenS + 3) != sig.size()) {
        return false;
    }

    // Null bytes at the start of S are not allowed, unless S would otherwise be
    // interpreted as a negative number.
    //
    // /!\ This check can only be performed after we checked that lenR and lenS
    //     are consistent with the size of the signature or we risk to access
    //     out of bound elements.
    if (lenS > 1 && (sig[startS + 2] == 0x00) && !(sig[startS + 3] & 0x80)) {
        return false;
    }

    return true;
}

bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
    assert(vchSig.size() > 0);
    if (CPubKey::CheckLowS(vchSig | boost::adaptors::sliced(0, vchSig.size() - 1))) {
        return true;
    }
    return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
}

static bool IsDefinedHashtypeSignature(const valtype &vchSig) {
    if (vchSig.size() == 0) {
        return false;
    }
    SigHashType nHashType = GetHashType(vchSig)
        & ~(SigHashType::ANYONECANPAY | SigHashType::FORKID);

    if (nHashType < SigHashType::ALL || nHashType > SigHashType::SINGLE)
        return false;

    return true;
}

bool CheckSignatureEncoding(const std::vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror) {
    // Empty signature. Not strictly DER encoded, but allowed to provide a
    // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
    if (vchSig.size() == 0) {
        return true;
    }
    if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
        return set_error(serror, SCRIPT_ERR_SIG_DER);
    }
    if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
        // serror is set
        return false;
    }
    if ((flags & SCRIPT_VERIFY_STRICTENC) != 0) {
        if (!IsDefinedHashtypeSignature(vchSig)) {
            return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
        }
        bool usesForkId = bool(GetHashType(vchSig) & SigHashType::FORKID);
        bool forkIdEnabled = flags & SCRIPT_ENABLE_SIGHASH_FORKID;
        if (!forkIdEnabled && usesForkId) {
            return set_error(serror, SCRIPT_ERR_ILLEGAL_FORKID);
        }
        if (forkIdEnabled && !usesForkId) {
            return set_error(serror, SCRIPT_ERR_MUST_USE_FORKID);
        }
    }
    return true;
}

bool CheckPubKeyEncoding(const valtype &vchPubKey, unsigned int flags, ScriptError *serror)
{
    if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey)) {
        return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
    }

    // Only compressed keys are accepted when
    // SCRIPT_VERIFY_COMPRESSED_PUBKEYTYPE is enabled.
    if (flags & SCRIPT_VERIFY_COMPRESSED_PUBKEYTYPE && !IsCompressedPubKey(vchPubKey))
    {
        return set_error(serror, SCRIPT_ERR_NONCOMPRESSED_PUBKEY);
    }
    return true;
}
<commit_msg>Ignore sighash when checking for DER encoding.<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Copyright (c) 2017-2018 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "script/sigencoding.h"

#include "pubkey.h"
#include "script/script_flags.h"

#include <vector>

typedef std::vector<unsigned char> valtype;

bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
    if (vchPubKey.size() < 33) {
        //  Non-canonical public key: too short
        return false;
    }
    if (vchPubKey[0] == 0x04) {
        if (vchPubKey.size() != 65) {
            //  Non-canonical public key: invalid length for uncompressed key
            return false;
        }
    } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
        if (vchPubKey.size() != 33) {
            //  Non-canonical public key: invalid length for compressed key
            return false;
        }
    } else {
          //  Non-canonical public key: neither compressed nor uncompressed
          return false;
    }
    return true;
}

static bool IsCompressedPubKey(const valtype &vchPubKey)
{
    if (vchPubKey.size() != 33)
    {
        //  Non-canonical public key: invalid length for compressed key
        return false;
    }
    if (vchPubKey[0] != 0x02 && vchPubKey[0] != 0x03)
    {
        //  Non-canonical public key: invalid prefix for compressed key
        return false;
    }
    return true;
}

/**
 * A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
 * Where R and S are not negative (their first byte has its highest bit not set), and not
 * excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
 * in which case a single 0 byte is necessary and even required).
 *
 * See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
 *
 * This function is consensus-critical since BIP66.
 */
static bool
IsValidSignatureEncoding(const boost::sliced_range<const valtype> &sig) {
    // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S]
    // * total-length: 1-byte length descriptor of everything that follows,
    //   excluding the sighash byte.
    // * R-length: 1-byte length descriptor of the R value that follows.
    // * R: arbitrary-length big-endian encoded R value. It must use the shortest
    //   possible encoding for a positive integers (which means no null bytes at
    //   the start, except a single one when the next byte has its highest bit set).
    // * S-length: 1-byte length descriptor of the S value that follows.
    // * S: arbitrary-length big-endian encoded S value. The same rules apply.

    // Minimum and maximum size constraints.
    if (sig.size() < 8 || sig.size() > 72) {
        return false;
    }

    //
    // Check that the signature is a coumpound structure of proper size.
    //

    // A signature is of type 0x30 (compound).
    if (sig[0] != 0x30) {
        return false;
    }

    // Make sure the length covers the entire signature.
    // Remove:
    // * 1 byte for the coupound type.
    // * 1 byte for the length of the signature.
    if (sig[1] != sig.size() - 2) {
        return false;
    }

    //
    // Check that R is an positive integer of sensible size.
    //

    // Check whether the R element is an integer.
    if (sig[2] != 0x02) {
        return false;
    }

    // Extract the length of the R element.
    const uint32_t lenR = sig[3];

    // Zero-length integers are not allowed for R.
    if (lenR == 0) {
        return false;
    }

    // Negative numbers are not allowed for R.
    if (sig[4] & 0x80) {
        return false;
    }

    // Make sure the length of the R element is consistent with the signature
    // size.
    // Remove:
    // * 1 byte for the coumpound type.
    // * 1 byte for the length of the signature.
    // * 2 bytes for the integer type of R and S.
    // * 2 bytes for the size of R and S.
    // * 1 byte for S itself.
    if (lenR > (sig.size() - 7)) {
        return false;
    }

    // Null bytes at the start of R are not allowed, unless R would otherwise be
    // interpreted as a negative number.
    //
    // /!\ This check can only be performed after we checked that lenR is
    //     consistent with the size of the signature or we risk to access out of
    //     bound elements.
    if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) {
        return false;
    }

    //
    // Check that S is an positive integer of sensible size.
    //

    // S's definition starts after R's definition:
    // * 1 byte for the coumpound type.
    // * 1 byte for the length of the signature.
    // * 1 byte for the size of R.
    // * lenR bytes for R itself.
    // * 1 byte to get to S.
    const uint32_t startS = lenR + 4;

    // Check whether the S element is an integer.
    if (sig[startS] != 0x02) {
        return false;
    }

    // Extract the length of the S element.
    const uint32_t lenS = sig[startS + 1];

    // Zero-length integers are not allowed for S.
    if (lenS == 0) {
        return false;
    }

    // Negative numbers are not allowed for S.
    if (sig[startS + 2] & 0x80) {
        return false;
    }

    // Verify that the length of S is consistent with the size of the signature
    // including metadatas:
    // * 1 byte for the integer type of S.
    // * 1 byte for the size of S.
    if (size_t(startS + lenS + 2) != sig.size()) {
        return false;
    }

    // Null bytes at the start of S are not allowed, unless S would otherwise be
    // interpreted as a negative number.
    //
    // /!\ This check can only be performed after we checked that lenR and lenS
    //     are consistent with the size of the signature or we risk to access
    //     out of bound elements.
    if (lenS > 1 && (sig[startS + 2] == 0x00) && !(sig[startS + 3] & 0x80)) {
        return false;
    }

    return true;
}

bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
    assert(vchSig.size() > 0);
    if (CPubKey::CheckLowS(vchSig | boost::adaptors::sliced(0, vchSig.size() - 1))) {
        return true;
    }
    return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
}

static bool IsDefinedHashtypeSignature(const valtype &vchSig) {
    if (vchSig.size() == 0) {
        return false;
    }
    SigHashType nHashType = GetHashType(vchSig)
        & ~(SigHashType::ANYONECANPAY | SigHashType::FORKID);

    if (nHashType < SigHashType::ALL || nHashType > SigHashType::SINGLE)
        return false;

    return true;
}

bool CheckSignatureEncoding(const std::vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror) {
    // Empty signature. Not strictly DER encoded, but allowed to provide a
    // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
    if (vchSig.size() == 0) {
        return true;
    }
    if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S |
                  SCRIPT_VERIFY_STRICTENC)) != 0 &&
        !IsValidSignatureEncoding(
            vchSig | boost::adaptors::sliced(0, vchSig.size() - 1))) {
        return set_error(serror, SCRIPT_ERR_SIG_DER);
    }
    if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
        // serror is set
        return false;
    }
    if ((flags & SCRIPT_VERIFY_STRICTENC) != 0) {
        if (!IsDefinedHashtypeSignature(vchSig)) {
            return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
        }
        bool usesForkId = bool(GetHashType(vchSig) & SigHashType::FORKID);
        bool forkIdEnabled = flags & SCRIPT_ENABLE_SIGHASH_FORKID;
        if (!forkIdEnabled && usesForkId) {
            return set_error(serror, SCRIPT_ERR_ILLEGAL_FORKID);
        }
        if (forkIdEnabled && !usesForkId) {
            return set_error(serror, SCRIPT_ERR_MUST_USE_FORKID);
        }
    }
    return true;
}

bool CheckPubKeyEncoding(const valtype &vchPubKey, unsigned int flags, ScriptError *serror)
{
    if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey)) {
        return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
    }

    // Only compressed keys are accepted when
    // SCRIPT_VERIFY_COMPRESSED_PUBKEYTYPE is enabled.
    if (flags & SCRIPT_VERIFY_COMPRESSED_PUBKEYTYPE && !IsCompressedPubKey(vchPubKey))
    {
        return set_error(serror, SCRIPT_ERR_NONCOMPRESSED_PUBKEY);
    }
    return true;
}
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */

#include "stdafx.h"

// Test the functions and objects in Service/JVM.cpp

#include "Service/JVM.h"

LOGGING (com.opengamma.language.service.JVMTest);

#define TIMEOUT_START_JVM		30000
#define TIMEOUT_STOP_JVM		10000

/**
 * Tries to start the JVM and invoke the same methods as MainTest/TestStartStop does.
 */
static void StartStop () {
	CJVM *pJvm = CJVM::Create ();
	ASSERT (pJvm);
	ASSERT (!pJvm->IsBusy (0));
	ASSERT (!pJvm->IsRunning ());
	LOGDEBUG (TEXT ("Starting JVM"));
	pJvm->Start ();
	int nAttempt = 0;
	while (pJvm->IsBusy (TIMEOUT_START_JVM / 10)) {
		LOGDEBUG (TEXT ("JVM busy"));
		ASSERT (++nAttempt < 10);
	}
	ASSERT (pJvm->IsRunning ());
	LOGDEBUG (TEXT ("Sending a client connection"));
	pJvm->UserConnection (TEXT ("TestUser"), TEXT ("Foo"), TEXT ("Bar"), TEXT ("test"));
	LOGDEBUG (TEXT ("Stopping JVM"));
	pJvm->Stop ();
	nAttempt = 0;
	while (pJvm->IsBusy (TIMEOUT_STOP_JVM / 10)) {
		LOGDEBUG (TEXT ("JVM busy"));
		ASSERT (++nAttempt < 10);
	}
	ASSERT (!pJvm->IsRunning ());
	LOGDEBUG (TEXT ("Destroying JVM"));
	delete pJvm;
}

//#define RUN_TESTS			// JVM limitations mean that ServiceTest will not pass if JVMTest is run

#ifndef RUN_TESTS
#undef BEGIN_TESTS
#define BEGIN_TESTS MANUAL_TESTS
#endif /* ifndef RUN_TESTS */

BEGIN_TESTS (JVMTest)
	TEST (StartStop)
END_TESTS
<commit_msg>[PLAT-1292] Correction to unit tests.<commit_after>/**
 * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */

#include "stdafx.h"

// Test the functions and objects in Service/JVM.cpp

#include "Service/JVM.h"

LOGGING (com.opengamma.language.service.JVMTest);

#define TIMEOUT_START_JVM		30000
#define TIMEOUT_STOP_JVM		10000

/**
 * Tries to start the JVM and invoke the same methods as MainTest/TestStartStop does.
 */
static void StartStop () {
	CErrorFeedback oFeedback;
	CJVM *pJvm = CJVM::Create (&oFeedback);
	ASSERT (pJvm);
	ASSERT (!pJvm->IsBusy (0));
	ASSERT (!pJvm->IsRunning ());
	LOGDEBUG (TEXT ("Starting JVM"));
	pJvm->Start (&oFeedback);
	int nAttempt = 0;
	while (pJvm->IsBusy (TIMEOUT_START_JVM / 10)) {
		LOGDEBUG (TEXT ("JVM busy"));
		ASSERT (++nAttempt < 10);
	}
	ASSERT (pJvm->IsRunning ());
	LOGDEBUG (TEXT ("Sending a client connection"));
	pJvm->UserConnection (TEXT ("TestUser"), TEXT ("Foo"), TEXT ("Bar"), TEXT ("test"));
	LOGDEBUG (TEXT ("Stopping JVM"));
	pJvm->Stop ();
	nAttempt = 0;
	while (pJvm->IsBusy (TIMEOUT_STOP_JVM / 10)) {
		LOGDEBUG (TEXT ("JVM busy"));
		ASSERT (++nAttempt < 10);
	}
	ASSERT (!pJvm->IsRunning ());
	LOGDEBUG (TEXT ("Destroying JVM"));
	delete pJvm;
}

//#define RUN_TESTS			// JVM limitations mean that ServiceTest will not pass if JVMTest is run

#ifndef RUN_TESTS
#undef BEGIN_TESTS
#define BEGIN_TESTS MANUAL_TESTS
#endif /* ifndef RUN_TESTS */

BEGIN_TESTS (JVMTest)
	TEST (StartStop)
END_TESTS
<|endoftext|>


<commit_before>/*
    Kopete Yahoo Protocol
    Send a notification

    Copyright (c) 2005 André Duffeck <andre.duffeck@kdemail.net>

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

#include "sendnotifytask.h"
#include "transfer.h"
#include "ymsgtransfer.h"
#include "yahootypes.h"
#include "client.h"
#include <qstring.h>
#include <kdebug.h>

SendNotifyTask::SendNotifyTask(Task* parent) : Task(parent)
{
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
}

SendNotifyTask::~SendNotifyTask()
{
}

void SendNotifyTask::onGo()
{
	YMSGTransfer *t = new YMSGTransfer(Yahoo::ServiceNotify);
	t->setId( client()->sessionID() );
	t->setStatus( Yahoo::StatusNotify );
	t->setParam( 4, (Q3CString)client()->userId().toLocal8Bit() );
	t->setParam( 5, (Q3CString)m_target.toLocal8Bit() );
	t->setParam( 14, " " );
	switch( m_type )
	{
	case NotifyTyping:
		t->setParam( 13, m_state );
		t->setParam( 49, "TYPING" );
	break;
	case NotifyWebcamInvite:
		t->setParam( 13, 0 );
		t->setParam( 49, "WEBCAMINVITE" );
	break;
	case NotifyGame:
	default:
		setSuccess( false );
		return;
	break;
	}
	send( t );

	setSuccess( true );
}

void SendNotifyTask::setType( Type type )
{
	m_type = type;
}

void SendNotifyTask::setTarget( const QString &to )
{
	m_target = to;
}

void SendNotifyTask::setState( State state)
{
	m_state = state;
}

#include "sendnotifytask.moc"
<commit_msg>fix memory leak (CID 2127)<commit_after>/*
    Kopete Yahoo Protocol
    Send a notification

    Copyright (c) 2005 André Duffeck <andre.duffeck@kdemail.net>

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

#include "sendnotifytask.h"
#include "transfer.h"
#include "ymsgtransfer.h"
#include "yahootypes.h"
#include "client.h"
#include <qstring.h>
#include <kdebug.h>

SendNotifyTask::SendNotifyTask(Task* parent) : Task(parent)
{
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
}

SendNotifyTask::~SendNotifyTask()
{
}

void SendNotifyTask::onGo()
{
	YMSGTransfer *t = new YMSGTransfer(Yahoo::ServiceNotify);
	t->setId( client()->sessionID() );
	t->setStatus( Yahoo::StatusNotify );
	t->setParam( 4, (Q3CString)client()->userId().toLocal8Bit() );
	t->setParam( 5, (Q3CString)m_target.toLocal8Bit() );
	t->setParam( 14, " " );
	switch( m_type )
	{
	case NotifyTyping:
		t->setParam( 13, m_state );
		t->setParam( 49, "TYPING" );
	break;
	case NotifyWebcamInvite:
		t->setParam( 13, 0 );
		t->setParam( 49, "WEBCAMINVITE" );
	break;
	case NotifyGame:
	default:
		setSuccess( false );
		delete t;
		return;
	break;
	}
	send( t );

	setSuccess( true );
}

void SendNotifyTask::setType( Type type )
{
	m_type = type;
}

void SendNotifyTask::setTarget( const QString &to )
{
	m_target = to;
}

void SendNotifyTask::setState( State state)
{
	m_state = state;
}

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


<commit_before>/*++

Copyright (C) 2019 3MF Consortium

All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Abstract:

NMR_UUID.cpp implements a datatype and functions to handle UUIDs

--*/

#include "Common/NMR_UUID.h"

#include "Common/NMR_StringUtils.h"
#include "Common/NMR_Exception.h"

#include <algorithm>

#ifdef _WIN32
#include <objbase.h>
#include <iomanip>
#else
#include <random>
#include <ctime>
#endif

namespace NMR
{
	CUUID::CUUID()
	{
#ifdef _WIN32
		GUID guid;
		if (CoCreateGuid(&guid) != S_OK)
			throw CNMRException(NMR_ERROR_UUIDGENERATIONFAILED);
		LPOLESTR str;
		if (StringFromCLSID(guid, &str) != S_OK)
			throw CNMRException(NMR_ERROR_UUIDGENERATIONFAILED);
		set(fnUTF16toUTF8(str).c_str());
#else
		// generation of a v4 UUID according to https://tools.ietf.org/html/rfc4122#section-4.4

		static std::random_device rd;
		std::mt19937 rng;
		rng.seed(rd() ^ (unsigned int)(time(nullptr)));
		std::uniform_int_distribution<std::mt19937::result_type> distHexaDec(0, 15);
		std::uniform_int_distribution<std::mt19937::result_type> dist4(0, 4);
		const nfChar* hexaDec = "0123456789abcdef";
		nfChar string[33];
		for (int i = 0; i < 32; i++)
			string[i] = hexaDec[distHexaDec(rng)];
		string[12] = hexaDec[4]; // set version 4
		string[16] = hexaDec[4 + dist4(rng)];
		string[32] = 0;

		set(string);
#endif
	}

	CUUID::CUUID(const nfChar* pString)
	{
		set(pString);
	}

	CUUID::CUUID(const std::string &string)
	{
		set(string.c_str());
	}

	std::string CUUID::toString() const
	{
		return m_sUUID;
	}

	bool InValid(char c)
	{
		return !(((c >= '0') && (c <= '9'))
			|| ((c >= 'a') && (c <= 'f'))
		 // || (c == '-')
			);
	}

	bool CUUID::set(const nfChar* pString)
	{
		// to lowercase, remove all non hex characters, insert dashes again
		std::string str = pString;
		std::transform(str.begin(), str.end(), str.begin(), ::tolower);
		str.erase(std::remove_if(str.begin(), str.end(), &InValid), str.end());
		if (str.length() != 32) {
			throw CNMRException(NMR_ERROR_ILLFORMATUUID);
		}
		m_sUUID = str.substr(0, 8) + '-' + str.substr(8, 4) + '-' + str.substr(12, 4) + '-' + str.substr(16, 4) + '-' + str.substr(20, 12);
		return true;
	}

	CUUID& CUUID::operator=(const CUUID& uuid)
	{
		if (&uuid == this)
			return *this;
		m_sUUID = uuid.m_sUUID;
		return *this;
	}

	bool CUUID::operator==(const CUUID& uuid)
	{
		if (&uuid == this)
			return true;
		return m_sUUID == uuid.m_sUUID;
	}

}
<commit_msg>Fix index-typo to make UUIDs correct v4<commit_after>/*++

Copyright (C) 2019 3MF Consortium

All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Abstract:

NMR_UUID.cpp implements a datatype and functions to handle UUIDs

--*/

#include "Common/NMR_UUID.h"

#include "Common/NMR_StringUtils.h"
#include "Common/NMR_Exception.h"

#include <algorithm>

#ifdef _WIN32
#include <objbase.h>
#include <iomanip>
#else
#include <random>
#include <ctime>
#endif

namespace NMR
{
	CUUID::CUUID()
	{
#ifdef _WIN32
		GUID guid;
		if (CoCreateGuid(&guid) != S_OK)
			throw CNMRException(NMR_ERROR_UUIDGENERATIONFAILED);
		LPOLESTR str;
		if (StringFromCLSID(guid, &str) != S_OK)
			throw CNMRException(NMR_ERROR_UUIDGENERATIONFAILED);
		set(fnUTF16toUTF8(str).c_str());
#else
		// generation of a v4 UUID according to https://tools.ietf.org/html/rfc4122#section-4.4

		static std::random_device rd;
		std::mt19937 rng;
		rng.seed(rd() ^ (unsigned int)(time(nullptr)));
		std::uniform_int_distribution<std::mt19937::result_type> distHexaDec(0, 15);
		std::uniform_int_distribution<std::mt19937::result_type> dist4(0, 4);
		const nfChar* hexaDec = "0123456789abcdef";
		nfChar string[33];
		for (int i = 0; i < 32; i++)
			string[i] = hexaDec[distHexaDec(rng)];
		string[12] = hexaDec[4]; // set version 4
		string[16] = hexaDec[8 + dist4(rng)];
		string[32] = 0;

		set(string);
#endif
	}

	CUUID::CUUID(const nfChar* pString)
	{
		set(pString);
	}

	CUUID::CUUID(const std::string &string)
	{
		set(string.c_str());
	}

	std::string CUUID::toString() const
	{
		return m_sUUID;
	}

	bool InValid(char c)
	{
		return !(((c >= '0') && (c <= '9'))
			|| ((c >= 'a') && (c <= 'f'))
		 // || (c == '-')
			);
	}

	bool CUUID::set(const nfChar* pString)
	{
		// to lowercase, remove all non hex characters, insert dashes again
		std::string str = pString;
		std::transform(str.begin(), str.end(), str.begin(), ::tolower);
		str.erase(std::remove_if(str.begin(), str.end(), &InValid), str.end());
		if (str.length() != 32) {
			throw CNMRException(NMR_ERROR_ILLFORMATUUID);
		}
		m_sUUID = str.substr(0, 8) + '-' + str.substr(8, 4) + '-' + str.substr(12, 4) + '-' + str.substr(16, 4) + '-' + str.substr(20, 12);
		return true;
	}

	CUUID& CUUID::operator=(const CUUID& uuid)
	{
		if (&uuid == this)
			return *this;
		m_sUUID = uuid.m_sUUID;
		return *this;
	}

	bool CUUID::operator==(const CUUID& uuid)
	{
		if (&uuid == this)
			return true;
		return m_sUUID == uuid.m_sUUID;
	}

}
<|endoftext|>


<commit_before>// ļΪminicodecvtһ֣ȨμLICENSEļ
// Copyright 2014, CHU.
//  2014/10/24
#include "unicode.h"

using namespace std;
using namespace minicodecvt;
using namespace minicodecvt::Exception;

/* UTF8 ʵ */
Decoder::UTF8::UTF8()
	: m_iState(0), m_incpChar(static_cast<char32_t>(0))
{}

Decoder::UTF8::UTF8(const UTF8& org)
	: m_iState(org.m_iState), m_incpChar(org.m_incpChar)
{}

bool Decoder::UTF8::operator() (uint8_t input, char32_t& output)
{
	// ״̬
	if (m_iState == 0)
	{
		// ǰֽ
		if (input >= 0xFCu && input <= 0xFDu)  // UCS4 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
		{
			m_incpChar = input & 0x01u;
			m_iState = 5;
		}
		else if (input >= 0xF8u && input <= 0xFBu) // UCS4 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
		{
			m_incpChar = input & 0x03u;
			m_iState = 4;
		}
		else if (input >= 0xF0u && input <= 0xF7u) // UCS4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
		{
			m_incpChar = input & 0x07u;
			m_iState = 3;
		}
		else if (input >= 0xE0u && input <= 0xEFu) // 0800~FFFF: 1110xxxx 10xxxxxx 10xxxxxx
		{
			m_incpChar = input & 0x0Fu;
			m_iState = 2;
		}
		else if (input >= 0xC0u && input <= 0xDFu) // 0080~07FF: 110xxxxx 10xxxxxx
		{
			m_incpChar = input & 0x1Fu;
			m_iState = 1;
		}
		else if (input >= 0x00u && input <= 0x7Fu) // 0000~007F: 0xxxxxxx
		{
			m_incpChar = input;
			m_iState = 0;
		}
		else
		{
			m_iState = 0;
			throw UnicodeEncodingError("Character encoding error, not a valid UTF-8 character.");
		}
	}
	else
	{
		if (input >= 0x80u && input <= 0xBFu)
		{
			m_incpChar = (m_incpChar << 6) | (input & 0x3Fu);
			--m_iState;
		}
		else
		{
			m_iState = 0;
			throw UnicodeEncodingError("Character encoding error, not a valid succeeded UTF-8 character.");
		}
	}

	//
	if (m_iState == 0)
	{
		if (m_incpChar >= 0xD800u && m_incpChar <= 0xDFFFu)
			throw UnicodeEncodingError("Character encoding error, surrogate character detected.");

		output = m_incpChar;
		return true;
	}
	else
		return false;
}

/* UTF16 ʵ */
Decoder::UTF16::UTF16()
	: m_iState(0), m_leadChar(0)
{}

Decoder::UTF16::UTF16(const UTF16& org)
	: m_iState(org.m_iState), m_leadChar(org.m_leadChar)
{
	m_cBuf[0] = org.m_cBuf[0];
	m_cBuf[1] = org.m_cBuf[1];
}

bool Decoder::UTF16::operator() (uint8_t input, char32_t& output)
{
	// ״̬
	switch (m_iState)
	{
	case 0:
		m_cBuf[0] = input;
		m_iState = 1;
		return false;
	case 1:
		m_cBuf[1] = input;
		m_leadChar = *reinterpret_cast<char16_t*>(m_cBuf);
		// ǷΪλ
		if (m_leadChar >= 0xD800u && m_leadChar < 0xDC00)
		{
			m_leadChar -= 0xD800u;
			m_iState = 2;
			return false;
		}
		else
		{
			output = static_cast<char32_t>(m_leadChar);
			m_iState = 0;
			return true;
		}
	case 2:
		m_cBuf[0] = input;
		m_iState = 3;
		return false;
	case 3:
		m_cBuf[1] = input;
		{
			char16_t tempChar = *reinterpret_cast<char16_t*>(m_cBuf);
			// ϲ
			if (tempChar >= 0xDC00u && tempChar < 0xE000)
			{
				output = static_cast<char32_t>((m_leadChar << 16) | (tempChar - 0xDC00u));
				m_iState = 0;
				return false;
			}
			else
				throw UnicodeEncodingError("invalid trailer character.");
		}
	default:
		throw UnicodeEncodingError("internal error.");
	}
}

/* UTF16LE ʵ */
Decoder::UTF16LE::UTF16LE()
	: m_iState(0), m_tempChar(0), m_leadChar(0)
{}

Decoder::UTF16LE::UTF16LE(const UTF16LE& org)
	: m_iState(org.m_iState), m_tempChar(org.m_tempChar), m_leadChar(org.m_leadChar)
{}

bool Decoder::UTF16LE::operator() (uint8_t input, char32_t& output)
{
	// ״̬
	switch (m_iState)
	{
	case 0:
		m_tempChar = input;
		m_iState = 1;
		return false;
	case 1:
		m_tempChar |= (input << 8);
		// ǷΪλ
		if (m_tempChar >= 0xD800u && m_tempChar < 0xDC00)
		{
			m_leadChar = m_tempChar - 0xD800u;
			m_iState = 2;
			return false;
		}
		else
		{
			output = static_cast<char32_t>(m_tempChar);
			m_iState = 0;
			return true;
		}
	case 2:
		m_tempChar = input;
		m_iState = 3;
		return false;
	case 3:
		m_tempChar |= (input << 8);
		// ϲ
		if (m_tempChar >= 0xDC00u && m_tempChar < 0xE000)
		{
			output = static_cast<char32_t>((m_leadChar << 16) | (m_tempChar - 0xDC00u));
			m_iState = 0;
			return false;
		}
		else
			throw UnicodeEncodingError("invalid trailer character.");
	default:
		throw UnicodeEncodingError("internal error.");
	}
}

/* UTF16BE ʵ */
Decoder::UTF16BE::UTF16BE()
	: m_iState(0), m_tempChar(0), m_leadChar(0)
{}

Decoder::UTF16BE::UTF16BE(const UTF16BE& org)
	: m_iState(org.m_iState), m_tempChar(org.m_tempChar), m_leadChar(org.m_leadChar)
{}

bool Decoder::UTF16BE::operator() (uint8_t input, char32_t& output)
{
	// ״̬
	switch (m_iState)
	{
	case 0:
		m_tempChar = input << 8;
		m_iState = 1;
		return false;
	case 1:
		m_tempChar |= input;
		// ǷΪλ
		if (m_tempChar >= 0xD800u && m_tempChar < 0xDC00)
		{
			m_leadChar = m_tempChar - 0xD800u;
			m_iState = 2;
			return false;
		}
		else
		{
			output = static_cast<char32_t>(m_tempChar);
			m_iState = 0;
			return true;
		}
	case 2:
		m_tempChar = input << 8;
		m_iState = 3;
		return false;
	case 3:
		m_tempChar |= input;
		// ϲ
		if (m_tempChar >= 0xDC00u && m_tempChar < 0xE000)
		{
			output = static_cast<char32_t>((m_leadChar << 16) | (m_tempChar - 0xDC00u));
			m_iState = 0;
			return false;
		}
		else
			throw UnicodeEncodingError("invalid trailer character.");
	default:
		throw UnicodeEncodingError("internal error.");
	}
}

/* UTF8 ʵ */
Encoder::UTF8::UTF8() {}

Encoder::UTF8::UTF8(const UTF8& org) {}

bool Encoder::UTF8::operator() (char32_t input, uint8_t*& output, size_t& size)
{
	int c;
	uint32_t uinput = (uint32_t)input;

	if (uinput < 0x80u)
		c = 0;
	else if (uinput < 0x800u)
		c = 1;
	else if (uinput < 0x10000u)
		c = 2;
	else if (uinput < 0x200000u)
		c = 3;
	else if (uinput < 0x4000000u)
		c = 4;
	else if (uinput < 0x80000000u)
		c = 5;
	else
		throw UnicodeEncodingError("invalid utf32 character.");

	// ֽ
	for (int i = c; i > 0; --i)
	{
		m_cBuf[i] = (uinput & 0x3Fu) | 0x80u;
		uinput >>= 6;
	}

	// ֽ
	m_cBuf[0] = (0xFEu << (6 - c)) | uinput;

	// д
	output = m_cBuf;
	size = c + 1;
	return true;
}

/* UTF16 ʵ */
Encoder::UTF16::UTF16() {}

Encoder::UTF16::UTF16(const UTF16& org) {}

bool Encoder::UTF16::operator() (char32_t input, uint8_t*& output, size_t& size)
{
	// ǷҪλ
	if (input >= 0x10000u)
	{
		input -= 0x10000u;
		m_cBuf[0] = (input >> 10) | 0xD800u;    // ǰֽ
		m_cBuf[1] = (input & 0x3FFu) | 0xDC00u; // βֽ
		output = reinterpret_cast<uint8_t*>(m_cBuf);
		size = 2 * sizeof(char16_t);
		return true;
	}
	else
	{
		m_cBuf[0] = input;
		output = reinterpret_cast<uint8_t*>(m_cBuf);
		size = 1 * sizeof(char16_t);
		return true;
	}
}

/* UTF16LE ʵ */
Encoder::UTF16LE::UTF16LE() {}

Encoder::UTF16LE::UTF16LE(const UTF16LE& org) {}

bool Encoder::UTF16LE::operator() (char32_t input, uint8_t*& output, size_t& size)
{
	// ǷҪλ
	if (input >= 0x10000u)
	{
		input -= 0x10000u;
		uint16_t tLeadByte = (input >> 10) | 0xD800u;     // ǰֽ
		uint16_t tTrailByte = (input & 0x3FFu) | 0xDC00u; // βֽ
		m_cBuf[0] = tLeadByte & 0xFFu;
		m_cBuf[1] = (tLeadByte >> 8) & 0xFFu;
		m_cBuf[2] = tTrailByte & 0xFFu;
		m_cBuf[3] = (tTrailByte >> 8) & 0xFFu;
		output = m_cBuf;
		size = 4;
		return true;
	}
	else
	{
		m_cBuf[0] = input & 0xFFu;
		m_cBuf[1] = (input >> 8) & 0xFFu;
		output = m_cBuf;
		size = 2;
		return true;
	}
}

/* UTF16BE ʵ */
Encoder::UTF16BE::UTF16BE() {}

Encoder::UTF16BE::UTF16BE(const UTF16BE& org) {}

bool Encoder::UTF16BE::operator() (char32_t input, uint8_t*& output, size_t& size)
{
	// ǷҪλ
	if (input >= 0x10000u)
	{
		input -= 0x10000u;
		uint16_t tLeadByte = (input >> 10) | 0xD800u;     // ǰֽ
		uint16_t tTrailByte = (input & 0x3FFu) | 0xDC00u; // βֽ
		m_cBuf[0] = (tLeadByte >> 8) & 0xFFu;
		m_cBuf[1] = tLeadByte & 0xFFu;
		m_cBuf[2] = (tTrailByte >> 8) & 0xFFu;
		m_cBuf[3] = tTrailByte & 0xFFu;
		output = m_cBuf;
		size = 4;
		return true;
	}
	else
	{
		m_cBuf[0] = (input >> 8) & 0xFFu;
		m_cBuf[1] = input & 0xFFu;
		output = m_cBuf;
		size = 2;
		return true;
	}
}
<commit_msg>bugfixed<commit_after>// ļΪminicodecvtһ֣ȨμLICENSEļ
// Copyright 2014, CHU.
//  2014/10/24
#include "unicode.h"

using namespace std;
using namespace minicodecvt;
using namespace minicodecvt::Exception;

/* UTF8 ʵ */
Decoder::UTF8::UTF8()
	: m_iState(0), m_incpChar(static_cast<char32_t>(0))
{}

Decoder::UTF8::UTF8(const UTF8& org)
	: m_iState(org.m_iState), m_incpChar(org.m_incpChar)
{}

bool Decoder::UTF8::operator() (uint8_t input, char32_t& output)
{
	// ״̬
	if (m_iState == 0)
	{
		// ǰֽ
		if (input >= 0xFCu && input <= 0xFDu)  // UCS4 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
		{
			m_incpChar = input & 0x01u;
			m_iState = 5;
		}
		else if (input >= 0xF8u && input <= 0xFBu) // UCS4 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
		{
			m_incpChar = input & 0x03u;
			m_iState = 4;
		}
		else if (input >= 0xF0u && input <= 0xF7u) // UCS4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
		{
			m_incpChar = input & 0x07u;
			m_iState = 3;
		}
		else if (input >= 0xE0u && input <= 0xEFu) // 0800~FFFF: 1110xxxx 10xxxxxx 10xxxxxx
		{
			m_incpChar = input & 0x0Fu;
			m_iState = 2;
		}
		else if (input >= 0xC0u && input <= 0xDFu) // 0080~07FF: 110xxxxx 10xxxxxx
		{
			m_incpChar = input & 0x1Fu;
			m_iState = 1;
		}
		else if (input >= 0x00u && input <= 0x7Fu) // 0000~007F: 0xxxxxxx
		{
			m_incpChar = input;
			m_iState = 0;
		}
		else
		{
			m_iState = 0;
			throw UnicodeEncodingError("Character encoding error, not a valid UTF-8 character.");
		}
	}
	else
	{
		if (input >= 0x80u && input <= 0xBFu)
		{
			m_incpChar = (m_incpChar << 6) | (input & 0x3Fu);
			--m_iState;
		}
		else
		{
			m_iState = 0;
			throw UnicodeEncodingError("Character encoding error, not a valid succeeded UTF-8 character.");
		}
	}

	//
	if (m_iState == 0)
	{
		if (m_incpChar >= 0xD800u && m_incpChar <= 0xDFFFu)
			throw UnicodeEncodingError("Character encoding error, surrogate character detected.");

		output = m_incpChar;
		return true;
	}
	else
		return false;
}

/* UTF16 ʵ */
Decoder::UTF16::UTF16()
	: m_iState(0), m_leadChar(0)
{}

Decoder::UTF16::UTF16(const UTF16& org)
	: m_iState(org.m_iState), m_leadChar(org.m_leadChar)
{
	m_cBuf[0] = org.m_cBuf[0];
	m_cBuf[1] = org.m_cBuf[1];
}

bool Decoder::UTF16::operator() (uint8_t input, char32_t& output)
{
	// ״̬
	switch (m_iState)
	{
	case 0:
		m_cBuf[0] = input;
		m_iState = 1;
		return false;
	case 1:
		m_cBuf[1] = input;
		m_leadChar = *reinterpret_cast<char16_t*>(m_cBuf);
		// ǷΪλ
		if (m_leadChar >= 0xD800u && m_leadChar < 0xDC00)
		{
			m_leadChar -= 0xD800u;
			m_iState = 2;
			return false;
		}
		else
		{
			output = static_cast<char32_t>(m_leadChar);
			m_iState = 0;
			return true;
		}
	case 2:
		m_cBuf[0] = input;
		m_iState = 3;
		return false;
	case 3:
		m_cBuf[1] = input;
		{
			char16_t tempChar = *reinterpret_cast<char16_t*>(m_cBuf);
			// ϲ
			if (tempChar >= 0xDC00u && tempChar < 0xE000)
			{
				output = static_cast<char32_t>((m_leadChar << 16) | (tempChar - 0xDC00u));
				m_iState = 0;
				return true;
			}
			else
				throw UnicodeEncodingError("invalid trailer character.");
		}
	default:
		throw UnicodeEncodingError("internal error.");
	}
}

/* UTF16LE ʵ */
Decoder::UTF16LE::UTF16LE()
	: m_iState(0), m_tempChar(0), m_leadChar(0)
{}

Decoder::UTF16LE::UTF16LE(const UTF16LE& org)
	: m_iState(org.m_iState), m_tempChar(org.m_tempChar), m_leadChar(org.m_leadChar)
{}

bool Decoder::UTF16LE::operator() (uint8_t input, char32_t& output)
{
	// ״̬
	switch (m_iState)
	{
	case 0:
		m_tempChar = input;
		m_iState = 1;
		return false;
	case 1:
		m_tempChar |= (input << 8);
		// ǷΪλ
		if (m_tempChar >= 0xD800u && m_tempChar < 0xDC00)
		{
			m_leadChar = m_tempChar - 0xD800u;
			m_iState = 2;
			return false;
		}
		else
		{
			output = static_cast<char32_t>(m_tempChar);
			m_iState = 0;
			return true;
		}
	case 2:
		m_tempChar = input;
		m_iState = 3;
		return false;
	case 3:
		m_tempChar |= (input << 8);
		// ϲ
		if (m_tempChar >= 0xDC00u && m_tempChar < 0xE000)
		{
			output = static_cast<char32_t>((m_leadChar << 16) | (m_tempChar - 0xDC00u));
			m_iState = 0;
			return true;
		}
		else
			throw UnicodeEncodingError("invalid trailer character.");
	default:
		throw UnicodeEncodingError("internal error.");
	}
}

/* UTF16BE ʵ */
Decoder::UTF16BE::UTF16BE()
	: m_iState(0), m_tempChar(0), m_leadChar(0)
{}

Decoder::UTF16BE::UTF16BE(const UTF16BE& org)
	: m_iState(org.m_iState), m_tempChar(org.m_tempChar), m_leadChar(org.m_leadChar)
{}

bool Decoder::UTF16BE::operator() (uint8_t input, char32_t& output)
{
	// ״̬
	switch (m_iState)
	{
	case 0:
		m_tempChar = input << 8;
		m_iState = 1;
		return false;
	case 1:
		m_tempChar |= input;
		// ǷΪλ
		if (m_tempChar >= 0xD800u && m_tempChar < 0xDC00)
		{
			m_leadChar = m_tempChar - 0xD800u;
			m_iState = 2;
			return false;
		}
		else
		{
			output = static_cast<char32_t>(m_tempChar);
			m_iState = 0;
			return true;
		}
	case 2:
		m_tempChar = input << 8;
		m_iState = 3;
		return false;
	case 3:
		m_tempChar |= input;
		// ϲ
		if (m_tempChar >= 0xDC00u && m_tempChar < 0xE000)
		{
			output = static_cast<char32_t>((m_leadChar << 16) | (m_tempChar - 0xDC00u));
			m_iState = 0;
			return true;
		}
		else
			throw UnicodeEncodingError("invalid trailer character.");
	default:
		throw UnicodeEncodingError("internal error.");
	}
}

/* UTF8 ʵ */
Encoder::UTF8::UTF8() {}

Encoder::UTF8::UTF8(const UTF8& org) {}

bool Encoder::UTF8::operator() (char32_t input, uint8_t*& output, size_t& size)
{
	int c;
	uint32_t uinput = (uint32_t)input;

	if (uinput < 0x80u)
		c = 0;
	else if (uinput < 0x800u)
		c = 1;
	else if (uinput < 0x10000u)
		c = 2;
	else if (uinput < 0x200000u)
		c = 3;
	else if (uinput < 0x4000000u)
		c = 4;
	else if (uinput < 0x80000000u)
		c = 5;
	else
		throw UnicodeEncodingError("invalid utf32 character.");

	// ֽ
	for (int i = c; i > 0; --i)
	{
		m_cBuf[i] = (uinput & 0x3Fu) | 0x80u;
		uinput >>= 6;
	}

	// ֽ
	m_cBuf[0] = (0xFEu << (6 - c)) | uinput;

	// д
	output = m_cBuf;
	size = c + 1;
	return true;
}

/* UTF16 ʵ */
Encoder::UTF16::UTF16() {}

Encoder::UTF16::UTF16(const UTF16& org) {}

bool Encoder::UTF16::operator() (char32_t input, uint8_t*& output, size_t& size)
{
	// ǷҪλ
	if (input >= 0x10000u)
	{
		input -= 0x10000u;
		m_cBuf[0] = (input >> 10) | 0xD800u;    // ǰֽ
		m_cBuf[1] = (input & 0x3FFu) | 0xDC00u; // βֽ
		output = reinterpret_cast<uint8_t*>(m_cBuf);
		size = 2 * sizeof(char16_t);
		return true;
	}
	else
	{
		m_cBuf[0] = input;
		output = reinterpret_cast<uint8_t*>(m_cBuf);
		size = 1 * sizeof(char16_t);
		return true;
	}
}

/* UTF16LE ʵ */
Encoder::UTF16LE::UTF16LE() {}

Encoder::UTF16LE::UTF16LE(const UTF16LE& org) {}

bool Encoder::UTF16LE::operator() (char32_t input, uint8_t*& output, size_t& size)
{
	// ǷҪλ
	if (input >= 0x10000u)
	{
		input -= 0x10000u;
		uint16_t tLeadByte = (input >> 10) | 0xD800u;     // ǰֽ
		uint16_t tTrailByte = (input & 0x3FFu) | 0xDC00u; // βֽ
		m_cBuf[0] = tLeadByte & 0xFFu;
		m_cBuf[1] = (tLeadByte >> 8) & 0xFFu;
		m_cBuf[2] = tTrailByte & 0xFFu;
		m_cBuf[3] = (tTrailByte >> 8) & 0xFFu;
		output = m_cBuf;
		size = 4;
		return true;
	}
	else
	{
		m_cBuf[0] = input & 0xFFu;
		m_cBuf[1] = (input >> 8) & 0xFFu;
		output = m_cBuf;
		size = 2;
		return true;
	}
}

/* UTF16BE ʵ */
Encoder::UTF16BE::UTF16BE() {}

Encoder::UTF16BE::UTF16BE(const UTF16BE& org) {}

bool Encoder::UTF16BE::operator() (char32_t input, uint8_t*& output, size_t& size)
{
	// ǷҪλ
	if (input >= 0x10000u)
	{
		input -= 0x10000u;
		uint16_t tLeadByte = (input >> 10) | 0xD800u;     // ǰֽ
		uint16_t tTrailByte = (input & 0x3FFu) | 0xDC00u; // βֽ
		m_cBuf[0] = (tLeadByte >> 8) & 0xFFu;
		m_cBuf[1] = tLeadByte & 0xFFu;
		m_cBuf[2] = (tTrailByte >> 8) & 0xFFu;
		m_cBuf[3] = tTrailByte & 0xFFu;
		output = m_cBuf;
		size = 4;
		return true;
	}
	else
	{
		m_cBuf[0] = (input >> 8) & 0xFFu;
		m_cBuf[1] = input & 0xFFu;
		output = m_cBuf;
		size = 2;
		return true;
	}
}
<|endoftext|>


<commit_before>/**
 * @file line_corpus.cpp
 * @author Sean Massung
 */

#include <algorithm>
#include <iostream>
#include "io/parser.h"
#include "io/mmap_file.h"
#include "corpus/line_corpus.h"

namespace meta {
namespace corpus {

line_corpus::line_corpus(const std::string & file):
    _cur{0},
    _num_lines{0},
    _parser{file, "\n"}
{
    std::cerr << "Counting number of lines in corpus file..." << std::endl;
    _num_lines = common::num_lines(file);
    std::cerr << "Found " << _num_lines << " documents in corpus." << std::endl;
}

bool line_corpus::has_next() const
{
    return _parser.has_next();
}

document line_corpus::next()
{
    std::string content = _parser.next();
    size_t space = content.find_first_of(" ");
    std::string name = common::to_string(_cur) + "_" + content.substr(0, space);
    document d{name, doc_id{_cur++}};
    d.set_content(content);
    return d;
}

uint64_t line_corpus::size() const
{
    return _num_lines;
}

}
}
<commit_msg>add default label for line corpus based on first token (usually what we want)<commit_after>/**
 * @file line_corpus.cpp
 * @author Sean Massung
 */

#include <algorithm>
#include <iostream>
#include "io/parser.h"
#include "io/mmap_file.h"
#include "corpus/line_corpus.h"

namespace meta {
namespace corpus {

line_corpus::line_corpus(const std::string & file):
    _cur{0},
    _num_lines{0},
    _parser{file, "\n"}
{
    std::cerr << "Counting number of lines in corpus file..." << std::endl;
    _num_lines = common::num_lines(file);
    std::cerr << "Found " << _num_lines << " documents in corpus." << std::endl;
}

bool line_corpus::has_next() const
{
    return _parser.has_next();
}

document line_corpus::next()
{
    std::string content = _parser.next();
    size_t space = content.find_first_of(" ");
    std::string name = common::to_string(_cur) + "_" + content.substr(0, space);
    document d{name, doc_id{_cur++}, class_label{content.substr(0, space)}};
    d.set_content(content);
    return d;
}

uint64_t line_corpus::size() const
{
    return _num_lines;
}

}
}
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkConfig.h"
#include "mitkCoreObjectFactory.h"

#include "mitkAffineInteractor.h"
#include "mitkColorProperty.h"
#include "mitkCone.h"
#include "mitkContour.h"
#include "mitkContourMapper2D.h"
#include "mitkContourSetMapper2D.h"
#include "mitkContourSetVtkMapper3D.h"
#include "mitkContourVtkMapper3D.h"
#include "mitkCuboid.h"
#include "mitkCylinder.h"
#include "mitkDataTreeNode.h"
#include "mitkEllipsoid.h"
#include "mitkEnumerationProperty.h"
#include "mitkGeometry2DData.h"
#include "mitkGeometry2DDataMapper2D.h"
#include "mitkGeometry2DDataVtkMapper3D.h"
#include "mitkGeometry3D.h"
#include "mitkGeometryData.h"
#include "mitkImage.h"
#include "mitkImageMapper2D.h"
#include "mitkLevelWindowProperty.h"
#include "mitkLookupTable.h"
#include "mitkLookupTableProperty.h"
#include "mitkMaterialProperty.h"
#include "mitkMeshMapper2D.h"
#include "mitkMeshVtkMapper3D.h"
#include "mitkPlaneGeometry.h"
#include "mitkPointDataVtkMapper3D.h"
#include "mitkPointSet.h"
#include "mitkPointSetMapper2D.h"
#include "mitkPointSetVtkMapper3D.h"
#include "mitkPolyDataGLMapper2D.h"
#include "mitkProperties.h"
#include "mitkPropertyList.h"
#include "mitkSeedsImage.h"
#include "mitkSlicedGeometry3D.h"
#include "mitkSmartPointerProperty.h"
#include "mitkStringProperty.h"
#include "mitkSurface.h"
#include "mitkSurface.h"
#include "mitkSurfaceMapper2D.h"
#include "mitkSurfaceVtkMapper3D.h"
#include "mitkTimeSlicedGeometry.h"
#include "mitkTransferFunctionProperty.h"
#include "mitkVolumeDataVtkMapper3D.h"
#include "mitkVtkInterpolationProperty.h"
#include "mitkVtkRepresentationProperty.h"

#include "mitkPicFileIOFactory.h"
#include "mitkPointSetIOFactory.h"
#include "mitkItkImageFileIOFactory.h"
#include "mitkParRecFileIOFactory.h"
#include "mitkSTLFileIOFactory.h"
#include "mitkObjFileIOFactory.h"
#include "mitkVtkSurfaceIOFactory.h"
#include "mitkVtkImageIOFactory.h"
#include "mitkVtiFileIOFactory.h"
#include "mitkPicVolumeTimeSeriesIOFactory.h"
#include "mitkStlVolumeTimeSeriesIOFactory.h"
#include "mitkVtkVolumeTimeSeriesIOFactory.h"

#define CREATE_CPP( TYPE, NAME ) else if ( className == NAME ) {pointer = new TYPE(); pointer->Register();}
#define CREATE_ITK( TYPE, NAME ) else if ( className == NAME ) pointer = TYPE::New();

itk::Object::Pointer mitk::CoreObjectFactory::CreateCoreObject( const std::string& className )
{
  itk::Object::Pointer pointer;

  if ( className == "" )
    return NULL;

    CREATE_CPP( BoolProperty, "BoolProperty" )
    CREATE_CPP( IntProperty, "IntProperty" )
    CREATE_CPP( FloatProperty, "FloatProperty" )
    CREATE_CPP( DoubleProperty, "DoubleProperty" )
    CREATE_CPP( Vector3DProperty, "Vector3DProperty" )
    CREATE_CPP( Point3dProperty, "Point3dProperty" )
    CREATE_CPP( Point3iProperty, "Point3iProperty" )
    CREATE_CPP( BoolProperty, "BoolProperty" )
    CREATE_CPP( ColorProperty, "ColorProperty" )
    CREATE_CPP( LevelWindowProperty, "LevelWindowProperty" )
    CREATE_CPP( LookupTableProperty, "LookupTableProperty" )
    CREATE_CPP( MaterialProperty, "MaterialProperty" )
    CREATE_CPP( StringProperty, "StringProperty" )
    CREATE_CPP( SmartPointerProperty, "SmartPointerProperty" )
    CREATE_CPP( TransferFunctionProperty, "TransferFunctionProperty" )
    CREATE_CPP( EnumerationProperty, "EnumerationProperty" )
    CREATE_CPP( VtkInterpolationProperty, "VtkInterpolationProperty" )
    CREATE_CPP( VtkRepresentationProperty, "VtkRepresentationProperty" )
    CREATE_ITK( GeometryData, "GeometryData" )
    CREATE_ITK( Contour, "Contour" )
    CREATE_ITK( Surface, "Surface" )
    CREATE_ITK( Ellipsoid, "Ellipsoid" )
    CREATE_ITK( Cylinder, "Cylinder" )
    CREATE_ITK( Cuboid, "Cuboid" )
    CREATE_ITK( Cone, "Cone" )
    CREATE_ITK( Image, "Image" )
    CREATE_ITK( SeedsImage, "SeedsImage" )
    CREATE_ITK( Geometry3D, "Geometry3D" )
    CREATE_ITK( TimeSlicedGeometry, "TimeSlicedGeometry" )
    CREATE_ITK( Surface, "Surface" )
    CREATE_ITK( PointSet, "PointSet" )
    CREATE_ITK( SlicedGeometry3D, "SlicedGeometry3D" )
    CREATE_ITK( PlaneGeometry, "PlaneGeometry" )
    CREATE_ITK( PropertyList, "PropertyList" )
    CREATE_ITK( SurfaceMapper2D, "SurfaceMapper2D" )
    CREATE_ITK( SurfaceVtkMapper3D, "SurfaceVtkMapper3D" )
    CREATE_ITK( ImageMapper2D, "ImageMapper2D" )
    CREATE_ITK( VolumeDataVtkMapper3D, "VolumeDataVtkMapper3D" )
    CREATE_ITK( LookupTable, "LookupTable" )
    CREATE_ITK( PointSetMapper2D, "PointSetMapper2D" )
    CREATE_ITK( PointSetVtkMapper3D, "PointSetVtkMapper3D" )

  else
    std::cout << "ObjectFactory::CreateObject: unknown class: " << className << std::endl;

  return pointer;
}

mitk::CoreObjectFactory::Pointer mitk::CoreObjectFactory::GetInstance() {
  static mitk::CoreObjectFactory::Pointer instance;
  if (instance.IsNull()) {
    std::list<itk::LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("mitkCoreObjectFactoryBase");
    std::list<itk::LightObject::Pointer>::iterator factoryIt = allobjects.begin();
    while (instance.IsNull() && factoryIt != allobjects.end() ) {
      if (std::string("SBCoreObjectFactory") == (*factoryIt)->GetNameOfClass() ) {
        instance = dynamic_cast<mitk::CoreObjectFactory*>(factoryIt->GetPointer());
      }
      ++factoryIt;
    }
    factoryIt = allobjects.begin();
    while (instance.IsNull() && factoryIt != allobjects.end() ) {
      if ( std::string("QMCoreObjectFactory") == (*factoryIt)->GetNameOfClass() ) {
        instance = dynamic_cast<mitk::CoreObjectFactory*>(factoryIt->GetPointer());
      }
      ++factoryIt;
    }
    if (instance.IsNull()) {
      instance = mitk::CoreObjectFactory::New();
    }
    std::cout << "CoreObjectFactory: created instance of " << instance->GetNameOfClass() << std::endl;
  }
  return instance;
}

void mitk::CoreObjectFactory::SetDefaultProperties(mitk::DataTreeNode* node)
{
  // don't do anything. Implementation is in subclasses.
}

mitk::CoreObjectFactory::CoreObjectFactory()
{
  itk::ObjectFactoryBase::RegisterFactory( PicFileIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( PointSetIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( ParRecFileIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( STLFileIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( ObjFileIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( VtkSurfaceIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( VtkImageIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( VtiFileIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( ItkImageFileIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( PicVolumeTimeSeriesIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( StlVolumeTimeSeriesIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( VtkVolumeTimeSeriesIOFactory::New() );
}

mitk::Mapper::Pointer mitk::CoreObjectFactory::CreateMapper(mitk::DataTreeNode* node, MapperSlotId id)
{
  mitk::Mapper::Pointer newMapper=NULL;

  if(id==mitk::BaseRenderer::Standard2D)
  {
    if((dynamic_cast<Image*>(node->GetData()) != NULL))
    {
      mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(node->GetData());
      newMapper = mitk::ImageMapper2D::New();
      newMapper->SetDataTreeNode(node);
    }
    else
      if((dynamic_cast<Geometry2DData*>(node->GetData())!=NULL))
      {
        newMapper = mitk::Geometry2DDataMapper2D::New();
        newMapper->SetDataTreeNode(node);
      }
      else
        if((dynamic_cast<Surface*>(node->GetData())!=NULL))
        {
          newMapper = mitk::SurfaceMapper2D::New();
          // cast because SetDataTreeNode is not virtual
          mitk::SurfaceMapper2D *castedMapper = (mitk::SurfaceMapper2D*)newMapper.GetPointer();
          castedMapper->SetDataTreeNode(node);
        }
        else
          if((dynamic_cast<Mesh*>(node->GetData())!=NULL))
          {
            newMapper = mitk::MeshMapper2D::New();
            newMapper->SetDataTreeNode(node);
          }
          else
            if((dynamic_cast<PointSet*>(node->GetData())!=NULL))
            {
              newMapper = mitk::PointSetMapper2D::New();
              newMapper->SetDataTreeNode(node);
            }
    if((dynamic_cast<PointData*>(node->GetData())!=NULL))
    {
      newMapper = mitk::PolyDataGLMapper2D::New();
      newMapper->SetDataTreeNode(node);
    }
    else
      if((dynamic_cast<Contour*>(node->GetData())!=NULL))
      {
        newMapper = mitk::ContourMapper2D::New();
        newMapper->SetDataTreeNode(node);
      }
      else
        if((dynamic_cast<ContourSet*>(node->GetData())!=NULL))
        {
          newMapper = mitk::ContourSetMapper2D::New();
          newMapper->SetDataTreeNode(node);
        }
  }
  else
    if(id==mitk::BaseRenderer::Standard3D)
    {
      if((dynamic_cast<Image*>(node->GetData()) != NULL))
      {
        mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(node->GetData());
        if (image->GetPixelType().GetNumberOfComponents() <= 1)
        {
          newMapper = mitk::VolumeDataVtkMapper3D::New();
          newMapper->SetDataTreeNode(node);
        }
        else
        {
          //newMapper = mitk::VectorImageVtkGlyphMapper3D::New();
          //newMapper->SetDataTreeNode(node);
        }
      }
      else
        if((dynamic_cast<Geometry2DData*>(node->GetData())!=NULL))
        {
          newMapper = mitk::Geometry2DDataVtkMapper3D::New();
          newMapper->SetDataTreeNode(node);
        }
        else
          if((dynamic_cast<Surface*>(node->GetData())!=NULL))
          {
            newMapper = mitk::SurfaceVtkMapper3D::New();
            newMapper->SetDataTreeNode(node);
          }
          else
            if((dynamic_cast<Mesh*>(node->GetData())!=NULL))
            {
              newMapper = mitk::MeshVtkMapper3D::New();
              newMapper->SetDataTreeNode(node);
            }
            else
              if((dynamic_cast<PointSet*>(node->GetData())!=NULL))
              {
                newMapper = mitk::PointSetVtkMapper3D::New();
                newMapper->SetDataTreeNode(node);
              }
      if((dynamic_cast<PointData*>(node->GetData())!=NULL))
      {
        newMapper = mitk::PointDataVtkMapper3D::New();
        newMapper->SetDataTreeNode(node);
      }
      else
        if((dynamic_cast<Contour*>(node->GetData())!=NULL))
        {
          newMapper = mitk::ContourVtkMapper3D::New();
          newMapper->SetDataTreeNode(node);
        }
        else
          if((dynamic_cast<ContourSet*>(node->GetData())!=NULL))
          {
            newMapper = mitk::ContourSetVtkMapper3D::New();
            newMapper->SetDataTreeNode(node);
          }
    }
  return newMapper;
}

#define EXTERNAL_FILE_EXTENSIONS \
    "All known formats(*.dcm *.DCM *.gdcm *.ima *.mps *.pic *.pic.gz *.bmp *.png *.jpg *.tiff *.pvtk *.stl *.vtk *.vtp *.obj *.vti *.hdr);;" \
    "DICOM files(*.dcm *.DCM *.gdcm);;" \
    "DKFZ Pic (*.seq *.pic *.pic.gz *.seq.gz);;" \
    "Point sets (*.mps);;" \
    "Sets of 2D slices (*.pic *.pic.gz *.bmp *.png *.dcm *.gdcm *.ima *.tiff);;" \
    "Surface files (*.stl *.vtk *.vtp *.obj)"

#define INTERNAL_FILE_EXTENSIONS \
    "all (*.seq *.mps *.pic *.pic.gz *.seq.gz *.pvtk *.stl *.vtk *.vtp *.obj *.vti *.ves " \
         "*.uvg *.dvg *.par *.dcm *.gdcm *.ima *.mhd *.hdr hpsonos.db HPSONOS.DB *.ssm *msm *.bmp *.png *.jpg *.tiff);;" \
    "DKFZ Pic (*.seq *.pic *.pic.gz *.seq.gz);;" \
    "Point sets (*.mps);;" \
    "surface files (*.stl *.vtk *.vtp *.obj);;" \
    "stl files (*.stl);;" \
    "vtk surface files (*.vtk);;" \
    "vtk image files (*.pvtk);;" \
    "vessel files (*.ves *.uvg *.dvg);;" \
    "par/rec files (*.par);;" \
    "DSR files (hpsonos.db HPSONOS.DB);;" \
    "DICOM files (*.dcm *.gdcm *.ima)"

#define SAVE_FILE_EXTENSIONS "all (*.pic *.mhd *.vtk *.vti *.hdr *.png *.tiff *.jpg)"

const char* mitk::CoreObjectFactory::GetFileExtensions()
{
  return EXTERNAL_FILE_EXTENSIONS;
};

const char* mitk::CoreObjectFactory::GetSaveFileExtensions() {
  return SAVE_FILE_EXTENSIONS;
};

mitk::CoreObjectFactory::FileWriterList mitk::CoreObjectFactory::GetFileWriters() {
  return m_FileWriters;
}
void mitk::CoreObjectFactory::MapEvent(const mitk::Event*, const int) {

}
<commit_msg>ENH: added point4dproperty<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkConfig.h"
#include "mitkCoreObjectFactory.h"

#include "mitkAffineInteractor.h"
#include "mitkColorProperty.h"
#include "mitkCone.h"
#include "mitkContour.h"
#include "mitkContourMapper2D.h"
#include "mitkContourSetMapper2D.h"
#include "mitkContourSetVtkMapper3D.h"
#include "mitkContourVtkMapper3D.h"
#include "mitkCuboid.h"
#include "mitkCylinder.h"
#include "mitkDataTreeNode.h"
#include "mitkEllipsoid.h"
#include "mitkEnumerationProperty.h"
#include "mitkGeometry2DData.h"
#include "mitkGeometry2DDataMapper2D.h"
#include "mitkGeometry2DDataVtkMapper3D.h"
#include "mitkGeometry3D.h"
#include "mitkGeometryData.h"
#include "mitkImage.h"
#include "mitkImageMapper2D.h"
#include "mitkLevelWindowProperty.h"
#include "mitkLookupTable.h"
#include "mitkLookupTableProperty.h"
#include "mitkMaterialProperty.h"
#include "mitkMeshMapper2D.h"
#include "mitkMeshVtkMapper3D.h"
#include "mitkPlaneGeometry.h"
#include "mitkPointDataVtkMapper3D.h"
#include "mitkPointSet.h"
#include "mitkPointSetMapper2D.h"
#include "mitkPointSetVtkMapper3D.h"
#include "mitkPolyDataGLMapper2D.h"
#include "mitkProperties.h"
#include "mitkPropertyList.h"
#include "mitkSeedsImage.h"
#include "mitkSlicedGeometry3D.h"
#include "mitkSmartPointerProperty.h"
#include "mitkStringProperty.h"
#include "mitkSurface.h"
#include "mitkSurface.h"
#include "mitkSurfaceMapper2D.h"
#include "mitkSurfaceVtkMapper3D.h"
#include "mitkTimeSlicedGeometry.h"
#include "mitkTransferFunctionProperty.h"
#include "mitkVolumeDataVtkMapper3D.h"
#include "mitkVtkInterpolationProperty.h"
#include "mitkVtkRepresentationProperty.h"

#include "mitkPicFileIOFactory.h"
#include "mitkPointSetIOFactory.h"
#include "mitkItkImageFileIOFactory.h"
#include "mitkParRecFileIOFactory.h"
#include "mitkSTLFileIOFactory.h"
#include "mitkObjFileIOFactory.h"
#include "mitkVtkSurfaceIOFactory.h"
#include "mitkVtkImageIOFactory.h"
#include "mitkVtiFileIOFactory.h"
#include "mitkPicVolumeTimeSeriesIOFactory.h"
#include "mitkStlVolumeTimeSeriesIOFactory.h"
#include "mitkVtkVolumeTimeSeriesIOFactory.h"

#define CREATE_CPP( TYPE, NAME ) else if ( className == NAME ) {pointer = new TYPE(); pointer->Register();}
#define CREATE_ITK( TYPE, NAME ) else if ( className == NAME ) pointer = TYPE::New();

itk::Object::Pointer mitk::CoreObjectFactory::CreateCoreObject( const std::string& className )
{
  itk::Object::Pointer pointer;

  if ( className == "" )
    return NULL;

    CREATE_CPP( BoolProperty, "BoolProperty" )
    CREATE_CPP( IntProperty, "IntProperty" )
    CREATE_CPP( FloatProperty, "FloatProperty" )
    CREATE_CPP( DoubleProperty, "DoubleProperty" )
    CREATE_CPP( Vector3DProperty, "Vector3DProperty" )
    CREATE_CPP( Point3dProperty, "Point3dProperty" )
    CREATE_CPP( Point4dProperty, "Point4dProperty" )
    CREATE_CPP( Point3iProperty, "Point3iProperty" )
    CREATE_CPP( BoolProperty, "BoolProperty" )
    CREATE_CPP( ColorProperty, "ColorProperty" )
    CREATE_CPP( LevelWindowProperty, "LevelWindowProperty" )
    CREATE_CPP( LookupTableProperty, "LookupTableProperty" )
    CREATE_CPP( MaterialProperty, "MaterialProperty" )
    CREATE_CPP( StringProperty, "StringProperty" )
    CREATE_CPP( SmartPointerProperty, "SmartPointerProperty" )
    CREATE_CPP( TransferFunctionProperty, "TransferFunctionProperty" )
    CREATE_CPP( EnumerationProperty, "EnumerationProperty" )
    CREATE_CPP( VtkInterpolationProperty, "VtkInterpolationProperty" )
    CREATE_CPP( VtkRepresentationProperty, "VtkRepresentationProperty" )
    CREATE_ITK( GeometryData, "GeometryData" )
    CREATE_ITK( Contour, "Contour" )
    CREATE_ITK( Surface, "Surface" )
    CREATE_ITK( Ellipsoid, "Ellipsoid" )
    CREATE_ITK( Cylinder, "Cylinder" )
    CREATE_ITK( Cuboid, "Cuboid" )
    CREATE_ITK( Cone, "Cone" )
    CREATE_ITK( Image, "Image" )
    CREATE_ITK( SeedsImage, "SeedsImage" )
    CREATE_ITK( Geometry3D, "Geometry3D" )
    CREATE_ITK( TimeSlicedGeometry, "TimeSlicedGeometry" )
    CREATE_ITK( Surface, "Surface" )
    CREATE_ITK( PointSet, "PointSet" )
    CREATE_ITK( SlicedGeometry3D, "SlicedGeometry3D" )
    CREATE_ITK( PlaneGeometry, "PlaneGeometry" )
    CREATE_ITK( PropertyList, "PropertyList" )
    CREATE_ITK( SurfaceMapper2D, "SurfaceMapper2D" )
    CREATE_ITK( SurfaceVtkMapper3D, "SurfaceVtkMapper3D" )
    CREATE_ITK( ImageMapper2D, "ImageMapper2D" )
    CREATE_ITK( VolumeDataVtkMapper3D, "VolumeDataVtkMapper3D" )
    CREATE_ITK( LookupTable, "LookupTable" )
    CREATE_ITK( PointSetMapper2D, "PointSetMapper2D" )
    CREATE_ITK( PointSetVtkMapper3D, "PointSetVtkMapper3D" )

  else
    std::cout << "ObjectFactory::CreateObject: unknown class: " << className << std::endl;

  return pointer;
}

mitk::CoreObjectFactory::Pointer mitk::CoreObjectFactory::GetInstance() {
  static mitk::CoreObjectFactory::Pointer instance;
  if (instance.IsNull()) {
    std::list<itk::LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("mitkCoreObjectFactoryBase");
    std::list<itk::LightObject::Pointer>::iterator factoryIt = allobjects.begin();
    while (instance.IsNull() && factoryIt != allobjects.end() ) {
      if (std::string("SBCoreObjectFactory") == (*factoryIt)->GetNameOfClass() ) {
        instance = dynamic_cast<mitk::CoreObjectFactory*>(factoryIt->GetPointer());
      }
      ++factoryIt;
    }
    factoryIt = allobjects.begin();
    while (instance.IsNull() && factoryIt != allobjects.end() ) {
      if ( std::string("QMCoreObjectFactory") == (*factoryIt)->GetNameOfClass() ) {
        instance = dynamic_cast<mitk::CoreObjectFactory*>(factoryIt->GetPointer());
      }
      ++factoryIt;
    }
    if (instance.IsNull()) {
      instance = mitk::CoreObjectFactory::New();
    }
    std::cout << "CoreObjectFactory: created instance of " << instance->GetNameOfClass() << std::endl;
  }
  return instance;
}

void mitk::CoreObjectFactory::SetDefaultProperties(mitk::DataTreeNode* node)
{
  // don't do anything. Implementation is in subclasses.
}

mitk::CoreObjectFactory::CoreObjectFactory()
{
  itk::ObjectFactoryBase::RegisterFactory( PicFileIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( PointSetIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( ParRecFileIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( STLFileIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( ObjFileIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( VtkSurfaceIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( VtkImageIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( VtiFileIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( ItkImageFileIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( PicVolumeTimeSeriesIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( StlVolumeTimeSeriesIOFactory::New() );
  itk::ObjectFactoryBase::RegisterFactory( VtkVolumeTimeSeriesIOFactory::New() );
}

mitk::Mapper::Pointer mitk::CoreObjectFactory::CreateMapper(mitk::DataTreeNode* node, MapperSlotId id)
{
  mitk::Mapper::Pointer newMapper=NULL;

  if(id==mitk::BaseRenderer::Standard2D)
  {
    if((dynamic_cast<Image*>(node->GetData()) != NULL))
    {
      mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(node->GetData());
      newMapper = mitk::ImageMapper2D::New();
      newMapper->SetDataTreeNode(node);
    }
    else
      if((dynamic_cast<Geometry2DData*>(node->GetData())!=NULL))
      {
        newMapper = mitk::Geometry2DDataMapper2D::New();
        newMapper->SetDataTreeNode(node);
      }
      else
        if((dynamic_cast<Surface*>(node->GetData())!=NULL))
        {
          newMapper = mitk::SurfaceMapper2D::New();
          // cast because SetDataTreeNode is not virtual
          mitk::SurfaceMapper2D *castedMapper = (mitk::SurfaceMapper2D*)newMapper.GetPointer();
          castedMapper->SetDataTreeNode(node);
        }
        else
          if((dynamic_cast<Mesh*>(node->GetData())!=NULL))
          {
            newMapper = mitk::MeshMapper2D::New();
            newMapper->SetDataTreeNode(node);
          }
          else
            if((dynamic_cast<PointSet*>(node->GetData())!=NULL))
            {
              newMapper = mitk::PointSetMapper2D::New();
              newMapper->SetDataTreeNode(node);
            }
    if((dynamic_cast<PointData*>(node->GetData())!=NULL))
    {
      newMapper = mitk::PolyDataGLMapper2D::New();
      newMapper->SetDataTreeNode(node);
    }
    else
      if((dynamic_cast<Contour*>(node->GetData())!=NULL))
      {
        newMapper = mitk::ContourMapper2D::New();
        newMapper->SetDataTreeNode(node);
      }
      else
        if((dynamic_cast<ContourSet*>(node->GetData())!=NULL))
        {
          newMapper = mitk::ContourSetMapper2D::New();
          newMapper->SetDataTreeNode(node);
        }
  }
  else
    if(id==mitk::BaseRenderer::Standard3D)
    {
      if((dynamic_cast<Image*>(node->GetData()) != NULL))
      {
        mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(node->GetData());
        if (image->GetPixelType().GetNumberOfComponents() <= 1)
        {
          newMapper = mitk::VolumeDataVtkMapper3D::New();
          newMapper->SetDataTreeNode(node);
        }
        else
        {
          //newMapper = mitk::VectorImageVtkGlyphMapper3D::New();
          //newMapper->SetDataTreeNode(node);
        }
      }
      else
        if((dynamic_cast<Geometry2DData*>(node->GetData())!=NULL))
        {
          newMapper = mitk::Geometry2DDataVtkMapper3D::New();
          newMapper->SetDataTreeNode(node);
        }
        else
          if((dynamic_cast<Surface*>(node->GetData())!=NULL))
          {
            newMapper = mitk::SurfaceVtkMapper3D::New();
            newMapper->SetDataTreeNode(node);
          }
          else
            if((dynamic_cast<Mesh*>(node->GetData())!=NULL))
            {
              newMapper = mitk::MeshVtkMapper3D::New();
              newMapper->SetDataTreeNode(node);
            }
            else
              if((dynamic_cast<PointSet*>(node->GetData())!=NULL))
              {
                newMapper = mitk::PointSetVtkMapper3D::New();
                newMapper->SetDataTreeNode(node);
              }
      if((dynamic_cast<PointData*>(node->GetData())!=NULL))
      {
        newMapper = mitk::PointDataVtkMapper3D::New();
        newMapper->SetDataTreeNode(node);
      }
      else
        if((dynamic_cast<Contour*>(node->GetData())!=NULL))
        {
          newMapper = mitk::ContourVtkMapper3D::New();
          newMapper->SetDataTreeNode(node);
        }
        else
          if((dynamic_cast<ContourSet*>(node->GetData())!=NULL))
          {
            newMapper = mitk::ContourSetVtkMapper3D::New();
            newMapper->SetDataTreeNode(node);
          }
    }
  return newMapper;
}

#define EXTERNAL_FILE_EXTENSIONS \
    "All known formats(*.dcm *.DCM *.gdcm *.ima *.mps *.pic *.pic.gz *.bmp *.png *.jpg *.tiff *.pvtk *.stl *.vtk *.vtp *.obj *.vti *.hdr);;" \
    "DICOM files(*.dcm *.DCM *.gdcm);;" \
    "DKFZ Pic (*.seq *.pic *.pic.gz *.seq.gz);;" \
    "Point sets (*.mps);;" \
    "Sets of 2D slices (*.pic *.pic.gz *.bmp *.png *.dcm *.gdcm *.ima *.tiff);;" \
    "Surface files (*.stl *.vtk *.vtp *.obj)"

#define INTERNAL_FILE_EXTENSIONS \
    "all (*.seq *.mps *.pic *.pic.gz *.seq.gz *.pvtk *.stl *.vtk *.vtp *.obj *.vti *.ves " \
         "*.uvg *.dvg *.par *.dcm *.gdcm *.ima *.mhd *.hdr hpsonos.db HPSONOS.DB *.ssm *msm *.bmp *.png *.jpg *.tiff);;" \
    "DKFZ Pic (*.seq *.pic *.pic.gz *.seq.gz);;" \
    "Point sets (*.mps);;" \
    "surface files (*.stl *.vtk *.vtp *.obj);;" \
    "stl files (*.stl);;" \
    "vtk surface files (*.vtk);;" \
    "vtk image files (*.pvtk);;" \
    "vessel files (*.ves *.uvg *.dvg);;" \
    "par/rec files (*.par);;" \
    "DSR files (hpsonos.db HPSONOS.DB);;" \
    "DICOM files (*.dcm *.gdcm *.ima)"

#define SAVE_FILE_EXTENSIONS "all (*.pic *.mhd *.vtk *.vti *.hdr *.png *.tiff *.jpg)"

const char* mitk::CoreObjectFactory::GetFileExtensions()
{
  return EXTERNAL_FILE_EXTENSIONS;
};

const char* mitk::CoreObjectFactory::GetSaveFileExtensions() {
  return SAVE_FILE_EXTENSIONS;
};

mitk::CoreObjectFactory::FileWriterList mitk::CoreObjectFactory::GetFileWriters() {
  return m_FileWriters;
}
void mitk::CoreObjectFactory::MapEvent(const mitk::Event*, const int) {

}
<|endoftext|>


<commit_before>/*===================================================================

 The Medical Imaging Interaction Toolkit (MITK)

 Copyright (c) German Cancer Research Center,
 Division of Medical and Biological Informatics.
 All rights reserved.

 This software is distributed WITHOUT ANY WARRANTY; without
 even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.

 See LICENSE.txt or http://www.mitk.org for details.

 ===================================================================*/

#include "mitkDispatcher.h"
#include "mitkInteractionEvent.h"
#include "mitkInternalEvent.h"

// MicroServices
#include "usGetModuleContext.h"

#include "mitkInteractionEventObserver.h"

mitk::Dispatcher::Dispatcher( const std::string& rendererName )
: m_ProcessingMode(REGULAR)
{
  // LDAP filter string to find all listeners specific for the renderer
  // corresponding to this dispatcher
  std::string specificRenderer = "(rendererName=" + rendererName +")";

  // LDAP filter string to find all listeners that are not specific
  // to any renderer
  std::string anyRenderer = "(!(rendererName=*))";

  // LDAP filter string to find only instances of  InteractionEventObserver
  // The '*' is needed because of some namespace issues
  std::string classInteractionEventObserver = "(" + us::ServiceConstants::OBJECTCLASS() + "=*InteractionEventObserver)";

  // Configure the LDAP filter to find all instances of InteractionEventObserver
  // that are specific to this dispatcher or unspecific to any dispatchers (real global listener)
  us::LDAPFilter filter( "(&(|"+ specificRenderer  + anyRenderer + ")"+classInteractionEventObserver+")" );

  // Give the filter to the ObserverTracker
  m_EventObserverTracker = new us::ServiceTracker<InteractionEventObserver>(us::GetModuleContext(), filter);
  m_EventObserverTracker->Open();
}

void mitk::Dispatcher::AddDataInteractor(const DataNode* dataNode)
{
  RemoveDataInteractor(dataNode);
  RemoveOrphanedInteractors();
  DataInteractor::Pointer dataInteractor = dataNode->GetDataInteractor();
  if (dataInteractor.IsNotNull())
  {
    m_Interactors.push_back(dataInteractor);
  }
}

/*
 * Note: One DataInteractor can only have one DataNode and vice versa,
 * BUT the m_Interactors list may contain another DataInteractor that is still connected to this DataNode,
 * in this case we have to remove >1 DataInteractor. (Some special case of switching DataNodes between DataInteractors and registering a
 * DataNode to a DataStorage after assigning it to an DataInteractor)
 */

void mitk::Dispatcher::RemoveDataInteractor(const DataNode* dataNode)
{
  for (ListInteractorType::iterator it = m_Interactors.begin(); it != m_Interactors.end();)
  {
    if ((*it)->GetDataNode() == dataNode)
    {
      it = m_Interactors.erase(it);
    }
    else
    {
      ++it;
    }
  }
}

size_t mitk::Dispatcher::GetNumberOfInteractors()
{
  return m_Interactors.size();
}

mitk::Dispatcher::~Dispatcher()
{
  m_EventObserverTracker->Close();
  delete m_EventObserverTracker;

  m_Interactors.clear();
}

bool mitk::Dispatcher::ProcessEvent(InteractionEvent* event)
{
  InteractionEvent::Pointer p = event;
  //MITK_INFO << event->GetEventClass();
  bool eventIsHandled = false;
  /* Filter out and handle Internal Events separately */
  InternalEvent* internalEvent = dynamic_cast<InternalEvent*>(event);
  if (internalEvent != NULL)
  {
    eventIsHandled = HandleInternalEvent(internalEvent);
    // InternalEvents that are handled are not sent to the listeners
    if (eventIsHandled)
    {
      return true;
    }
  }
  switch (m_ProcessingMode)
  {
  case CONNECTEDMOUSEACTION:
    // finished connected mouse action
    if (std::strcmp(p->GetNameOfClass(), "MouseReleaseEvent") == 0)
    {
      m_ProcessingMode = REGULAR;
      eventIsHandled = m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode());
    }
    // give event to selected interactor
    if (eventIsHandled == false)
    {
      eventIsHandled = m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode());
    }
    break;

  case GRABINPUT:
    eventIsHandled = m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode());
    SetEventProcessingMode(m_SelectedInteractor);
    break;

  case PREFERINPUT:
    if (m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode()) == true)
    {
      SetEventProcessingMode(m_SelectedInteractor);
      eventIsHandled = true;
    }
    break;

  case REGULAR:
    break;
  }
  // Standard behavior. Is executed in STANDARD mode  and PREFERINPUT mode, if preferred interactor rejects event.
  if (m_ProcessingMode == REGULAR || (m_ProcessingMode == PREFERINPUT && eventIsHandled == false))
  {
    m_Interactors.sort(cmp()); // sorts interactors by layer (descending);

    // copy the list to prevent iterator invalidation as executing actions
    // in HandleEvent() can cause the m_Interactors list to be updated
    std::list<DataInteractor::Pointer> tmpInteractorList( m_Interactors );
    std::list<DataInteractor::Pointer>::iterator it;
    for ( it=tmpInteractorList.begin(); it!=tmpInteractorList.end(); it++ )
    {
      DataInteractor::Pointer dataInteractor = *it;
      if ( (*it)->HandleEvent(event, dataInteractor->GetDataNode()) )
      { // if an event is handled several properties are checked, in order to determine the processing mode of the dispatcher
        SetEventProcessingMode(dataInteractor);
        if (std::strcmp(p->GetNameOfClass(), "MousePressEvent") == 0 && m_ProcessingMode == REGULAR)
        {
          m_SelectedInteractor = dataInteractor;
          m_ProcessingMode = CONNECTEDMOUSEACTION;
        }
        eventIsHandled = true;
        break;
      }
    }
  }

  /* Notify InteractionEventObserver  */
  std::vector<us::ServiceReference<InteractionEventObserver> > listEventObserver =
      m_EventObserverTracker->GetServiceReferences();
  for (std::vector<us::ServiceReference<InteractionEventObserver> >::iterator it = listEventObserver.begin();
       it != listEventObserver.end(); ++it)
  {
    InteractionEventObserver* interactionEventObserver = m_EventObserverTracker->GetService(*it);
    if (interactionEventObserver != NULL)
    {
      if (interactionEventObserver->IsEnabled())
      {
        interactionEventObserver->Notify(event, eventIsHandled);
      }
    }
  }

  // Process event queue
  if (!m_QueuedEvents.empty())
  {
    InteractionEvent::Pointer e = m_QueuedEvents.front();
    m_QueuedEvents.pop_front();
    ProcessEvent(e);
  }
  return eventIsHandled;
}

/*
 * Checks if DataNodes associated with DataInteractors point back to them.
 * If not remove the DataInteractors. (This can happen when s.o. tries to set DataNodes to multiple DataInteractors)
 */
void mitk::Dispatcher::RemoveOrphanedInteractors()
{
  for (ListInteractorType::iterator it = m_Interactors.begin(); it != m_Interactors.end();)
  {
    DataNode::Pointer dn = (*it)->GetDataNode();
    if (dn.IsNull())
    {
      it = m_Interactors.erase(it);
    }
    else
    {
      DataInteractor::Pointer interactor = dn->GetDataInteractor();
      if (interactor != it->GetPointer())
      {
        it = m_Interactors.erase(it);
      }
      else
      {
        ++it;
      }
    }
  }
}

void mitk::Dispatcher::QueueEvent(InteractionEvent* event)
{
  m_QueuedEvents.push_back(event);
}

void mitk::Dispatcher::SetEventProcessingMode(DataInteractor::Pointer dataInteractor)
{
  m_ProcessingMode = dataInteractor->GetMode();
  if (dataInteractor->GetMode() != REGULAR)
  {
    m_SelectedInteractor = dataInteractor;
  }
}

bool mitk::Dispatcher::HandleInternalEvent(InternalEvent* internalEvent)
{
  if (internalEvent->GetSignalName() == DataInteractor::IntDeactivateMe &&
      internalEvent->GetTargetInteractor() != NULL)
  {
    internalEvent->GetTargetInteractor()->GetDataNode()->SetDataInteractor(NULL);
    internalEvent->GetTargetInteractor()->SetDataNode(NULL);

    mitk::RenderingManager::GetInstance()->RequestUpdateAll();
    return true;
  }
  return false;
}
<commit_msg>Don not hard code interface ids in filter expressions.<commit_after>/*===================================================================

 The Medical Imaging Interaction Toolkit (MITK)

 Copyright (c) German Cancer Research Center,
 Division of Medical and Biological Informatics.
 All rights reserved.

 This software is distributed WITHOUT ANY WARRANTY; without
 even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.

 See LICENSE.txt or http://www.mitk.org for details.

 ===================================================================*/

#include "mitkDispatcher.h"
#include "mitkInteractionEvent.h"
#include "mitkInternalEvent.h"

// MicroServices
#include "usGetModuleContext.h"

#include "mitkInteractionEventObserver.h"

mitk::Dispatcher::Dispatcher( const std::string& rendererName )
: m_ProcessingMode(REGULAR)
{
  // LDAP filter string to find all listeners specific for the renderer
  // corresponding to this dispatcher
  std::string specificRenderer = "(rendererName=" + rendererName +")";

  // LDAP filter string to find all listeners that are not specific
  // to any renderer
  std::string anyRenderer = "(!(rendererName=*))";

  // LDAP filter string to find only instances of  InteractionEventObserver
  std::string classInteractionEventObserver = "(" + us::ServiceConstants::OBJECTCLASS() + "=" + us_service_interface_iid<InteractionEventObserver>() + ")";

  // Configure the LDAP filter to find all instances of InteractionEventObserver
  // that are specific to this dispatcher or unspecific to any dispatchers (real global listener)
  us::LDAPFilter filter( "(&(|"+ specificRenderer  + anyRenderer + ")"+classInteractionEventObserver+")" );

  // Give the filter to the ObserverTracker
  m_EventObserverTracker = new us::ServiceTracker<InteractionEventObserver>(us::GetModuleContext(), filter);
  m_EventObserverTracker->Open();
}

void mitk::Dispatcher::AddDataInteractor(const DataNode* dataNode)
{
  RemoveDataInteractor(dataNode);
  RemoveOrphanedInteractors();
  DataInteractor::Pointer dataInteractor = dataNode->GetDataInteractor();
  if (dataInteractor.IsNotNull())
  {
    m_Interactors.push_back(dataInteractor);
  }
}

/*
 * Note: One DataInteractor can only have one DataNode and vice versa,
 * BUT the m_Interactors list may contain another DataInteractor that is still connected to this DataNode,
 * in this case we have to remove >1 DataInteractor. (Some special case of switching DataNodes between DataInteractors and registering a
 * DataNode to a DataStorage after assigning it to an DataInteractor)
 */

void mitk::Dispatcher::RemoveDataInteractor(const DataNode* dataNode)
{
  for (ListInteractorType::iterator it = m_Interactors.begin(); it != m_Interactors.end();)
  {
    if ((*it)->GetDataNode() == dataNode)
    {
      it = m_Interactors.erase(it);
    }
    else
    {
      ++it;
    }
  }
}

size_t mitk::Dispatcher::GetNumberOfInteractors()
{
  return m_Interactors.size();
}

mitk::Dispatcher::~Dispatcher()
{
  m_EventObserverTracker->Close();
  delete m_EventObserverTracker;

  m_Interactors.clear();
}

bool mitk::Dispatcher::ProcessEvent(InteractionEvent* event)
{
  InteractionEvent::Pointer p = event;
  //MITK_INFO << event->GetEventClass();
  bool eventIsHandled = false;
  /* Filter out and handle Internal Events separately */
  InternalEvent* internalEvent = dynamic_cast<InternalEvent*>(event);
  if (internalEvent != NULL)
  {
    eventIsHandled = HandleInternalEvent(internalEvent);
    // InternalEvents that are handled are not sent to the listeners
    if (eventIsHandled)
    {
      return true;
    }
  }
  switch (m_ProcessingMode)
  {
  case CONNECTEDMOUSEACTION:
    // finished connected mouse action
    if (std::strcmp(p->GetNameOfClass(), "MouseReleaseEvent") == 0)
    {
      m_ProcessingMode = REGULAR;
      eventIsHandled = m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode());
    }
    // give event to selected interactor
    if (eventIsHandled == false)
    {
      eventIsHandled = m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode());
    }
    break;

  case GRABINPUT:
    eventIsHandled = m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode());
    SetEventProcessingMode(m_SelectedInteractor);
    break;

  case PREFERINPUT:
    if (m_SelectedInteractor->HandleEvent(event, m_SelectedInteractor->GetDataNode()) == true)
    {
      SetEventProcessingMode(m_SelectedInteractor);
      eventIsHandled = true;
    }
    break;

  case REGULAR:
    break;
  }
  // Standard behavior. Is executed in STANDARD mode  and PREFERINPUT mode, if preferred interactor rejects event.
  if (m_ProcessingMode == REGULAR || (m_ProcessingMode == PREFERINPUT && eventIsHandled == false))
  {
    m_Interactors.sort(cmp()); // sorts interactors by layer (descending);

    // copy the list to prevent iterator invalidation as executing actions
    // in HandleEvent() can cause the m_Interactors list to be updated
    std::list<DataInteractor::Pointer> tmpInteractorList( m_Interactors );
    std::list<DataInteractor::Pointer>::iterator it;
    for ( it=tmpInteractorList.begin(); it!=tmpInteractorList.end(); it++ )
    {
      DataInteractor::Pointer dataInteractor = *it;
      if ( (*it)->HandleEvent(event, dataInteractor->GetDataNode()) )
      { // if an event is handled several properties are checked, in order to determine the processing mode of the dispatcher
        SetEventProcessingMode(dataInteractor);
        if (std::strcmp(p->GetNameOfClass(), "MousePressEvent") == 0 && m_ProcessingMode == REGULAR)
        {
          m_SelectedInteractor = dataInteractor;
          m_ProcessingMode = CONNECTEDMOUSEACTION;
        }
        eventIsHandled = true;
        break;
      }
    }
  }

  /* Notify InteractionEventObserver  */
  std::vector<us::ServiceReference<InteractionEventObserver> > listEventObserver =
      m_EventObserverTracker->GetServiceReferences();
  for (std::vector<us::ServiceReference<InteractionEventObserver> >::iterator it = listEventObserver.begin();
       it != listEventObserver.end(); ++it)
  {
    InteractionEventObserver* interactionEventObserver = m_EventObserverTracker->GetService(*it);
    if (interactionEventObserver != NULL)
    {
      if (interactionEventObserver->IsEnabled())
      {
        interactionEventObserver->Notify(event, eventIsHandled);
      }
    }
  }

  // Process event queue
  if (!m_QueuedEvents.empty())
  {
    InteractionEvent::Pointer e = m_QueuedEvents.front();
    m_QueuedEvents.pop_front();
    ProcessEvent(e);
  }
  return eventIsHandled;
}

/*
 * Checks if DataNodes associated with DataInteractors point back to them.
 * If not remove the DataInteractors. (This can happen when s.o. tries to set DataNodes to multiple DataInteractors)
 */
void mitk::Dispatcher::RemoveOrphanedInteractors()
{
  for (ListInteractorType::iterator it = m_Interactors.begin(); it != m_Interactors.end();)
  {
    DataNode::Pointer dn = (*it)->GetDataNode();
    if (dn.IsNull())
    {
      it = m_Interactors.erase(it);
    }
    else
    {
      DataInteractor::Pointer interactor = dn->GetDataInteractor();
      if (interactor != it->GetPointer())
      {
        it = m_Interactors.erase(it);
      }
      else
      {
        ++it;
      }
    }
  }
}

void mitk::Dispatcher::QueueEvent(InteractionEvent* event)
{
  m_QueuedEvents.push_back(event);
}

void mitk::Dispatcher::SetEventProcessingMode(DataInteractor::Pointer dataInteractor)
{
  m_ProcessingMode = dataInteractor->GetMode();
  if (dataInteractor->GetMode() != REGULAR)
  {
    m_SelectedInteractor = dataInteractor;
  }
}

bool mitk::Dispatcher::HandleInternalEvent(InternalEvent* internalEvent)
{
  if (internalEvent->GetSignalName() == DataInteractor::IntDeactivateMe &&
      internalEvent->GetTargetInteractor() != NULL)
  {
    internalEvent->GetTargetInteractor()->GetDataNode()->SetDataInteractor(NULL);
    internalEvent->GetTargetInteractor()->SetDataNode(NULL);

    mitk::RenderingManager::GetInstance()->RequestUpdateAll();
    return true;
  }
  return false;
}
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <mitkSeedsInteractor.h>

#include <mitkProperties.h>
#include <mitkStringProperty.h>
#include <mitkAction.h>
#include <mitkDisplayPositionEvent.h>
#include <mitkOperationEvent.h>
#include <mitkInteractionConst.h>
#include <mitkUndoController.h>
#include <mitkDataTreeNode.h>
#include <mitkStateEvent.h>
#include <mitkState.h>
#include <mitkDrawOperation.h>

mitk::SeedsInteractor::SeedsInteractor(const char * type, mitk::DataTreeNode* dataTreeNode)
  : mitk::Interactor(type, dataTreeNode)
{
  m_Radius = 4;
}

mitk::SeedsInteractor::~SeedsInteractor()
{
}

bool mitk::SeedsInteractor::ExecuteAction(mitk::Action* action, mitk::StateEvent const* stateEvent)
{
  const mitk::DisplayPositionEvent* posEvent = dynamic_cast<const mitk::DisplayPositionEvent*>(stateEvent->GetEvent());
  if (posEvent == NULL)
    return false;

  event_point = posEvent->GetWorldPosition();

  m_SeedsImage = dynamic_cast<mitk::SeedsImage*>(m_DataTreeNode->GetData());

  bool ok = false;
  switch (action->GetActionId())
  {
  case mitk::AcINITFOREGROUND:
    {
      m_DrawState = 255;
      ok = true;
      break;
    }
  case mitk::AcINITBACKGROUND:
    {
      m_DrawState = 254;
      ok = true;
      break;
    }
  case mitk::AcINITNEUTRAL:
    {
      m_DrawState = 0;
      ok = true;
      break;
    }
  case mitk::AcADD:
    {
			last_point = event_point;
      mitk::DrawOperation* doOp = new mitk::DrawOperation(OpADD, event_point, last_point, m_DrawState, m_Radius);
      if (m_UndoEnabled){	//write to UndoMechanism/ Can probably be removed!
        mitk::DrawOperation* undoOp = new mitk::DrawOperation(OpUNDOADD, event_point, last_point, m_DrawState, m_Radius);
        mitk::OperationEvent *operationEvent = new mitk::OperationEvent(m_SeedsImage, doOp, undoOp);
			  m_UndoController->SetOperationEvent(operationEvent);
	    }
		  //execute the Operation
		  m_SeedsImage->ExecuteOperation(doOp);
      ok = true;
      break;
    }
  case mitk::AcMOVE:
    {
			last_point = event_point;
      mitk::DrawOperation* doOp = new mitk::DrawOperation(OpMOVE, event_point, last_point, m_DrawState, m_Radius);
      if (m_UndoEnabled){	//write to UndoMechanism/ Can probably be removed!
        mitk::DrawOperation* undoOp = new mitk::DrawOperation(OpUNDOMOVE, event_point, last_point, m_DrawState, m_Radius);
        mitk::OperationEvent *operationEvent = new mitk::OperationEvent(m_SeedsImage, doOp, undoOp);
			  m_UndoController->SetOperationEvent(operationEvent);
	    }
		  //execute the Operation
		  m_SeedsImage->ExecuteOperation(doOp);
      ok = true;
      break;
    }
  case mitk::AcFINISH:
    {
			last_point = event_point;
      ok = true;
      break;
    }
  default:
    return Superclass::ExecuteAction( action, stateEvent );
  }
  return ok;
}
<commit_msg>ENH: set the visibility of the data tree node true<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <mitkSeedsInteractor.h>

#include <mitkProperties.h>
#include <mitkStringProperty.h>
#include <mitkAction.h>
#include <mitkDisplayPositionEvent.h>
#include <mitkOperationEvent.h>
#include <mitkInteractionConst.h>
#include <mitkUndoController.h>
#include <mitkDataTreeNode.h>
#include <mitkStateEvent.h>
#include <mitkState.h>
#include <mitkDrawOperation.h>

mitk::SeedsInteractor::SeedsInteractor(const char * type, mitk::DataTreeNode* dataTreeNode)
  : mitk::Interactor(type, dataTreeNode)
{
  m_Radius = 4;
}

mitk::SeedsInteractor::~SeedsInteractor()
{
}

bool mitk::SeedsInteractor::ExecuteAction(mitk::Action* action, mitk::StateEvent const* stateEvent)
{
  const mitk::DisplayPositionEvent* posEvent = dynamic_cast<const mitk::DisplayPositionEvent*>(stateEvent->GetEvent());
  if (posEvent == NULL)
    return false;

  event_point = posEvent->GetWorldPosition();

  m_DataTreeNode->SetVisibility(true);
  m_SeedsImage = dynamic_cast<mitk::SeedsImage*>(m_DataTreeNode->GetData());

  bool ok = false;
  switch (action->GetActionId())
  {
  case mitk::AcINITFOREGROUND:
    {
      m_DrawState = 255;
      ok = true;
      break;
    }
  case mitk::AcINITBACKGROUND:
    {
      m_DrawState = 254;
      ok = true;
      break;
    }
  case mitk::AcINITNEUTRAL:
    {
      m_DrawState = 0;
      ok = true;
      break;
    }
  case mitk::AcADD:
    {
			last_point = event_point;
      mitk::DrawOperation* doOp = new mitk::DrawOperation(OpADD, event_point, last_point, m_DrawState, m_Radius);
      if (m_UndoEnabled){	//write to UndoMechanism/ Can probably be removed!
        mitk::DrawOperation* undoOp = new mitk::DrawOperation(OpUNDOADD, event_point, last_point, m_DrawState, m_Radius);
        mitk::OperationEvent *operationEvent = new mitk::OperationEvent(m_SeedsImage, doOp, undoOp);
			  m_UndoController->SetOperationEvent(operationEvent);
	    }
		  //execute the Operation
		  m_SeedsImage->ExecuteOperation(doOp);
      ok = true;
      break;
    }
  case mitk::AcMOVE:
    {
			last_point = event_point;
      mitk::DrawOperation* doOp = new mitk::DrawOperation(OpMOVE, event_point, last_point, m_DrawState, m_Radius);
      if (m_UndoEnabled){	//write to UndoMechanism/ Can probably be removed!
        mitk::DrawOperation* undoOp = new mitk::DrawOperation(OpUNDOMOVE, event_point, last_point, m_DrawState, m_Radius);
        mitk::OperationEvent *operationEvent = new mitk::OperationEvent(m_SeedsImage, doOp, undoOp);
			  m_UndoController->SetOperationEvent(operationEvent);
	    }
		  //execute the Operation
		  m_SeedsImage->ExecuteOperation(doOp);
      ok = true;
      break;
    }
  case mitk::AcFINISH:
    {
			last_point = event_point;
      ok = true;
      break;
    }
  default:
    return Superclass::ExecuteAction( action, stateEvent );
  }
  return ok;
}
<|endoftext|>