<commit_before>#include "./window.h"
#include <QOpenGLContext>
#include <QOpenGLDebugLogger>
#include <QDebug>
#include <QCoreApplication>
#include <QKeyEvent>
#include <QStateMachine>
#include <QAbstractState>
#include <QAbstractTransition>
#include <QLoggingCategory>
#include <iostream>
#include "./graphics/gl.h"
#include "./abstract_scene.h"

QLoggingCategory openGlChan("OpenGl");

Window::Window(std::shared_ptr<AbstractScene> scene, QWindow *parent)
  : QQuickView(parent), scene(scene)
{
  setClearBeforeRendering(false);

  connect(this, SIGNAL(widthChanged(int)), this, SLOT(resizeOpenGL()));
  connect(this, SIGNAL(heightChanged(int)), this, SLOT(resizeOpenGL()));

  connect(reinterpret_cast<QObject *>(engine()), SIGNAL(quit()), this,
          SLOT(close()));

  connect(this, SIGNAL(beforeRendering()), this, SLOT(render()),
          Qt::DirectConnection);

  auto format = createSurfaceFormat();
  setFormat(format);

  timer.start();
}

Window::~Window()
{
  delete gl;
  if (logger)
    delete logger;
}

QSurfaceFormat Window::createSurfaceFormat()
{
  QSurfaceFormat format;
  format.setDepthBufferSize(24);
  format.setMajorVersion(4);
  format.setMinorVersion(5);
  format.setSamples(4);
  format.setOption(QSurfaceFormat::DebugContext);

  return format;
}

void Window::initializeOpenGL()
{
  context = openglContext();
  gl = new Graphics::Gl();
  gl->initialize(context, size());

  logger = new QOpenGLDebugLogger();

  connect(logger, &QOpenGLDebugLogger::messageLogged, this,
          &Window::onMessageLogged, Qt::DirectConnection);

  if (logger->initialize())
  {
    logger->startLogging(QOpenGLDebugLogger::SynchronousLogging);
    logger->enableMessages();
  }

  glAssert(gl->glDisable(GL_CULL_FACE));
  glAssert(gl->glDisable(GL_DEPTH_TEST));
  glAssert(gl->glDisable(GL_STENCIL_TEST));
  glAssert(gl->glDisable(GL_BLEND));
  glAssert(gl->glDepthMask(GL_FALSE));
}

void Window::keyReleaseEvent(QKeyEvent *event)
{
  QQuickView::keyReleaseEvent(event);
  keysPressed -= static_cast<Qt::Key>(event->key());
}

void Window::keyPressEvent(QKeyEvent *event)
{
  QQuickView::keyPressEvent(event);
  keysPressed += static_cast<Qt::Key>(event->key());
}

void Window::handleLazyInitialization()
{
  static bool initialized = false;
  if (!initialized)
  {
    initializeOpenGL();

    scene->setContext(context, gl);
    scene->resize(size().width(), size().height());
    scene->initialize();
    initialized = true;
  }
}

void Window::render()
{
  handleLazyInitialization();

  update();
  scene->render();

  // Use to check for missing release calls
  // resetOpenGLState();

  QQuickView::update();
}

void Window::resizeOpenGL()
{
  if (!gl)
    return;

  scene->resize(width(), height());
  gl->setSize(this->size());
}

void Window::update()
{
  double frameTime = timer.restart() / 1000.0;
  updateAverageFrameTime(frameTime);

  scene->update(frameTime, keysPressed);
}

void Window::toggleFullscreen()
{
  setVisibility(visibility() == QWindow::Windowed ? QWindow::FullScreen
                                                  : QWindow::Windowed);
}

void Window::updateAverageFrameTime(double frameTime)
{
  runningTime += frameTime;
  ++framesInSecond;

  if (runningTime > 1.0)
  {
    avgFrameTime = runningTime / framesInSecond;
    emit averageFrameTimeUpdated();

    framesInSecond = 0;
    runningTime = 0;
  }
}

void Window::onMessageLogged(QOpenGLDebugMessage message)
{
  switch (message.severity())
  {
  case QOpenGLDebugMessage::Severity::NotificationSeverity:
    qCInfo(openGlChan) << message;
    break;

  case QOpenGLDebugMessage::Severity::LowSeverity:
    qCDebug(openGlChan) << message;
    break;
  case QOpenGLDebugMessage::Severity::MediumSeverity:
    qCWarning(openGlChan) << message;
    break;
  case QOpenGLDebugMessage::Severity::HighSeverity:
    qCCritical(openGlChan) << message;
    break;
  default:
    return;
  }
}

<commit_msg>Ignore some messages.<commit_after>#include "./window.h"
#include <QOpenGLContext>
#include <QOpenGLDebugLogger>
#include <QDebug>
#include <QCoreApplication>
#include <QKeyEvent>
#include <QStateMachine>
#include <QAbstractState>
#include <QAbstractTransition>
#include <QLoggingCategory>
#include <iostream>
#include "./graphics/gl.h"
#include "./abstract_scene.h"

QLoggingCategory openGlChan("OpenGl");

Window::Window(std::shared_ptr<AbstractScene> scene, QWindow *parent)
  : QQuickView(parent), scene(scene)
{
  setClearBeforeRendering(false);

  connect(this, SIGNAL(widthChanged(int)), this, SLOT(resizeOpenGL()));
  connect(this, SIGNAL(heightChanged(int)), this, SLOT(resizeOpenGL()));

  connect(reinterpret_cast<QObject *>(engine()), SIGNAL(quit()), this,
          SLOT(close()));

  connect(this, SIGNAL(beforeRendering()), this, SLOT(render()),
          Qt::DirectConnection);

  auto format = createSurfaceFormat();
  setFormat(format);

  timer.start();
}

Window::~Window()
{
  delete gl;
  if (logger)
    delete logger;
}

QSurfaceFormat Window::createSurfaceFormat()
{
  QSurfaceFormat format;
  format.setDepthBufferSize(24);
  format.setMajorVersion(4);
  format.setMinorVersion(5);
  format.setSamples(4);
  format.setOption(QSurfaceFormat::DebugContext);

  return format;
}

void Window::initializeOpenGL()
{
  context = openglContext();
  gl = new Graphics::Gl();
  gl->initialize(context, size());

  logger = new QOpenGLDebugLogger();

  connect(logger, &QOpenGLDebugLogger::messageLogged, this,
          &Window::onMessageLogged, Qt::DirectConnection);

  if (logger->initialize())
  {
    logger->startLogging(QOpenGLDebugLogger::SynchronousLogging);
    logger->enableMessages();
  }

  glAssert(gl->glDisable(GL_CULL_FACE));
  glAssert(gl->glDisable(GL_DEPTH_TEST));
  glAssert(gl->glDisable(GL_STENCIL_TEST));
  glAssert(gl->glDisable(GL_BLEND));
  glAssert(gl->glDepthMask(GL_FALSE));
}

void Window::keyReleaseEvent(QKeyEvent *event)
{
  QQuickView::keyReleaseEvent(event);
  keysPressed -= static_cast<Qt::Key>(event->key());
}

void Window::keyPressEvent(QKeyEvent *event)
{
  QQuickView::keyPressEvent(event);
  keysPressed += static_cast<Qt::Key>(event->key());
}

void Window::handleLazyInitialization()
{
  static bool initialized = false;
  if (!initialized)
  {
    initializeOpenGL();

    scene->setContext(context, gl);
    scene->resize(size().width(), size().height());
    scene->initialize();
    initialized = true;
  }
}

void Window::render()
{
  handleLazyInitialization();

  update();
  scene->render();

  // Use to check for missing release calls
  // resetOpenGLState();

  QQuickView::update();
}

void Window::resizeOpenGL()
{
  if (!gl)
    return;

  scene->resize(width(), height());
  gl->setSize(this->size());
}

void Window::update()
{
  double frameTime = timer.restart() / 1000.0;
  updateAverageFrameTime(frameTime);

  scene->update(frameTime, keysPressed);
}

void Window::toggleFullscreen()
{
  setVisibility(visibility() == QWindow::Windowed ? QWindow::FullScreen
                                                  : QWindow::Windowed);
}

void Window::updateAverageFrameTime(double frameTime)
{
  runningTime += frameTime;
  ++framesInSecond;

  if (runningTime > 1.0)
  {
    avgFrameTime = runningTime / framesInSecond;
    emit averageFrameTimeUpdated();

    framesInSecond = 0;
    runningTime = 0;
  }
}

void Window::onMessageLogged(QOpenGLDebugMessage message)
{
  // Ignore buffer detailed info which cannot be fixed
  if (message.id() == 131185)
    return;

  // Ignore buffer performance warning
  if (message.id() == 131186)
    return;

  switch (message.severity())
  {
  case QOpenGLDebugMessage::Severity::NotificationSeverity:
    qCInfo(openGlChan) << message;
    break;

  case QOpenGLDebugMessage::Severity::LowSeverity:
    qCDebug(openGlChan) << message;
    break;
  case QOpenGLDebugMessage::Severity::MediumSeverity:
    qCWarning(openGlChan) << message;
    break;
  case QOpenGLDebugMessage::Severity::HighSeverity:
    qCCritical(openGlChan) << message;
    break;
  default:
    return;
  }
}

<|endoftext|>


<commit_before>/*
 * 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 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2012 Chiyuan Zhang
 * Copyright (C) 2012 Chiyuan Zhang
 */

#include <vector>
#include <stack>

#include <shogun/multiclass/tree/ConditionalProbabilityTree.h>
#include <shogun/classifier/svm/OnlineLibLinear.h>

using namespace shogun;
using namespace std;

CMulticlassLabels* CConditionalProbabilityTree::apply_multiclass(CFeatures* data)
{
	if (data)
	{
		if (data->get_feature_class() != C_STREAMING_DENSE)
			SG_ERROR("Expected StreamingDenseFeatures\n")
		if (data->get_feature_type() != F_SHORTREAL)
			SG_ERROR("Expected float32_t feature type\n")

		set_features(dynamic_cast<CStreamingDenseFeatures<float32_t>* >(data));
	}

	vector<int32_t> predicts;

	m_feats->start_parser();
	while (m_feats->get_next_example())
	{
		predicts.push_back(apply_multiclass_example(m_feats->get_vector()));
		m_feats->release_example();
	}
	m_feats->end_parser();

	CMulticlassLabels *labels = new CMulticlassLabels(predicts.size());
	for (size_t i=0; i < predicts.size(); ++i)
		labels->set_int_label(i, predicts[i]);
	return labels;
}

int32_t CConditionalProbabilityTree::apply_multiclass_example(SGVector<float32_t> ex)
{
	compute_conditional_probabilities(ex);
	SGVector<float64_t> probs(m_leaves.size());
	for (map<int32_t,bnode_t*>::iterator it = m_leaves.begin(); it != m_leaves.end(); ++it)
	{
		probs[it->first] = accumulate_conditional_probability(it->second);
	}
	return SGVector<float64_t>::arg_max(probs.vector, 1, probs.vlen);
}

void CConditionalProbabilityTree::compute_conditional_probabilities(SGVector<float32_t> ex)
{
	stack<bnode_t *> nodes;
	nodes.push((bnode_t*) m_root);

	while (!nodes.empty())
	{
		bnode_t *node = nodes.top();
		nodes.pop();
		if (node->left())
		{
			nodes.push(node->left());
			nodes.push(node->right());

			// don't calculate for leaf
			node->data.p_right = predict_node(ex, node);
		}
	}
}

float64_t CConditionalProbabilityTree::accumulate_conditional_probability(bnode_t *leaf)
{
	float64_t prob = 1;
	bnode_t *par = (bnode_t*) leaf->parent();
	while (par != NULL)
	{
		if (leaf == par->left())
			prob *= (1-par->data.p_right);
		else
			prob *= par->data.p_right;

		leaf = par;
		par = (bnode_t*) leaf->parent();
	}

	return prob;
}

bool CConditionalProbabilityTree::train_machine(CFeatures* data)
{
	if (data)
	{
		if (data->get_feature_class() != C_STREAMING_DENSE)
			SG_ERROR("Expected StreamingDenseFeatures\n")
		if (data->get_feature_type() != F_SHORTREAL)
			SG_ERROR("Expected float32_t features\n")
		set_features(dynamic_cast<CStreamingDenseFeatures<float32_t> *>(data));
	}
	else
	{
		if (!m_feats)
			SG_ERROR("No data features provided\n")
	}

	m_machines->reset_array();
	SG_UNREF(m_root);
	m_root = NULL;

	m_leaves.clear();

	m_feats->start_parser();
	for (int32_t ipass=0; ipass < m_num_passes; ++ipass)
	{
		while (m_feats->get_next_example())
		{
			train_example(m_feats->get_vector(), static_cast<int32_t>(m_feats->get_label()));
			m_feats->release_example();
		}

		if (ipass < m_num_passes-1)
			m_feats->reset_stream();
	}
	m_feats->end_parser();

	for (int32_t i=0; i < m_machines->get_num_elements(); ++i)
	{
		COnlineLibLinear *lll = dynamic_cast<COnlineLibLinear *>(m_machines->get_element(i));
		lll->stop_train();
		SG_UNREF(lll);
	}

	return true;
}

void CConditionalProbabilityTree::print_tree()
{
	if (m_root)
		m_root->debug_print(ConditionalProbabilityTreeNodeData::print_data);
	else
		printf("Empty Tree\n");
}

void CConditionalProbabilityTree::train_example(SGVector<float32_t> ex, int32_t label)
{
	if (m_root == NULL)
	{
		m_root = new bnode_t();
		m_root->data.label = label;
		m_leaves.insert(make_pair(label, (bnode_t*) m_root));
		m_root->machine(create_machine(ex));
		return;
	}

	if (m_leaves.find(label) != m_leaves.end())
	{
		train_path(ex, m_leaves[label]);
	}
	else
	{
		bnode_t *node = (bnode_t*) m_root;
		while (node->left() != NULL)
		{
			// not a leaf
			bool is_left = which_subtree(node, ex);
			float64_t node_label;
			if (is_left)
				node_label = 0;
			else
				node_label = 1;
			train_node(ex, node_label, node);

			if (is_left)
				node = node->left();
			else
				node = node->right();
		}

		m_leaves.erase(node->data.label);

		bnode_t *left_node = new bnode_t();
		left_node->data.label = node->data.label;
		node->data.label = -1;
		COnlineLibLinear *node_mch = dynamic_cast<COnlineLibLinear *>(m_machines->get_element(node->machine()));
		COnlineLibLinear *mch = new COnlineLibLinear(node_mch);
		SG_UNREF(node_mch);
		mch->start_train();
		m_machines->push_back(mch);
		left_node->machine(m_machines->get_num_elements()-1);
		m_leaves.insert(make_pair(left_node->data.label, left_node));
		node->left(left_node);

		bnode_t *right_node = new bnode_t();
		right_node->data.label = label;
		right_node->machine(create_machine(ex));
		m_leaves.insert(make_pair(label, right_node));
		node->right(right_node);
	}
}

void CConditionalProbabilityTree::train_path(SGVector<float32_t> ex, bnode_t *node)
{
	float64_t node_label = 0;
	train_node(ex, node_label, node);

	bnode_t *par = (bnode_t*) node->parent();
	while (par != NULL)
	{
		if (par->left() == node)
			node_label = 0;
		else
			node_label = 1;

		train_node(ex, node_label, par);
		node = par;
		par = (bnode_t*) node->parent();
	}
}

void CConditionalProbabilityTree::train_node(SGVector<float32_t> ex, float64_t label, bnode_t *node)
{
	REQUIRE(node, "Node must not be NULL\n");
	REQUIRE(node->machine(), "Node's machine must not be NULL\n");
	COnlineLibLinear *mch = dynamic_cast<COnlineLibLinear *>(m_machines->get_element(node->machine()));
	REQUIRE(mch, "Instance of %s could not be casted to COnlineLibLinear\n", node->get_name());
	mch->train_one(ex, label);
	SG_UNREF(mch);
}

float64_t CConditionalProbabilityTree::predict_node(SGVector<float32_t> ex, bnode_t *node)
{
	REQUIRE(node, "Node must not be NULL\n");
	REQUIRE(node->machine(), "Node's machine must not be NULL\n");
	COnlineLibLinear *mch = dynamic_cast<COnlineLibLinear *>(m_machines->get_element(node->machine()));
	REQUIRE(mch, "Instance of %s could not be casted to COnlineLibLinear\n", node->get_name());
	float64_t pred = mch->apply_one(ex.vector, ex.vlen);
	SG_UNREF(mch);
	// use sigmoid function to turn the decision value into valid probability
	return 1.0/(1+CMath::exp(-pred));
}

int32_t CConditionalProbabilityTree::create_machine(SGVector<float32_t> ex)
{
	COnlineLibLinear *mch = new COnlineLibLinear();
	mch->start_train();
	mch->train_one(ex, 0);
	m_machines->push_back(mch);
	return m_machines->get_num_elements()-1;
}
<commit_msg>REQUIRE condition removed to counter travis failure<commit_after>/*
 * 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 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2012 Chiyuan Zhang
 * Copyright (C) 2012 Chiyuan Zhang
 */

#include <vector>
#include <stack>

#include <shogun/multiclass/tree/ConditionalProbabilityTree.h>
#include <shogun/classifier/svm/OnlineLibLinear.h>

using namespace shogun;
using namespace std;

CMulticlassLabels* CConditionalProbabilityTree::apply_multiclass(CFeatures* data)
{
	if (data)
	{
		if (data->get_feature_class() != C_STREAMING_DENSE)
			SG_ERROR("Expected StreamingDenseFeatures\n")
		if (data->get_feature_type() != F_SHORTREAL)
			SG_ERROR("Expected float32_t feature type\n")

		set_features(dynamic_cast<CStreamingDenseFeatures<float32_t>* >(data));
	}

	vector<int32_t> predicts;

	m_feats->start_parser();
	while (m_feats->get_next_example())
	{
		predicts.push_back(apply_multiclass_example(m_feats->get_vector()));
		m_feats->release_example();
	}
	m_feats->end_parser();

	CMulticlassLabels *labels = new CMulticlassLabels(predicts.size());
	for (size_t i=0; i < predicts.size(); ++i)
		labels->set_int_label(i, predicts[i]);
	return labels;
}

int32_t CConditionalProbabilityTree::apply_multiclass_example(SGVector<float32_t> ex)
{
	compute_conditional_probabilities(ex);
	SGVector<float64_t> probs(m_leaves.size());
	for (map<int32_t,bnode_t*>::iterator it = m_leaves.begin(); it != m_leaves.end(); ++it)
	{
		probs[it->first] = accumulate_conditional_probability(it->second);
	}
	return SGVector<float64_t>::arg_max(probs.vector, 1, probs.vlen);
}

void CConditionalProbabilityTree::compute_conditional_probabilities(SGVector<float32_t> ex)
{
	stack<bnode_t *> nodes;
	nodes.push((bnode_t*) m_root);

	while (!nodes.empty())
	{
		bnode_t *node = nodes.top();
		nodes.pop();
		if (node->left())
		{
			nodes.push(node->left());
			nodes.push(node->right());

			// don't calculate for leaf
			node->data.p_right = predict_node(ex, node);
		}
	}
}

float64_t CConditionalProbabilityTree::accumulate_conditional_probability(bnode_t *leaf)
{
	float64_t prob = 1;
	bnode_t *par = (bnode_t*) leaf->parent();
	while (par != NULL)
	{
		if (leaf == par->left())
			prob *= (1-par->data.p_right);
		else
			prob *= par->data.p_right;

		leaf = par;
		par = (bnode_t*) leaf->parent();
	}

	return prob;
}

bool CConditionalProbabilityTree::train_machine(CFeatures* data)
{
	if (data)
	{
		if (data->get_feature_class() != C_STREAMING_DENSE)
			SG_ERROR("Expected StreamingDenseFeatures\n")
		if (data->get_feature_type() != F_SHORTREAL)
			SG_ERROR("Expected float32_t features\n")
		set_features(dynamic_cast<CStreamingDenseFeatures<float32_t> *>(data));
	}
	else
	{
		if (!m_feats)
			SG_ERROR("No data features provided\n")
	}

	m_machines->reset_array();
	SG_UNREF(m_root);
	m_root = NULL;

	m_leaves.clear();

	m_feats->start_parser();
	for (int32_t ipass=0; ipass < m_num_passes; ++ipass)
	{
		while (m_feats->get_next_example())
		{
			train_example(m_feats->get_vector(), static_cast<int32_t>(m_feats->get_label()));
			m_feats->release_example();
		}

		if (ipass < m_num_passes-1)
			m_feats->reset_stream();
	}
	m_feats->end_parser();

	for (int32_t i=0; i < m_machines->get_num_elements(); ++i)
	{
		COnlineLibLinear *lll = dynamic_cast<COnlineLibLinear *>(m_machines->get_element(i));
		lll->stop_train();
		SG_UNREF(lll);
	}

	return true;
}

void CConditionalProbabilityTree::print_tree()
{
	if (m_root)
		m_root->debug_print(ConditionalProbabilityTreeNodeData::print_data);
	else
		printf("Empty Tree\n");
}

void CConditionalProbabilityTree::train_example(SGVector<float32_t> ex, int32_t label)
{
	if (m_root == NULL)
	{
		m_root = new bnode_t();
		m_root->data.label = label;
		m_leaves.insert(make_pair(label, (bnode_t*) m_root));
		m_root->machine(create_machine(ex));
		return;
	}

	if (m_leaves.find(label) != m_leaves.end())
	{
		train_path(ex, m_leaves[label]);
	}
	else
	{
		bnode_t *node = (bnode_t*) m_root;
		while (node->left() != NULL)
		{
			// not a leaf
			bool is_left = which_subtree(node, ex);
			float64_t node_label;
			if (is_left)
				node_label = 0;
			else
				node_label = 1;
			train_node(ex, node_label, node);

			if (is_left)
				node = node->left();
			else
				node = node->right();
		}

		m_leaves.erase(node->data.label);

		bnode_t *left_node = new bnode_t();
		left_node->data.label = node->data.label;
		node->data.label = -1;
		COnlineLibLinear *node_mch = dynamic_cast<COnlineLibLinear *>(m_machines->get_element(node->machine()));
		COnlineLibLinear *mch = new COnlineLibLinear(node_mch);
		SG_UNREF(node_mch);
		mch->start_train();
		m_machines->push_back(mch);
		left_node->machine(m_machines->get_num_elements()-1);
		m_leaves.insert(make_pair(left_node->data.label, left_node));
		node->left(left_node);

		bnode_t *right_node = new bnode_t();
		right_node->data.label = label;
		right_node->machine(create_machine(ex));
		m_leaves.insert(make_pair(label, right_node));
		node->right(right_node);
	}
}

void CConditionalProbabilityTree::train_path(SGVector<float32_t> ex, bnode_t *node)
{
	float64_t node_label = 0;
	train_node(ex, node_label, node);

	bnode_t *par = (bnode_t*) node->parent();
	while (par != NULL)
	{
		if (par->left() == node)
			node_label = 0;
		else
			node_label = 1;

		train_node(ex, node_label, par);
		node = par;
		par = (bnode_t*) node->parent();
	}
}

void CConditionalProbabilityTree::train_node(SGVector<float32_t> ex, float64_t label, bnode_t *node)
{
	REQUIRE(node, "Node must not be NULL\n");
	COnlineLibLinear *mch = dynamic_cast<COnlineLibLinear *>(m_machines->get_element(node->machine()));
	REQUIRE(mch, "Instance of %s could not be casted to COnlineLibLinear\n", node->get_name());
	mch->train_one(ex, label);
	SG_UNREF(mch);
}

float64_t CConditionalProbabilityTree::predict_node(SGVector<float32_t> ex, bnode_t *node)
{
	REQUIRE(node, "Node must not be NULL\n");
	COnlineLibLinear *mch = dynamic_cast<COnlineLibLinear *>(m_machines->get_element(node->machine()));
	REQUIRE(mch, "Instance of %s could not be casted to COnlineLibLinear\n", node->get_name());
	float64_t pred = mch->apply_one(ex.vector, ex.vlen);
	SG_UNREF(mch);
	// use sigmoid function to turn the decision value into valid probability
	return 1.0/(1+CMath::exp(-pred));
}

int32_t CConditionalProbabilityTree::create_machine(SGVector<float32_t> ex)
{
	COnlineLibLinear *mch = new COnlineLibLinear();
	mch->start_train();
	mch->train_one(ex, 0);
	m_machines->push_back(mch);
	return m_machines->get_num_elements()-1;
}
<|endoftext|>


<commit_before>#ifndef STAN__AGRAD__REV__OPERATORS__OPERATOR_UNARY_DECREMENT_HPP
#define STAN__AGRAD__REV__OPERATORS__OPERATOR_UNARY_DECREMENT_HPP

#include <stan/agrad/rev/var.hpp>
#include <stan/agrad/rev/internal/v_vari.hpp>

namespace stan {
  namespace agrad {

    namespace {
      class decrement_vari : public op_v_vari {
      public:
        decrement_vari(vari* avi) :
          op_v_vari(avi->val_ - 1.0, avi) {
        }
        void chain() {
          avi_->adj_ += adj_;
        }
      };
    }

    /**
     * Prefix decrement operator for variables (C++).
     *
     * Following C++, (--a) is defined to behave exactly as
     *
     * a = a - 1.0)
     *
     * does, but is faster and uses less memory.  In particular,
     * the result is an assignable lvalue.
     *
     * @param a Variable to decrement.
     * @return Reference the result of decrementing this input variable.
     */
    inline var& operator--(var& a) {
      a.vi_ = new decrement_vari(a.vi_);
      return a;
    }

    /**
     * Postfix decrement operator for variables (C++).
     *
     * Following C++, the expression (a--) is defined to
     * behave like the sequence of operations
     *
     * var temp = a;  a = a - 1.0;  return temp;
     *
     * @param a Variable to decrement.
     * @return Input variable.
     */
    inline var operator--(var& a, int /*dummy*/) {
      var temp(a);
      a.vi_ = new decrement_vari(a.vi_);
      return temp;
    }

  }
}
#endif
<commit_msg>fixed operator_unary_decrement so gradients return NaN<commit_after>#ifndef STAN__AGRAD__REV__OPERATORS__OPERATOR_UNARY_DECREMENT_HPP
#define STAN__AGRAD__REV__OPERATORS__OPERATOR_UNARY_DECREMENT_HPP

#include <stan/agrad/rev/var.hpp>
#include <stan/agrad/rev/internal/v_vari.hpp>
#include <boost/math/special_functions/fpclassify.hpp>

namespace stan {
  namespace agrad {

    namespace {
      class decrement_vari : public op_v_vari {
      public:
        decrement_vari(vari* avi) :
          op_v_vari(avi->val_ - 1.0, avi) {
        }
        void chain() {
          if (unlikely(boost::math::isnan(avi_->val_)))
            avi_->adj_ = std::numeric_limits<double>::quiet_NaN();
          else
            avi_->adj_ += adj_;
        }
      };
    }

    /**
     * Prefix decrement operator for variables (C++).
     *
     * Following C++, (--a) is defined to behave exactly as
     *
     * a = a - 1.0)
     *
     * does, but is faster and uses less memory.  In particular,
     * the result is an assignable lvalue.
     *
     * @param a Variable to decrement.
     * @return Reference the result of decrementing this input variable.
     */
    inline var& operator--(var& a) {
      a.vi_ = new decrement_vari(a.vi_);
      return a;
    }

    /**
     * Postfix decrement operator for variables (C++).
     *
     * Following C++, the expression (a--) is defined to
     * behave like the sequence of operations
     *
     * var temp = a;  a = a - 1.0;  return temp;
     *
     * @param a Variable to decrement.
     * @return Input variable.
     */
    inline var operator--(var& a, int /*dummy*/) {
      var temp(a);
      a.vi_ = new decrement_vari(a.vi_);
      return temp;
    }

  }
}
#endif
<|endoftext|>


<commit_before>{
	cout << "Bye bye" << endl;
}<commit_msg>Change comment in ucn_rootlogoff<commit_after>{
	cout << "Exiting ROOT interactive session" << endl;
}<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <fstream>
#include <set>
#include <sstream>
#include <string>

#include "perfetto/ext/base/file_utils.h"
#include "src/traced/probes/ftrace/ftrace_controller.h"
#include "src/traced/probes/ftrace/ftrace_procfs.h"
#include "test/gtest_and_gmock.h"

using testing::Contains;
using testing::HasSubstr;
using testing::IsEmpty;
using testing::Not;
using testing::UnorderedElementsAre;

namespace perfetto {
namespace {

std::string GetFtracePath() {
  size_t i = 0;
  while (!FtraceProcfs::Create(FtraceController::kTracingPaths[i])) {
    i++;
  }
  return std::string(FtraceController::kTracingPaths[i]);
}

void ResetFtrace(FtraceProcfs* ftrace) {
  ftrace->DisableAllEvents();
  ftrace->ClearTrace();
  ftrace->EnableTracing();
}

std::string ReadFile(const std::string& name) {
  std::string result;
  PERFETTO_CHECK(base::ReadFile(GetFtracePath() + name, &result));
  return result;
}

std::string GetTraceOutput() {
  std::string output = ReadFile("trace");
  if (output.empty()) {
    ADD_FAILURE() << "Could not read trace output";
  }
  return output;
}

}  // namespace

// TODO(lalitm): reenable these tests (see b/72306171).
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_CreateWithGoodPath CreateWithGoodPath
#else
#define MAYBE_CreateWithGoodPath DISABLED_CreateWithGoodPath
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_CreateWithGoodPath) {
  EXPECT_TRUE(FtraceProcfs::Create(GetFtracePath()));
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_CreateWithBadPath CreateWithBadPath
#else
#define MAYBE_CreateWithBadPath DISABLED_CreateWithBadath
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_CreateWithBadPath) {
  EXPECT_FALSE(FtraceProcfs::Create(GetFtracePath() + std::string("bad_path")));
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_ClearTrace ClearTrace
#else
#define MAYBE_ClearTrace DISABLED_ClearTrace
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_ClearTrace) {
  FtraceProcfs ftrace(GetFtracePath());
  ResetFtrace(&ftrace);
  ftrace.WriteTraceMarker("Hello, World!");
  ftrace.ClearTrace();
  EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("Hello, World!")));
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_TraceMarker TraceMarker
#else
#define MAYBE_TraceMarker DISABLED_TraceMarker
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_TraceMarker) {
  FtraceProcfs ftrace(GetFtracePath());
  ResetFtrace(&ftrace);
  ftrace.WriteTraceMarker("Hello, World!");
  EXPECT_THAT(GetTraceOutput(), HasSubstr("Hello, World!"));
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_EnableDisableEvent EnableDisableEvent
#else
#define MAYBE_EnableDisableEvent DISABLED_EnableDisableEvent
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_EnableDisableEvent) {
  FtraceProcfs ftrace(GetFtracePath());
  ResetFtrace(&ftrace);
  ftrace.EnableEvent("sched", "sched_switch");
  sleep(1);
  EXPECT_THAT(GetTraceOutput(), HasSubstr("sched_switch"));

  ftrace.DisableEvent("sched", "sched_switch");
  ftrace.ClearTrace();
  sleep(1);
  EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("sched_switch")));
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_EnableDisableTracing EnableDisableTracing
#else
#define MAYBE_EnableDisableTracing DISABLED_EnableDisableTracing
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_EnableDisableTracing) {
  FtraceProcfs ftrace(GetFtracePath());
  ResetFtrace(&ftrace);
  EXPECT_TRUE(ftrace.IsTracingEnabled());
  ftrace.WriteTraceMarker("Before");
  ftrace.DisableTracing();
  EXPECT_FALSE(ftrace.IsTracingEnabled());
  ftrace.WriteTraceMarker("During");
  ftrace.EnableTracing();
  EXPECT_TRUE(ftrace.IsTracingEnabled());
  ftrace.WriteTraceMarker("After");
  EXPECT_THAT(GetTraceOutput(), HasSubstr("Before"));
  EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("During")));
  EXPECT_THAT(GetTraceOutput(), HasSubstr("After"));
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_ReadFormatFile ReadFormatFile
#else
#define MAYBE_ReadFormatFile DISABLED_ReadFormatFile
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_ReadFormatFile) {
  FtraceProcfs ftrace(GetFtracePath());
  std::string format = ftrace.ReadEventFormat("ftrace", "print");
  EXPECT_THAT(format, HasSubstr("name: print"));
  EXPECT_THAT(format, HasSubstr("field:char buf"));
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_CanOpenTracePipeRaw CanOpenTracePipeRaw
#else
#define MAYBE_CanOpenTracePipeRaw DISABLED_CanOpenTracePipeRaw
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_CanOpenTracePipeRaw) {
  FtraceProcfs ftrace(GetFtracePath());
  EXPECT_TRUE(ftrace.OpenPipeForCpu(0));
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_Clock Clock
#else
#define MAYBE_Clock DISABLED_Clock
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_Clock) {
  FtraceProcfs ftrace(GetFtracePath());
  std::set<std::string> clocks = ftrace.AvailableClocks();
  EXPECT_THAT(clocks, Contains("local"));
  EXPECT_THAT(clocks, Contains("global"));

  EXPECT_TRUE(ftrace.SetClock("global"));
  EXPECT_EQ(ftrace.GetClock(), "global");
  EXPECT_TRUE(ftrace.SetClock("local"));
  EXPECT_EQ(ftrace.GetClock(), "local");
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_CanSetBufferSize CanSetBufferSize
#else
#define MAYBE_CanSetBufferSize DISABLED_CanSetBufferSize
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_CanSetBufferSize) {
  FtraceProcfs ftrace(GetFtracePath());
  EXPECT_TRUE(ftrace.SetCpuBufferSizeInPages(4ul));
  EXPECT_EQ(ReadFile("buffer_size_kb"), "16\n");  // (4096 * 4) / 1024
  EXPECT_TRUE(ftrace.SetCpuBufferSizeInPages(5ul));
  EXPECT_EQ(ReadFile("buffer_size_kb"), "20\n");  // (4096 * 5) / 1024
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_FtraceControllerHardReset FtraceControllerHardReset
#else
#define MAYBE_FtraceControllerHardReset DISABLED_FtraceControllerHardReset
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_FtraceControllerHardReset) {
  FtraceProcfs ftrace(GetFtracePath());
  ResetFtrace(&ftrace);

  ftrace.SetCpuBufferSizeInPages(4ul);
  ftrace.EnableTracing();
  ftrace.EnableEvent("sched", "sched_switch");
  ftrace.WriteTraceMarker("Hello, World!");

  EXPECT_EQ(ReadFile("buffer_size_kb"), "16\n");
  EXPECT_EQ(ReadFile("tracing_on"), "1\n");
  EXPECT_EQ(ReadFile("events/enable"), "X\n");
  EXPECT_THAT(GetTraceOutput(), HasSubstr("Hello"));

  HardResetFtraceState();

  EXPECT_EQ(ReadFile("buffer_size_kb"), "4\n");
  EXPECT_EQ(ReadFile("tracing_on"), "0\n");
  EXPECT_EQ(ReadFile("events/enable"), "0\n");
  EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("Hello")));
}

#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_ReadEnabledEvents ReadEnabledEvents
#else
#define MAYBE_ReadEnabledEvents DISABLED_ReadEnabledEvents
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_ReadEnabledEvents) {
  FtraceProcfs ftrace(GetFtracePath());
  ResetFtrace(&ftrace);

  EXPECT_THAT(ftrace.ReadEnabledEvents(), IsEmpty());

  ftrace.EnableEvent("sched", "sched_switch");
  ftrace.EnableEvent("kmem", "kmalloc");

  EXPECT_THAT(ftrace.ReadEnabledEvents(),
              UnorderedElementsAre("sched/sched_switch", "kmem/kmalloc"));

  ftrace.DisableEvent("sched", "sched_switch");
  ftrace.DisableEvent("kmem", "kmalloc");

  EXPECT_THAT(ftrace.ReadEnabledEvents(), IsEmpty());
}

}  // namespace perfetto
<commit_msg>Test: Improve FtraceProcfsIntegrationTest, skip if systrace is on am: 16b67309ba am: f9e65127ad am: 21be68b9b7 am: 032c2dc613<commit_after>/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <fstream>
#include <set>
#include <sstream>
#include <string>

#include "perfetto/ext/base/file_utils.h"
#include "src/traced/probes/ftrace/ftrace_controller.h"
#include "src/traced/probes/ftrace/ftrace_procfs.h"
#include "test/gtest_and_gmock.h"

using testing::Contains;
using testing::HasSubstr;
using testing::IsEmpty;
using testing::Not;
using testing::UnorderedElementsAre;

// These tests run only on Android because on linux they require access to
// ftrace, which would be problematic in the CI when multiple tests run
// concurrently on the same machine. Android instead uses one emulator instance
// for each worker.
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define ANDROID_ONLY_TEST(x) x
#else
#define ANDROID_ONLY_TEST(x) DISABLED_##x
#endif

namespace perfetto {
namespace {

std::string GetFtracePath() {
  size_t i = 0;
  while (!FtraceProcfs::Create(FtraceController::kTracingPaths[i])) {
    i++;
  }
  return std::string(FtraceController::kTracingPaths[i]);
}

std::string ReadFile(const std::string& name) {
  std::string result;
  PERFETTO_CHECK(base::ReadFile(GetFtracePath() + name, &result));
  return result;
}

std::string GetTraceOutput() {
  std::string output = ReadFile("trace");
  if (output.empty()) {
    ADD_FAILURE() << "Could not read trace output";
  }
  return output;
}

class FtraceProcfsIntegrationTest : public testing::Test {
 public:
  void SetUp() override;
  void TearDown() override;

  std::unique_ptr<FtraceProcfs> ftrace_;
};

void FtraceProcfsIntegrationTest::SetUp() {
  ftrace_ = FtraceProcfs::Create(GetFtracePath());
  ASSERT_TRUE(ftrace_);
  if (ftrace_->IsTracingEnabled()) {
    GTEST_SKIP() << "Something else is using ftrace, skipping";
  }

  ftrace_->DisableAllEvents();
  ftrace_->ClearTrace();
  ftrace_->EnableTracing();
}

void FtraceProcfsIntegrationTest::TearDown() {
  ftrace_->DisableAllEvents();
  ftrace_->ClearTrace();
  ftrace_->DisableTracing();
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(CreateWithBadPath)) {
  EXPECT_FALSE(FtraceProcfs::Create(GetFtracePath() + std::string("bad_path")));
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(ClearTrace)) {
  ftrace_->WriteTraceMarker("Hello, World!");
  ftrace_->ClearTrace();
  EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("Hello, World!")));
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(TraceMarker)) {
  ftrace_->WriteTraceMarker("Hello, World!");
  EXPECT_THAT(GetTraceOutput(), HasSubstr("Hello, World!"));
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(EnableDisableEvent)) {
  ftrace_->EnableEvent("sched", "sched_switch");
  sleep(1);
  EXPECT_THAT(GetTraceOutput(), HasSubstr("sched_switch"));

  ftrace_->DisableEvent("sched", "sched_switch");
  ftrace_->ClearTrace();
  sleep(1);
  EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("sched_switch")));
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(EnableDisableTracing)) {
  EXPECT_TRUE(ftrace_->IsTracingEnabled());
  ftrace_->WriteTraceMarker("Before");
  ftrace_->DisableTracing();
  EXPECT_FALSE(ftrace_->IsTracingEnabled());
  ftrace_->WriteTraceMarker("During");
  ftrace_->EnableTracing();
  EXPECT_TRUE(ftrace_->IsTracingEnabled());
  ftrace_->WriteTraceMarker("After");
  EXPECT_THAT(GetTraceOutput(), HasSubstr("Before"));
  EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("During")));
  EXPECT_THAT(GetTraceOutput(), HasSubstr("After"));
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(ReadFormatFile)) {
  std::string format = ftrace_->ReadEventFormat("ftrace", "print");
  EXPECT_THAT(format, HasSubstr("name: print"));
  EXPECT_THAT(format, HasSubstr("field:char buf"));
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(CanOpenTracePipeRaw)) {
  EXPECT_TRUE(ftrace_->OpenPipeForCpu(0));
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(Clock)) {
  std::set<std::string> clocks = ftrace_->AvailableClocks();
  EXPECT_THAT(clocks, Contains("local"));
  EXPECT_THAT(clocks, Contains("global"));

  EXPECT_TRUE(ftrace_->SetClock("global"));
  EXPECT_EQ(ftrace_->GetClock(), "global");
  EXPECT_TRUE(ftrace_->SetClock("local"));
  EXPECT_EQ(ftrace_->GetClock(), "local");
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(CanSetBufferSize)) {
  EXPECT_TRUE(ftrace_->SetCpuBufferSizeInPages(4ul));
  EXPECT_EQ(ReadFile("buffer_size_kb"), "16\n");  // (4096 * 4) / 1024
  EXPECT_TRUE(ftrace_->SetCpuBufferSizeInPages(5ul));
  EXPECT_EQ(ReadFile("buffer_size_kb"), "20\n");  // (4096 * 5) / 1024
}

TEST_F(FtraceProcfsIntegrationTest,
       ANDROID_ONLY_TEST(FtraceControllerHardReset)) {
  ftrace_->SetCpuBufferSizeInPages(4ul);
  ftrace_->EnableTracing();
  ftrace_->EnableEvent("sched", "sched_switch");
  ftrace_->WriteTraceMarker("Hello, World!");

  EXPECT_EQ(ReadFile("buffer_size_kb"), "16\n");
  EXPECT_EQ(ReadFile("tracing_on"), "1\n");
  EXPECT_EQ(ReadFile("events/enable"), "X\n");
  EXPECT_THAT(GetTraceOutput(), HasSubstr("Hello"));

  HardResetFtraceState();

  EXPECT_EQ(ReadFile("buffer_size_kb"), "4\n");
  EXPECT_EQ(ReadFile("tracing_on"), "0\n");
  EXPECT_EQ(ReadFile("events/enable"), "0\n");
  EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("Hello")));
}

TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(ReadEnabledEvents)) {
  EXPECT_THAT(ftrace_->ReadEnabledEvents(), IsEmpty());

  ftrace_->EnableEvent("sched", "sched_switch");
  ftrace_->EnableEvent("kmem", "kmalloc");

  EXPECT_THAT(ftrace_->ReadEnabledEvents(),
              UnorderedElementsAre("sched/sched_switch", "kmem/kmalloc"));

  ftrace_->DisableEvent("sched", "sched_switch");
  ftrace_->DisableEvent("kmem", "kmalloc");

  EXPECT_THAT(ftrace_->ReadEnabledEvents(), IsEmpty());
}

}  // namespace
}  // namespace perfetto
<|endoftext|>


<commit_before>class C
{
public:
    int nX;
    int nY;
    int nZ;
    int* pX;
    C();
    ~C();
};

#define DELETEZ( p )    ( delete p,p = 0 )

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>clang: add namespace class example<commit_after>class C
{
public:
    int nX;
    int nY;
    int nZ;
    int* pX;
    C();
    ~C();
};

namespace ns
{
class C
{
public:
    int nX;
    int mnY;
    int m_nZ;

    C()
    {
    }
};
}

#define DELETEZ( p )    ( delete p,p = 0 )

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: AccessibleDrawDocumentView.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: af $ $Date: 2002-04-22 08:38:30 $
 *
 *  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 _SD_ACCESSIBILITY_ACCESSIBLE_DRAW_DOCUMENT_VIEW_HXX
#include "AccessibleDrawDocumentView.hxx"
#endif

#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_
#include <com/sun/star/drawing/XDrawPage.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XDRAWVIEW_HPP_
#include <com/sun/star/drawing/XDrawView.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTINFOSUPPLIER_HPP_
#include <com/sun/star/document/XDocumentInfoSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTBROADCASTER_HPP_
#include <com/sun/star/document/XEventBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBLE_ACCESSIBLEEVENTID_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleEventId.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULSTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _RTL_USTRING_H_
#include <rtl/ustring.h>
#endif
#ifndef _SFXFRAME_HXX
#include<sfx2/viewfrm.hxx>
#endif

#include <svx/AccessibleShape.hxx>

#include <svx/svdobj.hxx>
#include <svx/svdmodel.hxx>
#include <svx/unoapi.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include "sdwindow.hxx"
#include <vcl/svapp.hxx>

#ifndef _SD_VIEWSHEL_HXX
#include "viewshel.hxx"
#endif
#ifndef _SD_SDVIEW_HXX
#include "sdview.hxx"
#endif
#include <memory>

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::drafts::com::sun::star::accessibility;

class SfxViewFrame;

namespace accessibility {

//=====  internal  ============================================================

AccessibleDrawDocumentView::AccessibleDrawDocumentView (
    SdWindow* pSdWindow,
    SdViewShell* pViewShell,
    const uno::Reference<frame::XController>& rxController,
    const uno::Reference<XAccessible>& rxParent)
    : AccessibleDocumentViewBase (pSdWindow, pViewShell, rxController, rxParent),
      mpChildrenManager (NULL)
{
}

AccessibleDrawDocumentView::~AccessibleDrawDocumentView (void)
{
    OSL_TRACE ("~AccessibleDrawDocumentView");

    // Unregister from the various event broadcasters.
    if (mpChildrenManager != NULL)
        delete mpChildrenManager;
}

void AccessibleDrawDocumentView::Init (void)
{
    AccessibleDocumentViewBase::Init ();

    // Determine the list of shapes on the current page.
    uno::Reference<drawing::XShapes> xShapeList;
    uno::Reference<drawing::XDrawView> xView (mxController, uno::UNO_QUERY);
    if (xView.is())
        xShapeList = uno::Reference<drawing::XShapes> (
            xView->getCurrentPage(), uno::UNO_QUERY);

    // Create the children manager.
    mpChildrenManager = new ChildrenManager(this, xShapeList, maShapeTreeInfo, *this);
    if (mpChildrenManager != NULL)
    {
        mpChildrenManager->AddAccessibleShape (CreateDrawPageShape());
        mpChildrenManager->Update ();
    }
}

void AccessibleDrawDocumentView::ViewForwarderChanged (ChangeType aChangeType,
    const IAccessibleViewForwarder* pViewForwarder)
{
    AccessibleDocumentViewBase::ViewForwarderChanged (aChangeType, pViewForwarder);
    if (mpChildrenManager != NULL)
        mpChildrenManager->ViewForwarderChanged (aChangeType, pViewForwarder);
}

/**  The page shape is created on every call at the moment (provided that
     every thing goes well).
*/
AccessiblePageShape* AccessibleDrawDocumentView::CreateDrawPageShape (void)
{
    AccessiblePageShape* pShape = NULL;

    // Create a shape that represents the actual draw page.
    uno::Reference<drawing::XDrawView> xView (mxController, uno::UNO_QUERY);
    if (xView.is())
    {
        uno::Reference<beans::XPropertySet> xSet (
            uno::Reference<beans::XPropertySet> (xView->getCurrentPage(), uno::UNO_QUERY));
        if (xSet.is())
        {
            // Create a rectangle shape that will represent the draw page.
            uno::Reference<lang::XMultiServiceFactory> xFactory (mxModel, uno::UNO_QUERY);
            uno::Reference<drawing::XShape> xRectangle;
            if (xFactory.is())
                xRectangle = uno::Reference<drawing::XShape>(xFactory->createInstance (
                    OUString (RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.RectangleShape"))),
                    uno::UNO_QUERY);

            // Set the shape's size and position.
            if (xRectangle.is())
            {
                uno::Any aValue;
                awt::Point aPosition;
                awt::Size aSize;

                // Set size and position of the shape to those of the draw
                // page.
                aValue = xSet->getPropertyValue (
                    OUString (RTL_CONSTASCII_USTRINGPARAM("BorderLeft")));
                aValue >>= aPosition.X;
                aValue = xSet->getPropertyValue (
                    OUString (RTL_CONSTASCII_USTRINGPARAM("BorderTop")));
                aValue >>= aPosition.Y;
                xRectangle->setPosition (aPosition);

                aValue = xSet->getPropertyValue (
                    OUString (RTL_CONSTASCII_USTRINGPARAM("Width")));
                aValue >>= aSize.Width;
                aValue = xSet->getPropertyValue (
                    OUString (RTL_CONSTASCII_USTRINGPARAM("Height")));
                aValue >>= aSize.Height;
                xRectangle->setSize (aSize);

                // Create the accessible object for the shape and set its
                // name and description to something more meaningfull than
                // "Rectangle..."
                pShape = new AccessiblePageShape (
                    xView->getCurrentPage(), this, maShapeTreeInfo);
            }
        }
    }
    return pShape;
}

//=====  XAccessibleContext  ==================================================

sal_Int32 SAL_CALL
    AccessibleDrawDocumentView::getAccessibleChildCount (void)
    throw (uno::RuntimeException)
{
    long mpChildCount = 0;

    // Forward request to children manager.
    if (mpChildrenManager != NULL)
        mpChildCount += mpChildrenManager->GetChildCount ();

    return mpChildCount;
}

uno::Reference<XAccessible> SAL_CALL
    AccessibleDrawDocumentView::getAccessibleChild (long nIndex)
    throw (::com::sun::star::uno::RuntimeException)
{
    if (mpChildrenManager != NULL)
    {
        // Forward request to children manager.
        return mpChildrenManager->GetChild (nIndex);
    }
    else
        throw lang::IndexOutOfBoundsException (
            ::rtl::OUString::createFromAscii ("no accessible child with index ") + nIndex,
            static_cast<uno::XWeak*>(this));
}

//=====  XServiceInfo  ========================================================

::rtl::OUString SAL_CALL
    AccessibleDrawDocumentView::getImplementationName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AccessibleDrawDocumentView"));
}

//=====  XEventListener  ======================================================

void SAL_CALL
    AccessibleDrawDocumentView::disposing (const lang::EventObject& rEventObject)
    throw (::com::sun::star::uno::RuntimeException)
{
    AccessibleDocumentViewBase::disposing (rEventObject);
    if (rEventObject.Source == mxModel)
    {
        ::osl::Guard< ::osl::Mutex> aGuard (::osl::Mutex::getGlobalMutex());
        // maShapeTreeInfo has been modified in base class.
        if (mpChildrenManager != NULL)
            mpChildrenManager->SetInfo (maShapeTreeInfo);
    }
}

//=====  XFrameActionListener  ================================================

void SAL_CALL
    AccessibleDrawDocumentView::frameAction (const frame::FrameActionEvent& rEventObject)
    throw (::com::sun::star::uno::RuntimeException)
{
    AccessibleDocumentViewBase::frameAction (rEventObject);

    if (rEventObject.Action == frame::FrameAction_COMPONENT_REATTACHED)
    {
        if (mpChildrenManager != NULL)
        {
            mpChildrenManager->ClearAccessibleShapeList ();
            mpChildrenManager->SetInfo (maShapeTreeInfo);
            mpChildrenManager->ViewForwarderChanged (
                IAccessibleViewForwarderListener::TRANSFORMATION,
                &maViewForwarder);

            // To properly inform the registered listeners of this we just have
            // to call the children manager and update its shape list.
            uno::Reference<drawing::XDrawView> xView (mxController, uno::UNO_QUERY);
            if (xView.is())
                mpChildrenManager->SetShapeList (
                    uno::Reference<drawing::XShapes> (
                        xView->getCurrentPage(), uno::UNO_QUERY));
            mpChildrenManager->AddAccessibleShape (CreateDrawPageShape ());
            mpChildrenManager->Update (false);
            OSL_TRACE ("done handling frame event for AccessibleDrawDocumentView");
        }
    }
}

//=====  XPropertyChangeListener  =============================================

void SAL_CALL
    AccessibleDrawDocumentView::propertyChange (const beans::PropertyChangeEvent& rEventObject)
    throw (::com::sun::star::uno::RuntimeException)
{
    AccessibleDocumentViewBase::propertyChange (rEventObject);

    OSL_TRACE ("AccessibleDrawDocumentView::propertyChange");
    if (rEventObject.PropertyName == OUString (RTL_CONSTASCII_USTRINGPARAM("CurrentPage")))
    {
        OSL_TRACE ("    current page changed");

        // The current page changed.  Update the children manager accordingly.
        uno::Reference<drawing::XDrawView> xView (mxController, uno::UNO_QUERY);
        if (xView.is() && mpChildrenManager!=NULL)
        {
            // Inform the children manager to forget all children and give
            // him the new ones.
            mpChildrenManager->ClearAccessibleShapeList ();
            uno::Reference<drawing::XShapes> xShapeList (
                xView->getCurrentPage(), uno::UNO_QUERY);
            mpChildrenManager->SetShapeList (xShapeList);
            mpChildrenManager->AddAccessibleShape (CreateDrawPageShape ());
            mpChildrenManager->Update (false);
        }
        else
            OSL_TRACE ("View invalid");
    }
    else if (rEventObject.PropertyName == OUString (RTL_CONSTASCII_USTRINGPARAM("VisibleArea")))
    {
        OSL_TRACE ("    visible area changed");
        if (mpChildreManager != NULL)
            mpChildrenManager->ViewForwarderChanged (
                IAccessibleViewForwarderListener::VISIBLE_AREA,
                &maViewForwarder);
    }
    else
    {
        OSL_TRACE ("  unhandled");
    }
    OSL_TRACE ("  done");
}

/// Create a name for this view.
::rtl::OUString
    AccessibleDrawDocumentView::CreateAccessibleName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString (
        RTL_CONSTASCII_USTRINGPARAM("AccessibleDrawDocumentView"));
}

/** Create a description for this view.  Use the model's description or URL
    if a description is not available.
*/
::rtl::OUString
    AccessibleDrawDocumentView::CreateAccessibleDescription (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    rtl::OUString sDescription;

    uno::Reference<lang::XServiceInfo> xInfo (mxController, uno::UNO_QUERY);
    if (xInfo.is())
    {
        OUString sFirstService = xInfo->getSupportedServiceNames()[0];
        if (sFirstService == OUString (
                RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.DrawingDocumentDrawView")))
        {
            sDescription = OUString (RTL_CONSTASCII_USTRINGPARAM("Draw Document"));
        }
        else
            sDescription = sFirstService;
    }
    else
        sDescription = OUString (
            RTL_CONSTASCII_USTRINGPARAM("Accessible Draw Document"));
    return sDescription;
}

} // end of namespace accessibility
<commit_msg>#65293# Fixed typo<commit_after>/*************************************************************************
 *
 *  $RCSfile: AccessibleDrawDocumentView.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: thb $ $Date: 2002-04-22 16:13:53 $
 *
 *  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 _SD_ACCESSIBILITY_ACCESSIBLE_DRAW_DOCUMENT_VIEW_HXX
#include "AccessibleDrawDocumentView.hxx"
#endif

#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_
#include <com/sun/star/drawing/XDrawPage.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XDRAWVIEW_HPP_
#include <com/sun/star/drawing/XDrawView.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTINFOSUPPLIER_HPP_
#include <com/sun/star/document/XDocumentInfoSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTBROADCASTER_HPP_
#include <com/sun/star/document/XEventBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBLE_ACCESSIBLEEVENTID_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleEventId.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULSTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _RTL_USTRING_H_
#include <rtl/ustring.h>
#endif
#ifndef _SFXFRAME_HXX
#include<sfx2/viewfrm.hxx>
#endif

#include <svx/AccessibleShape.hxx>

#include <svx/svdobj.hxx>
#include <svx/svdmodel.hxx>
#include <svx/unoapi.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include "sdwindow.hxx"
#include <vcl/svapp.hxx>

#ifndef _SD_VIEWSHEL_HXX
#include "viewshel.hxx"
#endif
#ifndef _SD_SDVIEW_HXX
#include "sdview.hxx"
#endif
#include <memory>

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::drafts::com::sun::star::accessibility;

class SfxViewFrame;

namespace accessibility {

//=====  internal  ============================================================

AccessibleDrawDocumentView::AccessibleDrawDocumentView (
    SdWindow* pSdWindow,
    SdViewShell* pViewShell,
    const uno::Reference<frame::XController>& rxController,
    const uno::Reference<XAccessible>& rxParent)
    : AccessibleDocumentViewBase (pSdWindow, pViewShell, rxController, rxParent),
      mpChildrenManager (NULL)
{
}

AccessibleDrawDocumentView::~AccessibleDrawDocumentView (void)
{
    OSL_TRACE ("~AccessibleDrawDocumentView");

    // Unregister from the various event broadcasters.
    if (mpChildrenManager != NULL)
        delete mpChildrenManager;
}

void AccessibleDrawDocumentView::Init (void)
{
    AccessibleDocumentViewBase::Init ();

    // Determine the list of shapes on the current page.
    uno::Reference<drawing::XShapes> xShapeList;
    uno::Reference<drawing::XDrawView> xView (mxController, uno::UNO_QUERY);
    if (xView.is())
        xShapeList = uno::Reference<drawing::XShapes> (
            xView->getCurrentPage(), uno::UNO_QUERY);

    // Create the children manager.
    mpChildrenManager = new ChildrenManager(this, xShapeList, maShapeTreeInfo, *this);
    if (mpChildrenManager != NULL)
    {
        mpChildrenManager->AddAccessibleShape (CreateDrawPageShape());
        mpChildrenManager->Update ();
    }
}

void AccessibleDrawDocumentView::ViewForwarderChanged (ChangeType aChangeType,
    const IAccessibleViewForwarder* pViewForwarder)
{
    AccessibleDocumentViewBase::ViewForwarderChanged (aChangeType, pViewForwarder);
    if (mpChildrenManager != NULL)
        mpChildrenManager->ViewForwarderChanged (aChangeType, pViewForwarder);
}

/**  The page shape is created on every call at the moment (provided that
     every thing goes well).
*/
AccessiblePageShape* AccessibleDrawDocumentView::CreateDrawPageShape (void)
{
    AccessiblePageShape* pShape = NULL;

    // Create a shape that represents the actual draw page.
    uno::Reference<drawing::XDrawView> xView (mxController, uno::UNO_QUERY);
    if (xView.is())
    {
        uno::Reference<beans::XPropertySet> xSet (
            uno::Reference<beans::XPropertySet> (xView->getCurrentPage(), uno::UNO_QUERY));
        if (xSet.is())
        {
            // Create a rectangle shape that will represent the draw page.
            uno::Reference<lang::XMultiServiceFactory> xFactory (mxModel, uno::UNO_QUERY);
            uno::Reference<drawing::XShape> xRectangle;
            if (xFactory.is())
                xRectangle = uno::Reference<drawing::XShape>(xFactory->createInstance (
                    OUString (RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.RectangleShape"))),
                    uno::UNO_QUERY);

            // Set the shape's size and position.
            if (xRectangle.is())
            {
                uno::Any aValue;
                awt::Point aPosition;
                awt::Size aSize;

                // Set size and position of the shape to those of the draw
                // page.
                aValue = xSet->getPropertyValue (
                    OUString (RTL_CONSTASCII_USTRINGPARAM("BorderLeft")));
                aValue >>= aPosition.X;
                aValue = xSet->getPropertyValue (
                    OUString (RTL_CONSTASCII_USTRINGPARAM("BorderTop")));
                aValue >>= aPosition.Y;
                xRectangle->setPosition (aPosition);

                aValue = xSet->getPropertyValue (
                    OUString (RTL_CONSTASCII_USTRINGPARAM("Width")));
                aValue >>= aSize.Width;
                aValue = xSet->getPropertyValue (
                    OUString (RTL_CONSTASCII_USTRINGPARAM("Height")));
                aValue >>= aSize.Height;
                xRectangle->setSize (aSize);

                // Create the accessible object for the shape and set its
                // name and description to something more meaningfull than
                // "Rectangle..."
                pShape = new AccessiblePageShape (
                    xView->getCurrentPage(), this, maShapeTreeInfo);
            }
        }
    }
    return pShape;
}

//=====  XAccessibleContext  ==================================================

sal_Int32 SAL_CALL
    AccessibleDrawDocumentView::getAccessibleChildCount (void)
    throw (uno::RuntimeException)
{
    long mpChildCount = 0;

    // Forward request to children manager.
    if (mpChildrenManager != NULL)
        mpChildCount += mpChildrenManager->GetChildCount ();

    return mpChildCount;
}

uno::Reference<XAccessible> SAL_CALL
    AccessibleDrawDocumentView::getAccessibleChild (long nIndex)
    throw (::com::sun::star::uno::RuntimeException)
{
    if (mpChildrenManager != NULL)
    {
        // Forward request to children manager.
        return mpChildrenManager->GetChild (nIndex);
    }
    else
        throw lang::IndexOutOfBoundsException (
            ::rtl::OUString::createFromAscii ("no accessible child with index ") + nIndex,
            static_cast<uno::XWeak*>(this));
}

//=====  XServiceInfo  ========================================================

::rtl::OUString SAL_CALL
    AccessibleDrawDocumentView::getImplementationName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AccessibleDrawDocumentView"));
}

//=====  XEventListener  ======================================================

void SAL_CALL
    AccessibleDrawDocumentView::disposing (const lang::EventObject& rEventObject)
    throw (::com::sun::star::uno::RuntimeException)
{
    AccessibleDocumentViewBase::disposing (rEventObject);
    if (rEventObject.Source == mxModel)
    {
        ::osl::Guard< ::osl::Mutex> aGuard (::osl::Mutex::getGlobalMutex());
        // maShapeTreeInfo has been modified in base class.
        if (mpChildrenManager != NULL)
            mpChildrenManager->SetInfo (maShapeTreeInfo);
    }
}

//=====  XFrameActionListener  ================================================

void SAL_CALL
    AccessibleDrawDocumentView::frameAction (const frame::FrameActionEvent& rEventObject)
    throw (::com::sun::star::uno::RuntimeException)
{
    AccessibleDocumentViewBase::frameAction (rEventObject);

    if (rEventObject.Action == frame::FrameAction_COMPONENT_REATTACHED)
    {
        if (mpChildrenManager != NULL)
        {
            mpChildrenManager->ClearAccessibleShapeList ();
            mpChildrenManager->SetInfo (maShapeTreeInfo);
            mpChildrenManager->ViewForwarderChanged (
                IAccessibleViewForwarderListener::TRANSFORMATION,
                &maViewForwarder);

            // To properly inform the registered listeners of this we just have
            // to call the children manager and update its shape list.
            uno::Reference<drawing::XDrawView> xView (mxController, uno::UNO_QUERY);
            if (xView.is())
                mpChildrenManager->SetShapeList (
                    uno::Reference<drawing::XShapes> (
                        xView->getCurrentPage(), uno::UNO_QUERY));
            mpChildrenManager->AddAccessibleShape (CreateDrawPageShape ());
            mpChildrenManager->Update (false);
            OSL_TRACE ("done handling frame event for AccessibleDrawDocumentView");
        }
    }
}

//=====  XPropertyChangeListener  =============================================

void SAL_CALL
    AccessibleDrawDocumentView::propertyChange (const beans::PropertyChangeEvent& rEventObject)
    throw (::com::sun::star::uno::RuntimeException)
{
    AccessibleDocumentViewBase::propertyChange (rEventObject);

    OSL_TRACE ("AccessibleDrawDocumentView::propertyChange");
    if (rEventObject.PropertyName == OUString (RTL_CONSTASCII_USTRINGPARAM("CurrentPage")))
    {
        OSL_TRACE ("    current page changed");

        // The current page changed.  Update the children manager accordingly.
        uno::Reference<drawing::XDrawView> xView (mxController, uno::UNO_QUERY);
        if (xView.is() && mpChildrenManager!=NULL)
        {
            // Inform the children manager to forget all children and give
            // him the new ones.
            mpChildrenManager->ClearAccessibleShapeList ();
            uno::Reference<drawing::XShapes> xShapeList (
                xView->getCurrentPage(), uno::UNO_QUERY);
            mpChildrenManager->SetShapeList (xShapeList);
            mpChildrenManager->AddAccessibleShape (CreateDrawPageShape ());
            mpChildrenManager->Update (false);
        }
        else
            OSL_TRACE ("View invalid");
    }
    else if (rEventObject.PropertyName == OUString (RTL_CONSTASCII_USTRINGPARAM("VisibleArea")))
    {
        OSL_TRACE ("    visible area changed");
        if (mpChildrenManager != NULL)
            mpChildrenManager->ViewForwarderChanged (
                IAccessibleViewForwarderListener::VISIBLE_AREA,
                &maViewForwarder);
    }
    else
    {
        OSL_TRACE ("  unhandled");
    }
    OSL_TRACE ("  done");
}

/// Create a name for this view.
::rtl::OUString
    AccessibleDrawDocumentView::CreateAccessibleName (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString (
        RTL_CONSTASCII_USTRINGPARAM("AccessibleDrawDocumentView"));
}

/** Create a description for this view.  Use the model's description or URL
    if a description is not available.
*/
::rtl::OUString
    AccessibleDrawDocumentView::CreateAccessibleDescription (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    rtl::OUString sDescription;

    uno::Reference<lang::XServiceInfo> xInfo (mxController, uno::UNO_QUERY);
    if (xInfo.is())
    {
        OUString sFirstService = xInfo->getSupportedServiceNames()[0];
        if (sFirstService == OUString (
                RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.DrawingDocumentDrawView")))
        {
            sDescription = OUString (RTL_CONSTASCII_USTRINGPARAM("Draw Document"));
        }
        else
            sDescription = sFirstService;
    }
    else
        sDescription = OUString (
            RTL_CONSTASCII_USTRINGPARAM("Accessible Draw Document"));
    return sDescription;
}

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


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

#ifndef SD_TASKPANE_CONTROLS_ANIMATION_SCHEMES_PANEL_HXX
#define SD_TASKPANE_CONTROLS_ANIMATION_SCHEMES_PANEL_HXX

#include "taskpane/SubToolPanel.hxx"

namespace sd {
class ViewShellBase;
}

namespace sd { namespace toolpanel {
class TreeNode;
} }

namespace sd { namespace toolpanel { namespace controls {

class AnimationSchemesPanel
    : public SubToolPanel
{
public:
    AnimationSchemesPanel (
        TreeNode* pParent,
        ViewShellBase& rBase);
    virtual ~AnimationSchemesPanel (void);

    virtual Size GetPreferredSize (void);
    virtual sal_Int32 GetPreferredWidth (sal_Int32 nHeigh);
    virtual sal_Int32 GetPreferredHeight (sal_Int32 nWidth);
    virtual ::Window* GetWindow (void);
    virtual bool IsResizable (void);
    virtual bool IsExpandable (void) const;

private:
    Size maPreferredSize;
    ::Window* mpWrappedControl;
};

} } } // end of namespace ::sd::toolpanel::controls

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

#ifndef SD_TASKPANE_CONTROLS_ANIMATION_SCHEMES_PANEL_HXX
#define SD_TASKPANE_CONTROLS_ANIMATION_SCHEMES_PANEL_HXX

#include "taskpane/SubToolPanel.hxx"

namespace sd {
class ViewShellBase;
}

namespace sd { namespace toolpanel {
class TreeNode;
} }

namespace sd { namespace toolpanel { namespace controls {

class AnimationSchemesPanel
    : public SubToolPanel
{
public:
    AnimationSchemesPanel (
        TreeNode* pParent,
        ViewShellBase& rBase);
    virtual ~AnimationSchemesPanel (void);

    virtual Size GetPreferredSize (void);
    virtual sal_Int32 GetPreferredWidth (sal_Int32 nHeigh);
    virtual sal_Int32 GetPreferredHeight (sal_Int32 nWidth);
    virtual ::Window* GetWindow (void);
    virtual bool IsResizable (void);
    virtual bool IsExpandable (void) const;

    using Window::GetWindow;

private:
    Size maPreferredSize;
    ::Window* mpWrappedControl;
};

} } } // end of namespace ::sd::toolpanel::controls

#endif
<|endoftext|>


<commit_before>#ifndef STD_LIST_HPP
#define STD_LIST_HPP

#include "EASTL/list.h"
namespace std
{

}

#endif
<commit_msg>Removed unused header<commit_after><|endoftext|>


<commit_before>
#include "ColorGradientDemo.h"

#include <gloperate/gloperate.h>
#include <gloperate/stages/base/ProgramStage.h>
#include <gloperate/stages/base/RenderPassStage.h>
#include <gloperate/stages/base/RasterizationStage.h>
#include <gloperate/stages/base/ClearStage.h>
#include <gloperate/stages/base/ShapeStage.h>
#include <gloperate/stages/base/TransformStage.h>
#include <gloperate/stages/base/ColorGradientStage.h>
#include <gloperate/stages/base/ColorGradientSelectionStage.h>
#include <gloperate/stages/base/ColorGradientTextureStage.h>
#include <gloperate/stages/navigation/TrackballStage.h>
#include <gloperate/rendering/ColorGradientList.h>
#include <gloperate/rendering/Shape.h>
#include <gloperate/rendering/Image.h>

CPPEXPOSE_COMPONENT(ColorGradientDemo, gloperate::Stage)

using namespace cppexpose;
using namespace gloperate;

ColorGradientDemo::ColorGradientDemo(Environment * environment, const std::string & name)
: Pipeline(environment, "ColorGradientDemo", name)
, renderInterface(this)
, colors("colors", this, dataPath() + "/gloperate/gradients/colorbrewer.json")
, gradient("gradient", this)
, value("value", this, 0.5f)
, m_trackball(cppassist::make_unique<TrackballStage>(environment, "Trackball"))
, m_shape(cppassist::make_unique<ShapeStage>(environment, "Shape"))
, m_colorGradientLoading(cppassist::make_unique<ColorGradientStage>(environment, "ColorGradientsLoading"))
, m_colorGradientTexture(cppassist::make_unique<ColorGradientTextureStage>(environment, "ColorGradientsTexture"))
, m_colorGradientSelection(cppassist::make_unique<ColorGradientSelectionStage>(environment, "ColorGradientsSelection"))
, m_shapeTransform(cppassist::make_unique<TransformStage>(environment, "ShapeTransform"))
, m_shapeProgram(cppassist::make_unique<ProgramStage>(environment, "ShapeProgram"))
, m_shapeRenderPass(cppassist::make_unique<RenderPassStage>(environment, "ShapeRenderPass"))
, m_clear(cppassist::make_unique<ClearStage>(environment, "Clear"))
, m_shapeRasterization(cppassist::make_unique<RasterizationStage>(environment, "ShapeRasterization"))
{
    // Get data path
    std::string dataPath = gloperate::dataPath();

    // Setup parameters
    value.setOption("minimumValue", 0.0f);
    value.setOption("maximumValue", 1.0f);
    value.setOption("updateOnDrag", true);
    value.valueChanged.connect([this] (const float & value)
    {
        float v = 0.2 + 0.8 * value;
        m_shapeTransform->scale = glm::vec3(v, v, v);
    });

    // Trackball stage
    addStage(m_trackball.get());
    m_trackball->viewport << renderInterface.deviceViewport;

    // Shape stage
    addStage(m_shape.get());
    m_shape->shapeType = ShapeType::Box;
    m_shape->width     = 1.0f;
    m_shape->height    = 1.0f;
    m_shape->depth     = 1.0f;
    m_shape->texCoords = false;

    // Color gradient load stage
    addStage(m_colorGradientLoading.get());
    m_colorGradientLoading->filePath << colors;
    m_colorGradientLoading->gradients.valueChanged.connect([this] (const gloperate::ColorGradientList * gradients)
    {
        gradient.setOption("choices", cppexpose::Variant::fromVector(gradients->names()));
        gradient.setOption("pixmaps", cppexpose::Variant::fromVector(gradients->pixmaps({ 80, 20 })));
        gradient.setValue(gradients->gradients().begin()->first);
    });

    // Color gradients texture stage
    addStage(m_colorGradientTexture.get());
    m_colorGradientTexture->gradients << m_colorGradientLoading->gradients;
    m_colorGradientTexture->textureWidth = 128;

    // Color gradient selection stage
    addStage(m_colorGradientSelection.get());
    m_colorGradientSelection->gradients << m_colorGradientLoading->gradients;
    m_colorGradientSelection->name << gradient;

    // Transform stage for shape
    addStage(m_shapeTransform.get());
    value.valueChanged(value.value());

    // Program stage for shape
    addStage(m_shapeProgram.get());
    *m_shapeProgram->createInput<cppassist::FilePath>("vertexShader")   = dataPath + "/gloperate/shaders/demos/gradient.vert";
    *m_shapeProgram->createInput<cppassist::FilePath>("fragmentShader") = dataPath + "/gloperate/shaders/demos/gradient.frag";

    // Render pass stage for shape
    addStage(m_shapeRenderPass.get());
    m_shapeRenderPass->culling = false;
    m_shapeRenderPass->drawable << m_shape->drawable;
    m_shapeRenderPass->program << m_shapeProgram->program;
    m_shapeRenderPass->camera << m_trackball->camera;
    m_shapeRenderPass->modelMatrix << m_shapeTransform->modelMatrix;
    m_shapeRenderPass->createInput("gradientTexture") << m_colorGradientTexture->texture;
    m_shapeRenderPass->createInput("gradientIndex") << m_colorGradientSelection->index;
    m_shapeRenderPass->createInput("value") << this->value;

    // Clear stage
    addStage(m_clear.get());
    m_clear->renderInterface.targetFBO << renderInterface.targetFBO;
    m_clear->renderInterface.deviceViewport << renderInterface.deviceViewport;
    m_clear->renderInterface.backgroundColor = Color(0.0f, 0.0f, 0.0f, 1.0f);
    m_clear->createInput("renderPass") << m_shapeRenderPass->renderPass;

    // Rasterization stage for shape
    addStage(m_shapeRasterization.get());
    m_shapeRasterization->renderInterface.targetFBO << m_clear->fboOut;
    m_shapeRasterization->renderInterface.deviceViewport << renderInterface.deviceViewport;
    m_shapeRasterization->drawable << m_shapeRenderPass->renderPass;

    // Outputs
    renderInterface.rendered << m_shapeRasterization->renderInterface.rendered;
}

ColorGradientDemo::~ColorGradientDemo()
{
}
<commit_msg>add explicit default value to color demo and remove setting first choice<commit_after>
#include "ColorGradientDemo.h"

#include <gloperate/gloperate.h>
#include <gloperate/stages/base/ProgramStage.h>
#include <gloperate/stages/base/RenderPassStage.h>
#include <gloperate/stages/base/RasterizationStage.h>
#include <gloperate/stages/base/ClearStage.h>
#include <gloperate/stages/base/ShapeStage.h>
#include <gloperate/stages/base/TransformStage.h>
#include <gloperate/stages/base/ColorGradientStage.h>
#include <gloperate/stages/base/ColorGradientSelectionStage.h>
#include <gloperate/stages/base/ColorGradientTextureStage.h>
#include <gloperate/stages/navigation/TrackballStage.h>
#include <gloperate/rendering/ColorGradientList.h>
#include <gloperate/rendering/Shape.h>
#include <gloperate/rendering/Image.h>

CPPEXPOSE_COMPONENT(ColorGradientDemo, gloperate::Stage)

using namespace cppexpose;
using namespace gloperate;

ColorGradientDemo::ColorGradientDemo(Environment * environment, const std::string & name)
: Pipeline(environment, "ColorGradientDemo", name)
, renderInterface(this)
, colors("colors", this, dataPath() + "/gloperate/gradients/colorbrewer.json")
, gradient("gradient", this, "Set1-5")
, value("value", this, 0.5f)
, m_trackball(cppassist::make_unique<TrackballStage>(environment, "Trackball"))
, m_shape(cppassist::make_unique<ShapeStage>(environment, "Shape"))
, m_colorGradientLoading(cppassist::make_unique<ColorGradientStage>(environment, "ColorGradientsLoading"))
, m_colorGradientTexture(cppassist::make_unique<ColorGradientTextureStage>(environment, "ColorGradientsTexture"))
, m_colorGradientSelection(cppassist::make_unique<ColorGradientSelectionStage>(environment, "ColorGradientsSelection"))
, m_shapeTransform(cppassist::make_unique<TransformStage>(environment, "ShapeTransform"))
, m_shapeProgram(cppassist::make_unique<ProgramStage>(environment, "ShapeProgram"))
, m_shapeRenderPass(cppassist::make_unique<RenderPassStage>(environment, "ShapeRenderPass"))
, m_clear(cppassist::make_unique<ClearStage>(environment, "Clear"))
, m_shapeRasterization(cppassist::make_unique<RasterizationStage>(environment, "ShapeRasterization"))
{
    // Get data path
    std::string dataPath = gloperate::dataPath();

    // Setup parameters
    value.setOption("minimumValue", 0.0f);
    value.setOption("maximumValue", 1.0f);
    value.setOption("updateOnDrag", true);
    value.valueChanged.connect([this] (const float & value)
    {
        float v = 0.2 + 0.8 * value;
        m_shapeTransform->scale = glm::vec3(v, v, v);
    });

    // Trackball stage
    addStage(m_trackball.get());
    m_trackball->viewport << renderInterface.deviceViewport;

    // Shape stage
    addStage(m_shape.get());
    m_shape->shapeType = ShapeType::Box;
    m_shape->width     = 1.0f;
    m_shape->height    = 1.0f;
    m_shape->depth     = 1.0f;
    m_shape->texCoords = false;

    // Color gradient load stage
    addStage(m_colorGradientLoading.get());
    m_colorGradientLoading->filePath << colors;
    m_colorGradientLoading->gradients.valueChanged.connect([this] (const gloperate::ColorGradientList * gradients)
    {
        gradient.setOption("choices", cppexpose::Variant::fromVector(gradients->names()));
        gradient.setOption("pixmaps", cppexpose::Variant::fromVector(gradients->pixmaps({ 80, 20 })));
    });

    // Color gradients texture stage
    addStage(m_colorGradientTexture.get());
    m_colorGradientTexture->gradients << m_colorGradientLoading->gradients;
    m_colorGradientTexture->textureWidth = 128;

    // Color gradient selection stage
    addStage(m_colorGradientSelection.get());
    m_colorGradientSelection->gradients << m_colorGradientLoading->gradients;
    m_colorGradientSelection->name << gradient;

    // Transform stage for shape
    addStage(m_shapeTransform.get());
    value.valueChanged(value.value());

    // Program stage for shape
    addStage(m_shapeProgram.get());
    *m_shapeProgram->createInput<cppassist::FilePath>("vertexShader")   = dataPath + "/gloperate/shaders/demos/gradient.vert";
    *m_shapeProgram->createInput<cppassist::FilePath>("fragmentShader") = dataPath + "/gloperate/shaders/demos/gradient.frag";

    // Render pass stage for shape
    addStage(m_shapeRenderPass.get());
    m_shapeRenderPass->culling = false;
    m_shapeRenderPass->drawable << m_shape->drawable;
    m_shapeRenderPass->program << m_shapeProgram->program;
    m_shapeRenderPass->camera << m_trackball->camera;
    m_shapeRenderPass->modelMatrix << m_shapeTransform->modelMatrix;
    m_shapeRenderPass->createInput("gradientTexture") << m_colorGradientTexture->texture;
    m_shapeRenderPass->createInput("gradientIndex") << m_colorGradientSelection->index;
    m_shapeRenderPass->createInput("value") << this->value;

    // Clear stage
    addStage(m_clear.get());
    m_clear->renderInterface.targetFBO << renderInterface.targetFBO;
    m_clear->renderInterface.deviceViewport << renderInterface.deviceViewport;
    m_clear->renderInterface.backgroundColor = Color(0.0f, 0.0f, 0.0f, 1.0f);
    m_clear->createInput("renderPass") << m_shapeRenderPass->renderPass;

    // Rasterization stage for shape
    addStage(m_shapeRasterization.get());
    m_shapeRasterization->renderInterface.targetFBO << m_clear->fboOut;
    m_shapeRasterization->renderInterface.deviceViewport << renderInterface.deviceViewport;
    m_shapeRasterization->drawable << m_shapeRenderPass->renderPass;

    // Outputs
    renderInterface.rendered << m_shapeRasterization->renderInterface.rendered;
}

ColorGradientDemo::~ColorGradientDemo()
{
}
<|endoftext|>