<commit_before>
#include <list>
#ifndef _WIN32
#include <unistd.h>
#endif
#include <QPixmap>
#include <QWindow>
#include <QGuiApplication>
#include <QWidget>
#include <QColor>
#include <QDesktopServices>

#include <utils/ColorRgb.h>
#include <effectengine/EffectDefinition.h>
#include <webserver/WebServer.h>

#include "hyperiond.h"
#include "systray.h"

SysTray::SysTray(HyperionDaemon *hyperiond)
	: QWidget()
	, _colorDlg(this)
	, _hyperiond(hyperiond)
	, _hyperion(nullptr)
	, _instanceManager(HyperionIManager::getInstance())
	, _webPort(8090)
{
	Q_INIT_RESOURCE(resources);

	// webserver port
	WebServer* webserver = hyperiond->getWebServerInstance();
	connect(webserver, &WebServer::portChanged, this, &SysTray::webserverPortChanged);

	// instance changes
	connect(_instanceManager, &HyperionIManager::instanceStateChanged, this, &SysTray::handleInstanceStateChange);
}

SysTray::~SysTray()
{
}

void SysTray::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
	switch (reason)
	{
		case QSystemTrayIcon::Trigger:
			break;
		case QSystemTrayIcon::DoubleClick:
			showColorDialog();
			break;
		case QSystemTrayIcon::MiddleClick:
			break;
		default: ;
	}
}

void SysTray::createTrayIcon()
{
	quitAction = new QAction(tr("&Quit"), this);
	QIcon quitIcon = QIcon::fromTheme("application-exit");
	quitAction->setIcon(quitIcon);
	connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));

	colorAction = new QAction(tr("&Color"), this);
	QIcon colorIcon = QIcon::fromTheme("applications-graphics");
	colorAction->setIcon(colorIcon);
	connect(colorAction, SIGNAL(triggered()), this, SLOT(showColorDialog()));

	settingsAction = new QAction(tr("&Settings"), this);
	QIcon settingsIcon = QIcon::fromTheme("preferences-system");
	settingsAction->setIcon(settingsIcon);
	connect(settingsAction, SIGNAL(triggered()), this, SLOT(settings()));

	clearAction = new QAction(tr("&Clear"), this);
	QIcon clearIcon = QIcon::fromTheme("edit-delete");
	clearAction->setIcon(clearIcon);
	connect(clearAction, SIGNAL(triggered()), this, SLOT(clearEfxColor()));

	const std::list<EffectDefinition> efxs = _hyperion->getEffects();
	_trayIconMenu = new QMenu(this);
	_trayIconEfxMenu = new QMenu(_trayIconMenu);
	_trayIconEfxMenu->setTitle(tr("Effects"));
	QIcon efxIcon = QIcon::fromTheme("media-playback-start");
	_trayIconEfxMenu->setIcon(efxIcon);
	for (auto efx : efxs)
	{
		QAction *efxAction = new QAction(efx.name, this);
		connect(efxAction, SIGNAL(triggered()), this, SLOT(setEffect()));
		_trayIconEfxMenu->addAction(efxAction);
	}

	_trayIconMenu->addAction(settingsAction);
	_trayIconMenu->addSeparator();
	_trayIconMenu->addAction(colorAction);
	_trayIconMenu->addMenu(_trayIconEfxMenu);
	_trayIconMenu->addAction(clearAction);
	_trayIconMenu->addSeparator();
	_trayIconMenu->addAction(quitAction);

	_trayIcon = new QSystemTrayIcon(this);
	_trayIcon->setContextMenu(_trayIconMenu);
}

void SysTray::setColor(const QColor & color)
{
	std::vector<ColorRgb> rgbColor{ ColorRgb{ (uint8_t)color.red(), (uint8_t)color.green(), (uint8_t)color.blue() } };

 	_hyperion->setColor(1 ,rgbColor, 0);
}

void SysTray::showColorDialog()
{
	if(_colorDlg.isVisible())
	{
		_colorDlg.hide();
	}
	else
	{
		_colorDlg.show();
	}
}

void SysTray::closeEvent(QCloseEvent *event)
{
	event->ignore();
}

void SysTray::settings()
{
#ifndef _WIN32
	// Hide error messages when opening webbrowser

	int out_pipe[2];
	int saved_stdout;
	int saved_stderr;

	// saving stdout and stderr file descriptor
	saved_stdout = ::dup( STDOUT_FILENO );
	saved_stderr = ::dup( STDERR_FILENO );

	if(::pipe(out_pipe) == 0)
	{
		// redirecting stdout to pipe
		::dup2(out_pipe[1], STDOUT_FILENO);
		::close(out_pipe[1]);
		// redirecting stderr to stdout
		::dup2(STDOUT_FILENO, STDERR_FILENO);
	}
	#endif

	QDesktopServices::openUrl(QUrl("http://localhost:"+QString::number(_webPort)+"/", QUrl::TolerantMode));

	#ifndef _WIN32
	// restoring stdout
	::dup2(saved_stdout, STDOUT_FILENO);
	// restoring stderr
	::dup2(saved_stderr, STDERR_FILENO);
	#endif
}

void SysTray::setEffect()
{
	QString efxName = qobject_cast<QAction*>(sender())->text();
	_hyperion->setEffect(efxName, 1);
}

void SysTray::clearEfxColor()
{
	_hyperion->clear(1);
}

void SysTray::handleInstanceStateChange(const instanceState& state, const quint8& instance, const QString& name)
{
	switch(state){
		case H_STARTED:
			if(instance == 0)
			{
				_hyperion = _instanceManager->getHyperionInstance(0);

				createTrayIcon();
				connect(_trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
					this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));

				connect(&_colorDlg, SIGNAL(currentColorChanged(const QColor&)), this, SLOT(setColor(const QColor &)));
				QIcon icon(":/hyperion-icon-32px.png");
				_trayIcon->setIcon(icon);
				_trayIcon->show();
				setWindowIcon(icon);
				_colorDlg.setOptions(QColorDialog::NoButtons);
			}

			break;
		default:
			break;
	}
}
<commit_msg>Open WebUI instead of the color picker<commit_after>
#include <list>
#ifndef _WIN32
#include <unistd.h>
#endif
#include <QPixmap>
#include <QWindow>
#include <QGuiApplication>
#include <QWidget>
#include <QColor>
#include <QDesktopServices>

#include <utils/ColorRgb.h>
#include <effectengine/EffectDefinition.h>
#include <webserver/WebServer.h>

#include "hyperiond.h"
#include "systray.h"

SysTray::SysTray(HyperionDaemon *hyperiond)
	: QWidget()
	, _colorDlg(this)
	, _hyperiond(hyperiond)
	, _hyperion(nullptr)
	, _instanceManager(HyperionIManager::getInstance())
	, _webPort(8090)
{
	Q_INIT_RESOURCE(resources);

	// webserver port
	WebServer* webserver = hyperiond->getWebServerInstance();
	connect(webserver, &WebServer::portChanged, this, &SysTray::webserverPortChanged);

	// instance changes
	connect(_instanceManager, &HyperionIManager::instanceStateChanged, this, &SysTray::handleInstanceStateChange);
}

SysTray::~SysTray()
{
}

void SysTray::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
	switch (reason)
	{
		case QSystemTrayIcon::Trigger:
			break;
		case QSystemTrayIcon::DoubleClick:
			settings();
			break;
		case QSystemTrayIcon::MiddleClick:
			break;
		default: ;
	}
}

void SysTray::createTrayIcon()
{
	quitAction = new QAction(tr("&Quit"), this);
	QIcon quitIcon = QIcon::fromTheme("application-exit");
	quitAction->setIcon(quitIcon);
	connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));

	colorAction = new QAction(tr("&Color"), this);
	QIcon colorIcon = QIcon::fromTheme("applications-graphics");
	colorAction->setIcon(colorIcon);
	connect(colorAction, SIGNAL(triggered()), this, SLOT(showColorDialog()));

	settingsAction = new QAction(tr("&Settings"), this);
	QIcon settingsIcon = QIcon::fromTheme("preferences-system");
	settingsAction->setIcon(settingsIcon);
	connect(settingsAction, SIGNAL(triggered()), this, SLOT(settings()));

	clearAction = new QAction(tr("&Clear"), this);
	QIcon clearIcon = QIcon::fromTheme("edit-delete");
	clearAction->setIcon(clearIcon);
	connect(clearAction, SIGNAL(triggered()), this, SLOT(clearEfxColor()));

	const std::list<EffectDefinition> efxs = _hyperion->getEffects();
	_trayIconMenu = new QMenu(this);
	_trayIconEfxMenu = new QMenu(_trayIconMenu);
	_trayIconEfxMenu->setTitle(tr("Effects"));
	QIcon efxIcon = QIcon::fromTheme("media-playback-start");
	_trayIconEfxMenu->setIcon(efxIcon);
	for (auto efx : efxs)
	{
		QAction *efxAction = new QAction(efx.name, this);
		connect(efxAction, SIGNAL(triggered()), this, SLOT(setEffect()));
		_trayIconEfxMenu->addAction(efxAction);
	}

	_trayIconMenu->addAction(settingsAction);
	_trayIconMenu->addSeparator();
	_trayIconMenu->addAction(colorAction);
	_trayIconMenu->addMenu(_trayIconEfxMenu);
	_trayIconMenu->addAction(clearAction);
	_trayIconMenu->addSeparator();
	_trayIconMenu->addAction(quitAction);

	_trayIcon = new QSystemTrayIcon(this);
	_trayIcon->setContextMenu(_trayIconMenu);
}

void SysTray::setColor(const QColor & color)
{
	std::vector<ColorRgb> rgbColor{ ColorRgb{ (uint8_t)color.red(), (uint8_t)color.green(), (uint8_t)color.blue() } };

 	_hyperion->setColor(1 ,rgbColor, 0);
}

void SysTray::showColorDialog()
{
	if(_colorDlg.isVisible())
	{
		_colorDlg.hide();
	}
	else
	{
		_colorDlg.show();
	}
}

void SysTray::closeEvent(QCloseEvent *event)
{
	event->ignore();
}

void SysTray::settings()
{
#ifndef _WIN32
	// Hide error messages when opening webbrowser

	int out_pipe[2];
	int saved_stdout;
	int saved_stderr;

	// saving stdout and stderr file descriptor
	saved_stdout = ::dup( STDOUT_FILENO );
	saved_stderr = ::dup( STDERR_FILENO );

	if(::pipe(out_pipe) == 0)
	{
		// redirecting stdout to pipe
		::dup2(out_pipe[1], STDOUT_FILENO);
		::close(out_pipe[1]);
		// redirecting stderr to stdout
		::dup2(STDOUT_FILENO, STDERR_FILENO);
	}
	#endif

	QDesktopServices::openUrl(QUrl("http://localhost:"+QString::number(_webPort)+"/", QUrl::TolerantMode));

	#ifndef _WIN32
	// restoring stdout
	::dup2(saved_stdout, STDOUT_FILENO);
	// restoring stderr
	::dup2(saved_stderr, STDERR_FILENO);
	#endif
}

void SysTray::setEffect()
{
	QString efxName = qobject_cast<QAction*>(sender())->text();
	_hyperion->setEffect(efxName, 1);
}

void SysTray::clearEfxColor()
{
	_hyperion->clear(1);
}

void SysTray::handleInstanceStateChange(const instanceState& state, const quint8& instance, const QString& name)
{
	switch(state){
		case H_STARTED:
			if(instance == 0)
			{
				_hyperion = _instanceManager->getHyperionInstance(0);

				createTrayIcon();
				connect(_trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
					this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));

				connect(&_colorDlg, SIGNAL(currentColorChanged(const QColor&)), this, SLOT(setColor(const QColor &)));
				QIcon icon(":/hyperion-icon-32px.png");
				_trayIcon->setIcon(icon);
				_trayIcon->show();
				setWindowIcon(icon);
				_colorDlg.setOptions(QColorDialog::NoButtons);
			}

			break;
		default:
			break;
	}
}
<|endoftext|>


<commit_before>// Copyright 2013 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 "ash/frame/caption_buttons/frame_caption_button.h"

#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/animation/slide_animation.h"
#include "ui/gfx/animation/throb_animation.h"
#include "ui/gfx/canvas.h"

namespace ash {

namespace {

// The duration of the crossfade animation when swapping the button's images.
const int kSwapImagesAnimationDurationMs = 200;

// The duration of the fade out animation of the old icon during a crossfade
// animation as a ratio of |kSwapImagesAnimationDurationMs|.
const float kFadeOutRatio = 0.5f;

// The alpha to draw inactive icons with.
const float kInactiveIconAlpha = 0.2f;

}  // namespace

// static
const char FrameCaptionButton::kViewClassName[] = "FrameCaptionButton";

FrameCaptionButton::FrameCaptionButton(views::ButtonListener* listener,
                                       CaptionButtonIcon icon)
    : CustomButton(listener),
      icon_(icon),
      paint_as_active_(false),
      alpha_(255),
      icon_image_id_(-1),
      hovered_background_image_id_(-1),
      pressed_background_image_id_(-1),
      swap_images_animation_(new gfx::SlideAnimation(this)) {
  swap_images_animation_->Reset(1);

  // Do not flip the gfx::Canvas passed to the OnPaint() method. The snap left
  // and snap right button icons should not be flipped. The other icons are
  // horizontally symmetrical.
}

FrameCaptionButton::~FrameCaptionButton() {
}

void FrameCaptionButton::SetImages(CaptionButtonIcon icon,
                                   Animate animate,
                                   int icon_image_id,
                                   int hovered_background_image_id,
                                   int pressed_background_image_id) {
  // The early return is dependant on |animate| because callers use SetImages()
  // with ANIMATE_NO to progress the crossfade animation to the end.
  if (icon == icon_ &&
      (animate == ANIMATE_YES || !swap_images_animation_->is_animating()) &&
      icon_image_id == icon_image_id_ &&
      hovered_background_image_id == hovered_background_image_id_ &&
      pressed_background_image_id == pressed_background_image_id_) {
    return;
  }

  if (animate == ANIMATE_YES)
    crossfade_icon_image_ = icon_image_;

  icon_ = icon;
  icon_image_id_ = icon_image_id;
  hovered_background_image_id_ = hovered_background_image_id;
  pressed_background_image_id_ = pressed_background_image_id;

  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
  icon_image_ = *rb.GetImageSkiaNamed(icon_image_id);
  hovered_background_image_ = *rb.GetImageSkiaNamed(
      hovered_background_image_id);
  pressed_background_image_ = *rb.GetImageSkiaNamed(
      pressed_background_image_id);

  if (animate == ANIMATE_YES) {
    swap_images_animation_->Reset(0);
    swap_images_animation_->SetSlideDuration(kSwapImagesAnimationDurationMs);
    swap_images_animation_->Show();
  } else {
    swap_images_animation_->Reset(1);
  }
  PreferredSizeChanged();
  SchedulePaint();
}

bool FrameCaptionButton::IsAnimatingImageSwap() const {
  return swap_images_animation_->is_animating();
}

void FrameCaptionButton::SetAlpha(int alpha) {
  if (alpha_ != alpha) {
    alpha_ = alpha;
    SchedulePaint();
  }
}

gfx::Size FrameCaptionButton::GetPreferredSize() const {
  return hovered_background_image_.isNull() ?
      gfx::Size() : hovered_background_image_.size();
}

const char* FrameCaptionButton::GetClassName() const {
  return kViewClassName;
}

void FrameCaptionButton::OnPaint(gfx::Canvas* canvas) {
  if (hover_animation_->is_animating() || state() == STATE_HOVERED) {
    int hovered_background_alpha = hover_animation_->is_animating() ?
        hover_animation_->CurrentValueBetween(0, 255) : 255;
    SkPaint paint;
    paint.setAlpha(hovered_background_alpha);
    canvas->DrawImageInt(hovered_background_image_, 0, 0, paint);
  } else if (state() == STATE_PRESSED) {
    canvas->DrawImageInt(pressed_background_image_, 0, 0);
  }

  int icon_alpha = swap_images_animation_->CurrentValueBetween(0, 255);
  int crossfade_icon_alpha = 0;
  if (icon_alpha < static_cast<int>(kFadeOutRatio * 255))
     crossfade_icon_alpha = static_cast<int>(255 - icon_alpha / kFadeOutRatio);

  if (crossfade_icon_alpha > 0 && !crossfade_icon_image_.isNull()) {
    gfx::Canvas icon_canvas(icon_image_.size(), canvas->image_scale(), false);
    SkPaint paint;
    paint.setAlpha(icon_alpha);
    icon_canvas.DrawImageInt(icon_image_, 0, 0, paint);

    paint.setAlpha(crossfade_icon_alpha);
    paint.setXfermodeMode(SkXfermode::kPlus_Mode);
    icon_canvas.DrawImageInt(crossfade_icon_image_, 0, 0, paint);

    PaintCentered(canvas, gfx::ImageSkia(icon_canvas.ExtractImageRep()),
                  alpha_);
  } else {
    if (!swap_images_animation_->is_animating())
      icon_alpha = alpha_;
    PaintCentered(canvas, icon_image_, icon_alpha);
  }
}

void FrameCaptionButton::OnGestureEvent(ui::GestureEvent* event) {
  // CustomButton does not become pressed when the user drags off and then back
  // onto the button. Make FrameCaptionButton pressed in this case because this
  // behavior is more consistent with AlternateFrameSizeButton.
  if (event->type() == ui::ET_GESTURE_SCROLL_BEGIN ||
      event->type() == ui::ET_GESTURE_SCROLL_UPDATE) {
    if (HitTestPoint(event->location())) {
      SetState(STATE_PRESSED);
      RequestFocus();
      event->StopPropagation();
    } else {
      SetState(STATE_NORMAL);
    }
  } else if (event->type() == ui::ET_GESTURE_SCROLL_END) {
    if (HitTestPoint(event->location())) {
      SetState(STATE_HOVERED);
      NotifyClick(*event);
      event->StopPropagation();
    }
  }
  CustomButton::OnGestureEvent(event);
}

void FrameCaptionButton::PaintCentered(gfx::Canvas* canvas,
                                       const gfx::ImageSkia& to_center,
                                       int alpha) {
  if (!paint_as_active_)
    alpha *= kInactiveIconAlpha;

  SkPaint paint;
  paint.setAlpha(alpha);
  canvas->DrawImageInt(to_center,
                       (width() - to_center.width()) / 2,
                       (height() - to_center.height()) / 2,
                       paint);
}

}  // namespace ash
<commit_msg>Show hovered and pressed unfocused ash caption buttons as active.<commit_after>// Copyright 2013 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 "ash/frame/caption_buttons/frame_caption_button.h"

#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/animation/slide_animation.h"
#include "ui/gfx/animation/throb_animation.h"
#include "ui/gfx/canvas.h"

namespace ash {

namespace {

// The duration of the crossfade animation when swapping the button's images.
const int kSwapImagesAnimationDurationMs = 200;

// The duration of the fade out animation of the old icon during a crossfade
// animation as a ratio of |kSwapImagesAnimationDurationMs|.
const float kFadeOutRatio = 0.5f;

// The alpha to draw inactive icons with.
const float kInactiveIconAlpha = 0.2f;

}  // namespace

// static
const char FrameCaptionButton::kViewClassName[] = "FrameCaptionButton";

FrameCaptionButton::FrameCaptionButton(views::ButtonListener* listener,
                                       CaptionButtonIcon icon)
    : CustomButton(listener),
      icon_(icon),
      paint_as_active_(false),
      alpha_(255),
      icon_image_id_(-1),
      hovered_background_image_id_(-1),
      pressed_background_image_id_(-1),
      swap_images_animation_(new gfx::SlideAnimation(this)) {
  swap_images_animation_->Reset(1);

  // Do not flip the gfx::Canvas passed to the OnPaint() method. The snap left
  // and snap right button icons should not be flipped. The other icons are
  // horizontally symmetrical.
}

FrameCaptionButton::~FrameCaptionButton() {
}

void FrameCaptionButton::SetImages(CaptionButtonIcon icon,
                                   Animate animate,
                                   int icon_image_id,
                                   int hovered_background_image_id,
                                   int pressed_background_image_id) {
  // The early return is dependant on |animate| because callers use SetImages()
  // with ANIMATE_NO to progress the crossfade animation to the end.
  if (icon == icon_ &&
      (animate == ANIMATE_YES || !swap_images_animation_->is_animating()) &&
      icon_image_id == icon_image_id_ &&
      hovered_background_image_id == hovered_background_image_id_ &&
      pressed_background_image_id == pressed_background_image_id_) {
    return;
  }

  if (animate == ANIMATE_YES)
    crossfade_icon_image_ = icon_image_;

  icon_ = icon;
  icon_image_id_ = icon_image_id;
  hovered_background_image_id_ = hovered_background_image_id;
  pressed_background_image_id_ = pressed_background_image_id;

  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
  icon_image_ = *rb.GetImageSkiaNamed(icon_image_id);
  hovered_background_image_ = *rb.GetImageSkiaNamed(
      hovered_background_image_id);
  pressed_background_image_ = *rb.GetImageSkiaNamed(
      pressed_background_image_id);

  if (animate == ANIMATE_YES) {
    swap_images_animation_->Reset(0);
    swap_images_animation_->SetSlideDuration(kSwapImagesAnimationDurationMs);
    swap_images_animation_->Show();
  } else {
    swap_images_animation_->Reset(1);
  }
  PreferredSizeChanged();
  SchedulePaint();
}

bool FrameCaptionButton::IsAnimatingImageSwap() const {
  return swap_images_animation_->is_animating();
}

void FrameCaptionButton::SetAlpha(int alpha) {
  if (alpha_ != alpha) {
    alpha_ = alpha;
    SchedulePaint();
  }
}

gfx::Size FrameCaptionButton::GetPreferredSize() const {
  return hovered_background_image_.isNull() ?
      gfx::Size() : hovered_background_image_.size();
}

const char* FrameCaptionButton::GetClassName() const {
  return kViewClassName;
}

void FrameCaptionButton::OnPaint(gfx::Canvas* canvas) {
  if (hover_animation_->is_animating() || state() == STATE_HOVERED) {
    int hovered_background_alpha = hover_animation_->is_animating() ?
        hover_animation_->CurrentValueBetween(0, 255) : 255;
    SkPaint paint;
    paint.setAlpha(hovered_background_alpha);
    canvas->DrawImageInt(hovered_background_image_, 0, 0, paint);
  } else if (state() == STATE_PRESSED) {
    canvas->DrawImageInt(pressed_background_image_, 0, 0);
  }

  int icon_alpha = swap_images_animation_->CurrentValueBetween(0, 255);
  int crossfade_icon_alpha = 0;
  if (icon_alpha < static_cast<int>(kFadeOutRatio * 255))
     crossfade_icon_alpha = static_cast<int>(255 - icon_alpha / kFadeOutRatio);

  if (crossfade_icon_alpha > 0 && !crossfade_icon_image_.isNull()) {
    gfx::Canvas icon_canvas(icon_image_.size(), canvas->image_scale(), false);
    SkPaint paint;
    paint.setAlpha(icon_alpha);
    icon_canvas.DrawImageInt(icon_image_, 0, 0, paint);

    paint.setAlpha(crossfade_icon_alpha);
    paint.setXfermodeMode(SkXfermode::kPlus_Mode);
    icon_canvas.DrawImageInt(crossfade_icon_image_, 0, 0, paint);

    PaintCentered(canvas, gfx::ImageSkia(icon_canvas.ExtractImageRep()),
                  alpha_);
  } else {
    if (!swap_images_animation_->is_animating())
      icon_alpha = alpha_;
    PaintCentered(canvas, icon_image_, icon_alpha);
  }
}

void FrameCaptionButton::OnGestureEvent(ui::GestureEvent* event) {
  // CustomButton does not become pressed when the user drags off and then back
  // onto the button. Make FrameCaptionButton pressed in this case because this
  // behavior is more consistent with AlternateFrameSizeButton.
  if (event->type() == ui::ET_GESTURE_SCROLL_BEGIN ||
      event->type() == ui::ET_GESTURE_SCROLL_UPDATE) {
    if (HitTestPoint(event->location())) {
      SetState(STATE_PRESSED);
      RequestFocus();
      event->StopPropagation();
    } else {
      SetState(STATE_NORMAL);
    }
  } else if (event->type() == ui::ET_GESTURE_SCROLL_END) {
    if (HitTestPoint(event->location())) {
      SetState(STATE_HOVERED);
      NotifyClick(*event);
      event->StopPropagation();
    }
  }
  CustomButton::OnGestureEvent(event);
}

void FrameCaptionButton::PaintCentered(gfx::Canvas* canvas,
                                       const gfx::ImageSkia& to_center,
                                       int alpha) {
  if (!paint_as_active_) {
    // Paint icons as active when they are hovered over or pressed.
    double inactive_alpha = kInactiveIconAlpha;
    if (hover_animation_->is_animating()) {
      inactive_alpha =
          hover_animation_->CurrentValueBetween(inactive_alpha, 1.0f);
    } else if (state() == STATE_PRESSED || state() == STATE_HOVERED) {
      inactive_alpha = 1.0f;
    }
    alpha *= inactive_alpha;
  }

  SkPaint paint;
  paint.setAlpha(alpha);
  canvas->DrawImageInt(to_center,
                       (width() - to_center.width()) / 2,
                       (height() - to_center.height()) / 2,
                       paint);
}

}  // namespace ash
<|endoftext|>


<commit_before>#include "SkImageRef.h"
#include "SkBitmap.h"
#include "SkFlattenable.h"
#include "SkImageDecoder.h"
#include "SkStream.h"
#include "SkTemplates.h"
#include "SkThread.h"

// can't be static, as SkImageRef_Pool needs to see it
SkMutex gImageRefMutex;

///////////////////////////////////////////////////////////////////////////////

SkImageRef::SkImageRef(SkStream* stream, SkBitmap::Config config,
                       int sampleSize)
        : SkPixelRef(&gImageRefMutex), fErrorInDecoding(false) {
    SkASSERT(stream);
    stream->ref();
    fStream = stream;
    fConfig = config;
    fSampleSize = sampleSize;
    fPrev = fNext = NULL;
    fFactory = NULL;

#ifdef DUMP_IMAGEREF_LIFECYCLE
    SkDebugf("add ImageRef %p [%d] data=%d\n",
              this, config, (int)stream->getLength());
#endif
}

SkImageRef::~SkImageRef() {
    SkASSERT(&gImageRefMutex == this->mutex());

#ifdef DUMP_IMAGEREF_LIFECYCLE
    SkDebugf("delete ImageRef %p [%d] data=%d\n",
              this, fConfig, (int)fStream->getLength());
#endif

    fStream->unref();
    fFactory->safeUnref();
}

bool SkImageRef::getInfo(SkBitmap* bitmap) {
    SkAutoMutexAcquire ac(gImageRefMutex);

    if (!this->prepareBitmap(SkImageDecoder::kDecodeBounds_Mode)) {
        return false;
    }

    SkASSERT(SkBitmap::kNo_Config != fBitmap.config());
    if (bitmap) {
        bitmap->setConfig(fBitmap.config(), fBitmap.width(), fBitmap.height());
    }
    return true;
}

SkImageDecoderFactory* SkImageRef::setDecoderFactory(
                                                SkImageDecoderFactory* fact) {
    SkRefCnt_SafeAssign(fFactory, fact);
    return fact;
}

///////////////////////////////////////////////////////////////////////////////

bool SkImageRef::onDecode(SkImageDecoder* codec, SkStream* stream,
                          SkBitmap* bitmap, SkBitmap::Config config,
                          SkImageDecoder::Mode mode) {
    return codec->decode(stream, bitmap, config, mode);
}

bool SkImageRef::prepareBitmap(SkImageDecoder::Mode mode) {
    SkASSERT(&gImageRefMutex == this->mutex());

    if (fErrorInDecoding) {
        return false;
    }

    /*  As soon as we really know our config, we record it, so that on
        subsequent calls to the codec, we are sure we will always get the same
        result.
    */
    if (SkBitmap::kNo_Config != fBitmap.config()) {
        fConfig = fBitmap.config();
    }

    if (NULL != fBitmap.getPixels() ||
            (SkBitmap::kNo_Config != fBitmap.config() &&
             SkImageDecoder::kDecodeBounds_Mode == mode)) {
        return true;
    }

    SkASSERT(fBitmap.getPixels() == NULL);

    fStream->rewind();

    SkImageDecoder* codec;
    if (fFactory) {
        codec = fFactory->newDecoder(fStream);
    } else {
        codec = SkImageDecoder::Factory(fStream);
    }

    if (codec) {
        SkAutoTDelete<SkImageDecoder> ad(codec);

        codec->setSampleSize(fSampleSize);
        if (this->onDecode(codec, fStream, &fBitmap, fConfig, mode)) {
            return true;
        }
    }

#ifdef DUMP_IMAGEREF_LIFECYCLE
    if (NULL == codec) {
        SkDebugf("--- ImageRef: <%s> failed to find codec\n", this->getURI());
    } else {
        SkDebugf("--- ImageRef: <%s> failed in codec for %d mode\n",
                 this->getURI(), mode);
    }
#endif
    fErrorInDecoding = true;
    fBitmap.reset();
    return false;
}

void* SkImageRef::onLockPixels(SkColorTable** ct) {
    SkASSERT(&gImageRefMutex == this->mutex());

    if (NULL == fBitmap.getPixels()) {
        (void)this->prepareBitmap(SkImageDecoder::kDecodePixels_Mode);
    }

    if (ct) {
        *ct = fBitmap.getColorTable();
    }
    return fBitmap.getPixels();
}

void SkImageRef::onUnlockPixels() {
    // we're already have the mutex locked
    SkASSERT(&gImageRefMutex == this->mutex());
}

size_t SkImageRef::ramUsed() const {
    size_t size = 0;

    if (fBitmap.getPixels()) {
        size = fBitmap.getSize();
        if (fBitmap.getColorTable()) {
            size += fBitmap.getColorTable()->count() * sizeof(SkPMColor);
        }
    }
    return size;
}

///////////////////////////////////////////////////////////////////////////////

SkImageRef::SkImageRef(SkFlattenableReadBuffer& buffer)
        : INHERITED(buffer, &gImageRefMutex), fErrorInDecoding(false) {
    fConfig = (SkBitmap::Config)buffer.readU8();
    fSampleSize = buffer.readU8();
    size_t length = buffer.readU32();
    fStream = SkNEW_ARGS(SkMemoryStream, (length));
    buffer.read((void*)fStream->getMemoryBase(), length);

    fPrev = fNext = NULL;
}

void SkImageRef::flatten(SkFlattenableWriteBuffer& buffer) const {
    this->INHERITED::flatten(buffer);

    buffer.write8(fConfig);
    buffer.write8(fSampleSize);
    size_t length = fStream->getLength();
    buffer.write32(length);
    fStream->rewind();
    buffer.readFromStream(fStream, length);
}

<commit_msg>Automated import from //branches/master/...@141344,141344<commit_after>#include "SkImageRef.h"
#include "SkBitmap.h"
#include "SkFlattenable.h"
#include "SkImageDecoder.h"
#include "SkStream.h"
#include "SkTemplates.h"
#include "SkThread.h"

// can't be static, as SkImageRef_Pool needs to see it
SkMutex gImageRefMutex;

///////////////////////////////////////////////////////////////////////////////

SkImageRef::SkImageRef(SkStream* stream, SkBitmap::Config config,
                       int sampleSize)
        : SkPixelRef(&gImageRefMutex), fErrorInDecoding(false) {
    SkASSERT(stream);
    stream->ref();
    fStream = stream;
    fConfig = config;
    fSampleSize = sampleSize;
    fPrev = fNext = NULL;
    fFactory = NULL;

#ifdef DUMP_IMAGEREF_LIFECYCLE
    SkDebugf("add ImageRef %p [%d] data=%d\n",
              this, config, (int)stream->getLength());
#endif
}

SkImageRef::~SkImageRef() {
    SkASSERT(&gImageRefMutex == this->mutex());

#ifdef DUMP_IMAGEREF_LIFECYCLE
    SkDebugf("delete ImageRef %p [%d] data=%d\n",
              this, fConfig, (int)fStream->getLength());
#endif

    fStream->unref();
    fFactory->safeUnref();
}

bool SkImageRef::getInfo(SkBitmap* bitmap) {
    SkAutoMutexAcquire ac(gImageRefMutex);

    if (!this->prepareBitmap(SkImageDecoder::kDecodeBounds_Mode)) {
        return false;
    }

    SkASSERT(SkBitmap::kNo_Config != fBitmap.config());
    if (bitmap) {
        bitmap->setConfig(fBitmap.config(), fBitmap.width(), fBitmap.height());
    }
    return true;
}

SkImageDecoderFactory* SkImageRef::setDecoderFactory(
                                                SkImageDecoderFactory* fact) {
    SkRefCnt_SafeAssign(fFactory, fact);
    return fact;
}

///////////////////////////////////////////////////////////////////////////////

bool SkImageRef::onDecode(SkImageDecoder* codec, SkStream* stream,
                          SkBitmap* bitmap, SkBitmap::Config config,
                          SkImageDecoder::Mode mode) {
    return codec->decode(stream, bitmap, config, mode);
}

bool SkImageRef::prepareBitmap(SkImageDecoder::Mode mode) {
    SkASSERT(&gImageRefMutex == this->mutex());

    if (fErrorInDecoding) {
        return false;
    }

    /*  As soon as we really know our config, we record it, so that on
        subsequent calls to the codec, we are sure we will always get the same
        result.
    */
    if (SkBitmap::kNo_Config != fBitmap.config()) {
        fConfig = fBitmap.config();
    }

    if (NULL != fBitmap.getPixels() ||
            (SkBitmap::kNo_Config != fBitmap.config() &&
             SkImageDecoder::kDecodeBounds_Mode == mode)) {
        return true;
    }

    SkASSERT(fBitmap.getPixels() == NULL);

    fStream->rewind();

    SkImageDecoder* codec;
    if (fFactory) {
        codec = fFactory->newDecoder(fStream);
    } else {
        codec = SkImageDecoder::Factory(fStream);
    }

    if (codec) {
        SkAutoTDelete<SkImageDecoder> ad(codec);

        codec->setSampleSize(fSampleSize);
        if (this->onDecode(codec, fStream, &fBitmap, fConfig, mode)) {
            return true;
        }
    }

#ifdef DUMP_IMAGEREF_LIFECYCLE
    if (NULL == codec) {
        SkDebugf("--- ImageRef: <%s> failed to find codec\n", this->getURI());
    } else {
        SkDebugf("--- ImageRef: <%s> failed in codec for %d mode\n",
                 this->getURI(), mode);
    }
#endif
    fErrorInDecoding = true;
    fBitmap.reset();
    return false;
}

void* SkImageRef::onLockPixels(SkColorTable** ct) {
    SkASSERT(&gImageRefMutex == this->mutex());

    if (NULL == fBitmap.getPixels()) {
        (void)this->prepareBitmap(SkImageDecoder::kDecodePixels_Mode);
    }

    if (ct) {
        *ct = fBitmap.getColorTable();
    }
    return fBitmap.getPixels();
}

void SkImageRef::onUnlockPixels() {
    // we're already have the mutex locked
    SkASSERT(&gImageRefMutex == this->mutex());
}

size_t SkImageRef::ramUsed() const {
    size_t size = 0;

    if (fBitmap.getPixels()) {
        size = fBitmap.getSize();
        if (fBitmap.getColorTable()) {
            size += fBitmap.getColorTable()->count() * sizeof(SkPMColor);
        }
    }
    return size;
}

///////////////////////////////////////////////////////////////////////////////

SkImageRef::SkImageRef(SkFlattenableReadBuffer& buffer)
        : INHERITED(buffer, &gImageRefMutex), fErrorInDecoding(false) {
    fConfig = (SkBitmap::Config)buffer.readU8();
    fSampleSize = buffer.readU8();
    size_t length = buffer.readU32();
    fStream = SkNEW_ARGS(SkMemoryStream, (length));
    buffer.read((void*)fStream->getMemoryBase(), length);

    fPrev = fNext = NULL;
    fFactory = NULL;
}

void SkImageRef::flatten(SkFlattenableWriteBuffer& buffer) const {
    this->INHERITED::flatten(buffer);

    buffer.write8(fConfig);
    buffer.write8(fSampleSize);
    size_t length = fStream->getLength();
    buffer.write32(length);
    fStream->rewind();
    buffer.readFromStream(fStream, length);
}

<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * 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.
 *****************************************************************************/

/**
 * @file conti_radar_message_manager.h
 * @brief The class of ContiRadarMessageManager
 */

#include "modules/drivers/conti_radar/conti_radar_message_manager.h"

#include "modules/drivers/conti_radar/protocol/cluster_general_info_701.h"
#include "modules/drivers/conti_radar/protocol/cluster_list_status_600.h"
#include "modules/drivers/conti_radar/protocol/cluster_quality_info_702.h"
#include "modules/drivers/conti_radar/protocol/object_extended_info_60d.h"
#include "modules/drivers/conti_radar/protocol/object_general_info_60b.h"
#include "modules/drivers/conti_radar/protocol/object_list_status_60a.h"
#include "modules/drivers/conti_radar/protocol/object_quality_info_60c.h"
#include "modules/drivers/conti_radar/protocol/radar_state_201.h"

namespace apollo {
namespace drivers {
namespace conti_radar {

using ::apollo::common::adapter::AdapterManager;

ContiRadarMessageManager::ContiRadarMessageManager() {
  AddRecvProtocolData<RadarState201, true>();
  AddRecvProtocolData<ClusterListStatus600, true>();
  AddRecvProtocolData<ClusterGeneralInfo701, true>();
  AddRecvProtocolData<ClusterQualityInfo702, true>();
  AddRecvProtocolData<ObjectExtendedInfo60D, true>();
  AddRecvProtocolData<ObjectGeneralInfo60B, true>();
  AddRecvProtocolData<ObjectListStatus60A, true>();
  AddRecvProtocolData<ObjectQualityInfo60C, true>();
}

void ContiRadarMessageManager::set_radar_conf(RadarConf radar_conf) {
  radar_config_.set_radar_conf(radar_conf);
}

void ContiRadarMessageManager::set_can_client(
    std::shared_ptr<CanClient> can_client) {
  can_client_ = can_client;
}

ProtocolData<ContiRadar> *ContiRadarMessageManager::GetMutableProtocolDataById(
    const uint32_t message_id) {
  uint32_t converted_message_id = message_id;
  if (protocol_data_map_.find(converted_message_id) ==
      protocol_data_map_.end()) {
    ADEBUG << "Unable to get protocol data because of invalid message_id:"
           << message_id;
    return nullptr;
  }
  return protocol_data_map_[converted_message_id];
}

void ContiRadarMessageManager::Parse(const uint32_t message_id,
                                     const uint8_t *data, int32_t length) {
  /*
if (length != ::apollo::drivers::canbus::CANBUS_MESSAGE_LENGTH) {
AERROR << "Incorrect ContiRadar message length, length:" << length
<< " required length: "
<< ::apollo::drivers::canbus::CANBUS_MESSAGE_LENGTH;
return;
}
*/
  ProtocolData<ContiRadar> *sensor_protocol_data =
      GetMutableProtocolDataById(message_id);
  if (sensor_protocol_data == nullptr) {
    return;
  }

  std::lock_guard<std::mutex> lock(sensor_data_mutex_);
  if (!is_configured_ && message_id != 0x201) {
    // read radar state message first
    return;
  }

  // trigger publishment
  if (message_id == 0x600 || message_id == 0x60A) {
    ADEBUG << sensor_data_.ShortDebugString();

    if (sensor_data_.contiobs_size() <=
        sensor_data_.object_list_status().nof_objects()) {
      // maybe lost a object_list_status msg
      AdapterManager::PublishContiRadar(sensor_data_);
    }
    sensor_data_.Clear();
    // fill header when recieve the general info message
    AdapterManager::FillContiRadarHeader(FLAGS_sensor_node_name, &sensor_data_);
  }

  sensor_protocol_data->Parse(data, length, &sensor_data_);

  if (message_id == 0x201) {
    ADEBUG << sensor_data_.ShortDebugString();
    if (sensor_data_.radar_state().send_quality() ==
            radar_config_.radar_conf().send_quality() &&
        sensor_data_.radar_state().send_ext_info() ==
            radar_config_.radar_conf().send_ext_info() &&
        sensor_data_.radar_state().max_distance() ==
            radar_config_.radar_conf().max_distance() &&
        sensor_data_.radar_state().output_type() ==
            radar_config_.radar_conf().output_type() &&
        sensor_data_.radar_state().rcs_threshold() ==
            radar_config_.radar_conf().rcs_threshold() &&
        sensor_data_.radar_state().radar_power() ==
            radar_config_.radar_conf().radar_power()) {
      is_configured_ = true;
    } else {
      AINFO << "configure radar again";
      SenderMessage<ContiRadar> sender_message(RadarConfig200::ID,
                                               &radar_config_);
      sender_message.Update();
      can_client_->SendSingleFrame({sender_message.CanFrame()});
    }
  }

  received_ids_.insert(message_id);
  // check if need to check period
  const auto it = check_ids_.find(message_id);
  if (it != check_ids_.end()) {
    const int64_t time = apollo::common::time::AsInt64<micros>(Clock::Now());
    it->second.real_period = time - it->second.last_time;
    // if period 1.5 large than base period, inc error_count
    const double period_multiplier = 1.5;
    if (it->second.real_period > (it->second.period * period_multiplier)) {
      it->second.error_count += 1;
    } else {
      it->second.error_count = 0;
    }
    it->second.last_time = time;
  }
}

}  // namespace conti_radar
}  // namespace drivers
}  // namespace apollo
<commit_msg>radar: remove canbus length check. (#1706)<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * 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.
 *****************************************************************************/

/**
 * @file conti_radar_message_manager.h
 * @brief The class of ContiRadarMessageManager
 */

#include "modules/drivers/conti_radar/conti_radar_message_manager.h"

#include "modules/drivers/conti_radar/protocol/cluster_general_info_701.h"
#include "modules/drivers/conti_radar/protocol/cluster_list_status_600.h"
#include "modules/drivers/conti_radar/protocol/cluster_quality_info_702.h"
#include "modules/drivers/conti_radar/protocol/object_extended_info_60d.h"
#include "modules/drivers/conti_radar/protocol/object_general_info_60b.h"
#include "modules/drivers/conti_radar/protocol/object_list_status_60a.h"
#include "modules/drivers/conti_radar/protocol/object_quality_info_60c.h"
#include "modules/drivers/conti_radar/protocol/radar_state_201.h"

namespace apollo {
namespace drivers {
namespace conti_radar {

using ::apollo::common::adapter::AdapterManager;

ContiRadarMessageManager::ContiRadarMessageManager() {
  AddRecvProtocolData<RadarState201, true>();
  AddRecvProtocolData<ClusterListStatus600, true>();
  AddRecvProtocolData<ClusterGeneralInfo701, true>();
  AddRecvProtocolData<ClusterQualityInfo702, true>();
  AddRecvProtocolData<ObjectExtendedInfo60D, true>();
  AddRecvProtocolData<ObjectGeneralInfo60B, true>();
  AddRecvProtocolData<ObjectListStatus60A, true>();
  AddRecvProtocolData<ObjectQualityInfo60C, true>();
}

void ContiRadarMessageManager::set_radar_conf(RadarConf radar_conf) {
  radar_config_.set_radar_conf(radar_conf);
}

void ContiRadarMessageManager::set_can_client(
    std::shared_ptr<CanClient> can_client) {
  can_client_ = can_client;
}

ProtocolData<ContiRadar> *ContiRadarMessageManager::GetMutableProtocolDataById(
    const uint32_t message_id) {
  uint32_t converted_message_id = message_id;
  if (protocol_data_map_.find(converted_message_id) ==
      protocol_data_map_.end()) {
    ADEBUG << "Unable to get protocol data because of invalid message_id:"
           << message_id;
    return nullptr;
  }
  return protocol_data_map_[converted_message_id];
}

void ContiRadarMessageManager::Parse(const uint32_t message_id,
                                     const uint8_t *data, int32_t length) {
  ProtocolData<ContiRadar> *sensor_protocol_data =
      GetMutableProtocolDataById(message_id);
  if (sensor_protocol_data == nullptr) {
    return;
  }

  std::lock_guard<std::mutex> lock(sensor_data_mutex_);
  if (!is_configured_ && message_id != 0x201) {
    // read radar state message first
    return;
  }

  // trigger publishment
  if (message_id == 0x600 || message_id == 0x60A) {
    ADEBUG << sensor_data_.ShortDebugString();

    if (sensor_data_.contiobs_size() <=
        sensor_data_.object_list_status().nof_objects()) {
      // maybe lost a object_list_status msg
      AdapterManager::PublishContiRadar(sensor_data_);
    }
    sensor_data_.Clear();
    // fill header when recieve the general info message
    AdapterManager::FillContiRadarHeader(FLAGS_sensor_node_name, &sensor_data_);
  }

  sensor_protocol_data->Parse(data, length, &sensor_data_);

  if (message_id == 0x201) {
    ADEBUG << sensor_data_.ShortDebugString();
    if (sensor_data_.radar_state().send_quality() ==
            radar_config_.radar_conf().send_quality() &&
        sensor_data_.radar_state().send_ext_info() ==
            radar_config_.radar_conf().send_ext_info() &&
        sensor_data_.radar_state().max_distance() ==
            radar_config_.radar_conf().max_distance() &&
        sensor_data_.radar_state().output_type() ==
            radar_config_.radar_conf().output_type() &&
        sensor_data_.radar_state().rcs_threshold() ==
            radar_config_.radar_conf().rcs_threshold() &&
        sensor_data_.radar_state().radar_power() ==
            radar_config_.radar_conf().radar_power()) {
      is_configured_ = true;
    } else {
      AINFO << "configure radar again";
      SenderMessage<ContiRadar> sender_message(RadarConfig200::ID,
                                               &radar_config_);
      sender_message.Update();
      can_client_->SendSingleFrame({sender_message.CanFrame()});
    }
  }

  received_ids_.insert(message_id);
  // check if need to check period
  const auto it = check_ids_.find(message_id);
  if (it != check_ids_.end()) {
    const int64_t time = apollo::common::time::AsInt64<micros>(Clock::Now());
    it->second.real_period = time - it->second.last_time;
    // if period 1.5 large than base period, inc error_count
    const double period_multiplier = 1.5;
    if (it->second.real_period > (it->second.period * period_multiplier)) {
      it->second.error_count += 1;
    } else {
      it->second.error_count = 0;
    }
    it->second.last_time = time;
  }
}

}  // namespace conti_radar
}  // namespace drivers
}  // namespace apollo
<|endoftext|>


<commit_before>// Copyright (c) 2013 Joshua Beitler, Mirus contributors

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#ifndef _MIRUS_KERNEL_SERIAL_H_
#define _MIRUS_KERNEL_SERIAL_H_

#include <core/ioport.hpp>

#define PORT 0x3f8  // com1

namespace mirus {
    void init_serial();
    int serial_received();
    char read_serial();
    int is_transmit_empty();
    void write_serial(char a);
}

#endif<commit_msg>Forgot to rename member in the header<commit_after>// Copyright (c) 2013 Joshua Beitler, Mirus contributors

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#ifndef _MIRUS_KERNEL_SERIAL_H_
#define _MIRUS_KERNEL_SERIAL_H_

#include <core/ioport.hpp>

#define PORT 0x3f8  // com1

namespace mirus {
    void serial_install();
    int serial_received();
    char read_serial();
    int is_transmit_empty();
    void write_serial(char a);
}

#endif<|endoftext|>


<commit_before>//
//  yas_audio_device_io.cpp
//

#include "yas_audio_engine_device_io.h"

#if (TARGET_OS_MAC && !TARGET_OS_IPHONE)

#include <iostream>
#include "yas_audio_device.h"
#include "yas_audio_device_io.h"
#include "yas_audio_engine_tap.h"
#include "yas_audio_graph.h"
#include "yas_audio_time.h"
#include "yas_result.h"

using namespace yas;

#pragma mark - audio::engine::device_io::impl

struct audio::engine::device_io::impl : base::impl, manageable_device_io::impl {
    audio::engine::node _node = {{.input_bus_count = 1, .output_bus_count = 1}};
    chaining::any_observer _connections_observer = nullptr;

    virtual ~impl() final = default;

    void prepare(engine::device_io const &engine_device_io, audio::device const &device) {
        set_device(device ?: device::default_output_device());

        auto weak_engine_device_io = to_weak(engine_device_io);

        _node.set_render_handler([weak_engine_device_io](auto args) {
            auto &buffer = args.buffer;

            if (auto engine_device_io = weak_engine_device_io.lock()) {
                if (auto const &device_io = engine_device_io.impl_ptr<impl>()->device_io()) {
                    auto &input_buffer = device_io.input_buffer_on_render();
                    if (input_buffer && input_buffer.format() == buffer.format()) {
                        buffer.copy_from(input_buffer);
                    }
                }
            }
        });

        this->_connections_observer = this->_node.chain(node::method::update_connections)
                                          .perform([weak_engine_device_io](auto const &) {
                                              if (auto engine_device_io = weak_engine_device_io.lock()) {
                                                  engine_device_io.impl_ptr<impl>()->_update_device_io_connections();
                                              }
                                          })
                                          .end();
    }

    void add_device_io() override {
        _core._device_io = audio::device_io{_core.device()};
    }

    void remove_device_io() override {
        _core._device_io = nullptr;
    }

    audio::device_io &device_io() override {
        return _core._device_io;
    }

    void set_device(audio::device const &device) {
        _core.set_device(device);
    }

    audio::device device() {
        return _core.device();
    }

   private:
    struct core {
        audio::device_io _device_io = nullptr;

        void set_device(audio::device const &device) {
            _device = device;
            if (_device_io) {
                _device_io.set_device(device);
            }
        }

        audio::device device() {
            return _device;
        }

       private:
        audio::device _device = nullptr;
    };

    core _core;

    void _update_device_io_connections() {
        auto &device_io = _core._device_io;
        if (!device_io) {
            return;
        }

        if (!_validate_connections()) {
            device_io.set_render_handler(nullptr);
            return;
        }

        auto weak_engine_device_io = to_weak(cast<engine::device_io>());
        auto weak_device_io = to_weak(device_io);

        auto render_handler = [weak_engine_device_io, weak_device_io](auto args) {
            if (auto engine_device_io = weak_engine_device_io.lock()) {
                if (auto kernel = engine_device_io.node().kernel()) {
                    if (args.output_buffer) {
                        auto const connections = kernel.input_connections();
                        if (connections.count(0) > 0) {
                            auto const &connection = connections.at(0);
                            if (auto src_node = connection.source_node()) {
                                if (connection.format() == src_node.output_format(connection.source_bus())) {
                                    src_node.render({.buffer = args.output_buffer,
                                                     .bus_idx = connection.source_bus(),
                                                     .when = args.when});
                                }
                            }
                        }
                    }

                    if (auto const device_io = weak_device_io.lock()) {
                        auto const connections = kernel.output_connections();
                        if (connections.count(0) > 0) {
                            auto const &connection = connections.at(0);
                            if (auto dst_node = connection.destination_node()) {
                                if (dst_node.is_input_renderable()) {
                                    auto input_buffer = device_io.input_buffer_on_render();
                                    auto const &input_time = device_io.input_time_on_render();
                                    if (input_buffer && input_time) {
                                        if (connection.format() ==
                                            dst_node.input_format(connection.destination_bus())) {
                                            dst_node.render({.buffer = input_buffer, .bus_idx = 0, .when = input_time});
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        };

        device_io.set_render_handler(std::move(render_handler));
    }

    bool _validate_connections() {
        if (auto const &device_io = _core._device_io) {
            auto &input_connections = _node.input_connections();
            if (input_connections.size() > 0) {
                auto const connections = lock_values(input_connections);
                if (connections.count(0) > 0) {
                    auto const &connection = connections.at(0);
                    auto const &connection_format = connection.format();
                    auto const &device_format = device_io.device().output_format();
                    if (connection_format != device_format) {
                        std::cout << __PRETTY_FUNCTION__ << " : output device io format is not match." << std::endl;
                        return false;
                    }
                }
            }

            auto &output_connections = _node.output_connections();
            if (output_connections.size() > 0) {
                auto const connections = lock_values(output_connections);
                if (connections.count(0) > 0) {
                    auto const &connection = connections.at(0);
                    auto const &connection_format = connection.format();
                    auto const &device_format = device_io.device().input_format();
                    if (connection_format != device_format) {
                        std::cout << __PRETTY_FUNCTION__ << " : input device io format is not match." << std::endl;
                        return false;
                    }
                }
            }
        }

        return true;
    }
};

#pragma mark - audio::engine::device_io

audio::engine::device_io::device_io() : device_io(audio::device(nullptr)) {
}

audio::engine::device_io::device_io(std::nullptr_t) : base(nullptr) {
}

audio::engine::device_io::device_io(audio::device const &device) : base(std::make_unique<impl>()) {
    impl_ptr<impl>()->prepare(*this, device);
}

audio::engine::device_io::~device_io() = default;

void audio::engine::device_io::set_device(audio::device const &device) {
    impl_ptr<impl>()->set_device(device);
}

audio::device audio::engine::device_io::device() const {
    return impl_ptr<impl>()->device();
}

audio::engine::node const &audio::engine::device_io::node() const {
    return impl_ptr<impl>()->_node;
}

audio::engine::node &audio::engine::device_io::node() {
    return impl_ptr<impl>()->_node;
}

audio::engine::manageable_device_io &audio::engine::device_io::manageable() {
    if (!_manageable) {
        _manageable = audio::engine::manageable_device_io{impl_ptr<manageable_device_io::impl>()};
    }
    return _manageable;
}

#endif
<commit_msg>device_io this<commit_after>//
//  yas_audio_device_io.cpp
//

#include "yas_audio_engine_device_io.h"

#if (TARGET_OS_MAC && !TARGET_OS_IPHONE)

#include <iostream>
#include "yas_audio_device.h"
#include "yas_audio_device_io.h"
#include "yas_audio_engine_tap.h"
#include "yas_audio_graph.h"
#include "yas_audio_time.h"
#include "yas_result.h"

using namespace yas;

#pragma mark - audio::engine::device_io::impl

struct audio::engine::device_io::impl : base::impl, manageable_device_io::impl {
    audio::engine::node _node = {{.input_bus_count = 1, .output_bus_count = 1}};
    chaining::any_observer _connections_observer = nullptr;

    virtual ~impl() final = default;

    void prepare(engine::device_io const &engine_device_io, audio::device const &device) {
        this->set_device(device ?: device::default_output_device());

        auto weak_engine_device_io = to_weak(engine_device_io);

        this->_node.set_render_handler([weak_engine_device_io](auto args) {
            auto &buffer = args.buffer;

            if (auto engine_device_io = weak_engine_device_io.lock()) {
                if (auto const &device_io = engine_device_io.impl_ptr<impl>()->device_io()) {
                    auto &input_buffer = device_io.input_buffer_on_render();
                    if (input_buffer && input_buffer.format() == buffer.format()) {
                        buffer.copy_from(input_buffer);
                    }
                }
            }
        });

        this->_connections_observer = this->_node.chain(node::method::update_connections)
                                          .perform([weak_engine_device_io](auto const &) {
                                              if (auto engine_device_io = weak_engine_device_io.lock()) {
                                                  engine_device_io.impl_ptr<impl>()->_update_device_io_connections();
                                              }
                                          })
                                          .end();
    }

    void add_device_io() override {
        this->_core._device_io = audio::device_io{_core.device()};
    }

    void remove_device_io() override {
        this->_core._device_io = nullptr;
    }

    audio::device_io &device_io() override {
        return this->_core._device_io;
    }

    void set_device(audio::device const &device) {
        this->_core.set_device(device);
    }

    audio::device device() {
        return this->_core.device();
    }

   private:
    struct core {
        audio::device_io _device_io = nullptr;

        void set_device(audio::device const &device) {
            this->_device = device;
            if (this->_device_io) {
                this->_device_io.set_device(device);
            }
        }

        audio::device device() {
            return this->_device;
        }

       private:
        audio::device _device = nullptr;
    };

    core _core;

    void _update_device_io_connections() {
        auto &device_io = this->_core._device_io;
        if (!device_io) {
            return;
        }

        if (!this->_validate_connections()) {
            device_io.set_render_handler(nullptr);
            return;
        }

        auto weak_engine_device_io = to_weak(cast<engine::device_io>());
        auto weak_device_io = to_weak(device_io);

        auto render_handler = [weak_engine_device_io, weak_device_io](auto args) {
            if (auto engine_device_io = weak_engine_device_io.lock()) {
                if (auto kernel = engine_device_io.node().kernel()) {
                    if (args.output_buffer) {
                        auto const connections = kernel.input_connections();
                        if (connections.count(0) > 0) {
                            auto const &connection = connections.at(0);
                            if (auto src_node = connection.source_node()) {
                                if (connection.format() == src_node.output_format(connection.source_bus())) {
                                    src_node.render({.buffer = args.output_buffer,
                                                     .bus_idx = connection.source_bus(),
                                                     .when = args.when});
                                }
                            }
                        }
                    }

                    if (auto const device_io = weak_device_io.lock()) {
                        auto const connections = kernel.output_connections();
                        if (connections.count(0) > 0) {
                            auto const &connection = connections.at(0);
                            if (auto dst_node = connection.destination_node()) {
                                if (dst_node.is_input_renderable()) {
                                    auto input_buffer = device_io.input_buffer_on_render();
                                    auto const &input_time = device_io.input_time_on_render();
                                    if (input_buffer && input_time) {
                                        if (connection.format() ==
                                            dst_node.input_format(connection.destination_bus())) {
                                            dst_node.render({.buffer = input_buffer, .bus_idx = 0, .when = input_time});
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        };

        device_io.set_render_handler(std::move(render_handler));
    }

    bool _validate_connections() {
        if (auto const &device_io = this->_core._device_io) {
            auto &input_connections = this->_node.input_connections();
            if (input_connections.size() > 0) {
                auto const connections = lock_values(input_connections);
                if (connections.count(0) > 0) {
                    auto const &connection = connections.at(0);
                    auto const &connection_format = connection.format();
                    auto const &device_format = device_io.device().output_format();
                    if (connection_format != device_format) {
                        std::cout << __PRETTY_FUNCTION__ << " : output device io format is not match." << std::endl;
                        return false;
                    }
                }
            }

            auto &output_connections = _node.output_connections();
            if (output_connections.size() > 0) {
                auto const connections = lock_values(output_connections);
                if (connections.count(0) > 0) {
                    auto const &connection = connections.at(0);
                    auto const &connection_format = connection.format();
                    auto const &device_format = device_io.device().input_format();
                    if (connection_format != device_format) {
                        std::cout << __PRETTY_FUNCTION__ << " : input device io format is not match." << std::endl;
                        return false;
                    }
                }
            }
        }

        return true;
    }
};

#pragma mark - audio::engine::device_io

audio::engine::device_io::device_io() : device_io(audio::device(nullptr)) {
}

audio::engine::device_io::device_io(std::nullptr_t) : base(nullptr) {
}

audio::engine::device_io::device_io(audio::device const &device) : base(std::make_unique<impl>()) {
    impl_ptr<impl>()->prepare(*this, device);
}

audio::engine::device_io::~device_io() = default;

void audio::engine::device_io::set_device(audio::device const &device) {
    impl_ptr<impl>()->set_device(device);
}

audio::device audio::engine::device_io::device() const {
    return impl_ptr<impl>()->device();
}

audio::engine::node const &audio::engine::device_io::node() const {
    return impl_ptr<impl>()->_node;
}

audio::engine::node &audio::engine::device_io::node() {
    return impl_ptr<impl>()->_node;
}

audio::engine::manageable_device_io &audio::engine::device_io::manageable() {
    if (!this->_manageable) {
        this->_manageable = audio::engine::manageable_device_io{impl_ptr<manageable_device_io::impl>()};
    }
    return this->_manageable;
}

#endif
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * 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 "modules/perception/obstacle/radar/modest/object_builder.h"

#include <cmath>

#include "modules/perception/obstacle/radar/modest/conti_radar_util.h"
#include "modules/perception/obstacle/radar/modest/radar_util.h"

namespace apollo {
namespace perception {

bool ObjectBuilder::Build(const ContiRadar &raw_obstacles,
                          const Eigen::Matrix4d &radar_pose,
                          const Eigen::Vector2d &main_velocity,
                          SensorObjects *radar_objects) {
  if (radar_objects == nullptr) {
    AERROR << "radar objects is nullptr.";
    return false;
  }
  std::unordered_map<int, int> current_con_ids;
  auto objects = &(radar_objects->objects);
  for (int i = 0; i < raw_obstacles.contiobs_size(); ++i) {
    ObjectPtr object_ptr = ObjectPtr(new Object());
    const int obstacle_id = raw_obstacles.contiobs(i).obstacle_id();
    auto continuous_id_it = continuous_ids_.find(obstacle_id);
    if (continuous_id_it != continuous_ids_.end()) {
      current_con_ids[obstacle_id] = continuous_id_it->second + 1;
    } else {
      current_con_ids[obstacle_id] = 1;
    }
    if (current_con_ids[obstacle_id] <= delay_frames_) {
      object_ptr->is_background = true;
    }
    int tracking_times = current_con_ids[obstacle_id];
    if (use_fp_filter_ &&
        ContiRadarUtil::IsFp(raw_obstacles.contiobs(i), conti_params_,
                             delay_frames_, tracking_times)) {
      object_ptr->is_background = true;
    }
    object_ptr->track_id = obstacle_id;
    Eigen::Matrix<double, 4, 1> location_r;
    Eigen::Matrix<double, 4, 1> location_w;
    location_r << raw_obstacles.contiobs(i).longitude_dist(),
        raw_obstacles.contiobs(i).lateral_dist(), 0.0, 1.0;
    location_w = radar_pose * location_r;
    Eigen::Vector3d point;
    point = location_w.topLeftCorner(3, 1);
    object_ptr->center = point;
    object_ptr->anchor_point = object_ptr->center;
    Eigen::Matrix<double, 3, 1> velocity_r;
    Eigen::Matrix<double, 3, 1> velocity_w;
    velocity_r << raw_obstacles.contiobs(i).longitude_vel(),
        raw_obstacles.contiobs(i).lateral_vel(), 0.0;
    velocity_w = radar_pose.topLeftCorner(3, 3) * velocity_r;

    //  calculate the absolute velodity
    object_ptr->velocity(0) = velocity_w[0] + main_velocity(0);
    object_ptr->velocity(1) = velocity_w[1] + main_velocity(1);
    object_ptr->velocity(2) = 0;

    Eigen::Vector3f ref_velocity(main_velocity(0), main_velocity(1), 0.0);
    if (ContiRadarUtil::IsConflict(ref_velocity,
                                   object_ptr->velocity.cast<float>())) {
      object_ptr->is_background = true;
    }

    object_ptr->length = 1.0;
    object_ptr->width = 1.0;
    object_ptr->height = 1.0;
    object_ptr->type = ObjectType::UNKNOWN;
    object_ptr->score_type = ScoreType::SCORE_RADAR;
    object_ptr->score =
        static_cast<float>(raw_obstacles.contiobs(i).probexist());

    Eigen::Matrix3d dist_rms;
    Eigen::Matrix3d vel_rms;
    vel_rms.setZero();
    dist_rms.setZero();
    dist_rms(0, 0) = raw_obstacles.contiobs(i).longitude_dist_rms();
    dist_rms(1, 1) = raw_obstacles.contiobs(i).lateral_dist_rms();
    vel_rms(0, 0) = raw_obstacles.contiobs(i).longitude_vel_rms();
    vel_rms(1, 1) = raw_obstacles.contiobs(i).lateral_vel_rms();
    object_ptr->position_uncertainty =
        radar_pose.topLeftCorner(3, 3) * dist_rms * dist_rms.transpose() *
        radar_pose.topLeftCorner(3, 3).transpose();
    object_ptr->velocity_uncertainty =
        radar_pose.topLeftCorner(3, 3) * vel_rms * vel_rms.transpose() *
        radar_pose.topLeftCorner(3, 3).transpose();

    double local_theta =
        raw_obstacles.contiobs(i).oritation_angle() / 180.0 * M_PI;
    Eigen::Vector3f direction =
        Eigen::Vector3f(cos(local_theta), sin(local_theta), 0);
    direction = radar_pose.topLeftCorner(3, 3).cast<float>() * direction;
    object_ptr->direction = direction.cast<double>();
    //  the avg time diff is from manual
    object_ptr->tracking_time = current_con_ids[obstacle_id] * 0.074;
    double theta = std::atan2(direction(1), direction(0));
    object_ptr->theta = theta;
    //  For radar obstacle , the polygon is supposed to have
    //  four mock point: around obstacle center.
    RadarUtil::MockRadarPolygon(point, object_ptr->length, object_ptr->width,
                                theta, &(object_ptr->polygon));
    if (object_ptr->radar_supplement == nullptr) {
      object_ptr->radar_supplement.reset(new RadarSupplement());
    }
    object_ptr->radar_supplement->range = std::sqrt(
        location_r[0] * location_r[0] + location_r[1] * location_r[1]);

    object_ptr->radar_supplement->angle = 0;
    objects->push_back(object_ptr);
  }
  continuous_ids_ = current_con_ids;
}

}  // namespace perception
}  // namespace apollo
<commit_msg>fix perception compile warning<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * 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 "modules/perception/obstacle/radar/modest/object_builder.h"

#include <cmath>

#include "modules/perception/obstacle/radar/modest/conti_radar_util.h"
#include "modules/perception/obstacle/radar/modest/radar_util.h"

namespace apollo {
namespace perception {

bool ObjectBuilder::Build(const ContiRadar &raw_obstacles,
                          const Eigen::Matrix4d &radar_pose,
                          const Eigen::Vector2d &main_velocity,
                          SensorObjects *radar_objects) {
  if (radar_objects == nullptr) {
    AERROR << "radar objects is nullptr.";
    return false;
  }
  std::unordered_map<int, int> current_con_ids;
  auto objects = &(radar_objects->objects);
  for (int i = 0; i < raw_obstacles.contiobs_size(); ++i) {
    ObjectPtr object_ptr = ObjectPtr(new Object());
    const int obstacle_id = raw_obstacles.contiobs(i).obstacle_id();
    auto continuous_id_it = continuous_ids_.find(obstacle_id);
    if (continuous_id_it != continuous_ids_.end()) {
      current_con_ids[obstacle_id] = continuous_id_it->second + 1;
    } else {
      current_con_ids[obstacle_id] = 1;
    }
    if (current_con_ids[obstacle_id] <= delay_frames_) {
      object_ptr->is_background = true;
    }
    int tracking_times = current_con_ids[obstacle_id];
    if (use_fp_filter_ &&
        ContiRadarUtil::IsFp(raw_obstacles.contiobs(i), conti_params_,
                             delay_frames_, tracking_times)) {
      object_ptr->is_background = true;
    }
    object_ptr->track_id = obstacle_id;
    Eigen::Matrix<double, 4, 1> location_r;
    Eigen::Matrix<double, 4, 1> location_w;
    location_r << raw_obstacles.contiobs(i).longitude_dist(),
        raw_obstacles.contiobs(i).lateral_dist(), 0.0, 1.0;
    location_w = radar_pose * location_r;
    Eigen::Vector3d point;
    point = location_w.topLeftCorner(3, 1);
    object_ptr->center = point;
    object_ptr->anchor_point = object_ptr->center;
    Eigen::Matrix<double, 3, 1> velocity_r;
    Eigen::Matrix<double, 3, 1> velocity_w;
    velocity_r << raw_obstacles.contiobs(i).longitude_vel(),
        raw_obstacles.contiobs(i).lateral_vel(), 0.0;
    velocity_w = radar_pose.topLeftCorner(3, 3) * velocity_r;

    //  calculate the absolute velodity
    object_ptr->velocity(0) = velocity_w[0] + main_velocity(0);
    object_ptr->velocity(1) = velocity_w[1] + main_velocity(1);
    object_ptr->velocity(2) = 0;

    Eigen::Vector3f ref_velocity(main_velocity(0), main_velocity(1), 0.0);
    if (ContiRadarUtil::IsConflict(ref_velocity,
                                   object_ptr->velocity.cast<float>())) {
      object_ptr->is_background = true;
    }

    object_ptr->length = 1.0;
    object_ptr->width = 1.0;
    object_ptr->height = 1.0;
    object_ptr->type = ObjectType::UNKNOWN;
    object_ptr->score_type = ScoreType::SCORE_RADAR;
    object_ptr->score =
        static_cast<float>(raw_obstacles.contiobs(i).probexist());

    Eigen::Matrix3d dist_rms;
    Eigen::Matrix3d vel_rms;
    vel_rms.setZero();
    dist_rms.setZero();
    dist_rms(0, 0) = raw_obstacles.contiobs(i).longitude_dist_rms();
    dist_rms(1, 1) = raw_obstacles.contiobs(i).lateral_dist_rms();
    vel_rms(0, 0) = raw_obstacles.contiobs(i).longitude_vel_rms();
    vel_rms(1, 1) = raw_obstacles.contiobs(i).lateral_vel_rms();
    object_ptr->position_uncertainty =
        radar_pose.topLeftCorner(3, 3) * dist_rms * dist_rms.transpose() *
        radar_pose.topLeftCorner(3, 3).transpose();
    object_ptr->velocity_uncertainty =
        radar_pose.topLeftCorner(3, 3) * vel_rms * vel_rms.transpose() *
        radar_pose.topLeftCorner(3, 3).transpose();

    double local_theta =
        raw_obstacles.contiobs(i).oritation_angle() / 180.0 * M_PI;
    Eigen::Vector3f direction =
        Eigen::Vector3f(cos(local_theta), sin(local_theta), 0);
    direction = radar_pose.topLeftCorner(3, 3).cast<float>() * direction;
    object_ptr->direction = direction.cast<double>();
    //  the avg time diff is from manual
    object_ptr->tracking_time = current_con_ids[obstacle_id] * 0.074;
    double theta = std::atan2(direction(1), direction(0));
    object_ptr->theta = theta;
    //  For radar obstacle , the polygon is supposed to have
    //  four mock point: around obstacle center.
    RadarUtil::MockRadarPolygon(point, object_ptr->length, object_ptr->width,
                                theta, &(object_ptr->polygon));
    if (object_ptr->radar_supplement == nullptr) {
      object_ptr->radar_supplement.reset(new RadarSupplement());
    }
    object_ptr->radar_supplement->range = std::sqrt(
        location_r[0] * location_r[0] + location_r[1] * location_r[1]);

    object_ptr->radar_supplement->angle = 0;
    objects->push_back(object_ptr);
  }
  continuous_ids_ = current_con_ids;
  return true;
}

}  // namespace perception
}  // namespace apollo
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2015 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program; if not, write to the Free Software Foundation, Inc., 51  *
* Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "../Node_test.h"
#include <SofaTest/Sofa_test.h>
#include <SceneCreator/SceneCreator.h>
#include <sofa/simulation/common/Visitor.h>
#include <sofa/simulation/graph/DAGNode.h>
#include <sofa/simulation/graph/DAGSimulation.h>

using sofa::simulation::graph::DAGNode;

namespace sofa {

using namespace modeling;
using namespace simulation;

/** Check the traversal of a Directed Acyclic Graph.
 * The traversal order is recorded in a string, and compared with an expected one.
 * @author Francois Faure, Matthieu Nesme @date 2014
 */
struct DAG_test : public Sofa_test<>
{
    DAG_test()
    {
        sofa::simulation::setSimulation(new simulation::graph::DAGSimulation());
    }

    /**
     * The TestVisitor struct records the name of the traversed nodes in a string.
     * The string can be analyzed as a trace of the traversal.
     */
    struct TestVisitor: public sofa::simulation::Visitor
    {

        std::string visited, topdown, bottomup;
        bool tree; // enforce tree traversal
        TreeTraversalRepetition repeat; // repeat callbacks

        TestVisitor()
            : Visitor(sofa::core::ExecParams::defaultInstance() )
            , tree( false )
            , repeat( NO_REPETITION )
        {
            clear();
        }

        void clear()
        {
            visited.clear();
            topdown.clear();
            bottomup.clear();
        }

        Result processNodeTopDown(simulation::Node* node)
        {
            visited += node->getName();
            topdown += node->getName();
            return RESULT_CONTINUE;
        }

        void processNodeBottomUp(simulation::Node* node)
        {
            visited += node->getName();
            bottomup += node->getName();
        }

        bool treeTraversal(TreeTraversalRepetition& r) { r=repeat; return tree; }

    };

    /// utility function testing a scene graph traversals with given expected results
    void traverse_test( Node::SPtr node, std::string treeTraverse, std::string treeTraverseRepeatAll, std::string treeTraverseRepeatOnce, std::string dagTopDown )
    {
        // dagBottumUp must be the exact inverse of dagTopDown
        std::string dagBottomUp(dagTopDown);
        std::reverse(dagBottomUp.begin(), dagBottomUp.end());

        TestVisitor t;

        t.tree = true; // visitor as TREE traversal w/o repetition
        t.execute( node.get() );
        //        cout<<"traverse_simple_tree: visited = " << t.visited << endl;
        if( t.visited != treeTraverse ){
            ADD_FAILURE() << "Dag_test::traverse_test treeTraverse: wrong traversal order, expected "<<treeTraverse<<", got " << t.visited;
        }
        t.clear();
        t.repeat = simulation::Visitor::REPEAT_ALL; // visitor as TREE traversal with repetitions
        t.execute( node.get() );
        //        cout<<"traverse_simple_tree: visited = " << t.visited << endl;
        if( t.visited != treeTraverseRepeatAll ){
            ADD_FAILURE() << "Dag_test::traverse_test treeTraverseRepeatAll: wrong traversal order, expected "<<treeTraverseRepeatAll<<", got " << t.visited;
        }
        t.clear();
        t.repeat = simulation::Visitor::REPEAT_ONCE; // visitor as TREE traversal with first repetition
        t.execute( node.get() );
        //        cout<<"traverse_simple_tree: visited = " << t.visited << endl;
        if( t.visited != treeTraverseRepeatOnce ){
            ADD_FAILURE() << "Dag_test::traverse_test treeTraverseRepeatOnce: wrong traversal order, expected "<<treeTraverseRepeatOnce<<", got " << t.visited;
        }

        t.clear();
        t.tree = false; // visitor as DAG traversal
        t.execute(node.get());
        //        cout<<"traverse_test: visited = " << t.visited << endl;
        if( t.topdown != dagTopDown ){
            ADD_FAILURE() << "Dag_test::traverse_test dagTopDown: wrong traversal order, expected "<<dagTopDown<<", got " << t.topdown;
        }
        if( t.bottomup != dagBottomUp ){
            ADD_FAILURE() << "Dag_test::traverse_test dagBottomUp: wrong traversal order, expected "<<dagBottomUp<<", got " << t.bottomup;
        }

//        sofa::simulation::getSimulation()->print(node.get());
    }

    /**
     * @brief The root and two children:
\f$
\begin{array}{ccc}
 & R & \\
 \diagup & & \diagdown \\
 A & & B
\end{array}
\f$
Expected output: RAABBR
     */
    void traverse_simple_tree()
    {
        Node::SPtr root = clearScene();
        root->setName("R");
        root->createChild("A");
        root->createChild("B");

        traverse_test( root, "RAABBR", "RAABBR", "RAABBR", "RAB" );
    }

    /**
     * @brief Diamond-shaped graph:
\f$
\begin{array}{ccc}
 & R & \\
 \diagup & & \diagdown \\
 A & & B \\
 \diagdown & & \diagup \\
 & C
\end{array}
\f$
Expected output: RABCCBAR
     */
    void traverse_simple_diamond()
    {
        Node::SPtr root = clearScene();
        root->setName("R");
        Node::SPtr A = root->createChild("A");
        Node::SPtr B = root->createChild("B");
        Node::SPtr C = A->createChild("C");
        B->addChild(C);

        traverse_test( root, "RACCABBR", "RACCABCCBR", "RACCABCCBR", "RABC" );
    }

/**
  * @brief More complex graph:

  R__
 / \ |
 A B |
 \ / |
  C  /
  \ /
   D
   |
   E

Expected output: RABCDEEDCBAR
     */
    void traverse_complex()
    {
        Node::SPtr root = clearScene();
        root->setName("R");
        Node::SPtr A = root->createChild("A");
        Node::SPtr B = root->createChild("B");
        Node::SPtr C = A->createChild("C");
        B->addChild(C);
        Node::SPtr D = C->createChild("D");
        root->addChild(D);
        Node::SPtr E = D->createChild("E");

        traverse_test( root, "RACDEEDCABBR", "RACDEEDCABCDEEDCBDEEDR", "RACDEEDCABCCBDDR", "RABCDE" );
    }

/**
  * @brief Even more complex graph:

  R__
 / \ |
 A B C
 \/ \|
  D  E
  |  |
  F  G

Expected output: RABCDEEDCBAR
     */
    void traverse_morecomplex()
    {
        Node::SPtr root = clearScene();
        root->setName("R");
        Node::SPtr A = root->createChild("A");
        Node::SPtr B = root->createChild("B");
        Node::SPtr C = root->createChild("C");
        Node::SPtr D = A->createChild("D");
        B->addChild(D);
        Node::SPtr E = B->createChild("E");
        C->addChild(E);
        Node::SPtr F = D->createChild("F");
        Node::SPtr G = E->createChild("G");

        traverse_test( root, "RADFFDABEGGEBCCR", "RADFFDABDFFDEGGEBCEGGECR", "RADFFDABDDEGGEBCEECR", "RABDFCEG" );
    }

};

TEST_F( DAG_test, traverse )
{
    traverse_simple_tree();
    traverse_simple_diamond();
    traverse_complex();
    traverse_morecomplex();
}

TEST(DAGNodeTest, objectDestruction_singleObject)
{
    Node_test_objectDestruction_singleObject<DAGNode>();
}

TEST(DAGNodeTest, objectDestruction_multipleObjects)
{
    Node_test_objectDestruction_multipleObjects<DAGNode>();
}

TEST(DAGNodeTest, objectDestruction_childNode_singleObject)
{
    Node_test_objectDestruction_childNode_singleObject<DAGNode>();
}

TEST(DAGNodeTest, objectDestruction_childNode_complexChild)
{
    Node_test_objectDestruction_childNode_complexChild<DAGNode>();
}

}// namespace sofa
<commit_msg>adding another (successful) DAG traversal test<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2015 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program; if not, write to the Free Software Foundation, Inc., 51  *
* Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "../Node_test.h"
#include <SofaTest/Sofa_test.h>
#include <SceneCreator/SceneCreator.h>
#include <sofa/simulation/common/Visitor.h>
#include <sofa/simulation/graph/DAGNode.h>
#include <sofa/simulation/graph/DAGSimulation.h>

using sofa::simulation::graph::DAGNode;

namespace sofa {

using namespace modeling;
using namespace simulation;

/** Check the traversal of a Directed Acyclic Graph.
 * The traversal order is recorded in a string, and compared with an expected one.
 * @author Francois Faure, Matthieu Nesme @date 2014
 */
struct DAG_test : public Sofa_test<>
{
    DAG_test()
    {
        sofa::simulation::setSimulation(new simulation::graph::DAGSimulation());
    }

    /**
     * The TestVisitor struct records the name of the traversed nodes in a string.
     * The string can be analyzed as a trace of the traversal.
     */
    struct TestVisitor: public sofa::simulation::Visitor
    {

        std::string visited, topdown, bottomup;
        bool tree; // enforce tree traversal
        TreeTraversalRepetition repeat; // repeat callbacks

        TestVisitor()
            : Visitor(sofa::core::ExecParams::defaultInstance() )
            , tree( false )
            , repeat( NO_REPETITION )
        {
            clear();
        }

        void clear()
        {
            visited.clear();
            topdown.clear();
            bottomup.clear();
        }

        Result processNodeTopDown(simulation::Node* node)
        {
            visited += node->getName();
            topdown += node->getName();
            return RESULT_CONTINUE;
        }

        void processNodeBottomUp(simulation::Node* node)
        {
            visited += node->getName();
            bottomup += node->getName();
        }

        bool treeTraversal(TreeTraversalRepetition& r) { r=repeat; return tree; }

    };

    /// utility function testing a scene graph traversals with given expected results
    void traverse_test( Node::SPtr node, std::string treeTraverse, std::string treeTraverseRepeatAll, std::string treeTraverseRepeatOnce, std::string dagTopDown )
    {
        // dagBottumUp must be the exact inverse of dagTopDown
        std::string dagBottomUp(dagTopDown);
        std::reverse(dagBottomUp.begin(), dagBottomUp.end());

        TestVisitor t;

        t.tree = true; // visitor as TREE traversal w/o repetition
        t.execute( node.get() );
        //        cout<<"traverse_simple_tree: visited = " << t.visited << endl;
        if( t.visited != treeTraverse ){
            ADD_FAILURE() << "Dag_test::traverse_test treeTraverse: wrong traversal order, expected "<<treeTraverse<<", got " << t.visited;
        }
        t.clear();
        t.repeat = simulation::Visitor::REPEAT_ALL; // visitor as TREE traversal with repetitions
        t.execute( node.get() );
        //        cout<<"traverse_simple_tree: visited = " << t.visited << endl;
        if( t.visited != treeTraverseRepeatAll ){
            ADD_FAILURE() << "Dag_test::traverse_test treeTraverseRepeatAll: wrong traversal order, expected "<<treeTraverseRepeatAll<<", got " << t.visited;
        }
        t.clear();
        t.repeat = simulation::Visitor::REPEAT_ONCE; // visitor as TREE traversal with first repetition
        t.execute( node.get() );
        //        cout<<"traverse_simple_tree: visited = " << t.visited << endl;
        if( t.visited != treeTraverseRepeatOnce ){
            ADD_FAILURE() << "Dag_test::traverse_test treeTraverseRepeatOnce: wrong traversal order, expected "<<treeTraverseRepeatOnce<<", got " << t.visited;
        }

        t.clear();
        t.tree = false; // visitor as DAG traversal
        t.execute(node.get());
        //        cout<<"traverse_test: visited = " << t.visited << endl;
        if( t.topdown != dagTopDown ){
            ADD_FAILURE() << "Dag_test::traverse_test dagTopDown: wrong traversal order, expected "<<dagTopDown<<", got " << t.topdown;
        }
        if( t.bottomup != dagBottomUp ){
            ADD_FAILURE() << "Dag_test::traverse_test dagBottomUp: wrong traversal order, expected "<<dagBottomUp<<", got " << t.bottomup;
        }

//        sofa::simulation::getSimulation()->print(node.get());
    }

    /**
     * @brief The root and two children:
\f$
\begin{array}{ccc}
 & R & \\
 \diagup & & \diagdown \\
 A & & B
\end{array}
\f$
Expected output: RAABBR
     */
    void traverse_simple_tree()
    {
        Node::SPtr root = clearScene();
        root->setName("R");
        root->createChild("A");
        root->createChild("B");

        traverse_test( root, "RAABBR", "RAABBR", "RAABBR", "RAB" );
    }

    /**
     * @brief Diamond-shaped graph:
\f$
\begin{array}{ccc}
 & R & \\
 \diagup & & \diagdown \\
 A & & B \\
 \diagdown & & \diagup \\
 & C
\end{array}
\f$
Expected output: RABCCBAR
     */
    void traverse_simple_diamond()
    {
        Node::SPtr root = clearScene();
        root->setName("R");
        Node::SPtr A = root->createChild("A");
        Node::SPtr B = root->createChild("B");
        Node::SPtr C = A->createChild("C");
        B->addChild(C);

        traverse_test( root, "RACCABBR", "RACCABCCBR", "RACCABCCBR", "RABC" );
    }

/**
  * @brief More complex graph:

  R__
 / \ \
 A B |
 \ / |
  C  /
  \ /
   D
   |
   E

Expected output: RABCDEEDCBAR
     */
    void traverse_complex()
    {
        Node::SPtr root = clearScene();
        root->setName("R");
        Node::SPtr A = root->createChild("A");
        Node::SPtr B = root->createChild("B");
        Node::SPtr C = A->createChild("C");
        B->addChild(C);
        Node::SPtr D = C->createChild("D");
        root->addChild(D);
        Node::SPtr E = D->createChild("E");

        traverse_test( root, "RACDEEDCABBR", "RACDEEDCABCDEEDCBDEEDR", "RACDEEDCABCCBDDR", "RABCDE" );
    }

/**
  * @brief Even more complex graph:

  R__
 / \ \
 A B C
 \/ \|
  D  E
  |  |
  F  G

     */
    void traverse_morecomplex()
    {
        Node::SPtr root = clearScene();
        root->setName("R");
        Node::SPtr A = root->createChild("A");
        Node::SPtr B = root->createChild("B");
        Node::SPtr C = root->createChild("C");
        Node::SPtr D = A->createChild("D");
        B->addChild(D);
        Node::SPtr E = B->createChild("E");
        C->addChild(E);
        Node::SPtr F = D->createChild("F");
        Node::SPtr G = E->createChild("G");

        traverse_test( root, "RADFFDABEGGEBCCR", "RADFFDABDFFDEGGEBCEGGECR", "RADFFDABDDEGGEBCEECR", "RABDFCEG" );
    }

/**
  * @brief another complex case

  R______
 / \ \ \ \
 A B C D E
 \/__/_/_/
  F
  |\
  G |
  |/
  H

     */
    void traverse_morecomplex2()
    {
        Node::SPtr root = clearScene();
        root->setName("R");
        Node::SPtr A = root->createChild("A");
        Node::SPtr B = root->createChild("B");
        Node::SPtr C = root->createChild("C");
        Node::SPtr D = root->createChild("D");
        Node::SPtr E = root->createChild("E");
        Node::SPtr F = A->createChild("F");
        B->addChild(F);
        C->addChild(F);
        D->addChild(F);
        E->addChild(F);
        Node::SPtr G = F->createChild("G");
        Node::SPtr H = G->createChild("H");
        F->addChild(H);

        traverse_test( root, "RAFGHHGFABBCCDDEER",
                       "RAFGHHGHHFABFGHHGHHFBCFGHHGHHFCDFGHHGHHFDEFGHHGHHFER",
                       "RAFGHHGHHFABFFBCFFCDFFDEFFER",
                       "RABCDEFGH" );
    }

};

TEST_F( DAG_test, traverse )
{
    traverse_simple_tree();
    traverse_simple_diamond();
    traverse_complex();
    traverse_morecomplex();
    traverse_morecomplex2();
}

TEST(DAGNodeTest, objectDestruction_singleObject)
{
    Node_test_objectDestruction_singleObject<DAGNode>();
}

TEST(DAGNodeTest, objectDestruction_multipleObjects)
{
    Node_test_objectDestruction_multipleObjects<DAGNode>();
}

TEST(DAGNodeTest, objectDestruction_childNode_singleObject)
{
    Node_test_objectDestruction_childNode_singleObject<DAGNode>();
}

TEST(DAGNodeTest, objectDestruction_childNode_complexChild)
{
    Node_test_objectDestruction_childNode_complexChild<DAGNode>();
}

}// namespace sofa
<|endoftext|>


<commit_before>#include "binary.h"
#include "arduino_gpio.hpp"
#include "arduino_clock.hpp"
#include "arduino_spi.hpp"
#include "arduino_serial.hpp"
#include "arduino_wire.hpp"
#include "Print.hpp"

using namespace ::arduino::gpio;
using namespace ::arduino::clock;
using namespace ::arduino::wire;
using namespace ::arduino::serial;
using namespace ::arduino::spi;
using namespace ::arduino::print;

#include <algorithm>
using namespace std;
typedef uint8_t							byte;
#define F(X)							X
#define pgm_read_byte(X)				(*X)
<commit_msg>(ARDUINO) Fix auto using namespace std in arduino frontend.<commit_after>#include "binary.h"
#include "arduino_gpio.hpp"
#include "arduino_clock.hpp"
#include "arduino_spi.hpp"
#include "arduino_serial.hpp"
#include "arduino_wire.hpp"
#include "Print.hpp"

using namespace ::arduino::gpio;
using namespace ::arduino::clock;
using namespace ::arduino::wire;
using namespace ::arduino::serial;
using namespace ::arduino::spi;
using namespace ::arduino::print;

#include <algorithm>
typedef uint8_t							byte;
#define F(X)							X
#define pgm_read_byte(X)				(*X)
<|endoftext|>