<commit_before>//
// Copyright (C) 2013-2018 University of Amsterdam
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program.  If not, see
// <http://www.gnu.org/licenses/>.
//

#include "factorsformbase.h"
#include "boundcontrolterms.h"
#include "analysis/analysisform.h"
#include "utilities/qutils.h"
#include "variableslistbase.h"
#include "log.h"

using namespace std;

FactorsFormBase::FactorsFormBase(QQuickItem *parent)
	: JASPListControl(parent), BoundControlBase(this)
{
	_controlType			= ControlType::FactorsForm;
	_useControlMouseArea	= false;
}

void FactorsFormBase::setUpModel()
{
	_factorsModel = new ListModelFactorsForm(this);

	JASPListControl::setUpModel();

	_availableVariablesListName = property("availableVariablesListName").toString();
	QVariant availableListVariant = property("availableVariablesList");
	_availableVariablesListItem = dynamic_cast<JASPControl*>(qobject_cast<QQuickItem *>(availableListVariant.value<QObject *>()));
}

void FactorsFormBase::bindTo(const Json::Value& value)
{
	BoundControlBase::bindTo(value);

	ListModelFactorsForm::FactorVec factors;

	for (const Json::Value& factor : value)
	{
		vector<string> indicators;
		for (const Json::Value& indicator : factor["indicators"])
			indicators.push_back(indicator.asString());

		factors.push_back(make_tuple(factor["name"].asString(), factor["title"].asString(), indicators));
	}

	_factorsModel->initFactors(factors);
}

Json::Value FactorsFormBase::createJson()
{
	Json::Value result(Json::arrayValue);

	for (int i = 0; i < _initNumberFactors; i++)
	{
		Json::Value row(Json::objectValue);
		QString name("Factor");
		name += QString::number(i+1);
		QString title("Factor ");
		title += QString::number(i+1);
		row["name"] = fq(name);
		row["title"] = fq(title);
		row["indicators"] = Json::Value(Json::arrayValue);

		result.append(row);
	}

	return result;
}

bool FactorsFormBase::isJsonValid(const Json::Value &value)
{
	bool valid = value.isArray();
	if (valid)
	{
		for (const Json::Value& factor : value)
		{
			valid = factor.isArray() && factor["name"].isString() && factor["title"].isString() && factor["indicators"].isArray();
			if (!valid) break;
		}
	}

	return valid;
}

void FactorsFormBase::termsChangedHandler()
{
	const ListModelFactorsForm::FactorVec &factors = _factorsModel->getFactors();
	Json::Value boundValue(Json::arrayValue);

	for (const auto &factor : factors)
	{
		Json::Value factorJson(Json::objectValue);
		factorJson["name"] = get<0>(factor);
		factorJson["title"] = get<1>(factor);
		Json::Value indicators(Json::arrayValue);
		for (const string &level : get<2>(factor))
			indicators.append(level);
		factorJson["indicators"] = indicators;
		boundValue.append(factorJson);
	}

	setBoundValue(boundValue);
}

void FactorsFormBase::factorAdded(int index, QVariant item)
{
	VariablesListBase* listView = item.value<VariablesListBase *>();
	if (!listView)
	{
		JASPControl* control = item.value<JASPControl *>();
		Log::log() << "JASP Control " << (control ? control->name() : "") << " is not a VariablesListBase in factorAdded" << std::endl;
		return;
	}

	_factorsModel->factorAdded(index, listView);

	connect(listView->model(), &ListModel::termsChanged, _factorsModel, &ListModelFactorsForm::resetModelTerms);
}
<commit_msg>FactorsForm check is wrong, should check for object not array... - Fixes https://github.com/jasp-stats/jasp-test-release/issues/1376<commit_after>//
// Copyright (C) 2013-2018 University of Amsterdam
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program.  If not, see
// <http://www.gnu.org/licenses/>.
//

#include "factorsformbase.h"
#include "boundcontrolterms.h"
#include "analysis/analysisform.h"
#include "utilities/qutils.h"
#include "variableslistbase.h"
#include "log.h"

using namespace std;

FactorsFormBase::FactorsFormBase(QQuickItem *parent)
	: JASPListControl(parent), BoundControlBase(this)
{
	_controlType			= ControlType::FactorsForm;
	_useControlMouseArea	= false;
}

void FactorsFormBase::setUpModel()
{
	_factorsModel = new ListModelFactorsForm(this);

	JASPListControl::setUpModel();

	_availableVariablesListName = property("availableVariablesListName").toString();
	QVariant availableListVariant = property("availableVariablesList");
	_availableVariablesListItem = dynamic_cast<JASPControl*>(qobject_cast<QQuickItem *>(availableListVariant.value<QObject *>()));
}

void FactorsFormBase::bindTo(const Json::Value& value)
{
	BoundControlBase::bindTo(value);

	ListModelFactorsForm::FactorVec factors;

	for (const Json::Value& factor : value)
	{
		vector<string> indicators;
		for (const Json::Value& indicator : factor["indicators"])
			indicators.push_back(indicator.asString());

		factors.push_back(make_tuple(factor["name"].asString(), factor["title"].asString(), indicators));
	}

	_factorsModel->initFactors(factors);
}

Json::Value FactorsFormBase::createJson()
{
	Json::Value result(Json::arrayValue);

	for (int i = 0; i < _initNumberFactors; i++)
	{
		Json::Value row(Json::objectValue);
		QString name("Factor");
		name += QString::number(i+1);
		QString title("Factor ");
		title += QString::number(i+1);
		row["name"] = fq(name);
		row["title"] = fq(title);
		row["indicators"] = Json::Value(Json::arrayValue);

		result.append(row);
	}

	return result;
}

bool FactorsFormBase::isJsonValid(const Json::Value &value)
{
	bool valid = value.isArray();
	if (valid)
	{
		for (const Json::Value& factor : value)
		{
			valid = factor.isObject() && factor["name"].isString() && factor["title"].isString() && factor["indicators"].isArray();
			if (!valid) break;
		}
	}

	return valid;
}

void FactorsFormBase::termsChangedHandler()
{
	const ListModelFactorsForm::FactorVec &factors = _factorsModel->getFactors();
	Json::Value boundValue(Json::arrayValue);

	for (const auto &factor : factors)
	{
		Json::Value factorJson(Json::objectValue);
		factorJson["name"] = get<0>(factor);
		factorJson["title"] = get<1>(factor);
		Json::Value indicators(Json::arrayValue);
		for (const string &level : get<2>(factor))
			indicators.append(level);
		factorJson["indicators"] = indicators;
		boundValue.append(factorJson);
	}

	setBoundValue(boundValue);
}

void FactorsFormBase::factorAdded(int index, QVariant item)
{
	VariablesListBase* listView = item.value<VariablesListBase *>();
	if (!listView)
	{
		JASPControl* control = item.value<JASPControl *>();
		Log::log() << "JASP Control " << (control ? control->name() : "") << " is not a VariablesListBase in factorAdded" << std::endl;
		return;
	}

	_factorsModel->factorAdded(index, listView);

	connect(listView->model(), &ListModel::termsChanged, _factorsModel, &ListModelFactorsForm::resetModelTerms);
}
<|endoftext|>


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

#include "sky/viewer/converters/input_event_types.h"

#include "base/logging.h"
#include "base/time/time.h"
#include "mojo/services/input_events/public/interfaces/input_event_constants.mojom.h"
#include "sky/engine/public/platform/WebInputEvent.h"

namespace sky {
namespace {

int EventFlagsToWebInputEventModifiers(int flags) {
  return
      (flags & mojo::EVENT_FLAGS_SHIFT_DOWN ?
       blink::WebInputEvent::ShiftKey : 0) |
      (flags & mojo::EVENT_FLAGS_CONTROL_DOWN ?
       blink::WebInputEvent::ControlKey : 0) |
      (flags & mojo::EVENT_FLAGS_CAPS_LOCK_DOWN ?
       blink::WebInputEvent::CapsLockOn : 0) |
      (flags & mojo::EVENT_FLAGS_ALT_DOWN ?
       blink::WebInputEvent::AltKey : 0);
}

scoped_ptr<blink::WebInputEvent> BuildWebPointerEvent(
    const mojo::EventPtr& event, float device_pixel_ratio) {
  scoped_ptr<blink::WebPointerEvent> web_event(new blink::WebPointerEvent);

  web_event->modifiers = EventFlagsToWebInputEventModifiers(event->flags);
  web_event->timeStampMS =
      base::TimeDelta::FromInternalValue(event->time_stamp).InMillisecondsF();

  switch (event->action) {
    case mojo::EVENT_TYPE_TOUCH_PRESSED:
    case mojo::EVENT_TYPE_MOUSE_PRESSED:
      web_event->type = blink::WebInputEvent::PointerDown;
      break;
    case mojo::EVENT_TYPE_TOUCH_MOVED:
    case mojo::EVENT_TYPE_MOUSE_DRAGGED:
      web_event->type = blink::WebInputEvent::PointerMove;
      break;
    case mojo::EVENT_TYPE_TOUCH_RELEASED:
    case mojo::EVENT_TYPE_MOUSE_RELEASED:
      web_event->type = blink::WebInputEvent::PointerUp;
      break;
    case mojo::EVENT_TYPE_TOUCH_CANCELLED:
      // FIXME: What mouse event should we listen to in order to learn when the
      // mouse moves out of the mojo::View?
      web_event->type = blink::WebInputEvent::PointerCancel;
      break;
    default:
      NOTIMPLEMENTED() << "Received unexpected event: " << event->action;
      break;
  }

  switch (event->action) {
    case mojo::EVENT_TYPE_TOUCH_CANCELLED:
    case mojo::EVENT_TYPE_TOUCH_MOVED:
    case mojo::EVENT_TYPE_TOUCH_PRESSED:
    case mojo::EVENT_TYPE_TOUCH_RELEASED:
      web_event->kind = blink::WebPointerEvent::Touch;
      break;
    case mojo::EVENT_TYPE_MOUSE_DRAGGED:
    case mojo::EVENT_TYPE_MOUSE_EXITED:
    case mojo::EVENT_TYPE_MOUSE_PRESSED:
    case mojo::EVENT_TYPE_MOUSE_RELEASED:
      web_event->kind = blink::WebPointerEvent::Mouse;
      break;
    default:
      NOTIMPLEMENTED() << "Received unexpected event: " << event->action;
      break;
  }

  if (event->touch_data)
    web_event->pointer = event->touch_data->pointer_id;

  const auto& location = event->location_data->in_view_location;
  web_event->x = location->x / device_pixel_ratio;
  web_event->y = location->y / device_pixel_ratio;

  return web_event.Pass();
}

scoped_ptr<blink::WebInputEvent> BuildWebGestureEvent(
    const mojo::EventPtr& event,
    float device_pixel_ratio) {
  scoped_ptr<blink::WebGestureEvent> web_event(new blink::WebGestureEvent);

  web_event->modifiers = EventFlagsToWebInputEventModifiers(event->flags);
  web_event->timeStampMS =
      base::TimeDelta::FromInternalValue(event->time_stamp).InMillisecondsF();

  switch (event->action) {
    case mojo::EVENT_TYPE_GESTURE_SCROLL_BEGIN:
      web_event->type = blink::WebInputEvent::GestureScrollBegin;
      break;
    case mojo::EVENT_TYPE_GESTURE_SCROLL_END:
      web_event->type = blink::WebInputEvent::GestureScrollEnd;
      break;
    case mojo::EVENT_TYPE_GESTURE_SCROLL_UPDATE:
      web_event->type = blink::WebInputEvent::GestureScrollUpdate;
      web_event->data.scrollUpdate.deltaX =
          event->gesture_data->scroll_x / device_pixel_ratio;
      web_event->data.scrollUpdate.deltaY =
          event->gesture_data->scroll_y / device_pixel_ratio;
      break;
    case mojo::EVENT_TYPE_SCROLL_FLING_START:
      web_event->type = blink::WebInputEvent::GestureFlingStart;
      // TODO(abarth): Why don't we need to divide by the device_pixel_ratio
      // here? For some reason, this seems to get the right velocity.
      web_event->data.flingStart.velocityX = event->gesture_data->velocity_x;
      web_event->data.flingStart.velocityY = event->gesture_data->velocity_y;
      break;
    case mojo::EVENT_TYPE_SCROLL_FLING_CANCEL:
      web_event->type = blink::WebInputEvent::GestureFlingCancel;
      break;
    case mojo::EVENT_TYPE_GESTURE_SHOW_PRESS:
      web_event->type = blink::WebInputEvent::GestureShowPress;
      break;
    case mojo::EVENT_TYPE_GESTURE_TAP:
      web_event->type = blink::WebInputEvent::GestureTap;
      web_event->data.tap.tapCount = event->gesture_data->tap_count;
      break;
    case mojo::EVENT_TYPE_GESTURE_TAP_UNCONFIRMED:
      web_event->type = blink::WebInputEvent::GestureTapUnconfirmed;
      web_event->data.tap.tapCount = event->gesture_data->tap_count;
      break;
    case mojo::EVENT_TYPE_GESTURE_TAP_DOWN:
      web_event->type = blink::WebInputEvent::GestureTapDown;
      break;
    case mojo::EVENT_TYPE_GESTURE_TAP_CANCEL:
      web_event->type = blink::WebInputEvent::GestureTapCancel;
      break;
    case mojo::EVENT_TYPE_GESTURE_DOUBLE_TAP:
      web_event->type = blink::WebInputEvent::GestureDoubleTap;
      web_event->data.tap.tapCount = event->gesture_data->tap_count;
      break;
    case mojo::EVENT_TYPE_GESTURE_TWO_FINGER_TAP:
      web_event->type = blink::WebInputEvent::GestureTwoFingerTap;
      break;
    case mojo::EVENT_TYPE_GESTURE_LONG_PRESS:
      web_event->type = blink::WebInputEvent::GestureLongPress;
      break;
    case mojo::EVENT_TYPE_GESTURE_LONG_TAP:
      web_event->type = blink::WebInputEvent::GestureLongTap;
      break;
    case mojo::EVENT_TYPE_GESTURE_PINCH_BEGIN:
      web_event->type = blink::WebInputEvent::GesturePinchBegin;
      break;
    case mojo::EVENT_TYPE_GESTURE_PINCH_END:
      web_event->type = blink::WebInputEvent::GesturePinchEnd;
      break;
    case mojo::EVENT_TYPE_GESTURE_PINCH_UPDATE:
      web_event->type = blink::WebInputEvent::GesturePinchUpdate;
      web_event->data.pinchUpdate.scale =
          event->gesture_data->scale / device_pixel_ratio;
      break;
    default:
      NOTIMPLEMENTED() << "Received unexpected event: " << event->action;
      break;
  }

  web_event->x = event->location_data->in_view_location->x / device_pixel_ratio;
  web_event->y = event->location_data->in_view_location->y / device_pixel_ratio;

  return web_event.Pass();
}

scoped_ptr<blink::WebInputEvent> BuildWebKeyboardEvent(
    const mojo::EventPtr& event,
    float device_pixel_ratio) {
  scoped_ptr<blink::WebKeyboardEvent> web_event(new blink::WebKeyboardEvent);

  web_event->modifiers = EventFlagsToWebInputEventModifiers(event->flags);
  web_event->timeStampMS =
      base::TimeDelta::FromInternalValue(event->time_stamp).InMillisecondsF();

  switch (event->action) {
    case mojo::EVENT_TYPE_KEY_PRESSED:
      web_event->type = event->key_data->is_char ? blink::WebInputEvent::Char :
          blink::WebInputEvent::KeyDown;
      break;
    case mojo::EVENT_TYPE_KEY_RELEASED:
      web_event->type = blink::WebInputEvent::KeyUp;
      break;
    default:
      NOTREACHED();
  }

  web_event->key = event->key_data->windows_key_code;
  web_event->charCode = event->key_data->text;
  web_event->unmodifiedCharCode = event->key_data->unmodified_text;

  return web_event.Pass();
}

scoped_ptr<blink::WebInputEvent> BuildWebWheelEvent(
    const mojo::EventPtr& event, float device_pixel_ratio) {
  scoped_ptr<blink::WebWheelEvent> web_event(new blink::WebWheelEvent);

  web_event->modifiers = EventFlagsToWebInputEventModifiers(event->flags);
  web_event->timeStampMS =
      base::TimeDelta::FromInternalValue(event->time_stamp).InMillisecondsF();

  web_event->type = blink::WebInputEvent::WheelEvent;

  const auto& location = event->location_data->in_view_location;
  web_event->x = location->x / device_pixel_ratio;
  web_event->y = location->y / device_pixel_ratio;

  web_event->offsetX = event->wheel_data->x_offset / device_pixel_ratio;
  web_event->offsetY = event->wheel_data->y_offset / device_pixel_ratio;

  return web_event.Pass();
}

}  // namespace

scoped_ptr<blink::WebInputEvent> ConvertEvent(const mojo::EventPtr& event,
                                              float device_pixel_ratio) {
  if (event->action == mojo::EVENT_TYPE_TOUCH_RELEASED ||
      event->action == mojo::EVENT_TYPE_TOUCH_PRESSED ||
      event->action == mojo::EVENT_TYPE_TOUCH_MOVED ||
      event->action == mojo::EVENT_TYPE_TOUCH_CANCELLED ||
      event->action == mojo::EVENT_TYPE_MOUSE_DRAGGED ||
      event->action == mojo::EVENT_TYPE_MOUSE_PRESSED ||
      event->action == mojo::EVENT_TYPE_MOUSE_RELEASED) {
    return BuildWebPointerEvent(event, device_pixel_ratio);
  } else if (event->action == mojo::EVENT_TYPE_GESTURE_SCROLL_BEGIN ||
             event->action == mojo::EVENT_TYPE_GESTURE_SCROLL_END ||
             event->action == mojo::EVENT_TYPE_GESTURE_SCROLL_UPDATE ||
             event->action == mojo::EVENT_TYPE_GESTURE_TAP ||
             event->action == mojo::EVENT_TYPE_GESTURE_TAP_DOWN ||
             event->action == mojo::EVENT_TYPE_GESTURE_TAP_CANCEL ||
             event->action == mojo::EVENT_TYPE_GESTURE_TAP_UNCONFIRMED ||
             event->action == mojo::EVENT_TYPE_GESTURE_DOUBLE_TAP ||
             event->action == mojo::EVENT_TYPE_GESTURE_BEGIN ||
             event->action == mojo::EVENT_TYPE_GESTURE_END ||
             event->action == mojo::EVENT_TYPE_GESTURE_TWO_FINGER_TAP ||
             event->action == mojo::EVENT_TYPE_GESTURE_PINCH_BEGIN ||
             event->action == mojo::EVENT_TYPE_GESTURE_PINCH_END ||
             event->action == mojo::EVENT_TYPE_GESTURE_PINCH_UPDATE ||
             event->action == mojo::EVENT_TYPE_GESTURE_LONG_PRESS ||
             event->action == mojo::EVENT_TYPE_GESTURE_LONG_TAP ||
             event->action == mojo::EVENT_TYPE_GESTURE_SWIPE ||
             event->action == mojo::EVENT_TYPE_GESTURE_SHOW_PRESS ||
             event->action == mojo::EVENT_TYPE_GESTURE_WIN8_EDGE_SWIPE ||
             event->action == mojo::EVENT_TYPE_SCROLL_FLING_START ||
             event->action == mojo::EVENT_TYPE_SCROLL_FLING_CANCEL) {
    return BuildWebGestureEvent(event, device_pixel_ratio);
  } else if ((event->action == mojo::EVENT_TYPE_KEY_PRESSED ||
              event->action == mojo::EVENT_TYPE_KEY_RELEASED) &&
             event->key_data) {
    return BuildWebKeyboardEvent(event, device_pixel_ratio);
  } else if (event->action == mojo::EVENT_TYPE_MOUSEWHEEL &&
             event->wheel_data) {
    return BuildWebWheelEvent(event, device_pixel_ratio);
  }

  return scoped_ptr<blink::WebInputEvent>();
}

}  // namespace mojo
<commit_msg>Don't spam the log for gesture events<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "sky/viewer/converters/input_event_types.h"

#include "base/logging.h"
#include "base/time/time.h"
#include "mojo/services/input_events/public/interfaces/input_event_constants.mojom.h"
#include "sky/engine/public/platform/WebInputEvent.h"

namespace sky {
namespace {

int EventFlagsToWebInputEventModifiers(int flags) {
  return
      (flags & mojo::EVENT_FLAGS_SHIFT_DOWN ?
       blink::WebInputEvent::ShiftKey : 0) |
      (flags & mojo::EVENT_FLAGS_CONTROL_DOWN ?
       blink::WebInputEvent::ControlKey : 0) |
      (flags & mojo::EVENT_FLAGS_CAPS_LOCK_DOWN ?
       blink::WebInputEvent::CapsLockOn : 0) |
      (flags & mojo::EVENT_FLAGS_ALT_DOWN ?
       blink::WebInputEvent::AltKey : 0);
}

scoped_ptr<blink::WebInputEvent> BuildWebPointerEvent(
    const mojo::EventPtr& event, float device_pixel_ratio) {
  scoped_ptr<blink::WebPointerEvent> web_event(new blink::WebPointerEvent);

  web_event->modifiers = EventFlagsToWebInputEventModifiers(event->flags);
  web_event->timeStampMS =
      base::TimeDelta::FromInternalValue(event->time_stamp).InMillisecondsF();

  switch (event->action) {
    case mojo::EVENT_TYPE_TOUCH_PRESSED:
    case mojo::EVENT_TYPE_MOUSE_PRESSED:
      web_event->type = blink::WebInputEvent::PointerDown;
      break;
    case mojo::EVENT_TYPE_TOUCH_MOVED:
    case mojo::EVENT_TYPE_MOUSE_DRAGGED:
      web_event->type = blink::WebInputEvent::PointerMove;
      break;
    case mojo::EVENT_TYPE_TOUCH_RELEASED:
    case mojo::EVENT_TYPE_MOUSE_RELEASED:
      web_event->type = blink::WebInputEvent::PointerUp;
      break;
    case mojo::EVENT_TYPE_TOUCH_CANCELLED:
      // FIXME: What mouse event should we listen to in order to learn when the
      // mouse moves out of the mojo::View?
      web_event->type = blink::WebInputEvent::PointerCancel;
      break;
    default:
      NOTIMPLEMENTED() << "Received unexpected event: " << event->action;
      break;
  }

  switch (event->action) {
    case mojo::EVENT_TYPE_TOUCH_CANCELLED:
    case mojo::EVENT_TYPE_TOUCH_MOVED:
    case mojo::EVENT_TYPE_TOUCH_PRESSED:
    case mojo::EVENT_TYPE_TOUCH_RELEASED:
      web_event->kind = blink::WebPointerEvent::Touch;
      break;
    case mojo::EVENT_TYPE_MOUSE_DRAGGED:
    case mojo::EVENT_TYPE_MOUSE_EXITED:
    case mojo::EVENT_TYPE_MOUSE_PRESSED:
    case mojo::EVENT_TYPE_MOUSE_RELEASED:
      web_event->kind = blink::WebPointerEvent::Mouse;
      break;
    default:
      NOTIMPLEMENTED() << "Received unexpected event: " << event->action;
      break;
  }

  if (event->touch_data)
    web_event->pointer = event->touch_data->pointer_id;

  const auto& location = event->location_data->in_view_location;
  web_event->x = location->x / device_pixel_ratio;
  web_event->y = location->y / device_pixel_ratio;

  return web_event.Pass();
}

scoped_ptr<blink::WebInputEvent> BuildWebGestureEvent(
    const mojo::EventPtr& event,
    float device_pixel_ratio) {
  scoped_ptr<blink::WebGestureEvent> web_event(new blink::WebGestureEvent);

  web_event->modifiers = EventFlagsToWebInputEventModifiers(event->flags);
  web_event->timeStampMS =
      base::TimeDelta::FromInternalValue(event->time_stamp).InMillisecondsF();

  switch (event->action) {
    case mojo::EVENT_TYPE_GESTURE_SCROLL_BEGIN:
      web_event->type = blink::WebInputEvent::GestureScrollBegin;
      break;
    case mojo::EVENT_TYPE_GESTURE_SCROLL_END:
      web_event->type = blink::WebInputEvent::GestureScrollEnd;
      break;
    case mojo::EVENT_TYPE_GESTURE_SCROLL_UPDATE:
      web_event->type = blink::WebInputEvent::GestureScrollUpdate;
      web_event->data.scrollUpdate.deltaX =
          event->gesture_data->scroll_x / device_pixel_ratio;
      web_event->data.scrollUpdate.deltaY =
          event->gesture_data->scroll_y / device_pixel_ratio;
      break;
    case mojo::EVENT_TYPE_SCROLL_FLING_START:
      web_event->type = blink::WebInputEvent::GestureFlingStart;
      // TODO(abarth): Why don't we need to divide by the device_pixel_ratio
      // here? For some reason, this seems to get the right velocity.
      web_event->data.flingStart.velocityX = event->gesture_data->velocity_x;
      web_event->data.flingStart.velocityY = event->gesture_data->velocity_y;
      break;
    case mojo::EVENT_TYPE_SCROLL_FLING_CANCEL:
      web_event->type = blink::WebInputEvent::GestureFlingCancel;
      break;
    case mojo::EVENT_TYPE_GESTURE_SHOW_PRESS:
      web_event->type = blink::WebInputEvent::GestureShowPress;
      break;
    case mojo::EVENT_TYPE_GESTURE_TAP:
      web_event->type = blink::WebInputEvent::GestureTap;
      web_event->data.tap.tapCount = event->gesture_data->tap_count;
      break;
    case mojo::EVENT_TYPE_GESTURE_TAP_UNCONFIRMED:
      web_event->type = blink::WebInputEvent::GestureTapUnconfirmed;
      web_event->data.tap.tapCount = event->gesture_data->tap_count;
      break;
    case mojo::EVENT_TYPE_GESTURE_TAP_DOWN:
      web_event->type = blink::WebInputEvent::GestureTapDown;
      break;
    case mojo::EVENT_TYPE_GESTURE_TAP_CANCEL:
      web_event->type = blink::WebInputEvent::GestureTapCancel;
      break;
    case mojo::EVENT_TYPE_GESTURE_DOUBLE_TAP:
      web_event->type = blink::WebInputEvent::GestureDoubleTap;
      web_event->data.tap.tapCount = event->gesture_data->tap_count;
      break;
    case mojo::EVENT_TYPE_GESTURE_TWO_FINGER_TAP:
      web_event->type = blink::WebInputEvent::GestureTwoFingerTap;
      break;
    case mojo::EVENT_TYPE_GESTURE_LONG_PRESS:
      web_event->type = blink::WebInputEvent::GestureLongPress;
      break;
    case mojo::EVENT_TYPE_GESTURE_LONG_TAP:
      web_event->type = blink::WebInputEvent::GestureLongTap;
      break;
    case mojo::EVENT_TYPE_GESTURE_PINCH_BEGIN:
      web_event->type = blink::WebInputEvent::GesturePinchBegin;
      break;
    case mojo::EVENT_TYPE_GESTURE_PINCH_END:
      web_event->type = blink::WebInputEvent::GesturePinchEnd;
      break;
    case mojo::EVENT_TYPE_GESTURE_PINCH_UPDATE:
      web_event->type = blink::WebInputEvent::GesturePinchUpdate;
      web_event->data.pinchUpdate.scale =
          event->gesture_data->scale / device_pixel_ratio;
      break;
    default:
      break;
  }

  web_event->x = event->location_data->in_view_location->x / device_pixel_ratio;
  web_event->y = event->location_data->in_view_location->y / device_pixel_ratio;

  return web_event.Pass();
}

scoped_ptr<blink::WebInputEvent> BuildWebKeyboardEvent(
    const mojo::EventPtr& event,
    float device_pixel_ratio) {
  scoped_ptr<blink::WebKeyboardEvent> web_event(new blink::WebKeyboardEvent);

  web_event->modifiers = EventFlagsToWebInputEventModifiers(event->flags);
  web_event->timeStampMS =
      base::TimeDelta::FromInternalValue(event->time_stamp).InMillisecondsF();

  switch (event->action) {
    case mojo::EVENT_TYPE_KEY_PRESSED:
      web_event->type = event->key_data->is_char ? blink::WebInputEvent::Char :
          blink::WebInputEvent::KeyDown;
      break;
    case mojo::EVENT_TYPE_KEY_RELEASED:
      web_event->type = blink::WebInputEvent::KeyUp;
      break;
    default:
      NOTREACHED();
  }

  web_event->key = event->key_data->windows_key_code;
  web_event->charCode = event->key_data->text;
  web_event->unmodifiedCharCode = event->key_data->unmodified_text;

  return web_event.Pass();
}

scoped_ptr<blink::WebInputEvent> BuildWebWheelEvent(
    const mojo::EventPtr& event, float device_pixel_ratio) {
  scoped_ptr<blink::WebWheelEvent> web_event(new blink::WebWheelEvent);

  web_event->modifiers = EventFlagsToWebInputEventModifiers(event->flags);
  web_event->timeStampMS =
      base::TimeDelta::FromInternalValue(event->time_stamp).InMillisecondsF();

  web_event->type = blink::WebInputEvent::WheelEvent;

  const auto& location = event->location_data->in_view_location;
  web_event->x = location->x / device_pixel_ratio;
  web_event->y = location->y / device_pixel_ratio;

  web_event->offsetX = event->wheel_data->x_offset / device_pixel_ratio;
  web_event->offsetY = event->wheel_data->y_offset / device_pixel_ratio;

  return web_event.Pass();
}

}  // namespace

scoped_ptr<blink::WebInputEvent> ConvertEvent(const mojo::EventPtr& event,
                                              float device_pixel_ratio) {
  if (event->action == mojo::EVENT_TYPE_TOUCH_RELEASED ||
      event->action == mojo::EVENT_TYPE_TOUCH_PRESSED ||
      event->action == mojo::EVENT_TYPE_TOUCH_MOVED ||
      event->action == mojo::EVENT_TYPE_TOUCH_CANCELLED ||
      event->action == mojo::EVENT_TYPE_MOUSE_DRAGGED ||
      event->action == mojo::EVENT_TYPE_MOUSE_PRESSED ||
      event->action == mojo::EVENT_TYPE_MOUSE_RELEASED) {
    return BuildWebPointerEvent(event, device_pixel_ratio);
  } else if (event->action == mojo::EVENT_TYPE_GESTURE_SCROLL_BEGIN ||
             event->action == mojo::EVENT_TYPE_GESTURE_SCROLL_END ||
             event->action == mojo::EVENT_TYPE_GESTURE_SCROLL_UPDATE ||
             event->action == mojo::EVENT_TYPE_GESTURE_TAP ||
             event->action == mojo::EVENT_TYPE_GESTURE_TAP_DOWN ||
             event->action == mojo::EVENT_TYPE_GESTURE_TAP_CANCEL ||
             event->action == mojo::EVENT_TYPE_GESTURE_TAP_UNCONFIRMED ||
             event->action == mojo::EVENT_TYPE_GESTURE_DOUBLE_TAP ||
             event->action == mojo::EVENT_TYPE_GESTURE_BEGIN ||
             event->action == mojo::EVENT_TYPE_GESTURE_END ||
             event->action == mojo::EVENT_TYPE_GESTURE_TWO_FINGER_TAP ||
             event->action == mojo::EVENT_TYPE_GESTURE_PINCH_BEGIN ||
             event->action == mojo::EVENT_TYPE_GESTURE_PINCH_END ||
             event->action == mojo::EVENT_TYPE_GESTURE_PINCH_UPDATE ||
             event->action == mojo::EVENT_TYPE_GESTURE_LONG_PRESS ||
             event->action == mojo::EVENT_TYPE_GESTURE_LONG_TAP ||
             event->action == mojo::EVENT_TYPE_GESTURE_SWIPE ||
             event->action == mojo::EVENT_TYPE_GESTURE_SHOW_PRESS ||
             event->action == mojo::EVENT_TYPE_GESTURE_WIN8_EDGE_SWIPE ||
             event->action == mojo::EVENT_TYPE_SCROLL_FLING_START ||
             event->action == mojo::EVENT_TYPE_SCROLL_FLING_CANCEL) {
    return BuildWebGestureEvent(event, device_pixel_ratio);
  } else if ((event->action == mojo::EVENT_TYPE_KEY_PRESSED ||
              event->action == mojo::EVENT_TYPE_KEY_RELEASED) &&
             event->key_data) {
    return BuildWebKeyboardEvent(event, device_pixel_ratio);
  } else if (event->action == mojo::EVENT_TYPE_MOUSEWHEEL &&
             event->wheel_data) {
    return BuildWebWheelEvent(event, device_pixel_ratio);
  }

  return scoped_ptr<blink::WebInputEvent>();
}

}  // namespace mojo
<|endoftext|>


<commit_before>/*
	Copyright (c) 2014, Madd Games.
	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.

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

#include <Apoc/Entity/World.h>
#include <Apoc/Video/RenderHandler.h>
#include <math.h>

#ifdef ENABLE_OPENAL
#include <AL/alut.h>
#endif

#ifndef M_PI
#define	M_PI 3.14159265359
#endif

extern RenderHandler *apocRenderHandler;

vector<Entity*> World::entities;
vector<Entity*> World::addQueue;
vector<Emitter*> World::emitters;
vector<Field*> World::fields;
Camera *World::camera = NULL;

void World::ActFields(EntityPhysics *phe, int dt)
{
	vector<Field*>::iterator it;
	for (it=fields.begin(); it!=fields.end(); ++it)
	{
		(*it)->actOn(phe, dt);
	};
};

void World::addEntity(Entity *entity)
{
	addQueue.push_back(entity);
};

void World::update()
{
	vector<Entity*>::iterator it;
	for (it=addQueue.begin(); it!=addQueue.end(); ++it)
	{
		entities.push_back(*it);
	};
	addQueue.clear();

	it = entities.begin();
	while (it != entities.end())
	{
		(*it)->update();
		if ((*it)->shouldRemove)
		{
			delete (*it);
			it = entities.erase(it);
		}
		else
		{
			it++;
		};
	};
};

void World::render(bool setMatrix)
{
	if (setMatrix)
	{
		GLint uViewMatrix = apocRenderHandler->getUniformLocation("uViewMatrix");
		GLint uEyePos = apocRenderHandler->getUniformLocation("uEyePos");
		Vector eye = Vector::Origin;
		if (camera != NULL)
		{
			eye = camera->getEye();
		};
		glUniform4fv(uEyePos, 1, &eye[0]);

		Matrix viewMatrix;
		if (camera != NULL)
		{
			viewMatrix = Matrix::LookAt(
				camera->getEye(),
				camera->getUpVector(),
				camera->getRef()
			);

#ifdef ENABLE_OPENAL
			Vector pos = camera->getEye();
			Vector orient = camera->getRef() - camera->getEye();

			alListenerfv(AL_POSITION, &pos[0]);
			alListenerfv(AL_ORIENTATION, &orient[0]);
#endif
		}
		else
		{
			viewMatrix = Matrix::LookAt(
				Vector(0.0, 2.0, -10.0),
				Vector(0.0, 1.0, 0.0),
				Vector(0.0, 0.0, 0.0)
			);
		};

		GLint uProjMatrix = apocRenderHandler->getUniformLocation("uProjectionMatrix");
		Matrix projMatrix = Matrix::Perspective(1366.0, 768.0, 1.0, 1000.0, 60.0*M_PI/180.0);
		glUniformMatrix4fv(uViewMatrix, 1, GL_FALSE, &viewMatrix[0][0]);
		glUniformMatrix4fv(uProjMatrix, 1, GL_FALSE, &projMatrix[0][0]);
	};

	vector<Entity*>::iterator it;
	for (it=entities.begin(); it!=entities.end(); ++it)
	{
		(*it)->renderObjects();
	};
};

void World::renderParticles()
{
	vector<Emitter*>::iterator eit = emitters.begin();
	while (eit != emitters.end())
	{
		(*eit)->update();
		if ((*eit)->shouldRemove)
		{
			delete (*eit);
			eit = emitters.erase(eit);
		}
		else
		{
			(*eit)->render();
			++eit;
		};
	};
};

void World::setCamera(Camera *camera)
{
	World::camera = camera;
};

void World::addEmitter(Emitter *emitter)
{
	emitters.push_back(emitter);
};

void World::addField(Field *field)
{
	fields.push_back(field);
};

vector<Entity*> World::findWithinRadius(Vector pos, float r)
{
	vector<Entity*> output;
	vector<Entity*>::iterator it;

	for (it=entities.begin(); it!=entities.end(); ++it)
	{
		Vector center = (*it)->getModelMatrix()[3];
		if ((pos-center).length() <= r)
		{
			output.push_back(*it);
		};
	};

	return output;
};
<commit_msg>Bugfix<commit_after>/*
	Copyright (c) 2014, Madd Games.
	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.

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

#include <Apoc/Entity/World.h>
#include <Apoc/Video/RenderHandler.h>
#include <math.h>

#ifdef ENABLE_OPENAL
#include <AL/alut.h>
#endif

#ifndef M_PI
#define	M_PI 3.14159265359
#endif

extern RenderHandler *apocRenderHandler;

vector<Entity*> World::entities;
vector<Entity*> World::addQueue;
vector<Emitter*> World::emitters;
vector<Field*> World::fields;
Camera *World::camera = NULL;

void World::ActFields(EntityPhysics *phe, int dt)
{
	vector<Field*>::iterator it;
	for (it=fields.begin(); it!=fields.end(); ++it)
	{
		(*it)->actOn(phe, dt);
	};
};

void World::addEntity(Entity *entity)
{
	addQueue.push_back(entity);
};

void World::update()
{
	vector<Entity*>::iterator it;
	for (it=addQueue.begin(); it!=addQueue.end(); ++it)
	{
		entities.push_back(*it);
	};
	addQueue.clear();

	it = entities.begin();
	while (it != entities.end())
	{
		(*it)->update();
		if ((*it)->shouldRemove)
		{
			delete (*it);
			it = entities.erase(it);
		}
		else
		{
			it++;
		};
	};
};

void World::render(bool setMatrix)
{
	if (setMatrix)
	{
		GLint uViewMatrix = apocRenderHandler->getUniformLocation("uViewMatrix");
		GLint uEyePos = apocRenderHandler->getUniformLocation("uEyePos");
		Vector eye = Vector::Origin;
		if (camera != NULL)
		{
			eye = camera->getEye();
		};
		glUniform4fv(uEyePos, 1, &eye[0]);

		Matrix viewMatrix;
		if (camera != NULL)
		{
			viewMatrix = Matrix::LookAt(
				camera->getEye(),
				camera->getUpVector(),
				camera->getRef()
			);

#ifdef ENABLE_OPENAL
			Vector pos = camera->getEye();
			Vector orient = camera->getRef() - camera->getEye();

			alListenerfv(AL_POSITION, &pos[0]);
			alListenerfv(AL_ORIENTATION, &orient[0]);
#endif
		}
		else
		{
			viewMatrix = Matrix::LookAt(
				Vector(0.0, 0.0, 0.0),
				Vector(0.0, 1.0, 0.0),
				Vector(0.0, 0.0, 1.0)
			);
		};

		GLint uProjMatrix = apocRenderHandler->getUniformLocation("uProjectionMatrix");
		Matrix projMatrix = Matrix::Perspective(1366.0, 768.0, 1.0, 1000.0, 60.0*M_PI/180.0);
		glUniformMatrix4fv(uViewMatrix, 1, GL_FALSE, &viewMatrix[0][0]);
		glUniformMatrix4fv(uProjMatrix, 1, GL_FALSE, &projMatrix[0][0]);
	};

	vector<Entity*>::iterator it;
	for (it=entities.begin(); it!=entities.end(); ++it)
	{
		(*it)->renderObjects();
	};
};

void World::renderParticles()
{
	vector<Emitter*>::iterator eit = emitters.begin();
	while (eit != emitters.end())
	{
		(*eit)->update();
		if ((*eit)->shouldRemove)
		{
			delete (*eit);
			eit = emitters.erase(eit);
		}
		else
		{
			(*eit)->render();
			++eit;
		};
	};
};

void World::setCamera(Camera *camera)
{
	World::camera = camera;
};

void World::addEmitter(Emitter *emitter)
{
	emitters.push_back(emitter);
};

void World::addField(Field *field)
{
	fields.push_back(field);
};

vector<Entity*> World::findWithinRadius(Vector pos, float r)
{
	vector<Entity*> output;
	vector<Entity*>::iterator it;

	for (it=entities.begin(); it!=entities.end(); ++it)
	{
		Vector center = (*it)->getModelMatrix()[3];
		if ((pos-center).length() <= r)
		{
			output.push_back(*it);
		};
	};

	return output;
};
<|endoftext|>


<commit_before>//#include "communicator.h" // ### implement later to handle communication with other clients via central server
#include "mainwindow.h"
#include "taskmanager.h"
#include <QDateTime>
#include <QDate>
#include <QDateTime>
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    const qint64 roleId1 = TaskManager::instance()->addRole(QSharedPointer<Role>(new Role("role 1")));
    const qint64 roleId2 = TaskManager::instance()->addRole(QSharedPointer<Role>(new Role("role 2")));
    const qint64 roleId3 = TaskManager::instance()->addRole(QSharedPointer<Role>(new Role("role 3")));
    const qint64 roleId4 = TaskManager::instance()->addRole(QSharedPointer<Role>(new Role("role 4")));
    const qint64 roleId5 = TaskManager::instance()->addRole(QSharedPointer<Role>(new Role("role 5")));
    const qint64 roleId6 = TaskManager::instance()->addRole(QSharedPointer<Role>(new Role("role 6")));
    const qint64 roleId7 = TaskManager::instance()->addRole(QSharedPointer<Role>(new Role("role 7")));

    const qint64 taskId1 = TaskManager::instance()
            ->addTask(QSharedPointer<Task>(new Task("task 1",
                                                    QDateTime(QDate(2015, 4, 1), QTime(0, 0)),
                                                    QDateTime(QDate(2015, 4, 2), QTime(0, 0)))));
    const qint64 taskId2 = TaskManager::instance()
            ->addTask(QSharedPointer<Task>(new Task("task 2",
                                                    QDateTime(QDate(2015, 4, 1), QTime(12, 0)),
                                                    QDateTime(QDate(2015, 4, 2), QTime(0, 0)))));
    const qint64 taskId3 = TaskManager::instance()
            ->addTask(QSharedPointer<Task>(new Task("task 3",
                                                    QDateTime(QDate(2015, 4, 1), QTime(0, 0)),
                                                    QDateTime(QDate(2015, 4, 1), QTime(12, 0)))));
    const qint64 taskId4 = TaskManager::instance()
            ->addTask(QSharedPointer<Task>(new Task("task 4",
                                                    QDateTime(QDate(2015, 4, 1), QTime(23, 45)),
                                                    QDateTime(QDate(2015, 4, 2), QTime(0, 15)))));

    const qint64 taskId5 = TaskManager::instance()
            ->addTask(QSharedPointer<Task>(new Task("task 5",
                                                    QDateTime(QDate(2015, 4, 2), QTime(0, 0)),
                                                    QDateTime(QDate(2015, 4, 2), QTime(1, 0)))));

    TaskManager::instance()->assignTaskToRole(taskId1, roleId2);
    TaskManager::instance()->assignTaskToRole(taskId2, roleId2);
    TaskManager::instance()->assignTaskToRole(taskId4, roleId3);
    TaskManager::instance()->assignTaskToRole(taskId1, roleId1); // to check reassignment to a different role
    TaskManager::instance()->assignTaskToRole(taskId3, roleId4);
    TaskManager::instance()->assignTaskToRole(taskId5, roleId4);

    MainWindow window(QDate(2015, 4, 1), 7);
    window.show();

    TaskManager::instance()->emitUpdated(); // ensure views are initialized
    return app.exec();
}
<commit_msg>Made random generator depend on current time<commit_after>//#include "communicator.h" // ### implement later to handle communication with other clients via central server
#include "mainwindow.h"
#include "taskmanager.h"
#include <QDateTime>
#include <QDate>
#include <QDateTime>
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    qsrand(QDateTime::currentDateTime().toTime_t());

    const qint64 roleId1 = TaskManager::instance()->addRole(QSharedPointer<Role>(new Role("role 1")));
    const qint64 roleId2 = TaskManager::instance()->addRole(QSharedPointer<Role>(new Role("role 2")));
    const qint64 roleId3 = TaskManager::instance()->addRole(QSharedPointer<Role>(new Role("role 3")));
    const qint64 roleId4 = TaskManager::instance()->addRole(QSharedPointer<Role>(new Role("role 4")));
    const qint64 roleId5 = TaskManager::instance()->addRole(QSharedPointer<Role>(new Role("role 5")));
    const qint64 roleId6 = TaskManager::instance()->addRole(QSharedPointer<Role>(new Role("role 6")));
    const qint64 roleId7 = TaskManager::instance()->addRole(QSharedPointer<Role>(new Role("role 7")));

    const qint64 taskId1 = TaskManager::instance()
            ->addTask(QSharedPointer<Task>(new Task("task 1",
                                                    QDateTime(QDate(2015, 4, 1), QTime(0, 0)),
                                                    QDateTime(QDate(2015, 4, 2), QTime(0, 0)))));
    const qint64 taskId2 = TaskManager::instance()
            ->addTask(QSharedPointer<Task>(new Task("task 2",
                                                    QDateTime(QDate(2015, 4, 1), QTime(12, 0)),
                                                    QDateTime(QDate(2015, 4, 2), QTime(0, 0)))));
    const qint64 taskId3 = TaskManager::instance()
            ->addTask(QSharedPointer<Task>(new Task("task 3",
                                                    QDateTime(QDate(2015, 4, 1), QTime(0, 0)),
                                                    QDateTime(QDate(2015, 4, 1), QTime(12, 0)))));
    const qint64 taskId4 = TaskManager::instance()
            ->addTask(QSharedPointer<Task>(new Task("task 4",
                                                    QDateTime(QDate(2015, 4, 1), QTime(23, 45)),
                                                    QDateTime(QDate(2015, 4, 2), QTime(0, 15)))));

    const qint64 taskId5 = TaskManager::instance()
            ->addTask(QSharedPointer<Task>(new Task("task 5",
                                                    QDateTime(QDate(2015, 4, 2), QTime(0, 0)),
                                                    QDateTime(QDate(2015, 4, 2), QTime(1, 0)))));

    TaskManager::instance()->assignTaskToRole(taskId1, roleId2);
    TaskManager::instance()->assignTaskToRole(taskId2, roleId2);
    TaskManager::instance()->assignTaskToRole(taskId4, roleId3);
    TaskManager::instance()->assignTaskToRole(taskId1, roleId1); // to check reassignment to a different role
    TaskManager::instance()->assignTaskToRole(taskId3, roleId4);
    TaskManager::instance()->assignTaskToRole(taskId5, roleId4);

    MainWindow window(QDate(2015, 4, 1), 7);
    window.show();

    TaskManager::instance()->emitUpdated(); // ensure views are initialized
    return app.exec();
}
<|endoftext|>


<commit_before>/*
 * Copyright 2016 The Cartographer Authors
 *
 * 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 "cartographer/io/xray_points_processor.h"

#include <cmath>
#include <string>

#include "Eigen/Core"
#include "cairo/cairo.h"
#include "cartographer/common/lua_parameter_dictionary.h"
#include "cartographer/common/make_unique.h"
#include "cartographer/common/math.h"
#include "cartographer/io/cairo_types.h"
#include "cartographer/mapping_3d/hybrid_grid.h"

namespace cartographer {
namespace io {
namespace {

// Takes the logarithm of each value in 'mat', clamping to 0 as smallest value.
void TakeLogarithm(Eigen::MatrixXf* mat) {
  for (int y = 0; y < mat->rows(); ++y) {
    for (int x = 0; x < mat->cols(); ++x) {
      const float value = (*mat)(y, x);
      if (value == 0.f) {
        continue;
      }
      const float new_value = std::log(value);
      (*mat)(y, x) = new_value;
    }
  }
}

// Write 'mat' as a pleasing-to-look-at PNG into 'filename'
void WritePng(const string& filename, const Eigen::MatrixXf& mat) {
  const int stride =
      cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, mat.cols());
  std::vector<uint32_t> pixels(stride * mat.rows(), 0.);

  const float max = mat.maxCoeff();
  for (int y = 0; y < mat.rows(); ++y) {
    for (int x = 0; x < mat.cols(); ++x) {
      const float value = mat(y, x);
      uint8_t shade = common::RoundToInt(255.f * (1.f - value / max));
      pixels[y * stride / 4 + x] =
          (255 << 24) | (shade << 16) | (shade << 8) | shade;
    }
  }

  // TODO(hrapp): cairo_image_surface_create_for_data does not take ownership of
  // the data until the surface is finalized. Once it is finalized though,
  // cairo_surface_write_to_png fails, complaining that the surface is already
  // finalized. This makes it pretty hard to pass back ownership of the image to
  // the caller.
  cairo::UniqueSurfacePtr surface(
      cairo_image_surface_create_for_data(
          reinterpret_cast<unsigned char*>(pixels.data()), CAIRO_FORMAT_ARGB32,
          mat.cols(), mat.rows(), stride),
      cairo_surface_destroy);
  cairo_surface_write_to_png(surface.get(), filename.c_str());
}

}  // namespace

XRayPointsProcessor::XRayPointsProcessor(const double voxel_size,
                                         const transform::Rigid3f& transform,
                                         const string& output_filename,
                                         PointsProcessor* next)
    : next_(next),
      output_filename_(output_filename),
      transform_(transform),
      voxels_(voxel_size, Eigen::Vector3f::Zero()) {}

std::unique_ptr<XRayPointsProcessor> XRayPointsProcessor::FromDictionary(
    common::LuaParameterDictionary* dictionary, PointsProcessor* next) {
  return common::make_unique<XRayPointsProcessor>(
      dictionary->GetDouble("voxel_size"),
      transform::FromDictionary(dictionary->GetDictionary("transform").get())
          .cast<float>(),
      dictionary->GetString("filename"), next);
}

void XRayPointsProcessor::Process(std::unique_ptr<PointsBatch> batch) {
  for (const auto& point : batch->points) {
    const Eigen::Vector3f camera_point = transform_ * point;
    *voxels_.mutable_value(voxels_.GetCellIndex(camera_point)) = true;
  }
  next_->Process(std::move(batch));
}

PointsProcessor::FlushResult XRayPointsProcessor::Flush() {
  WriteImage();
  switch (next_->Flush()) {
    case FlushResult::kRestartStream:
      LOG(FATAL) << "X-Ray generation must be configured to occur after any "
                    "stages that require multiple passes.";

    case FlushResult::kFinished:
      return FlushResult::kFinished;
  }
  LOG(FATAL);
}

void XRayPointsProcessor::WriteImage() {
  Eigen::Array3i min(std::numeric_limits<int>::max(),
                     std::numeric_limits<int>::max(),
                     std::numeric_limits<int>::max());
  Eigen::Array3i max(std::numeric_limits<int>::min(),
                     std::numeric_limits<int>::min(),
                     std::numeric_limits<int>::min());

  // Find the maximum and minimum cells.
  for (Voxels::Iterator it(voxels_); !it.Done(); it.Next()) {
    const Eigen::Array3i idx = it.GetCellIndex();
    min = min.min(idx);
    max = max.max(idx);
  }

  // Returns the (x, y) pixel of the given 'index'.
  const auto voxel_index_to_pixel = [&max, &min](const Eigen::Array3i& index) {
    // We flip the y axis, since matrices rows are counted from the top.
    return Eigen::Array2i(max[1] - index[1], max[2] - index[2]);
  };

  // Hybrid grid uses X: forward, Y: left, Z: up.
  // For the screen we are using. X: right, Y: up
  const int xsize = max[1] - min[1] + 1;
  const int ysize = max[2] - min[2] + 1;
  Eigen::MatrixXf image = Eigen::MatrixXf::Zero(ysize, xsize);
  for (Voxels::Iterator it(voxels_); !it.Done(); it.Next()) {
    const Eigen::Array2i pixel = voxel_index_to_pixel(it.GetCellIndex());
    ++image(pixel.y(), pixel.x());
  }
  TakeLogarithm(&image);
  WritePng(output_filename_, image);
}

}  // namespace io
}  // namespace cartographer
<commit_msg>Fix and add CHECKs when writing X-ray output. (#120)<commit_after>/*
 * Copyright 2016 The Cartographer Authors
 *
 * 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 "cartographer/io/xray_points_processor.h"

#include <cmath>
#include <string>

#include "Eigen/Core"
#include "cairo/cairo.h"
#include "cartographer/common/lua_parameter_dictionary.h"
#include "cartographer/common/make_unique.h"
#include "cartographer/common/math.h"
#include "cartographer/io/cairo_types.h"
#include "cartographer/mapping_3d/hybrid_grid.h"

namespace cartographer {
namespace io {
namespace {

// Takes the logarithm of each value in 'mat', clamping to 0 as smallest value.
void TakeLogarithm(Eigen::MatrixXf* mat) {
  for (int y = 0; y < mat->rows(); ++y) {
    for (int x = 0; x < mat->cols(); ++x) {
      const float value = (*mat)(y, x);
      if (value == 0.f) {
        continue;
      }
      const float new_value = std::log(value);
      (*mat)(y, x) = new_value;
    }
  }
}

// Write 'mat' as a pleasing-to-look-at PNG into 'filename'
void WritePng(const string& filename, const Eigen::MatrixXf& mat) {
  const int stride =
      cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, mat.cols());
  CHECK_EQ(stride % 4, 0);
  std::vector<uint32_t> pixels(stride / 4 * mat.rows(), 0.);

  const float max = mat.maxCoeff();
  for (int y = 0; y < mat.rows(); ++y) {
    for (int x = 0; x < mat.cols(); ++x) {
      const float value = mat(y, x);
      uint8_t shade = common::RoundToInt(255.f * (1.f - value / max));
      pixels[y * stride / 4 + x] =
          (255 << 24) | (shade << 16) | (shade << 8) | shade;
    }
  }

  // TODO(hrapp): cairo_image_surface_create_for_data does not take ownership of
  // the data until the surface is finalized. Once it is finalized though,
  // cairo_surface_write_to_png fails, complaining that the surface is already
  // finalized. This makes it pretty hard to pass back ownership of the image to
  // the caller.
  cairo::UniqueSurfacePtr surface(
      cairo_image_surface_create_for_data(
          reinterpret_cast<unsigned char*>(pixels.data()), CAIRO_FORMAT_ARGB32,
          mat.cols(), mat.rows(), stride),
      cairo_surface_destroy);
  CHECK_EQ(cairo_surface_status(surface.get()), CAIRO_STATUS_SUCCESS);
  CHECK_EQ(cairo_surface_write_to_png(surface.get(), filename.c_str()),
           CAIRO_STATUS_SUCCESS);
}

}  // namespace

XRayPointsProcessor::XRayPointsProcessor(const double voxel_size,
                                         const transform::Rigid3f& transform,
                                         const string& output_filename,
                                         PointsProcessor* next)
    : next_(next),
      output_filename_(output_filename),
      transform_(transform),
      voxels_(voxel_size, Eigen::Vector3f::Zero()) {}

std::unique_ptr<XRayPointsProcessor> XRayPointsProcessor::FromDictionary(
    common::LuaParameterDictionary* dictionary, PointsProcessor* next) {
  return common::make_unique<XRayPointsProcessor>(
      dictionary->GetDouble("voxel_size"),
      transform::FromDictionary(dictionary->GetDictionary("transform").get())
          .cast<float>(),
      dictionary->GetString("filename"), next);
}

void XRayPointsProcessor::Process(std::unique_ptr<PointsBatch> batch) {
  for (const auto& point : batch->points) {
    const Eigen::Vector3f camera_point = transform_ * point;
    *voxels_.mutable_value(voxels_.GetCellIndex(camera_point)) = true;
  }
  next_->Process(std::move(batch));
}

PointsProcessor::FlushResult XRayPointsProcessor::Flush() {
  WriteImage();
  switch (next_->Flush()) {
    case FlushResult::kRestartStream:
      LOG(FATAL) << "X-Ray generation must be configured to occur after any "
                    "stages that require multiple passes.";

    case FlushResult::kFinished:
      return FlushResult::kFinished;
  }
  LOG(FATAL);
}

void XRayPointsProcessor::WriteImage() {
  Eigen::Array3i min(std::numeric_limits<int>::max(),
                     std::numeric_limits<int>::max(),
                     std::numeric_limits<int>::max());
  Eigen::Array3i max(std::numeric_limits<int>::min(),
                     std::numeric_limits<int>::min(),
                     std::numeric_limits<int>::min());

  // Find the maximum and minimum cells.
  for (Voxels::Iterator it(voxels_); !it.Done(); it.Next()) {
    const Eigen::Array3i idx = it.GetCellIndex();
    min = min.min(idx);
    max = max.max(idx);
  }

  // Returns the (x, y) pixel of the given 'index'.
  const auto voxel_index_to_pixel = [&max, &min](const Eigen::Array3i& index) {
    // We flip the y axis, since matrices rows are counted from the top.
    return Eigen::Array2i(max[1] - index[1], max[2] - index[2]);
  };

  // Hybrid grid uses X: forward, Y: left, Z: up.
  // For the screen we are using. X: right, Y: up
  const int xsize = max[1] - min[1] + 1;
  const int ysize = max[2] - min[2] + 1;
  Eigen::MatrixXf image = Eigen::MatrixXf::Zero(ysize, xsize);
  for (Voxels::Iterator it(voxels_); !it.Done(); it.Next()) {
    const Eigen::Array2i pixel = voxel_index_to_pixel(it.GetCellIndex());
    ++image(pixel.y(), pixel.x());
  }
  TakeLogarithm(&image);
  WritePng(output_filename_, image);
}

}  // namespace io
}  // namespace cartographer
<|endoftext|>


<commit_before>#include "generator.hpp"
#include "grid.hpp"

#include <iostream>

int main(){
	Grid sample = Generator::getGrid(1);
	sample.print();
	std::cout << "All Tests Pass!" << std::endl;
	return 0;
}<commit_msg>Added testing for grids of all difficulty levels for completeness<commit_after>#include "generator.hpp"
#include "grid.hpp"

#include <iostream>

int main(){
    // Generates a grid for each difficulty level
	Grid sample = Generator::getGrid(1);
	sample.print();
	sample = Generator::getGrid(2);
	sample.print();
	sample = Generator::getGrid(3);
	sample.print();
	std::cout << "All Tests Pass!" << std::endl;
	return 0;
}
<|endoftext|>


<commit_before>// crbarker@google.com
//
// This is a ROS program to handle joystick-based navigation for portal.

#include <ros/ros.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Twist.h>

#include "joystick_navigator.h"
#include "portal_nav/PortalPose.h"

// #define DEBUG

class PortalNavigatorNode {
 public:
  PortalNavigatorNode(void) {}

  // Starts the run loop and does not return until killed.
  void Run(void);

  // Callbacks for ROS topic subscriptions:
  void HandleSpaceNav(const geometry_msgs::Twist::ConstPtr& twist);
  void HandleKioskPose(
      const portal_nav::PortalPose::ConstPtr& portal_pose);

 private:
  ros::NodeHandle n_;
  ros::Subscriber spacenav_sub_;
  ros::Subscriber kiosk_pose_sub_;
  ros::Publisher joystick_pub_;
  ros::Publisher kiosk_pub_;
  ros::Publisher display_pub_;

  double joystick_sensitivity_;

  JoystickNavigator kiosk_joystick_navigator_;
};

void PortalNavigatorNode::Run(void) {
  kiosk_pub_ = n_.advertise<geometry_msgs::PoseStamped>(
      "/portal_nav/kiosk_goto_pose", 1);
  display_pub_ = n_.advertise<geometry_msgs::PoseStamped>(
      "/portal_nav/display_goto_pose", 1);

  ros::param::param<double>(
      "~joystick_sensitivity",
      joystick_sensitivity_,
      1.0);

  kiosk_joystick_navigator_.Init(
      &kiosk_pub_, &display_pub_, joystick_sensitivity_);

  // This subscriber takes commands from the SpaceNav.
  spacenav_sub_ = n_.subscribe("/spacenav/twist", 0,
      &PortalNavigatorNode::HandleSpaceNav, this);

  // This subscriber gets camera poses back from the kiosk.
  // We have a small Rx queue to make sure we don't lose any.
  kiosk_pose_sub_ = n_.subscribe("/portal_kiosk/current_pose", 10,
      &PortalNavigatorNode::HandleKioskPose, this);

  // This publishes a normalized version of the SpaceNav inputs.
  joystick_pub_ = n_.advertise<geometry_msgs::Twist>("/joystick/twist", 0);

  // Does not return until killed:
  ros::spin();
}

void PortalNavigatorNode::HandleSpaceNav(
    const geometry_msgs::Twist::ConstPtr& twist) {
  // The SpaceNav twist values range [-350, 350], so it must be
  // normalized for the joystick code, which expects [-1.0, 1.0].
  static const double kSpaceNavScale = 350.0;

  // Our JoystickNavigator expects a right-hand-rule twist, where
  // X is right/left, Y is forward/backward, and Z is up/down.
  // The SpaceNav ROS driver swaps both linear and angular x/y.
  // It also sign-flips the y for both linear and angular.
  // We correct that here:
  geometry_msgs::Twist normalized_joy;
  normalized_joy.linear.x = twist->linear.y / kSpaceNavScale * -1.0;
  normalized_joy.linear.y = twist->linear.x / kSpaceNavScale;
  normalized_joy.linear.z = twist->linear.z / kSpaceNavScale;
  normalized_joy.angular.x = twist->angular.y / kSpaceNavScale * -1.0;
  normalized_joy.angular.y = twist->angular.x / kSpaceNavScale;
  normalized_joy.angular.z = twist->angular.z / kSpaceNavScale;

  kiosk_joystick_navigator_.ProcessJoy(normalized_joy);
  joystick_pub_.publish(normalized_joy);
}

void PortalNavigatorNode::HandleKioskPose(
    const portal_nav::PortalPose::ConstPtr& portal_pose) {
#ifdef DEBUG
  ROS_INFO("HandleKioskPose curr lat:%lf, lon:%lf, alt:%lf, hdg:%lf, tlt:%lf",
           portal_pose->current_pose.position.y,
           portal_pose->current_pose.position.x,
           portal_pose->current_pose.position.z,
           portal_pose->current_pose.orientation.z,
           portal_pose->current_pose.orientation.x);
  ROS_INFO("HandleKioskPose min lat:%lf, lon:%lf, alt:%lf, hdg:%lf, tlt:%lf",
           portal_pose->pose_minimums.position.y,
           portal_pose->pose_minimums.position.x,
           portal_pose->pose_minimums.position.z,
           portal_pose->pose_minimums.orientation.z,
           portal_pose->pose_minimums.orientation.x);
  ROS_INFO("HandleKioskPose max lat:%lf, lon:%lf, alt:%lf, hdg:%lf, tlt:%lf",
           portal_pose->pose_maximums.position.y,
           portal_pose->pose_maximums.position.x,
           portal_pose->pose_maximums.position.z,
           portal_pose->pose_maximums.orientation.z,
           portal_pose->pose_maximums.orientation.x);
#endif
  kiosk_joystick_navigator_.ProcessCameraMoved(*portal_pose);
}

/*
 * main()
 */
int main(int argc, char **argv) {
  ros::init(argc, argv, "portal_nav");
  PortalNavigatorNode node;
  node.Run();
  return 0;
}
<commit_msg>Tweak portal_nav queue lengths<commit_after>// crbarker@google.com
//
// This is a ROS program to handle joystick-based navigation for portal.

#include <ros/ros.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Twist.h>

#include "joystick_navigator.h"
#include "portal_nav/PortalPose.h"

// #define DEBUG

class PortalNavigatorNode {
 public:
  PortalNavigatorNode(void) {}

  // Starts the run loop and does not return until killed.
  void Run(void);

  // Callbacks for ROS topic subscriptions:
  void HandleSpaceNav(const geometry_msgs::Twist::ConstPtr& twist);
  void HandleKioskPose(
      const portal_nav::PortalPose::ConstPtr& portal_pose);

 private:
  ros::NodeHandle n_;
  ros::Subscriber spacenav_sub_;
  ros::Subscriber kiosk_pose_sub_;
  ros::Publisher joystick_pub_;
  ros::Publisher kiosk_pub_;
  ros::Publisher display_pub_;

  double joystick_sensitivity_;

  JoystickNavigator kiosk_joystick_navigator_;
};

void PortalNavigatorNode::Run(void) {
  kiosk_pub_ = n_.advertise<geometry_msgs::PoseStamped>(
      "/portal_nav/kiosk_goto_pose", 1);
  display_pub_ = n_.advertise<geometry_msgs::PoseStamped>(
      "/portal_nav/display_goto_pose", 1);

  ros::param::param<double>(
      "~joystick_sensitivity",
      joystick_sensitivity_,
      1.0);

  kiosk_joystick_navigator_.Init(
      &kiosk_pub_, &display_pub_, joystick_sensitivity_);

  // This subscriber takes commands from the SpaceNav.
  spacenav_sub_ = n_.subscribe("/spacenav/twist", 2,
      &PortalNavigatorNode::HandleSpaceNav, this);

  // This subscriber gets camera poses back from the kiosk.
  // We have a small Rx queue to make sure we don't lose any.
  kiosk_pose_sub_ = n_.subscribe("/portal_kiosk/current_pose", 1,
      &PortalNavigatorNode::HandleKioskPose, this);

  // This publishes a normalized version of the SpaceNav inputs.
  joystick_pub_ = n_.advertise<geometry_msgs::Twist>("/joystick/twist", 2);

  // Does not return until killed:
  ros::spin();
}

void PortalNavigatorNode::HandleSpaceNav(
    const geometry_msgs::Twist::ConstPtr& twist) {
  // The SpaceNav twist values range [-350, 350], so it must be
  // normalized for the joystick code, which expects [-1.0, 1.0].
  static const double kSpaceNavScale = 350.0;

  // Our JoystickNavigator expects a right-hand-rule twist, where
  // X is right/left, Y is forward/backward, and Z is up/down.
  // The SpaceNav ROS driver swaps both linear and angular x/y.
  // It also sign-flips the y for both linear and angular.
  // We correct that here:
  geometry_msgs::Twist normalized_joy;
  normalized_joy.linear.x = twist->linear.y / kSpaceNavScale * -1.0;
  normalized_joy.linear.y = twist->linear.x / kSpaceNavScale;
  normalized_joy.linear.z = twist->linear.z / kSpaceNavScale;
  normalized_joy.angular.x = twist->angular.y / kSpaceNavScale * -1.0;
  normalized_joy.angular.y = twist->angular.x / kSpaceNavScale;
  normalized_joy.angular.z = twist->angular.z / kSpaceNavScale;

  kiosk_joystick_navigator_.ProcessJoy(normalized_joy);
  joystick_pub_.publish(normalized_joy);
}

void PortalNavigatorNode::HandleKioskPose(
    const portal_nav::PortalPose::ConstPtr& portal_pose) {
#ifdef DEBUG
  ROS_INFO("HandleKioskPose curr lat:%lf, lon:%lf, alt:%lf, hdg:%lf, tlt:%lf",
           portal_pose->current_pose.position.y,
           portal_pose->current_pose.position.x,
           portal_pose->current_pose.position.z,
           portal_pose->current_pose.orientation.z,
           portal_pose->current_pose.orientation.x);
  ROS_INFO("HandleKioskPose min lat:%lf, lon:%lf, alt:%lf, hdg:%lf, tlt:%lf",
           portal_pose->pose_minimums.position.y,
           portal_pose->pose_minimums.position.x,
           portal_pose->pose_minimums.position.z,
           portal_pose->pose_minimums.orientation.z,
           portal_pose->pose_minimums.orientation.x);
  ROS_INFO("HandleKioskPose max lat:%lf, lon:%lf, alt:%lf, hdg:%lf, tlt:%lf",
           portal_pose->pose_maximums.position.y,
           portal_pose->pose_maximums.position.x,
           portal_pose->pose_maximums.position.z,
           portal_pose->pose_maximums.orientation.z,
           portal_pose->pose_maximums.orientation.x);
#endif
  kiosk_joystick_navigator_.ProcessCameraMoved(*portal_pose);
}

/*
 * main()
 */
int main(int argc, char **argv) {
  ros::init(argc, argv, "portal_nav");
  PortalNavigatorNode node;
  node.Run();
  return 0;
}
<|endoftext|>


<commit_before>// This file may be redistributed and modified under the terms of the
// GNU Lesser General Public License (See COPYING for details).
// Copyright (C) 2002 Michael Koch <konqueror@gmx.de>

#include "Bach.h"

namespace Atlas { namespace Codecs {

Bach::Bach(std::iostream& s, Atlas::Bridge* b)
    : m_socket(s)
    , m_bridge(b)
    , m_comma( false )
{
    m_state.push(PARSE_INIT);
}

void Bach::parseInit(char next)
{
    cout << "parseInit" << endl;

    if (next=='[')
    {
        m_bridge->streamBegin();
        m_state.push(PARSE_STREAM);
    }
}

void Bach::parseStream(char next)
{
    cout << "parseStream" << endl;

    switch (next)
    {
    case '{':
        m_bridge->streamMessage(m_mapBegin);
        m_state.push(PARSE_MAP);
        break;

    case ',':
        break;

    case ']':
        m_bridge->streamEnd();
        break;

    default:
        cout << "parseStream: unexpected character : " << next << endl;
        // FIXME signal error here
        // unexpected character
        break;
    }
}

void Bach::parseMap(char next)
{
    cout << "parseMap" << endl;

    switch (next)
    {
    case '}':
        m_bridge->mapEnd();
        m_state.pop();
        break;

    case ',':
        break;

    default:
        if (((next>='a')&&(next<='z'))||
            ((next>='A')&&(next<='Z')))
        {
            m_socket.putback(next);
            m_state.push(PARSE_DATA);
            m_state.push(PARSE_NAME);
        }
        else
        {
            cout << "parseMap: unexpected character: " << next << endl;
            // FIXME signal error here
            // unexpected character
        }
        break;
    }
}

void Bach::parseList(char next)
{
    cout << "parseList" << endl;

    switch (next)
    {
    case ']':
        m_bridge->listEnd();
        m_state.pop();
        break;

    case '{':
        m_bridge->listItem(m_mapBegin);
        m_state.push(PARSE_MAP);
        break;

    case '[':
        m_bridge->listItem(m_listBegin);
        m_state.push(PARSE_LIST);
        break;

    case ',':
        break;

    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
    case '0':
    case '-':
        m_state.push(PARSE_FLOAT);
        m_socket.putback(next);
        break;

    case '\"':
        m_state.push(PARSE_STRING);
        break;

    default:
        cout << "parseMap: unexpected character: " << next << endl;
        // FIXME signal error here
        // unexpected character
        break;
    }
}

void Bach::parseMapBegin(char next)
{
    cout << "parseMapBegin" << endl;

    m_bridge->mapItem(decodeString(m_name), m_mapBegin);
    m_socket.putback(next);
    m_state.pop();
    m_name.erase();
}

void Bach::parseListBegin(char next)
{
    cout << "parseListBegin" << endl;

    m_bridge->mapItem(decodeString(m_name), m_listBegin);
    m_socket.putback(next);
    m_state.pop();
    m_name.erase();
}

void Bach::parseInt(char next)
{
    cout << "parseInt" << endl;
}

void Bach::parseFloat(char next)
{
    cout << "parseFloat" << endl;

    switch (next)
    {
    case '[':
    case ']':
    case '(':
    case ')':
    case ',':
        m_socket.putback(next);
        m_state.pop();
        if (m_state.top() == PARSE_MAP)
        {
            cout << "Float: " << m_data << endl;

            m_bridge->mapItem(decodeString(m_name), atof(m_data.c_str()));
        }
        else if (m_state.top() == PARSE_LIST)
        {
            cout << "Float: " << m_data << endl;

            m_bridge->listItem(atof(m_data.c_str()));
        }
        else
        {
            cout << "Bach::parseFloat: Error: " << m_state.top() << endl;
            // FIXME some kind of sanity checking assertion here
        }
        m_name.erase();
        m_data.erase();
	break;

    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
    case '.':
    case '-':
    case '+':
    case 'e':
    case 'E':
        m_data += next;
	break;

    default:
        cout << "parseFloat: unexpected character: " << next << endl;
        // FIXME signal error here
        // unexpected character
	break;
    }
}

void Bach::parseString(char next)
{
    cout << "parseString" << endl;

    switch (next)
    {
    case '\"':
        m_state.pop();
        if (m_state.top() == PARSE_MAP)
        {
            cout << "String: " << m_data << endl;

            m_bridge->mapItem(decodeString(m_name), decodeString(m_data));
        }
        else if (m_state.top() == PARSE_LIST)
        {
            cout << "String: " << m_data << endl;

            m_bridge->listItem(decodeString(m_data));
        }
        else
        {
            cout << "Error" << endl;

            // FIXME some kind of sanity checking assertion here
        }
        m_name.erase();
        m_data.erase();
        break;

/*
    case '\\':
        // FIXME escape signs
        break;
*/

    default:
        m_data += next;
        break;
    }
}

void Bach::parseData(char next)
{
    cout << "parseData" << endl;

    switch (next)
    {
    case '-':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
    case '0':
        m_socket.putback(next);
        m_state.pop();
        m_state.push(PARSE_FLOAT);
        break;

    case '{':
        m_state.pop();
        m_state.push(PARSE_MAP);
        break;

    case '[':
        m_state.pop();
        m_state.push(PARSE_LIST);
        break;

    case '\"':
        m_state.pop();
        m_state.push(PARSE_STRING);
        break;

    case ',':
        break;

    default:
        cout << "parseData: unexpected character: " << next << endl;
        break;
    }
}

void Bach::parseName(char next)
{
    cout << "parseName" << endl;

    switch (next)
    {
    case ':':
        cout << "Name: " << m_name << endl;
        m_state.pop();
	break;

    default:
        if (((next>='a')&&(next<='z'))||
            ((next>='A')&&(next<='Z'))||
            ((next>='0')&&(next<='9')))
        {
            m_name += next;
        }
        else
        {
            cout << "parseName: unexpected character: " << next << endl;
            // FIXME signal error here
            // unexpected character
        }
	break;
    }
}

void Bach::poll(bool can_read)
{
    if (!can_read) return;
    do
    {
	char next = (char) m_socket.get();

        cout << "Character: " << next << "   ";

        switch (m_state.top())
	{
        case PARSE_INIT:       parseInit(next); break;
        case PARSE_STREAM:     parseStream(next); break;
        case PARSE_MAP:        parseMap(next); break;
        case PARSE_LIST:       parseList(next); break;
        case PARSE_MAP_BEGIN:  parseMapBegin(next); break;
        case PARSE_LIST_BEGIN: parseListBegin(next); break;
        case PARSE_DATA:       parseData(next); break;
        case PARSE_INT:	       parseInt(next); break;
        case PARSE_FLOAT:      parseFloat(next); break;
        case PARSE_STRING:     parseString(next); break;
        case PARSE_NAME:       parseName(next); break;
	}
    }
    while (m_socket.rdbuf()->in_avail());
}

const std::string Bach::decodeString(std::string toDecode)
{
    int pos;

    while((pos = toDecode.find( "\\\"" )) >= 0)
          toDecode.replace(pos, 2, '\"');

    while((pos = toDecode.find( "\\\\")) >= 0)
          toDecode.replace(pos, 2, '\\');

    return toDecode;
}

const std::string Bach::encodeString(std::string toEncode)
{
    int pos;

    while ((pos = toEncode.find ( '\\' )) >= 0)
	toEncode.replace( pos, 1, "\\\\" );

    while ((pos = toEncode.find ( '\"' )) >= 0)
	toEncode.replace( pos, 1, "\\\"" );

    return toEncode;
}

void Bach::writeItem(std::string name, long data)
{
    if( m_comma )
	m_socket << ",";

    if( name != "" )
	m_socket << name << ":";

    m_socket << data;
}

void Bach::writeItem(std::string name, double data)
{
    if( m_comma )
	m_socket << ",";

    if( name != "" )
	m_socket << name << ":";

    m_socket << data;
}

void Bach::writeItem(std::string name, std::string data)
{
    if( m_comma )
	m_socket << ",";

    if( name != "" )
	m_socket << name << ":";

    m_socket << "\"" << encodeString( data ) << "\"";
}

void Bach::writeLine(std::string line, bool endline, bool endtag)
{
    if (m_comma && !endtag)
	m_socket << ",";

    m_socket << line;
}

void Bach::streamBegin()
{
    writeLine( "[" );
    m_comma = false;
}

void Bach::streamEnd()
{
    writeLine( "]", true, true );
}

void Bach::streamMessage(const Map&)
{
    writeLine( "{" );
    m_comma = false;
}

void Bach::mapItem(const std::string& name, const Map&)
{
    writeLine( name + ":{" );
    m_comma = false;
}

void Bach::mapItem(const std::string& name, const List&)
{
    writeLine( name + ":[" );
    m_comma = false;
}

void Bach::mapItem(const std::string& name, long data)
{
    writeItem( name, data );
    m_comma = true;
}

void Bach::mapItem(const std::string& name, double data)
{
    writeItem( name, data );
    m_comma = true;
}

void Bach::mapItem(const std::string& name, const std::string& data)
{
    writeItem( name, data );
    m_comma = true;
}

void Bach::mapEnd()
{
    writeLine( "}", true, true );
    m_comma = true;
}

void Bach::listItem(const Map&)
{
    writeLine( "{" );
    m_comma = false;
}

void Bach::listItem(const List&)
{
    writeLine( "[" );
    m_comma = false;
}

void Bach::listItem(long data)
{
    writeItem( "", data );
    m_comma = true;
}

void Bach::listItem(double data)
{
    writeItem( "", data );
    m_comma = true;
}

void Bach::listItem(const std::string& data)
{
    writeItem( "", data );
    m_comma = true;
}

void Bach::listEnd()
{
    writeLine( "]", true, true );
    m_comma = true;
}

} } //namespace Atlas::Codecs
<commit_msg>- Fixed some bugs - Implemented parseInt - Moved debug output into macro for easier disabling<commit_after>// This file may be redistributed and modified under the terms of the
// GNU Lesser General Public License (See COPYING for details).
// Copyright (C) 2002 Michael Koch <konqueror@gmx.de>

#include "Bach.h"

//#define DEBUG(a) a;
#define DEBUG(a) ;

namespace Atlas { namespace Codecs {

Bach::Bach(std::iostream& s, Atlas::Bridge* b)
    : m_socket(s)
    , m_bridge(b)
    , m_comma( false )
{
    m_state.push(PARSE_INIT);
}

void Bach::parseInit(char next)
{
    DEBUG(cout << "parseInit" << endl;)

    if (next=='[')
    {
        m_bridge->streamBegin();
        m_state.push(PARSE_STREAM);
    }
}

void Bach::parseStream(char next)
{
    DEBUG(cout << "parseStream" << endl;)

    switch (next)
    {
    case '{':
        m_bridge->streamMessage(m_mapBegin);
        m_state.push(PARSE_MAP);
        m_state.push(PARSE_MAP_BEGIN);
        break;

    case ',':
    case EOF:
        break;

    case ']':
        m_bridge->streamEnd();
        break;

    default:
        cout << "parseStream: unexpected character : " << next << endl;
        // FIXME signal error here
        // unexpected character
        break;
    }
}

void Bach::parseMap(char next)
{
    DEBUG(cout << "parseMap" << endl;)

    switch (next)
    {
    case '}':
        //SF2 m_bridge->mapEnd();
        m_state.pop();
        break;

    case ',':
        break;

    default:
        if (((next>='a')&&(next<='z'))||
            ((next>='A')&&(next<='Z')))
        {
            m_socket.putback(next);
            m_state.push(PARSE_DATA);
            m_state.push(PARSE_NAME);
        }
        else
        {
            cout << "parseMap: unexpected character: " << next << endl;
            // FIXME signal error here
            // unexpected character
        }
        break;
    }
}

void Bach::parseList(char next)
{
    DEBUG(cout << "parseList" << endl;)

    switch (next)
    {
    case ']':
        m_bridge->listEnd();
        m_state.pop();
        break;

    case '{':
        m_bridge->listItem(m_mapBegin);
        m_state.push(PARSE_MAP);
        m_state.push(PARSE_MAP_BEGIN);
        break;

    case '[':
        m_bridge->listItem(m_listBegin);
        m_state.push(PARSE_LIST);
        m_state.push(PARSE_LIST_BEGIN);
        break;

    case ',':
        break;

    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
    case '0':
    case '-':
        m_state.push(PARSE_INT);
        m_socket.putback(next);
        break;

    case '\"':
        m_state.push(PARSE_STRING);
        break;

    default:
        cout << "parseMap: unexpected character: " << next << endl;
        // FIXME signal error here
        // unexpected character
        break;
    }
}

void Bach::parseMapBegin(char next)
{
    DEBUG(cout << "parseMapBegin" << endl;)

    m_bridge->mapItem(decodeString(m_name), m_mapBegin);
    m_socket.putback(next);
    m_state.pop();
    m_name.erase();
}

void Bach::parseListBegin(char next)
{
    DEBUG(cout << "parseListBegin" << endl;)

    m_bridge->mapItem(decodeString(m_name), m_listBegin);
    m_socket.putback(next);
    m_state.pop();
    m_name.erase();
}

void Bach::parseInt(char next)
{
    DEBUG(cout << "parseInt" << endl;)

    switch (next)
    {
    case '[':
    case ']':
    case '(':
    case ')':
    case ',':
        m_socket.putback(next);
        m_state.pop();
        if (m_state.top() == PARSE_MAP)
        {
            DEBUG(cout << "Float: " << m_name << ": " << m_data << endl;)

            m_bridge->mapItem(decodeString(m_name), atof(m_data.c_str()));
        }
        else if (m_state.top() == PARSE_LIST)
        {
            DEBUG(cout << "Float: " << m_data << endl;)

            m_bridge->listItem(atof(m_data.c_str()));
        }
        else
        {
            cout << "Bach::parseFloat: Error: " << m_state.top() << endl;
            // FIXME some kind of sanity checking assertion here
        }
        m_name.erase();
        m_data.erase();
	break;

    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
    case '-':
    case '+':
    case 'e':
    case 'E':
        m_data += next;
	break;

    case '.':
        m_state.pop();
        m_state.push(PARSE_FLOAT);
        m_data += next;
        break;

    default:
        cout << "parseInt: unexpected character: " << next << endl;
        // FIXME signal error here
        // unexpected character
	break;
    }
}

void Bach::parseFloat(char next)
{
    DEBUG(cout << "parseFloat" << endl;)

    switch (next)
    {
    case '[':
    case ']':
    case '(':
    case ')':
    case ',':
        m_socket.putback(next);
        m_state.pop();
        if (m_state.top() == PARSE_MAP)
        {
            DEBUG(cout << "Float: " << m_name << ": " << m_data << endl;)

            m_bridge->mapItem(decodeString(m_name), atof(m_data.c_str()));
        }
        else if (m_state.top() == PARSE_LIST)
        {
            DEBUG(cout << "Float: " << m_data << endl;)

            m_bridge->listItem(atof(m_data.c_str()));
        }
        else
        {
            cout << "Bach::parseFloat: Error: " << m_state.top() << endl;
            // FIXME some kind of sanity checking assertion here
        }
        m_name.erase();
        m_data.erase();
	break;

    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
    case '.':
    case '-':
    case '+':
    case 'e':
    case 'E':
        m_data += next;
	break;

    default:
        cout << "parseFloat: unexpected character: " << next << endl;
        // FIXME signal error here
        // unexpected character
	break;
    }
}

void Bach::parseString(char next)
{
    DEBUG(cout << "parseString" << endl;)

    switch (next)
    {
    case '\"':
        m_state.pop();
        if (m_state.top() == PARSE_MAP)
        {
            DEBUG(cout << "String: " << m_name << ": " << m_data << endl;)

            m_bridge->mapItem(decodeString(m_name), decodeString(m_data));
        }
        else if (m_state.top() == PARSE_LIST)
        {
            DEBUG(cout << "String: " << m_data << endl;)

            m_bridge->listItem(decodeString(m_data));
        }
        else
        {
            cout << "parseString: Error" << endl;

            // FIXME some kind of sanity checking assertion here
        }
        m_name.erase();
        m_data.erase();
        break;

/*
    case '\\':
        // FIXME escape signs
        break;
*/

    default:
        m_data += next;
        break;
    }
}

void Bach::parseData(char next)
{
    DEBUG(cout << "parseData" << endl;)

    switch (next)
    {
    case '-':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
    case '0':
        m_socket.putback(next);
        m_state.pop();
        m_state.push(PARSE_INT);
        break;

    case '{':
        m_state.pop();
        m_bridge->listItem(m_mapBegin);
        m_state.push(PARSE_MAP);
        m_state.push(PARSE_MAP_BEGIN);
        break;

    case '[':
        m_state.pop();
        m_bridge->listItem(m_listBegin);
        m_state.push(PARSE_LIST);
        m_state.push(PARSE_LIST_BEGIN);
        break;

    case '\"':
        m_state.pop();
        m_state.push(PARSE_STRING);
        break;

    case ',':
        break;

    default:
        cout << "parseData: unexpected character: " << next << endl;
        break;
    }
}

void Bach::parseName(char next)
{
    DEBUG(cout << "parseName" << endl;)

    switch (next)
    {
    case ':':
        DEBUG(cout << "Name: " << m_name << endl;)

        m_state.pop();
	break;

    default:
        if (((next>='a')&&(next<='z'))||
            ((next>='A')&&(next<='Z'))||
            ((next>='0')&&(next<='9')))
        {
            m_name += next;
        }
        else
        {
            cout << "parseName: unexpected character: " << next << endl;
            // FIXME signal error here
            // unexpected character
        }
	break;
    }
}

void Bach::poll(bool can_read)
{
    if (!can_read) return;
    do
    {
	char next = (char) m_socket.get();

        DEBUG(cout << "Character: " << next << "   ";)

        switch(next)
        {
        case '\n':
            continue;
            break;

        default:
            break;
        }

        switch (m_state.top())
	{
        case PARSE_INIT:       parseInit(next); break;
        case PARSE_STREAM:     parseStream(next); break;
        case PARSE_MAP:        parseMap(next); break;
        case PARSE_LIST:       parseList(next); break;
        case PARSE_MAP_BEGIN:  parseMapBegin(next); break;
        case PARSE_LIST_BEGIN: parseListBegin(next); break;
        case PARSE_DATA:       parseData(next); break;
        case PARSE_INT:	       parseInt(next); break;
        case PARSE_FLOAT:      parseFloat(next); break;
        case PARSE_STRING:     parseString(next); break;
        case PARSE_NAME:       parseName(next); break;
	}
    }
    while (m_socket.rdbuf()->in_avail());
}

const std::string Bach::decodeString(std::string toDecode)
{
    int pos;

    while((pos = toDecode.find( "\\\"" )) >= 0)
          toDecode.replace(pos, 2, '\"');

    while((pos = toDecode.find( "\\\\")) >= 0)
          toDecode.replace(pos, 2, '\\');

    return toDecode;
}

const std::string Bach::encodeString(std::string toEncode)
{
    int pos;

    while ((pos = toEncode.find ( '\\' )) >= 0)
	toEncode.replace( pos, 1, "\\\\" );

    while ((pos = toEncode.find ( '\"' )) >= 0)
	toEncode.replace( pos, 1, "\\\"" );

    return toEncode;
}

void Bach::writeItem(std::string name, long data)
{
    if( m_comma )
	m_socket << ",";

    if( name != "" )
	m_socket << name << ":";

    m_socket << data;
}

void Bach::writeItem(std::string name, double data)
{
    if( m_comma )
	m_socket << ",";

    if( name != "" )
	m_socket << name << ":";

    m_socket << data;
}

void Bach::writeItem(std::string name, std::string data)
{
    if( m_comma )
	m_socket << ",";

    if( name != "" )
	m_socket << name << ":";

    m_socket << "\"" << encodeString( data ) << "\"";
}

void Bach::writeLine(std::string line, bool endline, bool endtag)
{
    if (m_comma && !endtag)
	m_socket << ",";

    m_socket << line;
}

void Bach::streamBegin()
{
    writeLine( "[" );
    m_comma = false;
}

void Bach::streamEnd()
{
    writeLine( "]", true, true );
}

void Bach::streamMessage(const Map&)
{
    writeLine( "{" );
    m_comma = false;
}

void Bach::mapItem(const std::string& name, const Map&)
{
    writeLine( name + ":{" );
    m_comma = false;
}

void Bach::mapItem(const std::string& name, const List&)
{
    writeLine( name + ":[" );
    m_comma = false;
}

void Bach::mapItem(const std::string& name, long data)
{
    writeItem( name, data );
    m_comma = true;
}

void Bach::mapItem(const std::string& name, double data)
{
    writeItem( name, data );
    m_comma = true;
}

void Bach::mapItem(const std::string& name, const std::string& data)
{
    writeItem( name, data );
    m_comma = true;
}

void Bach::mapEnd()
{
    writeLine( "}", true, true );
    m_comma = true;
}

void Bach::listItem(const Map&)
{
    writeLine( "{" );
    m_comma = false;
}

void Bach::listItem(const List&)
{
    writeLine( "[" );
    m_comma = false;
}

void Bach::listItem(long data)
{
    writeItem( "", data );
    m_comma = true;
}

void Bach::listItem(double data)
{
    writeItem( "", data );
    m_comma = true;
}

void Bach::listItem(const std::string& data)
{
    writeItem( "", data );
    m_comma = true;
}

void Bach::listEnd()
{
    writeLine( "]", true, true );
    m_comma = true;
}

} } //namespace Atlas::Codecs
<|endoftext|>


<commit_before><commit_msg>Fix final memory leak in AST<commit_after><|endoftext|>


<commit_before><commit_msg>Skip debug road lines drawing when debug drawing disabled<commit_after><|endoftext|>


<commit_before>/*
   Copyright (c) 2009-2014, Jack Poulson
   All rights reserved.

   This file is part of Elemental and is under the BSD 2-Clause License,
   which can be found in the LICENSE file in the root directory, or at
   http://opensource.org/licenses/BSD-2-Clause
*/
#include "El.hpp"

namespace El {

template<typename Real>
void FoxLi( Matrix<Complex<Real>>& A, Int n, Real omega )
{
    DEBUG_ONLY(CallStackEntry cse("FoxLi"))
    typedef Complex<Real> C;
    const Real pi = 4*Atan( Real(1) );
    const C phi = Sqrt( C(0,omega/pi) );

    // Compute Gauss quadrature points and weights
    Matrix<Real> d, e;
    Zeros( d, n, 1 );
    e.Resize( n-1, 1 );
    for( Int j=0; j<n-1; ++j )
    {
        const Real betaInv = 2*Sqrt(1-Pow(j+Real(1),-2)/4);
        e.Set( j, 0, 1/betaInv );
    }
    Matrix<Real> x, Z;
    HermitianTridiagEig( d, e, x, Z, UNSORTED );
    auto z = Z( IR(0,1), IR(0,n) );
    Matrix<Real> sqrtWeights( z ), sqrtWeightsTrans;
    for( Int j=0; j<n; ++j )
        sqrtWeights.Set( 0, j, Sqrt(2)*Abs(sqrtWeights.Get(0,j)) );
    herm_eig::Sort( x, sqrtWeights, ASCENDING );
    Transpose( sqrtWeights, sqrtWeightsTrans );

    // Form the integral operator
    A.Resize( n, n );
    for( Int j=0; j<n; ++j )
    {
        for( Int i=0; i<n; ++i )
        {
            const Real theta = -omega*Pow(x.Get(i,0)-x.Get(j,0),2);
            const Real realPart = Cos(theta);
            const Real imagPart = Sin(theta);
            A.Set( i, j, phi*C(realPart,imagPart) );
        }
    }

    // Apply the weighting
    DiagonalScale( LEFT, NORMAL, sqrtWeightsTrans, A );
    DiagonalScale( RIGHT, NORMAL, sqrtWeightsTrans, A );
}

template<typename Real>
void FoxLi( AbstractDistMatrix<Complex<Real>>& APre, Int n, Real omega )
{
    DEBUG_ONLY(CallStackEntry cse("FoxLi"))
    typedef Complex<Real> C;
    const Real pi = 4*Atan( Real(1) );
    const C phi = Sqrt( C(0,omega/pi) );

    auto APtr = WriteProxy<C,MC,MR>( &APre );
    auto& A = *APtr;

    // Compute Gauss quadrature points and weights
    const Grid& g = A.Grid();
    DistMatrix<Real,VR,STAR> d(g), e(g);
    Zeros( d, n, 1 );
    e.Resize( n-1, 1 );
    for( Int iLoc=0; iLoc<e.LocalHeight(); ++iLoc )
    {
        const Int i = e.GlobalRow(iLoc);
        const Real betaInv = 2*Sqrt(1-Pow(i+Real(1),-2)/4);
        e.SetLocal( iLoc, 0, 1/betaInv );
    }
    DistMatrix<Real,VR,STAR> x(g);
    DistMatrix<Real,STAR,VR> Z(g);
    HermitianTridiagEig( d, e, x, Z, UNSORTED );
    auto z = Z( IR(0,1), IR(0,n) );
    DistMatrix<Real,STAR,VR> sqrtWeights( z );
    for( Int jLoc=0; jLoc<sqrtWeights.LocalWidth(); ++jLoc )
        sqrtWeights.SetLocal
        ( 0, jLoc, Sqrt(2)*Abs(sqrtWeights.GetLocal(0,jLoc)) );
    herm_eig::Sort( x, sqrtWeights, ASCENDING );

    // Form the integral operator
    A.Resize( n, n );
    DistMatrix<Real,MC,STAR> x_MC_STAR( A.Grid() );
    DistMatrix<Real,MR,STAR> x_MR_STAR( A.Grid() );
    x_MC_STAR.AlignWith( A );
    x_MR_STAR.AlignWith( A );
    x_MC_STAR = x;
    x_MR_STAR = x;
    for( Int jLoc=0; jLoc<A.LocalWidth(); ++jLoc )
    {
        for( Int iLoc=0; iLoc<A.LocalHeight(); ++iLoc )
        {
            const Real diff = x_MC_STAR.GetLocal(iLoc,0)-
                              x_MR_STAR.GetLocal(jLoc,0);
            const Real theta = -omega*Pow(diff,2);
            const Real realPart = Cos(theta);
            const Real imagPart = Sin(theta);
            A.SetLocal( iLoc, jLoc, phi*C(realPart,imagPart) );
        }
    }

    // Apply the weighting
    DistMatrix<Real,VR,STAR> sqrtWeightsTrans(g);
    Transpose( sqrtWeights, sqrtWeightsTrans );
    DiagonalScale( LEFT, NORMAL, sqrtWeightsTrans, A );
    DiagonalScale( RIGHT, NORMAL, sqrtWeightsTrans, A );
}

#define PROTO(Real) \
  template void FoxLi( Matrix<Complex<Real>>& A, Int n, Real omega ); \
  template void FoxLi \
  ( AbstractDistMatrix<Complex<Real>>& A, Int n, Real omega );

#define PROTO_FLOAT \
  template void FoxLi( Matrix<Complex<float>>& A, Int n, float omega );

#define EL_NO_INT_PROTO
#define EL_NO_COMPLEX_PROTO
#include "El/macros/Instantiate.h"

} // namespace El
<commit_msg>Adding missing FoxLi instantiation<commit_after>/*
   Copyright (c) 2009-2014, Jack Poulson
   All rights reserved.

   This file is part of Elemental and is under the BSD 2-Clause License,
   which can be found in the LICENSE file in the root directory, or at
   http://opensource.org/licenses/BSD-2-Clause
*/
#include "El.hpp"

namespace El {

template<typename Real>
void FoxLi( Matrix<Complex<Real>>& A, Int n, Real omega )
{
    DEBUG_ONLY(CallStackEntry cse("FoxLi"))
    typedef Complex<Real> C;
    const Real pi = 4*Atan( Real(1) );
    const C phi = Sqrt( C(0,omega/pi) );

    // Compute Gauss quadrature points and weights
    Matrix<Real> d, e;
    Zeros( d, n, 1 );
    e.Resize( n-1, 1 );
    for( Int j=0; j<n-1; ++j )
    {
        const Real betaInv = 2*Sqrt(1-Pow(j+Real(1),-2)/4);
        e.Set( j, 0, 1/betaInv );
    }
    Matrix<Real> x, Z;
    HermitianTridiagEig( d, e, x, Z, UNSORTED );
    auto z = Z( IR(0,1), IR(0,n) );
    Matrix<Real> sqrtWeights( z ), sqrtWeightsTrans;
    for( Int j=0; j<n; ++j )
        sqrtWeights.Set( 0, j, Sqrt(2)*Abs(sqrtWeights.Get(0,j)) );
    herm_eig::Sort( x, sqrtWeights, ASCENDING );
    Transpose( sqrtWeights, sqrtWeightsTrans );

    // Form the integral operator
    A.Resize( n, n );
    for( Int j=0; j<n; ++j )
    {
        for( Int i=0; i<n; ++i )
        {
            const Real theta = -omega*Pow(x.Get(i,0)-x.Get(j,0),2);
            const Real realPart = Cos(theta);
            const Real imagPart = Sin(theta);
            A.Set( i, j, phi*C(realPart,imagPart) );
        }
    }

    // Apply the weighting
    DiagonalScale( LEFT, NORMAL, sqrtWeightsTrans, A );
    DiagonalScale( RIGHT, NORMAL, sqrtWeightsTrans, A );
}

template<typename Real>
void FoxLi( AbstractDistMatrix<Complex<Real>>& APre, Int n, Real omega )
{
    DEBUG_ONLY(CallStackEntry cse("FoxLi"))
    typedef Complex<Real> C;
    const Real pi = 4*Atan( Real(1) );
    const C phi = Sqrt( C(0,omega/pi) );

    auto APtr = WriteProxy<C,MC,MR>( &APre );
    auto& A = *APtr;

    // Compute Gauss quadrature points and weights
    const Grid& g = A.Grid();
    DistMatrix<Real,VR,STAR> d(g), e(g);
    Zeros( d, n, 1 );
    e.Resize( n-1, 1 );
    for( Int iLoc=0; iLoc<e.LocalHeight(); ++iLoc )
    {
        const Int i = e.GlobalRow(iLoc);
        const Real betaInv = 2*Sqrt(1-Pow(i+Real(1),-2)/4);
        e.SetLocal( iLoc, 0, 1/betaInv );
    }
    DistMatrix<Real,VR,STAR> x(g);
    DistMatrix<Real,STAR,VR> Z(g);
    HermitianTridiagEig( d, e, x, Z, UNSORTED );
    auto z = Z( IR(0,1), IR(0,n) );
    DistMatrix<Real,STAR,VR> sqrtWeights( z );
    for( Int jLoc=0; jLoc<sqrtWeights.LocalWidth(); ++jLoc )
        sqrtWeights.SetLocal
        ( 0, jLoc, Sqrt(2)*Abs(sqrtWeights.GetLocal(0,jLoc)) );
    herm_eig::Sort( x, sqrtWeights, ASCENDING );

    // Form the integral operator
    A.Resize( n, n );
    DistMatrix<Real,MC,STAR> x_MC_STAR( A.Grid() );
    DistMatrix<Real,MR,STAR> x_MR_STAR( A.Grid() );
    x_MC_STAR.AlignWith( A );
    x_MR_STAR.AlignWith( A );
    x_MC_STAR = x;
    x_MR_STAR = x;
    for( Int jLoc=0; jLoc<A.LocalWidth(); ++jLoc )
    {
        for( Int iLoc=0; iLoc<A.LocalHeight(); ++iLoc )
        {
            const Real diff = x_MC_STAR.GetLocal(iLoc,0)-
                              x_MR_STAR.GetLocal(jLoc,0);
            const Real theta = -omega*Pow(diff,2);
            const Real realPart = Cos(theta);
            const Real imagPart = Sin(theta);
            A.SetLocal( iLoc, jLoc, phi*C(realPart,imagPart) );
        }
    }

    // Apply the weighting
    DistMatrix<Real,VR,STAR> sqrtWeightsTrans(g);
    Transpose( sqrtWeights, sqrtWeightsTrans );
    DiagonalScale( LEFT, NORMAL, sqrtWeightsTrans, A );
    DiagonalScale( RIGHT, NORMAL, sqrtWeightsTrans, A );
}

#define PROTO(Real) \
  template void FoxLi( Matrix<Complex<Real>>& A, Int n, Real omega ); \
  template void FoxLi \
  ( AbstractDistMatrix<Complex<Real>>& A, Int n, Real omega );

#define EL_NO_INT_PROTO
#define EL_NO_COMPLEX_PROTO
#include "El/macros/Instantiate.h"

} // namespace El
<|endoftext|>