<commit_before>#include <cstdint>
#include "constants.h"
#include "fork_motor_controller.h"

namespace hardware {

const uint16_t counts_per_revolution = 20000;  // Teknic M-3441E-LN-20D
const uint8_t ccr_channel = 0;                 // PWM Channel 0
const float max_current = 6.0;                 // Copley Controls ACJ-055-18
const float torque_constant = 106.459f * constants::Nm_per_ozfin;

ForkMotorController::ForkMotorController()
  : MotorController("Fork"),
  e_(STM32_TIM3, counts_per_revolution),
  m_(GPIOF, GPIOF_STEER_DIR, GPIOF_STEER_ENABLE, GPIOF_STEER_FAULT,
     STM32_TIM1, ccr_channel, max_current, torque_constant)
{
  instances[fork] = this;
}

ForkMotorController::~ForkMotorController()
{
  instances[fork] = 0;
}

void ForkMotorController::set_reference(float yaw_rate)
{
  yaw_rate_command_ = yaw_rate;
}

void ForkMotorController::disable()
{

}

void ForkMotorController::enable()
{

}

void ForkMotorController::update(Sample & s)
{
  s.encoder.steer = e_.get_angle();
  s.set_point.psi_dot = yaw_rate_command_;
  // TODO:
  //  implement rate divider
  //  determine motor current command, save it in s.motor_current
}

} // namespace hardware
<commit_msg>Add steer motor state logging code.<commit_after>#include <cstdint>
#include "constants.h"
#include "fork_motor_controller.h"
#include "SystemState.h"

namespace hardware {

const uint16_t counts_per_revolution = 20000;  // Teknic M-3441E-LN-20D
const uint8_t ccr_channel = 0;                 // PWM Channel 0
const float max_current = 6.0;                 // Copley Controls ACJ-055-18
const float torque_constant = 106.459f * constants::Nm_per_ozfin;

ForkMotorController::ForkMotorController()
  : MotorController("Fork"),
  e_(STM32_TIM3, counts_per_revolution),
  m_(GPIOF, GPIOF_STEER_DIR, GPIOF_STEER_ENABLE, GPIOF_STEER_FAULT,
     STM32_TIM1, ccr_channel, max_current, torque_constant)
{
  instances[fork] = this;
}

ForkMotorController::~ForkMotorController()
{
  instances[fork] = 0;
}

void ForkMotorController::set_reference(float yaw_rate)
{
  yaw_rate_command_ = yaw_rate;
}

void ForkMotorController::disable()
{

}

void ForkMotorController::enable()
{

}

void ForkMotorController::update(Sample & s)
{
  s.encoder.steer = e_.get_angle();
  s.set_point.psi_dot = yaw_rate_command_;

  // TODO:
  // 1) get rear wheel rate from sample
  // 2) update state estimate
  // 3) update lqr output
  // 4) update PI output
  // 5) compute & set steer torque

  s.motor_current.steer = m_.get_current();

  if (e_.rotation_direction())
    s.system_state |= systemstate::SteerEncoderDir;
  if (m_.is_enabled())
    s.system_state |= systemstate::SteerMotorEnable;
  if (m_.has_fault())
    s.system_state |= systemstate::SteerMotorFault;
  if (m_.current_direction())
    s.system_state |= systemstate::SteerMotorCurrentDir;
}

} // namespace hardware
<|endoftext|>


<commit_before>#pragma once
#include <mutex>
#include <type_traits>
#include <cassert>

namespace But
{
namespace Threading
{

/** @brief class for easy making your type lockable.
 *
 *
 *  class MyCollection: BasicLocable<MyCollection>
 *  {
 *    // ...
 *    bool empty();
 *    Element& top();
 *    void pop();
 *    // ...
 *  };
 *
 *  MyCollection mc;
 *
 *  // ...
 *
 *  {
 *    // NOTE: this whole block is locked, so sequence of operations is secure!
 *    const std::lock_guard<MyCollection> lock{mc};
 *    if( not mc.empty() )
 *    {
 *      process( mc.top() );
 *      mc.pop();
 *    }
 *  }
 *
 *
 *  @note each method of your type, should first do 'assert( locked() )', before proceeding.
 *        'locked()' is only available in debug mode, but can save a lot of time when looking for sync issues.
 */
template<typename CRTP>
class BasicLockable
{
public:
  void lock() const
  {
    m_.lock();
    assert( not locked(true) );
  }

  void unlock() const
  {
    assert( locked(false) );
    m_.unlock();
  }

protected:
  BasicLockable()
  {
    // test is here, as CRTP must be defined, before it can be used... :P
    static_assert( std::is_base_of<BasicLockable, CRTP>::value, "this class is meant to be derived from, to make it work" );
  }

  ~BasicLockable() = default;

#ifndef NDEBUG
  /** @brief to be used in derived classes, for checks like 'assert( locked() )' in methods.
   *  @note this is for debugging purposes in derived class only!
   *  @warning this method is NOT thread-safe on its own!
   *  @warning this method is available only in debug mode!
   */
  bool locked() const { return locked_; }
#endif

private:
#ifndef NDEBUG
  bool locked(const bool newState) const
  {
    const auto prev = locked_;
    locked_ = newState;
    return prev;
  }

  mutable bool locked_{false};
#endif

  mutable std::mutex m_;
};

}
}
<commit_msg>rename CRTP -> Derived, as it is easier to understand<commit_after>#pragma once
#include <mutex>
#include <type_traits>
#include <cassert>

namespace But
{
namespace Threading
{

/** @brief class for easy making your type lockable.
 *
 *
 *  class MyCollection: BasicLocable<MyCollection>
 *  {
 *    // ...
 *    bool empty();
 *    Element& top();
 *    void pop();
 *    // ...
 *  };
 *
 *  MyCollection mc;
 *
 *  // ...
 *
 *  {
 *    // NOTE: this whole block is locked, so sequence of operations is secure!
 *    const std::lock_guard<MyCollection> lock{mc};
 *    if( not mc.empty() )
 *    {
 *      process( mc.top() );
 *      mc.pop();
 *    }
 *  }
 *
 *
 *  @note each method of your type, should first do 'assert( locked() )', before proceeding.
 *        'locked()' is only available in debug mode, but can save a lot of time when looking for sync issues.
 */
template<typename Derived>
class BasicLockable
{
public:
  void lock() const
  {
    m_.lock();
    assert( not locked(true) );
  }

  void unlock() const
  {
    assert( locked(false) );
    m_.unlock();
  }

protected:
  BasicLockable()
  {
    // test is here, as 'Derived' must be defined, before it can be used... :P
    static_assert( std::is_base_of<BasicLockable, Derived>::value, "this class is meant to be derived from, to make it work" );
  }

  ~BasicLockable() = default;

#ifndef NDEBUG
  /** @brief to be used in derived classes, for checks like 'assert( locked() )' in methods.
   *  @note this is for debugging purposes in derived class only!
   *  @warning this method is NOT thread-safe on its own!
   *  @warning this method is available only in debug mode!
   */
  bool locked() const { return locked_; }
#endif

private:
#ifndef NDEBUG
  bool locked(const bool newState) const
  {
    const auto prev = locked_;
    locked_ = newState;
    return prev;
  }

  mutable bool locked_{false};
#endif

  mutable std::mutex m_;
};

}
}
<|endoftext|>


<commit_before>///A simple SAM viewer. Convert a SAM alignment file into a SVG vector graphic.
#include <fstream>
#include <iostream>
#include <string>

#include <seqan/store.h>
#include <seqan/misc/misc_cmdparser.h>
#include <seqan/misc/misc_svg.h>

using namespace seqan;

int main(int argc, const char *argv[])
{
	typedef FragmentStore<> TFragStore;
	typedef TFragStore::TContigPos TContigPos;

	//////////////////////////////////////////////////////////////////////////////
	// Define options
	CommandLineParser parser;
	addUsageLine(parser, "sam2svg [OPTION]... <SAM file> <SVG file>");
	addUsageLine(parser, "sam2svg [OPTION]... <SAM file> <GENOME file> <SVG file>");

	addOption(parser, CommandLineOption("c",  "contig",    "display only contig #NUM (default: show all contigs)", OptionType::Int | OptionType::Label | OptionType::List));
	addOption(parser, CommandLineOption("p",  "pos",    2, "set begin and end position (default: show whole strands)", OptionType::Int | OptionType::Label));
	addOption(parser, CommandLineOption("l",  "lines",  2, "set first and last line of the alignment (default: show whole alignment)", OptionType::Int | OptionType::Label));
	addOption(parser, CommandLineOption("a",  "ascii",     "output alignment in ASCII format instead of SVG", OptionType::Bool | OptionType::Label));
	requiredArguments(parser, 2);

	if (argc == 1)
	{
		shortHelp(parser, std::cerr);	// print short help and exit
		return 0;
	}

	bool stop = !parse(parser, argc, argv, std::cerr);

	//////////////////////////////////////////////////////////////////////////////
	// Extract and check options

	if (isSetLong(parser, "help") || isSetLong(parser, "version")) return 0;	// print help or version and exit

	String<unsigned> contigs;
	TContigPos left = 0;
	TContigPos right = SupremumValue<TContigPos>::VALUE;
	unsigned firstLine = 0;
	unsigned lastLine = SupremumValue<unsigned>::VALUE;
	bool inASCII = false;

	if (isSetLong(parser, "pos"))
	{
		getOptionValueLong(parser, "pos", 0, left);
		getOptionValueLong(parser, "pos", 1, right);
		if ((left >= right) && (stop = true))
			std::cerr << "Begin position must be less than end position." << std::endl;
	}

	if (isSetLong(parser, "lines"))
	{
		getOptionValueLong(parser, "lines", 0, firstLine);
		getOptionValueLong(parser, "lines", 1, lastLine);
		if ((firstLine >= lastLine) && (stop = true))
			std::cerr << "First line must be less or equal than last line." << std::endl;
	}

	TFragStore store;
	std::ifstream samFile(toCString(getArgumentValue(parser, 0)), std::ios_base::in | std::ios_base::binary);
	std::ofstream ascii;
	SVGFile svg;

	//////////////////////////////////////////////////////////////////////////////
	// Optionally load genome file
	uint outArgNo = 1;
	if (argumentCount(parser) > 2)
	{
		if (!loadContigs(store, getArgumentValue(parser, 1)) && (stop = true))
			std::cerr << "Failed to load genome." << std::endl;
		++outArgNo;
	}

	//////////////////////////////////////////////////////////////////////////////
	// Load SAM file
	if (!stop) read(samFile, store, SAM());

	//////////////////////////////////////////////////////////////////////////////
	// Choose contigs
	if (isSetLong(parser, "contig"))
	{
		resize(contigs, length(getOptionValuesLong(parser, "contig")));
		for (unsigned i = 0; i < length(contigs); ++i)
			getOptionValueLong(parser, "contig", i, contigs[i]);
	} else {
		resize(contigs, length(store.contigStore));
		for (unsigned i = 0; i < length(contigs); ++i)
			contigs[i] = i;
	}

	if (isSetLong(parser, "ascii"))
		inASCII = true;

	//////////////////////////////////////////////////////////////////////////////
	// Optionally load genome and open SVG file for writing
	if (!stop)
	{

		if (!stop)
		{
			if (inASCII)
			{
				ascii.open(toCString(getArgumentValue(parser, outArgNo)), std::ios_base::out | std::ios_base::trunc);
				if (!ascii.is_open()) stop = true;
			} else
				if (!open(svg, toCString(getArgumentValue(parser, outArgNo)))) stop = true;

			if (stop) std::cerr << "Failed to open output file for writing." << std::endl;
		}
	}

	// something went wrong
	if (stop)
	{
		std::cerr << "Exiting ..." << std::endl;
		return 1;
	}

	for(unsigned o=0;o<length(store.contigStore);++o)
	std::cerr<<store.contigNameStore[o]<<std::endl;

	//////////////////////////////////////////////////////////////////////////////
	// Output alignment
	AlignedReadLayout layout;
	std::cout << "Layouting reads ... " << std::flush;
	layoutAlignment(layout, store);
	std::cout << "done" << std::endl;

	for (unsigned i = 0; i < length(contigs); ++i)
		if (i < length(store.contigStore))
		{
			std::cout << "Writing contig " << contigs[i] << " ... " << std::flush;
			TContigPos right_ = right;
			if (right_ == SupremumValue<TContigPos>::VALUE)
			{
				right_ = 0;
				for (unsigned j = 0; j < length(layout.contigRows[i]); ++j)
				{
					unsigned id = back(layout.contigRows[i][j]);
					if (right_ < store.alignedReadStore[id].beginPos)
						right_ = store.alignedReadStore[id].beginPos;
					if (right_ < store.alignedReadStore[id].endPos)
						right_ = store.alignedReadStore[id].endPos;
				}
			}
			std::cout << left<<'\t'<<right_<<'\t'<<firstLine<<'\t'<<lastLine<<std::endl;
			if (inASCII)
				printAlignment(ascii, Raw(), layout, store, contigs[i], left, right_, firstLine, lastLine);
			else
				printAlignment(svg, Raw(), layout, store, contigs[i], left, right_, firstLine, lastLine);

			std::cout << "done" << std::endl;
		}

	return 0;
}
<commit_msg><commit_after>///A simple SAM viewer. Convert a SAM alignment file into a SVG vector graphic.
#include <fstream>
#include <iostream>
#include <string>

#include <seqan/store.h>
#include <seqan/misc/misc_cmdparser.h>
#include <seqan/misc/misc_svg.h>

using namespace seqan;

int main(int argc, const char *argv[])
{
	typedef FragmentStore<> TFragStore;
	typedef TFragStore::TContigPos TContigPos;

	//////////////////////////////////////////////////////////////////////////////
	// Define options
	CommandLineParser parser;
	addUsageLine(parser, "sam2svg [OPTION]... <SAM file> <SVG file>");
	addUsageLine(parser, "sam2svg [OPTION]... <SAM file> <GENOME file> <SVG file>");

	addOption(parser, CommandLineOption("c",  "contig",    "display only contig #NUM (default: show all contigs)", OptionType::Int | OptionType::Label | OptionType::List));
	addOption(parser, CommandLineOption("p",  "pos",    2, "set begin and end position (default: show whole strands)", OptionType::Int | OptionType::Label));
	addOption(parser, CommandLineOption("l",  "lines",  2, "set first and last line of the alignment (default: show whole alignment)", OptionType::Int | OptionType::Label));
	addOption(parser, CommandLineOption("a",  "ascii",     "output alignment in ASCII format instead of SVG", OptionType::Bool | OptionType::Label));
	requiredArguments(parser, 2);

	if (argc == 1)
	{
		shortHelp(parser, std::cerr);	// print short help and exit
		return 0;
	}

	bool stop = !parse(parser, argc, argv, std::cerr);

	//////////////////////////////////////////////////////////////////////////////
	// Extract and check options

	if (isSetLong(parser, "help") || isSetLong(parser, "version")) return 0;	// print help or version and exit

	String<unsigned> contigs;
	TContigPos left = 0;
	TContigPos right = SupremumValue<TContigPos>::VALUE;
	unsigned firstLine = 0;
	unsigned lastLine = SupremumValue<unsigned>::VALUE;
	bool inASCII = false;

	if (isSetLong(parser, "pos"))
	{
		getOptionValueLong(parser, "pos", 0, left);
		getOptionValueLong(parser, "pos", 1, right);
		if ((left >= right) && (stop = true))
			std::cerr << "Begin position must be less than end position." << std::endl;
	}

	if (isSetLong(parser, "lines"))
	{
		getOptionValueLong(parser, "lines", 0, firstLine);
		getOptionValueLong(parser, "lines", 1, lastLine);
		if ((firstLine >= lastLine) && (stop = true))
			std::cerr << "First line must be less or equal than last line." << std::endl;
	}

	TFragStore store;
	std::ifstream samFile(toCString(getArgumentValue(parser, 0)), std::ios_base::in | std::ios_base::binary);
	std::ofstream ascii;
	SVGFile svg;

	//////////////////////////////////////////////////////////////////////////////
	// Optionally load genome file
	uint outArgNo = 1;
	if (argumentCount(parser) > 2)
	{
		if (!loadContigs(store, getArgumentValue(parser, 1)) && (stop = true))
			std::cerr << "Failed to load genome." << std::endl;
		++outArgNo;
	}

	//////////////////////////////////////////////////////////////////////////////
	// Load SAM file
	if (!stop) read(samFile, store, SAM());

	//////////////////////////////////////////////////////////////////////////////
	// Choose contigs
	if (isSetLong(parser, "contig"))
	{
		resize(contigs, length(getOptionValuesLong(parser, "contig")));
		for (unsigned i = 0; i < length(contigs); ++i)
			getOptionValueLong(parser, "contig", i, contigs[i]);
	} else {
		resize(contigs, length(store.contigStore));
		for (unsigned i = 0; i < length(contigs); ++i)
			contigs[i] = i;
	}

	if (isSetLong(parser, "ascii"))
		inASCII = true;

	//////////////////////////////////////////////////////////////////////////////
	// Optionally load genome and open SVG file for writing
	if (!stop)
	{
		if (inASCII)
		{
			ascii.open(toCString(getArgumentValue(parser, outArgNo)), std::ios_base::out | std::ios_base::trunc);
			if (!ascii.is_open()) stop = true;
		} else
			if (!open(svg, toCString(getArgumentValue(parser, outArgNo)))) stop = true;

		if (stop) std::cerr << "Failed to open output file for writing." << std::endl;
	}

	// something went wrong
	if (stop)
	{
		std::cerr << "Exiting ..." << std::endl;
		return 1;
	}

	for(unsigned o=0;o<length(store.contigStore);++o)
	std::cerr<<store.contigNameStore[o]<<std::endl;

	//////////////////////////////////////////////////////////////////////////////
	// Output alignment
	AlignedReadLayout layout;
	std::cout << "Layouting reads ... " << std::flush;
	layoutAlignment(layout, store);
	std::cout << "done" << std::endl;

	for (unsigned i = 0; i < length(contigs); ++i)
		if (i < length(store.contigStore))
		{
			std::cout << "Writing contig " << contigs[i] << " ... " << std::flush;
			TContigPos right_ = right;
			if (right_ == SupremumValue<TContigPos>::VALUE)
			{
				right_ = 0;
				for (unsigned j = 0; j < length(layout.contigRows[i]); ++j)
				{
					unsigned id = back(layout.contigRows[i][j]);
					if (right_ < store.alignedReadStore[id].beginPos)
						right_ = store.alignedReadStore[id].beginPos;
					if (right_ < store.alignedReadStore[id].endPos)
						right_ = store.alignedReadStore[id].endPos;
				}
			}
			std::cout << left<<'\t'<<right_<<'\t'<<firstLine<<'\t'<<lastLine<<std::endl;
			if (inASCII)
				printAlignment(ascii, Raw(), layout, store, contigs[i], left, right_, firstLine, lastLine);
			else
				printAlignment(svg, Raw(), layout, store, contigs[i], left, right_, firstLine, lastLine);

			std::cout << "done" << std::endl;
		}

	return 0;
}
<|endoftext|>


<commit_before><commit_msg>Started maths::Matrix testing<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2009, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * 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.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// This code exists to generate minidump files for testing.

#include <stdlib.h>

#include <unistd.h>

#include "breakpad/src/client/linux/handler/exception_handler.h"
#include "breakpad/src/common/linux/linux_libc_support.h"
#include "breakpad/src/third_party/lss/linux_syscall_support.h"

static bool DumpCallback(const char* dump_path, const char* minidump_id,
                         void* context, bool success) {
  if (!success) {
    static const char msg[] = "Failed to write minidump\n";
    sys_write(2, msg, sizeof(msg) - 1);
    return false;
  }

  static const char msg[] = "Wrote minidump: ";
  sys_write(2, msg, sizeof(msg) - 1);
  sys_write(2, dump_path, my_strlen(dump_path));
  sys_write(2, "/", 1);
  sys_write(2, minidump_id, my_strlen(minidump_id));
  sys_write(2, ".dmp\n", 5);

  return true;
}

static void DoSomethingWhichCrashes() {
  int local_var = 1;
  *reinterpret_cast<char*>(NULL) = 1;
}

int main() {
  google_breakpad::ExceptionHandler breakpad(".", NULL, DumpCallback, NULL,
                                             true);
  DoSomethingWhichCrashes();
  return 0;
}
<commit_msg>Linux: Fix linux_syscall_support #include path for generate-test-dump.cc.<commit_after>// Copyright (c) 2009, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * 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.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// This code exists to generate minidump files for testing.

#include <stdlib.h>

#include <unistd.h>

#include "breakpad/src/client/linux/handler/exception_handler.h"
#include "breakpad/src/common/linux/linux_libc_support.h"
#include "third_party/lss/linux_syscall_support.h"

static bool DumpCallback(const char* dump_path, const char* minidump_id,
                         void* context, bool success) {
  if (!success) {
    static const char msg[] = "Failed to write minidump\n";
    sys_write(2, msg, sizeof(msg) - 1);
    return false;
  }

  static const char msg[] = "Wrote minidump: ";
  sys_write(2, msg, sizeof(msg) - 1);
  sys_write(2, dump_path, my_strlen(dump_path));
  sys_write(2, "/", 1);
  sys_write(2, minidump_id, my_strlen(minidump_id));
  sys_write(2, ".dmp\n", 5);

  return true;
}

static void DoSomethingWhichCrashes() {
  int local_var = 1;
  *reinterpret_cast<char*>(NULL) = 1;
}

int main() {
  google_breakpad::ExceptionHandler breakpad(".", NULL, DumpCallback, NULL,
                                             true);
  DoSomethingWhichCrashes();
  return 0;
}
<|endoftext|>


<commit_before>// Copyright 2018 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#define FML_USED_ON_EMBEDDER

#include "flutter/shell/platform/android/android_shell_holder.h"

#include <pthread.h>
#include <sys/resource.h>
#include <sys/time.h>

#include <sstream>
#include <string>
#include <utility>

#include "flutter/fml/message_loop.h"
#include "flutter/shell/common/rasterizer.h"
#include "flutter/shell/platform/android/platform_view_android.h"
#include "lib/fxl/functional/make_copyable.h"

namespace shell {

AndroidShellHolder::AndroidShellHolder(
    blink::Settings settings,
    fml::jni::JavaObjectWeakGlobalRef java_object)
    : settings_(std::move(settings)), java_object_(java_object) {
  static size_t shell_count = 1;
  auto thread_label = std::to_string(shell_count++);

  FXL_CHECK(pthread_key_create(&thread_destruct_key_, ThreadDestructCallback) ==
            0);

  thread_host_ = {thread_label, ThreadHost::Type::UI | ThreadHost::Type::GPU |
                                    ThreadHost::Type::IO};

  // Detach from JNI when the UI thread exits.
  thread_host_.ui_thread->GetTaskRunner()->PostTask(
      [key = thread_destruct_key_]() {
        FXL_CHECK(pthread_setspecific(key, reinterpret_cast<void*>(1)) == 0);
      });

  fml::WeakPtr<PlatformViewAndroid> weak_platform_view;
  Shell::CreateCallback<PlatformView> on_create_platform_view =
      [java_object, &weak_platform_view](Shell& shell) {
        auto platform_view_android = std::make_unique<PlatformViewAndroid>(
            shell,                   // delegate
            shell.GetTaskRunners(),  // task runners
            java_object,             // java object handle for JNI interop
            shell.GetSettings()
                .enable_software_rendering  // use software rendering
        );
        weak_platform_view = platform_view_android->GetWeakPtr();
        return platform_view_android;
      };

  Shell::CreateCallback<Rasterizer> on_create_rasterizer = [](Shell& shell) {
    return std::make_unique<Rasterizer>(shell.GetTaskRunners());
  };

  // The current thread will be used as the platform thread. Ensure that the
  // message loop is initialized.
  fml::MessageLoop::EnsureInitializedForCurrentThread();

  blink::TaskRunners task_runners(
      thread_label,                                    // label
      fml::MessageLoop::GetCurrent().GetTaskRunner(),  // platform
      thread_host_.gpu_thread->GetTaskRunner(),        // gpu
      thread_host_.ui_thread->GetTaskRunner(),         // ui
      thread_host_.io_thread->GetTaskRunner()          // io
  );

  shell_ =
      Shell::Create(task_runners,             // task runners
                    settings_,                // settings
                    on_create_platform_view,  // platform view create callback
                    on_create_rasterizer      // rasterizer create callback
      );

  platform_view_ = weak_platform_view;
  FXL_DCHECK(platform_view_);

  is_valid_ = shell_ != nullptr;

  if (is_valid_) {
    task_runners.GetGPUTaskRunner()->PostTask(
        []() {
          // Android describes -8 as "most important display threads, for
          // compositing the screen and retrieving input events". Conservatively
          // set the GPU thread to slightly lower priority than it.
          if (::setpriority(PRIO_PROCESS, gettid(), -5) != 0) {
            // Defensive fallback. Depending on the OEM, it may not be possible
            // to set priority to -5.
            if (::setpriority(PRIO_PROCESS, gettid(), -2) != 0) {
              FXL_LOG(ERROR) << "Failed to set GPU task runner priority";
            }
          }
        });
    task_runners.GetUITaskRunner()->PostTask(
        []() {
          if (::setpriority(PRIO_PROCESS, gettid(), -1) != 0) {
            FXL_LOG(ERROR) << "Failed to set UI task runner priority";
          }
        });
  }
}

AndroidShellHolder::~AndroidShellHolder() {
  shell_.reset();
  thread_host_.Reset();
  FXL_CHECK(pthread_key_delete(thread_destruct_key_) == 0);
}

void AndroidShellHolder::ThreadDestructCallback(void* value) {
  fml::jni::DetachFromVM();
}

bool AndroidShellHolder::IsValid() const {
  return is_valid_;
}

const blink::Settings& AndroidShellHolder::GetSettings() const {
  return settings_;
}

void AndroidShellHolder::Launch(RunConfiguration config) {
  if (!IsValid()) {
    return;
  }

  shell_->GetTaskRunners().GetUITaskRunner()->PostTask(
      fxl::MakeCopyable([engine = shell_->GetEngine(),  //
                         config = std::move(config)     //
  ]() mutable {
        if (engine) {
          if (!engine->Run(std::move(config))) {
            FXL_LOG(ERROR) << "Could not launch engine in configuration.";
          }
        }
      }));
}

void AndroidShellHolder::SetViewportMetrics(
    const blink::ViewportMetrics& metrics) {
  if (!IsValid()) {
    return;
  }

  shell_->GetTaskRunners().GetUITaskRunner()->PostTask(
      [engine = shell_->GetEngine(), metrics]() {
        if (engine) {
          engine->SetViewportMetrics(metrics);
        }
      });
}

void AndroidShellHolder::DispatchPointerDataPacket(
    std::unique_ptr<blink::PointerDataPacket> packet) {
  if (!IsValid()) {
    return;
  }

  shell_->GetTaskRunners().GetUITaskRunner()->PostTask(fxl::MakeCopyable(
      [engine = shell_->GetEngine(), packet = std::move(packet)] {
        if (engine) {
          engine->DispatchPointerDataPacket(*packet);
        }
      }));
}

Rasterizer::Screenshot AndroidShellHolder::Screenshot(
    Rasterizer::ScreenshotType type,
    bool base64_encode) {
  if (!IsValid()) {
    return {nullptr, SkISize::MakeEmpty()};
  }
  return shell_->Screenshot(type, base64_encode);
}

fml::WeakPtr<PlatformViewAndroid> AndroidShellHolder::GetPlatformView() {
  FXL_DCHECK(platform_view_);
  return platform_view_;
}

void AndroidShellHolder::UpdateAssetManager(
    fxl::RefPtr<blink::AssetManager> asset_manager) {
  if (!IsValid() || !asset_manager) {
    return;
  }

  shell_->GetTaskRunners().GetUITaskRunner()->PostTask(
      [engine = shell_->GetEngine(),
       asset_manager = std::move(asset_manager)]() {
        if (engine) {
          if (!engine->UpdateAssetManager(std::move(asset_manager))) {
            FXL_DLOG(ERROR) << "Could not update asset asset manager.";
          }
        }
      });
}

}  // namespace shell
<commit_msg>Detach from JNI before exiting the GPU thread. (#5231)<commit_after>// Copyright 2018 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#define FML_USED_ON_EMBEDDER

#include "flutter/shell/platform/android/android_shell_holder.h"

#include <pthread.h>
#include <sys/resource.h>
#include <sys/time.h>

#include <sstream>
#include <string>
#include <utility>

#include "flutter/fml/message_loop.h"
#include "flutter/shell/common/rasterizer.h"
#include "flutter/shell/platform/android/platform_view_android.h"
#include "lib/fxl/functional/make_copyable.h"

namespace shell {

AndroidShellHolder::AndroidShellHolder(
    blink::Settings settings,
    fml::jni::JavaObjectWeakGlobalRef java_object)
    : settings_(std::move(settings)), java_object_(java_object) {
  static size_t shell_count = 1;
  auto thread_label = std::to_string(shell_count++);

  FXL_CHECK(pthread_key_create(&thread_destruct_key_, ThreadDestructCallback) ==
            0);

  thread_host_ = {thread_label, ThreadHost::Type::UI | ThreadHost::Type::GPU |
                                    ThreadHost::Type::IO};

  // Detach from JNI when the UI and GPU threads exit.
  auto jni_exit_task([key = thread_destruct_key_]() {
    FXL_CHECK(pthread_setspecific(key, reinterpret_cast<void*>(1)) == 0);
  });
  thread_host_.ui_thread->GetTaskRunner()->PostTask(jni_exit_task);
  thread_host_.gpu_thread->GetTaskRunner()->PostTask(jni_exit_task);

  fml::WeakPtr<PlatformViewAndroid> weak_platform_view;
  Shell::CreateCallback<PlatformView> on_create_platform_view =
      [java_object, &weak_platform_view](Shell& shell) {
        auto platform_view_android = std::make_unique<PlatformViewAndroid>(
            shell,                   // delegate
            shell.GetTaskRunners(),  // task runners
            java_object,             // java object handle for JNI interop
            shell.GetSettings()
                .enable_software_rendering  // use software rendering
        );
        weak_platform_view = platform_view_android->GetWeakPtr();
        return platform_view_android;
      };

  Shell::CreateCallback<Rasterizer> on_create_rasterizer = [](Shell& shell) {
    return std::make_unique<Rasterizer>(shell.GetTaskRunners());
  };

  // The current thread will be used as the platform thread. Ensure that the
  // message loop is initialized.
  fml::MessageLoop::EnsureInitializedForCurrentThread();

  blink::TaskRunners task_runners(
      thread_label,                                    // label
      fml::MessageLoop::GetCurrent().GetTaskRunner(),  // platform
      thread_host_.gpu_thread->GetTaskRunner(),        // gpu
      thread_host_.ui_thread->GetTaskRunner(),         // ui
      thread_host_.io_thread->GetTaskRunner()          // io
  );

  shell_ =
      Shell::Create(task_runners,             // task runners
                    settings_,                // settings
                    on_create_platform_view,  // platform view create callback
                    on_create_rasterizer      // rasterizer create callback
      );

  platform_view_ = weak_platform_view;
  FXL_DCHECK(platform_view_);

  is_valid_ = shell_ != nullptr;

  if (is_valid_) {
    task_runners.GetGPUTaskRunner()->PostTask(
        []() {
          // Android describes -8 as "most important display threads, for
          // compositing the screen and retrieving input events". Conservatively
          // set the GPU thread to slightly lower priority than it.
          if (::setpriority(PRIO_PROCESS, gettid(), -5) != 0) {
            // Defensive fallback. Depending on the OEM, it may not be possible
            // to set priority to -5.
            if (::setpriority(PRIO_PROCESS, gettid(), -2) != 0) {
              FXL_LOG(ERROR) << "Failed to set GPU task runner priority";
            }
          }
        });
    task_runners.GetUITaskRunner()->PostTask(
        []() {
          if (::setpriority(PRIO_PROCESS, gettid(), -1) != 0) {
            FXL_LOG(ERROR) << "Failed to set UI task runner priority";
          }
        });
  }
}

AndroidShellHolder::~AndroidShellHolder() {
  shell_.reset();
  thread_host_.Reset();
  FXL_CHECK(pthread_key_delete(thread_destruct_key_) == 0);
}

void AndroidShellHolder::ThreadDestructCallback(void* value) {
  fml::jni::DetachFromVM();
}

bool AndroidShellHolder::IsValid() const {
  return is_valid_;
}

const blink::Settings& AndroidShellHolder::GetSettings() const {
  return settings_;
}

void AndroidShellHolder::Launch(RunConfiguration config) {
  if (!IsValid()) {
    return;
  }

  shell_->GetTaskRunners().GetUITaskRunner()->PostTask(
      fxl::MakeCopyable([engine = shell_->GetEngine(),  //
                         config = std::move(config)     //
  ]() mutable {
        if (engine) {
          if (!engine->Run(std::move(config))) {
            FXL_LOG(ERROR) << "Could not launch engine in configuration.";
          }
        }
      }));
}

void AndroidShellHolder::SetViewportMetrics(
    const blink::ViewportMetrics& metrics) {
  if (!IsValid()) {
    return;
  }

  shell_->GetTaskRunners().GetUITaskRunner()->PostTask(
      [engine = shell_->GetEngine(), metrics]() {
        if (engine) {
          engine->SetViewportMetrics(metrics);
        }
      });
}

void AndroidShellHolder::DispatchPointerDataPacket(
    std::unique_ptr<blink::PointerDataPacket> packet) {
  if (!IsValid()) {
    return;
  }

  shell_->GetTaskRunners().GetUITaskRunner()->PostTask(fxl::MakeCopyable(
      [engine = shell_->GetEngine(), packet = std::move(packet)] {
        if (engine) {
          engine->DispatchPointerDataPacket(*packet);
        }
      }));
}

Rasterizer::Screenshot AndroidShellHolder::Screenshot(
    Rasterizer::ScreenshotType type,
    bool base64_encode) {
  if (!IsValid()) {
    return {nullptr, SkISize::MakeEmpty()};
  }
  return shell_->Screenshot(type, base64_encode);
}

fml::WeakPtr<PlatformViewAndroid> AndroidShellHolder::GetPlatformView() {
  FXL_DCHECK(platform_view_);
  return platform_view_;
}

void AndroidShellHolder::UpdateAssetManager(
    fxl::RefPtr<blink::AssetManager> asset_manager) {
  if (!IsValid() || !asset_manager) {
    return;
  }

  shell_->GetTaskRunners().GetUITaskRunner()->PostTask(
      [engine = shell_->GetEngine(),
       asset_manager = std::move(asset_manager)]() {
        if (engine) {
          if (!engine->UpdateAssetManager(std::move(asset_manager))) {
            FXL_DLOG(ERROR) << "Could not update asset asset manager.";
          }
        }
      });
}

}  // namespace shell
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: viewobjectcontactofsdrmediaobj.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2004-08-24 07:20:33 $
 *
 *  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 <svx/sdr/contact/objectcontactofpageview.hxx>
#include <svx/sdr/contact/viewobjectcontactofsdrmediaobj.hxx>
#include <svx/sdr/contact/viewcontactofsdrmediaobj.hxx>
#include <svx/sdr/contact/displayinfo.hxx>
#include <svdobj.hxx>
#include <svdpagv.hxx>
#include <vcl/outdev.hxx>
#include <vcl/window.hxx>
#include <avmedia/mediaitem.hxx>
#include "sdrmediawindow.hxx"

namespace sdr { namespace contact {

// ----------------------------------
// - ViewObjectContactOfSdrMediaObj -
// ----------------------------------

ViewObjectContactOfSdrMediaObj::ViewObjectContactOfSdrMediaObj( ObjectContact& rObjectContact,
                                                                ViewContact& rViewContact,
                                                                const ::avmedia::MediaItem& rMediaItem ) :
    ViewObjectContact( rObjectContact, rViewContact ),
    mpMediaWindow( NULL )
{
    Window* pWindow = getWindow();

    if( pWindow )
    {
        mpMediaWindow = new SdrMediaWindow( pWindow, *this );
        executeMediaItem( rMediaItem );
        mpMediaWindow->show();
    }
}

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

ViewObjectContactOfSdrMediaObj::~ViewObjectContactOfSdrMediaObj()
{
    DBG_ASSERT( !mpMediaWindow, "ViewObjectContactOfSdrMediaObj::~ViewObjectContactOfSdrMediaObj(): mpMediaWindow != NULL" );
}

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

void ViewObjectContactOfSdrMediaObj::PrepareDelete()
{
    ViewObjectContact::PrepareDelete();
    delete mpMediaWindow;
    mpMediaWindow = NULL;
}

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

void ViewObjectContactOfSdrMediaObj::PaintObject(DisplayInfo& rDisplayInfo)
{
    SdrObject* pObj = GetViewContact().TryToGetSdrObject();

    ViewObjectContact::PaintObject( rDisplayInfo );

    if( pObj )
    {
        Rectangle       aPaintRect( pObj->GetCurrentBoundRect() );
        OutputDevice*   pOutDev = rDisplayInfo.GetOutputDevice();
        sal_Int32       nOffset( pOutDev->PixelToLogic( Size( 4, 4 ) ).Width() );
        bool            bWasPainted = false;

        aPaintRect.Left() += nOffset;
        aPaintRect.Top() += nOffset;
        aPaintRect.Right() -= nOffset;
        aPaintRect.Bottom() -= nOffset;

        if( !mpMediaWindow )
        {
            OutputDevice* pOutDev = rDisplayInfo.GetOutputDevice();

            if( pOutDev &&
                ( aPaintRect.Left() < aPaintRect.Right() &&
                  aPaintRect.Top() < aPaintRect.Bottom() ) )
            {
                pOutDev->SetLineColor( COL_BLACK );
                pOutDev->SetFillColor( COL_BLACK );
                pOutDev->DrawRect( aPaintRect );
                bWasPainted = true;
            }
        }
        else
        {
            Rectangle   aCurPaintRect( pOutDev->LogicToPixel( aPaintRect.TopLeft() ),
                                       pOutDev->LogicToPixel( aPaintRect.GetSize() ) );
            const bool  bNewPaintRect = ( maLastPaintRect.IsEmpty() || ( maLastPaintRect != aCurPaintRect ) );

            if( bNewPaintRect )
            {
                mpMediaWindow->setPosSize( aCurPaintRect );
                maLastPaintRect = aCurPaintRect;
            }
            else
            {
                Window* pWindow = mpMediaWindow->getWindow();

                if( pWindow )
                {
                    pWindow->Invalidate();
                    pWindow->Update();
                }
            }

            bWasPainted = true;
        }

        if( bWasPainted )
        {
            mbIsPainted = sal_True;
            mbIsInvalidated = sal_False;
            maPaintedRectangle = pObj->GetCurrentBoundRect();
        }
    }
}

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

Window* ViewObjectContactOfSdrMediaObj::getWindow() const
{
    OutputDevice& rOutDev = static_cast< ObjectContactOfPageView& >( GetObjectContact() ).GetPageViewWindow().GetOutputDevice();

    return( ( rOutDev.GetOutDevType() == OUTDEV_WINDOW ) ? static_cast< Window* >( &rOutDev ) : NULL );
}

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

bool ViewObjectContactOfSdrMediaObj::hasPreferredSize() const
{
    return( mpMediaWindow != NULL && mpMediaWindow->hasPreferredSize() );
}

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

Size ViewObjectContactOfSdrMediaObj::getPreferredSize() const
{
    Size aRet;

    if( mpMediaWindow )
        aRet = mpMediaWindow->getPreferredSize();

    return aRet;
}

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

void ViewObjectContactOfSdrMediaObj::updateMediaItem( ::avmedia::MediaItem& rItem ) const
{
    if( mpMediaWindow )
        mpMediaWindow->updateMediaItem( rItem );
}

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

void ViewObjectContactOfSdrMediaObj::executeMediaItem( const ::avmedia::MediaItem& rItem )
{
    if( mpMediaWindow )
    {
        ::avmedia::MediaItem aUpdatedItem;

        mpMediaWindow->executeMediaItem( rItem );

        // query new properties after trying to set the new properties
        updateMediaItem( aUpdatedItem );
        static_cast< ViewContactOfSdrMediaObj& >( GetViewContact() ).mediaPropertiesChanged( aUpdatedItem );
    }
}

} }
<commit_msg>INTEGRATION: CWS jmf3 (1.3.68); FILE MERGED 2004/10/04 10:33:12 ka 1.3.68.1: watch for correct cast<commit_after>/*************************************************************************
 *
 *  $RCSfile: viewobjectcontactofsdrmediaobj.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2004-11-03 16:03:37 $
 *
 *  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 <svx/sdr/contact/objectcontactofpageview.hxx>
#include <svx/sdr/contact/viewobjectcontactofsdrmediaobj.hxx>
#include <svx/sdr/contact/viewcontactofsdrmediaobj.hxx>
#include <svx/sdr/contact/displayinfo.hxx>
#include <svdobj.hxx>
#include <svdpagv.hxx>
#include <vcl/outdev.hxx>
#include <vcl/window.hxx>
#include <avmedia/mediaitem.hxx>
#include "sdrmediawindow.hxx"

namespace sdr { namespace contact {

// ----------------------------------
// - ViewObjectContactOfSdrMediaObj -
// ----------------------------------

ViewObjectContactOfSdrMediaObj::ViewObjectContactOfSdrMediaObj( ObjectContact& rObjectContact,
                                                                ViewContact& rViewContact,
                                                                const ::avmedia::MediaItem& rMediaItem ) :
    ViewObjectContact( rObjectContact, rViewContact ),
    mpMediaWindow( NULL )
{
    Window* pWindow = getWindow();

    if( pWindow )
    {
        mpMediaWindow = new SdrMediaWindow( pWindow, *this );
        executeMediaItem( rMediaItem );
        mpMediaWindow->show();
    }
}

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

ViewObjectContactOfSdrMediaObj::~ViewObjectContactOfSdrMediaObj()
{
    DBG_ASSERT( !mpMediaWindow, "ViewObjectContactOfSdrMediaObj::~ViewObjectContactOfSdrMediaObj(): mpMediaWindow != NULL" );
}

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

void ViewObjectContactOfSdrMediaObj::PrepareDelete()
{
    ViewObjectContact::PrepareDelete();
    delete mpMediaWindow;
    mpMediaWindow = NULL;
}

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

void ViewObjectContactOfSdrMediaObj::PaintObject(DisplayInfo& rDisplayInfo)
{
    SdrObject* pObj = GetViewContact().TryToGetSdrObject();

    ViewObjectContact::PaintObject( rDisplayInfo );

    if( pObj )
    {
        Rectangle       aPaintRect( pObj->GetCurrentBoundRect() );
        OutputDevice*   pOutDev = rDisplayInfo.GetOutputDevice();
        sal_Int32       nOffset( pOutDev->PixelToLogic( Size( 4, 4 ) ).Width() );
        bool            bWasPainted = false;

        aPaintRect.Left() += nOffset;
        aPaintRect.Top() += nOffset;
        aPaintRect.Right() -= nOffset;
        aPaintRect.Bottom() -= nOffset;

        if( !mpMediaWindow )
        {
            OutputDevice* pOutDev = rDisplayInfo.GetOutputDevice();

            if( pOutDev &&
                ( aPaintRect.Left() < aPaintRect.Right() &&
                  aPaintRect.Top() < aPaintRect.Bottom() ) )
            {
                pOutDev->SetLineColor( COL_BLACK );
                pOutDev->SetFillColor( COL_BLACK );
                pOutDev->DrawRect( aPaintRect );
                bWasPainted = true;
            }
        }
        else
        {
            Rectangle   aCurPaintRect( pOutDev->LogicToPixel( aPaintRect.TopLeft() ),
                                       pOutDev->LogicToPixel( aPaintRect.GetSize() ) );
            const bool  bNewPaintRect = ( maLastPaintRect.IsEmpty() || ( maLastPaintRect != aCurPaintRect ) );

            if( bNewPaintRect )
            {
                mpMediaWindow->setPosSize( aCurPaintRect );
                maLastPaintRect = aCurPaintRect;
            }
            else
            {
                Window* pWindow = mpMediaWindow->getWindow();

                if( pWindow )
                {
                    pWindow->Invalidate();
                    pWindow->Update();
                }
            }

            bWasPainted = true;
        }

        if( bWasPainted )
        {
            mbIsPainted = sal_True;
            mbIsInvalidated = sal_False;
            maPaintedRectangle = pObj->GetCurrentBoundRect();
        }
    }
}

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

Window* ViewObjectContactOfSdrMediaObj::getWindow() const
{
    ObjectContactOfPageView* pOC = dynamic_cast< ObjectContactOfPageView* >( &GetObjectContact() );

    if( pOC)
    {
        OutputDevice& rOutDev = pOC->GetPageViewWindow().GetOutputDevice();
        return( ( rOutDev.GetOutDevType() == OUTDEV_WINDOW ) ? static_cast< Window* >( &rOutDev ) : NULL );
    }

    return NULL;
}

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

bool ViewObjectContactOfSdrMediaObj::hasPreferredSize() const
{
    return( mpMediaWindow != NULL && mpMediaWindow->hasPreferredSize() );
}

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

Size ViewObjectContactOfSdrMediaObj::getPreferredSize() const
{
    Size aRet;

    if( mpMediaWindow )
        aRet = mpMediaWindow->getPreferredSize();

    return aRet;
}

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

void ViewObjectContactOfSdrMediaObj::updateMediaItem( ::avmedia::MediaItem& rItem ) const
{
    if( mpMediaWindow )
        mpMediaWindow->updateMediaItem( rItem );
}

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

void ViewObjectContactOfSdrMediaObj::executeMediaItem( const ::avmedia::MediaItem& rItem )
{
    if( mpMediaWindow )
    {
        ::avmedia::MediaItem aUpdatedItem;

        mpMediaWindow->executeMediaItem( rItem );

        // query new properties after trying to set the new properties
        updateMediaItem( aUpdatedItem );
        static_cast< ViewContactOfSdrMediaObj& >( GetViewContact() ).mediaPropertiesChanged( aUpdatedItem );
    }
}

} }
<|endoftext|>


<commit_before>/***************************************************************************
 *  The Kernel-Machine Library                                             *
 *  Copyright (C) 2004, 2005 by Rutger W. ter Borg                         *
 *                                                                         *
 *  This program is free software; you can redistribute it and/or          *
 *  modify it under the terms of the GNU General Public License            *
 *  as published by the Free Software Foundation; either version 2         *
 *  of the License, or (at your option) any later version.                 *
 *                                                                         *
 *  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, write to the Free Software            *
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307  *
 ***************************************************************************/

#ifndef KRLS_HPP
#define KRLS_HPP

// #include <online_greedy_determinate.hpp>
// #include "kernels.h"

// #include <design_matrix.hpp>

#include <boost/numeric/bindings/traits/ublas_matrix.hpp>
#include <boost/numeric/bindings/traits/ublas_symmetric.hpp>
#include <boost/numeric/bindings/traits/ublas_vector.hpp>

#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/bindings/atlas/cblas.hpp>
#include <kml/kernel_machine.hpp>
#include <kml/regression.hpp>
#include <kml/symmetric_view.hpp>

namespace atlas = boost::numeric::bindings::atlas;

namespace kml {

/*!
\brief Kernel Recursive Least Squares

A preprocessing step is taken to absorb the bias term into the weight vector w, by
redefining w as (w^T, b)^T and \f$\phi\f$ as (phi^T,1)^T. For details, see Engel et al,
Sparse Online Greedy Support Vector Regression, below on page 3:
\f$k(x,x')=k(x,x') + \lambda^2\f$, where \f$\lambda\f$ is a small, positive constant.

\section bibliography References
-# Engel et al., 2003. Kernel Recursive Least Squares.
*/

template< typename Problem, typename Kernel, typename PropertyMap, class Enable = void>
class krls: public kernel_machine< Problem, Kernel, PropertyMap > {};

template< typename Problem, typename Kernel, typename PropertyMap >
class krls< Problem, Kernel, PropertyMap, typename boost::enable_if< is_regression<Problem> >::type>:
         public kernel_machine< Problem, Kernel, PropertyMap > {

	typedef kernel_machine< Problem, Kernel, PropertyMap > base_type;
    typedef typename base_type::kernel_type kernel_type;
    typedef double scalar_type;

    typedef symmetric_view< ublas::matrix<double> > symmetric_type;

    typedef ublas::matrix<double> matrix_type;
    typedef ublas::vector<double> vector_type;

    typedef typename Problem::input_type input_type;
    typedef typename Problem::output_type output_type;

	typedef typename boost::property_traits<PropertyMap>::key_type key_type;
	typedef typename boost::property_traits<PropertyMap>::value_type object_type;

public:
    krls( scalar_type n, scalar_type l,
    		typename boost::call_traits<kernel_type>::param_type k,
        	typename boost::call_traits<PropertyMap>::param_type map ):
            base_type(k,map), nu(n), lambda_squared(l*l) {}

    template< typename TokenIterator >
    krls( TokenIterator const begin, TokenIterator const end,
         typename boost::call_traits<kernel_type>::param_type k,
         typename boost::call_traits<PropertyMap>::param_type map ):
		base_type(k,map) {
		nu = 1e-1;						// default value
		scalar_type lambda=1e-3;		// default value
		TokenIterator token(begin);
		if ( token != end ) {
			nu = boost::lexical_cast<double>( *token++ );
			if ( token != end ) lambda = boost::lexical_cast<double>( *token );
		}
		lambda_squared=lambda*lambda;
	}

    output_type operator()( input_type const &x ) {

		vector_type temp_K( base_type::key_lookup.size() );
		base_type::fill_kernel( x, base_type::key_lookup.begin(), base_type::key_lookup.end(), temp_K.begin() );
		for( int i=0; i < temp_K.size(); ++i )
           temp_K[i] += lambda_squared;
        return atlas::dot( base_type::weight, temp_K );

    }

   /*! learn the entire range of keys indicated by this range */
    template<typename KeyIterator>
    void learn( KeyIterator begin, KeyIterator end ) {
		KeyIterator key_iterator(begin);
		while( key_iterator != end ) {
			increment( *key_iterator );
			++key_iterator;
		}
    }

    /*! \param key key of example in data */
    void increment( key_type const &key ) {

	    //std::cout << "running key " << key << " through KRLS... " << std::endl;

		// calculate the base_type::kernel function on (x_t,x_t), needed later on
        scalar_type k_tt = base_type::kernel( key, key ) + lambda_squared;

        // check whether dictionary is still not initialised
        if ( base_type::key_lookup.empty() ) {

	    	// there is no dictionary yet, so initialise all variables
            // resize the matrix K, its inverse R and matrix P to 1 x 1
            K.grow_row_column();
            R.grow_row_column();
            P.grow_row_column();

            // and use values as stated in the paper
            K.matrix(0,0) = k_tt;
            R.matrix(0,0) = 1.0 / k_tt;
            P.matrix(0,0) = 1.0;

            // add to weight vector
		    base_type::weight.push_back( (*base_type::data)[key].second / k_tt );

            // add to support vector set
            base_type::key_lookup.push_back( key );

        } else {

            // KRLS already initialised, continue
            vector_type a_t( K.size1() );
            vector_type k_t( K.size1() );

		    // fill vector k_t
		    base_type::fill_kernel( key, base_type::key_lookup.begin(), base_type::key_lookup.end(), k_t.begin() );
		    for( int i=0; i<k_t.size(); ++i ) k_t[i] += lambda_squared;

			// a_t <- R %*% k_t
            ublas::matrix_range< ublas::matrix<double> > R_range( R.view() );
            ublas::symmetric_adaptor< ublas::matrix_range< ublas::matrix<double> > > R_view( R_range );
            atlas::symv( R_view, k_t, a_t );
            scalar_type delta_t = k_tt - atlas::dot( k_t, a_t );

            // Perform Approximate Linear Dependency (ALD) test
            if (delta_t > nu) {

                // add x_t to support vector set, adjust all needed variables
                unsigned int old_size = base_type::key_lookup.size();
                unsigned int new_size = old_size + 1;

				// update K (equation 14)
                // fetch a view into the last row of the matrix of the _old_ size
				K.grow_row_column();
 			    ublas::matrix_vector_slice< ublas::matrix<double> > K_row_part( K.shrinked_row(old_size) );
 			    atlas::copy( k_t, K_row_part );
                K.matrix( old_size, old_size ) = k_tt;

                // update R (equation 14)
                scalar_type factor = static_cast<scalar_type>(1) / delta_t;
                atlas::syr( factor, a_t, R_view );
                R.grow_row_column();
			    ublas::matrix_vector_slice< ublas::matrix<double> > R_row_part( R.shrinked_row(old_size) );
                atlas::scal( -factor, a_t );
                R_row_part.assign( a_t );
                R.matrix( old_size, old_size ) = factor;

                // update P (equation 15)
                // assign unit vector with 1 on last element.
                P.grow_row_column();
				ublas::matrix_vector_slice< ublas::matrix<double> > P_row_part( P.shrinked_row(old_size) );
				atlas::set(  0.0, P_row_part );
				P.matrix( old_size, old_size ) = 1.0;

                // adjust weight vector alpha (equation 16)
                factor = (*base_type::data)[key].second - atlas::dot(k_t,base_type::weight);
                atlas::axpy( factor, a_t, base_type::weight );

				// add new weight to the weight vector
                base_type::weight.push_back( factor / delta_t );

                // add support vector to the set
	        	base_type::key_lookup.push_back( key );

            } else {
                // support vector set unchanged (see algorithmic on page 4 of paper)
                // adjust weight vector and permutation matrix P
                // P_a <- P_t-1 %*% a_t
                vector_type P_a( base_type::key_lookup.size() );

                // spmv(A,x,y)       y <- A x
    	        ublas::matrix_range< ublas::matrix<double> > P_range( P.view() );
	            ublas::symmetric_adaptor< ublas::matrix_range< ublas::matrix<double> > > P_view( P_range );
                atlas::symv( P_view, a_t, P_a );

                // 1 / (1 + a_t %*% P_(t-1) %*% a)
                scalar_type factor = 1.0 / (1.0 + atlas::dot( a_t, P_a ));

                // update weights (equation 13)
                atlas::symv( factor* (*base_type::data)[key].second - atlas::dot(k_t,base_type::weight),
                			 R_view, P_a, static_cast<scalar_type>(1), base_type::weight );

                // update permutation matrix (equation 14)
                atlas::syr( -factor, P_a, P_view );
			}
        }
    }

private:

    symmetric_type K;                // kernel matrix K
    symmetric_type R;                // inverse of kernel matrix K
    symmetric_type P;                // permutation matrix P
    scalar_type nu;                  // ALD parameter
    scalar_type lambda_squared;      // kernel function addition
};

} // namespace kml

#endif

<commit_msg>removed an unused variable in krls.hpp<commit_after>/***************************************************************************
 *  The Kernel-Machine Library                                             *
 *  Copyright (C) 2004, 2005 by Rutger W. ter Borg                         *
 *                                                                         *
 *  This program is free software; you can redistribute it and/or          *
 *  modify it under the terms of the GNU General Public License            *
 *  as published by the Free Software Foundation; either version 2         *
 *  of the License, or (at your option) any later version.                 *
 *                                                                         *
 *  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, write to the Free Software            *
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307  *
 ***************************************************************************/

#ifndef KRLS_HPP
#define KRLS_HPP

// #include <online_greedy_determinate.hpp>
// #include "kernels.h"

// #include <design_matrix.hpp>

#include <boost/numeric/bindings/traits/ublas_matrix.hpp>
#include <boost/numeric/bindings/traits/ublas_symmetric.hpp>
#include <boost/numeric/bindings/traits/ublas_vector.hpp>

#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/bindings/atlas/cblas.hpp>
#include <kml/kernel_machine.hpp>
#include <kml/regression.hpp>
#include <kml/symmetric_view.hpp>

namespace atlas = boost::numeric::bindings::atlas;

namespace kml {

/*!
\brief Kernel Recursive Least Squares

A preprocessing step is taken to absorb the bias term into the weight vector w, by
redefining w as (w^T, b)^T and \f$\phi\f$ as (phi^T,1)^T. For details, see Engel et al,
Sparse Online Greedy Support Vector Regression, below on page 3:
\f$k(x,x')=k(x,x') + \lambda^2\f$, where \f$\lambda\f$ is a small, positive constant.

\section bibliography References
-# Engel et al., 2003. Kernel Recursive Least Squares.
*/

template< typename Problem, typename Kernel, typename PropertyMap, class Enable = void>
class krls: public kernel_machine< Problem, Kernel, PropertyMap > {};

template< typename Problem, typename Kernel, typename PropertyMap >
class krls< Problem, Kernel, PropertyMap, typename boost::enable_if< is_regression<Problem> >::type>:
         public kernel_machine< Problem, Kernel, PropertyMap > {

	typedef kernel_machine< Problem, Kernel, PropertyMap > base_type;
    typedef typename base_type::kernel_type kernel_type;
    typedef double scalar_type;

    typedef symmetric_view< ublas::matrix<double> > symmetric_type;

    typedef ublas::matrix<double> matrix_type;
    typedef ublas::vector<double> vector_type;

    typedef typename Problem::input_type input_type;
    typedef typename Problem::output_type output_type;

	typedef typename boost::property_traits<PropertyMap>::key_type key_type;
	typedef typename boost::property_traits<PropertyMap>::value_type object_type;

public:
    krls( scalar_type n, scalar_type l,
    		typename boost::call_traits<kernel_type>::param_type k,
        	typename boost::call_traits<PropertyMap>::param_type map ):
            base_type(k,map), nu(n), lambda_squared(l*l) {}

    template< typename TokenIterator >
    krls( TokenIterator const begin, TokenIterator const end,
         typename boost::call_traits<kernel_type>::param_type k,
         typename boost::call_traits<PropertyMap>::param_type map ):
		base_type(k,map) {
		nu = 1e-1;						// default value
		scalar_type lambda=1e-3;		// default value
		TokenIterator token(begin);
		if ( token != end ) {
			nu = boost::lexical_cast<double>( *token++ );
			if ( token != end ) lambda = boost::lexical_cast<double>( *token );
		}
		lambda_squared=lambda*lambda;
	}

    output_type operator()( input_type const &x ) {

		vector_type temp_K( base_type::key_lookup.size() );
		base_type::fill_kernel( x, base_type::key_lookup.begin(), base_type::key_lookup.end(), temp_K.begin() );
		for( int i=0; i < temp_K.size(); ++i )
           temp_K[i] += lambda_squared;
        return atlas::dot( base_type::weight, temp_K );

    }

   /*! learn the entire range of keys indicated by this range */
    template<typename KeyIterator>
    void learn( KeyIterator begin, KeyIterator end ) {
		KeyIterator key_iterator(begin);
		while( key_iterator != end ) {
			increment( *key_iterator );
			++key_iterator;
		}
    }

    /*! \param key key of example in data */
    void increment( key_type const &key ) {

	    //std::cout << "running key " << key << " through KRLS... " << std::endl;

		// calculate the base_type::kernel function on (x_t,x_t), needed later on
        scalar_type k_tt = base_type::kernel( key, key ) + lambda_squared;

        // check whether dictionary is still not initialised
        if ( base_type::key_lookup.empty() ) {

	    	// there is no dictionary yet, so initialise all variables
            // resize the matrix K, its inverse R and matrix P to 1 x 1
            K.grow_row_column();
            R.grow_row_column();
            P.grow_row_column();

            // and use values as stated in the paper
            K.matrix(0,0) = k_tt;
            R.matrix(0,0) = 1.0 / k_tt;
            P.matrix(0,0) = 1.0;

            // add to weight vector
		    base_type::weight.push_back( (*base_type::data)[key].second / k_tt );

            // add to support vector set
            base_type::key_lookup.push_back( key );

        } else {

            // KRLS already initialised, continue
            vector_type a_t( K.size1() );
            vector_type k_t( K.size1() );

		    // fill vector k_t
		    base_type::fill_kernel( key, base_type::key_lookup.begin(), base_type::key_lookup.end(), k_t.begin() );
		    for( int i=0; i<k_t.size(); ++i ) k_t[i] += lambda_squared;

			// a_t <- R %*% k_t
            ublas::matrix_range< ublas::matrix<double> > R_range( R.view() );
            ublas::symmetric_adaptor< ublas::matrix_range< ublas::matrix<double> > > R_view( R_range );
            atlas::symv( R_view, k_t, a_t );
            scalar_type delta_t = k_tt - atlas::dot( k_t, a_t );

            // Perform Approximate Linear Dependency (ALD) test
            if (delta_t > nu) {

                // add x_t to support vector set, adjust all needed variables
                unsigned int old_size = base_type::key_lookup.size();

		// update K (equation 14)
                // fetch a view into the last row of the matrix of the _old_ size
				K.grow_row_column();
 			    ublas::matrix_vector_slice< ublas::matrix<double> > K_row_part( K.shrinked_row(old_size) );
 			    atlas::copy( k_t, K_row_part );
                K.matrix( old_size, old_size ) = k_tt;

                // update R (equation 14)
                scalar_type factor = static_cast<scalar_type>(1) / delta_t;
                atlas::syr( factor, a_t, R_view );
                R.grow_row_column();
			    ublas::matrix_vector_slice< ublas::matrix<double> > R_row_part( R.shrinked_row(old_size) );
                atlas::scal( -factor, a_t );
                R_row_part.assign( a_t );
                R.matrix( old_size, old_size ) = factor;

                // update P (equation 15)
                // assign unit vector with 1 on last element.
                P.grow_row_column();
				ublas::matrix_vector_slice< ublas::matrix<double> > P_row_part( P.shrinked_row(old_size) );
				atlas::set(  0.0, P_row_part );
				P.matrix( old_size, old_size ) = 1.0;

                // adjust weight vector alpha (equation 16)
                factor = (*base_type::data)[key].second - atlas::dot(k_t,base_type::weight);
                atlas::axpy( factor, a_t, base_type::weight );

				// add new weight to the weight vector
                base_type::weight.push_back( factor / delta_t );

                // add support vector to the set
	        	base_type::key_lookup.push_back( key );

            } else {
                // support vector set unchanged (see algorithmic on page 4 of paper)
                // adjust weight vector and permutation matrix P
                // P_a <- P_t-1 %*% a_t
                vector_type P_a( base_type::key_lookup.size() );

                // spmv(A,x,y)       y <- A x
    	        ublas::matrix_range< ublas::matrix<double> > P_range( P.view() );
	            ublas::symmetric_adaptor< ublas::matrix_range< ublas::matrix<double> > > P_view( P_range );
                atlas::symv( P_view, a_t, P_a );

                // 1 / (1 + a_t %*% P_(t-1) %*% a)
                scalar_type factor = 1.0 / (1.0 + atlas::dot( a_t, P_a ));

                // update weights (equation 13)
                atlas::symv( factor* (*base_type::data)[key].second - atlas::dot(k_t,base_type::weight),
                			 R_view, P_a, static_cast<scalar_type>(1), base_type::weight );

                // update permutation matrix (equation 14)
                atlas::syr( -factor, P_a, P_view );
			}
        }
    }

private:

    symmetric_type K;                // kernel matrix K
    symmetric_type R;                // inverse of kernel matrix K
    symmetric_type P;                // permutation matrix P
    scalar_type nu;                  // ALD parameter
    scalar_type lambda_squared;      // kernel function addition
};

} // namespace kml

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xiroot.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2003-05-21 07:59:10 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "filt_pch.hxx"
#endif
#pragma hdrstop

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

#ifndef SC_XIROOT_HXX
#include "xiroot.hxx"
#endif

#ifndef SC_ADDINCOL_HXX
#include "addincol.hxx"
#endif

#ifndef SC_XILINK_HXX
#include "xilink.hxx"
#endif
#ifndef SC_XISTYLE_HXX
#include "xistyle.hxx"
#endif
#ifndef SC_XICONTENT_HXX
#include "xicontent.hxx"
#endif
#ifndef SC_XIESCHER_HXX
#include "xiescher.hxx"
#endif

#include "root.hxx"

// Global data ================================================================

XclImpRootData::XclImpRootData( XclBiff eBiff, ScDocument& rDocument, const String& rBasePath, CharSet eCharSet ) :
    XclRootData( eBiff, rDocument, rBasePath, eCharSet )
{
}

XclImpRootData::~XclImpRootData()
{
}

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

XclImpRoot::XclImpRoot( XclImpRootData& rImpRootData ) :
    XclRoot( rImpRootData ),
    mrImpData( rImpRootData )
{
    mrImpData.mpPalette.reset( new XclImpPalette( GetRoot() ) );
    mrImpData.mpFontBuffer.reset( new XclImpFontBuffer( GetRoot() ) );
    mrImpData.mpNumFmtBuffer.reset( new XclImpNumFmtBuffer( GetRoot() ) );
    mrImpData.mpXFBuffer.reset( new XclImpXFBuffer( GetRoot() ) );
    mrImpData.mpXFIndexBuffer.reset( new XclImpXFIndexBuffer( GetRoot() ) );
    mrImpData.mpTabIdBuffer.reset( new XclImpTabIdBuffer );
    mrImpData.mpLinkManager.reset( new XclImpLinkManager( GetRoot() ) );
}

XclImpRoot::XclImpRoot( const XclImpRoot& rRoot ) :
    XclRoot( rRoot ),
    mrImpData( rRoot.mrImpData )
{
}

XclImpRoot& XclImpRoot::operator=( const XclImpRoot& rRoot )
{
    XclRoot::operator=( rRoot );
    return *this;
}

void XclImpRoot::SetBiff( XclBiff eBiff )
{
    XclRoot::SetBiff( eBiff );
    GetPalette().OnChangeBiff();
}

XclImpSst& XclImpRoot::GetSst() const
{
    if( !mrImpData.mpSst.get() )
        mrImpData.mpSst.reset( new XclImpSst( GetRoot() ) );
    return *mrImpData.mpSst;
}

XclImpPalette& XclImpRoot::GetPalette() const
{
    return *mrImpData.mpPalette;
}

XclImpFontBuffer& XclImpRoot::GetFontBuffer() const
{
    return *mrImpData.mpFontBuffer;
}

XclImpNumFmtBuffer& XclImpRoot::GetNumFmtBuffer() const
{
    return *mrImpData.mpNumFmtBuffer;
}

XclImpXFBuffer& XclImpRoot::GetXFBuffer() const
{
    return *mrImpData.mpXFBuffer;
}

XclImpXFIndexBuffer& XclImpRoot::GetXFIndexBuffer() const
{
    return *mrImpData.mpXFIndexBuffer;
}

XclImpTabIdBuffer& XclImpRoot::GetTabIdBuffer() const
{
    return *mrImpData.mpTabIdBuffer;
}

XclImpLinkManager& XclImpRoot::GetLinkManager() const
{
    return *mrImpData.mpLinkManager;
}

XclImpObjectManager& XclImpRoot::GetObjectManager() const
{
    if( !mrImpData.mpObjManager.get() )
        mrImpData.mpObjManager.reset( new XclImpObjectManager( GetRoot() ) );
    return *mrImpData.mpObjManager;
}

XclImpWebQueryBuffer& XclImpRoot::GetWebQueryBuffer() const
{
    if( !mrImpData.mpWebQBuffer.get() )
        mrImpData.mpWebQBuffer.reset( new XclImpWebQueryBuffer( GetRoot() ) );
    return *mrImpData.mpWebQBuffer;
}

ExcelToSc& XclImpRoot::GetFmlaConverter() const
{
    return *mpRD->pFmlaConverter;
}

String XclImpRoot::GetScAddInName( const String& rXclName ) const
{
    String aScName;
    if( ScGlobal::GetAddInCollection()->GetCalcName( rXclName, aScName ) )
        return aScName;
    return rXclName;
}

bool XclImpRoot::CheckCellAddress( const ScAddress& rPos ) const
{
    return XclRoot::CheckCellAddress( rPos, GetScMaxPos() );
}

bool XclImpRoot::CheckCellRange( ScRange& rRange ) const
{
    return XclRoot::CheckCellRange( rRange, GetScMaxPos() );
}

void XclImpRoot::CheckCellRangeList( ScRangeList& rRanges ) const
{
    XclRoot::CheckCellRangeList( rRanges, GetScMaxPos() );
}

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

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

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

#ifndef SC_XIROOT_HXX
#include "xiroot.hxx"
#endif

#ifndef SC_ADDINCOL_HXX
#include "addincol.hxx"
#endif

#ifndef SC_XLTRACER_HXX
#include "xltracer.hxx"
#endif
#ifndef SC_XILINK_HXX
#include "xilink.hxx"
#endif
#ifndef SC_XISTYLE_HXX
#include "xistyle.hxx"
#endif
#ifndef SC_XICONTENT_HXX
#include "xicontent.hxx"
#endif
#ifndef SC_XIESCHER_HXX
#include "xiescher.hxx"
#endif

#include "root.hxx"

// Global data ================================================================

XclImpRootData::XclImpRootData( XclBiff eBiff, ScDocument& rDocument, const String& rDocUrl, CharSet eCharSet ) :
    XclRootData( eBiff, rDocument, rDocUrl, eCharSet )
{
}

XclImpRootData::~XclImpRootData()
{
}

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

XclImpRoot::XclImpRoot( XclImpRootData& rImpRootData ) :
    XclRoot( rImpRootData ),
    mrImpData( rImpRootData )
{
    mrImpData.mpTracer.reset( new XclTracer( GetDocUrl(), CREATE_OUSTRING( "Office.Tracing/Import/Excel" ) ) );
    mrImpData.mpPalette.reset( new XclImpPalette( GetRoot() ) );
    mrImpData.mpFontBuffer.reset( new XclImpFontBuffer( GetRoot() ) );
    mrImpData.mpNumFmtBuffer.reset( new XclImpNumFmtBuffer( GetRoot() ) );
    mrImpData.mpXFBuffer.reset( new XclImpXFBuffer( GetRoot() ) );
    mrImpData.mpXFIndexBuffer.reset( new XclImpXFIndexBuffer( GetRoot() ) );
    mrImpData.mpTabIdBuffer.reset( new XclImpTabIdBuffer );
    mrImpData.mpLinkManager.reset( new XclImpLinkManager( GetRoot() ) );
}

XclImpRoot::XclImpRoot( const XclImpRoot& rRoot ) :
    XclRoot( rRoot ),
    mrImpData( rRoot.mrImpData )
{
}

XclImpRoot& XclImpRoot::operator=( const XclImpRoot& rRoot )
{
    XclRoot::operator=( rRoot );
    return *this;
}

void XclImpRoot::SetBiff( XclBiff eBiff )
{
    XclRoot::SetBiff( eBiff );
    GetPalette().OnChangeBiff();
}

XclImpSst& XclImpRoot::GetSst() const
{
    if( !mrImpData.mpSst.get() )
        mrImpData.mpSst.reset( new XclImpSst( GetRoot() ) );
    return *mrImpData.mpSst;
}

XclImpPalette& XclImpRoot::GetPalette() const
{
    return *mrImpData.mpPalette;
}

XclImpFontBuffer& XclImpRoot::GetFontBuffer() const
{
    return *mrImpData.mpFontBuffer;
}

XclImpNumFmtBuffer& XclImpRoot::GetNumFmtBuffer() const
{
    return *mrImpData.mpNumFmtBuffer;
}

XclImpXFBuffer& XclImpRoot::GetXFBuffer() const
{
    return *mrImpData.mpXFBuffer;
}

XclImpXFIndexBuffer& XclImpRoot::GetXFIndexBuffer() const
{
    return *mrImpData.mpXFIndexBuffer;
}

XclImpTabIdBuffer& XclImpRoot::GetTabIdBuffer() const
{
    return *mrImpData.mpTabIdBuffer;
}

XclImpLinkManager& XclImpRoot::GetLinkManager() const
{
    return *mrImpData.mpLinkManager;
}

XclImpObjectManager& XclImpRoot::GetObjectManager() const
{
    if( !mrImpData.mpObjManager.get() )
        mrImpData.mpObjManager.reset( new XclImpObjectManager( GetRoot() ) );
    return *mrImpData.mpObjManager;
}

XclImpWebQueryBuffer& XclImpRoot::GetWebQueryBuffer() const
{
    if( !mrImpData.mpWebQBuffer.get() )
        mrImpData.mpWebQBuffer.reset( new XclImpWebQueryBuffer( GetRoot() ) );
    return *mrImpData.mpWebQBuffer;
}

ExcelToSc& XclImpRoot::GetFmlaConverter() const
{
    return *mpRD->pFmlaConverter;
}

String XclImpRoot::GetScAddInName( const String& rXclName ) const
{
    String aScName;
    if( ScGlobal::GetAddInCollection()->GetCalcName( rXclName, aScName ) )
        return aScName;
    return rXclName;
}

bool XclImpRoot::CheckCellAddress( const ScAddress& rPos ) const
{
    return XclRoot::CheckCellAddress( rPos, GetScMaxPos() );
}

bool XclImpRoot::CheckCellRange( ScRange& rRange ) const
{
    return XclRoot::CheckCellRange( rRange, GetScMaxPos() );
}

void XclImpRoot::CheckCellRangeList( ScRangeList& rRanges ) const
{
    XclRoot::CheckCellRangeList( rRanges, GetScMaxPos() );
}

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

<|endoftext|>