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

#ifndef HCKT_TREE_H
#define HCKT_TREE_H

#include <cassert>
#include <vector>
#include <bitset>
#include "lmemvector.hpp"

namespace hckt
{

template <typename ValueType>
class tree
{
protected:
    std::bitset<64>                    bitset;
    std::bitset<64>                    leaf;
    hckt::lmemvector<ValueType>        values;
    hckt::lmemvector<tree<ValueType>*> children;

public:
    tree() : bitset { 0 }, leaf { 0 }, values { }, children { }
    {
    }

    ~tree()
    {
        collapse();
    }

    //counts number of set bits
    static inline unsigned popcount(std::uint64_t x)
    {
#ifdef __SSE4_2__
        return _popcnt64(x);
#else
        constexpr std::uint64_t m1  { 0x5555555555555555 };
        constexpr std::uint64_t m2  { 0x3333333333333333 };
        constexpr std::uint64_t m4  { 0x0f0f0f0f0f0f0f0f };
        constexpr std::uint64_t h01 { 0x0101010101010101 };

        x -= (x >> 1) & m1;
        x  = (x & m2) + ((x >> 2) & m2);
        x  = (x + (x >> 4)) & m4;

        return (x * h01) >> 56;
#endif
    }

    unsigned get_children_position(const unsigned position) const
    {
        assert(position < 64);

        //we know it will be 0
        //plus - we cant shift by 64 without ub
        if(position == 0) {
            return 0;
        }

        return popcount(bitset.to_ullong() << (64 - position));
    }

    std::size_t calculate_memory_size() const
    {
        std::size_t size {
              sizeof(bitset)
            + sizeof(leaf)
            + sizeof(values)   + (values.capacity()   * sizeof(ValueType))
            + sizeof(children) + (children.capacity() * sizeof(tree<ValueType>*))
        };

        for(auto child : children) {
            size += child->calculate_memory_size();
        }

        return size;
    }

    std::size_t calculate_children_amount() const
    {
        std::size_t amount { popcount(bitset.to_ullong()) };

        for(auto child : children) {
            amount += child->calculate_children_amount();
        }

        return amount;
    }

    void mem_usage_info()
    {
        auto memsize = calculate_memory_size();
        auto camnt = calculate_children_amount();
        std::cout << "total:     " << memsize << std::endl;
        std::cout << "tree-size: " << sizeof(tree<ValueType>) << std::endl;
        std::cout << "children:  " << camnt << std::endl;
        std::cout << "per-child: " << (static_cast<float>(memsize) / camnt) << std::endl;
        std::cout << "val-size:  " << sizeof(ValueType) << std::endl;
        std::cout << "overhead:  " << (static_cast<float>(memsize - (camnt * sizeof(ValueType))) / camnt) << std::endl;
    }

    /*
     * 2d get position
     * convert three part positions to memory location
     * as input: (left = 0 | right = 1) + (top = 0 | bottom = 2)
     *
     * result will be:
     * y1:x1:y2:x2:y3:x3
     *
     */
    static unsigned get_position_2d(const unsigned d1, const unsigned d2, const unsigned d3)
    {
        assert(d1 < 4);
        assert(d2 < 4);
        assert(d3 < 4);

        return ((1 << 0) * ((d1 & 2) >> 1))
             + ((1 << 1) *  (d1 & 1))
             + ((1 << 2) * ((d2 & 2) >> 1))
             + ((1 << 3) *  (d2 & 1))
             + ((1 << 4) * ((d3 & 2) >> 1))
             + ((1 << 5) *  (d3 & 1));
    }

    static unsigned get_x_2d(const unsigned d1, const unsigned d2, const unsigned d3)
    {
        assert(d1 < 4);
        assert(d2 < 4);
        assert(d3 < 4);

        return ((d1 & 1) << 0)
             + ((d2 & 1) << 1)
             + ((d3 & 1) << 2);
    }

    static unsigned get_y_2d(const unsigned d1, const unsigned d2, const unsigned d3)
    {
        assert(d1 < 4);
        assert(d2 < 4);
        assert(d3 < 4);

        return ((d1 & 2) >> 1 << 0)
             + ((d2 & 2) >> 1 << 1)
             + ((d3 & 2) >> 1 << 2);
    }

    /*
     * 3d get position
     * convert two part positions to memory location
     * as input: (left = 0 | right = 1) + (top = 0 | bottom = 2) + (in = 0 | out = 4)
     *
     * result will be:
     * z1:y1:x1:z2:y2:x2
     *
     */
    static unsigned get_position_3d(const unsigned d1, const unsigned d2)
    {
        assert(d1 < 8);
        assert(d2 < 8);

        return ((1 << 0) * ((d1 & 4) >> 2))
             + ((1 << 1) * ((d1 & 2) >> 1))
             + ((1 << 2) *  (d1 & 1))
             + ((1 << 3) * ((d2 & 4) >> 2))
             + ((1 << 4) * ((d2 & 2) >> 1))
             + ((1 << 5) *  (d2 & 1));
    }

    static unsigned get_x_3d(const unsigned d1, const unsigned d2)
    {
        assert(d1 < 8);
        assert(d2 < 8);

        return ((d1 & 1) << 0)
             + ((d2 & 1) << 1);
    }

    static unsigned get_y_3d(const unsigned d1, const unsigned d2)
    {
        assert(d1 < 8);
        assert(d2 < 8);

        return ((d1 & 2) >> 1 << 0)
             + ((d2 & 2) >> 1 << 1);
    }

    static unsigned get_z_3d(const unsigned d1, const unsigned d2)
    {
        assert(d1 < 8);
        assert(d2 < 8);

        return ((d1 & 4) >> 2 << 0)
             + ((d2 & 4) >> 2 << 1);
    }

    /*
     * check if we have any children
     */
    bool empty() const
    {
        return bitset.none();
    }

    bool is_set(const unsigned position) const
    {
        assert(position < 64);
        return bitset[position];
    }

    bool is_leaf(const unsigned position) const
    {
        assert(position < 64);
        return leaf[position];
    }

    /*
     * destroy children
     */
    void collapse()
    {
        for(auto child : children) {
            child->collapse();
        }

        children.clear();
        values.clear();
        bitset.reset();
    }

    /*
     * insert an item into position of tree
     * position should be result of get_position
     */
    void insert(const unsigned position, const ValueType value)
    {
        assert(position < 64);
        assert(! is_set(position));

        const unsigned cpos { get_children_position(position) };

        children.insert(cpos, new tree<ValueType>());
        values.insert(cpos, value);
        bitset.set(position);
    }

    void insert_direct(const unsigned position, const unsigned cpos, const ValueType value)
    {
        assert(position < 64);
        assert(! isset(position));
        assert(cpos     < 64);

        children.insert(cpos, new tree<ValueType>());
        values.insert(cpos, value);
        bitset.set(position);
    }

    /*
     * removes an item from tree
     * position should be result of get_position
     */
    void remove(const unsigned position)
    {
        assert(position < 64);
        assert(is_set(position));

        const unsigned cpos { get_children_position(position) };

        children[cpos]->collapse();
        children.erase(cpos);
        values.erase(cpos);
        bitset.reset(position);
    }

    void remove_direct(const unsigned position, const unsigned cpos)
    {
        assert(position < 64);
        assert(isset(position));
        assert(cpos     < 64);

        children[cpos]->collapse();
        children.erase(cpos);
        values.erase(cpos);
        bitset.reset(position);
    }

    /*
     * get child node
     * position should be result of get_position
     */
    tree<ValueType> * child(const unsigned position) const
    {
        assert(position < 64);
        assert(is_set(position));

        return child_direct(get_children_position(position));
    }

    tree<ValueType> * child_direct(const unsigned cpos) const
    {
        assert(cpos < 64);

        return children[cpos];
    }

    /*
     * sets node to specific value
     * note: this does not check whether a value has been inserted here yet
     * position should be result of get_position
     */
    void set_value(const unsigned position, const ValueType value)
    {
        assert(position < 64);
        assert(is_set(position));

        set_value_direct(get_children_position(position));
    }

    void set_value_direct(const unsigned cpos, const ValueType value)
    {
        assert(cpos < 64);

        values[cpos] = value;
    }

    /*
     * gets value from specific position
     * note: this does not check whether a value has been inserted here yet
     * position should be result of get_position
     */
    ValueType get_value(const unsigned position) const
    {
        assert(position < 64);

        return get_value_direct(get_children_position(position));
    }

    ValueType get_value_direct(const unsigned cpos) const
    {
        assert(cpos < 64);
        assert(isset(cpos));

        return values[cpos];
    }
};

};

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

#ifndef HCKT_TREE_H
#define HCKT_TREE_H

#include <cassert>
#include <vector>
#include <bitset>
#include "lmemvector.hpp"

namespace hckt
{

template <typename ValueType>
class tree
{
protected:
    std::bitset<64>                    bitset;
    std::bitset<64>                    leaf;
    hckt::lmemvector<ValueType>        values;
    hckt::lmemvector<tree<ValueType>*> children;

public:
    tree() : bitset { 0 }, leaf { 0 }, values { }, children { }
    {
    }

    ~tree()
    {
        collapse();
    }

    //counts number of set bits
    static inline unsigned popcount(std::uint64_t x)
    {
#ifdef __SSE4_2__
        return _popcnt64(x);
#else
        constexpr std::uint64_t m1  { 0x5555555555555555 };
        constexpr std::uint64_t m2  { 0x3333333333333333 };
        constexpr std::uint64_t m4  { 0x0f0f0f0f0f0f0f0f };
        constexpr std::uint64_t h01 { 0x0101010101010101 };

        x -= (x >> 1) & m1;
        x  = (x & m2) + ((x >> 2) & m2);
        x  = (x + (x >> 4)) & m4;

        return (x * h01) >> 56;
#endif
    }

    unsigned get_children_position(const unsigned position) const
    {
        assert(position < 64);

        //we know it will be 0
        //plus - we cant shift by 64 without ub
        if(position == 0) {
            return 0;
        }

        return popcount(bitset.to_ullong() << (64 - position));
    }

    std::size_t calculate_memory_size() const
    {
        std::size_t size {
              sizeof(bitset)
            + sizeof(leaf)
            + sizeof(values)   + (values.capacity()   * sizeof(ValueType))
            + sizeof(children) + (children.capacity() * sizeof(tree<ValueType>*))
        };

        for(auto child : children) {
            size += child->calculate_memory_size();
        }

        return size;
    }

    std::size_t calculate_children_amount() const
    {
        std::size_t amount { popcount(bitset.to_ullong()) };

        for(auto child : children) {
            amount += child->calculate_children_amount();
        }

        return amount;
    }

    void mem_usage_info()
    {
        auto memsize = calculate_memory_size();
        auto camnt = calculate_children_amount();
        std::cout << "total:     " << memsize << std::endl;
        std::cout << "tree-size: " << sizeof(tree<ValueType>) << std::endl;
        std::cout << "children:  " << camnt << std::endl;
        std::cout << "per-child: " << (static_cast<float>(memsize) / camnt) << std::endl;
        std::cout << "val-size:  " << sizeof(ValueType) << std::endl;
        std::cout << "overhead:  " << (static_cast<float>(memsize - (camnt * sizeof(ValueType))) / camnt) << std::endl;
    }

    /*
     * 2d get position
     * convert three part positions to memory location
     * as input: (left = 0 | right = 1) + (top = 0 | bottom = 2)
     *
     * result will be:
     * y1:x1:y2:x2:y3:x3
     *
     */
    static unsigned get_position_2d(const unsigned d1, const unsigned d2, const unsigned d3)
    {
        assert(d1 < 4);
        assert(d2 < 4);
        assert(d3 < 4);

        return ((1 << 0) * ((d1 & 2) >> 1))
             + ((1 << 1) *  (d1 & 1))
             + ((1 << 2) * ((d2 & 2) >> 1))
             + ((1 << 3) *  (d2 & 1))
             + ((1 << 4) * ((d3 & 2) >> 1))
             + ((1 << 5) *  (d3 & 1));
    }

    static unsigned get_x_2d(const unsigned d1, const unsigned d2, const unsigned d3)
    {
        assert(d1 < 4);
        assert(d2 < 4);
        assert(d3 < 4);

        return ((d1 & 1) << 0)
             + ((d2 & 1) << 1)
             + ((d3 & 1) << 2);
    }

    static unsigned get_y_2d(const unsigned d1, const unsigned d2, const unsigned d3)
    {
        assert(d1 < 4);
        assert(d2 < 4);
        assert(d3 < 4);

        return ((d1 & 2) >> 1 << 0)
             + ((d2 & 2) >> 1 << 1)
             + ((d3 & 2) >> 1 << 2);
    }

    /*
     * 3d get position
     * convert two part positions to memory location
     * as input: (left = 0 | right = 1) + (top = 0 | bottom = 2) + (in = 0 | out = 4)
     *
     * result will be:
     * z1:y1:x1:z2:y2:x2
     *
     */
    static unsigned get_position_3d(const unsigned d1, const unsigned d2)
    {
        assert(d1 < 8);
        assert(d2 < 8);

        return ((1 << 0) * ((d1 & 4) >> 2))
             + ((1 << 1) * ((d1 & 2) >> 1))
             + ((1 << 2) *  (d1 & 1))
             + ((1 << 3) * ((d2 & 4) >> 2))
             + ((1 << 4) * ((d2 & 2) >> 1))
             + ((1 << 5) *  (d2 & 1));
    }

    static unsigned get_x_3d(const unsigned d1, const unsigned d2)
    {
        assert(d1 < 8);
        assert(d2 < 8);

        return ((d1 & 1) << 0)
             + ((d2 & 1) << 1);
    }

    static unsigned get_y_3d(const unsigned d1, const unsigned d2)
    {
        assert(d1 < 8);
        assert(d2 < 8);

        return ((d1 & 2) >> 1 << 0)
             + ((d2 & 2) >> 1 << 1);
    }

    static unsigned get_z_3d(const unsigned d1, const unsigned d2)
    {
        assert(d1 < 8);
        assert(d2 < 8);

        return ((d1 & 4) >> 2 << 0)
             + ((d2 & 4) >> 2 << 1);
    }

    /*
     * check if we have any children
     */
    bool empty() const
    {
        return bitset.none();
    }

    bool is_set(const unsigned position) const
    {
        assert(position < 64);
        return bitset[position];
    }

    bool is_leaf(const unsigned position) const
    {
        assert(position < 64);
        return leaf[position];
    }

    /*
     * destroy children
     */
    void collapse()
    {
        for(auto child : children) {
            child->collapse();
        }

        children.clear();
        values.clear();
        bitset.reset();
    }

    /*
     * insert an item into position of tree
     * position should be result of get_position
     */
    void insert(const unsigned position, const ValueType value)
    {
        assert(position < 64);
        assert(! is_set(position));

        const unsigned cpos { get_children_position(position) };

        children.insert(cpos, new tree<ValueType>());
        values.insert(cpos, value);
        bitset.set(position);
    }

    /*
     * removes an item from tree
     * position should be result of get_position
     */
    void remove(const unsigned position)
    {
        assert(position < 64);
        assert(is_set(position));

        const unsigned cpos { get_children_position(position) };

        children[cpos]->collapse();
        children.erase(cpos);
        values.erase(cpos);
        bitset.reset(position);
    }

    /*
     * get child node
     * position should be result of get_position
     */
    tree<ValueType> * child(const unsigned position) const
    {
        assert(position < 64);
        assert(is_set(position));

        const unsigned cpos { get_children_position(position) };

        return children[cpos];
    }

    /*
     * sets node to specific value
     * note: this does not check whether a value has been inserted here yet
     * position should be result of get_position
     */
    void set_value(const unsigned position, const ValueType value)
    {
        assert(position < 64);
        assert(is_set(position));

        const unsigned cpos { get_children_position(position) };

        values[cpos] = value;
    }

    /*
     * gets value from specific position
     * note: this does not check whether a value has been inserted here yet
     * position should be result of get_position
     */
    ValueType get_value(const unsigned position) const
    {
        assert(position < 64);

        const unsigned cpos { get_children_position(position) };

        return values[cpos];
    }
};

};

#endif
<|endoftext|>


<commit_before>/* This file is part of Ingen.
 * Copyright (C) 2007 Dave Robillard <http://drobilla.net>
 *
 * Ingen is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * Ingen is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <sstream>
#include <lv2ext/lv2_event.h>
#include "Responder.hpp"
#include "SetPortValueEvent.hpp"
#include "Engine.hpp"
#include "PortImpl.hpp"
#include "ClientBroadcaster.hpp"
#include "NodeImpl.hpp"
#include "ObjectStore.hpp"
#include "AudioBuffer.hpp"
#include "EventBuffer.hpp"
#include "ProcessContext.hpp"

using namespace std;

namespace Ingen {

/** Omni (all voices) control setting */
SetPortValueEvent::SetPortValueEvent(Engine&              engine,
                                     SharedPtr<Responder> responder,
                                     bool                 queued,
                                     SampleCount          timestamp,
                                     const string&        port_path,
                                     const string&        data_type,
                                     uint32_t             data_size,
                                     const void*          data)
	: QueuedEvent(engine, responder, timestamp)
	, _queued(queued)
	, _omni(true)
	, _voice_num(0)
	, _port_path(port_path)
	, _data_type(data_type)
	, _data_size(data_size)
	, _data(malloc(data_size))
	, _port(NULL)
	, _error(NO_ERROR)
{
	if (_queued)
		pre_process();

	memcpy(_data, data, data_size);
}

/** Voice-specific control setting */
SetPortValueEvent::SetPortValueEvent(Engine&              engine,
                                     SharedPtr<Responder> responder,
                                     bool                 queued,
                                     SampleCount          timestamp,
                                     uint32_t             voice_num,
                                     const string&        port_path,
                                     const string&        data_type,
                                     uint32_t             data_size,
                                     const void*          data)
	: QueuedEvent(engine, responder, timestamp)
	, _queued(queued)
	, _omni(false)
	, _voice_num(voice_num)
	, _data_type(data_type)
	, _data_size(data_size)
	, _data(malloc(data_size))
	, _port(NULL)
	, _error(NO_ERROR)
{
	if (_queued)
		pre_process();

	memcpy(_data, data, data_size);
}

SetPortValueEvent::~SetPortValueEvent()
{
	free(_data);
}

void
SetPortValueEvent::pre_process()
{
	if (_queued) {
		if (_port == NULL)
			_port = _engine.object_store()->find_port(_port_path);

		if (_port == NULL)
			_error = PORT_NOT_FOUND;
	}

	QueuedEvent::pre_process();
}

void
SetPortValueEvent::execute(ProcessContext& context)
{
	Event::execute(context);
	assert(_time >= context.start() && _time <= context.end());

	if (_port == NULL)
		_port = _engine.object_store()->find_port(_port_path);

	if (_port == NULL) {
		_error = PORT_NOT_FOUND;
	/*} else if (_port->buffer(0)->capacity() < _data_size) {
		_error = NO_SPACE;*/
	} else {
		Buffer* const buf = _port->buffer(0);
		AudioBuffer* const abuf = dynamic_cast<AudioBuffer*>(buf);
		if (abuf) {
			const uint32_t offset = (buf->size() == 1) ? 0 : _time - context.start();

			if (_omni)
				for (uint32_t i=0; i < _port->poly(); ++i)
					((AudioBuffer*)_port->buffer(i))->set(*(float*)_data, offset);
			else
				((AudioBuffer*)_port->buffer(_voice_num))->set(*(float*)_data, offset);

			return;
		}

		EventBuffer* const ebuf = dynamic_cast<EventBuffer*>(buf);
		// FIXME: eliminate string comparisons
		if (ebuf && _data_type == "lv2_midi:MidiEvent") {
			const LV2Features::Feature* f = _engine.world()->lv2_features->feature(LV2_URI_MAP_URI);
			LV2URIMap* map = (LV2URIMap*)f->controller;
			const uint32_t type_id = map->uri_to_id(NULL, "http://lv2plug.in/ns/ext/midi#MidiEvent");
			const uint32_t frames = std::max((uint32_t)(_time - context.start()), ebuf->latest_frames());
			ebuf->prepare_write(context.nframes());
			// FIXME: how should this work? binary over OSC, ick
			// Message is an event:
			ebuf->append(frames, 0, type_id, _data_size, (const unsigned char*)_data);
			// Message is an event buffer:
			//ebuf->append((LV2_Event_Buffer*)_data);
			_port->raise_set_by_user_flag();
			return;
		}

		cerr << "WARNING: Unknown value type " << _data_type << ", ignoring" << endl;
	}
}

void
SetPortValueEvent::post_process()
{
	if (_error == NO_ERROR) {
		assert(_port != NULL);

		_responder->respond_ok();
		_engine.broadcaster()->send_control_change(_port_path, *(float*)_data);

	} else if (_error == PORT_NOT_FOUND) {
		string msg = "Unable to find port ";
		msg.append(_port_path).append(" for set_port_value");
		_responder->respond_error(msg);

	} else if (_error == NO_SPACE) {
		std::ostringstream msg("Attempt to write ");
		msg << _data_size << " bytes to " << _port_path << ", with capacity "
			<< _port->buffer_size() << endl;
		_responder->respond_error(msg.str());
	}
}

} // namespace Ingen

<commit_msg>Fix crash on patch loading.<commit_after>/* This file is part of Ingen.
 * Copyright (C) 2007 Dave Robillard <http://drobilla.net>
 *
 * Ingen is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * Ingen is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <sstream>
#include <lv2ext/lv2_event.h>
#include "Responder.hpp"
#include "SetPortValueEvent.hpp"
#include "Engine.hpp"
#include "PortImpl.hpp"
#include "ClientBroadcaster.hpp"
#include "NodeImpl.hpp"
#include "ObjectStore.hpp"
#include "AudioBuffer.hpp"
#include "EventBuffer.hpp"
#include "ProcessContext.hpp"

using namespace std;

namespace Ingen {

/** Omni (all voices) control setting */
SetPortValueEvent::SetPortValueEvent(Engine&              engine,
                                     SharedPtr<Responder> responder,
                                     bool                 queued,
                                     SampleCount          timestamp,
                                     const string&        port_path,
                                     const string&        data_type,
                                     uint32_t             data_size,
                                     const void*          data)
	: QueuedEvent(engine, responder, timestamp)
	, _queued(queued)
	, _omni(true)
	, _voice_num(0)
	, _port_path(port_path)
	, _data_type(data_type)
	, _data_size(data_size)
	, _data(malloc(data_size))
	, _port(NULL)
	, _error(NO_ERROR)
{
	if (!_queued)
		pre_process();

	memcpy(_data, data, data_size);
}

/** Voice-specific control setting */
SetPortValueEvent::SetPortValueEvent(Engine&              engine,
                                     SharedPtr<Responder> responder,
                                     bool                 queued,
                                     SampleCount          timestamp,
                                     uint32_t             voice_num,
                                     const string&        port_path,
                                     const string&        data_type,
                                     uint32_t             data_size,
                                     const void*          data)
	: QueuedEvent(engine, responder, timestamp)
	, _queued(queued)
	, _omni(false)
	, _voice_num(voice_num)
	, _data_type(data_type)
	, _data_size(data_size)
	, _data(malloc(data_size))
	, _port(NULL)
	, _error(NO_ERROR)
{
	if (!_queued)
		pre_process();

	memcpy(_data, data, data_size);
}

SetPortValueEvent::~SetPortValueEvent()
{
	free(_data);
}

void
SetPortValueEvent::pre_process()
{
	if (_queued) {
		if (_port == NULL)
			_port = _engine.object_store()->find_port(_port_path);

		if (_port == NULL)
			_error = PORT_NOT_FOUND;
	}

	QueuedEvent::pre_process();
}

void
SetPortValueEvent::execute(ProcessContext& context)
{
	Event::execute(context);
	assert(_time >= context.start() && _time <= context.end());

	if (_port == NULL)
		_port = _engine.object_store()->find_port(_port_path);

	if (_port == NULL) {
		_error = PORT_NOT_FOUND;
	/*} else if (_port->buffer(0)->capacity() < _data_size) {
		_error = NO_SPACE;*/
	} else {
		Buffer* const buf = _port->buffer(0);
		AudioBuffer* const abuf = dynamic_cast<AudioBuffer*>(buf);
		if (abuf) {
			const uint32_t offset = (buf->size() == 1) ? 0 : _time - context.start();

			if (_omni)
				for (uint32_t i=0; i < _port->poly(); ++i)
					((AudioBuffer*)_port->buffer(i))->set(*(float*)_data, offset);
			else
				((AudioBuffer*)_port->buffer(_voice_num))->set(*(float*)_data, offset);

			return;
		}

		EventBuffer* const ebuf = dynamic_cast<EventBuffer*>(buf);
		// FIXME: eliminate string comparisons
		if (ebuf && _data_type == "lv2_midi:MidiEvent") {
			const LV2Features::Feature* f = _engine.world()->lv2_features->feature(LV2_URI_MAP_URI);
			LV2URIMap* map = (LV2URIMap*)f->controller;
			const uint32_t type_id = map->uri_to_id(NULL, "http://lv2plug.in/ns/ext/midi#MidiEvent");
			const uint32_t frames = std::max((uint32_t)(_time - context.start()), ebuf->latest_frames());
			ebuf->prepare_write(context.nframes());
			// FIXME: how should this work? binary over OSC, ick
			// Message is an event:
			ebuf->append(frames, 0, type_id, _data_size, (const unsigned char*)_data);
			// Message is an event buffer:
			//ebuf->append((LV2_Event_Buffer*)_data);
			_port->raise_set_by_user_flag();
			return;
		}

		cerr << "WARNING: Unknown value type " << _data_type << ", ignoring" << endl;
	}
}

void
SetPortValueEvent::post_process()
{
	if (_error == NO_ERROR) {
		assert(_port != NULL);

		_responder->respond_ok();
		_engine.broadcaster()->send_control_change(_port_path, *(float*)_data);

	} else if (_error == PORT_NOT_FOUND) {
		string msg = "Unable to find port ";
		msg.append(_port_path).append(" for set_port_value");
		_responder->respond_error(msg);

	} else if (_error == NO_SPACE) {
		std::ostringstream msg("Attempt to write ");
		msg << _data_size << " bytes to " << _port_path << ", with capacity "
			<< _port->buffer_size() << endl;
		_responder->respond_error(msg.str());
	}
}

} // namespace Ingen

<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "DrawViewShell.hxx"

#define ITEMID_COLOR            ATTR_ANIMATION_COLOR
#ifndef _XTABLE_HXX
#include <svx/xtable.hxx>
#endif
#include "sdattr.hxx"
#ifndef _AEITEM_HXX //autogen
#include <svtools/aeitem.hxx>
#endif
#ifndef _EEITEM_HXX //autogen
#include <svx/eeitem.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SVDITER_HXX //autogen
#include <svx/svditer.hxx>
#endif
#ifndef _SVX_COLRITEM_HXX //autogen
#include <svx/colritem.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _SVDUNDO_HXX //autogen
#include <svx/svdundo.hxx>
#endif
#ifndef _E3D_VIEW3D_HXX //autogen
#include <svx/view3d.hxx>
#endif

#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif

#ifndef _SVX_FLOAT3D_HXX
#include <svx/float3d.hxx>
#endif
#ifndef _SVX_F3DCHILD_HXX
#include <svx/f3dchild.hxx>
#endif
#ifndef _SVX_DIALOGS_HRC //autogen
#include <svx/dialogs.hrc>
#endif

#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif

#include "app.hrc"
#include "strings.hrc"

#include "drawdoc.hxx"
#include "DrawDocShell.hxx"
#include "anminfo.hxx"
#include "unoaprms.hxx"                 // Undo-Action
#include "sdundogr.hxx"                 // Undo Gruppe
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#include "sdresid.hxx"

using namespace ::com::sun::star;

namespace sd {

#define ATTR_MISSING    0       // Attribut nicht verfuegbar
#define ATTR_MIXED      1       // Attribut uneindeutig (bei Mehrfachselektion)
#define ATTR_SET        2       // Attribut eindeutig

#define ITEMVALUE(ItemSet,Id,Cast)  ((const Cast&)(ItemSet).Get(Id)).GetValue()

/*************************************************************************
|*
|* SfxRequests fuer EffekteWindow bearbeiten
|*
\************************************************************************/

void DrawViewShell::ExecEffectWin( SfxRequest& rReq )
{
    CheckLineTo (rReq);

    USHORT nSId = rReq.GetSlot();

    switch( nSId )
    {
        case SID_3D_INIT:
        {
            USHORT nId = Svx3DChildWindow::GetChildWindowId();
            SfxChildWindow* pWindow = GetViewFrame()->GetChildWindow( nId );
            if( pWindow )
            {
                Svx3DWin* p3DWin = (Svx3DWin*)( pWindow->GetWindow() );
                if( p3DWin )
                    p3DWin->InitColorLB( GetDoc() );
            }
        }
        break;

        case SID_3D_STATE:
        {
            Update3DWindow();
        }
        break;

        case SID_3D_ASSIGN:
        {
            AssignFrom3DWindow();
        }
        break;

    }
}

/*************************************************************************
|*
|* 3D - Assign / Update
|*
\************************************************************************/
void DrawViewShell::Update3DWindow()
{
    USHORT nId = Svx3DChildWindow::GetChildWindowId();
    SfxChildWindow* pWindow = GetViewFrame()->GetChildWindow( nId );
    if( pWindow )
    {
        Svx3DWin* p3DWin = (Svx3DWin*) pWindow->GetWindow();
        if( p3DWin && p3DWin->IsUpdateMode() )
        {
            SfxItemSet aTmpItemSet = GetView()->Get3DAttributes();
            p3DWin->Update( aTmpItemSet );
        }
    }
}

/*----------------------------------------------------------------------------*/

#pragma optimize ( "", off )

void DrawViewShell::AssignFrom3DWindow()
{
    USHORT nId = Svx3DChildWindow::GetChildWindowId();
    SfxChildWindow* pWin = GetViewFrame()->GetChildWindow( nId );
    if( pWin )
    {
        Svx3DWin* p3DWin = (Svx3DWin*) pWin->GetWindow();
        if( p3DWin && GetView() )
        {
            if(!GetView()->IsPresObjSelected())
            {
                SfxItemSet aSet( GetDoc()->GetPool(),
                    SDRATTR_START,  SDRATTR_END,
                    0, 0);
                p3DWin->GetAttr( aSet );

                // Eigene UNDO-Klammerung auch um die Wandlung in 3D
                GetView()->BegUndo(String(SdResId(STR_UNDO_APPLY_3D_FAVOURITE)));

                if(GetView()->IsConvertTo3DObjPossible())
                {
                    // Nur TextAttribute zuweisen
                    SfxItemSet aTextSet( GetDoc()->GetPool(),
                        EE_ITEMS_START, EE_ITEMS_END, 0 );
                    aTextSet.Put( aSet, FALSE );
                    GetView()->SetAttributes( aTextSet );

                    // Text in 3D umwandeln
                    USHORT nSId = SID_CONVERT_TO_3D;
                    SfxBoolItem aItem( nSId, TRUE );
                    GetViewFrame()->GetDispatcher()->Execute(
                        nSId, SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD, &aItem, 0L );

                    // Feststellen, ob ein FILL_Attribut gesetzt ist.
                    // Falls nicht, Fuellattribut hart setzen
                    XFillStyle eFillStyle = ITEMVALUE( aSet, XATTR_FILLSTYLE, XFillStyleItem );
                    if(eFillStyle == XFILL_NONE)
                        aSet.Put(XFillStyleItem (XFILL_SOLID));

                    // remove some 3DSCENE attributes since these were
                    // created by convert to 3D and may not be changed
                    // to the defaults again.
                    aSet.ClearItem(SDRATTR_3DSCENE_DISTANCE);
                    aSet.ClearItem(SDRATTR_3DSCENE_FOCAL_LENGTH);
                    aSet.ClearItem(SDRATTR_3DOBJ_DEPTH);
                }

                // Attribute zuweisen
                GetView()->Set3DAttributes( aSet );

                // Ende UNDO
                GetView()->EndUndo();
            }
            else
            {
                InfoBox aInfoBox (
                    GetActiveWindow(),
                    String(SdResId(STR_ACTION_NOTPOSSIBLE)));
                aInfoBox.Execute();
            }

            // Focus zurueckholen
            GetActiveWindow()->GrabFocus();
        }
    }
}

#pragma optimize ( "", on )

}
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.18.38); FILE MERGED 2006/11/22 15:15:34 cl 1.18.38.2: RESYNC: (1.18-1.19); FILE MERGED 2006/11/22 12:42:28 cl 1.18.38.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: drviewsi.cxx,v $
 *
 *  $Revision: 1.20 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-12 19:17:08 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "DrawViewShell.hxx"

#define ITEMID_COLOR            ATTR_ANIMATION_COLOR
#ifndef _XTABLE_HXX
#include <svx/xtable.hxx>
#endif
#include "sdattr.hxx"
#ifndef _AEITEM_HXX //autogen
#include <svtools/aeitem.hxx>
#endif
#ifndef _EEITEM_HXX //autogen
#include <svx/eeitem.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SVDITER_HXX //autogen
#include <svx/svditer.hxx>
#endif
#ifndef _SVX_COLRITEM_HXX //autogen
#include <svx/colritem.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _SVDUNDO_HXX //autogen
#include <svx/svdundo.hxx>
#endif
#ifndef _E3D_VIEW3D_HXX //autogen
#include <svx/view3d.hxx>
#endif

#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif

#ifndef _SVX_FLOAT3D_HXX
#include <svx/float3d.hxx>
#endif
#ifndef _SVX_F3DCHILD_HXX
#include <svx/f3dchild.hxx>
#endif
#ifndef _SVX_DIALOGS_HRC //autogen
#include <svx/dialogs.hrc>
#endif

#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif

#include "app.hrc"
#include "strings.hrc"

#include "drawdoc.hxx"
#include "DrawDocShell.hxx"
#include "anminfo.hxx"
#include "unoaprms.hxx"                 // Undo-Action
#include "sdundogr.hxx"                 // Undo Gruppe
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#include "sdresid.hxx"

using namespace ::com::sun::star;

namespace sd {

#define ATTR_MISSING    0       // Attribut nicht verfuegbar
#define ATTR_MIXED      1       // Attribut uneindeutig (bei Mehrfachselektion)
#define ATTR_SET        2       // Attribut eindeutig

#define ITEMVALUE(ItemSet,Id,Cast)  ((const Cast&)(ItemSet).Get(Id)).GetValue()

/*************************************************************************
|*
|* SfxRequests fuer EffekteWindow bearbeiten
|*
\************************************************************************/

void DrawViewShell::ExecEffectWin( SfxRequest& rReq )
{
    CheckLineTo (rReq);

    USHORT nSId = rReq.GetSlot();

    switch( nSId )
    {
        case SID_3D_INIT:
        {
            USHORT nId = Svx3DChildWindow::GetChildWindowId();
            SfxChildWindow* pWindow = GetViewFrame()->GetChildWindow( nId );
            if( pWindow )
            {
                Svx3DWin* p3DWin = (Svx3DWin*)( pWindow->GetWindow() );
                if( p3DWin )
                    p3DWin->InitColorLB( GetDoc() );
            }
        }
        break;

        case SID_3D_STATE:
        {
            Update3DWindow();
        }
        break;

        case SID_3D_ASSIGN:
        {
            AssignFrom3DWindow();
        }
        break;

    }
}

/*************************************************************************
|*
|* 3D - Assign / Update
|*
\************************************************************************/
void DrawViewShell::Update3DWindow()
{
    USHORT nId = Svx3DChildWindow::GetChildWindowId();
    SfxChildWindow* pWindow = GetViewFrame()->GetChildWindow( nId );
    if( pWindow )
    {
        Svx3DWin* p3DWin = (Svx3DWin*) pWindow->GetWindow();
        if( p3DWin && p3DWin->IsUpdateMode() )
        {
            SfxItemSet aTmpItemSet = GetView()->Get3DAttributes();
            p3DWin->Update( aTmpItemSet );
        }
    }
}

/*----------------------------------------------------------------------------*/

void DrawViewShell::AssignFrom3DWindow()
{
    USHORT nId = Svx3DChildWindow::GetChildWindowId();
    SfxChildWindow* pWin = GetViewFrame()->GetChildWindow( nId );
    if( pWin )
    {
        Svx3DWin* p3DWin = (Svx3DWin*) pWin->GetWindow();
        if( p3DWin && GetView() )
        {
            if(!GetView()->IsPresObjSelected())
            {
                SfxItemSet aSet( GetDoc()->GetPool(),
                    SDRATTR_START,  SDRATTR_END,
                    0, 0);
                p3DWin->GetAttr( aSet );

                // Eigene UNDO-Klammerung auch um die Wandlung in 3D
                GetView()->BegUndo(String(SdResId(STR_UNDO_APPLY_3D_FAVOURITE)));

                if(GetView()->IsConvertTo3DObjPossible())
                {
                    // Nur TextAttribute zuweisen
                    SfxItemSet aTextSet( GetDoc()->GetPool(),
                        EE_ITEMS_START, EE_ITEMS_END, 0 );
                    aTextSet.Put( aSet, FALSE );
                    GetView()->SetAttributes( aTextSet );

                    // Text in 3D umwandeln
                    USHORT nSId = SID_CONVERT_TO_3D;
                    SfxBoolItem aItem( nSId, TRUE );
                    GetViewFrame()->GetDispatcher()->Execute(
                        nSId, SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD, &aItem, 0L );

                    // Feststellen, ob ein FILL_Attribut gesetzt ist.
                    // Falls nicht, Fuellattribut hart setzen
                    XFillStyle eFillStyle = ITEMVALUE( aSet, XATTR_FILLSTYLE, XFillStyleItem );
                    if(eFillStyle == XFILL_NONE)
                        aSet.Put(XFillStyleItem (XFILL_SOLID));

                    // remove some 3DSCENE attributes since these were
                    // created by convert to 3D and may not be changed
                    // to the defaults again.
                    aSet.ClearItem(SDRATTR_3DSCENE_DISTANCE);
                    aSet.ClearItem(SDRATTR_3DSCENE_FOCAL_LENGTH);
                    aSet.ClearItem(SDRATTR_3DOBJ_DEPTH);
                }

                // Attribute zuweisen
                GetView()->Set3DAttributes( aSet );

                // Ende UNDO
                GetView()->EndUndo();
            }
            else
            {
                InfoBox aInfoBox (
                    GetActiveWindow(),
                    String(SdResId(STR_ACTION_NOTPOSSIBLE)));
                aInfoBox.Execute();
            }

            // Focus zurueckholen
            GetActiveWindow()->GrabFocus();
        }
    }
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: tabcontr.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: bm $ $Date: 2002-11-04 17:42:55 $
 *
 *  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 _SVDLAYER_HXX
#include <svx/svdlayer.hxx>
#endif
#ifndef _SVDPAGV_HXX //autogen
#include <svx/svdpagv.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif

#pragma hdrstop

#include "sdattr.hxx"
#include "app.hxx"
#include "tabcontr.hxx"
#include "app.hrc"
#include "glob.hrc"
#include "res_bmp.hrc"
#include "drviewsh.hxx"
#include "grviewsh.hxx"
#include "helpids.h"
#include "sdview.hxx"
#include "sdpage.hxx"
#include "drawdoc.hxx"
#include "sdwindow.hxx"
#include "unmodpg.hxx"
#include "docshell.hxx"
#include "sdresid.hxx"

#define SWITCH_TIMEOUT  20

// -----------------------------------------
// - SdTabControl::SdPageObjsTransferable -
// -----------------------------------------

SdTabControl::SdTabControlTransferable::~SdTabControlTransferable()
{
}

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

void SdTabControl::SdTabControlTransferable::AddSupportedFormats()
{
    AddFormat( SOT_FORMATSTR_ID_STARDRAW_TABBAR );
}

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

sal_Bool SdTabControl::SdTabControlTransferable::GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor )
{
    return sal_False;
}

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

void SdTabControl::SdTabControlTransferable::DragFinished( sal_Int8 nDropAction )
{
    mrParent.DragFinished( nDropAction );
}

/*************************************************************************
|*
|* Standard-Konstruktor
|*
\************************************************************************/

SdTabControl::SdTabControl(SdDrawViewShell* pViewSh, Window* pParent) :
    TabBar( pParent, WinBits( WB_BORDER | WB_3DLOOK | WB_SCROLL | WB_SIZEABLE | WB_DRAG) ),
    DragSourceHelper( this ),
    DropTargetHelper( this ),
    pDrViewSh(pViewSh),
    bInternalMove(FALSE)
{
    EnableEditMode();
    SetSizePixel(Size(0, 0));
    SetMaxPageWidth( 150 );
    SetHelpId( HID_SD_TABBAR_PAGES );
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

SdTabControl::~SdTabControl()
{
}

/*************************************************************************
|*
\************************************************************************/

void SdTabControl::Select()
{
    SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
    pDispatcher->Execute(SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON |
                            SFX_CALLMODE_RECORD);
}

/*************************************************************************
|*
\************************************************************************/

void  SdTabControl::MouseButtonDown(const MouseEvent& rMEvt)
{
    // eine saubere linke Maustaste ohne verwaessernde Modifier (damit koennte
    //ja das Kontextmenue gemeint sein)
    if ( rMEvt.IsLeft() && !rMEvt.IsMod1() && !rMEvt.IsMod2() && !rMEvt.IsShift())
    {
        Point aPos = PixelToLogic( rMEvt.GetPosPixel() );
        USHORT aPageId = GetPageId(aPos);

        if (aPageId == 0)
        {
            SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();

            pDispatcher->Execute(SID_INSERTPAGE_QUICK,
                                SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD);
        }
    }

    // A single left click with pressed control key on a tab page first
    // switches to that page before the usual handling (copying with drag
    // and drop) takes place.
    else if (rMEvt.IsLeft() && rMEvt.IsMod1() && !rMEvt.IsMod2() && !rMEvt.IsShift())
    {
        pDrViewSh->SwitchPage (GetPageId (rMEvt.GetPosPixel()) - 1);
    }

    TabBar::MouseButtonDown(rMEvt);
}

/*************************************************************************
|*
\************************************************************************/

void SdTabControl::DoubleClick()
{
    if (GetCurPageId() != 0)
    {
        SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
        pDispatcher->Execute( SID_MODIFYPAGE,
                        SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD );
    }
}

/*************************************************************************
|*
|* StartDrag-Request
|*
\************************************************************************/

void SdTabControl::StartDrag( sal_Int8 nAction, const Point& rPosPixel )
{
    bInternalMove = TRUE;

    // object is delete by reference mechanismn
    ( new SdTabControl::SdTabControlTransferable( *this ) )->StartDrag( this, DND_ACTION_COPYMOVE );
}

/*************************************************************************
|*
|* DragFinished
|*
\************************************************************************/

void SdTabControl::DragFinished( sal_Int8 nDropAction )
{
    bInternalMove = FALSE;
}

/*************************************************************************
|*
|* AcceptDrop-Event
|*
\************************************************************************/

sal_Int8 SdTabControl::AcceptDrop( const AcceptDropEvent& rEvt )
{
    sal_Int8 nRet = DND_ACTION_NONE;

    if( rEvt.mbLeaving )
        EndSwitchPage();

    if( !pDrViewSh->GetDocSh()->IsReadOnly() )
    {
        SdDrawDocument* pDoc = pDrViewSh->GetDoc();
        Point           aPos( rEvt.maPosPixel );

        if( bInternalMove )
        {
            if( rEvt.mbLeaving || ( pDrViewSh->GetEditMode() == EM_MASTERPAGE ) )
                HideDropPos();
            else
            {
                ShowDropPos( aPos );
                nRet = rEvt.mnAction;
            }
        }
        else
        {
            HideDropPos();

            USHORT nPageId = GetPageId( aPos ) - 1;

            if( ( nPageId >= 0 ) && pDoc->GetPage( nPageId ) )
            {
                SdWindow* pWindow = NULL;

                nRet = pDrViewSh->AcceptDrop( rEvt, *this, NULL, nPageId, SDRLAYER_NOTFOUND );
                SwitchPage( aPos );
            }
        }
    }

    return nRet;
}

/*************************************************************************
|*
|* ExecuteDrop-Event
|*
\************************************************************************/

sal_Int8 SdTabControl::ExecuteDrop( const ExecuteDropEvent& rEvt )
{
    SdDrawDocument* pDoc = pDrViewSh->GetDoc();
    Point           aPos( rEvt.maPosPixel );
    sal_Int8        nRet = DND_ACTION_NONE;

    if( bInternalMove )
    {
        USHORT nPageId = ShowDropPos( aPos ) - 1;

        switch (rEvt.mnAction)
        {
            case DND_ACTION_MOVE:
                if( pDrViewSh->IsSwitchPageAllowed() && pDoc->MovePages( nPageId ) )
                {
                    SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
                    pDispatcher->Execute(SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
                }
                break;

            case DND_ACTION_COPY:
            {
                // Copying the selected page to the place that rEvt points
                // takes place in three steps:
                // 1. Create a copy of the selected page.  This copy will
                // lie directly behind the selected page.
                // 2. Move the copy to the desired place.
                // 3. Select the copy.
                if (pDrViewSh->IsSwitchPageAllowed())
                {
                    // 1. Create a copy.
                    USHORT nPageNumOfCopy = pDoc->DuplicatePage (GetCurPageId() - 1);
                    // 2. Move page.  For this first switch to the copy:
                    // MovePages operates on the currently selected page(s).
                    pDrViewSh->SwitchPage (nPageNumOfCopy);
                    // Adapt target page id when necessary, i.e. page copy
                    // has been inserted in front of the target page.
                    USHORT nPageNum = nPageId;
                    if ((nPageNumOfCopy <= nPageNum) && (nPageNum != (USHORT)-1))
                        nPageNum += 1;
                    if (pDoc->MovePages(nPageNum))
                    {
                        // 3. Switch to the copy that has been moved to its
                        // final destination.  Use an asynchron slot call to
                        // be executed after the still pending ones.
                        if (nPageNumOfCopy >= nPageNum || (nPageNum == (USHORT)-1))
                            nPageNum += 1;
                        SetCurPageId (GetPageId(nPageNum));
                        SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
                        pDispatcher->Execute(SID_SWITCHPAGE,
                            SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
                    }
                }

                break;
            }
        }

        nRet = rEvt.mnAction;
    }
    else
    {
        USHORT nPageId = GetPageId( aPos ) - 1;

        if( ( nPageId >= 0 ) && pDoc->GetPage( nPageId ) )
        {
            nRet = pDrViewSh->ExecuteDrop( rEvt, *this, NULL, nPageId, SDRLAYER_NOTFOUND );
        }
    }

    HideDropPos();
    EndSwitchPage();

    return nRet;
}

/*************************************************************************
|*
\************************************************************************/

void SdTabControl::Command(const CommandEvent& rCEvt)
{
    USHORT nCmd = rCEvt.GetCommand();

    if ( nCmd == COMMAND_CONTEXTMENU )
    {
        BOOL bGraphicShell = pDrViewSh->ISA( SdGraphicViewShell );
        USHORT nResId = bGraphicShell ? RID_GRAPHIC_PAGETAB_POPUP :
                                        RID_DRAW_PAGETAB_POPUP;
        SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
        pDispatcher->ExecutePopup( SdResId( nResId ) );
    }
}

/*************************************************************************
|*
\************************************************************************/

long SdTabControl::StartRenaming()
{
    BOOL bOK = FALSE;

    if (pDrViewSh->GetPageKind() == PK_STANDARD)
    {
        bOK = TRUE;

        SdView* pView = pDrViewSh->GetView();

        if ( pView->IsTextEdit() )
            pView->EndTextEdit();
    }

    return( bOK );
}

/*************************************************************************
|*
\************************************************************************/

long SdTabControl::AllowRenaming()
{
    BOOL bOK = TRUE;

    String aNewName( GetEditText() );
    String aCompareName( GetPageText( GetEditPageId() ) );

    if( aCompareName != aNewName )
    {
        // Seite umbenennen
        if( pDrViewSh->GetDocSh()->CheckPageName( this, aNewName ) )
        {
            SetEditText( aNewName );
            EndRenaming();
        }
        else
        {
            bOK = FALSE;
        }
    }
    return( bOK );
}

/*************************************************************************
|*
\************************************************************************/

void SdTabControl::EndRenaming()
{
    if( !IsEditModeCanceled() )
        pDrViewSh->RenameSlide( GetEditPageId(), GetEditText() );
}

/*************************************************************************
|*
\************************************************************************/

void SdTabControl::ActivatePage()
{
    if ( /*IsInSwitching && */ pDrViewSh->IsSwitchPageAllowed() )
    {
        SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
        pDispatcher->Execute(SID_SWITCHPAGE,
                             SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
    }
}

/*************************************************************************
|*
\************************************************************************/

long SdTabControl::DeactivatePage()
{
    return pDrViewSh->IsSwitchPageAllowed();
}

void SdTabControl::SendActivatePageEvent (void)
{
    CallEventListeners (VCLEVENT_TABBAR_PAGEACTIVATED,
        reinterpret_cast<void*>(GetCurPageId()));
}

void SdTabControl::SendDeactivatePageEvent (void)
{
    CallEventListeners (VCLEVENT_TABBAR_PAGEDEACTIVATED,
        reinterpret_cast<void*>(GetCurPageId()));
}
<commit_msg>INTEGRATION: CWS impress1 (1.12.218); FILE MERGED 2003/09/17 08:22:35 af 1.12.218.1: #111996# Transition to stacked sub-shells. Introduction of namespace sd.<commit_after>/*************************************************************************
 *
 *  $RCSfile: tabcontr.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: obo $ $Date: 2004-01-20 12:56:06 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include "TabControl.hxx"

#ifndef _SVDLAYER_HXX
#include <svx/svdlayer.hxx>
#endif
#ifndef _SVDPAGV_HXX //autogen
#include <svx/svdpagv.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif

#pragma hdrstop

#include "sdattr.hxx"
#include "app.hxx"
#include "app.hrc"
#include "glob.hrc"
#include "res_bmp.hrc"
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_GRAPHIC_VIEW_SHELL_HXX
#include "GraphicViewShell.hxx"
#endif
#include "helpids.h"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#include "sdpage.hxx"
#include "drawdoc.hxx"
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#include "unmodpg.hxx"
#include "DrawDocShell.hxx"
#include "sdresid.hxx"

namespace sd {

#define SWITCH_TIMEOUT  20

// -----------------------------------------
// - SdTabControl::SdPageObjsTransferable -
// -----------------------------------------

TabControl::TabControlTransferable::~TabControlTransferable()
{
}

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

void TabControl::TabControlTransferable::AddSupportedFormats()
{
    AddFormat( SOT_FORMATSTR_ID_STARDRAW_TABBAR );
}

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

sal_Bool TabControl::TabControlTransferable::GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor )
{
    return sal_False;
}

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

void TabControl::TabControlTransferable::DragFinished( sal_Int8 nDropAction )
{
    mrParent.DragFinished( nDropAction );
}

/*************************************************************************
|*
|* Standard-Konstruktor
|*
\************************************************************************/

TabControl::TabControl(DrawViewShell* pViewSh, Window* pParent) :
    TabBar( pParent, WinBits( WB_BORDER | WB_3DLOOK | WB_SCROLL | WB_SIZEABLE | WB_DRAG) ),
    DragSourceHelper( this ),
    DropTargetHelper( this ),
    pDrViewSh(pViewSh),
    bInternalMove(FALSE)
{
    EnableEditMode();
    SetSizePixel(Size(0, 0));
    SetMaxPageWidth( 150 );
    SetHelpId( HID_SD_TABBAR_PAGES );
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

TabControl::~TabControl()
{
}

/*************************************************************************
|*
\************************************************************************/

void TabControl::Select()
{
    SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
    pDispatcher->Execute(SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON |
                            SFX_CALLMODE_RECORD);
}

/*************************************************************************
|*
\************************************************************************/

void  TabControl::MouseButtonDown(const MouseEvent& rMEvt)
{
    // eine saubere linke Maustaste ohne verwaessernde Modifier (damit koennte
    //ja das Kontextmenue gemeint sein)
    if ( rMEvt.IsLeft() && !rMEvt.IsMod1() && !rMEvt.IsMod2() && !rMEvt.IsShift())
    {
        Point aPos = PixelToLogic( rMEvt.GetPosPixel() );
        USHORT aPageId = GetPageId(aPos);

        if (aPageId == 0)
        {
            SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();

            pDispatcher->Execute(SID_INSERTPAGE_QUICK,
                                SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD);
        }
    }

    // A single left click with pressed control key on a tab page first
    // switches to that page before the usual handling (copying with drag
    // and drop) takes place.
    else if (rMEvt.IsLeft() && rMEvt.IsMod1() && !rMEvt.IsMod2() && !rMEvt.IsShift())
    {
        pDrViewSh->SwitchPage (GetPageId (rMEvt.GetPosPixel()) - 1);
    }

    TabBar::MouseButtonDown(rMEvt);
}

/*************************************************************************
|*
\************************************************************************/

void TabControl::DoubleClick()
{
    if (GetCurPageId() != 0)
    {
        SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
        pDispatcher->Execute( SID_MODIFYPAGE,
                        SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD );
    }
}

/*************************************************************************
|*
|* StartDrag-Request
|*
\************************************************************************/

void TabControl::StartDrag( sal_Int8 nAction, const Point& rPosPixel )
{
    bInternalMove = TRUE;

    // object is delete by reference mechanismn
    ( new TabControl::TabControlTransferable( *this ) )->StartDrag( this, DND_ACTION_COPYMOVE );
}

/*************************************************************************
|*
|* DragFinished
|*
\************************************************************************/

void TabControl::DragFinished( sal_Int8 nDropAction )
{
    bInternalMove = FALSE;
}

/*************************************************************************
|*
|* AcceptDrop-Event
|*
\************************************************************************/

sal_Int8 TabControl::AcceptDrop( const AcceptDropEvent& rEvt )
{
    sal_Int8 nRet = DND_ACTION_NONE;

    if( rEvt.mbLeaving )
        EndSwitchPage();

    if( !pDrViewSh->GetDocSh()->IsReadOnly() )
    {
        SdDrawDocument* pDoc = pDrViewSh->GetDoc();
        Point           aPos( rEvt.maPosPixel );

        if( bInternalMove )
        {
            if( rEvt.mbLeaving || ( pDrViewSh->GetEditMode() == EM_MASTERPAGE ) )
                HideDropPos();
            else
            {
                ShowDropPos( aPos );
                nRet = rEvt.mnAction;
            }
        }
        else
        {
            HideDropPos();

            USHORT nPageId = GetPageId( aPos ) - 1;

            if( ( nPageId >= 0 ) && pDoc->GetPage( nPageId ) )
            {
                ::sd::Window* pWindow = NULL;

                nRet = pDrViewSh->AcceptDrop( rEvt, *this, NULL, nPageId, SDRLAYER_NOTFOUND );
                SwitchPage( aPos );
            }
        }
    }

    return nRet;
}

/*************************************************************************
|*
|* ExecuteDrop-Event
|*
\************************************************************************/

sal_Int8 TabControl::ExecuteDrop( const ExecuteDropEvent& rEvt )
{
    SdDrawDocument* pDoc = pDrViewSh->GetDoc();
    Point           aPos( rEvt.maPosPixel );
    sal_Int8        nRet = DND_ACTION_NONE;

    if( bInternalMove )
    {
        USHORT nPageId = ShowDropPos( aPos ) - 1;

        switch (rEvt.mnAction)
        {
            case DND_ACTION_MOVE:
                if( pDrViewSh->IsSwitchPageAllowed() && pDoc->MovePages( nPageId ) )
                {
                    SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
                    pDispatcher->Execute(SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
                }
                break;

            case DND_ACTION_COPY:
            {
                // Copying the selected page to the place that rEvt points
                // takes place in three steps:
                // 1. Create a copy of the selected page.  This copy will
                // lie directly behind the selected page.
                // 2. Move the copy to the desired place.
                // 3. Select the copy.
                if (pDrViewSh->IsSwitchPageAllowed())
                {
                    // 1. Create a copy.
                    USHORT nPageNumOfCopy = pDoc->DuplicatePage (GetCurPageId() - 1);
                    // 2. Move page.  For this first switch to the copy:
                    // MovePages operates on the currently selected page(s).
                    pDrViewSh->SwitchPage (nPageNumOfCopy);
                    // Adapt target page id when necessary, i.e. page copy
                    // has been inserted in front of the target page.
                    USHORT nPageNum = nPageId;
                    if ((nPageNumOfCopy <= nPageNum) && (nPageNum != (USHORT)-1))
                        nPageNum += 1;
                    if (pDoc->MovePages(nPageNum))
                    {
                        // 3. Switch to the copy that has been moved to its
                        // final destination.  Use an asynchron slot call to
                        // be executed after the still pending ones.
                        if (nPageNumOfCopy >= nPageNum || (nPageNum == (USHORT)-1))
                            nPageNum += 1;
                        SetCurPageId (GetPageId(nPageNum));
                        SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
                        pDispatcher->Execute(SID_SWITCHPAGE,
                            SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
                    }
                }

                break;
            }
        }

        nRet = rEvt.mnAction;
    }
    else
    {
        USHORT nPageId = GetPageId( aPos ) - 1;

        if( ( nPageId >= 0 ) && pDoc->GetPage( nPageId ) )
        {
            nRet = pDrViewSh->ExecuteDrop( rEvt, *this, NULL, nPageId, SDRLAYER_NOTFOUND );
        }
    }

    HideDropPos();
    EndSwitchPage();

    return nRet;
}

/*************************************************************************
|*
\************************************************************************/

void TabControl::Command(const CommandEvent& rCEvt)
{
    USHORT nCmd = rCEvt.GetCommand();

    if ( nCmd == COMMAND_CONTEXTMENU )
    {
        BOOL bGraphicShell = pDrViewSh->ISA(GraphicViewShell);
        USHORT nResId = bGraphicShell ? RID_GRAPHIC_PAGETAB_POPUP :
                                        RID_DRAW_PAGETAB_POPUP;
        SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
        pDispatcher->ExecutePopup( SdResId( nResId ) );
    }
}

/*************************************************************************
|*
\************************************************************************/

long TabControl::StartRenaming()
{
    BOOL bOK = FALSE;

    if (pDrViewSh->GetPageKind() == PK_STANDARD)
    {
        bOK = TRUE;

        ::sd::View* pView = pDrViewSh->GetView();

        if ( pView->IsTextEdit() )
            pView->EndTextEdit();
    }

    return( bOK );
}

/*************************************************************************
|*
\************************************************************************/

long TabControl::AllowRenaming()
{
    BOOL bOK = TRUE;

    String aNewName( GetEditText() );
    String aCompareName( GetPageText( GetEditPageId() ) );

    if( aCompareName != aNewName )
    {
        // Seite umbenennen
        if( pDrViewSh->GetDocSh()->CheckPageName( this, aNewName ) )
        {
            SetEditText( aNewName );
            EndRenaming();
        }
        else
        {
            bOK = FALSE;
        }
    }
    return( bOK );
}

/*************************************************************************
|*
\************************************************************************/

void TabControl::EndRenaming()
{
    if( !IsEditModeCanceled() )
        pDrViewSh->RenameSlide( GetEditPageId(), GetEditText() );
}

/*************************************************************************
|*
\************************************************************************/

void TabControl::ActivatePage()
{
    if ( /*IsInSwitching && */ pDrViewSh->IsSwitchPageAllowed() )
    {
        SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher();
        pDispatcher->Execute(SID_SWITCHPAGE,
                             SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD);
    }
}

/*************************************************************************
|*
\************************************************************************/

long TabControl::DeactivatePage()
{
    return pDrViewSh->IsSwitchPageAllowed();
}

void TabControl::SendActivatePageEvent (void)
{
    CallEventListeners (VCLEVENT_TABBAR_PAGEACTIVATED,
        reinterpret_cast<void*>(GetCurPageId()));
}

void TabControl::SendDeactivatePageEvent (void)
{
    CallEventListeners (VCLEVENT_TABBAR_PAGEDEACTIVATED,
        reinterpret_cast<void*>(GetCurPageId()));
}

} // end of namespace sd
<|endoftext|>


<commit_before>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2013, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */

/** @file
    Random Number Generator interface
*/

#include <nta/types/Types.hpp>
#include <cstdlib>
#include <string>
#include <vector>

#ifndef NTA_RANDOM_HPP
#define NTA_RANDOM_HPP

typedef NTA_UInt64 (*RandomSeedFuncPtr)();

namespace nta {
  /**
   * @b Responsibility
   * Provides standardized random number generation for the NuPIC Runtime Engine.
   * Seed can be logged in one run and then set in another.
   * @b Rationale
   * Makes it possible to reproduce tests that are driven by random number generation.
   *
   * @b Description
   * Functionality is similar to the standard random() function that is provided by C.
   *
   * Each Random object is a random number generator. There are three ways of
   * creating one:
   * 1) explicit seed
   *       Random rng(seed);
   * 2) self-seeded
   *       Random rng;
   * 3) named generator -- normally self-seeded, but seed may be
   *    set explicitly through an environment variable
   *       Random rng("level2TP");
   *    If NTA_RANDOM_DEBUG is set, this object will log its self-seed
   *    The seed can be explicitly set through NTA_RANDOM_SEED_level2TP
   *
   * Good self-seeds are generated by an internal global random number generator.
   * This global rng is seeded from the current time, but its seed may be
   * overridden with NTA_RANDOM_SEED
   *
   * Automated tests that use random numbers should normally use named generators.
   * This allows them to get a different seed each time, but also allows reproducibility
   * in the case that a test failure is triggered by a particular seed.
   *
   * Random should not be used if cryptographic strength is required (e.g. for
   * generating a challenge in an authentication scheme).
   *
   * @todo Add ability to specify different rng algorithms.
   */
  class RandomImpl;

  class Random
  {
  public:
    /**
     * Retrieve the seeder. If seeder not set, allocates the
     * singleton and and initializes the seeder.
     */
    static RandomSeedFuncPtr getSeeder();

    Random(UInt64 seed = 0);

    // support copy constructor and operator= -- these require non-default
    // implementations because of the impl_ pointer.
    // They do a deep copy of impl_ so that an RNG and its copy generate the
    // same set of numbers.
    Random(const Random&);
    Random& operator=(const Random&);
    ~Random();

    // return a value uniformly distributed between 0 and max-1
    UInt32 getUInt32(UInt32 max = MAX32);
    UInt64 getUInt64(UInt64 max = MAX64);
    // return a double uniformly distributed on 0...1.0
    Real64 getReal64();

    // for STL compatibility
    UInt32 operator()(UInt32 n = MAX32) { return getUInt32(n); }

    // normally used for debugging only
    UInt64 getSeed() {return seed_;}

    // for STL
    typedef UInt32 argument_type;
    typedef UInt32 result_type;
    result_type max() { return MAX32; }
    result_type min() { return 0; }

    static const UInt32 MAX32;
    static const UInt64 MAX64;

    // called by the plugin framework so that plugins
    // get the "global" seeder
    static void initSeeder(const RandomSeedFuncPtr r);

    static void shutdown();

  protected:

    // each "universe" (application/plugin/python module) has its own instance,
    // but the instance should be NULL in all but one
    static Random *theInstanceP_;
    // seeder_ is a function called by the constructor to get new random seeds
    // If not set when we call Random constructor, then the singleton is allocated
    // and seeder_ is set to a function that uses our singleton
    // initFromPlatformServices can also be used to initialize the seeder_
    static RandomSeedFuncPtr seeder_;

    void reseed(UInt64 seed);

    RandomImpl *impl_;
    UInt64 seed_;

    friend class RandomTest;
    friend std::ostream& operator<<(std::ostream&, const Random&);
    friend std::istream& operator>>(std::istream&, Random&);
    friend NTA_UInt64 GetRandomSeed();

  };

  // serialization/deserialization
  std::ostream& operator<<(std::ostream&, const Random&);
  std::istream& operator>>(std::istream&, Random&);

  // This function returns seeds from the Random singleton in our
  // "universe" (application, plugin, python module). If, when the
  // Random constructor is called, seeder_ is NULL, then seeder_ is
  // set to this function. The plugin framework can override this
  // behavior by explicitly setting the seeder to the RandomSeeder
  // function provided by the application.
  NTA_UInt64 GetRandomSeed();

} // namespace nta

#endif // NTA_RANDOM_HPP

<commit_msg>Undef min and max for MSVC<commit_after>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2013, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */

/** @file
    Random Number Generator interface
*/

#include <nta/types/Types.hpp>
#include <cstdlib>
#include <string>
#include <vector>

#ifndef NTA_RANDOM_HPP
#define NTA_RANDOM_HPP

#if defined(NTA_COMPILER_MSVC)
    // max and min are macros for MSVC, will confuse Random::max() and Random::min()
    #undef min
    #undef max
#endif

typedef NTA_UInt64 (*RandomSeedFuncPtr)();

namespace nta {
  /**
   * @b Responsibility
   * Provides standardized random number generation for the NuPIC Runtime Engine.
   * Seed can be logged in one run and then set in another.
   * @b Rationale
   * Makes it possible to reproduce tests that are driven by random number generation.
   *
   * @b Description
   * Functionality is similar to the standard random() function that is provided by C.
   *
   * Each Random object is a random number generator. There are three ways of
   * creating one:
   * 1) explicit seed
   *       Random rng(seed);
   * 2) self-seeded
   *       Random rng;
   * 3) named generator -- normally self-seeded, but seed may be
   *    set explicitly through an environment variable
   *       Random rng("level2TP");
   *    If NTA_RANDOM_DEBUG is set, this object will log its self-seed
   *    The seed can be explicitly set through NTA_RANDOM_SEED_level2TP
   *
   * Good self-seeds are generated by an internal global random number generator.
   * This global rng is seeded from the current time, but its seed may be
   * overridden with NTA_RANDOM_SEED
   *
   * Automated tests that use random numbers should normally use named generators.
   * This allows them to get a different seed each time, but also allows reproducibility
   * in the case that a test failure is triggered by a particular seed.
   *
   * Random should not be used if cryptographic strength is required (e.g. for
   * generating a challenge in an authentication scheme).
   *
   * @todo Add ability to specify different rng algorithms.
   */
  class RandomImpl;

  class Random
  {
  public:
    /**
     * Retrieve the seeder. If seeder not set, allocates the
     * singleton and and initializes the seeder.
     */
    static RandomSeedFuncPtr getSeeder();

    Random(UInt64 seed = 0);

    // support copy constructor and operator= -- these require non-default
    // implementations because of the impl_ pointer.
    // They do a deep copy of impl_ so that an RNG and its copy generate the
    // same set of numbers.
    Random(const Random&);
    Random& operator=(const Random&);
    ~Random();

    // return a value uniformly distributed between 0 and max-1
    UInt32 getUInt32(UInt32 max = MAX32);
    UInt64 getUInt64(UInt64 max = MAX64);
    // return a double uniformly distributed on 0...1.0
    Real64 getReal64();

    // for STL compatibility
    UInt32 operator()(UInt32 n = MAX32) { return getUInt32(n); }

    // normally used for debugging only
    UInt64 getSeed() {return seed_;}

    // for STL
    typedef UInt32 argument_type;
    typedef UInt32 result_type;

    result_type max() { return MAX32; }
    result_type min() { return 0; }

    static const UInt32 MAX32;
    static const UInt64 MAX64;

    // called by the plugin framework so that plugins
    // get the "global" seeder
    static void initSeeder(const RandomSeedFuncPtr r);

    static void shutdown();

  protected:

    // each "universe" (application/plugin/python module) has its own instance,
    // but the instance should be NULL in all but one
    static Random *theInstanceP_;
    // seeder_ is a function called by the constructor to get new random seeds
    // If not set when we call Random constructor, then the singleton is allocated
    // and seeder_ is set to a function that uses our singleton
    // initFromPlatformServices can also be used to initialize the seeder_
    static RandomSeedFuncPtr seeder_;

    void reseed(UInt64 seed);

    RandomImpl *impl_;
    UInt64 seed_;

    friend class RandomTest;
    friend std::ostream& operator<<(std::ostream&, const Random&);
    friend std::istream& operator>>(std::istream&, Random&);
    friend NTA_UInt64 GetRandomSeed();

  };

  // serialization/deserialization
  std::ostream& operator<<(std::ostream&, const Random&);
  std::istream& operator>>(std::istream&, Random&);

  // This function returns seeds from the Random singleton in our
  // "universe" (application, plugin, python module). If, when the
  // Random constructor is called, seeder_ is NULL, then seeder_ is
  // set to this function. The plugin framework can override this
  // behavior by explicitly setting the seeder to the RandomSeeder
  // function provided by the application.
  NTA_UInt64 GetRandomSeed();

} // namespace nta

#endif // NTA_RANDOM_HPP

<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#include "XalanDefaultParsedSource.hpp"

#include <XalanDOM/XalanDocument.hpp>

#include <PlatformSupport/URISupport.hpp>

#include <XalanSourceTree/XalanSourceTreeDocument.hpp>
#include <XalanSourceTree/XalanSourceTreeDOMSupport.hpp>

XalanDefaultParsedSourceDOMSupport::XalanDefaultParsedSourceDOMSupport(const XalanSourceTreeDOMSupport&		theDOMSupport) :
	XalanSourceTreeDOMSupport(),
	m_domSupport(theDOMSupport)
{
}

XalanDefaultParsedSourceDOMSupport::~XalanDefaultParsedSourceDOMSupport()
{
}

void
XalanDefaultParsedSourceDOMSupport::reset()
{
}

const XalanDOMString*
XalanDefaultParsedSourceDOMSupport::getNamespaceForPrefix(
			const XalanDOMString&	prefix,
			const XalanElement&		namespaceContext) const
{
	return m_domSupport.getNamespaceForPrefix(
					prefix,
					namespaceContext);
}

const XalanDOMString&
XalanDefaultParsedSourceDOMSupport::getUnparsedEntityURI(
			const XalanDOMString&	theName,
			const XalanDocument&	theDocument) const
{
	const XalanDOMString&	theURI =
			m_domSupport.getUnparsedEntityURI(
					theName,
					theDocument);

	if (length(theURI) != 0)
	{
		return theURI;
	}
	else
	{
		return XalanSourceTreeDOMSupport::getUnparsedEntityURI(
					theName,
					theDocument);
	}
}

bool
XalanDefaultParsedSourceDOMSupport::isNodeAfter(
			const XalanNode&	node1,
			const XalanNode&	node2) const
{
	return m_domSupport.isNodeAfter(
					node1,
					node2);
}

XalanDefaultParsedSourceHelper::XalanDefaultParsedSourceHelper(
			const XalanSourceTreeDOMSupport&		theSourceDOMSupport,
			const XalanSourceTreeParserLiaison&		theSourceParserLiaison) :
	m_domSupport(theSourceDOMSupport),
	m_parserLiaison(theSourceParserLiaison.getDocumentNumber())
{
	m_domSupport.setParserLiaison(&m_parserLiaison);
}

DOMSupport&
XalanDefaultParsedSourceHelper::getDOMSupport()
{
	return m_domSupport;
}

XMLParserLiaison&
XalanDefaultParsedSourceHelper::getParserLiaison()
{
	return m_parserLiaison;
}

XalanDefaultParsedSource::XalanDefaultParsedSource(
			const XSLTInputSource&	theInputSource,
			bool					fValidate,
			ErrorHandler*			theErrorHandler,
			EntityResolver*			theEntityResolver) :
	XalanParsedSource(),
	m_domSupport(),
	m_parserLiaison(m_domSupport),
	m_parsedSource(0)
{
	m_parserLiaison.setUseValidation(fValidate);
	m_parserLiaison.setEntityResolver(theEntityResolver);
	m_parserLiaison.setErrorHandler(theErrorHandler);

	m_parsedSource = m_parserLiaison.mapDocument(m_parserLiaison.parseXMLStream(theInputSource));
	assert(m_parsedSource != 0);

	m_domSupport.setParserLiaison(&m_parserLiaison);

	const XalanDOMChar* const	theSystemID = theInputSource.getSystemId();

	if (theSystemID != 0)
	{
		try
		{
			m_uri = URISupport::getURLStringFromString(theSystemID);
		}
		catch(const XMLException&)
		{
			// Assume that any exception here relates to get the url from
			// the system ID.  We'll assume that it's just a fake base identifier
			// since the parser would have thrown an error if the system ID
			// wasn't resolved.
			m_uri = theSystemID;
		}
	}
}

XalanDefaultParsedSource::~XalanDefaultParsedSource()
{
}

XalanDocument*
XalanDefaultParsedSource::getDocument() const
{
	return m_parsedSource;
}

XalanParsedSourceHelper*
XalanDefaultParsedSource::createHelper() const
{
	return new XalanDefaultParsedSourceHelper(m_domSupport, m_parserLiaison);
}

const XalanDOMString&
XalanDefaultParsedSource::getURI() const
{
	return m_uri;
}
<commit_msg>Changed obsolete DOMSupport call .<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#include "XalanDefaultParsedSource.hpp"

#include <XalanDOM/XalanDocument.hpp>

#include <PlatformSupport/URISupport.hpp>

#include <DOMSupport/DOMServices.hpp>

#include <XalanSourceTree/XalanSourceTreeDocument.hpp>
#include <XalanSourceTree/XalanSourceTreeDOMSupport.hpp>

XalanDefaultParsedSourceDOMSupport::XalanDefaultParsedSourceDOMSupport(const XalanSourceTreeDOMSupport&		theDOMSupport) :
	XalanSourceTreeDOMSupport(),
	m_domSupport(theDOMSupport)
{
}

XalanDefaultParsedSourceDOMSupport::~XalanDefaultParsedSourceDOMSupport()
{
}

void
XalanDefaultParsedSourceDOMSupport::reset()
{
}

const XalanDOMString*
XalanDefaultParsedSourceDOMSupport::getNamespaceForPrefix(
			const XalanDOMString&	prefix,
			const XalanElement&		namespaceContext) const
{
	return DOMServices::getNamespaceForPrefix(
					prefix,
					namespaceContext);
}

const XalanDOMString&
XalanDefaultParsedSourceDOMSupport::getUnparsedEntityURI(
			const XalanDOMString&	theName,
			const XalanDocument&	theDocument) const
{
	const XalanDOMString&	theURI =
			m_domSupport.getUnparsedEntityURI(
					theName,
					theDocument);

	if (length(theURI) != 0)
	{
		return theURI;
	}
	else
	{
		return XalanSourceTreeDOMSupport::getUnparsedEntityURI(
					theName,
					theDocument);
	}
}

bool
XalanDefaultParsedSourceDOMSupport::isNodeAfter(
			const XalanNode&	node1,
			const XalanNode&	node2) const
{
	return m_domSupport.isNodeAfter(
					node1,
					node2);
}

XalanDefaultParsedSourceHelper::XalanDefaultParsedSourceHelper(
			const XalanSourceTreeDOMSupport&		theSourceDOMSupport,
			const XalanSourceTreeParserLiaison&		theSourceParserLiaison) :
	m_domSupport(theSourceDOMSupport),
	m_parserLiaison(theSourceParserLiaison.getDocumentNumber())
{
	m_domSupport.setParserLiaison(&m_parserLiaison);
}

DOMSupport&
XalanDefaultParsedSourceHelper::getDOMSupport()
{
	return m_domSupport;
}

XMLParserLiaison&
XalanDefaultParsedSourceHelper::getParserLiaison()
{
	return m_parserLiaison;
}

XalanDefaultParsedSource::XalanDefaultParsedSource(
			const XSLTInputSource&	theInputSource,
			bool					fValidate,
			ErrorHandler*			theErrorHandler,
			EntityResolver*			theEntityResolver) :
	XalanParsedSource(),
	m_domSupport(),
	m_parserLiaison(m_domSupport),
	m_parsedSource(0)
{
	m_parserLiaison.setUseValidation(fValidate);
	m_parserLiaison.setEntityResolver(theEntityResolver);
	m_parserLiaison.setErrorHandler(theErrorHandler);

	m_parsedSource = m_parserLiaison.mapDocument(m_parserLiaison.parseXMLStream(theInputSource));
	assert(m_parsedSource != 0);

	m_domSupport.setParserLiaison(&m_parserLiaison);

	const XalanDOMChar* const	theSystemID = theInputSource.getSystemId();

	if (theSystemID != 0)
	{
		try
		{
			m_uri = URISupport::getURLStringFromString(theSystemID);
		}
		catch(const XMLException&)
		{
			// Assume that any exception here relates to get the url from
			// the system ID.  We'll assume that it's just a fake base identifier
			// since the parser would have thrown an error if the system ID
			// wasn't resolved.
			m_uri = theSystemID;
		}
	}
}

XalanDefaultParsedSource::~XalanDefaultParsedSource()
{
}

XalanDocument*
XalanDefaultParsedSource::getDocument() const
{
	return m_parsedSource;
}

XalanParsedSourceHelper*
XalanDefaultParsedSource::createHelper() const
{
	return new XalanDefaultParsedSourceHelper(m_domSupport, m_parserLiaison);
}

const XalanDOMString&
XalanDefaultParsedSource::getURI() const
{
	return m_uri;
}
<|endoftext|>