text
stringlengths
54
60.6k
<commit_before><commit_msg>Remove dead code<commit_after><|endoftext|>
<commit_before>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/system/remote_command.hpp" #include <caf/scoped_actor.hpp> #include <iostream> #include "vast/detail/narrow.hpp" #include "vast/error.hpp" #include "vast/logger.hpp" #include "vast/system/connect_to_node.hpp" using namespace std::chrono_literals; namespace vast::system { caf::message remote_command(const command::invocation& invocation, caf::actor_system& sys) { VAST_TRACE(invocation); // Get a convenient and blocking way to interact with actors. caf::scoped_actor self{sys}; // Get VAST node. auto node_opt = connect_to_node(self, invocation.options); if (!node_opt) return caf::make_message(std::move(node_opt.error())); auto node = std::move(*node_opt); self->monitor(node); // Delegate invocation to node. caf::error err; self->send(node, std::move(invocation)); self->receive( [&](const caf::down_msg&) { err = ec::remote_node_down; }, [&](caf::ok_atom) { // Standard reply for success. }, [&](caf::actor&) { // "vast spawn" returns an actor. }, [&](const std::string& str) { // Status messages or query results. std::cout << str << std::endl; }, [&](caf::error& e) { err = std::move(e); } ); if (err) return caf::make_message(std::move(err)); return caf::none; } } // namespace vast::system <commit_msg>Allow all remote commands to work with `--node`<commit_after>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/system/remote_command.hpp" #include "vast/detail/narrow.hpp" #include "vast/error.hpp" #include "vast/logger.hpp" #include "vast/scope_linked.hpp" #include "vast/system/spawn_or_connect_to_node.hpp" #include <caf/actor.hpp> #include <caf/scoped_actor.hpp> #include <iostream> using namespace std::chrono_literals; namespace vast::system { caf::message remote_command(const command::invocation& invocation, caf::actor_system& sys) { VAST_TRACE(invocation); // Get a convenient and blocking way to interact with actors. caf::scoped_actor self{sys}; // Get VAST node. auto node_opt = spawn_or_connect_to_node(self, invocation.options, content(sys.config())); if (auto err = caf::get_if<caf::error>(&node_opt)) return caf::make_message(std::move(*err)); auto& node = caf::holds_alternative<caf::actor>(node_opt) ? caf::get<caf::actor>(node_opt) : caf::get<scope_linked_actor>(node_opt).get(); self->monitor(node); // Delegate invocation to node. caf::error err; self->send(node, std::move(invocation)); self->receive( [&](const caf::down_msg&) { err = ec::remote_node_down; }, [&](caf::ok_atom) { // Standard reply for success. }, [&](caf::actor&) { // "vast spawn" returns an actor. }, [&](const std::string& str) { // Status messages or query results. std::cout << str << std::endl; }, [&](caf::error& e) { err = std::move(e); } ); if (err) return caf::make_message(std::move(err)); return caf::none; } } // namespace vast::system <|endoftext|>
<commit_before>#pragma once /* * Copyright (c) 2013 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #ifndef _QI_DETAILS_TRACKABLE_HXX_ #define _QI_DETAILS_TRACKABLE_HXX_ #include <boost/function.hpp> #include <boost/bind.hpp> #include <boost/type_traits/is_base_of.hpp> #include <boost/type_traits/remove_pointer.hpp> #include <boost/weak_ptr.hpp> #include <boost/function_types/result_type.hpp> namespace qi { template<typename T> inline Trackable<T>::Trackable(T* ptr) : _wasDestroyed(false) { _ptr = boost::shared_ptr<T>(ptr, boost::bind(&Trackable::_destroyed, _1)); } template<typename T> inline void Trackable<T>::destroy() { _ptr.reset(); wait(); } template<typename T> inline void Trackable<T>::wait() { boost::mutex::scoped_lock lock(_mutex); while (!_wasDestroyed) { _cond.wait(lock); } } template<typename T> inline void Trackable<T>::_destroyed() { // unblock _wasDestroyed = true; _cond.notify_all(); } template<typename T> inline Trackable<T>::~Trackable() { // We expect destroy() to have been called from parent destructor, so from // this thread. if (!_wasDestroyed) { qiLogError("qi.Trackable") << "Trackable destroyed without calling destroy()"; // do it to mitigate the effect, but it's too late destroy(); } } template<typename T> inline boost::shared_ptr<T> Trackable<T>::lock() { return _ptr; } template<typename T> inline boost::weak_ptr<T> Trackable<T>::weakPtr() { return boost::weak_ptr<T>(_ptr); } namespace detail { // Functor that locks a weak ptr and make a call if successful // Generalize on shared_ptr and weak_ptr types in case we ever have // other types with their semantics template<typename WT, typename ST, typename F> class LockAndCall { public: typedef typename boost::function_types::result_type<F>::type Result; LockAndCall(const WT& arg, boost::function<F> func) : _wptr(arg) , _f(func) {} #define genCall(n, ATYPEDECL, ATYPES, ADECL, AUSE, comma) \ QI_GEN_MAYBE_TEMPLATE_OPEN(comma) \ ATYPEDECL \ QI_GEN_MAYBE_TEMPLATE_CLOSE(comma) \ Result operator()(ADECL) { \ ST s = _wptr.lock(); \ if (s) \ return _f(AUSE); \ else \ return Result(); \ } QI_GEN(genCall) #undef genCall WT _wptr; boost::function<F> _f; }; template<typename T, bool IS_TRACKABLE> struct BindTransform { typedef const T& type; static type transform(const T& arg) { return arg; } template<typename F> static boost::function<F> wrap(const T& arg, boost::function<F> func) { return func; } }; template<typename T> struct BindTransform<boost::weak_ptr<T>, false > { typedef T* type; static T* transform(const boost::weak_ptr<T>& arg) { // Note that we assume that lock if successful always return the same pointer // And that if lock fails once, it will fail forever from that point return arg.lock().get(); } template<typename F> static boost::function<F> wrap(const boost::weak_ptr<T>& arg, boost::function<F> func) { return LockAndCall<boost::weak_ptr<T>, boost::shared_ptr<T>, F>(arg, func); } }; template<typename T> struct BindTransform<T*, true> { typedef T* type; static T* transform(T* const & arg) { // Note that we assume that lock if successful always return the same pointer return arg; } template<typename F> static boost::function<F> wrap(T*const & arg, boost::function<F> func) { return LockAndCall<boost::weak_ptr<T>, boost::shared_ptr<T>, F>(arg->weakPtr(), func); } }; } #ifndef DOXYGEN template<typename RF, typename AF> boost::function<RF> bind(const AF& fun) { return fun; } #define genCall(n, ATYPEDECL, ATYPES, ADECL, AUSE, comma) \ template<typename RF, typename AF, typename ARG0 comma ATYPEDECL> \ boost::function<RF> bind(const AF& fun, const ARG0& arg0 comma ADECL) \ { \ typedef typename detail::BindTransform<ARG0, boost::is_base_of<TrackableBase, typename boost::remove_pointer<ARG0>::type>::value> Transform; \ typename Transform::type transformed = Transform::transform(arg0); \ boost::function<RF> f = boost::bind(fun, transformed comma AUSE); \ return Transform::wrap(arg0, f); \ } QI_GEN(genCall) #undef genCall #endif // DOXYGEN } #endif // _QI_DETAILS_TRACKABLE_HXX_ <commit_msg>Trackable: Fix a race condition (sic).<commit_after>#pragma once /* * Copyright (c) 2013 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #ifndef _QI_DETAILS_TRACKABLE_HXX_ #define _QI_DETAILS_TRACKABLE_HXX_ #include <boost/function.hpp> #include <boost/bind.hpp> #include <boost/type_traits/is_base_of.hpp> #include <boost/type_traits/remove_pointer.hpp> #include <boost/weak_ptr.hpp> #include <boost/function_types/result_type.hpp> namespace qi { template<typename T> inline Trackable<T>::Trackable(T* ptr) : _wasDestroyed(false) { _ptr = boost::shared_ptr<T>(ptr, boost::bind(&Trackable::_destroyed, _1)); } template<typename T> inline void Trackable<T>::destroy() { _ptr.reset(); wait(); } template<typename T> inline void Trackable<T>::wait() { boost::mutex::scoped_lock lock(_mutex); while (!_wasDestroyed) { _cond.wait(lock); } } template<typename T> inline void Trackable<T>::_destroyed() { // unblock boost::mutex::scoped_lock lock(_mutex); _wasDestroyed = true; _cond.notify_all(); } template<typename T> inline Trackable<T>::~Trackable() { // We expect destroy() to have been called from parent destructor, so from // this thread. if (!_wasDestroyed) { qiLogError("qi.Trackable") << "Trackable destroyed without calling destroy()"; // do it to mitigate the effect, but it's too late destroy(); } } template<typename T> inline boost::shared_ptr<T> Trackable<T>::lock() { return _ptr; } template<typename T> inline boost::weak_ptr<T> Trackable<T>::weakPtr() { return boost::weak_ptr<T>(_ptr); } namespace detail { // Functor that locks a weak ptr and make a call if successful // Generalize on shared_ptr and weak_ptr types in case we ever have // other types with their semantics template<typename WT, typename ST, typename F> class LockAndCall { public: typedef typename boost::function_types::result_type<F>::type Result; LockAndCall(const WT& arg, boost::function<F> func) : _wptr(arg) , _f(func) {} #define genCall(n, ATYPEDECL, ATYPES, ADECL, AUSE, comma) \ QI_GEN_MAYBE_TEMPLATE_OPEN(comma) \ ATYPEDECL \ QI_GEN_MAYBE_TEMPLATE_CLOSE(comma) \ Result operator()(ADECL) { \ ST s = _wptr.lock(); \ if (s) \ return _f(AUSE); \ else \ return Result(); \ } QI_GEN(genCall) #undef genCall WT _wptr; boost::function<F> _f; }; template<typename T, bool IS_TRACKABLE> struct BindTransform { typedef const T& type; static type transform(const T& arg) { return arg; } template<typename F> static boost::function<F> wrap(const T& arg, boost::function<F> func) { return func; } }; template<typename T> struct BindTransform<boost::weak_ptr<T>, false > { typedef T* type; static T* transform(const boost::weak_ptr<T>& arg) { // Note that we assume that lock if successful always return the same pointer // And that if lock fails once, it will fail forever from that point return arg.lock().get(); } template<typename F> static boost::function<F> wrap(const boost::weak_ptr<T>& arg, boost::function<F> func) { return LockAndCall<boost::weak_ptr<T>, boost::shared_ptr<T>, F>(arg, func); } }; template<typename T> struct BindTransform<T*, true> { typedef T* type; static T* transform(T* const & arg) { // Note that we assume that lock if successful always return the same pointer return arg; } template<typename F> static boost::function<F> wrap(T*const & arg, boost::function<F> func) { return LockAndCall<boost::weak_ptr<T>, boost::shared_ptr<T>, F>(arg->weakPtr(), func); } }; } #ifndef DOXYGEN template<typename RF, typename AF> boost::function<RF> bind(const AF& fun) { return fun; } #define genCall(n, ATYPEDECL, ATYPES, ADECL, AUSE, comma) \ template<typename RF, typename AF, typename ARG0 comma ATYPEDECL> \ boost::function<RF> bind(const AF& fun, const ARG0& arg0 comma ADECL) \ { \ typedef typename detail::BindTransform<ARG0, boost::is_base_of<TrackableBase, typename boost::remove_pointer<ARG0>::type>::value> Transform; \ typename Transform::type transformed = Transform::transform(arg0); \ boost::function<RF> f = boost::bind(fun, transformed comma AUSE); \ return Transform::wrap(arg0, f); \ } QI_GEN(genCall) #undef genCall #endif // DOXYGEN } #endif // _QI_DETAILS_TRACKABLE_HXX_ <|endoftext|>
<commit_before>#include "wordribbonitem.h" #include "mscalableimage.h" #include <QString> #include <QtCore> #include <QtGui> namespace { static const int FocusZoneMargin = 30; } WordRibbonItem::WordRibbonItem(WordRibbon::ItemStyleMode mode, MWidget* parent): MStylableWidget(parent), label(""), mPositionIndex(-1), isMousePressCancelled(false), highlightEffectEnabled(true), forceMaxWidth(-1), state(NormalState), mode(mode) { if (textPen.color() != style()->fontColor()) { textPen.setColor(style()->fontColor()); } recalculateItemSize(); } WordRibbonItem::~WordRibbonItem() { } void WordRibbonItem::drawBackground(QPainter *painter, const QStyleOptionGraphicsItem *option) const { Q_UNUSED(option); const WordRibbonItemStyle *s = static_cast<const WordRibbonItemStyle *>(style().operator ->()); if (!s->backgroundImage() && !s->backgroundImagePressed() && !s->backgroundImageSelected()) return ; qreal oldOpacity = painter->opacity(); painter->setOpacity(s->backgroundOpacity() * effectiveOpacity()); QSizeF currentSize = size() - QSizeF(s->marginLeft() + s->marginRight(), s->marginTop() + s->marginBottom()); switch (state) { case NormalState: if (s->backgroundImage()) s->backgroundImage()->draw(0.0, 0.0, currentSize.width(), currentSize.height(), painter); break; case SelectedState: if (s->backgroundImageSelected()) s->backgroundImageSelected()->draw(0.0, 0.0, currentSize.width(), currentSize.height(), painter); break; case PressState: if (s->backgroundImagePressed()) s->backgroundImagePressed()->draw(0.0, 0.0, currentSize.width(), currentSize.height(), painter); break; default: break; } painter->setOpacity(oldOpacity); } void WordRibbonItem::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const { if (label.length() == 0) { //No content inside candidate item. MStylableWidget::drawContents(painter, option); return ; } painter->setFont(drawFont); painter->setPen(textPen); if (mode == WordRibbon::RibbonStyleMode) painter->drawText(contentRect, Qt::AlignCenter, label); else painter->drawText(contentRect, Qt::AlignLeft, label); } QSizeF WordRibbonItem::sizeHint(Qt::SizeHint which, const QSizeF & constraint) const { Q_UNUSED(constraint); QSizeF size ; switch (which) { case Qt::MinimumSize: size = minimumSize; break; case Qt::PreferredSize: size = preferredSize; break; case Qt::MaximumSize: if (forceMaxWidth > 0) { size = preferredSize; size.setWidth(forceMaxWidth); } else { size = style()->maximumSize(); } break; default: break; } return size; } void WordRibbonItem::mousePressEvent(QGraphicsSceneMouseEvent * event) { if (!paddingRect.contains(event->pos().toPoint())) { isMousePressCancelled = true; return ; } isMousePressCancelled = false; updateStyleState(PressState); emit mousePressed(); } void WordRibbonItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) { Q_UNUSED(event); if (isMousePressCancelled) return ; else { highlight(); emit mouseReleased(); } } void WordRibbonItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) { if (isMousePressCancelled) return ; if (mode == WordRibbon::DialogStyleMode) { if (!paddingRect.contains(event->pos().toPoint())) { // In "DialogStyleMode", when the touch point has been moved // out of the area of current item, its "Pressed" state should // be cancelled. isMousePressCancelled = true; clearPress(); } } else { QRect moveRect = paddingRect.adjusted(-FocusZoneMargin, -FocusZoneMargin, +FocusZoneMargin, +FocusZoneMargin); if (!moveRect.contains(event->pos().toPoint())) { // In "RibbonStyleMode", even if the touch point is moved out of // the valid touch area of current item, its "Highlighted" state // should be kept. isMousePressCancelled = true; highlight(); } } } void WordRibbonItem::cancelEvent(MCancelEvent *event) { Q_UNUSED(event); isMousePressCancelled = true; clearPress(); } void WordRibbonItem::setText(const QString& str) { label = str; applyStyle(); recalculateItemSize(); update(); updateGeometry(); } void WordRibbonItem::clearText() { setText (""); } QString WordRibbonItem::text() { return label; } void WordRibbonItem::enableHighlight() { highlightEffectEnabled = true; } void WordRibbonItem::disableHighlight() { highlightEffectEnabled = false; } void WordRibbonItem::highlight() { if (!highlightEffectEnabled || highlighted()) { return ; } updateStyleState(SelectedState); } void WordRibbonItem::press() { if (!pressed()) updateStyleState(PressState); } void WordRibbonItem::clearHighlight() { if (highlighted()) updateStyleState(NormalState); } void WordRibbonItem::clearPress() { if (pressed()) updateStyleState(NormalState); } bool WordRibbonItem::highlighted() const { if (!highlightEffectEnabled) { return false; } return state == SelectedState; } bool WordRibbonItem::pressed() const { return state == PressState; } void WordRibbonItem::setPositionIndex(int index) { mPositionIndex = index; } int WordRibbonItem::positionIndex() const { return mPositionIndex; } void WordRibbonItem::applyStyle() { if (mode == WordRibbon::DialogStyleMode) { // In WordRibbon::DialogStyleMode the margins and paddings are depending // on the length of the label switch (label.length()) { case 1: style().setModeDialogstyleoneword(); break; case 2: style().setModeDialogstyletwoword(); break; case 3: style().setModeDialogstylethreeword(); break; default: style().setModeDialogstyleseveralword(); break; } } else { // In WordRibbon::RibbonStyleMode the margins and paddings are depending // on the length of the label switch (label.length()) { case 0: style().setModeDefault(); break; case 1: style().setModeRibbonstyleoneword(); break; default: style().setModeRibbonstyleseveralword(); break; } } } void WordRibbonItem::recalculateItemSize() { int paddingLeft, paddingRight, paddingTop, paddingBottom; int marginLeft, marginRight, marginTop, marginBottom; paddingLeft = style()->paddingLeft(); paddingRight = style()->paddingRight(); paddingTop = style()->paddingTop(); paddingBottom = style()->paddingBottom(); marginLeft = style()->marginLeft(); marginRight = style()->marginRight(); marginTop = style()->marginTop(); marginBottom = style()->marginBottom(); minimumSize = style()->minimumSize(); drawFont = style()->font(); if (label.length() == 0) { preferredSize = minimumSize; } else { // If label has characters, then the size of this widget // need to be update by calculating padding and margin. QFontMetrics fm(drawFont); QSize textSize = fm.size(Qt::TextSingleLine, label); if (mode == WordRibbon::DialogStyleMode) { // In WordRibbon::DialogStyleMode, reduce font size for long label // to fit the item width int maxWidth = forceMaxWidth > 0 ? forceMaxWidth : style()->maximumSize().width(); int currentWidth = textSize.width() + marginLeft + marginRight + paddingLeft + paddingRight; while (currentWidth > maxWidth) { if (drawFont.pixelSize() <= 5) { // too small break; } drawFont.setPixelSize(drawFont.pixelSize() - 1); textSize = fm.size(Qt::TextSingleLine, label); currentWidth = textSize.width() + marginLeft + marginRight + paddingLeft + paddingRight; } } preferredSize.setWidth(textSize.width() + marginLeft + marginRight + paddingLeft + paddingRight); preferredSize.setHeight(textSize.height() + marginTop + marginBottom + paddingTop + paddingBottom); minimumSize = preferredSize; } setMinimumSize(minimumSize); setPreferredSize(preferredSize); QSizeF tmpSize = preferredSize - QSizeF(marginLeft + marginRight, marginTop + marginBottom); paddingRect = QRect(marginLeft, marginTop, tmpSize.width(), tmpSize.height()); tmpSize = tmpSize - QSizeF(paddingLeft + paddingRight, paddingTop + paddingBottom); // ContentRect represents the drawing text area used in drawContents() function. // Don't need to calculate margin area. // Becuase in MWidgetView::paint(), it will call: // painter->translate(horizontalMargin, d->margins.top()); contentRect = QRect(paddingLeft, paddingTop, tmpSize.width(), tmpSize.height()); resize(preferredSize); } void WordRibbonItem::updateStyleState(ItemState newState) { state = newState; switch (state) { case NormalState: textPen.setColor(style()->fontColor()); break; case SelectedState: textPen.setColor(style()->selectedFontColor()); break; case PressState: textPen.setColor(style()->pressedFontColor()); break; default: break; } update(); } void WordRibbonItem::setMaxWidth(int width) { if (width < style()->minimumSize().width()) return; forceMaxWidth = width; } <commit_msg>Changes: Fix a bug that incorrect highlighted state displays in WordRibbonDialog.<commit_after>#include "wordribbonitem.h" #include "mscalableimage.h" #include <QString> #include <QtCore> #include <QtGui> namespace { static const int FocusZoneMargin = 30; } WordRibbonItem::WordRibbonItem(WordRibbon::ItemStyleMode mode, MWidget* parent): MStylableWidget(parent), label(""), mPositionIndex(-1), isMousePressCancelled(false), highlightEffectEnabled(true), forceMaxWidth(-1), state(NormalState), mode(mode) { if (textPen.color() != style()->fontColor()) { textPen.setColor(style()->fontColor()); } recalculateItemSize(); } WordRibbonItem::~WordRibbonItem() { } void WordRibbonItem::drawBackground(QPainter *painter, const QStyleOptionGraphicsItem *option) const { Q_UNUSED(option); const WordRibbonItemStyle *s = static_cast<const WordRibbonItemStyle *>(style().operator ->()); if (!s->backgroundImage() && !s->backgroundImagePressed() && !s->backgroundImageSelected()) return ; qreal oldOpacity = painter->opacity(); painter->setOpacity(s->backgroundOpacity() * effectiveOpacity()); QSizeF currentSize = size() - QSizeF(s->marginLeft() + s->marginRight(), s->marginTop() + s->marginBottom()); switch (state) { case NormalState: if (s->backgroundImage()) s->backgroundImage()->draw(0.0, 0.0, currentSize.width(), currentSize.height(), painter); break; case SelectedState: if (s->backgroundImageSelected()) s->backgroundImageSelected()->draw(0.0, 0.0, currentSize.width(), currentSize.height(), painter); break; case PressState: if (s->backgroundImagePressed()) s->backgroundImagePressed()->draw(0.0, 0.0, currentSize.width(), currentSize.height(), painter); break; default: break; } painter->setOpacity(oldOpacity); } void WordRibbonItem::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const { if (label.length() == 0) { //No content inside candidate item. MStylableWidget::drawContents(painter, option); return ; } painter->setFont(drawFont); painter->setPen(textPen); if (mode == WordRibbon::RibbonStyleMode) painter->drawText(contentRect, Qt::AlignCenter, label); else painter->drawText(contentRect, Qt::AlignLeft, label); } QSizeF WordRibbonItem::sizeHint(Qt::SizeHint which, const QSizeF & constraint) const { Q_UNUSED(constraint); QSizeF size ; switch (which) { case Qt::MinimumSize: size = minimumSize; break; case Qt::PreferredSize: size = preferredSize; break; case Qt::MaximumSize: if (forceMaxWidth > 0) { size = preferredSize; size.setWidth(forceMaxWidth); } else { size = style()->maximumSize(); } break; default: break; } return size; } void WordRibbonItem::mousePressEvent(QGraphicsSceneMouseEvent * event) { if (!paddingRect.contains(event->pos().toPoint())) { isMousePressCancelled = true; return ; } isMousePressCancelled = false; updateStyleState(PressState); emit mousePressed(); } void WordRibbonItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) { Q_UNUSED(event); if (isMousePressCancelled) return ; else { // Only show "highlighted" state for RibbonStyleMode here. if (mode == WordRibbon::RibbonStyleMode) highlight(); emit mouseReleased(); } } void WordRibbonItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) { if (isMousePressCancelled) return ; if (mode == WordRibbon::DialogStyleMode) { if (!paddingRect.contains(event->pos().toPoint())) { // In "DialogStyleMode", when the touch point has been moved // out of the area of current item, its "Pressed" state should // be cancelled. isMousePressCancelled = true; clearPress(); } } else { QRect moveRect = paddingRect.adjusted(-FocusZoneMargin, -FocusZoneMargin, +FocusZoneMargin, +FocusZoneMargin); if (!moveRect.contains(event->pos().toPoint())) { // In "RibbonStyleMode", even if the touch point is moved out of // the valid touch area of current item, its "Highlighted" state // should be kept. isMousePressCancelled = true; highlight(); } } } void WordRibbonItem::cancelEvent(MCancelEvent *event) { Q_UNUSED(event); isMousePressCancelled = true; clearPress(); } void WordRibbonItem::setText(const QString& str) { label = str; applyStyle(); recalculateItemSize(); update(); updateGeometry(); } void WordRibbonItem::clearText() { setText (""); } QString WordRibbonItem::text() { return label; } void WordRibbonItem::enableHighlight() { highlightEffectEnabled = true; } void WordRibbonItem::disableHighlight() { highlightEffectEnabled = false; } void WordRibbonItem::highlight() { if (!highlightEffectEnabled || highlighted()) { return ; } updateStyleState(SelectedState); } void WordRibbonItem::press() { if (!pressed()) updateStyleState(PressState); } void WordRibbonItem::clearHighlight() { if (highlighted()) updateStyleState(NormalState); } void WordRibbonItem::clearPress() { if (pressed()) updateStyleState(NormalState); } bool WordRibbonItem::highlighted() const { if (!highlightEffectEnabled) { return false; } return state == SelectedState; } bool WordRibbonItem::pressed() const { return state == PressState; } void WordRibbonItem::setPositionIndex(int index) { mPositionIndex = index; } int WordRibbonItem::positionIndex() const { return mPositionIndex; } void WordRibbonItem::applyStyle() { if (mode == WordRibbon::DialogStyleMode) { // In WordRibbon::DialogStyleMode the margins and paddings are depending // on the length of the label switch (label.length()) { case 1: style().setModeDialogstyleoneword(); break; case 2: style().setModeDialogstyletwoword(); break; case 3: style().setModeDialogstylethreeword(); break; default: style().setModeDialogstyleseveralword(); break; } } else { // In WordRibbon::RibbonStyleMode the margins and paddings are depending // on the length of the label switch (label.length()) { case 0: style().setModeDefault(); break; case 1: style().setModeRibbonstyleoneword(); break; default: style().setModeRibbonstyleseveralword(); break; } } } void WordRibbonItem::recalculateItemSize() { int paddingLeft, paddingRight, paddingTop, paddingBottom; int marginLeft, marginRight, marginTop, marginBottom; paddingLeft = style()->paddingLeft(); paddingRight = style()->paddingRight(); paddingTop = style()->paddingTop(); paddingBottom = style()->paddingBottom(); marginLeft = style()->marginLeft(); marginRight = style()->marginRight(); marginTop = style()->marginTop(); marginBottom = style()->marginBottom(); minimumSize = style()->minimumSize(); drawFont = style()->font(); if (label.length() == 0) { preferredSize = minimumSize; } else { // If label has characters, then the size of this widget // need to be update by calculating padding and margin. QFontMetrics fm(drawFont); QSize textSize = fm.size(Qt::TextSingleLine, label); if (mode == WordRibbon::DialogStyleMode) { // In WordRibbon::DialogStyleMode, reduce font size for long label // to fit the item width int maxWidth = forceMaxWidth > 0 ? forceMaxWidth : style()->maximumSize().width(); int currentWidth = textSize.width() + marginLeft + marginRight + paddingLeft + paddingRight; while (currentWidth > maxWidth) { if (drawFont.pixelSize() <= 5) { // too small break; } drawFont.setPixelSize(drawFont.pixelSize() - 1); textSize = fm.size(Qt::TextSingleLine, label); currentWidth = textSize.width() + marginLeft + marginRight + paddingLeft + paddingRight; } } preferredSize.setWidth(textSize.width() + marginLeft + marginRight + paddingLeft + paddingRight); preferredSize.setHeight(textSize.height() + marginTop + marginBottom + paddingTop + paddingBottom); minimumSize = preferredSize; } setMinimumSize(minimumSize); setPreferredSize(preferredSize); QSizeF tmpSize = preferredSize - QSizeF(marginLeft + marginRight, marginTop + marginBottom); paddingRect = QRect(marginLeft, marginTop, tmpSize.width(), tmpSize.height()); tmpSize = tmpSize - QSizeF(paddingLeft + paddingRight, paddingTop + paddingBottom); // ContentRect represents the drawing text area used in drawContents() function. // Don't need to calculate margin area. // Becuase in MWidgetView::paint(), it will call: // painter->translate(horizontalMargin, d->margins.top()); contentRect = QRect(paddingLeft, paddingTop, tmpSize.width(), tmpSize.height()); resize(preferredSize); } void WordRibbonItem::updateStyleState(ItemState newState) { state = newState; switch (state) { case NormalState: textPen.setColor(style()->fontColor()); break; case SelectedState: textPen.setColor(style()->selectedFontColor()); break; case PressState: textPen.setColor(style()->pressedFontColor()); break; default: break; } update(); } void WordRibbonItem::setMaxWidth(int width) { if (width < style()->minimumSize().width()) return; forceMaxWidth = width; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/application/browser/application_protocols.h" #include <algorithm> #include <map> #include <list> #include <string> #include <utility> #include <vector> #include "base/files/file_path.h" #include "base/memory/weak_ptr.h" #include "base/numerics/safe_math.h" #include "base/strings/stringprintf.h" #include "base/strings/string_util.h" #include "base/threading/thread_restrictions.h" #include "base/threading/worker_pool.h" #include "base/threading/sequenced_worker_pool.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/resource_request_info.h" #include "url/url_util.h" #include "net/base/net_errors.h" #include "net/http/http_response_headers.h" #include "net/http/http_response_info.h" #include "net/url_request/url_request_error_job.h" #include "net/url_request/url_request_file_job.h" #include "net/url_request/url_request_simple_job.h" #include "xwalk/application/browser/application_service.h" #include "xwalk/application/common/application_data.h" #include "xwalk/application/common/application_file_util.h" #include "xwalk/application/common/application_manifest_constants.h" #include "xwalk/application/common/application_resource.h" #include "xwalk/application/common/constants.h" #include "xwalk/application/common/manifest_handlers/csp_handler.h" #include "xwalk/runtime/common/xwalk_system_locale.h" using content::BrowserThread; using content::ResourceRequestInfo; namespace xwalk { namespace keys = application_manifest_keys; namespace application { namespace { net::HttpResponseHeaders* BuildHttpHeaders( const std::string& content_security_policy, const std::string& mime_type, const std::string& method, const base::FilePath& file_path, const base::FilePath& relative_path, bool is_authority_match) { std::string raw_headers; if (method == "GET") { if (relative_path.empty()) raw_headers.append("HTTP/1.1 400 Bad Request"); else if (!is_authority_match) raw_headers.append("HTTP/1.1 403 Forbidden"); else if (file_path.empty()) raw_headers.append("HTTP/1.1 404 Not Found"); else raw_headers.append("HTTP/1.1 200 OK"); } else { raw_headers.append("HTTP/1.1 501 Not Implemented"); } if (!content_security_policy.empty()) { raw_headers.append(1, '\0'); raw_headers.append("Content-Security-Policy: "); raw_headers.append(content_security_policy); } raw_headers.append(1, '\0'); raw_headers.append("Access-Control-Allow-Origin: *"); if (!mime_type.empty()) { raw_headers.append(1, '\0'); raw_headers.append("Content-Type: "); raw_headers.append(mime_type); } raw_headers.append(2, '\0'); return new net::HttpResponseHeaders(raw_headers); } void ReadResourceFilePath( const ApplicationResource& resource, base::FilePath* file_path) { *file_path = resource.GetFilePath(); } class URLRequestApplicationJob : public net::URLRequestFileJob { public: URLRequestApplicationJob( net::URLRequest* request, net::NetworkDelegate* network_delegate, const scoped_refptr<base::TaskRunner>& file_task_runner, const std::string& application_id, const base::FilePath& directory_path, const base::FilePath& relative_path, const std::string& content_security_policy, const std::list<std::string>& locales, bool is_authority_match) : net::URLRequestFileJob( request, network_delegate, base::FilePath(), file_task_runner), content_security_policy_(content_security_policy), locales_(locales), resource_(application_id, directory_path, relative_path), relative_path_(relative_path), is_authority_match_(is_authority_match), weak_factory_(this) { } void GetResponseInfo(net::HttpResponseInfo* info) override { std::string mime_type; GetMimeType(&mime_type); std::string method = request()->method(); response_info_.headers = BuildHttpHeaders( content_security_policy_, mime_type, method, file_path_, relative_path_, is_authority_match_); *info = response_info_; } void Start() override { base::FilePath* read_file_path = new base::FilePath; resource_.SetLocales(locales_); bool posted = base::WorkerPool::PostTaskAndReply( FROM_HERE, base::Bind(&ReadResourceFilePath, resource_, base::Unretained(read_file_path)), base::Bind(&URLRequestApplicationJob::OnFilePathRead, weak_factory_.GetWeakPtr(), base::Owned(read_file_path)), true /* task is slow */); DCHECK(posted); } protected: ~URLRequestApplicationJob() override {} std::string content_security_policy_; std::list<std::string> locales_; ApplicationResource resource_; base::FilePath relative_path_; private: void OnFilePathRead(base::FilePath* read_file_path) { file_path_ = *read_file_path; if (file_path_.empty()) NotifyHeadersComplete(); else URLRequestFileJob::Start(); } net::HttpResponseInfo response_info_; bool is_authority_match_; base::WeakPtrFactory<URLRequestApplicationJob> weak_factory_; }; // This class is a thread-safe cache of active application's data. // This class is used by ApplicationProtocolHandler which lives on // IO thread and hence cannot access ApplicationService directly. class ApplicationDataCache : public ApplicationService::Observer { public: scoped_refptr<ApplicationData> GetApplicationData( const std::string& application_id) const { base::AutoLock lock(lock_); ApplicationData::ApplicationDataMap::const_iterator it = cache_.find(application_id); if (it != cache_.end()) { return it->second; } return NULL; } static void CreateIfNeeded(ApplicationService* service) { DCHECK(service); DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (s_instance_) return; // The cache lives longer than ApplicationService, // so we do not need to remove cache_ from ApplicationService // observers list. s_instance_ = new ApplicationDataCache(); service->AddObserver(s_instance_); } static ApplicationDataCache* Get() { return s_instance_;} private: void DidLaunchApplication(Application* app) override { base::AutoLock lock(lock_); cache_.insert(std::pair<std::string, scoped_refptr<ApplicationData> >( app->id(), app->data())); } void WillDestroyApplication(Application* app) override { base::AutoLock lock(lock_); cache_.erase(app->id()); } ApplicationDataCache() = default; // The life time of the cache instance is equal to the process life time, // it is not supposed to be explicitly destroyed. ~ApplicationDataCache() override = default; ApplicationData::ApplicationDataMap cache_; mutable base::Lock lock_; static ApplicationDataCache* s_instance_; }; ApplicationDataCache* ApplicationDataCache::s_instance_; class ApplicationProtocolHandler : public net::URLRequestJobFactory::ProtocolHandler { public: explicit ApplicationProtocolHandler(ApplicationService* service) { ApplicationDataCache::CreateIfNeeded(service); } ~ApplicationProtocolHandler() override {} net::URLRequestJob* MaybeCreateJob( net::URLRequest* request, net::NetworkDelegate* network_delegate) const override; private: DISALLOW_COPY_AND_ASSIGN(ApplicationProtocolHandler); }; // The |locale| should be expanded to user agent locale. // Such as, "en-us" will be expaned as "en-us, en". void GetUserAgentLocales(const std::string& sys_locale, std::list<std::string>& ua_locales) { // NOLINT if (sys_locale.empty()) return; std::string locale = base::ToLowerASCII(sys_locale); size_t position; do { ua_locales.push_back(locale); position = locale.find_last_of("-"); locale = locale.substr(0, position); } while (position != std::string::npos); } net::URLRequestJob* ApplicationProtocolHandler::MaybeCreateJob( net::URLRequest* request, net::NetworkDelegate* network_delegate) const { const std::string& application_id = request->url().host(); scoped_refptr<ApplicationData> application = ApplicationDataCache::Get()->GetApplicationData(application_id); if (!application.get()) return new net::URLRequestErrorJob( request, network_delegate, net::ERR_FILE_NOT_FOUND); base::FilePath relative_path = ApplicationURLToRelativeFilePath(request->url()); base::FilePath directory_path; std::string content_security_policy; if (application.get()) { directory_path = application->path(); const char* csp_key = GetCSPKey(application->manifest_type()); const CSPInfo* csp_info = static_cast<CSPInfo*>( application->GetManifestData(csp_key)); if (csp_info) { const std::map<std::string, std::vector<std::string> >& policies = csp_info->GetDirectives(); std::map<std::string, std::vector<std::string> >::const_iterator it = policies.begin(); for (; it != policies.end(); ++it) { content_security_policy.append( it->first + ' ' + base::JoinString(it->second, ",") + ';'); } } } std::list<std::string> locales; if (application.get() && application->manifest_type() == Manifest::TYPE_WIDGET) { GetUserAgentLocales(GetSystemLocale(), locales); GetUserAgentLocales(application->GetManifest()->default_locale(), locales); } return new URLRequestApplicationJob( request, network_delegate, content::BrowserThread::GetBlockingPool()-> GetTaskRunnerWithShutdownBehavior( base::SequencedWorkerPool::SKIP_ON_SHUTDOWN), application_id, directory_path, relative_path, content_security_policy, locales, application.get()); } } // namespace linked_ptr<net::URLRequestJobFactory::ProtocolHandler> CreateApplicationProtocolHandler(ApplicationService* service) { return linked_ptr<net::URLRequestJobFactory::ProtocolHandler>( new ApplicationProtocolHandler(service)); } } // namespace application } // namespace xwalk <commit_msg>[Windows][Linux]Fix CSP HTTP request syntax<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/application/browser/application_protocols.h" #include <algorithm> #include <map> #include <list> #include <string> #include <utility> #include <vector> #include "base/files/file_path.h" #include "base/memory/weak_ptr.h" #include "base/numerics/safe_math.h" #include "base/strings/stringprintf.h" #include "base/strings/string_util.h" #include "base/threading/thread_restrictions.h" #include "base/threading/worker_pool.h" #include "base/threading/sequenced_worker_pool.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/resource_request_info.h" #include "url/url_util.h" #include "net/base/net_errors.h" #include "net/http/http_response_headers.h" #include "net/http/http_response_info.h" #include "net/url_request/url_request_error_job.h" #include "net/url_request/url_request_file_job.h" #include "net/url_request/url_request_simple_job.h" #include "xwalk/application/browser/application_service.h" #include "xwalk/application/common/application_data.h" #include "xwalk/application/common/application_file_util.h" #include "xwalk/application/common/application_manifest_constants.h" #include "xwalk/application/common/application_resource.h" #include "xwalk/application/common/constants.h" #include "xwalk/application/common/manifest_handlers/csp_handler.h" #include "xwalk/runtime/common/xwalk_system_locale.h" using content::BrowserThread; using content::ResourceRequestInfo; namespace xwalk { namespace keys = application_manifest_keys; namespace application { namespace { net::HttpResponseHeaders* BuildHttpHeaders( const std::string& content_security_policy, const std::string& mime_type, const std::string& method, const base::FilePath& file_path, const base::FilePath& relative_path, bool is_authority_match) { std::string raw_headers; if (method == "GET") { if (relative_path.empty()) raw_headers.append("HTTP/1.1 400 Bad Request"); else if (!is_authority_match) raw_headers.append("HTTP/1.1 403 Forbidden"); else if (file_path.empty()) raw_headers.append("HTTP/1.1 404 Not Found"); else raw_headers.append("HTTP/1.1 200 OK"); } else { raw_headers.append("HTTP/1.1 501 Not Implemented"); } if (!content_security_policy.empty()) { raw_headers.append(1, '\0'); raw_headers.append("Content-Security-Policy: "); raw_headers.append(content_security_policy); } raw_headers.append(1, '\0'); raw_headers.append("Access-Control-Allow-Origin: *"); if (!mime_type.empty()) { raw_headers.append(1, '\0'); raw_headers.append("Content-Type: "); raw_headers.append(mime_type); } raw_headers.append(2, '\0'); return new net::HttpResponseHeaders(raw_headers); } void ReadResourceFilePath( const ApplicationResource& resource, base::FilePath* file_path) { *file_path = resource.GetFilePath(); } class URLRequestApplicationJob : public net::URLRequestFileJob { public: URLRequestApplicationJob( net::URLRequest* request, net::NetworkDelegate* network_delegate, const scoped_refptr<base::TaskRunner>& file_task_runner, const std::string& application_id, const base::FilePath& directory_path, const base::FilePath& relative_path, const std::string& content_security_policy, const std::list<std::string>& locales, bool is_authority_match) : net::URLRequestFileJob( request, network_delegate, base::FilePath(), file_task_runner), content_security_policy_(content_security_policy), locales_(locales), resource_(application_id, directory_path, relative_path), relative_path_(relative_path), is_authority_match_(is_authority_match), weak_factory_(this) { } void GetResponseInfo(net::HttpResponseInfo* info) override { std::string mime_type; GetMimeType(&mime_type); std::string method = request()->method(); response_info_.headers = BuildHttpHeaders( content_security_policy_, mime_type, method, file_path_, relative_path_, is_authority_match_); *info = response_info_; } void Start() override { base::FilePath* read_file_path = new base::FilePath; resource_.SetLocales(locales_); bool posted = base::WorkerPool::PostTaskAndReply( FROM_HERE, base::Bind(&ReadResourceFilePath, resource_, base::Unretained(read_file_path)), base::Bind(&URLRequestApplicationJob::OnFilePathRead, weak_factory_.GetWeakPtr(), base::Owned(read_file_path)), true /* task is slow */); DCHECK(posted); } protected: ~URLRequestApplicationJob() override {} std::string content_security_policy_; std::list<std::string> locales_; ApplicationResource resource_; base::FilePath relative_path_; private: void OnFilePathRead(base::FilePath* read_file_path) { file_path_ = *read_file_path; if (file_path_.empty()) NotifyHeadersComplete(); else URLRequestFileJob::Start(); } net::HttpResponseInfo response_info_; bool is_authority_match_; base::WeakPtrFactory<URLRequestApplicationJob> weak_factory_; }; // This class is a thread-safe cache of active application's data. // This class is used by ApplicationProtocolHandler which lives on // IO thread and hence cannot access ApplicationService directly. class ApplicationDataCache : public ApplicationService::Observer { public: scoped_refptr<ApplicationData> GetApplicationData( const std::string& application_id) const { base::AutoLock lock(lock_); ApplicationData::ApplicationDataMap::const_iterator it = cache_.find(application_id); if (it != cache_.end()) { return it->second; } return NULL; } static void CreateIfNeeded(ApplicationService* service) { DCHECK(service); DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (s_instance_) return; // The cache lives longer than ApplicationService, // so we do not need to remove cache_ from ApplicationService // observers list. s_instance_ = new ApplicationDataCache(); service->AddObserver(s_instance_); } static ApplicationDataCache* Get() { return s_instance_;} private: void DidLaunchApplication(Application* app) override { base::AutoLock lock(lock_); cache_.insert(std::pair<std::string, scoped_refptr<ApplicationData> >( app->id(), app->data())); } void WillDestroyApplication(Application* app) override { base::AutoLock lock(lock_); cache_.erase(app->id()); } ApplicationDataCache() = default; // The life time of the cache instance is equal to the process life time, // it is not supposed to be explicitly destroyed. ~ApplicationDataCache() override = default; ApplicationData::ApplicationDataMap cache_; mutable base::Lock lock_; static ApplicationDataCache* s_instance_; }; ApplicationDataCache* ApplicationDataCache::s_instance_; class ApplicationProtocolHandler : public net::URLRequestJobFactory::ProtocolHandler { public: explicit ApplicationProtocolHandler(ApplicationService* service) { ApplicationDataCache::CreateIfNeeded(service); } ~ApplicationProtocolHandler() override {} net::URLRequestJob* MaybeCreateJob( net::URLRequest* request, net::NetworkDelegate* network_delegate) const override; private: DISALLOW_COPY_AND_ASSIGN(ApplicationProtocolHandler); }; // The |locale| should be expanded to user agent locale. // Such as, "en-us" will be expaned as "en-us, en". void GetUserAgentLocales(const std::string& sys_locale, std::list<std::string>& ua_locales) { // NOLINT if (sys_locale.empty()) return; std::string locale = base::ToLowerASCII(sys_locale); size_t position; do { ua_locales.push_back(locale); position = locale.find_last_of("-"); locale = locale.substr(0, position); } while (position != std::string::npos); } namespace { const char kSpace[] = " "; const char kSemicolon[] = ";"; } // namespace net::URLRequestJob* ApplicationProtocolHandler::MaybeCreateJob( net::URLRequest* request, net::NetworkDelegate* network_delegate) const { const std::string& application_id = request->url().host(); scoped_refptr<ApplicationData> application = ApplicationDataCache::Get()->GetApplicationData(application_id); if (!application.get()) return new net::URLRequestErrorJob( request, network_delegate, net::ERR_FILE_NOT_FOUND); base::FilePath relative_path = ApplicationURLToRelativeFilePath(request->url()); base::FilePath directory_path; std::string content_security_policy; if (application.get()) { directory_path = application->path(); const char* csp_key = GetCSPKey(application->manifest_type()); const CSPInfo* csp_info = static_cast<CSPInfo*>( application->GetManifestData(csp_key)); if (csp_info) { for (auto& directive : csp_info->GetDirectives()) { content_security_policy.append(directive.first) .append(kSpace) .append(base::JoinString(directive.second, kSpace)) .append(kSemicolon); } } } std::list<std::string> locales; if (application.get() && application->manifest_type() == Manifest::TYPE_WIDGET) { GetUserAgentLocales(GetSystemLocale(), locales); GetUserAgentLocales(application->GetManifest()->default_locale(), locales); } return new URLRequestApplicationJob( request, network_delegate, content::BrowserThread::GetBlockingPool()-> GetTaskRunnerWithShutdownBehavior( base::SequencedWorkerPool::SKIP_ON_SHUTDOWN), application_id, directory_path, relative_path, content_security_policy, locales, application.get()); } } // namespace linked_ptr<net::URLRequestJobFactory::ProtocolHandler> CreateApplicationProtocolHandler(ApplicationService* service) { return linked_ptr<net::URLRequestJobFactory::ProtocolHandler>( new ApplicationProtocolHandler(service)); } } // namespace application } // namespace xwalk <|endoftext|>
<commit_before>/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 "common/common.h" #include "nordic_common.h" #include "btle.h" #include "btle_clock.h" #include "ble_flash.h" #include "ble_conn_params.h" #include "btle_gap.h" #include "custom/custom_helper.h" #include "ble/GapEvents.h" #include "nRF5xn.h" #ifdef S110 #define IS_LEGACY_DEVICE_MANAGER_ENABLED 1 #elif defined(S130) || defined(S132) #define IS_LEGACY_DEVICE_MANAGER_ENABLED 0 #endif extern "C" { #if (IS_LEGACY_DEVICE_MANAGER_ENABLED) #include "pstorage.h" #else #include "fstorage.h" #include "fds.h" #include "ble_conn_state.h" #endif #include "softdevice_handler.h" #include "ble_stack_handler_types.h" } #include "nrf_ble_hci.h" #include "nRF5XPalGattClient.h" #include "nRF5XPalSecurityManager.h" bool isEventsSignaled = false; extern "C" void assert_nrf_callback(uint16_t line_num, const uint8_t *p_file_name); void app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t *p_file_name); extern "C" void SD_EVT_IRQHandler(void); // export the softdevice event handler for registration by nvic-set-vector. static void btle_handler(ble_evt_t *p_ble_evt); static void sys_evt_dispatch(uint32_t sys_evt) { #if (IS_LEGACY_DEVICE_MANAGER_ENABLED) pstorage_sys_event_handler(sys_evt); #else // Forward Softdevice events to the fstorage module fs_sys_event_handler(sys_evt); #endif } /** * This function is called in interrupt context to handle BLE events; i.e. pull * system and user events out of the pending events-queue of the BLE stack. The * BLE stack signals the availability of events by the triggering the SWI2 * interrupt, which forwards the handling to this function. * * The event processing loop is implemented in intern_softdevice_events_execute(). * * This function will signal to the user code by calling signalEventsToProcess * that their is events to process and BLE::processEvents should be called. */ static uint32_t signalEvent() { if(isEventsSignaled == false) { isEventsSignaled = true; nRF5xn::Instance(BLE::DEFAULT_INSTANCE).signalEventsToProcess(BLE::DEFAULT_INSTANCE); } return NRF_SUCCESS; } error_t btle_init(void) { nrf_clock_lf_cfg_t clockConfiguration; // register softdevice handler vector NVIC_SetVector(SD_EVT_IRQn, (uint32_t) SD_EVT_IRQHandler); // Configure the LF clock according to values provided by btle_clock.h. // It is input from the chain of the yotta configuration system. clockConfiguration.source = LFCLK_CONF_SOURCE; clockConfiguration.xtal_accuracy = LFCLK_CONF_ACCURACY; clockConfiguration.rc_ctiv = LFCLK_CONF_RC_CTIV; clockConfiguration.rc_temp_ctiv = LFCLK_CONF_RC_TEMP_CTIV; SOFTDEVICE_HANDLER_INIT(&clockConfiguration, signalEvent); // Enable BLE stack /** * Using this call, the application can select whether to include the * Service Changed characteristic in the GATT Server. The default in all * previous releases has been to include the Service Changed characteristic, * but this affects how GATT clients behave. Specifically, it requires * clients to subscribe to this attribute and not to cache attribute handles * between connections unless the devices are bonded. If the application * does not need to change the structure of the GATT server attributes at * runtime this adds unnecessary complexity to the interaction with peer * clients. If the SoftDevice is enabled with the Service Changed * Characteristics turned off, then clients are allowed to cache attribute * handles making applications simpler on both sides. */ static const bool IS_SRVC_CHANGED_CHARACT_PRESENT = true; ble_enable_params_t ble_enable_params; uint32_t err_code = softdevice_enable_get_default_config(CENTRAL_LINK_COUNT, PERIPHERAL_LINK_COUNT, &ble_enable_params); ble_enable_params.gatts_enable_params.attr_tab_size = GATTS_ATTR_TAB_SIZE; ble_enable_params.gatts_enable_params.service_changed = IS_SRVC_CHANGED_CHARACT_PRESENT; ble_enable_params.common_enable_params.vs_uuid_count = UUID_TABLE_MAX_ENTRIES; if(err_code != NRF_SUCCESS) { return ERROR_INVALID_PARAM; } if (softdevice_enable(&ble_enable_params) != NRF_SUCCESS) { return ERROR_INVALID_PARAM; } #if (NRF_SD_BLE_API_VERSION <= 2) ble_gap_addr_t addr; if (sd_ble_gap_address_get(&addr) != NRF_SUCCESS) { return ERROR_INVALID_PARAM; } if (sd_ble_gap_address_set(BLE_GAP_ADDR_CYCLE_MODE_NONE, &addr) != NRF_SUCCESS) { return ERROR_INVALID_PARAM; } #else #endif ASSERT_STATUS( softdevice_ble_evt_handler_set(btle_handler)); ASSERT_STATUS( softdevice_sys_evt_handler_set(sys_evt_dispatch)); return btle_gap_init(); } static void btle_handler(ble_evt_t *p_ble_evt) { using ble::pal::vendor::nordic::nRF5XGattClient; using ble::pal::vendor::nordic::nRF5xSecurityManager; /* Library service handlers */ #if SDK_CONN_PARAMS_MODULE_ENABLE ble_conn_params_on_ble_evt(p_ble_evt); #endif #if (IS_LEGACY_DEVICE_MANAGER_ENABLED) #else // Forward BLE events to the Connection State module. // This must be called before any event handler that uses this module. ble_conn_state_on_ble_evt(p_ble_evt); #endif #if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110) nRF5XGattClient::handle_events(p_ble_evt); #endif nRF5xn &ble = nRF5xn::Instance(BLE::DEFAULT_INSTANCE); nRF5xGap &gap = (nRF5xGap &) ble.getGap(); nRF5xGattServer &gattServer = (nRF5xGattServer &) ble.getGattServer(); nRF5xSecurityManager &securityManager = (nRF5xSecurityManager &) ble.getSecurityManager(); /* Custom event handler */ switch (p_ble_evt->header.evt_id) { case BLE_GAP_EVT_CONNECTED: { Gap::Handle_t handle = p_ble_evt->evt.gap_evt.conn_handle; #if defined(TARGET_MCU_NRF51_16K_S110) || defined(TARGET_MCU_NRF51_32K_S110) /* Only peripheral role is supported by S110 */ Gap::Role_t role = Gap::PERIPHERAL; #else Gap::Role_t role = static_cast<Gap::Role_t>(p_ble_evt->evt.gap_evt.params.connected.role); #endif gap.setConnectionHandle(handle); const Gap::ConnectionParams_t *params = reinterpret_cast<Gap::ConnectionParams_t *>(&(p_ble_evt->evt.gap_evt.params.connected.conn_params)); const ble_gap_addr_t *peer = &p_ble_evt->evt.gap_evt.params.connected.peer_addr; #if (NRF_SD_BLE_API_VERSION <= 2) const ble_gap_addr_t *own = &p_ble_evt->evt.gap_evt.params.connected.own_addr; gap.processConnectionEvent(handle, role, static_cast<BLEProtocol::AddressType_t>(peer->addr_type), peer->addr, static_cast<BLEProtocol::AddressType_t>(own->addr_type), own->addr, params); #else Gap::AddressType_t addr_type; Gap::Address_t own_address; gap.getAddress(&addr_type, own_address); gap.processConnectionEvent(handle, role, static_cast<BLEProtocol::AddressType_t>(peer->addr_type), peer->addr, addr_type, own_address, params); #endif break; } case BLE_GAP_EVT_DISCONNECTED: { Gap::Handle_t handle = p_ble_evt->evt.gap_evt.conn_handle; // Since we are not in a connection and have not started advertising, // store bonds gap.setConnectionHandle (BLE_CONN_HANDLE_INVALID); Gap::DisconnectionReason_t reason; switch (p_ble_evt->evt.gap_evt.params.disconnected.reason) { case BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION: reason = Gap::LOCAL_HOST_TERMINATED_CONNECTION; break; case BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION: reason = Gap::REMOTE_USER_TERMINATED_CONNECTION; break; case BLE_HCI_CONN_INTERVAL_UNACCEPTABLE: reason = Gap::CONN_INTERVAL_UNACCEPTABLE; break; default: /* Please refer to the underlying transport library for an * interpretion of this reason's value. */ reason = static_cast<Gap::DisconnectionReason_t>(p_ble_evt->evt.gap_evt.params.disconnected.reason); break; } #if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110) // Close all pending discoveries for this connection nRF5XGattClient::handle_connection_termination(handle); #endif gap.processDisconnectionEvent(handle, reason); break; } case BLE_GAP_EVT_TIMEOUT: gap.processTimeoutEvent(static_cast<Gap::TimeoutSource_t>(p_ble_evt->evt.gap_evt.params.timeout.src)); break; case BLE_GATTC_EVT_TIMEOUT: case BLE_GATTS_EVT_TIMEOUT: // Disconnect on GATT Server and Client timeout events. // ASSERT_STATUS_RET_VOID (sd_ble_gap_disconnect(m_conn_handle, // BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION)); break; case BLE_GAP_EVT_ADV_REPORT: { const ble_gap_evt_adv_report_t *advReport = &p_ble_evt->evt.gap_evt.params.adv_report; gap.processAdvertisementReport(advReport->peer_addr.addr, advReport->rssi, advReport->scan_rsp, static_cast<GapAdvertisingParams::AdvertisingType_t>(advReport->type), advReport->dlen, advReport->data, static_cast<BLEProtocol::AddressType_t>(advReport->peer_addr.addr_type)); break; } default: break; } // Process security manager events securityManager.sm_handler(p_ble_evt); gattServer.hwCallback(p_ble_evt); } /*! @brief Callback when an error occurs inside the SoftDevice */ void assert_nrf_callback(uint16_t line_num, const uint8_t *p_file_name) { ASSERT_TRUE(false, (void) 0); } /*! @brief Handler for general errors above the SoftDevice layer. Typically we can' recover from this so we do a reset. */ void app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t *p_file_name) { ASSERT_STATUS_RET_VOID( error_code ); NVIC_SystemReset(); } <commit_msg>BLE: Fix reference to security manager in Nordic event handler.<commit_after>/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 "common/common.h" #include "nordic_common.h" #include "btle.h" #include "btle_clock.h" #include "ble_flash.h" #include "ble_conn_params.h" #include "btle_gap.h" #include "custom/custom_helper.h" #include "ble/GapEvents.h" #include "nRF5xn.h" #ifdef S110 #define IS_LEGACY_DEVICE_MANAGER_ENABLED 1 #elif defined(S130) || defined(S132) #define IS_LEGACY_DEVICE_MANAGER_ENABLED 0 #endif extern "C" { #if (IS_LEGACY_DEVICE_MANAGER_ENABLED) #include "pstorage.h" #else #include "fstorage.h" #include "fds.h" #include "ble_conn_state.h" #endif #include "softdevice_handler.h" #include "ble_stack_handler_types.h" } #include "nrf_ble_hci.h" #include "nRF5XPalGattClient.h" #include "nRF5XPalSecurityManager.h" bool isEventsSignaled = false; extern "C" void assert_nrf_callback(uint16_t line_num, const uint8_t *p_file_name); void app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t *p_file_name); extern "C" void SD_EVT_IRQHandler(void); // export the softdevice event handler for registration by nvic-set-vector. static void btle_handler(ble_evt_t *p_ble_evt); static void sys_evt_dispatch(uint32_t sys_evt) { #if (IS_LEGACY_DEVICE_MANAGER_ENABLED) pstorage_sys_event_handler(sys_evt); #else // Forward Softdevice events to the fstorage module fs_sys_event_handler(sys_evt); #endif } /** * This function is called in interrupt context to handle BLE events; i.e. pull * system and user events out of the pending events-queue of the BLE stack. The * BLE stack signals the availability of events by the triggering the SWI2 * interrupt, which forwards the handling to this function. * * The event processing loop is implemented in intern_softdevice_events_execute(). * * This function will signal to the user code by calling signalEventsToProcess * that their is events to process and BLE::processEvents should be called. */ static uint32_t signalEvent() { if(isEventsSignaled == false) { isEventsSignaled = true; nRF5xn::Instance(BLE::DEFAULT_INSTANCE).signalEventsToProcess(BLE::DEFAULT_INSTANCE); } return NRF_SUCCESS; } error_t btle_init(void) { nrf_clock_lf_cfg_t clockConfiguration; // register softdevice handler vector NVIC_SetVector(SD_EVT_IRQn, (uint32_t) SD_EVT_IRQHandler); // Configure the LF clock according to values provided by btle_clock.h. // It is input from the chain of the yotta configuration system. clockConfiguration.source = LFCLK_CONF_SOURCE; clockConfiguration.xtal_accuracy = LFCLK_CONF_ACCURACY; clockConfiguration.rc_ctiv = LFCLK_CONF_RC_CTIV; clockConfiguration.rc_temp_ctiv = LFCLK_CONF_RC_TEMP_CTIV; SOFTDEVICE_HANDLER_INIT(&clockConfiguration, signalEvent); // Enable BLE stack /** * Using this call, the application can select whether to include the * Service Changed characteristic in the GATT Server. The default in all * previous releases has been to include the Service Changed characteristic, * but this affects how GATT clients behave. Specifically, it requires * clients to subscribe to this attribute and not to cache attribute handles * between connections unless the devices are bonded. If the application * does not need to change the structure of the GATT server attributes at * runtime this adds unnecessary complexity to the interaction with peer * clients. If the SoftDevice is enabled with the Service Changed * Characteristics turned off, then clients are allowed to cache attribute * handles making applications simpler on both sides. */ static const bool IS_SRVC_CHANGED_CHARACT_PRESENT = true; ble_enable_params_t ble_enable_params; uint32_t err_code = softdevice_enable_get_default_config(CENTRAL_LINK_COUNT, PERIPHERAL_LINK_COUNT, &ble_enable_params); ble_enable_params.gatts_enable_params.attr_tab_size = GATTS_ATTR_TAB_SIZE; ble_enable_params.gatts_enable_params.service_changed = IS_SRVC_CHANGED_CHARACT_PRESENT; ble_enable_params.common_enable_params.vs_uuid_count = UUID_TABLE_MAX_ENTRIES; if(err_code != NRF_SUCCESS) { return ERROR_INVALID_PARAM; } if (softdevice_enable(&ble_enable_params) != NRF_SUCCESS) { return ERROR_INVALID_PARAM; } #if (NRF_SD_BLE_API_VERSION <= 2) ble_gap_addr_t addr; if (sd_ble_gap_address_get(&addr) != NRF_SUCCESS) { return ERROR_INVALID_PARAM; } if (sd_ble_gap_address_set(BLE_GAP_ADDR_CYCLE_MODE_NONE, &addr) != NRF_SUCCESS) { return ERROR_INVALID_PARAM; } #else #endif ASSERT_STATUS( softdevice_ble_evt_handler_set(btle_handler)); ASSERT_STATUS( softdevice_sys_evt_handler_set(sys_evt_dispatch)); return btle_gap_init(); } static void btle_handler(ble_evt_t *p_ble_evt) { using ble::pal::vendor::nordic::nRF5XGattClient; using ble::pal::vendor::nordic::nRF5xSecurityManager; /* Library service handlers */ #if SDK_CONN_PARAMS_MODULE_ENABLE ble_conn_params_on_ble_evt(p_ble_evt); #endif #if (IS_LEGACY_DEVICE_MANAGER_ENABLED) #else // Forward BLE events to the Connection State module. // This must be called before any event handler that uses this module. ble_conn_state_on_ble_evt(p_ble_evt); #endif #if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110) nRF5XGattClient::handle_events(p_ble_evt); #endif nRF5xn &ble = nRF5xn::Instance(BLE::DEFAULT_INSTANCE); nRF5xGap &gap = (nRF5xGap &) ble.getGap(); nRF5xGattServer &gattServer = (nRF5xGattServer &) ble.getGattServer(); nRF5xSecurityManager &securityManager = nRF5xSecurityManager::get_security_manager(); /* Custom event handler */ switch (p_ble_evt->header.evt_id) { case BLE_GAP_EVT_CONNECTED: { Gap::Handle_t handle = p_ble_evt->evt.gap_evt.conn_handle; #if defined(TARGET_MCU_NRF51_16K_S110) || defined(TARGET_MCU_NRF51_32K_S110) /* Only peripheral role is supported by S110 */ Gap::Role_t role = Gap::PERIPHERAL; #else Gap::Role_t role = static_cast<Gap::Role_t>(p_ble_evt->evt.gap_evt.params.connected.role); #endif gap.setConnectionHandle(handle); const Gap::ConnectionParams_t *params = reinterpret_cast<Gap::ConnectionParams_t *>(&(p_ble_evt->evt.gap_evt.params.connected.conn_params)); const ble_gap_addr_t *peer = &p_ble_evt->evt.gap_evt.params.connected.peer_addr; #if (NRF_SD_BLE_API_VERSION <= 2) const ble_gap_addr_t *own = &p_ble_evt->evt.gap_evt.params.connected.own_addr; gap.processConnectionEvent(handle, role, static_cast<BLEProtocol::AddressType_t>(peer->addr_type), peer->addr, static_cast<BLEProtocol::AddressType_t>(own->addr_type), own->addr, params); #else Gap::AddressType_t addr_type; Gap::Address_t own_address; gap.getAddress(&addr_type, own_address); gap.processConnectionEvent(handle, role, static_cast<BLEProtocol::AddressType_t>(peer->addr_type), peer->addr, addr_type, own_address, params); #endif break; } case BLE_GAP_EVT_DISCONNECTED: { Gap::Handle_t handle = p_ble_evt->evt.gap_evt.conn_handle; // Since we are not in a connection and have not started advertising, // store bonds gap.setConnectionHandle (BLE_CONN_HANDLE_INVALID); Gap::DisconnectionReason_t reason; switch (p_ble_evt->evt.gap_evt.params.disconnected.reason) { case BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION: reason = Gap::LOCAL_HOST_TERMINATED_CONNECTION; break; case BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION: reason = Gap::REMOTE_USER_TERMINATED_CONNECTION; break; case BLE_HCI_CONN_INTERVAL_UNACCEPTABLE: reason = Gap::CONN_INTERVAL_UNACCEPTABLE; break; default: /* Please refer to the underlying transport library for an * interpretion of this reason's value. */ reason = static_cast<Gap::DisconnectionReason_t>(p_ble_evt->evt.gap_evt.params.disconnected.reason); break; } #if !defined(TARGET_MCU_NRF51_16K_S110) && !defined(TARGET_MCU_NRF51_32K_S110) // Close all pending discoveries for this connection nRF5XGattClient::handle_connection_termination(handle); #endif gap.processDisconnectionEvent(handle, reason); break; } case BLE_GAP_EVT_TIMEOUT: gap.processTimeoutEvent(static_cast<Gap::TimeoutSource_t>(p_ble_evt->evt.gap_evt.params.timeout.src)); break; case BLE_GATTC_EVT_TIMEOUT: case BLE_GATTS_EVT_TIMEOUT: // Disconnect on GATT Server and Client timeout events. // ASSERT_STATUS_RET_VOID (sd_ble_gap_disconnect(m_conn_handle, // BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION)); break; case BLE_GAP_EVT_ADV_REPORT: { const ble_gap_evt_adv_report_t *advReport = &p_ble_evt->evt.gap_evt.params.adv_report; gap.processAdvertisementReport(advReport->peer_addr.addr, advReport->rssi, advReport->scan_rsp, static_cast<GapAdvertisingParams::AdvertisingType_t>(advReport->type), advReport->dlen, advReport->data, static_cast<BLEProtocol::AddressType_t>(advReport->peer_addr.addr_type)); break; } default: break; } // Process security manager events securityManager.sm_handler(p_ble_evt); gattServer.hwCallback(p_ble_evt); } /*! @brief Callback when an error occurs inside the SoftDevice */ void assert_nrf_callback(uint16_t line_num, const uint8_t *p_file_name) { ASSERT_TRUE(false, (void) 0); } /*! @brief Handler for general errors above the SoftDevice layer. Typically we can' recover from this so we do a reset. */ void app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t *p_file_name) { ASSERT_STATUS_RET_VOID( error_code ); NVIC_SystemReset(); } <|endoftext|>
<commit_before>//============================================================================== // CellML Model Repository window //============================================================================== #include "cellmlmodelrepositorywindow.h" #include "cellmlmodelrepositorywidget.h" #include "coreutils.h" //============================================================================== #include "ui_cellmlmodelrepositorywindow.h" //============================================================================== #include <QClipboard> #include <QMenu> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> //============================================================================== #include <QJsonParser> //============================================================================== namespace OpenCOR { namespace CellMLModelRepository { //============================================================================== CellmlModelRepositoryWindow::CellmlModelRepositoryWindow(QWidget *pParent) : OrganisationWidget(pParent), mGui(new Ui::CellmlModelRepositoryWindow) { // Set up the GUI mGui->setupUi(this); // Make the name value our focus proxy setFocusProxy(mGui->nameValue); // Create and add the CellML Model Repository widget mCellmlModelRepositoryWidget = new CellmlModelRepositoryWidget(this); mGui->dockWidgetContents->layout()->addWidget(mCellmlModelRepositoryWidget); // We want our own context menu for the help widget (indeed, we don't want // the default one which has the reload menu item and not the other actions // that we have in our toolbar, so...) mCellmlModelRepositoryWidget->setContextMenuPolicy(Qt::CustomContextMenu); connect(mCellmlModelRepositoryWidget, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(customContextMenu(const QPoint &))); // Retrieve the list of models in the CellML Model Repository as JSON code // from http://models.cellml.org/workspace/rest/contents.json mNetworkAccessManager = new QNetworkAccessManager(this); // Make sure that we get told when the download of our Internet file is // complete connect(mNetworkAccessManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(finished(QNetworkReply *)) ); // Get the list of CellML models on_refreshButton_clicked(); } //============================================================================== CellmlModelRepositoryWindow::~CellmlModelRepositoryWindow() { // Delete the GUI delete mGui; } //============================================================================== void CellmlModelRepositoryWindow::retranslateUi() { // Retranslate the whole window mGui->retranslateUi(this); // Retranslate our list of models outputModelList(mModelList); } //============================================================================== void CellmlModelRepositoryWindow::outputModelList(const QStringList &pModelList) { // Output a given list of models mModelList = pModelList; QString contents = ""; const QString leadingSpaces = " "; if (mModelList.count()) { // We have models to list, so... if (mModelList.count() == 1) contents = tr("<strong>1</strong> CellML model was found:")+"\n"; else contents = tr("<strong>%1</strong> CellML models were found:").arg(mModelList.count())+"\n"; contents += leadingSpaces+"<ul>\n"; foreach (const QString &model, mModelList) contents += leadingSpaces+"<li><a href=\""+mModelUrls.at(mModelNames.indexOf(model))+"\">"+model+"</a></li>\n"; contents += leadingSpaces+"</ul>"; } else if (mModelNames.empty()) { if (mErrorMsg.size()) { // Something went wrong while trying to retrieve the list of models, // so... QString errorMsg = mErrorMsg.left(1).toLower()+mErrorMsg.right(mErrorMsg.size()-1); QString dots = (errorMsg.at(errorMsg.size()-1) == '.')?"..":"..."; contents = leadingSpaces+"Error: "+errorMsg+dots; } else { // The list is still being loaded, so... contents = leadingSpaces+tr("Please wait while the list of CellML models is being loaded..."); } } else { // No model could be found, so... contents = leadingSpaces+tr("No CellML model matches your criteria"); } // Output the list matching the search criteria, or a message telling the // user what went wrong, if anything mCellmlModelRepositoryWidget->output(contents); } //============================================================================== void CellmlModelRepositoryWindow::on_nameValue_textChanged(const QString &text) { // Generate a Web page that contains all the models which match our search // criteria outputModelList(mModelNames.filter(QRegExp(text, Qt::CaseInsensitive, QRegExp::RegExp2))); } //============================================================================== void CellmlModelRepositoryWindow::on_actionCopy_triggered() { // Copy the current slection to the clipboard QApplication::clipboard()->setText(mCellmlModelRepositoryWidget->selectedText()); } //============================================================================== void CellmlModelRepositoryWindow::on_refreshButton_clicked() { // Output the message telling the user that the list is being downloaded // Note: to clear mModelNames ensures that we get the correct message from // outputModelList... mModelNames.clear(); outputModelList(QStringList()); // Disable the GUI side, so that the user doesn't get confused and ask to // refresh over and over again while he should just be patient setEnabled(false); // Get the list of CellML models mNetworkAccessManager->get(QNetworkRequest(QUrl("http://models.cellml.org/workspace/rest/contents.json"))); } //============================================================================== void CellmlModelRepositoryWindow::finished(QNetworkReply *pNetworkReply) { // Clear some properties mModelNames.clear(); mModelUrls.clear(); mErrorMsg.clear(); // Output the list of models, should we have retrieved it without any // problem if (pNetworkReply->error() == QNetworkReply::NoError) { // Parse the JSON code QJson::Parser jsonParser; bool parsingOk; QVariantMap res = jsonParser.parse (pNetworkReply->readAll(), &parsingOk).toMap(); if (parsingOk) { // Retrieve the name of the keys QStringList keys; foreach (const QVariant &keyVariant, res["keys"].toList()) keys << keyVariant.toString(); // Retrieve the list of models itself foreach (const QVariant &modelVariant, res["values"].toList()) { QVariantList modelDetailsVariant = modelVariant.toList(); mModelNames << modelDetailsVariant.at(0).toString(); mModelUrls << modelDetailsVariant.at(1).toString(); } } } else { // Something went wrong, so... mErrorMsg = pNetworkReply->errorString(); } // Initialise the output using whatever search criteria is present on_nameValue_textChanged(mGui->nameValue->text()); // Re-enable the GUI side setEnabled(true); // Give, within the current window, the focus to mGui->nameValue, but only // if the current window already has the focus Core::setFocusTo(mGui->nameValue); } //============================================================================== void CellmlModelRepositoryWindow::customContextMenu(const QPoint &) const { // Create a custom context menu for our CellML Models Repository widget QMenu menu; menu.addAction(mGui->actionCopy); menu.exec(QCursor::pos()); } //============================================================================== } // namespace CellMLModelRepository } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Some minor cleaning up (#57).<commit_after>//============================================================================== // CellML Model Repository window //============================================================================== #include "cellmlmodelrepositorywindow.h" #include "cellmlmodelrepositorywidget.h" #include "coreutils.h" //============================================================================== #include "ui_cellmlmodelrepositorywindow.h" //============================================================================== #include <QClipboard> #include <QMenu> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> //============================================================================== #include <QJsonParser> //============================================================================== namespace OpenCOR { namespace CellMLModelRepository { //============================================================================== CellmlModelRepositoryWindow::CellmlModelRepositoryWindow(QWidget *pParent) : OrganisationWidget(pParent), mGui(new Ui::CellmlModelRepositoryWindow) { // Set up the GUI mGui->setupUi(this); // Make the name value our focus proxy setFocusProxy(mGui->nameValue); // Create and add the CellML Model Repository widget mCellmlModelRepositoryWidget = new CellmlModelRepositoryWidget(this); mGui->dockWidgetContents->layout()->addWidget(mCellmlModelRepositoryWidget); // We want our own context menu for the help widget (indeed, we don't want // the default one which has the reload menu item and not the other actions // that we have in our toolbar, so...) mCellmlModelRepositoryWidget->setContextMenuPolicy(Qt::CustomContextMenu); connect(mCellmlModelRepositoryWidget, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(customContextMenu(const QPoint &))); // Retrieve the list of models in the CellML Model Repository as JSON code // from http://models.cellml.org/workspace/rest/contents.json mNetworkAccessManager = new QNetworkAccessManager(this); // Make sure that we get told when the download of our Internet file is // complete connect(mNetworkAccessManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(finished(QNetworkReply *)) ); // Get the list of CellML models on_refreshButton_clicked(); } //============================================================================== CellmlModelRepositoryWindow::~CellmlModelRepositoryWindow() { // Delete the GUI delete mGui; } //============================================================================== void CellmlModelRepositoryWindow::retranslateUi() { // Retranslate the whole window mGui->retranslateUi(this); // Retranslate our list of models outputModelList(mModelList); } //============================================================================== void CellmlModelRepositoryWindow::outputModelList(const QStringList &pModelList) { // Output a given list of models mModelList = pModelList; QString contents = ""; const QString leadingSpaces = " "; if (mModelList.count()) { // We have models to list, so... if (mModelList.count() == 1) contents = tr("<strong>1</strong> CellML model was found:")+"\n"; else contents = tr("<strong>%1</strong> CellML models were found:").arg(mModelList.count())+"\n"; contents += leadingSpaces+"<ul>\n"; foreach (const QString &model, mModelList) contents += leadingSpaces+"<li><a href=\""+mModelUrls.at(mModelNames.indexOf(model))+"\">"+model+"</a></li>\n"; contents += leadingSpaces+"</ul>"; } else if (mModelNames.empty()) { if (mErrorMsg.size()) { // Something went wrong while trying to retrieve the list of models, // so... QString errorMsg = mErrorMsg.left(1).toLower()+mErrorMsg.right(mErrorMsg.size()-1); QString dots = (errorMsg.at(errorMsg.size()-1) == '.')?"..":"..."; contents = leadingSpaces+"Error: "+errorMsg+dots; } else { // The list is still being loaded, so... contents = leadingSpaces+tr("Please wait while the list of CellML models is being loaded..."); } } else { // No model could be found, so... contents = leadingSpaces+tr("No CellML model matches your criteria"); } // Output the list matching the search criteria, or a message telling the // user what went wrong, if anything mCellmlModelRepositoryWidget->output(contents); } //============================================================================== void CellmlModelRepositoryWindow::on_nameValue_textChanged(const QString &text) { // Generate a Web page that contains all the models which match our search // criteria outputModelList(mModelNames.filter(QRegExp(text, Qt::CaseInsensitive))); } //============================================================================== void CellmlModelRepositoryWindow::on_actionCopy_triggered() { // Copy the current slection to the clipboard QApplication::clipboard()->setText(mCellmlModelRepositoryWidget->selectedText()); } //============================================================================== void CellmlModelRepositoryWindow::on_refreshButton_clicked() { // Output the message telling the user that the list is being downloaded // Note: to clear mModelNames ensures that we get the correct message from // outputModelList... mModelNames.clear(); outputModelList(QStringList()); // Disable the GUI side, so that the user doesn't get confused and ask to // refresh over and over again while he should just be patient setEnabled(false); // Get the list of CellML models mNetworkAccessManager->get(QNetworkRequest(QUrl("http://models.cellml.org/workspace/rest/contents.json"))); } //============================================================================== void CellmlModelRepositoryWindow::finished(QNetworkReply *pNetworkReply) { // Clear some properties mModelNames.clear(); mModelUrls.clear(); mErrorMsg.clear(); // Output the list of models, should we have retrieved it without any // problem if (pNetworkReply->error() == QNetworkReply::NoError) { // Parse the JSON code QJson::Parser jsonParser; bool parsingOk; QVariantMap res = jsonParser.parse (pNetworkReply->readAll(), &parsingOk).toMap(); if (parsingOk) { // Retrieve the name of the keys QStringList keys; foreach (const QVariant &keyVariant, res["keys"].toList()) keys << keyVariant.toString(); // Retrieve the list of models itself foreach (const QVariant &modelVariant, res["values"].toList()) { QVariantList modelDetailsVariant = modelVariant.toList(); mModelNames << modelDetailsVariant.at(0).toString(); mModelUrls << modelDetailsVariant.at(1).toString(); } } } else { // Something went wrong, so... mErrorMsg = pNetworkReply->errorString(); } // Initialise the output using whatever search criteria is present on_nameValue_textChanged(mGui->nameValue->text()); // Re-enable the GUI side setEnabled(true); // Give, within the current window, the focus to mGui->nameValue, but only // if the current window already has the focus Core::setFocusTo(mGui->nameValue); } //============================================================================== void CellmlModelRepositoryWindow::customContextMenu(const QPoint &) const { // Create a custom context menu for our CellML Models Repository widget QMenu menu; menu.addAction(mGui->actionCopy); menu.exec(QCursor::pos()); } //============================================================================== } // namespace CellMLModelRepository } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>#include "BuildingQueue.h" #include "bwem.h" #include "UnitManager.h" #include "BaseManager.h" #include "BuildingPlacer.h" #include "DrawingManager.h" Neolib::BuildingQueue buildingQueue; namespace Neolib { void BuildingQueue::onFrame() { for (auto it = buildingQueue.begin(); it != buildingQueue.end(); ++it) { if (it->buildingType.getRace() == BWAPI::Races::Terran && !it->builder) { } if (it->builder) { auto order = it->builder->getOrder(); if (order == BWAPI::Orders::ConstructingBuilding) continue; else if (order == BWAPI::Orders::PlaceBuilding) continue; if (resourceManager.canAfford(it->buildingType)) { if (it->buildingUnit) { it->builder->rightClick(it->buildingUnit); } else { it->builder->build(it->buildingType, it->designatedLocation); } } } } } void BuildingQueue::onUnitComplete(BWAPI::Unit unit) { // Check if our building is done for (auto it = buildingQueue.begin(); it != buildingQueue.end();) { if (it->buildingUnit == unit) { if (it->buildingType.getRace() == BWAPI::Races::Terran && it->builder) baseManager.giveBackUnit(it->builder); it = buildingQueue.erase(it); } else { ++it; } } } void BuildingQueue::onUnitCreate(BWAPI::Unit unit) { // If our building was placed for (auto &o : buildingQueue) { if (o.buildingType == unit->getType() && o.designatedLocation == unit->getTilePosition()) { o.buildingUnit = unit; } } } void BuildingQueue::onUnitDestroy(BWAPI::Unit unit) { // Check if our builder died for (auto it = buildingQueue.begin(); it != buildingQueue.end(); ++it) { if (it->builder == unit) { // Find replacement builder it->builder = baseManager.findClosestBuilder(it->buildingType.whatBuilds().first, (BWAPI::Position)it->designatedLocation); if (it->builder) { baseManager.takeUnit(it->builder); if (it->buildingUnit && it->buildingUnit->exists()) { it->builder->rightClick(it->buildingUnit); } if (!it->buildingUnit) { it->builder->build(it->buildingType, it->designatedLocation); } } } } // Check if our building died for (auto it = buildingQueue.begin(); it != buildingQueue.end(); ++it) { if (it->buildingUnit == unit) { it->buildingUnit = nullptr; if (it->builder && it->builder->exists()) it->builder->build(it->buildingType, it->designatedLocation); } } } void BuildingQueue::onUnitMorph(BWAPI::Unit unit) { onUnitCreate(unit); } bool BuildingQueue::doBuild(BWAPI::UnitType building, BWAPI::TilePosition at, BWAPI::Unit u) { if (at == BWAPI::TilePositions::None) { if (!u && !(u = baseManager.findBuilder(building))) // Could not a find builder return false; at = buildingPlacer.getBuildLocation(building, u->getTilePosition()); if (at == BWAPI::TilePositions::None) { drawingManager.failedLocations.insert({ at, building }); BWAPI::Broodwar->pingMinimap((BWAPI::Position)at); return false; } } else if (!u && !(u = baseManager.findClosestBuilder(building, (BWAPI::Position) at))) // Could not a find builder return false; // If build location intersects another build location, nope out BWAPI::TilePosition buildingEnd(at + building.tileSize()); for (auto &o : buildingQueue) { BWAPI::TilePosition otherEnd(o.designatedLocation + o.buildingType.tileSize()); if (at.x < o.designatedLocation.x) { if (at.y < o.designatedLocation.y) { if (o.designatedLocation.x < buildingEnd.x && o.designatedLocation.y < buildingEnd.y) return false; else if (o.designatedLocation.x < buildingEnd.x && at.y < otherEnd.y) return false; } } else { if (at.y < o.designatedLocation.y) { if (at.x < otherEnd.x && o.designatedLocation.y < buildingEnd.y) return false; } else if (at.x < otherEnd.x && at.y < otherEnd.y) return false; } } if (u) baseManager.takeUnit(u); if (u->build(building, at)) { ConstructionProject cp; cp.builder = u; cp.buildingType = building; cp.designatedLocation = at; buildingQueue.emplace_back(cp); return true; } else { if (!BWAPI::Broodwar->isVisible(at)) u->move((BWAPI::Position)at); drawingManager.failedLocations.insert({ at, building }); BWAPI::Broodwar->pingMinimap((BWAPI::Position)at); return false; } } ResourceCount BuildingQueue::getQueuedResources() const { ResourceCount resourceCount; for (auto &o : this->buildingQueue) if (!o.buildingUnit) resourceCount += o.buildingType; return resourceCount; } SupplyCount BuildingQueue::getQueuedSupply(bool countResourceDepots) const { SupplyCount supplyCount; for (auto &o : buildingQueue) { // Terran if (o.buildingType == BWAPI::UnitTypes::Terran_Supply_Depot) supplyCount.terran += 16; else if (o.buildingType == BWAPI::UnitTypes::Terran_Command_Center && countResourceDepots) supplyCount.terran += 20; // Protoss else if (o.buildingType == BWAPI::UnitTypes::Protoss_Pylon) supplyCount.protoss += 16; else if (o.buildingType == BWAPI::UnitTypes::Protoss_Nexus && countResourceDepots) supplyCount.protoss += 18; // Zerg else if (o.buildingType == BWAPI::UnitTypes::Zerg_Overlord) supplyCount.zerg += 16; else if (o.buildingType == BWAPI::UnitTypes::Zerg_Hatchery && countResourceDepots) supplyCount.zerg += 2; } return supplyCount; } bool BuildingQueue::isWorkerBuilding(BWAPI::Unit u) const { for (auto &o : buildingQueue) if (o.builder == u) return true; return false; } const std::list <ConstructionProject> &BuildingQueue::buildingsQueued() { return buildingQueue; } } <commit_msg>Let's see how aggroing for building workers work<commit_after>#include "BuildingQueue.h" #include "bwem.h" #include "UnitManager.h" #include "BaseManager.h" #include "BuildingPlacer.h" #include "DrawingManager.h" Neolib::BuildingQueue buildingQueue; namespace Neolib { void BuildingQueue::onFrame() { for (auto it = buildingQueue.begin(); it != buildingQueue.end(); ++it) { if (it->buildingType.getRace() == BWAPI::Races::Terran && !it->builder) { } if (it->builder) { auto order = it->builder->getOrder(); if (order == BWAPI::Orders::ConstructingBuilding) continue; else if (order == BWAPI::Orders::PlaceBuilding) continue; if (resourceManager.canAfford(it->buildingType)) { if (it->buildingUnit) { it->builder->rightClick(it->buildingUnit); } else { it->builder->build(it->buildingType, it->designatedLocation); } } } } } void BuildingQueue::onUnitComplete(BWAPI::Unit unit) { // Check if our building is done for (auto it = buildingQueue.begin(); it != buildingQueue.end();) { if (it->buildingUnit == unit) { if (it->buildingType.getRace() == BWAPI::Races::Terran && it->builder) baseManager.giveBackUnit(it->builder); it = buildingQueue.erase(it); } else { ++it; } } } void BuildingQueue::onUnitCreate(BWAPI::Unit unit) { // If our building was placed for (auto &o : buildingQueue) { if (o.buildingType == unit->getType() && o.designatedLocation == unit->getTilePosition()) { o.buildingUnit = unit; } } } void BuildingQueue::onUnitDestroy(BWAPI::Unit unit) { // Check if our builder died for (auto it = buildingQueue.begin(); it != buildingQueue.end(); ++it) { if (it->builder == unit) { // Find replacement builder it->builder = baseManager.findClosestBuilder(it->buildingType.whatBuilds().first, (BWAPI::Position)it->designatedLocation); if (it->builder) { baseManager.takeUnit(it->builder); if (it->buildingUnit && it->buildingUnit->exists()) { it->builder->rightClick(it->buildingUnit); } if (!it->buildingUnit) { it->builder->build(it->buildingType, it->designatedLocation); } } } } // Check if our building died for (auto it = buildingQueue.begin(); it != buildingQueue.end(); ++it) { if (it->buildingUnit == unit) { it->buildingUnit = nullptr; if (it->builder && it->builder->exists()) it->builder->build(it->buildingType, it->designatedLocation); } } } void BuildingQueue::onUnitMorph(BWAPI::Unit unit) { onUnitCreate(unit); } bool BuildingQueue::doBuild(BWAPI::UnitType building, BWAPI::TilePosition at, BWAPI::Unit u) { if (at == BWAPI::TilePositions::None) { if (!u && !(u = baseManager.findBuilder(building))) // Could not a find builder return false; at = buildingPlacer.getBuildLocation(building, u->getTilePosition()); if (at == BWAPI::TilePositions::None) { drawingManager.failedLocations.insert({ at, building }); BWAPI::Broodwar->pingMinimap((BWAPI::Position)at); return false; } } else if (!u && !(u = baseManager.findClosestBuilder(building, (BWAPI::Position) at))) // Could not a find builder return false; // If build location intersects another build location, nope out BWAPI::TilePosition buildingEnd(at + building.tileSize()); for (auto &o : buildingQueue) { BWAPI::TilePosition otherEnd(o.designatedLocation + o.buildingType.tileSize()); if (at.x < o.designatedLocation.x) { if (at.y < o.designatedLocation.y) { if (o.designatedLocation.x < buildingEnd.x && o.designatedLocation.y < buildingEnd.y) return false; else if (o.designatedLocation.x < buildingEnd.x && at.y < otherEnd.y) return false; } } else { if (at.y < o.designatedLocation.y) { if (at.x < otherEnd.x && o.designatedLocation.y < buildingEnd.y) return false; } else if (at.x < otherEnd.x && at.y < otherEnd.y) return false; } } //if (u) // baseManager.takeUnit(u); if (u->build(building, at)) { ConstructionProject cp; cp.builder = u; cp.buildingType = building; cp.designatedLocation = at; buildingQueue.emplace_back(cp); return true; } else { if (!BWAPI::Broodwar->isVisible(at)) u->move((BWAPI::Position)at); drawingManager.failedLocations.insert({ at, building }); BWAPI::Broodwar->pingMinimap((BWAPI::Position)at); return false; } } ResourceCount BuildingQueue::getQueuedResources() const { ResourceCount resourceCount; for (auto &o : this->buildingQueue) if (!o.buildingUnit) resourceCount += o.buildingType; return resourceCount; } SupplyCount BuildingQueue::getQueuedSupply(bool countResourceDepots) const { SupplyCount supplyCount; for (auto &o : buildingQueue) { // Terran if (o.buildingType == BWAPI::UnitTypes::Terran_Supply_Depot) supplyCount.terran += 16; else if (o.buildingType == BWAPI::UnitTypes::Terran_Command_Center && countResourceDepots) supplyCount.terran += 20; // Protoss else if (o.buildingType == BWAPI::UnitTypes::Protoss_Pylon) supplyCount.protoss += 16; else if (o.buildingType == BWAPI::UnitTypes::Protoss_Nexus && countResourceDepots) supplyCount.protoss += 18; // Zerg else if (o.buildingType == BWAPI::UnitTypes::Zerg_Overlord) supplyCount.zerg += 16; else if (o.buildingType == BWAPI::UnitTypes::Zerg_Hatchery && countResourceDepots) supplyCount.zerg += 2; } return supplyCount; } bool BuildingQueue::isWorkerBuilding(BWAPI::Unit u) const { for (auto &o : buildingQueue) if (o.builder == u) return true; return false; } const std::list <ConstructionProject> &BuildingQueue::buildingsQueued() { return buildingQueue; } } <|endoftext|>
<commit_before>// Time: O(1) // Space: O(1) // Thread-Safe, Lazy Initilization class Solution { public: /** * @return: The same instance of this class every time */ static Solution* getInstance() { static Solution *instance = new Solution(); return instance; } private: Solution() {} };<commit_msg>Update singleton.cpp<commit_after>// Time: O(1) // Space: O(1) // Thread-Safe, Lazy Initilization class Solution { public: /** * @return: The same instance of this class every time */ static Solution* getInstance() { static Solution *instance = new Solution(); // C++ 11 thread-safe local-static-initialization return instance; } private: Solution() {} }; <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/corecache/p10_hcd_core_stopgrid.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2021 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p10_hcd_core_stopgrid.C /// @brief /// // *HWP HWP Owner : David Du <daviddu@us.ibm.com> // *HWP Backup HWP Owner : Greg Still <stillgs@us.ibm.com> // *HWP FW Owner : Prem Shanker Jha <premjha2@in.ibm.com> // *HWP Team : PM // *HWP Consumed by : SBE:QME // *HWP Level : 2 /// // EKB-Mirror-To: hw/ppe //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include "p10_hcd_core_stopgrid.H" #include "p10_hcd_mma_stopclocks.H" #include "p10_hcd_mma_poweroff.H" #include "p10_hcd_common.H" #ifdef __PPE_QME #include "p10_ppe_eq.H" #include "p10_ppe_c.H" using namespace scomt::ppe_eq; using namespace scomt::ppe_c; #else #include "p10_scom_eq.H" #include "p10_scom_c.H" using namespace scomt::eq; using namespace scomt::c; #endif //------------------------------------------------------------------------------ // Constant Definitions //------------------------------------------------------------------------------ enum P10_HCD_CORE_STOPGRID_CONSTANTS { HCD_ECL2_CLK_SYNC_DROP_POLL_TIMEOUT_HW_NS = 10000, // 10^4ns = 10us timeout HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_HW_NS = 100, // 100ns poll loop delay HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_SIM_CYCLE = 3200, // 3.2k sim cycle delay HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_TIMEOUT_HW_NS = 100000000, // 10^4ns = 10us timeout HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_HW_NS = 100, // 100ns poll loop delay HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_SIM_CYCLE = 3200, // 3.2k sim cycle delay }; //------------------------------------------------------------------------------ // Procedure: p10_hcd_core_stopgrid //------------------------------------------------------------------------------ fapi2::ReturnCode p10_hcd_core_stopgrid( const fapi2::Target < fapi2::TARGET_TYPE_CORE | fapi2::TARGET_TYPE_MULTICAST, fapi2::MULTICAST_AND > & i_target) { fapi2::Target < fapi2::TARGET_TYPE_EQ | fapi2::TARGET_TYPE_MULTICAST, fapi2::MULTICAST_AND > eq_target = i_target.getParent < fapi2::TARGET_TYPE_EQ | fapi2::TARGET_TYPE_MULTICAST > (); fapi2::buffer<buffer_t> l_mmioData = 0; fapi2::buffer<uint64_t> l_scomData = 0; uint32_t l_timeout = 0; uint32_t l_core_change_done = 0; uint32_t l_regions = i_target.getCoreSelect(); fapi2::Target < fapi2::TARGET_TYPE_SYSTEM > l_sys; fapi2::ATTR_RUNN_MODE_Type l_attr_runn_mode; FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_RUNN_MODE, l_sys, l_attr_runn_mode ) ); FAPI_INF(">>p10_hcd_core_stopgrid"); // also stop mma clocks after/with core clocks // not part of core_stopclocks for its pure usage at p10_stopclocks // shared with both stop11 and stop3 path FAPI_TRY( p10_hcd_mma_stopclocks( i_target ) ); //also shutdown mma power here as for WOF benefit //always turn off MMA if it becomes unavailable FAPI_TRY( p10_hcd_mma_poweroff( i_target ) ); FAPI_DBG("Disable ECL2 Skewadjust via CPMS_CGCSR_[1:CL2_CLK_SYNC_ENABLE]"); FAPI_TRY( HCD_PUTMMIO_S( i_target, CPMS_CGCSR_WO_CLEAR, BIT64(1) ) ); FAPI_DBG("Check ECL2 Skewadjust Removed via CPMS_CGCSR[33:CL2_CLK_SYNC_DONE]"); l_timeout = HCD_ECL2_CLK_SYNC_DROP_POLL_TIMEOUT_HW_NS / HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_HW_NS; do { FAPI_TRY( HCD_GETMMIO_S( i_target, CPMS_CGCSR, l_scomData ) ); // use multicastOR to check 0 if( ( !l_attr_runn_mode ) && ( SCOM_GET(33) == 0 ) ) { break; } fapi2::delay(HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_HW_NS, HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_SIM_CYCLE); } while( (--l_timeout) != 0 ); FAPI_ASSERT( ( l_attr_runn_mode ? ( SCOM_GET(33) == 0 ) : (l_timeout != 0) ), fapi2::ECL2_CLK_SYNC_DROP_TIMEOUT() .set_ECL2_CLK_SYNC_DROP_POLL_TIMEOUT_HW_NS(HCD_ECL2_CLK_SYNC_DROP_POLL_TIMEOUT_HW_NS) .set_CPMS_CGCSR(l_scomData) .set_CORE_TARGET(i_target), "ERROR: ECL2 Clock Sync Drop Timeout"); FAPI_DBG("Assert CORE_OFF_REQ[0:3] of Resonent Clocking via RCSCR[0:3]"); FAPI_TRY( HCD_PUTMMIO_Q( eq_target, QME_RCSCR_WO_OR, MMIO_LOAD32H( ( l_regions << SHIFT32(3) ) ) ) ); FAPI_DBG("Poll for CORE_CHANGE_DONE in RCSR[4:7]"); l_timeout = HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_TIMEOUT_HW_NS / HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_HW_NS; do { FAPI_TRY( HCD_GETMMIO_Q( eq_target, QME_RCSCR, l_mmioData ) ); MMIO_EXTRACT(4, 4, l_core_change_done); if( ( !l_attr_runn_mode ) && ( (l_core_change_done & l_regions) == l_regions) ) { break; } fapi2::delay(HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_HW_NS, HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_SIM_CYCLE); } while( (--l_timeout) != 0 ); FAPI_ASSERT( ( l_attr_runn_mode ? ((l_core_change_done & l_regions) == l_regions) : (l_timeout != 0)), fapi2::CORE_CHANGE_DONE_RESCLK_ENTRY_TIMEOUT() .set_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_TIMEOUT_HW_NS(HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_TIMEOUT_HW_NS) .set_CORE_CHANGE_DONE(l_core_change_done) .set_CORE_SELECT(l_regions) .set_CORE_TARGET(i_target), "ERROR: Core Resclk Change Done Entry Timeout"); FAPI_DBG("Switch glsmux to refclk to save clock grid power via CPMS_CGCSR[11]"); FAPI_TRY( HCD_PUTMMIO_S( i_target, CPMS_CGCSR_WO_CLEAR, BIT64(11) ) ); fapi_try_exit: FAPI_INF("<<p10_hcd_core_stopgrid"); return fapi2::current_err; } <commit_msg>QME: improve stop2 latency<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/corecache/p10_hcd_core_stopgrid.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2021 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p10_hcd_core_stopgrid.C /// @brief /// // *HWP HWP Owner : David Du <daviddu@us.ibm.com> // *HWP Backup HWP Owner : Greg Still <stillgs@us.ibm.com> // *HWP FW Owner : Prem Shanker Jha <premjha2@in.ibm.com> // *HWP Team : PM // *HWP Consumed by : SBE:QME // *HWP Level : 2 /// // EKB-Mirror-To: hw/ppe //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include "p10_hcd_core_stopgrid.H" #include "p10_hcd_mma_stopclocks.H" #include "p10_hcd_mma_poweroff.H" #include "p10_hcd_common.H" #ifdef __PPE_QME #include "p10_ppe_eq.H" #include "p10_ppe_c.H" using namespace scomt::ppe_eq; using namespace scomt::ppe_c; #else #include "p10_scom_eq.H" #include "p10_scom_c.H" using namespace scomt::eq; using namespace scomt::c; #endif //------------------------------------------------------------------------------ // Constant Definitions //------------------------------------------------------------------------------ enum P10_HCD_CORE_STOPGRID_CONSTANTS { HCD_ECL2_CLK_SYNC_DROP_POLL_TIMEOUT_HW_NS = 10000, // 10^4ns = 10us timeout HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_HW_NS = 100, // 100ns poll loop delay HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_SIM_CYCLE = 3200, // 3.2k sim cycle delay HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_TIMEOUT_HW_NS = 100000000, // 10^4ns = 10us timeout HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_HW_NS = 100, // 100ns poll loop delay HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_SIM_CYCLE = 3200, // 3.2k sim cycle delay }; //------------------------------------------------------------------------------ // Procedure: p10_hcd_core_stopgrid //------------------------------------------------------------------------------ fapi2::ReturnCode p10_hcd_core_stopgrid( const fapi2::Target < fapi2::TARGET_TYPE_CORE | fapi2::TARGET_TYPE_MULTICAST, fapi2::MULTICAST_AND > & i_target) { fapi2::Target < fapi2::TARGET_TYPE_EQ | fapi2::TARGET_TYPE_MULTICAST, fapi2::MULTICAST_AND > eq_target = i_target.getParent < fapi2::TARGET_TYPE_EQ | fapi2::TARGET_TYPE_MULTICAST > (); fapi2::buffer<buffer_t> l_mmioData = 0; fapi2::buffer<uint64_t> l_scomData = 0; uint32_t l_timeout = 0; uint32_t l_core_change_done = 0; uint32_t l_regions = i_target.getCoreSelect(); uint8_t l_attr_mma_poweroff_disable = 0; fapi2::Target < fapi2::TARGET_TYPE_SYSTEM > l_sys; fapi2::ATTR_RUNN_MODE_Type l_attr_runn_mode; FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_RUNN_MODE, l_sys, l_attr_runn_mode ) ); FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_SYSTEM_MMA_POWEROFF_DISABLE, l_sys, l_attr_mma_poweroff_disable ) ); FAPI_INF(">>p10_hcd_core_stopgrid"); // Also stop mma clocks after/with core clocks // not part of core_stopclocks for its pure usage at p10_stopclocks // this hwp is shared stop2,3,11 path FAPI_TRY( p10_hcd_mma_stopclocks( i_target ) ); if( !l_attr_mma_poweroff_disable ) { //also shutdown mma power here as for WOF benefit //only do so when dynamic mode is enabled FAPI_TRY( p10_hcd_mma_poweroff( i_target ) ); } FAPI_DBG("Disable ECL2 Skewadjust via CPMS_CGCSR_[1:CL2_CLK_SYNC_ENABLE]"); FAPI_TRY( HCD_PUTMMIO_S( i_target, CPMS_CGCSR_WO_CLEAR, BIT64(1) ) ); FAPI_DBG("Check ECL2 Skewadjust Removed via CPMS_CGCSR[33:CL2_CLK_SYNC_DONE]"); l_timeout = HCD_ECL2_CLK_SYNC_DROP_POLL_TIMEOUT_HW_NS / HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_HW_NS; do { FAPI_TRY( HCD_GETMMIO_S( i_target, CPMS_CGCSR, l_scomData ) ); // use multicastOR to check 0 if( ( !l_attr_runn_mode ) && ( SCOM_GET(33) == 0 ) ) { break; } fapi2::delay(HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_HW_NS, HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_SIM_CYCLE); } while( (--l_timeout) != 0 ); FAPI_ASSERT( ( l_attr_runn_mode ? ( SCOM_GET(33) == 0 ) : (l_timeout != 0) ), fapi2::ECL2_CLK_SYNC_DROP_TIMEOUT() .set_ECL2_CLK_SYNC_DROP_POLL_TIMEOUT_HW_NS(HCD_ECL2_CLK_SYNC_DROP_POLL_TIMEOUT_HW_NS) .set_CPMS_CGCSR(l_scomData) .set_CORE_TARGET(i_target), "ERROR: ECL2 Clock Sync Drop Timeout"); FAPI_DBG("Assert CORE_OFF_REQ[0:3] of Resonent Clocking via RCSCR[0:3]"); FAPI_TRY( HCD_PUTMMIO_Q( eq_target, QME_RCSCR_WO_OR, MMIO_LOAD32H( ( l_regions << SHIFT32(3) ) ) ) ); FAPI_DBG("Poll for CORE_CHANGE_DONE in RCSR[4:7]"); l_timeout = HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_TIMEOUT_HW_NS / HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_HW_NS; do { FAPI_TRY( HCD_GETMMIO_Q( eq_target, QME_RCSCR, l_mmioData ) ); MMIO_EXTRACT(4, 4, l_core_change_done); if( ( !l_attr_runn_mode ) && ( (l_core_change_done & l_regions) == l_regions) ) { break; } fapi2::delay(HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_HW_NS, HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_SIM_CYCLE); } while( (--l_timeout) != 0 ); FAPI_ASSERT( ( l_attr_runn_mode ? ((l_core_change_done & l_regions) == l_regions) : (l_timeout != 0)), fapi2::CORE_CHANGE_DONE_RESCLK_ENTRY_TIMEOUT() .set_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_TIMEOUT_HW_NS(HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_TIMEOUT_HW_NS) .set_CORE_CHANGE_DONE(l_core_change_done) .set_CORE_SELECT(l_regions) .set_CORE_TARGET(i_target), "ERROR: Core Resclk Change Done Entry Timeout"); FAPI_DBG("Switch glsmux to refclk to save clock grid power via CPMS_CGCSR[11]"); FAPI_TRY( HCD_PUTMMIO_S( i_target, CPMS_CGCSR_WO_CLEAR, BIT64(11) ) ); fapi_try_exit: FAPI_INF("<<p10_hcd_core_stopgrid"); return fapi2::current_err; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/corecache/p10_hcd_core_stopgrid.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2021 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p10_hcd_core_stopgrid.C /// @brief /// // *HWP HWP Owner : David Du <daviddu@us.ibm.com> // *HWP Backup HWP Owner : Greg Still <stillgs@us.ibm.com> // *HWP FW Owner : Prem Shanker Jha <premjha2@in.ibm.com> // *HWP Team : PM // *HWP Consumed by : SBE:QME // *HWP Level : 2 /// // EKB-Mirror-To: hw/ppe //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include "p10_hcd_core_stopgrid.H" #include "p10_hcd_mma_stopclocks.H" #include "p10_hcd_mma_poweroff.H" #include "p10_hcd_common.H" #ifdef __PPE_QME #include "p10_ppe_eq.H" #include "p10_ppe_c.H" using namespace scomt::ppe_eq; using namespace scomt::ppe_c; #else #include "p10_scom_eq.H" #include "p10_scom_c.H" using namespace scomt::eq; using namespace scomt::c; #endif //------------------------------------------------------------------------------ // Constant Definitions //------------------------------------------------------------------------------ enum P10_HCD_CORE_STOPGRID_CONSTANTS { HCD_ECL2_CLK_SYNC_DROP_POLL_TIMEOUT_HW_NS = 10000, // 10^4ns = 10us timeout HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_HW_NS = 100, // 100ns poll loop delay HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_SIM_CYCLE = 3200, // 3.2k sim cycle delay HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_TIMEOUT_HW_NS = 100000000, // 10^4ns = 10us timeout HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_HW_NS = 100, // 100ns poll loop delay HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_SIM_CYCLE = 3200, // 3.2k sim cycle delay }; //------------------------------------------------------------------------------ // Procedure: p10_hcd_core_stopgrid //------------------------------------------------------------------------------ fapi2::ReturnCode p10_hcd_core_stopgrid( const fapi2::Target < fapi2::TARGET_TYPE_CORE | fapi2::TARGET_TYPE_MULTICAST, fapi2::MULTICAST_AND > & i_target) { fapi2::Target < fapi2::TARGET_TYPE_EQ | fapi2::TARGET_TYPE_MULTICAST, fapi2::MULTICAST_AND > eq_target = i_target.getParent < fapi2::TARGET_TYPE_EQ | fapi2::TARGET_TYPE_MULTICAST > (); fapi2::buffer<buffer_t> l_mmioData = 0; fapi2::buffer<uint64_t> l_scomData = 0; uint32_t l_timeout = 0; uint32_t l_core_change_done = 0; uint32_t l_regions = i_target.getCoreSelect(); uint8_t l_attr_mma_poweroff_disable = 0; fapi2::Target < fapi2::TARGET_TYPE_SYSTEM > l_sys; FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_SYSTEM_MMA_POWEROFF_DISABLE, l_sys, l_attr_mma_poweroff_disable ) ); #ifdef USE_RUNN fapi2::ATTR_RUNN_MODE_Type l_attr_runn_mode; FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_RUNN_MODE, l_sys, l_attr_runn_mode ) ); #endif FAPI_INF(">>p10_hcd_core_stopgrid"); // Also stop mma clocks after/with core clocks // not part of core_stopclocks for its pure usage at p10_stopclocks // this hwp is shared stop2,3,11 path FAPI_TRY( p10_hcd_mma_stopclocks( i_target ) ); // PowerON_Dis = 0 and PowerOFF_Dis = 0 do poweroff mma as in dynamic // PowerON_Dis = 0 and PowerOFF_Dis = 1 do not poweroff mma as not in dynamic // PowerON_Dis = 1 and PowerOFF_Dis = 0 do poweroff mma as in dynamic // PowerON_Dis = 1 and PowerOFF_Dis = 1 do not poweroff mma as not in dynamic if( !l_attr_mma_poweroff_disable ) { //also shutdown mma power here as for WOF benefit //only do so when dynamic mode is enabled // //yes dynamic mode turn off mma power in stop2 //no need to power off mma in either mma off mode(already off) //or static mma mode, as mma needs to remain alive //or in sync with stop in such case stop2 only stopclock mma above FAPI_TRY( p10_hcd_mma_poweroff( i_target ) ); } FAPI_DBG("Disable ECL2 Skewadjust via CPMS_CGCSR_[1:CL2_CLK_SYNC_ENABLE]"); FAPI_TRY( HCD_PUTMMIO_S( i_target, CPMS_CGCSR_WO_CLEAR, BIT64(1) ) ); FAPI_DBG("Check ECL2 Skewadjust Removed via CPMS_CGCSR[33:CL2_CLK_SYNC_DONE]"); l_timeout = HCD_ECL2_CLK_SYNC_DROP_POLL_TIMEOUT_HW_NS / HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_HW_NS; do { FAPI_TRY( HCD_GETMMIO_S( i_target, CPMS_CGCSR, l_scomData ) ); // use multicastOR to check 0 if( #ifdef USE_RUNN ( !l_attr_runn_mode ) && #endif ( SCOM_GET(33) == 0 ) ) { break; } fapi2::delay(HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_HW_NS, HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_SIM_CYCLE); } while( (--l_timeout) != 0 ); HCD_ASSERT4( ( #ifdef USE_RUNN l_attr_runn_mode ? ( SCOM_GET(33) == 0 ) : #endif (l_timeout != 0) ), ECL2_CLK_SYNC_DROP_TIMEOUT, set_ECL2_CLK_SYNC_DROP_POLL_TIMEOUT_HW_NS, HCD_ECL2_CLK_SYNC_DROP_POLL_TIMEOUT_HW_NS, set_CPMS_CGCSR, l_scomData, set_MC_CORE_TARGET, i_target, set_CORE_SELECT, i_target.getCoreSelect(), "ERROR: ECL2 Clock Sync Drop Timeout"); FAPI_DBG("Assert CORE_OFF_REQ[0:3] of Resonent Clocking via RCSCR[0:3]"); FAPI_TRY( HCD_PUTMMIO_Q( eq_target, QME_RCSCR_WO_OR, MMIO_LOAD32H( ( l_regions << SHIFT32(3) ) ) ) ); FAPI_DBG("Poll for CORE_CHANGE_DONE in RCSR[4:7]"); l_timeout = HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_TIMEOUT_HW_NS / HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_HW_NS; do { FAPI_TRY( HCD_GETMMIO_Q( eq_target, QME_RCSCR, l_mmioData ) ); MMIO_EXTRACT(4, 4, l_core_change_done); if( #ifdef USE_RUNN ( !l_attr_runn_mode ) && #endif ( (l_core_change_done & l_regions) == l_regions) ) { break; } fapi2::delay(HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_HW_NS, HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_SIM_CYCLE); } while( (--l_timeout) != 0 ); HCD_ASSERT4( ( #ifdef USE_RUNN l_attr_runn_mode ? ((l_core_change_done & l_regions) == l_regions) : #endif (l_timeout != 0) ), CORE_CHANGE_DONE_RESCLK_ENTRY_TIMEOUT, set_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_TIMEOUT_HW_NS, HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_TIMEOUT_HW_NS, set_CORE_CHANGE_DONE, l_core_change_done, set_MC_CORE_TARGET, i_target, set_CORE_SELECT, i_target.getCoreSelect(), "ERROR: Core Resclk Change Done Entry Timeout"); FAPI_DBG("Switch glsmux to refclk to save clock grid power via CPMS_CGCSR[11]"); FAPI_TRY( HCD_PUTMMIO_S( i_target, CPMS_CGCSR_WO_CLEAR, BIT64(11) ) ); fapi_try_exit: FAPI_INF("<<p10_hcd_core_stopgrid"); return fapi2::current_err; } <commit_msg>skip stopgrid execution on zero core IOSCM chips<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/corecache/p10_hcd_core_stopgrid.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2022 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p10_hcd_core_stopgrid.C /// @brief /// // *HWP HWP Owner : David Du <daviddu@us.ibm.com> // *HWP Backup HWP Owner : Greg Still <stillgs@us.ibm.com> // *HWP FW Owner : Prem Shanker Jha <premjha2@in.ibm.com> // *HWP Team : PM // *HWP Consumed by : SBE:QME // *HWP Level : 2 /// // EKB-Mirror-To: hw/ppe //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include "p10_hcd_core_stopgrid.H" #include "p10_hcd_mma_stopclocks.H" #include "p10_hcd_mma_poweroff.H" #include "p10_hcd_common.H" #ifdef __PPE_QME #include "p10_ppe_eq.H" #include "p10_ppe_c.H" using namespace scomt::ppe_eq; using namespace scomt::ppe_c; #else #include "p10_scom_eq.H" #include "p10_scom_c.H" using namespace scomt::eq; using namespace scomt::c; #endif //------------------------------------------------------------------------------ // Constant Definitions //------------------------------------------------------------------------------ enum P10_HCD_CORE_STOPGRID_CONSTANTS { HCD_ECL2_CLK_SYNC_DROP_POLL_TIMEOUT_HW_NS = 10000, // 10^4ns = 10us timeout HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_HW_NS = 100, // 100ns poll loop delay HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_SIM_CYCLE = 3200, // 3.2k sim cycle delay HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_TIMEOUT_HW_NS = 100000000, // 10^4ns = 10us timeout HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_HW_NS = 100, // 100ns poll loop delay HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_SIM_CYCLE = 3200, // 3.2k sim cycle delay }; //------------------------------------------------------------------------------ // Procedure: p10_hcd_core_stopgrid //------------------------------------------------------------------------------ fapi2::ReturnCode p10_hcd_core_stopgrid( const fapi2::Target < fapi2::TARGET_TYPE_CORE | fapi2::TARGET_TYPE_MULTICAST, fapi2::MULTICAST_AND > & i_target) { fapi2::Target < fapi2::TARGET_TYPE_EQ | fapi2::TARGET_TYPE_MULTICAST, fapi2::MULTICAST_AND > eq_target = i_target.getParent < fapi2::TARGET_TYPE_EQ | fapi2::TARGET_TYPE_MULTICAST > (); fapi2::buffer<buffer_t> l_mmioData = 0; fapi2::buffer<uint64_t> l_scomData = 0; uint32_t l_timeout = 0; uint32_t l_core_change_done = 0; uint32_t l_regions = i_target.getCoreSelect(); uint8_t l_attr_mma_poweroff_disable = 0; #ifndef __PPE_QME auto l_chip_target = i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>(); fapi2::ATTR_ZERO_CORE_CHIP_Type l_zero_core_chip = 0; #endif fapi2::Target < fapi2::TARGET_TYPE_SYSTEM > l_sys; FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_SYSTEM_MMA_POWEROFF_DISABLE, l_sys, l_attr_mma_poweroff_disable ) ); #ifdef USE_RUNN fapi2::ATTR_RUNN_MODE_Type l_attr_runn_mode; FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_RUNN_MODE, l_sys, l_attr_runn_mode ) ); #endif FAPI_INF(">>p10_hcd_core_stopgrid"); #ifndef __PPE_QME FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_ZERO_CORE_CHIP, l_chip_target, l_zero_core_chip ) ); if (l_zero_core_chip) { goto fapi_try_exit; } #endif // Also stop mma clocks after/with core clocks // not part of core_stopclocks for its pure usage at p10_stopclocks // this hwp is shared stop2,3,11 path FAPI_TRY( p10_hcd_mma_stopclocks( i_target ) ); // PowerON_Dis = 0 and PowerOFF_Dis = 0 do poweroff mma as in dynamic // PowerON_Dis = 0 and PowerOFF_Dis = 1 do not poweroff mma as not in dynamic // PowerON_Dis = 1 and PowerOFF_Dis = 0 do poweroff mma as in dynamic // PowerON_Dis = 1 and PowerOFF_Dis = 1 do not poweroff mma as not in dynamic if( !l_attr_mma_poweroff_disable ) { //also shutdown mma power here as for WOF benefit //only do so when dynamic mode is enabled // //yes dynamic mode turn off mma power in stop2 //no need to power off mma in either mma off mode(already off) //or static mma mode, as mma needs to remain alive //or in sync with stop in such case stop2 only stopclock mma above FAPI_TRY( p10_hcd_mma_poweroff( i_target ) ); } FAPI_DBG("Disable ECL2 Skewadjust via CPMS_CGCSR_[1:CL2_CLK_SYNC_ENABLE]"); FAPI_TRY( HCD_PUTMMIO_S( i_target, CPMS_CGCSR_WO_CLEAR, BIT64(1) ) ); FAPI_DBG("Check ECL2 Skewadjust Removed via CPMS_CGCSR[33:CL2_CLK_SYNC_DONE]"); l_timeout = HCD_ECL2_CLK_SYNC_DROP_POLL_TIMEOUT_HW_NS / HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_HW_NS; do { FAPI_TRY( HCD_GETMMIO_S( i_target, CPMS_CGCSR, l_scomData ) ); // use multicastOR to check 0 if( #ifdef USE_RUNN ( !l_attr_runn_mode ) && #endif ( SCOM_GET(33) == 0 ) ) { break; } fapi2::delay(HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_HW_NS, HCD_ECL2_CLK_SYNC_DROP_POLL_DELAY_SIM_CYCLE); } while( (--l_timeout) != 0 ); HCD_ASSERT4( ( #ifdef USE_RUNN l_attr_runn_mode ? ( SCOM_GET(33) == 0 ) : #endif (l_timeout != 0) ), ECL2_CLK_SYNC_DROP_TIMEOUT, set_ECL2_CLK_SYNC_DROP_POLL_TIMEOUT_HW_NS, HCD_ECL2_CLK_SYNC_DROP_POLL_TIMEOUT_HW_NS, set_CPMS_CGCSR, l_scomData, set_MC_CORE_TARGET, i_target, set_CORE_SELECT, i_target.getCoreSelect(), "ERROR: ECL2 Clock Sync Drop Timeout"); FAPI_DBG("Assert CORE_OFF_REQ[0:3] of Resonent Clocking via RCSCR[0:3]"); FAPI_TRY( HCD_PUTMMIO_Q( eq_target, QME_RCSCR_WO_OR, MMIO_LOAD32H( ( l_regions << SHIFT32(3) ) ) ) ); FAPI_DBG("Poll for CORE_CHANGE_DONE in RCSR[4:7]"); l_timeout = HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_TIMEOUT_HW_NS / HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_HW_NS; do { FAPI_TRY( HCD_GETMMIO_Q( eq_target, QME_RCSCR, l_mmioData ) ); MMIO_EXTRACT(4, 4, l_core_change_done); if( #ifdef USE_RUNN ( !l_attr_runn_mode ) && #endif ( (l_core_change_done & l_regions) == l_regions) ) { break; } fapi2::delay(HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_HW_NS, HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_DELAY_SIM_CYCLE); } while( (--l_timeout) != 0 ); HCD_ASSERT4( ( #ifdef USE_RUNN l_attr_runn_mode ? ((l_core_change_done & l_regions) == l_regions) : #endif (l_timeout != 0) ), CORE_CHANGE_DONE_RESCLK_ENTRY_TIMEOUT, set_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_TIMEOUT_HW_NS, HCD_CORE_CHANGE_DONE_RESCLK_ENTRY_POLL_TIMEOUT_HW_NS, set_CORE_CHANGE_DONE, l_core_change_done, set_MC_CORE_TARGET, i_target, set_CORE_SELECT, i_target.getCoreSelect(), "ERROR: Core Resclk Change Done Entry Timeout"); FAPI_DBG("Switch glsmux to refclk to save clock grid power via CPMS_CGCSR[11]"); FAPI_TRY( HCD_PUTMMIO_S( i_target, CPMS_CGCSR_WO_CLEAR, BIT64(11) ) ); fapi_try_exit: FAPI_INF("<<p10_hcd_core_stopgrid"); return fapi2::current_err; } <|endoftext|>
<commit_before>/* * (C) Copyright 2016 Mirantis Inc. * * 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. * * Author: * Radoslaw Zarzynski <rzarzynski@mirantis.com> */ #include <cstddef> #include <type_traits> #include <tuple> template <class TypeT, size_t MaxSize> class static_ptr { /* All variants of static_ptr are friends. */ template <class Tf, size_t Sf> friend class static_ptr; public: typedef TypeT* pointer; typedef TypeT element_type; private: /* Virtual constructors for C++... */ struct LifeCycleManager { virtual void clone_obj(void *, TypeT&&) const = 0; virtual void clone_lcm(void *) const = 0; virtual void delete_obj(TypeT&) const = 0; }; typedef const LifeCycleManager* pointer_lcm; unsigned char storage[MaxSize]; unsigned char storage_lcm[sizeof(LifeCycleManager)]; bool is_empty = true; pointer_lcm get_lcm() noexcept { return reinterpret_cast<pointer_lcm>(storage_lcm); } template < class Te, class... Args, /* Dummy template parameter solely for SFINAE. */ typename std::enable_if< std::is_base_of<TypeT, Te>::value>::type* = nullptr > void _emplace(Args&&... args) { /* Life cycle manager for the type Te. Due to nesting this class, each * instance of the emplace template will receive its own LCM with info * about the concrete Te deeply buried inside. That's the way how we * support "virtual constructors" and call a proper destructor even if * TypeT hasn't declared its dtor as virtual. */ struct LCMe : public LifeCycleManager { virtual void clone_obj(void* p, TypeT&& u) const override { new (p) Te(static_cast<Te&&>(u)); } virtual void clone_lcm(void* p) const override { new (p) LCMe; } virtual void delete_obj(TypeT& t) const override { static_cast<Te&>(t).~Te(); } }; /* The storage_lcm shouldn't store anything more than the VPTR. */ new (storage_lcm) LCMe(); new (storage) Te(std::forward<Args>(args)...); is_empty = false; } /* Helpers for make_obj. */ template<int ...> struct seq { }; template<int N, int ...S> struct gens : gens<N-1, N-1, S...> { }; template<int ...S> struct gens<1, S...> { typedef seq<S...> type; }; template<class Type, class Tuple, int ...S> void _make_obj(Tuple&& tup, seq<S...>) { _emplace<Type>(std::get<S>(tup) ...); } template <class Tf, size_t Sf> void _clone(static_ptr<Tf, Sf>&& rhs) { typename static_ptr<Tf, Sf>::pointer rhs_obj_ptr = rhs.get(); if (rhs_obj_ptr) { rhs.get_lcm()->clone_obj(storage, std::move(*rhs_obj_ptr)); rhs.get_lcm()->clone_lcm(storage_lcm); /* Using the already std::moved rhs_obj_ptr is fully intensional. */ rhs.is_empty = true; rhs.get_lcm()->delete_obj(*rhs_obj_ptr); this->is_empty = false; } } public: /* All necessary things are initialized in the definitions. NOTE: we won't * zeroize or touch the storage in any other way as the only thing it could * bring is an impact on performance. */ static_ptr() noexcept = default; /* Constructor: the nullptr case. */ static_ptr(nullptr_t) noexcept : static_ptr() {}; /* Constructor: move from another instance of absolutely the same * variant of static_ptr. In other words, rhs must be an instance * of static<TypeT, MaxSize). The constructor is present only because * of the Return Value Optimization. */ static_ptr(static_ptr&& rhs) { _clone(std::move(rhs)); } /* Constructor: move from a compatible variant of static_ptr. Variants * are compatible only if: * 1) a source one is smaller or equal in terms of available storage * size than a destination one AND * 2) a destination one encapsulates a type that stays in is_base_of * relationship with type stored by a source one. */ template <class Tf, size_t Sf> static_ptr(static_ptr<Tf, Sf>&& rhs) { static_assert(MaxSize >= Sf, "constructed from too big static_ptr instance"); static_assert(std::is_base_of<TypeT, Tf>::value, "constructed from non-related static_ptr instance"); _clone(std::move(rhs)); } /* Constructor: the from-make_static case. */ template <class T> static_ptr(T&& tup) { using TypePtr = typename std::tuple_element<0, T>::type; using Type = typename std::remove_pointer<TypePtr>::type; constexpr size_t tup_size = std::tuple_size<T>::value; _make_obj<Type>(std::move(tup), typename gens< tup_size >::type()); } /* Assignment: move from a compatible variant of static_ptr. For details * please refer to the documentation of the corresponding constructor. */ template <class Tf, size_t Sf> static_ptr& operator=(static_ptr<Tf, Sf>&& rhs) { static_assert(MaxSize >= Sf, "assigned from too big static_ptr instance"); static_assert(std::is_base_of<TypeT, Tf>::value, "assigned from non-related static_ptr instance"); /* First, release (destroy) the currently stored object if necessary. */ pointer this_obj_ptr = this->get(); if (this_obj_ptr) { this->get_lcm()->delete_obj(*this_obj_ptr); this->is_empty = true; } /* Second, MoveConstruct a new object using our own storage but basing * on the object hold by rhs. */ _clone(std::move(rhs)); return *this; } /* Let's mimic the std::unique_ptr's behaviour. It's very useful to say to * the world who controls the lifetime of the contained object. */ static_ptr(const static_ptr&) = delete; static_ptr& operator=(const static_ptr&) = delete; ~static_ptr() { auto obj = get(); if (obj) { get_lcm()->delete_obj(*obj); } } TypeT* operator->() { return get(); } pointer get() noexcept { return is_empty ? nullptr : reinterpret_cast<pointer>(storage); } template < class Te, class... Args, /* Dummy template parameter solely for SFINAE. */ typename std::enable_if< std::is_base_of<TypeT, Te>::value>::type* = nullptr > bool emplace(Args&&... args) { /* The public emplace method can be called on empty static_pointer only. */ if (is_empty) { _emplace<Te>(std::forward<Args>(args)...); } return is_empty; } }; template <class First> constexpr size_t maxsizeof() { return sizeof(First); } template <class First, class Second, class... Args> constexpr size_t maxsizeof() { return maxsizeof<First>() > maxsizeof<Second, Args...>() ? maxsizeof<First>() : maxsizeof<Second, Args...>(); } /* C++ doesn't allow to explicitly specify parameters for template constructor * of a class template. They can be deduced only. Because of the restriction we * need a helper function to construct an instance of static_ptr::element_type * directly in the memory under static_ptr::storage_obj - without spawning any * temporary of static_ptr::element_type along the way. * * The idea is to prepare a std::tuple containing all information necessary to * create an object in its final destination and pass it to specific template * constructor of static_ptr that can live with the deduction-only limitation. * The std::tuple object should be optimized out thanks to the RVO. * * Another benefit is the similarity to std::make_shared and std::make_unique * functions. */ template <class T, class... Args> std::tuple<T*, Args...> make_static(Args&&... args) { /* As C++ doesn't offer a template constructor for a class template it's * impossible to construct the static_ptr::element_type inside */ return std::forward_as_tuple(static_cast<T*>(nullptr), std::forward<Args>(args)...); } <commit_msg>Improve naming and const-correctness in static_ptr.hpp.<commit_after>/* * (C) Copyright 2016 Mirantis Inc. * * 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. * * Author: * Radoslaw Zarzynski <rzarzynski@mirantis.com> */ #include <cstddef> #include <type_traits> #include <tuple> template <class TypeT, size_t MaxSize> class static_ptr { /* All variants of static_ptr are friends. */ template <class Tf, size_t Sf> friend class static_ptr; public: typedef TypeT* pointer; typedef TypeT element_type; static constexpr size_t element_max_size = MaxSize; private: /* Virtual constructors for C++... */ struct LifeCycleManager { virtual void clone_obj(void *, element_type&&) const = 0; virtual void clone_lcm(void *) const = 0; virtual void delete_obj(element_type&) const = 0; }; mutable unsigned char storage_obj[element_max_size]; unsigned char storage_lcm[sizeof(LifeCycleManager)]; bool is_empty = true; const LifeCycleManager& get_lcm() noexcept { return *reinterpret_cast<const LifeCycleManager*>(storage_lcm); } template < class Te, class... Args, /* Dummy template parameter solely for SFINAE. */ typename std::enable_if< std::is_base_of<element_type, Te>::value>::type* = nullptr > void _emplace(Args&&... args) { /* Life cycle manager for the type Te. Due to nesting this class, each * instance of the emplace template will receive its own LCM with info * about the concrete Te deeply buried inside. That's the way how we * support "virtual constructors" and call a proper destructor even if * element_type hasn't declared its dtor as virtual. */ struct LCMe : public LifeCycleManager { virtual void clone_obj(void* p, element_type&& u) const override { new (p) Te(static_cast<Te&&>(u)); } virtual void clone_lcm(void* p) const override { new (p) LCMe; } virtual void delete_obj(element_type& t) const override { static_cast<Te&>(t).~Te(); } }; /* The storage_lcm shouldn't store anything more than the VPTR. */ new (storage_lcm) LCMe(); new (storage_obj) Te(std::forward<Args>(args)...); is_empty = false; } /* Helpers for make_obj. */ template<int ...> struct seq { }; template<int N, int ...S> struct gens : gens<N-1, N-1, S...> { }; template<int ...S> struct gens<1, S...> { typedef seq<S...> type; }; template<class Type, class Tuple, int ...S> void _make_obj(Tuple&& tup, seq<S...>) { _emplace<Type>(std::get<S>(tup) ...); } template <class Tf, size_t Sf> void _transfer_obj(static_ptr<Tf, Sf>&& rhs) { typename static_ptr<Tf, Sf>::pointer rhs_obj_ptr = rhs.get(); if (rhs_obj_ptr) { rhs.get_lcm().clone_obj(storage_obj, std::move(*rhs_obj_ptr)); rhs.get_lcm().clone_lcm(storage_lcm); /* Using the already std::moved rhs_obj_ptr is fully intensional. */ rhs.is_empty = true; rhs.get_lcm().delete_obj(*rhs_obj_ptr); this->is_empty = false; } } public: /* All necessary things are initialized in the definitions. NOTE: we won't * zeroize or touch the storage in any other way as the only thing it could * bring is an impact on performance. */ static_ptr() noexcept = default; /* Constructor: the nullptr case. */ static_ptr(nullptr_t) noexcept : static_ptr() {}; /* Constructor: move from another instance of absolutely the same * variant of static_ptr. In other words, rhs must be an instance * of static<TypeT, MaxSize). The constructor is present only because * of the Return Value Optimization. */ static_ptr(static_ptr&& rhs) { _transfer_obj(std::move(rhs)); } /* Constructor: move from a compatible variant of static_ptr. Variants * are compatible only if: * 1) a source one is smaller or equal in terms of available storage * size than a destination one AND * 2) a destination one encapsulates a type that stays in is_base_of * relationship with type stored by a source one. */ template <class Tf, size_t Sf> static_ptr(static_ptr<Tf, Sf>&& rhs) { static_assert(element_max_size >= Sf, "constructed from too big static_ptr instance"); static_assert(std::is_base_of<element_type, Tf>::value, "constructed from non-related static_ptr instance"); _transfer_obj(std::move(rhs)); } /* Constructor: the from-make_static case. */ template <class T> static_ptr(T&& tup) { using TypePtr = typename std::tuple_element<0, T>::type; using Type = typename std::remove_pointer<TypePtr>::type; constexpr size_t tup_size = std::tuple_size<T>::value; _make_obj<Type>(std::move(tup), typename gens<tup_size>::type()); } /* Assignment: move from a compatible variant of static_ptr. For details * please refer to the documentation of the corresponding constructor. */ template <class Tf, size_t Sf> static_ptr& operator=(static_ptr<Tf, Sf>&& rhs) { static_assert(element_max_size >= Sf, "assigned from too big static_ptr instance"); static_assert(std::is_base_of<element_type, Tf>::value, "assigned from non-related static_ptr instance"); /* First, release (destroy) the currently stored object if necessary. */ pointer this_obj_ptr = this->get(); if (this_obj_ptr) { this->get_lcm().delete_obj(*this_obj_ptr); this->is_empty = true; } /* Second, MoveConstruct a new object using our own storage but basing * on the object hold by rhs. */ _transfer_obj(std::move(rhs)); return *this; } /* Let's mimic the std::unique_ptr's behaviour. It's very useful to say to * the world who controls the lifetime of the contained object. */ static_ptr(const static_ptr&) = delete; static_ptr& operator=(const static_ptr&) = delete; ~static_ptr() { auto obj = get(); if (obj) { get_lcm().delete_obj(*obj); } } pointer operator->() const { return get(); } pointer get() const noexcept { return is_empty ? nullptr : reinterpret_cast<pointer>(storage_obj); } template < class Te, class... Args, /* Dummy template parameter solely for SFINAE. */ typename std::enable_if< std::is_base_of<element_type, Te>::value>::type* = nullptr > bool emplace(Args&&... args) { /* The public emplace method can be called on empty static_pointer only. */ if (is_empty) { _emplace<Te>(std::forward<Args>(args)...); } return is_empty; } }; template <class First> constexpr size_t maxsizeof() { return sizeof(First); } template <class First, class Second, class... Args> constexpr size_t maxsizeof() { return maxsizeof<First>() > maxsizeof<Second, Args...>() ? maxsizeof<First>() : maxsizeof<Second, Args...>(); } /* C++ doesn't allow to explicitly specify parameters for template constructor * of a class template. They can be deduced only. Because of the restriction we * need a helper function to construct an instance of static_ptr::element_type * directly in the memory under static_ptr::storage_obj - without spawning any * temporary of static_ptr::element_type along the way. * * The idea is to prepare a std::tuple containing all information necessary to * create an object in its final destination and pass it to specific template * constructor of static_ptr that can live with the deduction-only limitation. * The std::tuple object should be optimized out thanks to the RVO. * * Another benefit is the similarity to std::make_shared and std::make_unique * functions. */ template <class T, class... Args> std::tuple<T*, Args...> make_static(Args&&... args) { /* As C++ doesn't offer a template constructor for a class template it's * impossible to construct the static_ptr::element_type inside */ return std::forward_as_tuple(static_cast<T*>(nullptr), std::forward<Args>(args)...); } <|endoftext|>
<commit_before>/** * Zillians MMO * Copyright (C) 2007-2011 Zillians.com, Inc. * For more information see http://www.zillians.com * * Zillians MMO is the library and runtime for massive multiplayer online game * development in utility computing model, which runs as a service for every * developer to build their virtual world running on our GPU-assisted machines. * * This is a close source library intended to be used solely within Zillians.com * * 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 * COPYRIGHT HOLDER(S) 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. */ #include "language/tree/basic/Identifier.h" #include "language/tree/basic/TypeSpecifier.h" #include "language/tree/declaration/TypenameDecl.h" namespace zillians { namespace language { namespace tree { SimpleIdentifier::SimpleIdentifier() { } SimpleIdentifier::SimpleIdentifier(const std::wstring& s) : name(s) { } std::wstring SimpleIdentifier::toString() const { return name; } bool SimpleIdentifier::isEmpty() const { return (name.length() == 0); } bool SimpleIdentifier::isEqualImpl(const ASTNode& rhs, ASTNodeSet& visited) const { BEGIN_COMPARE() COMPARE_MEMBER(name) END_COMPARE() } bool SimpleIdentifier::replaceUseWith(const ASTNode& from, const ASTNode& to, bool update_parent) { BEGIN_REPLACE() REPLACE_USE_WITH(name) END_REPLACE() } ASTNode* SimpleIdentifier::clone() const { return new SimpleIdentifier(name); } } } } namespace zillians { namespace language { namespace tree { NestedIdentifier::NestedIdentifier() { } std::wstring NestedIdentifier::toString() const { std::wstring t; foreach(i, identifier_list) { t += (*i)->toString(); if(!is_end_of_foreach(i, identifier_list)) t += L"."; } return t; } bool NestedIdentifier::isEmpty() const { foreach(i, identifier_list) { if(!(*i)->isEmpty()) return false; } return true; } void NestedIdentifier::appendIdentifier(Identifier* id) { id->parent = this; identifier_list.push_back(id); } bool NestedIdentifier::isEqualImpl(const ASTNode& rhs, ASTNodeSet& visited) const { BEGIN_COMPARE() COMPARE_MEMBER(identifier_list) END_COMPARE() } bool NestedIdentifier::replaceUseWith(const ASTNode& from, const ASTNode& to, bool update_parent) { BEGIN_REPLACE() REPLACE_USE_WITH(identifier_list) END_REPLACE() } ASTNode* NestedIdentifier::clone() const { NestedIdentifier* cloned = new NestedIdentifier(); foreach(i, identifier_list) cloned->appendIdentifier(cast<Identifier>((*i)->clone())); return cloned; } } } } namespace zillians { namespace language { namespace tree { TemplatedIdentifier::TemplatedIdentifier() { } TemplatedIdentifier::TemplatedIdentifier(Usage::type type, Identifier* id) : type(type), id(id) { id->parent = this; } std::wstring TemplatedIdentifier::toString() const { std::wstring t; t += id->toString(); t += L"<"; foreach(i, templated_type_list) { t += (*i)->name->toString(); if((*i)->specialized_type) { t += L":"; t += (*i)->specialized_type->toString(); } if(!is_end_of_foreach(i, templated_type_list)) t += L","; } t += L">"; return t; } bool TemplatedIdentifier::isVariadic() const { auto last = *templated_type_list.rbegin(); return last->name->toString() == L"..."; } bool TemplatedIdentifier::isFullySpecialized() const { foreach(i, templated_type_list) { if(!(*i)->specialized_type) { return false; } else { if((*i)->specialized_type->type == TypeSpecifier::ReferredType::UNSPECIFIED) { if(isa<TemplatedIdentifier>((*i)->specialized_type->referred.unspecified)) { if(!cast<TemplatedIdentifier>((*i)->specialized_type->referred.unspecified)->isFullySpecialized()) { return false; } } } } } return true; } void TemplatedIdentifier::specialize() { if(type == Usage::FORMAL_PARAMETER) { foreach(i, templated_type_list) { if(!(*i)->specialized_type) { TypeSpecifier* specialized_type = NULL; if(isa<TemplatedIdentifier>((*i)->name)) { TemplatedIdentifier* duplicated_id = cast<TemplatedIdentifier>((*i)->name->clone()); duplicated_id->specialize(); specialized_type = new TypeSpecifier(duplicated_id); specialized_type->parent = this; } else { specialized_type = new TypeSpecifier((*i)->name->clone()); specialized_type->parent = this; } SimpleIdentifier* dummy_identifier = new SimpleIdentifier(L"_"); (*i)->replaceUseWith(*((*i)->name), *dummy_identifier); (*i)->specialized_type = specialized_type; } } } } bool TemplatedIdentifier::isEmpty() const { if(id->isEmpty() && templated_type_list.size() == 0) return true; else return false; } void TemplatedIdentifier::setIdentifier(Identifier* identifier) { if(id) id->parent = NULL; id = identifier; id->parent = this; } void TemplatedIdentifier::append(TypenameDecl* type) { type->parent = this; templated_type_list.push_back(type); } bool TemplatedIdentifier::isEqualImpl(const ASTNode& rhs, ASTNodeSet& visited) const { BEGIN_COMPARE() COMPARE_MEMBER(type) COMPARE_MEMBER(id) COMPARE_MEMBER(templated_type_list) END_COMPARE() } bool TemplatedIdentifier::replaceUseWith(const ASTNode& from, const ASTNode& to, bool update_parent) { BEGIN_REPLACE() REPLACE_USE_WITH(type) REPLACE_USE_WITH(id) REPLACE_USE_WITH(templated_type_list) END_REPLACE() } ASTNode* TemplatedIdentifier::clone() const { TemplatedIdentifier* cloned = new TemplatedIdentifier(type, (id) ? cast<Identifier>(id->clone()) : NULL); foreach(i, templated_type_list) cloned->append(cast<TypenameDecl>((*i)->clone())); return cloned; } } } } <commit_msg>Fix restructure specialize wrong parent bug<commit_after>/** * Zillians MMO * Copyright (C) 2007-2011 Zillians.com, Inc. * For more information see http://www.zillians.com * * Zillians MMO is the library and runtime for massive multiplayer online game * development in utility computing model, which runs as a service for every * developer to build their virtual world running on our GPU-assisted machines. * * This is a close source library intended to be used solely within Zillians.com * * 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 * COPYRIGHT HOLDER(S) 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. */ #include "language/tree/basic/Identifier.h" #include "language/tree/basic/TypeSpecifier.h" #include "language/tree/declaration/TypenameDecl.h" namespace zillians { namespace language { namespace tree { SimpleIdentifier::SimpleIdentifier() { } SimpleIdentifier::SimpleIdentifier(const std::wstring& s) : name(s) { } std::wstring SimpleIdentifier::toString() const { return name; } bool SimpleIdentifier::isEmpty() const { return (name.length() == 0); } bool SimpleIdentifier::isEqualImpl(const ASTNode& rhs, ASTNodeSet& visited) const { BEGIN_COMPARE() COMPARE_MEMBER(name) END_COMPARE() } bool SimpleIdentifier::replaceUseWith(const ASTNode& from, const ASTNode& to, bool update_parent) { BEGIN_REPLACE() REPLACE_USE_WITH(name) END_REPLACE() } ASTNode* SimpleIdentifier::clone() const { return new SimpleIdentifier(name); } } } } namespace zillians { namespace language { namespace tree { NestedIdentifier::NestedIdentifier() { } std::wstring NestedIdentifier::toString() const { std::wstring t; foreach(i, identifier_list) { t += (*i)->toString(); if(!is_end_of_foreach(i, identifier_list)) t += L"."; } return t; } bool NestedIdentifier::isEmpty() const { foreach(i, identifier_list) { if(!(*i)->isEmpty()) return false; } return true; } void NestedIdentifier::appendIdentifier(Identifier* id) { id->parent = this; identifier_list.push_back(id); } bool NestedIdentifier::isEqualImpl(const ASTNode& rhs, ASTNodeSet& visited) const { BEGIN_COMPARE() COMPARE_MEMBER(identifier_list) END_COMPARE() } bool NestedIdentifier::replaceUseWith(const ASTNode& from, const ASTNode& to, bool update_parent) { BEGIN_REPLACE() REPLACE_USE_WITH(identifier_list) END_REPLACE() } ASTNode* NestedIdentifier::clone() const { NestedIdentifier* cloned = new NestedIdentifier(); foreach(i, identifier_list) cloned->appendIdentifier(cast<Identifier>((*i)->clone())); return cloned; } } } } namespace zillians { namespace language { namespace tree { TemplatedIdentifier::TemplatedIdentifier() { } TemplatedIdentifier::TemplatedIdentifier(Usage::type type, Identifier* id) : type(type), id(id) { id->parent = this; } std::wstring TemplatedIdentifier::toString() const { std::wstring t; t += id->toString(); t += L"<"; foreach(i, templated_type_list) { t += (*i)->name->toString(); if((*i)->specialized_type) { t += L":"; t += (*i)->specialized_type->toString(); } if(!is_end_of_foreach(i, templated_type_list)) t += L","; } t += L">"; return t; } bool TemplatedIdentifier::isVariadic() const { auto last = *templated_type_list.rbegin(); return last->name->toString() == L"..."; } bool TemplatedIdentifier::isFullySpecialized() const { foreach(i, templated_type_list) { if(!(*i)->specialized_type) { return false; } else { if((*i)->specialized_type->type == TypeSpecifier::ReferredType::UNSPECIFIED) { if(isa<TemplatedIdentifier>((*i)->specialized_type->referred.unspecified)) { if(!cast<TemplatedIdentifier>((*i)->specialized_type->referred.unspecified)->isFullySpecialized()) { return false; } } } } } return true; } void TemplatedIdentifier::specialize() { if(type == Usage::FORMAL_PARAMETER) { foreach(i, templated_type_list) { if(!(*i)->specialized_type) { TypeSpecifier* specialized_type = NULL; if(isa<TemplatedIdentifier>((*i)->name)) { TemplatedIdentifier* duplicated_id = cast<TemplatedIdentifier>((*i)->name->clone()); duplicated_id->specialize(); specialized_type = new TypeSpecifier(duplicated_id); specialized_type->parent = *i; } else { specialized_type = new TypeSpecifier((*i)->name->clone()); specialized_type->parent = *i; } SimpleIdentifier* dummy_identifier = new SimpleIdentifier(L"_"); (*i)->replaceUseWith(*((*i)->name), *dummy_identifier); (*i)->specialized_type = specialized_type; } } } } bool TemplatedIdentifier::isEmpty() const { if(id->isEmpty() && templated_type_list.size() == 0) return true; else return false; } void TemplatedIdentifier::setIdentifier(Identifier* identifier) { if(id) id->parent = NULL; id = identifier; id->parent = this; } void TemplatedIdentifier::append(TypenameDecl* type) { type->parent = this; templated_type_list.push_back(type); } bool TemplatedIdentifier::isEqualImpl(const ASTNode& rhs, ASTNodeSet& visited) const { BEGIN_COMPARE() COMPARE_MEMBER(type) COMPARE_MEMBER(id) COMPARE_MEMBER(templated_type_list) END_COMPARE() } bool TemplatedIdentifier::replaceUseWith(const ASTNode& from, const ASTNode& to, bool update_parent) { BEGIN_REPLACE() REPLACE_USE_WITH(type) REPLACE_USE_WITH(id) REPLACE_USE_WITH(templated_type_list) END_REPLACE() } ASTNode* TemplatedIdentifier::clone() const { TemplatedIdentifier* cloned = new TemplatedIdentifier(type, (id) ? cast<Identifier>(id->clone()) : NULL); foreach(i, templated_type_list) cloned->append(cast<TypenameDecl>((*i)->clone())); return cloned; } } } } <|endoftext|>
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 by Apex.AI Inc. 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. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_UTILS_CXX_VARIANT_INL #define IOX_UTILS_CXX_VARIANT_INL #include "iceoryx_utils/cxx/variant.hpp" namespace iox { namespace cxx { template <typename... Types> inline variant<Types...>::variant(const variant& f_rhs) noexcept : m_type_index(f_rhs.m_type_index) { if (m_type_index != INVALID_VARIANT_INDEX) { internal::call_at_index<0, Types...>::copyConstructor( m_type_index, const_cast<internal::byte_t*>(f_rhs.m_storage), m_storage); } } template <typename... Types> template <uint64_t N, typename... CTorArguments> inline variant<Types...>::variant(const in_place_index<N>&, CTorArguments&&... f_args) noexcept { emplace_at_index<N>(std::forward<CTorArguments>(f_args)...); } template <typename... Types> template <typename T, typename... CTorArguments> inline variant<Types...>::variant(const in_place_type<T>&, CTorArguments&&... f_args) noexcept { emplace<T>(std::forward<CTorArguments>(f_args)...); } template <typename... Types> variant<Types...>& variant<Types...>::operator=(const variant& f_rhs) noexcept { if (this != &f_rhs) { if (m_type_index != f_rhs.m_type_index) { call_element_destructor(); m_type_index = f_rhs.m_type_index; if (m_type_index != INVALID_VARIANT_INDEX) { internal::call_at_index<0, Types...>::copyConstructor( m_type_index, const_cast<internal::byte_t*>(f_rhs.m_storage), m_storage); } } else { if (m_type_index != INVALID_VARIANT_INDEX) { internal::call_at_index<0, Types...>::copy( m_type_index, const_cast<internal::byte_t*>(f_rhs.m_storage), m_storage); } } } return *this; } template <typename... Types> variant<Types...>::variant(variant&& f_rhs) noexcept : m_type_index{std::move(f_rhs.m_type_index)} { if (m_type_index != INVALID_VARIANT_INDEX) { internal::call_at_index<0, Types...>::moveConstructor(m_type_index, f_rhs.m_storage, m_storage); } } template <typename... Types> variant<Types...>& variant<Types...>::operator=(variant&& f_rhs) noexcept { if (this != &f_rhs) { if (m_type_index != f_rhs.m_type_index) { call_element_destructor(); m_type_index = std::move(f_rhs.m_type_index); if (m_type_index != INVALID_VARIANT_INDEX) { internal::call_at_index<0, Types...>::moveConstructor(m_type_index, f_rhs.m_storage, m_storage); } } else { if (m_type_index != INVALID_VARIANT_INDEX) { internal::call_at_index<0, Types...>::move(m_type_index, f_rhs.m_storage, m_storage); } } } return *this; } template <typename... Types> inline variant<Types...>::~variant() noexcept { call_element_destructor(); } template <typename... Types> void variant<Types...>::call_element_destructor() noexcept { if (m_type_index != INVALID_VARIANT_INDEX) { internal::call_at_index<0, Types...>::destructor(m_type_index, m_storage); } } template <typename... Types> template <typename T> inline typename std::enable_if<!std::is_same<T, variant<Types...>&>::value, variant<Types...>>::type& variant<Types...>::operator=(T&& f_rhs) noexcept { if (m_type_index == INVALID_VARIANT_INDEX) { m_type_index = internal::get_index_of_type<0, T, Types...>::index; } if (!has_bad_variant_element_access<T>()) { auto storage = static_cast<T*>(static_cast<void*>(m_storage)); *storage = (std::forward<T>(f_rhs)); } else { error_message(__PRETTY_FUNCTION__, "wrong variant type assignment, another type is already " "set in variant"); } return *this; } template <typename... Types> template <uint64_t TypeIndex, typename... CTorArguments> inline bool variant<Types...>::emplace_at_index(CTorArguments&&... f_args) noexcept { static_assert(TypeIndex <= sizeof...(Types), "TypeIndex is out of bounds"); using T = typename internal::get_type_at_index<0, TypeIndex, Types...>::type; call_element_destructor(); new (m_storage) T(std::forward<CTorArguments>(f_args)...); m_type_index = TypeIndex; return true; } template <typename... Types> template <typename T, typename... CTorArguments> inline bool variant<Types...>::emplace(CTorArguments&&... f_args) noexcept { if (m_type_index != INVALID_VARIANT_INDEX && has_bad_variant_element_access<T>()) { error_message(__PRETTY_FUNCTION__, "wrong variant type emplacement, another type is already " "set in variant"); return false; } if (m_type_index != INVALID_VARIANT_INDEX) { call_element_destructor(); } new (m_storage) T(std::forward<CTorArguments>(f_args)...); m_type_index = internal::get_index_of_type<0, T, Types...>::index; return true; } template <typename... Types> template <uint64_t TypeIndex> inline typename internal::get_type_at_index<0, TypeIndex, Types...>::type* variant<Types...>::get_at_index() noexcept { if (TypeIndex != m_type_index) { return nullptr; } using T = typename internal::get_type_at_index<0, TypeIndex, Types...>::type; return static_cast<T*>(static_cast<void*>(m_storage)); } template <typename... Types> template <uint64_t TypeIndex> inline const typename internal::get_type_at_index<0, TypeIndex, Types...>::type* variant<Types...>::get_at_index() const noexcept { using T = typename internal::get_type_at_index<0, TypeIndex, Types...>::type; return const_cast<const T*>(const_cast<variant*>(this)->get_at_index<TypeIndex>()); } template <typename... Types> template <typename T> inline const T* variant<Types...>::get() const noexcept { if (has_bad_variant_element_access<T>()) { return nullptr; } else { return static_cast<const T*>(static_cast<const void*>(m_storage)); } } template <typename... Types> template <typename T> inline T* variant<Types...>::get() noexcept { return const_cast<T*>(const_cast<const variant*>(this)->get<T>()); } template <typename... Types> template <typename T> inline T* variant<Types...>::get_if(T* f_default_value) noexcept { return const_cast<T*>(const_cast<const variant*>(this)->get_if<T>(const_cast<const T*>(f_default_value))); } template <typename... Types> template <typename T> inline const T* variant<Types...>::get_if(const T* f_default_value) const noexcept { if (has_bad_variant_element_access<T>()) { return f_default_value; } return this->get<T>(); } template <typename... Types> constexpr size_t variant<Types...>::index() const noexcept { return m_type_index; } template <typename... Types> template <typename T> inline bool variant<Types...>::has_bad_variant_element_access() const noexcept { static_assert(internal::does_contain_type<T, Types...>::value, "variant does not contain given type"); return (m_type_index != internal::get_index_of_type<0, T, Types...>::index); } template <typename... Types> inline void variant<Types...>::error_message(const char* f_source, const char* f_msg) noexcept { std::cerr << f_source << " ::: " << f_msg << std::endl; } template <typename T, typename... Types> inline constexpr bool holds_alternative(const variant<Types...>& f_variant) noexcept { return f_variant.template get<T>() != nullptr; } } // namespace cxx } // namespace iox #endif // IOX_UTILS_CXX_VARIANT_INL <commit_msg>Iox-#759 improve helix qac parsing coverage workaround to improve Helix QAC coverage by allowing it to parse this bit of code<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 by Apex.AI Inc. 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. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_UTILS_CXX_VARIANT_INL #define IOX_UTILS_CXX_VARIANT_INL #include "iceoryx_utils/cxx/variant.hpp" namespace iox { namespace cxx { template <typename... Types> inline variant<Types...>::variant(const variant& f_rhs) noexcept : m_type_index(f_rhs.m_type_index) { if (m_type_index != INVALID_VARIANT_INDEX) { internal::call_at_index<0, Types...>::copyConstructor( m_type_index, const_cast<internal::byte_t*>(f_rhs.m_storage), m_storage); } } template <typename... Types> template <uint64_t N, typename... CTorArguments> inline variant<Types...>::variant(const in_place_index<N>&, CTorArguments&&... f_args) noexcept { emplace_at_index<N>(std::forward<CTorArguments>(f_args)...); } template <typename... Types> template <typename T, typename... CTorArguments> inline variant<Types...>::variant(const in_place_type<T>&, CTorArguments&&... f_args) noexcept { emplace<T>(std::forward<CTorArguments>(f_args)...); } template <typename... Types> variant<Types...>& variant<Types...>::operator=(const variant& f_rhs) noexcept { if (this != &f_rhs) { if (m_type_index != f_rhs.m_type_index) { call_element_destructor(); m_type_index = f_rhs.m_type_index; if (m_type_index != INVALID_VARIANT_INDEX) { internal::call_at_index<0, Types...>::copyConstructor( m_type_index, const_cast<internal::byte_t*>(f_rhs.m_storage), m_storage); } } else { if (m_type_index != INVALID_VARIANT_INDEX) { internal::call_at_index<0, Types...>::copy( m_type_index, const_cast<internal::byte_t*>(f_rhs.m_storage), m_storage); } } } return *this; } template <typename... Types> variant<Types...>::variant(variant&& f_rhs) noexcept : m_type_index{std::move(f_rhs.m_type_index)} { if (m_type_index != INVALID_VARIANT_INDEX) { internal::call_at_index<0, Types...>::moveConstructor(m_type_index, f_rhs.m_storage, m_storage); } } template <typename... Types> variant<Types...>& variant<Types...>::operator=(variant&& f_rhs) noexcept { if (this != &f_rhs) { if (m_type_index != f_rhs.m_type_index) { call_element_destructor(); m_type_index = std::move(f_rhs.m_type_index); if (m_type_index != INVALID_VARIANT_INDEX) { internal::call_at_index<0, Types...>::moveConstructor(m_type_index, f_rhs.m_storage, m_storage); } } else { if (m_type_index != INVALID_VARIANT_INDEX) { internal::call_at_index<0, Types...>::move(m_type_index, f_rhs.m_storage, m_storage); } } } return *this; } template <typename... Types> inline variant<Types...>::~variant() noexcept { call_element_destructor(); } template <typename... Types> void variant<Types...>::call_element_destructor() noexcept { if (m_type_index != INVALID_VARIANT_INDEX) { internal::call_at_index<0, Types...>::destructor(m_type_index, m_storage); } } template <typename... Types> template <typename T> inline typename std::enable_if<!std::is_same<T, variant<Types...>&>::value, variant<Types...>>::type& variant<Types...>::operator=(T&& f_rhs) noexcept { if (m_type_index == INVALID_VARIANT_INDEX) { m_type_index = internal::get_index_of_type<0, T, Types...>::index; } if (!has_bad_variant_element_access<T>()) { auto storage = static_cast<T*>(static_cast<void*>(m_storage)); *storage = (std::forward<T>(f_rhs)); } else { error_message(__PRETTY_FUNCTION__, "wrong variant type assignment, another type is already " "set in variant"); } return *this; } template <typename... Types> template <uint64_t TypeIndex, typename... CTorArguments> inline bool variant<Types...>::emplace_at_index(CTorArguments&&... f_args) noexcept { static_assert(TypeIndex <= sizeof...(Types), "TypeIndex is out of bounds"); using T = typename internal::get_type_at_index<0, TypeIndex, Types...>::type; call_element_destructor(); new (m_storage) T(std::forward<CTorArguments>(f_args)...); m_type_index = TypeIndex; return true; } template <typename... Types> template <typename T, typename... CTorArguments> inline bool variant<Types...>::emplace(CTorArguments&&... f_args) noexcept { if (m_type_index != INVALID_VARIANT_INDEX && has_bad_variant_element_access<T>()) { error_message(__PRETTY_FUNCTION__, "wrong variant type emplacement, another type is already " "set in variant"); return false; } if (m_type_index != INVALID_VARIANT_INDEX) { call_element_destructor(); } new (m_storage) T(std::forward<CTorArguments>(f_args)...); m_type_index = internal::get_index_of_type<0, T, Types...>::index; return true; } template <typename... Types> template <uint64_t TypeIndex> inline typename internal::get_type_at_index<0, TypeIndex, Types...>::type* variant<Types...>::get_at_index() noexcept { if (TypeIndex != m_type_index) { return nullptr; } using T = typename internal::get_type_at_index<0, TypeIndex, Types...>::type; return static_cast<T*>(static_cast<void*>(m_storage)); } template <typename... Types> template <uint64_t TypeIndex> inline const typename internal::get_type_at_index<0, TypeIndex, Types...>::type* variant<Types...>::get_at_index() const noexcept { using T = typename internal::get_type_at_index<0, TypeIndex, Types...>::type; return const_cast<const T*>(const_cast<variant*>(this)->template get_at_index<TypeIndex>()); } template <typename... Types> template <typename T> inline const T* variant<Types...>::get() const noexcept { if (has_bad_variant_element_access<T>()) { return nullptr; } else { return static_cast<const T*>(static_cast<const void*>(m_storage)); } } template <typename... Types> template <typename T> inline T* variant<Types...>::get() noexcept { return const_cast<T*>(const_cast<const variant*>(this)->get<T>()); } template <typename... Types> template <typename T> inline T* variant<Types...>::get_if(T* f_default_value) noexcept { return const_cast<T*>(const_cast<const variant*>(this)->get_if<T>(const_cast<const T*>(f_default_value))); } template <typename... Types> template <typename T> inline const T* variant<Types...>::get_if(const T* f_default_value) const noexcept { if (has_bad_variant_element_access<T>()) { return f_default_value; } return this->get<T>(); } template <typename... Types> constexpr size_t variant<Types...>::index() const noexcept { return m_type_index; } template <typename... Types> template <typename T> inline bool variant<Types...>::has_bad_variant_element_access() const noexcept { static_assert(internal::does_contain_type<T, Types...>::value, "variant does not contain given type"); return (m_type_index != internal::get_index_of_type<0, T, Types...>::index); } template <typename... Types> inline void variant<Types...>::error_message(const char* f_source, const char* f_msg) noexcept { std::cerr << f_source << " ::: " << f_msg << std::endl; } template <typename T, typename... Types> inline constexpr bool holds_alternative(const variant<Types...>& f_variant) noexcept { return f_variant.template get<T>() != nullptr; } } // namespace cxx } // namespace iox #endif // IOX_UTILS_CXX_VARIANT_INL <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkBoundingShapeVtkMapper3D.h" #include "../DataManagement/mitkBoundingShapeUtil.h" #include <mitkBaseProperty.h> #include <vtkAppendPolyData.h> #include <vtkCamera.h> #include <vtkCubeSource.h> #include <vtkDataSetMapper.h> #include <vtkMath.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper.h> #include <vtkSphereSource.h> #include <vtkTransformFilter.h> namespace mitk { class BoundingShapeVtkMapper3D::Impl { class LocalStorage : public Mapper::BaseLocalStorage { public: LocalStorage(); ~LocalStorage(); LocalStorage(const LocalStorage &) = delete; LocalStorage &operator=(const LocalStorage &) = delete; std::vector<vtkSmartPointer<vtkSphereSource>> Handles; vtkSmartPointer<vtkActor> Actor; vtkSmartPointer<vtkActor> HandleActor; vtkSmartPointer<vtkActor> SelectedHandleActor; vtkSmartPointer<vtkPropAssembly> PropAssembly; }; public: Impl() : DistanceFromCam(1.0) { Point3D initialPoint; initialPoint.Fill(0); for (int i = 0; i < 6; ++i) HandlePropertyList.push_back(Handle(initialPoint, i, GetHandleIndices(i))); } double DistanceFromCam; std::vector<Handle> HandlePropertyList; mitk::LocalStorageHandler<LocalStorage> LocalStorageHandler; }; } mitk::BoundingShapeVtkMapper3D::Impl::LocalStorage::LocalStorage() : Actor(vtkSmartPointer<vtkActor>::New()), HandleActor(vtkSmartPointer<vtkActor>::New()), SelectedHandleActor(vtkSmartPointer<vtkActor>::New()), PropAssembly(vtkSmartPointer<vtkPropAssembly>::New()) { for (int i = 0; i < 6; i++) Handles.push_back(vtkSmartPointer<vtkSphereSource>::New()); } mitk::BoundingShapeVtkMapper3D::Impl::LocalStorage::~LocalStorage() { } void mitk::BoundingShapeVtkMapper3D::SetDefaultProperties(DataNode *node, BaseRenderer *renderer, bool overwrite) { Superclass::SetDefaultProperties(node, renderer, overwrite); } mitk::BoundingShapeVtkMapper3D::BoundingShapeVtkMapper3D() : m_Impl(new Impl) { } mitk::BoundingShapeVtkMapper3D::~BoundingShapeVtkMapper3D() { delete m_Impl; } void mitk::BoundingShapeVtkMapper3D::ApplyColorAndOpacityProperties(BaseRenderer *renderer, vtkActor *actor) { //Superclass::ApplyColorAndOpacityProperties(renderer, actor); } void mitk::BoundingShapeVtkMapper3D::ApplyBoundingShapeProperties(BaseRenderer *renderer, vtkActor *actor) { if (actor == nullptr) return; auto dataNode = this->GetDataNode(); if (dataNode == nullptr) return; bool isVisible = false; dataNode->GetBoolProperty("Bounding Shape.3D Rendering", isVisible, renderer); actor->SetVisibility(isVisible); float lineWidth = 1.0f; dataNode->GetFloatProperty("Bounding Shape.Line.Width", lineWidth, renderer); auto property = actor->GetProperty(); property->SetLineWidth(lineWidth); } void mitk::BoundingShapeVtkMapper3D::GenerateDataForRenderer(BaseRenderer *renderer) { auto dataNode = this->GetDataNode(); if (dataNode == nullptr) return; vtkCamera *camera = renderer->GetVtkRenderer()->GetActiveCamera(); auto localStorage = m_Impl->LocalStorageHandler.GetLocalStorage(renderer); bool needGenerateData = localStorage->GetLastGenerateDataTime() < dataNode->GetMTime(); double distance = camera->GetDistance(); if (std::abs(distance - m_Impl->DistanceFromCam) > mitk::eps) { m_Impl->DistanceFromCam = distance; needGenerateData = true; } if (needGenerateData) { bool isVisible = true; dataNode->GetVisibility(isVisible, renderer); if (!isVisible) { localStorage->Actor->VisibilityOff(); return; } // set the input-object at time t for the mapper GeometryData *geometryData = dynamic_cast<GeometryData *>(dataNode->GetData()); if (geometryData == nullptr) return; mitk::BaseGeometry::Pointer geometry = geometryData->GetGeometry(); mitk::Vector3D spacing = geometry->GetSpacing(); // calculate cornerpoints from geometry std::vector<Point3D> cornerPoints = GetCornerPoints(geometry, true); Point3D p0 = cornerPoints[0]; Point3D p1 = cornerPoints[1]; Point3D p2 = cornerPoints[2]; Point3D p4 = cornerPoints[4]; Point3D extent; extent[0] = sqrt((p0[0] - p4[0]) * (p0[0] - p4[0]) + (p0[1] - p4[1]) * (p0[1] - p4[1]) + (p0[2] - p4[2]) * (p0[2] - p4[2])); extent[1] = sqrt((p0[0] - p2[0]) * (p0[0] - p2[0]) + (p0[1] - p2[1]) * (p0[1] - p2[1]) + (p0[2] - p2[2]) * (p0[2] - p2[2])); extent[2] = sqrt((p0[0] - p1[0]) * (p0[0] - p1[0]) + (p0[1] - p1[1]) * (p0[1] - p1[1]) + (p0[2] - p1[2]) * (p0[2] - p1[2])); // calculate center based on half way of the distance between two opposing cornerpoints mitk::Point3D center = CalcAvgPoint(cornerPoints[7], cornerPoints[0]); if (m_Impl->HandlePropertyList.size() == 6) { // set handle positions Point3D pointLeft = CalcAvgPoint(cornerPoints[5], cornerPoints[6]); Point3D pointRight = CalcAvgPoint(cornerPoints[1], cornerPoints[2]); Point3D pointTop = CalcAvgPoint(cornerPoints[0], cornerPoints[6]); Point3D pointBottom = CalcAvgPoint(cornerPoints[7], cornerPoints[1]); Point3D pointFront = CalcAvgPoint(cornerPoints[2], cornerPoints[7]); Point3D pointBack = CalcAvgPoint(cornerPoints[4], cornerPoints[1]); m_Impl->HandlePropertyList[0].SetPosition(pointLeft); m_Impl->HandlePropertyList[1].SetPosition(pointRight); m_Impl->HandlePropertyList[2].SetPosition(pointTop); m_Impl->HandlePropertyList[3].SetPosition(pointBottom); m_Impl->HandlePropertyList[4].SetPosition(pointFront); m_Impl->HandlePropertyList[5].SetPosition(pointBack); } auto cube = vtkCubeSource::New(); cube->SetXLength(extent[0] / spacing[0]); cube->SetYLength(extent[1] / spacing[1]); cube->SetZLength(extent[2] / spacing[2]); // calculates translation based on offset+extent not on the transformation matrix vtkSmartPointer<vtkMatrix4x4> imageTransform = geometry->GetVtkTransform()->GetMatrix(); auto translation = vtkSmartPointer<vtkTransform>::New(); translation->Translate(center[0] - imageTransform->GetElement(0, 3), center[1] - imageTransform->GetElement(1, 3), center[2] - imageTransform->GetElement(2, 3)); auto transform = vtkSmartPointer<vtkTransform>::New(); transform->SetMatrix(imageTransform); transform->PostMultiply(); transform->Concatenate(translation); transform->Update(); cube->Update(); auto transformFilter = vtkSmartPointer<vtkTransformFilter>::New(); transformFilter->SetInputData(cube->GetOutput()); transformFilter->SetTransform(transform); transformFilter->Update(); cube->Delete(); vtkSmartPointer<vtkPolyData> polydata = transformFilter->GetPolyDataOutput(); if (polydata == nullptr) { localStorage->Actor->VisibilityOff(); return; } mitk::DoubleProperty::Pointer handleSizeProperty = dynamic_cast<mitk::DoubleProperty *>(this->GetDataNode()->GetProperty("Bounding Shape.Handle Size Factor")); ScalarType initialHandleSize; if (handleSizeProperty != nullptr) initialHandleSize = handleSizeProperty->GetValue(); else initialHandleSize = 1.0 / 40.0; double handlesize = ((camera->GetDistance() * std::tan(vtkMath::RadiansFromDegrees(camera->GetViewAngle()))) / 2.0) * initialHandleSize; if (localStorage->PropAssembly->GetParts()->IsItemPresent(localStorage->HandleActor)) localStorage->PropAssembly->RemovePart(localStorage->HandleActor); if (localStorage->PropAssembly->GetParts()->IsItemPresent(localStorage->Actor)) localStorage->PropAssembly->RemovePart(localStorage->Actor); auto selectedhandlemapper = vtkSmartPointer<vtkPolyDataMapper>::New(); auto appendPoly = vtkSmartPointer<vtkAppendPolyData>::New(); mitk::IntProperty::Pointer activeHandleId = dynamic_cast<mitk::IntProperty *>(dataNode->GetProperty("Bounding Shape.Active Handle ID")); int i = 0; for (auto &handle : localStorage->Handles) { Point3D handlecenter = m_Impl->HandlePropertyList[i].GetPosition(); handle->SetCenter(handlecenter[0], handlecenter[1], handlecenter[2]); handle->SetRadius(handlesize); handle->Update(); if (activeHandleId == nullptr) { appendPoly->AddInputConnection(handle->GetOutputPort()); } else { if (activeHandleId->GetValue() != m_Impl->HandlePropertyList[i].GetIndex()) { appendPoly->AddInputConnection(handle->GetOutputPort()); } else { selectedhandlemapper->SetInputData(handle->GetOutput()); localStorage->SelectedHandleActor->SetMapper(selectedhandlemapper); localStorage->SelectedHandleActor->GetProperty()->SetColor(0, 1, 0); localStorage->SelectedHandleActor->GetMapper()->SetInputDataObject(handle->GetOutput()); localStorage->PropAssembly->AddPart(localStorage->SelectedHandleActor); } } i++; } appendPoly->Update(); auto mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInputData(polydata); auto handlemapper = vtkSmartPointer<vtkPolyDataMapper>::New(); handlemapper->SetInputData(appendPoly->GetOutput()); localStorage->Actor->SetMapper(mapper); localStorage->Actor->GetMapper()->SetInputDataObject(polydata); localStorage->Actor->GetProperty()->SetOpacity(0.3); mitk::ColorProperty::Pointer selectedColor = dynamic_cast<mitk::ColorProperty *>(dataNode->GetProperty("color")); if (selectedColor != nullptr) { mitk::Color color = selectedColor->GetColor(); localStorage->Actor->GetProperty()->SetColor(color[0], color[1], color[2]); } localStorage->HandleActor->SetMapper(handlemapper); if (activeHandleId == nullptr) { localStorage->HandleActor->GetProperty()->SetColor(1, 1, 1); } else { localStorage->HandleActor->GetProperty()->SetColor(1, 0, 0); } localStorage->HandleActor->GetMapper()->SetInputDataObject(appendPoly->GetOutput()); this->ApplyColorAndOpacityProperties(renderer, localStorage->Actor); this->ApplyBoundingShapeProperties(renderer, localStorage->Actor); this->ApplyColorAndOpacityProperties(renderer, localStorage->HandleActor); this->ApplyBoundingShapeProperties(renderer, localStorage->HandleActor); this->ApplyColorAndOpacityProperties(renderer, localStorage->SelectedHandleActor); this->ApplyBoundingShapeProperties(renderer, localStorage->SelectedHandleActor); // apply properties read from the PropertyList // this->ApplyProperties(localStorage->m_Actor, renderer); // this->ApplyProperties(localStorage->m_HandleActor, renderer); // this->ApplyProperties(localStorage->m_SelectedHandleActor, renderer); localStorage->Actor->VisibilityOn(); localStorage->HandleActor->VisibilityOn(); localStorage->SelectedHandleActor->VisibilityOn(); localStorage->PropAssembly->AddPart(localStorage->Actor); localStorage->PropAssembly->AddPart(localStorage->HandleActor); localStorage->PropAssembly->VisibilityOn(); localStorage->UpdateGenerateDataTime(); } } vtkProp *mitk::BoundingShapeVtkMapper3D::GetVtkProp(BaseRenderer *renderer) { return m_Impl->LocalStorageHandler.GetLocalStorage(renderer)->PropAssembly; } <commit_msg>removed unused function parameter<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkBoundingShapeVtkMapper3D.h" #include "../DataManagement/mitkBoundingShapeUtil.h" #include <mitkBaseProperty.h> #include <vtkAppendPolyData.h> #include <vtkCamera.h> #include <vtkCubeSource.h> #include <vtkDataSetMapper.h> #include <vtkMath.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper.h> #include <vtkSphereSource.h> #include <vtkTransformFilter.h> namespace mitk { class BoundingShapeVtkMapper3D::Impl { class LocalStorage : public Mapper::BaseLocalStorage { public: LocalStorage(); ~LocalStorage(); LocalStorage(const LocalStorage &) = delete; LocalStorage &operator=(const LocalStorage &) = delete; std::vector<vtkSmartPointer<vtkSphereSource>> Handles; vtkSmartPointer<vtkActor> Actor; vtkSmartPointer<vtkActor> HandleActor; vtkSmartPointer<vtkActor> SelectedHandleActor; vtkSmartPointer<vtkPropAssembly> PropAssembly; }; public: Impl() : DistanceFromCam(1.0) { Point3D initialPoint; initialPoint.Fill(0); for (int i = 0; i < 6; ++i) HandlePropertyList.push_back(Handle(initialPoint, i, GetHandleIndices(i))); } double DistanceFromCam; std::vector<Handle> HandlePropertyList; mitk::LocalStorageHandler<LocalStorage> LocalStorageHandler; }; } mitk::BoundingShapeVtkMapper3D::Impl::LocalStorage::LocalStorage() : Actor(vtkSmartPointer<vtkActor>::New()), HandleActor(vtkSmartPointer<vtkActor>::New()), SelectedHandleActor(vtkSmartPointer<vtkActor>::New()), PropAssembly(vtkSmartPointer<vtkPropAssembly>::New()) { for (int i = 0; i < 6; i++) Handles.push_back(vtkSmartPointer<vtkSphereSource>::New()); } mitk::BoundingShapeVtkMapper3D::Impl::LocalStorage::~LocalStorage() { } void mitk::BoundingShapeVtkMapper3D::SetDefaultProperties(DataNode *node, BaseRenderer *renderer, bool overwrite) { Superclass::SetDefaultProperties(node, renderer, overwrite); } mitk::BoundingShapeVtkMapper3D::BoundingShapeVtkMapper3D() : m_Impl(new Impl) { } mitk::BoundingShapeVtkMapper3D::~BoundingShapeVtkMapper3D() { delete m_Impl; } void mitk::BoundingShapeVtkMapper3D::ApplyColorAndOpacityProperties(BaseRenderer*, vtkActor*) { //Superclass::ApplyColorAndOpacityProperties(renderer, actor); } void mitk::BoundingShapeVtkMapper3D::ApplyBoundingShapeProperties(BaseRenderer *renderer, vtkActor *actor) { if (actor == nullptr) return; auto dataNode = this->GetDataNode(); if (dataNode == nullptr) return; bool isVisible = false; dataNode->GetBoolProperty("Bounding Shape.3D Rendering", isVisible, renderer); actor->SetVisibility(isVisible); float lineWidth = 1.0f; dataNode->GetFloatProperty("Bounding Shape.Line.Width", lineWidth, renderer); auto property = actor->GetProperty(); property->SetLineWidth(lineWidth); } void mitk::BoundingShapeVtkMapper3D::GenerateDataForRenderer(BaseRenderer *renderer) { auto dataNode = this->GetDataNode(); if (dataNode == nullptr) return; vtkCamera *camera = renderer->GetVtkRenderer()->GetActiveCamera(); auto localStorage = m_Impl->LocalStorageHandler.GetLocalStorage(renderer); bool needGenerateData = localStorage->GetLastGenerateDataTime() < dataNode->GetMTime(); double distance = camera->GetDistance(); if (std::abs(distance - m_Impl->DistanceFromCam) > mitk::eps) { m_Impl->DistanceFromCam = distance; needGenerateData = true; } if (needGenerateData) { bool isVisible = true; dataNode->GetVisibility(isVisible, renderer); if (!isVisible) { localStorage->Actor->VisibilityOff(); return; } // set the input-object at time t for the mapper GeometryData *geometryData = dynamic_cast<GeometryData *>(dataNode->GetData()); if (geometryData == nullptr) return; mitk::BaseGeometry::Pointer geometry = geometryData->GetGeometry(); mitk::Vector3D spacing = geometry->GetSpacing(); // calculate cornerpoints from geometry std::vector<Point3D> cornerPoints = GetCornerPoints(geometry, true); Point3D p0 = cornerPoints[0]; Point3D p1 = cornerPoints[1]; Point3D p2 = cornerPoints[2]; Point3D p4 = cornerPoints[4]; Point3D extent; extent[0] = sqrt((p0[0] - p4[0]) * (p0[0] - p4[0]) + (p0[1] - p4[1]) * (p0[1] - p4[1]) + (p0[2] - p4[2]) * (p0[2] - p4[2])); extent[1] = sqrt((p0[0] - p2[0]) * (p0[0] - p2[0]) + (p0[1] - p2[1]) * (p0[1] - p2[1]) + (p0[2] - p2[2]) * (p0[2] - p2[2])); extent[2] = sqrt((p0[0] - p1[0]) * (p0[0] - p1[0]) + (p0[1] - p1[1]) * (p0[1] - p1[1]) + (p0[2] - p1[2]) * (p0[2] - p1[2])); // calculate center based on half way of the distance between two opposing cornerpoints mitk::Point3D center = CalcAvgPoint(cornerPoints[7], cornerPoints[0]); if (m_Impl->HandlePropertyList.size() == 6) { // set handle positions Point3D pointLeft = CalcAvgPoint(cornerPoints[5], cornerPoints[6]); Point3D pointRight = CalcAvgPoint(cornerPoints[1], cornerPoints[2]); Point3D pointTop = CalcAvgPoint(cornerPoints[0], cornerPoints[6]); Point3D pointBottom = CalcAvgPoint(cornerPoints[7], cornerPoints[1]); Point3D pointFront = CalcAvgPoint(cornerPoints[2], cornerPoints[7]); Point3D pointBack = CalcAvgPoint(cornerPoints[4], cornerPoints[1]); m_Impl->HandlePropertyList[0].SetPosition(pointLeft); m_Impl->HandlePropertyList[1].SetPosition(pointRight); m_Impl->HandlePropertyList[2].SetPosition(pointTop); m_Impl->HandlePropertyList[3].SetPosition(pointBottom); m_Impl->HandlePropertyList[4].SetPosition(pointFront); m_Impl->HandlePropertyList[5].SetPosition(pointBack); } auto cube = vtkCubeSource::New(); cube->SetXLength(extent[0] / spacing[0]); cube->SetYLength(extent[1] / spacing[1]); cube->SetZLength(extent[2] / spacing[2]); // calculates translation based on offset+extent not on the transformation matrix vtkSmartPointer<vtkMatrix4x4> imageTransform = geometry->GetVtkTransform()->GetMatrix(); auto translation = vtkSmartPointer<vtkTransform>::New(); translation->Translate(center[0] - imageTransform->GetElement(0, 3), center[1] - imageTransform->GetElement(1, 3), center[2] - imageTransform->GetElement(2, 3)); auto transform = vtkSmartPointer<vtkTransform>::New(); transform->SetMatrix(imageTransform); transform->PostMultiply(); transform->Concatenate(translation); transform->Update(); cube->Update(); auto transformFilter = vtkSmartPointer<vtkTransformFilter>::New(); transformFilter->SetInputData(cube->GetOutput()); transformFilter->SetTransform(transform); transformFilter->Update(); cube->Delete(); vtkSmartPointer<vtkPolyData> polydata = transformFilter->GetPolyDataOutput(); if (polydata == nullptr) { localStorage->Actor->VisibilityOff(); return; } mitk::DoubleProperty::Pointer handleSizeProperty = dynamic_cast<mitk::DoubleProperty *>(this->GetDataNode()->GetProperty("Bounding Shape.Handle Size Factor")); ScalarType initialHandleSize; if (handleSizeProperty != nullptr) initialHandleSize = handleSizeProperty->GetValue(); else initialHandleSize = 1.0 / 40.0; double handlesize = ((camera->GetDistance() * std::tan(vtkMath::RadiansFromDegrees(camera->GetViewAngle()))) / 2.0) * initialHandleSize; if (localStorage->PropAssembly->GetParts()->IsItemPresent(localStorage->HandleActor)) localStorage->PropAssembly->RemovePart(localStorage->HandleActor); if (localStorage->PropAssembly->GetParts()->IsItemPresent(localStorage->Actor)) localStorage->PropAssembly->RemovePart(localStorage->Actor); auto selectedhandlemapper = vtkSmartPointer<vtkPolyDataMapper>::New(); auto appendPoly = vtkSmartPointer<vtkAppendPolyData>::New(); mitk::IntProperty::Pointer activeHandleId = dynamic_cast<mitk::IntProperty *>(dataNode->GetProperty("Bounding Shape.Active Handle ID")); int i = 0; for (auto &handle : localStorage->Handles) { Point3D handlecenter = m_Impl->HandlePropertyList[i].GetPosition(); handle->SetCenter(handlecenter[0], handlecenter[1], handlecenter[2]); handle->SetRadius(handlesize); handle->Update(); if (activeHandleId == nullptr) { appendPoly->AddInputConnection(handle->GetOutputPort()); } else { if (activeHandleId->GetValue() != m_Impl->HandlePropertyList[i].GetIndex()) { appendPoly->AddInputConnection(handle->GetOutputPort()); } else { selectedhandlemapper->SetInputData(handle->GetOutput()); localStorage->SelectedHandleActor->SetMapper(selectedhandlemapper); localStorage->SelectedHandleActor->GetProperty()->SetColor(0, 1, 0); localStorage->SelectedHandleActor->GetMapper()->SetInputDataObject(handle->GetOutput()); localStorage->PropAssembly->AddPart(localStorage->SelectedHandleActor); } } i++; } appendPoly->Update(); auto mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInputData(polydata); auto handlemapper = vtkSmartPointer<vtkPolyDataMapper>::New(); handlemapper->SetInputData(appendPoly->GetOutput()); localStorage->Actor->SetMapper(mapper); localStorage->Actor->GetMapper()->SetInputDataObject(polydata); localStorage->Actor->GetProperty()->SetOpacity(0.3); mitk::ColorProperty::Pointer selectedColor = dynamic_cast<mitk::ColorProperty *>(dataNode->GetProperty("color")); if (selectedColor != nullptr) { mitk::Color color = selectedColor->GetColor(); localStorage->Actor->GetProperty()->SetColor(color[0], color[1], color[2]); } localStorage->HandleActor->SetMapper(handlemapper); if (activeHandleId == nullptr) { localStorage->HandleActor->GetProperty()->SetColor(1, 1, 1); } else { localStorage->HandleActor->GetProperty()->SetColor(1, 0, 0); } localStorage->HandleActor->GetMapper()->SetInputDataObject(appendPoly->GetOutput()); this->ApplyColorAndOpacityProperties(renderer, localStorage->Actor); this->ApplyBoundingShapeProperties(renderer, localStorage->Actor); this->ApplyColorAndOpacityProperties(renderer, localStorage->HandleActor); this->ApplyBoundingShapeProperties(renderer, localStorage->HandleActor); this->ApplyColorAndOpacityProperties(renderer, localStorage->SelectedHandleActor); this->ApplyBoundingShapeProperties(renderer, localStorage->SelectedHandleActor); // apply properties read from the PropertyList // this->ApplyProperties(localStorage->m_Actor, renderer); // this->ApplyProperties(localStorage->m_HandleActor, renderer); // this->ApplyProperties(localStorage->m_SelectedHandleActor, renderer); localStorage->Actor->VisibilityOn(); localStorage->HandleActor->VisibilityOn(); localStorage->SelectedHandleActor->VisibilityOn(); localStorage->PropAssembly->AddPart(localStorage->Actor); localStorage->PropAssembly->AddPart(localStorage->HandleActor); localStorage->PropAssembly->VisibilityOn(); localStorage->UpdateGenerateDataTime(); } } vtkProp *mitk::BoundingShapeVtkMapper3D::GetVtkProp(BaseRenderer *renderer) { return m_Impl->LocalStorageHandler.GetLocalStorage(renderer)->PropAssembly; } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_RENDERER_COMMON_PROCESS_RASTER_SYMBOLIZER_HPP #define MAPNIK_RENDERER_COMMON_PROCESS_RASTER_SYMBOLIZER_HPP // mapnik #include <mapnik/warp.hpp> #include <mapnik/raster.hpp> #include <mapnik/symbolizer.hpp> #include <mapnik/raster_colorizer.hpp> #include <mapnik/proj_transform.hpp> #include <mapnik/feature.hpp> // agg #include "agg_rendering_buffer.h" #include "agg_pixfmt_rgba.h" #include "agg_pixfmt_gray.h" #include "agg_rasterizer_scanline_aa.h" #include "agg_scanline_u.h" #include "agg_renderer_scanline.h" namespace mapnik { namespace detail { template <typename F> struct image_data_dispatcher : util::static_visitor<void> { using composite_function = F; image_data_dispatcher(int start_x, int start_y, int width, int height, double scale_x, double scale_y, scaling_method_e method, double filter_factor, double opacity, composite_mode_e comp_op, raster_symbolizer const& sym, feature_impl const& feature, F & composite, boost::optional<double> const& nodata) : start_x_(start_x), start_y_(start_y), width_(width), height_(height), scale_x_(scale_x), scale_y_(scale_y), method_(method), filter_factor_(filter_factor), opacity_(opacity), comp_op_(comp_op), sym_(sym), feature_(feature), composite_(composite), nodata_(nodata) {} void operator() (image_data_null const& data_in) const {} //no-op void operator() (image_data_rgba8 const& data_in) const { image_data_rgba8 data_out(width_, height_); scale_image_agg(data_out, data_in, method_, scale_x_, scale_y_, 0.0, 0.0, filter_factor_); composite_(data_out, comp_op_, opacity_, start_x_, start_y_); } template <typename T> void operator() (T const& data_in) const { using image_data_type = T; image_data_type data_out(width_, height_); scale_image_agg(data_out, data_in, method_, scale_x_, scale_y_, 0.0, 0.0, filter_factor_); image_data_rgba8 dst(width_, height_); raster_colorizer_ptr colorizer = get<raster_colorizer_ptr>(sym_, keys::colorizer); if (colorizer) colorizer->colorize(dst, data_out, nodata_, feature_); composite_(dst, comp_op_, opacity_, start_x_, start_y_); } private: int start_x_; int start_y_; int width_; int height_; double scale_x_; double scale_y_; scaling_method_e method_; double filter_factor_; double opacity_; composite_mode_e comp_op_; raster_symbolizer const& sym_; feature_impl const& feature_; composite_function & composite_; boost::optional<double> const& nodata_; }; template <typename F> struct image_data_warp_dispatcher : util::static_visitor<void> { using composite_function = F; image_data_warp_dispatcher(proj_transform const& prj_trans, int start_x, int start_y, int width, int height, box2d<double> const& target_ext, box2d<double> const& source_ext, double offset_x, double offset_y, unsigned mesh_size, scaling_method_e scaling_method, double filter_factor, double opacity, composite_mode_e comp_op, raster_symbolizer const& sym, feature_impl const& feature, F & composite, boost::optional<double> const& nodata) : prj_trans_(prj_trans), start_x_(start_x), start_y_(start_y), width_(width), height_(height), target_ext_(target_ext), source_ext_(source_ext), offset_x_(offset_x), offset_y_(offset_y), mesh_size_(mesh_size), scaling_method_(scaling_method), filter_factor_(filter_factor), opacity_(opacity), comp_op_(comp_op), sym_(sym), feature_(feature), composite_(composite), nodata_(nodata) {} void operator() (image_data_null const& data_in) const {} //no-op void operator() (image_data_rgba8 const& data_in) const { image_data_rgba8 data_out(width_, height_); warp_image(data_out, data_in, prj_trans_, target_ext_, source_ext_, offset_x_, offset_y_, mesh_size_, scaling_method_, filter_factor_); composite_(data_out, comp_op_, opacity_, start_x_, start_y_); } template <typename T> void operator() (T const& data_in) const { using image_data_type = T; image_data_type data_out(width_, height_); warp_image(data_out, data_in, prj_trans_, target_ext_, source_ext_, offset_x_, offset_y_, mesh_size_, scaling_method_, filter_factor_); image_data_rgba8 dst(width_, height_); raster_colorizer_ptr colorizer = get<raster_colorizer_ptr>(sym_, keys::colorizer); if (colorizer) colorizer->colorize(dst, data_out, nodata_, feature_); composite_(dst, comp_op_, opacity_, start_x_, start_y_); } private: proj_transform const& prj_trans_; int start_x_; int start_y_; int width_; int height_; box2d<double> const& target_ext_; box2d<double> const& source_ext_; double offset_x_; double offset_y_; unsigned mesh_size_; scaling_method_e scaling_method_; double filter_factor_; double opacity_; composite_mode_e comp_op_; raster_symbolizer const& sym_; feature_impl const& feature_; composite_function & composite_; boost::optional<double> const& nodata_; }; } template <typename F> void render_raster_symbolizer(raster_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans, renderer_common& common, F composite) { raster_ptr const& source = feature.get_raster(); if (source) { box2d<double> target_ext = box2d<double>(source->ext_); prj_trans.backward(target_ext, PROJ_ENVELOPE_POINTS); box2d<double> ext = common.t_.forward(target_ext); int start_x = static_cast<int>(std::floor(ext.minx()+.5)); int start_y = static_cast<int>(std::floor(ext.miny()+.5)); int end_x = static_cast<int>(std::floor(ext.maxx()+.5)); int end_y = static_cast<int>(std::floor(ext.maxy()+.5)); int raster_width = end_x - start_x; int raster_height = end_y - start_y; if (raster_width > 0 && raster_height > 0) { scaling_method_e scaling_method = get<scaling_method_e>(sym, keys::scaling, feature, common.vars_, SCALING_NEAR); composite_mode_e comp_op = get<composite_mode_e>(sym, keys::comp_op, feature, common.vars_, src_over); double opacity = get<double>(sym,keys::opacity,feature, common.vars_, 1.0); bool premultiply_source = !source->premultiplied_alpha_; auto is_premultiplied = get_optional<bool>(sym, keys::premultiplied, feature, common.vars_); if (is_premultiplied) { if (*is_premultiplied) premultiply_source = false; else premultiply_source = true; } // only premuiltiply rgba8 images if (premultiply_source && source->data_.is<image_data_rgba8>()) { agg::rendering_buffer buffer(source->data_.getBytes(), source->data_.width(), source->data_.height(), source->data_.width() * 4); agg::pixfmt_rgba32 pixf(buffer); pixf.premultiply(); } if (!prj_trans.equal()) { double offset_x = ext.minx() - start_x; double offset_y = ext.miny() - start_y; unsigned mesh_size = static_cast<unsigned>(get<value_integer>(sym,keys::mesh_size,feature, common.vars_, 16)); detail::image_data_warp_dispatcher<F> dispatcher(prj_trans, start_x, start_y, raster_width, raster_height, target_ext, source->ext_, offset_x, offset_y, mesh_size, scaling_method, source->get_filter_factor(), opacity, comp_op, sym, feature, composite, source->nodata()); util::apply_visitor(dispatcher, source->data_); } else { double image_ratio_x = ext.width() / source->data_.width(); double image_ratio_y = ext.height() / source->data_.height(); double eps = 1e-5; if ( (std::fabs(image_ratio_x - 1.0) <= eps) && (std::fabs(image_ratio_y - 1.0) <= eps) && (std::abs(start_x) <= eps) && (std::abs(start_y) <= eps) ) { if (source->data_.is<image_data_rgba8>()) { composite(util::get<image_data_rgba8>(source->data_), comp_op, opacity, start_x, start_y); } } else { detail::image_data_dispatcher<F> dispatcher(start_x, start_y, raster_width, raster_height, image_ratio_x, image_ratio_y, scaling_method, source->get_filter_factor(), opacity, comp_op, sym, feature, composite, source->nodata()); util::apply_visitor(dispatcher, source->data_); } } } } } } // namespace mapnik #endif // MAPNIK_RENDERER_COMMON_PROCESS_RASTER_SYMBOLIZER_HPP <commit_msg>warp - initialise target with nodata if available<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_RENDERER_COMMON_PROCESS_RASTER_SYMBOLIZER_HPP #define MAPNIK_RENDERER_COMMON_PROCESS_RASTER_SYMBOLIZER_HPP // mapnik #include <mapnik/warp.hpp> #include <mapnik/raster.hpp> #include <mapnik/symbolizer.hpp> #include <mapnik/raster_colorizer.hpp> #include <mapnik/proj_transform.hpp> #include <mapnik/feature.hpp> // agg #include "agg_rendering_buffer.h" #include "agg_pixfmt_rgba.h" #include "agg_pixfmt_gray.h" #include "agg_rasterizer_scanline_aa.h" #include "agg_scanline_u.h" #include "agg_renderer_scanline.h" namespace mapnik { namespace detail { template <typename F> struct image_data_dispatcher : util::static_visitor<void> { using composite_function = F; image_data_dispatcher(int start_x, int start_y, int width, int height, double scale_x, double scale_y, scaling_method_e method, double filter_factor, double opacity, composite_mode_e comp_op, raster_symbolizer const& sym, feature_impl const& feature, F & composite, boost::optional<double> const& nodata) : start_x_(start_x), start_y_(start_y), width_(width), height_(height), scale_x_(scale_x), scale_y_(scale_y), method_(method), filter_factor_(filter_factor), opacity_(opacity), comp_op_(comp_op), sym_(sym), feature_(feature), composite_(composite), nodata_(nodata) {} void operator() (image_data_null const& data_in) const {} //no-op void operator() (image_data_rgba8 const& data_in) const { image_data_rgba8 data_out(width_, height_); scale_image_agg(data_out, data_in, method_, scale_x_, scale_y_, 0.0, 0.0, filter_factor_); composite_(data_out, comp_op_, opacity_, start_x_, start_y_); } template <typename T> void operator() (T const& data_in) const { using image_data_type = T; image_data_type data_out(width_, height_); scale_image_agg(data_out, data_in, method_, scale_x_, scale_y_, 0.0, 0.0, filter_factor_); image_data_rgba8 dst(width_, height_); raster_colorizer_ptr colorizer = get<raster_colorizer_ptr>(sym_, keys::colorizer); if (colorizer) colorizer->colorize(dst, data_out, nodata_, feature_); composite_(dst, comp_op_, opacity_, start_x_, start_y_); } private: int start_x_; int start_y_; int width_; int height_; double scale_x_; double scale_y_; scaling_method_e method_; double filter_factor_; double opacity_; composite_mode_e comp_op_; raster_symbolizer const& sym_; feature_impl const& feature_; composite_function & composite_; boost::optional<double> const& nodata_; }; template <typename F> struct image_data_warp_dispatcher : util::static_visitor<void> { using composite_function = F; image_data_warp_dispatcher(proj_transform const& prj_trans, int start_x, int start_y, int width, int height, box2d<double> const& target_ext, box2d<double> const& source_ext, double offset_x, double offset_y, unsigned mesh_size, scaling_method_e scaling_method, double filter_factor, double opacity, composite_mode_e comp_op, raster_symbolizer const& sym, feature_impl const& feature, F & composite, boost::optional<double> const& nodata) : prj_trans_(prj_trans), start_x_(start_x), start_y_(start_y), width_(width), height_(height), target_ext_(target_ext), source_ext_(source_ext), offset_x_(offset_x), offset_y_(offset_y), mesh_size_(mesh_size), scaling_method_(scaling_method), filter_factor_(filter_factor), opacity_(opacity), comp_op_(comp_op), sym_(sym), feature_(feature), composite_(composite), nodata_(nodata) {} void operator() (image_data_null const& data_in) const {} //no-op void operator() (image_data_rgba8 const& data_in) const { image_data_rgba8 data_out(width_, height_); if (nodata_) data_out.set(*nodata_); warp_image(data_out, data_in, prj_trans_, target_ext_, source_ext_, offset_x_, offset_y_, mesh_size_, scaling_method_, filter_factor_); composite_(data_out, comp_op_, opacity_, start_x_, start_y_); } template <typename T> void operator() (T const& data_in) const { using image_data_type = T; image_data_type data_out(width_, height_); if (nodata_) data_out.set(*nodata_); warp_image(data_out, data_in, prj_trans_, target_ext_, source_ext_, offset_x_, offset_y_, mesh_size_, scaling_method_, filter_factor_); image_data_rgba8 dst(width_, height_); raster_colorizer_ptr colorizer = get<raster_colorizer_ptr>(sym_, keys::colorizer); if (colorizer) colorizer->colorize(dst, data_out, nodata_, feature_); composite_(dst, comp_op_, opacity_, start_x_, start_y_); } private: proj_transform const& prj_trans_; int start_x_; int start_y_; int width_; int height_; box2d<double> const& target_ext_; box2d<double> const& source_ext_; double offset_x_; double offset_y_; unsigned mesh_size_; scaling_method_e scaling_method_; double filter_factor_; double opacity_; composite_mode_e comp_op_; raster_symbolizer const& sym_; feature_impl const& feature_; composite_function & composite_; boost::optional<double> const& nodata_; }; } template <typename F> void render_raster_symbolizer(raster_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans, renderer_common& common, F composite) { raster_ptr const& source = feature.get_raster(); if (source) { box2d<double> target_ext = box2d<double>(source->ext_); prj_trans.backward(target_ext, PROJ_ENVELOPE_POINTS); box2d<double> ext = common.t_.forward(target_ext); int start_x = static_cast<int>(std::floor(ext.minx()+.5)); int start_y = static_cast<int>(std::floor(ext.miny()+.5)); int end_x = static_cast<int>(std::floor(ext.maxx()+.5)); int end_y = static_cast<int>(std::floor(ext.maxy()+.5)); int raster_width = end_x - start_x; int raster_height = end_y - start_y; if (raster_width > 0 && raster_height > 0) { scaling_method_e scaling_method = get<scaling_method_e>(sym, keys::scaling, feature, common.vars_, SCALING_NEAR); composite_mode_e comp_op = get<composite_mode_e>(sym, keys::comp_op, feature, common.vars_, src_over); double opacity = get<double>(sym,keys::opacity,feature, common.vars_, 1.0); bool premultiply_source = !source->premultiplied_alpha_; auto is_premultiplied = get_optional<bool>(sym, keys::premultiplied, feature, common.vars_); if (is_premultiplied) { if (*is_premultiplied) premultiply_source = false; else premultiply_source = true; } // only premuiltiply rgba8 images if (premultiply_source && source->data_.is<image_data_rgba8>()) { agg::rendering_buffer buffer(source->data_.getBytes(), source->data_.width(), source->data_.height(), source->data_.width() * 4); agg::pixfmt_rgba32 pixf(buffer); pixf.premultiply(); } if (!prj_trans.equal()) { double offset_x = ext.minx() - start_x; double offset_y = ext.miny() - start_y; unsigned mesh_size = static_cast<unsigned>(get<value_integer>(sym,keys::mesh_size,feature, common.vars_, 16)); detail::image_data_warp_dispatcher<F> dispatcher(prj_trans, start_x, start_y, raster_width, raster_height, target_ext, source->ext_, offset_x, offset_y, mesh_size, scaling_method, source->get_filter_factor(), opacity, comp_op, sym, feature, composite, source->nodata()); util::apply_visitor(dispatcher, source->data_); } else { double image_ratio_x = ext.width() / source->data_.width(); double image_ratio_y = ext.height() / source->data_.height(); double eps = 1e-5; if ( (std::fabs(image_ratio_x - 1.0) <= eps) && (std::fabs(image_ratio_y - 1.0) <= eps) && (std::abs(start_x) <= eps) && (std::abs(start_y) <= eps) ) { if (source->data_.is<image_data_rgba8>()) { composite(util::get<image_data_rgba8>(source->data_), comp_op, opacity, start_x, start_y); } } else { detail::image_data_dispatcher<F> dispatcher(start_x, start_y, raster_width, raster_height, image_ratio_x, image_ratio_y, scaling_method, source->get_filter_factor(), opacity, comp_op, sym, feature, composite, source->nodata()); util::apply_visitor(dispatcher, source->data_); } } } } } } // namespace mapnik #endif // MAPNIK_RENDERER_COMMON_PROCESS_RASTER_SYMBOLIZER_HPP <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //_________________________________________________________________________ // Implementation version v0 of EMCAL Manager class // An object of this class does not produce hits nor digits // It is the one to use if you do not want to produce outputs in TREEH or TREED // This class places a Geometry of the EMCAL in the ALICE Detector as defined in AliEMCALGeometry.cxx //*-- Author: Yves Schutz (SUBATECH) //*-- and : Sahal Yacoob (LBL / UCT) // This Version of AliEMCALv0 reduces the number of volumes placed in XEN1 (the envelope) to less than five hundred // The Envelope is Placed in Alice, And the Aluminium layer. Mini envelopes (XU) are then placed in XEN1. // Each mini envelope contains 2 scintillator, and 2 lead layers, except the last one which contains just one scintillator layer. // At the moment I cannot place the 36 and above layers in the mini envelopes so all layers are still placed in XEN1 // --- ROOT system --- #include "TPGON.h" #include "TTUBS.h" #include "TNode.h" #include "TRandom.h" #include "TGeometry.h" //#include "Tstring.h" // --- Standard library --- #include <stdio.h> #include <string.h> #include <stdlib.h> #include <strstream.h> #include <iostream.h> // --- AliRoot header files --- #include "AliEMCALv0.h" #include "AliEMCALGeometry.h" #include "AliConst.h" #include "AliRun.h" #include "AliMC.h" ClassImp(AliEMCALv0) //______________________________________________________________________ AliEMCALv0::AliEMCALv0(const char *name, const char *title): AliEMCAL(name,title){ // Standard Constructor if (strcmp(GetTitle(),"") != 0 ) fGeom = AliEMCALGeometry::GetInstance(GetTitle(), "") ; } //______________________________________________________________________ void AliEMCALv0::BuildGeometry(){ // Display Geometry for display.C const Int_t kColorArm1 = kBlue ; // Difine the shape of the Calorimeter new TTUBS("Envelop1", "Tubs that contains arm 1", "void", fGeom->GetEnvelop(0), // rmin fGeom->GetEnvelop(1) +30 , // rmax fGeom->GetEnvelop(2)/2.0, // half length in Z fGeom->GetArm1PhiMin(), // minimun phi angle fGeom->GetArm1PhiMax() // maximun phi angle ); // Place the Node TNode * envelop1node = new TNode("Envelop1", "Arm1 Envelop", "Envelop1") ; envelop1node->SetLineColor(kColorArm1) ; fNodes->Add(envelop1node) ; } //______________________________________________________________________ void AliEMCALv0::CreateGeometry(){ // Create the EMCAL geometry for Geant AliEMCALv0 *emcaltmp = (AliEMCALv0*)gAlice->GetModule("EMCAL") ; if ( emcaltmp == NULL ) { Warning("CreateGeometry","detector not found!"); return; } // end if // Get pointer to the array containing media indices Int_t *idtmed = fIdtmed->GetArray() - 1599 ; // Create an Envelope within which to place the Detector Float_t envelopA[5] ; envelopA[0] = fGeom->GetEnvelop(0) ; // rmin envelopA[1] = fGeom->GetEnvelop(1) + 30 ; // rmax envelopA[2] = fGeom->GetEnvelop(2) / 2.0 ; // dz envelopA[3] = fGeom->GetArm1PhiMin() ; // minimun phi angle envelopA[4] = fGeom->GetArm1PhiMax() ; // maximun phi angle // create XEN1 gMC->Gsvolu("XEN1", "TUBS ", idtmed[1599], envelopA, 5) ; //filled with air Int_t idrotm = 1; AliMatrix(idrotm, 90.0, 0., 90.0, 90.0, 0.0, 0.0) ; // Position the Envelope in Alice gMC->Gspos("XEN1", 1, "ALIC", 0.0, 0.0, 0.0, idrotm, "ONLY") ; envelopA[1] =envelopA[0] + fGeom->GetGap2Active(); TString label = "XU0"; envelopA[0] = envelopA[1]+ 3.18 ; //rmin Start mini envelopes after the aluminium layer envelopA[1] = envelopA[0] + 2.2 ; //rmax larger for first two layers (preshower) gMC->Gsvolu(label.Data(), "TUBS ", idtmed[1599], envelopA, 5) ; //filled with air gMC->Gspos(label.Data(), 1, "XEN1", 0.0, 0.0, 0.0, idrotm, "ONLY") ; // Place XU0 in to XEN1 for (int i = 1; i < ((fGeom->GetNLayers()-1)/2) + 1 ; i++ ){ label = "XU" ; label += i ; envelopA[0] = envelopA[1] ; //rmin envelopA[1] = envelopA[0] + 2.0 ; //rmax gMC->Gsvolu(label.Data(), "TUBS ", idtmed[1599], envelopA, 5) ; //filled with air gMC->Gspos(label.Data(), 1, "XEN1", 0.0, 0.0, 0.0, idrotm, "ONLY") ; } // end i // Create the shapes of active material (LEAD/Aluminium/Scintillator) to be placed Float_t envelopB[10]; // First Layer of Aluminium Float_t envelopC[10]; // Scintillator Layers Float_t envelopD[10]; // Lead Layers envelopC[0] = envelopD[0] = envelopB[0] = fGeom->GetArm1PhiMin(); //starting position in Phi envelopC[1] = envelopD[1] = envelopB[1] = fGeom->GetArm1PhiMax() - // Angular size of the Detector in Phi fGeom->GetArm1PhiMin(); envelopC[2] = envelopD[2] = envelopB[2] = fGeom->GetNPhi() ; // Number of Section in Phi envelopD[3] = envelopC[3] = envelopB[3] = 2; // each section will be passed 2 z coordinates envelopB[4] = (fGeom->GetEnvelop(0) + fGeom->GetGap2Active()) / (tan(2*atan(exp(0.7)))) ; // z co-ordinate 1 envelopB[5] = fGeom->GetEnvelop(0) + fGeom->GetGap2Active(); //rmin at z1 envelopD[6] = envelopB[6] = envelopB[5] + 3.18; //rmax at z1 envelopB[7] = (fGeom->GetEnvelop(0) + fGeom->GetGap2Active()) / (tan(2*atan(exp(-0.7)))) ; // z co-ordinate 2 envelopB[8] = envelopB[5] ; // envelopB[9] = envelopB[6] ; // radii are the same. // filled shapes wit hactive material gMC->Gsvolu("XALU", "PGON", idtmed[1602], envelopB, 10); // Define Aluminium volume completely gMC->Gsvolu("XPST", "PGON", idtmed[1601], 0, 0) ; // The polystyrene layers will be defined when placed gMC->Gsvolu("XPBX", "PGON", idtmed[1600], 0, 0) ; // as will the lead layers gMC->Gsdvn("XPHI", "XPST", fGeom->GetNPhi(), 2) ; // Dividind eta polystyrene divisions into phi segments. // Position Aluminium Layer in the Envelope gMC->Gspos("XALU", 1, "XEN1", 0.0, 0.0, 0.0 , idrotm, "ONLY") ; // The loop below places the scintillator in Lead Layers alternately. for (int i = 0; i < fGeom->GetNLayers() ; i++ ){ label = "XU" ; label += (int) i/2 ; // we will place two layers (i = one layer) in each mini envelope) envelopC[5] = envelopD[6] ; //rmin envelopC[6] = envelopD[6] + ((i > 1) ? 0.5 : 0.6) ; //rmax larger for first two layers (preshower) envelopC[8] = envelopD[6] ; //rmin envelopC[9] = envelopD[6] + ((i > 1 ) ? 0.5 : 0.6) ; //rmax larger for first two layers (preshower) for (int j =0; j < (fGeom->GetNZ()) ; j++){ envelopC[4] = envelopD[6]/tan(2*atan(exp(0.7-(j*1.4/ (fGeom->GetNZ()))))); //z begin envelopC[7] = envelopD[6]/tan(2*atan(exp(0.7-((j+1)*1.4/ (fGeom->GetNZ()))))); // z end gMC->Gsposp("XPST",1+j+i*(fGeom->GetNZ()), label.Data(), // should be used but there's a weird crash above i = 18, 0.0, 0.0, 0.0 , idrotm, "ONLY", envelopC, 10); // Position and define layer } // end for j if (i < (fGeom->GetNLayers()-1)){ envelopD[5] = envelopC[6] ; //rmin envelopD[6] = envelopC[6] + 0.5; //rmax envelopD[8] = envelopC[6] ; //rmin envelopD[9] = envelopC[6] + 0.5; //rmax for (int j =0; j < (fGeom->GetNZ()) ; j++){ envelopD[4] = envelopC[6]/tan(2*atan(exp(0.7-(j*1.4/ (fGeom->GetNZ()))))); // z begin envelopD[7] = envelopC[6]/tan(2*atan(exp(0.7-((j+1)*1.4/ (fGeom->GetNZ()))))); // z end gMC->Gsposp("XPBX",1+ j+i*(fGeom->GetNZ()), label.Data(), 0.0, 0.0, 0.0 , idrotm, "ONLY", envelopD, 10) ; // Position and Define Layer } // end for j } // end if i } // for i } //______________________________________________________________________ void AliEMCALv0::Init(void){ // Just prints an information message Int_t i; cout << endl; for(i=0;i<35;i++) cout <<"*"; cout << " EMCAL_INIT "; for(i=0;i<35;i++) cout << "*"; cout << endl; // Here the EMCAL initialisation code (if any!) if (fGeom!=0) cout << "AliEMCAL" << Version() << " : EMCAL geometry intialized for " << fGeom->GetName() << endl ; else cout << "AliEMCAL" << Version() << " : EMCAL geometry initialization failed !" << endl ; for(i=0;i<80;i++) printf("*"); cout << endl; } <commit_msg>Cleaned CreateGeometry<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //_________________________________________________________________________ // Implementation version v0 of EMCAL Manager class // An object of this class does not produce hits nor digits // It is the one to use if you do not want to produce outputs in TREEH or TREED // This class places a Geometry of the EMCAL in the ALICE Detector as defined in AliEMCALGeometry.cxx //*-- Author: Yves Schutz (SUBATECH) //*-- and : Sahal Yacoob (LBL / UCT) // This Version of AliEMCALv0 reduces the number of volumes placed in XEN1 (the envelope) to less than five hundred // The Envelope is Placed in Alice, And the Aluminium layer. Mini envelopes (XU) are then placed in XEN1. // Each mini envelope contains 2 scintillator, and 2 lead layers, except the last one which contains just one scintillator layer. // At the moment I cannot place the 36 and above layers in the mini envelopes so all layers are still placed in XEN1 // --- ROOT system --- #include "TPGON.h" #include "TTUBS.h" #include "TNode.h" #include "TRandom.h" #include "TGeometry.h" //#include "Tstring.h" // --- Standard library --- #include <stdio.h> #include <string.h> #include <stdlib.h> #include <strstream.h> #include <iostream.h> // --- AliRoot header files --- #include "AliEMCALv0.h" #include "AliEMCALGeometry.h" #include "AliConst.h" #include "AliRun.h" #include "AliMC.h" ClassImp(AliEMCALv0) //______________________________________________________________________ AliEMCALv0::AliEMCALv0(const char *name, const char *title): AliEMCAL(name,title){ // Standard Constructor if (strcmp(GetTitle(),"") != 0 ) fGeom = AliEMCALGeometry::GetInstance(GetTitle(), "") ; } //______________________________________________________________________ void AliEMCALv0::BuildGeometry(){ // Display Geometry for display.C const Int_t kColorArm1 = kBlue ; // Difine the shape of the Calorimeter new TTUBS("Envelop1", "Tubs that contains arm 1", "void", fGeom->GetEnvelop(0), // rmin fGeom->GetEnvelop(1) +30 , // rmax fGeom->GetEnvelop(2)/2.0, // half length in Z fGeom->GetArm1PhiMin(), // minimun phi angle fGeom->GetArm1PhiMax() // maximun phi angle ); // Place the Node TNode * envelop1node = new TNode("Envelop1", "Arm1 Envelop", "Envelop1") ; envelop1node->SetLineColor(kColorArm1) ; fNodes->Add(envelop1node) ; } //______________________________________________________________________ void AliEMCALv0::CreateGeometry(){ // Create the EMCAL geometry for Geant Float_t etamin,etamax; if(fGeom->IsInitialized()){ Error("CreateGeometry","EMCAL Geometry class has not been set up."); } // end if // Get pointer to the array containing media indices Int_t *idtmed = fIdtmed->GetArray() - 1599 ; // Create an Envelope within which to place the Detector Float_t envelopA[5]; envelopA[0] = fGeom->GetEnvelop(0); // rmin envelopA[1] = fGeom->GetEnvelop(1); // rmax envelopA[2] = fGeom->GetEnvelop(2)/2.0; // dz envelopA[3] = fGeom->GetArm1PhiMin(); // minimun phi angle envelopA[4] = fGeom->GetArm1PhiMax(); // maximun phi angle // create XEN1 gMC->Gsvolu("XEN1", "TUBS ", idtmed[1599], envelopA, 5) ; //filled with air Int_t idrotm = 1; AliMatrix(idrotm, 90.0, 0., 90.0, 90.0, 0.0, 0.0) ; // Position the EMCAL Mother Volume in Alice gMC->Gspos("XEN1", 1, "ALIC", 0.0, 0.0, 0.0, idrotm, "ONLY") ; // TString label = "XU0"; //rmin Start mini envelopes after the aluminium layer envelopA[0] = fGeom->GetEnvelop(0) + fGeom->GetGap2Active() + fGeom->GetAlFrontThickness(); //rmax larger for first two layers (preshower); Float_t tseg = fGeom->GetPreSintThick()+fGeom->GetPbRadThick(); envelopA[1] = envelopA[0] + 2.0*tseg; envelopA[2] = fGeom->GetEnvelop(2)/2.0; // dz envelopA[3] = fGeom->GetArm1PhiMin(); // minimun phi angle envelopA[4] = fGeom->GetArm1PhiMax(); // maximun phi angle //filled with air gMC->Gsvolu(label.Data(), "TUBS ", idtmed[1599], envelopA, 5); // Place XU0 in to XEN1 gMC->Gspos(label.Data(), 1, "XEN1", 0.0, 0.0, 0.0, idrotm, "ONLY"); tseg = fGeom->GetFullSintThick()+fGeom->GetPbRadThick(); for (int i = 1; i < ((fGeom->GetNLayers()-1)/2) + 1 ; i++ ){ label = "XU" ; label += i ; envelopA[0] = envelopA[1]; //rmin envelopA[1] = envelopA[0] + 2.0*tseg; //rmax //filled with air gMC->Gsvolu(label.Data(), "TUBS ", idtmed[1599], envelopA, 5); gMC->Gspos(label.Data(), 1, "XEN1", 0.0, 0.0, 0.0, idrotm, "ONLY") ; } // end i // Create the shapes of active material (LEAD/Aluminium/Scintillator) // to be placed Float_t envelopB[10]; // First Layer of Aluminium Float_t envelopC[10]; // Scintillator Layers Float_t envelopD[10]; // Lead Layers //starting position in Phi envelopC[0] = envelopD[0] = envelopB[0] = fGeom->GetArm1PhiMin(); // Angular size of the Detector in Phi envelopB[1] = fGeom->GetArm1PhiMax() - fGeom->GetArm1PhiMin(); envelopC[1] = envelopD[1] = envelopB[1]; // Number of Section in Phi envelopC[2] = envelopD[2] = envelopB[2] = fGeom->GetNPhi(); // each section will be passed 2 z coordinates envelopD[3] = envelopC[3] = envelopB[3] = 2; envelopB[4] = fGeom->ZFromEtaR(fGeom->GetEnvelop(0)+fGeom->GetGap2Active(), fGeom->GetArm1EtaMin());// z co-ordinate 1 envelopB[5] = fGeom->GetEnvelop(0) + fGeom->GetGap2Active(); //rmin at z1 envelopB[6] = envelopB[5] + fGeom->GetAlFrontThickness();//rmax at z1 envelopD[6] = envelopB[6]; envelopB[7] =fGeom->ZFromEtaR(fGeom->GetEnvelop(0)+fGeom->GetGap2Active(), fGeom->GetArm1EtaMax()); // z co-ordinate 2 envelopB[8] = envelopB[5] ; // envelopB[9] = envelopB[6] ; // radii are the same. // filled shapes wit hactive material // Define Aluminium volume completely gMC->Gsvolu("XALU", "PGON", idtmed[1602], envelopB, 10); // The polystyrene layers will be defined when placed gMC->Gsvolu("XPST", "PGON", idtmed[1601], 0, 0); gMC->Gsvolu("XPBX", "PGON", idtmed[1600], 0, 0);// as will the lead layers // Dividind eta polystyrene divisions into phi segments. gMC->Gsdvn("XPHI", "XPST", fGeom->GetNPhi(), 2); // Position Aluminium Layer in the Envelope gMC->Gspos("XALU", 1, "XEN1", 0.0, 0.0, 0.0 , idrotm, "ONLY") ; // The loop below places the scintillator in Lead Layers alternately. for (int i = 0; i < fGeom->GetNLayers() ; i++ ){ label = "XU" ; label += (int) i/2 ; // we will place two layers (i = one layer) in each mini envelope) envelopC[5] = envelopD[6] ; //rmin envelopC[6] = envelopD[6] + ((i > 1) ? fGeom->GetFullSintThick() : fGeom->GetPreSintThick());//rmax larger for first two layers (preshower) envelopC[8] = envelopD[6] ; //rmin envelopC[9] = envelopD[6] + ((i > 1 ) ? fGeom->GetFullSintThick() : fGeom->GetPreSintThick());//rmax larger for first two layers (preshower) for (int j =0; j < (fGeom->GetNEta()) ; j++){ etamin = fGeom->GetArm1EtaMin()+ (j*fGeom->GetDeltaEta()/(fGeom->GetNEta())); etamax = fGeom->GetArm1EtaMin()+ ((j+1)*fGeom->GetDeltaEta()/(fGeom->GetNEta())); envelopC[4] = fGeom->ZFromEtaR(envelopD[6],etamin); //z begin envelopC[7] = fGeom->ZFromEtaR(envelopD[6],etamax);// z end gMC->Gsposp("XPST",1+j+i*(fGeom->GetNEta()), label.Data(), // should be used but there's a weird crash above i = 18, 0.0, 0.0, 0.0 , idrotm, "ONLY", envelopC, 10); // Position and define layer } // end for j if (i < (fGeom->GetNLayers()-1)){ envelopD[5] = envelopC[6] ; //rmin envelopD[6] = envelopC[6] + fGeom->GetPbRadThick(); //rmax envelopD[8] = envelopC[6] ; //rmin envelopD[9] = envelopC[6] + fGeom->GetPbRadThick(); //rmax for (int j =0; j < (fGeom->GetNEta()) ; j++){ etamin = fGeom->GetArm1EtaMin()+ (j*fGeom->GetDeltaEta()/(fGeom->GetNEta())); etamax = fGeom->GetArm1EtaMin()+ ((j+1)*fGeom->GetDeltaEta()/(fGeom->GetNEta())); envelopD[4] = fGeom->ZFromEtaR(envelopC[6],etamin);//z begin envelopD[7] = fGeom->ZFromEtaR(envelopC[6],etamax);// z end // Position and Define Layer gMC->Gsposp("XPBX",1+ j+i*(fGeom->GetNEta()), label.Data(), 0.0, 0.0, 0.0 , idrotm, "ONLY", envelopD, 10); } // end for j } // end if i } // for i } //______________________________________________________________________ void AliEMCALv0::Init(void){ // Just prints an information message Int_t i; cout << endl; for(i=0;i<35;i++) cout <<"*"; cout << " EMCAL_INIT "; for(i=0;i<35;i++) cout << "*"; cout << endl; // Here the EMCAL initialisation code (if any!) if (fGeom!=0) cout << "AliEMCAL" << Version() << " : EMCAL geometry intialized for " << fGeom->GetName() << endl ; else cout << "AliEMCAL" << Version() << " : EMCAL geometry initialization failed !" << endl ; for(i=0;i<80;i++) printf("*"); cout << endl; } <|endoftext|>
<commit_before>/** * Copyright © 2016 IBM Corporation * * 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 <iostream> #include <memory> #include <cstring> #include <cstdlib> #include <chrono> #include <algorithm> #include "sensorset.hpp" #include "hwmon.hpp" #include "sysfs.hpp" #include "mainloop.hpp" #include "util.hpp" #include "env.hpp" using namespace std::literals::chrono_literals; static constexpr auto typeAttrMap = { // 1 - hwmon class // 2 - unit // 3 - sysfs scaling factor std::make_tuple( hwmon::type::ctemp, ValueInterface::Unit::DegreesC, -3), std::make_tuple( hwmon::type::cfan, ValueInterface::Unit::RPMS, 0), std::make_tuple( hwmon::type::cvolt, ValueInterface::Unit::Volts, -3), }; auto getHwmonType(decltype(typeAttrMap)::const_reference attrs) { return std::get<0>(attrs); } auto getUnit(decltype(typeAttrMap)::const_reference attrs) { return std::get<1>(attrs); } auto getScale(decltype(typeAttrMap)::const_reference attrs) { return std::get<2>(attrs); } MainLoop::MainLoop( sdbusplus::bus::bus&& bus, const std::string& path, const char* prefix, const char* root) : _bus(std::move(bus)), _manager(sdbusplus::server::manager::manager(_bus, root)), _shutdown(false), _path(path), _prefix(prefix), _root(root), state() { if (_path.back() == '/') { _path.pop_back(); } } void MainLoop::shutdown() noexcept { _shutdown = true; } void MainLoop::run() { // Check sysfs for available sensors. auto sensors = std::make_unique<SensorSet>(_path); for (auto& i : *sensors) { // Get sensor configuration from the environment. // Ignore inputs without a label. auto label = getEnv("LABEL", i.first); if (label.empty()) { continue; } // Get the initial value for the value interface. auto sysfsPath = make_sysfs_path( _path, i.first.first, i.first.second, hwmon::entry::input); int val = 0; read_sysfs(sysfsPath, val); std::string objectPath{_root}; objectPath.append("/"); objectPath.append(i.first.first); objectPath.append("/"); objectPath.append(label); ObjectInfo info(&_bus, std::move(objectPath), Object()); auto& o = std::get<Object>(info); auto iface = std::make_shared<ValueObject>(_bus, objectPath.c_str()); iface->value(val); const auto& attrs = std::find_if( typeAttrMap.begin(), typeAttrMap.end(), [&](const auto & e) { return i.first.first == getHwmonType(e); }); if (attrs != typeAttrMap.end()) { iface->unit(getUnit(*attrs)); iface->scale(getScale(*attrs)); } o.emplace(InterfaceType::VALUE, iface); auto value = std::make_tuple( std::move(i.second), std::move(label), std::move(info)); state[std::move(i.first)] = std::move(value); } { auto copy = std::unique_ptr<char, phosphor::utility::Free<char>>(strdup( _path.c_str())); auto busname = std::string(_prefix) + '.' + basename(copy.get()); _bus.request_name(busname.c_str()); } // TODO: Issue#3 - Need to make calls to the dbus sensor cache here to // ensure the objects all exist? // Polling loop. while (!_shutdown) { // Iterate through all the sensors. for (auto& i : state) { auto& attrs = std::get<0>(i.second); if (attrs.find(hwmon::entry::input) != attrs.end()) { // Read value from sensor. int value = 0; read_sysfs(make_sysfs_path(_path, i.first.first, i.first.second, hwmon::entry::input), value); auto& objInfo = std::get<ObjectInfo>(i.second); auto& obj = std::get<Object>(objInfo); auto iface = obj.find(InterfaceType::VALUE); if (iface != obj.end()) { auto realIface = std::experimental::any_cast<std::shared_ptr<ValueObject>> (iface->second); realIface->value(value); } } } // Respond to DBus _bus.process_discard(); // Sleep until next interval. // TODO: Issue#5 - Make this configurable. // TODO: Issue#6 - Optionally look at polling interval sysfs entry. _bus.wait((1000000us).count()); // TODO: Issue#7 - Should probably periodically check the SensorSet // for new entries. } } // vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 <commit_msg>Move value interface creation to a helper method.<commit_after>/** * Copyright © 2016 IBM Corporation * * 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 <iostream> #include <memory> #include <cstring> #include <cstdlib> #include <chrono> #include <algorithm> #include "sensorset.hpp" #include "hwmon.hpp" #include "sysfs.hpp" #include "mainloop.hpp" #include "util.hpp" #include "env.hpp" using namespace std::literals::chrono_literals; static constexpr auto typeAttrMap = { // 1 - hwmon class // 2 - unit // 3 - sysfs scaling factor std::make_tuple( hwmon::type::ctemp, ValueInterface::Unit::DegreesC, -3), std::make_tuple( hwmon::type::cfan, ValueInterface::Unit::RPMS, 0), std::make_tuple( hwmon::type::cvolt, ValueInterface::Unit::Volts, -3), }; auto getHwmonType(decltype(typeAttrMap)::const_reference attrs) { return std::get<0>(attrs); } auto getUnit(decltype(typeAttrMap)::const_reference attrs) { return std::get<1>(attrs); } auto getScale(decltype(typeAttrMap)::const_reference attrs) { return std::get<2>(attrs); } auto addValue(const SensorSet::key_type& sensor, const std::string& sysfsRoot, ObjectInfo& info) { // Get the initial value for the value interface. auto& bus = *std::get<sdbusplus::bus::bus*>(info); auto& obj = std::get<Object>(info); auto& objPath = std::get<std::string>(info); auto sysfsPath = make_sysfs_path( sysfsRoot, sensor.first, sensor.second, hwmon::entry::input); int val = 0; read_sysfs(sysfsPath, val); auto iface = std::make_shared<ValueObject>(bus, objPath.c_str()); iface->value(val); // *INDENT-OFF* const auto& attrs = std::find_if( typeAttrMap.begin(), typeAttrMap.end(), [&](const auto & e) { return sensor.first == getHwmonType(e); }); // *INDENT-ON* if (attrs != typeAttrMap.end()) { iface->unit(getUnit(*attrs)); iface->scale(getScale(*attrs)); } obj[InterfaceType::VALUE] = iface; return iface; } MainLoop::MainLoop( sdbusplus::bus::bus&& bus, const std::string& path, const char* prefix, const char* root) : _bus(std::move(bus)), _manager(sdbusplus::server::manager::manager(_bus, root)), _shutdown(false), _path(path), _prefix(prefix), _root(root), state() { if (_path.back() == '/') { _path.pop_back(); } } void MainLoop::shutdown() noexcept { _shutdown = true; } void MainLoop::run() { // Check sysfs for available sensors. auto sensors = std::make_unique<SensorSet>(_path); for (auto& i : *sensors) { // Get sensor configuration from the environment. // Ignore inputs without a label. auto label = getEnv("LABEL", i.first); if (label.empty()) { continue; } std::string objectPath{_root}; objectPath.append("/"); objectPath.append(i.first.first); objectPath.append("/"); objectPath.append(label); ObjectInfo info(&_bus, std::move(objectPath), Object()); auto valueInterface = addValue(i.first, _path, info); auto value = std::make_tuple( std::move(i.second), std::move(label), std::move(info)); state[std::move(i.first)] = std::move(value); } { auto copy = std::unique_ptr<char, phosphor::utility::Free<char>>(strdup( _path.c_str())); auto busname = std::string(_prefix) + '.' + basename(copy.get()); _bus.request_name(busname.c_str()); } // TODO: Issue#3 - Need to make calls to the dbus sensor cache here to // ensure the objects all exist? // Polling loop. while (!_shutdown) { // Iterate through all the sensors. for (auto& i : state) { auto& attrs = std::get<0>(i.second); if (attrs.find(hwmon::entry::input) != attrs.end()) { // Read value from sensor. int value = 0; read_sysfs(make_sysfs_path(_path, i.first.first, i.first.second, hwmon::entry::input), value); auto& objInfo = std::get<ObjectInfo>(i.second); auto& obj = std::get<Object>(objInfo); auto iface = obj.find(InterfaceType::VALUE); if (iface != obj.end()) { auto realIface = std::experimental::any_cast<std::shared_ptr<ValueObject>> (iface->second); realIface->value(value); } } } // Respond to DBus _bus.process_discard(); // Sleep until next interval. // TODO: Issue#5 - Make this configurable. // TODO: Issue#6 - Optionally look at polling interval sysfs entry. _bus.wait((1000000us).count()); // TODO: Issue#7 - Should probably periodically check the SensorSet // for new entries. } } // vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 <|endoftext|>
<commit_before>#include <iostream> #include <algorithm> #include <fstream> #include <vector> #include <string> #include <type_traits> #include <iomanip> #include "cmdline/cmdline.h" #include "picojson/picojson.h" #include "sais/sais.hxx" #include "wavelet_matrix.h" using namespace std; typedef int64_t index_type; #define iter(c) decltype((c).size()) vector<uint8_t> bwt(const vector<uint8_t> &S) { vector<uint8_t> T(S.size()); vector<index_type> tmp(S.size()); vector<uint8_t> &S2 = const_cast<vector<uint8_t> &>(S); saisxx_bwt(S2.begin(), T.begin(), tmp.begin(), (index_type)S.size()); return T; } vector<uint8_t> ibwt(const vector<uint8_t> &T, const index_type pid) { vector<uint64_t> C(256, 0); for (const auto &c : T) { ++C[c]; } uint64_t sum = 0; for (iter(C) i = 0; i < C.size(); ++i) { uint64_t cur = C[i]; C[i] = sum; sum += cur; } vector<index_type> phi(T.size()); for (iter(T) i = 0; i < T.size(); ++i) { phi[C[T[i]]] = i; ++C[T[i]]; } vector<uint8_t> S(T.size()); index_type j = pid; for (iter(T) i = 0; i < T.size(); ++i) { S[i] = T[phi[j]]; j = phi[j]; } return S; } string read_oneline(const string &ifname) { ifstream ifs(ifname); if (!ifs) { perror(ifname.c_str()); exit(EXIT_FAILURE); } string s; getline(ifs, s); return s; } void show_string_in_hex(const string &s) { for (iter(s) i = 0; i < s.size(); ++i) { if (i > 0) cout << ' '; unsigned char c = s[i]; cerr << "0x" << hex << (int)c; } cerr << endl; } bool is_utf8_start_char(unsigned char c) { // 2バイト目以降は先頭ビットが10である if ((c >> 6) == 2) return false; return true; } pair<index_type, index_type> fm_index(const WaveletMatrix &wat, const string &p) { index_type sp = 0; index_type ep = wat.length(); for (iter(p) i = 0; i < p.size(); ++i) { unsigned char c = p[p.size() - 1 - i]; sp = wat.rank_lt(c) + wat.rank(c, sp); ep = wat.rank_lt(c) + wat.rank(c, ep); if (sp >= ep) return make_pair(-1, -1); } return make_pair(sp, ep); } vector<vector<string>> read_datasets(const string &cfname) { ifstream ifs(cfname); if (!ifs) { perror(cfname.c_str()); exit(EXIT_FAILURE); } picojson::value json; string err = picojson::parse(json, ifs); if (!err.empty()) { cerr << err << endl; exit(EXIT_FAILURE); } picojson::array &array = json.get<picojson::array>(); vector<vector<string>> ret; for (const picojson::value &it : array) { picojson::object book = it.get<picojson::object>(); string filename = book["filename"].get<string>(); string title = book["title"].get<string>(); string author = book["author"].get<string>(); vector<string> vs = { read_oneline(filename), title, author }; ret.emplace_back(vs); } return ret; } void search(const string &query, const int num, const WaveletMatrix &wt_text, const WaveletMatrix &wt_freq, const vector<vector<string>> &datasets) { auto spep = fm_index(wt_text, query); vector<pair<WaveletMatrix::Index, int>> res = wt_freq.topk<int>(spep.first, spep.second, num); for (const auto &r : res) { if (r.second == datasets.size()) continue; cout << r.first << '\t' << datasets[r.second][1] << '\t' << datasets[r.second][2] << endl; } } int main(int argc, char *argv[]) { cmdline::parser parser; parser.add<string>("config", 'c', "config json file", /* need = */ true); parser.add<string>("query", 'q', "query string", /* need = */ false); parser.add<int>("number", 'n', "display first `number` lines", /* need = */ false, /* default = */ 20); parser.add("interact", 'i', "launch interactive shell"); parser.add("help", 'h', "show help"); if (!parser.parse(argc, argv) || parser.exist("help")) { cerr << parser.error_full() << parser.usage() << endl; exit(EXIT_FAILURE); } if (parser.exist("query") == false && parser.exist("interact") == false) { cerr << "you should enable --query or --interact" << endl; exit(EXIT_FAILURE); } string cfname = parser.get<string>("config"); vector<vector<string>> datasets = read_datasets(cfname); vector<uint8_t> SV; for (iter(datasets) i = 0; i < datasets.size(); ++i) { SV.insert(SV.end(), datasets[i][0].begin(), datasets[i][0].end()); SV.push_back('\n'); } SV.push_back('\0'); vector<index_type> SA(SV.size()); saisxx(SV.begin(), SA.begin(), (index_type)SV.size()); WaveletMatrix wt_text(8); { vector<uint8_t> TV = bwt(SV); wt_text.init(TV); } WaveletMatrix wt_freq(9); { vector<uint64_t> array(SV.size()); uint64_t sum = 0; for (iter(datasets) i = 0; i < datasets.size(); ++i) { for (iter(datasets[i][0]) j = 0; j < datasets[i][0].size(); ++j) { array[sum] = i; ++sum; } array[sum] = datasets.size(); ++sum; } array[sum] = datasets.size(); ++sum; vector<uint64_t> rev(SV.size()); for (iter(SV) i = 0; i < SV.size(); ++i) { rev[i] = array[SA[i]]; } wt_freq.init(rev); } if (parser.exist("query")) { string q = parser.get<string>("query"); search(q, parser.get<int>("number"), wt_text, wt_freq, datasets); } if (parser.exist("interact")) { while (true) { cout << "query> "; string q; if (cin >> q) { search(q, parser.get<int>("number"), wt_text, wt_freq, datasets); } else { break; } } } } <commit_msg>mainmain.cppの見かけのメモリ使用量を削減した<commit_after>#include <iostream> #include <algorithm> #include <fstream> #include <vector> #include <string> #include <type_traits> #include <iomanip> #include "cmdline/cmdline.h" #include "picojson/picojson.h" #include "sais/sais.hxx" #include "wavelet_matrix.h" using namespace std; typedef int64_t index_type; #define iter(c) decltype((c).size()) vector<uint8_t> bwt(const vector<uint8_t> &S) { vector<uint8_t> T(S.size()); vector<index_type> tmp(S.size()); vector<uint8_t> &S2 = const_cast<vector<uint8_t> &>(S); saisxx_bwt(S2.begin(), T.begin(), tmp.begin(), (index_type)S.size()); return T; } vector<uint8_t> ibwt(const vector<uint8_t> &T, const index_type pid) { vector<uint64_t> C(256, 0); for (const auto &c : T) { ++C[c]; } uint64_t sum = 0; for (iter(C) i = 0; i < C.size(); ++i) { uint64_t cur = C[i]; C[i] = sum; sum += cur; } vector<index_type> phi(T.size()); for (iter(T) i = 0; i < T.size(); ++i) { phi[C[T[i]]] = i; ++C[T[i]]; } vector<uint8_t> S(T.size()); index_type j = pid; for (iter(T) i = 0; i < T.size(); ++i) { S[i] = T[phi[j]]; j = phi[j]; } return S; } string read_oneline(const string &ifname) { ifstream ifs(ifname); if (!ifs) { perror(ifname.c_str()); exit(EXIT_FAILURE); } string s; getline(ifs, s); return s; } void show_string_in_hex(const string &s) { for (iter(s) i = 0; i < s.size(); ++i) { if (i > 0) cout << ' '; unsigned char c = s[i]; cerr << "0x" << hex << (int)c; } cerr << endl; } bool is_utf8_start_char(unsigned char c) { // 2バイト目以降は先頭ビットが10である if ((c >> 6) == 2) return false; return true; } pair<index_type, index_type> fm_index(const WaveletMatrix &wat, const string &p) { index_type sp = 0; index_type ep = wat.length(); for (iter(p) i = 0; i < p.size(); ++i) { unsigned char c = p[p.size() - 1 - i]; sp = wat.rank_lt(c) + wat.rank(c, sp); ep = wat.rank_lt(c) + wat.rank(c, ep); if (sp >= ep) return make_pair(-1, -1); } return make_pair(sp, ep); } vector<vector<string>> read_datasets(const string &cfname) { ifstream ifs(cfname); if (!ifs) { perror(cfname.c_str()); exit(EXIT_FAILURE); } picojson::value json; string err = picojson::parse(json, ifs); if (!err.empty()) { cerr << err << endl; exit(EXIT_FAILURE); } picojson::array &array = json.get<picojson::array>(); vector<vector<string>> ret; for (const picojson::value &it : array) { picojson::object book = it.get<picojson::object>(); string filename = book["filename"].get<string>(); string title = book["title"].get<string>(); string author = book["author"].get<string>(); vector<string> vs = { read_oneline(filename), title, author }; ret.emplace_back(vs); } return ret; } void search(const string &query, const int num, const WaveletMatrix &wt_text, const WaveletMatrix &wt_freq, const vector<vector<string>> &datasets) { auto spep = fm_index(wt_text, query); vector<pair<WaveletMatrix::Index, int>> res = wt_freq.topk<int>(spep.first, spep.second, num); for (const auto &r : res) { if (r.second == datasets.size()) continue; cout << r.first << '\t' << datasets[r.second][1] << '\t' << datasets[r.second][2] << endl; } } int main(int argc, char *argv[]) { cmdline::parser parser; parser.add<string>("config", 'c', "config json file", /* need = */ true); parser.add<string>("query", 'q', "query string", /* need = */ false); parser.add<int>("number", 'n', "display first `number` lines", /* need = */ false, /* default = */ 20); parser.add("interact", 'i', "launch interactive shell"); parser.add("help", 'h', "show help"); if (!parser.parse(argc, argv) || parser.exist("help")) { cerr << parser.error_full() << parser.usage() << endl; exit(EXIT_FAILURE); } if (parser.exist("query") == false && parser.exist("interact") == false) { cerr << "you should enable --query or --interact" << endl; exit(EXIT_FAILURE); } string cfname = parser.get<string>("config"); vector<vector<string>> datasets = read_datasets(cfname); WaveletMatrix wt_text(8); WaveletMatrix wt_freq(9); { vector<uint8_t> SV; for (iter(datasets) i = 0; i < datasets.size(); ++i) { SV.insert(SV.end(), datasets[i][0].begin(), datasets[i][0].end()); SV.push_back('\n'); } SV.push_back('\0'); vector<index_type> SA(SV.size()); saisxx(SV.begin(), SA.begin(), (index_type)SV.size()); { vector<uint8_t> TV = bwt(SV); wt_text.init(TV); } { vector<uint64_t> array(SV.size()); uint64_t sum = 0; for (iter(datasets) i = 0; i < datasets.size(); ++i) { for (iter(datasets[i][0]) j = 0; j < datasets[i][0].size(); ++j) { array[sum] = i; ++sum; } array[sum] = datasets.size(); ++sum; } array[sum] = datasets.size(); ++sum; vector<uint64_t> rev(SV.size()); for (iter(SV) i = 0; i < SV.size(); ++i) { rev[i] = array[SA[i]]; } wt_freq.init(rev); } } if (parser.exist("query")) { string q = parser.get<string>("query"); search(q, parser.get<int>("number"), wt_text, wt_freq, datasets); } if (parser.exist("interact")) { while (true) { cout << "query> "; string q; if (cin >> q) { search(q, parser.get<int>("number"), wt_text, wt_freq, datasets); } else { break; } } } } <|endoftext|>
<commit_before>#include "NeuralNetwork.hpp" using namespace std; NeuralNetwork::NeuralNetwork(const int nbi, const int nbh, const int nbo, const bool regression) : ni(nbi+1), nh(nbh+1), no(nbo), regression(regression), ai(ni, 1.0), ah(nh, 1.0), ao(no, 1.0) { wi = NeuralNetwork::makeMatrix(ni, nh); wo = NeuralNetwork::makeMatrix(nh, no); uniform_real_distribution<float> dist(-1, 1); for (int i = 0; i < ni; i++) { for (int j = 0; j < nh; j++) { wi[i][j] = dist(rng); } } for (int j = 0; j < nh; j++) { for (int k = 0; k < no; k++) { wo[j][k] = dist(rng); } } ci = makeMatrix(ni, nh); co = makeMatrix(nh, no); } vector<vector<float>> NeuralNetwork::makeMatrix(const int width, const int height, const float fill) { vector<vector<float>> matrix; for (int i = 0; i < width; i++) { matrix.push_back(vector<float>(height, fill)); } return matrix; } float NeuralNetwork::sigmoid(const float x) { return tanh(x); } float NeuralNetwork::dsigmoid(const float y) { return 1.0 - y*y; } vector<float> NeuralNetwork::update(const vector<float>& inputs) { if (inputs.size() != ni-1) { throw string("wrong number of inputs"); } for (unsigned int i = 0; i < ni-1; i++) { ai[i] = inputs[i]; } for (unsigned int j = 0; j < nh-1; j++) { float total = 0.0; for (int i = 0; i < ni; i++) { total += ai[i] * wi[i][j]; } ah[j] = sigmoid(total); } for (unsigned int k = 0; k < no; k++) { float total = 0.0; for (unsigned int j = 0; j < nh; j++) { total += ah[j] * wo[j][k]; } ao[k] = total; if (!regression) { ao[k] = sigmoid(total); } } return ao; } float NeuralNetwork::backPropagate(const vector<float>& targets, const float lr, const float mf) { if (targets.size() != no) { throw string("wrong number of target values"); } vector<float> output_deltas(no, 1.0); for (unsigned int k = 0; k < no; k++) { output_deltas[k] = targets[k] - ao[k]; if (!regression) { output_deltas[k] = dsigmoid(ao[k])*output_deltas[k]; } } vector<float> hidden_deltas(nh, 0.0); for (unsigned int j = 0; j < nh; j++) { float error = 0.0; for (unsigned int k = 0; k < no; k++) { error += output_deltas[k]*wo[j][k]; } hidden_deltas[j] = dsigmoid(ah[j])*error; } for (unsigned int j = 0; j < nh; j++) { for (unsigned int k = 0; k < no; k++) { float change = output_deltas[k]*ah[j]; wo[j][k] = wo[j][k] + lr*change + mf*co[j][k]; co[j][k] = change; } } for (unsigned int i = 0; i < ni; i++) { for (unsigned int j = 0; j < nh; j++) { float change = hidden_deltas[j]*ai[i]; wi[i][j] = wi[i][j] + lr*change + mf*ci[i][j]; ci[i][j] = change; } } float error = 0.0; for (unsigned int k = 0; k < targets.size(); k++) { error += 0.5*((targets[k]-ao[k])*(targets[k]-ao[k])); } return error; } vector<vector<float>> NeuralNetwork::test(const vector<vector<vector<float>>>& patterns, const bool verbose) { vector<vector<float>> tmp; for (const auto& p : patterns) { if (verbose) { cout << p[0][0] << " -> " << update(p[0])[0] << endl; } tmp.push_back(update(p[0])); } return tmp; } void NeuralNetwork::train(const vector<vector<vector<float>>>& patterns, const int iterations, const float lr, const float mf, const bool verbose) { for (int i = 0; i < iterations; i++) { float error = 0; for (const auto& p : patterns) { update(p[0]); float tmp = backPropagate(p[1], lr, mf); error += tmp; } if (i % 100 == 0) { cout << "error rate = " << error << endl; } } } <commit_msg>another whitespace fix<commit_after>#include "NeuralNetwork.hpp" using namespace std; NeuralNetwork::NeuralNetwork(const int nbi, const int nbh, const int nbo, const bool regression) : ni(nbi+1), nh(nbh+1), no(nbo), regression(regression), ai(ni, 1.0), ah(nh, 1.0), ao(no, 1.0) { wi = NeuralNetwork::makeMatrix(ni, nh); wo = NeuralNetwork::makeMatrix(nh, no); uniform_real_distribution<float> dist(-1, 1); for (int i = 0; i < ni; i++) { for (int j = 0; j < nh; j++) { wi[i][j] = dist(rng); } } for (int j = 0; j < nh; j++) { for (int k = 0; k < no; k++) { wo[j][k] = dist(rng); } } ci = makeMatrix(ni, nh); co = makeMatrix(nh, no); } vector<vector<float>> NeuralNetwork::makeMatrix(const int width, const int height, const float fill) { vector<vector<float>> matrix; for (int i = 0; i < width; i++) { matrix.push_back(vector<float>(height, fill)); } return matrix; } float NeuralNetwork::sigmoid(const float x) { return tanh(x); } float NeuralNetwork::dsigmoid(const float y) { return 1.0 - y*y; } vector<float> NeuralNetwork::update(const vector<float>& inputs) { if (inputs.size() != ni-1) { throw string("wrong number of inputs"); } for (unsigned int i = 0; i < ni-1; i++) { ai[i] = inputs[i]; } for (unsigned int j = 0; j < nh-1; j++) { float total = 0.0; for (int i = 0; i < ni; i++) { total += ai[i] * wi[i][j]; } ah[j] = sigmoid(total); } for (unsigned int k = 0; k < no; k++) { float total = 0.0; for (unsigned int j = 0; j < nh; j++) { total += ah[j] * wo[j][k]; } ao[k] = total; if (!regression) { ao[k] = sigmoid(total); } } return ao; } float NeuralNetwork::backPropagate(const vector<float>& targets, const float lr, const float mf) { if (targets.size() != no) { throw string("wrong number of target values"); } vector<float> output_deltas(no, 1.0); for (unsigned int k = 0; k < no; k++) { output_deltas[k] = targets[k] - ao[k]; if (!regression) { output_deltas[k] = dsigmoid(ao[k])*output_deltas[k]; } } vector<float> hidden_deltas(nh, 0.0); for (unsigned int j = 0; j < nh; j++) { float error = 0.0; for (unsigned int k = 0; k < no; k++) { error += output_deltas[k]*wo[j][k]; } hidden_deltas[j] = dsigmoid(ah[j])*error; } for (unsigned int j = 0; j < nh; j++) { for (unsigned int k = 0; k < no; k++) { float change = output_deltas[k]*ah[j]; wo[j][k] = wo[j][k] + lr*change + mf*co[j][k]; co[j][k] = change; } } for (unsigned int i = 0; i < ni; i++) { for (unsigned int j = 0; j < nh; j++) { float change = hidden_deltas[j]*ai[i]; wi[i][j] = wi[i][j] + lr*change + mf*ci[i][j]; ci[i][j] = change; } } float error = 0.0; for (unsigned int k = 0; k < targets.size(); k++) { error += 0.5*((targets[k]-ao[k])*(targets[k]-ao[k])); } return error; } vector<vector<float>> NeuralNetwork::test(const vector<vector<vector<float>>>& patterns, const bool verbose) { vector<vector<float>> tmp; for (const auto& p : patterns) { if (verbose) { cout << p[0][0] << " -> " << update(p[0])[0] << endl; } tmp.push_back(update(p[0])); } return tmp; } void NeuralNetwork::train(const vector<vector<vector<float>>>& patterns, const int iterations, const float lr, const float mf, const bool verbose) { for (int i = 0; i < iterations; i++) { float error = 0; for (const auto& p : patterns) { update(p[0]); float tmp = backPropagate(p[1], lr, mf); error += tmp; } if (i % 100 == 0) { cout << "error rate = " << error << endl; } } } <|endoftext|>
<commit_before>namespace iox { template <uint64_t Capacity, typename ValueType> IndexQueue<Capacity, ValueType>::IndexQueue(ConstructEmpty_t) : m_readPosition(Index(Capacity)) , m_writePosition(Index(Capacity)) { } template <uint64_t Capacity, typename ValueType> IndexQueue<Capacity, ValueType>::IndexQueue(ConstructFull_t) : m_readPosition(Index(0)) , m_writePosition(Index(Capacity)) { for (uint64_t i = 0; i < Capacity; ++i) { m_cells[i].store(Index(i)); } } template <uint64_t Capacity, typename ValueType> constexpr uint64_t IndexQueue<Capacity, ValueType>::capacity() { return Capacity; } template <uint64_t Capacity, typename ValueType> void IndexQueue<Capacity, ValueType>::push(ValueType index) { // we need the CAS loop here since we may fail due to concurrent push operations // note that we are always able to succeed to publish since we have // enough capacity for all unique indices used // case analyis // (1) loaded value is exactly one cycle behind: // value is from the last cycle // we can try to publish // (2) loaded value has the same cycle: // some other push has published but not updated the write position // help updating the write position // (3) loaded value is more than one cycle behind: // this should only happen due to wrap around when push is interrupted for a long time // reload write position and try again // note that a complete wraparound can lead to a false detection of 1) (ABA problem) // but this is very unlikely with e.g. a 64 bit value type // (4) loaded value is some cycle ahead: // write position is outdated, there must have been other pushes concurrently // reload write position and try again constexpr bool notPublished = true; auto writePosition = loadNextWritePosition(); do { auto oldValue = loadValueAt(writePosition); auto isFreeToPublish = [&]() { return oldValue.isOneCycleBehind(writePosition); }; if (isFreeToPublish()) { // case (1) Index newValue(index, writePosition.getCycle()); // if publish fails, another thread has published before us if (tryToPublishAt(writePosition, oldValue, newValue)) { break; } } // even if we are not able to publish, we check whether some other push has already updated the writePosition // before trying again to publish auto writePositionWasNotUpdated = [&]() { return oldValue.getCycle() == writePosition.getCycle(); }; if (writePositionWasNotUpdated()) { // case (2) // the writePosition was not updated yet by another push but the value was already written // help with the update updateNextWritePosition(writePosition); } else { // case (3) and (4) // note: we do not call updateNextWritePosition here, the CAS is bound to fail anyway // (our value of writePosition is not up to date so needs to be loaded again) writePosition = loadNextWritePosition(); } } while (notPublished); updateNextWritePosition(writePosition); } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::pop(ValueType& index) { // we need the CAS loop here since we may fail due to concurrent pop operations // we leave when we detect an empty queue, otherwise we retry the pop operation // case analyis // (1) loaded value has the same cycle: // value was not popped before // try to get ownership // (2) loaded value is exactly one cycle behind: // value is from the last cycle which means the queue is empty // return false // (3) loaded value is more than one cycle behind: // this should only happen due to wrap around when push is interrupted for a long time // reload read position and try again // (4) loaded value is some cycle ahead: // read position is outdated, there must have been pushes concurrently // reload read position and try again constexpr bool ownerShipGained = true; Index value; auto readPosition = loadNextReadPosition(); do { value = loadValueAt(readPosition); // we only dequeue if value and readPosition are in the same cycle auto isValidToRead = [&]() { return readPosition.getCycle() == value.getCycle(); }; // readPosition is ahead by one cycle, queue was empty at loadValueAt(..) auto isEmpty = [&]() { return value.isOneCycleBehind(readPosition); }; if (isValidToRead()) { // case (1) if (tryToGainOwnershipAt(readPosition)) { break; // pop successful } else { // retry, readPosition was already updated via CAS in tryToGainOwnershipAt // todo: maybe refactor to eliminate the continue but still skip the reload of // readPosition continue; } } else if (isEmpty()) { // case (2) return false; } // else readPosition is outdated, retry operation // case (3) and (4) readPosition = loadNextReadPosition(); } while (!ownerShipGained); // we leave if we gain ownership of readPosition index = value.getIndex(); return true; } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::popIfFull(ValueType& index) { // we do NOT need a CAS loop here since if we detect that the queue is not full // someone else popped an element and we do not retry to check whether it was filled AGAIN // concurrently (which will usually not be the case and then we would return false anyway) // if it is filled again we can (and will) retry popIfFull from the call site // the queue is full if and only if write position and read position are the same but read position is // one cycle behind write position // unfortunately it seems impossible in this design to check this condition without loading // write posiion and read position (which causes more contention) auto writePosition = loadNextWritePosition(); auto readPosition = loadNextReadPosition(); auto value = loadValueAt(readPosition); auto isFull = [&]() { return writePosition.getIndex() == readPosition.getIndex() && readPosition.isOneCycleBehind(writePosition); }; if (isFull()) { if (tryToGainOwnershipAt(readPosition)) { index = value.getIndex(); return true; } } // else someone else has popped an index return false; } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::empty() { auto oldReadIndex = m_readPosition.load(std::memory_order_relaxed); auto value = m_cells[oldReadIndex.getIndex()].load(std::memory_order_relaxed); // if m_readPosition is ahead by one cycle compared to the value stored at head, // the queue was empty at the time of the loads above (but might not be anymore!) return value.isOneCycleBehind(oldReadIndex); } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::Index IndexQueue<Capacity, ValueType>::loadNextReadPosition() const { return m_readPosition.load(std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::Index IndexQueue<Capacity, ValueType>::loadNextWritePosition() const { return m_writePosition.load(std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::Index IndexQueue<Capacity, ValueType>::loadValueAt(typename IndexQueue<Capacity, ValueType>::Index position) const { return m_cells[position.getIndex()].load(std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::tryToPublishAt(typename IndexQueue<Capacity, ValueType>::Index writePosition, Index& oldValue, Index newValue) { return m_cells[writePosition.getIndex()].compare_exchange_strong( oldValue, newValue, std::memory_order_relaxed, std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> void IndexQueue<Capacity, ValueType>::updateNextWritePosition(Index& writePosition) { // compare_exchange updates writePosition if NOT successful Index newWritePosition(writePosition + 1); auto updateSucceeded = m_writePosition.compare_exchange_strong( writePosition, newWritePosition, std::memory_order_relaxed, std::memory_order_relaxed); // not needed in the successful case, we do not retry // if (updateSucceeded) // { // writePosition = newWritePosition; // } } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::tryToGainOwnershipAt(Index& oldReadPosition) { Index newReadPosition(oldReadPosition + 1); return m_readPosition.compare_exchange_strong( oldReadPosition, newReadPosition, std::memory_order_relaxed, std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> void IndexQueue<Capacity, ValueType>::push(const UniqueIndex& index) { push(*index); } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::UniqueIndex IndexQueue<Capacity, ValueType>::pop() { ValueType value; if (pop(value)) { return UniqueIndex(value); } return UniqueIndex::invalid; } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::UniqueIndex IndexQueue<Capacity, ValueType>::popIfFull() { ValueType value; if (popIfFull(value)) { return UniqueIndex(value); } return UniqueIndex::invalid; } } // namespace iox<commit_msg>iox-#80 refactor code in index queue for comprehensibility<commit_after>namespace iox { template <uint64_t Capacity, typename ValueType> IndexQueue<Capacity, ValueType>::IndexQueue(ConstructEmpty_t) : m_readPosition(Index(Capacity)) , m_writePosition(Index(Capacity)) { } template <uint64_t Capacity, typename ValueType> IndexQueue<Capacity, ValueType>::IndexQueue(ConstructFull_t) : m_readPosition(Index(0)) , m_writePosition(Index(Capacity)) { for (uint64_t i = 0; i < Capacity; ++i) { m_cells[i].store(Index(i)); } } template <uint64_t Capacity, typename ValueType> constexpr uint64_t IndexQueue<Capacity, ValueType>::capacity() { return Capacity; } template <uint64_t Capacity, typename ValueType> void IndexQueue<Capacity, ValueType>::push(ValueType index) { // we need the CAS loop here since we may fail due to concurrent push operations // note that we are always able to succeed to publish since we have // enough capacity for all unique indices used // case analyis // (1) loaded value is exactly one cycle behind: // value is from the last cycle // we can try to publish // (2) loaded value has the same cycle: // some other push has published but not updated the write position // help updating the write position // (3) loaded value is more than one cycle behind: // this should only happen due to wrap around when push is interrupted for a long time // reload write position and try again // note that a complete wraparound can lead to a false detection of 1) (ABA problem) // but this is very unlikely with e.g. a 64 bit value type // (4) loaded value is some cycle ahead: // write position is outdated, there must have been other pushes concurrently // reload write position and try again constexpr bool notPublished = true; auto writePosition = loadNextWritePosition(); do { auto oldValue = loadValueAt(writePosition); auto cellIsFree = oldValue.isOneCycleBehind(writePosition); if (cellIsFree) { // case (1) Index newValue(index, writePosition.getCycle()); // if publish fails, another thread has published before us if (tryToPublishAt(writePosition, oldValue, newValue)) { break; } } // even if we are not able to publish, we check whether some other push has already updated the writePosition // before trying again to publish auto writePositionRequiresUpdate = oldValue.getCycle() == writePosition.getCycle(); if (writePositionRequiresUpdate) { // case (2) // the writePosition was not updated yet by another push but the value was already written // help with the update updateNextWritePosition(writePosition); } else { // case (3) and (4) // note: we do not call updateNextWritePosition here, the CAS is bound to fail anyway // (since our value of writePosition is not up to date so needs to be loaded again) writePosition = loadNextWritePosition(); } } while (notPublished); updateNextWritePosition(writePosition); } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::pop(ValueType& index) { // we need the CAS loop here since we may fail due to concurrent pop operations // we leave when we detect an empty queue, otherwise we retry the pop operation // case analyis // (1) loaded value has the same cycle: // value was not popped before // try to get ownership // (2) loaded value is exactly one cycle behind: // value is from the last cycle which means the queue is empty // return false // (3) loaded value is more than one cycle behind: // this should only happen due to wrap around when push is interrupted for a long time // reload read position and try again // (4) loaded value is some cycle ahead: // read position is outdated, there must have been pushes concurrently // reload read position and try again constexpr bool ownerShipGained = true; Index value; auto readPosition = loadNextReadPosition(); do { value = loadValueAt(readPosition); // we only dequeue if value and readPosition are in the same cycle auto cellIsValidToRead = readPosition.getCycle() == value.getCycle(); if (cellIsValidToRead) { // case (1) if (tryToGainOwnershipAt(readPosition)) { break; // pop successful } // retry, readPosition was already updated via CAS in tryToGainOwnershipAt } else { // readPosition is ahead by one cycle, queue was empty at loadValueAt(..) auto isEmpty = value.isOneCycleBehind(readPosition); if (isEmpty) { // case (2) return false; } // case (3) and (4) requires loading readPosition again readPosition = loadNextReadPosition(); } // readPosition is outdated, retry operation } while (!ownerShipGained); // we leave if we gain ownership of readPosition index = value.getIndex(); return true; } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::popIfFull(ValueType& index) { // we do NOT need a CAS loop here since if we detect that the queue is not full // someone else popped an element and we do not retry to check whether it was filled AGAIN // concurrently (which will usually not be the case and then we would return false anyway) // if it is filled again we can (and will) retry popIfFull from the call site // the queue is full if and only if write position and read position are the same but read position is // one cycle behind write position // unfortunately it seems impossible in this design to check this condition without loading // write posiion and read position (which causes more contention) auto writePosition = loadNextWritePosition(); auto readPosition = loadNextReadPosition(); auto value = loadValueAt(readPosition); auto isFull = writePosition.getIndex() == readPosition.getIndex() && readPosition.isOneCycleBehind(writePosition); if (isFull) { if (tryToGainOwnershipAt(readPosition)) { index = value.getIndex(); return true; } } // otherwise someone else has dequeued an index and the queue was not full at the start of this popIfFull return false; } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::empty() { auto oldReadIndex = m_readPosition.load(std::memory_order_relaxed); auto value = m_cells[oldReadIndex.getIndex()].load(std::memory_order_relaxed); // if m_readPosition is ahead by one cycle compared to the value stored at head, // the queue was empty at the time of the loads above (but might not be anymore!) return value.isOneCycleBehind(oldReadIndex); } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::Index IndexQueue<Capacity, ValueType>::loadNextReadPosition() const { return m_readPosition.load(std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::Index IndexQueue<Capacity, ValueType>::loadNextWritePosition() const { return m_writePosition.load(std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::Index IndexQueue<Capacity, ValueType>::loadValueAt(typename IndexQueue<Capacity, ValueType>::Index position) const { return m_cells[position.getIndex()].load(std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::tryToPublishAt(typename IndexQueue<Capacity, ValueType>::Index writePosition, Index& oldValue, Index newValue) { return m_cells[writePosition.getIndex()].compare_exchange_strong( oldValue, newValue, std::memory_order_relaxed, std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> void IndexQueue<Capacity, ValueType>::updateNextWritePosition(Index& writePosition) { // compare_exchange updates writePosition if NOT successful Index newWritePosition(writePosition + 1); auto updateSucceeded = m_writePosition.compare_exchange_strong( writePosition, newWritePosition, std::memory_order_relaxed, std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> bool IndexQueue<Capacity, ValueType>::tryToGainOwnershipAt(Index& oldReadPosition) { Index newReadPosition(oldReadPosition + 1); return m_readPosition.compare_exchange_strong( oldReadPosition, newReadPosition, std::memory_order_relaxed, std::memory_order_relaxed); } template <uint64_t Capacity, typename ValueType> void IndexQueue<Capacity, ValueType>::push(const UniqueIndex& index) { push(*index); } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::UniqueIndex IndexQueue<Capacity, ValueType>::pop() { ValueType value; if (pop(value)) { return UniqueIndex(value); } return UniqueIndex::invalid; } template <uint64_t Capacity, typename ValueType> typename IndexQueue<Capacity, ValueType>::UniqueIndex IndexQueue<Capacity, ValueType>::popIfFull() { ValueType value; if (popIfFull(value)) { return UniqueIndex(value); } return UniqueIndex::invalid; } } // namespace iox<|endoftext|>
<commit_before>namespace mant { namespace bbob { template <typename T = double> class BlackBoxOptimisationBenchmark : public OptimisationProblem<T, T> { static_assert(std::is_floating_point<T>::value, "T must be a floating point type."); public: explicit BlackBoxOptimisationBenchmark( const std::size_t numberOfDimensions) noexcept; virtual ~BlackBoxOptimisationBenchmark() = default; protected: arma::Col<T> getRandomParameterTranslation() const noexcept; arma::Col<T> getParameterConditioning( const T conditionNumber) const noexcept; arma::Col<T> getConditionedParameter( const arma::Col<T>& parameter) const noexcept; arma::Col<T> getAsymmetricParameter( const T asymmetry, const arma::Col<T>& parameter) const noexcept; T getOscillatedValue( const T oscilliation) const noexcept; arma::Col<T> getOscillatedParameter( const arma::Col<T>& parameter) const noexcept; T getBoundConstraintsValue( const arma::Col<T>& parameter) const noexcept; #if defined(MANTELLA_USE_PARALLEL_ALGORITHMS) friend class OptimisationAlgorithm; std::vector<double> serialise() const noexcept; void deserialise( const std::vector<double>& serialisedOptimisationProblem); #endif }; // // Implementation // template <typename T> BlackBoxOptimisationBenchmark<T>::BlackBoxOptimisationBenchmark( const std::size_t numberOfDimensions) noexcept : OptimisationProblem<T>(numberOfDimensions) { this->setLowerBounds(arma::zeros<arma::Col<T>>(this->numberOfDimensions_) - 5.0); this->setUpperBounds(arma::zeros<arma::Col<T>>(this->numberOfDimensions_) + 5.0); this->setObjectiveValueTranslation(std::min(1000.0, std::max(-1000.0, std::floor(std::cauchy_distribution<double>(0.0, 100.0)(Rng::getGenerator()) * 100) / 100))); this->setAcceptableObjectiveValue(this->objectiveValueTranslation_ + 1.0e-8); } template <typename T> arma::Col<T> BlackBoxOptimisationBenchmark<T>::getRandomParameterTranslation() const noexcept { arma::Col<T> randomParameterTranslation = arma::floor(arma::randu<arma::Col<T>>(this->numberOfDimensions_) * 1.0e4) / 1.0e4 * 8.0 - 4.0; randomParameterTranslation.elem(arma::find(randomParameterTranslation == 0)).fill(-1.0e-5); return randomParameterTranslation; } template <typename T> arma::Col<T> BlackBoxOptimisationBenchmark<T>::getParameterConditioning( const T conditionNumber) const noexcept { arma::Col<T> parameterConditioning = arma::linspace<arma::Col<T>>(0.0, 1.0, this->numberOfDimensions_); for (T& conditioning : parameterConditioning) { conditioning = std::pow(conditionNumber, conditioning); } return parameterConditioning; } template <typename T> arma::Col<T> BlackBoxOptimisationBenchmark<T>::getConditionedParameter( const arma::Col<T>& parameter) const noexcept { arma::Col<T> conditionedParameter = arma::linspace<arma::Col<T>>(0.0, 1.0, this->numberOfDimensions_); for (std::size_t n = 0; n < parameter.n_elem; ++n) { conditionedParameter(n) = std::pow(parameter(n), conditionedParameter(n)); } return conditionedParameter; } template <typename T> arma::Col<T> BlackBoxOptimisationBenchmark<T>::getAsymmetricParameter( const T asymmetry, const arma::Col<T>& parameter) const noexcept { arma::Col<T> asymmetricParameter(parameter.n_elem); const arma::Col<T>& spacing = arma::linspace<arma::Col<T>>(0.0, 1.0, this->numberOfDimensions_); for (std::size_t n = 0; n < parameter.n_elem; ++n) { const T value = parameter(n); if (value > 0.0) { asymmetricParameter(n) = std::pow(value, 1 + asymmetry * spacing(n) * std::sqrt(value)); } else { asymmetricParameter(n) = value; } } return asymmetricParameter; } template <typename T> T BlackBoxOptimisationBenchmark<T>::getOscillatedValue( const T value) const noexcept { if (value != 0.0) { T c1; T c2; if (value > 0.0) { c1 = 10.0; c2 = 7.9; } else { c1 = 5.5; c2 = 3.1; } const T& logAbsoluteValue = std::log(std::abs(value)); return std::copysign(1.0, value) * std::exp(logAbsoluteValue + 0.049 * (std::sin(c1 * logAbsoluteValue) + std::sin(c2 * logAbsoluteValue))); } else { return 0.0; } } template <typename T> arma::Col<T> BlackBoxOptimisationBenchmark<T>::getOscillatedParameter( const arma::Col<T>& parameter) const noexcept { arma::Col<T> oscillatedParameter(parameter.n_elem); for (std::size_t n = 0; n < parameter.n_elem; ++n) { oscillatedParameter(n) = getOscillatedValue(parameter(n)); } return oscillatedParameter; } template <typename T> T BlackBoxOptimisationBenchmark<T>::getBoundConstraintsValue( const arma::Col<T>& parameter) const noexcept { T boundConstraintsValue = 0.0; for (std::size_t n = 0; n < parameter.n_elem; ++n) { boundConstraintsValue += std::pow(std::max(0.0, std::abs(parameter(n)) - 5.0), 2.0); } return boundConstraintsValue; } #if defined(MANTELLA_USE_PARALLEL_ALGORITHMS) template <typename T> std::vector<double> BlackBoxOptimisationBenchmark<T>::serialise() const noexcept { return OptimisationProblem<T, T>::serialise(); } template <typename T> void BlackBoxOptimisationBenchmark<T>::deserialise( const std::vector<double>& serialisedOptimisationProblem) { OptimisationProblem<T, T>::deserialise(serialisedOptimisationProblem); } #endif } } <commit_msg>Added codomain templating to the BBOB base class<commit_after>namespace mant { namespace bbob { template <typename T, typename U = double> class BlackBoxOptimisationBenchmark : public OptimisationProblem<T, U> { static_assert(std::is_floating_point<T>::value, "T must be a floating point type."); static_assert(std::is_floating_point<U>::value, "The codomain type U must be a floating point type."); public: explicit BlackBoxOptimisationBenchmark( const std::size_t numberOfDimensions) noexcept; virtual ~BlackBoxOptimisationBenchmark() = default; protected: arma::Col<T> getRandomParameterTranslation() const noexcept; arma::Col<T> getParameterConditioning( const T conditionNumber) const noexcept; arma::Col<T> getConditionedParameter( const arma::Col<T>& parameter) const noexcept; arma::Col<T> getAsymmetricParameter( const T asymmetry, const arma::Col<T>& parameter) const noexcept; U getOscillatedValue( const U oscilliation) const noexcept; T getOscillatedValue( const T oscilliation) const noexcept; arma::Col<T> getOscillatedParameter( const arma::Col<T>& parameter) const noexcept; U getBoundConstraintsValue( const arma::Col<T>& parameter) const noexcept; #if defined(MANTELLA_USE_PARALLEL_ALGORITHMS) friend class OptimisationAlgorithm; std::vector<double> serialise() const noexcept; void deserialise( const std::vector<double>& serialisedOptimisationProblem); #endif }; // // Implementation // template <typename T, typename U> BlackBoxOptimisationBenchmark<T, U>::BlackBoxOptimisationBenchmark( const std::size_t numberOfDimensions) noexcept : OptimisationProblem<T, U>(numberOfDimensions) { this->setLowerBounds(arma::zeros<arma::Col<T>>(this->numberOfDimensions_) - static_cast<T>(5.0L)); this->setUpperBounds(arma::zeros<arma::Col<T>>(this->numberOfDimensions_) + static_cast<T>(5.0L)); this->setObjectiveValueTranslation(std::min(static_cast<U>(1000.0L), std::max(static_cast<U>(-1000.0L), std::floor(std::cauchy_distribution<U>(static_cast<U>(0.0L), static_cast<U>(100.0L))(Rng::getGenerator()) * static_cast<U>(100.0L)) / static_cast<U>(100.0L)))); this->setAcceptableObjectiveValue(this->objectiveValueTranslation_ + static_cast<U>(1.0e-8L)); } template <typename T, typename U> arma::Col<T> BlackBoxOptimisationBenchmark<T, U>::getRandomParameterTranslation() const noexcept { arma::Col<T> randomParameterTranslation = arma::floor(arma::randu<arma::Col<T>>(this->numberOfDimensions_) * static_cast<T>(1.0e4L)) / static_cast<T>(1.0e4L) * static_cast<T>(8.0L) - static_cast<T>(4.0L); randomParameterTranslation.elem(arma::find(randomParameterTranslation == static_cast<T>(0.0L))).fill(static_cast<T>(-1.0e-5L)); return randomParameterTranslation; } template <typename T, typename U> arma::Col<T> BlackBoxOptimisationBenchmark<T, U>::getParameterConditioning( const T conditionNumber) const noexcept { arma::Col<T> parameterConditioning = arma::linspace<arma::Col<T>>(static_cast<T>(0.0L), static_cast<T>(1.0L), this->numberOfDimensions_); for (T& conditioning : parameterConditioning) { conditioning = std::pow(conditionNumber, conditioning); } return parameterConditioning; } template <typename T, typename U> arma::Col<T> BlackBoxOptimisationBenchmark<T, U>::getConditionedParameter( const arma::Col<T>& parameter) const noexcept { arma::Col<T> conditionedParameter = arma::linspace<arma::Col<T>>(static_cast<T>(0.0L), static_cast<T>(1.0L), this->numberOfDimensions_); for (std::size_t n = 0; n < parameter.n_elem; ++n) { conditionedParameter(n) = std::pow(parameter(n), conditionedParameter(n)); } return conditionedParameter; } template <typename T, typename U> arma::Col<T> BlackBoxOptimisationBenchmark<T, U>::getAsymmetricParameter( const T asymmetry, const arma::Col<T>& parameter) const noexcept { arma::Col<T> asymmetricParameter(parameter.n_elem); const arma::Col<T>& spacing = arma::linspace<arma::Col<T>>(static_cast<T>(0.0L), static_cast<T>(1.0L), this->numberOfDimensions_); for (std::size_t n = 0; n < parameter.n_elem; ++n) { const T value = parameter(n); if (value > static_cast<T>(0.0L)) { asymmetricParameter(n) = std::pow(value, static_cast<T>(1.0L) + asymmetry * spacing(n) * std::sqrt(value)); } else { asymmetricParameter(n) = value; } } return asymmetricParameter; } template <typename T, typename U> U BlackBoxOptimisationBenchmark<T, U>::getOscillatedValue( const U value) const noexcept { if (value != static_cast<U>(0.0L)) { T c1; T c2; if (value > static_cast<U>(0.0L)) { c1 = static_cast<U>(10.0L); c2 = static_cast<U>(7.9L); } else { c1 = static_cast<U>(5.5L); c2 = static_cast<U>(3.1L); } const T& logAbsoluteValue = std::log(std::abs(value)); return std::copysign(static_cast<U>(1.0L), value) * std::exp(logAbsoluteValue + static_cast<U>(0.049L) * (std::sin(c1 * logAbsoluteValue) + std::sin(c2 * logAbsoluteValue))); } else { return static_cast<U>(0.0L); } } template <typename T, typename U> T BlackBoxOptimisationBenchmark<T, U>::getOscillatedValue( const T value) const noexcept { if (value != static_cast<U>(0.0L)) { T c1; T c2; if (value > static_cast<U>(0.0L)) { c1 = static_cast<U>(10.0L); c2 = static_cast<U>(7.9L); } else { c1 = static_cast<U>(5.5L); c2 = static_cast<U>(3.1L); } const T& logAbsoluteValue = std::log(std::abs(value)); return std::copysign(static_cast<U>(1.0L), value) * std::exp(logAbsoluteValue + static_cast<U>(0.049L) * (std::sin(c1 * logAbsoluteValue) + std::sin(c2 * logAbsoluteValue))); } else { return static_cast<U>(0.0L); } } template <typename T, typename U> arma::Col<T> BlackBoxOptimisationBenchmark<T, U>::getOscillatedParameter( const arma::Col<T>& parameter) const noexcept { arma::Col<T> oscillatedParameter(parameter.n_elem); for (std::size_t n = 0; n < parameter.n_elem; ++n) { oscillatedParameter(n) = getOscillatedValue(parameter(n)); } return oscillatedParameter; } template <typename T, typename U> U BlackBoxOptimisationBenchmark<T, U>::getBoundConstraintsValue( const arma::Col<T>& parameter) const noexcept { U boundConstraintsValue = static_cast<U>(0.0L); for (std::size_t n = 0; n < parameter.n_elem; ++n) { boundConstraintsValue += std::pow(std::max(static_cast<U>(0.0L), std::abs(parameter(n)) - static_cast<U>(5.0L)), static_cast<U>(2.0L)); } return boundConstraintsValue; } #if defined(MANTELLA_USE_PARALLEL_ALGORITHMS) template <typename T, typename U> std::vector<double> BlackBoxOptimisationBenchmark<T, U>::serialise() const noexcept { return OptimisationProblem<T, U>::serialise(); } template <typename T, typename U> void BlackBoxOptimisationBenchmark<T, U>::deserialise( const std::vector<double>& serialisedOptimisationProblem) { OptimisationProblem<T, U>::deserialise(serialisedOptimisationProblem); } #endif } } <|endoftext|>
<commit_before>/*************************************************************************** copyright : (C) 2002 - 2008 by Scott Wheeler email : wheeler@kde.org ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <tbytevector.h> #include <tdebug.h> #include <flacpicture.h> #include <xiphcomment.h> #include <tpropertymap.h> using namespace TagLib; typedef List<FLAC::Picture*> PictureList; class Ogg::XiphComment::XiphCommentPrivate { public: FieldListMap fieldListMap; String vendorID; String commentField; PictureList pictureList; }; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// Ogg::XiphComment::XiphComment() : TagLib::Tag() { d = new XiphCommentPrivate; } Ogg::XiphComment::XiphComment(const ByteVector &data) : TagLib::Tag() { d = new XiphCommentPrivate; parse(data); } Ogg::XiphComment::~XiphComment() { delete d; } String Ogg::XiphComment::title() const { if(d->fieldListMap["TITLE"].isEmpty()) return String::null; return d->fieldListMap["TITLE"].toString(); } String Ogg::XiphComment::artist() const { if(d->fieldListMap["ARTIST"].isEmpty()) return String::null; return d->fieldListMap["ARTIST"].toString(); } String Ogg::XiphComment::album() const { if(d->fieldListMap["ALBUM"].isEmpty()) return String::null; return d->fieldListMap["ALBUM"].toString(); } String Ogg::XiphComment::comment() const { if(!d->fieldListMap["DESCRIPTION"].isEmpty()) { d->commentField = "DESCRIPTION"; return d->fieldListMap["DESCRIPTION"].toString(); } if(!d->fieldListMap["COMMENT"].isEmpty()) { d->commentField = "COMMENT"; return d->fieldListMap["COMMENT"].toString(); } return String::null; } String Ogg::XiphComment::genre() const { if(d->fieldListMap["GENRE"].isEmpty()) return String::null; return d->fieldListMap["GENRE"].toString(); } TagLib::uint Ogg::XiphComment::year() const { if(!d->fieldListMap["DATE"].isEmpty()) return d->fieldListMap["DATE"].front().toInt(); if(!d->fieldListMap["YEAR"].isEmpty()) return d->fieldListMap["YEAR"].front().toInt(); return 0; } TagLib::uint Ogg::XiphComment::track() const { if(!d->fieldListMap["TRACKNUMBER"].isEmpty()) return d->fieldListMap["TRACKNUMBER"].front().toInt(); if(!d->fieldListMap["TRACKNUM"].isEmpty()) return d->fieldListMap["TRACKNUM"].front().toInt(); return 0; } void Ogg::XiphComment::setTitle(const String &s) { addField("TITLE", s); } void Ogg::XiphComment::setArtist(const String &s) { addField("ARTIST", s); } void Ogg::XiphComment::setAlbum(const String &s) { addField("ALBUM", s); } void Ogg::XiphComment::setComment(const String &s) { addField(d->commentField.isEmpty() ? "DESCRIPTION" : d->commentField, s); } void Ogg::XiphComment::setGenre(const String &s) { addField("GENRE", s); } void Ogg::XiphComment::setYear(uint i) { removeField("YEAR"); if(i == 0) removeField("DATE"); else addField("DATE", String::number(i)); } void Ogg::XiphComment::setTrack(uint i) { removeField("TRACKNUM"); if(i == 0) removeField("TRACKNUMBER"); else addField("TRACKNUMBER", String::number(i)); } bool Ogg::XiphComment::isEmpty() const { FieldListMap::ConstIterator it = d->fieldListMap.begin(); for(; it != d->fieldListMap.end(); ++it) if(!(*it).second.isEmpty()) return false; return true; } TagLib::uint Ogg::XiphComment::fieldCount() const { uint count = 0; FieldListMap::ConstIterator it = d->fieldListMap.begin(); for(; it != d->fieldListMap.end(); ++it) count += (*it).second.size(); count += d->pictureList.size(); return count; } const Ogg::FieldListMap &Ogg::XiphComment::fieldListMap() const { return d->fieldListMap; } PropertyMap Ogg::XiphComment::properties() const { return d->fieldListMap; } PropertyMap Ogg::XiphComment::setProperties(const PropertyMap &properties) { // check which keys are to be deleted StringList toRemove; for(FieldListMap::ConstIterator it = d->fieldListMap.begin(); it != d->fieldListMap.end(); ++it) if (!properties.contains(it->first)) toRemove.append(it->first); for(StringList::ConstIterator it = toRemove.begin(); it != toRemove.end(); ++it) removeField(*it); // now go through keys in \a properties and check that the values match those in the xiph comment PropertyMap invalid; PropertyMap::ConstIterator it = properties.begin(); for(; it != properties.end(); ++it) { if(!checkKey(it->first)) invalid.insert(it->first, it->second); else if(!d->fieldListMap.contains(it->first) || !(it->second == d->fieldListMap[it->first])) { const StringList &sl = it->second; if(sl.size() == 0) // zero size string list -> remove the tag with all values removeField(it->first); else { // replace all strings in the list for the tag StringList::ConstIterator valueIterator = sl.begin(); addField(it->first, *valueIterator, true); ++valueIterator; for(; valueIterator != sl.end(); ++valueIterator) addField(it->first, *valueIterator, false); } } } return invalid; } bool Ogg::XiphComment::checkKey(const String &key) { if(key.size() < 1) return false; for(String::ConstIterator it = key.begin(); it != key.end(); it++) // forbid non-printable, non-ascii, '=' (#61) and '~' (#126) if (*it < 32 || *it >= 128 || *it == 61 || *it == 126) return false; return true; } String Ogg::XiphComment::vendorID() const { return d->vendorID; } void Ogg::XiphComment::addField(const String &key, const String &value, bool replace) { if(replace) removeField(key.upper()); if(!key.isEmpty() && !value.isEmpty()) d->fieldListMap[key.upper()].append(value); } void Ogg::XiphComment::removeField(const String &key, const String &value) { if(!value.isNull()) { StringList::Iterator it = d->fieldListMap[key].begin(); while(it != d->fieldListMap[key].end()) { if(value == *it) it = d->fieldListMap[key].erase(it); else it++; } } else d->fieldListMap.erase(key); } bool Ogg::XiphComment::contains(const String &key) const { return d->fieldListMap.contains(key) && !d->fieldListMap[key].isEmpty(); } void Ogg::XiphComment::removePicture(FLAC::Picture *picture, bool del) { List<FLAC::Picture *>::Iterator it = d->pictureList.find(picture); if(it != d->pictureList.end()) d->pictureList.erase(it); if(del) delete picture; } void Ogg::XiphComment::removePictures() { PictureList newList; for(uint i = 0; i < d->pictureList.size(); i++) { delete d->pictureList[i]; } d->pictureList = newList; } void Ogg::XiphComment::addPicture(FLAC::Picture * picture) { d->pictureList.append(picture); } List<FLAC::Picture *> Ogg::XiphComment::pictureList() { return d->pictureList; } ByteVector Ogg::XiphComment::render() const { return render(true); } ByteVector Ogg::XiphComment::render(bool addFramingBit) const { ByteVector data; // Add the vendor ID length and the vendor ID. It's important to use the // length of the data(String::UTF8) rather than the length of the the string // since this is UTF8 text and there may be more characters in the data than // in the UTF16 string. ByteVector vendorData = d->vendorID.data(String::UTF8); data.append(ByteVector::fromUInt(vendorData.size(), false)); data.append(vendorData); // Add the number of fields. data.append(ByteVector::fromUInt(fieldCount(), false)); // Iterate over the the field lists. Our iterator returns a // std::pair<String, StringList> where the first String is the field name and // the StringList is the values associated with that field. FieldListMap::ConstIterator it = d->fieldListMap.begin(); for(; it != d->fieldListMap.end(); ++it) { // And now iterate over the values of the current list. String fieldName = (*it).first; StringList values = (*it).second; StringList::ConstIterator valuesIt = values.begin(); for(; valuesIt != values.end(); ++valuesIt) { ByteVector fieldData = fieldName.data(String::UTF8); fieldData.append('='); fieldData.append((*valuesIt).data(String::UTF8)); data.append(ByteVector::fromUInt(fieldData.size(), false)); data.append(fieldData); } } for(PictureList::ConstIterator it = d->pictureList.begin(); it != d->pictureList.end(); ++it) { ByteVector picture = (*it)->render().toBase64(); data.append(ByteVector::fromUInt(picture.size()+23,false)); data.append("METADATA_BLOCK_PICTURE="); data.append(picture); } // Append the "framing bit". if(addFramingBit) data.append(char(1)); return data; } //////////////////////////////////////////////////////////////////////////////// // protected members //////////////////////////////////////////////////////////////////////////////// void Ogg::XiphComment::parse(const ByteVector &data) { // The first thing in the comment data is the vendor ID length, followed by a // UTF8 string with the vendor ID. uint pos = 0; const uint vendorLength = data.toUInt(0, false); pos += 4; d->vendorID = String(data.mid(pos, vendorLength), String::UTF8); pos += vendorLength; // Next the number of fields in the comment vector. const uint commentFields = data.toUInt(pos, false); pos += 4; if(commentFields > (data.size() - 8) / 4) { return; } for(uint i = 0; i < commentFields; i++) { // Each comment field is in the format "KEY=value" in a UTF8 string and has // 4 bytes before the text starts that gives the length. const uint commentLength = data.toUInt(pos, false); pos += 4; ByteVector entry = data.mid(pos, commentLength); // Don't go past data end pos+=commentLength; if (pos>data.size()) break; // Handle Pictures separately if(entry.startsWith("METADATA_BLOCK_PICTURE=")) { // Decode base64 picture data ByteVector picturedata = entry.mid(23, entry.size()-23).fromBase64(); if(picturedata.size()==0) { debug("Empty picture data. Discarding content"); continue; } FLAC::Picture * picture = new FLAC::Picture(); if(picture->parse(picturedata)) d->pictureList.append(picture); else debug("Unable to parse METADATA_BLOCK_PICTURE. Discarding content."); } else { // Check for field separator int sep = entry.find('='); if (sep == -1) break; // Parse key and value String key = String(entry.mid(0,sep), String::UTF8); String value = String(entry.mid(sep+1, commentLength-sep), String::UTF8); addField(key, value, false); } } } <commit_msg>Delete pictures in XiphComment destructor<commit_after>/*************************************************************************** copyright : (C) 2002 - 2008 by Scott Wheeler email : wheeler@kde.org ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <tbytevector.h> #include <tdebug.h> #include <flacpicture.h> #include <xiphcomment.h> #include <tpropertymap.h> using namespace TagLib; typedef List<FLAC::Picture*> PictureList; class Ogg::XiphComment::XiphCommentPrivate { public: FieldListMap fieldListMap; String vendorID; String commentField; PictureList pictureList; }; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// Ogg::XiphComment::XiphComment() : TagLib::Tag() { d = new XiphCommentPrivate; } Ogg::XiphComment::XiphComment(const ByteVector &data) : TagLib::Tag() { d = new XiphCommentPrivate; parse(data); } Ogg::XiphComment::~XiphComment() { removePictures(); delete d; } String Ogg::XiphComment::title() const { if(d->fieldListMap["TITLE"].isEmpty()) return String::null; return d->fieldListMap["TITLE"].toString(); } String Ogg::XiphComment::artist() const { if(d->fieldListMap["ARTIST"].isEmpty()) return String::null; return d->fieldListMap["ARTIST"].toString(); } String Ogg::XiphComment::album() const { if(d->fieldListMap["ALBUM"].isEmpty()) return String::null; return d->fieldListMap["ALBUM"].toString(); } String Ogg::XiphComment::comment() const { if(!d->fieldListMap["DESCRIPTION"].isEmpty()) { d->commentField = "DESCRIPTION"; return d->fieldListMap["DESCRIPTION"].toString(); } if(!d->fieldListMap["COMMENT"].isEmpty()) { d->commentField = "COMMENT"; return d->fieldListMap["COMMENT"].toString(); } return String::null; } String Ogg::XiphComment::genre() const { if(d->fieldListMap["GENRE"].isEmpty()) return String::null; return d->fieldListMap["GENRE"].toString(); } TagLib::uint Ogg::XiphComment::year() const { if(!d->fieldListMap["DATE"].isEmpty()) return d->fieldListMap["DATE"].front().toInt(); if(!d->fieldListMap["YEAR"].isEmpty()) return d->fieldListMap["YEAR"].front().toInt(); return 0; } TagLib::uint Ogg::XiphComment::track() const { if(!d->fieldListMap["TRACKNUMBER"].isEmpty()) return d->fieldListMap["TRACKNUMBER"].front().toInt(); if(!d->fieldListMap["TRACKNUM"].isEmpty()) return d->fieldListMap["TRACKNUM"].front().toInt(); return 0; } void Ogg::XiphComment::setTitle(const String &s) { addField("TITLE", s); } void Ogg::XiphComment::setArtist(const String &s) { addField("ARTIST", s); } void Ogg::XiphComment::setAlbum(const String &s) { addField("ALBUM", s); } void Ogg::XiphComment::setComment(const String &s) { addField(d->commentField.isEmpty() ? "DESCRIPTION" : d->commentField, s); } void Ogg::XiphComment::setGenre(const String &s) { addField("GENRE", s); } void Ogg::XiphComment::setYear(uint i) { removeField("YEAR"); if(i == 0) removeField("DATE"); else addField("DATE", String::number(i)); } void Ogg::XiphComment::setTrack(uint i) { removeField("TRACKNUM"); if(i == 0) removeField("TRACKNUMBER"); else addField("TRACKNUMBER", String::number(i)); } bool Ogg::XiphComment::isEmpty() const { FieldListMap::ConstIterator it = d->fieldListMap.begin(); for(; it != d->fieldListMap.end(); ++it) if(!(*it).second.isEmpty()) return false; return true; } TagLib::uint Ogg::XiphComment::fieldCount() const { uint count = 0; FieldListMap::ConstIterator it = d->fieldListMap.begin(); for(; it != d->fieldListMap.end(); ++it) count += (*it).second.size(); count += d->pictureList.size(); return count; } const Ogg::FieldListMap &Ogg::XiphComment::fieldListMap() const { return d->fieldListMap; } PropertyMap Ogg::XiphComment::properties() const { return d->fieldListMap; } PropertyMap Ogg::XiphComment::setProperties(const PropertyMap &properties) { // check which keys are to be deleted StringList toRemove; for(FieldListMap::ConstIterator it = d->fieldListMap.begin(); it != d->fieldListMap.end(); ++it) if (!properties.contains(it->first)) toRemove.append(it->first); for(StringList::ConstIterator it = toRemove.begin(); it != toRemove.end(); ++it) removeField(*it); // now go through keys in \a properties and check that the values match those in the xiph comment PropertyMap invalid; PropertyMap::ConstIterator it = properties.begin(); for(; it != properties.end(); ++it) { if(!checkKey(it->first)) invalid.insert(it->first, it->second); else if(!d->fieldListMap.contains(it->first) || !(it->second == d->fieldListMap[it->first])) { const StringList &sl = it->second; if(sl.size() == 0) // zero size string list -> remove the tag with all values removeField(it->first); else { // replace all strings in the list for the tag StringList::ConstIterator valueIterator = sl.begin(); addField(it->first, *valueIterator, true); ++valueIterator; for(; valueIterator != sl.end(); ++valueIterator) addField(it->first, *valueIterator, false); } } } return invalid; } bool Ogg::XiphComment::checkKey(const String &key) { if(key.size() < 1) return false; for(String::ConstIterator it = key.begin(); it != key.end(); it++) // forbid non-printable, non-ascii, '=' (#61) and '~' (#126) if (*it < 32 || *it >= 128 || *it == 61 || *it == 126) return false; return true; } String Ogg::XiphComment::vendorID() const { return d->vendorID; } void Ogg::XiphComment::addField(const String &key, const String &value, bool replace) { if(replace) removeField(key.upper()); if(!key.isEmpty() && !value.isEmpty()) d->fieldListMap[key.upper()].append(value); } void Ogg::XiphComment::removeField(const String &key, const String &value) { if(!value.isNull()) { StringList::Iterator it = d->fieldListMap[key].begin(); while(it != d->fieldListMap[key].end()) { if(value == *it) it = d->fieldListMap[key].erase(it); else it++; } } else d->fieldListMap.erase(key); } bool Ogg::XiphComment::contains(const String &key) const { return d->fieldListMap.contains(key) && !d->fieldListMap[key].isEmpty(); } void Ogg::XiphComment::removePicture(FLAC::Picture *picture, bool del) { List<FLAC::Picture *>::Iterator it = d->pictureList.find(picture); if(it != d->pictureList.end()) d->pictureList.erase(it); if(del) delete picture; } void Ogg::XiphComment::removePictures() { PictureList newList; for(uint i = 0; i < d->pictureList.size(); i++) { delete d->pictureList[i]; } d->pictureList = newList; } void Ogg::XiphComment::addPicture(FLAC::Picture * picture) { d->pictureList.append(picture); } List<FLAC::Picture *> Ogg::XiphComment::pictureList() { return d->pictureList; } ByteVector Ogg::XiphComment::render() const { return render(true); } ByteVector Ogg::XiphComment::render(bool addFramingBit) const { ByteVector data; // Add the vendor ID length and the vendor ID. It's important to use the // length of the data(String::UTF8) rather than the length of the the string // since this is UTF8 text and there may be more characters in the data than // in the UTF16 string. ByteVector vendorData = d->vendorID.data(String::UTF8); data.append(ByteVector::fromUInt(vendorData.size(), false)); data.append(vendorData); // Add the number of fields. data.append(ByteVector::fromUInt(fieldCount(), false)); // Iterate over the the field lists. Our iterator returns a // std::pair<String, StringList> where the first String is the field name and // the StringList is the values associated with that field. FieldListMap::ConstIterator it = d->fieldListMap.begin(); for(; it != d->fieldListMap.end(); ++it) { // And now iterate over the values of the current list. String fieldName = (*it).first; StringList values = (*it).second; StringList::ConstIterator valuesIt = values.begin(); for(; valuesIt != values.end(); ++valuesIt) { ByteVector fieldData = fieldName.data(String::UTF8); fieldData.append('='); fieldData.append((*valuesIt).data(String::UTF8)); data.append(ByteVector::fromUInt(fieldData.size(), false)); data.append(fieldData); } } for(PictureList::ConstIterator it = d->pictureList.begin(); it != d->pictureList.end(); ++it) { ByteVector picture = (*it)->render().toBase64(); data.append(ByteVector::fromUInt(picture.size()+23,false)); data.append("METADATA_BLOCK_PICTURE="); data.append(picture); } // Append the "framing bit". if(addFramingBit) data.append(char(1)); return data; } //////////////////////////////////////////////////////////////////////////////// // protected members //////////////////////////////////////////////////////////////////////////////// void Ogg::XiphComment::parse(const ByteVector &data) { // The first thing in the comment data is the vendor ID length, followed by a // UTF8 string with the vendor ID. uint pos = 0; const uint vendorLength = data.toUInt(0, false); pos += 4; d->vendorID = String(data.mid(pos, vendorLength), String::UTF8); pos += vendorLength; // Next the number of fields in the comment vector. const uint commentFields = data.toUInt(pos, false); pos += 4; if(commentFields > (data.size() - 8) / 4) { return; } for(uint i = 0; i < commentFields; i++) { // Each comment field is in the format "KEY=value" in a UTF8 string and has // 4 bytes before the text starts that gives the length. const uint commentLength = data.toUInt(pos, false); pos += 4; ByteVector entry = data.mid(pos, commentLength); // Don't go past data end pos+=commentLength; if (pos>data.size()) break; // Handle Pictures separately if(entry.startsWith("METADATA_BLOCK_PICTURE=")) { // Decode base64 picture data ByteVector picturedata = entry.mid(23, entry.size()-23).fromBase64(); if(picturedata.size()==0) { debug("Empty picture data. Discarding content"); continue; } FLAC::Picture * picture = new FLAC::Picture(); if(picture->parse(picturedata)) d->pictureList.append(picture); else debug("Unable to parse METADATA_BLOCK_PICTURE. Discarding content."); } else { // Check for field separator int sep = entry.find('='); if (sep == -1) break; // Parse key and value String key = String(entry.mid(0,sep), String::UTF8); String value = String(entry.mid(sep+1, commentLength-sep), String::UTF8); addField(key, value, false); } } } <|endoftext|>
<commit_before>#include <iostream> #include <algorithm> #include <time.h> #include "../Eigen/Dense" using namespace Eigen; // Gaussian elimination // [ A | b ] = [ U | c ] bool GaussElimination(const MatrixXf &a, const VectorXf &b, MatrixXf &u, VectorXf &c) { // 'a' should be a square matrix assert(a.rows() == a.cols()); // right hand side vector c = b; // no pivoting upper triangular matrix 'nu' elimination begin with 'a' MatrixXf nu = a; // row_indexes has row order of 'nu' ArrayXi row_indexes(a.rows()); for (int r = 0; r < a.rows(); r++) { row_indexes(r) = r; } // 'i' is diagonal index of the matrix for (int i = 0; i < a.rows(); i++) { // find real pivot index int pivot_index = row_indexes[i]; float maximum = abs(nu(pivot_index, i)); for (int r = i + 1; r < a.rows(); r++) { float value = abs(nu(row_indexes[r], i)); if (value > maximum) { pivot_index = row_indexes[r]; maximum = value; } } // if row exchange is required if (pivot_index > i) { // swap pivot index with current row index std::swap(row_indexes[i], row_indexes[pivot_index]); std::swap(c[i], c[pivot_index]); } // get pivot value float pivot = nu(row_indexes[i], i); if (pivot == 0.0f) { // abandon decomposition if pivot does not exist return false; } for (int r = i + 1; r < a.rows(); r++) { // scaler for subtract a row float scaler = nu(row_indexes[r], i) / pivot; // subtract a row from scaled pivot row for (int c = i; c < a.cols(); c++) { nu(row_indexes[r], c) -= scaler * nu(row_indexes[i], c); } c[r] -= scaler * c[i]; } } // now row exchanges happen for (int r = 0; r < a.rows(); r++) { u.row(r) = nu.row(row_indexes[r]); } return true; } // Solve Ux = b, U is upper triangular matrix const VectorXf SolveUTriangular(const MatrixXf &u, const VectorXf &b) { VectorXf x(b.rows()); for (int r = u.rows() - 1; r >= 0; r--) { float k = 0; for (int c = r + 1; c < u.cols(); c++) { k += u(r, c) * x(c); } x(r) = (b(r) - k) / u(r, r); } return x; } // Solve Ax = b with gaussian elimination bool SolveGaussElimination(const MatrixXf &a, const VectorXf &b, VectorXf &x) { MatrixXf u(a.rows(), a.cols()); VectorXf c(b.rows()); if (!GaussElimination(a, b, u, c)) { return false; } //float determinant = u.diagonal().prod(); x = SolveUTriangular(u, c); return true; } void TestGaussElimination() { const int DIMENSION = 4; MatrixXf a(DIMENSION, DIMENSION); a << MatrixXf::Random(DIMENSION, DIMENSION); VectorXf b(DIMENSION); b << VectorXf::Random(DIMENSION); VectorXf x; bool invertible = ::SolveGaussElimination(a, b, x); if (!invertible) { std::cout << "ERROR: A is not invertible !!\n"; return; } std::cout << "A =\n"; std::cout << a << "\n\n"; std::cout << "b =\n"; std::cout << b << "\n\n"; std::cout << "Ax = b, x =\n"; std::cout << x << "\n\n"; PartialPivLU<MatrixXf> decomp(a); x = decomp.solve(b); std::cout << "Ax = b, x =\n"; std::cout << x << "\n\n"; } int main() { srand((unsigned int)time(0)); TestGaussElimination(); getchar(); return 0; } <commit_msg>Code adjustments<commit_after>#include <iostream> #include <algorithm> #include <time.h> #include "../Eigen/Dense" using namespace Eigen; // Gaussian elimination // [ A | b ] = [ U | c ] bool GaussElimination(const MatrixXf &a, const VectorXf &b, MatrixXf &u, VectorXf &c) { // 'a' should be a square matrix assert(a.rows() == a.cols()); // left hand side matrix A u = a; // right hand side vector b c = b; // 'i' is diagonal index of the matrix for (int i = 0; i < a.rows(); i++) { // find real pivot index int pivot_index = i; float maximum = abs(u(pivot_index, i)); for (int r = i + 1; r < a.rows(); r++) { float value = abs(u(r, i)); if (value > maximum) { pivot_index = r; maximum = value; } } // if row exchange is required if (pivot_index > i) { u.row(i).swap(u.row(pivot_index)); std::swap(c[i], c[pivot_index]); } // get pivot value float pivot = u(i, i); if (pivot == 0.0f) { // abandon decomposition if pivot does not exist return false; } for (int r = i + 1; r < a.rows(); r++) { // scaler for subtract a row float scaler = u(r, i) / pivot; // subtract a row from scaled pivot row for (int c = i; c < a.cols(); c++) { u(r, c) -= scaler * u(i, c); } c[r] -= scaler * c[i]; } } return true; } // Solve Ux = b, U is upper triangular matrix const VectorXf SolveUTriangular(const MatrixXf &u, const VectorXf &b) { VectorXf x(b.rows()); for (int r = u.rows() - 1; r >= 0; r--) { float k = 0; for (int c = r + 1; c < u.cols(); c++) { k += u(r, c) * x(c); } x(r) = (b(r) - k) / u(r, r); } return x; } // Solve Ax = b with gaussian elimination bool SolveGaussElimination(const MatrixXf &a, const VectorXf &b, VectorXf &x) { MatrixXf u(a.rows(), a.cols()); VectorXf c(b.rows()); if (!GaussElimination(a, b, u, c)) { return false; } std::cout << u << std::endl; //float determinant = u.diagonal().prod(); x = SolveUTriangular(u, c); return true; } void TestGaussElimination() { const int DIMENSION = 4; MatrixXf a(DIMENSION, DIMENSION); a << MatrixXf::Random(DIMENSION, DIMENSION); VectorXf b(DIMENSION); b << VectorXf::Random(DIMENSION); VectorXf x; bool invertible = ::SolveGaussElimination(a, b, x); if (!invertible) { std::cout << "ERROR: A is not invertible !!\n"; return; } std::cout << "A =\n"; std::cout << a << "\n\n"; std::cout << "b =\n"; std::cout << b << "\n\n"; std::cout << "Ax = b, x =\n"; std::cout << x << "\n\n"; PartialPivLU<MatrixXf> decomp(a); x = decomp.solve(b); std::cout << "Ax = b, x =\n"; std::cout << x << "\n\n"; } int main() { srand((unsigned int)time(0)); TestGaussElimination(); getchar(); return 0; } <|endoftext|>
<commit_before>#ifndef DUNE_STUFF_DEBUG_HH #define DUNE_STUFF_DEBUG_HH #include <cstring> #define SEGFAULT {int*J=0;*J=9;} //! from right/bottom limiter for file paths const char* rightPathLimiter( const char* path, int depth = 2 ) { char* c = new char[255]; strcpy(c,path); const char* p = strtok( c, "/" ); int i = 0; while ( p && i < depth ){ p = strtok( NULL, "/" ); } p = strtok( NULL, "\0" ); return p; } #ifndef NDEBUG #ifndef LOGIC_ERROR #include <stdexcept> #include <sstream> #define LOGIC_ERROR \ {\ std::stringstream ss; ss << __FILE__ << ":" << __LINE__ << " should never be called"; \ throw std::logic_error(ss.str());\ } #endif #else #define LOGIC_ERROR #endif char* copy(const char* s) { int l=strlen(s)+1; char* t = new char[l]; for(int i=0;i<l;i++) { t[i] = s[i]; } return t; } #define __CLASS__ strtok(copy(__PRETTY_FUNCTION__),"<(") #ifndef NDEBUG #define NEEDS_IMPLEMENTATION\ {\ std::stringstream ss; ss << " implementation missing: " << __CLASS__ << " -- "<< rightPathLimiter(__FILE__ )<< ":" << __LINE__ ; \ std::cerr << ss.str() << std::endl;\ } #else #define NEEDS_IMPLEMENTATION #endif //NDEBUG class assert_exception : public std::runtime_error { public: assert_exception(std::string msg) : std::runtime_error(msg) {} }; namespace Stuff { class singlerun_abort_exception : public std::runtime_error { public: singlerun_abort_exception(std::string msg) : std::runtime_error(msg) {} }; } #ifndef NDEBUG #define ASSERT_EXCEPTION(cond,msg) if(!(cond))\ { std::string rmsg ( std::string(__FILE__) + std::string(":") + Stuff::toString(__LINE__) + std::string("\n") + std::string(msg) ); \ throw assert_exception(rmsg); } #else #define ASSERT_EXCEPTION(cond,msg) #endif #if 1 /* there should be no more any compilers needing the "#else" version */ #define UNUSED(identifier) /* identifier */ #else /* stupid, broken compiler */ #define UNUSED(identifier) identifier #endif /* some arguments are only used in debug mode, but unused in release one */ #ifndef NDEBUG #define UNUSED_UNLESS_DEBUG(param) param #else #define UNUSED_UNLESS_DEBUG(param) UNUSED(param) #endif #endif // DUNE_STUFF_DEBUG_HH <commit_msg>new ASSERT_LT ASSERT_EQ macros, you want to use them<commit_after>#ifndef DUNE_STUFF_DEBUG_HH #define DUNE_STUFF_DEBUG_HH #include <cstring> #include <boost/assert.hpp> #include <boost/format.hpp> #define SEGFAULT {int*J=0;*J=9;} //! from right/bottom limiter for file paths const char* rightPathLimiter( const char* path, int depth = 2 ) { char* c = new char[255]; strcpy(c,path); const char* p = strtok( c, "/" ); int i = 0; while ( p && i < depth ){ p = strtok( NULL, "/" ); } p = strtok( NULL, "\0" ); return p; } #ifndef NDEBUG #ifndef LOGIC_ERROR #include <stdexcept> #include <sstream> #define LOGIC_ERROR \ {\ std::stringstream ss; ss << __FILE__ << ":" << __LINE__ << " should never be called"; \ throw std::logic_error(ss.str());\ } #endif #else #define LOGIC_ERROR #endif char* copy(const char* s) { int l=strlen(s)+1; char* t = new char[l]; for(int i=0;i<l;i++) { t[i] = s[i]; } return t; } #define __CLASS__ strtok(copy(__PRETTY_FUNCTION__),"<(") #ifndef NDEBUG #define NEEDS_IMPLEMENTATION\ {\ std::stringstream ss; ss << " implementation missing: " << __CLASS__ << " -- "<< rightPathLimiter(__FILE__ )<< ":" << __LINE__ ; \ std::cerr << ss.str() << std::endl;\ } #else #define NEEDS_IMPLEMENTATION #endif //NDEBUG class assert_exception : public std::runtime_error { public: assert_exception(std::string msg) : std::runtime_error(msg) {} }; namespace Stuff { class singlerun_abort_exception : public std::runtime_error { public: singlerun_abort_exception(std::string msg) : std::runtime_error(msg) {} }; } #ifndef NDEBUG #define ASSERT_EXCEPTION(cond,msg) if(!(cond))\ { std::string rmsg ( std::string(__FILE__) + std::string(":") + Stuff::toString(__LINE__) + std::string("\n") + std::string(msg) ); \ throw assert_exception(rmsg); } #else #define ASSERT_EXCEPTION(cond,msg) #endif #if 1 /* there should be no more any compilers needing the "#else" version */ #define UNUSED(identifier) /* identifier */ #else /* stupid, broken compiler */ #define UNUSED(identifier) identifier #endif /* some arguments are only used in debug mode, but unused in release one */ #ifndef NDEBUG #define UNUSED_UNLESS_DEBUG(param) param #else #define UNUSED_UNLESS_DEBUG(param) UNUSED(param) #endif #define ASSERT_LT( expt, actual ) \ BOOST_ASSERT_MSG( (expt<actual), (boost::format("assertion %1% < %2% failed: %3% >= %4%") % #expt % #actual % expt % actual).str().c_str() ) #define ASSERT_EQ( expt, actual ) \ BOOST_ASSERT_MSG( (expt==actual), (boost::format("assertion %1% == %2% failed: %3% != %4%") % #expt % #actual % expt % actual).str().c_str() ) #endif // DUNE_STUFF_DEBUG_HH <|endoftext|>
<commit_before>#ifndef DUNE_STUFF_DEBUG_HH #define DUNE_STUFF_DEBUG_HH #define SEGFAULT {int*J=0;*J=9;} //! from right/bottom limiter for file paths const char* rightPathLimiter( const char* path, int depth = 2 ) { char* c = new char[255]; strcpy(c,path); const char* p = strtok( c, "/" ); int i = 0; while ( p && i < depth ){ p = strtok( NULL, "/" ); } p = strtok( NULL, "\0" ); return p; } #ifndef NDEBUG #ifndef LOGIC_ERROR #include <stdexcept> #include <sstream> #define LOGIC_ERROR \ {\ std::stringstream ss; ss << __FILE__ << ":" << __LINE__ << " should never be called"; \ throw std::logic_error(ss.str());\ } #endif #else #define LOGIC_ERROR #endif char* copy(const char* s) { int l=strlen(s)+1; char* t = new char[l]; for(int i=0;i<l;i++) { t[i] = s[i]; } return t; } #define __CLASS__ strtok(copy(__PRETTY_FUNCTION__),"<(") #ifndef NDEBUG #define NEEDS_IMPLEMENTATION\ {\ std::stringstream ss; ss << " implementation missing: " << __CLASS__ << " -- "<< rightPathLimiter(__FILE__ )<< ":" << __LINE__ ; \ std::cerr << ss.str() << std::endl;\ } #else #define NEEDS_IMPLEMENTATION #endif //NDEBUG class assert_exception : public std::runtime_error { public: assert_exception(std::string msg) : std::runtime_error(msg) {}; }; #ifndef NDEBUG #define ASSERT_EXCEPTION(cond,msg) if(!(cond))\ { std::string rmsg ( std::string(__FILE__) + std::string(":") + Stuff::toString(__LINE__) + std::string("\n") + std::string(msg) ); \ throw assert_exception(rmsg); } #else #define ASSERT_EXCEPTION(cond,msg) #endif #endif // DUNE_STUFF_DEBUG_HH <commit_msg>new exception type<commit_after>#ifndef DUNE_STUFF_DEBUG_HH #define DUNE_STUFF_DEBUG_HH #define SEGFAULT {int*J=0;*J=9;} //! from right/bottom limiter for file paths const char* rightPathLimiter( const char* path, int depth = 2 ) { char* c = new char[255]; strcpy(c,path); const char* p = strtok( c, "/" ); int i = 0; while ( p && i < depth ){ p = strtok( NULL, "/" ); } p = strtok( NULL, "\0" ); return p; } #ifndef NDEBUG #ifndef LOGIC_ERROR #include <stdexcept> #include <sstream> #define LOGIC_ERROR \ {\ std::stringstream ss; ss << __FILE__ << ":" << __LINE__ << " should never be called"; \ throw std::logic_error(ss.str());\ } #endif #else #define LOGIC_ERROR #endif char* copy(const char* s) { int l=strlen(s)+1; char* t = new char[l]; for(int i=0;i<l;i++) { t[i] = s[i]; } return t; } #define __CLASS__ strtok(copy(__PRETTY_FUNCTION__),"<(") #ifndef NDEBUG #define NEEDS_IMPLEMENTATION\ {\ std::stringstream ss; ss << " implementation missing: " << __CLASS__ << " -- "<< rightPathLimiter(__FILE__ )<< ":" << __LINE__ ; \ std::cerr << ss.str() << std::endl;\ } #else #define NEEDS_IMPLEMENTATION #endif //NDEBUG class assert_exception : public std::runtime_error { public: assert_exception(std::string msg) : std::runtime_error(msg) {}; }; namespace Stuff { class singlerun_abort_exception : public std::runtime_error { public: singlerun_abort_exception(std::string msg) : std::runtime_error(msg) {}; }; } #ifndef NDEBUG #define ASSERT_EXCEPTION(cond,msg) if(!(cond))\ { std::string rmsg ( std::string(__FILE__) + std::string(":") + Stuff::toString(__LINE__) + std::string("\n") + std::string(msg) ); \ throw assert_exception(rmsg); } #else #define ASSERT_EXCEPTION(cond,msg) #endif #endif // DUNE_STUFF_DEBUG_HH <|endoftext|>
<commit_before>#include "yaml-cpp/yaml.h" #include "yaml-cpp/eventhandler.h" #include <fstream> #include <iostream> #include <vector> struct Params { bool hasFile; std::string fileName; }; Params ParseArgs(int argc, char **argv) { Params p; std::vector<std::string> args(argv + 1, argv + argc); return p; } class NullEventHandler: public YAML::EventHandler { public: virtual void OnDocumentStart(const YAML::Mark&) {} virtual void OnDocumentEnd() {} virtual void OnNull(const YAML::Mark&, YAML::anchor_t) {} virtual void OnAlias(const YAML::Mark&, YAML::anchor_t) {} virtual void OnScalar(const YAML::Mark&, const std::string&, YAML::anchor_t, const std::string&) {} virtual void OnSequenceStart(const YAML::Mark&, const std::string&, YAML::anchor_t) {} virtual void OnSequenceEnd() {} virtual void OnMapStart(const YAML::Mark&, const std::string&, YAML::anchor_t) {} virtual void OnMapEnd() {} }; void parse(std::istream& input) { try { #if YAML_CPP_OLD_API YAML::Parser parser(input); YAML::Node doc; while(parser.GetNextDocument(doc)) { YAML::Emitter emitter; emitter << doc; std::cout << emitter.c_str() << "\n"; } #else // TODO: Parse with new API #endif } catch(const YAML::Exception& e) { std::cerr << e.what() << "\n"; } } int main(int argc, char **argv) { Params p = ParseArgs(argc, argv); if(argc > 1) { std::ifstream fin; fin.open(argv[1]); parse(fin); } else { parse(std::cin); } return 0; } <commit_msg>Set up util/parse for the new API<commit_after>#include "yaml-cpp/yaml.h" #include "yaml-cpp/eventhandler.h" #include <fstream> #include <iostream> #include <vector> struct Params { bool hasFile; std::string fileName; }; Params ParseArgs(int argc, char **argv) { Params p; std::vector<std::string> args(argv + 1, argv + argc); return p; } class NullEventHandler: public YAML::EventHandler { public: virtual void OnDocumentStart(const YAML::Mark&) {} virtual void OnDocumentEnd() {} virtual void OnNull(const YAML::Mark&, YAML::anchor_t) {} virtual void OnAlias(const YAML::Mark&, YAML::anchor_t) {} virtual void OnScalar(const YAML::Mark&, const std::string&, YAML::anchor_t, const std::string&) {} virtual void OnSequenceStart(const YAML::Mark&, const std::string&, YAML::anchor_t) {} virtual void OnSequenceEnd() {} virtual void OnMapStart(const YAML::Mark&, const std::string&, YAML::anchor_t) {} virtual void OnMapEnd() {} }; void parse(std::istream& input) { try { #if YAML_CPP_OLD_API YAML::Parser parser(input); YAML::Node doc; while(parser.GetNextDocument(doc)) { YAML::Emitter emitter; emitter << doc; std::cout << emitter.c_str() << "\n"; } #else YAML::Node doc = YAML::Parse(input); std::cout << doc << "\n"; #endif } catch(const YAML::Exception& e) { std::cerr << e.what() << "\n"; } } int main(int argc, char **argv) { Params p = ParseArgs(argc, argv); if(argc > 1) { std::ifstream fin; fin.open(argv[1]); parse(fin); } else { parse(std::cin); } return 0; } <|endoftext|>
<commit_before>#define _USE_MATH_DEFINES #include <cmath> #include "Cylinder.h" #include <MathGeoLib/include/Math/MathFunc.h> ::Cylinder::Cylinder(GLfloat radius, GLfloat height) : Primitive(), Radius(radius), Height(height) {} ::Cylinder::Cylinder(const float3& position, const Quat& rotation, GLfloat radius, GLfloat height) : Primitive(position, rotation), Radius(radius), Height(height) {} ::Cylinder::Cylinder(const float3& position, const Quat& rotation, const float3& color, GLfloat radius, GLfloat height) : Primitive(position, rotation, color), Radius(radius), Height(height) {} ::Cylinder::~Cylinder() {} void ::Cylinder::Draw() { glPushMatrix(); glTranslatef(Position.x, Position.y, Position.z); float3 axis = Rotation.Axis(); glRotatef(RadToDeg(Rotation.Angle()), axis.x, axis.y, axis.z); glColor3f(Color.x, Color.y, Color.z); GLfloat x = 0.0; GLfloat y = 0.0; GLfloat angle = 0.0; GLfloat angle_stepsize = 0.1f; /** Draw the tube */ glBegin(GL_QUAD_STRIP); angle = 0.0; while (angle < 2 * M_PI) { x = Radius * cos(angle); y = Radius * sin(angle); glVertex3f(x, y, Height); glVertex3f(x, y, 0.0); angle = angle + angle_stepsize; } glVertex3f(Radius, 0.0, Height); glVertex3f(Radius, 0.0, 0.0); glEnd(); /** Draw the circle on top of cylinder */ glBegin(GL_POLYGON); angle = 0.0; while (angle < 2 * M_PI) { x = Radius * cos(angle); y = Radius * sin(angle); glVertex3f(x, y, Height); angle = angle + angle_stepsize; } glVertex3f(Radius, 0.0, Height); glEnd(); glPopMatrix(); }<commit_msg>Add bottom circle on cylinder<commit_after>#define _USE_MATH_DEFINES #include <cmath> #include "Cylinder.h" #include <MathGeoLib/include/Math/MathFunc.h> ::Cylinder::Cylinder(GLfloat radius, GLfloat height) : Primitive(), Radius(radius), Height(height) {} ::Cylinder::Cylinder(const float3& position, const Quat& rotation, GLfloat radius, GLfloat height) : Primitive(position, rotation), Radius(radius), Height(height) {} ::Cylinder::Cylinder(const float3& position, const Quat& rotation, const float3& color, GLfloat radius, GLfloat height) : Primitive(position, rotation, color), Radius(radius), Height(height) {} ::Cylinder::~Cylinder() {} void ::Cylinder::Draw() { glPushMatrix(); glTranslatef(Position.x, Position.y, Position.z); float3 axis = Rotation.Axis(); glRotatef(RadToDeg(Rotation.Angle()), axis.x, axis.y, axis.z); glColor3f(Color.x, Color.y, Color.z); GLfloat x = 0.0; GLfloat y = 0.0; GLfloat angle = 0.0; GLfloat angle_stepsize = 0.1f; /** Draw the tube */ glBegin(GL_QUAD_STRIP); angle = 0.0; while (angle < 2 * M_PI) { x = Radius * cos(angle); y = Radius * sin(angle); glVertex3f(x, y, Height); glVertex3f(x, y, 0.0); angle = angle + angle_stepsize; } glVertex3f(Radius, 0.0, Height); glVertex3f(Radius, 0.0, 0.0); glEnd(); /** Draw the circle on top of cylinder */ glBegin(GL_POLYGON); angle = 0.0; while (angle < 2 * M_PI) { x = Radius * cos(angle); y = Radius * sin(angle); glVertex3f(x, y, Height); angle = angle + angle_stepsize; } glVertex3f(Radius, 0.0, Height); glEnd(); /** Draw the circle on bottom of cylinder */ glBegin(GL_POLYGON); angle = 2 * M_PI; while (angle > 0.0) { x = Radius * cos(angle); y = Radius * sin(angle); glVertex3f(x, y, 0.0); angle = angle - angle_stepsize; } glVertex3f(Radius, 0.0, 0.0); glEnd(); glPopMatrix(); }<|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 2004, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /** @file AliFMDBaseDA.cxx @author Hans Hjersing Dalsgaard <canute@nbi.dk> @date Wed Mar 26 11:30:45 2008 @brief Base class for detector algorithms. */ // //This is the implementation of the (virtual) base class for the FMD detector //algorithms(DA). It implements the creation of the relevant containers and handles the //loop over the raw data. The derived classes can control the parameters and action //to be taken making this the base class for the Pedestal, Gain and Physics DA. // #include "AliFMDBaseDA.h" #include "iostream" #include "AliFMDRawReader.h" #include "AliLog.h" //_____________________________________________________________________ ClassImp(AliFMDBaseDA) //_____________________________________________________________________ AliFMDBaseDA::AliFMDBaseDA() : TNamed(), fDiagnosticsFilename("diagnosticsHistograms.root"), fOutputFile(), fConditionsFile(), fSaveHistograms(kFALSE), fDetectorArray(), fRequiredEvents(0), fCurrentEvent(0) { fDetectorArray.SetOwner(); fConditionsFile.open("conditions.csv"); } //_____________________________________________________________________ AliFMDBaseDA::AliFMDBaseDA(const AliFMDBaseDA & baseDA) : TNamed(baseDA), fDiagnosticsFilename(baseDA.fDiagnosticsFilename), fOutputFile(), fConditionsFile(), fSaveHistograms(baseDA.fSaveHistograms), fDetectorArray(baseDA.fDetectorArray), fRequiredEvents(baseDA.fRequiredEvents), fCurrentEvent(baseDA.fCurrentEvent) { fDetectorArray.SetOwner(); } //_____________________________________________________________________ AliFMDBaseDA::~AliFMDBaseDA() { //destructor } //_____________________________________________________________________ void AliFMDBaseDA::Run(AliRawReader* reader) { InitContainer(); Init(); TFile* diagFile = 0; if(fSaveHistograms) { diagFile = TFile::Open(fDiagnosticsFilename,"RECREATE"); for(UShort_t det=1;det<=3;det++) { UShort_t FirstRing = (det == 1 ? 1 : 0); for (UShort_t ir = FirstRing; ir < 2; ir++) { Char_t ring = (ir == 0 ? 'O' : 'I'); UShort_t nsec = (ir == 0 ? 40 : 20); UShort_t nstr = (ir == 0 ? 256 : 512); gDirectory->cd(Form("%s:/",fDiagnosticsFilename)); gDirectory->mkdir(Form("FMD%d%c",det,ring),Form("FMD%d%c",det,ring)); for(UShort_t sec =0; sec < nsec; sec++) { gDirectory->cd(Form("%s:/FMD%d%c",fDiagnosticsFilename,det,ring)); gDirectory->mkdir(Form("sector_%d",sec)); for(UShort_t strip = 0; strip < nstr; strip++) { gDirectory->cd(Form("%s:/FMD%d%c/sector_%d",fDiagnosticsFilename,det,ring,sec)); gDirectory->mkdir(Form("strip_%d",strip)); } } } } } reader->Reset(); AliFMDRawReader* fmdReader = new AliFMDRawReader(reader,0); TClonesArray* digitArray = new TClonesArray("AliFMDDigit",0); WriteConditionsData(); reader->NextEvent(); reader->NextEvent(); for(Int_t n =1;n <= GetRequiredEvents(); n++) { if(!reader->NextEvent()) continue; SetCurrentEvent(*(reader->GetEventId())); digitArray->Clear(); fmdReader->ReadAdcs(digitArray); //std::cout<<"In event # "<< *(reader->GetEventId()) << " with " <<digitArray->GetEntries()<<" digits \r"<<std::flush; for(Int_t i = 0; i<digitArray->GetEntries();i++) { AliFMDDigit* digit = static_cast<AliFMDDigit*>(digitArray->At(i)); FillChannels(digit); } FinishEvent(); } AliInfo(Form("Looped over %d events",GetCurrentEvent())); WriteHeaderToFile(); for(UShort_t det=1;det<=3;det++) { UShort_t FirstRing = (det == 1 ? 1 : 0); for (UShort_t ir = FirstRing; ir < 2; ir++) { Char_t ring = (ir == 0 ? 'O' : 'I'); UShort_t nsec = (ir == 0 ? 40 : 20); UShort_t nstr = (ir == 0 ? 256 : 512); for(UShort_t sec =0; sec < nsec; sec++) { for(UShort_t strip = 0; strip < nstr; strip++) { Analyse(det,ring,sec,strip); } } } } if(fOutputFile.is_open()) { fOutputFile.write("# EOF\n",6); fOutputFile.close(); } if(fSaveHistograms ) { AliInfo("Closing diagnostics file...please wait"); diagFile->Close(); } } //_____________________________________________________________________ void AliFMDBaseDA::InitContainer(){ TObjArray* detArray; TObjArray* ringArray; TObjArray* sectorArray; for(UShort_t det=1;det<=3;det++) { detArray = new TObjArray(); detArray->SetOwner(); fDetectorArray.AddAtAndExpand(detArray,det); UShort_t FirstRing = (det == 1 ? 1 : 0); for (UShort_t ir = FirstRing; ir < 2; ir++) { Char_t ring = (ir == 0 ? 'O' : 'I'); UShort_t nsec = (ir == 0 ? 40 : 20); UShort_t nstr = (ir == 0 ? 256 : 512); ringArray = new TObjArray(); ringArray->SetOwner(); detArray->AddAtAndExpand(ringArray,ir); for(UShort_t sec =0; sec < nsec; sec++) { sectorArray = new TObjArray(); sectorArray->SetOwner(); ringArray->AddAtAndExpand(sectorArray,sec); for(UShort_t strip = 0; strip < nstr; strip++) { AddChannelContainer(sectorArray, det, ring, sec, strip); } } } } } //_____________________________________________________________________ void AliFMDBaseDA::WriteConditionsData() { AliFMDParameters* pars = AliFMDParameters::Instance(); fConditionsFile.write(Form("# %s \n",pars->GetConditionsShuttleID()),14); fConditionsFile.write("# Sample Rate, timebins \n",25); UInt_t sampleRate = 4; UInt_t timebins = 544; fConditionsFile << sampleRate << ',' << timebins <<"\n"; //if(fConditionsFile.is_open()) { // // fConditionsFile.write("# EOF\n",6); // fConditionsFile.close(); //} } //_____________________________________________________________________ // // EOF // <commit_msg>New version with sample rate map and progress meter<commit_after>/************************************************************************** * Copyright(c) 2004, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /** @file AliFMDBaseDA.cxx @author Hans Hjersing Dalsgaard <canute@nbi.dk> @date Wed Mar 26 11:30:45 2008 @brief Base class for detector algorithms. */ // //This is the implementation of the (virtual) base class for the FMD detector //algorithms(DA). It implements the creation of the relevant containers and handles the //loop over the raw data. The derived classes can control the parameters and action //to be taken making this the base class for the Pedestal, Gain and Physics DA. // #include "AliFMDBaseDA.h" #include "iostream" #include "AliFMDRawReader.h" #include "AliFMDCalibSampleRate.h" #include "AliLog.h" //_____________________________________________________________________ ClassImp(AliFMDBaseDA) //_____________________________________________________________________ AliFMDBaseDA::AliFMDBaseDA() : TNamed(), fDiagnosticsFilename("diagnosticsHistograms.root"), fOutputFile(), fConditionsFile(), fSaveHistograms(kFALSE), fDetectorArray(), fRequiredEvents(0), fCurrentEvent(0) { fDetectorArray.SetOwner(); fConditionsFile.open("conditions.csv"); } //_____________________________________________________________________ AliFMDBaseDA::AliFMDBaseDA(const AliFMDBaseDA & baseDA) : TNamed(baseDA), fDiagnosticsFilename(baseDA.fDiagnosticsFilename), fOutputFile(), fConditionsFile(), fSaveHistograms(baseDA.fSaveHistograms), fDetectorArray(baseDA.fDetectorArray), fRequiredEvents(baseDA.fRequiredEvents), fCurrentEvent(baseDA.fCurrentEvent) { fDetectorArray.SetOwner(); } //_____________________________________________________________________ AliFMDBaseDA::~AliFMDBaseDA() { //destructor } //_____________________________________________________________________ void AliFMDBaseDA::Run(AliRawReader* reader) { InitContainer(); Init(); TFile* diagFile = 0; if(fSaveHistograms) { diagFile = TFile::Open(fDiagnosticsFilename,"RECREATE"); for(UShort_t det=1;det<=3;det++) { UShort_t FirstRing = (det == 1 ? 1 : 0); for (UShort_t ir = FirstRing; ir < 2; ir++) { Char_t ring = (ir == 0 ? 'O' : 'I'); UShort_t nsec = (ir == 0 ? 40 : 20); UShort_t nstr = (ir == 0 ? 256 : 512); gDirectory->cd(Form("%s:/",fDiagnosticsFilename)); gDirectory->mkdir(Form("FMD%d%c",det,ring),Form("FMD%d%c",det,ring)); for(UShort_t sec =0; sec < nsec; sec++) { gDirectory->cd(Form("%s:/FMD%d%c",fDiagnosticsFilename,det,ring)); gDirectory->mkdir(Form("sector_%d",sec)); for(UShort_t strip = 0; strip < nstr; strip++) { gDirectory->cd(Form("%s:/FMD%d%c/sector_%d",fDiagnosticsFilename,det,ring,sec)); gDirectory->mkdir(Form("strip_%d",strip)); } } } } } reader->Reset(); AliFMDRawReader* fmdReader = new AliFMDRawReader(reader,0); TClonesArray* digitArray = new TClonesArray("AliFMDDigit",0); WriteConditionsData(); reader->NextEvent(); reader->NextEvent(); int lastProgress = 0; for(Int_t n =1;n <= GetRequiredEvents(); n++) { if(!reader->NextEvent()) continue; SetCurrentEvent(*(reader->GetEventId())); digitArray->Clear(); fmdReader->ReadAdcs(digitArray); //std::cout<<"In event # "<< *(reader->GetEventId()) << " with " <<digitArray->GetEntries()<<" digits \r"<<std::flush; for(Int_t i = 0; i<digitArray->GetEntries();i++) { AliFMDDigit* digit = static_cast<AliFMDDigit*>(digitArray->At(i)); FillChannels(digit); } FinishEvent(); int progress = int((n *100)/ GetRequiredEvents()) ; if (progress <= lastProgress) continue; lastProgress = progress; std::cout << "Progress: " << lastProgress << " / 100 " << std::endl; } AliInfo(Form("Looped over %d events",GetCurrentEvent())); WriteHeaderToFile(); for(UShort_t det=1;det<=3;det++) { UShort_t FirstRing = (det == 1 ? 1 : 0); for (UShort_t ir = FirstRing; ir < 2; ir++) { Char_t ring = (ir == 0 ? 'O' : 'I'); UShort_t nsec = (ir == 0 ? 40 : 20); UShort_t nstr = (ir == 0 ? 256 : 512); for(UShort_t sec =0; sec < nsec; sec++) { for(UShort_t strip = 0; strip < nstr; strip++) { Analyse(det,ring,sec,strip); } } } } if(fOutputFile.is_open()) { fOutputFile.write("# EOF\n",6); fOutputFile.close(); } if(fSaveHistograms ) { AliInfo("Closing diagnostics file...please wait"); diagFile->Close(); } } //_____________________________________________________________________ void AliFMDBaseDA::InitContainer(){ TObjArray* detArray; TObjArray* ringArray; TObjArray* sectorArray; for(UShort_t det=1;det<=3;det++) { detArray = new TObjArray(); detArray->SetOwner(); fDetectorArray.AddAtAndExpand(detArray,det); UShort_t FirstRing = (det == 1 ? 1 : 0); for (UShort_t ir = FirstRing; ir < 2; ir++) { Char_t ring = (ir == 0 ? 'O' : 'I'); UShort_t nsec = (ir == 0 ? 40 : 20); UShort_t nstr = (ir == 0 ? 256 : 512); ringArray = new TObjArray(); ringArray->SetOwner(); detArray->AddAtAndExpand(ringArray,ir); for(UShort_t sec =0; sec < nsec; sec++) { sectorArray = new TObjArray(); sectorArray->SetOwner(); ringArray->AddAtAndExpand(sectorArray,sec); for(UShort_t strip = 0; strip < nstr; strip++) { AddChannelContainer(sectorArray, det, ring, sec, strip); } } } } } //_____________________________________________________________________ void AliFMDBaseDA::WriteConditionsData() { AliFMDParameters* pars = AliFMDParameters::Instance(); fConditionsFile.write(Form("# %s \n",pars->GetConditionsShuttleID()),14); fConditionsFile.write("# Sample Rate, timebins \n",25); UInt_t defSampleRate = 4; UInt_t timebins = 544; AliFMDCalibSampleRate* sampleRate = new AliFMDCalibSampleRate(); for(UShort_t det=1;det<=3;det++) { UShort_t FirstRing = (det == 1 ? 1 : 0); for (UShort_t ir = FirstRing; ir < 2; ir++) { Char_t ring = (ir == 0 ? 'O' : 'I'); UShort_t nsec = (ir == 0 ? 40 : 20); UShort_t nstr = (ir == 0 ? 256 : 512); for(UShort_t sec =0; sec < nsec; sec++) { for(UShort_t strip = 0; strip < nstr; strip++) { sampleRate->Set(det,ring,sec,strip,defSampleRate); } } } } pars->SetSampleRate(sampleRate); fConditionsFile << defSampleRate << ',' << timebins <<"\n"; if(fConditionsFile.is_open()) { // fConditionsFile.write("# EOF\n",6); fConditionsFile.close(); } } //_____________________________________________________________________ // // EOF // <|endoftext|>
<commit_before>#include "tst_qlistobject.h" void TST_QListObject::test() { CWF::QListObject listObj; listObj.add(new QObject); listObj.add(new QObject); QVERIFY2(listObj.size() == 2, "Should be equal 2"); QObject *obj = listObj[0]; QVERIFY2(obj != nullptr, "Should be different nullptr"); listObj.remove(obj); QVERIFY2(listObj.size() == 1, "Should be equal 1"); listObj.setAutoDelete(true); QVERIFY2(listObj.getAutoDelete() == true, "Should be equal true"); } <commit_msg>tst_qlistobject adjusts<commit_after>#include "tst_qlistobject.h" void TST_QListObject::test() { CWF::QListObject listObj; listObj.add(new QObject); listObj.add(new QObject); QVERIFY2(listObj.size() == 2, "Should be equal 2"); QObject *obj = listObj[0]; QVERIFY2(obj != nullptr, "Should be different nullptr"); listObj.remove(obj); QVERIFY2(listObj.size() == 1, "Should be equal 1"); listObj.setAutoDelete(false); QVERIFY2(listObj.getAutoDelete() == false, "Should be equal false"); } <|endoftext|>
<commit_before>#include <iostream> #include <stdint.h> #include <map> #include <vector> #include <string> #include <sys/stat.h> #include "boost/program_options.hpp" #include "api/BamReader.h" #include "utils/bamtools_pileup_engine.h" #include "utils/bamtools_fasta.h" #include "model.h" #include "parsers.h" using namespace std; using namespace BamTools; class VariantVisitor : public PileupVisitor{ public: VariantVisitor(const RefVector& bam_references, const SamHeader& header, const Fasta& idx_ref, const SampleMap& samples, BamAlignment& ali, int qual_cut, int mapping_cut, vector<uint64_t> &denoms) : PileupVisitor(), m_idx_ref(idx_ref), m_bam_ref(bam_references), m_header(header), m_samples(samples), m_qual_cut(qual_cut), m_ali(ali), m_denoms(denoms), m_mapping_cut(mapping_cut) { } ~VariantVisitor(void) { } public: void Visit(const PileupPosition& pileupData) { uint64_t pos = pileupData.Position; m_idx_ref.GetBase(pileupData.RefId, pos, current_base); ReadDataVector fwd_calls (m_samples.size(), ReadData{{ 0,0,0,0 }}); ReadDataVector rev_calls (m_samples.size(), ReadData{{ 0,0,0,0 }}); for(auto it = begin(pileupData.PileupAlignments); it != end(pileupData.PileupAlignments); ++it){ if( include_site(*it, m_mapping_cut, m_qual_cut) ){ it->Alignment.GetTag("RG", tag_id); uint32_t sindex = m_samples[tag_id]; //TODO check samples existed! uint16_t bindex = base_index(it->Alignment.QueryBases[it->PositionInAlignment]); if (bindex < 4 ){ if(it->Alignment.IsReverseStrand() ){ fwd_calls[sindex].reads[bindex] += 1; } else{ rev_calls[sindex].reads[bindex]+= 1; } } } } uint16_t ref_base_idx = base_index(current_base); if (ref_base_idx < 4 ){ //TODO Model for bases at which reference is 'N' ReadDataVector all_calls (m_samples.size(), ReadData{{ 0,0,0,0 }}); uint64_t total_depth = 0; for(size_t i = 1; i < m_samples.size(); i ++){ for(size_t j =0; j < 4; j++){ uint16_t sum_calls = fwd_calls[i].reads[j] + rev_calls[i].reads[j]; all_calls[i].reads[j] = sum_calls; total_depth += total_depth; } } uint32_t major_alleles = 0; for(auto it = begin(all_calls); it != end(all_calls); ++it){ major_alleles += *max_element(it->reads, it->reads + 4); } double major_freq = major_alleles / (double)total_depth; if(major_freq < 0.95){ return; } for(size_t i = 1; i < m_samples.size(); i++){ auto Fm = max_element(fwd_calls[i].reads, fwd_calls[i].reads+4); if (*Fm < 3){ continue; } auto Rm = max_element(rev_calls[i].reads, rev_calls[i].reads+4); if (*Rm < 3){ continue; } if(distance(rev_calls[i].reads, Rm) == distance(fwd_calls[i].reads, Fm)){ m_denoms[i] += 1; } } } } // ModelInput d = {ref_base_idx, bcalls}; // double prob_one = TetMAProbOneMutation(m_params,d); // double prob = TetMAProbability(m_params, d); // if(prob >= m_prob_cut){ // *m_ostream << m_bam_ref[pileupData.RefId].RefName << '\t' // << pos << '\t' // << current_base << '\t' // << prob << '\t' // << prob_one << '\t' // << endl; // } // } private: RefVector m_bam_ref; SamHeader m_header; Fasta m_idx_ref; SampleMap m_samples; BamAlignment& m_ali; int m_qual_cut; int m_mapping_cut; char current_base; string tag_id; uint64_t chr_index; vector<uint64_t>& m_denoms; }; int main(int argc, char** argv){ namespace po = boost::program_options; string ref_file; string config_path; po::options_description cmd("Command line options"); cmd.add_options() ("help,h", "Print a help message") ("bam,b", po::value<string>()->required(), "Path to BAM file") ("bam-index,x", po::value<string>()->default_value(""), "Path to BAM index, (defalult is <bam_path>.bai") ("reference,r", po::value<string>(&ref_file)->required(), "Path to reference genome") // ("ancestor,a", po::value<string>(&anc_tag), "Ancestor RG sample ID") // ("sample-name,s", po::value<vector <string> >()->required(), "Sample tags") ("qual,q", po::value<int>()->default_value(13), "Base quality cuttoff") ("mapping-qual,m", po::value<int>()->default_value(13), "Mapping quality cuttoff") ("intervals,i", po::value<string>(), "Path to bed file"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, cmd), vm); if (vm.count("help")){ cout << cmd << endl; return 0; } vm.notify(); string bam_path = vm["bam"].as<string>(); string index_path = vm["bam-index"].as<string>(); if(index_path == ""){ index_path = bam_path + ".bai"; } BamReader experiment; experiment.Open(bam_path); experiment.OpenIndex(index_path); RefVector references = experiment.GetReferenceData(); SamHeader header = experiment.GetHeader(); //Fasta reference Fasta reference_genome; // BamTools::Fasta struct stat file_info; string faidx_path = ref_file + ".fai"; if (stat(faidx_path.c_str(), &file_info) != 0){ reference_genome.CreateIndex(faidx_path); } reference_genome.Open(ref_file, faidx_path); // Map readgroups to samples // TODO: this presumes first sample is ancestor. True for our data, not for // others. // First map all sample names to an index for ReadDataVectors SampleMap name_map; uint16_t sindex = 0; for(auto it = header.ReadGroups.Begin(); it!= header.ReadGroups.End(); it++){ if(it->HasSample()){ auto s = name_map.find(it->Sample); if( s == name_map.end()){ // not in there yet name_map[it->Sample] = sindex; sindex += 1; } } } // And now, go back over the read groups to map RG:sample index SampleMap samples; for(auto it = header.ReadGroups.Begin(); it!= header.ReadGroups.End(); it++){ if(it->HasSample()){ samples[it->ID] = name_map[it->Sample]; } } PileupEngine pileup; BamAlignment ali; vector<uint64_t> denoms (sindex, 0); VariantVisitor *v = new VariantVisitor( references, header, reference_genome, // vm["sample-name"].as<vector< string> >(), samples, ali, vm["qual"].as<int>(), vm["mapping-qual"].as<int>(), denoms ); pileup.AddVisitor(v); if (vm.count("intervals")){ BedFile bed (vm["intervals"].as<string>()); BedInterval region; while(bed.get_interval(region) == 0){ int ref_id = experiment.GetReferenceID(region.chr); experiment.SetRegion(ref_id, region.start, ref_id, region.end); while( experiment.GetNextAlignment(ali) ){ pileup.AddAlignment(ali); } } } else{ while( experiment.GetNextAlignment(ali)){ pileup.AddAlignment(ali); } } pileup.Flush(); for(size_t i = 0; i < sindex; i++){ cerr << denoms[i] << '\t'; } cerr << endl; return 0; } <commit_msg>Calculate denom for a/c/t/g<commit_after>#include <iostream> #include <stdint.h> #include <map> #include <vector> #include <string> #include <sys/stat.h> #include "boost/program_options.hpp" #include "api/BamReader.h" #include "utils/bamtools_pileup_engine.h" #include "utils/bamtools_fasta.h" #include "model.h" #include "parsers.h" using namespace std; using namespace BamTools; ModelParams params = { 0.0001, {0.388, 0.112, 0.112, 0.338}, 1e-8, 0.01, 0.01, 0.005 }; void call_ancestor(const ModelParams &params, int ref_allele, const ReadData &d){ DiploidProbs genotypes = DiploidSequencing(params, ref_allele, d); Eigen::Array33d::Index idx; //std::cerr << genotypes.maxCoeff() << std::endl; genotypes.maxCoeff(&idx); uint16_t result[2]; result[1] = idx / 4; result[2] = idx % 4; std::cerr << result[1] << '\t' << result[2] << '\t'; } class VariantVisitor : public PileupVisitor{ public: VariantVisitor(const RefVector& bam_references, const SamHeader& header, const Fasta& idx_ref, const SampleMap& samples, BamAlignment& ali, int qual_cut, int mapping_cut, vector<uint64_t> &denoms) : PileupVisitor(), m_idx_ref(idx_ref), m_bam_ref(bam_references), m_header(header), m_samples(samples), m_qual_cut(qual_cut), m_ali(ali), m_denoms(denoms), m_mapping_cut(mapping_cut) { } ~VariantVisitor(void) { } public: void Visit(const PileupPosition& pileupData) { uint64_t pos = pileupData.Position; m_idx_ref.GetBase(pileupData.RefId, pos, current_base); ReadDataVector fwd_calls (m_samples.size(), ReadData{{ 0,0,0,0 }}); ReadDataVector rev_calls (m_samples.size(), ReadData{{ 0,0,0,0 }}); vector<int> keepers (m_samples.size(), 0); for(auto it = begin(pileupData.PileupAlignments); it != end(pileupData.PileupAlignments); ++it){ if( include_site(*it, m_mapping_cut, m_qual_cut) ){ it->Alignment.GetTag("RG", tag_id); uint32_t sindex = m_samples[tag_id]; //TODO check samples existed! uint16_t bindex = base_index(it->Alignment.QueryBases[it->PositionInAlignment]); if (bindex < 4 ){ if(it->Alignment.IsReverseStrand() ){ fwd_calls[sindex].reads[bindex] += 1; } else{ rev_calls[sindex].reads[bindex]+= 1; } } } } uint16_t ref_base_idx = base_index(current_base); if (ref_base_idx < 4 ){ //TODO Model for bases at which reference is 'N' ReadDataVector all_calls (m_samples.size(), ReadData{{ 0,0,0,0 }}); uint64_t total_depth = 0; for(size_t i = 0; i < m_samples.size(); i ++){ for(size_t j =0; j < 4; j++){ uint16_t sum_calls = fwd_calls[i].reads[j] + rev_calls[i].reads[j]; all_calls[i].reads[j] = sum_calls; total_depth += total_depth; } } call_ancestor(params, ref_base_idx, all_calls[0]); uint32_t major_alleles = 0; for(auto it = begin(all_calls); it != end(all_calls); ++it){ major_alleles += *max_element(it->reads, it->reads + 4); } double major_freq = major_alleles / (double)total_depth; if(major_freq < 0.95){ return; } for(size_t i = 1; i < m_samples.size(); i++){ auto Fm = max_element(fwd_calls[i].reads, fwd_calls[i].reads+4); if (*Fm < 3){ continue; } auto Rm = max_element(rev_calls[i].reads, rev_calls[i].reads+4); if (*Rm < 3){ continue; } if(distance(rev_calls[i].reads, Rm) == distance(fwd_calls[i].reads, Fm)){ m_denoms[i] += 1; keepers[i] = 1; } } } for(size_t i = 0; i < m_samples.size(); i++){ cerr << keepers[i] << '\t'; } cerr << endl; } // ModelInput d = {ref_base_idx, bcalls}; // double prob_one = TetMAProbOneMutation(m_params,d); // double prob = TetMAProbability(m_params, d); // if(prob >= m_prob_cut){ // *m_ostream << m_bam_ref[pileupData.RefId].RefName << '\t' // << pos << '\t' // << current_base << '\t' // << prob << '\t' // << prob_one << '\t' // << endl; // } // } private: RefVector m_bam_ref; SamHeader m_header; Fasta m_idx_ref; SampleMap m_samples; BamAlignment& m_ali; int m_qual_cut; int m_mapping_cut; char current_base; string tag_id; uint64_t chr_index; vector<uint64_t>& m_denoms; }; int main(int argc, char** argv){ namespace po = boost::program_options; string ref_file; string config_path; po::options_description cmd("Command line options"); cmd.add_options() ("help,h", "Print a help message") ("bam,b", po::value<string>()->required(), "Path to BAM file") ("bam-index,x", po::value<string>()->default_value(""), "Path to BAM index, (defalult is <bam_path>.bai") ("reference,r", po::value<string>(&ref_file)->required(), "Path to reference genome") // ("ancestor,a", po::value<string>(&anc_tag), "Ancestor RG sample ID") // ("sample-name,s", po::value<vector <string> >()->required(), "Sample tags") ("qual,q", po::value<int>()->default_value(13), "Base quality cuttoff") ("mapping-qual,m", po::value<int>()->default_value(13), "Mapping quality cuttoff") ("intervals,i", po::value<string>(), "Path to bed file"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, cmd), vm); if (vm.count("help")){ cout << cmd << endl; return 0; } vm.notify(); string bam_path = vm["bam"].as<string>(); string index_path = vm["bam-index"].as<string>(); if(index_path == ""){ index_path = bam_path + ".bai"; } BamReader experiment; experiment.Open(bam_path); experiment.OpenIndex(index_path); RefVector references = experiment.GetReferenceData(); SamHeader header = experiment.GetHeader(); //Fasta reference Fasta reference_genome; // BamTools::Fasta struct stat file_info; string faidx_path = ref_file + ".fai"; if (stat(faidx_path.c_str(), &file_info) != 0){ reference_genome.CreateIndex(faidx_path); } reference_genome.Open(ref_file, faidx_path); // Map readgroups to samples // TODO: this presumes first sample is ancestor. True for our data, not for // others. // First map all sample names to an index for ReadDataVectors SampleMap name_map; uint16_t sindex = 0; for(auto it = header.ReadGroups.Begin(); it!= header.ReadGroups.End(); it++){ if(it->HasSample()){ auto s = name_map.find(it->Sample); if( s == name_map.end()){ // not in there yet name_map[it->Sample] = sindex; sindex += 1; } } } // And now, go back over the read groups to map RG:sample index SampleMap samples; for(auto it = header.ReadGroups.Begin(); it!= header.ReadGroups.End(); it++){ if(it->HasSample()){ cout << it->Sample<< endl; samples[it->ID] = name_map[it->Sample]; } } PileupEngine pileup; BamAlignment ali; vector<uint64_t> denoms (sindex, 0); VariantVisitor *v = new VariantVisitor( references, header, reference_genome, // vm["sample-name"].as<vector< string> >(), samples, ali, vm["qual"].as<int>(), vm["mapping-qual"].as<int>(), denoms ); pileup.AddVisitor(v); if (vm.count("intervals")){ BedFile bed (vm["intervals"].as<string>()); BedInterval region; while(bed.get_interval(region) == 0){ int ref_id = experiment.GetReferenceID(region.chr); experiment.SetRegion(ref_id, region.start, ref_id, region.end); while( experiment.GetNextAlignment(ali) ){ pileup.AddAlignment(ali); } } } else{ while( experiment.GetNextAlignment(ali)){ pileup.AddAlignment(ali); } } pileup.Flush(); // for(size_t i = 0; i < sindex; i++){ // cerr << denoms[i] << '\t'; // } // cerr << endl; return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2007, 2008, 2009, 2010, 2011, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /// \file urbi/uvar.hh #ifndef URBI_UVAR_HH # define URBI_UVAR_HH # include <iosfwd> # include <string> # include <libport/fwd.hh> # include <libport/ufloat.hh> # include <urbi/ucontext.hh> # include <urbi/uvalue.hh> # include <urbi/uprop.hh> # include <urbi/uproperty.hh> namespace urbi { /** UVar class definition Each UVar instance corresponds to one URBI variable. The class provides access to the variable properties, and reading/writing the value to/from all known types. */ class URBI_SDK_API UVar: public UContext { public: /// Creates an unbound UVar. Call init() to bind it. UVar(); UVar(const std::string&, impl::UContextImpl* = 0); UVar(const std::string&, const std::string&, impl::UContextImpl* = 0); UVar(UObject&, const std::string&, impl::UContextImpl* = 0); UVar(const UVar&); private: UVar& operator=(const UVar&); public: ~UVar(); // Bind to \a object.slot. void init(const std::string& varname, impl::UContextImpl* = 0); void init(const std::string& object, const std::string& slot, impl::UContextImpl* = 0); void setOwned(); /// The type of the current content. UDataType type() const; /// Request the current value, wait until it is available. void syncValue(); /// Keep this UVar synchronized with kernel value. void keepSynchronized(); void reset (ufloat); UVar& operator=(ufloat); UVar& operator=(const std::string&); /// Deep copy. UVar& operator=(const UBinary&); /// Deep copy. UVar& operator=(const UImage& i); /// Deep copy. UVar& operator=(const USound& s); UVar& operator=(const UList& l); UVar& operator=(const UDictionary& d); UVar& operator=(const UValue& v); template<typename T> UVar& operator=(const T&); template<typename T> bool operator ==(const T&) const; /// Cast operator taking a dummy value of the target type. template<typename T> T as(T*) const; /// Generic cast operator using the extensible uvalue_cast mechanism. template<typename T> T as() const; /// Conveniance wrapper on as(). template<typename T> T& fill(T&) const; operator int() const; operator bool() const; // Cast to a UBinary to make copy through this operator. operator const UBinary&() const; /// Deep copy, binary will have to be deleted by the user. operator UBinary*() const; /// In plugin mode, gives direct access to the buffer, which may /// not be valid after the calling function returns. Changes to /// the other fields of the structure have no effect. operator UImage() const; /// In plugin mode, gives direct access to the buffer, which may /// not be valid after the calling function returns. Changes to /// the other fields of the structure have no effect. operator USound() const; operator ufloat() const; operator std::string() const; operator UList() const; operator UDictionary() const; /// Deactivate all callbacks associated with this UVar and stop synchro. void unnotify(); /// Kernel operators. ufloat& in(); ufloat& out(); /// Is the variable owned by the module? bool owned; /// Property accessors. UProp rangemin; UProp rangemax; UProp speedmin; UProp speedmax; UProp delta; UProp blend; UProp constant; UValue getProp(UProperty prop); void setProp(UProperty prop, const UValue& v); void setProp(UProperty prop, ufloat v); void setProp(UProperty prop, const char* v); void setProp(UProperty prop, const std::string& v) { setProp(prop, v.c_str()); } /// Enable bypass-mode for this UVar. Plugin-mode only. /// In bypass mode, if the UVar contains binary data, the data is never /// copied. The consequence is that the data is only accessible from /// notifyChange callbacks (urbiScript or C++): it is invalidated as soon /// as all callbacks have returned. bool setBypass(bool enable=true); /// Use RTP mode to transmit this variable if possible. void useRTP(bool enable=true); impl::UVarImpl* impl_; const UValue& val() const; ATTRIBUTE_PURE libport::utime_t timestamp() const; enum RtpMode { RTP_DEFAULT, ///< Use RTP if it is the default mode RTP_YES, ///< Force RTP RTP_NO ///< Do not use RTP }; /// Check that impl_ is set or throw a runtime error. void check() const; private: /// Pointer to internal data specifics. UVardata* vardata; void __init(); /// Define an attribute and its accessors. # define PRIVATE(Type, Name) \ public: \ Type get_ ## Name () \ { \ return Name; \ } \ Type get_ ## Name () const \ { \ return Name; \ } \ void set_ ## Name (const Type& v) \ { \ Name = v; \ } \ private: \ Type Name; /// Full name of the variable as seen in URBI. PRIVATE(std::string, name) /// True if the variable is a temporary and must not be stored in callbacks PRIVATE(bool, temp); PRIVATE(RtpMode, rtp); /// If set, this variable will never export its content remotely. PRIVATE(bool, local); # undef PRIVATE // Check that the invariants of this class are verified. bool invariant() const; friend class impl::UVarImpl; }; /*-------------------------. | Inline implementations. | `-------------------------*/ /// Helper macro to initialize UProps in UVar constructors. # define VAR_PROP_INIT \ rangemin(*this, PROP_RANGEMIN), \ rangemax(*this, PROP_RANGEMAX), \ speedmin(*this, PROP_SPEEDMIN), \ speedmax(*this, PROP_SPEEDMAX), \ delta(*this, PROP_DELTA), \ blend(*this, PROP_BLEND), \ constant(*this, PROP_CONSTANT) /// Report \a u on \a o for debugging. URBI_SDK_API std::ostream& operator<< (std::ostream& o, const UVar& u); } // end namespace urbi # include <urbi/uvar.hxx> #endif // ! URBI_UVAR_HH <commit_msg>UObject: Prevent "*UVar".<commit_after>/* * Copyright (C) 2007, 2008, 2009, 2010, 2011, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /// \file urbi/uvar.hh #ifndef URBI_UVAR_HH # define URBI_UVAR_HH # include <iosfwd> # include <string> # include <libport/fwd.hh> # include <libport/ufloat.hh> # include <urbi/ucontext.hh> # include <urbi/uvalue.hh> # include <urbi/uprop.hh> # include <urbi/uproperty.hh> namespace urbi { /** UVar class definition Each UVar instance corresponds to one URBI variable. The class provides access to the variable properties, and reading/writing the value to/from all known types. */ class URBI_SDK_API UVar: public UContext { public: /// Creates an unbound UVar. Call init() to bind it. UVar(); UVar(const std::string&, impl::UContextImpl* = 0); UVar(const std::string&, const std::string&, impl::UContextImpl* = 0); UVar(UObject&, const std::string&, impl::UContextImpl* = 0); UVar(const UVar&); private: UVar& operator=(const UVar&); public: ~UVar(); // Bind to \a object.slot. void init(const std::string& varname, impl::UContextImpl* = 0); void init(const std::string& object, const std::string& slot, impl::UContextImpl* = 0); void setOwned(); /// The type of the current content. UDataType type() const; /// Request the current value, wait until it is available. void syncValue(); /// Keep this UVar synchronized with kernel value. void keepSynchronized(); void reset (ufloat); UVar& operator=(ufloat); UVar& operator=(const std::string&); /// Deep copy. UVar& operator=(const UBinary&); /// Deep copy. UVar& operator=(const UImage& i); /// Deep copy. UVar& operator=(const USound& s); UVar& operator=(const UList& l); UVar& operator=(const UDictionary& d); UVar& operator=(const UValue& v); template<typename T> UVar& operator=(const T&); template<typename T> bool operator ==(const T&) const; /// Cast operator taking a dummy value of the target type. template<typename T> T as(T*) const; /// Generic cast operator using the extensible uvalue_cast mechanism. template<typename T> T as() const; /// Conveniance wrapper on as(). template<typename T> T& fill(T&) const; operator int() const; operator bool() const; // Cast to a UBinary to make copy through this operator. operator const UBinary&() const; /// Deep copy, binary will have to be deleted by the user. operator UBinary*() const; /// In plugin mode, gives direct access to the buffer, which may /// not be valid after the calling function returns. Changes to /// the other fields of the structure have no effect. operator UImage() const; /// In plugin mode, gives direct access to the buffer, which may /// not be valid after the calling function returns. Changes to /// the other fields of the structure have no effect. operator USound() const; operator ufloat() const; operator std::string() const; operator UList() const; operator UDictionary() const; /// Deactivate all callbacks associated with this UVar and stop synchro. void unnotify(); /// Kernel operators. ufloat& in(); ufloat& out(); /// Is the variable owned by the module? bool owned; /// Property accessors. UProp rangemin; UProp rangemax; UProp speedmin; UProp speedmax; UProp delta; UProp blend; UProp constant; UValue getProp(UProperty prop); void setProp(UProperty prop, const UValue& v); void setProp(UProperty prop, ufloat v); void setProp(UProperty prop, const char* v); void setProp(UProperty prop, const std::string& v) { setProp(prop, v.c_str()); } /// Enable bypass-mode for this UVar. Plugin-mode only. /// In bypass mode, if the UVar contains binary data, the data is never /// copied. The consequence is that the data is only accessible from /// notifyChange callbacks (urbiScript or C++): it is invalidated as soon /// as all callbacks have returned. bool setBypass(bool enable=true); /// Use RTP mode to transmit this variable if possible. void useRTP(bool enable=true); impl::UVarImpl* impl_; const UValue& val() const; ATTRIBUTE_PURE libport::utime_t timestamp() const; enum RtpMode { RTP_DEFAULT, ///< Use RTP if it is the default mode RTP_YES, ///< Force RTP RTP_NO, ///< Do not use RTP }; /// Check that impl_ is set or throw a runtime error. void check() const; private: /// Pointer to internal data specifics. UVardata* vardata; void __init(); /// Check that the invariants of this class are verified. bool invariant() const; friend class impl::UVarImpl; // C++ allows "*uvar", it makes it "*(uvar.operator UBinary*())". // This operator is there to avoid this. void operator*() const; /// Define an attribute and its accessors. # define PRIVATE(Type, Name) \ public: \ Type get_ ## Name () \ { \ return Name; \ } \ Type get_ ## Name () const \ { \ return Name; \ } \ void set_ ## Name (const Type& v) \ { \ Name = v; \ } \ private: \ Type Name; /// Full name of the variable as seen in URBI. PRIVATE(std::string, name) /// True if the variable is a temporary and must not be stored in callbacks PRIVATE(bool, temp); PRIVATE(RtpMode, rtp); /// If set, this variable will never export its content remotely. PRIVATE(bool, local); # undef PRIVATE }; /*-------------------------. | Inline implementations. | `-------------------------*/ /// Helper macro to initialize UProps in UVar constructors. # define VAR_PROP_INIT \ rangemin(*this, PROP_RANGEMIN), \ rangemax(*this, PROP_RANGEMAX), \ speedmin(*this, PROP_SPEEDMIN), \ speedmax(*this, PROP_SPEEDMAX), \ delta(*this, PROP_DELTA), \ blend(*this, PROP_BLEND), \ constant(*this, PROP_CONSTANT) /// Report \a u on \a o for debugging. URBI_SDK_API std::ostream& operator<< (std::ostream& o, const UVar& u); } // end namespace urbi # include <urbi/uvar.hxx> #endif // ! URBI_UVAR_HH <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Kirsten Weber #ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH #define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH #include <memory> #include <type_traits> #include <dune/common/exceptions.hh> #include <dune/common/fvector.hh> #include <dune/grid/io/file/vtk.hh> #include <dune/stuff/la/container/interfaces.hh> #include <dune/gdt/spaces/interface.hh> #include "local.hh" namespace Dune { namespace GDT { template <class SpaceImp, class VectorImp> class ConstDiscreteFunction : public Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType, SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols> { static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits>, SpaceImp>::value, "SpaceImp has to be derived from SpaceInterface!"); static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>, VectorImp>::value, "VectorImp has to be derived from Stuff::LA::VectorInterface!"); static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType>::value, "Types do not match!"); typedef Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType, SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols> BaseType; typedef ConstDiscreteFunction<SpaceImp, VectorImp> ThisType; public: typedef SpaceImp SpaceType; typedef VectorImp VectorType; typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; static const unsigned int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainFieldType DomainFieldType; typedef typename BaseType::DomainType DomainType; static const unsigned int dimRange = BaseType::dimRange; static const unsigned int dimRangeCols = BaseType::dimRangeCols; typedef typename BaseType::RangeFieldType RangeFieldType; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; typedef ConstLocalDiscreteFunction<SpaceType, VectorType> ConstLocalDiscreteFunctionType; ConstDiscreteFunction(const SpaceType& sp, const VectorType& vec, const std::string nm = "dune.gdt.constdiscretefunction") : space_(sp) , vector_(vec) , name_(nm) { assert(vector_.size() == space_.mapper().size() && "Given vector has wrong size!"); } ConstDiscreteFunction(const ThisType& other) : space_(other.space_) , vector_(other.vector_) , name_(other.name_) { } ConstDiscreteFunction(ThisType&& source) : space_(source.space_) , vector_(source.vector_) , name_(std::move(source.name_)) { } virtual ~ConstDiscreteFunction() { } ThisType& operator=(const ThisType& other) = delete; virtual ThisType* copy() const DS_OVERRIDE { return new ThisType(*this); } virtual std::string name() const DS_OVERRIDE { return name_; } const SpaceType& space() const { return space_; } const VectorType& vector() const { return vector_; } ConstLocalDiscreteFunctionType local_discrete_function(const EntityType& entity) const { assert(space_.grid_view()->indexSet().contains(entity)); return ConstLocalDiscreteFunctionType(space_, vector_, entity); } virtual std::unique_ptr<LocalfunctionType> local_function(const EntityType& entity) const DS_OVERRIDE { return std::unique_ptr<ConstLocalDiscreteFunctionType>( new ConstLocalDiscreteFunctionType(local_discrete_function(entity))); } void visualize(const std::string filename, const bool subsampling = (SpaceType::polOrder > 1), VTK::OutputType vtk_output_type = VTK::appendedraw) const { BaseType::template visualize<typename SpaceType::GridViewType>( *(space().grid_view()), filename, subsampling, vtk_output_type); } protected: const SpaceType& space_; private: const VectorType& vector_; const std::string name_; }; // class ConstDiscreteFunction template <class SpaceImp, class VectorImp> class DiscreteFunction : public ConstDiscreteFunction<SpaceImp, VectorImp> { typedef ConstDiscreteFunction<SpaceImp, VectorImp> BaseType; typedef DiscreteFunction<SpaceImp, VectorImp> ThisType; public: typedef typename BaseType::SpaceType SpaceType; typedef typename BaseType::VectorType VectorType; typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef LocalDiscreteFunction<SpaceType, VectorType> LocalDiscreteFunctionType; DiscreteFunction(const SpaceType& sp, VectorType& vec, const std::string nm = "dune.gdt.discretefunction") : BaseType(sp, vec, nm) , vector_(vec) { } DiscreteFunction(const ThisType& other) : BaseType(other) , vector_(other.vector_) { } DiscreteFunction(ThisType&& source) : BaseType(std::move(source)) , vector_(source.vector_) { } ~DiscreteFunction() { } ThisType& operator=(const ThisType& other) = delete; virtual ThisType* copy() const DS_OVERRIDE { return new ThisType(*this); } VectorType& vector() { return vector_; } using BaseType::local_discrete_function; LocalDiscreteFunctionType local_discrete_function(const EntityType& entity) { assert(space_.grid_view()->indexSet().contains(entity)); return LocalDiscreteFunctionType(space_, vector_, entity); } private: using BaseType::space_; VectorType& vector_; }; // class DiscreteFunction } // namespace GDT } // namespace Dune #endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH <commit_msg>[df] adds new DiscreteFunction with internal vector storage<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Kirsten Weber #ifndef DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH #define DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH #include <memory> #include <type_traits> #include <dune/common/exceptions.hh> #include <dune/common/fvector.hh> #include <dune/grid/io/file/vtk.hh> #include <dune/stuff/la/container/interfaces.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/gdt/spaces/interface.hh> #include "local.hh" namespace Dune { namespace GDT { template <class SpaceImp, class VectorImp> class ConstDiscreteFunction : public Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType, SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols> { static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits>, SpaceImp>::value, "SpaceImp has to be derived from SpaceInterface!"); static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>, VectorImp>::value, "VectorImp has to be derived from Stuff::LA::VectorInterface!"); static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType>::value, "Types do not match!"); typedef Stuff::LocalizableFunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType, SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols> BaseType; typedef ConstDiscreteFunction<SpaceImp, VectorImp> ThisType; public: typedef SpaceImp SpaceType; typedef VectorImp VectorType; typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; static const unsigned int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainFieldType DomainFieldType; typedef typename BaseType::DomainType DomainType; static const unsigned int dimRange = BaseType::dimRange; static const unsigned int dimRangeCols = BaseType::dimRangeCols; typedef typename BaseType::RangeFieldType RangeFieldType; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; typedef ConstLocalDiscreteFunction<SpaceType, VectorType> ConstLocalDiscreteFunctionType; ConstDiscreteFunction(const SpaceType& sp, const VectorType& vec, const std::string nm = "dune.gdt.constdiscretefunction") : space_(sp) , vector_(vec) , name_(nm) { assert(vector_.size() == space_.mapper().size() && "Given vector has wrong size!"); } ConstDiscreteFunction(const ThisType& other) : space_(other.space_) , vector_(other.vector_) , name_(other.name_) { } ConstDiscreteFunction(ThisType&& source) : space_(source.space_) , vector_(source.vector_) , name_(std::move(source.name_)) { } virtual ~ConstDiscreteFunction() { } ThisType& operator=(const ThisType& other) = delete; virtual ThisType* copy() const DS_OVERRIDE { return new ThisType(*this); } virtual std::string name() const DS_OVERRIDE { return name_; } const SpaceType& space() const { return space_; } const VectorType& vector() const { return vector_; } ConstLocalDiscreteFunctionType local_discrete_function(const EntityType& entity) const { assert(space_.grid_view()->indexSet().contains(entity)); return ConstLocalDiscreteFunctionType(space_, vector_, entity); } virtual std::unique_ptr<LocalfunctionType> local_function(const EntityType& entity) const DS_OVERRIDE { return std::unique_ptr<ConstLocalDiscreteFunctionType>( new ConstLocalDiscreteFunctionType(local_discrete_function(entity))); } void visualize(const std::string filename, const bool subsampling = (SpaceType::polOrder > 1), VTK::OutputType vtk_output_type = VTK::appendedraw) const { BaseType::template visualize<typename SpaceType::GridViewType>( *(space().grid_view()), filename, subsampling, vtk_output_type); } protected: const SpaceType& space_; private: const VectorType& vector_; const std::string name_; }; // class ConstDiscreteFunction template <class SpaceImp, class VectorImp> class DiscreteFunction : public ConstDiscreteFunction<SpaceImp, VectorImp> { typedef ConstDiscreteFunction<SpaceImp, VectorImp> BaseType; typedef DiscreteFunction<SpaceImp, VectorImp> ThisType; public: typedef typename BaseType::SpaceType SpaceType; typedef typename BaseType::VectorType VectorType; typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef LocalDiscreteFunction<SpaceType, VectorType> LocalDiscreteFunctionType; DiscreteFunction(const SpaceType& sp, VectorType& vec, const std::string nm = "dune.gdt.discretefunction") : BaseType(sp, vec, nm) , vector_(vec) { } DiscreteFunction(const ThisType& other) : BaseType(other) , vector_(other.vector_) { } DiscreteFunction(ThisType&& source) : BaseType(std::move(source)) , vector_(source.vector_) { } ~DiscreteFunction() { } ThisType& operator=(const ThisType& other) = delete; virtual ThisType* copy() const DS_OVERRIDE { return new ThisType(*this); } VectorType& vector() { return vector_; } using BaseType::local_discrete_function; LocalDiscreteFunctionType local_discrete_function(const EntityType& entity) { assert(space_.grid_view()->indexSet().contains(entity)); return LocalDiscreteFunctionType(space_, vector_, entity); } private: using BaseType::space_; VectorType& vector_; }; // class DiscreteFunction template <class SpaceImp, class VectorImp> class StoredDiscreteFunction : public DiscreteFunction<SpaceImp, VectorImp> { typedef DiscreteFunction<SpaceImp, VectorImp> BaseType; typedef StoredDiscreteFunction<SpaceImp, VectorImp> ThisType; public: typedef typename BaseType::SpaceType SpaceType; typedef typename BaseType::VectorType VectorType; typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef LocalDiscreteFunction<SpaceType, VectorType> LocalDiscreteFunctionType; StoredDiscreteFunction(const SpaceType& sp, const std::string nm = "dune.gdt.discretefunction") : BaseType(sp, vector_, nm) , vector_(sp.mapper().size()) { } ~StoredDiscreteFunction() { } ThisType& operator=(const ThisType& other) = delete; virtual ThisType* copy() const DS_OVERRIDE { return new ThisType(*this); } VectorType& vector() { return vector_; } LocalDiscreteFunctionType local_discrete_function(const EntityType& entity) { return LocalDiscreteFunctionType(BaseType::space(), vector_, entity); } bool dofsValid() const { for (const auto& val : vector_) { if (std::isnan(val) || std::isinf(val)) return false; } return true; } private: VectorType vector_; }; // class DiscreteFunction } // namespace GDT } // namespace Dune #endif // DUNE_GDT_DISCRETEFUNCTION_DEFAULT_HH <|endoftext|>
<commit_before>#include "PackTexture.h" #include "check_params.h" #include "utility.h" #include <ee/FileHelper.h> #include <ee/SettingData.h> #include <ee/Config.h> #include <ee/StringHelper.h> #include <ee/SymbolFile.h> #include <easytexpacker.h> #include <easyimage.h> #include <gimg_typedef.h> #include <gimg_import.h> #include <sprite2/SymType.h> #include <gum/Config.h> #include <wx/filefn.h> #include <fstream> namespace edb { std::string PackTexture::Command() const { return "pack-tex"; } std::string PackTexture::Description() const { return "pack texture"; } std::string PackTexture::Usage() const { std::string cmd0 = Command() + " [json str]"; std::string cmd1 = Command() + " [src dir] [dst dir] [min size] [max size] [trim file] [extrude]"; return cmd0 + " or " + cmd1; } int PackTexture::Run(int argc, char *argv[]) { if (!check_number(this, argc, 3)) return -1; int ret = init_gl(); if (ret < 0) { return ret; } // one param if (argc == 3) { Pack(argv[2]); } // multi params else { Package pkg; pkg.sources.push_back(argv[2]); pkg.format = "png"; pkg.size_min = atof(argv[4]); pkg.size_max = atof(argv[5]); if (argc > 6) { if (strcmp(argv[6], "null") != 0) { pkg.trim = new etexpacker::ImageTrimData(argv[6]); } } int extrude = 1; if (argc > 7) { extrude = atoi(argv[7]); } pkg.extrude_min = pkg.extrude_max = extrude; std::vector<Package> packages; packages.push_back(pkg); std::string dst_file = argv[3]; Pack(packages, argv[2], dst_file); delete pkg.trim; } return 0; } void PackTexture::Pack(const std::string& str_val) { std::vector<Package> packages; std::string src_dir, dst_file; etexpacker::ImageTrimData* trim = PreparePackages(str_val, packages, src_dir, dst_file); Pack(packages, src_dir, dst_file); delete trim; } void PackTexture::Pack(const std::vector<Package>& packages, const std::string& src_dir, const std::string& dst_file) { std::string dst_dir = ee::FileHelper::GetFileDir(dst_file); ee::FileHelper::MkDir(dst_dir); ee::SettingData& sd = ee::Config::Instance()->GetSettings(); bool ori_cfg = sd.open_image_edge_clip; sd.open_image_edge_clip = false; int start_id = 1; for (int i = 0, n = packages.size(); i < n; ++i) { PackPackage(packages[i], src_dir, dst_file, start_id); } sd.open_image_edge_clip = ori_cfg; } void PackTexture::CompressPackedTex(const etexpacker::NormalPack& tp, int& start_id, const std::string& file, const std::string& fmt, bool fast) { int begin = start_id; start_id += tp.DstTexCount(); int end = start_id; if (fmt == "pvr") { for (int i = begin; i < end; ++i) { std::string src = file + ee::StringHelper::ToString(i) + ".png"; std::string dst = file + ee::StringHelper::ToString(i) + ".pvr"; int w, h, fmt; uint8_t* pixels = gimg_import(src.c_str(), &w, &h, &fmt); if (fmt == GPF_RGBA && gum::Config::Instance()->GetPreMulAlpha()) { gimg_pre_mul_alpha(pixels, w, h); } int c = fmt == GPF_RGB ? 3 : 4; eimage::TransToPVR trans(pixels, w, h, c, false, fast); delete[] pixels; trans.OutputFile(dst); // wxRemoveFile(src); } } else if (fmt == "etc1") { for (int i = begin; i < end; ++i) { std::string src = file + ee::StringHelper::ToString(i) + ".png"; std::string dst = file + ee::StringHelper::ToString(i); int w, h, fmt; uint8_t* pixels = gimg_import(src.c_str(), &w, &h, &fmt); if (fmt == GPF_RGBA && gum::Config::Instance()->GetPreMulAlpha()) { gimg_pre_mul_alpha(pixels, w, h); } int c = fmt == GPF_RGB ? 3 : 4; eimage::TransToETC1 trans(pixels, w, h, c, false, fast); delete[] pixels; trans.OutputFile(dst); // wxRemoveFile(src); } } else if (fmt == "etc2") { for (int i = begin; i < end; ++i) { std::string src = file + ee::StringHelper::ToString(i) + ".png"; std::string dst = file + ee::StringHelper::ToString(i) + ".pkm"; int w, h, fmt; uint8_t* pixels = gimg_import(src.c_str(), &w, &h, &fmt); if (fmt == GPF_RGBA && gum::Config::Instance()->GetPreMulAlpha()) { gimg_pre_mul_alpha(pixels, w, h); } int c = fmt == GPF_RGB ? 3 : 4; eimage::TransToETC2 trans(pixels, w, h, c, eimage::TransToETC2::RGBA, false, fast); delete[] pixels; trans.OutputFile(dst); // wxRemoveFile(src); } } } etexpacker::ImageTrimData* PackTexture::PreparePackages(const std::string& str, std::vector<Package>& packages, std::string& src_dir, std::string& dst_file) { Json::Value value; Json::Reader reader; reader.parse(str, value); src_dir = value["src"].asString(); dst_file = value["dst"].asString(); etexpacker::ImageTrimData* trim = NULL; if (!value["trim_file"].isNull()) { std::string trim_file = value["trim_file"].asString(); trim = new etexpacker::ImageTrimData(trim_file); } const Json::Value& pkgs_val = value["packages"]; for (int i = 0, n = pkgs_val.size(); i < n; ++i) { const Json::Value& v = pkgs_val[i]; Package pkg; if (v["src"].isString()) { pkg.sources.push_back(v["src"].asString()); } else { assert(v["src"].isArray()); for (int i = 0, n = v["src"].size(); i < n; ++i) { pkg.sources.push_back(v["src"][i].asString()); } } pkg.format = v["format"].asString(); pkg.quality = v["quality"].asString(); pkg.size_max = v["size_max"].asInt(); pkg.size_min = v["size_min"].asInt(); pkg.trim = trim; pkg.extrude_min = v["extrude_min"].asInt(); pkg.extrude_max = v["extrude_max"].asInt(); packages.push_back(pkg); } for (int i = 0, n = packages.size(); i < n; ++i) { Package& pkg0 = packages[i]; if (pkg0.sources.size() == 1 && pkg0.sources[0] == "others") { for (int j = 0; j < n; ++j) { if (j == i) continue; const Package& pkg1 = packages[j]; if (pkg1.sources.size() == 1 && pkg1.sources[0] == "others") { continue; } for (int k = 0, m = pkg1.sources.size(); k < m; ++k) { const std::string& path = pkg1.sources[k]; if (path != "others" && path != src_dir) { pkg0.ignores.push_back(path); } } } pkg0.sources[0] = src_dir; } } return trim; } void PackTexture::PackPackage(const Package& pkg, const std::string& src_dir, const std::string& dst_file, int& start_id) { std::vector<std::string> images; wxArrayString files; if (pkg.ignores.empty()) { for (int i = 0, n = pkg.sources.size(); i < n; ++i) { ee::FileHelper::FetchAllFiles(pkg.sources[i], files); } } else { for (int i = 0, n = pkg.sources.size(); i < n; ++i) { ee::FileHelper::FetchAllFiles(pkg.sources[i], pkg.ignores, files); } } for (int i = 0, n = files.size(); i < n; ++i) { if (ee::SymbolFile::Instance()->Type(files[i].ToStdString()) == s2::SYM_IMAGE) { std::string filepath = ee::FileHelper::FormatFilepathAbsolute(files[i].ToStdString()); images.push_back(filepath); } } etexpacker::NormalPack tex_packer(images, pkg.trim, pkg.extrude_min, pkg.extrude_max, start_id); tex_packer.Pack(0, pkg.size_max, pkg.size_min); tex_packer.OutputInfo(src_dir, dst_file + ".json", pkg.format); tex_packer.OutputImage(dst_file + ".png"); CompressPackedTex(tex_packer, start_id, dst_file, pkg.format, pkg.quality == "fastest"); } }<commit_msg>[FIXED] pack compressed texture should not pre mul alpha, because it is read from png, already pre mul alpha.<commit_after>#include "PackTexture.h" #include "check_params.h" #include "utility.h" #include <ee/FileHelper.h> #include <ee/SettingData.h> #include <ee/Config.h> #include <ee/StringHelper.h> #include <ee/SymbolFile.h> #include <easytexpacker.h> #include <easyimage.h> #include <gimg_typedef.h> #include <gimg_import.h> #include <sprite2/SymType.h> #include <gum/Config.h> #include <wx/filefn.h> #include <fstream> namespace edb { std::string PackTexture::Command() const { return "pack-tex"; } std::string PackTexture::Description() const { return "pack texture"; } std::string PackTexture::Usage() const { std::string cmd0 = Command() + " [json str]"; std::string cmd1 = Command() + " [src dir] [dst dir] [min size] [max size] [trim file] [extrude]"; return cmd0 + " or " + cmd1; } int PackTexture::Run(int argc, char *argv[]) { if (!check_number(this, argc, 3)) return -1; int ret = init_gl(); if (ret < 0) { return ret; } // one param if (argc == 3) { Pack(argv[2]); } // multi params else { Package pkg; pkg.sources.push_back(argv[2]); pkg.format = "png"; pkg.size_min = atof(argv[4]); pkg.size_max = atof(argv[5]); if (argc > 6) { if (strcmp(argv[6], "null") != 0) { pkg.trim = new etexpacker::ImageTrimData(argv[6]); } } int extrude = 1; if (argc > 7) { extrude = atoi(argv[7]); } pkg.extrude_min = pkg.extrude_max = extrude; std::vector<Package> packages; packages.push_back(pkg); std::string dst_file = argv[3]; Pack(packages, argv[2], dst_file); delete pkg.trim; } return 0; } void PackTexture::Pack(const std::string& str_val) { std::vector<Package> packages; std::string src_dir, dst_file; etexpacker::ImageTrimData* trim = PreparePackages(str_val, packages, src_dir, dst_file); Pack(packages, src_dir, dst_file); delete trim; } void PackTexture::Pack(const std::vector<Package>& packages, const std::string& src_dir, const std::string& dst_file) { std::string dst_dir = ee::FileHelper::GetFileDir(dst_file); ee::FileHelper::MkDir(dst_dir); ee::SettingData& sd = ee::Config::Instance()->GetSettings(); bool ori_cfg = sd.open_image_edge_clip; sd.open_image_edge_clip = false; int start_id = 1; for (int i = 0, n = packages.size(); i < n; ++i) { PackPackage(packages[i], src_dir, dst_file, start_id); } sd.open_image_edge_clip = ori_cfg; } void PackTexture::CompressPackedTex(const etexpacker::NormalPack& tp, int& start_id, const std::string& file, const std::string& fmt, bool fast) { int begin = start_id; start_id += tp.DstTexCount(); int end = start_id; if (fmt == "pvr") { for (int i = begin; i < end; ++i) { std::string src = file + ee::StringHelper::ToString(i) + ".png"; std::string dst = file + ee::StringHelper::ToString(i) + ".pvr"; int w, h, fmt; uint8_t* pixels = gimg_import(src.c_str(), &w, &h, &fmt); // if (fmt == GPF_RGBA && gum::Config::Instance()->GetPreMulAlpha()) { // gimg_pre_mul_alpha(pixels, w, h); // } int c = fmt == GPF_RGB ? 3 : 4; eimage::TransToPVR trans(pixels, w, h, c, false, fast); delete[] pixels; trans.OutputFile(dst); // wxRemoveFile(src); } } else if (fmt == "etc1") { for (int i = begin; i < end; ++i) { std::string src = file + ee::StringHelper::ToString(i) + ".png"; std::string dst = file + ee::StringHelper::ToString(i); int w, h, fmt; uint8_t* pixels = gimg_import(src.c_str(), &w, &h, &fmt); // if (fmt == GPF_RGBA && gum::Config::Instance()->GetPreMulAlpha()) { // gimg_pre_mul_alpha(pixels, w, h); // } int c = fmt == GPF_RGB ? 3 : 4; eimage::TransToETC1 trans(pixels, w, h, c, false, fast); delete[] pixels; trans.OutputFile(dst); // wxRemoveFile(src); } } else if (fmt == "etc2") { for (int i = begin; i < end; ++i) { std::string src = file + ee::StringHelper::ToString(i) + ".png"; std::string dst = file + ee::StringHelper::ToString(i) + ".pkm"; int w, h, fmt; uint8_t* pixels = gimg_import(src.c_str(), &w, &h, &fmt); // if (fmt == GPF_RGBA && gum::Config::Instance()->GetPreMulAlpha()) { // gimg_pre_mul_alpha(pixels, w, h); // } int c = fmt == GPF_RGB ? 3 : 4; eimage::TransToETC2 trans(pixels, w, h, c, eimage::TransToETC2::RGBA, false, fast); delete[] pixels; trans.OutputFile(dst); // wxRemoveFile(src); } } } etexpacker::ImageTrimData* PackTexture::PreparePackages(const std::string& str, std::vector<Package>& packages, std::string& src_dir, std::string& dst_file) { Json::Value value; Json::Reader reader; reader.parse(str, value); src_dir = value["src"].asString(); dst_file = value["dst"].asString(); etexpacker::ImageTrimData* trim = NULL; if (!value["trim_file"].isNull()) { std::string trim_file = value["trim_file"].asString(); trim = new etexpacker::ImageTrimData(trim_file); } const Json::Value& pkgs_val = value["packages"]; for (int i = 0, n = pkgs_val.size(); i < n; ++i) { const Json::Value& v = pkgs_val[i]; Package pkg; if (v["src"].isString()) { pkg.sources.push_back(v["src"].asString()); } else { assert(v["src"].isArray()); for (int i = 0, n = v["src"].size(); i < n; ++i) { pkg.sources.push_back(v["src"][i].asString()); } } pkg.format = v["format"].asString(); pkg.quality = v["quality"].asString(); pkg.size_max = v["size_max"].asInt(); pkg.size_min = v["size_min"].asInt(); pkg.trim = trim; pkg.extrude_min = v["extrude_min"].asInt(); pkg.extrude_max = v["extrude_max"].asInt(); packages.push_back(pkg); } for (int i = 0, n = packages.size(); i < n; ++i) { Package& pkg0 = packages[i]; if (pkg0.sources.size() == 1 && pkg0.sources[0] == "others") { for (int j = 0; j < n; ++j) { if (j == i) continue; const Package& pkg1 = packages[j]; if (pkg1.sources.size() == 1 && pkg1.sources[0] == "others") { continue; } for (int k = 0, m = pkg1.sources.size(); k < m; ++k) { const std::string& path = pkg1.sources[k]; if (path != "others" && path != src_dir) { pkg0.ignores.push_back(path); } } } pkg0.sources[0] = src_dir; } } return trim; } void PackTexture::PackPackage(const Package& pkg, const std::string& src_dir, const std::string& dst_file, int& start_id) { std::vector<std::string> images; wxArrayString files; if (pkg.ignores.empty()) { for (int i = 0, n = pkg.sources.size(); i < n; ++i) { ee::FileHelper::FetchAllFiles(pkg.sources[i], files); } } else { for (int i = 0, n = pkg.sources.size(); i < n; ++i) { ee::FileHelper::FetchAllFiles(pkg.sources[i], pkg.ignores, files); } } for (int i = 0, n = files.size(); i < n; ++i) { if (ee::SymbolFile::Instance()->Type(files[i].ToStdString()) == s2::SYM_IMAGE) { std::string filepath = ee::FileHelper::FormatFilepathAbsolute(files[i].ToStdString()); images.push_back(filepath); } } etexpacker::NormalPack tex_packer(images, pkg.trim, pkg.extrude_min, pkg.extrude_max, start_id); tex_packer.Pack(0, pkg.size_max, pkg.size_min); tex_packer.OutputInfo(src_dir, dst_file + ".json", pkg.format); tex_packer.OutputImage(dst_file + ".png"); CompressPackedTex(tex_packer, start_id, dst_file, pkg.format, pkg.quality == "fastest"); } }<|endoftext|>
<commit_before>#include <fstream> #include <BGL.hh> #include "testbed.h" // Rectangle BGL::Point pointSet1[] = { BGL::Point(-8.590003524884, 8.590000000000), BGL::Point(-8.590046474991, -8.590000000000), BGL::Point( 8.590000000000, -8.590000000000), BGL::Point( 8.590000000000, 8.590000000000), BGL::Point(-8.590003524884, 8.590000000000) }; // Smaller Rectangle BGL::Point pointSet2[] = { BGL::Point(-9.999997000000, 10.000000000000), BGL::Point(-9.849997000000, 10.000000000000), BGL::Point(-9.849997000000, 8.590000000000), BGL::Point(-9.999997000000, 8.590000000000), BGL::Point(-9.999997000000, 10.000000000000) }; int main(int argc, char**argv) { char fname[128]; double infillInset=1.410000; BGL::Path path1(sizeof(pointSet1)/sizeof(BGL::Point), pointSet1); BGL::Path path2(sizeof(pointSet2)/sizeof(BGL::Point), pointSet2); fstream fout; BGL::SVG svg(250, 250); synthesize_testfile_name(fname, sizeof(fname), argv[0], "diff", "svg"); fout.open(fname, fstream::out | fstream::trunc); if (fout.good()) { svg.header(fout); BGL::Paths outPaths; BGL::Path::differenceOf(path1, path2, outPaths); BGL::Paths::iterator it; fout << "<g stroke=\"#77f\">" << endl; path1 *= 3.0; path1.svgPathWithOffset(fout, 30, 30); fout << "</g>" << endl; fout << "<g stroke=\"#f77\">" << endl; path2 *= 3.0; path2.svgPathWithOffset(fout, 30, 30); fout << "</g>" << endl; for (it = outPaths.begin(); it != outPaths.end(); it++) { *it *= 3.0; it->svgPathWithOffset(fout, 30, 30); } svg.footer(fout); fout.sync(); fout.close(); } return 0; } <commit_msg>Removed unused variable.<commit_after>#include <fstream> #include <BGL.hh> #include "testbed.h" // Rectangle BGL::Point pointSet1[] = { BGL::Point(-8.590003524884, 8.590000000000), BGL::Point(-8.590046474991, -8.590000000000), BGL::Point( 8.590000000000, -8.590000000000), BGL::Point( 8.590000000000, 8.590000000000), BGL::Point(-8.590003524884, 8.590000000000) }; // Smaller Rectangle BGL::Point pointSet2[] = { BGL::Point(-9.999997000000, 10.000000000000), BGL::Point(-9.849997000000, 10.000000000000), BGL::Point(-9.849997000000, 8.590000000000), BGL::Point(-9.999997000000, 8.590000000000), BGL::Point(-9.999997000000, 10.000000000000) }; int main(int argc, char**argv) { char fname[128]; BGL::Path path1(sizeof(pointSet1)/sizeof(BGL::Point), pointSet1); BGL::Path path2(sizeof(pointSet2)/sizeof(BGL::Point), pointSet2); fstream fout; BGL::SVG svg(250, 250); synthesize_testfile_name(fname, sizeof(fname), argv[0], "diff", "svg"); fout.open(fname, fstream::out | fstream::trunc); if (fout.good()) { svg.header(fout); BGL::Paths outPaths; BGL::Path::differenceOf(path1, path2, outPaths); BGL::Paths::iterator it; fout << "<g stroke=\"#77f\">" << endl; path1 *= 3.0; path1.svgPathWithOffset(fout, 30, 30); fout << "</g>" << endl; fout << "<g stroke=\"#f77\">" << endl; path2 *= 3.0; path2.svgPathWithOffset(fout, 30, 30); fout << "</g>" << endl; for (it = outPaths.begin(); it != outPaths.end(); it++) { *it *= 3.0; it->svgPathWithOffset(fout, 30, 30); } svg.footer(fout); fout.sync(); fout.close(); } return 0; } <|endoftext|>
<commit_before><commit_msg>Increase simulation loop rate to 1 kHz<commit_after><|endoftext|>
<commit_before>#include "StatefulTimer.h" #include "BackpropErrorsv2Cached.h" using namespace std; #undef STATIC #define STATIC #undef VIRTUAL #define VIRTUAL VIRTUAL BackpropErrorsv2Cached::~BackpropErrorsv2Cached() { delete kernel; delete applyActivationDeriv; } VIRTUAL void BackpropErrorsv2Cached::backpropErrors( int batchSize, CLWrapper *inputDataWrapper, CLWrapper *errorsWrapper, CLWrapper *weightsWrapper, CLWrapper *errorsForUpstreamWrapper ) { StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached start" ); // const int batchSize, // global const float *errorsGlobal, // global const float *filtersGlobal, // global float *errorsForUpstream, // local float *_errorBoard, // local float *_filterBoard ) { kernel ->in( batchSize ) ->in( errorsWrapper ) ->in( weightsWrapper ) ->out( errorsForUpstreamWrapper ) ->localFloats( square( dim.outputBoardSize ) ) ->localFloats( square( dim.filterSize ) ); int numWorkgroups = batchSize * dim.inputPlanes; int workgroupSize = square( dim.inputBoardSize ); workgroupSize = std::max( 32, workgroupSize ); // no point in wasting cores... int globalSize = numWorkgroups * workgroupSize; // int globalSize = batchSize * dim.inputCubeSize; // int workgroupsize = cl->getMaxWorkgroupSize(); // globalSize = ( ( globalSize + workgroupsize - 1 ) / workgroupsize ) * workgroupsize; // kernel->run_1d(globalSize, workgroupsize); float const*errorsForUpstream = (float *)errorsForUpstreamWrapper->getHostArray(); kernel->run_1d(globalSize, workgroupSize); cl->finish(); errorsForUpstreamWrapper->copyToHost(); StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached after first kernel" ); for( int i = 0; i < min( 40, batchSize * dim.inputCubeSize ); i++ ) { cout << "efu[" << i << "]=" << errorsForUpstream[i] << endl; } // applyActivationDeriv->in( batchSize * dim.inputCubeSize )->in( errorsForUpstreamWrapper )->in( inputDataWrapper ); // applyActivationDeriv->run_1d(globalSize, workgroupSize); applyActivationDeriv->in( batchSize * dim.inputCubeSize )->in( errorsForUpstreamWrapper )->in( inputDataWrapper ); applyActivationDeriv->run_1d(globalSize, workgroupSize); cl->finish(); StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached after applyActivationDeriv" ); errorsForUpstreamWrapper->copyToHost(); for( int i = 0; i < min( 40, batchSize * dim.inputCubeSize ); i++ ) { cout << "efu2[" << i << "]=" << errorsForUpstream[i] << endl; } StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached end" ); } BackpropErrorsv2Cached::BackpropErrorsv2Cached( OpenCLHelper *cl, LayerDimensions dim, ActivationFunction const *upstreamFn ) : BackpropErrorsv2( cl, dim, upstreamFn ) { std::string options = dim.buildOptionsString(); options += " -D " + upstreamFn->getDefineName(); // [[[cog // import stringify // stringify.write_kernel2( "kernel", "cl/backproperrorsv2cached.cl", "calcErrorsForUpstreamCached", 'options' ) // # stringify.write_kernel2( "broadcastMultiply", "cl/backproperrorsv2.cl", "broadcast_multiply", 'options' ) // stringify.write_kernel2( "applyActivationDeriv", "cl/applyActivationDeriv.cl", "applyActivationDeriv", 'options' ) // # stringify.write_kernel( "kernelSource", "ClConvolve.cl") // ]]] // generated using cog: const char * kernelSource = "// Copyright Hugh Perkins 2014, 2015 hughperkins at gmail\n" "//\n" "// This Source Code Form is subject to the terms of the Mozilla Public License,\n" "// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n" "// obtain one at http://mozilla.org/MPL/2.0/.\n" "\n" "// as calcErrorsForUpstream, but with local cache\n" "// convolve weights with errors to produce errorsForUpstream\n" "// workgroupid: [n][inputPlane]\n" "// localid: [upstreamrow][upstreamcol]\n" "// per-thread aggregation: [outPlane][filterRow][filterCol]\n" "// need to store locally:\n" "// - _errorBoard. size = outputBoardSizeSquared\n" "// - _filterBoard. size = filtersizesquared\n" "// note: currently doesnt use bias as input. thats probably an error?\n" "// inputs: errors :convolve: filters => errorsForUpstream\n" "//\n" "// global:\n" "// errors: [n][outPlane][outRow][outCol] 128 * 32 * 19 * 19 * 4\n" "// weights: [filterId][upstreamplane][filterRow][filterCol] 32 * 32 * 5 * 5 * 4\n" "// per workgroup:\n" "// errors: [outPlane][outRow][outCol] 32 * 19 * 19 * 4 = 46KB\n" "// weights: [filterId][filterRow][filterCol] 32 * 5 * 5 * 4 = 3.2KB\n" "// errorsforupstream: [n][upstreamPlane][upstreamRow][upstreamCol]\n" "void kernel calcErrorsForUpstreamCached(\n" " const int batchSize,\n" " global const float *errorsGlobal,\n" " global const float *filtersGlobal,\n" " global float *errorsForUpstream,\n" " local float *_errorBoard,\n" " local float *_filterBoard ) {\n" "\n" " const int globalId = get_global_id(0);\n" " const int localId = get_local_id(0);\n" " const int workgroupId = get_group_id(0);\n" " const int workgroupSize = get_local_size(0);\n" "\n" " const int n = workgroupId / gInputPlanes;\n" " const int upstreamPlane = workgroupId % gInputPlanes;\n" "\n" " const int upstreamRow = localId / gInputBoardSize;\n" " const int upstreamCol = localId % gInputBoardSize;\n" "\n" " const int minFilterRow = max( 0, upstreamRow + gMargin - (gOutputBoardSize - 1) );\n" " const int maxFilterRow = min( gFilterSize - 1, upstreamRow + gMargin );\n" " const int minFilterCol = max( 0, upstreamCol + gMargin - (gOutputBoardSize -1) );\n" " const int maxFilterCol = min( gFilterSize - 1, upstreamCol + gMargin );\n" "\n" " const int filterPixelCopiesPerThread = ( gFilterSizeSquared + workgroupSize - 1 ) / workgroupSize;\n" " const int errorPixelCopiesPerThread = ( gOutputBoardSizeSquared + workgroupSize - 1 ) / workgroupSize;\n" " const int pixelCopiesPerThread = max( filterPixelCopiesPerThread, errorPixelCopiesPerThread );\n" "\n" " float sumWeightTimesOutError = 0;\n" " for( int outPlane = 0; outPlane < gNumFilters; outPlane++ ) {\n" " const int filterBoardGlobalOffset =( outPlane * gInputPlanes + upstreamPlane ) * gFilterSizeSquared;\n" " const int errorBoardGlobalOffset = ( n * gNumFilters + outPlane ) * gOutputBoardSizeSquared;\n" " barrier(CLK_LOCAL_MEM_FENCE);\n" " for( int i = 0; i < pixelCopiesPerThread; i++ ) {\n" " int thisOffset = workgroupSize * i + localId;\n" " if( thisOffset < gFilterSizeSquared ) {\n" " _filterBoard[ thisOffset ] = filtersGlobal[ filterBoardGlobalOffset + thisOffset ];\n" " }\n" " if( thisOffset < gOutputBoardSizeSquared ) {\n" " _errorBoard[ thisOffset ] = errorsGlobal[ errorBoardGlobalOffset + thisOffset ];\n" " }\n" " }\n" " barrier(CLK_LOCAL_MEM_FENCE);\n" "// if( globalId == 0 ) {\n" "// for( int i = 0; i < gFilterSizeSquared; i++ ) {\n" "// errorsForUpstream[ (outPlane+1)*100 + i ] = _filterBoard[i];\n" "// }\n" "// }\n" " for( int filterRow = minFilterRow; filterRow <= maxFilterRow; filterRow++ ) {\n" " int outRow = upstreamRow + gMargin - filterRow;\n" " for( int filterCol = minFilterCol; filterCol <= maxFilterCol; filterCol++ ) {\n" " int outCol = upstreamCol + gMargin - filterCol;\n" " int resultIndex = outRow * gOutputBoardSize + outCol;\n" " float thisError = _errorBoard[resultIndex];\n" " int thisWeightIndex = filterRow * gFilterSize + filterCol;\n" " float thisWeight = _filterBoard[thisWeightIndex];\n" " float thisWeightTimesError = thisWeight * thisError;\n" " sumWeightTimesOutError += thisWeightTimesError;\n" " }\n" " }\n" " }\n" " const int upstreamBoardGlobalOffset = ( n * gInputPlanes + upstreamPlane ) * gInputBoardSizeSquared;\n" " if( localId < gInputBoardSizeSquared ) {\n" " errorsForUpstream[upstreamBoardGlobalOffset + localId] = sumWeightTimesOutError;\n" " }\n" "}\n" "\n" ""; kernel = cl->buildKernelFromString( kernelSource, "calcErrorsForUpstreamCached", options, "cl/backproperrorsv2cached.cl" ); // generated using cog: const char * applyActivationDerivSource = "// Copyright Hugh Perkins 201, 2015 hughperkins at gmail\n" "//\n" "// This Source Code Form is subject to the terms of the Mozilla Public License,\n" "// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n" "// obtain one at http://mozilla.org/MPL/2.0/.\n" "\n" "// expected defines:\n" "// one of: [ TANH | RELU | LINEAR | SIGMOID | SCALEDTANH ]\n" "\n" "#ifdef TANH\n" " #define ACTIVATION_DERIV(output) (1 - output * output)\n" "#elif defined SCALEDTANH\n" " #define ACTIVATION_DERIV(output) ( 0.66667f * ( 1.7159f - 1 / 1.7159f * output * output ) )\n" "#elif defined SIGMOID\n" " #define ACTIVATION_DERIV(output) (output * ( 1 - output ) )\n" "#elif defined RELU\n" " #define ACTIVATION_DERIV(output) (output > 0 ? 1 : 0)\n" "#elif defined LINEAR\n" " #define ACTIVATION_DERIV(output) (1.0f)\n" "#endif\n" "\n" "//#ifdef ACTIVATION_DERIV\n" "//void kernel applyActivationDeriv(\n" "// const int N,\n" "// global float *inout ) {\n" "// int globalId = get_global_id(0);\n" "// inout[globalId] = ACTIVATION_DERIV( inout[globalId] );\n" "//}\n" "//#endif\n" "\n" "#ifdef ACTIVATION_DERIV\n" "void kernel applyActivationDeriv(\n" " const int N,\n" " global float *target, global const float *source ) {\n" " int globalId = get_global_id(0);\n" " target[globalId] *= ACTIVATION_DERIV( source[globalId] );\n" " // target[globalId] *= source[globalId];\n" "}\n" "#endif\n" "\n" ""; applyActivationDeriv = cl->buildKernelFromString( applyActivationDerivSource, "applyActivationDeriv", options, "cl/applyActivationDeriv.cl" ); // [[[end]]] // kernel = cl->buildKernel( "backproperrorsv2.cl", "calcErrorsForUpstream", options ); // kernel = cl->buildKernelFromString( kernelSource, "calcErrorsForUpstream", options ); } <commit_msg>change in to inout<commit_after>#include "StatefulTimer.h" #include "BackpropErrorsv2Cached.h" using namespace std; #undef STATIC #define STATIC #undef VIRTUAL #define VIRTUAL VIRTUAL BackpropErrorsv2Cached::~BackpropErrorsv2Cached() { delete kernel; delete applyActivationDeriv; } VIRTUAL void BackpropErrorsv2Cached::backpropErrors( int batchSize, CLWrapper *inputDataWrapper, CLWrapper *errorsWrapper, CLWrapper *weightsWrapper, CLWrapper *errorsForUpstreamWrapper ) { StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached start" ); // const int batchSize, // global const float *errorsGlobal, // global const float *filtersGlobal, // global float *errorsForUpstream, // local float *_errorBoard, // local float *_filterBoard ) { kernel ->in( batchSize ) ->in( errorsWrapper ) ->in( weightsWrapper ) ->out( errorsForUpstreamWrapper ) ->localFloats( square( dim.outputBoardSize ) ) ->localFloats( square( dim.filterSize ) ); int numWorkgroups = batchSize * dim.inputPlanes; int workgroupSize = square( dim.inputBoardSize ); workgroupSize = std::max( 32, workgroupSize ); // no point in wasting cores... int globalSize = numWorkgroups * workgroupSize; // int globalSize = batchSize * dim.inputCubeSize; // int workgroupsize = cl->getMaxWorkgroupSize(); // globalSize = ( ( globalSize + workgroupsize - 1 ) / workgroupsize ) * workgroupsize; // kernel->run_1d(globalSize, workgroupsize); float const*errorsForUpstream = (float *)errorsForUpstreamWrapper->getHostArray(); kernel->run_1d(globalSize, workgroupSize); cl->finish(); errorsForUpstreamWrapper->copyToHost(); StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached after first kernel" ); for( int i = 0; i < min( 40, batchSize * dim.inputCubeSize ); i++ ) { cout << "efu[" << i << "]=" << errorsForUpstream[i] << endl; } // applyActivationDeriv->in( batchSize * dim.inputCubeSize )->in( errorsForUpstreamWrapper )->in( inputDataWrapper ); // applyActivationDeriv->run_1d(globalSize, workgroupSize); applyActivationDeriv->in( batchSize * dim.inputCubeSize )->inout( errorsForUpstreamWrapper )->in( inputDataWrapper ); applyActivationDeriv->run_1d(globalSize, workgroupSize); cl->finish(); StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached after applyActivationDeriv" ); errorsForUpstreamWrapper->copyToHost(); for( int i = 0; i < min( 40, batchSize * dim.inputCubeSize ); i++ ) { cout << "efu2[" << i << "]=" << errorsForUpstream[i] << endl; } StatefulTimer::instance()->timeCheck("BackpropErrorsv2Cached end" ); } BackpropErrorsv2Cached::BackpropErrorsv2Cached( OpenCLHelper *cl, LayerDimensions dim, ActivationFunction const *upstreamFn ) : BackpropErrorsv2( cl, dim, upstreamFn ) { std::string options = dim.buildOptionsString(); options += " -D " + upstreamFn->getDefineName(); // [[[cog // import stringify // stringify.write_kernel2( "kernel", "cl/backproperrorsv2cached.cl", "calcErrorsForUpstreamCached", 'options' ) // # stringify.write_kernel2( "broadcastMultiply", "cl/backproperrorsv2.cl", "broadcast_multiply", 'options' ) // stringify.write_kernel2( "applyActivationDeriv", "cl/applyActivationDeriv.cl", "applyActivationDeriv", 'options' ) // # stringify.write_kernel( "kernelSource", "ClConvolve.cl") // ]]] // generated using cog: const char * kernelSource = "// Copyright Hugh Perkins 2014, 2015 hughperkins at gmail\n" "//\n" "// This Source Code Form is subject to the terms of the Mozilla Public License,\n" "// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n" "// obtain one at http://mozilla.org/MPL/2.0/.\n" "\n" "// as calcErrorsForUpstream, but with local cache\n" "// convolve weights with errors to produce errorsForUpstream\n" "// workgroupid: [n][inputPlane]\n" "// localid: [upstreamrow][upstreamcol]\n" "// per-thread aggregation: [outPlane][filterRow][filterCol]\n" "// need to store locally:\n" "// - _errorBoard. size = outputBoardSizeSquared\n" "// - _filterBoard. size = filtersizesquared\n" "// note: currently doesnt use bias as input. thats probably an error?\n" "// inputs: errors :convolve: filters => errorsForUpstream\n" "//\n" "// global:\n" "// errors: [n][outPlane][outRow][outCol] 128 * 32 * 19 * 19 * 4\n" "// weights: [filterId][upstreamplane][filterRow][filterCol] 32 * 32 * 5 * 5 * 4\n" "// per workgroup:\n" "// errors: [outPlane][outRow][outCol] 32 * 19 * 19 * 4 = 46KB\n" "// weights: [filterId][filterRow][filterCol] 32 * 5 * 5 * 4 = 3.2KB\n" "// errorsforupstream: [n][upstreamPlane][upstreamRow][upstreamCol]\n" "void kernel calcErrorsForUpstreamCached(\n" " const int batchSize,\n" " global const float *errorsGlobal,\n" " global const float *filtersGlobal,\n" " global float *errorsForUpstream,\n" " local float *_errorBoard,\n" " local float *_filterBoard ) {\n" "\n" " const int globalId = get_global_id(0);\n" " const int localId = get_local_id(0);\n" " const int workgroupId = get_group_id(0);\n" " const int workgroupSize = get_local_size(0);\n" "\n" " const int n = workgroupId / gInputPlanes;\n" " const int upstreamPlane = workgroupId % gInputPlanes;\n" "\n" " const int upstreamRow = localId / gInputBoardSize;\n" " const int upstreamCol = localId % gInputBoardSize;\n" "\n" " const int minFilterRow = max( 0, upstreamRow + gMargin - (gOutputBoardSize - 1) );\n" " const int maxFilterRow = min( gFilterSize - 1, upstreamRow + gMargin );\n" " const int minFilterCol = max( 0, upstreamCol + gMargin - (gOutputBoardSize -1) );\n" " const int maxFilterCol = min( gFilterSize - 1, upstreamCol + gMargin );\n" "\n" " const int filterPixelCopiesPerThread = ( gFilterSizeSquared + workgroupSize - 1 ) / workgroupSize;\n" " const int errorPixelCopiesPerThread = ( gOutputBoardSizeSquared + workgroupSize - 1 ) / workgroupSize;\n" " const int pixelCopiesPerThread = max( filterPixelCopiesPerThread, errorPixelCopiesPerThread );\n" "\n" " float sumWeightTimesOutError = 0;\n" " for( int outPlane = 0; outPlane < gNumFilters; outPlane++ ) {\n" " const int filterBoardGlobalOffset =( outPlane * gInputPlanes + upstreamPlane ) * gFilterSizeSquared;\n" " const int errorBoardGlobalOffset = ( n * gNumFilters + outPlane ) * gOutputBoardSizeSquared;\n" " barrier(CLK_LOCAL_MEM_FENCE);\n" " for( int i = 0; i < pixelCopiesPerThread; i++ ) {\n" " int thisOffset = workgroupSize * i + localId;\n" " if( thisOffset < gFilterSizeSquared ) {\n" " _filterBoard[ thisOffset ] = filtersGlobal[ filterBoardGlobalOffset + thisOffset ];\n" " }\n" " if( thisOffset < gOutputBoardSizeSquared ) {\n" " _errorBoard[ thisOffset ] = errorsGlobal[ errorBoardGlobalOffset + thisOffset ];\n" " }\n" " }\n" " barrier(CLK_LOCAL_MEM_FENCE);\n" "// if( globalId == 0 ) {\n" "// for( int i = 0; i < gFilterSizeSquared; i++ ) {\n" "// errorsForUpstream[ (outPlane+1)*100 + i ] = _filterBoard[i];\n" "// }\n" "// }\n" " for( int filterRow = minFilterRow; filterRow <= maxFilterRow; filterRow++ ) {\n" " int outRow = upstreamRow + gMargin - filterRow;\n" " for( int filterCol = minFilterCol; filterCol <= maxFilterCol; filterCol++ ) {\n" " int outCol = upstreamCol + gMargin - filterCol;\n" " int resultIndex = outRow * gOutputBoardSize + outCol;\n" " float thisError = _errorBoard[resultIndex];\n" " int thisWeightIndex = filterRow * gFilterSize + filterCol;\n" " float thisWeight = _filterBoard[thisWeightIndex];\n" " float thisWeightTimesError = thisWeight * thisError;\n" " sumWeightTimesOutError += thisWeightTimesError;\n" " }\n" " }\n" " }\n" " const int upstreamBoardGlobalOffset = ( n * gInputPlanes + upstreamPlane ) * gInputBoardSizeSquared;\n" " if( localId < gInputBoardSizeSquared ) {\n" " errorsForUpstream[upstreamBoardGlobalOffset + localId] = sumWeightTimesOutError;\n" " }\n" "}\n" "\n" ""; kernel = cl->buildKernelFromString( kernelSource, "calcErrorsForUpstreamCached", options, "cl/backproperrorsv2cached.cl" ); // generated using cog: const char * applyActivationDerivSource = "// Copyright Hugh Perkins 201, 2015 hughperkins at gmail\n" "//\n" "// This Source Code Form is subject to the terms of the Mozilla Public License,\n" "// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n" "// obtain one at http://mozilla.org/MPL/2.0/.\n" "\n" "// expected defines:\n" "// one of: [ TANH | RELU | LINEAR | SIGMOID | SCALEDTANH ]\n" "\n" "#ifdef TANH\n" " #define ACTIVATION_DERIV(output) (1 - output * output)\n" "#elif defined SCALEDTANH\n" " #define ACTIVATION_DERIV(output) ( 0.66667f * ( 1.7159f - 1 / 1.7159f * output * output ) )\n" "#elif defined SIGMOID\n" " #define ACTIVATION_DERIV(output) (output * ( 1 - output ) )\n" "#elif defined RELU\n" " #define ACTIVATION_DERIV(output) (output > 0 ? 1 : 0)\n" "#elif defined LINEAR\n" " #define ACTIVATION_DERIV(output) (1.0f)\n" "#endif\n" "\n" "//#ifdef ACTIVATION_DERIV\n" "//void kernel applyActivationDeriv(\n" "// const int N,\n" "// global float *inout ) {\n" "// int globalId = get_global_id(0);\n" "// inout[globalId] = ACTIVATION_DERIV( inout[globalId] );\n" "//}\n" "//#endif\n" "\n" "#ifdef ACTIVATION_DERIV\n" "void kernel applyActivationDeriv(\n" " const int N,\n" " global float *target, global const float *source ) {\n" " int globalId = get_global_id(0);\n" " target[globalId] *= ACTIVATION_DERIV( source[globalId] );\n" " // target[globalId] *= source[globalId];\n" "}\n" "#endif\n" "\n" ""; applyActivationDeriv = cl->buildKernelFromString( applyActivationDerivSource, "applyActivationDeriv", options, "cl/applyActivationDeriv.cl" ); // [[[end]]] // kernel = cl->buildKernel( "backproperrorsv2.cl", "calcErrorsForUpstream", options ); // kernel = cl->buildKernelFromString( kernelSource, "calcErrorsForUpstream", options ); } <|endoftext|>
<commit_before>#include <iostream> #include <mutex> #include <highgui.h> #include <Camera/ClickIndexTaker.h> namespace Camera{ ClickIndexTaker::ClickIndexTaker(const Image& data) : _data(data) { updateCoords(0,0); } void ClickIndexTaker::updateCoords(int row, int column){ cv::namedWindow("Choose two points..", cv::WINDOW_AUTOSIZE); cv::imshow("Choose two points..", _data.rgb); cv::Mat sblargaba=cv::imread("/home/simo/kinectData/rgb.png"); cv::namedWindow("mySister", cv::WINDOW_AUTOSIZE);; cv::imshow("mySister", sblargaba); cv::waitKey(1); std::array<std::mutex, 2> clicks; clicks[0].lock(); clicks[1].lock(); std::array<int, 2> xc, yc; int count=0; /*** WE NEED THIS TO CAST THE FUNCTION TO A POINTER (PASSING CONTEXT) **/ struct parameterToCallback{ std::array<std::mutex, 2>* clicks; std::array<int, 2>* xc; std::array<int, 2>* yc; int *count; }; parameterToCallback theParameter({&clicks, &xc, &yc, &count}); cv::setMouseCallback("Choose two points..", [] (int event, int x, int y, int flags, void* stafava) -> void { parameterToCallback* par=static_cast<parameterToCallback*> (stafava); auto clicks=par->clicks; auto xc=par->xc; auto yc=par->yc; auto count=par->count; if(event==CV_EVENT_LBUTTONDOWN){ std::cout << "Click.\nCount="<<*count <<"\n"; if((*count)<2){ std::cout << "Unlocking mutex #" << *count << "..\n"; (*clicks)[*count].unlock(); (*xc)[*count]=x; (*yc)[*count]=y; (*count)++; } } } , &theParameter); std::cout << "Click for first point..\n"; while(!clicks[0].try_lock()){ cv::waitKey(100); } std::cout << "Click for second point..\n"; while(!clicks[1].try_lock()){ cv::waitKey(100); } std::cout << "Thanks. Points: (" << xc[0] << "," << yc[0] << ") and (" << xc[1] << "," << yc[1] << ")\n"; _x1=xc[0]; _x2=xc[1]; _y1=yc[0]; _y2=yc[1]; cv::destroyWindow("Choose two points.."); } } <commit_msg>Remove debug stuff<commit_after>#include <iostream> #include <mutex> #include <highgui.h> #include <Camera/ClickIndexTaker.h> namespace Camera{ ClickIndexTaker::ClickIndexTaker(const Image& data) : _data(data) { updateCoords(0,0); } void ClickIndexTaker::updateCoords(int row, int column){ cv::namedWindow("Choose two points..", cv::WINDOW_AUTOSIZE); cv::imshow("Choose two points..", _data.rgb); cv::waitKey(1); std::array<std::mutex, 2> clicks; clicks[0].lock(); clicks[1].lock(); std::array<int, 2> xc, yc; int count=0; /*** WE NEED THIS TO CAST THE FUNCTION TO A POINTER (PASSING CONTEXT) **/ struct parameterToCallback{ std::array<std::mutex, 2>* clicks; std::array<int, 2>* xc; std::array<int, 2>* yc; int *count; }; parameterToCallback theParameter({&clicks, &xc, &yc, &count}); cv::setMouseCallback("Choose two points..", [] (int event, int x, int y, int flags, void* stafava) -> void { parameterToCallback* par=static_cast<parameterToCallback*> (stafava); auto clicks=par->clicks; auto xc=par->xc; auto yc=par->yc; auto count=par->count; if(event==CV_EVENT_LBUTTONDOWN){ std::cout << "Click.\nCount="<<*count <<"\n"; if((*count)<2){ std::cout << "Unlocking mutex #" << *count << "..\n"; (*clicks)[*count].unlock(); (*xc)[*count]=x; (*yc)[*count]=y; (*count)++; } } } , &theParameter); std::cout << "Click for first point..\n"; while(!clicks[0].try_lock()){ cv::waitKey(100); } std::cout << "Click for second point..\n"; while(!clicks[1].try_lock()){ cv::waitKey(100); } std::cout << "Thanks. Points: (" << xc[0] << "," << yc[0] << ") and (" << xc[1] << "," << yc[1] << ")\n"; _x1=xc[0]; _x2=xc[1]; _y1=yc[0]; _y2=yc[1]; cv::destroyWindow("Choose two points.."); } } <|endoftext|>
<commit_before>namespace mant { namespace bbob { class EllipsoidalFunctionRotated : public BlackBoxOptimisationBenchmark { public: inline explicit EllipsoidalFunctionRotated( const unsigned int numberOfDimensions) noexcept; inline std::string toString() const noexcept override; protected: const arma::Col<double> parameterConditoning_; inline double getObjectiveValueImplementation( const arma::Col<double>& parameter) const noexcept override; #if defined(MANTELLA_USE_PARALLEL) friend class cereal::access; template <typename Archive> void serialize( Archive& archive) noexcept { archive(cereal::make_nvp("BlackBoxOptimisationBenchmark", cereal::base_class<BlackBoxOptimisationBenchmark>(this))); archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions_)); } template <typename Archive> static void load_and_construct( Archive& archive, cereal::construct<EllipsoidalFunctionRotated>& construct) noexcept { unsigned int numberOfDimensions; archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions)); construct(numberOfDimensions); archive(cereal::make_nvp("BlackBoxOptimisationBenchmark", cereal::base_class<BlackBoxOptimisationBenchmark>(construct.ptr()))); } #endif }; // // Implementation // inline EllipsoidalFunctionRotated::EllipsoidalFunctionRotated( const unsigned int numberOfDimensions) noexcept : BlackBoxOptimisationBenchmark(numberOfDimensions), parameterConditoning_(getParameterConditioning(1000000.0)) { setParameterTranslation(getRandomParameterTranslation()); setParameterRotation(getRandomRotationMatrix(numberOfDimensions_)); } inline double EllipsoidalFunctionRotated::getObjectiveValueImplementation( const arma::Col<double>& parameter) const noexcept { return arma::dot(parameterConditoning_, arma::square(getOscillatedParameter(parameter))); } inline std::string EllipsoidalFunctionRotated::toString() const noexcept { return "bbob_ellipsoidal_function_rotated"; } } } #if defined(MANTELLA_USE_PARALLEL) CEREAL_REGISTER_TYPE(mant::bbob::EllipsoidalFunctionRotated); #endif <commit_msg>Fixed minor spelling error (internal field name)<commit_after>namespace mant { namespace bbob { class EllipsoidalFunctionRotated : public BlackBoxOptimisationBenchmark { public: inline explicit EllipsoidalFunctionRotated( const unsigned int numberOfDimensions) noexcept; inline std::string toString() const noexcept override; protected: const arma::Col<double> parameterConditioning_; inline double getObjectiveValueImplementation( const arma::Col<double>& parameter) const noexcept override; #if defined(MANTELLA_USE_PARALLEL) friend class cereal::access; template <typename Archive> void serialize( Archive& archive) noexcept { archive(cereal::make_nvp("BlackBoxOptimisationBenchmark", cereal::base_class<BlackBoxOptimisationBenchmark>(this))); archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions_)); } template <typename Archive> static void load_and_construct( Archive& archive, cereal::construct<EllipsoidalFunctionRotated>& construct) noexcept { unsigned int numberOfDimensions; archive(cereal::make_nvp("numberOfDimensions", numberOfDimensions)); construct(numberOfDimensions); archive(cereal::make_nvp("BlackBoxOptimisationBenchmark", cereal::base_class<BlackBoxOptimisationBenchmark>(construct.ptr()))); } #endif }; // // Implementation // inline EllipsoidalFunctionRotated::EllipsoidalFunctionRotated( const unsigned int numberOfDimensions) noexcept : BlackBoxOptimisationBenchmark(numberOfDimensions), parameterConditioning_(getParameterConditioning(1000000.0)) { setParameterTranslation(getRandomParameterTranslation()); setParameterRotation(getRandomRotationMatrix(numberOfDimensions_)); } inline double EllipsoidalFunctionRotated::getObjectiveValueImplementation( const arma::Col<double>& parameter) const noexcept { return arma::dot(parameterConditioning_, arma::square(getOscillatedParameter(parameter))); } inline std::string EllipsoidalFunctionRotated::toString() const noexcept { return "bbob_ellipsoidal_function_rotated"; } } } #if defined(MANTELLA_USE_PARALLEL) CEREAL_REGISTER_TYPE(mant::bbob::EllipsoidalFunctionRotated); #endif <|endoftext|>
<commit_before>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <visionaray/math/math.h> #include <gtest/gtest.h> using namespace visionaray; TEST(Vector, Ctor) { // Test constructability from vectors with different // sizes to define a higher-dimensional vector vector<3, float> v3(1.0f, 2.0f, 3.0f); vector<2, float> v2(4.0f, 5.0f); vector<5, float> v5(v3, v2); EXPECT_FLOAT_EQ(v5[0], 1.0f); EXPECT_FLOAT_EQ(v5[1], 2.0f); EXPECT_FLOAT_EQ(v5[2], 3.0f); EXPECT_FLOAT_EQ(v5[3], 4.0f); EXPECT_FLOAT_EQ(v5[4], 5.0f); // Test vec4 specialization of this ctor vector<4, float> v4(v2, vector<2, float>(6.0f, 7.0f)); EXPECT_FLOAT_EQ(v4[0], 4.0f); EXPECT_FLOAT_EQ(v4[1], 5.0f); EXPECT_FLOAT_EQ(v4[2], 6.0f); EXPECT_FLOAT_EQ(v4[3], 7.0f); } TEST(Vector, MinMaxElement) { // FPU vector<3, float> vf(1.0f, 2.0f, 3.0f); auto minef = min_element(vf); auto maxef = max_element(vf); EXPECT_FLOAT_EQ(minef, 1.0f); EXPECT_FLOAT_EQ(maxef, 3.0f); // SSE vector<3, simd::float4> v4(1.0f, 2.0f, 3.0f); auto mine4 = min_element(v4); auto maxe4 = max_element(v4); EXPECT_TRUE( all(mine4 == simd::float4(1.0f)) ); EXPECT_TRUE( all(maxe4 == simd::float4(3.0f)) ); #if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX // AVX vector<3, simd::float8> v8(1.0f, 2.0f, 3.0f); auto mine8 = min_element(v8); auto maxe8 = max_element(v8); EXPECT_TRUE( all(mine8 == simd::float8(1.0f)) ); EXPECT_TRUE( all(maxe8 == simd::float8(3.0f)) ); #endif // VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX } <commit_msg>More unit tests for math vectors<commit_after>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <visionaray/math/math.h> #include <gtest/gtest.h> using namespace visionaray; TEST(Vector, Ctor) { // Test constructability from vectors with different // sizes to define a higher-dimensional vector vector<3, float> v3(1.0f, 2.0f, 3.0f); vector<2, float> v2(4.0f, 5.0f); vector<5, float> v5(v3, v2); EXPECT_FLOAT_EQ(v5[0], 1.0f); EXPECT_FLOAT_EQ(v5[1], 2.0f); EXPECT_FLOAT_EQ(v5[2], 3.0f); EXPECT_FLOAT_EQ(v5[3], 4.0f); EXPECT_FLOAT_EQ(v5[4], 5.0f); // Test vec4 specialization of this ctor vector<4, float> v4(v2, vector<2, float>(6.0f, 7.0f)); EXPECT_FLOAT_EQ(v4[0], 4.0f); EXPECT_FLOAT_EQ(v4[1], 5.0f); EXPECT_FLOAT_EQ(v4[2], 6.0f); EXPECT_FLOAT_EQ(v4[3], 7.0f); } TEST(Vector, Dot) { // Test dot product for different vector sizes // (implementation may in general depend on size) vector<2, float> v2_1(1.0f, 2.0f); vector<2, float> v2_2(2.0f, 1.0f); EXPECT_FLOAT_EQ(dot(v2_1, v2_2), 4.0f); vector<3, float> v3_1(1.0f, 2.0f, 3.0f); vector<3, float> v3_2(3.0f, 2.0f, 1.0f); EXPECT_FLOAT_EQ(dot(v3_1, v3_2), 10.0f); vector<4, float> v4_1(1.0f, 2.0f, 3.0f, 4.0f); vector<4, float> v4_2(4.0f, 3.0f, 2.0f, 1.0f); EXPECT_FLOAT_EQ(dot(v4_1, v4_2), 20.0f); float f5_1[5] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f }; float f5_2[5] = { 5.0f, 4.0f, 3.0f, 2.0f, 1.0f }; vector<5, float> v5_1(f5_1); vector<5, float> v5_2(f5_2); EXPECT_FLOAT_EQ(dot(v5_1, v5_2), 35.0f); float f6_1[6] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f }; float f6_2[6] = { 6.0f, 5.0f, 4.0f, 3.0f, 2.0f, 1.0f }; vector<6, float> v6_1(f6_1); vector<6, float> v6_2(f6_2); EXPECT_FLOAT_EQ(dot(v6_1, v6_2), 56.0f); } TEST(Vector, MinMaxElement) { // FPU vector<3, float> vf(1.0f, 2.0f, 3.0f); auto minef = min_element(vf); auto maxef = max_element(vf); EXPECT_FLOAT_EQ(minef, 1.0f); EXPECT_FLOAT_EQ(maxef, 3.0f); // SSE vector<3, simd::float4> v4(1.0f, 2.0f, 3.0f); auto mine4 = min_element(v4); auto maxe4 = max_element(v4); EXPECT_TRUE( all(mine4 == simd::float4(1.0f)) ); EXPECT_TRUE( all(maxe4 == simd::float4(3.0f)) ); #if VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX // AVX vector<3, simd::float8> v8(1.0f, 2.0f, 3.0f); auto mine8 = min_element(v8); auto maxe8 = max_element(v8); EXPECT_TRUE( all(mine8 == simd::float8(1.0f)) ); EXPECT_TRUE( all(maxe8 == simd::float8(3.0f)) ); #endif // VSNRAY_SIMD_ISA >= VSNRAY_SIMD_ISA_AVX } <|endoftext|>
<commit_before>// CompMap.cpp #include "CompMap.h" #include "MassTable.h" #include "CycArithmetic.h" #include "CycException.h" #include "CycLimits.h" #include <sstream> #include <cmath> // std::abs using namespace std; LogLevel CompMap::log_level_ = LEV_INFO3; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CompMap::CompMap(Basis b) { init(b); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CompMap::CompMap(const CompMap& other) { init(other.basis()); map_ = other.map(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CompMap::~CompMap() { } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CompMap::iterator CompMap::begin() { return map_.begin(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CompMap::iterator CompMap::end() { return map_.end(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double& CompMap::operator[](const int& tope) { normalized_ = false; return map_.operator[](tope); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int CompMap::count(Iso tope) const { return map_.count(tope); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::erase(Iso tope) { normalized_ = false; map_.erase(tope); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::erase(CompMap::iterator position) { normalized_ = false; map_.erase(position); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool CompMap::empty() const { return map_.empty(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int CompMap::size() const { return map_.size(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool CompMap::operator==(const CompMap& rhs) const { return almostEqual(rhs, 0); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool CompMap::operator<(const CompMap& rhs) const { return (ID_ < rhs.ID()); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool CompMap::almostEqual(const CompMap& rhs, double threshold) const{ // I learned at // http://www.ualberta.ca/~kbeach/comp_phys/fp_err.html#testing-for-equality // that the following is less naive than the intuitive way of doing this... // almost equal if : // (abs(x-y) < abs(x)*eps) && (abs(x-y) < abs(y)*epsilon) if ( threshold < 0 ) { stringstream ss; ss << "The threshold cannot be negative. The value provided was " << threshold << " ."; throw CycNegativeValueException(ss.str()); } if ( size() != rhs.size() ) { return false; } for (const_iterator it = map_.begin(); it != map_.end(); it++) { if (rhs.count(it->first) == 0) { return false; } double minuend = rhs.massFraction(it->first); double subtrahend = massFraction(it->first); double diff = minuend - subtrahend; if (abs(minuend) == 0 || abs(subtrahend) == 0){ if (abs(diff) > abs(diff)*threshold){ return false; } } else if (abs(diff) > abs(minuend)*threshold || abs(diff) > abs(subtrahend)*threshold) { return false; } } return true; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool CompMap::recorded() const { return (ID_ > 0); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Basis CompMap::basis() const { return basis_; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Map CompMap::map() const { return map_; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int CompMap::ID() const { return ID_; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double CompMap::massFraction(const Iso& tope) const { if (count(tope) == 0 || mass_to_atom_ratio_ == 0) { return 0.0; } double factor = 1.0; if (basis_ != MASS) { factor = MT->gramsPerMol(tope) / mass_to_atom_ratio_; } return factor * map_.find(tope)->second; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double CompMap::atomFraction(const Iso& tope) const { if (count(tope) == 0 || mass_to_atom_ratio_ == 0) { return 0.0; } double factor = 1.0; if (basis_ != ATOM) { factor = 1 / (MT->gramsPerMol(tope) / mass_to_atom_ratio_); } return factor * map_.find(tope)->second; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CompMapPtr CompMap::parent() const { return parent_; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int CompMap::decay_time() const { return decay_time_; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool CompMap::normalized() const { return normalized_; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double CompMap::mass_to_atom_ratio() const { return mass_to_atom_ratio_; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CompMapPtr CompMap::me() { return shared_from_this(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CompMapPtr CompMap::root_comp() { CompMapPtr child = me(); while (child->parent()) { child = child->parent(); } return child; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int CompMap::root_decay_time() { CompMapPtr child = me(); int time = decay_time(); while (child->parent()) { child = child->parent(); time += child->decay_time(); } return time; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::massify() { change_basis(MASS); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::atomify() { change_basis(ATOM); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::normalize() { double sum; double other_sum; vector<double> vec; vector<double> other_vec; bool atom = (basis_ == ATOM); for (iterator it = map_.begin(); it != map_.end(); ++it) { validateEntry(it->first,it->second); vec.push_back(it->second); if (atom) { other_vec.push_back(it->second * MT->gramsPerMol(it->first)); } else { other_vec.push_back(it->second / MT->gramsPerMol(it->first)); } } sum = CycArithmetic::KahanSum(vec); other_sum = CycArithmetic::KahanSum(other_vec); if (sum == 0) { mass_to_atom_ratio_ = 0; } else if (atom){ mass_to_atom_ratio_ = other_sum / sum; } else { mass_to_atom_ratio_ = sum / other_sum; } normalize(sum); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::init(Basis b) { basis_ = b; map_ = Map(); normalized_ = false; mass_to_atom_ratio_ = 1; ID_ = 0; decay_time_ = 0; parent_.reset(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::change_basis(Basis b) { if (!normalized()) { normalize(); } if (basis_ != b) { // only change if we have to for (iterator it = map_.begin(); it != map_.end(); it++) { switch (b) { case ATOM: map_[it->first] = atomFraction(it->first); break; case MASS: map_[it->first] = massFraction(it->first); break; default: throw CycRangeException("Basis not atom or mass."); break; } } basis_ = b; } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::normalize(double sum) { if (sum != 1 && sum != 0) { // only normalize if needed for (iterator it = map_.begin(); it != map_.end(); it++) { it->second /= sum; } } normalized_ = true; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int CompMap::getAtomicNum(Iso tope) { validateIsotopeNumber(tope); return tope / 1000; // integer division; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int CompMap::getMassNum(Iso tope) { validateIsotopeNumber(tope); return tope % 1000; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::validate() { for (Map::iterator it = map_.begin(); it != map_.end(); it ++) { validateEntry(it->first,it->second); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::validateEntry(const Iso& tope, const double& value) { validateIsotopeNumber(tope); validateValue(value); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::validateIsotopeNumber(const Iso& tope) { int lower_limit = 1001; int upper_limit = 1182949; if (tope < lower_limit || tope > upper_limit) { stringstream ss(""); ss << tope; throw CycRangeException("Isotope identifier '" + ss.str() + "' is not valid."); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::validateValue(const double& value) { if (value < 0.0) { string err_msg = "CompMap has negative quantity for an isotope."; throw CycRangeException(err_msg); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::print() { CLOG(log_level_) << detail(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - std::string CompMap::detail() { stringstream ss; vector<string> entries = compStrings(); for (vector<string>::iterator entry = entries.begin(); entry != entries.end(); entry++) { CLOG(log_level_) << *entry; } return ""; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - std::vector<std::string> CompMap::compStrings() { stringstream ss; vector<string> comp_strings; for (const_iterator entry = map_.begin(); entry != map_.end(); entry++) { ss.str(""); ss << entry->first << ": " << entry->second << " % / kg"; comp_strings.push_back(ss.str()); } return comp_strings; } <commit_msg>prefer prepended iterator<commit_after>// CompMap.cpp #include "CompMap.h" #include "MassTable.h" #include "CycArithmetic.h" #include "CycException.h" #include "CycLimits.h" #include <sstream> #include <cmath> // std::abs using namespace std; LogLevel CompMap::log_level_ = LEV_INFO3; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CompMap::CompMap(Basis b) { init(b); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CompMap::CompMap(const CompMap& other) { init(other.basis()); map_ = other.map(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CompMap::~CompMap() { } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CompMap::iterator CompMap::begin() { return map_.begin(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CompMap::iterator CompMap::end() { return map_.end(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double& CompMap::operator[](const int& tope) { normalized_ = false; return map_.operator[](tope); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int CompMap::count(Iso tope) const { return map_.count(tope); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::erase(Iso tope) { normalized_ = false; map_.erase(tope); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::erase(CompMap::iterator position) { normalized_ = false; map_.erase(position); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool CompMap::empty() const { return map_.empty(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int CompMap::size() const { return map_.size(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool CompMap::operator==(const CompMap& rhs) const { return almostEqual(rhs, 0); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool CompMap::operator<(const CompMap& rhs) const { return (ID_ < rhs.ID()); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool CompMap::almostEqual(const CompMap& rhs, double threshold) const{ // I learned at // http://www.ualberta.ca/~kbeach/comp_phys/fp_err.html#testing-for-equality // that the following is less naive than the intuitive way of doing this... // almost equal if : // (abs(x-y) < abs(x)*eps) && (abs(x-y) < abs(y)*epsilon) if ( threshold < 0 ) { stringstream ss; ss << "The threshold cannot be negative. The value provided was " << threshold << " ."; throw CycNegativeValueException(ss.str()); } if ( size() != rhs.size() ) { return false; } for (const_iterator it = map_.begin(); it != map_.end(); it++) { if (rhs.count(it->first) == 0) { return false; } double minuend = rhs.massFraction(it->first); double subtrahend = massFraction(it->first); double diff = minuend - subtrahend; if (abs(minuend) == 0 || abs(subtrahend) == 0){ if (abs(diff) > abs(diff)*threshold){ return false; } } else if (abs(diff) > abs(minuend)*threshold || abs(diff) > abs(subtrahend)*threshold) { return false; } } return true; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool CompMap::recorded() const { return (ID_ > 0); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Basis CompMap::basis() const { return basis_; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Map CompMap::map() const { return map_; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int CompMap::ID() const { return ID_; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double CompMap::massFraction(const Iso& tope) const { if (count(tope) == 0 || mass_to_atom_ratio_ == 0) { return 0.0; } double factor = 1.0; if (basis_ != MASS) { factor = MT->gramsPerMol(tope) / mass_to_atom_ratio_; } return factor * map_.find(tope)->second; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double CompMap::atomFraction(const Iso& tope) const { if (count(tope) == 0 || mass_to_atom_ratio_ == 0) { return 0.0; } double factor = 1.0; if (basis_ != ATOM) { factor = 1 / (MT->gramsPerMol(tope) / mass_to_atom_ratio_); } return factor * map_.find(tope)->second; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CompMapPtr CompMap::parent() const { return parent_; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int CompMap::decay_time() const { return decay_time_; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool CompMap::normalized() const { return normalized_; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double CompMap::mass_to_atom_ratio() const { return mass_to_atom_ratio_; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CompMapPtr CompMap::me() { return shared_from_this(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CompMapPtr CompMap::root_comp() { CompMapPtr child = me(); while (child->parent()) { child = child->parent(); } return child; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int CompMap::root_decay_time() { CompMapPtr child = me(); int time = decay_time(); while (child->parent()) { child = child->parent(); time += child->decay_time(); } return time; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::massify() { change_basis(MASS); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::atomify() { change_basis(ATOM); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::normalize() { double sum; double other_sum; vector<double> vec; vector<double> other_vec; bool atom = (basis_ == ATOM); for (iterator it = map_.begin(); it != map_.end(); ++it) { validateEntry(it->first,it->second); vec.push_back(it->second); if (atom) { other_vec.push_back(it->second * MT->gramsPerMol(it->first)); } else { other_vec.push_back(it->second / MT->gramsPerMol(it->first)); } } sum = CycArithmetic::KahanSum(vec); other_sum = CycArithmetic::KahanSum(other_vec); if (sum == 0) { mass_to_atom_ratio_ = 0; } else if (atom){ mass_to_atom_ratio_ = other_sum / sum; } else { mass_to_atom_ratio_ = sum / other_sum; } normalize(sum); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::init(Basis b) { basis_ = b; map_ = Map(); normalized_ = false; mass_to_atom_ratio_ = 1; ID_ = 0; decay_time_ = 0; parent_.reset(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::change_basis(Basis b) { if (!normalized()) { normalize(); } if (basis_ != b) { // only change if we have to for (iterator it = map_.begin(); it != map_.end(); ++it) { switch (b) { case ATOM: map_[it->first] = atomFraction(it->first); break; case MASS: map_[it->first] = massFraction(it->first); break; default: throw CycRangeException("Basis not atom or mass."); break; } } basis_ = b; } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::normalize(double sum) { if (sum != 1 && sum != 0) { // only normalize if needed for (iterator it = map_.begin(); it != map_.end(); it++) { it->second /= sum; } } normalized_ = true; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int CompMap::getAtomicNum(Iso tope) { validateIsotopeNumber(tope); return tope / 1000; // integer division; }; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int CompMap::getMassNum(Iso tope) { validateIsotopeNumber(tope); return tope % 1000; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::validate() { for (Map::iterator it = map_.begin(); it != map_.end(); it ++) { validateEntry(it->first,it->second); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::validateEntry(const Iso& tope, const double& value) { validateIsotopeNumber(tope); validateValue(value); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::validateIsotopeNumber(const Iso& tope) { int lower_limit = 1001; int upper_limit = 1182949; if (tope < lower_limit || tope > upper_limit) { stringstream ss(""); ss << tope; throw CycRangeException("Isotope identifier '" + ss.str() + "' is not valid."); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::validateValue(const double& value) { if (value < 0.0) { string err_msg = "CompMap has negative quantity for an isotope."; throw CycRangeException(err_msg); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CompMap::print() { CLOG(log_level_) << detail(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - std::string CompMap::detail() { stringstream ss; vector<string> entries = compStrings(); for (vector<string>::iterator entry = entries.begin(); entry != entries.end(); entry++) { CLOG(log_level_) << *entry; } return ""; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - std::vector<std::string> CompMap::compStrings() { stringstream ss; vector<string> comp_strings; for (const_iterator entry = map_.begin(); entry != map_.end(); entry++) { ss.str(""); ss << entry->first << ": " << entry->second << " % / kg"; comp_strings.push_back(ss.str()); } return comp_strings; } <|endoftext|>
<commit_before> #include <qcheckbox.h> #include <qdir.h> #include <qlineedit.h> #include <kaboutdata.h> #include <kapplication.h> #include <kconfig.h> #include <kdebug.h> #include <kiconloader.h> #include <kglobal.h> #include <kstandarddirs.h> #include <ksimpleconfig.h> #include <kurlrequester.h> #include <kabc/stdaddressbook.h> #include <kabc/resourcefile.h> #include <kparts/genericfactory.h> #include <ksync_mainwindow.h> #include <addressbooksyncee.h> #include "addressbookbase.h" #include "ksync_addressbookpart.h" typedef KParts::GenericFactory< KSync::AddressBookPart> AddressBookPartFactory; K_EXPORT_COMPONENT_FACTORY( libaddressbookpart, AddressBookPartFactory ); using namespace KSync; AddressBookPart::AddressBookPart( QWidget* parent, const char* name, QObject* obj, const char* , const QStringList & ) : ManipulatorPart( parent ? parent : obj , name ) { setInstance( AddressBookPartFactory::instance() ); m_pixmap = KGlobal::iconLoader()->loadIcon("kaddressbook", KIcon::Desktop, 48 ); } AddressBookPart::~AddressBookPart(){ } KAboutData *AddressBookPart::createAboutData(){ return new KAboutData("KSyncAddressBookPart", I18N_NOOP("Sync AddressBook Part"), "0.0" ); } QPixmap* AddressBookPart::pixmap(){ return &m_pixmap; } QString AddressBookPart::type()const { return QString::fromLatin1("Addressbook"); } QString AddressBookPart::name()const{ return i18n("Addressbook"); } QString AddressBookPart::iconName()const { return QString::fromLatin1("kaddressbook"); } QString AddressBookPart::description()const { return i18n("The Addressbook Part"); } bool AddressBookPart::configIsVisible()const { return false; } bool AddressBookPart::canSync()const{ return true; } /* * SYnc it aye? * 1. get the currentProfile + Konnector * 2. get the paths + the path to the meta data * 3. search our AddressBookSyncee * 4. load the File * 5. do meta * 6. sync * 7. write Meta * 8. save * 9. write back * 10. party */ void AddressBookPart::sync( const Syncee::PtrList& in, Syncee::PtrList& out ){ kdDebug(5228) << "processEntry in AddressBookPart aye" << endl; /* 1. */ Profile prof = core()->currentProfile(); KonnectorProfile kon = core()->konnectorProfile(); /* 2. */ QString meta = kon.uid() + "/" + prof.uid() + "addressbook.rc"; bool met = kon.kapabilities().isMetaSyncingEnabled(); kdDebug(5228) << "Is meta syncing enabled? " << met << endl; /* 3. */ Syncee* syncee = 0l; AddressBookSyncee* aBook=0l; QPtrListIterator<Syncee> syncIt( in ); for ( ; syncIt.current(); ++syncIt ) { syncee = syncIt.current(); if (syncee->type() == QString::fromLatin1("AddressBookSyncee") ) { kdDebug(5228) << "Found our syncee" << endl; aBook = (AddressBookSyncee*) syncee; break; } } if (!aBook) {done(); return;} progress( Progress(i18n("Going to load AddressBook") ) ); /* 4. */ AddressBookSyncee* ourbook; ourbook = load(); if (!ourbook) { error( Error(i18n("Could not load the AddressBook") ) ); done(); } /* 5. */ if (met) doMeta( ourbook, meta ); progress( Progress(i18n("Going to sync AddressBook") ) ); /* 6. */ Syncer sync( core()->syncUi(), core()->syncAlgorithm() ); sync.addSyncee( aBook ); sync.addSyncee( ourbook ); sync.sync(); /* 7. KABC seems broken so we do meta from save*/ /* if (met) writeMeta( ourbook, meta ); */ progress( Progress(i18n("Going to save AddressBook") ) ); /* 8. */ save( ourbook, met ? meta : QString::null ); /* writeback */ out.append( ourbook ); done(); } void AddressBookPart::slotConfigOk(){ } /* * let's load it * if path is empty or default Take KStdAddressBook * otherwise load the file */ AddressBookSyncee* AddressBookPart::load() { KABC::AddressBook* book; AddressBookSyncee* sync; kdDebug(5228) << "use default one " << endl; book = KABC::StdAddressBook::self(); if (!book->load() ) return 0l; sync = book2syncee( book ); return sync; } void AddressBookPart::doMeta( Syncee* syncee, const QString& path ) { kdDebug(5228) << "Do Meta" << endl; QString str = QDir::homeDirPath(); str += "/.kitchensync/meta/konnector-" + path; if (!QFile::exists( str ) ) { kdDebug(5228) << "Path does not exist ->First Sync" << endl; kdDebug(5228) << "Path was " << str << " " << path << endl; syncee->setFirstSync( true ); syncee->setSyncMode( Syncee::MetaMode ); return; } syncee->setSyncMode( Syncee::MetaMode ); KSimpleConfig conf( str ); SyncEntry* entry; QString timestmp; QStringList ids; /* mod + added */ for (entry= syncee->firstEntry(); entry; entry = syncee->nextEntry() ) { ids << entry->id(); kdDebug(5228) << "Entry " << entry->name() << endl << "Entry id" << entry->id() << endl; if ( conf.hasGroup( entry->id() ) ) { conf.setGroup( entry->id() ); timestmp = conf.readEntry("time"); kdDebug(5228) << "Timestamp Old" << timestmp << endl; kdDebug(5228) << "Timestamp New" << entry->timestamp() << endl; if ( timestmp != entry->timestamp() ) entry->setState( SyncEntry::Modified ); } /* added */ else { kdDebug(5228) << "Entry added" << endl; entry->setState( SyncEntry::Added ); } } /* find removed item... through reversed mapping */ QStringList groups = conf.groupList(); QStringList::Iterator it; for (it = groups.begin(); it != groups.end(); ++it ) { // removed items if ids is not present if (!ids.contains( (*it) ) ) { kdDebug(5228) << "Entry removed from abook" << (*it) << endl; KABC::Addressee adr; adr.setUid( (*it) ); AddressBookSyncEntry* entry; entry = new AddressBookSyncEntry( adr ); entry->setState( SyncEntry::Removed ); syncee->addEntry( entry ); } } } void AddressBookPart::writeMeta( KABC::AddressBook* book, const QString& path ) { /* no meta info to save */ if (path.isEmpty() ) return; kdDebug(5228) << "WriteMeta AddressBookPart " << endl; QString str = QDir::homeDirPath(); str += "/.kitchensync/meta/konnector-" + path; if (!QFile::exists( str ) ) { kdDebug(5228) << "Path does not exist " << endl; kdDebug(5228) << "Path = " << str << endl; KonnectorProfile kon = core()->konnectorProfile(); QDir dir; dir.mkdir( dir.homeDirPath() + "/.kitchensync"); dir.mkdir( dir.homeDirPath() + "/.kitchensync/meta"); dir.mkdir( dir.homeDirPath() + "/.kitchensync/meta/konnector-" + kon.uid() ); kdDebug(5228) << "Kon UID " << kon.uid() << endl; } KSimpleConfig conf( str ); QStringList grpList = conf.groupList(); QStringList::Iterator it; for ( it = grpList.begin(); it != grpList.end(); ++it ) { conf.deleteGroup( (*it) ); } KABC::AddressBook::Iterator aIt; for ( aIt = book->begin(); aIt != book->end(); ++aIt ) { kdDebug(5228) << "Name " << (*aIt).realName() << endl; kdDebug(5228) << "UID " << (*aIt).uid() << endl; kdDebug(5228) << "Timestamp " << (*aIt).revision().toString() << endl; conf.setGroup( (*aIt).uid() ); conf.writeEntry( "time", (*aIt).revision().toString() ); } } void AddressBookPart::save( AddressBookSyncee* sync, const QString& meta) { AddressBookSyncEntry* entry; KABC::AddressBook* book; // save to the std. addressbook book = KABC::StdAddressBook::self(); /* clear the old book first */ book->clear(); for ( entry = (AddressBookSyncEntry*)sync->firstEntry(); entry; entry= (AddressBookSyncEntry*) sync->nextEntry() ) { if( entry->state() != SyncEntry::Removed ) { KABC::Addressee adr = entry->addressee(); adr.setResource( resource(entry->resource() ) ); book->insertAddressee( adr ); } } KABC::StdAddressBook::save(); kdDebug(5228) << "dumped abook " << endl; writeMeta( book, meta ); KABC::StdAddressBook::close(); } /*bool AddressBookPart::pathIsDefault( const QString& path ) { if ( path.isEmpty() ) return true; if ( path.stripWhiteSpace() == QString::fromLatin1("default") ) return true; kdDebug(5228) << "Path is not default" << endl; return false; }*/ AddressBookSyncee* AddressBookPart::book2syncee( KABC::AddressBook* book) { AddressBookSyncee* syncee = new AddressBookSyncee(); AddressBookSyncEntry* entry=0l; KABC::AddressBook::Iterator it = book->begin(); for ( ; it != book->end(); ++it ) { entry = new AddressBookSyncEntry( (*it) ); QString res = (*it).resource() ? (*it).resource()->type() : QString::null; entry->setResource( res ); syncee->addEntry( entry ); } return syncee; } /*void AddressBookPart::saveAll( KABC::AddressBook* ab) { KABC::Resource *res = 0l; QPtrList<KABC::Resource> list = ab->resources(); for (uint i = 0; i < list.count(); ++i ) { res = list.at( i ); if (!res->readOnly() ) { KABC::Ticket* ticket = ab->requestSaveTicket( res ); if (ticket) ab->save( ticket ); } } }*/ KABC::Resource* AddressBookPart::resource( const QString& type ) { QPtrListIterator<KABC::Resource> it(KABC::StdAddressBook::self()->resources() ); KABC::Resource* res = 0l; while ( (res = it.current()) ) { ++it; if ( res->type() == type ) return res; } return 0; } #include "ksync_addressbookpart.moc" <commit_msg>If the KABC::StdAddressBook::self() fails to open not only emit an error but return. This crash was found and debugged by Mathieu Chouniard. Thank you<commit_after> #include <qcheckbox.h> #include <qdir.h> #include <qlineedit.h> #include <kaboutdata.h> #include <kapplication.h> #include <kconfig.h> #include <kdebug.h> #include <kiconloader.h> #include <kglobal.h> #include <kstandarddirs.h> #include <ksimpleconfig.h> #include <kurlrequester.h> #include <kabc/stdaddressbook.h> #include <kabc/resourcefile.h> #include <kparts/genericfactory.h> #include <ksync_mainwindow.h> #include <addressbooksyncee.h> #include "addressbookbase.h" #include "ksync_addressbookpart.h" typedef KParts::GenericFactory< KSync::AddressBookPart> AddressBookPartFactory; K_EXPORT_COMPONENT_FACTORY( libaddressbookpart, AddressBookPartFactory ); using namespace KSync; AddressBookPart::AddressBookPart( QWidget* parent, const char* name, QObject* obj, const char* , const QStringList & ) : ManipulatorPart( parent ? parent : obj , name ) { setInstance( AddressBookPartFactory::instance() ); m_pixmap = KGlobal::iconLoader()->loadIcon("kaddressbook", KIcon::Desktop, 48 ); } AddressBookPart::~AddressBookPart(){ } KAboutData *AddressBookPart::createAboutData(){ return new KAboutData("KSyncAddressBookPart", I18N_NOOP("Sync AddressBook Part"), "0.0" ); } QPixmap* AddressBookPart::pixmap(){ return &m_pixmap; } QString AddressBookPart::type()const { return QString::fromLatin1("Addressbook"); } QString AddressBookPart::name()const{ return i18n("Addressbook"); } QString AddressBookPart::iconName()const { return QString::fromLatin1("kaddressbook"); } QString AddressBookPart::description()const { return i18n("The Addressbook Part"); } bool AddressBookPart::configIsVisible()const { return false; } bool AddressBookPart::canSync()const{ return true; } /* * SYnc it aye? * 1. get the currentProfile + Konnector * 2. get the paths + the path to the meta data * 3. search our AddressBookSyncee * 4. load the File * 5. do meta * 6. sync * 7. write Meta * 8. save * 9. write back * 10. party */ void AddressBookPart::sync( const Syncee::PtrList& in, Syncee::PtrList& out ){ kdDebug(5228) << "processEntry in AddressBookPart aye" << endl; /* 1. */ Profile prof = core()->currentProfile(); KonnectorProfile kon = core()->konnectorProfile(); /* 2. */ QString meta = kon.uid() + "/" + prof.uid() + "addressbook.rc"; bool met = kon.kapabilities().isMetaSyncingEnabled(); kdDebug(5228) << "Is meta syncing enabled? " << met << endl; /* 3. */ Syncee* syncee = 0l; AddressBookSyncee* aBook=0l; QPtrListIterator<Syncee> syncIt( in ); for ( ; syncIt.current(); ++syncIt ) { syncee = syncIt.current(); if (syncee->type() == QString::fromLatin1("AddressBookSyncee") ) { kdDebug(5228) << "Found our syncee" << endl; aBook = (AddressBookSyncee*) syncee; break; } } if (!aBook) {done(); return;} progress( Progress(i18n("Going to load AddressBook") ) ); /* 4. */ AddressBookSyncee* ourbook; ourbook = load(); if (!ourbook) { error( Error(i18n("Could not load the AddressBook") ) ); done(); return; } /* 5. */ if (met) doMeta( ourbook, meta ); progress( Progress(i18n("Going to sync AddressBook") ) ); /* 6. */ Syncer sync( core()->syncUi(), core()->syncAlgorithm() ); sync.addSyncee( aBook ); sync.addSyncee( ourbook ); sync.sync(); /* 7. KABC seems broken so we do meta from save*/ /* if (met) writeMeta( ourbook, meta ); */ progress( Progress(i18n("Going to save AddressBook") ) ); /* 8. */ save( ourbook, met ? meta : QString::null ); /* writeback */ out.append( ourbook ); done(); } void AddressBookPart::slotConfigOk(){ } /* * let's load it * if path is empty or default Take KStdAddressBook * otherwise load the file */ AddressBookSyncee* AddressBookPart::load() { KABC::AddressBook* book; AddressBookSyncee* sync; kdDebug(5228) << "use default one " << endl; book = KABC::StdAddressBook::self(); if (!book->load() ) return 0l; sync = book2syncee( book ); return sync; } void AddressBookPart::doMeta( Syncee* syncee, const QString& path ) { kdDebug(5228) << "Do Meta" << endl; QString str = QDir::homeDirPath(); str += "/.kitchensync/meta/konnector-" + path; if (!QFile::exists( str ) ) { kdDebug(5228) << "Path does not exist ->First Sync" << endl; kdDebug(5228) << "Path was " << str << " " << path << endl; syncee->setFirstSync( true ); syncee->setSyncMode( Syncee::MetaMode ); return; } syncee->setSyncMode( Syncee::MetaMode ); KSimpleConfig conf( str ); SyncEntry* entry; QString timestmp; QStringList ids; /* mod + added */ for (entry= syncee->firstEntry(); entry; entry = syncee->nextEntry() ) { ids << entry->id(); kdDebug(5228) << "Entry " << entry->name() << endl << "Entry id" << entry->id() << endl; if ( conf.hasGroup( entry->id() ) ) { conf.setGroup( entry->id() ); timestmp = conf.readEntry("time"); kdDebug(5228) << "Timestamp Old" << timestmp << endl; kdDebug(5228) << "Timestamp New" << entry->timestamp() << endl; if ( timestmp != entry->timestamp() ) entry->setState( SyncEntry::Modified ); } /* added */ else { kdDebug(5228) << "Entry added" << endl; entry->setState( SyncEntry::Added ); } } /* find removed item... through reversed mapping */ QStringList groups = conf.groupList(); QStringList::Iterator it; for (it = groups.begin(); it != groups.end(); ++it ) { // removed items if ids is not present if (!ids.contains( (*it) ) ) { kdDebug(5228) << "Entry removed from abook" << (*it) << endl; KABC::Addressee adr; adr.setUid( (*it) ); AddressBookSyncEntry* entry; entry = new AddressBookSyncEntry( adr ); entry->setState( SyncEntry::Removed ); syncee->addEntry( entry ); } } } void AddressBookPart::writeMeta( KABC::AddressBook* book, const QString& path ) { /* no meta info to save */ if (path.isEmpty() ) return; kdDebug(5228) << "WriteMeta AddressBookPart " << endl; QString str = QDir::homeDirPath(); str += "/.kitchensync/meta/konnector-" + path; if (!QFile::exists( str ) ) { kdDebug(5228) << "Path does not exist " << endl; kdDebug(5228) << "Path = " << str << endl; KonnectorProfile kon = core()->konnectorProfile(); QDir dir; dir.mkdir( dir.homeDirPath() + "/.kitchensync"); dir.mkdir( dir.homeDirPath() + "/.kitchensync/meta"); dir.mkdir( dir.homeDirPath() + "/.kitchensync/meta/konnector-" + kon.uid() ); kdDebug(5228) << "Kon UID " << kon.uid() << endl; } KSimpleConfig conf( str ); QStringList grpList = conf.groupList(); QStringList::Iterator it; for ( it = grpList.begin(); it != grpList.end(); ++it ) { conf.deleteGroup( (*it) ); } KABC::AddressBook::Iterator aIt; for ( aIt = book->begin(); aIt != book->end(); ++aIt ) { kdDebug(5228) << "Name " << (*aIt).realName() << endl; kdDebug(5228) << "UID " << (*aIt).uid() << endl; kdDebug(5228) << "Timestamp " << (*aIt).revision().toString() << endl; conf.setGroup( (*aIt).uid() ); conf.writeEntry( "time", (*aIt).revision().toString() ); } } void AddressBookPart::save( AddressBookSyncee* sync, const QString& meta) { AddressBookSyncEntry* entry; KABC::AddressBook* book; // save to the std. addressbook book = KABC::StdAddressBook::self(); /* clear the old book first */ book->clear(); for ( entry = (AddressBookSyncEntry*)sync->firstEntry(); entry; entry= (AddressBookSyncEntry*) sync->nextEntry() ) { if( entry->state() != SyncEntry::Removed ) { KABC::Addressee adr = entry->addressee(); adr.setResource( resource(entry->resource() ) ); book->insertAddressee( adr ); } } KABC::StdAddressBook::save(); kdDebug(5228) << "dumped abook " << endl; writeMeta( book, meta ); KABC::StdAddressBook::close(); } /*bool AddressBookPart::pathIsDefault( const QString& path ) { if ( path.isEmpty() ) return true; if ( path.stripWhiteSpace() == QString::fromLatin1("default") ) return true; kdDebug(5228) << "Path is not default" << endl; return false; }*/ AddressBookSyncee* AddressBookPart::book2syncee( KABC::AddressBook* book) { AddressBookSyncee* syncee = new AddressBookSyncee(); AddressBookSyncEntry* entry=0l; KABC::AddressBook::Iterator it = book->begin(); for ( ; it != book->end(); ++it ) { entry = new AddressBookSyncEntry( (*it) ); QString res = (*it).resource() ? (*it).resource()->type() : QString::null; entry->setResource( res ); syncee->addEntry( entry ); } return syncee; } /*void AddressBookPart::saveAll( KABC::AddressBook* ab) { KABC::Resource *res = 0l; QPtrList<KABC::Resource> list = ab->resources(); for (uint i = 0; i < list.count(); ++i ) { res = list.at( i ); if (!res->readOnly() ) { KABC::Ticket* ticket = ab->requestSaveTicket( res ); if (ticket) ab->save( ticket ); } } }*/ KABC::Resource* AddressBookPart::resource( const QString& type ) { QPtrListIterator<KABC::Resource> it(KABC::StdAddressBook::self()->resources() ); KABC::Resource* res = 0l; while ( (res = it.current()) ) { ++it; if ( res->type() == type ) return res; } return 0; } #include "ksync_addressbookpart.moc" <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "../../cvmfs/statistics.h" using namespace std; // NOLINT namespace perf { TEST(T_Statistics, Counter) { Counter counter; EXPECT_EQ(0, counter.Get()); counter.Set(1); EXPECT_EQ(1, counter.Get()); counter.Inc(); EXPECT_EQ(2, counter.Get()); counter.Dec(); EXPECT_EQ(1, counter.Get()); EXPECT_EQ(1, counter.Xadd(-1)); EXPECT_EQ(0, counter.Get()); counter.Dec(); EXPECT_EQ(-1, counter.Get()); counter.Set(1024*1024); EXPECT_EQ("1048576", counter.Print()); EXPECT_EQ("1024", counter.PrintKi()); EXPECT_EQ("1048", counter.PrintK()); EXPECT_EQ("1", counter.PrintM()); EXPECT_EQ("1", counter.PrintMi()); Counter counter2; EXPECT_EQ("inf", counter.PrintRatio(counter2)); counter2.Set(1024); EXPECT_EQ("1024.000", counter.PrintRatio(counter2)); } TEST(T_Statistics, Statistics) { Statistics statistics; Counter *counter = statistics.Register("test.counter", "a test counter"); ASSERT_TRUE(counter != NULL); EXPECT_EQ(0, counter->Get()); EXPECT_EQ(NULL, statistics.Register("test.counter", "Name Clash")); EXPECT_EQ(0, statistics.Lookup("test.counter")->Get()); EXPECT_EQ("a test counter", statistics.LookupDesc("test.counter")); EXPECT_EQ(NULL, statistics.Lookup("test.unknown")); EXPECT_EQ("test.counter|0|a test counter\n", statistics.PrintList(Statistics::kPrintSimple)); } } // namespace perf <commit_msg>style<commit_after>#include "gtest/gtest.h" #include "../../cvmfs/statistics.h" using namespace std; // NOLINT namespace perf { TEST(T_Statistics, Counter) { Counter counter; EXPECT_EQ(0, counter.Get()); counter.Set(1); EXPECT_EQ(1, counter.Get()); counter.Inc(); EXPECT_EQ(2, counter.Get()); counter.Dec(); EXPECT_EQ(1, counter.Get()); EXPECT_EQ(1, counter.Xadd(-1)); EXPECT_EQ(0, counter.Get()); counter.Dec(); EXPECT_EQ(-1, counter.Get()); counter.Set(1024*1024); EXPECT_EQ("1048576", counter.Print()); EXPECT_EQ("1024", counter.PrintKi()); EXPECT_EQ("1048", counter.PrintK()); EXPECT_EQ("1", counter.PrintM()); EXPECT_EQ("1", counter.PrintMi()); Counter counter2; EXPECT_EQ("inf", counter.PrintRatio(counter2)); counter2.Set(1024); EXPECT_EQ("1024.000", counter.PrintRatio(counter2)); } TEST(T_Statistics, Statistics) { Statistics statistics; Counter *counter = statistics.Register("test.counter", "a test counter"); ASSERT_TRUE(counter != NULL); EXPECT_EQ(0, counter->Get()); EXPECT_EQ(NULL, statistics.Register("test.counter", "Name Clash")); EXPECT_EQ(0, statistics.Lookup("test.counter")->Get()); EXPECT_EQ("a test counter", statistics.LookupDesc("test.counter")); EXPECT_EQ(NULL, statistics.Lookup("test.unknown")); EXPECT_EQ("test.counter|0|a test counter\n", statistics.PrintList(Statistics::kPrintSimple)); } } // namespace perf <|endoftext|>
<commit_before>// This file is distributed under the BSD License. // See "license.txt" for details. // Copyright 2009, Jonathan Turner (jturner@minnow-lang.org) // and Jason Turner (lefticus@gmail.com) // http://www.chaiscript.com #include <boost/preprocessor.hpp> #include <boost/preprocessor/arithmetic/inc.hpp> #define param(z,n,text) BOOST_PP_CAT(_, BOOST_PP_INC(n)) #ifndef BOOST_PP_IS_ITERATING #ifndef __bind_first_hpp__ #define __bind_first_hpp__ #include <boost/function.hpp> #include <boost/bind.hpp> #include <boost/ref.hpp> #define BOOST_PP_ITERATION_LIMITS ( 0, 8 ) #define BOOST_PP_FILENAME_1 <chaiscript/dispatchkit/bind_first.hpp> #include BOOST_PP_ITERATE() # endif #else # define n BOOST_PP_ITERATION() namespace chaiscript { template<typename Ret, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) > boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))> bind_first(Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param)), boost::reference_wrapper<Class> &o) { return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, ~)); } template<typename Ret, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) > boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))> bind_first(Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param)) const, boost::reference_wrapper<Class> &o) { return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, ~)); } template<typename Ret, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) > boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))> bind_first(Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param)), Class *o) { return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, ~)); } template<typename Ret, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) > boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))> bind_first(Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param))const, Class *o) { return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, ~)); } template<typename Ret, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) > boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))> bind_first(Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param)), boost::shared_ptr<Class> o) { return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, ~)); } template<typename Ret, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) > boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))> bind_first(Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param))const, boost::shared_ptr<Class> o) { return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, ~)); } } #endif <commit_msg>Reduce # of required versions for bound_fun and enhance it to work with non-member functions<commit_after>// This file is distributed under the BSD License. // See "license.txt" for details. // Copyright 2009, Jonathan Turner (jturner@minnow-lang.org) // and Jason Turner (lefticus@gmail.com) // http://www.chaiscript.com #include <boost/preprocessor.hpp> #include <boost/preprocessor/arithmetic/inc.hpp> #define param(z,n,text) BOOST_PP_CAT(_, BOOST_PP_INC(n)) #ifndef BOOST_PP_IS_ITERATING #ifndef __bind_first_hpp__ #define __bind_first_hpp__ #include <boost/function.hpp> #include <boost/bind.hpp> #include <boost/ref.hpp> #define BOOST_PP_ITERATION_LIMITS ( 0, 8 ) #define BOOST_PP_FILENAME_1 <chaiscript/dispatchkit/bind_first.hpp> #include BOOST_PP_ITERATE() # endif #else # define n BOOST_PP_ITERATION() namespace chaiscript { template<typename Ret, typename O, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) > boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))> bind_first(Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param)), const O &o) { return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, ~)); } template<typename Ret, typename O, typename Class BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) > boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))> bind_first(Ret (Class::*f)(BOOST_PP_ENUM_PARAMS(n, Param))const, const O &o) { return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, ~)); } template<typename Ret,typename O BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename Param) > boost::function<Ret (BOOST_PP_ENUM_PARAMS(n, Param))> bind_first(Ret (*f)(BOOST_PP_ENUM_PARAMS(n, Param)), const O &o) { return boost::bind(f, o BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, param, ~)); } } #endif <|endoftext|>
<commit_before>/* Copyright (c) 2006, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ROUTING_TABLE_HPP #define ROUTING_TABLE_HPP #include <vector> #include <boost/cstdint.hpp> #include <boost/utility.hpp> #include <boost/tuple/tuple.hpp> #include <boost/array.hpp> #include <set> #include <libtorrent/kademlia/logging.hpp> #include <libtorrent/kademlia/node_id.hpp> #include <libtorrent/kademlia/node_entry.hpp> #include <libtorrent/session_settings.hpp> #include <libtorrent/size_type.hpp> #include <libtorrent/assert.hpp> #include <libtorrent/ptime.hpp> namespace libtorrent { struct session_status; } namespace libtorrent { namespace dht { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_DECLARE_LOG(table); #endif typedef std::vector<node_entry> bucket_t; struct routing_table_node { bucket_t replacements; bucket_t live_nodes; ptime last_active; }; // differences in the implementation from the description in // the paper: // // * Nodes are not marked as being stale, they keep a counter // that tells how many times in a row they have failed. When // a new node is to be inserted, the node that has failed // the most times is replaced. If none of the nodes in the // bucket has failed, then it is put in the replacement // cache (just like in the paper). class TORRENT_EXPORT routing_table { public: routing_table(node_id const& id, int bucket_size , dht_settings const& settings); void status(session_status& s) const; void node_failed(node_id const& id); // adds an endpoint that will never be added to // the routing table void add_router_node(udp::endpoint router); // iterates over the router nodes added typedef std::set<udp::endpoint>::const_iterator router_iterator; router_iterator router_begin() const { return m_router_nodes.begin(); } router_iterator router_end() const { return m_router_nodes.end(); } bool add_node(node_entry const& e); // this function is called every time the node sees // a sign of a node being alive. This node will either // be inserted in the k-buckets or be moved to the top // of its bucket. bool node_seen(node_id const& id, udp::endpoint ep); // this may add a node to the routing table and mark it as // not pinged. If the bucket the node falls into is full, // the node will be ignored. void heard_about(node_id const& id, udp::endpoint const& ep); // if any bucket in the routing table needs to be refreshed // this function will return true and set the target to an // appropriate target inside that bucket bool need_refresh(node_id& target) const; enum { include_failed = 1 }; // fills the vector with the count nodes from our buckets that // are nearest to the given id. void find_node(node_id const& id, std::vector<node_entry>& l , int options, int count = 0); int bucket_size(int bucket) { int num_buckets = m_buckets.size(); if (bucket < num_buckets) bucket = num_buckets - 1; table_t::iterator i = m_buckets.begin(); std::advance(i, bucket); return (int)i->live_nodes.size(); } void for_each_node(void (*)(void*, node_entry const&) , void (*)(void*, node_entry const&), void* userdata) const; int bucket_size() const { return m_bucket_size; } boost::tuple<int, int> size() const; size_type num_global_nodes() const; // returns true if there are no working nodes // in the routing table bool need_bootstrap() const; int num_active_buckets() const { return m_buckets.size(); } void replacement_cache(bucket_t& nodes) const; #if defined TORRENT_DHT_VERBOSE_LOGGING || defined TORRENT_DEBUG // used for debug and monitoring purposes. This will print out // the state of the routing table to the given stream void print_state(std::ostream& os) const; #endif void touch_bucket(node_id const& target); private: typedef std::list<routing_table_node> table_t; table_t::iterator find_bucket(node_id const& id); // constant called k in paper int m_bucket_size; dht_settings const& m_settings; // (k-bucket, replacement cache) pairs // the first entry is the bucket the furthest // away from our own ID. Each time the bucket // closest to us (m_buckets.back()) has more than // bucket size nodes in it, another bucket is // added to the end and it's split up between them table_t m_buckets; node_id m_id; // our own node id // the last time need_bootstrap() returned true mutable ptime m_last_bootstrap; // this is a set of all the endpoints that have // been identified as router nodes. They will // be used in searches, but they will never // be added to the routing table. std::set<udp::endpoint> m_router_nodes; }; } } // namespace libtorrent::dht #endif // ROUTING_TABLE_HPP <commit_msg>added missing include<commit_after>/* Copyright (c) 2006, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ROUTING_TABLE_HPP #define ROUTING_TABLE_HPP #include <vector> #include <boost/cstdint.hpp> #include <boost/utility.hpp> #include <boost/tuple/tuple.hpp> #include <boost/array.hpp> #include <set> #include <list> #include <libtorrent/kademlia/logging.hpp> #include <libtorrent/kademlia/node_id.hpp> #include <libtorrent/kademlia/node_entry.hpp> #include <libtorrent/session_settings.hpp> #include <libtorrent/size_type.hpp> #include <libtorrent/assert.hpp> #include <libtorrent/ptime.hpp> namespace libtorrent { struct session_status; } namespace libtorrent { namespace dht { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_DECLARE_LOG(table); #endif typedef std::vector<node_entry> bucket_t; struct routing_table_node { bucket_t replacements; bucket_t live_nodes; ptime last_active; }; // differences in the implementation from the description in // the paper: // // * Nodes are not marked as being stale, they keep a counter // that tells how many times in a row they have failed. When // a new node is to be inserted, the node that has failed // the most times is replaced. If none of the nodes in the // bucket has failed, then it is put in the replacement // cache (just like in the paper). class TORRENT_EXPORT routing_table { public: routing_table(node_id const& id, int bucket_size , dht_settings const& settings); void status(session_status& s) const; void node_failed(node_id const& id); // adds an endpoint that will never be added to // the routing table void add_router_node(udp::endpoint router); // iterates over the router nodes added typedef std::set<udp::endpoint>::const_iterator router_iterator; router_iterator router_begin() const { return m_router_nodes.begin(); } router_iterator router_end() const { return m_router_nodes.end(); } bool add_node(node_entry const& e); // this function is called every time the node sees // a sign of a node being alive. This node will either // be inserted in the k-buckets or be moved to the top // of its bucket. bool node_seen(node_id const& id, udp::endpoint ep); // this may add a node to the routing table and mark it as // not pinged. If the bucket the node falls into is full, // the node will be ignored. void heard_about(node_id const& id, udp::endpoint const& ep); // if any bucket in the routing table needs to be refreshed // this function will return true and set the target to an // appropriate target inside that bucket bool need_refresh(node_id& target) const; enum { include_failed = 1 }; // fills the vector with the count nodes from our buckets that // are nearest to the given id. void find_node(node_id const& id, std::vector<node_entry>& l , int options, int count = 0); int bucket_size(int bucket) { int num_buckets = m_buckets.size(); if (bucket < num_buckets) bucket = num_buckets - 1; table_t::iterator i = m_buckets.begin(); std::advance(i, bucket); return (int)i->live_nodes.size(); } void for_each_node(void (*)(void*, node_entry const&) , void (*)(void*, node_entry const&), void* userdata) const; int bucket_size() const { return m_bucket_size; } boost::tuple<int, int> size() const; size_type num_global_nodes() const; // returns true if there are no working nodes // in the routing table bool need_bootstrap() const; int num_active_buckets() const { return m_buckets.size(); } void replacement_cache(bucket_t& nodes) const; #if defined TORRENT_DHT_VERBOSE_LOGGING || defined TORRENT_DEBUG // used for debug and monitoring purposes. This will print out // the state of the routing table to the given stream void print_state(std::ostream& os) const; #endif void touch_bucket(node_id const& target); private: typedef std::list<routing_table_node> table_t; table_t::iterator find_bucket(node_id const& id); // constant called k in paper int m_bucket_size; dht_settings const& m_settings; // (k-bucket, replacement cache) pairs // the first entry is the bucket the furthest // away from our own ID. Each time the bucket // closest to us (m_buckets.back()) has more than // bucket size nodes in it, another bucket is // added to the end and it's split up between them table_t m_buckets; node_id m_id; // our own node id // the last time need_bootstrap() returned true mutable ptime m_last_bootstrap; // this is a set of all the endpoints that have // been identified as router nodes. They will // be used in searches, but they will never // be added to the routing table. std::set<udp::endpoint> m_router_nodes; }; } } // namespace libtorrent::dht #endif // ROUTING_TABLE_HPP <|endoftext|>
<commit_before>// Copyright (c) 2017 Sony Corporation. 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. /** Batch Normalization */ #ifndef __NBLA_FUNCTION_BATCHNORM_HPP__ #define __NBLA_FUNCTION_BATCHNORM_HPP__ #include <nbla/cpu.hpp> #include <nbla/function.hpp> #include <nbla/function_registry.hpp> #include <vector> using std::vector; namespace nbla { NBLA_REGISTER_FUNCTION_HEADER(BatchNormalization, const vector<int> &, float, float, bool); /** Batch normalization at training time defined as @f[ \begin{array}{lcl} \mu &=& \frac{1}{M} \sum x_i\\ \sigma^2 &=& \frac{1}{M} \left(\sum x_i - \mu\right)^2\\ \hat{x}_i &=& \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon}} \\ y_i &=& \hat{x}_i \gamma + \beta. \end{array} @f] In testing, mean and variance computed by moving average calculated during training are used. Inputs: - N-D array of input. - N-D array of beta which is learned. - N-D array of gamma which is learned. - N-D array of running mean (modified during forward execution). - N-D array of running variance (modified during forward execution). Outputs (1 or 3): - N-D array. - (Optional) N-D array of running mean. - (Optional) N-D array of running variance. @tparam T Data type for computation. @param axes Axes mean and variance are taken. @param decay_rate Decay rate of running mean and variance. @param eps Tiny value to avoid zero division by std. @param batch_stat Use mini-batch statistics rather than running ones. @sa Ioffe and Szegedy, Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift. https://arxiv.org/abs/1502.03167 \ingroup FunctionImplGrp */ template <typename T> class BatchNormalization : public BaseFunction<const vector<int> &, float, float, bool> { protected: vector<int> axes_; float decay_rate_; float eps_; bool batch_stat_; Variable mean_; Variable var_; int size0_, size1_, size2_, size02_, size12_; public: BatchNormalization(const Context &ctx, const vector<int> axes, float decay_rate, float eps, bool batch_stat) : BaseFunction(ctx, axes, decay_rate, eps, batch_stat), axes_(axes), decay_rate_(decay_rate), eps_(eps), batch_stat_(batch_stat) {} virtual ~BatchNormalization() {} virtual shared_ptr<Function> copy() const { return create_BatchNormalization(ctx_, axes_, decay_rate_, eps_, batch_stat_); } virtual vector<dtypes> in_types() { return vector<dtypes>{get_dtype<T>(), get_dtype<T>(), get_dtype<T>(), get_dtype<T>(), get_dtype<T>()}; } virtual vector<dtypes> out_types() { return vector<dtypes>{get_dtype<T>(), get_dtype<T>(), get_dtype<T>()}; } virtual int min_inputs() { return 5; } virtual int min_outputs() { return 1; } virtual string name() { return "BatchNormalization"; } virtual vector<string> allowed_array_classes() { return SingletonManager::get<Cpu>()->array_classes(); } virtual bool grad_depends_output_data(int i, int o) const { // Gradient computation always requires output mean and var. return o > 0; } protected: NBLA_API virtual void setup_impl(const Variables &inputs, const Variables &outputs); NBLA_API virtual void forward_impl(const Variables &inputs, const Variables &outputs); NBLA_API virtual void backward_impl(const Variables &inputs, const Variables &outputs, const vector<bool> &propagate_down, const vector<bool> &accum); NBLA_API virtual void forward_impl_batch(const Variables &inputs, const Variables &outputs); NBLA_API virtual void forward_impl_global(const Variables &inputs, const Variables &outputs); NBLA_API virtual void backward_impl_batch(const Variables &inputs, const Variables &outputs, const vector<bool> &propagate_down, const vector<bool> &accum); }; } #endif <commit_msg>fix comments in BatchNormalization function<commit_after>// Copyright (c) 2017 Sony Corporation. 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. /** Batch Normalization */ #ifndef __NBLA_FUNCTION_BATCHNORM_HPP__ #define __NBLA_FUNCTION_BATCHNORM_HPP__ #include <nbla/cpu.hpp> #include <nbla/function.hpp> #include <nbla/function_registry.hpp> #include <vector> using std::vector; namespace nbla { NBLA_REGISTER_FUNCTION_HEADER(BatchNormalization, const vector<int> &, float, float, bool); /** Batch normalization at training time defined as @f[ \begin{array}{lcl} \mu &=& \frac{1}{M} \sum x_i\\ \sigma^2 &=& \frac{1}{M} \left(\sum x_i - \mu\right)^2\\ \hat{x}_i &=& \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon}} \\ y_i &=& \hat{x}_i \gamma + \beta. \end{array} @f] In testing, mean and variance computed by moving average calculated during training are used. Inputs: - N-D array of input. - N-D array of beta which is learned. - N-D array of gamma which is learned. - N-D array of running mean (modified during forward execution). - N-D array of running variance (modified during forward execution). Outputs (1 or 3): - N-D array. - (Optional) N-D array of batch mean. - (Optional) N-D array of batch variance. @tparam T Data type for computation. @param axes Axes mean and variance are taken. @param decay_rate Decay rate of running mean and variance. @param eps Tiny value to avoid zero division by std. @param batch_stat Use mini-batch statistics rather than running ones. @sa Ioffe and Szegedy, Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift. https://arxiv.org/abs/1502.03167 \ingroup FunctionImplGrp */ template <typename T> class BatchNormalization : public BaseFunction<const vector<int> &, float, float, bool> { protected: vector<int> axes_; float decay_rate_; float eps_; bool batch_stat_; Variable mean_; Variable var_; int size0_, size1_, size2_, size02_, size12_; public: BatchNormalization(const Context &ctx, const vector<int> axes, float decay_rate, float eps, bool batch_stat) : BaseFunction(ctx, axes, decay_rate, eps, batch_stat), axes_(axes), decay_rate_(decay_rate), eps_(eps), batch_stat_(batch_stat) {} virtual ~BatchNormalization() {} virtual shared_ptr<Function> copy() const { return create_BatchNormalization(ctx_, axes_, decay_rate_, eps_, batch_stat_); } virtual vector<dtypes> in_types() { return vector<dtypes>{get_dtype<T>(), get_dtype<T>(), get_dtype<T>(), get_dtype<T>(), get_dtype<T>()}; } virtual vector<dtypes> out_types() { return vector<dtypes>{get_dtype<T>(), get_dtype<T>(), get_dtype<T>()}; } virtual int min_inputs() { return 5; } virtual int min_outputs() { return 1; } virtual string name() { return "BatchNormalization"; } virtual vector<string> allowed_array_classes() { return SingletonManager::get<Cpu>()->array_classes(); } virtual bool grad_depends_output_data(int i, int o) const { // Gradient computation always requires output mean and var. return o > 0; } protected: NBLA_API virtual void setup_impl(const Variables &inputs, const Variables &outputs); NBLA_API virtual void forward_impl(const Variables &inputs, const Variables &outputs); NBLA_API virtual void backward_impl(const Variables &inputs, const Variables &outputs, const vector<bool> &propagate_down, const vector<bool> &accum); NBLA_API virtual void forward_impl_batch(const Variables &inputs, const Variables &outputs); NBLA_API virtual void forward_impl_global(const Variables &inputs, const Variables &outputs); NBLA_API virtual void backward_impl_batch(const Variables &inputs, const Variables &outputs, const vector<bool> &propagate_down, const vector<bool> &accum); }; } #endif <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 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 Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ /****************************************************************************** * Contributors: * - damien.marchal@univ-lille1.fr *****************************************************************************/ #include <sofa/simulation/Node.h> using sofa::simulation::Node ; #include <SofaSimulationGraph/testing/BaseSimulationTest.h> using sofa::helper::testing::BaseSimulationTest ; using sofa::simulation::Node ; using sofa::core::visual::VisualModel ; class NodeContext_test: public BaseSimulationTest { public: void testGetNodeObjects() { std::stringstream scene ; scene << "<?xml version='1.0'?>" "<Node name='Root' gravity='0 -9.81 0' time='0' animate='0' > \n" " <OglModel/> \n" " <Node name='child1'> \n" " <OglModel/> \n" " <OglModel/> \n" " <MechanicalObject /> \n" " <Node name='child2'> \n" " <OglModel/> \n" " <OglModel/> \n" " </Node> \n" " </Node> \n" "</Node> \n" ; SceneInstance c("xml", scene.str()) ; c.initScene() ; Node* m_root = c.root.get() ; ASSERT_NE(m_root, nullptr) ; EXPECT_MSG_NOEMIT(Error, Warning) ; Node* node =m_root->getChild("child1") ; /// Query a specific model in a container, this is the old API std::vector<VisualModel*> results ; node->getNodeObjects<VisualModel, std::vector<VisualModel*> >( &results ) ; ASSERT_EQ( results.size() , (unsigned int)2 ) ; /// Query a specific model with a nicer syntax std::vector<VisualModel*> results2 ; ASSERT_EQ( node->getNodeObjects(results2).size(), (unsigned int)2 ) ; /// Query a specific model with a nicer syntax std::vector<VisualModel*> results3 ; ASSERT_EQ( node->getNodeObjects(&results3)->size(), (unsigned int)2 ) ; /// Query a specific model with a compact syntax, this returns std::vector<BaseObject*> /// So there is 4 base object in the scene. for(auto& m : node->getNodeObjects() ) { SOFA_UNUSED(m); } ASSERT_EQ( node->getNodeObjects().size(), (unsigned int)3 ) ; } void testGetTreeObjects() { std::stringstream scene ; scene << "<?xml version='1.0'?>" "<Node name='Root' gravity='0 -9.81 0' time='0' animate='0' > \n" " <OglModel/> \n" " <Node name='child1'> \n" " <OglModel/> \n" " <OglModel/> \n" " <MechanicalObject /> \n" " <Node name='child2'> \n" " <OglModel/> \n" " <OglModel/> \n" " </Node> \n" " </Node> \n" "</Node> \n" ; SceneInstance c("xml", scene.str()) ; c.initScene() ; Node* m_root = c.root.get() ; ASSERT_NE(m_root, nullptr) ; EXPECT_MSG_NOEMIT(Error, Warning) ; Node* node =m_root->getChild("child1") ; /// Query a specific model in a container, this is the old API std::vector<VisualModel*> results ; node->getTreeObjects<VisualModel, std::vector<VisualModel*> >( &results ) ; ASSERT_EQ( results.size() , (unsigned int)4 ) ; /// Query a specific model with a nicer syntax std::vector<VisualModel*> results2 ; ASSERT_EQ( node->getTreeObjects(results2).size(), (unsigned int)4 ) ; /// Query a specific model with a nicer syntax std::vector<VisualModel*> results3 ; ASSERT_EQ( node->getTreeObjects(&results3)->size(), (unsigned int)4 ) ; /// Query a specific model with a compact syntax, this returns std::vector<BaseObject*> /// So there is 4 base object in the scene. for(auto& m : node->getTreeObjects() ) { SOFA_UNUSED(m); } ASSERT_EQ( node->getTreeObjects().size(), (unsigned int)5 ) ; } }; TEST_F(NodeContext_test , testGetNodeObjects ) { this->testGetNodeObjects(); } TEST_F(NodeContext_test , testGetTreeObjects ) { this->testGetTreeObjects(); } <commit_msg>[SofaKernel/frameworkextra_test] Fix test to correctly load the required plugin<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 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 Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ /****************************************************************************** * Contributors: * - damien.marchal@univ-lille1.fr *****************************************************************************/ #include <sofa/simulation/Node.h> using sofa::simulation::Node ; #include <SofaSimulationGraph/testing/BaseSimulationTest.h> using sofa::helper::testing::BaseSimulationTest ; using sofa::simulation::Node ; using sofa::core::visual::VisualModel ; #include <sofa/helper/system/PluginManager.h> using sofa::helper::system::PluginManager ; class NodeContext_test: public BaseSimulationTest { public: NodeContext_test() { importPlugin("SofaAllCommonComponents") ; } void testGetNodeObjects() { std::stringstream scene ; scene << "<?xml version='1.0'?>" "<Node name='Root' gravity='0 -9.81 0' time='0' animate='0' > \n" " <OglModel/> \n" " <Node name='child1'> \n" " <OglModel/> \n" " <OglModel/> \n" " <MechanicalObject /> \n" " <Node name='child2'> \n" " <OglModel/> \n" " <OglModel/> \n" " </Node> \n" " </Node> \n" "</Node> \n" ; SceneInstance c("xml", scene.str()) ; c.initScene() ; Node* m_root = c.root.get() ; ASSERT_NE(m_root, nullptr) ; EXPECT_MSG_NOEMIT(Error, Warning) ; Node* node =m_root->getChild("child1") ; /// Query a specific model in a container, this is the old API std::vector<VisualModel*> results ; node->getNodeObjects<VisualModel, std::vector<VisualModel*> >( &results ) ; ASSERT_EQ( results.size() , (unsigned int)2 ) ; /// Query a specific model with a nicer syntax std::vector<VisualModel*> results2 ; ASSERT_EQ( node->getNodeObjects(results2).size(), (unsigned int)2 ) ; /// Query a specific model with a nicer syntax std::vector<VisualModel*> results3 ; ASSERT_EQ( node->getNodeObjects(&results3)->size(), (unsigned int)2 ) ; /// Query a specific model with a compact syntax, this returns std::vector<BaseObject*> /// So there is 4 base object in the scene. for(auto& m : node->getNodeObjects() ) { SOFA_UNUSED(m); } ASSERT_EQ( node->getNodeObjects().size(), (unsigned int)3 ) ; } void testGetTreeObjects() { std::stringstream scene ; scene << "<?xml version='1.0'?>" "<Node name='Root' gravity='0 -9.81 0' time='0' animate='0' > \n" " <OglModel/> \n" " <Node name='child1'> \n" " <OglModel/> \n" " <OglModel/> \n" " <MechanicalObject /> \n" " <Node name='child2'> \n" " <OglModel/> \n" " <OglModel/> \n" " </Node> \n" " </Node> \n" "</Node> \n" ; SceneInstance c("xml", scene.str()) ; c.initScene() ; Node* m_root = c.root.get() ; ASSERT_NE(m_root, nullptr) ; EXPECT_MSG_NOEMIT(Error, Warning) ; Node* node =m_root->getChild("child1") ; /// Query a specific model in a container, this is the old API std::vector<VisualModel*> results ; node->getTreeObjects<VisualModel, std::vector<VisualModel*> >( &results ) ; ASSERT_EQ( results.size() , (unsigned int)4 ) ; /// Query a specific model with a nicer syntax std::vector<VisualModel*> results2 ; ASSERT_EQ( node->getTreeObjects(results2).size(), (unsigned int)4 ) ; /// Query a specific model with a nicer syntax std::vector<VisualModel*> results3 ; ASSERT_EQ( node->getTreeObjects(&results3)->size(), (unsigned int)4 ) ; /// Query a specific model with a compact syntax, this returns std::vector<BaseObject*> /// So there is 4 base object in the scene. for(auto& m : node->getTreeObjects() ) { SOFA_UNUSED(m); } ASSERT_EQ( node->getTreeObjects().size(), (unsigned int)5 ) ; } }; TEST_F(NodeContext_test , testGetNodeObjects ) { this->testGetNodeObjects(); } TEST_F(NodeContext_test , testGetTreeObjects ) { this->testGetTreeObjects(); } <|endoftext|>
<commit_before>#include "Vajra/Engine/AssetLibrary/AssetLibrary.h" #include "Vajra/Engine/Components/DerivedComponents/Renderer/WaterRenderer.h" #include "Vajra/Engine/Core/Engine.h" #include "Vajra/Engine/Timer/Timer.h" #include "Vajra/Framework/OpenGL/OpenGLWrapper/OpenGLWrapper.h" #include "Vajra/Framework/OpenGL/ShaderSet/ShaderSet.h" WaterRenderer::WaterRenderer() : MeshRenderer() { this->init(); } WaterRenderer::WaterRenderer(Object* object_) : MeshRenderer(object_) { this->init(); } WaterRenderer::~WaterRenderer() { this->destroy(); } void WaterRenderer::InitMesh(std::string urlOfMesh) { MeshRenderer::InitMesh(urlOfMesh); } void WaterRenderer::SetScrollingUVs(float uvScrollSpeed) { this->scrollingUVs_speed = uvScrollSpeed; } void WaterRenderer::SetSecondaryTexture(std::string pathToTexture) { this->secondaryTexture = ENGINE->GetAssetLibrary()->GetAsset<TextureAsset>(pathToTexture); } void WaterRenderer::HandleMessage(MessageChunk messageChunk) { MeshRenderer::HandleMessage(messageChunk); switch (messageChunk->GetMessageType()) { case MESSAGE_TYPE_FRAME_EVENT: { this->scrollUVs(); } break; default : { } break; } } void WaterRenderer::Draw() { ShaderSet* currentShaderSet = FRAMEWORK->GetOpenGLWrapper()->GetCurrentShaderSet(); if (currentShaderSet->HasHandle(SHADER_VARIABLE_VARIABLENAME_scrolling_uv_offset)) { GLint scrolling_uv_offset_handle = currentShaderSet->GetHandle(SHADER_VARIABLE_VARIABLENAME_scrolling_uv_offset); GLCALL(glUniform1f, scrolling_uv_offset_handle, this->scrollingUVsOffset); } if (this->secondaryTexture) { this->secondaryTexture->Draw(2); } MeshRenderer::Draw(); } void WaterRenderer::scrollUVs() { this->scrollingUVsOffset += this->scrollingUVs_speed * ENGINE->GetTimer()->GetDeltaFrameTime(); // TODO [Hack] Don't blow floating point limit if (this->scrollingUVsOffset > 100000.0f) { this->scrollingUVsOffset -= 100000.0f; } } void WaterRenderer::init() { this->scrollingUVsOffset = 0.0f; this->scrollingUVs_speed = 0.1f; this->SetPreventCulling(true); this->addSubscriptionToMessageType(MESSAGE_TYPE_FRAME_EVENT, this->GetTypeId(), false); } void WaterRenderer::destroy() { this->removeSubscriptionToAllMessageTypes(this->GetTypeId()); } <commit_msg>Fix that scrolling water texture thing, for reals.<commit_after>#include "Vajra/Engine/AssetLibrary/AssetLibrary.h" #include "Vajra/Engine/Components/DerivedComponents/Renderer/WaterRenderer.h" #include "Vajra/Engine/Core/Engine.h" #include "Vajra/Engine/Timer/Timer.h" #include "Vajra/Framework/OpenGL/OpenGLWrapper/OpenGLWrapper.h" #include "Vajra/Framework/OpenGL/ShaderSet/ShaderSet.h" WaterRenderer::WaterRenderer() : MeshRenderer() { this->init(); } WaterRenderer::WaterRenderer(Object* object_) : MeshRenderer(object_) { this->init(); } WaterRenderer::~WaterRenderer() { this->destroy(); } void WaterRenderer::InitMesh(std::string urlOfMesh) { MeshRenderer::InitMesh(urlOfMesh); } void WaterRenderer::SetScrollingUVs(float uvScrollSpeed) { this->scrollingUVs_speed = uvScrollSpeed; } void WaterRenderer::SetSecondaryTexture(std::string pathToTexture) { this->secondaryTexture = ENGINE->GetAssetLibrary()->GetAsset<TextureAsset>(pathToTexture); } void WaterRenderer::HandleMessage(MessageChunk messageChunk) { MeshRenderer::HandleMessage(messageChunk); switch (messageChunk->GetMessageType()) { case MESSAGE_TYPE_FRAME_EVENT: { this->scrollUVs(); } break; default : { } break; } } void WaterRenderer::Draw() { ShaderSet* currentShaderSet = FRAMEWORK->GetOpenGLWrapper()->GetCurrentShaderSet(); if (currentShaderSet->HasHandle(SHADER_VARIABLE_VARIABLENAME_scrolling_uv_offset)) { GLint scrolling_uv_offset_handle = currentShaderSet->GetHandle(SHADER_VARIABLE_VARIABLENAME_scrolling_uv_offset); GLCALL(glUniform1f, scrolling_uv_offset_handle, this->scrollingUVsOffset); } if (this->secondaryTexture) { this->secondaryTexture->Draw(2); } MeshRenderer::Draw(); } void WaterRenderer::scrollUVs() { this->scrollingUVsOffset += this->scrollingUVs_speed * ENGINE->GetTimer()->GetDeltaFrameTime(); // TODO [Hack] Don't blow floating point limit if (this->scrollingUVsOffset > 1.0f) { this->scrollingUVsOffset -= 1.0f; } } void WaterRenderer::init() { this->scrollingUVsOffset = 0.0f; this->scrollingUVs_speed = 0.1f; this->SetPreventCulling(true); this->addSubscriptionToMessageType(MESSAGE_TYPE_FRAME_EVENT, this->GetTypeId(), false); } void WaterRenderer::destroy() { this->removeSubscriptionToAllMessageTypes(this->GetTypeId()); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkAxes.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkAxes.h" #include "vtkCellArray.h" #include "vtkFloatArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPolyData.h" vtkCxxRevisionMacro(vtkAxes, "1.44"); vtkStandardNewMacro(vtkAxes); // Construct with origin=(0,0,0) and scale factor=1. vtkAxes::vtkAxes() { this->Origin[0] = 0.0; this->Origin[1] = 0.0; this->Origin[2] = 0.0; this->ScaleFactor = 1.0; this->Symmetric = 0; this->ComputeNormals = 1; this->SetNumberOfInputPorts(0); } int vtkAxes::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **vtkNotUsed(inputVector), vtkInformationVector *outputVector) { // get the info object vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the ouptut vtkPolyData *output = vtkPolyData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); int numPts=6, numLines=3; vtkPoints *newPts; vtkCellArray *newLines; vtkFloatArray *newScalars; vtkFloatArray *newNormals; double x[3], n[3]; vtkIdType ptIds[2]; vtkDebugMacro(<<"Creating x-y-z axes"); newPts = vtkPoints::New(); newPts->Allocate(numPts); newLines = vtkCellArray::New(); newLines->Allocate(newLines->EstimateSize(numLines,2)); newScalars = vtkFloatArray::New(); newScalars->Allocate(numPts); newScalars->SetName("Axes"); newNormals = vtkFloatArray::New(); newNormals->SetNumberOfComponents(3); newNormals->Allocate(numPts); newNormals->SetName("Normals"); // // Create axes // x[0] = this->Origin[0]; x[1] = this->Origin[1]; x[2] = this->Origin[2]; if (this->Symmetric) { x[0] = this->Origin[0] - this->ScaleFactor; } n[0] = 0.0; n[1] = 1.0; n[2] = 0.0; ptIds[0] = newPts->InsertNextPoint(x); newScalars->InsertNextValue(0.0); newNormals->InsertNextTuple(n); x[0] = this->Origin[0] + this->ScaleFactor; x[1] = this->Origin[1]; x[2] = this->Origin[2]; ptIds[1] = newPts->InsertNextPoint(x); newLines->InsertNextCell(2,ptIds); newScalars->InsertNextValue(0.0); newNormals->InsertNextTuple(n); x[0] = this->Origin[0]; x[1] = this->Origin[1]; x[2] = this->Origin[2]; if (this->Symmetric) { x[1] = this->Origin[1] - this->ScaleFactor; } n[0] = 0.0; n[1] = 0.0; n[2] = 1.0; ptIds[0] = newPts->InsertNextPoint(x); newScalars->InsertNextValue(0.25); newNormals->InsertNextTuple(n); x[0] = this->Origin[0]; x[1] = this->Origin[1] + this->ScaleFactor; x[2] = this->Origin[2]; ptIds[1] = newPts->InsertNextPoint(x); newScalars->InsertNextValue(0.25); newNormals->InsertNextTuple(n); newLines->InsertNextCell(2,ptIds); x[0] = this->Origin[0]; x[1] = this->Origin[1]; x[2] = this->Origin[2]; if (this->Symmetric) { x[2] = this->Origin[2] - this->ScaleFactor; } n[0] = 1.0; n[1] = 0.0; n[2] = 0.0; ptIds[0] = newPts->InsertNextPoint(x); newScalars->InsertNextValue(0.5); newNormals->InsertNextTuple(n); x[0] = this->Origin[0]; x[1] = this->Origin[1]; x[2] = this->Origin[2] + this->ScaleFactor; ptIds[1] = newPts->InsertNextPoint(x); newScalars->InsertNextValue(0.5); newNormals->InsertNextTuple(n); newLines->InsertNextCell(2,ptIds); // // Update our output and release memory // output->SetPoints(newPts); newPts->Delete(); output->GetPointData()->SetScalars(newScalars); newScalars->Delete(); if (this->ComputeNormals) { output->GetPointData()->SetNormals(newNormals); } newNormals->Delete(); output->SetLines(newLines); newLines->Delete(); return 1; } //---------------------------------------------------------------------------- // This source does not know how to generate pieces yet. int vtkAxes::ComputeDivisionExtents(vtkDataObject *vtkNotUsed(output), int idx, int numDivisions) { if (idx == 0 && numDivisions == 1) { // I will give you the whole thing return 1; } else { // I have nothing to give you for this piece. return 0; } } void vtkAxes::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Origin: (" << this->Origin[0] << ", " << this->Origin[1] << ", " << this->Origin[2] << ")\n"; os << indent << "Scale Factor: " << this->ScaleFactor << "\n"; os << indent << "Symmetric: " << this->Symmetric << "\n"; os << indent << "ComputeNormals: " << this->ComputeNormals << "\n"; } <commit_msg>STYLE: minor style fix<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkAxes.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkAxes.h" #include "vtkCellArray.h" #include "vtkFloatArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPolyData.h" vtkCxxRevisionMacro(vtkAxes, "1.45"); vtkStandardNewMacro(vtkAxes); //---------------------------------------------------------------------------- // Construct with origin=(0,0,0) and scale factor=1. vtkAxes::vtkAxes() { this->Origin[0] = 0.0; this->Origin[1] = 0.0; this->Origin[2] = 0.0; this->ScaleFactor = 1.0; this->Symmetric = 0; this->ComputeNormals = 1; this->SetNumberOfInputPorts(0); } int vtkAxes::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **vtkNotUsed(inputVector), vtkInformationVector *outputVector) { // get the info object vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the ouptut vtkPolyData *output = vtkPolyData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); int numPts=6, numLines=3; vtkPoints *newPts; vtkCellArray *newLines; vtkFloatArray *newScalars; vtkFloatArray *newNormals; double x[3], n[3]; vtkIdType ptIds[2]; vtkDebugMacro(<<"Creating x-y-z axes"); newPts = vtkPoints::New(); newPts->Allocate(numPts); newLines = vtkCellArray::New(); newLines->Allocate(newLines->EstimateSize(numLines,2)); newScalars = vtkFloatArray::New(); newScalars->Allocate(numPts); newScalars->SetName("Axes"); newNormals = vtkFloatArray::New(); newNormals->SetNumberOfComponents(3); newNormals->Allocate(numPts); newNormals->SetName("Normals"); // // Create axes // x[0] = this->Origin[0]; x[1] = this->Origin[1]; x[2] = this->Origin[2]; if (this->Symmetric) { x[0] = this->Origin[0] - this->ScaleFactor; } n[0] = 0.0; n[1] = 1.0; n[2] = 0.0; ptIds[0] = newPts->InsertNextPoint(x); newScalars->InsertNextValue(0.0); newNormals->InsertNextTuple(n); x[0] = this->Origin[0] + this->ScaleFactor; x[1] = this->Origin[1]; x[2] = this->Origin[2]; ptIds[1] = newPts->InsertNextPoint(x); newLines->InsertNextCell(2,ptIds); newScalars->InsertNextValue(0.0); newNormals->InsertNextTuple(n); x[0] = this->Origin[0]; x[1] = this->Origin[1]; x[2] = this->Origin[2]; if (this->Symmetric) { x[1] = this->Origin[1] - this->ScaleFactor; } n[0] = 0.0; n[1] = 0.0; n[2] = 1.0; ptIds[0] = newPts->InsertNextPoint(x); newScalars->InsertNextValue(0.25); newNormals->InsertNextTuple(n); x[0] = this->Origin[0]; x[1] = this->Origin[1] + this->ScaleFactor; x[2] = this->Origin[2]; ptIds[1] = newPts->InsertNextPoint(x); newScalars->InsertNextValue(0.25); newNormals->InsertNextTuple(n); newLines->InsertNextCell(2,ptIds); x[0] = this->Origin[0]; x[1] = this->Origin[1]; x[2] = this->Origin[2]; if (this->Symmetric) { x[2] = this->Origin[2] - this->ScaleFactor; } n[0] = 1.0; n[1] = 0.0; n[2] = 0.0; ptIds[0] = newPts->InsertNextPoint(x); newScalars->InsertNextValue(0.5); newNormals->InsertNextTuple(n); x[0] = this->Origin[0]; x[1] = this->Origin[1]; x[2] = this->Origin[2] + this->ScaleFactor; ptIds[1] = newPts->InsertNextPoint(x); newScalars->InsertNextValue(0.5); newNormals->InsertNextTuple(n); newLines->InsertNextCell(2,ptIds); // // Update our output and release memory // output->SetPoints(newPts); newPts->Delete(); output->GetPointData()->SetScalars(newScalars); newScalars->Delete(); if (this->ComputeNormals) { output->GetPointData()->SetNormals(newNormals); } newNormals->Delete(); output->SetLines(newLines); newLines->Delete(); return 1; } //---------------------------------------------------------------------------- // This source does not know how to generate pieces yet. int vtkAxes::ComputeDivisionExtents(vtkDataObject *vtkNotUsed(output), int idx, int numDivisions) { if (idx == 0 && numDivisions == 1) { // I will give you the whole thing return 1; } else { // I have nothing to give you for this piece. return 0; } } //---------------------------------------------------------------------------- void vtkAxes::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Origin: (" << this->Origin[0] << ", " << this->Origin[1] << ", " << this->Origin[2] << ")\n"; os << indent << "Scale Factor: " << this->ScaleFactor << "\n"; os << indent << "Symmetric: " << this->Symmetric << "\n"; os << indent << "ComputeNormals: " << this->ComputeNormals << "\n"; } <|endoftext|>
<commit_before>/* * Copyright 2010 Martin Hebnes Pedersen, martinhpedersen @ "google mail" * All rights reserved. Distributed under the terms of the MIT License. */ #include "HTGTweetTextView.h" static size_t WriteUrlCallback(void *ptr, size_t size, size_t nmemb, void *data); status_t _threadDownloadLinkIconURLs(void *data); HTGTweetTextView::HTGTweetTextView(BRect frame, const char *name, BRect textRect, uint32 resizingMode, uint32 flags) : BTextView(frame, name, textRect, resizingMode, flags) { tweetId = std::string(""); urls = new BList(); } HTGTweetTextView::HTGTweetTextView(BRect frame, const char *name, BRect textRect, const BFont* font, const rgb_color* color, uint32 resizingMode, uint32 flags) : BTextView(frame, name, textRect, font, color, resizingMode, flags) { tweetId = std::string(""); } void HTGTweetTextView::setTweetId(const char* tweetId) { this->tweetId = std::string(tweetId); } /*This function is not in use, but I'm keeping it around for now*/ void HTGTweetTextView::parseForUrlsAndDownloadIcons() { /*Kill the update thread and clean up*/ kill_thread(currentThread); for(int i = 0; i < urls->CountItems(); i++) { delete (HTGTweetMenuItem* )urls->RemoveItem(i); } delete urls; urls = getUrls(); currentThread = spawn_thread(_threadDownloadLinkIconURLs, "favIcon downloader", 10, this); resume_thread(currentThread); } void HTGTweetTextView::MouseDown(BPoint point) { int32 buttons; Window()->CurrentMessage()->FindInt32("buttons", &buttons); if ((buttons & B_SECONDARY_MOUSE_BUTTON) != 0) { ConvertToScreen(&point); BPopUpMenu *myPopUp = new BPopUpMenu("TweetOptions", false, true, B_ITEMS_IN_COLUMN); int32 selectionStart; int32 selectionFinish; GetSelection(&selectionStart, &selectionFinish); if((selectionFinish - selectionStart) > 0) { myPopUp->AddItem(new HTGTweetMenuItem("Copy", new BMessage(B_COPY))); myPopUp->AddSeparatorItem(); } myPopUp->AddItem(new HTGTweetMenuItem("Retweet...", new BMessage(GO_RETWEET))); myPopUp->AddItem(new HTGTweetMenuItem("Reply...", new BMessage(GO_REPLY))); myPopUp->AddSeparatorItem(); BList *screenNameList = this->getScreenNames(); for(int i = 0; i < screenNameList->CountItems(); i++) myPopUp->AddItem((HTGTweetMenuItem *)screenNameList->ItemAt(i)); //urls = getUrls(); //currentThread = spawn_thread(_threadDownloadLinkIconURLs, "favIcon downloader", 10, this); //resume_thread(currentThread); if(urls->CountItems() > 0) myPopUp->AddSeparatorItem(); for(int i = 0; i < urls->CountItems(); i++) { myPopUp->AddItem((HTGTweetMenuItem *)urls->ItemAt(i)); } BList *tagList = this->getTags(); if(tagList->CountItems() > 0) myPopUp->AddSeparatorItem(); for(int i = 0; i < tagList->CountItems(); i++) myPopUp->AddItem((HTGTweetMenuItem *)tagList->ItemAt(i)); myPopUp->SetAsyncAutoDestruct(true); myPopUp->SetTargetForItems(BMessenger(this)); myPopUp->Go(point+BPoint(1,1), true, true, true); } else BTextView::MouseDown(point); } BList* HTGTweetTextView::getScreenNames() { BList *theList = new BList(); std::string tweetersName(this->Name()); tweetersName.insert(0, "@"); tweetersName.append("..."); BMessage *firstMessage = new BMessage(GO_USER); firstMessage->AddString("text", this->Name()); theList->AddItem(new HTGTweetMenuItem(tweetersName.c_str(), firstMessage)); for(int i = 0; Text()[i] != '\0'; i++) { if(Text()[i] == '@') { i++; //Skip leading '@' std::string newName(""); while(isValidScreenNameChar(Text()[i])) { newName.append(1, Text()[i]); i++; } BMessage *theMessage = new BMessage(GO_USER); theMessage->AddString("text", newName.c_str()); newName.insert(0, "@"); newName.append("..."); theList->AddItem(new HTGTweetMenuItem(newName.c_str(), theMessage)); } } return theList; } BList* HTGTweetTextView::getUrls() { BList *theList = new BList(); size_t pos = 0; std::string theText(this->Text()); /*Search for :// (URIs)*/ while(pos != std::string::npos) { pos = theText.find("://", pos); if(pos != std::string::npos) { int start = pos; int end = pos; while(start >= 0 && theText[start] != ' ' && theText[start] != '\n' && theText[start] > 0) { start--; } while(end < theText.length() && theText[end] != ' ') { end++; } BMessage *theMessage = new BMessage(GO_TO_URL); theMessage->AddString("url", theText.substr(start+1, end-start-1).c_str()); theList->AddItem(new HTGTweetMenuItem(theText.substr(start+1, end-start-1).c_str(), theMessage)); pos = end; } } /*Search for www.*/ pos = 0; while(pos != std::string::npos) { pos = theText.find("www.", pos); if(theText.find("://", pos-3, 3) != std::string::npos) //So we don't add URL's detected from the method above. pos++; else if (pos != std::string::npos) { int start = pos; int end = pos; while(end < theText.length() && theText[end] != ' ') { end++; } BMessage *theMessage = new BMessage(GO_TO_URL); std::string httpString(theText.substr(start, end-start).c_str()); httpString.insert(0, "http://"); //Add the http:// prefix. theMessage->AddString("url", httpString.c_str()); theList->AddItem(new HTGTweetMenuItem(httpString.c_str(), theMessage)); pos = end; } } return theList; } BList* HTGTweetTextView::getTags() { BList *theList = new BList(); size_t pos = 0; std::string theText(this->Text()); while(pos != std::string::npos) { pos = theText.find("#", pos); if(pos != std::string::npos) { int start = pos; int end = pos; while(end < theText.length() && theText[end] != ' ' && theText[end] != '\n') { end++; } if(end == theText.length()-2) //For some reason, we have to do this. end--; BMessage *theMessage = new BMessage(GO_SEARCH); theMessage->AddString("text", theText.substr(start, end-start).c_str()); theList->AddItem(new HTGTweetMenuItem(theText.substr(start, end-start).c_str(), theMessage)); pos = end; } } return theList; } bool HTGTweetTextView::isValidScreenNameChar(const char& c) { if(c <= 'z' && c >= 'a') return true; if(c <= 'Z' && c >= 'A') return true; if(c <= '9' && c >= '0') return true; if(c == '_') return true; return false; } void HTGTweetTextView::sendRetweetMsgToParent() { BMessage *retweetMsg = new BMessage(NEW_TWEET); std::string RTString(this->Text()); RTString.insert(0, ": "); RTString.insert(0, this->Name()); RTString.insert(0, "@"); RTString.insert(0, "♺ "); retweetMsg->AddString("text", RTString.c_str()); retweetMsg->AddString("reply_to_id", tweetId.c_str()); BTextView::MessageReceived(retweetMsg); } void HTGTweetTextView::sendReplyMsgToParent() { BMessage *replyMsg = new BMessage(NEW_TWEET); std::string theString(" "); theString.insert(0, this->Name()); theString.insert(0, "@"); replyMsg->AddString("text", theString.c_str()); replyMsg->AddString("reply_to_id", tweetId.c_str()); BTextView::MessageReceived(replyMsg); } void HTGTweetTextView::MessageReceived(BMessage *msg) { const char* url_label = "url"; const char* name_label = "screenName"; std::string newTweetAppend(" "); switch(msg->what) { case GO_RETWEET: this->sendRetweetMsgToParent(); break; case GO_REPLY: this->sendReplyMsgToParent(); break; case GO_TO_URL: this->openUrl(msg->FindString(url_label, (int32)0)); break; default: BTextView::MessageReceived(msg); } } void HTGTweetTextView::openUrl(const char *url) { // be lazy and let /bin/open open the URL entry_ref ref; if (get_ref_for_path("/bin/open", &ref)) return; const char* args[] = { "/bin/open", url, NULL }; be_roster->Launch(&ref, 2, args); } HTGTweetTextView::~HTGTweetTextView() { /*Kill the update thread*/ kill_thread(currentThread); } status_t _threadDownloadLinkIconURLs(void *data) { HTGTweetTextView *super = (HTGTweetTextView*)data; CURL *curl_handle; BMallocIO *mallocIO = NULL; HTGTweetMenuItem* currentItem = NULL; for(int i = 0; i < super->urls->CountItems(); i++) { currentItem = (HTGTweetMenuItem *)super->urls->ItemAt(i); char hei[1000]; curl_global_init(CURL_GLOBAL_ALL); curl_handle = curl_easy_init(); curl_easy_setopt(curl_handle, CURLOPT_URL, currentItem->Label()); curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl_handle, CURLOPT_HEADER, 1); /*send all data to this function*/ curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteUrlCallback); /*we pass out 'mallocIO' object to the callback function*/ mallocIO = new BMallocIO(); curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)mallocIO); curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "haikutwitter-agent/1.0"); /*get the data*/ if(curl_easy_perform(curl_handle) < 0) std::cout << "libcURL: Download of linked page failed." << std::endl; /*cleanup curl stuff*/ curl_easy_cleanup(curl_handle); char *rawData = (char *)mallocIO->Buffer(); rawData[mallocIO->BufferLength()-1] = '\0'; std::string replyMsg(rawData); /*Parse for base-url*/ std::string location(currentItem->Label()); int pos = 0; while(pos != std::string::npos) { pos = location.find("http://", pos); if(pos != std::string::npos) { int end = location.find("/", pos+8); location = location.substr(pos, end-pos); pos = end; i++; } } /*Parse for redirects (Location: http://)*/ const char *queryTag = "Location: http://"; pos = 0; while(pos != std::string::npos) { pos = replyMsg.find(queryTag, pos); if(pos != std::string::npos) { int start = pos+strlen(queryTag)-7; int end = replyMsg.find("/", start+8); location = replyMsg.substr(start, end-start); pos = end; i++; } } /*Parse for url to favIcon*/ //<link rel="shortcut icon" href="http://static.ak.fbcdn.net/rsrc.php/z9Q0Q/hash/8yhim1ep.ico" /> queryTag = "shortcut icon\" href=\""; pos = 0; while(pos != std::string::npos) { pos = replyMsg.find(queryTag, pos); if(pos != std::string::npos) { int start = pos+strlen(queryTag); int end = replyMsg.find(".ico", start)+4; if(end == std::string::npos+4) break; std::string searchQuery(replyMsg.substr(start, end-start)); if(searchQuery[0] != 'h') { //URL is relative, add the guessed location from above searchQuery.insert(0, "/"); searchQuery.insert(0, location); std::cout << searchQuery << std::endl; } currentItem->setLinkIconUrl(searchQuery); std::cout << "Detected icon at: " << searchQuery << std::endl; pos = end; i++; } } /*Delete the buffer*/ delete mallocIO; } return B_OK; } /*Callback function for cURL (favIcon download)*/ static size_t WriteUrlCallback(void *ptr, size_t size, size_t nmemb, void *data) { size_t realsize = size *nmemb; BMallocIO *mallocIO = (BMallocIO *)data; size_t written = mallocIO->Write(ptr, realsize); /*Only download head*/ char *rawData = (char *)mallocIO->Buffer(); std::string replyMsg(rawData, mallocIO->BufferLength()); if(replyMsg.find("</head>") != std::string::npos) return 0; if(mallocIO->BufferLength() > 10000) {//We don't want to download large files. std::cout << "Aborting search for URL icon: Too large file" << std::endl; return 0; } else return written; } <commit_msg>Woops, forgot to uncomment.<commit_after>/* * Copyright 2010 Martin Hebnes Pedersen, martinhpedersen @ "google mail" * All rights reserved. Distributed under the terms of the MIT License. */ #include "HTGTweetTextView.h" static size_t WriteUrlCallback(void *ptr, size_t size, size_t nmemb, void *data); status_t _threadDownloadLinkIconURLs(void *data); HTGTweetTextView::HTGTweetTextView(BRect frame, const char *name, BRect textRect, uint32 resizingMode, uint32 flags) : BTextView(frame, name, textRect, resizingMode, flags) { tweetId = std::string(""); urls = new BList(); } HTGTweetTextView::HTGTweetTextView(BRect frame, const char *name, BRect textRect, const BFont* font, const rgb_color* color, uint32 resizingMode, uint32 flags) : BTextView(frame, name, textRect, font, color, resizingMode, flags) { tweetId = std::string(""); } void HTGTweetTextView::setTweetId(const char* tweetId) { this->tweetId = std::string(tweetId); } /*This function is not in use, but I'm keeping it around for now*/ void HTGTweetTextView::parseForUrlsAndDownloadIcons() { /*Kill the update thread and clean up*/ kill_thread(currentThread); for(int i = 0; i < urls->CountItems(); i++) { delete (HTGTweetMenuItem* )urls->RemoveItem(i); } delete urls; urls = getUrls(); currentThread = spawn_thread(_threadDownloadLinkIconURLs, "favIcon downloader", 10, this); resume_thread(currentThread); } void HTGTweetTextView::MouseDown(BPoint point) { int32 buttons; Window()->CurrentMessage()->FindInt32("buttons", &buttons); if ((buttons & B_SECONDARY_MOUSE_BUTTON) != 0) { ConvertToScreen(&point); BPopUpMenu *myPopUp = new BPopUpMenu("TweetOptions", false, true, B_ITEMS_IN_COLUMN); int32 selectionStart; int32 selectionFinish; GetSelection(&selectionStart, &selectionFinish); if((selectionFinish - selectionStart) > 0) { myPopUp->AddItem(new HTGTweetMenuItem("Copy", new BMessage(B_COPY))); myPopUp->AddSeparatorItem(); } myPopUp->AddItem(new HTGTweetMenuItem("Retweet...", new BMessage(GO_RETWEET))); myPopUp->AddItem(new HTGTweetMenuItem("Reply...", new BMessage(GO_REPLY))); myPopUp->AddSeparatorItem(); BList *screenNameList = this->getScreenNames(); for(int i = 0; i < screenNameList->CountItems(); i++) myPopUp->AddItem((HTGTweetMenuItem *)screenNameList->ItemAt(i)); urls = getUrls(); currentThread = spawn_thread(_threadDownloadLinkIconURLs, "favIcon downloader", 10, this); resume_thread(currentThread); if(urls->CountItems() > 0) myPopUp->AddSeparatorItem(); for(int i = 0; i < urls->CountItems(); i++) { myPopUp->AddItem((HTGTweetMenuItem *)urls->ItemAt(i)); } BList *tagList = this->getTags(); if(tagList->CountItems() > 0) myPopUp->AddSeparatorItem(); for(int i = 0; i < tagList->CountItems(); i++) myPopUp->AddItem((HTGTweetMenuItem *)tagList->ItemAt(i)); myPopUp->SetAsyncAutoDestruct(true); myPopUp->SetTargetForItems(BMessenger(this)); myPopUp->Go(point+BPoint(1,1), true, true, true); } else BTextView::MouseDown(point); } BList* HTGTweetTextView::getScreenNames() { BList *theList = new BList(); std::string tweetersName(this->Name()); tweetersName.insert(0, "@"); tweetersName.append("..."); BMessage *firstMessage = new BMessage(GO_USER); firstMessage->AddString("text", this->Name()); theList->AddItem(new HTGTweetMenuItem(tweetersName.c_str(), firstMessage)); for(int i = 0; Text()[i] != '\0'; i++) { if(Text()[i] == '@') { i++; //Skip leading '@' std::string newName(""); while(isValidScreenNameChar(Text()[i])) { newName.append(1, Text()[i]); i++; } BMessage *theMessage = new BMessage(GO_USER); theMessage->AddString("text", newName.c_str()); newName.insert(0, "@"); newName.append("..."); theList->AddItem(new HTGTweetMenuItem(newName.c_str(), theMessage)); } } return theList; } BList* HTGTweetTextView::getUrls() { BList *theList = new BList(); size_t pos = 0; std::string theText(this->Text()); /*Search for :// (URIs)*/ while(pos != std::string::npos) { pos = theText.find("://", pos); if(pos != std::string::npos) { int start = pos; int end = pos; while(start >= 0 && theText[start] != ' ' && theText[start] != '\n' && theText[start] > 0) { start--; } while(end < theText.length() && theText[end] != ' ') { end++; } BMessage *theMessage = new BMessage(GO_TO_URL); theMessage->AddString("url", theText.substr(start+1, end-start-1).c_str()); theList->AddItem(new HTGTweetMenuItem(theText.substr(start+1, end-start-1).c_str(), theMessage)); pos = end; } } /*Search for www.*/ pos = 0; while(pos != std::string::npos) { pos = theText.find("www.", pos); if(theText.find("://", pos-3, 3) != std::string::npos) //So we don't add URL's detected from the method above. pos++; else if (pos != std::string::npos) { int start = pos; int end = pos; while(end < theText.length() && theText[end] != ' ') { end++; } BMessage *theMessage = new BMessage(GO_TO_URL); std::string httpString(theText.substr(start, end-start).c_str()); httpString.insert(0, "http://"); //Add the http:// prefix. theMessage->AddString("url", httpString.c_str()); theList->AddItem(new HTGTweetMenuItem(httpString.c_str(), theMessage)); pos = end; } } return theList; } BList* HTGTweetTextView::getTags() { BList *theList = new BList(); size_t pos = 0; std::string theText(this->Text()); while(pos != std::string::npos) { pos = theText.find("#", pos); if(pos != std::string::npos) { int start = pos; int end = pos; while(end < theText.length() && theText[end] != ' ' && theText[end] != '\n') { end++; } if(end == theText.length()-2) //For some reason, we have to do this. end--; BMessage *theMessage = new BMessage(GO_SEARCH); theMessage->AddString("text", theText.substr(start, end-start).c_str()); theList->AddItem(new HTGTweetMenuItem(theText.substr(start, end-start).c_str(), theMessage)); pos = end; } } return theList; } bool HTGTweetTextView::isValidScreenNameChar(const char& c) { if(c <= 'z' && c >= 'a') return true; if(c <= 'Z' && c >= 'A') return true; if(c <= '9' && c >= '0') return true; if(c == '_') return true; return false; } void HTGTweetTextView::sendRetweetMsgToParent() { BMessage *retweetMsg = new BMessage(NEW_TWEET); std::string RTString(this->Text()); RTString.insert(0, ": "); RTString.insert(0, this->Name()); RTString.insert(0, "@"); RTString.insert(0, "♺ "); retweetMsg->AddString("text", RTString.c_str()); retweetMsg->AddString("reply_to_id", tweetId.c_str()); BTextView::MessageReceived(retweetMsg); } void HTGTweetTextView::sendReplyMsgToParent() { BMessage *replyMsg = new BMessage(NEW_TWEET); std::string theString(" "); theString.insert(0, this->Name()); theString.insert(0, "@"); replyMsg->AddString("text", theString.c_str()); replyMsg->AddString("reply_to_id", tweetId.c_str()); BTextView::MessageReceived(replyMsg); } void HTGTweetTextView::MessageReceived(BMessage *msg) { const char* url_label = "url"; const char* name_label = "screenName"; std::string newTweetAppend(" "); switch(msg->what) { case GO_RETWEET: this->sendRetweetMsgToParent(); break; case GO_REPLY: this->sendReplyMsgToParent(); break; case GO_TO_URL: this->openUrl(msg->FindString(url_label, (int32)0)); break; default: BTextView::MessageReceived(msg); } } void HTGTweetTextView::openUrl(const char *url) { // be lazy and let /bin/open open the URL entry_ref ref; if (get_ref_for_path("/bin/open", &ref)) return; const char* args[] = { "/bin/open", url, NULL }; be_roster->Launch(&ref, 2, args); } HTGTweetTextView::~HTGTweetTextView() { /*Kill the update thread*/ kill_thread(currentThread); } status_t _threadDownloadLinkIconURLs(void *data) { HTGTweetTextView *super = (HTGTweetTextView*)data; CURL *curl_handle; BMallocIO *mallocIO = NULL; HTGTweetMenuItem* currentItem = NULL; for(int i = 0; i < super->urls->CountItems(); i++) { currentItem = (HTGTweetMenuItem *)super->urls->ItemAt(i); char hei[1000]; curl_global_init(CURL_GLOBAL_ALL); curl_handle = curl_easy_init(); curl_easy_setopt(curl_handle, CURLOPT_URL, currentItem->Label()); curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl_handle, CURLOPT_HEADER, 1); /*send all data to this function*/ curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteUrlCallback); /*we pass out 'mallocIO' object to the callback function*/ mallocIO = new BMallocIO(); curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)mallocIO); curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "haikutwitter-agent/1.0"); /*get the data*/ if(curl_easy_perform(curl_handle) < 0) std::cout << "libcURL: Download of linked page failed." << std::endl; /*cleanup curl stuff*/ curl_easy_cleanup(curl_handle); char *rawData = (char *)mallocIO->Buffer(); rawData[mallocIO->BufferLength()-1] = '\0'; std::string replyMsg(rawData); /*Parse for base-url*/ std::string location(currentItem->Label()); int pos = 0; while(pos != std::string::npos) { pos = location.find("http://", pos); if(pos != std::string::npos) { int end = location.find("/", pos+8); location = location.substr(pos, end-pos); pos = end; i++; } } /*Parse for redirects (Location: http://)*/ const char *queryTag = "Location: http://"; pos = 0; while(pos != std::string::npos) { pos = replyMsg.find(queryTag, pos); if(pos != std::string::npos) { int start = pos+strlen(queryTag)-7; int end = replyMsg.find("/", start+8); location = replyMsg.substr(start, end-start); pos = end; i++; } } /*Parse for url to favIcon*/ //<link rel="shortcut icon" href="http://static.ak.fbcdn.net/rsrc.php/z9Q0Q/hash/8yhim1ep.ico" /> queryTag = "shortcut icon\" href=\""; pos = 0; while(pos != std::string::npos) { pos = replyMsg.find(queryTag, pos); if(pos != std::string::npos) { int start = pos+strlen(queryTag); int end = replyMsg.find(".ico", start)+4; if(end == std::string::npos+4) break; std::string searchQuery(replyMsg.substr(start, end-start)); if(searchQuery[0] != 'h') { //URL is relative, add the guessed location from above searchQuery.insert(0, "/"); searchQuery.insert(0, location); std::cout << searchQuery << std::endl; } currentItem->setLinkIconUrl(searchQuery); std::cout << "Detected icon at: " << searchQuery << std::endl; pos = end; i++; } } /*Delete the buffer*/ delete mallocIO; } return B_OK; } /*Callback function for cURL (favIcon download)*/ static size_t WriteUrlCallback(void *ptr, size_t size, size_t nmemb, void *data) { size_t realsize = size *nmemb; BMallocIO *mallocIO = (BMallocIO *)data; size_t written = mallocIO->Write(ptr, realsize); /*Only download head*/ char *rawData = (char *)mallocIO->Buffer(); std::string replyMsg(rawData, mallocIO->BufferLength()); if(replyMsg.find("</head>") != std::string::npos) return 0; if(mallocIO->BufferLength() > 10000) {//We don't want to download large files. std::cout << "Aborting search for URL icon: Too large file" << std::endl; return 0; } else return written; } <|endoftext|>
<commit_before><commit_msg>cppcheck: redundantAssignment<commit_after><|endoftext|>
<commit_before>// Copyright (c) Microsoft. All rights reserved. // // i2ctesttool // // Utility to read and write I2C devices from the command line. // Shows how to use C++/CX in console applications. // #include <ppltasks.h> #include <string> #include <vector> #include <sstream> #include <iostream> #include <cwctype> using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Devices::I2c; class wexception { public: explicit wexception (const std::wstring &msg) : msg_(msg) { } virtual ~wexception () { /*empty*/ } virtual const wchar_t *wwhat () const { return msg_.c_str(); } private: std::wstring msg_; }; I2cDevice^ MakeDevice (int slaveAddress, _In_opt_ String^ friendlyName) { using namespace Windows::Devices::Enumeration; String^ aqs; if (friendlyName) aqs = I2cDevice::GetDeviceSelector(friendlyName); else aqs = I2cDevice::GetDeviceSelector(); auto dis = concurrency::create_task(DeviceInformation::FindAllAsync(aqs)).get(); if (dis->Size != 1) { throw wexception(L"I2C bus not found"); } String^ id = dis->GetAt(0)->Id; auto device = concurrency::create_task(I2cDevice::FromIdAsync( id, ref new I2cConnectionSettings(slaveAddress))).get(); if (!device) { std::wostringstream msg; msg << L"Slave address 0x" << std::hex << slaveAddress << L" on bus " << id->Data() << L" is in use. Please ensure that no other applications are using I2C."; throw wexception(msg.str()); } return device; } std::wostream& operator<< (std::wostream& os, const I2cTransferResult& result) { switch (result.Status) { case I2cTransferStatus::FullTransfer: break; case I2cTransferStatus::PartialTransfer: os << L"Partial Transfer. Transferred " << result.BytesTransferred << L" bytes\n"; break; case I2cTransferStatus::SlaveAddressNotAcknowledged: os << L"Slave address was not acknowledged\n"; break; default: throw wexception(L"Invalid transfer status value"); } return os; } std::wistream& expect (std::wistream& is, wchar_t delim) { wchar_t ch; while (is.get(ch)) { if (ch == delim) return is; if (!isspace(ch)) { is.clear(is.failbit); break; } } return is; } std::wistream& operator>> (std::wistream& is, std::vector<BYTE>& bytes) { bytes.clear(); if (!expect(is, L'{')) { std::wcout << L"Syntax error: expecting '{'\n"; return is; } // get a sequence of bytes, e.g. // write { 0 1 2 3 4 aa bb cc dd } unsigned int byte; while (is >> std::hex >> byte) { if (byte > 0xff) { std::wcout << L"Out of range [0, 0xff]: " << std::hex << byte << L"\n"; is.clear(is.failbit); return is; } bytes.push_back(static_cast<BYTE>(byte)); } if (bytes.empty()) { std::wcout << L"Zero-length buffers are not allowed\n"; is.clear(is.failbit); return is; } is.clear(); if (!expect(is, L'}')) { std::wcout << L"Syntax error: expecting '}'\n"; return is; } return is; } std::wostream& operator<< (std::wostream& os, const Platform::Array<BYTE>^ bytes) { for (auto byte : bytes) os << L" " << std::hex << byte; return os; } std::wostream& operator<< (std::wostream& os, I2cBusSpeed busSpeed) { switch (busSpeed) { case I2cBusSpeed::StandardMode: return os << L"StandardMode (100Khz)"; case I2cBusSpeed::FastMode: return os << L"FastMode (400kHz)"; default: return os << L"[Invalid bus speed]"; } } PCWSTR Help = L"Commands:\n" L" > write { 00 11 22 .. FF } Write bytes to device\n" L" > read N Read N bytes\n" L" > writeread { 00 11 .. FF } N Write bytes, restart, read N bytes\n" L" > info Display device information\n" L" > help Display this help message\n" L" > quit Quit\n\n"; void ShowPrompt (I2cDevice^ device) { while (std::wcin) { std::wcout << L"> "; std::wstring line; if (!std::getline(std::wcin, line)) { return; } std::wistringstream linestream(line); std::wstring command; linestream >> command; if ((command == L"q") || (command == L"quit")) { return; } else if ((command == L"h") || (command == L"help")) { std::wcout << Help; } else if (command == L"write") { std::vector<BYTE> writeBuf; if (!(linestream >> writeBuf)) { std::wcout << L"Usage: write { 55 a0 ... ff }\n"; continue; } I2cTransferResult result = device->WritePartial( ArrayReference<BYTE>( writeBuf.data(), static_cast<unsigned int>(writeBuf.size()))); switch (result.Status) { case I2cTransferStatus::FullTransfer: break; case I2cTransferStatus::PartialTransfer: std::wcout << L"Partial Transfer. Transferred " << result.BytesTransferred << L" bytes\n"; break; case I2cTransferStatus::SlaveAddressNotAcknowledged: std::wcout << L"Slave address was not acknowledged\n"; break; default: throw wexception(L"Invalid transfer status value"); } } else if (command == L"read") { // expecting a single int, number of bytes to read unsigned int bytesToRead; if (!(linestream >> std::dec >> bytesToRead)) { std::wcout << L"Expecting integer. e.g: read 4\n"; continue; } auto readBuf = ref new Platform::Array<BYTE>(bytesToRead); I2cTransferResult result = device->ReadPartial(readBuf); switch (result.Status) { case I2cTransferStatus::FullTransfer: std::wcout << readBuf << L"\n"; break; case I2cTransferStatus::PartialTransfer: std::wcout << L"Partial Transfer. Transferred " << result.BytesTransferred << L" bytes\n"; std::wcout << readBuf << L"\n"; break; case I2cTransferStatus::SlaveAddressNotAcknowledged: std::wcout << L"Slave address was not acknowledged\n"; break; default: throw wexception(L"Invalid transfer status value"); } } else if (command == L"writeread") { // get a sequence of bytes, e.g. // write 0 1 2 3 4 aa bb cc dd std::vector<BYTE> writeBuf; if (!(linestream >> writeBuf)) { std::wcout << L"Usage: writeread { 55 a0 ... ff } 4\n"; continue; } unsigned int bytesToRead; if (!(linestream >> std::dec >> bytesToRead)) { std::wcout << L"Syntax error: expecting integer\n"; std::wcout << L"Usage: writeread { 55 a0 ... ff } 4\n"; continue; } auto readBuf = ref new Array<BYTE>(bytesToRead); I2cTransferResult result = device->WriteReadPartial( ArrayReference<BYTE>( writeBuf.data(), static_cast<unsigned int>(writeBuf.size())), readBuf); switch (result.Status) { case I2cTransferStatus::FullTransfer: std::wcout << readBuf << L"\n"; break; case I2cTransferStatus::PartialTransfer: { std::wcout << L"Partial Transfer. Transferred " << result.BytesTransferred << L" bytes\n"; int bytesRead = result.BytesTransferred - int(writeBuf.size()); if (bytesRead > 0) { std::wcout << readBuf << L"\n"; } break; } case I2cTransferStatus::SlaveAddressNotAcknowledged: std::wcout << L"Slave address was not acknowledged\n"; break; default: throw wexception(L"Invalid transfer status value"); } } else if (command == L"info") { int slaveAddress = device->ConnectionSettings->SlaveAddress; I2cBusSpeed busSpeed = device->ConnectionSettings->BusSpeed; std::wcout << L" DeviceId: " << device->DeviceId->Data() << "\n"; std::wcout << L" Slave address: 0x" << std::hex << slaveAddress << L"\n"; std::wcout << L" Bus Speed: " << busSpeed << L"\n"; } else if (command.empty()) { // ignore } else { std::wcout << L"Unrecognized command: " << command << L". Type 'help' for command usage.\n"; } } } void PrintUsage (PCWSTR name) { wprintf( L"I2cTestTool: Command line I2C testing utility\n" L"Usage: %s SlaveAddress [FriendlyName]\n" L"\n" L" SlaveAddress The slave address of the device with which you\n" L" wish to communicate. This is a required parameter.\n" L" FriendlyName The friendly name of the I2C controller over\n" L" which you wish to communicate. This parameter is\n" L" optional and defaults to the first enumerated\n" L" I2C controller.\n" L"\n" L"Examples:\n" L" %s 0x57\n" L" %s 0x57 I2C1\n", name, name, name); } int main (Platform::Array<Platform::String^>^ args) { unsigned int optind = 1; if (optind < args->Length) { if ((args->get(optind) == L"-h") || (args->get(optind) == L"-?")) { PrintUsage(args->get(0)->Data()); return 0; } } else { std::wcerr << L"Missing required command line parameter SlaveAddress\n\n"; PrintUsage(args->get(0)->Data()); return 1; } int slaveAddress; { String^ arg = args->get(optind++); wchar_t *endptr; slaveAddress = int(wcstoul(arg->Data(), &endptr, 0)); if (endptr != arg->End()) { std::wcerr << L"Expecting integer: " << arg->Data() << L"\n"; std::wcerr << L"Type '" << args->get(0)->Data() << " -h' for usage\n"; return 1; } } String^ friendlyName; if (optind < args->Length) { friendlyName = args->get(optind++); } try { auto device = MakeDevice(slaveAddress, friendlyName); std::wcout << L" Type 'help' for a list of commands\n"; ShowPrompt(device); } catch (const wexception& ex) { std::wcerr << L"Error: " << ex.wwhat() << L"\n"; return 1; } catch (Platform::Exception^ ex) { std::wcerr << L"Error: " << ex->Message->Data() << L"\n"; return 1; } return 0; } <commit_msg>Enable I2cTestTool to work with first enumerated device.<commit_after>// Copyright (c) Microsoft. All rights reserved. // // i2ctesttool // // Utility to read and write I2C devices from the command line. // Shows how to use C++/CX in console applications. // #include <ppltasks.h> #include <string> #include <vector> #include <sstream> #include <iostream> #include <cwctype> using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Devices::I2c; class wexception { public: explicit wexception (const std::wstring &msg) : msg_(msg) { } virtual ~wexception () { /*empty*/ } virtual const wchar_t *wwhat () const { return msg_.c_str(); } private: std::wstring msg_; }; I2cDevice^ MakeDevice (int slaveAddress, _In_opt_ String^ friendlyName) { using namespace Windows::Devices::Enumeration; String^ aqs; if (friendlyName) aqs = I2cDevice::GetDeviceSelector(friendlyName); else aqs = I2cDevice::GetDeviceSelector(); auto dis = concurrency::create_task(DeviceInformation::FindAllAsync(aqs)).get(); if (dis->Size < 1) { throw wexception(L"I2C bus not found"); } String^ id = dis->GetAt(0)->Id; auto device = concurrency::create_task(I2cDevice::FromIdAsync( id, ref new I2cConnectionSettings(slaveAddress))).get(); if (!device) { std::wostringstream msg; msg << L"Slave address 0x" << std::hex << slaveAddress << L" on bus " << id->Data() << L" is in use. Please ensure that no other applications are using I2C."; throw wexception(msg.str()); } return device; } std::wostream& operator<< (std::wostream& os, const I2cTransferResult& result) { switch (result.Status) { case I2cTransferStatus::FullTransfer: break; case I2cTransferStatus::PartialTransfer: os << L"Partial Transfer. Transferred " << result.BytesTransferred << L" bytes\n"; break; case I2cTransferStatus::SlaveAddressNotAcknowledged: os << L"Slave address was not acknowledged\n"; break; default: throw wexception(L"Invalid transfer status value"); } return os; } std::wistream& expect (std::wistream& is, wchar_t delim) { wchar_t ch; while (is.get(ch)) { if (ch == delim) return is; if (!isspace(ch)) { is.clear(is.failbit); break; } } return is; } std::wistream& operator>> (std::wistream& is, std::vector<BYTE>& bytes) { bytes.clear(); if (!expect(is, L'{')) { std::wcout << L"Syntax error: expecting '{'\n"; return is; } // get a sequence of bytes, e.g. // write { 0 1 2 3 4 aa bb cc dd } unsigned int byte; while (is >> std::hex >> byte) { if (byte > 0xff) { std::wcout << L"Out of range [0, 0xff]: " << std::hex << byte << L"\n"; is.clear(is.failbit); return is; } bytes.push_back(static_cast<BYTE>(byte)); } if (bytes.empty()) { std::wcout << L"Zero-length buffers are not allowed\n"; is.clear(is.failbit); return is; } is.clear(); if (!expect(is, L'}')) { std::wcout << L"Syntax error: expecting '}'\n"; return is; } return is; } std::wostream& operator<< (std::wostream& os, const Platform::Array<BYTE>^ bytes) { for (auto byte : bytes) os << L" " << std::hex << byte; return os; } std::wostream& operator<< (std::wostream& os, I2cBusSpeed busSpeed) { switch (busSpeed) { case I2cBusSpeed::StandardMode: return os << L"StandardMode (100Khz)"; case I2cBusSpeed::FastMode: return os << L"FastMode (400kHz)"; default: return os << L"[Invalid bus speed]"; } } PCWSTR Help = L"Commands:\n" L" > write { 00 11 22 .. FF } Write bytes to device\n" L" > read N Read N bytes\n" L" > writeread { 00 11 .. FF } N Write bytes, restart, read N bytes\n" L" > info Display device information\n" L" > help Display this help message\n" L" > quit Quit\n\n"; void ShowPrompt (I2cDevice^ device) { while (std::wcin) { std::wcout << L"> "; std::wstring line; if (!std::getline(std::wcin, line)) { return; } std::wistringstream linestream(line); std::wstring command; linestream >> command; if ((command == L"q") || (command == L"quit")) { return; } else if ((command == L"h") || (command == L"help")) { std::wcout << Help; } else if (command == L"write") { std::vector<BYTE> writeBuf; if (!(linestream >> writeBuf)) { std::wcout << L"Usage: write { 55 a0 ... ff }\n"; continue; } I2cTransferResult result = device->WritePartial( ArrayReference<BYTE>( writeBuf.data(), static_cast<unsigned int>(writeBuf.size()))); switch (result.Status) { case I2cTransferStatus::FullTransfer: break; case I2cTransferStatus::PartialTransfer: std::wcout << L"Partial Transfer. Transferred " << result.BytesTransferred << L" bytes\n"; break; case I2cTransferStatus::SlaveAddressNotAcknowledged: std::wcout << L"Slave address was not acknowledged\n"; break; default: throw wexception(L"Invalid transfer status value"); } } else if (command == L"read") { // expecting a single int, number of bytes to read unsigned int bytesToRead; if (!(linestream >> std::dec >> bytesToRead)) { std::wcout << L"Expecting integer. e.g: read 4\n"; continue; } auto readBuf = ref new Platform::Array<BYTE>(bytesToRead); I2cTransferResult result = device->ReadPartial(readBuf); switch (result.Status) { case I2cTransferStatus::FullTransfer: std::wcout << readBuf << L"\n"; break; case I2cTransferStatus::PartialTransfer: std::wcout << L"Partial Transfer. Transferred " << result.BytesTransferred << L" bytes\n"; std::wcout << readBuf << L"\n"; break; case I2cTransferStatus::SlaveAddressNotAcknowledged: std::wcout << L"Slave address was not acknowledged\n"; break; default: throw wexception(L"Invalid transfer status value"); } } else if (command == L"writeread") { // get a sequence of bytes, e.g. // write 0 1 2 3 4 aa bb cc dd std::vector<BYTE> writeBuf; if (!(linestream >> writeBuf)) { std::wcout << L"Usage: writeread { 55 a0 ... ff } 4\n"; continue; } unsigned int bytesToRead; if (!(linestream >> std::dec >> bytesToRead)) { std::wcout << L"Syntax error: expecting integer\n"; std::wcout << L"Usage: writeread { 55 a0 ... ff } 4\n"; continue; } auto readBuf = ref new Array<BYTE>(bytesToRead); I2cTransferResult result = device->WriteReadPartial( ArrayReference<BYTE>( writeBuf.data(), static_cast<unsigned int>(writeBuf.size())), readBuf); switch (result.Status) { case I2cTransferStatus::FullTransfer: std::wcout << readBuf << L"\n"; break; case I2cTransferStatus::PartialTransfer: { std::wcout << L"Partial Transfer. Transferred " << result.BytesTransferred << L" bytes\n"; int bytesRead = result.BytesTransferred - int(writeBuf.size()); if (bytesRead > 0) { std::wcout << readBuf << L"\n"; } break; } case I2cTransferStatus::SlaveAddressNotAcknowledged: std::wcout << L"Slave address was not acknowledged\n"; break; default: throw wexception(L"Invalid transfer status value"); } } else if (command == L"info") { int slaveAddress = device->ConnectionSettings->SlaveAddress; I2cBusSpeed busSpeed = device->ConnectionSettings->BusSpeed; std::wcout << L" DeviceId: " << device->DeviceId->Data() << "\n"; std::wcout << L" Slave address: 0x" << std::hex << slaveAddress << L"\n"; std::wcout << L" Bus Speed: " << busSpeed << L"\n"; } else if (command.empty()) { // ignore } else { std::wcout << L"Unrecognized command: " << command << L". Type 'help' for command usage.\n"; } } } void PrintUsage (PCWSTR name) { wprintf( L"I2cTestTool: Command line I2C testing utility\n" L"Usage: %s SlaveAddress [FriendlyName]\n" L"\n" L" SlaveAddress The slave address of the device with which you\n" L" wish to communicate. This is a required parameter.\n" L" FriendlyName The friendly name of the I2C controller over\n" L" which you wish to communicate. This parameter is\n" L" optional and defaults to the first enumerated\n" L" I2C controller.\n" L"\n" L"Examples:\n" L" %s 0x57\n" L" %s 0x57 I2C1\n", name, name, name); } int main (Platform::Array<Platform::String^>^ args) { unsigned int optind = 1; if (optind < args->Length) { if ((args->get(optind) == L"-h") || (args->get(optind) == L"-?")) { PrintUsage(args->get(0)->Data()); return 0; } } else { std::wcerr << L"Missing required command line parameter SlaveAddress\n\n"; PrintUsage(args->get(0)->Data()); return 1; } int slaveAddress; { String^ arg = args->get(optind++); wchar_t *endptr; slaveAddress = int(wcstoul(arg->Data(), &endptr, 0)); if (endptr != arg->End()) { std::wcerr << L"Expecting integer: " << arg->Data() << L"\n"; std::wcerr << L"Type '" << args->get(0)->Data() << " -h' for usage\n"; return 1; } } String^ friendlyName; if (optind < args->Length) { friendlyName = args->get(optind++); } try { auto device = MakeDevice(slaveAddress, friendlyName); std::wcout << L" Type 'help' for a list of commands\n"; ShowPrompt(device); } catch (const wexception& ex) { std::wcerr << L"Error: " << ex.wwhat() << L"\n"; return 1; } catch (Platform::Exception^ ex) { std::wcerr << L"Error: " << ex->Message->Data() << L"\n"; return 1; } return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: openCherry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "cherryDefaultSaveable.h" #include "../cherryIWorkbenchPart.h" #include "../cherryIWorkbenchPage.h" #include "../cherryUIException.h" #include "../cherryImageDescriptor.h" namespace cherry { DefaultSaveable::DefaultSaveable(IWorkbenchPart::Pointer _part) : part(_part) { } void DefaultSaveable::DoSave(/*IProgressMonitor monitor*/) { if (part.Cast<ISaveablePart> () != 0) { part.Cast<ISaveablePart>()->DoSave(/*monitor*/); } } std::string DefaultSaveable::GetName() const { return part->GetPartName(); } ImageDescriptor::Pointer DefaultSaveable::GetImageDescriptor() const { //TODO DefaultSaveable GetImageDescriptor // Image image = part.getTitleImage(); // if (image == null) // { // return null; // } // return ImageDescriptor.createFromImage(image); return ImageDescriptor::Pointer(0); } std::string DefaultSaveable::GetToolTipText() const { return part->GetTitleToolTip(); } bool DefaultSaveable::IsDirty() const { if (part.Cast<ISaveablePart> () != 0) { return part.Cast<ISaveablePart>()->IsDirty(); } return false; } bool DefaultSaveable::operator<(const Saveable* obj) const { if (this == obj) return false; if (obj == 0) return true; const DefaultSaveable* other = dynamic_cast<const DefaultSaveable*>(obj); if (part == 0) { if (other->part != 0) return true; } else return part < other->part; } bool DefaultSaveable::Show(IWorkbenchPage::Pointer page) { IWorkbenchPartReference::Pointer reference = page->GetReference(part); if (reference != 0) { page->Activate(part); return true; } if (part.Cast<IViewPart>() != 0) { IViewPart::Pointer viewPart = part.Cast<IViewPart>(); try { page->ShowView(viewPart->GetViewSite()->GetId(), viewPart ->GetViewSite()->GetSecondaryId(), IWorkbenchPage::VIEW_ACTIVATE); } catch (PartInitException& /*e*/) { return false; } return true; } return false; } } <commit_msg>COMP: fixing return value in operator<<commit_after>/*========================================================================= Program: openCherry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "cherryDefaultSaveable.h" #include "../cherryIWorkbenchPart.h" #include "../cherryIWorkbenchPage.h" #include "../cherryUIException.h" #include "../cherryImageDescriptor.h" namespace cherry { DefaultSaveable::DefaultSaveable(IWorkbenchPart::Pointer _part) : part(_part) { } void DefaultSaveable::DoSave(/*IProgressMonitor monitor*/) { if (part.Cast<ISaveablePart> () != 0) { part.Cast<ISaveablePart> ()->DoSave(/*monitor*/); } } std::string DefaultSaveable::GetName() const { return part->GetPartName(); } ImageDescriptor::Pointer DefaultSaveable::GetImageDescriptor() const { //TODO DefaultSaveable GetImageDescriptor // Image image = part.getTitleImage(); // if (image == null) // { // return null; // } // return ImageDescriptor.createFromImage(image); return ImageDescriptor::Pointer(0); } std::string DefaultSaveable::GetToolTipText() const { return part->GetTitleToolTip(); } bool DefaultSaveable::IsDirty() const { if (part.Cast<ISaveablePart> () != 0) { return part.Cast<ISaveablePart> ()->IsDirty(); } return false; } bool DefaultSaveable::operator<(const Saveable* obj) const { if (this == obj) return false; if (obj == 0) return true; const DefaultSaveable* other = dynamic_cast<const DefaultSaveable*> (obj); if (part == 0) { return other->part != 0; } else return part < other->part; } bool DefaultSaveable::Show(IWorkbenchPage::Pointer page) { IWorkbenchPartReference::Pointer reference = page->GetReference(part); if (reference != 0) { page->Activate(part); return true; } if (part.Cast<IViewPart> () != 0) { IViewPart::Pointer viewPart = part.Cast<IViewPart> (); try { page->ShowView(viewPart->GetViewSite()->GetId(), viewPart ->GetViewSite()->GetSecondaryId(), IWorkbenchPage::VIEW_ACTIVATE); } catch (PartInitException& /*e*/) { return false; } return true; } return false; } } <|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/dreamview/backend/handlers/websocket_handler.h" #include <chrono> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "modules/common/log.h" using ::testing::ElementsAre; namespace apollo { namespace dreamview { class MockClient { public: MockClient(const char *host, int port) { conn = mg_connect_websocket_client(host, port, 0, error_buffer, 100, "/websocket", "", &MockClient::OnMessage, nullptr, nullptr); CHECK_NOTNULL(conn); } const std::vector<std::string> &GetReceivedMessages() { return received_messages_; } private: static int OnMessage(struct mg_connection *conn, int bits, char *data, size_t data_len, void *cbdata) { AINFO << "Get " << *data; received_messages_.emplace_back(data); return 1; } mg_connection *conn; char error_buffer[100]; static std::vector<std::string> received_messages_; }; std::vector<std::string> MockClient::received_messages_; static WebSocketHandler handler("Test"); TEST(WebSocketTest, IntegrationTest) { // NOTE: Here a magic number is picked up as the port, which is not ideal but // in almost all cases this should be fine for a small integration test. CivetServer server({"listening_ports", "32695"}); server.addWebSocketHandler("/websocket", handler); // Wait for a small amount of time to make sure that the server is up. std::this_thread::sleep_for(std::chrono::milliseconds(300)); MockClient client("localhost", 32695); // Wait for a small amount of time to make sure that the client is up and // connected. std::this_thread::sleep_for(std::chrono::milliseconds(300)); // Send 3 messages. for (int i = 0; i < 3; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); handler.BroadcastData(std::to_string(i)); } std::this_thread::sleep_for(std::chrono::milliseconds(200)); // Check that the 3 messages are successfully received and processed. EXPECT_THAT(client.GetReceivedMessages(), ElementsAre("0", "1", "2")); } } // namespace dreamview } // namespace apollo <commit_msg>add unit test for dreamview web handler (#4900)<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/dreamview/backend/handlers/websocket_handler.h" #include <chrono> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "modules/common/log.h" using ::testing::ElementsAre; namespace apollo { namespace dreamview { class MockClient { public: MockClient(const char *host, int port) { conn = mg_connect_websocket_client(host, port, 0, error_buffer, 100, "/websocket", "", &MockClient::OnMessage, nullptr, nullptr); CHECK_NOTNULL(conn); } const std::vector<std::string> &GetReceivedMessages() { return received_messages_; } private: static int OnMessage(struct mg_connection *conn, int bits, char *data, size_t data_len, void *cbdata) { AINFO << "Get " << *data; received_messages_.emplace_back(data); return 1; } mg_connection *conn; char error_buffer[100]; static std::vector<std::string> received_messages_; }; std::vector<std::string> MockClient::received_messages_; static WebSocketHandler handler("Test"); TEST(WebSocketTest, IntegrationTest) { // NOTE: Here a magic number is picked up as the port, which is not ideal but // in almost all cases this should be fine for a small integration test. CivetServer server({"listening_ports", "32695"}); server.addWebSocketHandler("/websocket", handler); // Wait for a small amount of time to make sure that the server is up. std::this_thread::sleep_for(std::chrono::milliseconds(300)); MockClient client("localhost", 32695); // Wait for a small amount of time to make sure that the client is up and // connected. std::this_thread::sleep_for(std::chrono::milliseconds(300)); // Send 3 messages. for (int i = 0; i < 3; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); handler.BroadcastData(std::to_string(i)); } std::this_thread::sleep_for(std::chrono::milliseconds(200)); // Check that the 3 messages are successfully received and processed. EXPECT_THAT(client.GetReceivedMessages(), ElementsAre("0", "1", "2")); } TEST(WebSocketTest, handleData) { // NOTE: Here a magic number is picked up as the port, which is not ideal but // in almost all cases this should be fine for a small integration test. CivetServer server({"listening_ports", "32695"}); server.addWebSocketHandler("/websocket", handler); handler.RegisterMessageHandler("test", [this](const WebSocketHandler::Json &json, WebSocketHandler::Connection *conn) { AINFO << "Received test request."; }); // Wait for a small amount of time to make sure that the server is up. std::this_thread::sleep_for(std::chrono::milliseconds(300)); mg_connection *conn; std::string data = "{\"type\":\"test\"}"; char *data_char = const_cast<char *>(data.c_str()); EXPECT_TRUE( handler.handleData(&server, conn, 0x81, data_char, data.length())); } } // namespace dreamview } // namespace apollo <|endoftext|>
<commit_before>/* Copyright 2007-2015 QReal Research Group * * 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 "interpreterCore/interpreter/interpreter.h" #include <QtCore/QCoreApplication> #include <QtWidgets/QAction> #include <qrtext/languageToolboxInterface.h> #include <utils/timelineInterface.h> #include <kitBase/robotModel/robotModelInterface.h> using namespace qReal; using namespace interpreterCore::interpreter; using namespace kitBase::robotModel; const Id startingElementType = Id("RobotsMetamodel", "RobotsDiagram", "InitialNode"); const int maxThreadsCount = 100; Interpreter::Interpreter(const GraphicalModelAssistInterface &graphicalModelApi , LogicalModelAssistInterface &logicalModelApi , qReal::gui::MainWindowInterpretersInterface &interpretersInterface , const qReal::ProjectManagementInterface &projectManager , BlocksFactoryManagerInterface &blocksFactoryManager , const kitBase::robotModel::RobotModelManagerInterface &robotModelManager , qrtext::LanguageToolboxInterface &languageToolbox , QAction &connectToRobotAction ) : mGraphicalModelApi(graphicalModelApi) , mLogicalModelApi(logicalModelApi) , mInterpretersInterface(interpretersInterface) , mState(idle) , mRobotModelManager(robotModelManager) , mBlocksTable(new details::BlocksTable(blocksFactoryManager, robotModelManager)) , mActionConnectToRobot(connectToRobotAction) , mSensorVariablesUpdater(robotModelManager, languageToolbox) , mAutoconfigurer(mGraphicalModelApi, *mBlocksTable, *mInterpretersInterface.errorReporter()) , mLanguageToolbox(languageToolbox) { // Other components may want to subscribe to allDevicesConfigured() signal because // it seems to be the only way to perform robot devices additional initialization. // We must let them work out before interpretation starts, so creating queued connection. connect( &mRobotModelManager , &kitBase::robotModel::RobotModelManagerInterface::allDevicesConfigured , this , &Interpreter::devicesConfiguredSlot , Qt::QueuedConnection ); connect( &mRobotModelManager , &kitBase::robotModel::RobotModelManagerInterface::connected , this , &Interpreter::connectedSlot ); connect(&projectManager, &qReal::ProjectManagementInterface::beforeOpen, this, &Interpreter::userStopRobot); connectDevicesConfigurationProvider(&mAutoconfigurer); } Interpreter::~Interpreter() { qDeleteAll(mThreads); delete mBlocksTable; } void Interpreter::interpret() { mInterpretersInterface.errorReporter()->clear(); if (mRobotModelManager.model().connectionState() != RobotModelInterface::connectedState) { mInterpretersInterface.errorReporter()->addInformation(tr("No connection to robot")); return; } if (mState != idle) { mInterpretersInterface.errorReporter()->addInformation(tr("Interpreter is already running")); return; } mRobotModelManager.model().stopRobot(); mBlocksTable->clear(); mState = waitingForDevicesConfiguredToLaunch; if (!mAutoconfigurer.configure(mGraphicalModelApi.children(Id::rootId()), mRobotModelManager.model().robotId())) { return; } mLanguageToolbox.clear(); /// @todo Temporarily loading initial configuration from a network of SensorConfigurationProviders. /// To be done more adequately. const QString modelName = mRobotModelManager.model().robotId(); for (const PortInfo &port : mRobotModelManager.model().configurablePorts()) { const DeviceInfo deviceInfo = currentConfiguration(modelName, port); mRobotModelManager.model().configureDevice(port, deviceInfo); } mRobotModelManager.model().applyConfiguration(); } void Interpreter::stopRobot(qReal::interpretation::StopReason reason) { mSensorVariablesUpdater.suspend(); mRobotModelManager.model().stopRobot(); mState = idle; qDeleteAll(mThreads); mThreads.clear(); mBlocksTable->setFailure(); emit stopped(reason); } int Interpreter::timeElapsed() const { return mState == interpreting ? mRobotModelManager.model().timeline().timestamp() - mInterpretationStartedTimestamp : 0; } void Interpreter::connectedSlot(bool success, const QString &errorString) { if (success) { if (mRobotModelManager.model().needsConnection()) { mInterpretersInterface.errorReporter()->addInformation(tr("Connected successfully")); } } else { if (errorString.isEmpty()) { mInterpretersInterface.errorReporter()->addError(tr("Can't connect to a robot.")); } else { mInterpretersInterface.errorReporter()->addError(errorString); } } mActionConnectToRobot.setChecked(success); } void Interpreter::devicesConfiguredSlot() { if (mRobotModelManager.model().connectionState() != RobotModelInterface::connectedState) { mInterpretersInterface.errorReporter()->addInformation(tr("No connection to robot")); mState = idle; return; } if (mState == waitingForDevicesConfiguredToLaunch) { mState = interpreting; mInterpretationStartedTimestamp = mRobotModelManager.model().timeline().timestamp(); mSensorVariablesUpdater.run(); const Id &currentDiagramId = mInterpretersInterface.activeDiagram(); qReal::interpretation::Thread * const initialThread = new qReal::interpretation::Thread(&mGraphicalModelApi , mInterpretersInterface, startingElementType, currentDiagramId, *mBlocksTable, "main"); emit started(); addThread(initialThread, "main"); } } void Interpreter::threadStopped(qReal::interpretation::StopReason reason) { qReal::interpretation::Thread * const thread = static_cast<qReal::interpretation::Thread *>(sender()); mThreads.remove(thread->id()); delete thread; if (mThreads.isEmpty()) { stopRobot(reason); } } void Interpreter::newThread(const Id &startBlockId, const QString &threadId) { if (mThreads.contains(threadId)) { reportError(tr("Cannot create new thread with already occupied id %1").arg(threadId)); stopRobot(qReal::interpretation::StopReason::error); return; } qReal::interpretation::Thread * const thread = new qReal::interpretation::Thread(&mGraphicalModelApi , mInterpretersInterface, startingElementType, *mBlocksTable, startBlockId, threadId); addThread(thread, threadId); } void Interpreter::addThread(qReal::interpretation::Thread * const thread, const QString &threadId) { if (mThreads.count() >= maxThreadsCount) { reportError(tr("Threads limit exceeded. Maximum threads count is %1").arg(maxThreadsCount)); stopRobot(qReal::interpretation::StopReason::error); } mThreads[threadId] = thread; connect(thread, &interpretation::Thread::stopped, this, &Interpreter::threadStopped); connect(thread, &qReal::interpretation::Thread::newThread, this, &Interpreter::newThread); connect(thread, &qReal::interpretation::Thread::killThread, this, &Interpreter::killThread); connect(thread, &qReal::interpretation::Thread::sendMessage, this, &Interpreter::sendMessage); QCoreApplication::processEvents(); if (mState != idle) { thread->interpret(); } } void Interpreter::killThread(const QString &threadId) { if (mThreads.contains(threadId)) { mThreads[threadId]->stop(); } else { reportError(tr("Killing non-existent thread %1").arg(threadId)); } } void Interpreter::sendMessage(const QString &threadId, const QString &message) { if (mThreads.contains(threadId)) { mThreads[threadId]->newMessage(message); } } void Interpreter::connectToRobot() { if (mState == interpreting) { return; } if (mRobotModelManager.model().connectionState() == RobotModelInterface::connectedState) { mRobotModelManager.model().stopRobot(); mRobotModelManager.model().disconnectFromRobot(); } else { mRobotModelManager.model().connectToRobot(); } mActionConnectToRobot.setChecked( mRobotModelManager.model().connectionState() == RobotModelInterface::connectedState); } void Interpreter::reportError(const QString &message) { mInterpretersInterface.errorReporter()->addError(message); } <commit_msg>Fixed interpreter is already running error after sensors configuration conflict<commit_after>/* Copyright 2007-2015 QReal Research Group * * 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 "interpreterCore/interpreter/interpreter.h" #include <QtCore/QCoreApplication> #include <QtWidgets/QAction> #include <qrtext/languageToolboxInterface.h> #include <utils/timelineInterface.h> #include <kitBase/robotModel/robotModelInterface.h> using namespace qReal; using namespace interpreterCore::interpreter; using namespace kitBase::robotModel; const Id startingElementType = Id("RobotsMetamodel", "RobotsDiagram", "InitialNode"); const int maxThreadsCount = 100; Interpreter::Interpreter(const GraphicalModelAssistInterface &graphicalModelApi , LogicalModelAssistInterface &logicalModelApi , qReal::gui::MainWindowInterpretersInterface &interpretersInterface , const qReal::ProjectManagementInterface &projectManager , BlocksFactoryManagerInterface &blocksFactoryManager , const kitBase::robotModel::RobotModelManagerInterface &robotModelManager , qrtext::LanguageToolboxInterface &languageToolbox , QAction &connectToRobotAction ) : mGraphicalModelApi(graphicalModelApi) , mLogicalModelApi(logicalModelApi) , mInterpretersInterface(interpretersInterface) , mState(idle) , mRobotModelManager(robotModelManager) , mBlocksTable(new details::BlocksTable(blocksFactoryManager, robotModelManager)) , mActionConnectToRobot(connectToRobotAction) , mSensorVariablesUpdater(robotModelManager, languageToolbox) , mAutoconfigurer(mGraphicalModelApi, *mBlocksTable, *mInterpretersInterface.errorReporter()) , mLanguageToolbox(languageToolbox) { // Other components may want to subscribe to allDevicesConfigured() signal because // it seems to be the only way to perform robot devices additional initialization. // We must let them work out before interpretation starts, so creating queued connection. connect( &mRobotModelManager , &kitBase::robotModel::RobotModelManagerInterface::allDevicesConfigured , this , &Interpreter::devicesConfiguredSlot , Qt::QueuedConnection ); connect( &mRobotModelManager , &kitBase::robotModel::RobotModelManagerInterface::connected , this , &Interpreter::connectedSlot ); connect(&projectManager, &qReal::ProjectManagementInterface::beforeOpen, this, &Interpreter::userStopRobot); connectDevicesConfigurationProvider(&mAutoconfigurer); } Interpreter::~Interpreter() { qDeleteAll(mThreads); delete mBlocksTable; } void Interpreter::interpret() { mInterpretersInterface.errorReporter()->clear(); if (mRobotModelManager.model().connectionState() != RobotModelInterface::connectedState) { mInterpretersInterface.errorReporter()->addInformation(tr("No connection to robot")); return; } if (mState != idle) { mInterpretersInterface.errorReporter()->addInformation(tr("Interpreter is already running")); return; } mRobotModelManager.model().stopRobot(); mBlocksTable->clear(); mState = waitingForDevicesConfiguredToLaunch; if (!mAutoconfigurer.configure(mGraphicalModelApi.children(Id::rootId()), mRobotModelManager.model().robotId())) { mState = idle; return; } mLanguageToolbox.clear(); /// @todo Temporarily loading initial configuration from a network of SensorConfigurationProviders. /// To be done more adequately. const QString modelName = mRobotModelManager.model().robotId(); for (const PortInfo &port : mRobotModelManager.model().configurablePorts()) { const DeviceInfo deviceInfo = currentConfiguration(modelName, port); mRobotModelManager.model().configureDevice(port, deviceInfo); } mRobotModelManager.model().applyConfiguration(); } void Interpreter::stopRobot(qReal::interpretation::StopReason reason) { mSensorVariablesUpdater.suspend(); mRobotModelManager.model().stopRobot(); mState = idle; qDeleteAll(mThreads); mThreads.clear(); mBlocksTable->setFailure(); emit stopped(reason); } int Interpreter::timeElapsed() const { return mState == interpreting ? mRobotModelManager.model().timeline().timestamp() - mInterpretationStartedTimestamp : 0; } void Interpreter::connectedSlot(bool success, const QString &errorString) { if (success) { if (mRobotModelManager.model().needsConnection()) { mInterpretersInterface.errorReporter()->addInformation(tr("Connected successfully")); } } else { if (errorString.isEmpty()) { mInterpretersInterface.errorReporter()->addError(tr("Can't connect to a robot.")); } else { mInterpretersInterface.errorReporter()->addError(errorString); } } mActionConnectToRobot.setChecked(success); } void Interpreter::devicesConfiguredSlot() { if (mRobotModelManager.model().connectionState() != RobotModelInterface::connectedState) { mInterpretersInterface.errorReporter()->addInformation(tr("No connection to robot")); mState = idle; return; } if (mState == waitingForDevicesConfiguredToLaunch) { mState = interpreting; mInterpretationStartedTimestamp = mRobotModelManager.model().timeline().timestamp(); mSensorVariablesUpdater.run(); const Id &currentDiagramId = mInterpretersInterface.activeDiagram(); qReal::interpretation::Thread * const initialThread = new qReal::interpretation::Thread(&mGraphicalModelApi , mInterpretersInterface, startingElementType, currentDiagramId, *mBlocksTable, "main"); emit started(); addThread(initialThread, "main"); } } void Interpreter::threadStopped(qReal::interpretation::StopReason reason) { qReal::interpretation::Thread * const thread = static_cast<qReal::interpretation::Thread *>(sender()); mThreads.remove(thread->id()); delete thread; if (mThreads.isEmpty()) { stopRobot(reason); } } void Interpreter::newThread(const Id &startBlockId, const QString &threadId) { if (mThreads.contains(threadId)) { reportError(tr("Cannot create new thread with already occupied id %1").arg(threadId)); stopRobot(qReal::interpretation::StopReason::error); return; } qReal::interpretation::Thread * const thread = new qReal::interpretation::Thread(&mGraphicalModelApi , mInterpretersInterface, startingElementType, *mBlocksTable, startBlockId, threadId); addThread(thread, threadId); } void Interpreter::addThread(qReal::interpretation::Thread * const thread, const QString &threadId) { if (mThreads.count() >= maxThreadsCount) { reportError(tr("Threads limit exceeded. Maximum threads count is %1").arg(maxThreadsCount)); stopRobot(qReal::interpretation::StopReason::error); } mThreads[threadId] = thread; connect(thread, &interpretation::Thread::stopped, this, &Interpreter::threadStopped); connect(thread, &qReal::interpretation::Thread::newThread, this, &Interpreter::newThread); connect(thread, &qReal::interpretation::Thread::killThread, this, &Interpreter::killThread); connect(thread, &qReal::interpretation::Thread::sendMessage, this, &Interpreter::sendMessage); QCoreApplication::processEvents(); if (mState != idle) { thread->interpret(); } } void Interpreter::killThread(const QString &threadId) { if (mThreads.contains(threadId)) { mThreads[threadId]->stop(); } else { reportError(tr("Killing non-existent thread %1").arg(threadId)); } } void Interpreter::sendMessage(const QString &threadId, const QString &message) { if (mThreads.contains(threadId)) { mThreads[threadId]->newMessage(message); } } void Interpreter::connectToRobot() { if (mState == interpreting) { return; } if (mRobotModelManager.model().connectionState() == RobotModelInterface::connectedState) { mRobotModelManager.model().stopRobot(); mRobotModelManager.model().disconnectFromRobot(); } else { mRobotModelManager.model().connectToRobot(); } mActionConnectToRobot.setChecked( mRobotModelManager.model().connectionState() == RobotModelInterface::connectedState); } void Interpreter::reportError(const QString &message) { mInterpretersInterface.errorReporter()->addError(message); } <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "filestormetrics.h" #include <vespa/metrics/loadmetric.hpp> #include <vespa/metrics/summetric.hpp> #include <sstream> namespace storage { using metrics::MetricSet; using metrics::LoadTypeSet; FileStorThreadMetrics::Op::Op(const std::string& id, const std::string& name, MetricSet* owner) : MetricSet(id, {}, name + " load in filestor thread", owner), _name(name), count("count", {{"yamasdefault"}}, "Number of requests processed.", this), latency("latency", {{"yamasdefault"}}, "Latency of successful requests.", this), failed("failed", {{"yamasdefault"}}, "Number of failed requests.", this) { } FileStorThreadMetrics::Op::~Op() = default; MetricSet * FileStorThreadMetrics::Op::clone(std::vector<Metric::UP>& ownerList, CopyType copyType, MetricSet* owner, bool includeUnused) const { if (copyType == INACTIVE) { return MetricSet::clone(ownerList, INACTIVE, owner, includeUnused); } return (Op*) (new Op(getName(), _name, owner))->assignValues(*this); } template <typename BaseOp> FileStorThreadMetrics::OpWithRequestSize<BaseOp>::OpWithRequestSize(const std::string& id, const std::string& name, MetricSet* owner) : BaseOp(id, name, owner), request_size("request_size", {}, "Size of requests, in bytes", this) { } template <typename BaseOp> FileStorThreadMetrics::OpWithRequestSize<BaseOp>::~OpWithRequestSize() = default; // FIXME this has very non-intuitive semantics, ending up with copy&paste patterns template <typename BaseOp> MetricSet* FileStorThreadMetrics::OpWithRequestSize<BaseOp>::clone( std::vector<Metric::UP>& ownerList, CopyType copyType, MetricSet* owner, bool includeUnused) const { if (copyType == INACTIVE) { return MetricSet::clone(ownerList, INACTIVE, owner, includeUnused); } return static_cast<OpWithRequestSize<BaseOp>*>((new OpWithRequestSize<BaseOp>(this->getName(), this->_name, owner)) ->assignValues(*this)); } template <typename BaseOp> FileStorThreadMetrics::OpWithTestAndSetFailed<BaseOp>::OpWithTestAndSetFailed(const std::string& id, const std::string& name, MetricSet* owner) : BaseOp(id, name, owner), test_and_set_failed("test_and_set_failed", {{"yamasdefault"}}, "Number of times operations were failed due to a " "test-and-set condition mismatch", this) { } template <typename BaseOp> FileStorThreadMetrics::OpWithTestAndSetFailed<BaseOp>::~OpWithTestAndSetFailed() = default; // FIXME this has very non-intuitive semantics, ending up with copy&paste patterns (yet again...) template <typename BaseOp> MetricSet* FileStorThreadMetrics::OpWithTestAndSetFailed<BaseOp>::clone( std::vector<Metric::UP>& ownerList, CopyType copyType, MetricSet* owner, bool includeUnused) const { if (copyType == INACTIVE) { return MetricSet::clone(ownerList, INACTIVE, owner, includeUnused); } return static_cast<OpWithTestAndSetFailed<BaseOp>*>((new OpWithTestAndSetFailed<BaseOp>(this->getName(), this->_name, owner)) ->assignValues(*this)); } FileStorThreadMetrics::OpWithNotFound::OpWithNotFound(const std::string& id, const std::string& name, MetricSet* owner) : Op(id, name, owner), notFound("not_found", {}, "Number of requests that could not be completed due to source document not found.", this) { } FileStorThreadMetrics::OpWithNotFound::~OpWithNotFound() = default; MetricSet * FileStorThreadMetrics::OpWithNotFound::clone(std::vector<Metric::UP>& ownerList, CopyType copyType, MetricSet* owner, bool includeUnused) const { if (copyType == INACTIVE) { return MetricSet::clone(ownerList, INACTIVE, owner, includeUnused); } return (OpWithNotFound*) (new OpWithNotFound(getName(), _name, owner)) ->assignValues(*this); } FileStorThreadMetrics::Update::Update(MetricSet* owner) : OpWithTestAndSetFailed("update", "Update", owner), latencyRead("latency_read", {}, "Latency of the source read in the request.", this) { } FileStorThreadMetrics::Update::~Update() = default; MetricSet * FileStorThreadMetrics::Update::clone(std::vector<Metric::UP>& ownerList, CopyType copyType, MetricSet* owner, bool includeUnused) const { if (copyType == INACTIVE) { return MetricSet::clone(ownerList, INACTIVE, owner, includeUnused); } return (Update*) (new Update(owner))->assignValues(*this); } FileStorThreadMetrics::Visitor::Visitor(MetricSet* owner) : Op("visit", "Visit", owner), documentsPerIterate("docs", {}, "Number of entries read per iterate call", this) { } FileStorThreadMetrics::Visitor::~Visitor() = default; MetricSet * FileStorThreadMetrics::Visitor::clone(std::vector<Metric::UP>& ownerList, CopyType copyType, MetricSet* owner, bool includeUnused) const { if (copyType == INACTIVE) { return MetricSet::clone(ownerList, INACTIVE, owner, includeUnused); } return (Visitor*) (new Visitor(owner))->assignValues(*this); } FileStorThreadMetrics::FileStorThreadMetrics(const std::string& name, const std::string& desc, const LoadTypeSet& lt) : MetricSet(name, {{"filestor"},{"partofsum"}}, desc), operations("operations", {}, "Number of operations processed.", this), failedOperations("failedoperations", {}, "Number of operations throwing exceptions.", this), put(lt, PutMetricType("put", "Put"), this), get(lt, GetMetricType("get", "Get"), this), remove(lt, RemoveMetricType("remove", "Remove"), this), removeLocation(lt, Op("remove_location", "Remove location"), this), statBucket(lt, Op("stat_bucket", "Stat bucket"), this), update(lt, Update(), this), revert(lt, OpWithNotFound("revert", "Revert"), this), createIterator("createiterator", {}, this), visit(lt, Visitor(), this), multiOp(lt, Op("multioperations", "The number of multioperations that have been created"), this), createBuckets("createbuckets", "Number of buckets that has been created.", this), deleteBuckets("deletebuckets", "Number of buckets that has been deleted.", this), repairs("bucketverified", "Number of times buckets have been checked.", this), repairFixed("bucketfixed", {}, "Number of times bucket has been fixed because of corruption", this), recheckBucketInfo("recheckbucketinfo", "Number of times bucket info has been explicitly " "rechecked due to buckets being marked modified by " "the persistence provider", this), splitBuckets("splitbuckets", "Number of times buckets have been split.", this), joinBuckets("joinbuckets", "Number of times buckets have been joined.", this), setBucketStates("setbucketstates", "Number of times buckets have been activated or deactivated.", this), movedBuckets("movedbuckets", "Number of buckets moved between disks", this), readBucketList("readbucketlist", "Number of read bucket list requests", this), readBucketInfo("readbucketinfo", "Number of read bucket info requests", this), internalJoin("internaljoin", "Number of joins to join buckets on multiple disks during " "storage initialization.", this), mergeBuckets("mergebuckets", "Number of times buckets have been merged.", this), getBucketDiff("getbucketdiff", "Number of getbucketdiff commands that have been processed.", this), applyBucketDiff("applybucketdiff", "Number of applybucketdiff commands that have been processed.", this), getBucketDiffReply("getbucketdiffreply", {}, "Number of getbucketdiff replies that have been processed.", this), applyBucketDiffReply("applybucketdiffreply", {}, "Number of applybucketdiff replies that have been processed.", this), merge_handler_metrics(this), batchingSize("batchingsize", {}, "Number of operations batched per bucket (only counts " "batches of size > 1)", this) { } FileStorThreadMetrics::~FileStorThreadMetrics() = default; FileStorStripeMetrics::FileStorStripeMetrics(const std::string& name, const std::string& description, const LoadTypeSet& loadTypes) : MetricSet(name, {{"partofsum"}}, description), averageQueueWaitingTime(loadTypes, metrics::DoubleAverageMetric("averagequeuewait", {}, "Average time an operation spends in input queue."), this) { } FileStorStripeMetrics::~FileStorStripeMetrics() = default; FileStorDiskMetrics::FileStorDiskMetrics(const std::string& name, const std::string& description, const metrics::LoadTypeSet& loadTypes, MetricSet* owner) : MetricSet(name, {{"partofsum"}}, description, owner), sumThreads("allthreads", {{"sum"}}, "", this), sumStripes("allstripes", {{"sum"}}, "", this), averageQueueWaitingTime(loadTypes, metrics::DoubleAverageMetric("averagequeuewait", {}, "Average time an operation spends in input queue."), this), queueSize("queuesize", {}, "Size of input message queue.", this), pendingMerges("pendingmerge", {}, "Number of buckets currently being merged.", this), waitingForLockHitRate("waitingforlockrate", {}, "Amount of times a filestor thread has needed to wait for " "lock to take next message in queue.", this), lockWaitTime("lockwaittime", {}, "Amount of time waiting used waiting for lock.", this) { pendingMerges.unsetOnZeroValue(); waitingForLockHitRate.unsetOnZeroValue(); } FileStorDiskMetrics::~FileStorDiskMetrics() = default; void FileStorDiskMetrics::initDiskMetrics(const LoadTypeSet& loadTypes, uint32_t numStripes, uint32_t threadsPerDisk) { threads.clear(); threads.resize(threadsPerDisk); for (uint32_t i=0; i<threadsPerDisk; ++i) { std::ostringstream desc; std::ostringstream name; name << "thread" << i; desc << "Thread " << i << '/' << threadsPerDisk; threads[i] = std::make_shared<FileStorThreadMetrics>(name.str(), desc.str(), loadTypes); registerMetric(*threads[i]); sumThreads.addMetricToSum(*threads[i]); } stripes.clear(); stripes.resize(numStripes); for (uint32_t i=0; i<numStripes; ++i) { std::ostringstream desc; std::ostringstream name; name << "stripe" << i; desc << "Stripe " << i << '/' << numStripes; stripes[i] = std::make_shared<FileStorStripeMetrics>(name.str(), desc.str(), loadTypes); registerMetric(*stripes[i]); sumStripes.addMetricToSum(*stripes[i]); } } FileStorMetrics::FileStorMetrics(const LoadTypeSet&) : MetricSet("filestor", {{"filestor"}}, ""), sum("alldisks", {{"sum"}}, "", this), directoryEvents("directoryevents", {}, "Number of directory events received.", this), partitionEvents("partitionevents", {}, "Number of partition events received.", this), diskEvents("diskevents", {}, "Number of disk events received.", this), bucket_db_init_latency("bucket_db_init_latency", {}, "Time taken (in ms) to initialize bucket databases with " "information from the persistence provider", this) { } FileStorMetrics::~FileStorMetrics() = default; void FileStorMetrics::initDiskMetrics(const LoadTypeSet& loadTypes, uint32_t numStripes, uint32_t threadsPerDisk) { if (disk) { throw vespalib::IllegalStateException("Can't initialize disk twice", VESPA_STRLOC); } // Currently FileStorHandlerImpl expects metrics to exist for // disks that are not in use too. disk = std::make_shared<FileStorDiskMetrics>( "disk_0", "Disk 0", loadTypes, this); sum.addMetricToSum(*disk); disk->initDiskMetrics(loadTypes, numStripes, threadsPerDisk); } } template class metrics::LoadMetric<storage::FileStorThreadMetrics::Op>; template class metrics::LoadMetric<storage::FileStorThreadMetrics::OpWithNotFound>; template class metrics::LoadMetric<storage::FileStorThreadMetrics::Update>; template class metrics::LoadMetric<storage::FileStorThreadMetrics::Visitor>; template class metrics::LoadMetric<storage::FileStorThreadMetrics::PutMetricType>; template class metrics::LoadMetric<storage::FileStorThreadMetrics::GetMetricType>; template class metrics::LoadMetric<storage::FileStorThreadMetrics::RemoveMetricType>; template class metrics::SumMetric<storage::FileStorThreadMetrics::Op>; template class metrics::SumMetric<storage::FileStorThreadMetrics::OpWithNotFound>; template class metrics::SumMetric<storage::FileStorThreadMetrics::Update>; template class metrics::SumMetric<storage::FileStorThreadMetrics::Visitor>; <commit_msg>Use simple assert instead<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "filestormetrics.h" #include <vespa/metrics/loadmetric.hpp> #include <vespa/metrics/summetric.hpp> #include <sstream> namespace storage { using metrics::MetricSet; using metrics::LoadTypeSet; FileStorThreadMetrics::Op::Op(const std::string& id, const std::string& name, MetricSet* owner) : MetricSet(id, {}, name + " load in filestor thread", owner), _name(name), count("count", {{"yamasdefault"}}, "Number of requests processed.", this), latency("latency", {{"yamasdefault"}}, "Latency of successful requests.", this), failed("failed", {{"yamasdefault"}}, "Number of failed requests.", this) { } FileStorThreadMetrics::Op::~Op() = default; MetricSet * FileStorThreadMetrics::Op::clone(std::vector<Metric::UP>& ownerList, CopyType copyType, MetricSet* owner, bool includeUnused) const { if (copyType == INACTIVE) { return MetricSet::clone(ownerList, INACTIVE, owner, includeUnused); } return (Op*) (new Op(getName(), _name, owner))->assignValues(*this); } template <typename BaseOp> FileStorThreadMetrics::OpWithRequestSize<BaseOp>::OpWithRequestSize(const std::string& id, const std::string& name, MetricSet* owner) : BaseOp(id, name, owner), request_size("request_size", {}, "Size of requests, in bytes", this) { } template <typename BaseOp> FileStorThreadMetrics::OpWithRequestSize<BaseOp>::~OpWithRequestSize() = default; // FIXME this has very non-intuitive semantics, ending up with copy&paste patterns template <typename BaseOp> MetricSet* FileStorThreadMetrics::OpWithRequestSize<BaseOp>::clone( std::vector<Metric::UP>& ownerList, CopyType copyType, MetricSet* owner, bool includeUnused) const { if (copyType == INACTIVE) { return MetricSet::clone(ownerList, INACTIVE, owner, includeUnused); } return static_cast<OpWithRequestSize<BaseOp>*>((new OpWithRequestSize<BaseOp>(this->getName(), this->_name, owner)) ->assignValues(*this)); } template <typename BaseOp> FileStorThreadMetrics::OpWithTestAndSetFailed<BaseOp>::OpWithTestAndSetFailed(const std::string& id, const std::string& name, MetricSet* owner) : BaseOp(id, name, owner), test_and_set_failed("test_and_set_failed", {{"yamasdefault"}}, "Number of times operations were failed due to a " "test-and-set condition mismatch", this) { } template <typename BaseOp> FileStorThreadMetrics::OpWithTestAndSetFailed<BaseOp>::~OpWithTestAndSetFailed() = default; // FIXME this has very non-intuitive semantics, ending up with copy&paste patterns (yet again...) template <typename BaseOp> MetricSet* FileStorThreadMetrics::OpWithTestAndSetFailed<BaseOp>::clone( std::vector<Metric::UP>& ownerList, CopyType copyType, MetricSet* owner, bool includeUnused) const { if (copyType == INACTIVE) { return MetricSet::clone(ownerList, INACTIVE, owner, includeUnused); } return static_cast<OpWithTestAndSetFailed<BaseOp>*>((new OpWithTestAndSetFailed<BaseOp>(this->getName(), this->_name, owner)) ->assignValues(*this)); } FileStorThreadMetrics::OpWithNotFound::OpWithNotFound(const std::string& id, const std::string& name, MetricSet* owner) : Op(id, name, owner), notFound("not_found", {}, "Number of requests that could not be completed due to source document not found.", this) { } FileStorThreadMetrics::OpWithNotFound::~OpWithNotFound() = default; MetricSet * FileStorThreadMetrics::OpWithNotFound::clone(std::vector<Metric::UP>& ownerList, CopyType copyType, MetricSet* owner, bool includeUnused) const { if (copyType == INACTIVE) { return MetricSet::clone(ownerList, INACTIVE, owner, includeUnused); } return (OpWithNotFound*) (new OpWithNotFound(getName(), _name, owner)) ->assignValues(*this); } FileStorThreadMetrics::Update::Update(MetricSet* owner) : OpWithTestAndSetFailed("update", "Update", owner), latencyRead("latency_read", {}, "Latency of the source read in the request.", this) { } FileStorThreadMetrics::Update::~Update() = default; MetricSet * FileStorThreadMetrics::Update::clone(std::vector<Metric::UP>& ownerList, CopyType copyType, MetricSet* owner, bool includeUnused) const { if (copyType == INACTIVE) { return MetricSet::clone(ownerList, INACTIVE, owner, includeUnused); } return (Update*) (new Update(owner))->assignValues(*this); } FileStorThreadMetrics::Visitor::Visitor(MetricSet* owner) : Op("visit", "Visit", owner), documentsPerIterate("docs", {}, "Number of entries read per iterate call", this) { } FileStorThreadMetrics::Visitor::~Visitor() = default; MetricSet * FileStorThreadMetrics::Visitor::clone(std::vector<Metric::UP>& ownerList, CopyType copyType, MetricSet* owner, bool includeUnused) const { if (copyType == INACTIVE) { return MetricSet::clone(ownerList, INACTIVE, owner, includeUnused); } return (Visitor*) (new Visitor(owner))->assignValues(*this); } FileStorThreadMetrics::FileStorThreadMetrics(const std::string& name, const std::string& desc, const LoadTypeSet& lt) : MetricSet(name, {{"filestor"},{"partofsum"}}, desc), operations("operations", {}, "Number of operations processed.", this), failedOperations("failedoperations", {}, "Number of operations throwing exceptions.", this), put(lt, PutMetricType("put", "Put"), this), get(lt, GetMetricType("get", "Get"), this), remove(lt, RemoveMetricType("remove", "Remove"), this), removeLocation(lt, Op("remove_location", "Remove location"), this), statBucket(lt, Op("stat_bucket", "Stat bucket"), this), update(lt, Update(), this), revert(lt, OpWithNotFound("revert", "Revert"), this), createIterator("createiterator", {}, this), visit(lt, Visitor(), this), multiOp(lt, Op("multioperations", "The number of multioperations that have been created"), this), createBuckets("createbuckets", "Number of buckets that has been created.", this), deleteBuckets("deletebuckets", "Number of buckets that has been deleted.", this), repairs("bucketverified", "Number of times buckets have been checked.", this), repairFixed("bucketfixed", {}, "Number of times bucket has been fixed because of corruption", this), recheckBucketInfo("recheckbucketinfo", "Number of times bucket info has been explicitly " "rechecked due to buckets being marked modified by " "the persistence provider", this), splitBuckets("splitbuckets", "Number of times buckets have been split.", this), joinBuckets("joinbuckets", "Number of times buckets have been joined.", this), setBucketStates("setbucketstates", "Number of times buckets have been activated or deactivated.", this), movedBuckets("movedbuckets", "Number of buckets moved between disks", this), readBucketList("readbucketlist", "Number of read bucket list requests", this), readBucketInfo("readbucketinfo", "Number of read bucket info requests", this), internalJoin("internaljoin", "Number of joins to join buckets on multiple disks during " "storage initialization.", this), mergeBuckets("mergebuckets", "Number of times buckets have been merged.", this), getBucketDiff("getbucketdiff", "Number of getbucketdiff commands that have been processed.", this), applyBucketDiff("applybucketdiff", "Number of applybucketdiff commands that have been processed.", this), getBucketDiffReply("getbucketdiffreply", {}, "Number of getbucketdiff replies that have been processed.", this), applyBucketDiffReply("applybucketdiffreply", {}, "Number of applybucketdiff replies that have been processed.", this), merge_handler_metrics(this), batchingSize("batchingsize", {}, "Number of operations batched per bucket (only counts " "batches of size > 1)", this) { } FileStorThreadMetrics::~FileStorThreadMetrics() = default; FileStorStripeMetrics::FileStorStripeMetrics(const std::string& name, const std::string& description, const LoadTypeSet& loadTypes) : MetricSet(name, {{"partofsum"}}, description), averageQueueWaitingTime(loadTypes, metrics::DoubleAverageMetric("averagequeuewait", {}, "Average time an operation spends in input queue."), this) { } FileStorStripeMetrics::~FileStorStripeMetrics() = default; FileStorDiskMetrics::FileStorDiskMetrics(const std::string& name, const std::string& description, const metrics::LoadTypeSet& loadTypes, MetricSet* owner) : MetricSet(name, {{"partofsum"}}, description, owner), sumThreads("allthreads", {{"sum"}}, "", this), sumStripes("allstripes", {{"sum"}}, "", this), averageQueueWaitingTime(loadTypes, metrics::DoubleAverageMetric("averagequeuewait", {}, "Average time an operation spends in input queue."), this), queueSize("queuesize", {}, "Size of input message queue.", this), pendingMerges("pendingmerge", {}, "Number of buckets currently being merged.", this), waitingForLockHitRate("waitingforlockrate", {}, "Amount of times a filestor thread has needed to wait for " "lock to take next message in queue.", this), lockWaitTime("lockwaittime", {}, "Amount of time waiting used waiting for lock.", this) { pendingMerges.unsetOnZeroValue(); waitingForLockHitRate.unsetOnZeroValue(); } FileStorDiskMetrics::~FileStorDiskMetrics() = default; void FileStorDiskMetrics::initDiskMetrics(const LoadTypeSet& loadTypes, uint32_t numStripes, uint32_t threadsPerDisk) { threads.clear(); threads.resize(threadsPerDisk); for (uint32_t i=0; i<threadsPerDisk; ++i) { std::ostringstream desc; std::ostringstream name; name << "thread" << i; desc << "Thread " << i << '/' << threadsPerDisk; threads[i] = std::make_shared<FileStorThreadMetrics>(name.str(), desc.str(), loadTypes); registerMetric(*threads[i]); sumThreads.addMetricToSum(*threads[i]); } stripes.clear(); stripes.resize(numStripes); for (uint32_t i=0; i<numStripes; ++i) { std::ostringstream desc; std::ostringstream name; name << "stripe" << i; desc << "Stripe " << i << '/' << numStripes; stripes[i] = std::make_shared<FileStorStripeMetrics>(name.str(), desc.str(), loadTypes); registerMetric(*stripes[i]); sumStripes.addMetricToSum(*stripes[i]); } } FileStorMetrics::FileStorMetrics(const LoadTypeSet&) : MetricSet("filestor", {{"filestor"}}, ""), sum("alldisks", {{"sum"}}, "", this), directoryEvents("directoryevents", {}, "Number of directory events received.", this), partitionEvents("partitionevents", {}, "Number of partition events received.", this), diskEvents("diskevents", {}, "Number of disk events received.", this), bucket_db_init_latency("bucket_db_init_latency", {}, "Time taken (in ms) to initialize bucket databases with " "information from the persistence provider", this) { } FileStorMetrics::~FileStorMetrics() = default; void FileStorMetrics::initDiskMetrics(const LoadTypeSet& loadTypes, uint32_t numStripes, uint32_t threadsPerDisk) { assert( ! disk); // Currently FileStorHandlerImpl expects metrics to exist for // disks that are not in use too. disk = std::make_shared<FileStorDiskMetrics>( "disk_0", "Disk 0", loadTypes, this); sum.addMetricToSum(*disk); disk->initDiskMetrics(loadTypes, numStripes, threadsPerDisk); } } template class metrics::LoadMetric<storage::FileStorThreadMetrics::Op>; template class metrics::LoadMetric<storage::FileStorThreadMetrics::OpWithNotFound>; template class metrics::LoadMetric<storage::FileStorThreadMetrics::Update>; template class metrics::LoadMetric<storage::FileStorThreadMetrics::Visitor>; template class metrics::LoadMetric<storage::FileStorThreadMetrics::PutMetricType>; template class metrics::LoadMetric<storage::FileStorThreadMetrics::GetMetricType>; template class metrics::LoadMetric<storage::FileStorThreadMetrics::RemoveMetricType>; template class metrics::SumMetric<storage::FileStorThreadMetrics::Op>; template class metrics::SumMetric<storage::FileStorThreadMetrics::OpWithNotFound>; template class metrics::SumMetric<storage::FileStorThreadMetrics::Update>; template class metrics::SumMetric<storage::FileStorThreadMetrics::Visitor>; <|endoftext|>
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "feedconfigstore.h" #include "feedstates.h" #include "ifeedview.h" #include "ireplayconfig.h" #include "replaypacketdispatcher.h" #include "replay_throttling_policy.h" #include <vespa/searchcore/proton/bucketdb/ibucketdbhandler.h> #include <vespa/searchcore/proton/feedoperation/operations.h> #include <vespa/searchcore/proton/common/eventlogger.h> #include <vespa/searchcore/proton/common/replay_feed_token_factory.h> #include <vespa/vespalib/util/idestructorcallback.h> #include <vespa/vespalib/util/lambdatask.h> #include <vespa/vespalib/util/shared_operation_throttler.h> #include <cassert> #include <vespa/log/log.h> LOG_SETUP(".proton.server.feedstates"); using search::transactionlog::Packet; using search::transactionlog::client::RPC; using search::SerialNum; using vespalib::Executor; using vespalib::makeLambdaTask; using vespalib::IDestructorCallback; using vespalib::SharedOperationThrottler; using vespalib::make_string; using proton::bucketdb::IBucketDBHandler; namespace proton { namespace { const search::SerialNum REPLAY_PROGRESS_INTERVAL = 50000; void handleProgress(TlsReplayProgress &progress, SerialNum currentSerial) { progress.updateCurrent(currentSerial); if (LOG_WOULD_LOG(event) && (LOG_WOULD_LOG(debug) || (progress.getCurrent() % REPLAY_PROGRESS_INTERVAL == 0))) { EventLogger::transactionLogReplayProgress(progress.getDomainName(), progress.getProgress(), progress.getFirst(), progress.getLast(), progress.getCurrent()); } } class TransactionLogReplayPacketHandler : public IReplayPacketHandler { IFeedView *& _feed_view_ptr; // Pointer can be changed in executor thread. IBucketDBHandler &_bucketDBHandler; IReplayConfig &_replay_config; FeedConfigStore &_config_store; IIncSerialNum &_inc_serial_num; CommitTimeTracker _commitTimeTracker; std::unique_ptr<SharedOperationThrottler> _throttler; std::unique_ptr<feedtoken::ReplayFeedTokenFactory> _replay_feed_token_factory; static std::unique_ptr<SharedOperationThrottler> make_throttler(const ReplayThrottlingPolicy& replay_throttling_policy) { auto& params = replay_throttling_policy.get_params(); if (!params.has_value()) { return SharedOperationThrottler::make_unlimited_throttler(); } return SharedOperationThrottler::make_dynamic_throttler(params.value()); } public: TransactionLogReplayPacketHandler(IFeedView *& feed_view_ptr, IBucketDBHandler &bucketDBHandler, IReplayConfig &replay_config, FeedConfigStore &config_store, const ReplayThrottlingPolicy& replay_throttling_policy, IIncSerialNum &inc_serial_num) : _feed_view_ptr(feed_view_ptr), _bucketDBHandler(bucketDBHandler), _replay_config(replay_config), _config_store(config_store), _inc_serial_num(inc_serial_num), _commitTimeTracker(5ms), _throttler(make_throttler(replay_throttling_policy)), _replay_feed_token_factory(std::make_unique<feedtoken::ReplayFeedTokenFactory>(false)) { } ~TransactionLogReplayPacketHandler() override = default; FeedToken make_replay_feed_token(const FeedOperation& op) { SharedOperationThrottler::Token throttler_token = _throttler->blocking_acquire_one(); return _replay_feed_token_factory->make_replay_feed_token(std::move(throttler_token), op); } void replay(const PutOperation &op) override { _feed_view_ptr->handlePut(make_replay_feed_token(op), op); } void replay(const RemoveOperation &op) override { _feed_view_ptr->handleRemove(make_replay_feed_token(op), op); } void replay(const UpdateOperation &op) override { _feed_view_ptr->handleUpdate(make_replay_feed_token(op), op); } void replay(const NoopOperation &) override {} // ignored void replay(const NewConfigOperation &op) override { _replay_config.replayConfig(op.getSerialNum()); } void replay(const DeleteBucketOperation &op) override { _feed_view_ptr->handleDeleteBucket(op, make_replay_feed_token(op)); } void replay(const SplitBucketOperation &op) override { _bucketDBHandler.handleSplit(op.getSerialNum(), op.getSource(), op.getTarget1(), op.getTarget2()); } void replay(const JoinBucketsOperation &op) override { _bucketDBHandler.handleJoin(op.getSerialNum(), op.getSource1(), op.getSource2(), op.getTarget()); } void replay(const PruneRemovedDocumentsOperation &op) override { _feed_view_ptr->handlePruneRemovedDocuments(op, make_replay_feed_token(op)); } void replay(const MoveOperation &op) override { _feed_view_ptr->handleMove(op, make_replay_feed_token(op)); } void replay(const CreateBucketOperation &) override { } void replay(const CompactLidSpaceOperation &op) override { _feed_view_ptr->handleCompactLidSpace(op, make_replay_feed_token(op)); } NewConfigOperation::IStreamHandler &getNewConfigStreamHandler() override { return _config_store; } const document::DocumentTypeRepo &getDeserializeRepo() override { return *_feed_view_ptr->getDocumentTypeRepo(); } void check_serial_num(search::SerialNum serial_num) override { auto exp_serial_num = _inc_serial_num.inc_serial_num(); if (exp_serial_num != serial_num) { LOG(warning, "Expected replay serial number %" PRIu64 ", got serial number %" PRIu64, exp_serial_num, serial_num); assert(exp_serial_num == serial_num); } } void optionalCommit(search::SerialNum serialNum) override { if (_commitTimeTracker.needCommit()) { _feed_view_ptr->forceCommit(serialNum); } } }; class PacketDispatcher { public: PacketDispatcher(IReplayPacketHandler *packet_handler) : _packet_handler(packet_handler) {} void handlePacket(PacketWrapper & wrap); private: void handleEntry(const Packet::Entry &entry); IReplayPacketHandler *_packet_handler; }; void PacketDispatcher::handlePacket(PacketWrapper & wrap) { vespalib::nbostream_longlivedbuf handle(wrap.packet.getHandle().data(), wrap.packet.getHandle().size()); while ( !handle.empty() ) { Packet::Entry entry; entry.deserialize(handle); handleEntry(entry); if (wrap.progress != nullptr) { handleProgress(*wrap.progress, entry.serial()); } } wrap.result = RPC::OK; wrap.gate.countDown(); } void PacketDispatcher::handleEntry(const Packet::Entry &entry) { // Called by handlePacket() in executor thread. LOG(spam, "replay packet entry: entrySerial(%" PRIu64 "), entryType(%u)", entry.serial(), entry.type()); auto entry_serial_num = entry.serial(); _packet_handler->check_serial_num(entry_serial_num); ReplayPacketDispatcher dispatcher(*_packet_handler); dispatcher.replayEntry(entry); _packet_handler->optionalCommit(entry_serial_num); } } // namespace ReplayTransactionLogState::ReplayTransactionLogState( const vespalib::string &name, IFeedView *& feed_view_ptr, IBucketDBHandler &bucketDBHandler, IReplayConfig &replay_config, FeedConfigStore &config_store, const ReplayThrottlingPolicy &replay_throttling_policy, IIncSerialNum& inc_serial_num) : FeedState(REPLAY_TRANSACTION_LOG), _doc_type_name(name), _packet_handler(std::make_unique<TransactionLogReplayPacketHandler>(feed_view_ptr, bucketDBHandler, replay_config, config_store, replay_throttling_policy, inc_serial_num)) { } ReplayTransactionLogState::~ReplayTransactionLogState() = default; void ReplayTransactionLogState::receive(const PacketWrapper::SP &wrap, Executor &executor) { executor.execute(makeLambdaTask([this, wrap = wrap] () { PacketDispatcher dispatcher(_packet_handler.get()); dispatcher.handlePacket(*wrap); })); } } // namespace proton <commit_msg>Enable tracking of replay feed tokens.<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "feedconfigstore.h" #include "feedstates.h" #include "ifeedview.h" #include "ireplayconfig.h" #include "replaypacketdispatcher.h" #include "replay_throttling_policy.h" #include <vespa/searchcore/proton/bucketdb/ibucketdbhandler.h> #include <vespa/searchcore/proton/feedoperation/operations.h> #include <vespa/searchcore/proton/common/eventlogger.h> #include <vespa/searchcore/proton/common/replay_feed_token_factory.h> #include <vespa/vespalib/util/idestructorcallback.h> #include <vespa/vespalib/util/lambdatask.h> #include <vespa/vespalib/util/shared_operation_throttler.h> #include <cassert> #include <vespa/log/log.h> LOG_SETUP(".proton.server.feedstates"); using search::transactionlog::Packet; using search::transactionlog::client::RPC; using search::SerialNum; using vespalib::Executor; using vespalib::makeLambdaTask; using vespalib::IDestructorCallback; using vespalib::SharedOperationThrottler; using vespalib::make_string; using proton::bucketdb::IBucketDBHandler; namespace proton { namespace { const search::SerialNum REPLAY_PROGRESS_INTERVAL = 50000; void handleProgress(TlsReplayProgress &progress, SerialNum currentSerial) { progress.updateCurrent(currentSerial); if (LOG_WOULD_LOG(event) && (LOG_WOULD_LOG(debug) || (progress.getCurrent() % REPLAY_PROGRESS_INTERVAL == 0))) { EventLogger::transactionLogReplayProgress(progress.getDomainName(), progress.getProgress(), progress.getFirst(), progress.getLast(), progress.getCurrent()); } } class TransactionLogReplayPacketHandler : public IReplayPacketHandler { IFeedView *& _feed_view_ptr; // Pointer can be changed in executor thread. IBucketDBHandler &_bucketDBHandler; IReplayConfig &_replay_config; FeedConfigStore &_config_store; IIncSerialNum &_inc_serial_num; CommitTimeTracker _commitTimeTracker; std::unique_ptr<SharedOperationThrottler> _throttler; std::unique_ptr<feedtoken::ReplayFeedTokenFactory> _replay_feed_token_factory; static std::unique_ptr<SharedOperationThrottler> make_throttler(const ReplayThrottlingPolicy& replay_throttling_policy) { auto& params = replay_throttling_policy.get_params(); if (!params.has_value()) { return SharedOperationThrottler::make_unlimited_throttler(); } return SharedOperationThrottler::make_dynamic_throttler(params.value()); } public: TransactionLogReplayPacketHandler(IFeedView *& feed_view_ptr, IBucketDBHandler &bucketDBHandler, IReplayConfig &replay_config, FeedConfigStore &config_store, const ReplayThrottlingPolicy& replay_throttling_policy, IIncSerialNum &inc_serial_num) : _feed_view_ptr(feed_view_ptr), _bucketDBHandler(bucketDBHandler), _replay_config(replay_config), _config_store(config_store), _inc_serial_num(inc_serial_num), _commitTimeTracker(5ms), _throttler(make_throttler(replay_throttling_policy)), _replay_feed_token_factory(std::make_unique<feedtoken::ReplayFeedTokenFactory>(true)) { } ~TransactionLogReplayPacketHandler() override = default; FeedToken make_replay_feed_token(const FeedOperation& op) { SharedOperationThrottler::Token throttler_token = _throttler->blocking_acquire_one(); return _replay_feed_token_factory->make_replay_feed_token(std::move(throttler_token), op); } void replay(const PutOperation &op) override { _feed_view_ptr->handlePut(make_replay_feed_token(op), op); } void replay(const RemoveOperation &op) override { _feed_view_ptr->handleRemove(make_replay_feed_token(op), op); } void replay(const UpdateOperation &op) override { _feed_view_ptr->handleUpdate(make_replay_feed_token(op), op); } void replay(const NoopOperation &) override {} // ignored void replay(const NewConfigOperation &op) override { _replay_config.replayConfig(op.getSerialNum()); } void replay(const DeleteBucketOperation &op) override { _feed_view_ptr->handleDeleteBucket(op, make_replay_feed_token(op)); } void replay(const SplitBucketOperation &op) override { _bucketDBHandler.handleSplit(op.getSerialNum(), op.getSource(), op.getTarget1(), op.getTarget2()); } void replay(const JoinBucketsOperation &op) override { _bucketDBHandler.handleJoin(op.getSerialNum(), op.getSource1(), op.getSource2(), op.getTarget()); } void replay(const PruneRemovedDocumentsOperation &op) override { _feed_view_ptr->handlePruneRemovedDocuments(op, make_replay_feed_token(op)); } void replay(const MoveOperation &op) override { _feed_view_ptr->handleMove(op, make_replay_feed_token(op)); } void replay(const CreateBucketOperation &) override { } void replay(const CompactLidSpaceOperation &op) override { _feed_view_ptr->handleCompactLidSpace(op, make_replay_feed_token(op)); } NewConfigOperation::IStreamHandler &getNewConfigStreamHandler() override { return _config_store; } const document::DocumentTypeRepo &getDeserializeRepo() override { return *_feed_view_ptr->getDocumentTypeRepo(); } void check_serial_num(search::SerialNum serial_num) override { auto exp_serial_num = _inc_serial_num.inc_serial_num(); if (exp_serial_num != serial_num) { LOG(warning, "Expected replay serial number %" PRIu64 ", got serial number %" PRIu64, exp_serial_num, serial_num); assert(exp_serial_num == serial_num); } } void optionalCommit(search::SerialNum serialNum) override { if (_commitTimeTracker.needCommit()) { _feed_view_ptr->forceCommit(serialNum); } } }; class PacketDispatcher { public: PacketDispatcher(IReplayPacketHandler *packet_handler) : _packet_handler(packet_handler) {} void handlePacket(PacketWrapper & wrap); private: void handleEntry(const Packet::Entry &entry); IReplayPacketHandler *_packet_handler; }; void PacketDispatcher::handlePacket(PacketWrapper & wrap) { vespalib::nbostream_longlivedbuf handle(wrap.packet.getHandle().data(), wrap.packet.getHandle().size()); while ( !handle.empty() ) { Packet::Entry entry; entry.deserialize(handle); handleEntry(entry); if (wrap.progress != nullptr) { handleProgress(*wrap.progress, entry.serial()); } } wrap.result = RPC::OK; wrap.gate.countDown(); } void PacketDispatcher::handleEntry(const Packet::Entry &entry) { // Called by handlePacket() in executor thread. LOG(spam, "replay packet entry: entrySerial(%" PRIu64 "), entryType(%u)", entry.serial(), entry.type()); auto entry_serial_num = entry.serial(); _packet_handler->check_serial_num(entry_serial_num); ReplayPacketDispatcher dispatcher(*_packet_handler); dispatcher.replayEntry(entry); _packet_handler->optionalCommit(entry_serial_num); } } // namespace ReplayTransactionLogState::ReplayTransactionLogState( const vespalib::string &name, IFeedView *& feed_view_ptr, IBucketDBHandler &bucketDBHandler, IReplayConfig &replay_config, FeedConfigStore &config_store, const ReplayThrottlingPolicy &replay_throttling_policy, IIncSerialNum& inc_serial_num) : FeedState(REPLAY_TRANSACTION_LOG), _doc_type_name(name), _packet_handler(std::make_unique<TransactionLogReplayPacketHandler>(feed_view_ptr, bucketDBHandler, replay_config, config_store, replay_throttling_policy, inc_serial_num)) { } ReplayTransactionLogState::~ReplayTransactionLogState() = default; void ReplayTransactionLogState::receive(const PacketWrapper::SP &wrap, Executor &executor) { executor.execute(makeLambdaTask([this, wrap = wrap] () { PacketDispatcher dispatcher(_packet_handler.get()); dispatcher.handlePacket(*wrap); })); } } // namespace proton <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "feedconfigstore.h" #include "feedstates.h" #include "ifeedview.h" #include "ireplayconfig.h" #include "replaypacketdispatcher.h" #include <vespa/searchcore/proton/bucketdb/ibucketdbhandler.h> #include <vespa/searchcore/proton/feedoperation/operations.h> #include <vespa/searchcore/proton/common/eventlogger.h> #include <vespa/vespalib/util/idestructorcallback.h> #include <vespa/vespalib/util/closuretask.h> #include <vespa/vespalib/util/lambdatask.h> #include <cassert> #include <vespa/log/log.h> LOG_SETUP(".proton.server.feedstates"); using search::transactionlog::Packet; using search::transactionlog::client::RPC; using search::SerialNum; using vespalib::Executor; using vespalib::makeClosure; using vespalib::makeLambdaTask; using vespalib::makeTask; using vespalib::make_string; using proton::bucketdb::IBucketDBHandler; namespace proton { namespace { typedef vespalib::Closure1<const Packet::Entry &>::UP EntryHandler; const search::SerialNum REPLAY_PROGRESS_INTERVAL = 50000; void handleProgress(TlsReplayProgress &progress, SerialNum currentSerial) { progress.updateCurrent(currentSerial); if (LOG_WOULD_LOG(event) && (LOG_WOULD_LOG(debug) || (progress.getCurrent() % REPLAY_PROGRESS_INTERVAL == 0))) { EventLogger::transactionLogReplayProgress(progress.getDomainName(), progress.getProgress(), progress.getFirst(), progress.getLast(), progress.getCurrent()); } } void handlePacket(PacketWrapper & wrap, EntryHandler entryHandler) { vespalib::nbostream_longlivedbuf handle(wrap.packet.getHandle().data(), wrap.packet.getHandle().size()); while ( !handle.empty() ) { Packet::Entry entry; entry.deserialize(handle); entryHandler->call(entry); if (wrap.progress != nullptr) { handleProgress(*wrap.progress, entry.serial()); } } wrap.result = RPC::OK; wrap.gate.countDown(); } class TransactionLogReplayPacketHandler : public IReplayPacketHandler { IFeedView *& _feed_view_ptr; // Pointer can be changed in executor thread. IBucketDBHandler &_bucketDBHandler; IReplayConfig &_replay_config; FeedConfigStore &_config_store; IIncSerialNum &_inc_serial_num; CommitTimeTracker _commitTimeTracker; public: TransactionLogReplayPacketHandler(IFeedView *& feed_view_ptr, IBucketDBHandler &bucketDBHandler, IReplayConfig &replay_config, FeedConfigStore &config_store, IIncSerialNum &inc_serial_num) : _feed_view_ptr(feed_view_ptr), _bucketDBHandler(bucketDBHandler), _replay_config(replay_config), _config_store(config_store), _inc_serial_num(inc_serial_num), _commitTimeTracker(5ms) { } ~TransactionLogReplayPacketHandler() override = default; void replay(const PutOperation &op) override { _feed_view_ptr->handlePut(FeedToken(), op); } void replay(const RemoveOperation &op) override { _feed_view_ptr->handleRemove(FeedToken(), op); } void replay(const UpdateOperation &op) override { _feed_view_ptr->handleUpdate(FeedToken(), op); } void replay(const NoopOperation &) override {} // ignored void replay(const NewConfigOperation &op) override { _replay_config.replayConfig(op.getSerialNum()); } void replay(const DeleteBucketOperation &op) override { _feed_view_ptr->handleDeleteBucket(op); } void replay(const SplitBucketOperation &op) override { _bucketDBHandler.handleSplit(op.getSerialNum(), op.getSource(), op.getTarget1(), op.getTarget2()); } void replay(const JoinBucketsOperation &op) override { _bucketDBHandler.handleJoin(op.getSerialNum(), op.getSource1(), op.getSource2(), op.getTarget()); } void replay(const PruneRemovedDocumentsOperation &op) override { _feed_view_ptr->handlePruneRemovedDocuments(op); } void replay(const MoveOperation &op) override { _feed_view_ptr->handleMove(op, vespalib::IDestructorCallback::SP()); } void replay(const CreateBucketOperation &) override { } void replay(const CompactLidSpaceOperation &op) override { _feed_view_ptr->handleCompactLidSpace(op); } NewConfigOperation::IStreamHandler &getNewConfigStreamHandler() override { return _config_store; } const document::DocumentTypeRepo &getDeserializeRepo() override { return *_feed_view_ptr->getDocumentTypeRepo(); } void check_serial_num(search::SerialNum serial_num) override { auto exp_serial_num = _inc_serial_num.inc_serial_num(); if (exp_serial_num != serial_num) { LOG(warning, "Expected replay serial number %" PRIu64 ", got serial number %" PRIu64, exp_serial_num, serial_num); assert(exp_serial_num == serial_num); } } void optionalCommit(search::SerialNum serialNum) override { if (_commitTimeTracker.needCommit()) { _feed_view_ptr->forceCommit(serialNum); } } }; void startDispatch(IReplayPacketHandler *packet_handler, const Packet::Entry &entry) { // Called by handlePacket() in executor thread. LOG(spam, "replay packet entry: entrySerial(%" PRIu64 "), entryType(%u)", entry.serial(), entry.type()); auto entry_serial_num = entry.serial(); packet_handler->check_serial_num(entry_serial_num); ReplayPacketDispatcher dispatcher(*packet_handler); dispatcher.replayEntry(entry); packet_handler->optionalCommit(entry_serial_num); } } // namespace ReplayTransactionLogState::ReplayTransactionLogState( const vespalib::string &name, IFeedView *& feed_view_ptr, IBucketDBHandler &bucketDBHandler, IReplayConfig &replay_config, FeedConfigStore &config_store, IIncSerialNum& inc_serial_num) : FeedState(REPLAY_TRANSACTION_LOG), _doc_type_name(name), _packet_handler(std::make_unique<TransactionLogReplayPacketHandler>(feed_view_ptr, bucketDBHandler, replay_config, config_store, inc_serial_num)) { } ReplayTransactionLogState::~ReplayTransactionLogState() = default; void ReplayTransactionLogState::receive(const PacketWrapper::SP &wrap, Executor &executor) { EntryHandler closure = makeClosure(&startDispatch, _packet_handler.get()); executor.execute(makeLambdaTask([wrap = wrap, dispatch = std::move(closure)] () mutable { handlePacket(*wrap, std::move(dispatch)); })); } } // namespace proton <commit_msg>Simplify by avoiding closure.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "feedconfigstore.h" #include "feedstates.h" #include "ifeedview.h" #include "ireplayconfig.h" #include "replaypacketdispatcher.h" #include <vespa/searchcore/proton/bucketdb/ibucketdbhandler.h> #include <vespa/searchcore/proton/feedoperation/operations.h> #include <vespa/searchcore/proton/common/eventlogger.h> #include <vespa/vespalib/util/idestructorcallback.h> #include <vespa/vespalib/util/lambdatask.h> #include <cassert> #include <vespa/log/log.h> LOG_SETUP(".proton.server.feedstates"); using search::transactionlog::Packet; using search::transactionlog::client::RPC; using search::SerialNum; using vespalib::Executor; using vespalib::makeLambdaTask; using vespalib::make_string; using proton::bucketdb::IBucketDBHandler; namespace proton { namespace { const search::SerialNum REPLAY_PROGRESS_INTERVAL = 50000; void handleProgress(TlsReplayProgress &progress, SerialNum currentSerial) { progress.updateCurrent(currentSerial); if (LOG_WOULD_LOG(event) && (LOG_WOULD_LOG(debug) || (progress.getCurrent() % REPLAY_PROGRESS_INTERVAL == 0))) { EventLogger::transactionLogReplayProgress(progress.getDomainName(), progress.getProgress(), progress.getFirst(), progress.getLast(), progress.getCurrent()); } } class TransactionLogReplayPacketHandler : public IReplayPacketHandler { IFeedView *& _feed_view_ptr; // Pointer can be changed in executor thread. IBucketDBHandler &_bucketDBHandler; IReplayConfig &_replay_config; FeedConfigStore &_config_store; IIncSerialNum &_inc_serial_num; CommitTimeTracker _commitTimeTracker; public: TransactionLogReplayPacketHandler(IFeedView *& feed_view_ptr, IBucketDBHandler &bucketDBHandler, IReplayConfig &replay_config, FeedConfigStore &config_store, IIncSerialNum &inc_serial_num) : _feed_view_ptr(feed_view_ptr), _bucketDBHandler(bucketDBHandler), _replay_config(replay_config), _config_store(config_store), _inc_serial_num(inc_serial_num), _commitTimeTracker(5ms) { } ~TransactionLogReplayPacketHandler() override = default; void replay(const PutOperation &op) override { _feed_view_ptr->handlePut(FeedToken(), op); } void replay(const RemoveOperation &op) override { _feed_view_ptr->handleRemove(FeedToken(), op); } void replay(const UpdateOperation &op) override { _feed_view_ptr->handleUpdate(FeedToken(), op); } void replay(const NoopOperation &) override {} // ignored void replay(const NewConfigOperation &op) override { _replay_config.replayConfig(op.getSerialNum()); } void replay(const DeleteBucketOperation &op) override { _feed_view_ptr->handleDeleteBucket(op); } void replay(const SplitBucketOperation &op) override { _bucketDBHandler.handleSplit(op.getSerialNum(), op.getSource(), op.getTarget1(), op.getTarget2()); } void replay(const JoinBucketsOperation &op) override { _bucketDBHandler.handleJoin(op.getSerialNum(), op.getSource1(), op.getSource2(), op.getTarget()); } void replay(const PruneRemovedDocumentsOperation &op) override { _feed_view_ptr->handlePruneRemovedDocuments(op); } void replay(const MoveOperation &op) override { _feed_view_ptr->handleMove(op, vespalib::IDestructorCallback::SP()); } void replay(const CreateBucketOperation &) override { } void replay(const CompactLidSpaceOperation &op) override { _feed_view_ptr->handleCompactLidSpace(op); } NewConfigOperation::IStreamHandler &getNewConfigStreamHandler() override { return _config_store; } const document::DocumentTypeRepo &getDeserializeRepo() override { return *_feed_view_ptr->getDocumentTypeRepo(); } void check_serial_num(search::SerialNum serial_num) override { auto exp_serial_num = _inc_serial_num.inc_serial_num(); if (exp_serial_num != serial_num) { LOG(warning, "Expected replay serial number %" PRIu64 ", got serial number %" PRIu64, exp_serial_num, serial_num); assert(exp_serial_num == serial_num); } } void optionalCommit(search::SerialNum serialNum) override { if (_commitTimeTracker.needCommit()) { _feed_view_ptr->forceCommit(serialNum); } } }; class PacketDispatcher { public: PacketDispatcher(IReplayPacketHandler *packet_handler) : _packet_handler(packet_handler) {} void handlePacket(PacketWrapper & wrap); private: void handleEntry(const Packet::Entry &entry); IReplayPacketHandler *_packet_handler; }; void PacketDispatcher::handlePacket(PacketWrapper & wrap) { vespalib::nbostream_longlivedbuf handle(wrap.packet.getHandle().data(), wrap.packet.getHandle().size()); while ( !handle.empty() ) { Packet::Entry entry; entry.deserialize(handle); handleEntry(entry); if (wrap.progress != nullptr) { handleProgress(*wrap.progress, entry.serial()); } } wrap.result = RPC::OK; wrap.gate.countDown(); } void PacketDispatcher::handleEntry(const Packet::Entry &entry) { // Called by handlePacket() in executor thread. LOG(spam, "replay packet entry: entrySerial(%" PRIu64 "), entryType(%u)", entry.serial(), entry.type()); auto entry_serial_num = entry.serial(); _packet_handler->check_serial_num(entry_serial_num); ReplayPacketDispatcher dispatcher(*_packet_handler); dispatcher.replayEntry(entry); _packet_handler->optionalCommit(entry_serial_num); } } // namespace ReplayTransactionLogState::ReplayTransactionLogState( const vespalib::string &name, IFeedView *& feed_view_ptr, IBucketDBHandler &bucketDBHandler, IReplayConfig &replay_config, FeedConfigStore &config_store, IIncSerialNum& inc_serial_num) : FeedState(REPLAY_TRANSACTION_LOG), _doc_type_name(name), _packet_handler(std::make_unique<TransactionLogReplayPacketHandler>(feed_view_ptr, bucketDBHandler, replay_config, config_store, inc_serial_num)) { } ReplayTransactionLogState::~ReplayTransactionLogState() = default; void ReplayTransactionLogState::receive(const PacketWrapper::SP &wrap, Executor &executor) { executor.execute(makeLambdaTask([this, wrap = wrap] () { PacketDispatcher dispatcher(_packet_handler.get()); dispatcher.handlePacket(*wrap); })); } } // namespace proton <|endoftext|>
<commit_before>/** * \file * \brief SysTick_Handler() for ARMv6-M and ARMv7-M * * \author Copyright (C) 2014-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/internal/scheduler/getScheduler.hpp" #include "distortos/internal/scheduler/Scheduler.hpp" #include "distortos/architecture/requestContextSwitch.hpp" #ifdef CONFIG_CHECK_STACK_GUARD_SYSTEM_TICK_ENABLE #include "distortos/chip/CMSIS-proxy.h" #include "distortos/FATAL_ERROR.h" #endif // def CONFIG_CHECK_STACK_GUARD_SYSTEM_TICK_ENABLE /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ /** * \brief SysTick_Handler() for ARMv6-M and ARMv7-M * * Tick interrupt of scheduler. This function also checks stack pointer range when this functionality is enabled - if * the check fails, FATAL_ERROR() is called. */ extern "C" void SysTick_Handler() { auto& scheduler = distortos::internal::getScheduler(); #ifdef CONFIG_CHECK_STACK_GUARD_SYSTEM_TICK_ENABLE const auto stackPointer = reinterpret_cast<const void*>(__get_PSP()); if (scheduler.getCurrentThreadControlBlock().getStack().checkStackPointer(stackPointer) == false) FATAL_ERROR("Stack overflow detected!"); #endif // def CONFIG_CHECK_STACK_GUARD_SYSTEM_TICK_ENABLE const auto contextSwitchRequired = scheduler.tickInterruptHandler(); if (contextSwitchRequired == true) distortos::architecture::requestContextSwitch(); } <commit_msg>Fix conditions for stack pointer range checks in SysTick_Handler()<commit_after>/** * \file * \brief SysTick_Handler() for ARMv6-M and ARMv7-M * * \author Copyright (C) 2014-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "distortos/internal/scheduler/getScheduler.hpp" #include "distortos/internal/scheduler/Scheduler.hpp" #include "distortos/architecture/requestContextSwitch.hpp" #ifdef CONFIG_CHECK_STACK_POINTER_RANGE_SYSTEM_TICK_ENABLE #include "distortos/chip/CMSIS-proxy.h" #include "distortos/FATAL_ERROR.h" #endif // def CONFIG_CHECK_STACK_POINTER_RANGE_SYSTEM_TICK_ENABLE /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ /** * \brief SysTick_Handler() for ARMv6-M and ARMv7-M * * Tick interrupt of scheduler. This function also checks stack pointer range when this functionality is enabled - if * the check fails, FATAL_ERROR() is called. */ extern "C" void SysTick_Handler() { auto& scheduler = distortos::internal::getScheduler(); #ifdef CONFIG_CHECK_STACK_POINTER_RANGE_SYSTEM_TICK_ENABLE const auto stackPointer = reinterpret_cast<const void*>(__get_PSP()); if (scheduler.getCurrentThreadControlBlock().getStack().checkStackPointer(stackPointer) == false) FATAL_ERROR("Stack overflow detected!"); #endif // def CONFIG_CHECK_STACK_POINTER_RANGE_SYSTEM_TICK_ENABLE const auto contextSwitchRequired = scheduler.tickInterruptHandler(); if (contextSwitchRequired == true) distortos::architecture::requestContextSwitch(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pam.hxx,v $ * * $Revision: 1.17 $ * * last change: $Author: hr $ $Date: 2007-09-27 08:07:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _PAM_HXX #define _PAM_HXX #include <stddef.h> // fuer MemPool #ifndef _GEN_HXX //autogen #include <tools/gen.hxx> #endif #ifndef _SVMEMPOOL_HXX //autogen #include <tools/mempool.hxx> #endif #ifndef _CSHTYP_HXX #include <cshtyp.hxx> // fuer die Funktions-Definitionen #endif #ifndef _RING_HXX #include <ring.hxx> // Superklasse #endif #ifndef _INDEX_HXX #include <index.hxx> // fuer SwIndex #endif #ifndef _NDINDEX_HXX #include <ndindex.hxx> // fuer SwNodeIndex #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif class SwFmt; class SfxPoolItem; class SfxItemSet; class SwDoc; class SwNode; class SwCntntNode; class SwPaM; namespace com { namespace sun { namespace star { namespace util { struct SearchOptions; } } } } namespace utl { class TextSearch; } struct SwPosition { SwNodeIndex nNode; SwIndex nContent; SwPosition( const SwNode& rNode ); SwPosition( const SwNodeIndex &rNode ); SwPosition( const SwNodeIndex &rNode, const SwIndex &rCntnt ); /* @@@MAINTAINABILITY-HORROR@@@ SwPosition desperately needs a constructor SwPosition( const SwNode& rNode, xub_StrLen nOffset ); */ SwPosition( const SwPosition & ); SwPosition &operator=(const SwPosition &); // #111827# /** Returns the document this position is in. @return the document this position is in. */ SwDoc * GetDoc() const; BOOL operator < (const SwPosition &) const; BOOL operator > (const SwPosition &) const; BOOL operator <=(const SwPosition &) const; BOOL operator >=(const SwPosition &) const; BOOL operator ==(const SwPosition &) const; BOOL operator !=(const SwPosition &) const; }; // das Ergebnis eines Positions Vergleiches enum SwComparePosition { POS_BEFORE, // Pos1 liegt vor Pos2 POS_BEHIND, // Pos1 liegt hinter Pos2 POS_INSIDE, // Pos1 liegt vollstaendig in Pos2 POS_OUTSIDE, // Pos2 liegt vollstaendig in Pos1 POS_EQUAL, // Pos1 ist genauso gross wie Pos2 POS_OVERLAP_BEFORE, // Pos1 ueberlappt Pos2 am Anfang POS_OVERLAP_BEHIND, // Pos1 ueberlappt Pos2 am Ende POS_COLLIDE_START, // Pos1 Start stoesst an Pos2 Ende POS_COLLIDE_END // Pos1 End stoesst an Pos2 Start }; SwComparePosition ComparePosition( const SwPosition& rStt1, const SwPosition& rEnd1, const SwPosition& rStt2, const SwPosition& rEnd2 ); SwComparePosition ComparePosition( const unsigned long nStt1, const unsigned long nEnd1, const unsigned long nStt2, const unsigned long nEnd2 ); // SwPointAndMark / SwPaM struct SwMoveFnCollection; typedef SwMoveFnCollection* SwMoveFn; SW_DLLPUBLIC extern SwMoveFn fnMoveForward; // SwPam::Move()/Find() default argument. extern SwMoveFn fnMoveBackward; typedef BOOL (*SwGoInDoc)( SwPaM& rPam, SwMoveFn fnMove ); extern SwGoInDoc fnGoDoc; extern SwGoInDoc fnGoSection; extern SwGoInDoc fnGoNode; SW_DLLPUBLIC extern SwGoInDoc fnGoCntnt; // SwPam::Move() default argument. extern SwGoInDoc fnGoCntntCells; extern SwGoInDoc fnGoCntntSkipHidden; extern SwGoInDoc fnGoCntntCellsSkipHidden; void _InitPam(); class SwPaM : public Ring { SwPosition aBound1; SwPosition aBound2; SwPosition *pPoint; SwPosition *pMark; BOOL bIsInFrontOfLabel; SwPaM* MakeRegion( SwMoveFn fnMove, const SwPaM * pOrigRg = 0 ); public: SwPaM( const SwPosition& rPos, SwPaM* pRing = 0 ); SwPaM( const SwPosition& rMk, const SwPosition& rPt, SwPaM* pRing = 0 ); SwPaM( const SwNodeIndex& rMk, const SwNodeIndex& rPt, long nMkOffset = 0, long nPtOffset = 0, SwPaM* pRing = 0 ); SwPaM( const SwNode& rMk, const SwNode& rPt, long nMkOffset = 0, long nPtOffset = 0, SwPaM* pRing = 0 ); SwPaM( const SwNodeIndex& rMk, xub_StrLen nMkCntnt, const SwNodeIndex& rPt, xub_StrLen nPtCntnt, SwPaM* pRing = 0 ); SwPaM( const SwNode& rMk, xub_StrLen nMkCntnt, const SwNode& rPt, xub_StrLen nPtCntnt, SwPaM* pRing = 0 ); SwPaM( const SwNode& rNd, xub_StrLen nCntnt = 0, SwPaM* pRing = 0 ); SwPaM( const SwNodeIndex& rNd, xub_StrLen nCntnt = 0, SwPaM* pRing = 0 ); virtual ~SwPaM(); // @@@ semantic: no copy ctor. SwPaM( SwPaM & ); // @@@ semantic: no copy assignment for super class Ring. SwPaM& operator=( const SwPaM & ); // Bewegen des Cursors BOOL Move( SwMoveFn fnMove = fnMoveForward, SwGoInDoc fnGo = fnGoCntnt ); // Suchen BYTE Find( const com::sun::star::util::SearchOptions& rSearchOpt, utl::TextSearch& rSTxt, SwMoveFn fnMove = fnMoveForward, const SwPaM *pPam =0, BOOL bInReadOnly = FALSE); BOOL Find( const SwFmt& rFmt, SwMoveFn fnMove = fnMoveForward, const SwPaM *pPam =0, BOOL bInReadOnly = FALSE); BOOL Find( const SfxPoolItem& rAttr, BOOL bValue = TRUE, SwMoveFn fnMove = fnMoveForward, const SwPaM *pPam =0, BOOL bInReadOnly = FALSE ); BOOL Find( const SfxItemSet& rAttr, BOOL bNoColls = FALSE, SwMoveFn fnMove = fnMoveForward, const SwPaM *pPam =0, BOOL bInReadOnly = FALSE ); inline BOOL IsInFrontOfLabel() const { return bIsInFrontOfLabel; } inline void _SetInFrontOfLabel( BOOL bNew ) { bIsInFrontOfLabel = bNew; } virtual void SetMark(); void DeleteMark() { pMark = pPoint; } #ifdef PRODUCT void Exchange() { if(pPoint != pMark) { SwPosition *pTmp = pPoint; pPoint = pMark; pMark = pTmp; } } #else void Exchange(); #endif /* * Undokumented Feature: Liefert zurueck, ob das Pam ueber * eine Selektion verfuegt oder nicht. Definition einer * Selektion: Point und Mark zeigen auf unterschiedliche * Puffer. */ BOOL HasMark() const { return pPoint == pMark? FALSE : TRUE; } const SwPosition *GetPoint() const { return pPoint; } SwPosition *GetPoint() { return pPoint; } const SwPosition *GetMark() const { return pMark; } SwPosition *GetMark() { return pMark; } const SwPosition *Start() const { return (*pPoint) <= (*pMark)? pPoint: pMark; } SwPosition *Start() { return (*pPoint) <= (*pMark)? pPoint: pMark; } const SwPosition *End() const { return (*pPoint) > (*pMark)? pPoint: pMark; } SwPosition *End() { return (*pPoint) > (*pMark)? pPoint: pMark; } // erfrage vom SwPaM den aktuellen Node/ContentNode am SPoint / Mark SwNode* GetNode( BOOL bPoint = TRUE ) const { return &( bPoint ? pPoint->nNode : pMark->nNode ).GetNode(); } SwCntntNode* GetCntntNode( BOOL bPoint = TRUE ) const { return ( bPoint ? pPoint->nNode : pMark->nNode ).GetNode().GetCntntNode(); } /** Normalizes PaM, i.e. sort point and mark. @param bPointFirst TRUE: If the point is behind the mark then swap. FALSE: If the mark is behind the point then swap. */ SwPaM & Normalize(BOOL bPointFirst = TRUE); // erfrage vom SwPaM das Dokument, in dem er angemeldet ist SwDoc* GetDoc() const { return pPoint->nNode.GetNode().GetDoc(); } SwPosition& GetBound( BOOL bOne = TRUE ) { return bOne ? aBound1 : aBound2; } const SwPosition& GetBound( BOOL bOne = TRUE ) const { return bOne ? aBound1 : aBound2; } // erfrage die Seitennummer auf der der Cursor steht USHORT GetPageNum( BOOL bAtPoint = TRUE, const Point* pLayPos = 0 ); // steht in etwas geschuetztem oder in die Selektion umspannt // etwas geschuetztes. BOOL HasReadonlySel( bool bFormView ) const; BOOL ContainsPosition(const SwPosition & rPos) { return *Start() <= rPos && rPos <= *End(); } DECL_FIXEDMEMPOOL_NEWDEL(SwPaM); String GetTxt() const; }; BOOL CheckNodesRange( const SwNodeIndex&, const SwNodeIndex&, BOOL ); BOOL GoInCntnt( SwPaM & rPam, SwMoveFn fnMove ); #endif // _PAM_HXX <commit_msg>INTEGRATION: CWS sw8u10bf05 (1.17.138); FILE MERGED 2008/01/11 08:03:28 ama 1.17.138.1: Fix #b6640846#: Don't skip empty paragraphs<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pam.hxx,v $ * * $Revision: 1.18 $ * * last change: $Author: vg $ $Date: 2008-03-18 15:53:12 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _PAM_HXX #define _PAM_HXX #include <stddef.h> // fuer MemPool #ifndef _GEN_HXX //autogen #include <tools/gen.hxx> #endif #ifndef _SVMEMPOOL_HXX //autogen #include <tools/mempool.hxx> #endif #ifndef _CSHTYP_HXX #include <cshtyp.hxx> // fuer die Funktions-Definitionen #endif #ifndef _RING_HXX #include <ring.hxx> // Superklasse #endif #ifndef _INDEX_HXX #include <index.hxx> // fuer SwIndex #endif #ifndef _NDINDEX_HXX #include <ndindex.hxx> // fuer SwNodeIndex #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif class SwFmt; class SfxPoolItem; class SfxItemSet; class SwDoc; class SwNode; class SwCntntNode; class SwPaM; namespace com { namespace sun { namespace star { namespace util { struct SearchOptions; } } } } namespace utl { class TextSearch; } struct SwPosition { SwNodeIndex nNode; SwIndex nContent; SwPosition( const SwNode& rNode ); SwPosition( const SwNodeIndex &rNode ); SwPosition( const SwNodeIndex &rNode, const SwIndex &rCntnt ); /* @@@MAINTAINABILITY-HORROR@@@ SwPosition desperately needs a constructor SwPosition( const SwNode& rNode, xub_StrLen nOffset ); */ SwPosition( const SwPosition & ); SwPosition &operator=(const SwPosition &); // #111827# /** Returns the document this position is in. @return the document this position is in. */ SwDoc * GetDoc() const; BOOL operator < (const SwPosition &) const; BOOL operator > (const SwPosition &) const; BOOL operator <=(const SwPosition &) const; BOOL operator >=(const SwPosition &) const; BOOL operator ==(const SwPosition &) const; BOOL operator !=(const SwPosition &) const; }; // das Ergebnis eines Positions Vergleiches enum SwComparePosition { POS_BEFORE, // Pos1 liegt vor Pos2 POS_BEHIND, // Pos1 liegt hinter Pos2 POS_INSIDE, // Pos1 liegt vollstaendig in Pos2 POS_OUTSIDE, // Pos2 liegt vollstaendig in Pos1 POS_EQUAL, // Pos1 ist genauso gross wie Pos2 POS_OVERLAP_BEFORE, // Pos1 ueberlappt Pos2 am Anfang POS_OVERLAP_BEHIND, // Pos1 ueberlappt Pos2 am Ende POS_COLLIDE_START, // Pos1 Start stoesst an Pos2 Ende POS_COLLIDE_END // Pos1 End stoesst an Pos2 Start }; SwComparePosition ComparePosition( const SwPosition& rStt1, const SwPosition& rEnd1, const SwPosition& rStt2, const SwPosition& rEnd2 ); SwComparePosition ComparePosition( const unsigned long nStt1, const unsigned long nEnd1, const unsigned long nStt2, const unsigned long nEnd2 ); // SwPointAndMark / SwPaM struct SwMoveFnCollection; typedef SwMoveFnCollection* SwMoveFn; SW_DLLPUBLIC extern SwMoveFn fnMoveForward; // SwPam::Move()/Find() default argument. extern SwMoveFn fnMoveBackward; typedef BOOL (*SwGoInDoc)( SwPaM& rPam, SwMoveFn fnMove ); extern SwGoInDoc fnGoDoc; extern SwGoInDoc fnGoSection; extern SwGoInDoc fnGoNode; SW_DLLPUBLIC extern SwGoInDoc fnGoCntnt; // SwPam::Move() default argument. extern SwGoInDoc fnGoCntntCells; extern SwGoInDoc fnGoCntntSkipHidden; extern SwGoInDoc fnGoCntntCellsSkipHidden; void _InitPam(); class SwPaM : public Ring { SwPosition aBound1; SwPosition aBound2; SwPosition *pPoint; SwPosition *pMark; BOOL bIsInFrontOfLabel; SwPaM* MakeRegion( SwMoveFn fnMove, const SwPaM * pOrigRg = 0 ); public: SwPaM( const SwPosition& rPos, SwPaM* pRing = 0 ); SwPaM( const SwPosition& rMk, const SwPosition& rPt, SwPaM* pRing = 0 ); SwPaM( const SwNodeIndex& rMk, const SwNodeIndex& rPt, long nMkOffset = 0, long nPtOffset = 0, SwPaM* pRing = 0 ); SwPaM( const SwNode& rMk, const SwNode& rPt, long nMkOffset = 0, long nPtOffset = 0, SwPaM* pRing = 0 ); SwPaM( const SwNodeIndex& rMk, xub_StrLen nMkCntnt, const SwNodeIndex& rPt, xub_StrLen nPtCntnt, SwPaM* pRing = 0 ); SwPaM( const SwNode& rMk, xub_StrLen nMkCntnt, const SwNode& rPt, xub_StrLen nPtCntnt, SwPaM* pRing = 0 ); SwPaM( const SwNode& rNd, xub_StrLen nCntnt = 0, SwPaM* pRing = 0 ); SwPaM( const SwNodeIndex& rNd, xub_StrLen nCntnt = 0, SwPaM* pRing = 0 ); virtual ~SwPaM(); // @@@ semantic: no copy ctor. SwPaM( SwPaM & ); // @@@ semantic: no copy assignment for super class Ring. SwPaM& operator=( const SwPaM & ); // Bewegen des Cursors BOOL Move( SwMoveFn fnMove = fnMoveForward, SwGoInDoc fnGo = fnGoCntnt ); // Suchen BYTE Find( const com::sun::star::util::SearchOptions& rSearchOpt, utl::TextSearch& rSTxt, SwMoveFn fnMove = fnMoveForward, const SwPaM *pPam =0, BOOL bInReadOnly = FALSE); BOOL Find( const SwFmt& rFmt, SwMoveFn fnMove = fnMoveForward, const SwPaM *pPam =0, BOOL bInReadOnly = FALSE); BOOL Find( const SfxPoolItem& rAttr, BOOL bValue = TRUE, SwMoveFn fnMove = fnMoveForward, const SwPaM *pPam =0, BOOL bInReadOnly = FALSE ); BOOL Find( const SfxItemSet& rAttr, BOOL bNoColls, SwMoveFn fnMove, const SwPaM *pPam, BOOL bInReadOnly, BOOL bMoveFirst ); inline BOOL IsInFrontOfLabel() const { return bIsInFrontOfLabel; } inline void _SetInFrontOfLabel( BOOL bNew ) { bIsInFrontOfLabel = bNew; } virtual void SetMark(); void DeleteMark() { pMark = pPoint; } #ifdef PRODUCT void Exchange() { if(pPoint != pMark) { SwPosition *pTmp = pPoint; pPoint = pMark; pMark = pTmp; } } #else void Exchange(); #endif /* * Undokumented Feature: Liefert zurueck, ob das Pam ueber * eine Selektion verfuegt oder nicht. Definition einer * Selektion: Point und Mark zeigen auf unterschiedliche * Puffer. */ BOOL HasMark() const { return pPoint == pMark? FALSE : TRUE; } const SwPosition *GetPoint() const { return pPoint; } SwPosition *GetPoint() { return pPoint; } const SwPosition *GetMark() const { return pMark; } SwPosition *GetMark() { return pMark; } const SwPosition *Start() const { return (*pPoint) <= (*pMark)? pPoint: pMark; } SwPosition *Start() { return (*pPoint) <= (*pMark)? pPoint: pMark; } const SwPosition *End() const { return (*pPoint) > (*pMark)? pPoint: pMark; } SwPosition *End() { return (*pPoint) > (*pMark)? pPoint: pMark; } // erfrage vom SwPaM den aktuellen Node/ContentNode am SPoint / Mark SwNode* GetNode( BOOL bPoint = TRUE ) const { return &( bPoint ? pPoint->nNode : pMark->nNode ).GetNode(); } SwCntntNode* GetCntntNode( BOOL bPoint = TRUE ) const { return ( bPoint ? pPoint->nNode : pMark->nNode ).GetNode().GetCntntNode(); } /** Normalizes PaM, i.e. sort point and mark. @param bPointFirst TRUE: If the point is behind the mark then swap. FALSE: If the mark is behind the point then swap. */ SwPaM & Normalize(BOOL bPointFirst = TRUE); // erfrage vom SwPaM das Dokument, in dem er angemeldet ist SwDoc* GetDoc() const { return pPoint->nNode.GetNode().GetDoc(); } SwPosition& GetBound( BOOL bOne = TRUE ) { return bOne ? aBound1 : aBound2; } const SwPosition& GetBound( BOOL bOne = TRUE ) const { return bOne ? aBound1 : aBound2; } // erfrage die Seitennummer auf der der Cursor steht USHORT GetPageNum( BOOL bAtPoint = TRUE, const Point* pLayPos = 0 ); // steht in etwas geschuetztem oder in die Selektion umspannt // etwas geschuetztes. BOOL HasReadonlySel( bool bFormView ) const; BOOL ContainsPosition(const SwPosition & rPos) { return *Start() <= rPos && rPos <= *End(); } DECL_FIXEDMEMPOOL_NEWDEL(SwPaM); String GetTxt() const; }; BOOL CheckNodesRange( const SwNodeIndex&, const SwNodeIndex&, BOOL ); BOOL GoInCntnt( SwPaM & rPam, SwMoveFn fnMove ); #endif // _PAM_HXX <|endoftext|>
<commit_before>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2016 */ /* * OTRadValve SIM900 tests. */ #include <gtest/gtest.h> #include <stdio.h> #include <stdlib.h> #include "OTSIM900Link.h" // Test the getter function definitely does what it should. TEST(OTSIM900Link, getterFunction) { const char SIM900_PIN[] = "1111"; const OTSIM900Link::OTSIM900LinkConfig_t SIM900Config(false, SIM900_PIN, NULL, NULL, NULL); EXPECT_EQ(SIM900_PIN[0], SIM900Config.get((const uint8_t *)SIM900Config.PIN)); } // Test for general sanity of OTSIM900Link. // Make sure that an instance can be created and does not die horribly. // Underlying simulated serial/SIM900 never accepts data or responds, eg like a dead card. TEST(OTSIM900Link,basicsDeadCard) { const bool verbose = false; class NULLSerialStream final : public Stream { public: void begin(unsigned long) { } void begin(unsigned long, uint8_t); void end(); virtual size_t write(uint8_t c) override { if(verbose) { fprintf(stderr, "%c\n", (char) c); } return(0); } virtual int available() override { return(-1); } virtual int read() override { return(-1); } virtual int peek() override { return(-1); } virtual void flush() override { } }; const char SIM900_PIN[] = "1111"; const char SIM900_APN[] = "apn"; const char SIM900_UDP_ADDR[] = "0.0.0.0"; // ORS server const char SIM900_UDP_PORT[] = "9999"; const OTSIM900Link::OTSIM900LinkConfig_t SIM900Config(false, SIM900_PIN, SIM900_APN, SIM900_UDP_ADDR, SIM900_UDP_PORT); const OTRadioLink::OTRadioChannelConfig l0Config(&SIM900Config, true); OTSIM900Link::OTSIM900Link<0, 0, 0, NULLSerialStream> l0; EXPECT_TRUE(l0.configure(1, &l0Config)); EXPECT_TRUE(l0.begin()); EXPECT_EQ(OTSIM900Link::GET_STATE, l0._getState()); // Try to hang just by calling poll() repeatedly. for(int i = 0; i < 100; ++i) { l0.poll(); } EXPECT_EQ(OTSIM900Link::PANIC, l0._getState()) << "should keep trying to start with GET_STATE, RETRY_GET_STATE and START_UP"; // ... l0.end(); } // Test for general sanity of OTSIM900Link. // Make sure that an instance can be created and does not die horribly. // Underlying simulated serial/SIM900 accepts output, does not respond. namespace B1 { const bool verbose = true; // Does a trivial simulation of SIM900, responding to start of 'A' of AT command. // Exercises every major non-PANIC state of the OTSIM900Link implementation. class TrivialSimulator final : public Stream { public: // Events exposed. static bool haveSeenCommandStart; private: // Command being collected from OTSIM900Link. bool waitingForCommand = true; bool collectingCommand = false; // Entire request starting "AT"; no trailing CR or LF stored. std::string command; // Reply (postfix) being returned to OTSIM900Link: empty if none. std::string reply; public: void begin(unsigned long) { } void begin(unsigned long, uint8_t); void end(); virtual size_t write(uint8_t uc) override { const char c = (char)uc; if(waitingForCommand) { // Look for leading 'A' of 'AT' to start a command. if('A' == c) { waitingForCommand = false; collectingCommand = true; command = 'A'; haveSeenCommandStart = true; // Note at least one command start. } } else { // Look for CR (or LF) to terminate a command. if(('\r' == c) || ('\n' == c)) { waitingForCommand = true; collectingCommand = false; if(verbose) { fprintf(stderr, "command received: %s\n", command.c_str()); } // Respond to particular commands... if("AT" == command) { reply = "AT\r"; } // Relevant states: GET_STATE, RETRY_GET_STATE, START_UP // DHD20161101: "No PIN" response (deliberately not typical SIM900 response) resulted in SIGSEGV from not checking getResponse() result for NULL. // Should futz/vary the response to check sensitivity. // TODO: have at least one response be expected SIM900 answer for no-PIN SIM. else if("AT+CPIN?" == command) { reply = (random() & 1) ? "No PIN\r" : "OK READY\r"; } // Relevant states: CHECK_PIN else if("AT+CREG?" == command) { reply = (random() & 1) ? "+CREG: 0,0\r" : "+CREG: 0,5\r"; } // Relevant states: WAIT_FOR_REGISTRATION else if("AT+CSTT=apn" == command) { reply = (random() & 1) ? "gbfhs\r" : "AT+CSTT\r\n\r\nOK\r"; } // Relevant states: SET_APN } else if(collectingCommand) { command += c; } } if(verbose) { if(isprint(c)) { fprintf(stderr, "<%c\n", c); } else { fprintf(stderr, "< %d\n", (int)c); } } return(1); } virtual int read() override { if(0 == reply.size()) { return(-1); } const char c = reply[0]; if(verbose) { if(isprint(c)) { fprintf(stderr, ">%c\n", c); } else { fprintf(stderr, "> %d\n", (int)c); } } reply.erase(0, 1); return(c); } virtual int available() override { return(-1); } virtual int peek() override { return(-1); } virtual void flush() override { } }; // Events exposed. bool TrivialSimulator::haveSeenCommandStart; } TEST(OTSIM900Link,basicsSimpleSimulator) { // const bool verbose = true; srandom(::testing::UnitTest::GetInstance()->random_seed()); // Seed random() for use in simulator; --gtest_shuffle will force it to change. const char SIM900_PIN[] = "1111"; const char SIM900_APN[] = "apn"; const char SIM900_UDP_ADDR[] = "0.0.0.0"; // ORS server const char SIM900_UDP_PORT[] = "9999"; const OTSIM900Link::OTSIM900LinkConfig_t SIM900Config(false, SIM900_PIN, SIM900_APN, SIM900_UDP_ADDR, SIM900_UDP_PORT); const OTRadioLink::OTRadioChannelConfig l0Config(&SIM900Config, true); ASSERT_FALSE(B1::TrivialSimulator::haveSeenCommandStart); OTSIM900Link::OTSIM900Link<0, 0, 0, B1::TrivialSimulator> l0; EXPECT_TRUE(l0.configure(1, &l0Config)); EXPECT_TRUE(l0.begin()); EXPECT_EQ(OTSIM900Link::GET_STATE, l0._getState()); // Try to hang just by calling poll() repeatedly. for(int i = 0; i < 100; ++i) { l0.poll(); } EXPECT_TRUE(B1::TrivialSimulator::haveSeenCommandStart) << "should see some attempt to communicate with SIM900"; EXPECT_LE(OTSIM900Link::WAIT_FOR_REGISTRATION, l0._getState()) << "should make it to at least WAIT_FOR_REGISTRATION"; // ... l0.end(); } <commit_msg>TODO-1034: improved description of test goals<commit_after>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2016 */ /* * OTRadValve SIM900 tests. */ #include <gtest/gtest.h> #include <stdio.h> #include <stdlib.h> #include "OTSIM900Link.h" // Test the getter function definitely does what it should. TEST(OTSIM900Link, getterFunction) { const char SIM900_PIN[] = "1111"; const OTSIM900Link::OTSIM900LinkConfig_t SIM900Config(false, SIM900_PIN, NULL, NULL, NULL); EXPECT_EQ(SIM900_PIN[0], SIM900Config.get((const uint8_t *)SIM900Config.PIN)); } // Test for general sanity of OTSIM900Link. // Make sure that an instance can be created and does not die horribly. // Underlying simulated serial/SIM900 never accepts data or responds, eg like a dead card. TEST(OTSIM900Link,basicsDeadCard) { const bool verbose = false; class NULLSerialStream final : public Stream { public: void begin(unsigned long) { } void begin(unsigned long, uint8_t); void end(); virtual size_t write(uint8_t c) override { if(verbose) { fprintf(stderr, "%c\n", (char) c); } return(0); } virtual int available() override { return(-1); } virtual int read() override { return(-1); } virtual int peek() override { return(-1); } virtual void flush() override { } }; const char SIM900_PIN[] = "1111"; const char SIM900_APN[] = "apn"; const char SIM900_UDP_ADDR[] = "0.0.0.0"; // ORS server const char SIM900_UDP_PORT[] = "9999"; const OTSIM900Link::OTSIM900LinkConfig_t SIM900Config(false, SIM900_PIN, SIM900_APN, SIM900_UDP_ADDR, SIM900_UDP_PORT); const OTRadioLink::OTRadioChannelConfig l0Config(&SIM900Config, true); OTSIM900Link::OTSIM900Link<0, 0, 0, NULLSerialStream> l0; EXPECT_TRUE(l0.configure(1, &l0Config)); EXPECT_TRUE(l0.begin()); EXPECT_EQ(OTSIM900Link::GET_STATE, l0._getState()); // Try to hang just by calling poll() repeatedly. for(int i = 0; i < 100; ++i) { l0.poll(); } EXPECT_EQ(OTSIM900Link::PANIC, l0._getState()) << "should keep trying to start with GET_STATE, RETRY_GET_STATE and START_UP"; // ... l0.end(); } // Test for general sanity of OTSIM900Link. // Make sure that an instance can be created and does not die horribly. // Underlying simulated serial/SIM900 accepts output, does not respond. namespace B1 { const bool verbose = true; // Does a trivial simulation of SIM900, responding to start of 'A' of AT command. // Exercises every major non-PANIC state of the OTSIM900Link implementation. // Is meant to mainly walk through all the normal expected SIM900 behaviour when all is well. // Other test can look at error handling including unexpected/garbage responses. class TrivialSimulator final : public Stream { public: // Events exposed. static bool haveSeenCommandStart; private: // Command being collected from OTSIM900Link. bool waitingForCommand = true; bool collectingCommand = false; // Entire request starting "AT"; no trailing CR or LF stored. std::string command; // Reply (postfix) being returned to OTSIM900Link: empty if none. std::string reply; public: void begin(unsigned long) { } void begin(unsigned long, uint8_t); void end(); virtual size_t write(uint8_t uc) override { const char c = (char)uc; if(waitingForCommand) { // Look for leading 'A' of 'AT' to start a command. if('A' == c) { waitingForCommand = false; collectingCommand = true; command = 'A'; haveSeenCommandStart = true; // Note at least one command start. } } else { // Look for CR (or LF) to terminate a command. if(('\r' == c) || ('\n' == c)) { waitingForCommand = true; collectingCommand = false; if(verbose) { fprintf(stderr, "command received: %s\n", command.c_str()); } // Respond to particular commands... if("AT" == command) { reply = "AT\r"; } // Relevant states: GET_STATE, RETRY_GET_STATE, START_UP // DHD20161101: "No PIN" response (deliberately not typical SIM900 response) resulted in SIGSEGV from not checking getResponse() result for NULL. // Should futz/vary the response to check sensitivity. // TODO: have at least one response be expected SIM900 answer for no-PIN SIM. else if("AT+CPIN?" == command) { reply = (random() & 1) ? "No PIN\r" : "OK READY\r"; } // Relevant states: CHECK_PIN else if("AT+CREG?" == command) { reply = (random() & 1) ? "+CREG: 0,0\r" : "+CREG: 0,5\r"; } // Relevant states: WAIT_FOR_REGISTRATION else if("AT+CSTT=apn" == command) { reply = (random() & 1) ? "gbfhs\r" : "AT+CSTT\r\n\r\nOK\r"; } // Relevant states: SET_APN } else if(collectingCommand) { command += c; } } if(verbose) { if(isprint(c)) { fprintf(stderr, "<%c\n", c); } else { fprintf(stderr, "< %d\n", (int)c); } } return(1); } virtual int read() override { if(0 == reply.size()) { return(-1); } const char c = reply[0]; if(verbose) { if(isprint(c)) { fprintf(stderr, ">%c\n", c); } else { fprintf(stderr, "> %d\n", (int)c); } } reply.erase(0, 1); return(c); } virtual int available() override { return(-1); } virtual int peek() override { return(-1); } virtual void flush() override { } }; // Events exposed. bool TrivialSimulator::haveSeenCommandStart; } TEST(OTSIM900Link,basicsSimpleSimulator) { // const bool verbose = true; srandom(::testing::UnitTest::GetInstance()->random_seed()); // Seed random() for use in simulator; --gtest_shuffle will force it to change. const char SIM900_PIN[] = "1111"; const char SIM900_APN[] = "apn"; const char SIM900_UDP_ADDR[] = "0.0.0.0"; // ORS server const char SIM900_UDP_PORT[] = "9999"; const OTSIM900Link::OTSIM900LinkConfig_t SIM900Config(false, SIM900_PIN, SIM900_APN, SIM900_UDP_ADDR, SIM900_UDP_PORT); const OTRadioLink::OTRadioChannelConfig l0Config(&SIM900Config, true); ASSERT_FALSE(B1::TrivialSimulator::haveSeenCommandStart); OTSIM900Link::OTSIM900Link<0, 0, 0, B1::TrivialSimulator> l0; EXPECT_TRUE(l0.configure(1, &l0Config)); EXPECT_TRUE(l0.begin()); EXPECT_EQ(OTSIM900Link::GET_STATE, l0._getState()); // Try to hang just by calling poll() repeatedly. for(int i = 0; i < 100; ++i) { l0.poll(); } EXPECT_TRUE(B1::TrivialSimulator::haveSeenCommandStart) << "should see some attempt to communicate with SIM900"; EXPECT_LE(OTSIM900Link::WAIT_FOR_REGISTRATION, l0._getState()) << "should make it to at least WAIT_FOR_REGISTRATION"; // ... l0.end(); } <|endoftext|>
<commit_before>/* yahoochatselectordialog.h Copyright (c) 2006 by Andre Duffeck <andre@duffeck.de> Kopete (c) 2002-2006 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * 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. * * * ************************************************************************* */ #include <QDomDocument> #include <QTreeWidgetItem> #include <QHeaderView> #include "ui_yahoochatselectorwidgetbase.h" #include "yahoochatselectordialog.h" YahooChatSelectorDialog::YahooChatSelectorDialog( QWidget *parent ) : KDialog( parent ) { setCaption( i18n( "Choose a chat room..." ) ); setButtons( KDialog::Ok | KDialog::Cancel ); setDefaultButton( KDialog::Ok ); showButtonSeparator( true ); mUi = new Ui_YahooChatSelectorWidgetBase(); QBoxLayout *layout = new QVBoxLayout(this); QWidget *widget = new QWidget(this); mUi->setupUi(widget); layout->addWidget(widget); setMainWidget(widget); mUi->treeCategories->header()->hide(); mUi->treeRooms->header()->hide(); QTreeWidgetItem *loading = new QTreeWidgetItem(mUi->treeCategories); loading->setText( 0, i18n("Loading...") ); mUi->treeCategories->addTopLevelItem( loading ); connect(mUi->treeCategories, SIGNAL(currentItemChanged ( QTreeWidgetItem *, QTreeWidgetItem * )), this, SLOT(slotCategorySelectionChanged( QTreeWidgetItem *, QTreeWidgetItem * ))); connect(mUi->treeRooms, SIGNAL(itemDoubleClicked( QTreeWidgetItem *, int )), this, SLOT(slotChatRoomDoubleClicked( QTreeWidgetItem *, int )) ); } YahooChatSelectorDialog::~YahooChatSelectorDialog() { delete mUi; } void YahooChatSelectorDialog::slotCategorySelectionChanged( QTreeWidgetItem *newItem, QTreeWidgetItem *oldItem ) { Q_UNUSED( oldItem ); kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << "Selected Category: " << newItem->text( 0 ) << "(" << newItem->data( 0, Qt::UserRole ).toInt() << ")" << endl; mUi->treeRooms->clear(); QTreeWidgetItem *loading = new QTreeWidgetItem(mUi->treeRooms); loading->setText( 0, i18n("Loading...") ); mUi->treeRooms->addTopLevelItem( loading ); Yahoo::ChatCategory category; category.id = newItem->data( 0, Qt::UserRole ).toInt(); category.name = newItem->text( 0 ); emit chatCategorySelected( category ); } void YahooChatSelectorDialog::slotChatRoomDoubleClicked( QTreeWidgetItem * item, int column ) { Q_UNUSED( column ); Q_UNUSED( item ); QDialog::accept(); } void YahooChatSelectorDialog::slotSetChatCategories( const QDomDocument &doc ) { kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << doc.toString() << endl; mUi->treeCategories->takeTopLevelItem(0); QTreeWidgetItem *root = new QTreeWidgetItem( mUi->treeCategories ); root->setText( 0, i18n("Yahoo Chat rooms") ); QDomNode child = doc.firstChild(); mUi->treeCategories->setItemExpanded( root, true ); while( !child.isNull() ) { parseChatCategory(child, root); child = child.nextSibling(); } } void YahooChatSelectorDialog::parseChatCategory( const QDomNode &node, QTreeWidgetItem *parentItem ) { QTreeWidgetItem *newParent = parentItem; if( node.nodeName().startsWith( "category" ) ) { QTreeWidgetItem *item = new QTreeWidgetItem( parentItem ); item->setText( 0, node.toElement().attribute( "name" ) ); item->setData( 0, Qt::UserRole, node.toElement().attribute( "id" ) ); parentItem->addChild( item ); newParent = item; } QDomNode child = node.firstChild(); while( !child.isNull() ) { parseChatCategory(child, newParent); child = child.nextSibling(); } } void YahooChatSelectorDialog::slotSetChatRooms( const Yahoo::ChatCategory &category, const QDomDocument &doc ) { kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << doc.toString() << endl; Q_UNUSED( category ); mUi->treeRooms->clear(); QDomNode child = doc.firstChild(); while( !child.isNull() ) { parseChatRoom( child ); child = child.nextSibling(); } } void YahooChatSelectorDialog::parseChatRoom( const QDomNode &node ) { if( node.nodeName().startsWith( "room" ) ) { QTreeWidgetItem *item = new QTreeWidgetItem( mUi->treeRooms ); QDomElement elem = node.toElement(); QString name = elem.attribute( "name" ); QString id = elem.attribute( "id" ); item->setText( 0, name ); item->setData( 0, Qt::ToolTipRole, elem.attribute( "topic" ) ); item->setData( 0, Qt::UserRole, id ); QDomNode child; for( child = node.firstChild(); !child.isNull(); child = child.nextSibling() ) { if( child.nodeName().startsWith( "lobby" ) ) { QTreeWidgetItem *lobby = new QTreeWidgetItem( item ); QDomElement e = child.toElement(); QString voices = e.attribute( "voices" ); QString users = e.attribute( "users" ); QString webcams = e.attribute( "webcams" ); QString count = e.attribute( "count" ); lobby->setText( 0, name + QString( ": %1 (u:%2, v:%3, w:%4)" ) .arg( count, users, voices, webcams ) ); lobby->setData( 0, Qt::UserRole, id ); item->addChild( lobby ); } } } else { QDomNode child = node.firstChild(); while( !child.isNull() ) { parseChatRoom( child ); child = child.nextSibling(); } } } Yahoo::ChatRoom YahooChatSelectorDialog::selectedRoom() { Yahoo::ChatRoom room; QTreeWidgetItem *item = mUi->treeRooms->selectedItems().first(); room.name = item->text( 0 ); room.topic = item->data( 0, Qt::ToolTipRole ).toString(); room.id = item->data( 0, Qt::UserRole ).toInt(); return room; } #include "yahoochatselectordialog.moc" <commit_msg>Show users, webcam and voices in tooltip.<commit_after>/* yahoochatselectordialog.h Copyright (c) 2006 by Andre Duffeck <andre@duffeck.de> Kopete (c) 2002-2006 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * 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. * * * ************************************************************************* */ #include <QDomDocument> #include <QTreeWidgetItem> #include <QHeaderView> #include "ui_yahoochatselectorwidgetbase.h" #include "yahoochatselectordialog.h" YahooChatSelectorDialog::YahooChatSelectorDialog( QWidget *parent ) : KDialog( parent ) { setCaption( i18n( "Choose a chat room..." ) ); setButtons( KDialog::Ok | KDialog::Cancel ); setDefaultButton( KDialog::Ok ); showButtonSeparator( true ); mUi = new Ui_YahooChatSelectorWidgetBase(); QBoxLayout *layout = new QVBoxLayout(this); QWidget *widget = new QWidget(this); mUi->setupUi(widget); layout->addWidget(widget); setMainWidget(widget); mUi->treeCategories->header()->hide(); mUi->treeRooms->header()->hide(); QTreeWidgetItem *loading = new QTreeWidgetItem(mUi->treeCategories); loading->setText( 0, i18n("Loading...") ); mUi->treeCategories->addTopLevelItem( loading ); connect(mUi->treeCategories, SIGNAL(currentItemChanged ( QTreeWidgetItem *, QTreeWidgetItem * )), this, SLOT(slotCategorySelectionChanged( QTreeWidgetItem *, QTreeWidgetItem * ))); connect(mUi->treeRooms, SIGNAL(itemDoubleClicked( QTreeWidgetItem *, int )), this, SLOT(slotChatRoomDoubleClicked( QTreeWidgetItem *, int )) ); } YahooChatSelectorDialog::~YahooChatSelectorDialog() { delete mUi; } void YahooChatSelectorDialog::slotCategorySelectionChanged( QTreeWidgetItem *newItem, QTreeWidgetItem *oldItem ) { Q_UNUSED( oldItem ); kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << "Selected Category: " << newItem->text( 0 ) << "(" << newItem->data( 0, Qt::UserRole ).toInt() << ")" << endl; mUi->treeRooms->clear(); QTreeWidgetItem *loading = new QTreeWidgetItem(mUi->treeRooms); loading->setText( 0, i18n("Loading...") ); mUi->treeRooms->addTopLevelItem( loading ); Yahoo::ChatCategory category; category.id = newItem->data( 0, Qt::UserRole ).toInt(); category.name = newItem->text( 0 ); emit chatCategorySelected( category ); } void YahooChatSelectorDialog::slotChatRoomDoubleClicked( QTreeWidgetItem * item, int column ) { Q_UNUSED( column ); Q_UNUSED( item ); QDialog::accept(); } void YahooChatSelectorDialog::slotSetChatCategories( const QDomDocument &doc ) { kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << doc.toString() << endl; mUi->treeCategories->takeTopLevelItem(0); QTreeWidgetItem *root = new QTreeWidgetItem( mUi->treeCategories ); root->setText( 0, i18n("Yahoo Chat rooms") ); QDomNode child = doc.firstChild(); mUi->treeCategories->setItemExpanded( root, true ); while( !child.isNull() ) { parseChatCategory(child, root); child = child.nextSibling(); } } void YahooChatSelectorDialog::parseChatCategory( const QDomNode &node, QTreeWidgetItem *parentItem ) { QTreeWidgetItem *newParent = parentItem; if( node.nodeName().startsWith( "category" ) ) { QTreeWidgetItem *item = new QTreeWidgetItem( parentItem ); item->setText( 0, node.toElement().attribute( "name" ) ); item->setData( 0, Qt::UserRole, node.toElement().attribute( "id" ) ); parentItem->addChild( item ); newParent = item; } QDomNode child = node.firstChild(); while( !child.isNull() ) { parseChatCategory(child, newParent); child = child.nextSibling(); } } void YahooChatSelectorDialog::slotSetChatRooms( const Yahoo::ChatCategory &category, const QDomDocument &doc ) { kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << doc.toString() << endl; Q_UNUSED( category ); mUi->treeRooms->clear(); QDomNode child = doc.firstChild(); while( !child.isNull() ) { parseChatRoom( child ); child = child.nextSibling(); } } void YahooChatSelectorDialog::parseChatRoom( const QDomNode &node ) { if( node.nodeName().startsWith( "room" ) ) { QTreeWidgetItem *item = new QTreeWidgetItem( mUi->treeRooms ); QDomElement elem = node.toElement(); QString name = elem.attribute( "name" ); QString id = elem.attribute( "id" ); item->setText( 0, name ); item->setData( 0, Qt::ToolTipRole, elem.attribute( "topic" ) ); item->setData( 0, Qt::UserRole, id ); QDomNode child; for( child = node.firstChild(); !child.isNull(); child = child.nextSibling() ) { if( child.nodeName().startsWith( "lobby" ) ) { QTreeWidgetItem *lobby = new QTreeWidgetItem( item ); QDomElement e = child.toElement(); QString voices = e.attribute( "voices" ); QString users = e.attribute( "users" ); QString webcams = e.attribute( "webcams" ); QString count = e.attribute( "count" ); lobby->setText( 0, name + QString( ":%1" ) .arg( count ) ); lobby->setData( 0, Qt::ToolTipRole, QString( "Users: %1 Webcams: %2 Voices: %3" ) .arg( users, webcams, voices ) ); lobby->setData( 0, Qt::UserRole, id ); item->addChild( lobby ); } } } else { QDomNode child = node.firstChild(); while( !child.isNull() ) { parseChatRoom( child ); child = child.nextSibling(); } } } Yahoo::ChatRoom YahooChatSelectorDialog::selectedRoom() { Yahoo::ChatRoom room; QTreeWidgetItem *item = mUi->treeRooms->selectedItems().first(); room.name = item->text( 0 ); room.topic = item->data( 0, Qt::ToolTipRole ).toString(); room.id = item->data( 0, Qt::UserRole ).toInt(); return room; } #include "yahoochatselectordialog.moc" <|endoftext|>
<commit_before><commit_msg>When run chrome with --no-sandbox, the renderer process calls the dtor of BrokerServicesBase. There some API calls have invalid parameters.<commit_after><|endoftext|>
<commit_before>/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "YogaLayoutableShadowNode.h" #include <algorithm> #include <limits> #include <memory> #include <react/components/view/conversions.h> #include <react/core/LayoutConstraints.h> #include <react/core/LayoutContext.h> #include <react/debug/DebugStringConvertibleItem.h> #include <react/debug/SystraceSection.h> #include <yoga/Yoga.h> namespace facebook { namespace react { YogaLayoutableShadowNode::YogaLayoutableShadowNode() : yogaNode_({}), yogaConfig_(nullptr) { initializeYogaConfig(yogaConfig_); yogaNode_.setConfig(&yogaConfig_); yogaNode_.setContext(this); } YogaLayoutableShadowNode::YogaLayoutableShadowNode( const YogaLayoutableShadowNode &layoutableShadowNode) : LayoutableShadowNode(layoutableShadowNode), yogaNode_(layoutableShadowNode.yogaNode_), yogaConfig_(nullptr) { initializeYogaConfig(yogaConfig_); yogaNode_.setConfig(&yogaConfig_); yogaNode_.setContext(this); yogaNode_.setOwner(nullptr); // Yoga node must inherit dirty flag. assert(layoutableShadowNode.yogaNode_.isDirty() == yogaNode_.isDirty()); } void YogaLayoutableShadowNode::cleanLayout() { yogaNode_.setDirty(false); } void YogaLayoutableShadowNode::dirtyLayout() { yogaNode_.setDirty(true); } bool YogaLayoutableShadowNode::getIsLayoutClean() const { return !yogaNode_.isDirty(); } bool YogaLayoutableShadowNode::getHasNewLayout() const { return yogaNode_.getHasNewLayout(); } void YogaLayoutableShadowNode::setHasNewLayout(bool hasNewLayout) { yogaNode_.setHasNewLayout(hasNewLayout); } #pragma mark - Mutating Methods void YogaLayoutableShadowNode::enableMeasurement() { ensureUnsealed(); yogaNode_.setMeasureFunc( YogaLayoutableShadowNode::yogaNodeMeasureCallbackConnector); } void YogaLayoutableShadowNode::appendChild(YogaLayoutableShadowNode *child) { ensureUnsealed(); yogaNode_.setDirty(true); auto yogaNodeRawPtr = &yogaNode_; auto childYogaNodeRawPtr = &child->yogaNode_; if (childYogaNodeRawPtr->getOwner() != nullptr) { child = static_cast<YogaLayoutableShadowNode *>( cloneAndReplaceChild(child, yogaNode_.getChildren().size())); childYogaNodeRawPtr = &child->yogaNode_; } // Inserted node must have a clear owner (must not be shared). assert(childYogaNodeRawPtr->getOwner() == nullptr); child->ensureUnsealed(); childYogaNodeRawPtr->setOwner(yogaNodeRawPtr); yogaNodeRawPtr->insertChild( childYogaNodeRawPtr, yogaNodeRawPtr->getChildren().size()); } void YogaLayoutableShadowNode::setChildren( YogaLayoutableShadowNode::UnsharedList children) { ensureUnsealed(); // Optimization: // If the new list of child nodes consists of clean nodes, and if their styles // are identical to styles of old children, we don't dirty the node. bool isClean = !yogaNode_.getDirtied() && children.size() == yogaNode_.getChildren().size(); auto oldChildren = isClean ? yogaNode_.getChildren() : YGVector{}; yogaNode_.setChildren({}); auto i = int{0}; for (auto const &child : children) { appendChild(child); isClean = isClean && !child->yogaNode_.isDirty() && child->yogaNode_.getStyle() == oldChildren[i++]->getStyle(); } yogaNode_.setDirty(!isClean); } void YogaLayoutableShadowNode::setProps(const YogaStylableProps &props) { ensureUnsealed(); // Resetting `dirty` flag only if `yogaStyle` portion of `Props` was changed. if (!yogaNode_.isDirty() && (props.yogaStyle != yogaNode_.getStyle())) { yogaNode_.setDirty(true); } yogaNode_.setStyle(props.yogaStyle); } void YogaLayoutableShadowNode::setSize(Size size) const { ensureUnsealed(); auto style = yogaNode_.getStyle(); style.dimensions()[YGDimensionWidth] = yogaStyleValueFromFloat(size.width); style.dimensions()[YGDimensionHeight] = yogaStyleValueFromFloat(size.height); yogaNode_.setStyle(style); yogaNode_.setDirty(true); } void YogaLayoutableShadowNode::setPositionType( YGPositionType positionType) const { ensureUnsealed(); auto style = yogaNode_.getStyle(); style.positionType() = positionType; yogaNode_.setStyle(style); yogaNode_.setDirty(true); } void YogaLayoutableShadowNode::layout(LayoutContext layoutContext) { if (!getIsLayoutClean()) { ensureUnsealed(); /* * In Yoga, every single Yoga Node has to have a (non-null) pointer to * Yoga Config (this config can be shared between many nodes), * so every node can be individually configured. This does *not* mean * however that Yoga consults with every single Yoga Node Config for every * config parameter. Especially in case of `pointScaleFactor`, * the only value in the config of the root node is taken into account * (and this is by design). */ yogaConfig_.pointScaleFactor = layoutContext.pointScaleFactor; { SystraceSection s("YogaLayoutableShadowNode::YGNodeCalculateLayout"); YGNodeCalculateLayout( &yogaNode_, YGUndefined, YGUndefined, YGDirectionInherit); } } LayoutableShadowNode::layout(layoutContext); } void YogaLayoutableShadowNode::layoutChildren(LayoutContext layoutContext) { for (const auto &childYogaNode : yogaNode_.getChildren()) { if (!childYogaNode->getHasNewLayout()) { continue; } auto childNode = static_cast<YogaLayoutableShadowNode *>(childYogaNode->getContext()); // Verifying that the Yoga node belongs to the ShadowNode. assert(&childNode->yogaNode_ == childYogaNode); LayoutMetrics childLayoutMetrics = layoutMetricsFromYogaNode(childNode->yogaNode_); childLayoutMetrics.pointScaleFactor = layoutContext.pointScaleFactor; // We must copy layout metrics from Yoga node only once (when the parent // node exclusively ownes the child node). assert(childYogaNode->getOwner() == &yogaNode_); childNode->ensureUnsealed(); auto affected = childNode->setLayoutMetrics(childLayoutMetrics); if (affected && layoutContext.affectedNodes) { layoutContext.affectedNodes->push_back(childNode); } } } LayoutableShadowNode::UnsharedList YogaLayoutableShadowNode::getLayoutableChildNodes() const { LayoutableShadowNode::UnsharedList yogaLayoutableChildNodes; yogaLayoutableChildNodes.reserve(yogaNode_.getChildren().size()); for (const auto &childYogaNode : yogaNode_.getChildren()) { auto childNode = static_cast<YogaLayoutableShadowNode *>(childYogaNode->getContext()); yogaLayoutableChildNodes.push_back(childNode); } return yogaLayoutableChildNodes; } #pragma mark - Yoga Connectors YGNode *YogaLayoutableShadowNode::yogaNodeCloneCallbackConnector( YGNode *oldYogaNode, YGNode *parentYogaNode, int childIndex) { SystraceSection s("YogaLayoutableShadowNode::yogaNodeCloneCallbackConnector"); // At this point it is garanteed that all shadow nodes associated with yoga // nodes are `YogaLayoutableShadowNode` subclasses. auto parentNode = static_cast<YogaLayoutableShadowNode *>(parentYogaNode->getContext()); auto oldNode = static_cast<YogaLayoutableShadowNode *>(oldYogaNode->getContext()); auto clonedNode = static_cast<YogaLayoutableShadowNode *>( parentNode->cloneAndReplaceChild(oldNode, childIndex)); return &clonedNode->yogaNode_; } YGSize YogaLayoutableShadowNode::yogaNodeMeasureCallbackConnector( YGNode *yogaNode, float width, YGMeasureMode widthMode, float height, YGMeasureMode heightMode) { SystraceSection s( "YogaLayoutableShadowNode::yogaNodeMeasureCallbackConnector"); auto shadowNodeRawPtr = static_cast<YogaLayoutableShadowNode *>(yogaNode->getContext()); auto minimumSize = Size{0, 0}; auto maximumSize = Size{std::numeric_limits<Float>::infinity(), std::numeric_limits<Float>::infinity()}; switch (widthMode) { case YGMeasureModeUndefined: break; case YGMeasureModeExactly: minimumSize.width = floatFromYogaFloat(width); maximumSize.width = floatFromYogaFloat(width); break; case YGMeasureModeAtMost: maximumSize.width = floatFromYogaFloat(width); break; } switch (heightMode) { case YGMeasureModeUndefined: break; case YGMeasureModeExactly: minimumSize.height = floatFromYogaFloat(height); maximumSize.height = floatFromYogaFloat(height); break; case YGMeasureModeAtMost: maximumSize.height = floatFromYogaFloat(height); break; } auto size = shadowNodeRawPtr->measure({minimumSize, maximumSize}); return YGSize{yogaFloatFromFloat(size.width), yogaFloatFromFloat(size.height)}; } void YogaLayoutableShadowNode::initializeYogaConfig(YGConfig &config) { config.setCloneNodeCallback( YogaLayoutableShadowNode::yogaNodeCloneCallbackConnector); } } // namespace react } // namespace facebook <commit_msg>Fabric: Enable `useLegacyStretchBehaviour` for Yoga in Fabric<commit_after>/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "YogaLayoutableShadowNode.h" #include <algorithm> #include <limits> #include <memory> #include <react/components/view/conversions.h> #include <react/core/LayoutConstraints.h> #include <react/core/LayoutContext.h> #include <react/debug/DebugStringConvertibleItem.h> #include <react/debug/SystraceSection.h> #include <yoga/Yoga.h> namespace facebook { namespace react { YogaLayoutableShadowNode::YogaLayoutableShadowNode() : yogaNode_({}), yogaConfig_(nullptr) { initializeYogaConfig(yogaConfig_); yogaNode_.setConfig(&yogaConfig_); yogaNode_.setContext(this); } YogaLayoutableShadowNode::YogaLayoutableShadowNode( const YogaLayoutableShadowNode &layoutableShadowNode) : LayoutableShadowNode(layoutableShadowNode), yogaNode_(layoutableShadowNode.yogaNode_), yogaConfig_(nullptr) { initializeYogaConfig(yogaConfig_); yogaNode_.setConfig(&yogaConfig_); yogaNode_.setContext(this); yogaNode_.setOwner(nullptr); // Yoga node must inherit dirty flag. assert(layoutableShadowNode.yogaNode_.isDirty() == yogaNode_.isDirty()); } void YogaLayoutableShadowNode::cleanLayout() { yogaNode_.setDirty(false); } void YogaLayoutableShadowNode::dirtyLayout() { yogaNode_.setDirty(true); } bool YogaLayoutableShadowNode::getIsLayoutClean() const { return !yogaNode_.isDirty(); } bool YogaLayoutableShadowNode::getHasNewLayout() const { return yogaNode_.getHasNewLayout(); } void YogaLayoutableShadowNode::setHasNewLayout(bool hasNewLayout) { yogaNode_.setHasNewLayout(hasNewLayout); } #pragma mark - Mutating Methods void YogaLayoutableShadowNode::enableMeasurement() { ensureUnsealed(); yogaNode_.setMeasureFunc( YogaLayoutableShadowNode::yogaNodeMeasureCallbackConnector); } void YogaLayoutableShadowNode::appendChild(YogaLayoutableShadowNode *child) { ensureUnsealed(); yogaNode_.setDirty(true); auto yogaNodeRawPtr = &yogaNode_; auto childYogaNodeRawPtr = &child->yogaNode_; if (childYogaNodeRawPtr->getOwner() != nullptr) { child = static_cast<YogaLayoutableShadowNode *>( cloneAndReplaceChild(child, yogaNode_.getChildren().size())); childYogaNodeRawPtr = &child->yogaNode_; } // Inserted node must have a clear owner (must not be shared). assert(childYogaNodeRawPtr->getOwner() == nullptr); child->ensureUnsealed(); childYogaNodeRawPtr->setOwner(yogaNodeRawPtr); yogaNodeRawPtr->insertChild( childYogaNodeRawPtr, yogaNodeRawPtr->getChildren().size()); } void YogaLayoutableShadowNode::setChildren( YogaLayoutableShadowNode::UnsharedList children) { ensureUnsealed(); // Optimization: // If the new list of child nodes consists of clean nodes, and if their styles // are identical to styles of old children, we don't dirty the node. bool isClean = !yogaNode_.getDirtied() && children.size() == yogaNode_.getChildren().size(); auto oldChildren = isClean ? yogaNode_.getChildren() : YGVector{}; yogaNode_.setChildren({}); auto i = int{0}; for (auto const &child : children) { appendChild(child); isClean = isClean && !child->yogaNode_.isDirty() && child->yogaNode_.getStyle() == oldChildren[i++]->getStyle(); } yogaNode_.setDirty(!isClean); } void YogaLayoutableShadowNode::setProps(const YogaStylableProps &props) { ensureUnsealed(); // Resetting `dirty` flag only if `yogaStyle` portion of `Props` was changed. if (!yogaNode_.isDirty() && (props.yogaStyle != yogaNode_.getStyle())) { yogaNode_.setDirty(true); } yogaNode_.setStyle(props.yogaStyle); } void YogaLayoutableShadowNode::setSize(Size size) const { ensureUnsealed(); auto style = yogaNode_.getStyle(); style.dimensions()[YGDimensionWidth] = yogaStyleValueFromFloat(size.width); style.dimensions()[YGDimensionHeight] = yogaStyleValueFromFloat(size.height); yogaNode_.setStyle(style); yogaNode_.setDirty(true); } void YogaLayoutableShadowNode::setPositionType( YGPositionType positionType) const { ensureUnsealed(); auto style = yogaNode_.getStyle(); style.positionType() = positionType; yogaNode_.setStyle(style); yogaNode_.setDirty(true); } void YogaLayoutableShadowNode::layout(LayoutContext layoutContext) { if (!getIsLayoutClean()) { ensureUnsealed(); /* * In Yoga, every single Yoga Node has to have a (non-null) pointer to * Yoga Config (this config can be shared between many nodes), * so every node can be individually configured. This does *not* mean * however that Yoga consults with every single Yoga Node Config for every * config parameter. Especially in case of `pointScaleFactor`, * the only value in the config of the root node is taken into account * (and this is by design). */ yogaConfig_.pointScaleFactor = layoutContext.pointScaleFactor; { SystraceSection s("YogaLayoutableShadowNode::YGNodeCalculateLayout"); YGNodeCalculateLayout( &yogaNode_, YGUndefined, YGUndefined, YGDirectionInherit); } } LayoutableShadowNode::layout(layoutContext); } void YogaLayoutableShadowNode::layoutChildren(LayoutContext layoutContext) { for (const auto &childYogaNode : yogaNode_.getChildren()) { if (!childYogaNode->getHasNewLayout()) { continue; } auto childNode = static_cast<YogaLayoutableShadowNode *>(childYogaNode->getContext()); // Verifying that the Yoga node belongs to the ShadowNode. assert(&childNode->yogaNode_ == childYogaNode); LayoutMetrics childLayoutMetrics = layoutMetricsFromYogaNode(childNode->yogaNode_); childLayoutMetrics.pointScaleFactor = layoutContext.pointScaleFactor; // We must copy layout metrics from Yoga node only once (when the parent // node exclusively ownes the child node). assert(childYogaNode->getOwner() == &yogaNode_); childNode->ensureUnsealed(); auto affected = childNode->setLayoutMetrics(childLayoutMetrics); if (affected && layoutContext.affectedNodes) { layoutContext.affectedNodes->push_back(childNode); } } } LayoutableShadowNode::UnsharedList YogaLayoutableShadowNode::getLayoutableChildNodes() const { LayoutableShadowNode::UnsharedList yogaLayoutableChildNodes; yogaLayoutableChildNodes.reserve(yogaNode_.getChildren().size()); for (const auto &childYogaNode : yogaNode_.getChildren()) { auto childNode = static_cast<YogaLayoutableShadowNode *>(childYogaNode->getContext()); yogaLayoutableChildNodes.push_back(childNode); } return yogaLayoutableChildNodes; } #pragma mark - Yoga Connectors YGNode *YogaLayoutableShadowNode::yogaNodeCloneCallbackConnector( YGNode *oldYogaNode, YGNode *parentYogaNode, int childIndex) { SystraceSection s("YogaLayoutableShadowNode::yogaNodeCloneCallbackConnector"); // At this point it is garanteed that all shadow nodes associated with yoga // nodes are `YogaLayoutableShadowNode` subclasses. auto parentNode = static_cast<YogaLayoutableShadowNode *>(parentYogaNode->getContext()); auto oldNode = static_cast<YogaLayoutableShadowNode *>(oldYogaNode->getContext()); auto clonedNode = static_cast<YogaLayoutableShadowNode *>( parentNode->cloneAndReplaceChild(oldNode, childIndex)); return &clonedNode->yogaNode_; } YGSize YogaLayoutableShadowNode::yogaNodeMeasureCallbackConnector( YGNode *yogaNode, float width, YGMeasureMode widthMode, float height, YGMeasureMode heightMode) { SystraceSection s( "YogaLayoutableShadowNode::yogaNodeMeasureCallbackConnector"); auto shadowNodeRawPtr = static_cast<YogaLayoutableShadowNode *>(yogaNode->getContext()); auto minimumSize = Size{0, 0}; auto maximumSize = Size{std::numeric_limits<Float>::infinity(), std::numeric_limits<Float>::infinity()}; switch (widthMode) { case YGMeasureModeUndefined: break; case YGMeasureModeExactly: minimumSize.width = floatFromYogaFloat(width); maximumSize.width = floatFromYogaFloat(width); break; case YGMeasureModeAtMost: maximumSize.width = floatFromYogaFloat(width); break; } switch (heightMode) { case YGMeasureModeUndefined: break; case YGMeasureModeExactly: minimumSize.height = floatFromYogaFloat(height); maximumSize.height = floatFromYogaFloat(height); break; case YGMeasureModeAtMost: maximumSize.height = floatFromYogaFloat(height); break; } auto size = shadowNodeRawPtr->measure({minimumSize, maximumSize}); return YGSize{yogaFloatFromFloat(size.width), yogaFloatFromFloat(size.height)}; } void YogaLayoutableShadowNode::initializeYogaConfig(YGConfig &config) { config.setCloneNodeCallback( YogaLayoutableShadowNode::yogaNodeCloneCallbackConnector); config.useLegacyStretchBehaviour = true; } } // namespace react } // namespace facebook <|endoftext|>
<commit_before> #include "../../Flare.h" #include "FlareSpacecraftDockingSystem.h" #include "../FlareStationDock.h" #include "../FlareSpacecraft.h" #define LOCTEXT_NAMESPACE "FlareSpacecraftDockingSystem" /*---------------------------------------------------- Constructor ----------------------------------------------------*/ UFlareSpacecraftDockingSystem::UFlareSpacecraftDockingSystem(const class FObjectInitializer& PCIP) : Super(PCIP) , Spacecraft(NULL) { } /*---------------------------------------------------- Gameplay events ----------------------------------------------------*/ void UFlareSpacecraftDockingSystem::TickSystem(float DeltaSeconds) { } void UFlareSpacecraftDockingSystem::Initialize(AFlareSpacecraft* OwnerSpacecraft, FFlareSpacecraftSave* OwnerData) { Spacecraft = OwnerSpacecraft; Components = Spacecraft->GetComponentsByClass(UFlareSpacecraftComponent::StaticClass()); Description = Spacecraft->GetDescription(); Data = OwnerData; } void UFlareSpacecraftDockingSystem::Start() { // Dock data int32 Count = 0; TArray<UActorComponent*> ActorComponents; Spacecraft->GetComponents(ActorComponents); // Fill all dock slots for (TArray<UActorComponent*>::TIterator ComponentIt(ActorComponents); ComponentIt; ++ComponentIt) { UFlareStationDock* Component = Cast<UFlareStationDock>(*ComponentIt); if (Component) { // Get data FVector DockLocation; FRotator DockRotation; Component->GetSocketWorldLocationAndRotation(FName("dock"), DockLocation, DockRotation); // Fill info FFlareDockingInfo Info; Info.LocalAxis = Spacecraft->Airframe->GetComponentToWorld().Inverse().GetRotation().RotateVector(DockRotation.RotateVector(FVector(1,0,0))); Info.LocalLocation = Spacecraft->Airframe->GetComponentToWorld().Inverse().TransformPosition(DockLocation); Info.DockId = Count; Info.DockSize = Component->DockSize; Info.Station = Spacecraft; Info.Granted = false; Info.Occupied = false; // Push this slot DockingSlots.Add(Info); Count++; } } } bool UFlareSpacecraftDockingSystem::HasCompatibleDock(IFlareSpacecraftInterface* Ship) const { for (int32 i = 0; i < DockingSlots.Num(); i++) { if (DockingSlots[i].DockSize == Ship->GetSize()) { return true; } } return false; } FFlareDockingInfo UFlareSpacecraftDockingSystem::RequestDock(IFlareSpacecraftInterface* Ship, FVector PreferredLocation) { FLOGV("UFlareSpacecraftDockingSystem::RequestDock ('%s')", *Ship->_getUObject()->GetName()); int32 BestIndex = -1; float BestDistance = 0; // Looking for nearest available slot for (int32 i = 0; i < DockingSlots.Num(); i++) { if (!DockingSlots[i].Granted && DockingSlots[i].DockSize == Ship->GetSize()) { float DockDistance = (Spacecraft->Airframe->GetComponentToWorld().TransformPosition(DockingSlots[i].LocalLocation) - PreferredLocation).Size(); if (BestIndex < 0 || DockDistance < BestDistance) { BestDistance = DockDistance; BestIndex = i; } } } if (BestIndex >=0) { FLOGV("UFlareSpacecraftDockingSystem::RequestDock : found valid dock %d", BestIndex); DockingSlots[BestIndex].Granted = true; DockingSlots[BestIndex].Ship = Ship; return DockingSlots[BestIndex]; } // Default values FFlareDockingInfo Info; Info.Granted = false; Info.Station = Spacecraft; return Info; } void UFlareSpacecraftDockingSystem::ReleaseDock(IFlareSpacecraftInterface* Ship, int32 DockId) { FLOGV("UFlareSpacecraftDockingSystem::ReleaseDock %d ('%s')", DockId, *Ship->_getUObject()->GetName()); DockingSlots[DockId].Granted = false; DockingSlots[DockId].Occupied = false; DockingSlots[DockId].Ship = NULL; } void UFlareSpacecraftDockingSystem::Dock(IFlareSpacecraftInterface* Ship, int32 DockId) { FLOGV("UFlareSpacecraftDockingSystem::Dock %d ('%s')", DockId, *Ship->_getUObject()->GetName()); DockingSlots[DockId].Granted = true; DockingSlots[DockId].Occupied = true; DockingSlots[DockId].Ship = Ship; } TArray<IFlareSpacecraftInterface*> UFlareSpacecraftDockingSystem::GetDockedShips() { TArray<IFlareSpacecraftInterface*> Result; for (int32 i = 0; i < DockingSlots.Num(); i++) { if (DockingSlots[i].Granted) { FLOGV("UFlareSpacecraftDockingSystem::GetDockedShips : found valid dock %d", i); Result.AddUnique(DockingSlots[i].Ship); } } return Result; } bool UFlareSpacecraftDockingSystem::HasAvailableDock(IFlareSpacecraftInterface* Ship) const { // Looking for slot for (int32 i = 0; i < DockingSlots.Num(); i++) { if (!DockingSlots[i].Granted) { return true; } } return false; } int UFlareSpacecraftDockingSystem::GetDockCount() const { return DockingSlots.Num(); } FFlareDockingInfo UFlareSpacecraftDockingSystem::GetDockInfo(int32 DockId) { return DockingSlots[DockId]; } bool UFlareSpacecraftDockingSystem::IsGrantedShip(IFlareSpacecraftInterface* ShipCanditate) const { for (int32 i = 0; i < DockingSlots.Num(); i++) { if (DockingSlots[i].Granted && DockingSlots[i].Ship == ShipCanditate) { return true; } } return false; } bool UFlareSpacecraftDockingSystem::IsDockedShip(IFlareSpacecraftInterface* ShipCanditate) const { for (int32 i = 0; i < DockingSlots.Num(); i++) { if (DockingSlots[i].Occupied && DockingSlots[i].Ship == ShipCanditate) { return true; } } return false; } #undef LOCTEXT_NAMESPACE <commit_msg>Don't show docking ship in docked ship list<commit_after> #include "../../Flare.h" #include "FlareSpacecraftDockingSystem.h" #include "../FlareStationDock.h" #include "../FlareSpacecraft.h" #define LOCTEXT_NAMESPACE "FlareSpacecraftDockingSystem" /*---------------------------------------------------- Constructor ----------------------------------------------------*/ UFlareSpacecraftDockingSystem::UFlareSpacecraftDockingSystem(const class FObjectInitializer& PCIP) : Super(PCIP) , Spacecraft(NULL) { } /*---------------------------------------------------- Gameplay events ----------------------------------------------------*/ void UFlareSpacecraftDockingSystem::TickSystem(float DeltaSeconds) { } void UFlareSpacecraftDockingSystem::Initialize(AFlareSpacecraft* OwnerSpacecraft, FFlareSpacecraftSave* OwnerData) { Spacecraft = OwnerSpacecraft; Components = Spacecraft->GetComponentsByClass(UFlareSpacecraftComponent::StaticClass()); Description = Spacecraft->GetDescription(); Data = OwnerData; } void UFlareSpacecraftDockingSystem::Start() { // Dock data int32 Count = 0; TArray<UActorComponent*> ActorComponents; Spacecraft->GetComponents(ActorComponents); // Fill all dock slots for (TArray<UActorComponent*>::TIterator ComponentIt(ActorComponents); ComponentIt; ++ComponentIt) { UFlareStationDock* Component = Cast<UFlareStationDock>(*ComponentIt); if (Component) { // Get data FVector DockLocation; FRotator DockRotation; Component->GetSocketWorldLocationAndRotation(FName("dock"), DockLocation, DockRotation); // Fill info FFlareDockingInfo Info; Info.LocalAxis = Spacecraft->Airframe->GetComponentToWorld().Inverse().GetRotation().RotateVector(DockRotation.RotateVector(FVector(1,0,0))); Info.LocalLocation = Spacecraft->Airframe->GetComponentToWorld().Inverse().TransformPosition(DockLocation); Info.DockId = Count; Info.DockSize = Component->DockSize; Info.Station = Spacecraft; Info.Granted = false; Info.Occupied = false; // Push this slot DockingSlots.Add(Info); Count++; } } } bool UFlareSpacecraftDockingSystem::HasCompatibleDock(IFlareSpacecraftInterface* Ship) const { for (int32 i = 0; i < DockingSlots.Num(); i++) { if (DockingSlots[i].DockSize == Ship->GetSize()) { return true; } } return false; } FFlareDockingInfo UFlareSpacecraftDockingSystem::RequestDock(IFlareSpacecraftInterface* Ship, FVector PreferredLocation) { FLOGV("UFlareSpacecraftDockingSystem::RequestDock ('%s')", *Ship->_getUObject()->GetName()); int32 BestIndex = -1; float BestDistance = 0; // Looking for nearest available slot for (int32 i = 0; i < DockingSlots.Num(); i++) { if (!DockingSlots[i].Granted && DockingSlots[i].DockSize == Ship->GetSize()) { float DockDistance = (Spacecraft->Airframe->GetComponentToWorld().TransformPosition(DockingSlots[i].LocalLocation) - PreferredLocation).Size(); if (BestIndex < 0 || DockDistance < BestDistance) { BestDistance = DockDistance; BestIndex = i; } } } if (BestIndex >=0) { FLOGV("UFlareSpacecraftDockingSystem::RequestDock : found valid dock %d", BestIndex); DockingSlots[BestIndex].Granted = true; DockingSlots[BestIndex].Ship = Ship; return DockingSlots[BestIndex]; } // Default values FFlareDockingInfo Info; Info.Granted = false; Info.Station = Spacecraft; return Info; } void UFlareSpacecraftDockingSystem::ReleaseDock(IFlareSpacecraftInterface* Ship, int32 DockId) { FLOGV("UFlareSpacecraftDockingSystem::ReleaseDock %d ('%s')", DockId, *Ship->_getUObject()->GetName()); DockingSlots[DockId].Granted = false; DockingSlots[DockId].Occupied = false; DockingSlots[DockId].Ship = NULL; } void UFlareSpacecraftDockingSystem::Dock(IFlareSpacecraftInterface* Ship, int32 DockId) { FLOGV("UFlareSpacecraftDockingSystem::Dock %d ('%s')", DockId, *Ship->_getUObject()->GetName()); DockingSlots[DockId].Granted = true; DockingSlots[DockId].Occupied = true; DockingSlots[DockId].Ship = Ship; } TArray<IFlareSpacecraftInterface*> UFlareSpacecraftDockingSystem::GetDockedShips() { TArray<IFlareSpacecraftInterface*> Result; for (int32 i = 0; i < DockingSlots.Num(); i++) { if (DockingSlots[i].Granted && DockingSlots[i].Occupied) { FLOGV("UFlareSpacecraftDockingSystem::GetDockedShips : found valid dock %d", i); Result.AddUnique(DockingSlots[i].Ship); } } return Result; } bool UFlareSpacecraftDockingSystem::HasAvailableDock(IFlareSpacecraftInterface* Ship) const { // Looking for slot for (int32 i = 0; i < DockingSlots.Num(); i++) { if (!DockingSlots[i].Granted) { return true; } } return false; } int UFlareSpacecraftDockingSystem::GetDockCount() const { return DockingSlots.Num(); } FFlareDockingInfo UFlareSpacecraftDockingSystem::GetDockInfo(int32 DockId) { return DockingSlots[DockId]; } bool UFlareSpacecraftDockingSystem::IsGrantedShip(IFlareSpacecraftInterface* ShipCanditate) const { for (int32 i = 0; i < DockingSlots.Num(); i++) { if (DockingSlots[i].Granted && DockingSlots[i].Ship == ShipCanditate) { return true; } } return false; } bool UFlareSpacecraftDockingSystem::IsDockedShip(IFlareSpacecraftInterface* ShipCanditate) const { for (int32 i = 0; i < DockingSlots.Num(); i++) { if (DockingSlots[i].Occupied && DockingSlots[i].Ship == ShipCanditate) { return true; } } return false; } #undef LOCTEXT_NAMESPACE <|endoftext|>
<commit_before>#include "Event.h" #include "FightSystem.h" #include "Components\PowerComponent.h" #include "Events\FightResolvedEvent.h" #include "..\Events\ShipDefeatedEvent.h" #include "..\Events\ShipVictoriousEvent.h" using namespace PinnedDownGameplay::Events; using namespace PinnedDownGameplay::Systems; using namespace PinnedDownNet::Components; using namespace PinnedDownNet::Events; FightSystem::FightSystem() { } void FightSystem::InitSystem(Game* game) { GameSystem::InitSystem(game); this->game->eventManager->AddListener(this, FightStartedEvent::FightStartedEventType); } void FightSystem::OnEvent(Event & newEvent) { CALL_EVENT_HANDLER(FightStartedEvent); } EVENT_HANDLER_DEFINITION(FightSystem, FightStartedEvent) { // Compute player power. auto playerPowerComponent = this->game->entityManager->GetComponent<PowerComponent>(data.playerShip, PowerComponent::PowerComponentType); auto playerPower = playerPowerComponent->power; // Compute enemy power. auto enemyPower = 0; for (auto it = data.enemyShips->begin(); it != data.enemyShips->end(); ++it) { auto enemyPowerComponent = this->game->entityManager->GetComponent<PowerComponent>(*it, PowerComponent::PowerComponentType); enemyPower += enemyPowerComponent->power; } // Compare power. if (playerPower <= enemyPower) { // Enemy victory. for (auto it = data.enemyShips->begin(); it != data.enemyShips->end(); ++it) { auto shipVictoriousEvent = std::make_shared<ShipVictoriousEvent>(*it); this->game->eventManager->QueueEvent(shipVictoriousEvent); } auto shipDefeatedEvent = std::make_shared<ShipDefeatedEvent>(data.playerShip); this->game->eventManager->QueueEvent(shipDefeatedEvent); } else { // Player victory. auto shipVictoriousEvent = std::make_shared<ShipVictoriousEvent>(data.playerShip); this->game->eventManager->QueueEvent(shipVictoriousEvent); for (auto it = data.enemyShips->begin(); it != data.enemyShips->end(); ++it) { auto shipDefeatedEvent = std::make_shared<ShipDefeatedEvent>(*it); this->game->eventManager->QueueEvent(shipDefeatedEvent); } } // Notify client. auto fightResolvedEvent = std::make_shared<FightResolvedEvent>(data.playerShip); this->game->eventManager->QueueEvent(fightResolvedEvent); } <commit_msg>CHANGED: Event - Including fight outcome in FightResolved event.<commit_after>#include "Event.h" #include "FightSystem.h" #include "Components\PowerComponent.h" #include "Data\FightOutcome.h" #include "Events\FightResolvedEvent.h" #include "..\Events\ShipDefeatedEvent.h" #include "..\Events\ShipVictoriousEvent.h" using namespace PinnedDownGameplay::Events; using namespace PinnedDownGameplay::Systems; using namespace PinnedDownNet::Components; using namespace PinnedDownNet::Data; using namespace PinnedDownNet::Events; FightSystem::FightSystem() { } void FightSystem::InitSystem(Game* game) { GameSystem::InitSystem(game); this->game->eventManager->AddListener(this, FightStartedEvent::FightStartedEventType); } void FightSystem::OnEvent(Event & newEvent) { CALL_EVENT_HANDLER(FightStartedEvent); } EVENT_HANDLER_DEFINITION(FightSystem, FightStartedEvent) { // Compute player power. auto playerPowerComponent = this->game->entityManager->GetComponent<PowerComponent>(data.playerShip, PowerComponent::PowerComponentType); auto playerPower = playerPowerComponent->power; // Compute enemy power. auto enemyPower = 0; for (auto it = data.enemyShips->begin(); it != data.enemyShips->end(); ++it) { auto enemyPowerComponent = this->game->entityManager->GetComponent<PowerComponent>(*it, PowerComponent::PowerComponentType); enemyPower += enemyPowerComponent->power; } // Compare power. if (playerPower <= enemyPower) { // Enemy victory. for (auto it = data.enemyShips->begin(); it != data.enemyShips->end(); ++it) { auto shipVictoriousEvent = std::make_shared<ShipVictoriousEvent>(*it); this->game->eventManager->QueueEvent(shipVictoriousEvent); } auto shipDefeatedEvent = std::make_shared<ShipDefeatedEvent>(data.playerShip); this->game->eventManager->QueueEvent(shipDefeatedEvent); // Notify client. auto fightResolvedEvent = std::make_shared<FightResolvedEvent>(data.playerShip, FightOutcome::EnemyVictory); this->game->eventManager->QueueEvent(fightResolvedEvent); } else { // Player victory. auto shipVictoriousEvent = std::make_shared<ShipVictoriousEvent>(data.playerShip); this->game->eventManager->QueueEvent(shipVictoriousEvent); for (auto it = data.enemyShips->begin(); it != data.enemyShips->end(); ++it) { auto shipDefeatedEvent = std::make_shared<ShipDefeatedEvent>(*it); this->game->eventManager->QueueEvent(shipDefeatedEvent); } // Notify client. auto fightResolvedEvent = std::make_shared<FightResolvedEvent>(data.playerShip, FightOutcome::PlayerVictory); this->game->eventManager->QueueEvent(fightResolvedEvent); } } <|endoftext|>
<commit_before>//----------------------------------- // Copyright Pierric Gimmig 2013-2017 //----------------------------------- #include "Track.h" #include "Capture.h" #include "GlCanvas.h" #include "TimeGraphLayout.h" #include "absl/strings/str_format.h" float TEXT_Z = -0.004f; float TRACK_Z = -0.005f; //----------------------------------------------------------------------------- Track::Track() { m_ID = 0; m_MousePos[0] = m_MousePos[1] = Vec2(0, 0); m_Pos = Vec2(0, 0); m_Size = Vec2(0, 0); m_PickingOffset = Vec2(0, 0); m_Picked = false; m_Moving = false; m_Canvas = nullptr; label_display_mode_ = NAME_AND_TID; unsigned char alpha = 255; unsigned char grey = 60; m_Color = Color(grey, grey, grey, alpha); } //----------------------------------------------------------------------------- void Track::Draw(GlCanvas* a_Canvas, bool a_Picking) { static volatile unsigned char alpha = 255; static volatile unsigned char grey = 60; auto col = Color(grey, grey, grey, alpha); a_Picking ? PickingManager::SetPickingColor( a_Canvas->GetPickingManager().CreatePickableId(this)) : glColor4ubv(&m_Color[0]); float x0 = m_Pos[0]; float x1 = x0 + m_Size[0]; float y0 = m_Pos[1]; float y1 = y0 - m_Size[1]; if (m_Picked) { glColor4ub(0, 128, 255, 128); } glBegin(GL_QUADS); glVertex3f(x0, y0, TRACK_Z); glVertex3f(x1, y0, TRACK_Z); glVertex3f(x1, y1, TRACK_Z); glVertex3f(x0, y1, TRACK_Z); glEnd(); if (a_Canvas->GetPickingManager().GetPicked() == this) glColor4ub(255, 255, 255, 255); else glColor4ubv(&m_Color[0]); glBegin(GL_LINES); glVertex3f(x0, y0, TRACK_Z); glVertex3f(x1, y0, TRACK_Z); glVertex3f(x1, y1, TRACK_Z); glVertex3f(x0, y1, TRACK_Z); glEnd(); std::string track_label; switch(label_display_mode_) { case NAME_AND_TID: track_label = absl::StrFormat("%s [%u]", m_Name, m_ID); break; case TID_ONLY: track_label = absl::StrFormat("[%u]", m_ID); break; case NAME_ONLY: track_label = absl::StrFormat("%s", m_Name, m_ID); break; case EMPTY: track_label = ""; } a_Canvas->AddText(track_label.c_str(), x0, y1, TEXT_Z, Color(255, 255, 255, 255)); m_Canvas = a_Canvas; } //----------------------------------------------------------------------------- void Track::SetPos(float a_X, float a_Y) { if (!m_Moving) { m_Pos = Vec2(a_X, a_Y); } } //----------------------------------------------------------------------------- void Track::SetSize(float a_SizeX, float a_SizeY) { m_Size = Vec2(a_SizeX, a_SizeY); } //----------------------------------------------------------------------------- void Track::OnPick(int a_X, int a_Y) { Vec2& mousePos = m_MousePos[0]; m_Canvas->ScreenToWorld(a_X, a_Y, mousePos[0], mousePos[1]); m_PickingOffset = mousePos - m_Pos; m_MousePos[1] = m_MousePos[0]; m_Picked = true; } //----------------------------------------------------------------------------- void Track::OnRelease() { m_Picked = false; m_Moving = false; m_TimeGraph->NeedsUpdate(); } //----------------------------------------------------------------------------- void Track::OnDrag(int a_X, int a_Y) { m_Moving = true; float x = 0.f; m_Canvas->ScreenToWorld(a_X, a_Y, x, m_Pos[1]); m_MousePos[1] = m_Pos; m_Pos[1] -= m_PickingOffset[1]; m_TimeGraph->NeedsUpdate(); } <commit_msg>Fix build of OrbitGl/Track.cpp<commit_after>//----------------------------------- // Copyright Pierric Gimmig 2013-2017 //----------------------------------- #include "Track.h" #include "Capture.h" #include "GlCanvas.h" #include "TimeGraphLayout.h" #include "absl/strings/str_format.h" float TEXT_Z = -0.004f; float TRACK_Z = -0.005f; //----------------------------------------------------------------------------- Track::Track() { m_ID = 0; m_MousePos[0] = m_MousePos[1] = Vec2(0, 0); m_Pos = Vec2(0, 0); m_Size = Vec2(0, 0); m_PickingOffset = Vec2(0, 0); m_Picked = false; m_Moving = false; m_Canvas = nullptr; label_display_mode_ = NAME_AND_TID; unsigned char alpha = 255; unsigned char grey = 60; m_Color = Color(grey, grey, grey, alpha); } //----------------------------------------------------------------------------- void Track::Draw(GlCanvas* a_Canvas, bool a_Picking) { static volatile unsigned char alpha = 255; static volatile unsigned char grey = 60; auto col = Color(grey, grey, grey, alpha); a_Picking ? PickingManager::SetPickingColor( a_Canvas->GetPickingManager().CreatePickableId(this)) : glColor4ubv(&m_Color[0]); float x0 = m_Pos[0]; float x1 = x0 + m_Size[0]; float y0 = m_Pos[1]; float y1 = y0 - m_Size[1]; if (m_Picked) { glColor4ub(0, 128, 255, 128); } glBegin(GL_QUADS); glVertex3f(x0, y0, TRACK_Z); glVertex3f(x1, y0, TRACK_Z); glVertex3f(x1, y1, TRACK_Z); glVertex3f(x0, y1, TRACK_Z); glEnd(); if (a_Canvas->GetPickingManager().GetPicked() == this) glColor4ub(255, 255, 255, 255); else glColor4ubv(&m_Color[0]); glBegin(GL_LINES); glVertex3f(x0, y0, TRACK_Z); glVertex3f(x1, y0, TRACK_Z); glVertex3f(x1, y1, TRACK_Z); glVertex3f(x0, y1, TRACK_Z); glEnd(); std::string track_label; switch(label_display_mode_) { case NAME_AND_TID: track_label = absl::StrFormat("%s [%u]", m_Name, m_ID); break; case TID_ONLY: track_label = absl::StrFormat("[%u]", m_ID); break; case NAME_ONLY: track_label = absl::StrFormat("%s", m_Name); break; case EMPTY: track_label = ""; } a_Canvas->AddText(track_label.c_str(), x0, y1, TEXT_Z, Color(255, 255, 255, 255)); m_Canvas = a_Canvas; } //----------------------------------------------------------------------------- void Track::SetPos(float a_X, float a_Y) { if (!m_Moving) { m_Pos = Vec2(a_X, a_Y); } } //----------------------------------------------------------------------------- void Track::SetSize(float a_SizeX, float a_SizeY) { m_Size = Vec2(a_SizeX, a_SizeY); } //----------------------------------------------------------------------------- void Track::OnPick(int a_X, int a_Y) { Vec2& mousePos = m_MousePos[0]; m_Canvas->ScreenToWorld(a_X, a_Y, mousePos[0], mousePos[1]); m_PickingOffset = mousePos - m_Pos; m_MousePos[1] = m_MousePos[0]; m_Picked = true; } //----------------------------------------------------------------------------- void Track::OnRelease() { m_Picked = false; m_Moving = false; m_TimeGraph->NeedsUpdate(); } //----------------------------------------------------------------------------- void Track::OnDrag(int a_X, int a_Y) { m_Moving = true; float x = 0.f; m_Canvas->ScreenToWorld(a_X, a_Y, x, m_Pos[1]); m_MousePos[1] = m_Pos; m_Pos[1] -= m_PickingOffset[1]; m_TimeGraph->NeedsUpdate(); } <|endoftext|>
<commit_before>/* * SessionProjects.hpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef SESSION_PROJECTS_HPP #define SESSION_PROJECTS_HPP #include <string> namespace core { class Error; class FilePath; } namespace session { namespace projects { core::Error startup(); core::Error initialize(); } // namespace projects } // namesapce session #endif // SESSION_PROJECTS_HPP <commit_msg>ammend last commit w/ extra hpp file<commit_after>/* * SessionProjects.hpp * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef SESSION_PROJECTS_PROJECTS_HPP #define SESSION_PROJECTS_PROJECTS_HPP namespace core { class FilePath; } namespace session { namespace projects { bool projectIsActive(); core::FilePath projectFilePath(); core::FilePath projectDirectory(); core::FilePath projectScratchPath(); } // namespace projects } // namesapce session #endif // SESSION_PROJECTS_PROJECTS_HPP <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ScriptingContext.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: dfoster $ $Date: 2003-11-04 17:45:28 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <com/sun/star/beans/PropertyAttribute.hpp> #include <com/sun/star/frame/XModel.hpp> #include <cppuhelper/implementationentry.hxx> #include <cppuhelper/factory.hxx> #include <util/scriptingconstants.hxx> #include <util/util.hxx> #include "ScriptingContext.hxx" using namespace com::sun::star; using namespace com::sun::star::uno; #define DOC_REF_PROPID 1 #define DOC_STORAGE_ID_PROPID 2 #define DOC_URI_PROPID 3 #define RESOLVED_STORAGE_ID_PROPID 4 #define SCRIPT_INFO_PROPID 5 #define SCRIPTINGCONTEXT_DEFAULT_ATTRIBS() beans::PropertyAttribute::TRANSIENT | beans::PropertyAttribute::MAYBEVOID namespace func_provider { //************************************************************************* // XScriptingContext implementation // //************************************************************************* ScriptingContext::ScriptingContext( const Reference< XComponentContext > & xContext ) : //ScriptingContextImpl_BASE( GetMutex()), OPropertyContainer( GetBroadcastHelper() ), m_xContext( xContext ) { OSL_TRACE( "< ScriptingContext ctor called >\n" ); validateXRef( m_xContext, "ScriptingContext::ScriptingContext: No context available\n" ); Any nullAny; scripting_constants::ScriptingConstantsPool& scriptingConstantsPool = scripting_constants::ScriptingConstantsPool::instance(); registerPropertyNoMember( scriptingConstantsPool.DOC_REF, DOC_REF_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(),::getCppuType( (const Reference< css::frame::XModel >* ) NULL ), NULL ) ; registerPropertyNoMember( scriptingConstantsPool.DOC_STORAGE_ID, DOC_STORAGE_ID_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const sal_Int32* ) NULL ), NULL ) ; registerPropertyNoMember( scriptingConstantsPool.DOC_URI, DOC_URI_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const ::rtl::OUString* ) NULL ), NULL ) ; registerPropertyNoMember( scriptingConstantsPool.RESOLVED_STORAGE_ID, RESOLVED_STORAGE_ID_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const sal_Int32* ) NULL ), NULL ); registerPropertyNoMember( scriptingConstantsPool.SCRIPT_INFO, SCRIPT_INFO_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const sal_Int32* ) NULL ), NULL ); } ScriptingContext::~ScriptingContext() { OSL_TRACE( "< ScriptingContext dtor called >\n" ); } // ----------------------------------------------------------------------------- // OPropertySetHelper // ----------------------------------------------------------------------------- ::cppu::IPropertyArrayHelper& ScriptingContext::getInfoHelper( ) { return *getArrayHelper(); } // ----------------------------------------------------------------------------- // OPropertyArrayUsageHelper // ----------------------------------------------------------------------------- ::cppu::IPropertyArrayHelper* ScriptingContext::createArrayHelper( ) const { Sequence< beans::Property > aProps; describeProperties( aProps ); return new ::cppu::OPropertyArrayHelper( aProps ); } // ----------------------------------------------------------------------------- // XPropertySet // ----------------------------------------------------------------------------- Reference< beans::XPropertySetInfo > ScriptingContext::getPropertySetInfo( ) throw (RuntimeException) { Reference< beans::XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } // -----------------------------------------------------------------------------// XTypeProvider // ----------------------------------------------------------------------------- IMPLEMENT_GET_IMPLEMENTATION_ID( ScriptingContext ) css::uno::Sequence< css::uno::Type > SAL_CALL ScriptingContext::getTypes( ) throw (css::uno::RuntimeException) { return OPropertyContainer::getTypes(); } } // namespace func_provider <commit_msg>INTEGRATION: CWS ooo19126 (1.6.90); FILE MERGED 2005/09/05 12:05:20 rt 1.6.90.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ScriptingContext.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-09 02:31:14 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <com/sun/star/beans/PropertyAttribute.hpp> #include <com/sun/star/frame/XModel.hpp> #include <cppuhelper/implementationentry.hxx> #include <cppuhelper/factory.hxx> #include <util/scriptingconstants.hxx> #include <util/util.hxx> #include "ScriptingContext.hxx" using namespace com::sun::star; using namespace com::sun::star::uno; #define DOC_REF_PROPID 1 #define DOC_STORAGE_ID_PROPID 2 #define DOC_URI_PROPID 3 #define RESOLVED_STORAGE_ID_PROPID 4 #define SCRIPT_INFO_PROPID 5 #define SCRIPTINGCONTEXT_DEFAULT_ATTRIBS() beans::PropertyAttribute::TRANSIENT | beans::PropertyAttribute::MAYBEVOID namespace func_provider { //************************************************************************* // XScriptingContext implementation // //************************************************************************* ScriptingContext::ScriptingContext( const Reference< XComponentContext > & xContext ) : //ScriptingContextImpl_BASE( GetMutex()), OPropertyContainer( GetBroadcastHelper() ), m_xContext( xContext ) { OSL_TRACE( "< ScriptingContext ctor called >\n" ); validateXRef( m_xContext, "ScriptingContext::ScriptingContext: No context available\n" ); Any nullAny; scripting_constants::ScriptingConstantsPool& scriptingConstantsPool = scripting_constants::ScriptingConstantsPool::instance(); registerPropertyNoMember( scriptingConstantsPool.DOC_REF, DOC_REF_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(),::getCppuType( (const Reference< css::frame::XModel >* ) NULL ), NULL ) ; registerPropertyNoMember( scriptingConstantsPool.DOC_STORAGE_ID, DOC_STORAGE_ID_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const sal_Int32* ) NULL ), NULL ) ; registerPropertyNoMember( scriptingConstantsPool.DOC_URI, DOC_URI_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const ::rtl::OUString* ) NULL ), NULL ) ; registerPropertyNoMember( scriptingConstantsPool.RESOLVED_STORAGE_ID, RESOLVED_STORAGE_ID_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const sal_Int32* ) NULL ), NULL ); registerPropertyNoMember( scriptingConstantsPool.SCRIPT_INFO, SCRIPT_INFO_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const sal_Int32* ) NULL ), NULL ); } ScriptingContext::~ScriptingContext() { OSL_TRACE( "< ScriptingContext dtor called >\n" ); } // ----------------------------------------------------------------------------- // OPropertySetHelper // ----------------------------------------------------------------------------- ::cppu::IPropertyArrayHelper& ScriptingContext::getInfoHelper( ) { return *getArrayHelper(); } // ----------------------------------------------------------------------------- // OPropertyArrayUsageHelper // ----------------------------------------------------------------------------- ::cppu::IPropertyArrayHelper* ScriptingContext::createArrayHelper( ) const { Sequence< beans::Property > aProps; describeProperties( aProps ); return new ::cppu::OPropertyArrayHelper( aProps ); } // ----------------------------------------------------------------------------- // XPropertySet // ----------------------------------------------------------------------------- Reference< beans::XPropertySetInfo > ScriptingContext::getPropertySetInfo( ) throw (RuntimeException) { Reference< beans::XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } // -----------------------------------------------------------------------------// XTypeProvider // ----------------------------------------------------------------------------- IMPLEMENT_GET_IMPLEMENTATION_ID( ScriptingContext ) css::uno::Sequence< css::uno::Type > SAL_CALL ScriptingContext::getTypes( ) throw (css::uno::RuntimeException) { return OPropertyContainer::getTypes(); } } // namespace func_provider <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: TaskPaneTreeNode.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 06:02:41 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_TASKPANE_TREE_NODE_HXX #define SD_TASKPANE_TREE_NODE_HXX #include "ILayoutableWindow.hxx" #include <memory> #include <vector> #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_ #include <com/sun/star/accessibility/XAccessible.hpp> #endif #include <tools/link.hxx> namespace sd { class ObjectBarManager; }; namespace sd { namespace toolpanel { class ControlContainer; class TaskPaneShellManager; enum TreeNodeStateChangeEventId { EID_CHILD_ADDED, EID_ALL_CHILDREN_REMOVED, EID_EXPANSION_STATE_CHANGED, EID_FOCUSED_STATE_CHANGED, EID_SHOWING_STATE_CHANGED }; /** Base class for all members of the object hierarchy that makes up the tool panel. There are usually at least three levels. At the top level is the ToolPanel with one instance: the root of the tree. At the middle level there are SubToolPanels and Window/Control objects. At the lowest level there are only Window or Control objects. This class provides the means of communication between objects on different levels. */ class TreeNode : public ILayoutableWindow, public ILayouter { public: TreeNode (TreeNode* pParent); virtual ~TreeNode (void); /** Returns <TRUE/> if the node has no children, i.e. is a leaf of a tree. In this case mpControlContainer is NULL. */ bool IsLeaf (void); /** Returns true if the node has no parent, i.e. is the root of a tree. */ bool IsRoot (void); void SetParentNode (TreeNode* pNewParent); TreeNode* GetParentNode (void); /** Return the Window pointer of a tree node. */ virtual ::Window* GetWindow (void); /** Return a const pointer to the window of a tree node. */ virtual const ::Window* GetConstWindow (void) const; /** Return the joined minimum width of all children, i.e. the largest of the minimum widths. */ virtual sal_Int32 GetMinimumWidth (void); /** Give each node access to the object bar manager of the tool panel. At least the root node has to overwrite this method since the default implementation simply returns the object bar manager of the parent. */ virtual ObjectBarManager* GetObjectBarManager (void); /** The default implementaion always returns <FALSE/> */ virtual bool IsResizable (void); /** Call this method whenever the size of one of the children of the called node has to be changed, e.g. when the layout menu shows more or less items than before. As a typical result the node will layout and resize its children according to their size requirements. Please remember that the size of the children can be changed in the first place because scroll bars can give a node the space it needs. The default implementation passes this call to its parent. */ virtual void RequestResize (void); /** The default implementation shows the window (when it exists) when bExpansionState is <TRUE/>. It hides the window otherwise. @return Returns <TRUE/> when the expansion state changes. When an expansion state is requested that is already in place then <FALSE/> is returned. */ virtual bool Expand (bool bExpansionState); /** The default implementation returns whether the window is showing. When there is no window then it returns <FALSE/>. */ virtual bool IsExpanded (void) const; /** Return whether the node can be expanded or collapsed. The default implementation always returns <TRUE/> when there is window and <FALSE/> otherwise. If <FALSE/> is returned then Expand() may be called but it will not change the expansion state. */ virtual bool IsExpandable (void) const; /** The default implementation calls GetWindow()->Show(). */ virtual void Show (bool bVisibilityState); /** The default implementation returns GetWindow()->IsVisible(). */ virtual bool IsShowing (void) const; ControlContainer& GetControlContainer (void); /** Give each node access to a shell manage. This usually is the shell manager of the TaskPaneViewShell. At least the root node has to overwrite this method since the default implementation simply returns the shell manager of its parent. */ virtual TaskPaneShellManager* GetShellManager (void); /** You will rarely need to overload this method. To supply your own accessible object you should overload CreateAccessible() instead. */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> GetAccessibleObject (void); /** Overload this method in order to supply a class specific accessible object. The default implementation will return a new instance of AccessibleTreeNode. @param rxParent The accessible parent of the accessible object to create. It is not necessaryly the accessible object of the parent window of GetWindow(). */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> CreateAccessibleObject ( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible>&rxParent); /** Add a listener that will be informated in the future about state changes of the tree node. This includes adding and removing children as well as focus, visibility, and expansion state. Multiple calls are ignored. Each listener is added only once. */ void AddStateChangeListener (const Link& rListener); /** Remove the listener form the list of state change listeners. @param rListener It is OK to specify a listener that is not currently registered. Only when the listener is registered it is removed. Otherwise the call is ignored. */ void RemoveStateChangeListener (const Link& rListener); /** Call the state change listeners and pass a state change event with the specified event id. The source field is set to this. @param pChild This optional parameter makes sense only with the EID_CHILD_ADDED event. */ void FireStateChangeEvent ( TreeNodeStateChangeEventId eEventId, TreeNode* pChild = NULL) const; protected: ::std::auto_ptr<ControlContainer> mpControlContainer; private: TreeNode* mpParent; typedef ::std::vector<Link> StateChangeListenerContainer; StateChangeListenerContainer maStateChangeListeners; }; /** Objects of this class are sent to listeners to notify them about state changes of a tree node. */ class TreeNodeStateChangeEvent { public: TreeNodeStateChangeEvent ( const TreeNode& rNode, TreeNodeStateChangeEventId eEventId, TreeNode* pChild = NULL); const TreeNode& mrSource; TreeNodeStateChangeEventId meEventId; TreeNode* mpChild; }; } } // end of namespace ::sd::toolpanel #endif <commit_msg>INTEGRATION: CWS sdwarningsbegone (1.5.316); FILE MERGED 2006/11/22 12:42:08 cl 1.5.316.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: TaskPaneTreeNode.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2006-12-12 17:55:25 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_TASKPANE_TREE_NODE_HXX #define SD_TASKPANE_TREE_NODE_HXX #include "ILayoutableWindow.hxx" #include <memory> #include <vector> #ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_ #include <com/sun/star/accessibility/XAccessible.hpp> #endif #include <tools/link.hxx> namespace sd { class ObjectBarManager; } namespace sd { namespace toolpanel { class ControlContainer; class TaskPaneShellManager; enum TreeNodeStateChangeEventId { EID_CHILD_ADDED, EID_ALL_CHILDREN_REMOVED, EID_EXPANSION_STATE_CHANGED, EID_FOCUSED_STATE_CHANGED, EID_SHOWING_STATE_CHANGED }; /** Base class for all members of the object hierarchy that makes up the tool panel. There are usually at least three levels. At the top level is the ToolPanel with one instance: the root of the tree. At the middle level there are SubToolPanels and Window/Control objects. At the lowest level there are only Window or Control objects. This class provides the means of communication between objects on different levels. */ class TreeNode : public ILayoutableWindow, public ILayouter { public: TreeNode (TreeNode* pParent); virtual ~TreeNode (void); /** Returns <TRUE/> if the node has no children, i.e. is a leaf of a tree. In this case mpControlContainer is NULL. */ bool IsLeaf (void); /** Returns true if the node has no parent, i.e. is the root of a tree. */ bool IsRoot (void); void SetParentNode (TreeNode* pNewParent); TreeNode* GetParentNode (void); /** Return the Window pointer of a tree node. */ virtual ::Window* GetWindow (void); /** Return a const pointer to the window of a tree node. */ virtual const ::Window* GetConstWindow (void) const; /** Return the joined minimum width of all children, i.e. the largest of the minimum widths. */ virtual sal_Int32 GetMinimumWidth (void); /** Give each node access to the object bar manager of the tool panel. At least the root node has to overwrite this method since the default implementation simply returns the object bar manager of the parent. */ virtual ObjectBarManager* GetObjectBarManager (void); /** The default implementaion always returns <FALSE/> */ virtual bool IsResizable (void); /** Call this method whenever the size of one of the children of the called node has to be changed, e.g. when the layout menu shows more or less items than before. As a typical result the node will layout and resize its children according to their size requirements. Please remember that the size of the children can be changed in the first place because scroll bars can give a node the space it needs. The default implementation passes this call to its parent. */ virtual void RequestResize (void); /** The default implementation shows the window (when it exists) when bExpansionState is <TRUE/>. It hides the window otherwise. @return Returns <TRUE/> when the expansion state changes. When an expansion state is requested that is already in place then <FALSE/> is returned. */ virtual bool Expand (bool bExpansionState); /** The default implementation returns whether the window is showing. When there is no window then it returns <FALSE/>. */ virtual bool IsExpanded (void) const; /** Return whether the node can be expanded or collapsed. The default implementation always returns <TRUE/> when there is window and <FALSE/> otherwise. If <FALSE/> is returned then Expand() may be called but it will not change the expansion state. */ virtual bool IsExpandable (void) const; /** The default implementation calls GetWindow()->Show(). */ virtual void Show (bool bVisibilityState); /** The default implementation returns GetWindow()->IsVisible(). */ virtual bool IsShowing (void) const; ControlContainer& GetControlContainer (void); /** Give each node access to a shell manage. This usually is the shell manager of the TaskPaneViewShell. At least the root node has to overwrite this method since the default implementation simply returns the shell manager of its parent. */ virtual TaskPaneShellManager* GetShellManager (void); /** You will rarely need to overload this method. To supply your own accessible object you should overload CreateAccessible() instead. */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> GetAccessibleObject (void); /** Overload this method in order to supply a class specific accessible object. The default implementation will return a new instance of AccessibleTreeNode. @param rxParent The accessible parent of the accessible object to create. It is not necessaryly the accessible object of the parent window of GetWindow(). */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> CreateAccessibleObject ( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible>&rxParent); /** Add a listener that will be informated in the future about state changes of the tree node. This includes adding and removing children as well as focus, visibility, and expansion state. Multiple calls are ignored. Each listener is added only once. */ void AddStateChangeListener (const Link& rListener); /** Remove the listener form the list of state change listeners. @param rListener It is OK to specify a listener that is not currently registered. Only when the listener is registered it is removed. Otherwise the call is ignored. */ void RemoveStateChangeListener (const Link& rListener); /** Call the state change listeners and pass a state change event with the specified event id. The source field is set to this. @param pChild This optional parameter makes sense only with the EID_CHILD_ADDED event. */ void FireStateChangeEvent ( TreeNodeStateChangeEventId eEventId, TreeNode* pChild = NULL) const; protected: ::std::auto_ptr<ControlContainer> mpControlContainer; private: TreeNode* mpParent; typedef ::std::vector<Link> StateChangeListenerContainer; StateChangeListenerContainer maStateChangeListeners; }; /** Objects of this class are sent to listeners to notify them about state changes of a tree node. */ class TreeNodeStateChangeEvent { public: TreeNodeStateChangeEvent ( const TreeNode& rNode, TreeNodeStateChangeEventId eEventId, TreeNode* pChild = NULL); const TreeNode& mrSource; TreeNodeStateChangeEventId meEventId; TreeNode* mpChild; }; } } // end of namespace ::sd::toolpanel #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: undopage.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: dl $ $Date: 2001-09-27 15:03:46 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include <svx/svxids.hrc> #ifndef _SFX_BINDINGS_HXX //autogen #include <sfx2/bindings.hxx> #endif #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #ifndef _SFXVIEWFRM_HXX #include <sfx2/viewfrm.hxx> #endif #include "sdpage.hxx" #include "drviewsh.hxx" #include "drawview.hxx" #include "undopage.hxx" #ifndef _SVDPAGV_HXX //autogen #include <svx/svdpagv.hxx> #endif TYPEINIT1(SdPageFormatUndoAction, SdUndoAction); TYPEINIT1(SdPageLRUndoAction, SdUndoAction); TYPEINIT1(SdPageULUndoAction, SdUndoAction); /************************************************************************* |* |* Destruktor |* \************************************************************************/ SdPageFormatUndoAction::~SdPageFormatUndoAction() { } /************************************************************************* |* |* Undo() |* \************************************************************************/ void SdPageFormatUndoAction::Undo() { Rectangle aOldBorderRect(nOldLeft, nOldUpper, nOldRight, nOldLower); pPage->ScaleObjects(aOldSize, aOldBorderRect, bNewScale); pPage->SetSize(aOldSize); pPage->SetLftBorder(nOldLeft); pPage->SetRgtBorder(nOldRight); pPage->SetUppBorder(nOldUpper); pPage->SetLwrBorder(nOldLower); pPage->SetOrientation(eOldOrientation); pPage->SetPaperBin( nOldPaperBin ); pPage->SetBackgroundFullSize( bOldFullSize ); if( !pPage->IsMasterPage() ) ( (SdPage*) pPage->GetMasterPage(0) )->SetBackgroundFullSize( bOldFullSize ); SfxViewShell* pViewShell = SfxViewShell::Current(); if ( pViewShell->ISA(SdDrawViewShell) ) { SdDrawViewShell* pDrViewShell = (SdDrawViewShell*) pViewShell; long nWidth = pPage->GetSize().Width(); long nHeight = pPage->GetSize().Height(); Point aPageOrg = Point(nWidth, nHeight / 2); Size aViewSize = Size(nWidth * 3, nHeight * 2); pDrViewShell->InitWindows(aPageOrg, aViewSize, Point(-1, -1), TRUE); pDrViewShell->GetView()->SetWorkArea(Rectangle(Point(0,0) - aPageOrg, aViewSize)); pDrViewShell->UpdateScrollBars(); pDrViewShell->GetView()->GetPageViewPvNum(0)->SetPageOrigin(Point(0,0)); pViewShell->GetViewFrame()->GetBindings().Invalidate(SID_RULER_NULL_OFFSET); pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_SIZE_PAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD); } } /************************************************************************* |* |* Redo() |* \************************************************************************/ void SdPageFormatUndoAction::Redo() { Rectangle aNewBorderRect(nNewLeft, nNewUpper, nNewRight, nNewLower); pPage->ScaleObjects(aNewSize, aNewBorderRect, bNewScale); pPage->SetSize(aNewSize); pPage->SetLftBorder(nNewLeft); pPage->SetRgtBorder(nNewRight); pPage->SetUppBorder(nNewUpper); pPage->SetLwrBorder(nNewLower); pPage->SetOrientation(eNewOrientation); pPage->SetPaperBin( nNewPaperBin ); pPage->SetBackgroundFullSize( bNewFullSize ); if( !pPage->IsMasterPage() ) ( (SdPage*) pPage->GetMasterPage(0) )->SetBackgroundFullSize( bNewFullSize ); SfxViewShell* pViewShell = SfxViewShell::Current(); if ( pViewShell->ISA(SdDrawViewShell) ) { SdDrawViewShell* pDrViewShell = (SdDrawViewShell*) pViewShell; long nWidth = pPage->GetSize().Width(); long nHeight = pPage->GetSize().Height(); Point aPageOrg = Point(nWidth, nHeight / 2); Size aViewSize = Size(nWidth * 3, nHeight * 2); pDrViewShell->InitWindows(aPageOrg, aViewSize, Point(-1, -1), TRUE); pDrViewShell->GetView()->SetWorkArea(Rectangle(Point(0,0) - aPageOrg, aViewSize)); pDrViewShell->UpdateScrollBars(); pDrViewShell->GetView()->GetPageViewPvNum(0)->SetPageOrigin(Point(0,0)); pViewShell->GetViewFrame()->GetBindings().Invalidate(SID_RULER_NULL_OFFSET); pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_SIZE_PAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD); } } /************************************************************************* |* |* Repeat() |* \************************************************************************/ void SdPageFormatUndoAction::Repeat() { Redo(); } /************************************************************************* |* |* LR-Destruktor |* \************************************************************************/ SdPageLRUndoAction::~SdPageLRUndoAction() { } /************************************************************************* |* |* LR-Undo() |* \************************************************************************/ void SdPageLRUndoAction::Undo() { pPage->SetLftBorder(nOldLeft); pPage->SetRgtBorder(nOldRight); } /************************************************************************* |* |* LR-Redo() |* \************************************************************************/ void SdPageLRUndoAction::Redo() { pPage->SetLftBorder(nNewLeft); pPage->SetRgtBorder(nNewRight); } /************************************************************************* |* |* LR-Repeat() |* \************************************************************************/ void SdPageLRUndoAction::Repeat() { Redo(); } /************************************************************************* |* |* UL-Destruktor |* \************************************************************************/ SdPageULUndoAction::~SdPageULUndoAction() { } /************************************************************************* |* |* UL-Undo() |* \************************************************************************/ void SdPageULUndoAction::Undo() { pPage->SetUppBorder(nOldUpper); pPage->SetLwrBorder(nOldLower); } /************************************************************************* |* |* UL-Redo() |* \************************************************************************/ void SdPageULUndoAction::Redo() { pPage->SetUppBorder(nNewUpper); pPage->SetLwrBorder(nNewLower); } /************************************************************************* |* |* UL-Repeat() |* \************************************************************************/ void SdPageULUndoAction::Repeat() { Redo(); } <commit_msg>INTEGRATION: CWS impress1 (1.3.240); FILE MERGED 2004/01/09 16:32:28 af 1.3.240.2: #111996# Renamed header files DrawView.hxx, Fader.hxx, and ShowView.hxx back to lowercase version. 2003/09/17 09:06:12 af 1.3.240.1: #111996# Transition to stacked sub-shells. Introduction of namespace sd.<commit_after>/************************************************************************* * * $RCSfile: undopage.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-01-20 11:25:06 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include "undopage.hxx" #include <svx/svxids.hrc> #ifndef _SFX_BINDINGS_HXX //autogen #include <sfx2/bindings.hxx> #endif #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #ifndef _SFXVIEWFRM_HXX #include <sfx2/viewfrm.hxx> #endif #include "sdpage.hxx" #ifndef SD_DRAW_VIEW_SHELL_HXX #include "DrawViewShell.hxx" #endif #ifndef SD_DRAW_VIEW_HXX #include "drawview.hxx" #endif #ifndef _SVDPAGV_HXX //autogen #include <svx/svdpagv.hxx> #endif TYPEINIT1(SdPageFormatUndoAction, SdUndoAction); TYPEINIT1(SdPageLRUndoAction, SdUndoAction); TYPEINIT1(SdPageULUndoAction, SdUndoAction); /************************************************************************* |* |* Destruktor |* \************************************************************************/ SdPageFormatUndoAction::~SdPageFormatUndoAction() { } /************************************************************************* |* |* Undo() |* \************************************************************************/ void SdPageFormatUndoAction::Undo() { Rectangle aOldBorderRect(nOldLeft, nOldUpper, nOldRight, nOldLower); pPage->ScaleObjects(aOldSize, aOldBorderRect, bNewScale); pPage->SetSize(aOldSize); pPage->SetLftBorder(nOldLeft); pPage->SetRgtBorder(nOldRight); pPage->SetUppBorder(nOldUpper); pPage->SetLwrBorder(nOldLower); pPage->SetOrientation(eOldOrientation); pPage->SetPaperBin( nOldPaperBin ); pPage->SetBackgroundFullSize( bOldFullSize ); if( !pPage->IsMasterPage() ) ( (SdPage*) pPage->GetMasterPage(0) )->SetBackgroundFullSize( bOldFullSize ); SfxViewShell* pViewShell = SfxViewShell::Current(); /* if ( pViewShell->ISA(::sd::DrawViewShell)) { ::sd::DrawViewShell* pDrViewShell = static_cast< ::sd::DrawViewShell*>(pViewShell); long nWidth = pPage->GetSize().Width(); long nHeight = pPage->GetSize().Height(); Point aPageOrg = Point(nWidth, nHeight / 2); Size aViewSize = Size(nWidth * 3, nHeight * 2); pDrViewShell->InitWindows(aPageOrg, aViewSize, Point(-1, -1), TRUE); pDrViewShell->GetView()->SetWorkArea(Rectangle(Point(0,0) - aPageOrg, aViewSize)); pDrViewShell->UpdateScrollBars(); pDrViewShell->GetView()->GetPageViewPvNum(0)->SetPageOrigin(Point(0,0)); pViewShell->GetViewFrame()->GetBindings().Invalidate(SID_RULER_NULL_OFFSET); pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_SIZE_PAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD); } */ } /************************************************************************* |* |* Redo() |* \************************************************************************/ void SdPageFormatUndoAction::Redo() { Rectangle aNewBorderRect(nNewLeft, nNewUpper, nNewRight, nNewLower); pPage->ScaleObjects(aNewSize, aNewBorderRect, bNewScale); pPage->SetSize(aNewSize); pPage->SetLftBorder(nNewLeft); pPage->SetRgtBorder(nNewRight); pPage->SetUppBorder(nNewUpper); pPage->SetLwrBorder(nNewLower); pPage->SetOrientation(eNewOrientation); pPage->SetPaperBin( nNewPaperBin ); pPage->SetBackgroundFullSize( bNewFullSize ); if( !pPage->IsMasterPage() ) ( (SdPage*) pPage->GetMasterPage(0) )->SetBackgroundFullSize( bNewFullSize ); SfxViewShell* pViewShell = SfxViewShell::Current(); /* if ( pViewShell->ISA(::sd::DrawViewShell)) { ::sd::DrawViewShell* pDrViewShell = static_cast< ::sd::DrawViewShell*>(pViewShell); long nWidth = pPage->GetSize().Width(); long nHeight = pPage->GetSize().Height(); Point aPageOrg = Point(nWidth, nHeight / 2); Size aViewSize = Size(nWidth * 3, nHeight * 2); pDrViewShell->InitWindows(aPageOrg, aViewSize, Point(-1, -1), TRUE); pDrViewShell->GetView()->SetWorkArea(Rectangle(Point(0,0) - aPageOrg, aViewSize)); pDrViewShell->UpdateScrollBars(); pDrViewShell->GetView()->GetPageViewPvNum(0)->SetPageOrigin(Point(0,0)); pViewShell->GetViewFrame()->GetBindings().Invalidate(SID_RULER_NULL_OFFSET); pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_SIZE_PAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD); } */ } /************************************************************************* |* |* Repeat() |* \************************************************************************/ void SdPageFormatUndoAction::Repeat() { Redo(); } /************************************************************************* |* |* LR-Destruktor |* \************************************************************************/ SdPageLRUndoAction::~SdPageLRUndoAction() { } /************************************************************************* |* |* LR-Undo() |* \************************************************************************/ void SdPageLRUndoAction::Undo() { pPage->SetLftBorder(nOldLeft); pPage->SetRgtBorder(nOldRight); } /************************************************************************* |* |* LR-Redo() |* \************************************************************************/ void SdPageLRUndoAction::Redo() { pPage->SetLftBorder(nNewLeft); pPage->SetRgtBorder(nNewRight); } /************************************************************************* |* |* LR-Repeat() |* \************************************************************************/ void SdPageLRUndoAction::Repeat() { Redo(); } /************************************************************************* |* |* UL-Destruktor |* \************************************************************************/ SdPageULUndoAction::~SdPageULUndoAction() { } /************************************************************************* |* |* UL-Undo() |* \************************************************************************/ void SdPageULUndoAction::Undo() { pPage->SetUppBorder(nOldUpper); pPage->SetLwrBorder(nOldLower); } /************************************************************************* |* |* UL-Redo() |* \************************************************************************/ void SdPageULUndoAction::Redo() { pPage->SetUppBorder(nNewUpper); pPage->SetLwrBorder(nNewLower); } /************************************************************************* |* |* UL-Repeat() |* \************************************************************************/ void SdPageULUndoAction::Repeat() { Redo(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: undopage.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-09-16 19:00:21 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "undopage.hxx" #include <svx/svxids.hrc> #ifndef _SFX_BINDINGS_HXX //autogen #include <sfx2/bindings.hxx> #endif #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #ifndef _SFXVIEWFRM_HXX #include <sfx2/viewfrm.hxx> #endif #include "sdpage.hxx" #ifndef SD_DRAW_VIEW_SHELL_HXX #include "DrawViewShell.hxx" #endif #ifndef SD_DRAW_VIEW_HXX #include "drawview.hxx" #endif #ifndef _SVDPAGV_HXX //autogen #include <svx/svdpagv.hxx> #endif TYPEINIT1(SdPageFormatUndoAction, SdUndoAction); TYPEINIT1(SdPageLRUndoAction, SdUndoAction); TYPEINIT1(SdPageULUndoAction, SdUndoAction); /************************************************************************* |* |* Destruktor |* \************************************************************************/ SdPageFormatUndoAction::~SdPageFormatUndoAction() { } /************************************************************************* |* |* Undo() |* \************************************************************************/ void SdPageFormatUndoAction::Undo() { Rectangle aOldBorderRect(nOldLeft, nOldUpper, nOldRight, nOldLower); pPage->ScaleObjects(aOldSize, aOldBorderRect, bNewScale); pPage->SetSize(aOldSize); pPage->SetLftBorder(nOldLeft); pPage->SetRgtBorder(nOldRight); pPage->SetUppBorder(nOldUpper); pPage->SetLwrBorder(nOldLower); pPage->SetOrientation(eOldOrientation); pPage->SetPaperBin( nOldPaperBin ); pPage->SetBackgroundFullSize( bOldFullSize ); if( !pPage->IsMasterPage() ) ( (SdPage&) pPage->TRG_GetMasterPage() ).SetBackgroundFullSize( bOldFullSize ); SfxViewShell* pViewShell = SfxViewShell::Current(); /* if ( pViewShell->ISA(::sd::DrawViewShell)) { ::sd::DrawViewShell* pDrViewShell = static_cast< ::sd::DrawViewShell*>(pViewShell); long nWidth = pPage->GetSize().Width(); long nHeight = pPage->GetSize().Height(); Point aPageOrg = Point(nWidth, nHeight / 2); Size aViewSize = Size(nWidth * 3, nHeight * 2); pDrViewShell->InitWindows(aPageOrg, aViewSize, Point(-1, -1), TRUE); pDrViewShell->GetView()->SetWorkArea(Rectangle(Point(0,0) - aPageOrg, aViewSize)); pDrViewShell->UpdateScrollBars(); pDrViewShell->GetView()->GetPageViewPvNum(0)->SetPageOrigin(Point(0,0)); pViewShell->GetViewFrame()->GetBindings().Invalidate(SID_RULER_NULL_OFFSET); pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_SIZE_PAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD); } */ } /************************************************************************* |* |* Redo() |* \************************************************************************/ void SdPageFormatUndoAction::Redo() { Rectangle aNewBorderRect(nNewLeft, nNewUpper, nNewRight, nNewLower); pPage->ScaleObjects(aNewSize, aNewBorderRect, bNewScale); pPage->SetSize(aNewSize); pPage->SetLftBorder(nNewLeft); pPage->SetRgtBorder(nNewRight); pPage->SetUppBorder(nNewUpper); pPage->SetLwrBorder(nNewLower); pPage->SetOrientation(eNewOrientation); pPage->SetPaperBin( nNewPaperBin ); pPage->SetBackgroundFullSize( bNewFullSize ); if( !pPage->IsMasterPage() ) ( (SdPage&) pPage->TRG_GetMasterPage() ).SetBackgroundFullSize( bNewFullSize ); SfxViewShell* pViewShell = SfxViewShell::Current(); /* if ( pViewShell->ISA(::sd::DrawViewShell)) { ::sd::DrawViewShell* pDrViewShell = static_cast< ::sd::DrawViewShell*>(pViewShell); long nWidth = pPage->GetSize().Width(); long nHeight = pPage->GetSize().Height(); Point aPageOrg = Point(nWidth, nHeight / 2); Size aViewSize = Size(nWidth * 3, nHeight * 2); pDrViewShell->InitWindows(aPageOrg, aViewSize, Point(-1, -1), TRUE); pDrViewShell->GetView()->SetWorkArea(Rectangle(Point(0,0) - aPageOrg, aViewSize)); pDrViewShell->UpdateScrollBars(); pDrViewShell->GetView()->GetPageViewPvNum(0)->SetPageOrigin(Point(0,0)); pViewShell->GetViewFrame()->GetBindings().Invalidate(SID_RULER_NULL_OFFSET); pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_SIZE_PAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD); } */ } /************************************************************************* |* |* Repeat() |* \************************************************************************/ void SdPageFormatUndoAction::Repeat() { Redo(); } /************************************************************************* |* |* LR-Destruktor |* \************************************************************************/ SdPageLRUndoAction::~SdPageLRUndoAction() { } /************************************************************************* |* |* LR-Undo() |* \************************************************************************/ void SdPageLRUndoAction::Undo() { pPage->SetLftBorder(nOldLeft); pPage->SetRgtBorder(nOldRight); } /************************************************************************* |* |* LR-Redo() |* \************************************************************************/ void SdPageLRUndoAction::Redo() { pPage->SetLftBorder(nNewLeft); pPage->SetRgtBorder(nNewRight); } /************************************************************************* |* |* LR-Repeat() |* \************************************************************************/ void SdPageLRUndoAction::Repeat() { Redo(); } /************************************************************************* |* |* UL-Destruktor |* \************************************************************************/ SdPageULUndoAction::~SdPageULUndoAction() { } /************************************************************************* |* |* UL-Undo() |* \************************************************************************/ void SdPageULUndoAction::Undo() { pPage->SetUppBorder(nOldUpper); pPage->SetLwrBorder(nOldLower); } /************************************************************************* |* |* UL-Redo() |* \************************************************************************/ void SdPageULUndoAction::Redo() { pPage->SetUppBorder(nNewUpper); pPage->SetLwrBorder(nNewLower); } /************************************************************************* |* |* UL-Repeat() |* \************************************************************************/ void SdPageULUndoAction::Repeat() { Redo(); } <commit_msg>INTEGRATION: CWS aw024 (1.5.174); FILE MERGED 2006/09/21 23:20:02 aw 1.5.174.3: RESYNC: (1.6-1.7); FILE MERGED 2005/09/17 11:45:44 aw 1.5.174.2: RESYNC: (1.5-1.6); FILE MERGED 2005/05/19 12:11:29 aw 1.5.174.1: #i39529#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: undopage.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: ihi $ $Date: 2006-11-14 14:32:12 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "undopage.hxx" #include <svx/svxids.hrc> #ifndef _SFX_BINDINGS_HXX //autogen #include <sfx2/bindings.hxx> #endif #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #ifndef _SFXVIEWFRM_HXX #include <sfx2/viewfrm.hxx> #endif #include "sdpage.hxx" #ifndef SD_DRAW_VIEW_SHELL_HXX #include "DrawViewShell.hxx" #endif #ifndef SD_DRAW_VIEW_HXX #include "drawview.hxx" #endif #ifndef _SVDPAGV_HXX //autogen #include <svx/svdpagv.hxx> #endif TYPEINIT1(SdPageFormatUndoAction, SdUndoAction); TYPEINIT1(SdPageLRUndoAction, SdUndoAction); TYPEINIT1(SdPageULUndoAction, SdUndoAction); /************************************************************************* |* |* Destruktor |* \************************************************************************/ SdPageFormatUndoAction::~SdPageFormatUndoAction() { } /************************************************************************* |* |* Undo() |* \************************************************************************/ void SdPageFormatUndoAction::Undo() { Rectangle aOldBorderRect(nOldLeft, nOldUpper, nOldRight, nOldLower); pPage->ScaleObjects(aOldSize, aOldBorderRect, bNewScale); pPage->SetSize(aOldSize); pPage->SetLftBorder(nOldLeft); pPage->SetRgtBorder(nOldRight); pPage->SetUppBorder(nOldUpper); pPage->SetLwrBorder(nOldLower); pPage->SetOrientation(eOldOrientation); pPage->SetPaperBin( nOldPaperBin ); pPage->SetBackgroundFullSize( bOldFullSize ); if( !pPage->IsMasterPage() ) ( (SdPage&) pPage->TRG_GetMasterPage() ).SetBackgroundFullSize( bOldFullSize ); SfxViewShell* pViewShell = SfxViewShell::Current(); /* if ( pViewShell->ISA(::sd::DrawViewShell)) { ::sd::DrawViewShell* pDrViewShell = static_cast< ::sd::DrawViewShell*>(pViewShell); long nWidth = pPage->GetSize().Width(); long nHeight = pPage->GetSize().Height(); Point aPageOrg = Point(nWidth, nHeight / 2); Size aViewSize = Size(nWidth * 3, nHeight * 2); pDrViewShell->InitWindows(aPageOrg, aViewSize, Point(-1, -1), TRUE); pDrViewShell->GetView()->SetWorkArea(Rectangle(Point(0,0) - aPageOrg, aViewSize)); pDrViewShell->UpdateScrollBars(); pDrViewShell->GetView()->GetPageViewByIndex(0)->SetPageOrigin(Point(0,0)); pViewShell->GetViewFrame()->GetBindings().Invalidate(SID_RULER_NULL_OFFSET); pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_SIZE_PAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD); } */ } /************************************************************************* |* |* Redo() |* \************************************************************************/ void SdPageFormatUndoAction::Redo() { Rectangle aNewBorderRect(nNewLeft, nNewUpper, nNewRight, nNewLower); pPage->ScaleObjects(aNewSize, aNewBorderRect, bNewScale); pPage->SetSize(aNewSize); pPage->SetLftBorder(nNewLeft); pPage->SetRgtBorder(nNewRight); pPage->SetUppBorder(nNewUpper); pPage->SetLwrBorder(nNewLower); pPage->SetOrientation(eNewOrientation); pPage->SetPaperBin( nNewPaperBin ); pPage->SetBackgroundFullSize( bNewFullSize ); if( !pPage->IsMasterPage() ) ( (SdPage&) pPage->TRG_GetMasterPage() ).SetBackgroundFullSize( bNewFullSize ); SfxViewShell* pViewShell = SfxViewShell::Current(); /* if ( pViewShell->ISA(::sd::DrawViewShell)) { ::sd::DrawViewShell* pDrViewShell = static_cast< ::sd::DrawViewShell*>(pViewShell); long nWidth = pPage->GetSize().Width(); long nHeight = pPage->GetSize().Height(); Point aPageOrg = Point(nWidth, nHeight / 2); Size aViewSize = Size(nWidth * 3, nHeight * 2); pDrViewShell->InitWindows(aPageOrg, aViewSize, Point(-1, -1), TRUE); pDrViewShell->GetView()->SetWorkArea(Rectangle(Point(0,0) - aPageOrg, aViewSize)); pDrViewShell->UpdateScrollBars(); pDrViewShell->GetView()->GetPageViewByIndex(0)->SetPageOrigin(Point(0,0)); pViewShell->GetViewFrame()->GetBindings().Invalidate(SID_RULER_NULL_OFFSET); pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_SIZE_PAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD); } */ } /************************************************************************* |* |* Repeat() |* \************************************************************************/ void SdPageFormatUndoAction::Repeat() { Redo(); } /************************************************************************* |* |* LR-Destruktor |* \************************************************************************/ SdPageLRUndoAction::~SdPageLRUndoAction() { } /************************************************************************* |* |* LR-Undo() |* \************************************************************************/ void SdPageLRUndoAction::Undo() { pPage->SetLftBorder(nOldLeft); pPage->SetRgtBorder(nOldRight); } /************************************************************************* |* |* LR-Redo() |* \************************************************************************/ void SdPageLRUndoAction::Redo() { pPage->SetLftBorder(nNewLeft); pPage->SetRgtBorder(nNewRight); } /************************************************************************* |* |* LR-Repeat() |* \************************************************************************/ void SdPageLRUndoAction::Repeat() { Redo(); } /************************************************************************* |* |* UL-Destruktor |* \************************************************************************/ SdPageULUndoAction::~SdPageULUndoAction() { } /************************************************************************* |* |* UL-Undo() |* \************************************************************************/ void SdPageULUndoAction::Undo() { pPage->SetUppBorder(nOldUpper); pPage->SetLwrBorder(nOldLower); } /************************************************************************* |* |* UL-Redo() |* \************************************************************************/ void SdPageULUndoAction::Redo() { pPage->SetUppBorder(nNewUpper); pPage->SetLwrBorder(nNewLower); } /************************************************************************* |* |* UL-Repeat() |* \************************************************************************/ void SdPageULUndoAction::Repeat() { Redo(); } <|endoftext|>
<commit_before><commit_msg>don't crash on formatting outline level 10 in master view<commit_after><|endoftext|>
<commit_before>#ifndef ASYNCCURL_HPP_ #define ASYNCCURL_HPP_ /* * Author: jrahm * created: 2015/02/13 * AsyncCurl.hpp: <description> */ #include <curl/curl.h> #include <os/Runnable.hpp> #include <containers/BlockingQueue.hpp> #include <lang/Deallocator.hpp> namespace curl { class CurlException: public CException { public: CurlException(const char* err, int code): CException(err, code){} }; typedef s32_t http_response_code_t; class CurlObserver { public: virtual void onOK(http_response_code_t status_code) = 0 ; virtual void onException(CurlException& exc) = 0 ; virtual void read(const byte* bytes, size_t size) = 0 ; virtual inline ~CurlObserver(){} }; class AsyncCurl; class Curl { public: friend class AsyncCurl; inline Curl() { raw = curl_easy_init(); } inline void setSSLPeerVerifyEnabled( bool enabled ) { curl_easy_setopt(raw, CURLOPT_SSL_VERIFYPEER, enabled); } inline void setSSLHostVerifyEnabled( bool enabled ) { curl_easy_setopt(raw, CURLOPT_SSL_VERIFYHOST, enabled); } inline void setURL( const char* url ) { curl_easy_setopt(raw, CURLOPT_URL, url); } inline void setFollowLocation( bool follow ) { curl_easy_setopt(raw, CURLOPT_FOLLOWLOCATION, follow); } inline void setPostFields( const char* data ) { curl_easy_setopt(raw, CURLOPT_POSTFIELDS, data); } private: CURL* raw; }; class AsyncCurl: public os::Runnable { public: AsyncCurl(); /* Send a curl request */ void sendRequest( Curl& c, CurlObserver* observer, lang::Deallocator<CurlObserver>* dalloc=NULL ); void run(); private: static size_t __curl_consume_subroutine( void*, size_t, size_t, void* ); static bool curl_init ; class Triad { public: CURL* request; CurlObserver* observer; lang::Deallocator<CurlObserver>* dalloc; }; void enqueue_raw( CURL* c, CurlObserver* obs, lang::Deallocator<CurlObserver>* dealloc ); containers::BlockingQueue<Triad*> requests; }; } #endif /* ASYNCCURL_HPP_ */ <commit_msg>patched async curl<commit_after>#ifndef ASYNCCURL_HPP_ #define ASYNCCURL_HPP_ /* * Author: jrahm * created: 2015/02/13 * AsyncCurl.hpp: <description> */ #include <curl/curl.h> #include <os/Runnable.hpp> #include <containers/BlockingQueue.hpp> #include <lang/Deallocator.hpp> namespace curl { class CurlException: public CException { public: CurlException(const char* err, int code): CException(err, code){} }; typedef s32_t http_response_code_t; class CurlObserver { public: virtual void onOK(http_response_code_t status_code) = 0 ; virtual void onException(CurlException& exc) = 0 ; virtual void read(const byte* bytes, size_t size) = 0 ; virtual inline ~CurlObserver(){} }; class AsyncCurl; class Curl { public: friend class AsyncCurl; inline Curl() { raw = curl_easy_init(); } inline void setSSLPeerVerifyEnabled( bool enabled ) { curl_easy_setopt(raw, CURLOPT_SSL_VERIFYPEER, enabled); } inline void setSSLHostVerifyEnabled( bool enabled ) { curl_easy_setopt(raw, CURLOPT_SSL_VERIFYHOST, enabled); } inline void setURL( const char* url ) { curl_easy_setopt(raw, CURLOPT_URL, url); } inline void setFollowLocation( bool follow ) { curl_easy_setopt(raw, CURLOPT_FOLLOWLOCATION, follow); } inline void setPostFields( const char* data ) { curl_easy_setopt(raw, CURLOPT_POSTFIELDS, strdup(data)); } private: CURL* raw; }; class AsyncCurl: public os::Runnable { public: AsyncCurl(); /* Send a curl request */ void sendRequest( Curl& c, CurlObserver* observer, lang::Deallocator<CurlObserver>* dalloc=NULL ); void run(); private: static size_t __curl_consume_subroutine( void*, size_t, size_t, void* ); static bool curl_init ; class Triad { public: CURL* request; CurlObserver* observer; lang::Deallocator<CurlObserver>* dalloc; }; void enqueue_raw( CURL* c, CurlObserver* obs, lang::Deallocator<CurlObserver>* dealloc ); containers::BlockingQueue<Triad*> requests; }; } #endif /* ASYNCCURL_HPP_ */ <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 "CloseTransportsTask.h" #include <activemq/exceptions/ActiveMQException.h> using namespace activemq; using namespace activemq::threads; using namespace activemq::exceptions; using namespace activemq::transport; using namespace activemq::transport::failover; using namespace decaf; using namespace decaf::lang; using namespace decaf::util; using namespace decaf::util::concurrent; //////////////////////////////////////////////////////////////////////////////// void CloseTransportsTask::add( const Pointer<Transport>& transport ) { synchronized( &transports ) { transports.push( transport ); } } //////////////////////////////////////////////////////////////////////////////// bool CloseTransportsTask::isPending() const { synchronized( &transports ) { return !transports.empty(); } } //////////////////////////////////////////////////////////////////////////////// bool CloseTransportsTask::iterate() { synchronized( &transports ) { if( !transports.empty() ) { Pointer<Transport> transport = transports.pop(); try{ transport->close(); } AMQ_CATCHALL_NOTHROW() transport.reset( NULL ); return !transports.empty(); } } return false; } <commit_msg>Fix a warning on Windows<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 "CloseTransportsTask.h" #include <activemq/exceptions/ActiveMQException.h> using namespace activemq; using namespace activemq::threads; using namespace activemq::exceptions; using namespace activemq::transport; using namespace activemq::transport::failover; using namespace decaf; using namespace decaf::lang; using namespace decaf::util; using namespace decaf::util::concurrent; //////////////////////////////////////////////////////////////////////////////// void CloseTransportsTask::add( const Pointer<Transport>& transport ) { synchronized( &transports ) { transports.push( transport ); } } //////////////////////////////////////////////////////////////////////////////// bool CloseTransportsTask::isPending() const { bool result = false; synchronized( &transports ) { result = !transports.empty(); } return result; } //////////////////////////////////////////////////////////////////////////////// bool CloseTransportsTask::iterate() { synchronized( &transports ) { if( !transports.empty() ) { Pointer<Transport> transport = transports.pop(); try{ transport->close(); } AMQ_CATCHALL_NOTHROW() transport.reset( NULL ); return !transports.empty(); } } return false; } <|endoftext|>
<commit_before>#ifdef HAVE_CONFIG_H # include <simgear_config.h> #endif #include "event_mgr.hxx" #include <simgear/debug/logstream.hxx> void SGEventMgr::add(const std::string& name, SGCallback* cb, double interval, double delay, bool repeat, bool simtime) { // Clamp the delay value to 1 usec, so that user code can use // "zero" as a synonym for "next frame". if(delay <= 0) delay = 1e-6; if(interval <= 0) interval = 1e-6; // No timer endless loops please... SGTimer* t = new SGTimer; t->interval = interval; t->callback = cb; t->repeat = repeat; t->name = name; t->running = false; SGTimerQueue* q = simtime ? &_simQueue : &_rtQueue; q->insert(t, delay); } SGTimer::~SGTimer() { delete callback; callback = NULL; } void SGTimer::run() { (*callback)(); } SGEventMgr::SGEventMgr() : _inited(false) { } SGEventMgr::~SGEventMgr() { } void SGEventMgr::unbind() { _freezeProp.clear(); _rtProp.clear(); } void SGEventMgr::init() { if (_inited) { SG_LOG(SG_GENERAL, SG_WARN, "duplicate init of SGEventMgr"); } _inited = true; } void SGEventMgr::shutdown() { _inited = false; _simQueue.clear(); _rtQueue.clear(); } void SGEventMgr::update(double delta_time_sec) { _simQueue.update(delta_time_sec); double rt = _rtProp ? _rtProp->getDoubleValue() : 0; _rtQueue.update(rt); } void SGEventMgr::removeTask(const std::string& name) { // due to the ordering of the event-mgr in FG, tasks can be removed // after we are shutdown (and hence, have all been cleared). Guard // against this so we don't generate warnings below. if (!_inited) { return; } SGTimer* t = _simQueue.findByName(name); if (t) { _simQueue.remove(t); } else if ((t = _rtQueue.findByName(name))) { _rtQueue.remove(t); } else { SG_LOG(SG_GENERAL, SG_WARN, "removeTask: no task found with name:" << name); return; } if (t->running) { // mark as not repeating so that the SGTimerQueue::update() // will clean it up t->repeat = false; } else { delete t; } } //////////////////////////////////////////////////////////////////////// // SGTimerQueue // This is the priority queue implementation: //////////////////////////////////////////////////////////////////////// SGTimerQueue::SGTimerQueue(int size) { _now = 0; _numEntries = 0; _tableSize = 1; while(size > _tableSize) _tableSize = ((_tableSize + 1)<<1) - 1; _table = new HeapEntry[_tableSize]; for(int i=0; i<_tableSize; i++) { _table[i].pri = 0; _table[i].timer = 0; } } SGTimerQueue::~SGTimerQueue() { clear(); delete[] _table; } void SGTimerQueue::clear() { // delete entries for(int i=0; i<_numEntries; i++) { delete _table[i].timer; } _numEntries = 0; // clear entire table to empty for(int i=0; i<_tableSize; i++) { _table[i].pri = 0; _table[i].timer = 0; } } void SGTimerQueue::update(double deltaSecs) { _now += deltaSecs; while(_numEntries && nextTime() <= _now) { SGTimer* t = remove(); if(t->repeat) insert(t, t->interval); // warning: this is not thread safe // but the entire timer queue isn't either t->running = true; t->run(); t->running = false; if (!t->repeat) delete t; } } void SGTimerQueue::insert(SGTimer* timer, double time) { if(_numEntries >= _tableSize) growArray(); _numEntries++; _table[_numEntries-1].pri = -(_now + time); _table[_numEntries-1].timer = timer; siftUp(_numEntries-1); } SGTimer* SGTimerQueue::remove(SGTimer* t) { int entry; for(entry=0; entry<_numEntries; entry++) if(_table[entry].timer == t) break; if(entry == _numEntries) return 0; // Swap in the last item in the table, and sift down swap(entry, _numEntries-1); _numEntries--; siftDown(entry); return t; } SGTimer* SGTimerQueue::remove() { if(_numEntries == 0) { return 0; } else if(_numEntries == 1) { _numEntries = 0; return _table[0].timer; } SGTimer *result = _table[0].timer; _table[0] = _table[_numEntries - 1]; _numEntries--; siftDown(0); return result; } void SGTimerQueue::siftDown(int n) { // While we have children bigger than us, swap us with the biggest // child. while(lchild(n) < _numEntries) { int bigc = lchild(n); if(rchild(n) < _numEntries && pri(rchild(n)) > pri(bigc)) bigc = rchild(n); if(pri(bigc) <= pri(n)) break; swap(n, bigc); n = bigc; } } void SGTimerQueue::siftUp(int n) { while((n != 0) && (_table[n].pri > _table[parent(n)].pri)) { swap(n, parent(n)); n = parent(n); } siftDown(n); } void SGTimerQueue::growArray() { _tableSize = ((_tableSize+1)<<1) - 1; HeapEntry *newTable = new HeapEntry[_tableSize]; for(int i=0; i<_numEntries; i++) { newTable[i].pri = _table[i].pri; newTable[i].timer = _table[i].timer; } delete[] _table; _table = newTable; } SGTimer* SGTimerQueue::findByName(const std::string& name) const { for (int i=0; i < _numEntries; ++i) { if (_table[i].timer->name == name) { return _table[i].timer; } } return NULL; } <commit_msg>Avoid a warning on startup<commit_after>#ifdef HAVE_CONFIG_H # include <simgear_config.h> #endif #include "event_mgr.hxx" #include <simgear/debug/logstream.hxx> void SGEventMgr::add(const std::string& name, SGCallback* cb, double interval, double delay, bool repeat, bool simtime) { // Clamp the delay value to 1 usec, so that user code can use // "zero" as a synonym for "next frame". if(delay <= 0) delay = 1e-6; if(interval <= 0) interval = 1e-6; // No timer endless loops please... SGTimer* t = new SGTimer; t->interval = interval; t->callback = cb; t->repeat = repeat; t->name = name; t->running = false; SGTimerQueue* q = simtime ? &_simQueue : &_rtQueue; q->insert(t, delay); } SGTimer::~SGTimer() { delete callback; callback = NULL; } void SGTimer::run() { (*callback)(); } SGEventMgr::SGEventMgr() : _inited(false) { } SGEventMgr::~SGEventMgr() { } void SGEventMgr::unbind() { _freezeProp.clear(); _rtProp.clear(); } void SGEventMgr::init() { if (_inited) { // protected against duplicate calls here, in case // init ever does something more complex in the future. return; } _inited = true; } void SGEventMgr::shutdown() { _inited = false; _simQueue.clear(); _rtQueue.clear(); } void SGEventMgr::update(double delta_time_sec) { _simQueue.update(delta_time_sec); double rt = _rtProp ? _rtProp->getDoubleValue() : 0; _rtQueue.update(rt); } void SGEventMgr::removeTask(const std::string& name) { // due to the ordering of the event-mgr in FG, tasks can be removed // after we are shutdown (and hence, have all been cleared). Guard // against this so we don't generate warnings below. if (!_inited) { return; } SGTimer* t = _simQueue.findByName(name); if (t) { _simQueue.remove(t); } else if ((t = _rtQueue.findByName(name))) { _rtQueue.remove(t); } else { SG_LOG(SG_GENERAL, SG_WARN, "removeTask: no task found with name:" << name); return; } if (t->running) { // mark as not repeating so that the SGTimerQueue::update() // will clean it up t->repeat = false; } else { delete t; } } //////////////////////////////////////////////////////////////////////// // SGTimerQueue // This is the priority queue implementation: //////////////////////////////////////////////////////////////////////// SGTimerQueue::SGTimerQueue(int size) { _now = 0; _numEntries = 0; _tableSize = 1; while(size > _tableSize) _tableSize = ((_tableSize + 1)<<1) - 1; _table = new HeapEntry[_tableSize]; for(int i=0; i<_tableSize; i++) { _table[i].pri = 0; _table[i].timer = 0; } } SGTimerQueue::~SGTimerQueue() { clear(); delete[] _table; } void SGTimerQueue::clear() { // delete entries for(int i=0; i<_numEntries; i++) { delete _table[i].timer; } _numEntries = 0; // clear entire table to empty for(int i=0; i<_tableSize; i++) { _table[i].pri = 0; _table[i].timer = 0; } } void SGTimerQueue::update(double deltaSecs) { _now += deltaSecs; while(_numEntries && nextTime() <= _now) { SGTimer* t = remove(); if(t->repeat) insert(t, t->interval); // warning: this is not thread safe // but the entire timer queue isn't either t->running = true; t->run(); t->running = false; if (!t->repeat) delete t; } } void SGTimerQueue::insert(SGTimer* timer, double time) { if(_numEntries >= _tableSize) growArray(); _numEntries++; _table[_numEntries-1].pri = -(_now + time); _table[_numEntries-1].timer = timer; siftUp(_numEntries-1); } SGTimer* SGTimerQueue::remove(SGTimer* t) { int entry; for(entry=0; entry<_numEntries; entry++) if(_table[entry].timer == t) break; if(entry == _numEntries) return 0; // Swap in the last item in the table, and sift down swap(entry, _numEntries-1); _numEntries--; siftDown(entry); return t; } SGTimer* SGTimerQueue::remove() { if(_numEntries == 0) { return 0; } else if(_numEntries == 1) { _numEntries = 0; return _table[0].timer; } SGTimer *result = _table[0].timer; _table[0] = _table[_numEntries - 1]; _numEntries--; siftDown(0); return result; } void SGTimerQueue::siftDown(int n) { // While we have children bigger than us, swap us with the biggest // child. while(lchild(n) < _numEntries) { int bigc = lchild(n); if(rchild(n) < _numEntries && pri(rchild(n)) > pri(bigc)) bigc = rchild(n); if(pri(bigc) <= pri(n)) break; swap(n, bigc); n = bigc; } } void SGTimerQueue::siftUp(int n) { while((n != 0) && (_table[n].pri > _table[parent(n)].pri)) { swap(n, parent(n)); n = parent(n); } siftDown(n); } void SGTimerQueue::growArray() { _tableSize = ((_tableSize+1)<<1) - 1; HeapEntry *newTable = new HeapEntry[_tableSize]; for(int i=0; i<_numEntries; i++) { newTable[i].pri = _table[i].pri; newTable[i].timer = _table[i].timer; } delete[] _table; _table = newTable; } SGTimer* SGTimerQueue::findByName(const std::string& name) const { for (int i=0; i < _numEntries; ++i) { if (_table[i].timer->name == name) { return _table[i].timer; } } return NULL; } <|endoftext|>
<commit_before>#include <iostream> #include "readatomslinks.h" #include "limits.h" #include "spin.h" std::vector<Atom> atoms; /** * Computes the energy of the system. * <p> * Using the atom, the spin and the neighbors, it is computed the energy of the system. * @param atoms vector with the spin values of the atom * @param spin random spin orientation of the atom * @param csr compressed sparse row that contains the information of the atoms' neighbors * @return double Ener the energy of the system. */ double compute_energy (const std::vector<Atom>& atoms, const std::vector<Spin>& spins, const CSRMatrix& csr) { /** Energy of the system. */ double Ener{0}; /** Spin value of the atom and the neighbors. */ double SpinValue; for (int i = 0; i < atoms.size(); ++i) { for (int j = csr.limits[i] ; j < csr.limits[i+1]; ++j) { SpinValue = spins[i] * spins[csr.neighboors[j]]; Ener -= csr.exchanges[j] * atoms[i].s * atoms[csr.neighboors[j]].s * SpinValue; } } return Ener; }<commit_msg>Testing something with the branches<commit_after>#include <iostream> #include "readatomslinks.h" #include "limits.h" #include "spin.h" std::vector<Atom> atoms; /** * Computes the energy of the system. * <p> * Using the atom, the spin and the neighbors, it is computed the energy of the system. * @param atoms vector with the spin values of the atom * @param spin random spin orientation of the atom * @param csr compressed sparse row that contains the information of the atoms' neighbors * @return double ener the energy of the system. */ double compute_energy (const std::vector<Atom>& atoms, const std::vector<Spin>& spins, const CSRMatrix& csr) { /** Energy of the system. */ double ener{0}; /** Spin value of the atom and the neighbors. */ double SpinValue; for (int i = 0; i < atoms.size(); ++i) { for (int j = csr.limits[i] ; j < csr.limits[i+1]; ++j) { SpinValue = spins[i] * spins[csr.neighboors[j]]; ener -= csr.exchanges[j] * atoms[i].s * atoms[csr.neighboors[j]].s * SpinValue; } } return ener; }<|endoftext|>
<commit_before>#include <cstring> #include <iostream> #include <net/ethernet.h> #include <netinet/ether.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <arpa/inet.h> #include "colors.h" #include "interface.h" using namespace std; using namespace Colors; void sigint_handler(int); int main(int argc, char* argv[]) { if (argc != 2) { std::cerr << "Usage: phantom <interface>" << endl; exit(-1); } if (initSignal(sigint_handler) < 0) exit(-1); int socket; if (initSocket(socket) < 0) exit(-1); struct ifreq ifr; strcpy(ifr.ifr_name, argv[1]); if (initInterface(socket, ifr) < 0) exit(-1); // Ready to capture. :-) cout << blue << "Ready to capture from: " << reset << ifr.ifr_name << endl; cout << blue << " Interface Index: " << reset << ifr.ifr_ifindex << endl; cout << blue << " Hardware Addr: " << reset << ether_ntoa((struct ether_addr*)ifr.ifr_hwaddr.sa_data) << endl; cout << blue << " Protocol Addr: " << reset << inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr) << endl; if (resetInterface(socket, ifr) < 0) exit(-1); if (closeSocket(socket) < 0) exit(-1); return 0; } void sigint_handler(int) { } <commit_msg>Add sniffing for ethernet & ip packets.<commit_after>#include <cstring> #include <iostream> #include <thread> #include <net/ethernet.h> #include <netinet/ether.h> #include <linux/ip.h> #include <netinet/udp.h> #include <arpa/inet.h> #include "colors.h" #include "interface.h" using namespace std; using namespace Colors; void sigint_handler(int); void sniff(const int, const ifreq&); bool stop = false; int main(int argc, char* argv[]) { if (argc != 2) { std::cerr << "Usage: phantom <interface>" << endl; exit(-1); } if (initSignal(sigint_handler) < 0) exit(-1); int socket; if (initSocket(socket) < 0) exit(-1); struct ifreq ifr; strcpy(ifr.ifr_name, argv[1]); if (initInterface(socket, ifr) < 0) exit(-1); std::thread sniffer(sniff, socket, ifr); sniffer.join(); if (resetInterface(socket, ifr) < 0) exit(-1); if (closeSocket(socket) < 0) exit(-1); return 0; } void sigint_handler(int) { cout << yellow << "Received SIGINT to interrupt execution." << reset << endl; stop = true; } void sniff(const int socket, const ifreq& ifr) { cout << blue << "Ready to capture from: " << reset << ifr.ifr_name << endl; cout << blue << " Interface Index: " << reset << ifr.ifr_ifindex << endl; cout << blue << " Hardware Addr: " << reset << ether_ntoa((struct ether_addr*)ifr.ifr_hwaddr.sa_data) << endl; cout << blue << " Protocol Addr: " << reset << inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr) << endl; u_char buff[ETHER_MAX_LEN]; for (;;) { if (stop) break; if (recv(socket, (char*)&buff, sizeof(buff), 0x00) < ETHER_MIN_LEN) continue; struct ether_header ether; memcpy(&ether, &buff, sizeof(ether)); cout << endl; cout << blue << "Ethernet Packet" << reset << endl; cout << blue << "Destination: " << reset << ether_ntoa((struct ether_addr*)ether.ether_dhost) << endl; cout << blue << " Src: " << reset << ether_ntoa((struct ether_addr*)ether.ether_shost) << endl; cout << blue << " Type: " << reset << ntohs(ether.ether_type) << endl; if (ntohs(ether.ether_type) == ETHERTYPE_IP) { struct iphdr ip; memcpy(&ip, &buff[ETHER_HDR_LEN], sizeof(iphdr)); cout << endl; cout << blue << "IP Packet" << reset << endl; cout << blue << " IHL: " << reset << ip.ihl << endl; cout << blue << " Version: " << reset << ip.version << endl; cout << blue << " TOS: " << reset << ip.tos << endl; cout << blue << " LEN: " << reset << ip.tot_len << endl; cout << blue << " ID: " << reset << ip.id << endl; cout << blue << " Frag Off: " << reset << ip.frag_off << endl; cout << blue << " TTL: " << reset << ip.ttl << endl; cout << blue << " Protocol: " << reset << ntohs(ip.protocol) << endl; cout << blue << " Check: " << reset << ip.check << endl; cout << blue << " Source: " << reset << inet_ntoa(((struct sockaddr_in *)&ip.saddr)->sin_addr) << endl; cout << blue << "Destination: " << reset << inet_ntoa(((struct sockaddr_in *)&ip.daddr)->sin_addr) << endl; if (ntohs(ip.protocol) == IPPROTO_UDP) { cout << endl << red << "Received UDP packet!" << reset << endl; } } } } <|endoftext|>
<commit_before>#include <cstdint> #include <cstring> #include <memory> #include <cmath> namespace Sieves { constexpr size_t compileTimeLogBase2(size_t n) { return (n <= 1) ? 0 : 1 + compileTimeLogBase2(n / 2); } constexpr size_t sizeOfElementInBytes = sizeof(uint32_t); constexpr size_t sizeOfElementInBits = 8 * sizeOfElementInBytes; constexpr size_t logSizeOfElementInBits = compileTimeLogBase2(sizeOfElementInBits); class PrimeSieve { std::unique_ptr<uint32_t[]> m_sieve; public: PrimeSieve(const PrimeSieve&) = default; PrimeSieve(PrimeSieve&&) = default; PrimeSieve& operator=(const PrimeSieve&) = default; PrimeSieve& operator=(PrimeSieve&&) = default; explicit PrimeSieve(const size_t minSieveSize) { const size_t numOfElementsInArray = 1 + minSieveSize / sizeOfElementInBits; m_sieve = std::make_unique<uint32_t[]>(numOfElementsInArray); const size_t totalSizeInBytes = numOfElementsInArray*sizeOfElementInBytes; uint32_t* const sieve = m_sieve.get(); std::memset(sieve, 0xAA, totalSizeInBytes); sieve[0] ^= 6; const size_t limit = numOfElementsInArray*sizeOfElementInBits; const size_t sqrtLimit = std::sqrt(limit - 1); for (size_t i = 3; i <= sqrtLimit; i += 2) if (sieve[i >> logSizeOfElementInBits] & (1 << (i&(sizeOfElementInBits - 1)))) for (size_t j = i + i; j < limit; j += i) sieve[j >> logSizeOfElementInBits] &= ~(1 << (j&(sizeOfElementInBits - 1))); } inline bool isPrime(size_t number) const { return m_sieve[number >> logSizeOfElementInBits] & (1 << (number&(sizeOfElementInBits - 1))); } auto countPrimes(const size_t minSieveSize) { const size_t numOfElementsInArray = 1 + minSieveSize / sizeOfElementInBits; uint32_t sum = 0; for (size_t i = 0; i < numOfElementsInArray; ++i) #ifdef _MSC_VER sum += _mm_popcnt_u32(m_sieve[i]); #else sum += __builtin_popcount(m_sieve[i]); #endif return sum; } }; class FactorCountSieve { std::unique_ptr<uint8_t[]> m_sieve; public: explicit FactorCountSieve(const size_t limit) : m_sieve(new uint8_t[limit + 1]) { uint8_t* const sieve = m_sieve.get(); std::memset(sieve, 0, limit + 1); for (size_t i = 2; i <= limit; ++i) if (!sieve[i]) for (size_t j = i + i; j <= limit; j += i) sieve[j]++; } inline uint8_t numOfFactors(size_t number) const { return m_sieve[number]; } inline uint8_t* get() const { return m_sieve.get(); } }; }<commit_msg>fixed count for non intsize multiples<commit_after>#include <cstdint> #include <cstring> #include <memory> #include <cmath> namespace Sieves { constexpr size_t compileTimeLogBase2(size_t n) { return (n <= 1) ? 0 : 1 + compileTimeLogBase2(n / 2); } constexpr size_t sizeOfElementInBytes = sizeof(uint32_t); constexpr size_t sizeOfElementInBits = 8 * sizeOfElementInBytes; constexpr size_t logSizeOfElementInBits = compileTimeLogBase2(sizeOfElementInBits); class PrimeSieve { std::unique_ptr<uint32_t[]> m_sieve; public: PrimeSieve(const PrimeSieve&) = default; PrimeSieve(PrimeSieve&&) = default; PrimeSieve& operator=(const PrimeSieve&) = default; PrimeSieve& operator=(PrimeSieve&&) = default; explicit PrimeSieve(const size_t minSieveSize) { const size_t numOfElementsInArray = 1 + minSieveSize / sizeOfElementInBits; m_sieve = std::make_unique<uint32_t[]>(numOfElementsInArray); const size_t totalSizeInBytes = numOfElementsInArray*sizeOfElementInBytes; uint32_t* const sieve = m_sieve.get(); std::memset(sieve, 0xAA, totalSizeInBytes); sieve[0] ^= 6; const size_t limit = numOfElementsInArray*sizeOfElementInBits; const size_t sqrtLimit = std::sqrt(limit - 1); for (size_t i = 3; i <= sqrtLimit; i += 2) if (sieve[i >> logSizeOfElementInBits] & (1 << (i&(sizeOfElementInBits - 1)))) for (size_t j = i + i; j < limit; j += i) sieve[j >> logSizeOfElementInBits] &= ~(1 << (j&(sizeOfElementInBits - 1))); } inline bool isPrime(size_t number) const { return m_sieve[number >> logSizeOfElementInBits] & (1 << (number&(sizeOfElementInBits - 1))); } auto countPrimes(const size_t minSieveSize) { const size_t lastIdx = minSieveSize / sizeOfElementInBits; uint32_t sum = 0; for (size_t i = 0; i < lastIdx; ++i) #ifdef _MSC_VER sum += _mm_popcnt_u32(m_sieve[i]); #else sum += __builtin_popcount(m_sieve[i]); #endif const size_t remaining = minSieveSize & (sizeOfElementInBits - 1); for (size_t i = 0; i < remaining; ++i) if((m_sieve[lastIdx] >> i) & 1) sum++; return sum; } }; class FactorCountSieve { std::unique_ptr<uint8_t[]> m_sieve; public: explicit FactorCountSieve(const size_t limit) : m_sieve(new uint8_t[limit + 1]) { uint8_t* const sieve = m_sieve.get(); std::memset(sieve, 0, limit + 1); for (size_t i = 2; i <= limit; ++i) if (!sieve[i]) for (size_t j = i + i; j <= limit; j += i) sieve[j]++; } inline uint8_t numOfFactors(size_t number) const { return m_sieve[number]; } inline uint8_t* get() const { return m_sieve.get(); } }; } <|endoftext|>
<commit_before>#include "LiquidCrystal.h" #include "LiquidCrystalRus.h" #include <stdio.h> #include <string.h> #include <inttypes.h> #include <avr/pgmspace.h> #include "WProgram.h" // except 0401 --> 0xa2 = , 0451 --> 0xb5 PROGMEM prog_uchar utf_recode[] = { 0x41,0xa0,0x42,0xa1,0xe0,0x45,0xa3,0xa4,0xa5,0xa6,0x4b,0xa7,0x4d,0x48,0x4f, 0xa8,0x50,0x43,0x54,0xa9,0xaa,0x58,0xe1,0xab,0xac,0xe2,0xad,0xae,0x62,0xaf,0xb0,0xb1, 0x61,0xb2,0xb3,0xb4,0xe3,0x65,0xb6,0xb7,0xb8,0xb9,0xba,0xbb,0xbc,0xbd,0x6f, 0xbe,0x70,0x63,0xbf,0x79,0xe4,0x78,0xe5,0xc0,0xc1,0xe6,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7 }; void LiquidCrystalRus::write(uint8_t value) { uint8_t out_char = value; if (value >= 0x80) // UTF-8 handling { if (value >= 0xc0) utf_hi_char = value - 0xd0; else { value &= 0x3f; if (!utf_hi_char && value == 1) out_char = 0xa2; // else if (utf_hi_char == 1 && value == 0x11) out_char = 0xb5; // else out_char = pgm_read_byte_near(utf_recode + value + (utf_hi_char << 6) - 0x10); LiquidCrystal::write(out_char); } } else LiquidCrystal::write(out_char); } <commit_msg>Converted LiquidCrystalRus.cpp source to UTF-8 encoding<commit_after>#include "LiquidCrystal.h" #include "LiquidCrystalRus.h" #include <stdio.h> #include <string.h> #include <inttypes.h> #include <avr/pgmspace.h> #include "WProgram.h" // except 0401 --> 0xa2 = Ё, 0451 --> 0xb5 = ё PROGMEM prog_uchar utf_recode[] = { 0x41,0xa0,0x42,0xa1,0xe0,0x45,0xa3,0xa4,0xa5,0xa6,0x4b,0xa7,0x4d,0x48,0x4f, 0xa8,0x50,0x43,0x54,0xa9,0xaa,0x58,0xe1,0xab,0xac,0xe2,0xad,0xae,0x62,0xaf,0xb0,0xb1, 0x61,0xb2,0xb3,0xb4,0xe3,0x65,0xb6,0xb7,0xb8,0xb9,0xba,0xbb,0xbc,0xbd,0x6f, 0xbe,0x70,0x63,0xbf,0x79,0xe4,0x78,0xe5,0xc0,0xc1,0xe6,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7 }; void LiquidCrystalRus::write(uint8_t value) { uint8_t out_char = value; if (value >= 0x80) // UTF-8 handling { if (value >= 0xc0) utf_hi_char = value - 0xd0; else { value &= 0x3f; if (!utf_hi_char && value == 1) out_char = 0xa2; // Ё else if (utf_hi_char == 1 && value == 0x11) out_char = 0xb5; // ё else out_char = pgm_read_byte_near(utf_recode + value + (utf_hi_char << 6) - 0x10); LiquidCrystal::write(out_char); } } else LiquidCrystal::write(out_char); } <|endoftext|>
<commit_before>// Copyright 2015 Esri. // 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 "ChangeViewpoint.h" #include "Map.h" #include "MapView.h" #include <QVBoxLayout> #include <QGraphicsProxyWidget> using namespace Esri::ArcGISRuntime; ChangeViewpoint::ChangeViewpoint(QWidget* parent) : QWidget(parent), m_map(nullptr), m_mapView(nullptr) { // Create a map using an imagery basemap m_map = new Map(Basemap::imageryWithLabels(this), this); // Create a map view, and pass in the map m_mapView = new MapView(m_map, this); m_rotationValue = 0; // Create and populate a combo box with several viewpoint types m_viewpointCombo = new QComboBox(this); m_viewpointCombo->adjustSize(); m_viewpointCombo->setStyleSheet("QComboBox#combo {color: black; background-color:#000000;}"); m_viewpointCombo->addItems(QStringList() << "Center" << "Center and scale" << "Geometry" << "Geometry and padding" << "Rotation" << "Scale: 1:5,000,000" << "Scale: 1:10,000,000" << "Animation"); // Connect the combo box signal to slot for setting new viewpoint connect(m_viewpointCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changeToNewViewpoint(int))); // Set up the UI QWidget* widget = new QWidget(); QVBoxLayout* layout = new QVBoxLayout(); layout->setMargin(0); layout->addWidget(m_viewpointCombo); widget->setLayout(layout); QGraphicsProxyWidget *proxy = m_mapView->scene()->addWidget(widget); proxy->setPos(10, 10); proxy->setOpacity(0.95); QVBoxLayout *vBoxLayout = new QVBoxLayout(); vBoxLayout->addWidget(m_mapView); setLayout(vBoxLayout); } void ChangeViewpoint::changeToNewViewpoint(int index) { // Create the objects used to change viewpoint in various cases Point ptEsriHeadquarters(-117.195681, 34.056218, 0.0, 0.0, SpatialReference(4236)); Point ptHawaii(-157.564, 20.677, SpatialReference(4236)); Envelope envBeijing(116.380, 39.920, 116.400, 39.940, SpatialReference(4236)); Viewpoint vpSpring(Envelope(-12338668.348591767, 5546908.424239618, -12338247.594362013, 5547223.989911933, SpatialReference(102100))); switch (index) { // Call setViewpoint and pass in the appropriate viewpoint case 0: // "Center" m_mapView->setViewpointCenter(ptEsriHeadquarters); break; case 1: // "Center and scale" m_mapView->setViewpointCenter(ptHawaii, 4000000.0); break; case 2: // "Geometry" m_mapView->setViewpointGeometry(envBeijing); break; case 3: // "Geometry and padding" m_mapView->setViewpointGeometry(envBeijing, 200); break; case 4: // "Rotation" m_rotationValue = (m_rotationValue + 45) % 360; m_mapView->setViewpointRotation(m_rotationValue); break; case 5: // "Scale: 1:5,000,000" m_mapView->setViewpointScale(5000000.0); break; case 6: // "Scale: 1:10,000,000" m_mapView->setViewpointScale(10000000.0); break; case 7: // "Scale: 1:5,000,000" m_mapView->setViewpointAnimated(vpSpring, 4.0, AnimationCurve::EaseInOutCubic); break; } } ChangeViewpoint::~ChangeViewpoint() { } <commit_msg>Fix geometry usage. Just pass x and y.<commit_after>// Copyright 2015 Esri. // 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 "ChangeViewpoint.h" #include "Map.h" #include "MapView.h" #include <QVBoxLayout> #include <QGraphicsProxyWidget> using namespace Esri::ArcGISRuntime; ChangeViewpoint::ChangeViewpoint(QWidget* parent) : QWidget(parent), m_map(nullptr), m_mapView(nullptr) { // Create a map using an imagery basemap m_map = new Map(Basemap::imageryWithLabels(this), this); // Create a map view, and pass in the map m_mapView = new MapView(m_map, this); m_rotationValue = 0; // Create and populate a combo box with several viewpoint types m_viewpointCombo = new QComboBox(this); m_viewpointCombo->adjustSize(); m_viewpointCombo->setStyleSheet("QComboBox#combo {color: black; background-color:#000000;}"); m_viewpointCombo->addItems(QStringList() << "Center" << "Center and scale" << "Geometry" << "Geometry and padding" << "Rotation" << "Scale: 1:5,000,000" << "Scale: 1:10,000,000" << "Animation"); // Connect the combo box signal to slot for setting new viewpoint connect(m_viewpointCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changeToNewViewpoint(int))); // Set up the UI QWidget* widget = new QWidget(); QVBoxLayout* layout = new QVBoxLayout(); layout->setMargin(0); layout->addWidget(m_viewpointCombo); widget->setLayout(layout); QGraphicsProxyWidget *proxy = m_mapView->scene()->addWidget(widget); proxy->setPos(10, 10); proxy->setOpacity(0.95); QVBoxLayout *vBoxLayout = new QVBoxLayout(); vBoxLayout->addWidget(m_mapView); setLayout(vBoxLayout); } void ChangeViewpoint::changeToNewViewpoint(int index) { // Create the objects used to change viewpoint in various cases Point ptEsriHeadquarters(-117.195681, 34.056218, SpatialReference(4236)); Point ptHawaii(-157.564, 20.677, SpatialReference(4236)); Envelope envBeijing(116.380, 39.920, 116.400, 39.940, SpatialReference(4236)); Viewpoint vpSpring(Envelope(-12338668.348591767, 5546908.424239618, -12338247.594362013, 5547223.989911933, SpatialReference(102100))); switch (index) { // Call setViewpoint and pass in the appropriate viewpoint case 0: // "Center" m_mapView->setViewpointCenter(ptEsriHeadquarters); break; case 1: // "Center and scale" m_mapView->setViewpointCenter(ptHawaii, 4000000.0); break; case 2: // "Geometry" m_mapView->setViewpointGeometry(envBeijing); break; case 3: // "Geometry and padding" m_mapView->setViewpointGeometry(envBeijing, 200); break; case 4: // "Rotation" m_rotationValue = (m_rotationValue + 45) % 360; m_mapView->setViewpointRotation(m_rotationValue); break; case 5: // "Scale: 1:5,000,000" m_mapView->setViewpointScale(5000000.0); break; case 6: // "Scale: 1:10,000,000" m_mapView->setViewpointScale(10000000.0); break; case 7: // "Scale: 1:5,000,000" m_mapView->setViewpointAnimated(vpSpring, 4.0, AnimationCurve::EaseInOutCubic); break; } } ChangeViewpoint::~ChangeViewpoint() { } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "ElemLiteralResult.hpp" #include <algorithm> #include <sax/AttributeList.hpp> #include <sax/SAXException.hpp> #include <Include/STLHelper.hpp> #include <PlatformSupport/DoubleSupport.hpp> #include <PlatformSupport/StringTokenizer.hpp> #include <DOMSupport/DOMServices.hpp> #include "AVT.hpp" #include "Constants.hpp" #include "Stylesheet.hpp" #include "StylesheetConstructionContext.hpp" #include "StylesheetExecutionContext.hpp" ElemLiteralResult::ElemLiteralResult( StylesheetConstructionContext& constructionContext, Stylesheet& stylesheetTree, const XalanDOMChar* name, const AttributeList& atts, int lineNumber, int columnNumber, int xslToken) : ElemUse(constructionContext, stylesheetTree, lineNumber, columnNumber, xslToken), m_elementName(name), m_avts() { const unsigned int nAttrs = atts.getLength(); m_avts.reserve(nAttrs); for(unsigned int i = 0; i < nAttrs; i++) { const XalanDOMChar* const aname = atts.getName(i); bool needToProcess = true; const unsigned int indexOfNSSep = indexOf(aname, XalanUnicode::charColon); XalanDOMString prefix; if(indexOfNSSep < length(aname)) { prefix = substring(aname, 0, indexOfNSSep); if(!equals(prefix, DOMServices::s_XMLNamespace)) { const XalanDOMString* const ns = getNamespaceForPrefixInternal(prefix, true); if(ns != 0 && equals(*ns, stylesheetTree.getXSLTNamespaceURI())) { const XalanDOMString localName = substring(aname, indexOfNSSep + 1); if(processPrefixControl(constructionContext, stylesheetTree, localName, atts.getValue(i)) == true) { needToProcess = false; } else if (equals(localName, Constants::ATTRNAME_VERSION) == true) { const XalanDOMChar* const value = atts.getValue(i); stylesheetTree.setXSLTVerDeclared(DoubleSupport::toDouble(value)); } } } else { // don't process namespace decls needToProcess = false; } } if(needToProcess == true) { processSpaceAttr(aname, atts, i); // Add xmlns attribute(except xmlns:xsl), xml:space, etc... // Ignore anything with xsl:xxx if(! processUseAttributeSets(constructionContext, aname, atts, i) && isAttrOK(aname, atts, i, constructionContext)) { m_avts.push_back(new AVT(aname, atts.getType(i), atts.getValue(i), *this, constructionContext)); } } } // Shrink the vector of AVTS, if necessary... if (m_avts.capacity() > m_avts.size()) { // Make a copy that's the exact size, and // swap the two... AVTVectorType(m_avts).swap(m_avts); } } ElemLiteralResult::~ElemLiteralResult() { #if !defined(XALAN_NO_NAMESPACES) using std::for_each; #endif // Clean up all entries in the vector. for_each(m_avts.begin(), m_avts.end(), DeleteFunctor<AVT>()); } const XalanDOMString& ElemLiteralResult::getElementName() const { return m_elementName; } void ElemLiteralResult::postConstruction( StylesheetConstructionContext& constructionContext, const NamespacesHandler& theParentHandler) { // OK, now check all attribute AVTs to make sure // our NamespacesHandler knows about any prefixes // that will need namespace declarations... const AVTVectorType::size_type nAttrs = m_avts.size(); for(AVTVectorType::size_type i = 0; i < nAttrs; ++i) { const AVT* const avt = m_avts[i]; const XalanDOMString& theName = avt->getName(); const unsigned int theColonIndex = indexOf(theName, XalanUnicode::charColon); if (theColonIndex != length(theName)) { m_namespacesHandler.addActivePrefix(substring(theName, 0, theColonIndex)); } } // OK, now we can chain-up... ElemUse::postConstruction(constructionContext, theParentHandler); } inline void ElemLiteralResult::doAddResultAttribute( StylesheetExecutionContext& executionContext, const XalanDOMString& thePrefix, const XalanDOMString& theName, const XalanDOMString& theValue) const { if (isEmpty(thePrefix) == true || shouldExcludeResultNamespaceNode( thePrefix, theValue) == false) { executionContext.addResultAttribute( theName, theValue); } } void ElemLiteralResult::execute(StylesheetExecutionContext& executionContext) const { executionContext.startElement(c_wstr(getElementName())); ElemUse::execute(executionContext); m_namespacesHandler.outputResultNamespaces(executionContext); // OK, now let's check to make sure we don't have to change the default namespace... const XalanDOMString* const theCurrentDefaultNamespace = executionContext.getResultNamespaceForPrefix(s_emptyString); if (theCurrentDefaultNamespace != 0) { const XalanDOMString* const theElementDefaultNamespace = m_namespacesHandler.getNamespace(s_emptyString); if (theElementDefaultNamespace == 0) { // There was no default namespace, so we have to turn the // current one off. executionContext.addResultAttribute(DOMServices::s_XMLNamespace, s_emptyString); } else if (equals(*theCurrentDefaultNamespace, *theElementDefaultNamespace) == false) { executionContext.addResultAttribute(DOMServices::s_XMLNamespace, *theElementDefaultNamespace); } } if(0 != m_avts.size()) { const AVTVectorType::size_type nAttrs = m_avts.size(); StylesheetExecutionContext::GetAndReleaseCachedString theGuard(executionContext); XalanDOMString& theStringedValue = theGuard.get(); for(AVTVectorType::size_type i = 0; i < nAttrs; ++i) { const AVT* const avt = m_avts[i]; const XalanDOMString& theName = avt->getName(); const XalanDOMString& thePrefix = avt->getPrefix(); const XalanDOMString& theSimpleValue = avt->getSimpleValue(); if (isEmpty(theSimpleValue) == false) { doAddResultAttribute(executionContext, thePrefix, theName, theSimpleValue); } else { avt->evaluate(theStringedValue, executionContext.getCurrentNode(), *this, executionContext); doAddResultAttribute(executionContext, thePrefix, theName, theStringedValue); } } } executeChildren(executionContext); executionContext.endElement(c_wstr(getElementName())); } bool ElemLiteralResult::isAttrOK( int tok, const XalanDOMChar* attrName, const AttributeList& atts, int which) const { return ElemUse::isAttrOK(tok, attrName, atts, which); } bool ElemLiteralResult::isAttrOK( const XalanDOMChar* attrName, const AttributeList& /* atts */, int /* which */, StylesheetConstructionContext& constructionContext) const { bool isAttrOK = equals(attrName, DOMServices::s_XMLNamespace) || startsWith(attrName, DOMServices::s_XMLNamespaceWithSeparator); if(isAttrOK == false) { const unsigned int indexOfNSSep = indexOf(attrName, XalanUnicode::charColon); if(indexOfNSSep < length(attrName)) { const XalanDOMString prefix = substring(attrName, 0, indexOfNSSep); const XalanDOMString* const ns = getStylesheet().getNamespaceForPrefixFromStack(prefix); if (ns != 0 && equals(*ns, constructionContext.getXSLTNamespaceURI()) == false) { isAttrOK = true; } } else { // An empty namespace is OK. isAttrOK = true; } } // TODO: Well, process it... return isAttrOK; } bool ElemLiteralResult::processPrefixControl( StylesheetConstructionContext& constructionContext, const Stylesheet& stylesheetTree, const XalanDOMString& localName, const XalanDOMChar* attrValue) { if(equals(localName, Constants::ATTRNAME_EXTENSIONELEMENTPREFIXES)) { m_namespacesHandler.processExtensionElementPrefixes(attrValue, stylesheetTree.getNamespaces(), constructionContext); return true; } else if (equals(localName, Constants::ATTRNAME_EXCLUDE_RESULT_PREFIXES)) { m_namespacesHandler.processExcludeResultPrefixes(attrValue, stylesheetTree.getNamespaces(), constructionContext); return true; } else { return false; } } bool ElemLiteralResult::shouldExcludeResultNamespaceNode( const XalanDOMString& thePrefix, const XalanDOMString& theURI) const { return m_namespacesHandler.shouldExcludeResultNamespaceNode( getStylesheet().getXSLTNamespaceURI(), thePrefix, theURI); } <commit_msg>Removed unneeded include.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "ElemLiteralResult.hpp" #include <algorithm> #include <sax/AttributeList.hpp> #include <sax/SAXException.hpp> #include <Include/STLHelper.hpp> #include <PlatformSupport/DoubleSupport.hpp> #include <DOMSupport/DOMServices.hpp> #include "AVT.hpp" #include "Constants.hpp" #include "Stylesheet.hpp" #include "StylesheetConstructionContext.hpp" #include "StylesheetExecutionContext.hpp" ElemLiteralResult::ElemLiteralResult( StylesheetConstructionContext& constructionContext, Stylesheet& stylesheetTree, const XalanDOMChar* name, const AttributeList& atts, int lineNumber, int columnNumber, int xslToken) : ElemUse(constructionContext, stylesheetTree, lineNumber, columnNumber, xslToken), m_elementName(name), m_avts() { const unsigned int nAttrs = atts.getLength(); m_avts.reserve(nAttrs); for(unsigned int i = 0; i < nAttrs; i++) { const XalanDOMChar* const aname = atts.getName(i); bool needToProcess = true; const unsigned int indexOfNSSep = indexOf(aname, XalanUnicode::charColon); XalanDOMString prefix; if(indexOfNSSep < length(aname)) { prefix = substring(aname, 0, indexOfNSSep); if(!equals(prefix, DOMServices::s_XMLNamespace)) { const XalanDOMString* const ns = getNamespaceForPrefixInternal(prefix, true); if(ns != 0 && equals(*ns, stylesheetTree.getXSLTNamespaceURI())) { const XalanDOMString localName = substring(aname, indexOfNSSep + 1); if(processPrefixControl(constructionContext, stylesheetTree, localName, atts.getValue(i)) == true) { needToProcess = false; } else if (equals(localName, Constants::ATTRNAME_VERSION) == true) { const XalanDOMChar* const value = atts.getValue(i); stylesheetTree.setXSLTVerDeclared(DoubleSupport::toDouble(value)); } } } else { // don't process namespace decls needToProcess = false; } } if(needToProcess == true) { processSpaceAttr(aname, atts, i); // Add xmlns attribute(except xmlns:xsl), xml:space, etc... // Ignore anything with xsl:xxx if(! processUseAttributeSets(constructionContext, aname, atts, i) && isAttrOK(aname, atts, i, constructionContext)) { m_avts.push_back(new AVT(aname, atts.getType(i), atts.getValue(i), *this, constructionContext)); } } } // Shrink the vector of AVTS, if necessary... if (m_avts.capacity() > m_avts.size()) { // Make a copy that's the exact size, and // swap the two... AVTVectorType(m_avts).swap(m_avts); } } ElemLiteralResult::~ElemLiteralResult() { #if !defined(XALAN_NO_NAMESPACES) using std::for_each; #endif // Clean up all entries in the vector. for_each(m_avts.begin(), m_avts.end(), DeleteFunctor<AVT>()); } const XalanDOMString& ElemLiteralResult::getElementName() const { return m_elementName; } void ElemLiteralResult::postConstruction( StylesheetConstructionContext& constructionContext, const NamespacesHandler& theParentHandler) { // OK, now check all attribute AVTs to make sure // our NamespacesHandler knows about any prefixes // that will need namespace declarations... const AVTVectorType::size_type nAttrs = m_avts.size(); for(AVTVectorType::size_type i = 0; i < nAttrs; ++i) { const AVT* const avt = m_avts[i]; const XalanDOMString& theName = avt->getName(); const unsigned int theColonIndex = indexOf(theName, XalanUnicode::charColon); if (theColonIndex != length(theName)) { m_namespacesHandler.addActivePrefix(substring(theName, 0, theColonIndex)); } } // OK, now we can chain-up... ElemUse::postConstruction(constructionContext, theParentHandler); } inline void ElemLiteralResult::doAddResultAttribute( StylesheetExecutionContext& executionContext, const XalanDOMString& thePrefix, const XalanDOMString& theName, const XalanDOMString& theValue) const { if (isEmpty(thePrefix) == true || shouldExcludeResultNamespaceNode( thePrefix, theValue) == false) { executionContext.addResultAttribute( theName, theValue); } } void ElemLiteralResult::execute(StylesheetExecutionContext& executionContext) const { executionContext.startElement(c_wstr(getElementName())); ElemUse::execute(executionContext); m_namespacesHandler.outputResultNamespaces(executionContext); // OK, now let's check to make sure we don't have to change the default namespace... const XalanDOMString* const theCurrentDefaultNamespace = executionContext.getResultNamespaceForPrefix(s_emptyString); if (theCurrentDefaultNamespace != 0) { const XalanDOMString* const theElementDefaultNamespace = m_namespacesHandler.getNamespace(s_emptyString); if (theElementDefaultNamespace == 0) { // There was no default namespace, so we have to turn the // current one off. executionContext.addResultAttribute(DOMServices::s_XMLNamespace, s_emptyString); } else if (equals(*theCurrentDefaultNamespace, *theElementDefaultNamespace) == false) { executionContext.addResultAttribute(DOMServices::s_XMLNamespace, *theElementDefaultNamespace); } } if(0 != m_avts.size()) { const AVTVectorType::size_type nAttrs = m_avts.size(); StylesheetExecutionContext::GetAndReleaseCachedString theGuard(executionContext); XalanDOMString& theStringedValue = theGuard.get(); for(AVTVectorType::size_type i = 0; i < nAttrs; ++i) { const AVT* const avt = m_avts[i]; const XalanDOMString& theName = avt->getName(); const XalanDOMString& thePrefix = avt->getPrefix(); const XalanDOMString& theSimpleValue = avt->getSimpleValue(); if (isEmpty(theSimpleValue) == false) { doAddResultAttribute(executionContext, thePrefix, theName, theSimpleValue); } else { avt->evaluate(theStringedValue, executionContext.getCurrentNode(), *this, executionContext); doAddResultAttribute(executionContext, thePrefix, theName, theStringedValue); } } } executeChildren(executionContext); executionContext.endElement(c_wstr(getElementName())); } bool ElemLiteralResult::isAttrOK( int tok, const XalanDOMChar* attrName, const AttributeList& atts, int which) const { return ElemUse::isAttrOK(tok, attrName, atts, which); } bool ElemLiteralResult::isAttrOK( const XalanDOMChar* attrName, const AttributeList& /* atts */, int /* which */, StylesheetConstructionContext& constructionContext) const { bool isAttrOK = equals(attrName, DOMServices::s_XMLNamespace) || startsWith(attrName, DOMServices::s_XMLNamespaceWithSeparator); if(isAttrOK == false) { const unsigned int indexOfNSSep = indexOf(attrName, XalanUnicode::charColon); if(indexOfNSSep < length(attrName)) { const XalanDOMString prefix = substring(attrName, 0, indexOfNSSep); const XalanDOMString* const ns = getStylesheet().getNamespaceForPrefixFromStack(prefix); if (ns != 0 && equals(*ns, constructionContext.getXSLTNamespaceURI()) == false) { isAttrOK = true; } } else { // An empty namespace is OK. isAttrOK = true; } } // TODO: Well, process it... return isAttrOK; } bool ElemLiteralResult::processPrefixControl( StylesheetConstructionContext& constructionContext, const Stylesheet& stylesheetTree, const XalanDOMString& localName, const XalanDOMChar* attrValue) { if(equals(localName, Constants::ATTRNAME_EXTENSIONELEMENTPREFIXES)) { m_namespacesHandler.processExtensionElementPrefixes(attrValue, stylesheetTree.getNamespaces(), constructionContext); return true; } else if (equals(localName, Constants::ATTRNAME_EXCLUDE_RESULT_PREFIXES)) { m_namespacesHandler.processExcludeResultPrefixes(attrValue, stylesheetTree.getNamespaces(), constructionContext); return true; } else { return false; } } bool ElemLiteralResult::shouldExcludeResultNamespaceNode( const XalanDOMString& thePrefix, const XalanDOMString& theURI) const { return m_namespacesHandler.shouldExcludeResultNamespaceNode( getStylesheet().getXSLTNamespaceURI(), thePrefix, theURI); } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "ElemLiteralResult.hpp" #include <algorithm> #include <sax/AttributeList.hpp> #include <sax/SAXException.hpp> #include <PlatformSupport/DoubleSupport.hpp> #include <PlatformSupport/StringTokenizer.hpp> #include <PlatformSupport/STLHelper.hpp> #include <DOMSupport/DOMServices.hpp> #include "AVT.hpp" #include "Constants.hpp" #include "Stylesheet.hpp" #include "StylesheetConstructionContext.hpp" #include "StylesheetExecutionContext.hpp" ElemLiteralResult::ElemLiteralResult( StylesheetConstructionContext& constructionContext, Stylesheet& stylesheetTree, const XalanDOMString& name, const AttributeList& atts, int lineNumber, int columnNumber, int xslToken) : ElemUse(constructionContext, stylesheetTree, name, lineNumber, columnNumber, xslToken), m_avts(), m_namespacesHandler(stylesheetTree.getNamespacesHandler(), stylesheetTree.getNamespaces(), stylesheetTree.getXSLTNamespaceURI()) { const unsigned int nAttrs = atts.getLength(); m_avts.reserve(nAttrs); for(unsigned int i = 0; i < nAttrs; i++) { const XalanDOMChar* const aname = atts.getName(i); bool needToProcess = true; const unsigned int indexOfNSSep = indexOf(aname, XalanUnicode::charColon); XalanDOMString prefix; if(indexOfNSSep < length(aname)) { prefix = substring(aname, 0, indexOfNSSep); if(!equals(prefix, DOMServices::s_XMLNamespace)) { const XalanDOMString ns = getNamespaceForPrefix(prefix); if(equals(ns, stylesheetTree.getXSLTNamespaceURI())) { const XalanDOMString localName = substring(aname,indexOfNSSep + 1); if(processPrefixControl(constructionContext, stylesheetTree, localName, atts.getValue(i)) == true) { needToProcess = false; } else if (equals(localName, Constants::ATTRNAME_VERSION) == true) { const XalanDOMChar* const value = atts.getValue(i); stylesheetTree.setXSLTVerDeclared(DoubleSupport::toDouble(value)); } } } else { // don't process namespace decls needToProcess = false; } } if(needToProcess == true) { processSpaceAttr(aname, atts, i); // Add xmlns attribute(except xmlns:xsl), xml:space, etc... // Ignore anything with xsl:xxx if(! processUseAttributeSets(constructionContext, aname, atts, i) && isAttrOK(aname, atts, i, constructionContext)) { m_avts.push_back(new AVT(aname, atts.getType(i), atts.getValue(i), *this, constructionContext)); } } } // Shrink the vector of AVTS, if necessary... if (m_avts.capacity() > m_avts.size()) { // Make a copy that's the exact size, and // swap the two... AVTVectorType(m_avts).swap(m_avts); } } ElemLiteralResult::~ElemLiteralResult() { #if !defined(XALAN_NO_NAMESPACES) using std::for_each; #endif // Clean up all entries in the vector. for_each(m_avts.begin(), m_avts.end(), DeleteFunctor<AVT>()); } const NamespacesHandler& ElemLiteralResult::getNamespacesHandler() const { return m_namespacesHandler; } void ElemLiteralResult::postConstruction(const NamespacesHandler& theParentHandler) { const XalanDOMString& theElementName = getElementName(); assert(length(theElementName) > 0); const unsigned int indexOfNSSep = indexOf(theElementName, XalanUnicode::charColon); const XalanDOMString thePrefix = indexOfNSSep < length(theElementName) ? substring(theElementName, 0, indexOfNSSep) : XalanDOMString(); m_namespacesHandler.postConstruction(thePrefix, &theParentHandler); ElemUse::postConstruction(m_namespacesHandler); } void ElemLiteralResult::execute( StylesheetExecutionContext& executionContext, XalanNode* sourceTree, XalanNode* sourceNode, const QName& mode) const { executionContext.startElement(toCharArray(getElementName())); ElemUse::execute(executionContext, sourceTree, sourceNode, mode); if(0 != m_avts.size()) { const AVTVectorType::size_type nAttrs = m_avts.size(); for(AVTVectorType::size_type i = 0; i < nAttrs; i++) { const AVT* const avt = m_avts[i]; XalanDOMString theStringedValue; avt->evaluate(theStringedValue, sourceNode, *this, executionContext); if(isEmpty(theStringedValue) == false) { XalanDOMString thePrefix; const XalanDOMString& theName = avt->getName(); if (startsWith(theName, DOMServices::s_XMLNamespaceWithSeparator) == true) { thePrefix = substring(theName, DOMServices::s_XMLNamespaceWithSeparatorLength); } if (isEmpty(thePrefix) == true || shouldExcludeResultNamespaceNode( thePrefix, theStringedValue) == false) { executionContext.replacePendingAttribute( c_wstr(avt->getName()), c_wstr(avt->getType()), c_wstr(theStringedValue)); } } } } m_namespacesHandler.outputResultNamespaces(executionContext); executeChildren(executionContext, sourceTree, sourceNode, mode); executionContext.endElement(toCharArray(getElementName())); } bool ElemLiteralResult::isAttrOK( int tok, const XalanDOMChar* attrName, const AttributeList& atts, int which) const { return ElemUse::isAttrOK(tok, attrName, atts, which); } bool ElemLiteralResult::isAttrOK( const XalanDOMChar* attrName, const AttributeList& /* atts */, int /* which */, StylesheetConstructionContext& constructionContext) const { bool isAttrOK = equals(attrName, DOMServices::s_XMLNamespace) || startsWith(attrName, DOMServices::s_XMLNamespaceWithSeparator); if(isAttrOK == false) { const unsigned int indexOfNSSep = indexOf(attrName, XalanUnicode::charColon); if(indexOfNSSep < length(attrName)) { const XalanDOMString prefix = substring(attrName, 0, indexOfNSSep); const XalanDOMString ns = getStylesheet().getNamespaceForPrefixFromStack(prefix); if (equals(ns, constructionContext.getXSLTNamespaceURI()) == false) { isAttrOK = true; } } else { // An empty namespace is OK. isAttrOK = true; } } // TODO: Well, process it... return isAttrOK; } bool ElemLiteralResult::processPrefixControl( StylesheetConstructionContext& constructionContext, const Stylesheet& stylesheetTree, const XalanDOMString& localName, const XalanDOMString& attrValue) { if(equals(localName, Constants::ATTRNAME_EXTENSIONELEMENTPREFIXES)) { m_namespacesHandler.processExtensionElementPrefixes(c_wstr(attrValue), stylesheetTree.getNamespaces(), constructionContext); return true; } else if (equals(localName, Constants::ATTRNAME_EXCLUDE_RESULT_PREFIXES)) { m_namespacesHandler.processExcludeResultPrefixes(c_wstr(attrValue), stylesheetTree.getNamespaces(), constructionContext); return true; } else { return false; } } bool ElemLiteralResult::shouldExcludeResultNamespaceNode( const XalanDOMString& thePrefix, const XalanDOMString& theURI) const { return m_namespacesHandler.shouldExcludeResultNamespaceNode( getStylesheet().getXSLTNamespaceURI(), thePrefix, theURI); } <commit_msg>Fixed bug with calling NamespacesHandler::postConstruction(). (lre15)<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "ElemLiteralResult.hpp" #include <algorithm> #include <sax/AttributeList.hpp> #include <sax/SAXException.hpp> #include <PlatformSupport/DoubleSupport.hpp> #include <PlatformSupport/StringTokenizer.hpp> #include <PlatformSupport/STLHelper.hpp> #include <DOMSupport/DOMServices.hpp> #include "AVT.hpp" #include "Constants.hpp" #include "Stylesheet.hpp" #include "StylesheetConstructionContext.hpp" #include "StylesheetExecutionContext.hpp" ElemLiteralResult::ElemLiteralResult( StylesheetConstructionContext& constructionContext, Stylesheet& stylesheetTree, const XalanDOMString& name, const AttributeList& atts, int lineNumber, int columnNumber, int xslToken) : ElemUse(constructionContext, stylesheetTree, name, lineNumber, columnNumber, xslToken), m_avts(), m_namespacesHandler(stylesheetTree.getNamespacesHandler(), stylesheetTree.getNamespaces(), stylesheetTree.getXSLTNamespaceURI()) { const unsigned int nAttrs = atts.getLength(); m_avts.reserve(nAttrs); for(unsigned int i = 0; i < nAttrs; i++) { const XalanDOMChar* const aname = atts.getName(i); bool needToProcess = true; const unsigned int indexOfNSSep = indexOf(aname, XalanUnicode::charColon); XalanDOMString prefix; if(indexOfNSSep < length(aname)) { prefix = substring(aname, 0, indexOfNSSep); if(!equals(prefix, DOMServices::s_XMLNamespace)) { const XalanDOMString ns = getNamespaceForPrefix(prefix); if(equals(ns, stylesheetTree.getXSLTNamespaceURI())) { const XalanDOMString localName = substring(aname,indexOfNSSep + 1); if(processPrefixControl(constructionContext, stylesheetTree, localName, atts.getValue(i)) == true) { needToProcess = false; } else if (equals(localName, Constants::ATTRNAME_VERSION) == true) { const XalanDOMChar* const value = atts.getValue(i); stylesheetTree.setXSLTVerDeclared(DoubleSupport::toDouble(value)); } } } else { // don't process namespace decls needToProcess = false; } } if(needToProcess == true) { processSpaceAttr(aname, atts, i); // Add xmlns attribute(except xmlns:xsl), xml:space, etc... // Ignore anything with xsl:xxx if(! processUseAttributeSets(constructionContext, aname, atts, i) && isAttrOK(aname, atts, i, constructionContext)) { m_avts.push_back(new AVT(aname, atts.getType(i), atts.getValue(i), *this, constructionContext)); } } } // Shrink the vector of AVTS, if necessary... if (m_avts.capacity() > m_avts.size()) { // Make a copy that's the exact size, and // swap the two... AVTVectorType(m_avts).swap(m_avts); } } ElemLiteralResult::~ElemLiteralResult() { #if !defined(XALAN_NO_NAMESPACES) using std::for_each; #endif // Clean up all entries in the vector. for_each(m_avts.begin(), m_avts.end(), DeleteFunctor<AVT>()); } const NamespacesHandler& ElemLiteralResult::getNamespacesHandler() const { return m_namespacesHandler; } void ElemLiteralResult::postConstruction(const NamespacesHandler& theParentHandler) { m_namespacesHandler.postConstruction(getElementName(), &theParentHandler); ElemUse::postConstruction(m_namespacesHandler); } void ElemLiteralResult::execute( StylesheetExecutionContext& executionContext, XalanNode* sourceTree, XalanNode* sourceNode, const QName& mode) const { executionContext.startElement(toCharArray(getElementName())); ElemUse::execute(executionContext, sourceTree, sourceNode, mode); if(0 != m_avts.size()) { const AVTVectorType::size_type nAttrs = m_avts.size(); for(AVTVectorType::size_type i = 0; i < nAttrs; i++) { const AVT* const avt = m_avts[i]; XalanDOMString theStringedValue; avt->evaluate(theStringedValue, sourceNode, *this, executionContext); if(isEmpty(theStringedValue) == false) { XalanDOMString thePrefix; const XalanDOMString& theName = avt->getName(); if (startsWith(theName, DOMServices::s_XMLNamespaceWithSeparator) == true) { thePrefix = substring(theName, DOMServices::s_XMLNamespaceWithSeparatorLength); } if (isEmpty(thePrefix) == true || shouldExcludeResultNamespaceNode( thePrefix, theStringedValue) == false) { executionContext.replacePendingAttribute( c_wstr(avt->getName()), c_wstr(avt->getType()), c_wstr(theStringedValue)); } } } } m_namespacesHandler.outputResultNamespaces(executionContext); executeChildren(executionContext, sourceTree, sourceNode, mode); executionContext.endElement(toCharArray(getElementName())); } bool ElemLiteralResult::isAttrOK( int tok, const XalanDOMChar* attrName, const AttributeList& atts, int which) const { return ElemUse::isAttrOK(tok, attrName, atts, which); } bool ElemLiteralResult::isAttrOK( const XalanDOMChar* attrName, const AttributeList& /* atts */, int /* which */, StylesheetConstructionContext& constructionContext) const { bool isAttrOK = equals(attrName, DOMServices::s_XMLNamespace) || startsWith(attrName, DOMServices::s_XMLNamespaceWithSeparator); if(isAttrOK == false) { const unsigned int indexOfNSSep = indexOf(attrName, XalanUnicode::charColon); if(indexOfNSSep < length(attrName)) { const XalanDOMString prefix = substring(attrName, 0, indexOfNSSep); const XalanDOMString ns = getStylesheet().getNamespaceForPrefixFromStack(prefix); if (equals(ns, constructionContext.getXSLTNamespaceURI()) == false) { isAttrOK = true; } } else { // An empty namespace is OK. isAttrOK = true; } } // TODO: Well, process it... return isAttrOK; } bool ElemLiteralResult::processPrefixControl( StylesheetConstructionContext& constructionContext, const Stylesheet& stylesheetTree, const XalanDOMString& localName, const XalanDOMString& attrValue) { if(equals(localName, Constants::ATTRNAME_EXTENSIONELEMENTPREFIXES)) { m_namespacesHandler.processExtensionElementPrefixes(c_wstr(attrValue), stylesheetTree.getNamespaces(), constructionContext); return true; } else if (equals(localName, Constants::ATTRNAME_EXCLUDE_RESULT_PREFIXES)) { m_namespacesHandler.processExcludeResultPrefixes(c_wstr(attrValue), stylesheetTree.getNamespaces(), constructionContext); return true; } else { return false; } } bool ElemLiteralResult::shouldExcludeResultNamespaceNode( const XalanDOMString& thePrefix, const XalanDOMString& theURI) const { return m_namespacesHandler.shouldExcludeResultNamespaceNode( getStylesheet().getXSLTNamespaceURI(), thePrefix, theURI); } <|endoftext|>
<commit_before>/* * This file is part of telepathy-accounts-kcm * * Copyright (C) 2011 David Edmundson <kde@davidedmundson.co.uk> * Copyright (C) 2012 Daniele E. Domenichelli <daniele.domenichelli@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "accounts-list-delegate.h" #include "edit-display-name-button.h" #include "change-icon-button.h" #include <KTp/presence.h> #include <KTp/Models/accounts-list-model.h> #include <KDE/KLocale> #include <KDE/KIconButton> #include <KDE/KMenu> #include <KDE/KAction> #include <KDE/KDebug> #include <QtGui/QApplication> #include <QtGui/QPainter> #include <QtGui/QCheckBox> #include <QtGui/QAbstractItemView> #include <QtGui/QSortFilterProxyModel> #include <QtGui/QLabel> #include <sys/stat.h> AccountsListDelegate::AccountsListDelegate(QAbstractItemView *itemView, QObject *parent) : KWidgetItemDelegate(itemView, parent) { } QSize AccountsListDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(index); int iconHeight = option.decorationSize.height() + (m_vpadding*2); //icon height + padding either side int textHeight = option.fontMetrics.height()*2 + (m_vpadding*2) + 10; // text height * 2 + padding + some space between the lines return QSize(-1,qMax(iconHeight, textHeight)); //any width,the view should give us the whole thing. } QList<QWidget*> AccountsListDelegate::createItemWidgets() const { // Items created by this method and added to the list returned will be // deleted by KWidgetItemDelegate QCheckBox *checkbox = new QCheckBox(); connect(checkbox, SIGNAL(clicked(bool)), SLOT(onCheckBoxToggled(bool))); ChangeIconButton *changeIconButton = new ChangeIconButton(); changeIconButton->setFlat(true); changeIconButton->setToolTip(i18n("Change account icon")); changeIconButton->setWhatsThis(i18n("This button allows to change the icon for your account.<br />" "This icon is just used locally on your computer, your contacts will not be able to see it.")); QLabel *statusTextLabel = new QLabel(); QLabel *statusIconLabel = new QLabel(); EditDisplayNameButton *displayNameButton = new EditDisplayNameButton(); displayNameButton->setFlat(true); displayNameButton->setToolTip(i18n("Change account display name")); displayNameButton->setWhatsThis(i18n("This button allows to change the display name for your account.<br />" "The display name is an alias for your account and is just used locally " "on your computer, your contacts will not be able to see it.")); QLabel *connectionErrorLabel = new QLabel(); return QList<QWidget*>() << checkbox << changeIconButton << statusTextLabel << statusIconLabel << displayNameButton << connectionErrorLabel; } void AccountsListDelegate::updateItemWidgets(const QList<QWidget *> widgets, const QStyleOptionViewItem &option, const QPersistentModelIndex &index) const { // draws: // AccountName // Checkbox | Icon | | ConnectionIcon | ConnectionState // errorMessage if (!index.isValid()) { return; } Q_ASSERT(widgets.size() == 6); // Get the widgets QCheckBox* checkbox = qobject_cast<QCheckBox*>(widgets.at(0)); ChangeIconButton* changeIconButton = qobject_cast<ChangeIconButton*>(widgets.at(1)); QLabel *statusTextLabel = qobject_cast<QLabel*>(widgets.at(2)); QLabel *statusIconLabel = qobject_cast<QLabel*>(widgets.at(3)); EditDisplayNameButton *displayNameButton = qobject_cast<EditDisplayNameButton*>(widgets.at(4)); QLabel *connectionErrorLabel = qobject_cast<QLabel*>(widgets.at(5)); Q_ASSERT(checkbox); Q_ASSERT(changeIconButton); Q_ASSERT(statusTextLabel); Q_ASSERT(statusIconLabel); Q_ASSERT(displayNameButton); Q_ASSERT(connectionErrorLabel); bool isSelected(itemView()->selectionModel()->isSelected(index) && itemView()->hasFocus()); bool isEnabled(index.data(Qt::CheckStateRole).toBool()); KIcon accountIcon(index.data(Qt::DecorationRole).value<QIcon>()); KIcon statusIcon(index.data(AccountsListModel::ConnectionStateIconRole).value<QIcon>()); QString statusText(index.data(AccountsListModel::ConnectionStateDisplayRole).toString()); QString displayName(index.data(Qt::DisplayRole).toString()); QString connectionError(index.data(AccountsListModel::ConnectionErrorMessageDisplayRole).toString()); Tp::AccountPtr account(index.data(AccountsListModel::AccountRole).value<Tp::AccountPtr>()); QRect outerRect(0, 0, option.rect.width(), option.rect.height()); QRect contentRect = outerRect.adjusted(m_hpadding,m_vpadding,-m_hpadding,-m_vpadding); //add some padding // checkbox if (isEnabled) { checkbox->setChecked(true);; checkbox->setToolTip(i18n("Disable account")); } else { checkbox->setChecked(false); checkbox->setToolTip(i18n("Enable account")); } int checkboxLeftMargin = contentRect.left(); int checkboxTopMargin = (outerRect.height() - checkbox->height()) / 2; checkbox->move(checkboxLeftMargin, checkboxTopMargin); // changeIconButton changeIconButton->setIcon(accountIcon); changeIconButton->setAccount(account); // At the moment (KDE 4.8.1) decorationSize is not passed from KWidgetItemDelegate // through the QStyleOptionViewItem, therefore we leave default size unless // the user has a more recent version. if (option.decorationSize.width() > -1) { changeIconButton->setButtonIconSize(option.decorationSize.width()); } int changeIconButtonLeftMargin = checkboxLeftMargin + checkbox->width(); int changeIconButtonTopMargin = (outerRect.height() - changeIconButton->height()) / 2; changeIconButton->move(changeIconButtonLeftMargin, changeIconButtonTopMargin); // statusTextLabel QFont statusTextFont = option.font; QPalette statusTextLabelPalette = option.palette; if (isEnabled) { statusTextLabel->setEnabled(true); statusTextFont.setItalic(false); } else { statusTextLabel->setDisabled(true); statusTextFont.setItalic(true); } if (isSelected) { statusTextLabelPalette.setColor(QPalette::Text, statusTextLabelPalette.color(QPalette::Active, QPalette::HighlightedText)); } statusTextLabel->setPalette(statusTextLabelPalette); statusTextLabel->setFont(statusTextFont); statusTextLabel->setText(statusText); statusTextLabel->setFixedSize(statusTextLabel->fontMetrics().boundingRect(statusText).width(), statusTextLabel->height()); int statusTextLabelLeftMargin = contentRect.right() - statusTextLabel->width(); int statusTextLabelTopMargin = (outerRect.height() - statusTextLabel->height()) / 2; statusTextLabel->move(statusTextLabelLeftMargin, statusTextLabelTopMargin); // statusIconLabel statusIconLabel->setPixmap(statusIcon.pixmap(KIconLoader::SizeSmall)); statusIconLabel->setFixedSize(statusIconLabel->minimumSizeHint()); int statusIconLabelLeftMargin = contentRect.right() - statusTextLabel->width() - statusIconLabel->width() - 6; int statusIconLabelTopMargin = (outerRect.height() - statusIconLabel->height()) / 2; statusIconLabel->move(statusIconLabelLeftMargin, statusIconLabelTopMargin); QRect innerRect = contentRect.adjusted(changeIconButton->geometry().right() - contentRect.left(), 0, -statusTextLabel->width() - statusIconLabel->width() - 6, 0); // rect containing account name and error message // displayNameButton QFont displayNameButtonFont = option.font; QPalette displayNameButtonPalette = option.palette; if (isEnabled) { displayNameButtonPalette.setColor(QPalette::WindowText, displayNameButtonPalette.color(QPalette::Active, QPalette::Text)); displayNameButtonFont.setBold(true); } else { displayNameButtonFont.setItalic(true); // NOTE: Flat QPushButton use WindowText instead of ButtonText for button text color displayNameButtonPalette.setColor(QPalette::WindowText, displayNameButtonPalette.color(QPalette::Disabled, QPalette::Text)); } if (isSelected) { // Account is selected displayNameButtonPalette.setColor(QPalette::WindowText, displayNameButtonPalette.color(QPalette::Active, QPalette::HighlightedText)); } displayNameButton->setFont(displayNameButtonFont); displayNameButton->setPalette(displayNameButtonPalette); QString displayNameButtonText = displayNameButton->fontMetrics().elidedText(displayName, Qt::ElideRight, innerRect.width() - (m_hpadding*2)); displayNameButton->setText(displayNameButtonText); displayNameButton->setFixedSize(displayNameButton->fontMetrics().boundingRect(displayNameButtonText).width() + (m_hpadding*2), displayNameButton->minimumSizeHint().height()); displayNameButton->setAccount(account); int displayNameButtonLeftMargin = innerRect.left(); int displayNameButtonTopMargin = innerRect.top(); displayNameButton->move(displayNameButtonLeftMargin, displayNameButtonTopMargin); // connectionErrorLabel QFont connectionErrorLabelFont = option.font; QPalette connectionErrorLabelPalette = option.palette; if (isEnabled) { connectionErrorLabelPalette.setColor(QPalette::WindowText, connectionErrorLabelPalette.color(QPalette::Active, QPalette::Text)); } else { connectionErrorLabelFont.setItalic(true); connectionErrorLabelPalette.setColor(QPalette::Text, connectionErrorLabelPalette.color(QPalette::Disabled, QPalette::Text)); } if (isSelected) { // Account is selected connectionErrorLabelPalette.setColor(QPalette::Text, connectionErrorLabelPalette.color(QPalette::Active, QPalette::HighlightedText)); } connectionErrorLabel->setFont(connectionErrorLabelFont); connectionErrorLabel->setPalette(connectionErrorLabelPalette); QString connectionErrorLabelText = connectionErrorLabel->fontMetrics().elidedText(connectionError, Qt::ElideRight, innerRect.width() - (m_hpadding*2)); connectionErrorLabel->setText(connectionErrorLabelText); connectionErrorLabel->setFixedSize(connectionErrorLabel->fontMetrics().boundingRect(connectionErrorLabelText).width(), displayNameButton->height()); int connectionErrorLabelLeftMargin = innerRect.left() + m_hpadding; int connectionErrorLabelTopMargin = contentRect.bottom() - displayNameButton->height(); connectionErrorLabel->move(connectionErrorLabelLeftMargin, connectionErrorLabelTopMargin); } void AccountsListDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (!index.isValid()) { return; } QApplication::style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter, 0); } void AccountsListDelegate::onCheckBoxToggled(bool checked) { QModelIndex index = focusedIndex(); Q_EMIT itemChecked(index, checked); } <commit_msg>Add message "click checkbox to enable" if the account is disabled<commit_after>/* * This file is part of telepathy-accounts-kcm * * Copyright (C) 2011 David Edmundson <kde@davidedmundson.co.uk> * Copyright (C) 2012 Daniele E. Domenichelli <daniele.domenichelli@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "accounts-list-delegate.h" #include "edit-display-name-button.h" #include "change-icon-button.h" #include <KTp/presence.h> #include <KTp/Models/accounts-list-model.h> #include <KDE/KLocale> #include <KDE/KIconButton> #include <KDE/KMenu> #include <KDE/KAction> #include <KDE/KDebug> #include <QtGui/QApplication> #include <QtGui/QPainter> #include <QtGui/QCheckBox> #include <QtGui/QAbstractItemView> #include <QtGui/QSortFilterProxyModel> #include <QtGui/QLabel> #include <sys/stat.h> AccountsListDelegate::AccountsListDelegate(QAbstractItemView *itemView, QObject *parent) : KWidgetItemDelegate(itemView, parent) { } QSize AccountsListDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(index); int iconHeight = option.decorationSize.height() + (m_vpadding*2); //icon height + padding either side int textHeight = option.fontMetrics.height()*2 + (m_vpadding*2) + 10; // text height * 2 + padding + some space between the lines return QSize(-1,qMax(iconHeight, textHeight)); //any width,the view should give us the whole thing. } QList<QWidget*> AccountsListDelegate::createItemWidgets() const { // Items created by this method and added to the list returned will be // deleted by KWidgetItemDelegate QCheckBox *checkbox = new QCheckBox(); connect(checkbox, SIGNAL(clicked(bool)), SLOT(onCheckBoxToggled(bool))); ChangeIconButton *changeIconButton = new ChangeIconButton(); changeIconButton->setFlat(true); changeIconButton->setToolTip(i18n("Change account icon")); changeIconButton->setWhatsThis(i18n("This button allows to change the icon for your account.<br />" "This icon is just used locally on your computer, your contacts will not be able to see it.")); QLabel *statusTextLabel = new QLabel(); QLabel *statusIconLabel = new QLabel(); EditDisplayNameButton *displayNameButton = new EditDisplayNameButton(); displayNameButton->setFlat(true); displayNameButton->setToolTip(i18n("Change account display name")); displayNameButton->setWhatsThis(i18n("This button allows to change the display name for your account.<br />" "The display name is an alias for your account and is just used locally " "on your computer, your contacts will not be able to see it.")); QLabel *connectionErrorLabel = new QLabel(); return QList<QWidget*>() << checkbox << changeIconButton << statusTextLabel << statusIconLabel << displayNameButton << connectionErrorLabel; } void AccountsListDelegate::updateItemWidgets(const QList<QWidget *> widgets, const QStyleOptionViewItem &option, const QPersistentModelIndex &index) const { // draws: // AccountName // Checkbox | Icon | | ConnectionIcon | ConnectionState // errorMessage if (!index.isValid()) { return; } Q_ASSERT(widgets.size() == 6); // Get the widgets QCheckBox* checkbox = qobject_cast<QCheckBox*>(widgets.at(0)); ChangeIconButton* changeIconButton = qobject_cast<ChangeIconButton*>(widgets.at(1)); QLabel *statusTextLabel = qobject_cast<QLabel*>(widgets.at(2)); QLabel *statusIconLabel = qobject_cast<QLabel*>(widgets.at(3)); EditDisplayNameButton *displayNameButton = qobject_cast<EditDisplayNameButton*>(widgets.at(4)); QLabel *connectionErrorLabel = qobject_cast<QLabel*>(widgets.at(5)); Q_ASSERT(checkbox); Q_ASSERT(changeIconButton); Q_ASSERT(statusTextLabel); Q_ASSERT(statusIconLabel); Q_ASSERT(displayNameButton); Q_ASSERT(connectionErrorLabel); bool isSelected(itemView()->selectionModel()->isSelected(index) && itemView()->hasFocus()); bool isEnabled(index.data(Qt::CheckStateRole).toBool()); KIcon accountIcon(index.data(Qt::DecorationRole).value<QIcon>()); KIcon statusIcon(index.data(AccountsListModel::ConnectionStateIconRole).value<QIcon>()); QString statusText(index.data(AccountsListModel::ConnectionStateDisplayRole).toString()); QString displayName(index.data(Qt::DisplayRole).toString()); QString connectionError(index.data(AccountsListModel::ConnectionErrorMessageDisplayRole).toString()); Tp::AccountPtr account(index.data(AccountsListModel::AccountRole).value<Tp::AccountPtr>()); if (!account->isEnabled()) { connectionError = i18n("Click checkbox to enable"); } QRect outerRect(0, 0, option.rect.width(), option.rect.height()); QRect contentRect = outerRect.adjusted(m_hpadding,m_vpadding,-m_hpadding,-m_vpadding); //add some padding // checkbox if (isEnabled) { checkbox->setChecked(true);; checkbox->setToolTip(i18n("Disable account")); } else { checkbox->setChecked(false); checkbox->setToolTip(i18n("Enable account")); } int checkboxLeftMargin = contentRect.left(); int checkboxTopMargin = (outerRect.height() - checkbox->height()) / 2; checkbox->move(checkboxLeftMargin, checkboxTopMargin); // changeIconButton changeIconButton->setIcon(accountIcon); changeIconButton->setAccount(account); // At the moment (KDE 4.8.1) decorationSize is not passed from KWidgetItemDelegate // through the QStyleOptionViewItem, therefore we leave default size unless // the user has a more recent version. if (option.decorationSize.width() > -1) { changeIconButton->setButtonIconSize(option.decorationSize.width()); } int changeIconButtonLeftMargin = checkboxLeftMargin + checkbox->width(); int changeIconButtonTopMargin = (outerRect.height() - changeIconButton->height()) / 2; changeIconButton->move(changeIconButtonLeftMargin, changeIconButtonTopMargin); // statusTextLabel QFont statusTextFont = option.font; QPalette statusTextLabelPalette = option.palette; if (isEnabled) { statusTextLabel->setEnabled(true); statusTextFont.setItalic(false); } else { statusTextLabel->setDisabled(true); statusTextFont.setItalic(true); } if (isSelected) { statusTextLabelPalette.setColor(QPalette::Text, statusTextLabelPalette.color(QPalette::Active, QPalette::HighlightedText)); } statusTextLabel->setPalette(statusTextLabelPalette); statusTextLabel->setFont(statusTextFont); statusTextLabel->setText(statusText); statusTextLabel->setFixedSize(statusTextLabel->fontMetrics().boundingRect(statusText).width(), statusTextLabel->height()); int statusTextLabelLeftMargin = contentRect.right() - statusTextLabel->width(); int statusTextLabelTopMargin = (outerRect.height() - statusTextLabel->height()) / 2; statusTextLabel->move(statusTextLabelLeftMargin, statusTextLabelTopMargin); // statusIconLabel statusIconLabel->setPixmap(statusIcon.pixmap(KIconLoader::SizeSmall)); statusIconLabel->setFixedSize(statusIconLabel->minimumSizeHint()); int statusIconLabelLeftMargin = contentRect.right() - statusTextLabel->width() - statusIconLabel->width() - 6; int statusIconLabelTopMargin = (outerRect.height() - statusIconLabel->height()) / 2; statusIconLabel->move(statusIconLabelLeftMargin, statusIconLabelTopMargin); QRect innerRect = contentRect.adjusted(changeIconButton->geometry().right() - contentRect.left(), 0, -statusTextLabel->width() - statusIconLabel->width() - 6, 0); // rect containing account name and error message // displayNameButton QFont displayNameButtonFont = option.font; QPalette displayNameButtonPalette = option.palette; if (isEnabled) { displayNameButtonPalette.setColor(QPalette::WindowText, displayNameButtonPalette.color(QPalette::Active, QPalette::Text)); displayNameButtonFont.setBold(true); } else { displayNameButtonFont.setItalic(true); // NOTE: Flat QPushButton use WindowText instead of ButtonText for button text color displayNameButtonPalette.setColor(QPalette::WindowText, displayNameButtonPalette.color(QPalette::Disabled, QPalette::Text)); } if (isSelected) { // Account is selected displayNameButtonPalette.setColor(QPalette::WindowText, displayNameButtonPalette.color(QPalette::Active, QPalette::HighlightedText)); } displayNameButton->setFont(displayNameButtonFont); displayNameButton->setPalette(displayNameButtonPalette); QString displayNameButtonText = displayNameButton->fontMetrics().elidedText(displayName, Qt::ElideRight, innerRect.width() - (m_hpadding*2)); displayNameButton->setText(displayNameButtonText); displayNameButton->setFixedSize(displayNameButton->fontMetrics().boundingRect(displayNameButtonText).width() + (m_hpadding*2), displayNameButton->minimumSizeHint().height()); displayNameButton->setAccount(account); int displayNameButtonLeftMargin = innerRect.left(); int displayNameButtonTopMargin = innerRect.top(); displayNameButton->move(displayNameButtonLeftMargin, displayNameButtonTopMargin); // connectionErrorLabel QFont connectionErrorLabelFont = option.font; QPalette connectionErrorLabelPalette = option.palette; if (isEnabled) { connectionErrorLabelPalette.setColor(QPalette::WindowText, connectionErrorLabelPalette.color(QPalette::Active, QPalette::Text)); } else { connectionErrorLabelFont.setItalic(true); connectionErrorLabelPalette.setColor(QPalette::Text, connectionErrorLabelPalette.color(QPalette::Disabled, QPalette::Text)); } if (isSelected) { // Account is selected connectionErrorLabelPalette.setColor(QPalette::Text, connectionErrorLabelPalette.color(QPalette::Active, QPalette::HighlightedText)); } connectionErrorLabel->setFont(connectionErrorLabelFont); connectionErrorLabel->setPalette(connectionErrorLabelPalette); QString connectionErrorLabelText = connectionErrorLabel->fontMetrics().elidedText(connectionError, Qt::ElideRight, innerRect.width() - (m_hpadding*2)); connectionErrorLabel->setText(connectionErrorLabelText); connectionErrorLabel->setFixedSize(connectionErrorLabel->fontMetrics().boundingRect(connectionErrorLabelText).width(), displayNameButton->height()); int connectionErrorLabelLeftMargin = innerRect.left() + m_hpadding; int connectionErrorLabelTopMargin = contentRect.bottom() - displayNameButton->height(); connectionErrorLabel->move(connectionErrorLabelLeftMargin, connectionErrorLabelTopMargin); } void AccountsListDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (!index.isValid()) { return; } QApplication::style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter, 0); } void AccountsListDelegate::onCheckBoxToggled(bool checked) { QModelIndex index = focusedIndex(); Q_EMIT itemChecked(index, checked); } <|endoftext|>
<commit_before>#include "yebash.hpp" #include "History.hpp" #include "catch.hpp" #include <iostream> #include <algorithm> #include <sstream> using namespace yb; using namespace std; namespace { void tearDown() { std::stringstream output, ss; Printer printer(output); History history; history.read(ss); HistorySuggestion suggestion(history); yebash(suggestion, printer, '\n'); } } // anon namespace TEST_CASE( "No suggestions when history is empty", "[basic.empty_history]" ) { auto testCharacter = [] (char const c) { std::stringstream ss; std::stringstream output; History history; history.read(ss); HistorySuggestion suggestion(history); Printer printer(output); auto result = yebash(suggestion, printer, c); REQUIRE(result == c); REQUIRE(output.str() == ""); }; string domain = "abcdefghijklmnopqrstuvwxyz01234567890-_"; for_each(begin(domain), end(domain), testCharacter); tearDown(); } TEST_CASE( "Order of commands from history is preserved", "[basic.history_order_preserved]" ) { std::stringstream ss; ss << "abc1" << std::endl; ss << "abc2" << std::endl; std::stringstream output; History history; history.read(ss); HistorySuggestion suggestion(history); Printer printer(output); auto character = 'a'; auto result = yebash(suggestion, printer, character); REQUIRE(result == character); REQUIRE(output.str() == "bc2"); tearDown(); } <commit_msg>refactored code to avoid code duplication<commit_after>#include "yebash.hpp" #include "History.hpp" #include "catch.hpp" #include <initializer_list> #include <iostream> #include <algorithm> #include <sstream> using namespace yb; using namespace std; namespace { History createHistory(initializer_list<string> const& commands) { stringstream ss; for (auto && command: commands) { ss << command << std::endl; } History history; history.read(ss); return history; } void tearDown() { std::stringstream output, ss; Printer printer(output); History history; history.read(ss); HistorySuggestion suggestion(history); yebash(suggestion, printer, '\n'); } } // anon namespace TEST_CASE( "No suggestions when history is empty", "[basic.empty_history]" ) { auto testCharacter = [] (char const c) { History history = createHistory({}); HistorySuggestion suggestion(history); std::stringstream output; Printer printer(output); auto result = yebash(suggestion, printer, c); REQUIRE(result == c); REQUIRE(output.str() == ""); }; string domain = "abcdefghijklmnopqrstuvwxyz01234567890-_"; for_each(begin(domain), end(domain), testCharacter); tearDown(); } TEST_CASE( "Order of commands from history is preserved", "[basic.history_order_preserved]" ) { History history = createHistory({"abc1", "abc2"}); HistorySuggestion suggestion(history); std::stringstream output; Printer printer(output); auto character = 'a'; auto result = yebash(suggestion, printer, character); REQUIRE(result == character); REQUIRE(output.str() == "bc2"); tearDown(); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "window.h" Window::Window(QWidget *parent) : QWidget(parent), m_iconSize(64, 64) { m_ui.setupUi(this); QButtonGroup *buttonGroup = qFindChild<QButtonGroup *>(this); // ### workaround for uic in 4.4 m_ui.easingCurvePicker->setIconSize(m_iconSize); m_ui.easingCurvePicker->setMinimumHeight(m_iconSize.height() + 50); buttonGroup->setId(m_ui.lineRadio, 0); buttonGroup->setId(m_ui.circleRadio, 1); QEasingCurve dummy; m_ui.periodSpinBox->setValue(dummy.period()); m_ui.amplitudeSpinBox->setValue(dummy.amplitude()); m_ui.overshootSpinBox->setValue(dummy.overshoot()); connect(m_ui.easingCurvePicker, SIGNAL(currentRowChanged(int)), this, SLOT(curveChanged(int))); connect(buttonGroup, SIGNAL(buttonClicked(int)), this, SLOT(pathChanged(int))); connect(m_ui.periodSpinBox, SIGNAL(valueChanged(double)), this, SLOT(periodChanged(double))); connect(m_ui.amplitudeSpinBox, SIGNAL(valueChanged(double)), this, SLOT(amplitudeChanged(double))); connect(m_ui.overshootSpinBox, SIGNAL(valueChanged(double)), this, SLOT(overshootChanged(double))); createCurveIcons(); QPixmap pix(QLatin1String(":/images/qt-logo.png")); m_item = new PixmapItem(pix); m_scene.addItem(m_item); m_ui.graphicsView->setScene(&m_scene); m_anim = new Animation(m_item, "pos"); m_anim->setEasingCurve(QEasingCurve::OutBounce); m_ui.easingCurvePicker->setCurrentRow(int(QEasingCurve::OutBounce)); startAnimation(); } void Window::createCurveIcons() { QPixmap pix(m_iconSize); QPainter painter(&pix); QLinearGradient gradient(0,0, 0, m_iconSize.height()); gradient.setColorAt(0.0, QColor(240, 240, 240)); gradient.setColorAt(1.0, QColor(224, 224, 224)); QBrush brush(gradient); const QMetaObject &mo = QEasingCurve::staticMetaObject; QMetaEnum metaEnum = mo.enumerator(mo.indexOfEnumerator("Type")); // Skip QEasingCurve::Custom for (int i = 0; i < QEasingCurve::NCurveTypes - 1; ++i) { painter.fillRect(QRect(QPoint(0, 0), m_iconSize), brush); QEasingCurve curve((QEasingCurve::Type)i); painter.setPen(QColor(0, 0, 255, 64)); qreal xAxis = m_iconSize.height()/1.5; qreal yAxis = m_iconSize.width()/3; painter.drawLine(0, xAxis, m_iconSize.width(), xAxis); painter.drawLine(yAxis, 0, yAxis, m_iconSize.height()); painter.setPen(Qt::black); qreal curveScale = m_iconSize.height()/2; QPoint currentPos(yAxis, xAxis); for (qreal t = 0; t < 1.0; t+=1.0/curveScale) { QPoint to; to.setX(yAxis + curveScale * t); to.setY(xAxis - curveScale * curve.valueForProgress(t)); painter.drawLine(currentPos, to); currentPos = to; } QListWidgetItem *item = new QListWidgetItem; item->setIcon(QIcon(pix)); item->setText(metaEnum.key(i)); m_ui.easingCurvePicker->addItem(item); } } void Window::startAnimation() { m_anim->setStartValue(QPointF(0, 0)); m_anim->setEndValue(QPointF(100, 100)); m_anim->setDuration(2000); m_anim->setLoopCount(-1); // forever m_anim->start(); } void Window::curveChanged(int row) { QEasingCurve::Type curveType = (QEasingCurve::Type)row; m_anim->setEasingCurve(curveType); m_anim->setCurrentTime(0); bool isElastic = curveType >= QEasingCurve::InElastic && curveType <= QEasingCurve::OutInElastic; bool isBounce = curveType >= QEasingCurve::InBounce && curveType <= QEasingCurve::OutInBounce; m_ui.periodSpinBox->setEnabled(isElastic); m_ui.amplitudeSpinBox->setEnabled(isElastic || isBounce); m_ui.overshootSpinBox->setEnabled(curveType >= QEasingCurve::InBack && curveType <= QEasingCurve::OutInBack); } void Window::pathChanged(int index) { m_anim->setPathType((Animation::PathType)index); } void Window::periodChanged(double value) { QEasingCurve curve = m_anim->easingCurve(); curve.setPeriod(value); m_anim->setEasingCurve(curve); } void Window::amplitudeChanged(double value) { QEasingCurve curve = m_anim->easingCurve(); curve.setAmplitude(value); m_anim->setEasingCurve(curve); } void Window::overshootChanged(double value) { QEasingCurve curve = m_anim->easingCurve(); curve.setOvershoot(value); m_anim->setEasingCurve(curve); } <commit_msg>Make the easing curve icons more beautiful.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "window.h" Window::Window(QWidget *parent) : QWidget(parent), m_iconSize(64, 64) { m_ui.setupUi(this); QButtonGroup *buttonGroup = qFindChild<QButtonGroup *>(this); // ### workaround for uic in 4.4 m_ui.easingCurvePicker->setIconSize(m_iconSize); m_ui.easingCurvePicker->setMinimumHeight(m_iconSize.height() + 50); buttonGroup->setId(m_ui.lineRadio, 0); buttonGroup->setId(m_ui.circleRadio, 1); QEasingCurve dummy; m_ui.periodSpinBox->setValue(dummy.period()); m_ui.amplitudeSpinBox->setValue(dummy.amplitude()); m_ui.overshootSpinBox->setValue(dummy.overshoot()); connect(m_ui.easingCurvePicker, SIGNAL(currentRowChanged(int)), this, SLOT(curveChanged(int))); connect(buttonGroup, SIGNAL(buttonClicked(int)), this, SLOT(pathChanged(int))); connect(m_ui.periodSpinBox, SIGNAL(valueChanged(double)), this, SLOT(periodChanged(double))); connect(m_ui.amplitudeSpinBox, SIGNAL(valueChanged(double)), this, SLOT(amplitudeChanged(double))); connect(m_ui.overshootSpinBox, SIGNAL(valueChanged(double)), this, SLOT(overshootChanged(double))); createCurveIcons(); QPixmap pix(QLatin1String(":/images/qt-logo.png")); m_item = new PixmapItem(pix); m_scene.addItem(m_item); m_ui.graphicsView->setScene(&m_scene); m_anim = new Animation(m_item, "pos"); m_anim->setEasingCurve(QEasingCurve::OutBounce); m_ui.easingCurvePicker->setCurrentRow(int(QEasingCurve::OutBounce)); startAnimation(); } void Window::createCurveIcons() { QPixmap pix(m_iconSize); QPainter painter(&pix); QLinearGradient gradient(0,0, 0, m_iconSize.height()); gradient.setColorAt(0.0, QColor(240, 240, 240)); gradient.setColorAt(1.0, QColor(224, 224, 224)); QBrush brush(gradient); const QMetaObject &mo = QEasingCurve::staticMetaObject; QMetaEnum metaEnum = mo.enumerator(mo.indexOfEnumerator("Type")); // Skip QEasingCurve::Custom for (int i = 0; i < QEasingCurve::NCurveTypes - 1; ++i) { painter.fillRect(QRect(QPoint(0, 0), m_iconSize), brush); QEasingCurve curve((QEasingCurve::Type)i); painter.setPen(QColor(0, 0, 255, 64)); qreal xAxis = m_iconSize.height()/1.5; qreal yAxis = m_iconSize.width()/3; painter.drawLine(0, xAxis, m_iconSize.width(), xAxis); painter.drawLine(yAxis, 0, yAxis, m_iconSize.height()); qreal curveScale = m_iconSize.height()/2; painter.setPen(Qt::NoPen); // start point painter.setBrush(Qt::red); QPoint start(yAxis, xAxis - curveScale * curve.valueForProgress(0)); painter.drawRect(start.x() - 1, start.y() - 1, 3, 3); // end point painter.setBrush(Qt::blue); QPoint end(yAxis + curveScale, xAxis - curveScale * curve.valueForProgress(1)); painter.drawRect(end.x() - 1, end.y() - 1, 3, 3); painter.setPen(QColor(32, 32, 32)); painter.setRenderHint(QPainter::Antialiasing, true); QPoint currentPos(start); for (qreal t = 0; t < 1.0; t+=1.0/curveScale) { QPoint to; to.setX(yAxis + curveScale * t); to.setY(xAxis - curveScale * curve.valueForProgress(t)); painter.drawLine(currentPos, to); currentPos = to; } painter.setRenderHint(QPainter::Antialiasing, false); QListWidgetItem *item = new QListWidgetItem; item->setIcon(QIcon(pix)); item->setText(metaEnum.key(i)); m_ui.easingCurvePicker->addItem(item); } } void Window::startAnimation() { m_anim->setStartValue(QPointF(0, 0)); m_anim->setEndValue(QPointF(100, 100)); m_anim->setDuration(2000); m_anim->setLoopCount(-1); // forever m_anim->start(); } void Window::curveChanged(int row) { QEasingCurve::Type curveType = (QEasingCurve::Type)row; m_anim->setEasingCurve(curveType); m_anim->setCurrentTime(0); bool isElastic = curveType >= QEasingCurve::InElastic && curveType <= QEasingCurve::OutInElastic; bool isBounce = curveType >= QEasingCurve::InBounce && curveType <= QEasingCurve::OutInBounce; m_ui.periodSpinBox->setEnabled(isElastic); m_ui.amplitudeSpinBox->setEnabled(isElastic || isBounce); m_ui.overshootSpinBox->setEnabled(curveType >= QEasingCurve::InBack && curveType <= QEasingCurve::OutInBack); } void Window::pathChanged(int index) { m_anim->setPathType((Animation::PathType)index); } void Window::periodChanged(double value) { QEasingCurve curve = m_anim->easingCurve(); curve.setPeriod(value); m_anim->setEasingCurve(curve); } void Window::amplitudeChanged(double value) { QEasingCurve curve = m_anim->easingCurve(); curve.setAmplitude(value); m_anim->setEasingCurve(curve); } void Window::overshootChanged(double value) { QEasingCurve curve = m_anim->easingCurve(); curve.setOvershoot(value); m_anim->setEasingCurve(curve); } <|endoftext|>
<commit_before>#ifndef SDD_CG_HPP #define SDD_CG_HPP #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <cmath> #include <boost/range/algorithm.hpp> #include <amgcl/amgcl.hpp> #include <amgcl/backend/builtin.hpp> #include <amgcl/backend/crs_tuple.hpp> #include <amgcl/coarsening/plain_aggregates.hpp> #include <amgcl/coarsening/smoothed_aggregation.hpp> #include <amgcl/relaxation/spai0.hpp> #include <amgcl/solver/bicgstabl.hpp> #include <amgcl/mpi/deflation.hpp> #include <amgcl/profiler.hpp> #include "domain_partition.hpp" struct linear_deflation { long n; double h; std::vector<long> idx; linear_deflation(long n) : n(n), h(1.0 / (n - 1)), idx(n * n) {} size_t dim() const { return 3; } double operator()(long i, int j) const { switch(j) { case 1: return h * (idx[i] % n); case 2: return h * (idx[i] / n); case 0: default: return 1; } } }; int main(int argc, char *argv[]) { boost::mpi::environment env; boost::mpi::communicator world; const long n = argc > 1 ? atoi(argv[1]) : 1024; const long n2 = n * n; boost::array<long, 2> lo = { {0, 0} }; boost::array<long, 2> hi = { {n - 1, n - 1} }; amgcl::profiler<> prof; prof.tic("partition"); domain_partition<2> part(lo, hi, world.size()); const long chunk = part.size( world.rank() ); std::vector<long> domain(world.size() + 1); all_gather(world, chunk, &domain[1]); boost::partial_sum(domain, domain.begin()); const long chunk_start = domain[world.rank()]; const long chunk_end = domain[world.rank() + 1]; linear_deflation lindef(n); std::vector<long> renum(n2); for(long j = 0, idx = 0; j < n; ++j) { for(long i = 0; i < n; ++i, ++idx) { boost::array<long, 2> p = {{i, j}}; std::pair<int,long> v = part.index(p); renum[idx] = domain[v.first] + v.second; lindef.idx[renum[idx]] = idx; } } prof.toc("partition"); prof.tic("assemble"); std::vector<long> ptr; std::vector<long> col; std::vector<double> val; std::vector<double> rhs; ptr.reserve(chunk + 1); col.reserve(chunk * 5); val.reserve(chunk * 5); rhs.reserve(chunk); ptr.push_back(0); const double h2i = (n - 1) * (n - 1); for(long j = 0, idx = 0; j < n; ++j) { for(long i = 0; i < n; ++i, ++idx) { if (renum[idx] < chunk_start || renum[idx] >= chunk_end) continue; if (i == 0 || j == 0 || i + 1 == n || j + 1 == n) { col.push_back(renum[idx]); val.push_back(1); rhs.push_back(0); } else { if (j > 0) { col.push_back(renum[idx - n]); val.push_back(-h2i); } if (i > 0) { col.push_back(renum[idx - 1]); val.push_back(-h2i); } col.push_back(renum[idx]); val.push_back(4 * h2i); if (i + 1 < n) { col.push_back(renum[idx + 1]); val.push_back(-h2i); } if (j + 1 < n) { col.push_back(renum[idx + n]); val.push_back(-h2i); } rhs.push_back(1); } ptr.push_back( col.size() ); } } prof.toc("assemble"); prof.tic("setup"); typedef amgcl::mpi::subdomain_deflation< amgcl::backend::builtin<double>, amgcl::coarsening::smoothed_aggregation< amgcl::coarsening::plain_aggregates >, amgcl::relaxation::spai0, amgcl::solver::bicgstabl > Solver; typename Solver::AMG_params amg_prm; typename Solver::Solver_params slv_prm(2, 500, 1e-6); Solver solve(world, boost::tie(chunk, ptr, col, val), lindef, amg_prm, slv_prm ); prof.toc("setup"); prof.tic("solve"); std::vector<double> x(chunk, 0); size_t iters; double resid; boost::tie(iters, resid) = solve(rhs, x); prof.toc("solve"); prof.tic("save"); if (world.rank() == 0) { std::vector<double> X(n2); boost::copy(x, X.begin()); for(int i = 1; i < world.size(); ++i) world.recv(i, 42, &X[domain[i]], domain[i+1] - domain[i]); std::ofstream f("out.dat", std::ios::binary); int m = n2; f.write((char*)&m, sizeof(int)); for(long i = 0; i < n2; ++i) f.write((char*)&X[renum[i]], sizeof(double)); } else { world.send(0, 42, x.data(), chunk); } prof.toc("save"); if (world.rank() == 0) { std::cout << "Iterations: " << iters << std::endl << "Error: " << resid << std::endl << std::endl << prof << std::endl; } } #endif <commit_msg>Truly unsymmetric matrix in examples/mpi/subdomain_deflation.cpp<commit_after>#ifndef SDD_CG_HPP #define SDD_CG_HPP #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <cmath> #include <boost/range/algorithm.hpp> #include <amgcl/amgcl.hpp> #include <amgcl/backend/builtin.hpp> #include <amgcl/backend/crs_tuple.hpp> #include <amgcl/coarsening/plain_aggregates.hpp> #include <amgcl/coarsening/smoothed_aggregation.hpp> #include <amgcl/relaxation/spai0.hpp> #include <amgcl/solver/bicgstabl.hpp> #include <amgcl/mpi/deflation.hpp> #include <amgcl/profiler.hpp> #include "domain_partition.hpp" #define CONVECTION struct linear_deflation { long n; double h; std::vector<long> idx; linear_deflation(long n) : n(n), h(1.0 / (n - 1)), idx(n * n) {} size_t dim() const { return 3; } double operator()(long i, int j) const { switch(j) { case 1: return h * (idx[i] % n); case 2: return h * (idx[i] / n); case 0: default: return 1; } } }; int main(int argc, char *argv[]) { boost::mpi::environment env; boost::mpi::communicator world; const long n = argc > 1 ? atoi(argv[1]) : 1024; const long n2 = n * n; boost::array<long, 2> lo = { {0, 0} }; boost::array<long, 2> hi = { {n - 1, n - 1} }; amgcl::profiler<> prof; prof.tic("partition"); domain_partition<2> part(lo, hi, world.size()); const long chunk = part.size( world.rank() ); std::vector<long> domain(world.size() + 1); all_gather(world, chunk, &domain[1]); boost::partial_sum(domain, domain.begin()); const long chunk_start = domain[world.rank()]; const long chunk_end = domain[world.rank() + 1]; linear_deflation lindef(n); std::vector<long> renum(n2); for(long j = 0, idx = 0; j < n; ++j) { for(long i = 0; i < n; ++i, ++idx) { boost::array<long, 2> p = {{i, j}}; std::pair<int,long> v = part.index(p); renum[idx] = domain[v.first] + v.second; lindef.idx[renum[idx]] = idx; } } prof.toc("partition"); prof.tic("assemble"); std::vector<long> ptr; std::vector<long> col; std::vector<double> val; std::vector<double> rhs; ptr.reserve(chunk + 1); col.reserve(chunk * 5); val.reserve(chunk * 5); rhs.reserve(chunk); ptr.push_back(0); const double hinv = (n - 1); const double h2i = (n - 1) * (n - 1); for(long j = 0, idx = 0; j < n; ++j) { for(long i = 0; i < n; ++i, ++idx) { if (renum[idx] < chunk_start || renum[idx] >= chunk_end) continue; if (j > 0) { col.push_back(renum[idx - n]); val.push_back(-h2i); } if (i > 0) { col.push_back(renum[idx - 1]); val.push_back(-h2i #ifdef CONVECTION - hinv #endif ); } col.push_back(renum[idx]); val.push_back(4 * h2i #ifdef CONVECTION + hinv #endif ); if (i + 1 < n) { col.push_back(renum[idx + 1]); val.push_back(-h2i); } if (j + 1 < n) { col.push_back(renum[idx + n]); val.push_back(-h2i); } rhs.push_back(1); ptr.push_back( col.size() ); } } prof.toc("assemble"); prof.tic("setup"); typedef amgcl::mpi::subdomain_deflation< amgcl::backend::builtin<double>, amgcl::coarsening::smoothed_aggregation< amgcl::coarsening::plain_aggregates >, amgcl::relaxation::spai0, amgcl::solver::bicgstabl > Solver; typename Solver::AMG_params amg_prm; typename Solver::Solver_params slv_prm(2, 500, 1e-6); Solver solve(world, boost::tie(chunk, ptr, col, val), lindef, amg_prm, slv_prm ); prof.toc("setup"); prof.tic("solve"); std::vector<double> x(chunk, 0); size_t iters; double resid; boost::tie(iters, resid) = solve(rhs, x); prof.toc("solve"); prof.tic("save"); if (world.rank() == 0) { std::vector<double> X(n2); boost::copy(x, X.begin()); for(int i = 1; i < world.size(); ++i) world.recv(i, 42, &X[domain[i]], domain[i+1] - domain[i]); std::ofstream f("out.dat", std::ios::binary); int m = n2; f.write((char*)&m, sizeof(int)); for(long i = 0; i < n2; ++i) f.write((char*)&X[renum[i]], sizeof(double)); } else { world.send(0, 42, x.data(), chunk); } prof.toc("save"); if (world.rank() == 0) { std::cout << "Iterations: " << iters << std::endl << "Error: " << resid << std::endl << std::endl << prof << std::endl; } } #endif <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (C) 2006-2011 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ /// \file StereoSettings.h /// #include <asp/Core/StereoSettings.h> #include <vw/Core/Thread.h> #include <vw/Core/Log.h> #include <fstream> namespace po = boost::program_options; using namespace vw; // --------------------------------------------------- // Create a single instance of the StereoSettings // --------------------------------------------------- namespace { vw::RunOnce stereo_settings_once = VW_RUNONCE_INIT; boost::shared_ptr<StereoSettings> stereo_settings_ptr; void init_stereo_settings() { stereo_settings_ptr = boost::shared_ptr<StereoSettings>(new StereoSettings()); } } StereoSettings& stereo_settings() { stereo_settings_once.run( init_stereo_settings ); return *stereo_settings_ptr; } // ---------------------------------------------------------- // Utilities for parsing lines out of the stereo.default file // ---------------------------------------------------------- // Determine whether the given character is a space character. inline bool is_space_char(int c) { return (c == ' ' || c == '\t' || c == '\n' || c == '\r'); } // Read from stream until (but not including) the next non-space character. inline void ignorespace(std::istream& s) { int c; if(s.eof()) return; while((c = s.get()) != EOF && is_space_char(c)){} if(c != EOF) s.unget(); } // Read from stream until (but not including) the beginning of the next line. inline void ignoreline(std::istream& s) { int c; if(s.eof()) return; while((c = s.get()) != EOF && c != '\n'){} } // Read from stream until (but not including) the next space character. Ignores space characters at beginning. inline void getword(std::istream& s, std::string& str) { int c; str.clear(); ignorespace(s); if(s.eof()) return; while((c = s.get()) != EOF && !is_space_char(c)) str.push_back(c); if(c != EOF) s.unget(); } //-------------------------------------------------- // StereoSettings Methods //-------------------------------------------------- StereoSettings::StereoSettings() { #define ASSOC_INT(X,Y,V,D) m_desc.add_options()(X, po::value<int>(&(this->Y))->default_value(V), D) #define ASSOC_FLOAT(X,Y,V,D) m_desc.add_options()(X, po::value<float>(&(this->Y))->default_value(V), D) #define ASSOC_DOUBLE(X,Y,V,D) m_desc.add_options()(X, po::value<double>(&(this->Y))->default_value(V), D) #define ASSOC_STRING(X,Y,V,D) m_desc.add_options()(X, po::value<std::string>(&(this->Y))->default_value(V), D) // --------------------- // Preprocessing options // --------------------- // Alignment ASSOC_INT("DO_INTERESTPOINT_ALIGNMENT", keypoint_alignment, 0, "Align images using the interest point alignment method"); ASSOC_INT("INTERESTPOINT_ALIGNMENT_SUBSAMPLING", keypoint_align_subsampling, 1, "Image sub-sampling factor for keypoint alignment."); ASSOC_INT("DO_EPIPOLAR_ALIGNMENT", epipolar_alignment, 0, "Align images using epipolar constraints"); // Image normalization ASSOC_INT("FORCE_USE_ENTIRE_RANGE", force_max_min, 0, "Use images entire values, otherwise compress image range to -+2.5 sigmas around mean."); ASSOC_INT("DO_INDIVIDUAL_NORMALIZATION", individually_normalize, 0, "Normalize each image individually before processsing."); // ------------------- // Correlation Options // ------------------- // Preproc filter ASSOC_INT("PREPROCESSING_FILTER_MODE", pre_filter_mode, 3, "selects the preprocessing filter"); ASSOC_FLOAT("SLOG_KERNEL_WIDTH", slogW, 1.5, "SIGMA for the gaussian blure in LOG and SLOG"); // Integer correlator ASSOC_INT("COST_MODE", cost_mode, 2, "0 - absolute different, 1 - squared difference, 2 - normalized cross correlation"); ASSOC_FLOAT("XCORR_THRESHOLD", xcorr_threshold, 2.0, ""); ASSOC_FLOAT("CORRSCORE_REJECTION_THRESHOLD", corrscore_rejection_threshold, 1.1, ""); ASSOC_INT("COST_BLUR", cost_blur, 0, "Reduces the number of missing pixels by blurring the fitness landscape computed by the cost function."); ASSOC_INT("H_KERNEL", kernel[0], 25, "kernel width"); ASSOC_INT("V_KERNEL", kernel[1], 25, "kernel height"); ASSOC_INT("H_CORR_MAX", search_range.max()[0], 0, "correlation window size max x"); ASSOC_INT("H_CORR_MIN", search_range.min()[0], 0, "correlation window size min x"); ASSOC_INT("V_CORR_MAX", search_range.max()[1], 0, "correlation window size max y"); ASSOC_INT("V_CORR_MIN", search_range.min()[1], 0, "correlation window size min y"); ASSOC_INT("SUBPIXEL_MODE", subpixel_mode, 2, "0 - no subpixel, 1 - parabola, 2 - bayes EM"); ASSOC_INT("SUBPIXEL_H_KERNEL", subpixel_kernel[0], 35, "subpixel kernel width"); ASSOC_INT("SUBPIXEL_V_KERNEL", subpixel_kernel[1], 35, "subpixel kernel height"); ASSOC_INT("DO_H_SUBPIXEL", do_h_subpixel, 1, "Do vertical subpixel interpolation."); ASSOC_INT("DO_V_SUBPIXEL", do_v_subpixel, 1, "Do horizontal subpixel interpolation."); // EMSubpixelCorrelator options ASSOC_INT("SUBPIXEL_EM_ITER", subpixel_em_iter, 15, "Maximum number of EM iterations for EMSubpixelCorrelator"); ASSOC_INT("SUBPIXEL_AFFINE_ITER", subpixel_affine_iter, 5, "Maximum number of affine optimization iterations for EMSubpixelCorrelator"); ASSOC_INT("SUBPIXEL_PYRAMID_LEVELS", subpixel_pyramid_levels, 3, "Number of pyramid levels for EMSubpixelCorrelator"); // Filtering Options ASSOC_INT("RM_H_HALF_KERN", rm_h_half_kern, 5, "low conf pixel removal kernel half size"); ASSOC_INT("RM_V_HALF_KERN", rm_v_half_kern, 5, ""); ASSOC_INT("RM_MIN_MATCHES", rm_min_matches, 60, "min # of pxls to be matched to keep pxl"); ASSOC_INT("RM_THRESHOLD", rm_threshold, 3, "rm_threshold > disp[n]-disp[m] pixels are not matching"); ASSOC_INT("RM_CLEANUP_PASSES", rm_cleanup_passes, 1, "number of passes for cleanup during the post-processing phase"); ASSOC_INT("ERODE_MAX_SIZE", erode_max_size, 1000, "max size of islands that should be removed"); ASSOC_INT("FILL_HOLES", fill_holes, 1, "fill holes using an inpainting method"); ASSOC_INT("FILL_HOLE_MAX_SIZE", fill_hole_max_size, 100000, "max size in pixels that should be filled"); ASSOC_INT("MASK_FLATFIELD", mask_flatfield, 0, "mask pixels that are less than 0. (for use with apollo metric camera only!)"); // Triangulation Options ASSOC_STRING("UNIVERSE_CENTER", universe_center, "NONE", "center for radius measurements [CAMERA, ZERO, NONE]"); ASSOC_FLOAT("NEAR_UNIVERSE_RADIUS", near_universe_radius, 0.0, "radius of inner boundary of universe [m]"); ASSOC_FLOAT("FAR_UNIVERSE_RADIUS", far_universe_radius, 0.0, "radius of outer boundary of universe [m]"); ASSOC_INT("USE_LEAST_SQUARES", use_least_squares, 0, "use a more rigorous triangulation"); // System Settings ASSOC_STRING("CACHE_DIR", cache_dir, "/tmp", "Change if can't write large files to /tmp (i.e. Super Computer)"); ASSOC_STRING("TIF_COMPRESS", tif_compress, "", "Compression option for TIF"); #undef ASSOC_INT #undef ASSOC_FLOAT #undef ASSOC_DOUBLE #undef ASSOC_STRING int argc = 1; char* argv[1]; argv[0] = (char*)malloc(2*sizeof(char)); argv[0][0] = 'a'; po::store(po::parse_command_line(argc, argv, m_desc), m_vm); po::notify(m_vm); } void StereoSettings::read(std::string const& filename) { std::ifstream fp(filename.c_str()); if(!fp) { std::cerr << "Error: cannot open stereo default file: " << filename << "\n"; exit(EXIT_FAILURE); } std::string name, value, line; int c; while(!fp.eof()) { ignorespace(fp); if(!fp.eof() && (c = fp.peek()) != '#') { std::istringstream ss; //NOTE: cannot move this up with other //variable declarations because then //calling store(parse_config_file()) //multiple times does not work as //expected getword(fp, name); getword(fp, value); line = name.append(" = ").append(value); ss.str(line); try { po::store(po::parse_config_file(ss, m_desc), m_vm); } catch (boost::program_options::unknown_option const& e) { vw::vw_out() << "\tWARNING --> Unknown stereo settings option: " << line << "\n"; } } ignoreline(fp); } po::notify(m_vm); fp.close(); } void StereoSettings::copy_settings(std::string const& filename, std::string const& destination) { std::ifstream in(filename.c_str()); std::ofstream out(destination.c_str()); out<<in.rdbuf(); // copy file in.close(); out.close(); } bool StereoSettings::is_search_defined() const { return !( search_range.min() == Vector2i() && search_range.max() == Vector2i() ); } <commit_msg>stereo: Clean up style of stereo settings<commit_after>// __BEGIN_LICENSE__ // Copyright (C) 2006-2011 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ /// \file StereoSettings.h /// #include <asp/Core/StereoSettings.h> #include <vw/Core/Thread.h> #include <vw/Core/Log.h> #include <fstream> namespace po = boost::program_options; using namespace vw; // --------------------------------------------------- // Create a single instance of the StereoSettings // --------------------------------------------------- namespace { vw::RunOnce stereo_settings_once = VW_RUNONCE_INIT; boost::shared_ptr<StereoSettings> stereo_settings_ptr; void init_stereo_settings() { stereo_settings_ptr = boost::shared_ptr<StereoSettings>(new StereoSettings()); } } StereoSettings& stereo_settings() { stereo_settings_once.run( init_stereo_settings ); return *stereo_settings_ptr; } // ---------------------------------------------------------- // Utilities for parsing lines out of the stereo.default file // ---------------------------------------------------------- // Determine whether the given character is a space character. inline bool is_space_char(int c) { return (c == ' ' || c == '\t' || c == '\n' || c == '\r'); } // Read from stream until (but not including) the next non-space character. inline void ignorespace(std::istream& s) { int c; if(s.eof()) return; while((c = s.get()) != EOF && is_space_char(c)){} if(c != EOF) s.unget(); } // Read from stream until (but not including) the beginning of the next line. inline void ignoreline(std::istream& s) { int c; if(s.eof()) return; while((c = s.get()) != EOF && c != '\n'){} } // Read from stream until (but not including) the next space character. Ignores space characters at beginning. inline void getword(std::istream& s, std::string& str) { int c; str.clear(); ignorespace(s); if(s.eof()) return; while((c = s.get()) != EOF && !is_space_char(c)) str.push_back(c); if(c != EOF) s.unget(); } //-------------------------------------------------- // StereoSettings Methods //-------------------------------------------------- StereoSettings::StereoSettings() { #define ASSOC(X, Y, V, D) m_desc.add_options()(X, po::value(&(this->Y))->default_value(V), D) #define ASSOC_SIMPLE(X, Y) m_desc.add_options()(X, po::value(&(this->Y))) // --------------------- // Preprocessing options // --------------------- // Alignment ASSOC("DO_INTERESTPOINT_ALIGNMENT", keypoint_alignment, 0, "Align images using the interest point alignment method"); ASSOC("INTERESTPOINT_ALIGNMENT_SUBSAMPLING", keypoint_align_subsampling, 1, "Image sub-sampling factor for keypoint alignment."); ASSOC("DO_EPIPOLAR_ALIGNMENT", epipolar_alignment, 0, "Align images using epipolar constraints"); // Image normalization ASSOC("FORCE_USE_ENTIRE_RANGE", force_max_min, 0, "Use images entire values, otherwise compress image range to -+2.5 sigmas around mean."); ASSOC("DO_INDIVIDUAL_NORMALIZATION", individually_normalize, 0, "Normalize each image individually before processsing."); // ------------------- // Correlation Options // ------------------- // Preproc filter ASSOC("PREPROCESSING_FILTER_MODE", pre_filter_mode, 3, "selects the preprocessing filter"); ASSOC("SLOG_KERNEL_WIDTH", slogW, 1.5, "SIGMA for the gaussian blure in LOG and SLOG"); // Integer correlator ASSOC("COST_MODE", cost_mode, 2, "0 - absolute different, 1 - squared difference, 2 - normalized cross correlation"); ASSOC("XCORR_THRESHOLD", xcorr_threshold, 2.0, ""); ASSOC("CORRSCORE_REJECTION_THRESHOLD", corrscore_rejection_threshold, 1.1, ""); ASSOC("COST_BLUR", cost_blur, 0, "Reduces the number of missing pixels by blurring the fitness landscape computed by the cost function."); ASSOC("H_KERNEL", kernel[0], 25, "kernel width"); ASSOC("V_KERNEL", kernel[1], 25, "kernel height"); ASSOC("H_CORR_MAX", search_range.max()[0], 0, "correlation window size max x"); ASSOC("H_CORR_MIN", search_range.min()[0], 0, "correlation window size min x"); ASSOC("V_CORR_MAX", search_range.max()[1], 0, "correlation window size max y"); ASSOC("V_CORR_MIN", search_range.min()[1], 0, "correlation window size min y"); ASSOC("SUBPIXEL_MODE", subpixel_mode, 2, "0 - no subpixel, 1 - parabola, 2 - bayes EM"); ASSOC("SUBPIXEL_H_KERNEL", subpixel_kernel[0], 35, "subpixel kernel width"); ASSOC("SUBPIXEL_V_KERNEL", subpixel_kernel[1], 35, "subpixel kernel height"); ASSOC("DO_H_SUBPIXEL", do_h_subpixel, 1, "Do vertical subpixel interpolation."); ASSOC("DO_V_SUBPIXEL", do_v_subpixel, 1, "Do horizontal subpixel interpolation."); // EMSubpixelCorrelator options ASSOC("SUBPIXEL_EM_ITER", subpixel_em_iter, 15, "Maximum number of EM iterations for EMSubpixelCorrelator"); ASSOC("SUBPIXEL_AFFINE_ITER", subpixel_affine_iter, 5, "Maximum number of affine optimization iterations for EMSubpixelCorrelator"); ASSOC("SUBPIXEL_PYRAMID_LEVELS", subpixel_pyramid_levels, 3, "Number of pyramid levels for EMSubpixelCorrelator"); // Filtering Options ASSOC("RM_H_HALF_KERN", rm_h_half_kern, 5, "low conf pixel removal kernel half size"); ASSOC("RM_V_HALF_KERN", rm_v_half_kern, 5, ""); ASSOC("RM_MIN_MATCHES", rm_min_matches, 60, "min # of pxls to be matched to keep pxl"); ASSOC("RM_THRESHOLD", rm_threshold, 3, "rm_threshold > disp[n]-disp[m] pixels are not matching"); ASSOC("RM_CLEANUP_PASSES", rm_cleanup_passes, 1, "number of passes for cleanup during the post-processing phase"); ASSOC("ERODE_MAX_SIZE", erode_max_size, 1000, "max size of islands that should be removed"); ASSOC("FILL_HOLES", fill_holes, 1, "fill holes using an inpainting method"); ASSOC("FILL_HOLE_MAX_SIZE", fill_hole_max_size, 100000, "max size in pixels that should be filled"); ASSOC("MASK_FLATFIELD", mask_flatfield, 0, "mask pixels that are less than 0. (for use with apollo metric camera only!)"); // Triangulation Options ASSOC("UNIVERSE_CENTER", universe_center, "NONE", "center for radius measurements [CAMERA, ZERO, NONE]"); ASSOC("NEAR_UNIVERSE_RADIUS", near_universe_radius, 0.0, "radius of inner boundary of universe [m]"); ASSOC("FAR_UNIVERSE_RADIUS", far_universe_radius, 0.0, "radius of outer boundary of universe [m]"); ASSOC("USE_LEAST_SQUARES", use_least_squares, 0, "use a more rigorous triangulation"); // System Settings ASSOC("CACHE_DIR", cache_dir, "/tmp", "Change if can't write large files to /tmp (i.e. Super Computer)"); ASSOC_SIMPLE("TIF_COMPRESS", tif_compress); #undef ASSOC #undef ASSOC_SIMPLE int argc = 1; char* argv[1]; argv[0] = (char*)malloc(2*sizeof(char)); argv[0][0] = 'a'; po::store(po::parse_command_line(argc, argv, m_desc), m_vm); po::notify(m_vm); } void StereoSettings::read(std::string const& filename) { std::ifstream fp(filename.c_str()); if(!fp) { std::cerr << "Error: cannot open stereo default file: " << filename << "\n"; exit(EXIT_FAILURE); } std::string name, value, line; int c; while(!fp.eof()) { ignorespace(fp); if(!fp.eof() && (c = fp.peek()) != '#') { std::istringstream ss; //NOTE: cannot move this up with other //variable declarations because then //calling store(parse_config_file()) //multiple times does not work as //expected getword(fp, name); getword(fp, value); line = name.append(" = ").append(value); ss.str(line); try { po::store(po::parse_config_file(ss, m_desc), m_vm); } catch (boost::program_options::unknown_option const& e) { vw::vw_out() << "\tWARNING --> Unknown stereo settings option: " << line << "\n"; } } ignoreline(fp); } po::notify(m_vm); fp.close(); } void StereoSettings::copy_settings(std::string const& filename, std::string const& destination) { std::ifstream in(filename.c_str()); std::ofstream out(destination.c_str()); out<<in.rdbuf(); // copy file in.close(); out.close(); } bool StereoSettings::is_search_defined() const { return !( search_range.min() == Vector2i() && search_range.max() == Vector2i() ); } <|endoftext|>
<commit_before>/* OpenSceneGraph example, osganimate. * * 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 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. */ #include <osg/Notify> #include <osgDB/ReadFile> #include <osgGA/TrackballManipulator> #include <osgViewer/Viewer> int main( int argc, char **argv ) { osg::ArgumentParser arguments(&argc,argv); // initialize the viewer. osgViewer::Viewer viewer(arguments); osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments); if (!model) { OSG_NOTICE<<"No models loaded, please specify a model file on the command line"<<std::endl; return 1; } viewer.setSceneData(model.get()); viewer.setCameraManipulator(new osgGA::TrackballManipulator()); return viewer.run(); } <commit_msg>Experiments with modifying the projection matrix to provide keystoning.<commit_after>/* OpenSceneGraph example, osganimate. * * 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 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. */ #include <osg/Notify> #include <osg/io_utils> #include <osgDB/ReadFile> #include <osgGA/TrackballManipulator> #include <osgViewer/Viewer> int main( int argc, char **argv ) { osg::ArgumentParser arguments(&argc,argv); // initialize the viewer. osgViewer::Viewer viewer(arguments); osg::Vec2d translate(0.0,0.0); osg::Vec2d scale(1.0,1.0); osg::Vec2d taper(1.0,1.0); double angle = 0; // osg::inDegrees(45.0); if (arguments.read("-a",angle)) { OSG_NOTICE<<"angle = "<<angle<<std::endl; angle = osg::inDegrees(angle); } if (arguments.read("-t",translate.x(), translate.y())) { OSG_NOTICE<<"translate = "<<translate<<std::endl;} if (arguments.read("-s",scale.x(), scale.y())) { OSG_NOTICE<<"scale = "<<scale<<std::endl;} if (arguments.read("-k",taper.x(), taper.y())) { OSG_NOTICE<<"taper = "<<taper<<std::endl;} osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments); if (!model) { OSG_NOTICE<<"No models loaded, please specify a model file on the command line"<<std::endl; return 1; } viewer.setSceneData(model.get()); viewer.setCameraManipulator(new osgGA::TrackballManipulator()); viewer.realize(); viewer.getCamera()->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR); osg::Matrixd& pm = viewer.getCamera()->getProjectionMatrix(); pm.postMultRotate(osg::Quat(angle, osg::Vec3d(0.0,0.0,1.0))); pm.postMultScale(osg::Vec3d(scale.x(),scale.y(),1.0)); pm.postMultTranslate(osg::Vec3d(translate.x(),translate.y(),0.0)); if (taper.x()!=1.0) { double x0 = (1.0+taper.x())/(1-taper.x()); OSG_NOTICE<<"x0 = "<<x0<<std::endl; pm.postMult(osg::Matrixd(1.0-x0, 0.0, 0.0, 1.0, 0.0, 1.0-x0, 0.0, 0.0, 0.0, 0.0, (1.0-x0)*0.5, 0.0, 0.0, 0.0, 0.0, -x0)); } return viewer.run(); } <|endoftext|>
<commit_before>#include <osg/Group> #include <osg/Notify> #include <osg/Geometry> #include <osg/ArgumentParser> #include <osg/ApplicationUsage> #include <osg/Texture2D> #include <osg/Geode> #include <osg/PagedLOD> #include <osgDB/Registry> #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osgUtil/Optimizer> #include <iostream> #include <sstream> class WriteOutPagedLODSubgraphsVistor : public osg::NodeVisitor { public: WriteOutPagedLODSubgraphsVistor(): osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN) { } virtual void apply(osg::PagedLOD& plod) { // go through all the named children and write them out to disk. for(unsigned int i=0;i<plod.getNumChildren();++i) { osg::Node* child = plod.getChild(i); std::string filename = plod.getFileName(i); if (!filename.empty()) { osg::notify(osg::NOTICE)<<"Writing out "<<filename<<std::endl; osgDB::writeNodeFile(*child,filename); } } traverse(plod); } }; class ConvertToPageLODVistor : public osg::NodeVisitor { public: ConvertToPageLODVistor(const std::string& basename, const std::string& extension): osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), _basename(basename), _extension(extension) { } virtual ~ConvertToPageLODVistor() { } virtual void apply(osg::LOD& lod) { _lodSet.insert(&lod); traverse(lod); } virtual void apply(osg::PagedLOD& plod) { // do thing, but want to avoid call LOD. traverse(plod); } void convert() { unsigned int lodNum = 0; for(LODSet::iterator itr = _lodSet.begin(); itr != _lodSet.end(); ++itr, ++lodNum) { osg::ref_ptr<osg::LOD> lod = const_cast<osg::LOD*>(itr->get()); if (lod->getNumParents()==0) { osg::notify(osg::NOTICE)<<"Warning can't operator on root node."<<std::endl; break; } osg::notify(osg::NOTICE)<<"Converting LOD to PagedLOD"<<std::endl; osg::PagedLOD* plod = new osg::PagedLOD; const osg::LOD::RangeList& originalRangeList = lod->getRangeList(); typedef std::map< osg::LOD::MinMaxPair , unsigned int > MinMaxPairMap; MinMaxPairMap rangeMap; unsigned int pos = 0; for(osg::LOD::RangeList::const_iterator ritr = originalRangeList.begin(); ritr != originalRangeList.end(); ++ritr, ++pos) { rangeMap[*ritr] = pos; } pos = 0; for(MinMaxPairMap::reverse_iterator mitr = rangeMap.rbegin(); mitr != rangeMap.rend(); ++mitr, ++pos) { if (pos==0) { plod->addChild(lod->getChild(mitr->second), mitr->first.first, mitr->first.second); osg::notify(osg::NOTICE)<<" adding staight child"<<std::endl; } else { std::string filename = _basename; std::ostringstream os; os << _basename << "_"<<lodNum<<"_"<<pos<<_extension; plod->addChild(lod->getChild(mitr->second), mitr->first.first, mitr->first.second, os.str()); osg::notify(osg::NOTICE)<<" adding tiled subgraph"<<os.str()<<std::endl; } } osg::Node::ParentList parents = lod->getParents(); for(osg::Node::ParentList::iterator pitr=parents.begin(); pitr!=parents.end(); ++pitr) { (*pitr)->replaceChild(lod.get(),plod); } plod->setCenter(plod->getBound().center()); plod->setCenter(plod->getBound().center()); } } typedef std::set< osg::ref_ptr<osg::LOD> > LODSet; LODSet _lodSet; std::string _basename; std::string _extension; }; int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" creates a hierachy of files for paging which can be later loaded by viewers."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } // if (arguments.argc()<=1) // { // arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION); // return 1; // } osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments); if (!model) { osg::notify(osg::NOTICE)<<"No model loaded."<<std::endl; return 1; } ConvertToPageLODVistor converter("tile",".ive"); model->accept(converter); converter.convert(); if (model.valid()) { osgDB::writeNodeFile(*model,"tile.ive"); WriteOutPagedLODSubgraphsVistor woplsv; model->accept(woplsv); } return 0; } <commit_msg>Updates<commit_after>#include <osg/Group> #include <osg/Notify> #include <osg/Geometry> #include <osg/ArgumentParser> #include <osg/ApplicationUsage> #include <osg/Texture2D> #include <osg/Geode> #include <osg/PagedLOD> #include <osgDB/Registry> #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osgDB/FileNameUtils> #include <osgUtil/Optimizer> #include <iostream> #include <sstream> class NameVistor : public osg::NodeVisitor { public: NameVistor(): osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), _count(0) { } virtual void apply(osg::Node& node) { std::ostringstream os; os << node.className() << "_"<<_count++; node.setName(os.str()); traverse(node); } unsigned int _count; }; class CheckVisitor : public osg::NodeVisitor { public: CheckVisitor(): osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN) { } virtual void apply(osg::PagedLOD& plod) { std::cout<<"PagedLOD "<<plod.getName()<<" numRanges = "<< plod.getNumRanges()<<" numFiles = "<<plod.getNumFileNames()<<std::endl; for(unsigned int i=0;i<plod.getNumFileNames();++i) { std::cout<<" files = '"<<plod.getFileName(i)<<"'"<<std::endl; } } }; class WriteOutPagedLODSubgraphsVistor : public osg::NodeVisitor { public: WriteOutPagedLODSubgraphsVistor(): osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN) { } virtual void apply(osg::PagedLOD& plod) { // go through all the named children and write them out to disk. for(unsigned int i=0;i<plod.getNumChildren();++i) { osg::Node* child = plod.getChild(i); std::string filename = plod.getFileName(i); if (!filename.empty()) { osg::notify(osg::NOTICE)<<"Writing out "<<filename<<std::endl; osgDB::writeNodeFile(*child,filename); } } traverse(plod); } }; class ConvertToPageLODVistor : public osg::NodeVisitor { public: ConvertToPageLODVistor(const std::string& basename, const std::string& extension, bool makeAllChildrenPaged): osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), _basename(basename), _extension(extension), _makeAllChildrenPaged(makeAllChildrenPaged) { } virtual ~ConvertToPageLODVistor() { } virtual void apply(osg::LOD& lod) { _lodSet.insert(&lod); traverse(lod); } virtual void apply(osg::PagedLOD& plod) { // do thing, but want to avoid call LOD. traverse(plod); } void convert() { unsigned int lodNum = 0; for(LODSet::iterator itr = _lodSet.begin(); itr != _lodSet.end(); ++itr, ++lodNum) { osg::ref_ptr<osg::LOD> lod = const_cast<osg::LOD*>(itr->get()); if (lod->getNumParents()==0) { osg::notify(osg::NOTICE)<<"Warning can't operator on root node."<<std::endl; break; } if (!_makeAllChildrenPaged && lod->getNumRanges()<2) { osg::notify(osg::NOTICE)<<"Leaving LOD with one child as is."<<std::endl; break; } osg::notify(osg::NOTICE)<<"Converting LOD to PagedLOD."<<std::endl; osg::PagedLOD* plod = new osg::PagedLOD; const osg::LOD::RangeList& originalRangeList = lod->getRangeList(); typedef std::multimap< osg::LOD::MinMaxPair , unsigned int > MinMaxPairMap; MinMaxPairMap rangeMap; unsigned int pos = 0; for(osg::LOD::RangeList::const_iterator ritr = originalRangeList.begin(); ritr != originalRangeList.end(); ++ritr, ++pos) { rangeMap.insert(std::multimap< osg::LOD::MinMaxPair , unsigned int >::value_type(*ritr, pos)); } pos = 0; for(MinMaxPairMap::reverse_iterator mitr = rangeMap.rbegin(); mitr != rangeMap.rend(); ++mitr, ++pos) { if (pos==0 && !_makeAllChildrenPaged) { plod->addChild(lod->getChild(mitr->second), mitr->first.first, mitr->first.second); } else { std::string filename = _basename; std::ostringstream os; os << _basename << "_"<<lodNum<<"_"<<pos<<_extension; plod->addChild(lod->getChild(mitr->second), mitr->first.first, mitr->first.second, os.str()); } } osg::Node::ParentList parents = lod->getParents(); for(osg::Node::ParentList::iterator pitr=parents.begin(); pitr!=parents.end(); ++pitr) { (*pitr)->replaceChild(lod.get(),plod); } plod->setCenter(plod->getBound().center()); } } typedef std::set< osg::ref_ptr<osg::LOD> > LODSet; LODSet _lodSet; std::string _basename; std::string _extension; bool _makeAllChildrenPaged; }; int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" creates a hierachy of files for paging which can be later loaded by viewers."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information"); arguments.getApplicationUsage()->addCommandLineOption("-o","set the output file (defaults to output.ive)"); arguments.getApplicationUsage()->addCommandLineOption("--makeAllChildrenPaged","Force all children of LOD to be written out as external PagedLOD children"); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return 1; } std::string outputfile("output.ive"); while (arguments.read("-o",outputfile)) {} bool makeAllChildrenPaged = false; while (arguments.read("--makeAllChildrenPaged")) { makeAllChildrenPaged = true; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occured when parsing the program aguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } // if (arguments.argc()<=1) // { // arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION); // return 1; // } osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments); if (!model) { osg::notify(osg::NOTICE)<<"No model loaded."<<std::endl; return 1; } std::string basename( osgDB::getNameLessExtension(outputfile) ); std::string ext = '.'+ osgDB::getFileExtension(outputfile); ConvertToPageLODVistor converter(basename,ext, makeAllChildrenPaged); model->accept(converter); converter.convert(); NameVistor nameNodes; model->accept(nameNodes); //CheckVisitor checkNodes; //model->accept(checkNodes); if (model.valid()) { osgDB::writeNodeFile(*model,outputfile); WriteOutPagedLODSubgraphsVistor woplsv; model->accept(woplsv); } return 0; } <|endoftext|>
<commit_before>//===-- MipsTargetInfo.cpp - Mips Target Implementation -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Mips.h" #include "llvm/IR/Module.h" #include "llvm/Support/TargetRegistry.h" using namespace llvm; Target &llvm::getTheMipsTarget() { static Target TheMipsTarget; return TheMipsTarget; } Target &llvm::getTheMipselTarget() { static Target TheMipselTarget; return TheMipselTarget; } Target &llvm::getTheMips64Target() { static Target TheMips64Target; return TheMips64Target; } Target &llvm::getTheMips64elTarget() { static Target TheMips64elTarget; return TheMips64elTarget; } extern "C" void LLVMInitializeMipsTargetInfo() { RegisterTarget<Triple::mips, /*HasJIT=*/true> X(getTheMipsTarget(), "mips", "Mips", "Mips"); RegisterTarget<Triple::mipsel, /*HasJIT=*/true> Y(getTheMipselTarget(), "mipsel", "Mipsel", "Mips"); RegisterTarget<Triple::mips64, /*HasJIT=*/true> A(getTheMips64Target(), "mips64", "Mips64 [experimental]", "Mips"); RegisterTarget<Triple::mips64el, /*HasJIT=*/true> B(getTheMips64elTarget(), "mips64el", "Mips64el [experimental]", "Mips"); } <commit_msg>[mips] Remove obsoleted "experimental" tag from MIPS 64-bit targets. NFC<commit_after>//===-- MipsTargetInfo.cpp - Mips Target Implementation -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Mips.h" #include "llvm/IR/Module.h" #include "llvm/Support/TargetRegistry.h" using namespace llvm; Target &llvm::getTheMipsTarget() { static Target TheMipsTarget; return TheMipsTarget; } Target &llvm::getTheMipselTarget() { static Target TheMipselTarget; return TheMipselTarget; } Target &llvm::getTheMips64Target() { static Target TheMips64Target; return TheMips64Target; } Target &llvm::getTheMips64elTarget() { static Target TheMips64elTarget; return TheMips64elTarget; } extern "C" void LLVMInitializeMipsTargetInfo() { RegisterTarget<Triple::mips, /*HasJIT=*/true> X(getTheMipsTarget(), "mips", "Mips", "Mips"); RegisterTarget<Triple::mipsel, /*HasJIT=*/true> Y(getTheMipselTarget(), "mipsel", "Mipsel", "Mips"); RegisterTarget<Triple::mips64, /*HasJIT=*/true> A(getTheMips64Target(), "mips64", "Mips64", "Mips"); RegisterTarget<Triple::mips64el, /*HasJIT=*/true> B(getTheMips64elTarget(), "mips64el", "Mips64el", "Mips"); } <|endoftext|>
<commit_before>//===-- VPlanHCFGBuilder.cpp ----------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// This file implements the construction of a VPlan-based Hierarchical CFG /// (H-CFG) for an incoming IR. This construction comprises the following /// components and steps: // /// 1. PlainCFGBuilder class: builds a plain VPBasicBlock-based CFG that /// faithfully represents the CFG in the incoming IR. A VPRegionBlock (Top /// Region) is created to enclose and serve as parent of all the VPBasicBlocks /// in the plain CFG. /// NOTE: At this point, there is a direct correspondence between all the /// VPBasicBlocks created for the initial plain CFG and the incoming /// BasicBlocks. However, this might change in the future. /// //===----------------------------------------------------------------------===// #include "VPlanHCFGBuilder.h" #include "LoopVectorizationPlanner.h" #include "llvm/Analysis/LoopIterator.h" #define DEBUG_TYPE "loop-vectorize" using namespace llvm; // Class that is used to build the plain CFG for the incoming IR. class PlainCFGBuilder { private: // The outermost loop of the input loop nest considered for vectorization. Loop *TheLoop; // Loop Info analysis. LoopInfo *LI; // Vectorization plan that we are working on. VPlan &Plan; // Output Top Region. VPRegionBlock *TopRegion = nullptr; // Builder of the VPlan instruction-level representation. VPBuilder VPIRBuilder; // NOTE: The following maps are intentionally destroyed after the plain CFG // construction because subsequent VPlan-to-VPlan transformation may // invalidate them. // Map incoming BasicBlocks to their newly-created VPBasicBlocks. DenseMap<BasicBlock *, VPBasicBlock *> BB2VPBB; // Map incoming Value definitions to their newly-created VPValues. DenseMap<Value *, VPValue *> IRDef2VPValue; // Hold phi node's that need to be fixed once the plain CFG has been built. SmallVector<PHINode *, 8> PhisToFix; // Utility functions. void setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB); void fixPhiNodes(); VPBasicBlock *getOrCreateVPBB(BasicBlock *BB); bool isExternalDef(Value *Val); VPValue *getOrCreateVPOperand(Value *IRVal); void createVPInstructionsForVPBB(VPBasicBlock *VPBB, BasicBlock *BB); public: PlainCFGBuilder(Loop *Lp, LoopInfo *LI, VPlan &P) : TheLoop(Lp), LI(LI), Plan(P) {} // Build the plain CFG and return its Top Region. VPRegionBlock *buildPlainCFG(); }; // Return true if \p Inst is an incoming Instruction to be ignored in the VPlan // representation. static bool isInstructionToIgnore(Instruction *Inst) { return isa<BranchInst>(Inst); } // Set predecessors of \p VPBB in the same order as they are in \p BB. \p VPBB // must have no predecessors. void PlainCFGBuilder::setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB) { SmallVector<VPBlockBase *, 8> VPBBPreds; // Collect VPBB predecessors. for (BasicBlock *Pred : predecessors(BB)) VPBBPreds.push_back(getOrCreateVPBB(Pred)); VPBB->setPredecessors(VPBBPreds); } // Add operands to VPInstructions representing phi nodes from the input IR. void PlainCFGBuilder::fixPhiNodes() { for (auto *Phi : PhisToFix) { assert(IRDef2VPValue.count(Phi) && "Missing VPInstruction for PHINode."); VPValue *VPVal = IRDef2VPValue[Phi]; assert(isa<VPInstruction>(VPVal) && "Expected VPInstruction for phi node."); auto *VPPhi = cast<VPInstruction>(VPVal); assert(VPPhi->getNumOperands() == 0 && "Expected VPInstruction with no operands."); for (Value *Op : Phi->operands()) VPPhi->addOperand(getOrCreateVPOperand(Op)); } } // Create a new empty VPBasicBlock for an incoming BasicBlock or retrieve an // existing one if it was already created. VPBasicBlock *PlainCFGBuilder::getOrCreateVPBB(BasicBlock *BB) { auto BlockIt = BB2VPBB.find(BB); if (BlockIt != BB2VPBB.end()) // Retrieve existing VPBB. return BlockIt->second; // Create new VPBB. LLVM_DEBUG(dbgs() << "Creating VPBasicBlock for " << BB->getName() << "\n"); VPBasicBlock *VPBB = new VPBasicBlock(BB->getName()); BB2VPBB[BB] = VPBB; VPBB->setParent(TopRegion); return VPBB; } // Return true if \p Val is considered an external definition. An external // definition is either: // 1. A Value that is not an Instruction. This will be refined in the future. // 2. An Instruction that is outside of the CFG snippet represented in VPlan, // i.e., is not part of: a) the loop nest, b) outermost loop PH and, c) // outermost loop exits. bool PlainCFGBuilder::isExternalDef(Value *Val) { // All the Values that are not Instructions are considered external // definitions for now. Instruction *Inst = dyn_cast<Instruction>(Val); if (!Inst) return true; BasicBlock *InstParent = Inst->getParent(); assert(InstParent && "Expected instruction parent."); // Check whether Instruction definition is in loop PH. BasicBlock *PH = TheLoop->getLoopPreheader(); assert(PH && "Expected loop pre-header."); if (InstParent == PH) // Instruction definition is in outermost loop PH. return false; // Check whether Instruction definition is in the loop exit. BasicBlock *Exit = TheLoop->getUniqueExitBlock(); assert(Exit && "Expected loop with single exit."); if (InstParent == Exit) { // Instruction definition is in outermost loop exit. return false; } // Check whether Instruction definition is in loop body. return !TheLoop->contains(Inst); } // Create a new VPValue or retrieve an existing one for the Instruction's // operand \p IRVal. This function must only be used to create/retrieve VPValues // for *Instruction's operands* and not to create regular VPInstruction's. For // the latter, please, look at 'createVPInstructionsForVPBB'. VPValue *PlainCFGBuilder::getOrCreateVPOperand(Value *IRVal) { auto VPValIt = IRDef2VPValue.find(IRVal); if (VPValIt != IRDef2VPValue.end()) // Operand has an associated VPInstruction or VPValue that was previously // created. return VPValIt->second; // Operand doesn't have a previously created VPInstruction/VPValue. This // means that operand is: // A) a definition external to VPlan, // B) any other Value without specific representation in VPlan. // For now, we use VPValue to represent A and B and classify both as external // definitions. We may introduce specific VPValue subclasses for them in the // future. assert(isExternalDef(IRVal) && "Expected external definition as operand."); // A and B: Create VPValue and add it to the pool of external definitions and // to the Value->VPValue map. VPValue *NewVPVal = new VPValue(IRVal); Plan.addExternalDef(NewVPVal); IRDef2VPValue[IRVal] = NewVPVal; return NewVPVal; } // Create new VPInstructions in a VPBasicBlock, given its BasicBlock // counterpart. This function must be invoked in RPO so that the operands of a // VPInstruction in \p BB have been visited before (except for Phi nodes). void PlainCFGBuilder::createVPInstructionsForVPBB(VPBasicBlock *VPBB, BasicBlock *BB) { VPIRBuilder.setInsertPoint(VPBB); for (Instruction &InstRef : *BB) { Instruction *Inst = &InstRef; if (isInstructionToIgnore(Inst)) continue; // There should't be any VPValue for Inst at this point. Otherwise, we // visited Inst when we shouldn't, breaking the RPO traversal order. assert(!IRDef2VPValue.count(Inst) && "Instruction shouldn't have been visited."); VPInstruction *NewVPInst; if (PHINode *Phi = dyn_cast<PHINode>(Inst)) { // Phi node's operands may have not been visited at this point. We create // an empty VPInstruction that we will fix once the whole plain CFG has // been built. NewVPInst = cast<VPInstruction>(VPIRBuilder.createNaryOp( Inst->getOpcode(), {} /*No operands*/, Inst)); PhisToFix.push_back(Phi); } else { // Translate LLVM-IR operands into VPValue operands and set them in the // new VPInstruction. SmallVector<VPValue *, 4> VPOperands; for (Value *Op : Inst->operands()) VPOperands.push_back(getOrCreateVPOperand(Op)); // Build VPInstruction for any arbitraty Instruction without specific // representation in VPlan. NewVPInst = cast<VPInstruction>( VPIRBuilder.createNaryOp(Inst->getOpcode(), VPOperands, Inst)); } IRDef2VPValue[Inst] = NewVPInst; } } // Main interface to build the plain CFG. VPRegionBlock *PlainCFGBuilder::buildPlainCFG() { // 1. Create the Top Region. It will be the parent of all VPBBs. TopRegion = new VPRegionBlock("TopRegion", false /*isReplicator*/); // 2. Scan the body of the loop in a topological order to visit each basic // block after having visited its predecessor basic blocks. Create a VPBB for // each BB and link it to its successor and predecessor VPBBs. Note that // predecessors must be set in the same order as they are in the incomming IR. // Otherwise, there might be problems with existing phi nodes and algorithm // based on predecessors traversal. // Loop PH needs to be explicitly visited since it's not taken into account by // LoopBlocksDFS. BasicBlock *PreheaderBB = TheLoop->getLoopPreheader(); assert((PreheaderBB->getTerminator()->getNumSuccessors() == 1) && "Unexpected loop preheader"); VPBasicBlock *PreheaderVPBB = getOrCreateVPBB(PreheaderBB); createVPInstructionsForVPBB(PreheaderVPBB, PreheaderBB); // Create empty VPBB for Loop H so that we can link PH->H. VPBlockBase *HeaderVPBB = getOrCreateVPBB(TheLoop->getHeader()); // Preheader's predecessors will be set during the loop RPO traversal below. PreheaderVPBB->setOneSuccessor(HeaderVPBB); LoopBlocksRPO RPO(TheLoop); RPO.perform(LI); for (BasicBlock *BB : RPO) { // Create or retrieve the VPBasicBlock for this BB and create its // VPInstructions. VPBasicBlock *VPBB = getOrCreateVPBB(BB); createVPInstructionsForVPBB(VPBB, BB); // Set VPBB successors. We create empty VPBBs for successors if they don't // exist already. Recipes will be created when the successor is visited // during the RPO traversal. TerminatorInst *TI = BB->getTerminator(); assert(TI && "Terminator expected."); unsigned NumSuccs = TI->getNumSuccessors(); if (NumSuccs == 1) { VPBasicBlock *SuccVPBB = getOrCreateVPBB(TI->getSuccessor(0)); assert(SuccVPBB && "VPBB Successor not found."); VPBB->setOneSuccessor(SuccVPBB); } else if (NumSuccs == 2) { VPBasicBlock *SuccVPBB0 = getOrCreateVPBB(TI->getSuccessor(0)); assert(SuccVPBB0 && "Successor 0 not found."); VPBasicBlock *SuccVPBB1 = getOrCreateVPBB(TI->getSuccessor(1)); assert(SuccVPBB1 && "Successor 1 not found."); VPBB->setTwoSuccessors(SuccVPBB0, SuccVPBB1); } else llvm_unreachable("Number of successors not supported."); // Set VPBB predecessors in the same order as they are in the incoming BB. setVPBBPredsFromBB(VPBB, BB); } // 3. Process outermost loop exit. We created an empty VPBB for the loop // single exit BB during the RPO traversal of the loop body but Instructions // weren't visited because it's not part of the the loop. BasicBlock *LoopExitBB = TheLoop->getUniqueExitBlock(); assert(LoopExitBB && "Loops with multiple exits are not supported."); VPBasicBlock *LoopExitVPBB = BB2VPBB[LoopExitBB]; createVPInstructionsForVPBB(LoopExitVPBB, LoopExitBB); // Loop exit was already set as successor of the loop exiting BB. // We only set its predecessor VPBB now. setVPBBPredsFromBB(LoopExitVPBB, LoopExitBB); // 4. The whole CFG has been built at this point so all the input Values must // have a VPlan couterpart. Fix VPlan phi nodes by adding their corresponding // VPlan operands. fixPhiNodes(); // 5. Final Top Region setup. Set outermost loop pre-header and single exit as // Top Region entry and exit. TopRegion->setEntry(PreheaderVPBB); TopRegion->setExit(LoopExitVPBB); return TopRegion; } // Public interface to build a H-CFG. void VPlanHCFGBuilder::buildHierarchicalCFG(VPlan &Plan) { // Build Top Region enclosing the plain CFG and set it as VPlan entry. PlainCFGBuilder PCFGBuilder(TheLoop, LI, Plan); VPRegionBlock *TopRegion = PCFGBuilder.buildPlainCFG(); Plan.setEntry(TopRegion); LLVM_DEBUG(Plan.setName("HCFGBuilder: Plain CFG\n"); dbgs() << Plan); Verifier.verifyHierarchicalCFG(TopRegion); } <commit_msg>[NFC][VPlan] Wrap PlainCFGBuilder with an anonymous namespace.<commit_after>//===-- VPlanHCFGBuilder.cpp ----------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// This file implements the construction of a VPlan-based Hierarchical CFG /// (H-CFG) for an incoming IR. This construction comprises the following /// components and steps: // /// 1. PlainCFGBuilder class: builds a plain VPBasicBlock-based CFG that /// faithfully represents the CFG in the incoming IR. A VPRegionBlock (Top /// Region) is created to enclose and serve as parent of all the VPBasicBlocks /// in the plain CFG. /// NOTE: At this point, there is a direct correspondence between all the /// VPBasicBlocks created for the initial plain CFG and the incoming /// BasicBlocks. However, this might change in the future. /// //===----------------------------------------------------------------------===// #include "VPlanHCFGBuilder.h" #include "LoopVectorizationPlanner.h" #include "llvm/Analysis/LoopIterator.h" #define DEBUG_TYPE "loop-vectorize" using namespace llvm; namespace { // Class that is used to build the plain CFG for the incoming IR. class PlainCFGBuilder { private: // The outermost loop of the input loop nest considered for vectorization. Loop *TheLoop; // Loop Info analysis. LoopInfo *LI; // Vectorization plan that we are working on. VPlan &Plan; // Output Top Region. VPRegionBlock *TopRegion = nullptr; // Builder of the VPlan instruction-level representation. VPBuilder VPIRBuilder; // NOTE: The following maps are intentionally destroyed after the plain CFG // construction because subsequent VPlan-to-VPlan transformation may // invalidate them. // Map incoming BasicBlocks to their newly-created VPBasicBlocks. DenseMap<BasicBlock *, VPBasicBlock *> BB2VPBB; // Map incoming Value definitions to their newly-created VPValues. DenseMap<Value *, VPValue *> IRDef2VPValue; // Hold phi node's that need to be fixed once the plain CFG has been built. SmallVector<PHINode *, 8> PhisToFix; // Utility functions. void setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB); void fixPhiNodes(); VPBasicBlock *getOrCreateVPBB(BasicBlock *BB); bool isExternalDef(Value *Val); VPValue *getOrCreateVPOperand(Value *IRVal); void createVPInstructionsForVPBB(VPBasicBlock *VPBB, BasicBlock *BB); public: PlainCFGBuilder(Loop *Lp, LoopInfo *LI, VPlan &P) : TheLoop(Lp), LI(LI), Plan(P) {} // Build the plain CFG and return its Top Region. VPRegionBlock *buildPlainCFG(); }; } // anonymous namespace // Return true if \p Inst is an incoming Instruction to be ignored in the VPlan // representation. static bool isInstructionToIgnore(Instruction *Inst) { return isa<BranchInst>(Inst); } // Set predecessors of \p VPBB in the same order as they are in \p BB. \p VPBB // must have no predecessors. void PlainCFGBuilder::setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB) { SmallVector<VPBlockBase *, 8> VPBBPreds; // Collect VPBB predecessors. for (BasicBlock *Pred : predecessors(BB)) VPBBPreds.push_back(getOrCreateVPBB(Pred)); VPBB->setPredecessors(VPBBPreds); } // Add operands to VPInstructions representing phi nodes from the input IR. void PlainCFGBuilder::fixPhiNodes() { for (auto *Phi : PhisToFix) { assert(IRDef2VPValue.count(Phi) && "Missing VPInstruction for PHINode."); VPValue *VPVal = IRDef2VPValue[Phi]; assert(isa<VPInstruction>(VPVal) && "Expected VPInstruction for phi node."); auto *VPPhi = cast<VPInstruction>(VPVal); assert(VPPhi->getNumOperands() == 0 && "Expected VPInstruction with no operands."); for (Value *Op : Phi->operands()) VPPhi->addOperand(getOrCreateVPOperand(Op)); } } // Create a new empty VPBasicBlock for an incoming BasicBlock or retrieve an // existing one if it was already created. VPBasicBlock *PlainCFGBuilder::getOrCreateVPBB(BasicBlock *BB) { auto BlockIt = BB2VPBB.find(BB); if (BlockIt != BB2VPBB.end()) // Retrieve existing VPBB. return BlockIt->second; // Create new VPBB. LLVM_DEBUG(dbgs() << "Creating VPBasicBlock for " << BB->getName() << "\n"); VPBasicBlock *VPBB = new VPBasicBlock(BB->getName()); BB2VPBB[BB] = VPBB; VPBB->setParent(TopRegion); return VPBB; } // Return true if \p Val is considered an external definition. An external // definition is either: // 1. A Value that is not an Instruction. This will be refined in the future. // 2. An Instruction that is outside of the CFG snippet represented in VPlan, // i.e., is not part of: a) the loop nest, b) outermost loop PH and, c) // outermost loop exits. bool PlainCFGBuilder::isExternalDef(Value *Val) { // All the Values that are not Instructions are considered external // definitions for now. Instruction *Inst = dyn_cast<Instruction>(Val); if (!Inst) return true; BasicBlock *InstParent = Inst->getParent(); assert(InstParent && "Expected instruction parent."); // Check whether Instruction definition is in loop PH. BasicBlock *PH = TheLoop->getLoopPreheader(); assert(PH && "Expected loop pre-header."); if (InstParent == PH) // Instruction definition is in outermost loop PH. return false; // Check whether Instruction definition is in the loop exit. BasicBlock *Exit = TheLoop->getUniqueExitBlock(); assert(Exit && "Expected loop with single exit."); if (InstParent == Exit) { // Instruction definition is in outermost loop exit. return false; } // Check whether Instruction definition is in loop body. return !TheLoop->contains(Inst); } // Create a new VPValue or retrieve an existing one for the Instruction's // operand \p IRVal. This function must only be used to create/retrieve VPValues // for *Instruction's operands* and not to create regular VPInstruction's. For // the latter, please, look at 'createVPInstructionsForVPBB'. VPValue *PlainCFGBuilder::getOrCreateVPOperand(Value *IRVal) { auto VPValIt = IRDef2VPValue.find(IRVal); if (VPValIt != IRDef2VPValue.end()) // Operand has an associated VPInstruction or VPValue that was previously // created. return VPValIt->second; // Operand doesn't have a previously created VPInstruction/VPValue. This // means that operand is: // A) a definition external to VPlan, // B) any other Value without specific representation in VPlan. // For now, we use VPValue to represent A and B and classify both as external // definitions. We may introduce specific VPValue subclasses for them in the // future. assert(isExternalDef(IRVal) && "Expected external definition as operand."); // A and B: Create VPValue and add it to the pool of external definitions and // to the Value->VPValue map. VPValue *NewVPVal = new VPValue(IRVal); Plan.addExternalDef(NewVPVal); IRDef2VPValue[IRVal] = NewVPVal; return NewVPVal; } // Create new VPInstructions in a VPBasicBlock, given its BasicBlock // counterpart. This function must be invoked in RPO so that the operands of a // VPInstruction in \p BB have been visited before (except for Phi nodes). void PlainCFGBuilder::createVPInstructionsForVPBB(VPBasicBlock *VPBB, BasicBlock *BB) { VPIRBuilder.setInsertPoint(VPBB); for (Instruction &InstRef : *BB) { Instruction *Inst = &InstRef; if (isInstructionToIgnore(Inst)) continue; // There should't be any VPValue for Inst at this point. Otherwise, we // visited Inst when we shouldn't, breaking the RPO traversal order. assert(!IRDef2VPValue.count(Inst) && "Instruction shouldn't have been visited."); VPInstruction *NewVPInst; if (PHINode *Phi = dyn_cast<PHINode>(Inst)) { // Phi node's operands may have not been visited at this point. We create // an empty VPInstruction that we will fix once the whole plain CFG has // been built. NewVPInst = cast<VPInstruction>(VPIRBuilder.createNaryOp( Inst->getOpcode(), {} /*No operands*/, Inst)); PhisToFix.push_back(Phi); } else { // Translate LLVM-IR operands into VPValue operands and set them in the // new VPInstruction. SmallVector<VPValue *, 4> VPOperands; for (Value *Op : Inst->operands()) VPOperands.push_back(getOrCreateVPOperand(Op)); // Build VPInstruction for any arbitraty Instruction without specific // representation in VPlan. NewVPInst = cast<VPInstruction>( VPIRBuilder.createNaryOp(Inst->getOpcode(), VPOperands, Inst)); } IRDef2VPValue[Inst] = NewVPInst; } } // Main interface to build the plain CFG. VPRegionBlock *PlainCFGBuilder::buildPlainCFG() { // 1. Create the Top Region. It will be the parent of all VPBBs. TopRegion = new VPRegionBlock("TopRegion", false /*isReplicator*/); // 2. Scan the body of the loop in a topological order to visit each basic // block after having visited its predecessor basic blocks. Create a VPBB for // each BB and link it to its successor and predecessor VPBBs. Note that // predecessors must be set in the same order as they are in the incomming IR. // Otherwise, there might be problems with existing phi nodes and algorithm // based on predecessors traversal. // Loop PH needs to be explicitly visited since it's not taken into account by // LoopBlocksDFS. BasicBlock *PreheaderBB = TheLoop->getLoopPreheader(); assert((PreheaderBB->getTerminator()->getNumSuccessors() == 1) && "Unexpected loop preheader"); VPBasicBlock *PreheaderVPBB = getOrCreateVPBB(PreheaderBB); createVPInstructionsForVPBB(PreheaderVPBB, PreheaderBB); // Create empty VPBB for Loop H so that we can link PH->H. VPBlockBase *HeaderVPBB = getOrCreateVPBB(TheLoop->getHeader()); // Preheader's predecessors will be set during the loop RPO traversal below. PreheaderVPBB->setOneSuccessor(HeaderVPBB); LoopBlocksRPO RPO(TheLoop); RPO.perform(LI); for (BasicBlock *BB : RPO) { // Create or retrieve the VPBasicBlock for this BB and create its // VPInstructions. VPBasicBlock *VPBB = getOrCreateVPBB(BB); createVPInstructionsForVPBB(VPBB, BB); // Set VPBB successors. We create empty VPBBs for successors if they don't // exist already. Recipes will be created when the successor is visited // during the RPO traversal. TerminatorInst *TI = BB->getTerminator(); assert(TI && "Terminator expected."); unsigned NumSuccs = TI->getNumSuccessors(); if (NumSuccs == 1) { VPBasicBlock *SuccVPBB = getOrCreateVPBB(TI->getSuccessor(0)); assert(SuccVPBB && "VPBB Successor not found."); VPBB->setOneSuccessor(SuccVPBB); } else if (NumSuccs == 2) { VPBasicBlock *SuccVPBB0 = getOrCreateVPBB(TI->getSuccessor(0)); assert(SuccVPBB0 && "Successor 0 not found."); VPBasicBlock *SuccVPBB1 = getOrCreateVPBB(TI->getSuccessor(1)); assert(SuccVPBB1 && "Successor 1 not found."); VPBB->setTwoSuccessors(SuccVPBB0, SuccVPBB1); } else llvm_unreachable("Number of successors not supported."); // Set VPBB predecessors in the same order as they are in the incoming BB. setVPBBPredsFromBB(VPBB, BB); } // 3. Process outermost loop exit. We created an empty VPBB for the loop // single exit BB during the RPO traversal of the loop body but Instructions // weren't visited because it's not part of the the loop. BasicBlock *LoopExitBB = TheLoop->getUniqueExitBlock(); assert(LoopExitBB && "Loops with multiple exits are not supported."); VPBasicBlock *LoopExitVPBB = BB2VPBB[LoopExitBB]; createVPInstructionsForVPBB(LoopExitVPBB, LoopExitBB); // Loop exit was already set as successor of the loop exiting BB. // We only set its predecessor VPBB now. setVPBBPredsFromBB(LoopExitVPBB, LoopExitBB); // 4. The whole CFG has been built at this point so all the input Values must // have a VPlan couterpart. Fix VPlan phi nodes by adding their corresponding // VPlan operands. fixPhiNodes(); // 5. Final Top Region setup. Set outermost loop pre-header and single exit as // Top Region entry and exit. TopRegion->setEntry(PreheaderVPBB); TopRegion->setExit(LoopExitVPBB); return TopRegion; } // Public interface to build a H-CFG. void VPlanHCFGBuilder::buildHierarchicalCFG(VPlan &Plan) { // Build Top Region enclosing the plain CFG and set it as VPlan entry. PlainCFGBuilder PCFGBuilder(TheLoop, LI, Plan); VPRegionBlock *TopRegion = PCFGBuilder.buildPlainCFG(); Plan.setEntry(TopRegion); LLVM_DEBUG(Plan.setName("HCFGBuilder: Plain CFG\n"); dbgs() << Plan); Verifier.verifyHierarchicalCFG(TopRegion); } <|endoftext|>
<commit_before><commit_msg>Yet another Ex28 commit<commit_after><|endoftext|>
<commit_before>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bohrium 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 Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <bh.h> #include <stdio.h> using namespace std; typedef vector<bh_instruction> ilist; typedef ilist::iterator ilist_iter; void filter(bh_ir &bhir) { for(ilist_iter it = bhir.instr_list.begin(); it!=bhir.instr_list.end(); ++it) { bh_instruction& instr = *it; switch(instr.opcode) { case BH_ADD_REDUCE: case BH_MULTIPLY_REDUCE: case BH_MINIMUM_REDUCE: case BH_MAXIMUM_REDUCE: case BH_LOGICAL_AND_REDUCE: case BH_BITWISE_AND_REDUCE: case BH_LOGICAL_OR_REDUCE: case BH_BITWISE_OR_REDUCE: case BH_LOGICAL_XOR_REDUCE: case BH_BITWISE_XOR_REDUCE: printf("Reduction..."); break; case BH_FREE: printf("Free..."); break; case BH_DISCARD: printf("Discard..."); break; default: printf("Something else."); break; } } } <commit_msg>filter-complete-reduction: First draft of the filter.<commit_after>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bohrium 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 Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <bh.h> #include <stdio.h> using namespace std; typedef vector<bh_instruction> ilist; typedef ilist::iterator ilist_iter; void rewrite_chain(vector<bh_instruction*>& links, bh_instruction* first, bh_instruction* last) { // Rewrite the first reduction as a "COMPLETE" REDUCE. // Copy the meta-data of the SCALAR output from the last REDUCE first->operand[0] = last->operand[0]; // Set the last reduction to NONE, it no longer needs execution. last->opcode = BH_NONE; // Set all the instructions "links" in the chain as BH_NONE // they no longer need execution. for(vector<bh_instruction*>::iterator rit=links.begin(); rit!=links.end(); ++rit) { bh_instruction& rinstr = **rit; rinstr.opcode = BH_NONE; } } void filter(bh_ir &bhir) { bh_base* reduce_output = NULL; bh_opcode reduce_opcode = BH_NONE; bh_instruction* first; bh_instruction* last; vector<bh_instruction*> links; // Instructions in the chain that are not, // the first and the last reduction. for(ilist_iter it = bhir.instr_list.begin(); it!=bhir.instr_list.end(); ++it) { bh_instruction& instr = *it; // Find the "first" reduction in a reduction chain. if ((reduce_output == NULL) and \ (bh_opcode_is_reduction(instr.opcode))) { reduce_output = instr.operand[0].base; reduce_opcode = instr.opcode; first = &instr; printf("Beginning the chain...\n"); // A potential continuation of the chain } else if ( (reduce_output != NULL) and \ (reduce_opcode == instr.opcode) and \ (reduce_output == instr.operand[1].base)) { bool other_use=false, gets_freed=false, gets_discarded=false; for(ilist_iter rit(it+1); rit!=bhir.instr_list.end(); ++rit) { bh_instruction& other_instr = *rit; switch(other_instr.opcode) { case BH_FREE: if (other_instr.operand[0].base == reduce_output) { gets_freed = true; links.push_back(&other_instr); } break; case BH_DISCARD: if (other_instr.operand[0].base == reduce_output) { gets_discarded = true; links.push_back(&other_instr); } break; default: for(int oidx=0; oidx<bh_operands(other_instr.opcode); ++oidx) { if (bh_is_constant(&other_instr.operand[oidx])) { continue; } if (other_instr.operand[oidx].base == reduce_output) { other_use = true; } } break; } // Can stop looking further if it gets used by something else // or if it gets freed and discarded. if (other_use or (gets_freed and gets_discarded)) { break; } } bool is_continuation = gets_freed and gets_discarded and not other_use; bool is_scalar = (instr.operand[0].ndim == 1) and (instr.operand[0].shape[0] == 1); reduce_output = instr.operand[0].base; if (is_continuation and is_scalar) { // End of the chain printf("Ending the chain and REWRITE as COMPLETE REDUCE\n"); last = &instr; rewrite_chain(links, first, last); } else if (is_continuation and not is_scalar) { // Continuation printf("Continuing the chain...\n"); links.push_back(&instr); } else { // Break the chain. printf("Break the chain.\n"); } if (not is_continuation or is_scalar) { // Reset the search printf("Resetting search.\n"); reduce_output = NULL; reduce_opcode = BH_NONE; links.clear(); } // A break } else if (reduce_output != NULL) { reduce_output = NULL; reduce_opcode = BH_NONE; links.clear(); printf("Breaking the chain...\n"); } } } <|endoftext|>
<commit_before>#include "filefilteritems.h" #include <qdebug.h> namespace QmlProjectManager { FileFilterBaseItem::FileFilterBaseItem(QObject *parent) : QmlProjectContentItem(parent), m_recursive(false) { connect(&m_fsWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(updateFileList())); connect(&m_fsWatcher, SIGNAL(fileChanged(QString)), this, SLOT(updateFileList())); } QString FileFilterBaseItem::directory() const { return m_rootDir; } void FileFilterBaseItem::setDirectory(const QString &dirPath) { if (m_rootDir == dirPath) return; m_rootDir = dirPath; emit directoryChanged(); updateFileList(); } void FileFilterBaseItem::setDefaultDirectory(const QString &dirPath) { if (m_defaultDir == dirPath) return; m_defaultDir = dirPath; updateFileList(); } QString FileFilterBaseItem::filter() const { return m_filter; } void FileFilterBaseItem::setFilter(const QString &filter) { if (filter == m_filter) return; m_filter = filter; m_regex.setPattern(m_filter); m_regex.setPatternSyntax(QRegExp::Wildcard); emit filterChanged(); updateFileList(); } bool FileFilterBaseItem::recursive() const { return m_recursive; } void FileFilterBaseItem::setRecursive(bool recursive) { if (recursive == m_recursive) return; m_recursive = recursive; updateFileList(); } QStringList FileFilterBaseItem::files() const { return m_files.toList(); } QString FileFilterBaseItem::absoluteDir() const { QString absoluteDir; if (QFileInfo(m_rootDir).isAbsolute()) { absoluteDir = m_rootDir; } else if (!m_defaultDir.isEmpty()) { absoluteDir = m_defaultDir + QLatin1Char('/') + m_rootDir; } return absoluteDir; } void FileFilterBaseItem::updateFileList() { const QString projectDir = absoluteDir(); if (projectDir.isEmpty()) return; QSet<QString> dirsToBeWatched; const QSet<QString> newFiles = filesInSubTree(QDir(m_defaultDir), QDir(projectDir), &dirsToBeWatched); if (newFiles != m_files) { // update watched files const QSet<QString> unwatchFiles = QSet<QString>(m_files - newFiles); const QSet<QString> watchFiles = QSet<QString>(newFiles - m_files); if (!unwatchFiles.isEmpty()) m_fsWatcher.removePaths(unwatchFiles.toList()); if (!watchFiles.isEmpty()) m_fsWatcher.addPaths(QSet<QString>(newFiles - m_files).toList()); m_files = newFiles; emit filesChanged(); } // update watched directories const QSet<QString> watchedDirectories = m_fsWatcher.directories().toSet(); const QSet<QString> unwatchDirs = watchedDirectories - dirsToBeWatched; const QSet<QString> watchDirs = dirsToBeWatched - watchedDirectories; if (!unwatchDirs.isEmpty()) m_fsWatcher.removePaths(unwatchDirs.toList()); if (!watchDirs.isEmpty()) m_fsWatcher.addPaths(watchDirs.toList()); } QSet<QString> FileFilterBaseItem::filesInSubTree(const QDir &rootDir, const QDir &dir, QSet<QString> *parsedDirs) { QSet<QString> fileSet; if (parsedDirs) parsedDirs->insert(dir.absolutePath()); foreach (const QFileInfo &file, dir.entryInfoList(QDir::Files)) { if (m_regex.exactMatch(file.fileName())) { fileSet.insert(file.absoluteFilePath()); } } if (m_recursive) { foreach (const QFileInfo &subDir, dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot)) { fileSet += filesInSubTree(rootDir, QDir(subDir.absoluteFilePath())); } } return fileSet; } QmlFileFilterItem::QmlFileFilterItem(QObject *parent) : FileFilterBaseItem(parent) { setFilter(QLatin1String("*.qml")); } } // namespace QmlProjectManager QML_DEFINE_TYPE(QmlProject,1,0,QmlFiles,QmlProjectManager::QmlFileFilterItem) <commit_msg>Also watch sub-directories for changes<commit_after>#include "filefilteritems.h" #include <qdebug.h> namespace QmlProjectManager { FileFilterBaseItem::FileFilterBaseItem(QObject *parent) : QmlProjectContentItem(parent), m_recursive(false) { connect(&m_fsWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(updateFileList())); connect(&m_fsWatcher, SIGNAL(fileChanged(QString)), this, SLOT(updateFileList())); } QString FileFilterBaseItem::directory() const { return m_rootDir; } void FileFilterBaseItem::setDirectory(const QString &dirPath) { if (m_rootDir == dirPath) return; m_rootDir = dirPath; emit directoryChanged(); updateFileList(); } void FileFilterBaseItem::setDefaultDirectory(const QString &dirPath) { if (m_defaultDir == dirPath) return; m_defaultDir = dirPath; updateFileList(); } QString FileFilterBaseItem::filter() const { return m_filter; } void FileFilterBaseItem::setFilter(const QString &filter) { if (filter == m_filter) return; m_filter = filter; m_regex.setPattern(m_filter); m_regex.setPatternSyntax(QRegExp::Wildcard); emit filterChanged(); updateFileList(); } bool FileFilterBaseItem::recursive() const { return m_recursive; } void FileFilterBaseItem::setRecursive(bool recursive) { if (recursive == m_recursive) return; m_recursive = recursive; updateFileList(); } QStringList FileFilterBaseItem::files() const { return m_files.toList(); } QString FileFilterBaseItem::absoluteDir() const { QString absoluteDir; if (QFileInfo(m_rootDir).isAbsolute()) { absoluteDir = m_rootDir; } else if (!m_defaultDir.isEmpty()) { absoluteDir = m_defaultDir + QLatin1Char('/') + m_rootDir; } return absoluteDir; } void FileFilterBaseItem::updateFileList() { const QString projectDir = absoluteDir(); if (projectDir.isEmpty()) return; QSet<QString> dirsToBeWatched; const QSet<QString> newFiles = filesInSubTree(QDir(m_defaultDir), QDir(projectDir), &dirsToBeWatched); if (newFiles != m_files) { // update watched files const QSet<QString> unwatchFiles = QSet<QString>(m_files - newFiles); const QSet<QString> watchFiles = QSet<QString>(newFiles - m_files); if (!unwatchFiles.isEmpty()) m_fsWatcher.removePaths(unwatchFiles.toList()); if (!watchFiles.isEmpty()) m_fsWatcher.addPaths(QSet<QString>(newFiles - m_files).toList()); m_files = newFiles; emit filesChanged(); } // update watched directories const QSet<QString> watchedDirectories = m_fsWatcher.directories().toSet(); const QSet<QString> unwatchDirs = watchedDirectories - dirsToBeWatched; const QSet<QString> watchDirs = dirsToBeWatched - watchedDirectories; if (!unwatchDirs.isEmpty()) m_fsWatcher.removePaths(unwatchDirs.toList()); if (!watchDirs.isEmpty()) m_fsWatcher.addPaths(watchDirs.toList()); } QSet<QString> FileFilterBaseItem::filesInSubTree(const QDir &rootDir, const QDir &dir, QSet<QString> *parsedDirs) { QSet<QString> fileSet; if (parsedDirs) parsedDirs->insert(dir.absolutePath()); foreach (const QFileInfo &file, dir.entryInfoList(QDir::Files)) { if (m_regex.exactMatch(file.fileName())) { fileSet.insert(file.absoluteFilePath()); } } if (m_recursive) { foreach (const QFileInfo &subDir, dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot)) { fileSet += filesInSubTree(rootDir, QDir(subDir.absoluteFilePath()), parsedDirs); } } return fileSet; } QmlFileFilterItem::QmlFileFilterItem(QObject *parent) : FileFilterBaseItem(parent) { setFilter(QLatin1String("*.qml")); } } // namespace QmlProjectManager QML_DEFINE_TYPE(QmlProject,1,0,QmlFiles,QmlProjectManager::QmlFileFilterItem) <|endoftext|>
<commit_before>/* * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "Spell.h" #include "zulgurub.h" /* * @todo * - Fix timers (research some more) */ enum Says { SAY_VENOXIS_TRANSFORM = 1, // Let the coils of hate unfurl! SAY_VENOXIS_DEATH = 2 // Ssserenity.. at lassst! }; enum Spells { // troll form SPELL_THRASH = 3391, SPELL_DISPEL_MAGIC = 23859, SPELL_RENEW = 23895, SPELL_HOLY_NOVA = 23858, SPELL_HOLY_FIRE = 23860, SPELL_HOLY_WRATH = 23979, // snake form SPELL_POISON_CLOUD = 23861, SPELL_VENOM_SPIT = 23862, SPELL_PARASITIC_SERPENT = 23865, SPELL_SUMMON_PARASITIC_SERPENT = 23866, SPELL_PARASITIC_SERPENT_TRIGGER = 23867, // used when swapping event-stages SPELL_VENOXIS_TRANSFORM = 23849, // 50% health - shapechange to cobra SPELL_FRENZY = 8269, // 20% health - frenzy SPELL_POISON = 24097 }; enum Events { // troll form EVENT_THRASH = 1, EVENT_DISPEL_MAGIC = 2, EVENT_RENEW = 3, EVENT_HOLY_NOVA = 4, EVENT_HOLY_FIRE = 5, EVENT_HOLY_WRATH = 6, // phase-changing EVENT_TRANSFORM = 7, // snake form events EVENT_POISON_CLOUD = 8, EVENT_VENOM_SPIT = 9, EVENT_PARASITIC_SERPENT = 10, EVENT_FRENZY = 11, EVENT_POISON }; enum Phases { PHASE_ONE = 1, // troll form PHASE_TWO = 2 // snake form }; enum NPCs { NPC_PARASITIC_SERPENT = 14884, NPC_RAZZASHI_COBRA = 11373, BOSS_VENOXIS = 14507 }; class boss_venoxis : public CreatureScript { public: boss_venoxis() : CreatureScript("boss_venoxis") { } struct boss_venoxisAI : public BossAI { boss_venoxisAI(Creature* creature) : BossAI(creature, DATA_VENOXIS) { } void Reset() override { _Reset(); // remove all spells and auras from previous attempts me->RemoveAllAuras(); me->SetReactState(REACT_PASSIVE); // set some internally used variables to their defaults _inMeleeRange = 0; _transformed = false; _frenzied = false; events.SetPhase(PHASE_ONE); SpawnCobras(); } void JustDied(Unit* /*killer*/) override { _JustDied(); Talk(SAY_VENOXIS_DEATH); me->RemoveAllAuras(); } void SpawnCobras() { me->SummonCreature(NPC_RAZZASHI_COBRA, -12021.20f, -1719.73f, 39.34f, 0.85f, TEMPSUMMON_CORPSE_DESPAWN); me->SummonCreature(NPC_RAZZASHI_COBRA, -12029.40f, -1714.54f, 39.36f, 0.68f, TEMPSUMMON_CORPSE_DESPAWN); me->SummonCreature(NPC_RAZZASHI_COBRA, -12036.79f, -1704.27f, 40.06f, 0.45f, TEMPSUMMON_CORPSE_DESPAWN); me->SummonCreature(NPC_RAZZASHI_COBRA, -12037.70f, -1694.20f, 39.35f, 0.27f, TEMPSUMMON_CORPSE_DESPAWN); } void SetCombatCombras() { std::list<Creature*> cobraList; me->GetCreatureListWithEntryInGrid(cobraList, NPC_RAZZASHI_COBRA, 50.0f); if (!cobraList.empty()) { for (auto cobras : cobraList) { cobras->SetInCombatWithZone(); } } } void EnterCombat(Unit* /*who*/) override { _EnterCombat(); me->SetReactState(REACT_AGGRESSIVE); // Always running events events.ScheduleEvent(EVENT_THRASH, 5000); // Phase one events (regular form) events.ScheduleEvent(EVENT_HOLY_NOVA, 5000, 0, PHASE_ONE); events.ScheduleEvent(EVENT_DISPEL_MAGIC, 35000, 0, PHASE_ONE); events.ScheduleEvent(EVENT_HOLY_FIRE, 10000, 0, PHASE_ONE); events.ScheduleEvent(EVENT_RENEW, 30000, 0, PHASE_ONE); events.ScheduleEvent(EVENT_HOLY_WRATH, 60000, 0, PHASE_ONE); events.SetPhase(PHASE_ONE); // Set zone in combat DoZoneInCombat(); SetCombatCombras(); } void DamageTaken(Unit*, uint32& /*damage*/, DamageEffectType, SpellSchoolMask) override { // check if venoxis is ready to transform if (!_transformed && !HealthAbovePct(50)) { _transformed = true; // schedule the event that changes our phase events.ScheduleEvent(EVENT_TRANSFORM, 100); } // we're losing health, bad, go frenzy else if (!_frenzied && !HealthAbovePct(20)) { _frenzied = true; events.ScheduleEvent(EVENT_FRENZY, 100); } } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); // return back to main code if we're still casting if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { // thrash is available in all phases case EVENT_THRASH: DoCast(me, SPELL_THRASH, true); events.ScheduleEvent(EVENT_THRASH, urand(10000, 20000)); break; // troll form spells and Actions (first part) case EVENT_DISPEL_MAGIC: DoCast(me, SPELL_DISPEL_MAGIC); events.ScheduleEvent(EVENT_DISPEL_MAGIC, urand(15000, 20000), 0, PHASE_ONE); break; case EVENT_RENEW: DoCast(me, SPELL_RENEW); events.ScheduleEvent(EVENT_RENEW, urand(25000, 30000), 0, PHASE_ONE); break; case EVENT_HOLY_NOVA: _inMeleeRange = 0; for (uint8 i = 0; i < 10; ++i) { if (Unit* target = SelectTarget(SelectTargetMethod::MaxThreat, i)) // check if target is within melee-distance if (me->IsWithinMeleeRange(target)) ++_inMeleeRange; } // trigger spellcast only if we have 3 or more targets to affect if (_inMeleeRange >= 3) DoCastVictim(SPELL_HOLY_NOVA); events.ScheduleEvent(EVENT_HOLY_NOVA, urand(45000, 75000), 0, PHASE_ONE); break; case EVENT_HOLY_FIRE: if (Unit* target = SelectTarget(SelectTargetMethod::Random)) DoCast(target, SPELL_HOLY_FIRE); events.ScheduleEvent(EVENT_HOLY_FIRE, urand(45000, 60000), 0, PHASE_ONE); break; case EVENT_HOLY_WRATH: if (Unit* target = SelectTarget(SelectTargetMethod::Random)) DoCast(target, SPELL_HOLY_WRATH); events.ScheduleEvent(EVENT_HOLY_WRATH, urand(45000, 60000), 0, PHASE_ONE); break; // // snake form spells and Actions // case EVENT_VENOM_SPIT: if (Unit* target = SelectTarget(SelectTargetMethod::Random)) DoCast(target, SPELL_VENOM_SPIT); events.ScheduleEvent(EVENT_VENOM_SPIT, urand(5000, 15000), 0, PHASE_TWO); break; case EVENT_POISON_CLOUD: if (Unit* target = SelectTarget(SelectTargetMethod::Random)) DoCast(target, SPELL_POISON_CLOUD); events.ScheduleEvent(EVENT_POISON_CLOUD, urand(15000, 20000), 0, PHASE_TWO); break; case EVENT_PARASITIC_SERPENT: if (Unit* target = SelectTarget(SelectTargetMethod::Random)) DoCast(target, SPELL_SUMMON_PARASITIC_SERPENT); events.ScheduleEvent(EVENT_PARASITIC_SERPENT, 15000, 0, PHASE_TWO); break; case EVENT_FRENZY: // frenzy at 20% health DoCast(me, SPELL_FRENZY, true); break; // // shape and phase-changing // case EVENT_TRANSFORM: // shapeshift at 50% health DoCast(me, SPELL_VENOXIS_TRANSFORM); Talk(SAY_VENOXIS_TRANSFORM); DoResetThreat(); // phase two events (snakeform) events.ScheduleEvent(EVENT_VENOM_SPIT, 5000, 0, PHASE_TWO); events.ScheduleEvent(EVENT_POISON_CLOUD, 10000, 0, PHASE_TWO); events.ScheduleEvent(EVENT_PARASITIC_SERPENT, 30000, 0, PHASE_TWO); // transformed, start phase two events.SetPhase(PHASE_TWO); break; default: break; } } DoMeleeAttackIfReady(); } private: uint8 _inMeleeRange; bool _transformed; bool _frenzied; }; CreatureAI* GetAI(Creature* creature) const override { return GetZulGurubAI<boss_venoxisAI>(creature); } }; class npc_razzashi_cobra_venoxis : public CreatureScript { public: npc_razzashi_cobra_venoxis() : CreatureScript("npc_razzashi_cobra_venoxis") {} struct npc_razzashi_cobra_venoxis_AI : public ScriptedAI { npc_razzashi_cobra_venoxis_AI(Creature* creature) : ScriptedAI(creature) {} EventMap events; void Reset() { events.Reset(); } void EnterCombat(Unit*) { events.ScheduleEvent(EVENT_POISON, 8 * IN_MILLISECONDS); if (Creature* Venoxis = GetVenoxis()) { Venoxis->SetInCombatWithZone(); } } Creature* GetVenoxis() { return me->FindNearestCreature(BOSS_VENOXIS, 200.0f, true); } void UpdateAI(uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_POISON: { me->CastSpell(me->GetVictim(), SPELL_POISON); events.ScheduleEvent(EVENT_POISON, 15 * IN_MILLISECONDS); break; } } } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return new npc_razzashi_cobra_venoxis_AI(creature); } }; void AddSC_boss_venoxis() { new boss_venoxis(); new npc_razzashi_cobra_venoxis(); } <commit_msg>fix(Scripts/ZulGurub): Venoxis - Holy wrath and Holy nova event (#12089)<commit_after>/* * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "Spell.h" #include "zulgurub.h" /* * @todo * - Fix timers (research some more) */ enum Says { SAY_VENOXIS_TRANSFORM = 1, // Let the coils of hate unfurl! SAY_VENOXIS_DEATH = 2 // Ssserenity.. at lassst! }; enum Spells { // troll form SPELL_THRASH = 3391, SPELL_DISPEL_MAGIC = 23859, SPELL_RENEW = 23895, SPELL_HOLY_NOVA = 23858, SPELL_HOLY_FIRE = 23860, SPELL_HOLY_WRATH = 23979, // snake form SPELL_POISON_CLOUD = 23861, SPELL_VENOM_SPIT = 23862, SPELL_PARASITIC_SERPENT = 23865, SPELL_SUMMON_PARASITIC_SERPENT = 23866, SPELL_PARASITIC_SERPENT_TRIGGER = 23867, // used when swapping event-stages SPELL_VENOXIS_TRANSFORM = 23849, // 50% health - shapechange to cobra SPELL_FRENZY = 8269, // 20% health - frenzy SPELL_POISON = 24097 }; enum Events { // troll form EVENT_THRASH = 1, EVENT_DISPEL_MAGIC = 2, EVENT_RENEW = 3, EVENT_HOLY_NOVA = 4, EVENT_HOLY_FIRE = 5, EVENT_HOLY_WRATH = 6, // phase-changing EVENT_TRANSFORM = 7, // snake form events EVENT_POISON_CLOUD = 8, EVENT_VENOM_SPIT = 9, EVENT_PARASITIC_SERPENT = 10, EVENT_FRENZY = 11, EVENT_POISON }; enum Phases { PHASE_ONE = 1, // troll form PHASE_TWO = 2 // snake form }; enum NPCs { NPC_PARASITIC_SERPENT = 14884, NPC_RAZZASHI_COBRA = 11373, BOSS_VENOXIS = 14507 }; class boss_venoxis : public CreatureScript { public: boss_venoxis() : CreatureScript("boss_venoxis") { } struct boss_venoxisAI : public BossAI { boss_venoxisAI(Creature* creature) : BossAI(creature, DATA_VENOXIS) { } void Reset() override { _Reset(); // remove all spells and auras from previous attempts me->RemoveAllAuras(); me->SetReactState(REACT_PASSIVE); // set some internally used variables to their defaults _inMeleeRange = 0; _transformed = false; _frenzied = false; events.SetPhase(PHASE_ONE); SpawnCobras(); } void JustDied(Unit* /*killer*/) override { _JustDied(); Talk(SAY_VENOXIS_DEATH); me->RemoveAllAuras(); } void SpawnCobras() { me->SummonCreature(NPC_RAZZASHI_COBRA, -12021.20f, -1719.73f, 39.34f, 0.85f, TEMPSUMMON_CORPSE_DESPAWN); me->SummonCreature(NPC_RAZZASHI_COBRA, -12029.40f, -1714.54f, 39.36f, 0.68f, TEMPSUMMON_CORPSE_DESPAWN); me->SummonCreature(NPC_RAZZASHI_COBRA, -12036.79f, -1704.27f, 40.06f, 0.45f, TEMPSUMMON_CORPSE_DESPAWN); me->SummonCreature(NPC_RAZZASHI_COBRA, -12037.70f, -1694.20f, 39.35f, 0.27f, TEMPSUMMON_CORPSE_DESPAWN); } void SetCombatCombras() { std::list<Creature*> cobraList; me->GetCreatureListWithEntryInGrid(cobraList, NPC_RAZZASHI_COBRA, 50.0f); if (!cobraList.empty()) { for (auto cobras : cobraList) { cobras->SetInCombatWithZone(); } } } void EnterCombat(Unit* /*who*/) override { _EnterCombat(); me->SetReactState(REACT_AGGRESSIVE); // Always running events events.ScheduleEvent(EVENT_THRASH, 5000); // Phase one events (regular form) events.ScheduleEvent(EVENT_HOLY_NOVA, urand(5000, 15000), 0, PHASE_ONE); events.ScheduleEvent(EVENT_DISPEL_MAGIC, 35000, 0, PHASE_ONE); events.ScheduleEvent(EVENT_HOLY_FIRE, urand(10000,20000), 0, PHASE_ONE); events.ScheduleEvent(EVENT_RENEW, 30000, 0, PHASE_ONE); events.ScheduleEvent(EVENT_HOLY_WRATH, urand(15000, 25000), 0, PHASE_ONE); events.SetPhase(PHASE_ONE); // Set zone in combat DoZoneInCombat(); SetCombatCombras(); } void DamageTaken(Unit*, uint32& /*damage*/, DamageEffectType, SpellSchoolMask) override { // check if venoxis is ready to transform if (!_transformed && !HealthAbovePct(50)) { _transformed = true; // schedule the event that changes our phase events.ScheduleEvent(EVENT_TRANSFORM, 100); } // we're losing health, bad, go frenzy else if (!_frenzied && !HealthAbovePct(20)) { _frenzied = true; events.ScheduleEvent(EVENT_FRENZY, 100); } } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); // return back to main code if we're still casting if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { // thrash is available in all phases case EVENT_THRASH: DoCast(me, SPELL_THRASH, true); events.ScheduleEvent(EVENT_THRASH, urand(10000, 20000)); break; // troll form spells and Actions (first part) case EVENT_DISPEL_MAGIC: DoCast(me, SPELL_DISPEL_MAGIC); events.ScheduleEvent(EVENT_DISPEL_MAGIC, urand(15000, 20000), 0, PHASE_ONE); break; case EVENT_RENEW: DoCast(me, SPELL_RENEW); events.ScheduleEvent(EVENT_RENEW, urand(25000, 30000), 0, PHASE_ONE); break; case EVENT_HOLY_WRATH: if (Unit* target = SelectTarget(SelectTargetMethod::MaxThreat)) DoCast(target, SPELL_HOLY_WRATH); events.ScheduleEvent(EVENT_HOLY_WRATH, urand(12000, 22000), 0, PHASE_ONE); break; case EVENT_HOLY_FIRE: if (Unit* target = SelectTarget(SelectTargetMethod::Random)) DoCast(target, SPELL_HOLY_FIRE); events.ScheduleEvent(EVENT_HOLY_FIRE, urand(10000, 24000), 0, PHASE_ONE); break; case EVENT_HOLY_NOVA: DoCastSelf(SPELL_HOLY_NOVA); events.ScheduleEvent(EVENT_HOLY_NOVA, urand(10000, 24000), 0, PHASE_ONE); break; // // snake form spells and Actions // case EVENT_VENOM_SPIT: if (Unit* target = SelectTarget(SelectTargetMethod::Random)) DoCast(target, SPELL_VENOM_SPIT); events.ScheduleEvent(EVENT_VENOM_SPIT, urand(5000, 15000), 0, PHASE_TWO); break; case EVENT_POISON_CLOUD: if (Unit* target = SelectTarget(SelectTargetMethod::Random)) DoCast(target, SPELL_POISON_CLOUD); events.ScheduleEvent(EVENT_POISON_CLOUD, urand(15000, 20000), 0, PHASE_TWO); break; case EVENT_PARASITIC_SERPENT: if (Unit* target = SelectTarget(SelectTargetMethod::Random)) DoCast(target, SPELL_SUMMON_PARASITIC_SERPENT); events.ScheduleEvent(EVENT_PARASITIC_SERPENT, 15000, 0, PHASE_TWO); break; case EVENT_FRENZY: // frenzy at 20% health DoCast(me, SPELL_FRENZY, true); break; // // shape and phase-changing // case EVENT_TRANSFORM: // shapeshift at 50% health DoCast(me, SPELL_VENOXIS_TRANSFORM); Talk(SAY_VENOXIS_TRANSFORM); DoResetThreat(); // phase two events (snakeform) events.ScheduleEvent(EVENT_VENOM_SPIT, 5000, 0, PHASE_TWO); events.ScheduleEvent(EVENT_POISON_CLOUD, 10000, 0, PHASE_TWO); events.ScheduleEvent(EVENT_PARASITIC_SERPENT, 30000, 0, PHASE_TWO); // transformed, start phase two events.SetPhase(PHASE_TWO); break; default: break; } } DoMeleeAttackIfReady(); } private: uint8 _inMeleeRange; bool _transformed; bool _frenzied; }; CreatureAI* GetAI(Creature* creature) const override { return GetZulGurubAI<boss_venoxisAI>(creature); } }; class npc_razzashi_cobra_venoxis : public CreatureScript { public: npc_razzashi_cobra_venoxis() : CreatureScript("npc_razzashi_cobra_venoxis") {} struct npc_razzashi_cobra_venoxis_AI : public ScriptedAI { npc_razzashi_cobra_venoxis_AI(Creature* creature) : ScriptedAI(creature) {} EventMap events; void Reset() { events.Reset(); } void EnterCombat(Unit*) { events.ScheduleEvent(EVENT_POISON, 8 * IN_MILLISECONDS); if (Creature* Venoxis = GetVenoxis()) { Venoxis->SetInCombatWithZone(); } } Creature* GetVenoxis() { return me->FindNearestCreature(BOSS_VENOXIS, 200.0f, true); } void UpdateAI(uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_POISON: { me->CastSpell(me->GetVictim(), SPELL_POISON); events.ScheduleEvent(EVENT_POISON, 15 * IN_MILLISECONDS); break; } } } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return new npc_razzashi_cobra_venoxis_AI(creature); } }; void AddSC_boss_venoxis() { new boss_venoxis(); new npc_razzashi_cobra_venoxis(); } <|endoftext|>
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/log/log.h> LOG_SETUP("generation_handler_stress_test"); #include <vespa/vespalib/gtest/gtest.h> #include <vespa/vespalib/util/generationhandler.h> #include <vespa/vespalib/util/lambdatask.h> #include <vespa/vespalib/util/threadstackexecutor.h> #include <vespa/vespalib/util/size_literals.h> #include <thread> using vespalib::Executor; using vespalib::GenerationHandler; using vespalib::makeLambdaTask; using vespalib::ThreadStackExecutor; namespace { bool smoke_test = false; const vespalib::string smoke_test_option = "--smoke-test"; } struct WorkContext { std::atomic<uint64_t> _generation; WorkContext() noexcept : _generation(0) { } }; struct IndirectContext { std::atomic<uint64_t *> _value_ptr; char _pad[256]; static constexpr size_t values_size = 65536; uint64_t _values[values_size]; IndirectContext(); uint64_t* calc_value_ptr(uint64_t idx) { return &_values[(idx & (values_size - 1))]; } }; IndirectContext::IndirectContext() : _value_ptr(nullptr), _pad(), _values() { _value_ptr = &_values[0]; } class Fixture : public ::testing::Test { protected: GenerationHandler _generationHandler; uint32_t _readThreads; ThreadStackExecutor _writer; // 1 write thread std::unique_ptr<ThreadStackExecutor> _readers; // multiple reader threads std::atomic<long> _readSeed; std::atomic<long> _doneWriteWork; std::atomic<long> _doneReadWork; std::atomic<bool> _stopRead; bool _reportWork; Fixture(); ~Fixture(); void set_read_threads(uint32_t read_threads); uint32_t getReadThreads() const { return _readThreads; } void stressTest(uint32_t writeCnt); void stress_test_indirect(uint64_t write_cnt); public: void readWork(const WorkContext &context); void writeWork(uint32_t cnt, WorkContext &context); void read_indirect_work(const IndirectContext& context); void write_indirect_work(uint64_t cnt, IndirectContext& context); private: Fixture(const Fixture &index) = delete; Fixture(Fixture &&index) = delete; Fixture &operator=(const Fixture &index) = delete; Fixture &operator=(Fixture &&index) = delete; }; Fixture::Fixture() : ::testing::Test(), _generationHandler(), _readThreads(1), _writer(1, 128_Ki), _readers(), _doneWriteWork(0), _doneReadWork(0), _stopRead(false), _reportWork(false) { set_read_threads(1); } Fixture::~Fixture() { if (_readers) { _readers->sync(); _readers->shutdown(); } _writer.sync(); _writer.shutdown(); if (_reportWork) { LOG(info, "readWork=%ld, writeWork=%ld", _doneReadWork.load(), _doneWriteWork.load()); } } void Fixture::set_read_threads(uint32_t read_threads) { if (_readers) { _readers->sync(); _readers->shutdown(); } _readThreads = read_threads; _readers = std::make_unique<ThreadStackExecutor>(read_threads, 128_Ki); } void Fixture::readWork(const WorkContext &context) { uint32_t i; uint32_t cnt = std::numeric_limits<uint32_t>::max(); for (i = 0; i < cnt && !_stopRead.load(); ++i) { auto guard = _generationHandler.takeGuard(); auto generation = context._generation.load(std::memory_order_relaxed); EXPECT_GE(generation, guard.getGeneration()); } _doneReadWork += i; LOG(info, "done %u read work", i); } void Fixture::writeWork(uint32_t cnt, WorkContext &context) { for (uint32_t i = 0; i < cnt; ++i) { context._generation.store(_generationHandler.getNextGeneration(), std::memory_order_relaxed); _generationHandler.incGeneration(); } _doneWriteWork += cnt; _stopRead = true; LOG(info, "done %u write work", cnt); } namespace { class ReadWorkTask : public vespalib::Executor::Task { Fixture &_f; std::shared_ptr<WorkContext> _context; public: ReadWorkTask(Fixture &f, std::shared_ptr<WorkContext> context) : _f(f), _context(context) { } virtual void run() override { _f.readWork(*_context); } }; class WriteWorkTask : public vespalib::Executor::Task { Fixture &_f; uint32_t _cnt; std::shared_ptr<WorkContext> _context; public: WriteWorkTask(Fixture &f, uint32_t cnt, std::shared_ptr<WorkContext> context) : _f(f), _cnt(cnt), _context(context) { } virtual void run() override { _f.writeWork(_cnt, *_context); } }; } void Fixture::stressTest(uint32_t writeCnt) { _reportWork = true; uint32_t readThreads = getReadThreads(); LOG(info, "starting stress test, 1 write thread, %u read threads, %u writes", readThreads, writeCnt); auto context = std::make_shared<WorkContext>(); _writer.execute(std::make_unique<WriteWorkTask>(*this, writeCnt, context)); for (uint32_t i = 0; i < readThreads; ++i) { _readers->execute(std::make_unique<ReadWorkTask>(*this, context)); } _writer.sync(); _readers->sync(); } void Fixture::read_indirect_work(const IndirectContext& context) { uint64_t i; uint64_t cnt = std::numeric_limits<uint32_t>::max(); uint64_t old_value = 0; for (i = 0; i < cnt && !_stopRead.load(); ++i) { auto guard = _generationHandler.takeGuard(); // Data referenced by pointer is protected by guard auto v_ptr = context._value_ptr.load(std::memory_order_acquire); EXPECT_GE(*v_ptr, old_value); old_value = *v_ptr; } _doneReadWork += i; LOG(info, "done %" PRIu64 " read work", i); } void Fixture::write_indirect_work(uint64_t cnt, IndirectContext& context) { uint32_t sleep_cnt = 0; ASSERT_EQ(0, _generationHandler.getCurrentGeneration()); auto oldest_gen = _generationHandler.getFirstUsedGeneration(); for (uint64_t i = 0; i < cnt; ++i) { auto gen = _generationHandler.getCurrentGeneration(); // Hold data for gen, write new data for next_gen auto next_gen = gen + 1; auto *v_ptr = context.calc_value_ptr(next_gen); ASSERT_EQ(0u, *v_ptr) << (_stopRead = true, ""); *v_ptr = next_gen; context._value_ptr.store(v_ptr, std::memory_order_release); _generationHandler.incGeneration(); auto first_used_gen = _generationHandler.getFirstUsedGeneration(); while (oldest_gen < first_used_gen) { // Clear data that readers should no longer have access to. *context.calc_value_ptr(oldest_gen) = 0; ++oldest_gen; } while ((next_gen - first_used_gen) >= context.values_size - 2) { // Sleep if writer gets too much ahead of readers. std::this_thread::sleep_for(1ms); ++sleep_cnt; _generationHandler.updateFirstUsedGeneration(); first_used_gen = _generationHandler.getFirstUsedGeneration(); } } _doneWriteWork += cnt; _stopRead = true; LOG(info, "done %" PRIu64 " write work, %u sleeps", cnt, sleep_cnt); } void Fixture::stress_test_indirect(uint64_t write_cnt) { _reportWork = true; uint32_t read_threads = getReadThreads(); LOG(info, "starting stress test indirect, 1 write thread, %u read threads, %" PRIu64 " writes", read_threads, write_cnt); auto context = std::make_shared<IndirectContext>(); _writer.execute(makeLambdaTask([this, context, write_cnt]() { write_indirect_work(write_cnt, *context); })); #if 1 for (uint32_t i = 0; i < read_threads; ++i) { _readers->execute(makeLambdaTask([this, context]() { read_indirect_work(*context); })); } #endif _writer.sync(); _readers->sync(); } using GenerationHandlerStressTest = Fixture; TEST_F(GenerationHandlerStressTest, stress_test_2_readers) { set_read_threads(2); stressTest(smoke_test ? 10000 : 1000000); } TEST_F(GenerationHandlerStressTest, stress_test_4_readers) { set_read_threads(4); stressTest(smoke_test ? 10000 : 1000000); } TEST_F(GenerationHandlerStressTest, stress_test_indirect_2_readers) { set_read_threads(2); stress_test_indirect(smoke_test ? 10000 : 1000000); } TEST_F(GenerationHandlerStressTest, stress_test_indirect_4_readers) { set_read_threads(4); stress_test_indirect(smoke_test ? 10000 : 1000000); } int main(int argc, char **argv) { if (argc > 1 && argv[1] == smoke_test_option) { smoke_test = true; ++argv; --argc; } ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Remove unneeded preprocessor directives. Make stopping of readers more robust.<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/log/log.h> LOG_SETUP("generation_handler_stress_test"); #include <vespa/vespalib/gtest/gtest.h> #include <vespa/vespalib/util/generationhandler.h> #include <vespa/vespalib/util/lambdatask.h> #include <vespa/vespalib/util/threadstackexecutor.h> #include <vespa/vespalib/util/size_literals.h> #include <thread> using vespalib::Executor; using vespalib::GenerationHandler; using vespalib::makeLambdaTask; using vespalib::ThreadStackExecutor; namespace { bool smoke_test = false; const vespalib::string smoke_test_option = "--smoke-test"; } class ReadStopper { std::atomic<bool> &_stop_read; public: ReadStopper(std::atomic<bool>& stop_read) : _stop_read(stop_read) { } ~ReadStopper() { _stop_read = true; } }; struct WorkContext { std::atomic<uint64_t> _generation; WorkContext() noexcept : _generation(0) { } }; struct IndirectContext { std::atomic<uint64_t *> _value_ptr; char _pad[256]; static constexpr size_t values_size = 65536; uint64_t _values[values_size]; IndirectContext(); uint64_t* calc_value_ptr(uint64_t idx) { return &_values[(idx & (values_size - 1))]; } }; IndirectContext::IndirectContext() : _value_ptr(nullptr), _pad(), _values() { _value_ptr = &_values[0]; } class Fixture : public ::testing::Test { protected: GenerationHandler _generationHandler; uint32_t _readThreads; ThreadStackExecutor _writer; // 1 write thread std::unique_ptr<ThreadStackExecutor> _readers; // multiple reader threads std::atomic<long> _readSeed; std::atomic<long> _doneWriteWork; std::atomic<long> _doneReadWork; std::atomic<bool> _stopRead; bool _reportWork; Fixture(); ~Fixture(); void set_read_threads(uint32_t read_threads); uint32_t getReadThreads() const { return _readThreads; } void stressTest(uint32_t writeCnt); void stress_test_indirect(uint64_t write_cnt); public: void readWork(const WorkContext &context); void writeWork(uint32_t cnt, WorkContext &context); void read_indirect_work(const IndirectContext& context); void write_indirect_work(uint64_t cnt, IndirectContext& context); private: Fixture(const Fixture &index) = delete; Fixture(Fixture &&index) = delete; Fixture &operator=(const Fixture &index) = delete; Fixture &operator=(Fixture &&index) = delete; }; Fixture::Fixture() : ::testing::Test(), _generationHandler(), _readThreads(1), _writer(1, 128_Ki), _readers(), _doneWriteWork(0), _doneReadWork(0), _stopRead(false), _reportWork(false) { set_read_threads(1); } Fixture::~Fixture() { if (_readers) { _readers->sync(); _readers->shutdown(); } _writer.sync(); _writer.shutdown(); if (_reportWork) { LOG(info, "readWork=%ld, writeWork=%ld", _doneReadWork.load(), _doneWriteWork.load()); } } void Fixture::set_read_threads(uint32_t read_threads) { if (_readers) { _readers->sync(); _readers->shutdown(); } _readThreads = read_threads; _readers = std::make_unique<ThreadStackExecutor>(read_threads, 128_Ki); } void Fixture::readWork(const WorkContext &context) { uint32_t i; uint32_t cnt = std::numeric_limits<uint32_t>::max(); for (i = 0; i < cnt && !_stopRead.load(); ++i) { auto guard = _generationHandler.takeGuard(); auto generation = context._generation.load(std::memory_order_relaxed); EXPECT_GE(generation, guard.getGeneration()); } _doneReadWork += i; LOG(info, "done %u read work", i); } void Fixture::writeWork(uint32_t cnt, WorkContext &context) { ReadStopper read_stopper(_stopRead); for (uint32_t i = 0; i < cnt; ++i) { context._generation.store(_generationHandler.getNextGeneration(), std::memory_order_relaxed); _generationHandler.incGeneration(); } _doneWriteWork += cnt; LOG(info, "done %u write work", cnt); } namespace { class ReadWorkTask : public vespalib::Executor::Task { Fixture &_f; std::shared_ptr<WorkContext> _context; public: ReadWorkTask(Fixture &f, std::shared_ptr<WorkContext> context) : _f(f), _context(context) { } virtual void run() override { _f.readWork(*_context); } }; class WriteWorkTask : public vespalib::Executor::Task { Fixture &_f; uint32_t _cnt; std::shared_ptr<WorkContext> _context; public: WriteWorkTask(Fixture &f, uint32_t cnt, std::shared_ptr<WorkContext> context) : _f(f), _cnt(cnt), _context(context) { } virtual void run() override { _f.writeWork(_cnt, *_context); } }; } void Fixture::stressTest(uint32_t writeCnt) { _reportWork = true; uint32_t readThreads = getReadThreads(); LOG(info, "starting stress test, 1 write thread, %u read threads, %u writes", readThreads, writeCnt); auto context = std::make_shared<WorkContext>(); _writer.execute(std::make_unique<WriteWorkTask>(*this, writeCnt, context)); for (uint32_t i = 0; i < readThreads; ++i) { _readers->execute(std::make_unique<ReadWorkTask>(*this, context)); } _writer.sync(); _readers->sync(); } void Fixture::read_indirect_work(const IndirectContext& context) { uint64_t i; uint64_t cnt = std::numeric_limits<uint32_t>::max(); uint64_t old_value = 0; for (i = 0; i < cnt && !_stopRead.load(); ++i) { auto guard = _generationHandler.takeGuard(); // Data referenced by pointer is protected by guard auto v_ptr = context._value_ptr.load(std::memory_order_acquire); EXPECT_GE(*v_ptr, old_value); old_value = *v_ptr; } _doneReadWork += i; LOG(info, "done %" PRIu64 " read work", i); } void Fixture::write_indirect_work(uint64_t cnt, IndirectContext& context) { ReadStopper read_stopper(_stopRead); uint32_t sleep_cnt = 0; ASSERT_EQ(0, _generationHandler.getCurrentGeneration()); auto oldest_gen = _generationHandler.getFirstUsedGeneration(); for (uint64_t i = 0; i < cnt; ++i) { auto gen = _generationHandler.getCurrentGeneration(); // Hold data for gen, write new data for next_gen auto next_gen = gen + 1; auto *v_ptr = context.calc_value_ptr(next_gen); ASSERT_EQ(0u, *v_ptr); *v_ptr = next_gen; context._value_ptr.store(v_ptr, std::memory_order_release); _generationHandler.incGeneration(); auto first_used_gen = _generationHandler.getFirstUsedGeneration(); while (oldest_gen < first_used_gen) { // Clear data that readers should no longer have access to. *context.calc_value_ptr(oldest_gen) = 0; ++oldest_gen; } while ((next_gen - first_used_gen) >= context.values_size - 2) { // Sleep if writer gets too much ahead of readers. std::this_thread::sleep_for(1ms); ++sleep_cnt; _generationHandler.updateFirstUsedGeneration(); first_used_gen = _generationHandler.getFirstUsedGeneration(); } } _doneWriteWork += cnt; LOG(info, "done %" PRIu64 " write work, %u sleeps", cnt, sleep_cnt); } void Fixture::stress_test_indirect(uint64_t write_cnt) { _reportWork = true; uint32_t read_threads = getReadThreads(); LOG(info, "starting stress test indirect, 1 write thread, %u read threads, %" PRIu64 " writes", read_threads, write_cnt); auto context = std::make_shared<IndirectContext>(); _writer.execute(makeLambdaTask([this, context, write_cnt]() { write_indirect_work(write_cnt, *context); })); for (uint32_t i = 0; i < read_threads; ++i) { _readers->execute(makeLambdaTask([this, context]() { read_indirect_work(*context); })); } _writer.sync(); _readers->sync(); } using GenerationHandlerStressTest = Fixture; TEST_F(GenerationHandlerStressTest, stress_test_2_readers) { set_read_threads(2); stressTest(smoke_test ? 10000 : 1000000); } TEST_F(GenerationHandlerStressTest, stress_test_4_readers) { set_read_threads(4); stressTest(smoke_test ? 10000 : 1000000); } TEST_F(GenerationHandlerStressTest, stress_test_indirect_2_readers) { set_read_threads(2); stress_test_indirect(smoke_test ? 10000 : 1000000); } TEST_F(GenerationHandlerStressTest, stress_test_indirect_4_readers) { set_read_threads(4); stress_test_indirect(smoke_test ? 10000 : 1000000); } int main(int argc, char **argv) { if (argc > 1 && argv[1] == smoke_test_option) { smoke_test = true; ++argv; --argc; } ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "Runtime/World/CScriptSwitch.hpp" #include "Runtime/CStateManager.hpp" #include "TCastTo.hpp" // Generated file, do not modify include path namespace urde { CScriptSwitch::CScriptSwitch(TUniqueId uid, std::string_view name, const CEntityInfo& info, bool active, bool opened, bool closeOnOpened) : CEntity(uid, info, active, name), x34_opened(opened), x35_closeOnOpened(closeOnOpened) {} void CScriptSwitch::Accept(IVisitor& visitor) { visitor.Visit(this); } void CScriptSwitch::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId objId, CStateManager& mgr) { if (GetActive()) { if (msg == EScriptObjectMessage::Open) x34_opened = true; else if (msg == EScriptObjectMessage::Close) x34_opened = false; else if (msg == EScriptObjectMessage::SetToZero) { if (x34_opened) { SendScriptMsgs(EScriptObjectState::Open, mgr, EScriptObjectMessage::None); if (x35_closeOnOpened) x34_opened = false; } else SendScriptMsgs(EScriptObjectState::Closed, mgr, EScriptObjectMessage::None); } } CEntity::AcceptScriptMsg(msg, objId, mgr); } } // namespace urde <commit_msg>CScriptSwitch: Brace conditionals where applicable<commit_after>#include "Runtime/World/CScriptSwitch.hpp" #include "Runtime/CStateManager.hpp" #include "TCastTo.hpp" // Generated file, do not modify include path namespace urde { CScriptSwitch::CScriptSwitch(TUniqueId uid, std::string_view name, const CEntityInfo& info, bool active, bool opened, bool closeOnOpened) : CEntity(uid, info, active, name), x34_opened(opened), x35_closeOnOpened(closeOnOpened) {} void CScriptSwitch::Accept(IVisitor& visitor) { visitor.Visit(this); } void CScriptSwitch::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId objId, CStateManager& mgr) { if (GetActive()) { if (msg == EScriptObjectMessage::Open) { x34_opened = true; } else if (msg == EScriptObjectMessage::Close) { x34_opened = false; } else if (msg == EScriptObjectMessage::SetToZero) { if (x34_opened) { SendScriptMsgs(EScriptObjectState::Open, mgr, EScriptObjectMessage::None); if (x35_closeOnOpened) x34_opened = false; } else { SendScriptMsgs(EScriptObjectState::Closed, mgr, EScriptObjectMessage::None); } } } CEntity::AcceptScriptMsg(msg, objId, mgr); } } // namespace urde <|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the TEM tomography project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "CentralWidget.h" #include "ui_CentralWidget.h" #include <pqView.h> #include <vtkAxis.h> #include <vtkChartXY.h> #include <vtkContextMouseEvent.h> #include <vtkContextScene.h> #include <vtkContextView.h> #include <vtkEventQtSlotConnect.h> #include <vtkFloatArray.h> #include <vtkImageData.h> #include <vtkIntArray.h> #include <vtkMathUtilities.h> #include <vtkObjectFactory.h> #include <vtkPlotBar.h> #include <vtkPointData.h> #include <vtkSMSourceProxy.h> #include <vtkSMViewProxy.h> #include <vtkTable.h> #include <vtkTransform2D.h> #include <vtkTrivialProducer.h> #include <QtDebug> #include <QThread> #include "ActiveObjects.h" #include "ComputeHistogram.h" #include "ModuleContour.h" #include "ModuleManager.h" #include "Utilities.h" namespace TEM { //----------------------------------------------------------------------------- // This is just here for now - quick and dirty historgram calculations... void PopulateHistogram(vtkImageData *input, vtkTable *output) { // The output table will have the twice the number of columns, they will be // the x and y for input column. This is the bin centers, and the population. double minmax[2] = { 0.0, 0.0 }; const int numberOfBins = 200; // The bin values are the centers, extending +/- half an inc either side switch (input->GetScalarType()) { vtkTemplateMacro( TEM::GetScalarRange(reinterpret_cast<VTK_TT *>(input->GetPointData()->GetScalars()->GetVoidPointer(0)), input->GetPointData()->GetScalars()->GetNumberOfTuples(), minmax)); default: break; } if (minmax[0] == minmax[1]) { minmax[1] = minmax[0] + 1.0; } double inc = (minmax[1] - minmax[0]) / numberOfBins; double halfInc = inc / 2.0; vtkSmartPointer<vtkFloatArray> extents = vtkFloatArray::SafeDownCast( output->GetColumnByName(vtkStdString("image_extents").c_str())); if (!extents) { extents = vtkSmartPointer<vtkFloatArray>::New(); extents->SetName(vtkStdString("image_extents").c_str()); } extents->SetNumberOfTuples(numberOfBins); double min = minmax[0] + halfInc; for (int j = 0; j < numberOfBins; ++j) { extents->SetValue(j, min + j * inc); } vtkSmartPointer<vtkIntArray> populations = vtkIntArray::SafeDownCast( output->GetColumnByName(vtkStdString("image_pops").c_str())); if (!populations) { populations = vtkSmartPointer<vtkIntArray>::New(); populations->SetName(vtkStdString("image_pops").c_str()); } populations->SetNumberOfTuples(numberOfBins); int *pops = static_cast<int *>(populations->GetVoidPointer(0)); for (int k = 0; k < numberOfBins; ++k) { pops[k] = 0; } switch (input->GetScalarType()) { vtkTemplateMacro( TEM::CalculateHistogram(reinterpret_cast<VTK_TT *>(input->GetPointData()->GetScalars()->GetVoidPointer(0)), input->GetPointData()->GetScalars()->GetNumberOfTuples(), minmax[0], pops, inc, numberOfBins)); default: cout << "UpdateFromFile: Unknown data type" << endl; } #ifndef NDEBUG vtkIdType total = 0; for (int i = 0; i < numberOfBins; ++i) total += pops[i]; assert(total == input->GetPointData()->GetScalars()->GetNumberOfTuples()); #endif output->AddColumn(extents.GetPointer()); output->AddColumn(populations.GetPointer()); } // Quick background thread for the histogram calculation. class HistogramWorker : public QThread { Q_OBJECT void run(); public: HistogramWorker(QObject *p = 0) : QThread(p) {} vtkSmartPointer<vtkImageData> input; vtkSmartPointer<vtkTable> output; }; void HistogramWorker::run() { if (input && output) { PopulateHistogram(input.Get(), output.Get()); } } class CentralWidget::CWInternals { public: Ui::CentralWidget Ui; }; class vtkChartHistogram : public vtkChartXY { public: static vtkChartHistogram * New(); bool MouseDoubleClickEvent(const vtkContextMouseEvent &mouse); vtkNew<vtkTransform2D> Transform; double PositionX; }; vtkStandardNewMacro(vtkChartHistogram) bool vtkChartHistogram::MouseDoubleClickEvent(const vtkContextMouseEvent &m) { // Determine the location of the click, and emit something we can listen to! vtkPlotBar *histo = 0; if (this->GetNumberOfPlots() == 1) { histo = vtkPlotBar::SafeDownCast(this->GetPlot(0)); } if (!histo) { return false; } if (this->Transform->GetMTime() < histo->GetMTime()) { this->CalculateUnscaledPlotTransform(histo->GetXAxis(), histo->GetYAxis(), this->Transform.Get()); } vtkVector2f pos; this->Transform->InverseTransformPoints(m.GetScenePos().GetData(), pos.GetData(), 1); this->PositionX = pos.GetX(); this->InvokeEvent(vtkCommand::CursorChangedEvent); return true; } //----------------------------------------------------------------------------- CentralWidget::CentralWidget(QWidget* parentObject, Qt::WindowFlags wflags) : Superclass(parentObject, wflags), Internals(new CentralWidget::CWInternals()), Worker(NULL) { this->Internals->Ui.setupUi(this); QList<int> sizes; sizes << 200 << 200; this->Internals->Ui.splitter->setSizes(sizes); this->Internals->Ui.splitter->setStretchFactor(0, 0); this->Internals->Ui.splitter->setStretchFactor(1, 1); // Set up our little chart. this->Histogram ->SetInteractor(this->Internals->Ui.histogramWidget->GetInteractor()); this->Internals->Ui.histogramWidget ->SetRenderWindow(this->Histogram->GetRenderWindow()); vtkChartHistogram* chart = this->Chart.Get(); this->Histogram->GetScene()->AddItem(chart); chart->SetBarWidthFraction(0.95); chart->SetRenderEmpty(true); chart->SetAutoAxes(false); chart->GetAxis(vtkAxis::LEFT)->SetTitle(""); chart->GetAxis(vtkAxis::BOTTOM)->SetTitle(""); chart->GetAxis(vtkAxis::LEFT)->SetBehavior(vtkAxis::FIXED); chart->GetAxis(vtkAxis::LEFT)->SetRange(0.0001, 10); chart->GetAxis(vtkAxis::LEFT)->SetMinimumLimit(1); chart->GetAxis(vtkAxis::LEFT)->SetLogScale(true); this->EventLink->Connect(chart, vtkCommand::CursorChangedEvent, this, SLOT(histogramClicked(vtkObject*))); } //----------------------------------------------------------------------------- CentralWidget::~CentralWidget() { } //----------------------------------------------------------------------------- void CentralWidget::setDataSource(vtkSMSourceProxy* source) { this->DataSource = source; // Whenever the data source changes clear the plot, and then populate when // ready (or use the cached histogram values. this->Chart->ClearPlots(); // Get the actual data source, build a histogram out of it. vtkTrivialProducer *t = vtkTrivialProducer::SafeDownCast(source->GetClientSideObject()); vtkImageData *data = vtkImageData::SafeDownCast(t->GetOutputDataObject(0)); // Check our cache, and use that if appopriate (or update it). if (this->HistogramCache.contains(data)) { vtkTable *cachedTable = this->HistogramCache[data]; if (cachedTable->GetMTime() > data->GetMTime()) { this->setHistogramTable(cachedTable); return; } else { // Should this ever happen? Do we want to support this? qDebug() << "Image data changed after histogram calculation."; return; } } // Calculate a histogram. vtkNew<vtkTable> table; this->HistogramCache[data] = table.Get(); if (!this->Worker) { this->Worker = new HistogramWorker(this); connect(this->Worker, SIGNAL(finished()), SLOT(histogramReady())); } else if (this->Worker->isRunning()) { // FIXME: Queue, abort, something. qDebug() << "Worker already running, skipping this one."; return; } this->Worker->input = data; this->Worker->output = table.Get(); this->Worker->start(); } void CentralWidget::histogramReady() { if (!this->Worker || !this->Worker->input || !this->Worker->output) return; this->setHistogramTable(this->Worker->output.Get()); this->Worker->input = NULL; this->Worker->output = NULL; } void CentralWidget::histogramClicked(vtkObject *caller) { //qDebug() << "Histogram clicked at" << this->Chart->PositionX // << "making this a great spot to ask for an isosurface at value" // << this->Chart->PositionX; Q_ASSERT(this->DataSource); vtkSMViewProxy* view = ActiveObjects::instance().activeView(); if (!view) { return; } // Use active ModuleContour is possible. Otherwise, find the first existing // ModuleContour instance or just create a new one, if none exists. ModuleContour* contour = qobject_cast<ModuleContour*>( ActiveObjects::instance().activeModule()); if (!contour) { QList<ModuleContour*> contours = ModuleManager::instance().findModules<ModuleContour*>(this->DataSource, view); if (contours.size() == 0) { contour = qobject_cast<ModuleContour*>(ModuleManager::instance().createAndAddModule( "Contour", this->DataSource, view)); } else { contour = contours[0]; } ActiveObjects::instance().setActiveModule(contour); } Q_ASSERT(contour); contour->setIsoValue(this->Chart->PositionX); TEM::convert<pqView*>(view)->render(); } void CentralWidget::setHistogramTable(vtkTable *table) { this->Chart->ClearPlots(); vtkPlot *plot = this->Chart->AddPlot(vtkChart::BAR); plot->SetInputData(table, "image_extents", "image_pops"); vtkDataArray *arr = vtkDataArray::SafeDownCast(table->GetColumnByName("image_pops")); if (arr) { double max = log10(arr->GetRange()[1]); vtkAxis *axis = this->Chart->GetAxis(vtkAxis::LEFT); axis->SetUnscaledMinimum(1.0); axis->SetMaximumLimit(max + 2.0); axis->SetMaximum(static_cast<int>(max) + 1.0); } } } // end of namespace TEM #include "CentralWidget.moc" <commit_msg>Set a marker, make the bars blue with black outline<commit_after>/****************************************************************************** This source file is part of the TEM tomography project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "CentralWidget.h" #include "ui_CentralWidget.h" #include <pqView.h> #include <vtkAxis.h> #include <vtkChartXY.h> #include <vtkContextMouseEvent.h> #include <vtkContextScene.h> #include <vtkContextView.h> #include <vtkEventQtSlotConnect.h> #include <vtkFloatArray.h> #include <vtkImageData.h> #include <vtkIntArray.h> #include <vtkMathUtilities.h> #include <vtkObjectFactory.h> #include <vtkPlotBar.h> #include <vtkPointData.h> #include <vtkSMSourceProxy.h> #include <vtkSMViewProxy.h> #include <vtkTable.h> #include <vtkTransform2D.h> #include <vtkTrivialProducer.h> #include <vtkContext2D.h> #include <vtkPen.h> #include <QtDebug> #include <QThread> #include "ActiveObjects.h" #include "ComputeHistogram.h" #include "ModuleContour.h" #include "ModuleManager.h" #include "Utilities.h" namespace TEM { //----------------------------------------------------------------------------- // This is just here for now - quick and dirty historgram calculations... void PopulateHistogram(vtkImageData *input, vtkTable *output) { // The output table will have the twice the number of columns, they will be // the x and y for input column. This is the bin centers, and the population. double minmax[2] = { 0.0, 0.0 }; const int numberOfBins = 200; // The bin values are the centers, extending +/- half an inc either side switch (input->GetScalarType()) { vtkTemplateMacro( TEM::GetScalarRange(reinterpret_cast<VTK_TT *>(input->GetPointData()->GetScalars()->GetVoidPointer(0)), input->GetPointData()->GetScalars()->GetNumberOfTuples(), minmax)); default: break; } if (minmax[0] == minmax[1]) { minmax[1] = minmax[0] + 1.0; } double inc = (minmax[1] - minmax[0]) / numberOfBins; double halfInc = inc / 2.0; vtkSmartPointer<vtkFloatArray> extents = vtkFloatArray::SafeDownCast( output->GetColumnByName(vtkStdString("image_extents").c_str())); if (!extents) { extents = vtkSmartPointer<vtkFloatArray>::New(); extents->SetName(vtkStdString("image_extents").c_str()); } extents->SetNumberOfTuples(numberOfBins); double min = minmax[0] + halfInc; for (int j = 0; j < numberOfBins; ++j) { extents->SetValue(j, min + j * inc); } vtkSmartPointer<vtkIntArray> populations = vtkIntArray::SafeDownCast( output->GetColumnByName(vtkStdString("image_pops").c_str())); if (!populations) { populations = vtkSmartPointer<vtkIntArray>::New(); populations->SetName(vtkStdString("image_pops").c_str()); } populations->SetNumberOfTuples(numberOfBins); int *pops = static_cast<int *>(populations->GetVoidPointer(0)); for (int k = 0; k < numberOfBins; ++k) { pops[k] = 0; } switch (input->GetScalarType()) { vtkTemplateMacro( TEM::CalculateHistogram(reinterpret_cast<VTK_TT *>(input->GetPointData()->GetScalars()->GetVoidPointer(0)), input->GetPointData()->GetScalars()->GetNumberOfTuples(), minmax[0], pops, inc, numberOfBins)); default: cout << "UpdateFromFile: Unknown data type" << endl; } #ifndef NDEBUG vtkIdType total = 0; for (int i = 0; i < numberOfBins; ++i) total += pops[i]; assert(total == input->GetPointData()->GetScalars()->GetNumberOfTuples()); #endif output->AddColumn(extents.GetPointer()); output->AddColumn(populations.GetPointer()); } // Quick background thread for the histogram calculation. class HistogramWorker : public QThread { Q_OBJECT void run(); public: HistogramWorker(QObject *p = 0) : QThread(p) {} vtkSmartPointer<vtkImageData> input; vtkSmartPointer<vtkTable> output; }; void HistogramWorker::run() { if (input && output) { PopulateHistogram(input.Get(), output.Get()); } } class CentralWidget::CWInternals { public: Ui::CentralWidget Ui; }; class vtkHistogramMarker : public vtkPlot { public: static vtkHistogramMarker * New() { return new vtkHistogramMarker; } double PositionX; bool Paint(vtkContext2D *painter) { vtkNew<vtkPen> pen; pen->SetColor(255, 0, 0, 255); pen->SetWidth(2.0); painter->ApplyPen(pen.Get()); painter->DrawLine(PositionX, 0, PositionX, 1e9); return true; } }; class vtkChartHistogram : public vtkChartXY { public: static vtkChartHistogram * New(); bool MouseDoubleClickEvent(const vtkContextMouseEvent &mouse); vtkNew<vtkTransform2D> Transform; double PositionX; vtkNew<vtkHistogramMarker> Marker; }; vtkStandardNewMacro(vtkChartHistogram) bool vtkChartHistogram::MouseDoubleClickEvent(const vtkContextMouseEvent &m) { // Determine the location of the click, and emit something we can listen to! vtkPlotBar *histo = 0; if (this->GetNumberOfPlots() > 0) { histo = vtkPlotBar::SafeDownCast(this->GetPlot(0)); } if (!histo) { return false; } if (this->Transform->GetMTime() < histo->GetMTime()) { this->CalculateUnscaledPlotTransform(histo->GetXAxis(), histo->GetYAxis(), this->Transform.Get()); } vtkVector2f pos; this->Transform->InverseTransformPoints(m.GetScenePos().GetData(), pos.GetData(), 1); this->PositionX = pos.GetX(); this->Marker->PositionX = this->PositionX; this->Marker->Modified(); this->Scene->SetDirty(true); if (this->GetNumberOfPlots() == 1) { this->AddPlot(this->Marker.Get()); } this->InvokeEvent(vtkCommand::CursorChangedEvent); return true; } //----------------------------------------------------------------------------- CentralWidget::CentralWidget(QWidget* parentObject, Qt::WindowFlags wflags) : Superclass(parentObject, wflags), Internals(new CentralWidget::CWInternals()), Worker(NULL) { this->Internals->Ui.setupUi(this); QList<int> sizes; sizes << 200 << 200; this->Internals->Ui.splitter->setSizes(sizes); this->Internals->Ui.splitter->setStretchFactor(0, 0); this->Internals->Ui.splitter->setStretchFactor(1, 1); // Set up our little chart. this->Histogram ->SetInteractor(this->Internals->Ui.histogramWidget->GetInteractor()); this->Internals->Ui.histogramWidget ->SetRenderWindow(this->Histogram->GetRenderWindow()); vtkChartHistogram* chart = this->Chart.Get(); this->Histogram->GetScene()->AddItem(chart); chart->SetBarWidthFraction(0.95); chart->SetRenderEmpty(true); chart->SetAutoAxes(false); chart->GetAxis(vtkAxis::LEFT)->SetTitle(""); chart->GetAxis(vtkAxis::BOTTOM)->SetTitle(""); chart->GetAxis(vtkAxis::LEFT)->SetBehavior(vtkAxis::FIXED); chart->GetAxis(vtkAxis::LEFT)->SetRange(0.0001, 10); chart->GetAxis(vtkAxis::LEFT)->SetMinimumLimit(1); chart->GetAxis(vtkAxis::LEFT)->SetLogScale(true); this->EventLink->Connect(chart, vtkCommand::CursorChangedEvent, this, SLOT(histogramClicked(vtkObject*))); } //----------------------------------------------------------------------------- CentralWidget::~CentralWidget() { } //----------------------------------------------------------------------------- void CentralWidget::setDataSource(vtkSMSourceProxy* source) { this->DataSource = source; // Whenever the data source changes clear the plot, and then populate when // ready (or use the cached histogram values. this->Chart->ClearPlots(); // Get the actual data source, build a histogram out of it. vtkTrivialProducer *t = vtkTrivialProducer::SafeDownCast(source->GetClientSideObject()); vtkImageData *data = vtkImageData::SafeDownCast(t->GetOutputDataObject(0)); // Check our cache, and use that if appopriate (or update it). if (this->HistogramCache.contains(data)) { vtkTable *cachedTable = this->HistogramCache[data]; if (cachedTable->GetMTime() > data->GetMTime()) { this->setHistogramTable(cachedTable); return; } else { // Should this ever happen? Do we want to support this? qDebug() << "Image data changed after histogram calculation."; return; } } // Calculate a histogram. vtkNew<vtkTable> table; this->HistogramCache[data] = table.Get(); if (!this->Worker) { this->Worker = new HistogramWorker(this); connect(this->Worker, SIGNAL(finished()), SLOT(histogramReady())); } else if (this->Worker->isRunning()) { // FIXME: Queue, abort, something. qDebug() << "Worker already running, skipping this one."; return; } this->Worker->input = data; this->Worker->output = table.Get(); this->Worker->start(); } void CentralWidget::histogramReady() { if (!this->Worker || !this->Worker->input || !this->Worker->output) return; this->setHistogramTable(this->Worker->output.Get()); this->Worker->input = NULL; this->Worker->output = NULL; } void CentralWidget::histogramClicked(vtkObject *caller) { //qDebug() << "Histogram clicked at" << this->Chart->PositionX // << "making this a great spot to ask for an isosurface at value" // << this->Chart->PositionX; Q_ASSERT(this->DataSource); vtkSMViewProxy* view = ActiveObjects::instance().activeView(); if (!view) { return; } // Use active ModuleContour is possible. Otherwise, find the first existing // ModuleContour instance or just create a new one, if none exists. ModuleContour* contour = qobject_cast<ModuleContour*>( ActiveObjects::instance().activeModule()); if (!contour) { QList<ModuleContour*> contours = ModuleManager::instance().findModules<ModuleContour*>(this->DataSource, view); if (contours.size() == 0) { contour = qobject_cast<ModuleContour*>(ModuleManager::instance().createAndAddModule( "Contour", this->DataSource, view)); } else { contour = contours[0]; } ActiveObjects::instance().setActiveModule(contour); } Q_ASSERT(contour); contour->setIsoValue(this->Chart->PositionX); TEM::convert<pqView*>(view)->render(); } void CentralWidget::setHistogramTable(vtkTable *table) { this->Chart->ClearPlots(); vtkPlot *plot = this->Chart->AddPlot(vtkChart::BAR); plot->SetInputData(table, "image_extents", "image_pops"); plot->SetColor(0, 0, 255, 255); vtkDataArray *arr = vtkDataArray::SafeDownCast(table->GetColumnByName("image_pops")); if (arr) { double max = log10(arr->GetRange()[1]); vtkAxis *axis = this->Chart->GetAxis(vtkAxis::LEFT); axis->SetUnscaledMinimum(1.0); axis->SetMaximumLimit(max + 2.0); axis->SetMaximum(static_cast<int>(max) + 1.0); } } } // end of namespace TEM #include "CentralWidget.moc" <|endoftext|>
<commit_before>#include "BinaryTree.hpp" #include <catch.hpp> SCENARIO("default constructor") { Tree<int> node; REQUIRE(node.root_() == nullptr); } SCENARIO("insert") { Tree<int> tree; tree.insert(7); REQUIRE(tree.x_() == 7); REQUIRE(tree.left_() == nullptr); REQUIRE(tree.right_() == nullptr); } SCENARIO("search") { Tree<int> tree; bool a; tree.insert(7); a = tree.check_search(7); REQUIRE(a == true); } SCENARIO("size") { Tree<int> tree; int size = 0; tree.insert(7); size = tree.size(tree.root_()); REQUIRE(size == 1); } SCENARIO("prev_") { Tree<int> tree; Node<int> * node; tree.insert(3); tree.insert(4); tree.insert(2); node = tree.prev_(4); REQUIRE(node->x == 3); } SCENARIO("deleteX") { Tree<int> tree; int size1, size2; tree.insert(3); tree.insert(4); tree.insert(2); tree.insert(0); size1 = tree.size(tree.root_()); tree.deleteX(0); size2 = tree.size(tree.root_()); REQUIRE(size1 == 1 + size2); } SCENARIO("out_to_file", "fIn") { Tree<int> tree1, tree2; int size1, size2; tree1.insert(3); tree1.insert(4); tree1.out_to_file("TreeOut.txt"); size1 = tree1.size(tree1.root_()); tree2.fIn("TreeOut.txt"); size2 = tree2.size(tree2.root_()); REQUIRE(size1 == 2); REQUIRE(size2 == 2); REQUIRE(tree2.x_() == 3); REQUIRE(tree2.left_() == nullptr); REQUIRE(tree2.right_() != nullptr); } <commit_msg>Update init.cpp<commit_after>#include "BinaryTree.hpp" #include <catch.hpp> SCENARIO("default constructor") { Tree<int> node; REQUIRE(node.root_() == nullptr); } SCENARIO("insert") { Tree<int> tree; tree.insert(7); REQUIRE(tree.x_() == 7); REQUIRE(tree.left_() == nullptr); REQUIRE(tree.right_() == nullptr); } SCENARIO("search") { Tree<int> tree; bool a; tree.insert(7); a = tree.check_search(7); REQUIRE(a == true); } SCENARIO("size") { Tree<int> tree; int size = 0; tree.insert(7); size = tree.size(tree.root_()); REQUIRE(size == 1); } SCENARIO("prev_") { Tree<int> tree; Node<int> * node; tree.insert(3); tree.insert(4); tree.insert(2); node = tree.prev_(4); REQUIRE(node->x == 3); } SCENARIO("deleteX") { Tree<int> tree; int size1, size2; tree.insert(3); tree.insert(4); tree.insert(2); tree.insert(0); size1 = tree.size(tree.root_()); tree.deleteX(0); size2 = tree.size(tree.root_()); REQUIRE(size1 == 1 + size2); } SCENARIO("out_to_file", "fIn") { Tree<int> tree1, tree2; int size1, size2; tree1.insert(3); tree1.insert(4); tree1.out_to_file("TreeOut.txt"); size1 = tree1.size(tree1.root_()); tree2.fIn("TreeOut.txt"); size2 = tree2.size(tree2.root_()); REQUIRE(size1 == 2); REQUIRE(size2 == 2); REQUIRE(tree2.x_() == 3); } <|endoftext|>