<commit_before>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2013 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
#include "joynr/PrivateCopyAssign.h"
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "joynr/MessageRouter.h"
#include "joynr/JoynrMessage.h"
#include "joynr/Dispatcher.h"
#include "joynr/SubscriptionCallback.h"
#include "joynr/SubscriptionPublication.h"
#include "joynr/SubscriptionStop.h"
#include "joynr/JoynrMessageFactory.h"
#include "joynr/Request.h"
#include "joynr/Reply.h"
#include "joynr/InterfaceRegistrar.h"
#include "joynr/MetaTypeRegistrar.h"
#include "joynr/tests/testRequestInterpreter.h"
#include "tests/utils/MockObjects.h"
#include "joynr/QtOnChangeWithKeepAliveSubscriptionQos.h"
#include <QString>
#include "joynr/LibjoynrSettings.h"

#include "joynr/types/Localisation_QtGpsLocation.h"

using namespace ::testing;

using namespace joynr;

ACTION_P(ReleaseSemaphore,semaphore)
{
    semaphore->release(1);
}

/**
  * Is an integration test. Tests from Dispatcher -> SubscriptionListener and RequestCaller
  */
class BroadcastSubscriptionTest : public ::testing::Test {
public:
    BroadcastSubscriptionTest() :
        mockMessageRouter(new MockMessageRouter()),
        mockRequestCaller(new MockTestRequestCaller()),
        mockSubscriptionListenerOne(new MockSubscriptionListenerOneType<types::Localisation::QtGpsLocation>()),
        mockSubscriptionListenerTwo(new MockSubscriptionListenerTwoTypes<types::Localisation::QtGpsLocation, double>()),
        gpsLocation1(1.1, 2.2, 3.3, types::Localisation::GpsFixEnum::MODE2D, 0.0, 0.0, 0.0, 0.0, 444, 444, 444),
        speed1(100),
        qos(2000),
        providerParticipantId("providerParticipantId"),
        proxyParticipantId("proxyParticipantId"),
        messageFactory(),
        messageSender(mockMessageRouter),
        dispatcher(&messageSender),
        subscriptionManager(NULL)
    {
    }

    void SetUp(){
        QFile::remove(LibjoynrSettings::DEFAULT_BROADCASTSUBSCRIPTIONREQUEST_STORAGE_FILENAME()); //remove stored subscriptions
        subscriptionManager = new SubscriptionManager();
        dispatcher.registerSubscriptionManager(subscriptionManager);
        InterfaceRegistrar::instance().registerRequestInterpreter<tests::testRequestInterpreter>(tests::ItestBase::INTERFACE_NAME());
        MetaTypeRegistrar::instance().registerMetaType<types::Localisation::QtGpsLocation>();
        MetaTypeRegistrar::instance().registerMetaType<types::Localisation::QtGpsLocation, double>();
    }

    void TearDown(){

    }

protected:
    std::shared_ptr<MockMessageRouter> mockMessageRouter;
    std::shared_ptr<MockTestRequestCaller> mockRequestCaller;
    std::shared_ptr<MockSubscriptionListenerOneType<types::Localisation::QtGpsLocation> > mockSubscriptionListenerOne;
    std::shared_ptr<MockSubscriptionListenerTwoTypes<types::Localisation::QtGpsLocation, double> > mockSubscriptionListenerTwo;

    types::Localisation::GpsLocation gpsLocation1;
    double speed1;

    // create test data
    MessagingQos qos;
    QString providerParticipantId;
    QString proxyParticipantId;

    JoynrMessageFactory messageFactory;
    JoynrMessageSender messageSender;
    Dispatcher dispatcher;
    SubscriptionManager * subscriptionManager;
private:
    DISALLOW_COPY_AND_ASSIGN(BroadcastSubscriptionTest);
};

/**
  * Trigger:    The dispatcher receives a Publication from a broadcast with a single output parameter.
  * Expected:   The SubscriptionManager retrieves the correct SubscriptionCallback and the
  *             Interpreter executes it correctly
  */
TEST_F(BroadcastSubscriptionTest, receive_publication_singleOutputParameter ) {

    qRegisterMetaType<SubscriptionPublication>("SubscriptionPublication");

    // Use a semaphore to count and wait on calls to the mockSubscriptionListener
    QSemaphore semaphore(0);
    EXPECT_CALL(*mockSubscriptionListenerOne, onReceive(A<const types::Localisation::QtGpsLocation&>()))
            .WillRepeatedly(ReleaseSemaphore(&semaphore));

    //register the subscription on the consumer side
    QString subscribeToName = "locationUpdate";
    Variant subscriptionQos = Variant::make<OnChangeWithKeepAliveSubscriptionQos>(OnChangeWithKeepAliveSubscriptionQos(
                80, // validity_ms
                100, // minInterval_ms
                200, // maxInterval_ms
                80 // alertInterval_ms
    ));

    BroadcastSubscriptionRequest subscriptionRequest;
    //construct a reply containing a QtGpsLocation
    SubscriptionPublication subscriptionPublication;
    subscriptionPublication.setSubscriptionId(subscriptionRequest.getSubscriptionId());
    std::vector<Variant> response;
    response.push_back(Variant::make<types::Localisation::GpsLocation>(gpsLocation1));
    subscriptionPublication.setResponse(response);

    std::shared_ptr<SubscriptionCallback<types::Localisation::QtGpsLocation>> subscriptionCallback(
            new SubscriptionCallback<types::Localisation::QtGpsLocation>(mockSubscriptionListenerOne));

    // subscriptionRequest is an out param
    subscriptionManager->registerSubscription(
                subscribeToName,
                subscriptionCallback,
                subscriptionQos,
                subscriptionRequest);
    // incoming publication from the provider
    JoynrMessage msg = messageFactory.createSubscriptionPublication(
                providerParticipantId,
                proxyParticipantId,
                qos,
                subscriptionPublication);

    dispatcher.receive(msg);

    // Assert that only one subscription message is received by the subscription listener
    ASSERT_TRUE(semaphore.tryAcquire(1, 1000));
    ASSERT_FALSE(semaphore.tryAcquire(1, 250));
}

/**
  * Trigger:    The dispatcher receives a Publication from a broadcast with multiple output parameters.
  * Expected:   The SubscriptionManager retrieves the correct SubscriptionCallback and the
  *             Interpreter executes it correctly
  */
TEST_F(BroadcastSubscriptionTest, receive_publication_multipleOutputParameters ) {

    qRegisterMetaType<SubscriptionPublication>("SubscriptionPublication");

    // Use a semaphore to count and wait on calls to the mockSubscriptionListener
    QSemaphore semaphore(0);
    EXPECT_CALL(*mockSubscriptionListenerTwo, onReceive(A<const types::Localisation::QtGpsLocation&>(), A<const double&>()))
            .WillRepeatedly(ReleaseSemaphore(&semaphore));

    //register the subscription on the consumer side
    QString subscribeToName = "locationUpdateWithSpeed";
    Variant subscriptionQos = Variant::make<OnChangeWithKeepAliveSubscriptionQos>(OnChangeWithKeepAliveSubscriptionQos(
                80, // validity_ms
                100, // minInterval_ms
                200, // maxInterval_ms
                80 // alertInterval_ms
    ));

    BroadcastSubscriptionRequest subscriptionRequest;
    //construct a reply containing a QtGpsLocation
    SubscriptionPublication subscriptionPublication;
    subscriptionPublication.setSubscriptionId(subscriptionRequest.getSubscriptionId());
    std::vector<Variant> response;
    response.push_back(Variant::make<types::Localisation::GpsLocation>(gpsLocation1));
    response.push_back(Variant::make<double>(speed1));
    subscriptionPublication.setResponse(response);

    std::shared_ptr<SubscriptionCallback<types::Localisation::QtGpsLocation, double>> subscriptionCallback(
            new SubscriptionCallback<types::Localisation::QtGpsLocation, double>(mockSubscriptionListenerTwo));

    // subscriptionRequest is an out param
    subscriptionManager->registerSubscription(
                subscribeToName,
                subscriptionCallback,
                subscriptionQos,
                subscriptionRequest);
    // incoming publication from the provider
    JoynrMessage msg = messageFactory.createSubscriptionPublication(
                providerParticipantId,
                proxyParticipantId,
                qos,
                subscriptionPublication);

    dispatcher.receive(msg);

    // Assert that only one subscription message is received by the subscription listener
    ASSERT_TRUE(semaphore.tryAcquire(1, 1000));
    ASSERT_FALSE(semaphore.tryAcquire(1, 250));
}
<commit_msg>[C++] fixed BroadcastSubscriptionTest<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2013 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
#include "joynr/PrivateCopyAssign.h"
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "joynr/MessageRouter.h"
#include "joynr/JoynrMessage.h"
#include "joynr/Dispatcher.h"
#include "joynr/SubscriptionCallback.h"
#include "joynr/SubscriptionPublication.h"
#include "joynr/SubscriptionStop.h"
#include "joynr/JoynrMessageFactory.h"
#include "joynr/Request.h"
#include "joynr/Reply.h"
#include "joynr/InterfaceRegistrar.h"
#include "joynr/MetaTypeRegistrar.h"
#include "joynr/tests/testRequestInterpreter.h"
#include "tests/utils/MockObjects.h"
#include "joynr/OnChangeWithKeepAliveSubscriptionQos.h"
#include <QString>
#include "joynr/LibjoynrSettings.h"

#include "joynr/types/Localisation/GpsLocation.h"

using namespace ::testing;

using namespace joynr;

ACTION_P(ReleaseSemaphore,semaphore)
{
    semaphore->release(1);
}

/**
  * Is an integration test. Tests from Dispatcher -> SubscriptionListener and RequestCaller
  */
class BroadcastSubscriptionTest : public ::testing::Test {
public:
    BroadcastSubscriptionTest() :
        mockMessageRouter(new MockMessageRouter()),
        mockRequestCaller(new MockTestRequestCaller()),
        mockSubscriptionListenerOne(new MockSubscriptionListenerOneType<types::Localisation::GpsLocation>()),
        mockSubscriptionListenerTwo(new MockSubscriptionListenerTwoTypes<types::Localisation::GpsLocation, double>()),
        gpsLocation1(1.1, 2.2, 3.3, types::Localisation::GpsFixEnum::MODE2D, 0.0, 0.0, 0.0, 0.0, 444, 444, 444),
        speed1(100),
        qos(2000),
        providerParticipantId("providerParticipantId"),
        proxyParticipantId("proxyParticipantId"),
        messageFactory(),
        messageSender(mockMessageRouter),
        dispatcher(&messageSender),
        subscriptionManager(NULL)
    {
    }

    void SetUp(){
        QFile::remove(LibjoynrSettings::DEFAULT_BROADCASTSUBSCRIPTIONREQUEST_STORAGE_FILENAME()); //remove stored subscriptions
        subscriptionManager = new SubscriptionManager();
        dispatcher.registerSubscriptionManager(subscriptionManager);
        InterfaceRegistrar::instance().registerRequestInterpreter<tests::testRequestInterpreter>(tests::ItestBase::INTERFACE_NAME());
        MetaTypeRegistrar::instance().registerMetaType<types::Localisation::GpsLocation>();
        MetaTypeRegistrar::instance().registerMetaType<types::Localisation::GpsLocation, double>();
    }

    void TearDown(){

    }

protected:
    std::shared_ptr<MockMessageRouter> mockMessageRouter;
    std::shared_ptr<MockTestRequestCaller> mockRequestCaller;
    std::shared_ptr<MockSubscriptionListenerOneType<types::Localisation::GpsLocation> > mockSubscriptionListenerOne;
    std::shared_ptr<MockSubscriptionListenerTwoTypes<types::Localisation::GpsLocation, double> > mockSubscriptionListenerTwo;

    types::Localisation::GpsLocation gpsLocation1;
    double speed1;

    // create test data
    MessagingQos qos;
    QString providerParticipantId;
    QString proxyParticipantId;

    JoynrMessageFactory messageFactory;
    JoynrMessageSender messageSender;
    Dispatcher dispatcher;
    SubscriptionManager * subscriptionManager;
private:
    DISALLOW_COPY_AND_ASSIGN(BroadcastSubscriptionTest);
};

/**
  * Trigger:    The dispatcher receives a Publication from a broadcast with a single output parameter.
  * Expected:   The SubscriptionManager retrieves the correct SubscriptionCallback and the
  *             Interpreter executes it correctly
  */
TEST_F(BroadcastSubscriptionTest, receive_publication_singleOutputParameter ) {

    qRegisterMetaType<SubscriptionPublication>("SubscriptionPublication");

    // Use a semaphore to count and wait on calls to the mockSubscriptionListener
    QSemaphore semaphore(0);
    EXPECT_CALL(*mockSubscriptionListenerOne, onReceive(A<const types::Localisation::GpsLocation&>()))
            .WillRepeatedly(ReleaseSemaphore(&semaphore));

    //register the subscription on the consumer side
    QString subscribeToName = "locationUpdate";
    Variant subscriptionQos = Variant::make<OnChangeWithKeepAliveSubscriptionQos>(OnChangeWithKeepAliveSubscriptionQos(
                80, // validity_ms
                100, // minInterval_ms
                200, // maxInterval_ms
                80 // alertInterval_ms
    ));

    BroadcastSubscriptionRequest subscriptionRequest;
    //construct a reply containing a QtGpsLocation
    SubscriptionPublication subscriptionPublication;
    subscriptionPublication.setSubscriptionId(subscriptionRequest.getSubscriptionId());
    std::vector<Variant> response;
    response.push_back(Variant::make<types::Localisation::GpsLocation>(gpsLocation1));
    subscriptionPublication.setResponse(response);

    std::shared_ptr<SubscriptionCallback<types::Localisation::GpsLocation>> subscriptionCallback(
            new SubscriptionCallback<types::Localisation::GpsLocation>(mockSubscriptionListenerOne));

    // subscriptionRequest is an out param
    subscriptionManager->registerSubscription(
                subscribeToName,
                subscriptionCallback,
                subscriptionQos,
                subscriptionRequest);
    // incoming publication from the provider
    JoynrMessage msg = messageFactory.createSubscriptionPublication(
                providerParticipantId,
                proxyParticipantId,
                qos,
                subscriptionPublication);

    dispatcher.receive(msg);

    // Assert that only one subscription message is received by the subscription listener
    ASSERT_TRUE(semaphore.tryAcquire(1, 1000));
    ASSERT_FALSE(semaphore.tryAcquire(1, 250));
}

/**
  * Trigger:    The dispatcher receives a Publication from a broadcast with multiple output parameters.
  * Expected:   The SubscriptionManager retrieves the correct SubscriptionCallback and the
  *             Interpreter executes it correctly
  */
TEST_F(BroadcastSubscriptionTest, receive_publication_multipleOutputParameters ) {

    // Use a semaphore to count and wait on calls to the mockSubscriptionListener
    QSemaphore semaphore(0);
    EXPECT_CALL(*mockSubscriptionListenerTwo, onReceive(A<const types::Localisation::GpsLocation&>(), A<const double&>()))
            .WillRepeatedly(ReleaseSemaphore(&semaphore));

    //register the subscription on the consumer side
    QString subscribeToName = "locationUpdateWithSpeed";
    Variant subscriptionQos = Variant::make<OnChangeWithKeepAliveSubscriptionQos>(OnChangeWithKeepAliveSubscriptionQos(
                80, // validity_ms
                100, // minInterval_ms
                200, // maxInterval_ms
                80 // alertInterval_ms
    ));

    BroadcastSubscriptionRequest subscriptionRequest;
    //construct a reply containing a GpsLocation
    SubscriptionPublication subscriptionPublication;
    subscriptionPublication.setSubscriptionId(subscriptionRequest.getSubscriptionId());
    std::vector<Variant> response;
    response.push_back(Variant::make<types::Localisation::GpsLocation>(gpsLocation1));
    response.push_back(Variant::make<double>(speed1));
    subscriptionPublication.setResponse(response);

    std::shared_ptr<SubscriptionCallback<types::Localisation::GpsLocation, double>> subscriptionCallback(
            new SubscriptionCallback<types::Localisation::GpsLocation, double>(mockSubscriptionListenerTwo));

    // subscriptionRequest is an out param
    subscriptionManager->registerSubscription(
                subscribeToName,
                subscriptionCallback,
                subscriptionQos,
                subscriptionRequest);
    // incoming publication from the provider
    JoynrMessage msg = messageFactory.createSubscriptionPublication(
                providerParticipantId,
                proxyParticipantId,
                qos,
                subscriptionPublication);

    dispatcher.receive(msg);

    // Assert that only one subscription message is received by the subscription listener
    ASSERT_TRUE(semaphore.tryAcquire(1, 1000));
    ASSERT_FALSE(semaphore.tryAcquire(1, 250));
}
<|endoftext|>


<commit_before>/*
 FILNAMN: 		room.cc
 PROGRAMMERARE:	hanel742, eriek984, jened502, tobgr602, niker917, davha227
 SKAPAD DATUM:	2013-11-14
 BESKRIVNING:
 */

#include "room.h"

using namespace std;

// ----------------------------------
// Constructor

Room::Room(string inName,Master* master) {
    masterPointer = master;
    name = inName;
}

// ----------------------------------------
// Help functions

void ifRoomRemove(Room* inRoom) {
    cout << "IfRoomRemove: ";
    cout << inRoom->getName() << endl;
    User* userTemp = dynamic_cast<User*>(inRoom);

    if (userTemp == nullptr) {
        inRoom->masterPointer->removeRoom(inRoom->getName());
    }
}

void throwUp(Room* inRoom) {
    inRoom->chooseRoom(inRoom->parentRoom->parentRoom);
}

void deleteRooms(Room* inRoom) {

}

// ----------------------------------------
// Destructor

Room::~Room() {
    for_each(rooms.begin(), rooms.end(), ifRoomRemove);

    if ( parentRoom == nullptr) {
        rooms.clear();
    }
    else {

        parentRoom->removeRoom(this);

        for_each(rooms.begin(), rooms.end(), throwUp);
        parentRoom = nullptr;
    }

    masterPointer = nullptr;

}

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

unsigned int Room::getPosOfRoom(string name) const{
    for( unsigned int i = 0 ; i < rooms.size() ; i++) {
        if(rooms.at(i)->getName() == name){
            return i;
        }
    }
    throw logic_error("No such room in Rooms");
    return 0;
}

// ----------------------------------------
// Automatically called from child when child room is destroyed
void Room::removeRoom(Room* inRoom) {
    unsigned int pos = getPosOfRoom(inRoom->getName());
    rooms.at(pos) = nullptr;
    rooms.erase(rooms.begin() + pos);
}

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

void Room::sendMessage(Message inMessage) {
    string to = inMessage.getTo();

    try {
        getRoom(to)->receiveMessage(inMessage);
    } catch (...) {
        Message errorMessage("No such user in this room.",name,inMessage.getFrom());
    }

}

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

void Room::listRooms(){
    for (unsigned int it = 0; it < rooms.size() ; it++){
        User* userTemp = dynamic_cast<User*>(rooms.at(it));
        if(userTemp == nullptr ){
            cout << rooms.at(it)->getName() << endl;
        }
    }
    return;
}

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

void Room::listUsers(){
    for (unsigned int it = 0; it < rooms.size() ; it++){
        User* userTemp = dynamic_cast<User*>(rooms.at(it));
        if( userTemp == nullptr ){
            continue;
        }
        else{
            cout << rooms.at(it)->getName() << endl;
        }
    }
    return;
}

void Room::receiveMessage(Message inMessage) {
    string to = inMessage.getTo();
    if(to == name){
        log.push_back(inMessage);

        sendMessageAll(inMessage);

        saveToFile(inMessage);
    }
    else{
        sendMessage(inMessage);
    }
}

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

void Room::sendMessageAll(Message inMessage) {
    string to = inMessage.getTo();

    unsigned int pos = getPosOfRoom(to);

    for (unsigned int i = 0; i < rooms.size(); i++) {
        User* userTemp = dynamic_cast<User*>(rooms.at(pos));
        if ( userTemp == nullptr ) {
            continue;
        }
        rooms.at(pos)->receiveMessage(inMessage);
    }
}

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

void Room::addRoom(Room* inRoom) {
    this->rooms.push_back(inRoom);
}

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

void Room::saveToFile(Message inMessage) {
    cout << inMessage.getMessage() << endl;
    return;
}

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

string Room::getName() {
    return name;
}

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

void Room::createRoom(std::string inName){
	addRoom(masterPointer->createRoom(inName));
}

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

Room* Room::getRoom(std::string name){
    for( unsigned int i = 0 ; i < rooms.size() ; i++) {
        if(rooms.at(i)->getName() == name){
            return rooms.at(i);
        }
    }
    throw logic_error("No such room in Rooms");

    return nullptr;
}

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

Message Room::getMessage(unsigned int i){
    if (log.size() < i){
        throw logic_error{"No message at that position!"};
    }
    return log.at(i);
}

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

void Room::chooseRoom(Room*) {
    throw logic_error{"You're a retard since you're trying to move a room."};
}
<commit_msg>Can't fix segfault<commit_after>/*
 FILNAMN: 		room.cc
 PROGRAMMERARE:	hanel742, eriek984, jened502, tobgr602, niker917, davha227
 SKAPAD DATUM:	2013-11-14
 BESKRIVNING:
 */

#include "room.h"

using namespace std;

// ----------------------------------
// Constructor

Room::Room(string inName,Master* master) {
    masterPointer = master;
    name = inName;
}

// ----------------------------------------
// Help functions

void ifRoomRemove(Room* inRoom) {
    cout << "IfRoomRemove: ";
    cout << inRoom->getName() << endl;
    User* userTemp = dynamic_cast<User*>(inRoom);

    if (userTemp == nullptr) {
        cout << "nullptr" << endl;
        inRoom->masterPointer->removeRoom(inRoom->getName());
    }
}

void throwUp(Room* inRoom) {
    inRoom->chooseRoom(inRoom->parentRoom->parentRoom);
}

// ----------------------------------------
// Destructor

Room::~Room() {
    for_each(rooms.begin(), rooms.end(), ifRoomRemove);

    if ( parentRoom == nullptr) {
        rooms.clear();
    }
    else {

        parentRoom->removeRoom(this);

        for_each(rooms.begin(), rooms.end(), throwUp);
        parentRoom = nullptr;
    }

    masterPointer = nullptr;

}

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

unsigned int Room::getPosOfRoom(string name) const{
    for( unsigned int i = 0 ; i < rooms.size() ; i++) {
        if(rooms.at(i)->getName() == name){
            return i;
        }
    }
    throw logic_error("No such room in Rooms");
    return 0;
}

// ----------------------------------------
// Automatically called from child when child room is destroyed
void Room::removeRoom(Room* inRoom) {
    unsigned int pos = getPosOfRoom(inRoom->getName());
    rooms.at(pos) = nullptr;
    rooms.erase(rooms.begin() + pos);
}

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

void Room::sendMessage(Message inMessage) {
    string to = inMessage.getTo();

    try {
        getRoom(to)->receiveMessage(inMessage);
    } catch (...) {
        Message errorMessage("No such user in this room.",name,inMessage.getFrom());
    }

}

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

void Room::listRooms(){
    for (unsigned int it = 0; it < rooms.size() ; it++){
        User* userTemp = dynamic_cast<User*>(rooms.at(it));
        if(userTemp == nullptr ){
            cout << rooms.at(it)->getName() << endl;
        }
    }
    return;
}

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

void Room::listUsers(){
    for (unsigned int it = 0; it < rooms.size() ; it++){
        User* userTemp = dynamic_cast<User*>(rooms.at(it));
        if( userTemp == nullptr ){
            continue;
        }
        else{
            cout << rooms.at(it)->getName() << endl;
        }
    }
    return;
}

void Room::receiveMessage(Message inMessage) {
    string to = inMessage.getTo();
    if(to == name){
        log.push_back(inMessage);

        sendMessageAll(inMessage);

        saveToFile(inMessage);
    }
    else{
        sendMessage(inMessage);
    }
}

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

void Room::sendMessageAll(Message inMessage) {
    string to = inMessage.getTo();

    unsigned int pos = getPosOfRoom(to);

    for (unsigned int i = 0; i < rooms.size(); i++) {
        User* userTemp = dynamic_cast<User*>(rooms.at(pos));
        if ( userTemp == nullptr ) {
            continue;
        }
        rooms.at(pos)->receiveMessage(inMessage);
    }
}

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

void Room::addRoom(Room* inRoom) {
    this->rooms.push_back(inRoom);
}

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

void Room::saveToFile(Message inMessage) {
    cout << inMessage.getMessage() << endl;
    return;
}

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

string Room::getName() {
    return name;
}

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

void Room::createRoom(std::string inName){
	addRoom(masterPointer->createRoom(inName));
}

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

Room* Room::getRoom(std::string name){
    for( unsigned int i = 0 ; i < rooms.size() ; i++) {
        if(rooms.at(i)->getName() == name){
            return rooms.at(i);
        }
    }
    throw logic_error("No such room in Rooms");

    return nullptr;
}

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

Message Room::getMessage(unsigned int i){
    if (log.size() < i){
        throw logic_error{"No message at that position!"};
    }
    return log.at(i);
}

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

void Room::chooseRoom(Room*) {
    throw logic_error{"You're a retard since you're trying to move a room."};
}
<|endoftext|>


<commit_before>// Sh: A GPU metaprogramming language.
//
// Copyright 2003-2005 Serious Hack Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA  02110-1301, USA
//////////////////////////////////////////////////////////////////////////////
#include "ShLinearAllocator.hpp"
#include <set>
#include <algorithm>
#include "ShDebug.hpp"

namespace {

struct LifeToken {
  LifeToken(const SH::ShVariableNodePtr& var, int index, bool end)
    : var(var), index(index), end(end)
  {
  }

  SH::ShVariableNodePtr var;
  int index;
  bool end;

  // order by index, then end
  bool operator<(const LifeToken& other) const
  {
    if (index == other.index) {
      return !end;
    }
    return index < other.index;
  }
};

}

namespace SH {

ShLinearAllocator::ShLinearAllocator(ShBackendCodePtr backendCode)
  : m_backendCode(backendCode)
{
}

void ShLinearAllocator::mark(const ShVariableNodePtr& var, int index)
{
  if (!var) return;
  LifetimeMap::iterator I = m_lifetimes.find(var);

  if (I == m_lifetimes.end()) {
    m_lifetimes[var] = ShLifeTime(var, index);
  } else {
    I->second.mark(index);
  }
}

void ShLinearAllocator::debugDump()
{
#ifdef SH_DEBUG
  for (LifetimeMap::const_iterator I = m_lifetimes.begin(); I != m_lifetimes.end(); ++I) {
    SH_DEBUG_PRINT(I->first->name() << " = {" << I->second.first << ", " << I->second.last << "}");
  }
#endif
}

void ShLinearAllocator::allocate()
{
  std::multiset<LifeToken> temps;

  for (LifetimeMap::const_iterator I = m_lifetimes.begin(); I != m_lifetimes.end(); ++I) {
    temps.insert(LifeToken(I->first, I->second.first, false));
    temps.insert(LifeToken(I->first, I->second.last, true));
  }

  for (std::multiset<LifeToken>::const_iterator I = temps.begin(); I != temps.end(); ++I) {
    if (!I->end) {
      if (!m_backendCode->allocateRegister(I->var)) {
        // TODO: Error
        SH_DEBUG_WARN("Error allocating a register for " << I->var->name());
      }
    } else {
      m_backendCode->freeRegister(I->var);
    }
  }
}

}

<commit_msg>Allocate: multiset requires strict weak ordering; LifeToken (operator<): if (a<b) -> !(b<a).<commit_after>// Sh: A GPU metaprogramming language.
//
// Copyright 2003-2005 Serious Hack Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA  02110-1301, USA
//////////////////////////////////////////////////////////////////////////////
#include "ShLinearAllocator.hpp"
#include <set>
#include <algorithm>
#include "ShDebug.hpp"

namespace {

struct LifeToken {
  LifeToken(const SH::ShVariableNodePtr& var, int index, bool end)
    : var(var), index(index), end(end)
  {
  }

  SH::ShVariableNodePtr var;
  int index;
  bool end;

  /**
   * Order by index, then end.
   * Strict weak ordering:
   * if (a<b) -> !(b<a).
   */
  bool operator<(const LifeToken& other) const
  {
    if (index == other.index) {
      return !end && other.end;
    }
    return index < other.index;
  }
};

}

namespace SH {

ShLinearAllocator::ShLinearAllocator(ShBackendCodePtr backendCode)
  : m_backendCode(backendCode)
{
}

void ShLinearAllocator::mark(const ShVariableNodePtr& var, int index)
{
  if (!var) return;
  LifetimeMap::iterator I = m_lifetimes.find(var);

  if (I == m_lifetimes.end()) {
    m_lifetimes[var] = ShLifeTime(var, index);
  } else {
    I->second.mark(index);
  }
}

void ShLinearAllocator::debugDump()
{
#ifdef SH_DEBUG
  for (LifetimeMap::const_iterator I = m_lifetimes.begin(); I != m_lifetimes.end(); ++I) {
    SH_DEBUG_PRINT(I->first->name() << " = {" << I->second.first << ", " << I->second.last << "}");
  }
#endif
}

void ShLinearAllocator::allocate()
{
  std::multiset<LifeToken> temps;

  for (LifetimeMap::const_iterator I = m_lifetimes.begin(); I != m_lifetimes.end(); ++I) {
    temps.insert(LifeToken(I->first, I->second.first, false));
    temps.insert(LifeToken(I->first, I->second.last, true));
  }

  for (std::multiset<LifeToken>::const_iterator I = temps.begin(); I != temps.end(); ++I) {
    if (!I->end) {
      if (!m_backendCode->allocateRegister(I->var)) {
        // TODO: Error
        SH_DEBUG_WARN("Error allocating a register for " << I->var->name());
      }
    } else {
      m_backendCode->freeRegister(I->var);
    }
  }
}

}

<|endoftext|>


<commit_before>/// COMPONENT
#include <csapex/model/node.h>
#include <csapex/model/node_modifier.h>
#include <csapex/msg/io.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex_opencv/cv_mat_message.h>

namespace csapex
{
using namespace csapex;
using namespace connection_types;

class BGRToIlluminationInvariant : public csapex::Node
{
public:
    BGRToIlluminationInvariant() = default;
    virtual ~BGRToIlluminationInvariant() = default;

    virtual void process() override
    {
        CvMatMessage::ConstPtr in = msg::getMessage<connection_types::CvMatMessage>(input_);
        if (!in->getEncoding().matches(enc::bgr))
            throw std::runtime_error("Image needs to be BGR for fitting conversion.");

        CvMatMessage::Ptr out(new connection_types::CvMatMessage(enc::mono, in->frame_id, in->stamp_micro_seconds));
        out->value = cv::Mat(in->value.rows, in->value.cols, CV_32FC1, cv::Scalar());
        CvMatMessage::Ptr out_mask(new connection_types::CvMatMessage(enc::mono, in->frame_id, in->stamp_micro_seconds));
        out_mask->value = cv::Mat(in->value.rows, in->value.cols, CV_8UC1, cv::Scalar(0));

        // bool cap
        // conditional for cap (min/max) interval param
        // mask also with capped pixels
        // ternary after norm for cap (after ill.invar)
        // labels : 0 unaltered, 1 invalid, 2 capped (or 2 for min capped 3 for max
        // capped)
        //--> labels to mask <-> generate mask from label (as parameter)
        //--> labels to random color <-> check examples for random colors

        std::pair<float, float> threshold_min_max = readParameter<std::pair<int, int>>("threshold range");
        threshold_min_max.first = threshold_min_max.first / 100.0;
        threshold_min_max.second = threshold_min_max.second / 100.0;

        bool use_threshold = readParameter<bool>("threshold");

        switch (method_) {
            case NewmanOriginal: {
                const cv::Vec3b* src = in->value.ptr<cv::Vec3b>();
                float* dst = out->value.ptr<float>();
                uchar* mask = out_mask->value.ptr<uchar>();
                const std::size_t size = static_cast<std::size_t>(out->value.cols * out->value.rows);

                for (std::size_t i = 0; i < size; ++i) {
                    const cv::Vec3b& p = src[i];
                    if (p[0] == 0 || p[1] == 0 || p[2] == 0) {
                        mask[i] = 0;
                        continue;
                    }
                    cv::Vec3f c(p[0] / 255.0, p[1] / 255.0, p[2] / 255.0);
                    dst[i] = 0.5 + std::log(c[1]) - alpha_ * std::log(c[0]) - (1.0 - alpha_) * std::log(c[2]);
                }
            } break;
            case Newman: {
                // N = (0.5+log(g)) - alpha*log(b) - (1-alpha)*log(r)
                // Max= 0.5 + log(255) - alpha*log(b) - log(r) + alpha*log(r) = 0.5 +
                // log(255)   (alpha,b,r = 0) Min= 0.5 + log(1) - alpha*log(b) - log(r) +
                // alpha*log(r) = 0.5 - log(255) (alpha=1,b=255, r=0)
                double min = 0.5 - std::log(255.0);
                double max = 0.5 + std::log(255.0);

                const cv::Vec3b* src = in->value.ptr<cv::Vec3b>();
                float* dst = out->value.ptr<float>();
                uchar* mask = out_mask->value.ptr<uchar>();
                const std::size_t size = static_cast<std::size_t>(out->value.cols * out->value.rows);

                auto get_thresholded = [&](int i) -> std::pair<double, double> {
                    if (use_threshold) {
                        if (dst[i] < threshold_min_max.first) {
                            return std::make_pair(threshold_min_max.first, 2);
                        } else if (dst[i] > threshold_min_max.second) {
                            return std::make_pair(threshold_min_max.second, 3);
                        }
                    }
                    return std::make_pair(dst[i], mask[i]);
                };

                for (std::size_t i = 0; i < size; ++i) {
                    const cv::Vec3b& p = src[i];
                    cv::Vec3f c(p);
                    if (p[0] == 0 || p[1] == 0 || p[2] == 0) {
                        mask[i] = 0;
                        continue;
                    }
                    dst[i] = (0.5 + std::log(c[1]) - alpha_ * std::log(c[0]) - (1.0 - alpha_) * std::log(c[2]));
                    dst[i] = ((dst[i] - min) / (max - min));         // normalize 0-1
                    std::tie(dst[i], mask[i]) = get_thresholded(i);  // threshold min/max
                                                                     // vals
                    dst[i] = dst[i] * 255.0;                         // discretize 0-255
                }
            } break;
            case SantosOriginal: {
                const cv::Vec3b* src = in->value.ptr<cv::Vec3b>();
                float* dst = out->value.ptr<float>();
                uchar* mask = out_mask->value.ptr<uchar>();
                const std::size_t size = static_cast<std::size_t>(out->value.cols * out->value.rows);

                const double theta = M_PI * alpha_;
                const double ct = std::cos(theta);
                const double st = std::sin(theta);

                const static cv::Vec3f v1(1.0 / std::sqrt(2.0), -1.0 / std::sqrt(2.0), 0.0);
                const static cv::Vec3f v2(1.0 / std::sqrt(6.0), 1.0 / std::sqrt(6.0),
                                          -2.0 / std::sqrt(6.0));  //// Entropy Minimization for Shadow Removal

                // double min = 0.0;
                double max = std::log(1.0 / std::sqrt(1.0 / 255.0)) / std::sqrt(2.0);

                for (std::size_t i = 0; i < size; ++i) {
                    const cv::Vec3b& p = src[i];
                    if (p[0] == 0 && p[1] == 0 && p[2] == 0) {
                        mask[i] = 0;
                        dst[i] = 0;
                        continue;
                    }
                    cv::Vec3f c(p[0] / 255.0, p[1] / 255.0, p[2] / 255.0);
                    const double rho = std::sqrt(c.ddot(c));
                    c /= rho;
                    const cv::Vec2f psi(c.ddot(v1), c.ddot(v2));
                    dst[i] = (psi[0] * ct + psi[1] * st) / max;
                }

                /// sqrt2(1) <=> sqrt2(1/255.)
                /// ct + st <= sqrt(2)
            } break;

            case Santos: {
                const cv::Vec3b* src = in->value.ptr<cv::Vec3b>();
                float* dst = out->value.ptr<float>();
                uchar* mask = out_mask->value.ptr<uchar>();
                const std::size_t size = static_cast<std::size_t>(out->value.cols * out->value.rows);

                const double theta = M_PI * alpha_;
                const double ct = std::cos(theta);
                const double st = std::sin(theta);
                const static cv::Vec3f v1(1.0 / std::sqrt(2.0), -1.0 / std::sqrt(2.0), 0.0);
                const static cv::Vec3f v2(1.0 / std::sqrt(6.0), 1.0 / std::sqrt(6.0),
                                          -2.0 / std::sqrt(6.0));  //// Entropy Minimization for Shadow Removal

                // p_M = cbrt(pr*pg*pb)                    max=1, min=1/255
                // chi_r,g,b = log(p_r,g,b/p_M)            max=log(255), min=log(1)
                // psi_1,2 = U x chi_r,g,b                 psi_1:max/min = +/-
                // (1/sqrt(2)*log(255)), psi_2:max/min = +/- (2/sqrt(6)*log(255)) I =
                // psi_1*cos(theta)+psi_2*sin(theta)   max/min = +/-
                // (log(255)*(1/2+1/sqrt(3))

                double max = std::log(255.0) * (0.5 + (1.0 / std::sqrt(3)));
                double min = -max;

                auto get_thresholded = [&](int i) -> std::pair<double, double> {
                    if (use_threshold) {
                        if (dst[i] < threshold_min_max.first) {
                            return std::make_pair(threshold_min_max.first, 2);
                        } else if (dst[i] > threshold_min_max.second) {
                            return std::make_pair(threshold_min_max.second, 3);
                        }
                    }
                    return std::make_pair(dst[i], mask[i]);
                };

                for (std::size_t i = 0; i < size; ++i) {
                    const cv::Vec3b& p = src[i];
                    if (p[0] == 0 || p[1] == 0 || p[2] == 0) {
                        mask[i] = 1;
                        //                    dst[i] = 128;
                        dst[i] = (p[2] > p[1] || p[2] > p[0]) ? 1 : 0;
                        continue;
                    }

                    cv::Vec3f c(p[0] / 255.0, p[1] / 255.0, p[2] / 255.0);

                    const double rho = std::pow((c[0] * c[1] * c[2]), 1.0 / 3);
                    c /= rho;
                    c[0] = std::log(c[0]);
                    c[1] = std::log(c[1]);
                    c[2] = std::log(c[2]);
                    const cv::Vec2f psi(c.ddot(v1), c.ddot(v2));
                    dst[i] = ((psi[0] * ct + psi[1] * st) - min) / (max - min);  // normalize

                    std::tie(dst[i], mask[i]) = get_thresholded(i);  // threshold min/max
                                                                     // vals

                    dst[i] = dst[i] * 255.0;  // discretize 0-255
                }
            } break;
            default:
                break;
        }
        msg::publish(output_, out);
        msg::publish(output_mask_, out_mask);
    }

    virtual void setup(csapex::NodeModifier& node_modifier) override
    {
        input_ = node_modifier.addInput<CvMatMessage>("original");
        output_ = node_modifier.addOutput<CvMatMessage>("adjusted");
        output_mask_ = node_modifier.addOutput<CvMatMessage>("label mask");
    }

    virtual void setupParameters(Parameterizable& parameters)
    {
        parameters.addParameter(param::ParameterFactory::declareRange("alpha", 0.0, 1.0, 1.5, 0.001), alpha_);
        std::map<std::string, int> methods = { { "Newman", (int)Newman }, { "NewmanOriginal", (int)NewmanOriginal }, { "Santos", (int)Santos }, { "SantosOriginal", (int)SantosOriginal } };

        parameters.addParameter(param::ParameterFactory::declareParameterSet<int>("method", methods, Newman), method_);

        param::Parameter::Ptr method = param::factory::declareBool("threshold", param::ParameterDescription("Apply min/max thresholding."), true);

        parameters.addParameter(method, std::bind(&BGRToIlluminationInvariant::submit, this));

        std::function<bool()> k_cond = (std::bind(&param::Parameter::as<bool>, method.get()));
        parameters.addConditionalParameter(param::factory::declareInterval("threshold range", param::ParameterDescription("Valid and acceptable range"), 0, 100, 0, 100, 1), k_cond,
                                           std::bind(&BGRToIlluminationInvariant::submit, this));

        parameters.setParameter("threshold range", std::pair<int, int>(5, 95));
    }
    void submit()
    {
    }

protected:
    csapex::Output* output_;
    csapex::Output* output_mask_;

    enum Type
    {
        Newman,
        NewmanOriginal,
        Santos,
        SantosOriginal
    };

    csapex::Input* input_;
    double alpha_;
    int method_;
    bool recover_bgr_;
};
}  // namespace csapex

CSAPEX_REGISTER_CLASS(csapex::BGRToIlluminationInvariant, csapex::Node)
<commit_msg>illumination invariance optimizations<commit_after>/// COMPONENT
#include <csapex/model/node.h>
#include <csapex/model/node_modifier.h>
#include <csapex/msg/io.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex_opencv/cv_mat_message.h>

namespace csapex
{
using namespace csapex;
using namespace connection_types;

class BGRToIlluminationInvariant : public csapex::Node
{
public:
    BGRToIlluminationInvariant() = default;
    virtual ~BGRToIlluminationInvariant() = default;

    virtual void process() override
    {
        CvMatMessage::ConstPtr in = msg::getMessage<connection_types::CvMatMessage>(input_);
        if (!in->getEncoding().matches(enc::bgr))
            throw std::runtime_error("Image needs to be BGR for fitting conversion.");

        CvMatMessage::Ptr out(new connection_types::CvMatMessage(enc::mono, in->frame_id, in->stamp_micro_seconds));
        out->value = cv::Mat(in->value.rows, in->value.cols, CV_32FC1, cv::Scalar());
        CvMatMessage::Ptr out_mask(new connection_types::CvMatMessage(enc::mono, in->frame_id, in->stamp_micro_seconds));
        out_mask->value = cv::Mat(in->value.rows, in->value.cols, CV_8UC1, cv::Scalar(0));

        // bool cap
        // conditional for cap (min/max) interval param
        // mask also with capped pixels
        // ternary after norm for cap (after ill.invar)
        // labels : 0 unaltered, 1 invalid, 2 capped (or 2 for min capped 3 for max
        // capped)
        //--> labels to mask <-> generate mask from label (as parameter)
        //--> labels to random color <-> check examples for random colors

        std::pair<float, float> threshold_min_max = readParameter<std::pair<int, int>>("threshold range");
        threshold_min_max.first = threshold_min_max.first / 100.0;
        threshold_min_max.second = threshold_min_max.second / 100.0;

        bool use_threshold = readParameter<bool>("threshold");

        switch (method_) {
            case NewmanOriginal: {
                const cv::Vec3b* src = in->value.ptr<cv::Vec3b>();
                float* dst = out->value.ptr<float>();
                uchar* mask = out_mask->value.ptr<uchar>();
                const std::size_t size = static_cast<std::size_t>(out->value.cols * out->value.rows);

                for (std::size_t i = 0; i < size; ++i) {
                    const cv::Vec3b& p = src[i];
                    if (p[0] == 0 || p[1] == 0 || p[2] == 0) {
                        mask[i] = 0;
                        continue;
                    }
                    cv::Vec3f c(p[0] / 255.0, p[1] / 255.0, p[2] / 255.0);
                    dst[i] = 0.5 + std::log(c[1]) - alpha_ * std::log(c[0]) - (1.0 - alpha_) * std::log(c[2]);
                }
            } break;
            case Newman: {
                // N = (0.5+log(g)) - alpha*log(b) - (1-alpha)*log(r)
                // Max= 0.5 + log(255) - alpha*log(b) - log(r) + alpha*log(r) = 0.5 +
                // log(255)   (alpha,b,r = 0) Min= 0.5 + log(1) - alpha*log(b) - log(r) +
                // alpha*log(r) = 0.5 - log(255) (alpha=1,b=255, r=0)
//                double min = 0.5 - std::log(255.0);
//                double max = 0.5 + std::log(255.0);

                const cv::Vec3b* src = in->value.ptr<cv::Vec3b>();
                float* dst = out->value.ptr<float>();
                uchar* mask = out_mask->value.ptr<uchar>();
                const std::size_t size = static_cast<std::size_t>(out->value.cols * out->value.rows);

                for (std::size_t i = 0; i < size; ++i) {
                    const cv::Vec3b& p = src[i];
                    cv::Vec3f c(p);
                    if (p[0] == 0 || p[1] == 0 || p[2] == 0) {
                        mask[i] = 0;
                        continue;
                    }
                    dst[i] = (0.5 + std::log(c[1]) - alpha_ * std::log(c[0]) - (1.0 - alpha_) * std::log(c[2]));
                    dst[i] = ((dst[i] - newman_min) / (newman_max - newman_min));         // normalize 0-1

                    //threshold min/max
                    if (use_threshold) {
                      if (dst[i] < threshold_min_max.first) {
                        dst[i] = threshold_min_max.first;
                        mask[i] = 2;
                      } else if (dst[i] > threshold_min_max.second) {
                        dst[i] = threshold_min_max.second;
                        mask[i] = 3;
                      }
                    }

                    dst[i] = dst[i] * 255.0;                         // discretize 0-255
                }
            } break;
            case SantosOriginal: {
                const cv::Vec3b* src = in->value.ptr<cv::Vec3b>();
                float* dst = out->value.ptr<float>();
                uchar* mask = out_mask->value.ptr<uchar>();
                const std::size_t size = static_cast<std::size_t>(out->value.cols * out->value.rows);

                const double theta = M_PI * alpha_;
                const double ct = std::cos(theta);
                const double st = std::sin(theta);

                const static cv::Vec3f v1(1.0 / std::sqrt(2.0), -1.0 / std::sqrt(2.0), 0.0);
                const static cv::Vec3f v2(1.0 / std::sqrt(6.0), 1.0 / std::sqrt(6.0),
                                          -2.0 / std::sqrt(6.0));  //// Entropy Minimization for Shadow Removal

                // double min = 0.0;
                double max = std::log(1.0 / std::sqrt(1.0 / 255.0)) / std::sqrt(2.0);

                for (std::size_t i = 0; i < size; ++i) {
                    const cv::Vec3b& p = src[i];
                    if (p[0] == 0 && p[1] == 0 && p[2] == 0) {
                        mask[i] = 0;
                        dst[i] = 0;
                        continue;
                    }
                    cv::Vec3f c(p[0] / 255.0, p[1] / 255.0, p[2] / 255.0);
                    const double rho = std::sqrt(c.ddot(c));
                    c /= rho;
                    const cv::Vec2f psi(c.ddot(v1), c.ddot(v2));
                    dst[i] = (psi[0] * ct + psi[1] * st) / max;
                }

                /// sqrt2(1) <=> sqrt2(1/255.)
                /// ct + st <= sqrt(2)
            } break;

            case Santos: {
                const cv::Vec3b* src = in->value.ptr<cv::Vec3b>();
                float* dst = out->value.ptr<float>();
                uchar* mask = out_mask->value.ptr<uchar>();
                const std::size_t size = static_cast<std::size_t>(out->value.cols * out->value.rows);

                const double theta = M_PI * alpha_;
                const double ct = std::cos(theta);
                const double st = std::sin(theta);
                const static cv::Vec3f v1(1.0 / std::sqrt(2.0), -1.0 / std::sqrt(2.0), 0.0);
                const static cv::Vec3f v2(1.0 / std::sqrt(6.0), 1.0 / std::sqrt(6.0),
                                          -2.0 / std::sqrt(6.0));  //// Entropy Minimization for Shadow Removal

                // p_M = cbrt(pr*pg*pb)                    max=1, min=1/255
                // chi_r,g,b = log(p_r,g,b/p_M)            max=log(255), min=log(1)
                // psi_1,2 = U x chi_r,g,b                 psi_1:max/min = +/-
                // (1/sqrt(2)*log(255)), psi_2:max/min = +/- (2/sqrt(6)*log(255)) I =
                // psi_1*cos(theta)+psi_2*sin(theta)   max/min = +/-
                // (log(255)*(1/2+1/sqrt(3))

//                double max = std::log(255.0) * (0.5 + (1.0 / std::sqrt(3)));
//                double min = -max;

                for (std::size_t i = 0; i < size; ++i) {
                    const cv::Vec3b& p = src[i];
                    if (p[0] == 0 || p[1] == 0 || p[2] == 0) {
                        mask[i] = 1;
                        //                    dst[i] = 128;
                        dst[i] = (p[2] > p[1] || p[2] > p[0]) ? 1 : 0;
//                        dst[i] = 0;
                        continue;
                    }

                    cv::Vec3f c(p[0] / 255.0, p[1] / 255.0, p[2] / 255.0);
//                    const double rho = std::pow((c[0] * c[1] * c[2]), 1.0 / 3);
                    const double rho = LUT_rho_cbrt[p[0]][p[1]][p[2]];

                    c /= rho;
                    c[0] = std::log(c[0]); //comment logs for optimization
                    c[1] = std::log(c[1]);
                    c[2] = std::log(c[2]);
                    const cv::Vec2f psi(c.ddot(v1), c.ddot(v2));
                    dst[i] = ((psi[0] * ct + psi[1] * st) - santos_min) / (santos_max - santos_min);  // normalize

                    //threshold values
                    if (use_threshold) {
                      if (dst[i] < threshold_min_max.first) {
                        dst[i] = threshold_min_max.first;
                        mask[i] = 2;
                      } else if (dst[i] > threshold_min_max.second) {
                        dst[i] = threshold_min_max.second;
                        mask[i] = 3;
                      }
                    }

                    dst[i] = dst[i] * 255.0;  // discretize 0-255
                }
            } break;
            default:
                break;
        }
        msg::publish(output_, out);
        msg::publish(output_mask_, out_mask);
    }

    virtual void setup(csapex::NodeModifier& node_modifier) override
    {
        input_ = node_modifier.addInput<CvMatMessage>("original");
        output_ = node_modifier.addOutput<CvMatMessage>("adjusted");
        output_mask_ = node_modifier.addOutput<CvMatMessage>("label mask");

        for (int i = 0; i < 255; i++) {
          for (int j = 0; j < 255; j++) {
            for (int k = 0; k < 255; k++) {
              LUT_rho_cbrt[i][j][k] = std::pow((i/255.0 * j/255.0 * k/255.0), 1.0/3);
            }
          }
        }
        santos_max = std::log(255.0) * (0.5 + (1.0 / std::sqrt(3)));
        santos_min = -santos_max;

        newman_min = 0.5 - std::log(255.0);
        newman_max = 0.5 + std::log(255.0);
//        ct = std::cos(M_PI);
//        st = std::sin(M_PI);

    }

    virtual void setupParameters(Parameterizable& parameters)
    {
        parameters.addParameter(param::ParameterFactory::declareRange("alpha", 0.0, 1.0, 1.5, 0.001), alpha_);
        std::map<std::string, int> methods = { { "Newman", (int)Newman }, { "NewmanOriginal", (int)NewmanOriginal }, { "Santos", (int)Santos }, { "SantosOriginal", (int)SantosOriginal } };

        parameters.addParameter(param::ParameterFactory::declareParameterSet<int>("method", methods, Newman), method_);

        param::Parameter::Ptr method = param::factory::declareBool("threshold", param::ParameterDescription("Apply min/max thresholding."), true);

        parameters.addParameter(method, std::bind(&BGRToIlluminationInvariant::submit, this));

        std::function<bool()> k_cond = (std::bind(&param::Parameter::as<bool>, method.get()));
        parameters.addConditionalParameter(param::factory::declareInterval("threshold range", param::ParameterDescription("Valid and acceptable range"), 0, 100, 0, 100, 1), k_cond,
                                           std::bind(&BGRToIlluminationInvariant::submit, this));

        parameters.setParameter("threshold range", std::pair<int, int>(5, 95));
    }
    void submit()
    {
    }

protected:
    csapex::Output* output_;
    csapex::Output* output_mask_;

    enum Type
    {
        Newman,
        NewmanOriginal,
        Santos,
        SantosOriginal
    };

    csapex::Input* input_;
    double alpha_;
    int method_;
    bool recover_bgr_;
    float LUT_rho_cbrt[256][256][256];
    double santos_min;
    double santos_max;
    double newman_min;
    double newman_max;
//    double ct;
//    double st;
};
}  // namespace csapex

CSAPEX_REGISTER_CLASS(csapex::BGRToIlluminationInvariant, csapex::Node)
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions Inc. 1990-2013.  All rights reserved
 */
//  TEST    Foundation::Memory
#include    "Stroika/Foundation/StroikaPreComp.h"

#include    "Stroika/Foundation/Containers/Mapping.h"
#include    "Stroika/Foundation/Debug/Assertions.h"
#include    "Stroika/Foundation/Debug/Trace.h"

#include    "Stroika/Foundation/Memory/AnyVariantValue.h"
#include    "Stroika/Foundation/Memory/Optional.h"
#include    "Stroika/Foundation/Memory/SharedByValue.h"
#include    "Stroika/Foundation/Memory/VariantValue.h"

#include    "../TestHarness/SimpleClass.h"
#include    "../TestHarness/TestHarness.h"

using   namespace   Stroika;
using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Memory;

//TODO: DOES IT EVEN NEED TO BE SAID? THese tests are a bit sparse ;-)

namespace   {
    void    Test1_Optional ()
    {
        {
            Optional<int>   x;
            VerifyTestResult (x.empty ());
            x = 1;
            VerifyTestResult (not x.empty ());
            VerifyTestResult (*x == 1);
        }
        {
            // Careful about self-assignment
            Optional<int>   x;
            x = 3;
            x = max (*x, 1);
            VerifyTestResult (x == 3);
        }
    }
    void    Test2_SharedByValue ()
    {
    }
    void    Test3_VariantValue ()
    {
        {
            VariantValue v;
            VerifyTestResult (v.empty ());
            v = String (L"hi");
            VerifyTestResult (v == L"hi");
        }
    }
    void    Test_4_Optional_Of_Mapping_Copy_Problem_ ()
    {
        using   namespace   Stroika::Foundation::Memory;
        using   namespace   Stroika::Foundation::Containers;
        Mapping<int, float>  ml1, ml2;
        ml1 = ml2;

        Optional<Mapping<int, float>>  ol1, ol2;
        if (ol2.IsPresent ()) {
            ml1 = *ol2;
        }
        ol1 = ml1;
        Optional<Mapping<int, float>>  xxxx2 (ml1);

        // fails to compile prior to 2013-09-09
        Optional<Mapping<int, float>>  xxxx1 (ol1);
        // fails to compile prior to 2013-09-09
        ol1 = ol2;
    }
    void    Test_5_AnyVariantValue_ ()
    {
        {
            VerifyTestResult (AnyVariantValue ().empty ());
            VerifyTestResult (not AnyVariantValue (1).empty ());
            VerifyTestResult (not AnyVariantValue ("1").empty ());
            //VerifyTestResult (AnyVariantValue ("1").GetType () == typeid ("1"));  // not sure why this fails but not worthy worrying about yet
            VerifyTestResult (static_cast<int> (AnyVariantValue (1)) == 1);
        }
        {
            AnyVariantValue v;
            VerifyTestResult (v.empty ());
            v = 1;
            VerifyTestResult (not v.empty ());
            VerifyTestResult (v.GetType () == typeid (1));
            VerifyTestResult (static_cast<int> (v) == 1);
            v = L"a";
            //VerifyTestResult (v.GetType () == typeid (L"a")); // not sure why this fails but not worthy worrying about yet
            VerifyTestResult (not v.empty ());
            v.clear ();
            VerifyTestResult (v.empty ());
            VerifyTestResult (v.GetType () == typeid (void));
        }
        {
            struct JIM {
                int a;
            };
            AnyVariantValue v;
            VerifyTestResult (v.empty ());
            v = JIM ();
            VerifyTestResult (v.GetType () == typeid (JIM));
        }
        {
            AnyVariantValue v;
            VerifyTestResult (v.empty ());
            v = 1;
            v = v;
            VerifyTestResult (v.GetType () == typeid (1));
            VerifyTestResult (static_cast<int> (v) == 1);
            v = AnyVariantValue (v);
            VerifyTestResult (v.GetType () == typeid (1));
            VerifyTestResult (static_cast<int> (v) == 1);
        }
    }
}

namespace   {

    void    DoRegressionTests_ ()
    {
        Test1_Optional ();
        Test2_SharedByValue ();
        Test3_VariantValue ();
        Test_4_Optional_Of_Mapping_Copy_Problem_ ();
        Test_5_AnyVariantValue_ ();
    }
}

int main (int argc, const char* argv[])
{
    Stroika::TestHarness::Setup ();
    Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
    return EXIT_SUCCESS;
}

<commit_msg>Embellished AnyVariantValue test code<commit_after>/*
 * Copyright(c) Sophist Solutions Inc. 1990-2013.  All rights reserved
 */
//  TEST    Foundation::Memory
#include    "Stroika/Foundation/StroikaPreComp.h"

#include    "Stroika/Foundation/Containers/Mapping.h"
#include    "Stroika/Foundation/Debug/Assertions.h"
#include    "Stroika/Foundation/Debug/Trace.h"

#include    "Stroika/Foundation/Memory/AnyVariantValue.h"
#include    "Stroika/Foundation/Memory/Optional.h"
#include    "Stroika/Foundation/Memory/SharedByValue.h"
#include    "Stroika/Foundation/Memory/VariantValue.h"

#include    "../TestHarness/SimpleClass.h"
#include    "../TestHarness/TestHarness.h"

using   namespace   Stroika;
using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Memory;

//TODO: DOES IT EVEN NEED TO BE SAID? THese tests are a bit sparse ;-)

namespace   {
    void    Test1_Optional ()
    {
        {
            Optional<int>   x;
            VerifyTestResult (x.empty ());
            x = 1;
            VerifyTestResult (not x.empty ());
            VerifyTestResult (*x == 1);
        }
        {
            // Careful about self-assignment
            Optional<int>   x;
            x = 3;
            x = max (*x, 1);
            VerifyTestResult (x == 3);
        }
    }
    void    Test2_SharedByValue ()
    {
    }
    void    Test3_VariantValue ()
    {
        {
            VariantValue v;
            VerifyTestResult (v.empty ());
            v = String (L"hi");
            VerifyTestResult (v == L"hi");
        }
    }
    void    Test_4_Optional_Of_Mapping_Copy_Problem_ ()
    {
        using   namespace   Stroika::Foundation::Memory;
        using   namespace   Stroika::Foundation::Containers;
        Mapping<int, float>  ml1, ml2;
        ml1 = ml2;

        Optional<Mapping<int, float>>  ol1, ol2;
        if (ol2.IsPresent ()) {
            ml1 = *ol2;
        }
        ol1 = ml1;
        Optional<Mapping<int, float>>  xxxx2 (ml1);

        // fails to compile prior to 2013-09-09
        Optional<Mapping<int, float>>  xxxx1 (ol1);
        // fails to compile prior to 2013-09-09
        ol1 = ol2;
    }
    void    Test_5_AnyVariantValue_ ()
    {
        {
            VerifyTestResult (AnyVariantValue ().empty ());
            VerifyTestResult (not AnyVariantValue (1).empty ());
            VerifyTestResult (not AnyVariantValue ("1").empty ());
            //VerifyTestResult (AnyVariantValue ("1").GetType () == typeid ("1"));  // not sure why this fails but not worthy worrying about yet
            VerifyTestResult (static_cast<int> (AnyVariantValue (1)) == 1);
        }
        {
            AnyVariantValue v;
            VerifyTestResult (v.empty ());
            v = 1;
            VerifyTestResult (not v.empty ());
            VerifyTestResult (v.GetType () == typeid (1));
            VerifyTestResult (static_cast<int> (v) == 1);
            v = L"a";
            //VerifyTestResult (v.GetType () == typeid (L"a")); // not sure why this fails but not worthy worrying about yet
            VerifyTestResult (not v.empty ());
            v.clear ();
            VerifyTestResult (v.empty ());
            VerifyTestResult (v.GetType () == typeid (void));
        }
        {
            struct JIM {
                int a;
            };
            AnyVariantValue v;
            VerifyTestResult (v.empty ());
            v = JIM ();
            VerifyTestResult (v.GetType () == typeid (JIM));
        }
        {
            AnyVariantValue v;
            VerifyTestResult (v.empty ());
            v = 1;
            v = v;
            VerifyTestResult (v.GetType () == typeid (1));
            VerifyTestResult (static_cast<int> (v) == 1);
            v = AnyVariantValue (v);
            VerifyTestResult (v.GetType () == typeid (1));
            VerifyTestResult (static_cast<int> (v) == 1);
        }
        {
            static int nCopies = 0;
            struct Copyable {
                Copyable () {
                    ++nCopies;
                }
                Copyable (const Copyable&) {
                    ++nCopies;
                }
                ~Copyable () {
                    --nCopies;
                }
                NO_ASSIGNMENT_OPERATOR(Copyable);
            };
            {
                AnyVariantValue v;
                VerifyTestResult (v.empty ());
                v = Copyable ();
                v = v;
                v = AnyVariantValue (AnyVariantValue (v));
                v = AnyVariantValue (AnyVariantValue (Copyable ()));
                VerifyTestResult (v.GetType () == typeid (Copyable));
            }
            VerifyTestResult (0 == nCopies);
        }
    }
}

namespace   {

    void    DoRegressionTests_ ()
    {
        Test1_Optional ();
        Test2_SharedByValue ();
        Test3_VariantValue ();
        Test_4_Optional_Of_Mapping_Copy_Problem_ ();
        Test_5_AnyVariantValue_ ();
    }
}

int main (int argc, const char* argv[])
{
    Stroika::TestHarness::Setup ();
    Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
    return EXIT_SUCCESS;
}

<|endoftext|>


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

#ifndef SC_ACREDLIN_HXX
#define SC_ACREDLIN_HXX

#ifndef _MOREBTN_HXX //autogen
#include <vcl/morebtn.hxx>
#endif
#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif

#ifndef _HEADBAR_HXX //autogen
#include <svtools/headbar.hxx>
#endif

#ifndef _SVTABBX_HXX //autogen
#include <svtools/svtabbx.hxx>
#endif

#ifndef SC_RANGENAM_HXX
#include "rangenam.hxx"
#endif

#ifndef SC_ANYREFDG_HXX
#include "anyrefdg.hxx"
#endif

#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _SVX_ACREDLIN_HXX
#include <svx/ctredlin.hxx>
#endif

#ifndef _SVX_SIMPTABL_HXX
#include <svx/simptabl.hxx>
#endif

#ifndef _SVARRAY_HXX
#define _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif

#ifndef SC_CHGTRACK_HXX
#include "chgtrack.hxx"
#endif

#ifndef SC_CHGVISET_HXX
#include "chgviset.hxx"
#endif

#ifndef _SV_TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif

class ScViewData;
class ScDocument;

#define FLT_DATE_BEFORE     0
#define FLT_DATE_SINCE      1
#define FLT_DATE_EQUAL      2
#define FLT_DATE_NOTEQUAL   3
#define FLT_DATE_BETWEEN    4
#define FLT_DATE_SAVE       5

class ScViewEntryPtr
{
private:
    String*         pAction;
    String*         pPos;
    String*         pAuthor;
    String*         pDate;
    String*         pComment;
    void*           pData;

public:

    String*         GetpAction()    {return pAction; }
    String*         GetpPos()       {return pPos;    }
    String*         GetpAuthor()    {return pAuthor; }
    String*         GetpDate()      {return pDate;   }
    String*         GetpComment()   {return pComment;}
    void*           GetpData()      {return pData;   }

    void        SetpAction (String* pString)    {pAction= pString;}
    void        SetpPos    (String* pString)    {pPos   = pString;}
    void        SetpAuthor (String* pString)    {pAuthor= pString;}
    void        SetpDate   (String* pString)    {pDate  = pString;}
    void        SetpComment(String* pString)    {pComment=pString;}
    void        SetpData   (void*   pdata)      {pData   =pdata;}
};

class ScViewEntryPtrList
{
    ScViewEntryPtrList* pNext;
    ScViewEntryPtrList* pLast;

    ScViewEntryPtr* pData;
};

class ScRedlinData : public RedlinData
{
public:

                    ScRedlinData();
                    ~ScRedlinData();
    USHORT          nTable;
    USHORT          nCol;
    USHORT          nRow;
    ULONG           nActionNo;
    ULONG           nInfo;
    BOOL            bIsRejectable;
    BOOL            bIsAcceptable;
};

typedef long LExpNum;

//@ Expand-Entrys nicht eindeutig, daher gestrichen
//DECLARE_TABLE( ScChgTrackExps, LExpNum)
//==================================================================

class ScAcceptChgDlg : public SfxModelessDialog
{
private:

    Timer                   aSelectionTimer;
    Timer                   aReOpenTimer;
    SvxAcceptChgCtr         aAcceptChgCtr;
    ScViewData*             pViewData;
    ScDocument*             pDoc;
    ScRangeName             aLocalRangeName;
    Selection               theCurSel;
    SvxTPFilter*            pTPFilter;
    SvxTPView*              pTPView;
    SvxRedlinTable*         pTheView;
    Size                    MinSize;
    ScRangeList             aRangeList;
    ScChangeViewSettings    aChangeViewSet;
    String                  aStrInsertCols;
    String                  aStrInsertRows;
    String                  aStrInsertTabs;
    String                  aStrDeleteCols;
    String                  aStrDeleteRows;
    String                  aStrDeleteTabs;
    String                  aStrMove;
    String                  aStrContent;
    String                  aStrReject;
    String                  aUnknown;
    String                  aStrAllAccepted;
    String                  aStrAllRejected;
    String                  aStrNoEntry;
    String                  aStrContentWithChild;
    String                  aStrChildContent;
    String                  aStrChildOrgContent;
    String                  aStrEmpty;
    ULONG                   nAcceptCount;
    ULONG                   nRejectCount;
    BOOL                    bAcceptEnableFlag;
    BOOL                    bRejectEnableFlag;
    BOOL                    bNeedsUpdate;
    BOOL                    bIgnoreMsg;
    BOOL                    bNoSelection;
    BOOL                    bHasFilterEntry;
    BOOL                    bUseColor;
    //ScChgTrackExps            aExpandArray;

    void            Init();
    void            InitFilter();
    void            SetMyStaticData();

    DECL_LINK( FilterHandle, SvxTPFilter* );
    DECL_LINK( RefHandle, SvxTPFilter* );
    DECL_LINK( FilterModified, SvxTPFilter* );
    DECL_LINK( MinSizeHandle, SvxAcceptChgCtr*);
    DECL_LINK( RejectHandle, SvxTPView*);
    DECL_LINK( AcceptHandle, SvxTPView*);
    DECL_LINK( RejectAllHandle, SvxTPView*);
    DECL_LINK( AcceptAllHandle, SvxTPView*);
    DECL_LINK( ExpandingHandle, SvxRedlinTable*);
    DECL_LINK( SelectHandle, SvxRedlinTable*);
    DECL_LINK( RefInfoHandle, String*);

    DECL_LINK( UpdateSelectionHdl, Timer*);
    DECL_LINK( ChgTrackModHdl, ScChangeTrack*);
    DECL_LINK( CommandHdl, Control*);
    DECL_LINK( ReOpenTimerHdl, Timer*);
    DECL_LINK( ColCompareHdl, SvSortData*);

protected:

    virtual void    Resize();
    virtual BOOL    Close();

    void            RejectFiltered();
    void            AcceptFiltered();

    BOOL            IsValidAction(const ScChangeAction* pScChangeAction);

    String*         MakeTypeString(ScChangeActionType eType);

    SvLBoxEntry*    InsertChangeAction(const ScChangeAction* pScChangeAction,ScChangeActionState eState,
                                    SvLBoxEntry* pParent=NULL,BOOL bDelMaster=FALSE,
                                    BOOL bDisabled=FALSE,ULONG nPos=LIST_APPEND);

    SvLBoxEntry*    InsertFilteredAction(const ScChangeAction* pScChangeAction,ScChangeActionState eState,
                                    SvLBoxEntry* pParent=NULL,BOOL bDelMaster=FALSE,
                                    BOOL bDisabled=FALSE,ULONG nPos=LIST_APPEND);

    SvLBoxEntry*    InsertChangeActionContent(const ScChangeActionContent* pScChangeAction,
                                              SvLBoxEntry* pParent,ULONG nSpecial);

    void            GetDependents( const ScChangeAction* pScChangeAction,
                                ScChangeActionTable& aActionTable,
                                SvLBoxEntry* pEntry);

    BOOL            InsertContentChilds(ScChangeActionTable* pActionTable,SvLBoxEntry* pParent);

    BOOL            InsertAcceptedORejected(SvLBoxEntry* pParent);

    BOOL            InsertDeletedChilds(const ScChangeAction *pChangeAction, ScChangeActionTable* pActionTable,
                                        SvLBoxEntry* pParent);

    BOOL            InsertChilds(ScChangeActionTable* pActionTable,SvLBoxEntry* pParent);

    void            AppendChanges(ScChangeTrack* pChanges,ULONG nStartAction, ULONG nEndAction,
                                    ULONG nPos=LIST_APPEND);

    void            RemoveEntrys(ULONG nStartAction,ULONG nEndAction);
    void            UpdateEntrys(ScChangeTrack* pChgTrack, ULONG nStartAction,ULONG nEndAction);

    void            UpdateView();
    void            ClearView();

    BOOL            Expand(ScChangeTrack* pChanges,const ScChangeAction* pScChangeAction,
                            SvLBoxEntry* pEntry, BOOL bFilter=FALSE);

public:
                    ScAcceptChgDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent,
                               ScViewData*      ptrViewData);

                    ~ScAcceptChgDlg();

    void            ReInit(ScViewData* ptrViewData);

    virtual long    PreNotify( NotifyEvent& rNEvt );

    void            Initialize (SfxChildWinInfo* pInfo);
    virtual void    FillInfo(SfxChildWinInfo&) const;

};

#endif // SC_NAMEDLG_HXX

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

#ifndef SC_ACREDLIN_HXX
#define SC_ACREDLIN_HXX

#ifndef _MOREBTN_HXX //autogen
#include <vcl/morebtn.hxx>
#endif
#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif
#ifndef _GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif

#ifndef _HEADBAR_HXX //autogen
#include <svtools/headbar.hxx>
#endif

#ifndef _SVTABBX_HXX //autogen
#include <svtools/svtabbx.hxx>
#endif

#ifndef SC_RANGENAM_HXX
#include "rangenam.hxx"
#endif

#ifndef SC_ANYREFDG_HXX
#include "anyrefdg.hxx"
#endif

#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _SVX_ACREDLIN_HXX
#include <svx/ctredlin.hxx>
#endif

#ifndef _SVX_SIMPTABL_HXX
#include <svx/simptabl.hxx>
#endif

#ifndef _SVARRAY_HXX
#define _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif

#ifndef SC_CHGTRACK_HXX
#include "chgtrack.hxx"
#endif

#ifndef SC_CHGVISET_HXX
#include "chgviset.hxx"
#endif

#ifndef _SV_TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif

class ScViewData;
class ScDocument;

#define FLT_DATE_BEFORE     0
#define FLT_DATE_SINCE      1
#define FLT_DATE_EQUAL      2
#define FLT_DATE_NOTEQUAL   3
#define FLT_DATE_BETWEEN    4
#define FLT_DATE_SAVE       5

class ScViewEntryPtr
{
private:
    String*         pAction;
    String*         pPos;
    String*         pAuthor;
    String*         pDate;
    String*         pComment;
    void*           pData;

public:

    String*         GetpAction()    {return pAction; }
    String*         GetpPos()       {return pPos;    }
    String*         GetpAuthor()    {return pAuthor; }
    String*         GetpDate()      {return pDate;   }
    String*         GetpComment()   {return pComment;}
    void*           GetpData()      {return pData;   }

    void        SetpAction (String* pString)    {pAction= pString;}
    void        SetpPos    (String* pString)    {pPos   = pString;}
    void        SetpAuthor (String* pString)    {pAuthor= pString;}
    void        SetpDate   (String* pString)    {pDate  = pString;}
    void        SetpComment(String* pString)    {pComment=pString;}
    void        SetpData   (void*   pdata)      {pData   =pdata;}
};

class ScViewEntryPtrList
{
    ScViewEntryPtrList* pNext;
    ScViewEntryPtrList* pLast;

    ScViewEntryPtr* pData;
};

class ScRedlinData : public RedlinData
{
public:

                    ScRedlinData();
                    ~ScRedlinData();
    SCTAB           nTable;
    SCCOL           nCol;
    SCROW           nRow;
    ULONG           nActionNo;
    ULONG           nInfo;
    BOOL            bIsRejectable;
    BOOL            bIsAcceptable;
};

typedef long LExpNum;

//@ Expand-Entrys nicht eindeutig, daher gestrichen
//DECLARE_TABLE( ScChgTrackExps, LExpNum)
//==================================================================

class ScAcceptChgDlg : public SfxModelessDialog
{
private:

    Timer                   aSelectionTimer;
    Timer                   aReOpenTimer;
    SvxAcceptChgCtr         aAcceptChgCtr;
    ScViewData*             pViewData;
    ScDocument*             pDoc;
    ScRangeName             aLocalRangeName;
    Selection               theCurSel;
    SvxTPFilter*            pTPFilter;
    SvxTPView*              pTPView;
    SvxRedlinTable*         pTheView;
    Size                    MinSize;
    ScRangeList             aRangeList;
    ScChangeViewSettings    aChangeViewSet;
    String                  aStrInsertCols;
    String                  aStrInsertRows;
    String                  aStrInsertTabs;
    String                  aStrDeleteCols;
    String                  aStrDeleteRows;
    String                  aStrDeleteTabs;
    String                  aStrMove;
    String                  aStrContent;
    String                  aStrReject;
    String                  aUnknown;
    String                  aStrAllAccepted;
    String                  aStrAllRejected;
    String                  aStrNoEntry;
    String                  aStrContentWithChild;
    String                  aStrChildContent;
    String                  aStrChildOrgContent;
    String                  aStrEmpty;
    ULONG                   nAcceptCount;
    ULONG                   nRejectCount;
    BOOL                    bAcceptEnableFlag;
    BOOL                    bRejectEnableFlag;
    BOOL                    bNeedsUpdate;
    BOOL                    bIgnoreMsg;
    BOOL                    bNoSelection;
    BOOL                    bHasFilterEntry;
    BOOL                    bUseColor;
    //ScChgTrackExps            aExpandArray;

    void            Init();
    void            InitFilter();
    void            SetMyStaticData();

    DECL_LINK( FilterHandle, SvxTPFilter* );
    DECL_LINK( RefHandle, SvxTPFilter* );
    DECL_LINK( FilterModified, SvxTPFilter* );
    DECL_LINK( MinSizeHandle, SvxAcceptChgCtr*);
    DECL_LINK( RejectHandle, SvxTPView*);
    DECL_LINK( AcceptHandle, SvxTPView*);
    DECL_LINK( RejectAllHandle, SvxTPView*);
    DECL_LINK( AcceptAllHandle, SvxTPView*);
    DECL_LINK( ExpandingHandle, SvxRedlinTable*);
    DECL_LINK( SelectHandle, SvxRedlinTable*);
    DECL_LINK( RefInfoHandle, String*);

    DECL_LINK( UpdateSelectionHdl, Timer*);
    DECL_LINK( ChgTrackModHdl, ScChangeTrack*);
    DECL_LINK( CommandHdl, Control*);
    DECL_LINK( ReOpenTimerHdl, Timer*);
    DECL_LINK( ColCompareHdl, SvSortData*);

protected:

    virtual void    Resize();
    virtual BOOL    Close();

    void            RejectFiltered();
    void            AcceptFiltered();

    BOOL            IsValidAction(const ScChangeAction* pScChangeAction);

    String*         MakeTypeString(ScChangeActionType eType);

    SvLBoxEntry*    InsertChangeAction(const ScChangeAction* pScChangeAction,ScChangeActionState eState,
                                    SvLBoxEntry* pParent=NULL,BOOL bDelMaster=FALSE,
                                    BOOL bDisabled=FALSE,ULONG nPos=LIST_APPEND);

    SvLBoxEntry*    InsertFilteredAction(const ScChangeAction* pScChangeAction,ScChangeActionState eState,
                                    SvLBoxEntry* pParent=NULL,BOOL bDelMaster=FALSE,
                                    BOOL bDisabled=FALSE,ULONG nPos=LIST_APPEND);

    SvLBoxEntry*    InsertChangeActionContent(const ScChangeActionContent* pScChangeAction,
                                              SvLBoxEntry* pParent,ULONG nSpecial);

    void            GetDependents( const ScChangeAction* pScChangeAction,
                                ScChangeActionTable& aActionTable,
                                SvLBoxEntry* pEntry);

    BOOL            InsertContentChilds(ScChangeActionTable* pActionTable,SvLBoxEntry* pParent);

    BOOL            InsertAcceptedORejected(SvLBoxEntry* pParent);

    BOOL            InsertDeletedChilds(const ScChangeAction *pChangeAction, ScChangeActionTable* pActionTable,
                                        SvLBoxEntry* pParent);

    BOOL            InsertChilds(ScChangeActionTable* pActionTable,SvLBoxEntry* pParent);

    void            AppendChanges(ScChangeTrack* pChanges,ULONG nStartAction, ULONG nEndAction,
                                    ULONG nPos=LIST_APPEND);

    void            RemoveEntrys(ULONG nStartAction,ULONG nEndAction);
    void            UpdateEntrys(ScChangeTrack* pChgTrack, ULONG nStartAction,ULONG nEndAction);

    void            UpdateView();
    void            ClearView();

    BOOL            Expand(ScChangeTrack* pChanges,const ScChangeAction* pScChangeAction,
                            SvLBoxEntry* pEntry, BOOL bFilter=FALSE);

public:
                    ScAcceptChgDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent,
                               ScViewData*      ptrViewData);

                    ~ScAcceptChgDlg();

    void            ReInit(ScViewData* ptrViewData);

    virtual long    PreNotify( NotifyEvent& rNEvt );

    void            Initialize (SfxChildWinInfo* pInfo);
    virtual void    FillInfo(SfxChildWinInfo&) const;

};

#endif // SC_NAMEDLG_HXX

<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: dbnamdlg.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef SC_DBNAMDLG_HXX
#define SC_DBNAMDLG_HXX

#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif

#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef _MOREBTN_HXX //autogen
#include <vcl/morebtn.hxx>
#endif
#include "anyrefdg.hxx"
#include "dbcolect.hxx"
#include "expftext.hxx"

class ScViewData;
class ScDocument;

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

class ScDbNameDlg : public ScAnyRefDlg
{
public:
                    ScDbNameDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent,
                                 ScViewData*    ptrViewData );
                    ~ScDbNameDlg();

    virtual void    SetReference( const ScRange& rRef, ScDocument* pDoc );

    virtual BOOL    IsRefInputMode() const;
    virtual void    SetActive();
    virtual BOOL    Close();

private:
    FixedLine           aFlName;
    ComboBox            aEdName;

    FixedLine           aFlAssign;
    ScRefEdit           aEdAssign;
    ScRefButton         aRbAssign;

    FixedLine           aFlOptions;
    CheckBox            aBtnHeader;
    CheckBox            aBtnDoSize;
    CheckBox            aBtnKeepFmt;
    CheckBox            aBtnStripData;
    ScExpandedFixedText aFTSource;     //@18.09.97 erweiterter FixedText
    FixedText           aFTOperations;

    OKButton        aBtnOk;
    CancelButton    aBtnCancel;
    HelpButton      aBtnHelp;
    PushButton      aBtnAdd;
    PushButton      aBtnRemove;
    MoreButton      aBtnMore;

    BOOL            bSaved;

    const String    aStrAdd;    // "Hinzufuegen"
    const String    aStrModify; // "Aendern"
    const String    aStrNoName; // "unbenannt"
    const String    aStrInvalid;

    String          aStrSource;
    String          aStrOperations;

    ScViewData*     pViewData;
    ScDocument*     pDoc;
    BOOL            bRefInputMode;

    ScDBCollection  aLocalDbCol;
    ScRange         theCurArea;
    List            aRemoveList;

#ifdef _DBNAMDLG_CXX
private:
    void            Init();
    void            UpdateNames();
    void            UpdateDBData( const String& rStrName );
    void            SetInfoStrings( const ScDBData* pDBData );

    DECL_LINK( CancelBtnHdl, void * );
    DECL_LINK( OkBtnHdl, void * );
    DECL_LINK( AddBtnHdl, void * );
    DECL_LINK( RemoveBtnHdl, void * );
    DECL_LINK( NameModifyHdl, void * );
    DECL_LINK( AssModifyHdl, void * );
#endif
};

#endif // SC_DBNAMDLG_HXX

<commit_msg>INTEGRATION: CWS koheiformula01 (1.3.684); FILE MERGED 2008/04/23 15:07:34 kohei 1.3.684.2: RESYNC: (1.3-1.4); FILE MERGED 2008/03/20 04:38:05 kohei 1.3.684.1: use grammar in the database range dialog.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: dbnamdlg.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef SC_DBNAMDLG_HXX
#define SC_DBNAMDLG_HXX

#ifndef _COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif

#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef _MOREBTN_HXX //autogen
#include <vcl/morebtn.hxx>
#endif
#include "anyrefdg.hxx"
#include "dbcolect.hxx"
#include "expftext.hxx"

class ScViewData;
class ScDocument;

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

class ScDbNameDlg : public ScAnyRefDlg
{
public:
                    ScDbNameDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent,
                                 ScViewData*    ptrViewData );
                    ~ScDbNameDlg();

    virtual void    SetReference( const ScRange& rRef, ScDocument* pDoc );

    virtual BOOL    IsRefInputMode() const;
    virtual void    SetActive();
    virtual BOOL    Close();

private:
    FixedLine           aFlName;
    ComboBox            aEdName;

    FixedLine           aFlAssign;
    ScRefEdit           aEdAssign;
    ScRefButton         aRbAssign;

    FixedLine           aFlOptions;
    CheckBox            aBtnHeader;
    CheckBox            aBtnDoSize;
    CheckBox            aBtnKeepFmt;
    CheckBox            aBtnStripData;
    ScExpandedFixedText aFTSource;     //@18.09.97 erweiterter FixedText
    FixedText           aFTOperations;

    OKButton        aBtnOk;
    CancelButton    aBtnCancel;
    HelpButton      aBtnHelp;
    PushButton      aBtnAdd;
    PushButton      aBtnRemove;
    MoreButton      aBtnMore;

    BOOL            bSaved;

    const String    aStrAdd;    // "Hinzufuegen"
    const String    aStrModify; // "Aendern"
    const String    aStrNoName; // "unbenannt"
    const String    aStrInvalid;

    String          aStrSource;
    String          aStrOperations;

    ScViewData*     pViewData;
    ScDocument*     pDoc;
    BOOL            bRefInputMode;
    ScAddress::Details aAddrDetails;

    ScDBCollection  aLocalDbCol;
    ScRange         theCurArea;
    List            aRemoveList;

#ifdef _DBNAMDLG_CXX
private:
    void            Init();
    void            UpdateNames();
    void            UpdateDBData( const String& rStrName );
    void            SetInfoStrings( const ScDBData* pDBData );

    DECL_LINK( CancelBtnHdl, void * );
    DECL_LINK( OkBtnHdl, void * );
    DECL_LINK( AddBtnHdl, void * );
    DECL_LINK( RemoveBtnHdl, void * );
    DECL_LINK( NameModifyHdl, void * );
    DECL_LINK( AssModifyHdl, void * );
#endif
};

#endif // SC_DBNAMDLG_HXX

<|endoftext|>