text stringlengths 54 60.6k |
|---|
<commit_before>#include "ddQVTKWidgetView.h"
#include "ddFPSCounter.h"
#include "vtkTDxInteractorStyleCallback.h"
#include "vtkSimpleActorInteractor.h"
#include <vtkBoundingBox.h>
#include <vtkSmartPointer.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkInteractorStyle.h>
#include <vtkObjectFactory.h>
#include <vtkActor.h>
#include <vtkPolyDataMapper.h>
#include <vtkConeSource.h>
#include <vtkOrientationMarkerWidget.h>
#include <vtkInteractorStyleTrackballCamera.h>
#include <vtkInteractorStyleRubberBand3D.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkAxesActor.h>
#include <vtkEventQtSlotConnect.h>
#include <vtkCaptionActor2D.h>
#include <vtkTextProperty.h>
#include <QVTKWidget.h>
#include <QVBoxLayout>
#include <QTimer>
//-----------------------------------------------------------------------------
class vtkCustomRubberBandStyle : public vtkInteractorStyleRubberBand3D
{
public:
static vtkCustomRubberBandStyle *New();
vtkTypeMacro(vtkCustomRubberBandStyle, vtkInteractorStyleRubberBand3D);
virtual void OnRightButtonDown()
{
if(this->Interaction == NONE)
{
this->Interaction = ZOOMING;
this->FindPokedRenderer(
this->Interactor->GetEventPosition()[0],
this->Interactor->GetEventPosition()[1]);
this->InvokeEvent(vtkCommand::StartInteractionEvent);
}
}
};
vtkStandardNewMacro(vtkCustomRubberBandStyle);
//-----------------------------------------------------------------------------
class ddQVTKWidgetView::ddInternal
{
public:
ddInternal()
{
this->RenderPending = false;
this->Connector = vtkSmartPointer<vtkEventQtSlotConnect>::New();
this->RenderTimer.setSingleShot(false);
int timerFramesPerSeconds = 60;
this->RenderTimer.setInterval(1000/timerFramesPerSeconds);
}
QVTKWidget* VTKWidget;
vtkSmartPointer<vtkRenderer> Renderer;
vtkSmartPointer<vtkRenderWindow> RenderWindow;
vtkSmartPointer<vtkOrientationMarkerWidget> OrientationWidget;
vtkSmartPointer<vtkTDxInteractorStyleCallback> TDxInteractor;
vtkSmartPointer<vtkEventQtSlotConnect> Connector;
QList<QList<double> > CustomBounds;
bool RenderPending;
ddFPSCounter FPSCounter;
QTimer RenderTimer;
};
//-----------------------------------------------------------------------------
ddQVTKWidgetView::ddQVTKWidgetView(QWidget* parent) : ddViewBase(parent)
{
this->Internal = new ddInternal;
QVBoxLayout* layout = new QVBoxLayout(this);
layout->setMargin(0);
this->Internal->VTKWidget = new QVTKWidget;
layout->addWidget(this->Internal->VTKWidget);
this->Internal->VTKWidget->SetUseTDx(true);
this->Internal->RenderWindow = vtkSmartPointer<vtkRenderWindow>::New();
this->Internal->RenderWindow->SetMultiSamples(8);
this->Internal->RenderWindow->StereoCapableWindowOn();
this->Internal->RenderWindow->SetStereoTypeToRedBlue();
this->Internal->RenderWindow->StereoRenderOff();
this->Internal->RenderWindow->StereoUpdate();
this->Internal->VTKWidget->SetRenderWindow(this->Internal->RenderWindow);
this->Internal->TDxInteractor = vtkSmartPointer<vtkTDxInteractorStyleCallback>::New();
vtkInteractorStyle::SafeDownCast(this->Internal->RenderWindow->GetInteractor()->GetInteractorStyle())->SetTDxStyle(this->Internal->TDxInteractor);
this->Internal->Renderer = vtkSmartPointer<vtkRenderer>::New();
this->Internal->RenderWindow->AddRenderer(this->Internal->Renderer);
//vtkMapper::SetResolveCoincidentTopologyToPolygonOffset();
this->Internal->Renderer->GradientBackgroundOn();
this->Internal->Renderer->SetBackground(0.0, 0.0, 0.0);
this->Internal->Renderer->SetBackground2(0.3, 0.3, 0.3);
this->Internal->Connector->Connect(this->Internal->Renderer, vtkCommand::StartEvent, this, SLOT(onStartRender()));
this->Internal->Connector->Connect(this->Internal->Renderer, vtkCommand::EndEvent, this, SLOT(onEndRender()));
this->setupOrientationMarker();
this->Internal->Renderer->ResetCamera();
this->connect(&this->Internal->RenderTimer, SIGNAL(timeout()), SLOT(onRenderTimer()));
this->Internal->RenderTimer.start();
}
//-----------------------------------------------------------------------------
ddQVTKWidgetView::~ddQVTKWidgetView()
{
delete this->Internal;
}
//-----------------------------------------------------------------------------
vtkCamera* ddQVTKWidgetView::camera() const
{
return this->Internal->Renderer->GetActiveCamera();
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::installImageInteractor()
{
this->renderWindow()->GetInteractor()->SetInteractorStyle(vtkCustomRubberBandStyle::New());
}
//-----------------------------------------------------------------------------
vtkRenderWindow* ddQVTKWidgetView::renderWindow() const
{
return this->Internal->VTKWidget->GetRenderWindow();
}
//-----------------------------------------------------------------------------
vtkRenderer* ddQVTKWidgetView::renderer() const
{
return this->Internal->Renderer;
}
//-----------------------------------------------------------------------------
vtkRenderer* ddQVTKWidgetView::backgroundRenderer() const
{
return this->Internal->Renderer;
}
//-----------------------------------------------------------------------------
QVTKWidget* ddQVTKWidgetView::vtkWidget() const
{
return this->Internal->VTKWidget;
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::render()
{
if (!this->Internal->RenderPending)
{
this->Internal->RenderPending = true;
}
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::forceRender()
{
this->Internal->Renderer->ResetCameraClippingRange();
this->Internal->RenderWindow->Render();
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::onStartRender()
{
this->Internal->RenderPending = false;
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::onEndRender()
{
this->Internal->FPSCounter.update();
//printf("end render: %.2f fps\n", this->Internal->FPSCounter.averageFPS());
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::onRenderTimer()
{
if (this->Internal->RenderPending)
{
this->forceRender();
}
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::addCustomBounds(const QList<double>& bounds)
{
this->Internal->CustomBounds.append(bounds);
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::resetCamera()
{
this->Internal->CustomBounds.clear();
emit this->computeBoundsRequest(this);
if (this->Internal->CustomBounds.size())
{
vtkBoundingBox bbox;
foreach (const QList<double>& b, this->Internal->CustomBounds)
{
double bounds[6] = {b[0], b[1], b[2], b[3], b[4], b[5]};
bbox.AddBounds(bounds);
}
double bounds[6];
bbox.GetBounds(bounds);
this->renderer()->ResetCamera(bounds);
}
else
{
this->renderer()->ResetCamera();
}
this->Internal->Renderer->ResetCameraClippingRange();
}
//-----------------------------------------------------------------------------
QList<double> ddQVTKWidgetView::lastTDxMotion() const
{
double motionInfo[7];
this->Internal->TDxInteractor->GetTranslation(motionInfo);
this->Internal->TDxInteractor->GetAngleAxis(motionInfo+3);
QList<double> motionInfoList;
for (int i = 0; i < 7; ++i)
{
motionInfoList << motionInfo[i];
}
return motionInfoList;
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::setActorManipulationStyle()
{
this->renderWindow()->GetInteractor()->SetInteractorStyle(vtkSmartPointer<vtkSimpleActorInteractor>::New());
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::setCameraManipulationStyle()
{
this->renderWindow()->GetInteractor()->SetInteractorStyle(vtkSmartPointer<vtkInteractorStyleTrackballCamera>::New());
}
namespace {
void SetTextProperty(vtkTextProperty* prop)
{
prop->ShadowOff();
prop->BoldOff();
prop->ItalicOff();
//prop->SetColor(0,0,0);
}
}
//-----------------------------------------------------------------------------
vtkOrientationMarkerWidget* ddQVTKWidgetView::orientationMarkerWidget() const
{
return this->Internal->OrientationWidget;
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::setupOrientationMarker()
{
this->renderWindow()->GetInteractor()->Disable();
vtkSmartPointer<vtkAxesActor> axesActor = vtkSmartPointer<vtkAxesActor>::New();
SetTextProperty(axesActor->GetXAxisCaptionActor2D()->GetCaptionTextProperty());
SetTextProperty(axesActor->GetYAxisCaptionActor2D()->GetCaptionTextProperty());
SetTextProperty(axesActor->GetZAxisCaptionActor2D()->GetCaptionTextProperty());
vtkSmartPointer<vtkOrientationMarkerWidget> widget = vtkSmartPointer<vtkOrientationMarkerWidget>::New();
widget->SetOutlineColor(1.0, 1.0, 1.0);
widget->SetOrientationMarker(axesActor);
widget->SetInteractor(this->renderWindow()->GetInteractor());
widget->SetViewport(0.0, 0.0, 0.2, 0.2);
widget->SetEnabled(1);
widget->InteractiveOff();
this->Internal->OrientationWidget = widget;
this->renderWindow()->GetInteractor()->Enable();
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::addCone()
{
vtkSmartPointer<vtkConeSource> cone = vtkSmartPointer<vtkConeSource>::New();
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
cone->SetResolution( 8 );
mapper->AddInputConnection(cone->GetOutputPort());
actor->SetMapper(mapper);
this->Internal->Renderer->AddActor(actor);
}
<commit_msg>add background renderer to ddQVTKWidgetView<commit_after>#include "ddQVTKWidgetView.h"
#include "ddFPSCounter.h"
#include "vtkTDxInteractorStyleCallback.h"
#include "vtkSimpleActorInteractor.h"
#include <vtkBoundingBox.h>
#include <vtkSmartPointer.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkInteractorStyle.h>
#include <vtkObjectFactory.h>
#include <vtkActor.h>
#include <vtkPolyDataMapper.h>
#include <vtkConeSource.h>
#include <vtkOrientationMarkerWidget.h>
#include <vtkInteractorStyleTrackballCamera.h>
#include <vtkInteractorStyleRubberBand3D.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkAxesActor.h>
#include <vtkEventQtSlotConnect.h>
#include <vtkCaptionActor2D.h>
#include <vtkTextProperty.h>
#include <QVTKWidget.h>
#include <QVBoxLayout>
#include <QTimer>
//-----------------------------------------------------------------------------
class vtkCustomRubberBandStyle : public vtkInteractorStyleRubberBand3D
{
public:
static vtkCustomRubberBandStyle *New();
vtkTypeMacro(vtkCustomRubberBandStyle, vtkInteractorStyleRubberBand3D);
virtual void OnRightButtonDown()
{
if(this->Interaction == NONE)
{
this->Interaction = ZOOMING;
this->FindPokedRenderer(
this->Interactor->GetEventPosition()[0],
this->Interactor->GetEventPosition()[1]);
this->InvokeEvent(vtkCommand::StartInteractionEvent);
}
}
};
vtkStandardNewMacro(vtkCustomRubberBandStyle);
//-----------------------------------------------------------------------------
class ddQVTKWidgetView::ddInternal
{
public:
ddInternal()
{
this->RenderPending = false;
this->Connector = vtkSmartPointer<vtkEventQtSlotConnect>::New();
this->RenderTimer.setSingleShot(false);
int timerFramesPerSeconds = 60;
this->RenderTimer.setInterval(1000/timerFramesPerSeconds);
}
QVTKWidget* VTKWidget;
vtkSmartPointer<vtkRenderer> Renderer;
vtkSmartPointer<vtkRenderer> RendererBase;
vtkSmartPointer<vtkRenderWindow> RenderWindow;
vtkSmartPointer<vtkOrientationMarkerWidget> OrientationWidget;
vtkSmartPointer<vtkTDxInteractorStyleCallback> TDxInteractor;
vtkSmartPointer<vtkEventQtSlotConnect> Connector;
QList<QList<double> > CustomBounds;
bool RenderPending;
ddFPSCounter FPSCounter;
QTimer RenderTimer;
};
//-----------------------------------------------------------------------------
ddQVTKWidgetView::ddQVTKWidgetView(QWidget* parent) : ddViewBase(parent)
{
this->Internal = new ddInternal;
QVBoxLayout* layout = new QVBoxLayout(this);
layout->setMargin(0);
this->Internal->VTKWidget = new QVTKWidget;
layout->addWidget(this->Internal->VTKWidget);
this->Internal->VTKWidget->SetUseTDx(true);
this->Internal->RenderWindow = vtkSmartPointer<vtkRenderWindow>::New();
this->Internal->RenderWindow->SetMultiSamples(8);
this->Internal->RenderWindow->StereoCapableWindowOn();
this->Internal->RenderWindow->SetStereoTypeToRedBlue();
this->Internal->RenderWindow->StereoRenderOff();
this->Internal->RenderWindow->StereoUpdate();
this->Internal->VTKWidget->SetRenderWindow(this->Internal->RenderWindow);
this->Internal->TDxInteractor = vtkSmartPointer<vtkTDxInteractorStyleCallback>::New();
vtkInteractorStyle::SafeDownCast(this->Internal->RenderWindow->GetInteractor()->GetInteractorStyle())->SetTDxStyle(this->Internal->TDxInteractor);
this->Internal->RenderWindow->SetNumberOfLayers(2);
this->Internal->RendererBase = vtkSmartPointer<vtkRenderer>::New();
this->Internal->RenderWindow->AddRenderer(this->Internal->RendererBase);
this->Internal->Renderer = vtkSmartPointer<vtkRenderer>::New();
this->Internal->Renderer->SetLayer(1);
this->Internal->RenderWindow->AddRenderer(this->Internal->Renderer);
//vtkMapper::SetResolveCoincidentTopologyToPolygonOffset();
this->Internal->RendererBase->GradientBackgroundOn();
this->Internal->RendererBase->SetBackground(0.0, 0.0, 0.0);
this->Internal->RendererBase->SetBackground2(0.3, 0.3, 0.3);
this->Internal->Connector->Connect(this->Internal->Renderer, vtkCommand::StartEvent, this, SLOT(onStartRender()));
this->Internal->Connector->Connect(this->Internal->Renderer, vtkCommand::EndEvent, this, SLOT(onEndRender()));
this->setupOrientationMarker();
this->Internal->Renderer->ResetCamera();
this->connect(&this->Internal->RenderTimer, SIGNAL(timeout()), SLOT(onRenderTimer()));
this->Internal->RenderTimer.start();
}
//-----------------------------------------------------------------------------
ddQVTKWidgetView::~ddQVTKWidgetView()
{
delete this->Internal;
}
//-----------------------------------------------------------------------------
vtkCamera* ddQVTKWidgetView::camera() const
{
return this->Internal->Renderer->GetActiveCamera();
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::installImageInteractor()
{
this->renderWindow()->GetInteractor()->SetInteractorStyle(vtkCustomRubberBandStyle::New());
}
//-----------------------------------------------------------------------------
vtkRenderWindow* ddQVTKWidgetView::renderWindow() const
{
return this->Internal->VTKWidget->GetRenderWindow();
}
//-----------------------------------------------------------------------------
vtkRenderer* ddQVTKWidgetView::renderer() const
{
return this->Internal->Renderer;
}
//-----------------------------------------------------------------------------
vtkRenderer* ddQVTKWidgetView::backgroundRenderer() const
{
return this->Internal->RendererBase;
}
//-----------------------------------------------------------------------------
QVTKWidget* ddQVTKWidgetView::vtkWidget() const
{
return this->Internal->VTKWidget;
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::render()
{
if (!this->Internal->RenderPending)
{
this->Internal->RenderPending = true;
}
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::forceRender()
{
this->Internal->Renderer->ResetCameraClippingRange();
this->Internal->RenderWindow->Render();
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::onStartRender()
{
this->Internal->RenderPending = false;
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::onEndRender()
{
this->Internal->FPSCounter.update();
//printf("end render: %.2f fps\n", this->Internal->FPSCounter.averageFPS());
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::onRenderTimer()
{
if (this->Internal->RenderPending)
{
this->forceRender();
}
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::addCustomBounds(const QList<double>& bounds)
{
this->Internal->CustomBounds.append(bounds);
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::resetCamera()
{
this->Internal->CustomBounds.clear();
emit this->computeBoundsRequest(this);
if (this->Internal->CustomBounds.size())
{
vtkBoundingBox bbox;
foreach (const QList<double>& b, this->Internal->CustomBounds)
{
double bounds[6] = {b[0], b[1], b[2], b[3], b[4], b[5]};
bbox.AddBounds(bounds);
}
double bounds[6];
bbox.GetBounds(bounds);
this->renderer()->ResetCamera(bounds);
}
else
{
this->renderer()->ResetCamera();
}
this->Internal->Renderer->ResetCameraClippingRange();
}
//-----------------------------------------------------------------------------
QList<double> ddQVTKWidgetView::lastTDxMotion() const
{
double motionInfo[7];
this->Internal->TDxInteractor->GetTranslation(motionInfo);
this->Internal->TDxInteractor->GetAngleAxis(motionInfo+3);
QList<double> motionInfoList;
for (int i = 0; i < 7; ++i)
{
motionInfoList << motionInfo[i];
}
return motionInfoList;
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::setActorManipulationStyle()
{
this->renderWindow()->GetInteractor()->SetInteractorStyle(vtkSmartPointer<vtkSimpleActorInteractor>::New());
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::setCameraManipulationStyle()
{
this->renderWindow()->GetInteractor()->SetInteractorStyle(vtkSmartPointer<vtkInteractorStyleTrackballCamera>::New());
}
namespace {
void SetTextProperty(vtkTextProperty* prop)
{
prop->ShadowOff();
prop->BoldOff();
prop->ItalicOff();
//prop->SetColor(0,0,0);
}
}
//-----------------------------------------------------------------------------
vtkOrientationMarkerWidget* ddQVTKWidgetView::orientationMarkerWidget() const
{
return this->Internal->OrientationWidget;
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::setupOrientationMarker()
{
this->renderWindow()->GetInteractor()->Disable();
vtkSmartPointer<vtkAxesActor> axesActor = vtkSmartPointer<vtkAxesActor>::New();
SetTextProperty(axesActor->GetXAxisCaptionActor2D()->GetCaptionTextProperty());
SetTextProperty(axesActor->GetYAxisCaptionActor2D()->GetCaptionTextProperty());
SetTextProperty(axesActor->GetZAxisCaptionActor2D()->GetCaptionTextProperty());
vtkSmartPointer<vtkOrientationMarkerWidget> widget = vtkSmartPointer<vtkOrientationMarkerWidget>::New();
widget->SetOutlineColor(1.0, 1.0, 1.0);
widget->SetOrientationMarker(axesActor);
widget->SetInteractor(this->renderWindow()->GetInteractor());
widget->SetViewport(0.0, 0.0, 0.2, 0.2);
widget->SetEnabled(1);
widget->InteractiveOff();
this->Internal->OrientationWidget = widget;
this->renderWindow()->GetInteractor()->Enable();
}
//-----------------------------------------------------------------------------
void ddQVTKWidgetView::addCone()
{
vtkSmartPointer<vtkConeSource> cone = vtkSmartPointer<vtkConeSource>::New();
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
cone->SetResolution( 8 );
mapper->AddInputConnection(cone->GetOutputPort());
actor->SetMapper(mapper);
this->Internal->Renderer->AddActor(actor);
}
<|endoftext|> |
<commit_before>//===--- TextDiagnosticPrinter.cpp - Diagnostic Printer -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This diagnostic client prints out their diagnostic messages.
//
//===----------------------------------------------------------------------===//
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/Lexer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/SmallString.h"
#include <algorithm>
using namespace clang;
void TextDiagnosticPrinter::
PrintIncludeStack(SourceLocation Loc, const SourceManager &SM) {
if (Loc.isInvalid()) return;
PresumedLoc PLoc = SM.getPresumedLoc(Loc);
// Print out the other include frames first.
PrintIncludeStack(PLoc.getIncludeLoc(), SM);
OS << "In file included from " << PLoc.getFilename()
<< ':' << PLoc.getLine() << ":\n";
}
/// HighlightRange - Given a SourceRange and a line number, highlight (with ~'s)
/// any characters in LineNo that intersect the SourceRange.
void TextDiagnosticPrinter::HighlightRange(const SourceRange &R,
const SourceManager &SM,
unsigned LineNo, FileID FID,
std::string &CaretLine,
const std::string &SourceLine) {
assert(CaretLine.size() == SourceLine.size() &&
"Expect a correspondence between source and caret line!");
if (!R.isValid()) return;
SourceLocation Begin = SM.getInstantiationLoc(R.getBegin());
SourceLocation End = SM.getInstantiationLoc(R.getEnd());
// If the End location and the start location are the same and are a macro
// location, then the range was something that came from a macro expansion
// or _Pragma. If this is an object-like macro, the best we can do is to
// highlight the range. If this is a function-like macro, we'd also like to
// highlight the arguments.
if (Begin == End && R.getEnd().isMacroID())
End = SM.getInstantiationRange(R.getEnd()).second;
unsigned StartLineNo = SM.getInstantiationLineNumber(Begin);
if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
return; // No intersection.
unsigned EndLineNo = SM.getInstantiationLineNumber(End);
if (EndLineNo < LineNo || SM.getFileID(End) != FID)
return; // No intersection.
// Compute the column number of the start.
unsigned StartColNo = 0;
if (StartLineNo == LineNo) {
StartColNo = SM.getInstantiationColumnNumber(Begin);
if (StartColNo) --StartColNo; // Zero base the col #.
}
// Pick the first non-whitespace column.
while (StartColNo < SourceLine.size() &&
(SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
++StartColNo;
// Compute the column number of the end.
unsigned EndColNo = CaretLine.size();
if (EndLineNo == LineNo) {
EndColNo = SM.getInstantiationColumnNumber(End);
if (EndColNo) {
--EndColNo; // Zero base the col #.
// Add in the length of the token, so that we cover multi-char tokens.
EndColNo += Lexer::MeasureTokenLength(End, SM, *LangOpts);
} else {
EndColNo = CaretLine.size();
}
}
// Pick the last non-whitespace column.
if (EndColNo <= SourceLine.size())
while (EndColNo-1 &&
(SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
--EndColNo;
else
EndColNo = SourceLine.size();
// Fill the range with ~'s.
assert(StartColNo <= EndColNo && "Invalid range!");
for (unsigned i = StartColNo; i < EndColNo; ++i)
CaretLine[i] = '~';
}
void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc,
SourceRange *Ranges,
unsigned NumRanges,
SourceManager &SM,
const CodeModificationHint *Hints,
unsigned NumHints) {
assert(!Loc.isInvalid() && "must have a valid source location here");
// We always emit diagnostics about the instantiation points, not the spelling
// points. This more closely correlates to what the user writes.
if (!Loc.isFileID()) {
SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first;
EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM);
// Map the location through the macro.
Loc = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(Loc));
// Map the ranges.
for (unsigned i = 0; i != NumRanges; ++i) {
SourceLocation S = Ranges[i].getBegin(), E = Ranges[i].getEnd();
if (S.isMacroID())
S = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(S));
if (E.isMacroID())
E = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(E));
Ranges[i] = SourceRange(S, E);
}
// Emit the file/line/column that this expansion came from.
OS << SM.getBufferName(Loc) << ':' << SM.getInstantiationLineNumber(Loc)
<< ':';
if (ShowColumn)
OS << SM.getInstantiationColumnNumber(Loc) << ':';
OS << " note: instantiated from:\n";
}
// Decompose the location into a FID/Offset pair.
std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
FileID FID = LocInfo.first;
unsigned FileOffset = LocInfo.second;
// Get information about the buffer it points into.
std::pair<const char*, const char*> BufferInfo = SM.getBufferData(FID);
const char *BufStart = BufferInfo.first;
unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
// Rewind from the current position to the start of the line.
const char *TokPtr = BufStart+FileOffset;
const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
// Compute the line end. Scan forward from the error position to the end of
// the line.
const char *LineEnd = TokPtr;
while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
++LineEnd;
// Copy the line of code into an std::string for ease of manipulation.
std::string SourceLine(LineStart, LineEnd);
// Create a line for the caret that is filled with spaces that is the same
// length as the line of source code.
std::string CaretLine(LineEnd-LineStart, ' ');
// Highlight all of the characters covered by Ranges with ~ characters.
if (NumRanges) {
unsigned LineNo = SM.getLineNumber(FID, FileOffset);
for (unsigned i = 0, e = NumRanges; i != e; ++i)
HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine);
}
// Next, insert the caret itself.
if (ColNo-1 < CaretLine.size())
CaretLine[ColNo-1] = '^';
else
CaretLine.push_back('^');
// Scan the source line, looking for tabs. If we find any, manually expand
// them to 8 characters and update the CaretLine to match.
for (unsigned i = 0; i != SourceLine.size(); ++i) {
if (SourceLine[i] != '\t') continue;
// Replace this tab with at least one space.
SourceLine[i] = ' ';
// Compute the number of spaces we need to insert.
unsigned NumSpaces = ((i+8)&~7) - (i+1);
assert(NumSpaces < 8 && "Invalid computation of space amt");
// Insert spaces into the SourceLine.
SourceLine.insert(i+1, NumSpaces, ' ');
// Insert spaces or ~'s into CaretLine.
CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
}
// Finally, remove any blank spaces from the end of CaretLine.
while (CaretLine[CaretLine.size()-1] == ' ')
CaretLine.erase(CaretLine.end()-1);
// Emit what we have computed.
OS << SourceLine << '\n';
OS << CaretLine << '\n';
if (NumHints && PrintFixItInfo) {
std::string InsertionLine;
for (const CodeModificationHint *Hint = Hints, *LastHint = Hints + NumHints;
Hint != LastHint; ++Hint) {
if (Hint->InsertionLoc.isValid()) {
// We have an insertion hint. Determine whether the inserted
// code is on the same line as the caret.
std::pair<FileID, unsigned> HintLocInfo
= SM.getDecomposedInstantiationLoc(Hint->InsertionLoc);
if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) ==
SM.getLineNumber(FID, FileOffset)) {
// Insert the new code into the line just below the code
// that the user wrote.
unsigned HintColNo
= SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
unsigned LastColumnModified
= HintColNo - 1 + Hint->CodeToInsert.size();
if (LastColumnModified > InsertionLine.size())
InsertionLine.resize(LastColumnModified, ' ');
std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
InsertionLine.begin() + HintColNo - 1);
}
}
}
if (!InsertionLine.empty())
OS << InsertionLine << '\n';
}
}
void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
const DiagnosticInfo &Info) {
// If the location is specified, print out a file/line/col and include trace
// if enabled.
if (Info.getLocation().isValid()) {
const SourceManager &SM = Info.getLocation().getManager();
PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());
unsigned LineNo = PLoc.getLine();
// First, if this diagnostic is not in the main file, print out the
// "included from" lines.
if (LastWarningLoc != PLoc.getIncludeLoc()) {
LastWarningLoc = PLoc.getIncludeLoc();
PrintIncludeStack(LastWarningLoc, SM);
}
// Compute the column number.
if (ShowLocation) {
OS << PLoc.getFilename() << ':' << LineNo << ':';
if (ShowColumn)
if (unsigned ColNo = PLoc.getColumn())
OS << ColNo << ':';
if (PrintRangeInfo && Info.getNumRanges()) {
FileID CaretFileID =
SM.getFileID(SM.getInstantiationLoc(Info.getLocation()));
bool PrintedRange = false;
for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
// Ignore invalid ranges.
if (!Info.getRange(i).isValid()) continue;
SourceLocation B = Info.getRange(i).getBegin();
SourceLocation E = Info.getRange(i).getEnd();
std::pair<FileID, unsigned> BInfo=SM.getDecomposedInstantiationLoc(B);
E = SM.getInstantiationLoc(E);
std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
// If the start or end of the range is in another file, just discard
// it.
if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
continue;
// Add in the length of the token, so that we cover multi-char tokens.
unsigned TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
<< SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
<< SM.getLineNumber(EInfo.first, EInfo.second) << ':'
<< (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) << '}';
PrintedRange = true;
}
if (PrintedRange)
OS << ':';
}
OS << ' ';
}
}
switch (Level) {
case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
case Diagnostic::Note: OS << "note: "; break;
case Diagnostic::Warning: OS << "warning: "; break;
case Diagnostic::Error: OS << "error: "; break;
case Diagnostic::Fatal: OS << "fatal error: "; break;
}
llvm::SmallString<100> OutStr;
Info.FormatDiagnostic(OutStr);
OS.write(OutStr.begin(), OutStr.size());
if (PrintDiagnosticOption)
if (const char *Option = Diagnostic::getWarningOptionForDiag(Info.getID()))
OS << " [-W" << Option << ']';
OS << '\n';
// If caret diagnostics are enabled and we have location, we want to
// emit the caret. However, we only do this if the location moved
// from the last diagnostic, if the last diagnostic was a note that
// was part of a different warning or error diagnostic, or if the
// diagnostic has ranges. We don't want to emit the same caret
// multiple times if one loc has multiple diagnostics.
if (CaretDiagnostics && Info.getLocation().isValid() &&
((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
(LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Info.getNumCodeModificationHints())) {
// Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
LastLoc = Info.getLocation();
LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
// Get the ranges into a local array we can hack on.
SourceRange Ranges[20];
unsigned NumRanges = Info.getNumRanges();
assert(NumRanges < 20 && "Out of space");
for (unsigned i = 0; i != NumRanges; ++i)
Ranges[i] = Info.getRange(i);
unsigned NumHints = Info.getNumCodeModificationHints();
for (unsigned idx = 0; idx < NumHints; ++idx) {
const CodeModificationHint &Hint = Info.getCodeModificationHint(idx);
if (Hint.RemoveRange.isValid()) {
assert(NumRanges < 20 && "Out of space");
Ranges[NumRanges++] = Hint.RemoveRange;
}
}
EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
Info.getCodeModificationHints(),
Info.getNumCodeModificationHints());
}
OS.flush();
}
<commit_msg>make "in included from" and "in instatiation from" messages respect -fno-show-location, patch by Alexei Svitkine (PR4024)<commit_after>//===--- TextDiagnosticPrinter.cpp - Diagnostic Printer -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This diagnostic client prints out their diagnostic messages.
//
//===----------------------------------------------------------------------===//
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/Lexer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/SmallString.h"
#include <algorithm>
using namespace clang;
void TextDiagnosticPrinter::
PrintIncludeStack(SourceLocation Loc, const SourceManager &SM) {
if (Loc.isInvalid()) return;
PresumedLoc PLoc = SM.getPresumedLoc(Loc);
// Print out the other include frames first.
PrintIncludeStack(PLoc.getIncludeLoc(), SM);
if (ShowLocation)
OS << "In file included from " << PLoc.getFilename()
<< ':' << PLoc.getLine() << ":\n";
else
OS << "In included file:\n";
}
/// HighlightRange - Given a SourceRange and a line number, highlight (with ~'s)
/// any characters in LineNo that intersect the SourceRange.
void TextDiagnosticPrinter::HighlightRange(const SourceRange &R,
const SourceManager &SM,
unsigned LineNo, FileID FID,
std::string &CaretLine,
const std::string &SourceLine) {
assert(CaretLine.size() == SourceLine.size() &&
"Expect a correspondence between source and caret line!");
if (!R.isValid()) return;
SourceLocation Begin = SM.getInstantiationLoc(R.getBegin());
SourceLocation End = SM.getInstantiationLoc(R.getEnd());
// If the End location and the start location are the same and are a macro
// location, then the range was something that came from a macro expansion
// or _Pragma. If this is an object-like macro, the best we can do is to
// highlight the range. If this is a function-like macro, we'd also like to
// highlight the arguments.
if (Begin == End && R.getEnd().isMacroID())
End = SM.getInstantiationRange(R.getEnd()).second;
unsigned StartLineNo = SM.getInstantiationLineNumber(Begin);
if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
return; // No intersection.
unsigned EndLineNo = SM.getInstantiationLineNumber(End);
if (EndLineNo < LineNo || SM.getFileID(End) != FID)
return; // No intersection.
// Compute the column number of the start.
unsigned StartColNo = 0;
if (StartLineNo == LineNo) {
StartColNo = SM.getInstantiationColumnNumber(Begin);
if (StartColNo) --StartColNo; // Zero base the col #.
}
// Pick the first non-whitespace column.
while (StartColNo < SourceLine.size() &&
(SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
++StartColNo;
// Compute the column number of the end.
unsigned EndColNo = CaretLine.size();
if (EndLineNo == LineNo) {
EndColNo = SM.getInstantiationColumnNumber(End);
if (EndColNo) {
--EndColNo; // Zero base the col #.
// Add in the length of the token, so that we cover multi-char tokens.
EndColNo += Lexer::MeasureTokenLength(End, SM, *LangOpts);
} else {
EndColNo = CaretLine.size();
}
}
// Pick the last non-whitespace column.
if (EndColNo <= SourceLine.size())
while (EndColNo-1 &&
(SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
--EndColNo;
else
EndColNo = SourceLine.size();
// Fill the range with ~'s.
assert(StartColNo <= EndColNo && "Invalid range!");
for (unsigned i = StartColNo; i < EndColNo; ++i)
CaretLine[i] = '~';
}
void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc,
SourceRange *Ranges,
unsigned NumRanges,
SourceManager &SM,
const CodeModificationHint *Hints,
unsigned NumHints) {
assert(!Loc.isInvalid() && "must have a valid source location here");
// We always emit diagnostics about the instantiation points, not the spelling
// points. This more closely correlates to what the user writes.
if (!Loc.isFileID()) {
SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first;
EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM);
// Map the location through the macro.
Loc = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(Loc));
// Map the ranges.
for (unsigned i = 0; i != NumRanges; ++i) {
SourceLocation S = Ranges[i].getBegin(), E = Ranges[i].getEnd();
if (S.isMacroID())
S = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(S));
if (E.isMacroID())
E = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(E));
Ranges[i] = SourceRange(S, E);
}
if (ShowLocation) {
// Emit the file/line/column that this expansion came from.
OS << SM.getBufferName(Loc) << ':' << SM.getInstantiationLineNumber(Loc)
<< ':';
if (ShowColumn)
OS << SM.getInstantiationColumnNumber(Loc) << ':';
OS << ' ';
}
OS << "note: instantiated from:\n";
}
// Decompose the location into a FID/Offset pair.
std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
FileID FID = LocInfo.first;
unsigned FileOffset = LocInfo.second;
// Get information about the buffer it points into.
std::pair<const char*, const char*> BufferInfo = SM.getBufferData(FID);
const char *BufStart = BufferInfo.first;
unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
// Rewind from the current position to the start of the line.
const char *TokPtr = BufStart+FileOffset;
const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
// Compute the line end. Scan forward from the error position to the end of
// the line.
const char *LineEnd = TokPtr;
while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
++LineEnd;
// Copy the line of code into an std::string for ease of manipulation.
std::string SourceLine(LineStart, LineEnd);
// Create a line for the caret that is filled with spaces that is the same
// length as the line of source code.
std::string CaretLine(LineEnd-LineStart, ' ');
// Highlight all of the characters covered by Ranges with ~ characters.
if (NumRanges) {
unsigned LineNo = SM.getLineNumber(FID, FileOffset);
for (unsigned i = 0, e = NumRanges; i != e; ++i)
HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine);
}
// Next, insert the caret itself.
if (ColNo-1 < CaretLine.size())
CaretLine[ColNo-1] = '^';
else
CaretLine.push_back('^');
// Scan the source line, looking for tabs. If we find any, manually expand
// them to 8 characters and update the CaretLine to match.
for (unsigned i = 0; i != SourceLine.size(); ++i) {
if (SourceLine[i] != '\t') continue;
// Replace this tab with at least one space.
SourceLine[i] = ' ';
// Compute the number of spaces we need to insert.
unsigned NumSpaces = ((i+8)&~7) - (i+1);
assert(NumSpaces < 8 && "Invalid computation of space amt");
// Insert spaces into the SourceLine.
SourceLine.insert(i+1, NumSpaces, ' ');
// Insert spaces or ~'s into CaretLine.
CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
}
// Finally, remove any blank spaces from the end of CaretLine.
while (CaretLine[CaretLine.size()-1] == ' ')
CaretLine.erase(CaretLine.end()-1);
// Emit what we have computed.
OS << SourceLine << '\n';
OS << CaretLine << '\n';
if (NumHints && PrintFixItInfo) {
std::string InsertionLine;
for (const CodeModificationHint *Hint = Hints, *LastHint = Hints + NumHints;
Hint != LastHint; ++Hint) {
if (Hint->InsertionLoc.isValid()) {
// We have an insertion hint. Determine whether the inserted
// code is on the same line as the caret.
std::pair<FileID, unsigned> HintLocInfo
= SM.getDecomposedInstantiationLoc(Hint->InsertionLoc);
if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) ==
SM.getLineNumber(FID, FileOffset)) {
// Insert the new code into the line just below the code
// that the user wrote.
unsigned HintColNo
= SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
unsigned LastColumnModified
= HintColNo - 1 + Hint->CodeToInsert.size();
if (LastColumnModified > InsertionLine.size())
InsertionLine.resize(LastColumnModified, ' ');
std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
InsertionLine.begin() + HintColNo - 1);
}
}
}
if (!InsertionLine.empty())
OS << InsertionLine << '\n';
}
}
void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
const DiagnosticInfo &Info) {
// If the location is specified, print out a file/line/col and include trace
// if enabled.
if (Info.getLocation().isValid()) {
const SourceManager &SM = Info.getLocation().getManager();
PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());
unsigned LineNo = PLoc.getLine();
// First, if this diagnostic is not in the main file, print out the
// "included from" lines.
if (LastWarningLoc != PLoc.getIncludeLoc()) {
LastWarningLoc = PLoc.getIncludeLoc();
PrintIncludeStack(LastWarningLoc, SM);
}
// Compute the column number.
if (ShowLocation) {
OS << PLoc.getFilename() << ':' << LineNo << ':';
if (ShowColumn)
if (unsigned ColNo = PLoc.getColumn())
OS << ColNo << ':';
if (PrintRangeInfo && Info.getNumRanges()) {
FileID CaretFileID =
SM.getFileID(SM.getInstantiationLoc(Info.getLocation()));
bool PrintedRange = false;
for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
// Ignore invalid ranges.
if (!Info.getRange(i).isValid()) continue;
SourceLocation B = Info.getRange(i).getBegin();
SourceLocation E = Info.getRange(i).getEnd();
std::pair<FileID, unsigned> BInfo=SM.getDecomposedInstantiationLoc(B);
E = SM.getInstantiationLoc(E);
std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
// If the start or end of the range is in another file, just discard
// it.
if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
continue;
// Add in the length of the token, so that we cover multi-char tokens.
unsigned TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
<< SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
<< SM.getLineNumber(EInfo.first, EInfo.second) << ':'
<< (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) << '}';
PrintedRange = true;
}
if (PrintedRange)
OS << ':';
}
OS << ' ';
}
}
switch (Level) {
case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
case Diagnostic::Note: OS << "note: "; break;
case Diagnostic::Warning: OS << "warning: "; break;
case Diagnostic::Error: OS << "error: "; break;
case Diagnostic::Fatal: OS << "fatal error: "; break;
}
llvm::SmallString<100> OutStr;
Info.FormatDiagnostic(OutStr);
OS.write(OutStr.begin(), OutStr.size());
if (PrintDiagnosticOption)
if (const char *Option = Diagnostic::getWarningOptionForDiag(Info.getID()))
OS << " [-W" << Option << ']';
OS << '\n';
// If caret diagnostics are enabled and we have location, we want to
// emit the caret. However, we only do this if the location moved
// from the last diagnostic, if the last diagnostic was a note that
// was part of a different warning or error diagnostic, or if the
// diagnostic has ranges. We don't want to emit the same caret
// multiple times if one loc has multiple diagnostics.
if (CaretDiagnostics && Info.getLocation().isValid() &&
((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
(LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Info.getNumCodeModificationHints())) {
// Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
LastLoc = Info.getLocation();
LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
// Get the ranges into a local array we can hack on.
SourceRange Ranges[20];
unsigned NumRanges = Info.getNumRanges();
assert(NumRanges < 20 && "Out of space");
for (unsigned i = 0; i != NumRanges; ++i)
Ranges[i] = Info.getRange(i);
unsigned NumHints = Info.getNumCodeModificationHints();
for (unsigned idx = 0; idx < NumHints; ++idx) {
const CodeModificationHint &Hint = Info.getCodeModificationHint(idx);
if (Hint.RemoveRange.isValid()) {
assert(NumRanges < 20 && "Out of space");
Ranges[NumRanges++] = Hint.RemoveRange;
}
}
EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
Info.getCodeModificationHints(),
Info.getNumCodeModificationHints());
}
OS.flush();
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <thread>
#include <chrono>
#include <opencv2/opencv.hpp>
#include <bot_core/timestamp.h>
#include <jpeg-utils/jpeg-utils.h>
#include <lcm/lcm-cpp.hpp>
#include <ConciseArgs>
#include <flycapture/FlyCapture2.h>
#include <lcmtypes/bot_core/image_t.hpp>
int main(const int iArgc, const char** iArgv) {
// parse arguments
std::string channel = "DUMMY_CAMERA_CHANNEL";
int compressionQuality = 100;
int frameRate = 0;
int rotation = 0;
int64_t desiredSerial = -1;
ConciseArgs opt(iArgc, (char**)iArgv);
opt.add(channel, "c", "channel", "output channel");
opt.add(compressionQuality, "q", "quality",
"compression quality (100=no compression)");
opt.add(frameRate, "f", "framerate", "frame rate (0=max)");
opt.add(rotation, "r", "rotation", "rotation (0,90,180,270)");
opt.add(desiredSerial, "s", "serial number");
opt.parse();
if ((rotation != 0) && (rotation != 90) &&
(rotation != 180) && (rotation != 270)) {
std::cout << "error: invalid rotation " << rotation << std::endl;
return -1;
}
bool shouldCompress = (compressionQuality < 100);
int periodMs = (frameRate == 0 ? 0 : 1000/frameRate);
lcm::LCM lcm;
// determine which camera id to connect to
FlyCapture2::Error error;
FlyCapture2::PGRGuid cameraUid;
bool foundCamera = false;
if (desiredSerial >= 0) {
FlyCapture2::BusManager busManager;
unsigned int numCameras;
error = busManager.GetNumOfCameras(&numCameras);
if (error != FlyCapture2::PGRERROR_OK) {
std::cout << "Could not get number of cameras" << std::endl;
return -1;
}
for (int i = 0; i < numCameras; ++i) {
unsigned int curSerial;
error = busManager.GetCameraSerialNumberFromIndex(i, &curSerial);
if (error != FlyCapture2::PGRERROR_OK) {
std::cout << "Could not get serial number from index " <<
i << std::endl;
return -1;
}
if (curSerial == desiredSerial) {
error = busManager.GetCameraFromIndex(i, &cameraUid);
if (error != FlyCapture2::PGRERROR_OK) {
std::cout << "Could not get camera id from index " <<
i << std::endl;
return -1;
}
foundCamera = true;
break;
}
}
if (!foundCamera) {
std::cout << "Could not find camera with serial " <<
desiredSerial << std::endl;
return -1;
}
}
FlyCapture2::Camera camera;
FlyCapture2::CameraInfo camInfo;
// connect to camera
if (desiredSerial >= 0) {
error = camera.Connect(&cameraUid);
}
else {
error = camera.Connect(NULL);
}
if (error != FlyCapture2::PGRERROR_OK) {
std::cout << "Failed to connect to camera" << std::endl;
return -1;
}
// stop capture if in bad state
error = camera.StopCapture();
if (error != FlyCapture2::PGRERROR_OK) {}
// get camera info
error = camera.GetCameraInfo(&camInfo);
if (error != FlyCapture2::PGRERROR_OK) {
std::cout << "Failed to get camera info from camera" << std::endl;
return -1;
}
std::cout << "Camera information: "
<< camInfo.vendorName << " "
<< camInfo.modelName << " "
<< camInfo.serialNumber << std::endl;
error = camera.StartCapture();
if (error == FlyCapture2::PGRERROR_ISOCH_BANDWIDTH_EXCEEDED) {
std::cout << "Bandwidth exceeded" << std::endl;
return -1;
}
else if (error != FlyCapture2::PGRERROR_OK) {
std::cout << "Failed to start image capture" << std::endl;
return -1;
}
int64_t imageCount = 0;
int64_t totalBytes = 0;
int64_t prevTime = 0;
while (true) {
int64_t checkpointStart = bot_timestamp_now();
// grab image
FlyCapture2::Image rawImage;
error = camera.RetrieveBuffer(&rawImage);
if (error != FlyCapture2::PGRERROR_OK) {
std::cout << "capture error" << std::endl;
continue;
}
// TODO: this can be grabbed from image metadata via GetTimeStamp()
int64_t imageTime = bot_timestamp_now();
// convert to rgb
FlyCapture2::Image rgbImage;
rawImage.Convert(FlyCapture2::PIXEL_FORMAT_RGB, &rgbImage);
// convert to opencv
cv::Mat cvImage(rgbImage.GetRows(), rgbImage.GetCols(), CV_8UC3,
rgbImage.GetData(), rgbImage.GetStride());
// rotate
switch (rotation) {
case 0:
break;
case 90:
cv::transpose(cvImage, cvImage);
cv::flip(cvImage, cvImage, 1);
break;
case 180:
cv::flip(cvImage, cvImage, -1);
break;
case 270:
cv::transpose(cvImage, cvImage);
cv::flip(cvImage, cvImage, 0);
break;
default:
std::cout << "error: cannot rotate by " << rotation << std::endl;
break;
}
// convert to libbot image type
bot_core::image_t msg;
msg.utime = imageTime;
msg.width = cvImage.cols;
msg.height = cvImage.rows;
msg.row_stride = cvImage.step;
msg.nmetadata = 0;
// compress if necessary
uint8_t* data = cvImage.data;
msg.size = msg.height*msg.row_stride;
if (shouldCompress) {
std::vector<uint8_t> dest(msg.height*msg.row_stride);
jpeg_compress_8u_rgb(data, msg.width, msg.height, msg.row_stride,
dest.data(), &msg.size, compressionQuality);
msg.pixelformat = bot_core::image_t::PIXEL_FORMAT_MJPEG;
msg.data.resize(msg.size);
std::copy(dest.data(), dest.data()+msg.size, msg.data.begin());
}
// otherwise just set raw bytes
else {
msg.pixelformat = bot_core::image_t::PIXEL_FORMAT_RGB;
msg.data.resize(msg.size);
std::copy(data, data + msg.size, msg.data.begin());
}
// transmit message
lcm.publish(channel, &msg);
// print frame rate
++imageCount;
totalBytes += msg.data.size();
if (prevTime == 0) prevTime = msg.utime;
double timeDelta = (msg.utime - prevTime)/1e6;
if (timeDelta > 5) {
double bitRate = totalBytes/timeDelta*8/1024;
std::string rateUnit = "Kbps";
if (bitRate > 1024) {
bitRate /= 1024;
rateUnit = "Mbps";
}
fprintf(stdout, "%.1f Hz, %.2f %s\n", imageCount/timeDelta, bitRate,
rateUnit.c_str());
prevTime = msg.utime;
imageCount = 0;
totalBytes = 0;
}
// sleep if necessary
int64_t elapsedMs = (bot_timestamp_now() - checkpointStart)/1000;
if (periodMs > 0) {
std::this_thread::sleep_for
(std::chrono::milliseconds(periodMs - elapsedMs));
}
}
// clean up
error = camera.StopCapture();
if (error != FlyCapture2::PGRERROR_OK) {}
camera.Disconnect();
return 0;
}
<commit_msg>git-svn-id: https://svn.csail.mit.edu/drc/trunk@6338 c7283977-0100-402a-a91a-fa70b306dbfe<commit_after>#include <iostream>
#include <thread>
#include <chrono>
#include <opencv2/opencv.hpp>
#include <bot_core/timestamp.h>
#include <jpeg-utils/jpeg-utils.h>
#include <lcm/lcm-cpp.hpp>
#include <ConciseArgs>
#include <flycapture/FlyCapture2.h>
#include <lcmtypes/bot_core/image_t.hpp>
int main(const int iArgc, const char** iArgv) {
// parse arguments
std::string channel = "DUMMY_CAMERA_CHANNEL";
int compressionQuality = 100;
int frameRate = 0;
int rotation = 0;
int64_t desiredSerial = -1;
ConciseArgs opt(iArgc, (char**)iArgv);
opt.add(channel, "c", "channel", "output channel");
opt.add(compressionQuality, "q", "quality",
"compression quality (100=no compression)");
opt.add(frameRate, "f", "framerate", "frame rate (0=max)");
opt.add(rotation, "r", "rotation", "rotation (0,90,180,270)");
opt.add(desiredSerial, "s", "serial number");
opt.parse();
if ((rotation != 0) && (rotation != 90) &&
(rotation != 180) && (rotation != 270)) {
std::cout << "error: invalid rotation " << rotation << std::endl;
return -1;
}
bool shouldCompress = (compressionQuality < 100);
int periodMs = (frameRate == 0 ? 0 : 1000/frameRate);
lcm::LCM lcm;
// determine which camera id to connect to
FlyCapture2::Error error;
FlyCapture2::PGRGuid cameraUid;
bool foundCamera = false;
if (desiredSerial >= 0) {
std::cout << "About to create FlyCapture2 Object\n";
FlyCapture2::BusManager busManager;
std::cout << "... finished creating\n";
unsigned int numCameras;
error = busManager.GetNumOfCameras(&numCameras);
if (error != FlyCapture2::PGRERROR_OK) {
std::cout << "Could not get number of cameras" << std::endl;
return -1;
}
for (int i = 0; i < numCameras; ++i) {
unsigned int curSerial;
error = busManager.GetCameraSerialNumberFromIndex(i, &curSerial);
if (error != FlyCapture2::PGRERROR_OK) {
std::cout << "Could not get serial number from index " <<
i << std::endl;
return -1;
}
if (curSerial == desiredSerial) {
error = busManager.GetCameraFromIndex(i, &cameraUid);
if (error != FlyCapture2::PGRERROR_OK) {
std::cout << "Could not get camera id from index " <<
i << std::endl;
return -1;
}
foundCamera = true;
break;
}
}
if (!foundCamera) {
std::cout << "Could not find camera with serial " <<
desiredSerial << std::endl;
return -1;
}
}
FlyCapture2::Camera camera;
FlyCapture2::CameraInfo camInfo;
// connect to camera
if (desiredSerial >= 0) {
error = camera.Connect(&cameraUid);
}
else {
error = camera.Connect(NULL);
}
if (error != FlyCapture2::PGRERROR_OK) {
std::cout << "Failed to connect to camera" << std::endl;
return -1;
}
// stop capture if in bad state
error = camera.StopCapture();
if (error != FlyCapture2::PGRERROR_OK) {}
// get camera info
error = camera.GetCameraInfo(&camInfo);
if (error != FlyCapture2::PGRERROR_OK) {
std::cout << "Failed to get camera info from camera" << std::endl;
return -1;
}
std::cout << "Camera information: "
<< camInfo.vendorName << " "
<< camInfo.modelName << " "
<< camInfo.serialNumber << std::endl;
error = camera.StartCapture();
if (error == FlyCapture2::PGRERROR_ISOCH_BANDWIDTH_EXCEEDED) {
std::cout << "Bandwidth exceeded" << std::endl;
return -1;
}
else if (error != FlyCapture2::PGRERROR_OK) {
std::cout << "Failed to start image capture" << std::endl;
return -1;
}
int64_t imageCount = 0;
int64_t totalBytes = 0;
int64_t prevTime = 0;
while (true) {
int64_t checkpointStart = bot_timestamp_now();
// grab image
FlyCapture2::Image rawImage;
error = camera.RetrieveBuffer(&rawImage);
if (error != FlyCapture2::PGRERROR_OK) {
std::cout << "capture error" << std::endl;
continue;
}
// TODO: this can be grabbed from image metadata via GetTimeStamp()
int64_t imageTime = bot_timestamp_now();
// convert to rgb
FlyCapture2::Image rgbImage;
rawImage.Convert(FlyCapture2::PIXEL_FORMAT_RGB, &rgbImage);
// convert to opencv
cv::Mat cvImage(rgbImage.GetRows(), rgbImage.GetCols(), CV_8UC3,
rgbImage.GetData(), rgbImage.GetStride());
// rotate
switch (rotation) {
case 0:
break;
case 90:
cv::transpose(cvImage, cvImage);
cv::flip(cvImage, cvImage, 1);
break;
case 180:
cv::flip(cvImage, cvImage, -1);
break;
case 270:
cv::transpose(cvImage, cvImage);
cv::flip(cvImage, cvImage, 0);
break;
default:
std::cout << "error: cannot rotate by " << rotation << std::endl;
break;
}
// convert to libbot image type
bot_core::image_t msg;
msg.utime = imageTime;
msg.width = cvImage.cols;
msg.height = cvImage.rows;
msg.row_stride = cvImage.step;
msg.nmetadata = 0;
// compress if necessary
uint8_t* data = cvImage.data;
msg.size = msg.height*msg.row_stride;
if (shouldCompress) {
std::vector<uint8_t> dest(msg.height*msg.row_stride);
jpeg_compress_8u_rgb(data, msg.width, msg.height, msg.row_stride,
dest.data(), &msg.size, compressionQuality);
msg.pixelformat = bot_core::image_t::PIXEL_FORMAT_MJPEG;
msg.data.resize(msg.size);
std::copy(dest.data(), dest.data()+msg.size, msg.data.begin());
}
// otherwise just set raw bytes
else {
msg.pixelformat = bot_core::image_t::PIXEL_FORMAT_RGB;
msg.data.resize(msg.size);
std::copy(data, data + msg.size, msg.data.begin());
}
// transmit message
lcm.publish(channel, &msg);
// print frame rate
++imageCount;
totalBytes += msg.data.size();
if (prevTime == 0) prevTime = msg.utime;
double timeDelta = (msg.utime - prevTime)/1e6;
if (timeDelta > 5) {
double bitRate = totalBytes/timeDelta*8/1024;
std::string rateUnit = "Kbps";
if (bitRate > 1024) {
bitRate /= 1024;
rateUnit = "Mbps";
}
fprintf(stdout, "%.1f Hz, %.2f %s\n", imageCount/timeDelta, bitRate,
rateUnit.c_str());
prevTime = msg.utime;
imageCount = 0;
totalBytes = 0;
}
// sleep if necessary
int64_t elapsedMs = (bot_timestamp_now() - checkpointStart)/1000;
if (periodMs > 0) {
std::this_thread::sleep_for
(std::chrono::milliseconds(periodMs - elapsedMs));
}
}
// clean up
error = camera.StopCapture();
if (error != FlyCapture2::PGRERROR_OK) {}
camera.Disconnect();
return 0;
}
<|endoftext|> |
<commit_before>#include <FAST/Testing.hpp>
#include <FAST/Importers/WholeSlideImageImporter.hpp>
#include <FAST/Visualization/ImagePyramidRenderer/ImagePyramidRenderer.hpp>
#include <FAST/Visualization/ImageRenderer/ImageRenderer.hpp>
#include <FAST/Visualization/SimpleWindow.hpp>
#include <FAST/Data/ImagePyramid.hpp>
#include <FAST/Data/Image.hpp>
#include <FAST/Algorithms/ImagePatch/PatchGenerator.hpp>
#include <FAST/Algorithms/ImagePatch/PatchStitcher.hpp>
#include <FAST/Algorithms/ImagePatch/ImageToBatchGenerator.hpp>
#include <FAST/Algorithms/NeuralNetwork/NeuralNetwork.hpp>
#include <FAST/Importers/ImageFileImporter.hpp>
#include <FAST/Visualization/VolumeRenderer/AlphaBlendingVolumeRenderer.hpp>
using namespace fast;
TEST_CASE("Patch generator for WSI", "[fast][wsi][PatchGenerator][visual]") {
auto importer = WholeSlideImageImporter::New();
importer->setFilename(Config::getTestDataPath() + "/CMU-1.tiff");
auto generator = PatchGenerator::New();
generator->setPatchSize(512, 512);
generator->setPatchLevel(0);
generator->setInputConnection(importer->getOutputPort());
auto renderer = ImageRenderer::New();
renderer->addInputConnection(generator->getOutputPort());
auto window = SimpleWindow::New();
window->addRenderer(renderer);
window->setTimeout(2000);
window->set2DMode();
window->start();
}
TEST_CASE("Patch generator for volumes", "[fast][volume][PatchGenerator][visual]") {
auto importer = ImageFileImporter::New();
importer->setFilename(Config::getTestDataPath() + "/CT/CT-Thorax.mhd");
auto generator = PatchGenerator::New();
generator->setPatchSize(512, 512, 32);
generator->setInputConnection(importer->getOutputPort());
auto renderer = AlphaBlendingVolumeRenderer::New();
renderer->setTransferFunction(TransferFunction::CT_Blood_And_Bone());
renderer->addInputConnection(generator->getOutputPort());
auto window = SimpleWindow::New();
window->addRenderer(renderer);
window->setTimeout(3000);
window->start();
}
TEST_CASE("Patch generator and stitcher for volumes", "[fast][volume][patchgenerator][PatchStitcher][visual]") {
auto importer = ImageFileImporter::New();
importer->setFilename(Config::getTestDataPath() + "/CT/CT-Thorax.mhd");
auto generator = PatchGenerator::New();
generator->setPatchSize(512, 512, 32);
generator->setInputConnection(importer->getOutputPort());
auto stitcher = PatchStitcher::New();
stitcher->setInputConnection(generator->getOutputPort());
auto renderer = AlphaBlendingVolumeRenderer::New();
renderer->setTransferFunction(TransferFunction::CT_Blood_And_Bone());
renderer->addInputConnection(stitcher->getOutputPort());
auto window = SimpleWindow::New();
window->addRenderer(renderer);
window->setTimeout(1000);
window->start();
}
TEST_CASE("Patch generator and stitcher for WSI", "[fast][wsi][PatchStitcher][visual]") {
auto importer = WholeSlideImageImporter::New();
importer->setFilename(Config::getTestDataPath() + "/CMU-1.tiff");
auto generator = PatchGenerator::New();
generator->setPatchSize(512, 512);
generator->setPatchLevel(4);
generator->setInputConnection(importer->getOutputPort());
auto stitcher = PatchStitcher::New();
stitcher->setInputConnection(generator->getOutputPort());
auto renderer = ImageRenderer::New();
renderer->addInputConnection(stitcher->getOutputPort());
auto window = SimpleWindow::New();
window->addRenderer(renderer);
//window->setTimeout(1000);
window->set2DMode();
window->start();
}
TEST_CASE("Patch generator, sticher and image to batch generator for WSI", "[fast][wsi][ImageToBatchGenerator]") {
auto importer = WholeSlideImageImporter::New();
importer->setFilename(Config::getTestDataPath() + "/CMU-1.tiff");
auto generator = PatchGenerator::New();
generator->setPatchSize(512, 512);
generator->setPatchLevel(4);
generator->setInputConnection(importer->getOutputPort());
auto batchGenerator = ImageToBatchGenerator::New();
batchGenerator->setInputConnection(generator->getOutputPort());
batchGenerator->setMaxBatchSize(4);
auto port = batchGenerator->getOutputPort();
Batch::pointer batch;
int i = 0;
do {
batchGenerator->update(); // This will only call execute once
batch = port->getNextFrame<Batch>(); // This will block if batch does not exist atm
std::cout << "Got a batch" << std::endl;
} while(!batch->isLastFrame());
std::cout << "Done" << std::endl;
}<commit_msg>Fixed some WSI patch tests which used old data<commit_after>#include <FAST/Testing.hpp>
#include <FAST/Importers/WholeSlideImageImporter.hpp>
#include <FAST/Visualization/ImagePyramidRenderer/ImagePyramidRenderer.hpp>
#include <FAST/Visualization/ImageRenderer/ImageRenderer.hpp>
#include <FAST/Visualization/SimpleWindow.hpp>
#include <FAST/Data/ImagePyramid.hpp>
#include <FAST/Data/Image.hpp>
#include <FAST/Algorithms/ImagePatch/PatchGenerator.hpp>
#include <FAST/Algorithms/ImagePatch/PatchStitcher.hpp>
#include <FAST/Algorithms/ImagePatch/ImageToBatchGenerator.hpp>
#include <FAST/Algorithms/NeuralNetwork/NeuralNetwork.hpp>
#include <FAST/Importers/ImageFileImporter.hpp>
#include <FAST/Visualization/VolumeRenderer/AlphaBlendingVolumeRenderer.hpp>
using namespace fast;
TEST_CASE("Patch generator for WSI", "[fast][wsi][PatchGenerator][visual]") {
auto importer = WholeSlideImageImporter::New();
importer->setFilename(Config::getTestDataPath() + "/WSI/A05.svs");
auto generator = PatchGenerator::New();
generator->setPatchSize(512, 512);
generator->setPatchLevel(0);
generator->setInputConnection(importer->getOutputPort());
auto renderer = ImageRenderer::New();
renderer->addInputConnection(generator->getOutputPort());
auto window = SimpleWindow::New();
window->addRenderer(renderer);
window->setTimeout(2000);
window->set2DMode();
window->start();
}
TEST_CASE("Patch generator for volumes", "[fast][volume][PatchGenerator][visual]") {
auto importer = ImageFileImporter::New();
importer->setFilename(Config::getTestDataPath() + "/CT/CT-Thorax.mhd");
auto generator = PatchGenerator::New();
generator->setPatchSize(512, 512, 32);
generator->setInputConnection(importer->getOutputPort());
auto renderer = AlphaBlendingVolumeRenderer::New();
renderer->setTransferFunction(TransferFunction::CT_Blood_And_Bone());
renderer->addInputConnection(generator->getOutputPort());
auto window = SimpleWindow::New();
window->addRenderer(renderer);
window->setTimeout(3000);
window->start();
}
TEST_CASE("Patch generator and stitcher for volumes", "[fast][volume][patchgenerator][PatchStitcher][visual]") {
auto importer = ImageFileImporter::New();
importer->setFilename(Config::getTestDataPath() + "/CT/CT-Thorax.mhd");
auto generator = PatchGenerator::New();
generator->setPatchSize(512, 512, 32);
generator->setInputConnection(importer->getOutputPort());
auto stitcher = PatchStitcher::New();
stitcher->setInputConnection(generator->getOutputPort());
auto renderer = AlphaBlendingVolumeRenderer::New();
renderer->setTransferFunction(TransferFunction::CT_Blood_And_Bone());
renderer->addInputConnection(stitcher->getOutputPort());
auto window = SimpleWindow::New();
window->addRenderer(renderer);
window->setTimeout(1000);
window->start();
}
TEST_CASE("Patch generator and stitcher for WSI", "[fast][wsi][PatchStitcher][visual]") {
auto importer = WholeSlideImageImporter::New();
importer->setFilename(Config::getTestDataPath() + "/WSI/A05.svs");
auto generator = PatchGenerator::New();
generator->setPatchSize(512, 512);
generator->setPatchLevel(2);
generator->setInputConnection(importer->getOutputPort());
auto stitcher = PatchStitcher::New();
stitcher->setInputConnection(generator->getOutputPort());
auto renderer = ImageRenderer::New();
renderer->addInputConnection(stitcher->getOutputPort());
auto window = SimpleWindow::New();
window->addRenderer(renderer);
window->setTimeout(3000);
window->set2DMode();
window->start();
}
TEST_CASE("Patch generator, sticher and image to batch generator for WSI", "[fast][wsi][ImageToBatchGenerator]") {
auto importer = WholeSlideImageImporter::New();
importer->setFilename(Config::getTestDataPath() + "/WSI/A05.svs");
auto generator = PatchGenerator::New();
generator->setPatchSize(512, 512);
generator->setPatchLevel(2);
generator->setInputConnection(importer->getOutputPort());
auto batchGenerator = ImageToBatchGenerator::New();
batchGenerator->setInputConnection(generator->getOutputPort());
batchGenerator->setMaxBatchSize(4);
auto port = batchGenerator->getOutputPort();
Batch::pointer batch;
int i = 0;
do {
batchGenerator->update(); // This will only call execute once
batch = port->getNextFrame<Batch>(); // This will block if batch does not exist atm
std::cout << "Got a batch" << std::endl;
} while(!batch->isLastFrame());
std::cout << "Done" << std::endl;
}<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/logging.h"
#include "views/window/client_view.h"
#if defined(OS_LINUX)
#include "views/window/hit_test.h"
#endif
#include "views/window/window.h"
#include "views/window/window_delegate.h"
namespace views {
///////////////////////////////////////////////////////////////////////////////
// ClientView, public:
ClientView::ClientView(Window* window, View* contents_view)
: window_(window),
contents_view_(contents_view) {
}
int ClientView::NonClientHitTest(const gfx::Point& point) {
return bounds().Contains(point) ? HTCLIENT : HTNOWHERE;
}
void ClientView::WindowClosing() {
window_->GetDelegate()->WindowClosing();
}
///////////////////////////////////////////////////////////////////////////////
// ClientView, View overrides:
gfx::Size ClientView::GetPreferredSize() {
// |contents_view_| is allowed to be NULL up until the point where this view
// is attached to a Container.
if (contents_view_)
return contents_view_->GetPreferredSize();
return gfx::Size();
}
void ClientView::Layout() {
// |contents_view_| is allowed to be NULL up until the point where this view
// is attached to a Container.
if (contents_view_)
contents_view_->SetBounds(0, 0, width(), height());
}
void ClientView::ViewHierarchyChanged(bool is_add, View* parent, View* child) {
if (is_add && child == this) {
DCHECK(GetWidget());
DCHECK(contents_view_); // |contents_view_| must be valid now!
AddChildView(contents_view_);
}
}
void ClientView::DidChangeBounds(const gfx::Rect& previous,
const gfx::Rect& current) {
// Overridden to do nothing. The NonClientView manually calls Layout on the
// ClientView when it is itself laid out, see comment in
// NonClientView::Layout.
}
bool ClientView::GetAccessibleRole(AccessibilityTypes::Role* role) {
*role = AccessibilityTypes::ROLE_CLIENT;
return true;
}
} // namespace views
<commit_msg>Fix focus traversal order in dialogs. In a dialog, the contents view is added after the buttons have been added. That would mess up the focus traversal order. The problem was particularly visible in the basic auth dialog. This CL ensures the contents is added as the first view so the focus chain is right.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/logging.h"
#include "views/window/client_view.h"
#if defined(OS_LINUX)
#include "views/window/hit_test.h"
#endif
#include "views/window/window.h"
#include "views/window/window_delegate.h"
namespace views {
///////////////////////////////////////////////////////////////////////////////
// ClientView, public:
ClientView::ClientView(Window* window, View* contents_view)
: window_(window),
contents_view_(contents_view) {
}
int ClientView::NonClientHitTest(const gfx::Point& point) {
return bounds().Contains(point) ? HTCLIENT : HTNOWHERE;
}
void ClientView::WindowClosing() {
window_->GetDelegate()->WindowClosing();
}
///////////////////////////////////////////////////////////////////////////////
// ClientView, View overrides:
gfx::Size ClientView::GetPreferredSize() {
// |contents_view_| is allowed to be NULL up until the point where this view
// is attached to a Container.
if (contents_view_)
return contents_view_->GetPreferredSize();
return gfx::Size();
}
void ClientView::Layout() {
// |contents_view_| is allowed to be NULL up until the point where this view
// is attached to a Container.
if (contents_view_)
contents_view_->SetBounds(0, 0, width(), height());
}
void ClientView::ViewHierarchyChanged(bool is_add, View* parent, View* child) {
if (is_add && child == this) {
DCHECK(GetWidget());
DCHECK(contents_view_); // |contents_view_| must be valid now!
// Insert |contents_view_| at index 0 so it is first in the focus chain.
// (the OK/Cancel buttons are inserted before contents_view_)
AddChildView(0, contents_view_);
}
}
void ClientView::DidChangeBounds(const gfx::Rect& previous,
const gfx::Rect& current) {
// Overridden to do nothing. The NonClientView manually calls Layout on the
// ClientView when it is itself laid out, see comment in
// NonClientView::Layout.
}
bool ClientView::GetAccessibleRole(AccessibilityTypes::Role* role) {
*role = AccessibilityTypes::ROLE_CLIENT;
return true;
}
} // namespace views
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "ipc/ipc_channel_proxy.h"
#include "ipc/ipc_logging.h"
#include "ipc/ipc_message_utils.h"
namespace IPC {
//------------------------------------------------------------------------------
// This task ensures the message is deleted if the task is deleted without
// having been run.
class SendTask : public Task {
public:
SendTask(ChannelProxy::Context* context, Message* message)
: context_(context),
message_(message) {
}
virtual void Run() {
context_->OnSendMessage(message_.release());
}
private:
scoped_refptr<ChannelProxy::Context> context_;
scoped_ptr<Message> message_;
DISALLOW_COPY_AND_ASSIGN(SendTask);
};
//------------------------------------------------------------------------------
ChannelProxy::MessageFilter::MessageFilter() {}
ChannelProxy::MessageFilter::~MessageFilter() {}
void ChannelProxy::MessageFilter::OnFilterAdded(Channel* channel) {}
void ChannelProxy::MessageFilter::OnFilterRemoved() {}
void ChannelProxy::MessageFilter::OnChannelConnected(int32 peer_pid) {}
void ChannelProxy::MessageFilter::OnChannelError() {}
void ChannelProxy::MessageFilter::OnChannelClosing() {}
bool ChannelProxy::MessageFilter::OnMessageReceived(const Message& message) {
return false;
}
void ChannelProxy::MessageFilter::OnDestruct() const {
delete this;
}
//------------------------------------------------------------------------------
ChannelProxy::Context::Context(Channel::Listener* listener,
base::MessageLoopProxy* ipc_message_loop)
: listener_message_loop_(base::MessageLoopProxy::current()),
listener_(listener),
ipc_message_loop_(ipc_message_loop),
peer_pid_(0),
channel_connected_called_(false) {
}
ChannelProxy::Context::~Context() {
}
void ChannelProxy::Context::CreateChannel(const IPC::ChannelHandle& handle,
const Channel::Mode& mode) {
DCHECK(channel_.get() == NULL);
channel_id_ = handle.name;
channel_.reset(new Channel(handle, mode, this));
}
bool ChannelProxy::Context::TryFilters(const Message& message) {
#ifdef IPC_MESSAGE_LOG_ENABLED
Logging* logger = Logging::GetInstance();
if (logger->Enabled())
logger->OnPreDispatchMessage(message);
#endif
for (size_t i = 0; i < filters_.size(); ++i) {
if (filters_[i]->OnMessageReceived(message)) {
#ifdef IPC_MESSAGE_LOG_ENABLED
if (logger->Enabled())
logger->OnPostDispatchMessage(message, channel_id_);
#endif
return true;
}
}
return false;
}
// Called on the IPC::Channel thread
bool ChannelProxy::Context::OnMessageReceived(const Message& message) {
// First give a chance to the filters to process this message.
if (!TryFilters(message))
OnMessageReceivedNoFilter(message);
return true;
}
// Called on the IPC::Channel thread
bool ChannelProxy::Context::OnMessageReceivedNoFilter(const Message& message) {
// NOTE: This code relies on the listener's message loop not going away while
// this thread is active. That should be a reasonable assumption, but it
// feels risky. We may want to invent some more indirect way of referring to
// a MessageLoop if this becomes a problem.
listener_message_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &Context::OnDispatchMessage, message));
return true;
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelConnected(int32 peer_pid) {
// Add any pending filters. This avoids a race condition where someone
// creates a ChannelProxy, calls AddFilter, and then right after starts the
// peer process. The IO thread could receive a message before the task to add
// the filter is run on the IO thread.
OnAddFilter();
peer_pid_ = peer_pid;
for (size_t i = 0; i < filters_.size(); ++i)
filters_[i]->OnChannelConnected(peer_pid);
// See above comment about using listener_message_loop_ here.
listener_message_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &Context::OnDispatchConnected));
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelError() {
for (size_t i = 0; i < filters_.size(); ++i)
filters_[i]->OnChannelError();
// See above comment about using listener_message_loop_ here.
listener_message_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &Context::OnDispatchError));
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelOpened() {
DCHECK(channel_ != NULL);
// Assume a reference to ourselves on behalf of this thread. This reference
// will be released when we are closed.
AddRef();
if (!channel_->Connect()) {
OnChannelError();
return;
}
for (size_t i = 0; i < filters_.size(); ++i)
filters_[i]->OnFilterAdded(channel_.get());
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelClosed() {
// It's okay for IPC::ChannelProxy::Close to be called more than once, which
// would result in this branch being taken.
if (!channel_.get())
return;
for (size_t i = 0; i < filters_.size(); ++i) {
filters_[i]->OnChannelClosing();
filters_[i]->OnFilterRemoved();
}
// We don't need the filters anymore.
filters_.clear();
channel_.reset();
// Balance with the reference taken during startup. This may result in
// self-destruction.
Release();
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnSendMessage(Message* message) {
if (!channel_.get()) {
delete message;
OnChannelClosed();
return;
}
if (!channel_->Send(message))
OnChannelError();
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnAddFilter() {
std::vector<scoped_refptr<MessageFilter> > filters;
{
base::AutoLock auto_lock(pending_filters_lock_);
filters.swap(pending_filters_);
}
for (size_t i = 0; i < filters.size(); ++i) {
filters_.push_back(filters[i]);
// If the channel has already been created, then we need to send this
// message so that the filter gets access to the Channel.
if (channel_.get())
filters[i]->OnFilterAdded(channel_.get());
// Ditto for the peer process id.
if (peer_pid_)
filters[i]->OnChannelConnected(peer_pid_);
}
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnRemoveFilter(MessageFilter* filter) {
for (size_t i = 0; i < filters_.size(); ++i) {
if (filters_[i].get() == filter) {
filter->OnFilterRemoved();
filters_.erase(filters_.begin() + i);
return;
}
}
NOTREACHED() << "filter to be removed not found";
}
// Called on the listener's thread
void ChannelProxy::Context::AddFilter(MessageFilter* filter) {
base::AutoLock auto_lock(pending_filters_lock_);
pending_filters_.push_back(make_scoped_refptr(filter));
ipc_message_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &Context::OnAddFilter));
}
// Called on the listener's thread
void ChannelProxy::Context::OnDispatchMessage(const Message& message) {
if (!listener_)
return;
OnDispatchConnected();
#ifdef IPC_MESSAGE_LOG_ENABLED
Logging* logger = Logging::GetInstance();
if (message.type() == IPC_LOGGING_ID) {
logger->OnReceivedLoggingMessage(message);
return;
}
if (logger->Enabled())
logger->OnPreDispatchMessage(message);
#endif
listener_->OnMessageReceived(message);
#ifdef IPC_MESSAGE_LOG_ENABLED
if (logger->Enabled())
logger->OnPostDispatchMessage(message, channel_id_);
#endif
}
// Called on the listener's thread
void ChannelProxy::Context::OnDispatchConnected() {
if (channel_connected_called_)
return;
channel_connected_called_ = true;
if (listener_)
listener_->OnChannelConnected(peer_pid_);
}
// Called on the listener's thread
void ChannelProxy::Context::OnDispatchError() {
if (listener_)
listener_->OnChannelError();
}
//-----------------------------------------------------------------------------
ChannelProxy::ChannelProxy(const IPC::ChannelHandle& channel_handle,
Channel::Mode mode,
Channel::Listener* listener,
base::MessageLoopProxy* ipc_thread)
: context_(new Context(listener, ipc_thread)),
outgoing_message_filter_(NULL) {
Init(channel_handle, mode, ipc_thread, true);
}
ChannelProxy::ChannelProxy(const IPC::ChannelHandle& channel_handle,
Channel::Mode mode,
base::MessageLoopProxy* ipc_thread,
Context* context,
bool create_pipe_now)
: context_(context),
outgoing_message_filter_(NULL) {
Init(channel_handle, mode, ipc_thread, create_pipe_now);
}
ChannelProxy::~ChannelProxy() {
Close();
}
void ChannelProxy::Init(const IPC::ChannelHandle& channel_handle,
Channel::Mode mode,
base::MessageLoopProxy* ipc_thread_loop,
bool create_pipe_now) {
#if defined(OS_POSIX)
// When we are creating a server on POSIX, we need its file descriptor
// to be created immediately so that it can be accessed and passed
// to other processes. Forcing it to be created immediately avoids
// race conditions that may otherwise arise.
if (mode & Channel::MODE_SERVER_FLAG) {
create_pipe_now = true;
}
#endif // defined(OS_POSIX)
if (create_pipe_now) {
// Create the channel immediately. This effectively sets up the
// low-level pipe so that the client can connect. Without creating
// the pipe immediately, it is possible for a listener to attempt
// to connect and get an error since the pipe doesn't exist yet.
context_->CreateChannel(channel_handle, mode);
} else {
context_->ipc_message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
context_.get(), &Context::CreateChannel, channel_handle, mode));
}
// complete initialization on the background thread
context_->ipc_message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
context_.get(), &Context::OnChannelOpened));
}
void ChannelProxy::Close() {
// Clear the backpointer to the listener so that any pending calls to
// Context::OnDispatchMessage or OnDispatchError will be ignored. It is
// possible that the channel could be closed while it is receiving messages!
context_->Clear();
if (context_->ipc_message_loop()) {
context_->ipc_message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
context_.get(), &Context::OnChannelClosed));
}
}
bool ChannelProxy::Send(Message* message) {
if (outgoing_message_filter())
message = outgoing_message_filter()->Rewrite(message);
#ifdef IPC_MESSAGE_LOG_ENABLED
Logging::GetInstance()->OnSendMessage(message, context_->channel_id());
#endif
context_->ipc_message_loop()->PostTask(FROM_HERE,
new SendTask(context_.get(), message));
return true;
}
void ChannelProxy::AddFilter(MessageFilter* filter) {
context_->AddFilter(filter);
}
void ChannelProxy::RemoveFilter(MessageFilter* filter) {
context_->ipc_message_loop()->PostTask(
FROM_HERE, NewRunnableMethod(
context_.get(),
&Context::OnRemoveFilter,
make_scoped_refptr(filter)));
}
void ChannelProxy::ClearIPCMessageLoop() {
context()->ClearIPCMessageLoop();
}
#if defined(OS_POSIX) && !defined(OS_NACL)
// See the TODO regarding lazy initialization of the channel in
// ChannelProxy::Init().
// We assume that IPC::Channel::GetClientFileDescriptorMapping() is thread-safe.
int ChannelProxy::GetClientFileDescriptor() const {
Channel *channel = context_.get()->channel_.get();
// Channel must have been created first.
DCHECK(channel) << context_.get()->channel_id_;
return channel->GetClientFileDescriptor();
}
bool ChannelProxy::GetClientEuid(uid_t* client_euid) const {
Channel *channel = context_.get()->channel_.get();
// Channel must have been created first.
DCHECK(channel) << context_.get()->channel_id_;
return channel->GetClientEuid(client_euid);
}
#endif
//-----------------------------------------------------------------------------
} // namespace IPC
<commit_msg>ipc: rename a variable to make code clearer<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "ipc/ipc_channel_proxy.h"
#include "ipc/ipc_logging.h"
#include "ipc/ipc_message_utils.h"
namespace IPC {
//------------------------------------------------------------------------------
// This task ensures the message is deleted if the task is deleted without
// having been run.
class SendTask : public Task {
public:
SendTask(ChannelProxy::Context* context, Message* message)
: context_(context),
message_(message) {
}
virtual void Run() {
context_->OnSendMessage(message_.release());
}
private:
scoped_refptr<ChannelProxy::Context> context_;
scoped_ptr<Message> message_;
DISALLOW_COPY_AND_ASSIGN(SendTask);
};
//------------------------------------------------------------------------------
ChannelProxy::MessageFilter::MessageFilter() {}
ChannelProxy::MessageFilter::~MessageFilter() {}
void ChannelProxy::MessageFilter::OnFilterAdded(Channel* channel) {}
void ChannelProxy::MessageFilter::OnFilterRemoved() {}
void ChannelProxy::MessageFilter::OnChannelConnected(int32 peer_pid) {}
void ChannelProxy::MessageFilter::OnChannelError() {}
void ChannelProxy::MessageFilter::OnChannelClosing() {}
bool ChannelProxy::MessageFilter::OnMessageReceived(const Message& message) {
return false;
}
void ChannelProxy::MessageFilter::OnDestruct() const {
delete this;
}
//------------------------------------------------------------------------------
ChannelProxy::Context::Context(Channel::Listener* listener,
base::MessageLoopProxy* ipc_message_loop)
: listener_message_loop_(base::MessageLoopProxy::current()),
listener_(listener),
ipc_message_loop_(ipc_message_loop),
peer_pid_(0),
channel_connected_called_(false) {
}
ChannelProxy::Context::~Context() {
}
void ChannelProxy::Context::CreateChannel(const IPC::ChannelHandle& handle,
const Channel::Mode& mode) {
DCHECK(channel_.get() == NULL);
channel_id_ = handle.name;
channel_.reset(new Channel(handle, mode, this));
}
bool ChannelProxy::Context::TryFilters(const Message& message) {
#ifdef IPC_MESSAGE_LOG_ENABLED
Logging* logger = Logging::GetInstance();
if (logger->Enabled())
logger->OnPreDispatchMessage(message);
#endif
for (size_t i = 0; i < filters_.size(); ++i) {
if (filters_[i]->OnMessageReceived(message)) {
#ifdef IPC_MESSAGE_LOG_ENABLED
if (logger->Enabled())
logger->OnPostDispatchMessage(message, channel_id_);
#endif
return true;
}
}
return false;
}
// Called on the IPC::Channel thread
bool ChannelProxy::Context::OnMessageReceived(const Message& message) {
// First give a chance to the filters to process this message.
if (!TryFilters(message))
OnMessageReceivedNoFilter(message);
return true;
}
// Called on the IPC::Channel thread
bool ChannelProxy::Context::OnMessageReceivedNoFilter(const Message& message) {
// NOTE: This code relies on the listener's message loop not going away while
// this thread is active. That should be a reasonable assumption, but it
// feels risky. We may want to invent some more indirect way of referring to
// a MessageLoop if this becomes a problem.
listener_message_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &Context::OnDispatchMessage, message));
return true;
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelConnected(int32 peer_pid) {
// Add any pending filters. This avoids a race condition where someone
// creates a ChannelProxy, calls AddFilter, and then right after starts the
// peer process. The IO thread could receive a message before the task to add
// the filter is run on the IO thread.
OnAddFilter();
peer_pid_ = peer_pid;
for (size_t i = 0; i < filters_.size(); ++i)
filters_[i]->OnChannelConnected(peer_pid);
// See above comment about using listener_message_loop_ here.
listener_message_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &Context::OnDispatchConnected));
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelError() {
for (size_t i = 0; i < filters_.size(); ++i)
filters_[i]->OnChannelError();
// See above comment about using listener_message_loop_ here.
listener_message_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &Context::OnDispatchError));
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelOpened() {
DCHECK(channel_ != NULL);
// Assume a reference to ourselves on behalf of this thread. This reference
// will be released when we are closed.
AddRef();
if (!channel_->Connect()) {
OnChannelError();
return;
}
for (size_t i = 0; i < filters_.size(); ++i)
filters_[i]->OnFilterAdded(channel_.get());
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelClosed() {
// It's okay for IPC::ChannelProxy::Close to be called more than once, which
// would result in this branch being taken.
if (!channel_.get())
return;
for (size_t i = 0; i < filters_.size(); ++i) {
filters_[i]->OnChannelClosing();
filters_[i]->OnFilterRemoved();
}
// We don't need the filters anymore.
filters_.clear();
channel_.reset();
// Balance with the reference taken during startup. This may result in
// self-destruction.
Release();
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnSendMessage(Message* message) {
if (!channel_.get()) {
delete message;
OnChannelClosed();
return;
}
if (!channel_->Send(message))
OnChannelError();
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnAddFilter() {
std::vector<scoped_refptr<MessageFilter> > new_filters;
{
base::AutoLock auto_lock(pending_filters_lock_);
new_filters.swap(pending_filters_);
}
for (size_t i = 0; i < new_filters.size(); ++i) {
filters_.push_back(new_filters[i]);
// If the channel has already been created, then we need to send this
// message so that the filter gets access to the Channel.
if (channel_.get())
new_filters[i]->OnFilterAdded(channel_.get());
// Ditto for if the channel has been connected.
if (peer_pid_)
new_filters[i]->OnChannelConnected(peer_pid_);
}
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnRemoveFilter(MessageFilter* filter) {
for (size_t i = 0; i < filters_.size(); ++i) {
if (filters_[i].get() == filter) {
filter->OnFilterRemoved();
filters_.erase(filters_.begin() + i);
return;
}
}
NOTREACHED() << "filter to be removed not found";
}
// Called on the listener's thread
void ChannelProxy::Context::AddFilter(MessageFilter* filter) {
base::AutoLock auto_lock(pending_filters_lock_);
pending_filters_.push_back(make_scoped_refptr(filter));
ipc_message_loop_->PostTask(
FROM_HERE,
NewRunnableMethod(this, &Context::OnAddFilter));
}
// Called on the listener's thread
void ChannelProxy::Context::OnDispatchMessage(const Message& message) {
if (!listener_)
return;
OnDispatchConnected();
#ifdef IPC_MESSAGE_LOG_ENABLED
Logging* logger = Logging::GetInstance();
if (message.type() == IPC_LOGGING_ID) {
logger->OnReceivedLoggingMessage(message);
return;
}
if (logger->Enabled())
logger->OnPreDispatchMessage(message);
#endif
listener_->OnMessageReceived(message);
#ifdef IPC_MESSAGE_LOG_ENABLED
if (logger->Enabled())
logger->OnPostDispatchMessage(message, channel_id_);
#endif
}
// Called on the listener's thread
void ChannelProxy::Context::OnDispatchConnected() {
if (channel_connected_called_)
return;
channel_connected_called_ = true;
if (listener_)
listener_->OnChannelConnected(peer_pid_);
}
// Called on the listener's thread
void ChannelProxy::Context::OnDispatchError() {
if (listener_)
listener_->OnChannelError();
}
//-----------------------------------------------------------------------------
ChannelProxy::ChannelProxy(const IPC::ChannelHandle& channel_handle,
Channel::Mode mode,
Channel::Listener* listener,
base::MessageLoopProxy* ipc_thread)
: context_(new Context(listener, ipc_thread)),
outgoing_message_filter_(NULL) {
Init(channel_handle, mode, ipc_thread, true);
}
ChannelProxy::ChannelProxy(const IPC::ChannelHandle& channel_handle,
Channel::Mode mode,
base::MessageLoopProxy* ipc_thread,
Context* context,
bool create_pipe_now)
: context_(context),
outgoing_message_filter_(NULL) {
Init(channel_handle, mode, ipc_thread, create_pipe_now);
}
ChannelProxy::~ChannelProxy() {
Close();
}
void ChannelProxy::Init(const IPC::ChannelHandle& channel_handle,
Channel::Mode mode,
base::MessageLoopProxy* ipc_thread_loop,
bool create_pipe_now) {
#if defined(OS_POSIX)
// When we are creating a server on POSIX, we need its file descriptor
// to be created immediately so that it can be accessed and passed
// to other processes. Forcing it to be created immediately avoids
// race conditions that may otherwise arise.
if (mode & Channel::MODE_SERVER_FLAG) {
create_pipe_now = true;
}
#endif // defined(OS_POSIX)
if (create_pipe_now) {
// Create the channel immediately. This effectively sets up the
// low-level pipe so that the client can connect. Without creating
// the pipe immediately, it is possible for a listener to attempt
// to connect and get an error since the pipe doesn't exist yet.
context_->CreateChannel(channel_handle, mode);
} else {
context_->ipc_message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
context_.get(), &Context::CreateChannel, channel_handle, mode));
}
// complete initialization on the background thread
context_->ipc_message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
context_.get(), &Context::OnChannelOpened));
}
void ChannelProxy::Close() {
// Clear the backpointer to the listener so that any pending calls to
// Context::OnDispatchMessage or OnDispatchError will be ignored. It is
// possible that the channel could be closed while it is receiving messages!
context_->Clear();
if (context_->ipc_message_loop()) {
context_->ipc_message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
context_.get(), &Context::OnChannelClosed));
}
}
bool ChannelProxy::Send(Message* message) {
if (outgoing_message_filter())
message = outgoing_message_filter()->Rewrite(message);
#ifdef IPC_MESSAGE_LOG_ENABLED
Logging::GetInstance()->OnSendMessage(message, context_->channel_id());
#endif
context_->ipc_message_loop()->PostTask(FROM_HERE,
new SendTask(context_.get(), message));
return true;
}
void ChannelProxy::AddFilter(MessageFilter* filter) {
context_->AddFilter(filter);
}
void ChannelProxy::RemoveFilter(MessageFilter* filter) {
context_->ipc_message_loop()->PostTask(
FROM_HERE, NewRunnableMethod(
context_.get(),
&Context::OnRemoveFilter,
make_scoped_refptr(filter)));
}
void ChannelProxy::ClearIPCMessageLoop() {
context()->ClearIPCMessageLoop();
}
#if defined(OS_POSIX) && !defined(OS_NACL)
// See the TODO regarding lazy initialization of the channel in
// ChannelProxy::Init().
// We assume that IPC::Channel::GetClientFileDescriptorMapping() is thread-safe.
int ChannelProxy::GetClientFileDescriptor() const {
Channel *channel = context_.get()->channel_.get();
// Channel must have been created first.
DCHECK(channel) << context_.get()->channel_id_;
return channel->GetClientFileDescriptor();
}
bool ChannelProxy::GetClientEuid(uid_t* client_euid) const {
Channel *channel = context_.get()->channel_.get();
// Channel must have been created first.
DCHECK(channel) << context_.get()->channel_id_;
return channel->GetClientEuid(client_euid);
}
#endif
//-----------------------------------------------------------------------------
} // namespace IPC
<|endoftext|> |
<commit_before>/** Copyright (C) 2017 European Spallation Source ERIC */
#include <test/TestBase.h>
#pragma GCC diagnostic push
#ifdef SYSTEM_NAME_DARWIN
#pragma GCC diagnostic ignored "-Wkeyword-macro"
#pragma GCC diagnostic ignored "-Wmacro-redefined"
#endif
#define protected public
#include <common/clustering/AbstractMatcher.h>
#ifdef protected
#undef protected
#define protected protected
#endif
#pragma GCC diagnostic pop
class MockMatcher : public AbstractMatcher {
public:
explicit MockMatcher(uint64_t latency)
: AbstractMatcher(latency) {}
MockMatcher(uint64_t latency, uint8_t plane1, uint8_t plane2)
: AbstractMatcher(latency, plane1, plane2) {}
void match(bool) override {}
};
class AbstractMatcherTest : public TestBase {
protected:
ClusterContainer x, y;
void add_cluster(ClusterContainer &ret, uint8_t plane,
uint16_t coord_start, uint16_t coord_end, uint16_t coord_step,
uint64_t time_start, uint64_t time_end, uint64_t time_step) {
Cluster c;
Hit e;
e.plane = plane;
e.weight = 1;
for (e.time = time_start; e.time <= time_end; e.time += time_step)
for (e.coordinate = coord_start; e.coordinate <= coord_end; e.coordinate += coord_step)
c.insert(e);
ret.push_back(c);
}
};
TEST_F(AbstractMatcherTest, Construction1) {
MockMatcher matcher(100, 3, 7);
EXPECT_EQ(matcher.latency_, 100);
EXPECT_EQ(matcher.plane1_, 3);
EXPECT_EQ(matcher.plane2_, 7);
}
TEST_F(AbstractMatcherTest, Construction2) {
MockMatcher matcher(100);
EXPECT_EQ(matcher.latency_, 100);
EXPECT_EQ(matcher.plane1_, 0);
EXPECT_EQ(matcher.plane2_, 1);
}
TEST_F(AbstractMatcherTest, InsertingMovesData) {
MockMatcher matcher(100);
add_cluster(x, 0, 0, 10, 1, 0, 200, 10);
matcher.insert(0, x);
EXPECT_TRUE(x.empty());
}
TEST_F(AbstractMatcherTest, AcceptXY) {
MockMatcher matcher(100);
add_cluster(x, 0, 0, 10, 1, 100, 200, 10);
matcher.insert(0, x);
EXPECT_EQ(matcher.unmatched_clusters_.size(), 1);
EXPECT_EQ(matcher.latest_x_, 100);
EXPECT_EQ(matcher.latest_y_, 0);
add_cluster(y, 1, 0, 10, 1, 100, 200, 10);
matcher.insert(1, y);
EXPECT_EQ(matcher.unmatched_clusters_.size(), 2);
EXPECT_EQ(matcher.latest_x_, 100);
EXPECT_EQ(matcher.latest_y_, 100);
}
TEST_F(AbstractMatcherTest, AcceptOtherPlanes) {
MockMatcher matcher(100, 3, 4);
add_cluster(x, 3, 0, 10, 1, 100, 200, 10);
matcher.insert(3, x);
EXPECT_EQ(matcher.unmatched_clusters_.size(), 1);
EXPECT_EQ(matcher.latest_x_, 100);
EXPECT_EQ(matcher.latest_y_, 0);
add_cluster(y, 4, 0, 10, 1, 100, 200, 10);
matcher.insert(4, y);
EXPECT_EQ(matcher.unmatched_clusters_.size(), 2);
EXPECT_EQ(matcher.latest_x_, 100);
EXPECT_EQ(matcher.latest_y_, 100);
}
TEST_F(AbstractMatcherTest, RejectUnselectedPlanes) {
MockMatcher matcher(100, 3, 4);
add_cluster(x, 7, 0, 10, 1, 100, 200, 10);
matcher.insert(7, x);
EXPECT_EQ(matcher.unmatched_clusters_.size(), 0);
EXPECT_EQ(matcher.latest_x_, 0);
EXPECT_EQ(matcher.latest_y_, 0);
add_cluster(y, 0, 0, 10, 1, 100, 200, 10);
matcher.insert(0, y);
EXPECT_EQ(matcher.unmatched_clusters_.size(), 0);
EXPECT_EQ(matcher.latest_x_, 0);
EXPECT_EQ(matcher.latest_y_, 0);
}
TEST_F(AbstractMatcherTest, Ready) {
MockMatcher matcher(100);
Cluster c;
c.insert({0,0,0,0});
EXPECT_FALSE(matcher.ready_to_be_matched(c));
matcher.latest_x_ = 99;
matcher.latest_y_ = 99;
EXPECT_FALSE(matcher.ready_to_be_matched(c));
matcher.latest_x_ = 100;
matcher.latest_y_ = 100;
EXPECT_FALSE(matcher.ready_to_be_matched(c));
matcher.latest_x_ = 101;
EXPECT_FALSE(matcher.ready_to_be_matched(c));
matcher.latest_y_ = 101;
EXPECT_TRUE(matcher.ready_to_be_matched(c));
}
TEST_F(AbstractMatcherTest, Stash) {
MockMatcher matcher(100);
Event e;
e.insert({0,0,0,0});
e.insert({0,1,0,0});
matcher.stash_event(e);
EXPECT_EQ(matcher.matched_events.size(), 1);
EXPECT_EQ(matcher.stats_event_count, 1);
matcher.matched_events.clear();
matcher.stash_event(e);
EXPECT_EQ(matcher.matched_events.size(), 1);
EXPECT_EQ(matcher.stats_event_count, 2);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Fixed design.<commit_after>/** Copyright (C) 2017 European Spallation Source ERIC */
#include <test/TestBase.h>
#pragma GCC diagnostic push
#ifdef SYSTEM_NAME_DARWIN
#pragma GCC diagnostic ignored "-Wkeyword-macro"
#pragma GCC diagnostic ignored "-Wmacro-redefined"
#endif
#include <common/clustering/AbstractMatcher.h>
#pragma GCC diagnostic pop
class MockMatcher : public AbstractMatcher {
public:
explicit MockMatcher(uint64_t latency)
: AbstractMatcher(latency) {}
MockMatcher(uint64_t latency, uint8_t plane1, uint8_t plane2)
: AbstractMatcher(latency, plane1, plane2) {}
void match(bool) override {}
using AbstractMatcher::latency_;
using AbstractMatcher::plane1_;
using AbstractMatcher::plane2_;
using AbstractMatcher::latest_x_;
using AbstractMatcher::latest_y_;
using AbstractMatcher::unmatched_clusters_;
using AbstractMatcher::ready_to_be_matched;
using AbstractMatcher::stash_event;
};
class AbstractMatcherTest : public TestBase {
protected:
ClusterContainer x, y;
void add_cluster(ClusterContainer &ret, uint8_t plane,
uint16_t coord_start, uint16_t coord_end, uint16_t coord_step,
uint64_t time_start, uint64_t time_end, uint64_t time_step) {
Cluster c;
Hit e;
e.plane = plane;
e.weight = 1;
for (e.time = time_start; e.time <= time_end; e.time += time_step)
for (e.coordinate = coord_start; e.coordinate <= coord_end; e.coordinate += coord_step)
c.insert(e);
ret.push_back(c);
}
};
TEST_F(AbstractMatcherTest, Construction1) {
MockMatcher matcher(100, 3, 7);
EXPECT_EQ(matcher.latency_, 100);
EXPECT_EQ(matcher.plane1_, 3);
EXPECT_EQ(matcher.plane2_, 7);
}
TEST_F(AbstractMatcherTest, Construction2) {
MockMatcher matcher(100);
EXPECT_EQ(matcher.latency_, 100);
EXPECT_EQ(matcher.plane1_, 0);
EXPECT_EQ(matcher.plane2_, 1);
}
TEST_F(AbstractMatcherTest, InsertingMovesData) {
MockMatcher matcher(100);
add_cluster(x, 0, 0, 10, 1, 0, 200, 10);
matcher.insert(0, x);
EXPECT_TRUE(x.empty());
}
TEST_F(AbstractMatcherTest, AcceptXY) {
MockMatcher matcher(100);
add_cluster(x, 0, 0, 10, 1, 100, 200, 10);
matcher.insert(0, x);
EXPECT_EQ(matcher.unmatched_clusters_.size(), 1);
EXPECT_EQ(matcher.latest_x_, 100);
EXPECT_EQ(matcher.latest_y_, 0);
add_cluster(y, 1, 0, 10, 1, 100, 200, 10);
matcher.insert(1, y);
EXPECT_EQ(matcher.unmatched_clusters_.size(), 2);
EXPECT_EQ(matcher.latest_x_, 100);
EXPECT_EQ(matcher.latest_y_, 100);
}
TEST_F(AbstractMatcherTest, AcceptOtherPlanes) {
MockMatcher matcher(100, 3, 4);
add_cluster(x, 3, 0, 10, 1, 100, 200, 10);
matcher.insert(3, x);
EXPECT_EQ(matcher.unmatched_clusters_.size(), 1);
EXPECT_EQ(matcher.latest_x_, 100);
EXPECT_EQ(matcher.latest_y_, 0);
add_cluster(y, 4, 0, 10, 1, 100, 200, 10);
matcher.insert(4, y);
EXPECT_EQ(matcher.unmatched_clusters_.size(), 2);
EXPECT_EQ(matcher.latest_x_, 100);
EXPECT_EQ(matcher.latest_y_, 100);
}
TEST_F(AbstractMatcherTest, RejectUnselectedPlanes) {
MockMatcher matcher(100, 3, 4);
add_cluster(x, 7, 0, 10, 1, 100, 200, 10);
matcher.insert(7, x);
EXPECT_EQ(matcher.unmatched_clusters_.size(), 0);
EXPECT_EQ(matcher.latest_x_, 0);
EXPECT_EQ(matcher.latest_y_, 0);
add_cluster(y, 0, 0, 10, 1, 100, 200, 10);
matcher.insert(0, y);
EXPECT_EQ(matcher.unmatched_clusters_.size(), 0);
EXPECT_EQ(matcher.latest_x_, 0);
EXPECT_EQ(matcher.latest_y_, 0);
}
TEST_F(AbstractMatcherTest, Ready) {
MockMatcher matcher(100);
Cluster c;
c.insert({0,0,0,0});
EXPECT_FALSE(matcher.ready_to_be_matched(c));
matcher.latest_x_ = 99;
matcher.latest_y_ = 99;
EXPECT_FALSE(matcher.ready_to_be_matched(c));
matcher.latest_x_ = 100;
matcher.latest_y_ = 100;
EXPECT_FALSE(matcher.ready_to_be_matched(c));
matcher.latest_x_ = 101;
EXPECT_FALSE(matcher.ready_to_be_matched(c));
matcher.latest_y_ = 101;
EXPECT_TRUE(matcher.ready_to_be_matched(c));
}
TEST_F(AbstractMatcherTest, Stash) {
MockMatcher matcher(100);
Event e;
e.insert({0,0,0,0});
e.insert({0,1,0,0});
matcher.stash_event(e);
EXPECT_EQ(matcher.matched_events.size(), 1);
EXPECT_EQ(matcher.stats_event_count, 1);
matcher.matched_events.clear();
matcher.stash_event(e);
EXPECT_EQ(matcher.matched_events.size(), 1);
EXPECT_EQ(matcher.stats_event_count, 2);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>#include "GUI.hpp"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLineEdit>
#include <QDir>
#include <QLabel>
#include <QImage>
#include <FAST/Visualization/ImageRenderer/ImageRenderer.hpp>
#include <FAST/Streamers/IGTLinkStreamer.hpp>
#include "OpenIGTLinkClient.hpp"
#include <QMessageBox>
#include <QElapsedTimer>
#include <QComboBox>
#include <FAST/Visualization/TextRenderer/TextRenderer.hpp>
#include <FAST/Visualization/SegmentationRenderer/SegmentationRenderer.hpp>
#include <FAST/Visualization/HeatmapRenderer/HeatmapRenderer.hpp>
#include "FAST/Algorithms/NeuralNetwork/ImageClassifier.hpp"
#include "FAST/Algorithms/NeuralNetwork/PixelClassification.hpp"
namespace fast {
GUI::GUI() {
const int menuWidth = 300;
mClient = OpenIGTLinkClient::New();
mConnected = false;
mRecordTimer = new QElapsedTimer;
QVBoxLayout* viewLayout = new QVBoxLayout;
QHBoxLayout* selectStreamLayout = new QHBoxLayout;
QHBoxLayout* selectPipelineLayout = new QHBoxLayout;
viewLayout->addLayout(selectStreamLayout);
viewLayout->addLayout(selectPipelineLayout);
QLabel* selectStreamLabel = new QLabel;
selectStreamLabel->setText("Active input stream: ");
selectStreamLabel->setFixedHeight(30);
selectStreamLabel->setFixedWidth(150);
selectStreamLayout->addWidget(selectStreamLabel);
mSelectStream = new QComboBox;
selectStreamLayout->addWidget(mSelectStream);
QObject::connect(mSelectStream, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated), std::bind(&GUI::selectStream, this));
QLabel* selectPipelineLabel = new QLabel;
selectPipelineLabel->setText("Active pipeline: ");
selectPipelineLabel->setFixedHeight(30);
selectPipelineLabel->setFixedWidth(150);
selectPipelineLayout->addWidget(selectPipelineLabel);
mSelectPipeline = new QComboBox;
mPipelines = getAvailablePipelines();
int index = 0;
int counter = 0;
for(auto pipeline : mPipelines) {
mSelectPipeline->addItem((pipeline.getName() + " (" + pipeline.getDescription() + ")").c_str());
if(pipeline.getName() == "Image renderer") {
index = counter;
}
++counter;
}
mSelectPipeline->setCurrentIndex(index);
selectPipelineLayout->addWidget(mSelectPipeline);
QObject::connect(mSelectPipeline, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated), std::bind(&GUI::selectPipeline, this));
View* view = createView();
view->set2DMode();
view->setBackgroundColor(Color::Black());
setWidth(1280);
setHeight(768);
enableMaximized();
setTitle("FAST - OpenIGTLink Client");
viewLayout->addWidget(view);
// First create the menu layout
QVBoxLayout* menuLayout = new QVBoxLayout;
// Menu items should be aligned to the top
menuLayout->setAlignment(Qt::AlignTop);
// Logo
QImage* image = new QImage;
image->load((Config::getDocumentationPath() + "images/FAST_logo_square.png").c_str());
QLabel* logo = new QLabel;
logo->setPixmap(QPixmap::fromImage(image->scaled(300, (300.0f/image->width())*image->height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation)));
logo->adjustSize();
menuLayout->addWidget(logo);
// Title label
QLabel* title = new QLabel;
title->setText("<div style=\"text-align: center; font-weight: bold; font-size: 24px;\">OpenIGTLink<br>Client</div>");
menuLayout->addWidget(title);
// Quit button
QPushButton* quitButton = new QPushButton;
quitButton->setText("Quit (q)");
quitButton->setStyleSheet("QPushButton { background-color: red; color: white; }");
quitButton->setFixedWidth(menuWidth);
menuLayout->addWidget(quitButton);
// Connect the clicked signal of the quit button to the stop method for the window
QObject::connect(quitButton, &QPushButton::clicked, std::bind(&Window::stop, this));
// Address and port
QLabel* addressLabel = new QLabel;
addressLabel->setText("Server address");
menuLayout->addWidget(addressLabel);
mAddress = new QLineEdit;
mAddress->setText("localhost");
mAddress->setFixedWidth(menuWidth);
menuLayout->addWidget(mAddress);
QLabel* portLabel = new QLabel;
portLabel->setText("Server port");
menuLayout->addWidget(portLabel);
mPort = new QLineEdit;
mPort->setText("18944");
mPort->setFixedWidth(menuWidth);
menuLayout->addWidget(mPort);
connectButton = new QPushButton;
connectButton->setText("Connect");
connectButton->setFixedWidth(menuWidth);
connectButton->setStyleSheet("QPushButton { background-color: green; color: white; }");
menuLayout->addWidget(connectButton);
QObject::connect(connectButton, &QPushButton::clicked, std::bind(&GUI::connect, this));
QLabel* storageDirLabel = new QLabel;
storageDirLabel->setText("Storage directory");
menuLayout->addWidget(storageDirLabel);
storageDir = new QLineEdit;
storageDir->setText(QDir::homePath() + QDir::separator() + QString("FAST_Recordings"));
storageDir->setFixedWidth(menuWidth);
menuLayout->addWidget(storageDir);
recordButton = new QPushButton;
recordButton->setText("Record (spacebar)");
recordButton->setFixedWidth(menuWidth);
recordButton->setStyleSheet("QPushButton { background-color: green; color: white; }");
menuLayout->addWidget(recordButton);
recordingInformation = new QLabel;
recordingInformation->setFixedWidth(menuWidth);
recordingInformation->setStyleSheet("QLabel { font-size: 14px; }");
menuLayout->addWidget(recordingInformation);
QObject::connect(recordButton, &QPushButton::clicked, std::bind(&GUI::record, this));
// Add menu and view to main layout
QHBoxLayout* layout = new QHBoxLayout;
layout->addLayout(menuLayout);
layout->addLayout(viewLayout);
mWidget->setLayout(layout);
// Update messages frequently
QTimer* timer = new QTimer(this);
timer->start(1000/5); // in milliseconds
timer->setSingleShot(false);
QObject::connect(timer, &QTimer::timeout, std::bind(&GUI::updateMessages, this));
// Update streams info now and then
QTimer* timer2 = new QTimer(this);
timer2->start(1000); // in milliseconds
timer2->setSingleShot(false);
QObject::connect(timer2, &QTimer::timeout, std::bind(&GUI::refreshStreams, this));
connectButton->setFocus();
}
void GUI::selectPipeline() {
// Stop computation thread before removing renderers
stopComputationThread();
getView(0)->removeAllRenderers();
int selectedPipeline = mSelectPipeline->currentIndex();
Pipeline pipeline = mPipelines.at(selectedPipeline);
try {
std::vector<SharedPointer<Renderer>> renderers = pipeline.setup(mClient->getOutputPort());
for(auto renderer : renderers) {
// A hack for text renderer which needs a reference to the view
if(renderer->getNameOfClass() == "TextRenderer") {
TextRenderer::pointer textRenderer = renderer;
textRenderer->setView(getView(0));
}
getView(0)->addRenderer(renderer);
}
} catch(Exception &e) {
QMessageBox* message = new QMessageBox;
message->setWindowTitle("Error");
message->setText(e.what());
message->show();
}
startComputationThread();
recordButton->setFocus();
}
void GUI::selectStream() {
std::string streamName = mStreamNames[mSelectStream->currentIndex()];
reportInfo() << "Changing to " << streamName << " stream " << reportEnd();
// Stop computation thread before removing renderers
stopComputationThread();
getView(0)->removeAllRenderers();
mStreamer->stop(); // This should probably block until it has stopped
reportInfo() << "Disconnected" << reportEnd();
startComputationThread();
reportInfo() << "Trying to connect..." << reportEnd();
mStreamer = IGTLinkStreamer::New();
mStreamer->setConnectionAddress(mAddress->text().toStdString());
mStreamer->setConnectionPort(std::stoi(mPort->text().toStdString()));
mClient->setInputConnection(mStreamer->getOutputPort<Image>(streamName));
try {
mStreamer->update();
} catch(Exception &e) {
QMessageBox* message = new QMessageBox;
message->setWindowTitle("Error");
message->setText(e.what());
message->show();
return;
}
reportInfo() << "Connected to OpenIGTLink server." << reportEnd();
selectPipeline();
// This causes seg fault for some reason... wrong thread maybe?
//getView(0)->reinitialize();
recordButton->setFocus();
//refreshStreams();
}
void GUI::connect() {
if(mConnected) {
// Stop computation thread before removing renderers
stopComputationThread();
getView(0)->removeAllRenderers();
mStreamer->stop(); // This should probably block until it has stopped
reportInfo() << "Disconnected" << reportEnd();
startComputationThread();
connectButton->setText("Connect");
connectButton->setStyleSheet("QPushButton { background-color: green; color: white; }");
mAddress->setDisabled(false);
mPort->setDisabled(false);
mConnected = false;
connectButton->setFocus();
mSelectStream->clear();
} else {
reportInfo() << "Trying to connect..." << reportEnd();
mStreamer = IGTLinkStreamer::New();
mStreamer->setConnectionAddress(mAddress->text().toStdString());
mStreamer->setConnectionPort(std::stoi(mPort->text().toStdString()));
mClient->setInputConnection(mStreamer->getOutputPort());
try {
mStreamer->update();
} catch(Exception &e) {
QMessageBox* message = new QMessageBox;
message->setWindowTitle("Error");
message->setText(e.what());
message->show();
return;
}
reportInfo() << "Connected to OpenIGTLink server." << reportEnd();
ImageRenderer::pointer renderer = ImageRenderer::New();
renderer->addInputConnection(mClient->getOutputPort());
getView(0)->addRenderer(renderer);
getView(0)->reinitialize();
connectButton->setText("Disconnect");
connectButton->setStyleSheet("QPushButton { background-color: red; color: white; }");
mAddress->setDisabled(true);
mPort->setDisabled(true);
mConnected = true;
recordButton->setFocus();
//refreshStreams();
}
}
void GUI::refreshStreams() {// Get all stream names and put in select box
if(mConnected) {
int activeIndex = 0;
std::vector<std::string> activeStreams = mStreamer->getActiveImageStreamNames();
int counter = 0;
mStreamNames.clear();
mSelectStream->clear();
for(std::string streamName : mStreamer->getImageStreamNames()) {
mSelectStream->addItem((streamName + " (" + mStreamer->getStreamDescription(streamName) + ")").c_str());
mStreamNames.push_back(streamName);
if(streamName == activeStreams[0]) {
activeIndex = counter;
}
++counter;
}
mSelectStream->setCurrentIndex(activeIndex);
}
}
void GUI::record() {
if(!mConnected) {
// Can't record if not connected
QMessageBox* message = new QMessageBox;
message->setWindowTitle("Error");
message->setText("You have to connect to a server before recording.");
message->show();
return;
}
bool recording = mClient->toggleRecord(storageDir->text().toStdString());
if(recording) {
mRecordTimer->start();
std::string msg = "Recording to: " + mClient->getRecordingName();
recordingInformation->setText(msg.c_str());
// Start
recordButton->setText("Stop recording (spacebar)");
recordButton->setStyleSheet("QPushButton { background-color: red; color: white; }");
storageDir->setDisabled(true);
recordButton->setFocus();
} else {
// Stop
std::string msg = "Recording saved in: " + mClient->getRecordingName() + "\n";
msg += std::to_string(mClient->getFramesStored()) + " frames stored\n";
msg += format("%.1f seconds", (float)mRecordTimer->elapsed()/1000.0f);
recordingInformation->setText(msg.c_str());
recordButton->setText("Record (spacebar)");
recordButton->setStyleSheet("QPushButton { background-color: green; color: white; }");
storageDir->setDisabled(false);
recordButton->setFocus();
}
}
void GUI::updateMessages() {
if(mClient->isRecording()) {
std::string msg = "Recording to: " + mClient->getRecordingName() + "\n";
msg += std::to_string(mClient->getFramesStored()) + " frames stored\n";
msg += format("%.1f seconds", (float)mRecordTimer->elapsed()/1000.0f);
recordingInformation->setText(msg.c_str());
}
}
}
<commit_msg>Moved pipeline and stream to sidebar<commit_after>#include "GUI.hpp"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLineEdit>
#include <QDir>
#include <QLabel>
#include <QImage>
#include <FAST/Visualization/ImageRenderer/ImageRenderer.hpp>
#include <FAST/Streamers/IGTLinkStreamer.hpp>
#include "OpenIGTLinkClient.hpp"
#include <QMessageBox>
#include <QElapsedTimer>
#include <QComboBox>
#include <FAST/Visualization/TextRenderer/TextRenderer.hpp>
#include <FAST/Visualization/SegmentationRenderer/SegmentationRenderer.hpp>
#include <FAST/Visualization/HeatmapRenderer/HeatmapRenderer.hpp>
#include "FAST/Algorithms/NeuralNetwork/ImageClassifier.hpp"
#include "FAST/Algorithms/NeuralNetwork/PixelClassification.hpp"
namespace fast {
GUI::GUI() {
const int menuWidth = 300;
mClient = OpenIGTLinkClient::New();
mConnected = false;
mRecordTimer = new QElapsedTimer;
QVBoxLayout* viewLayout = new QVBoxLayout;
View* view = createView();
view->set2DMode();
view->setBackgroundColor(Color::Black());
setWidth(1280);
setHeight(768);
enableMaximized();
setTitle("FAST - OpenIGTLink Client");
viewLayout->addWidget(view);
QVBoxLayout* menuLayout = new QVBoxLayout;
menuLayout->setAlignment(Qt::AlignTop);
// Logo
QImage* image = new QImage;
image->load((Config::getDocumentationPath() + "images/FAST_logo_square.png").c_str());
QLabel* logo = new QLabel;
logo->setPixmap(QPixmap::fromImage(image->scaled(menuWidth, ((float)menuWidth/image->width())*image->height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation)));
logo->adjustSize();
menuLayout->addWidget(logo);
// Title label
QLabel* title = new QLabel;
title->setText("<div style=\"text-align: center; font-weight: bold; font-size: 24px;\">OpenIGTLink<br>Client</div>");
menuLayout->addWidget(title);
// Quit button
QPushButton* quitButton = new QPushButton;
quitButton->setText("Quit (q)");
quitButton->setStyleSheet("QPushButton { background-color: red; color: white; }");
quitButton->setFixedWidth(menuWidth);
menuLayout->addWidget(quitButton);
// Connect the clicked signal of the quit button to the stop method for the window
QObject::connect(quitButton, &QPushButton::clicked, std::bind(&Window::stop, this));
// Address and port
QLabel* addressLabel = new QLabel;
addressLabel->setText("Server address");
menuLayout->addWidget(addressLabel);
mAddress = new QLineEdit;
mAddress->setText("localhost");
mAddress->setFixedWidth(menuWidth);
menuLayout->addWidget(mAddress);
QLabel* portLabel = new QLabel;
portLabel->setText("Server port");
menuLayout->addWidget(portLabel);
mPort = new QLineEdit;
mPort->setText("18944");
mPort->setFixedWidth(menuWidth);
menuLayout->addWidget(mPort);
connectButton = new QPushButton;
connectButton->setText("Connect");
connectButton->setFixedWidth(menuWidth);
connectButton->setStyleSheet("QPushButton { background-color: green; color: white; }");
menuLayout->addWidget(connectButton);
QObject::connect(connectButton, &QPushButton::clicked, std::bind(&GUI::connect, this));
QLabel* storageDirLabel = new QLabel;
storageDirLabel->setText("Storage directory");
menuLayout->addWidget(storageDirLabel);
storageDir = new QLineEdit;
storageDir->setText(QDir::homePath() + QDir::separator() + QString("FAST_Recordings"));
storageDir->setFixedWidth(menuWidth);
menuLayout->addWidget(storageDir);
recordButton = new QPushButton;
recordButton->setText("Record (spacebar)");
recordButton->setFixedWidth(menuWidth);
recordButton->setStyleSheet("QPushButton { background-color: green; color: white; }");
menuLayout->addWidget(recordButton);
recordingInformation = new QLabel;
recordingInformation->setFixedWidth(menuWidth);
recordingInformation->setStyleSheet("QLabel { font-size: 14px; }");
menuLayout->addWidget(recordingInformation);
QObject::connect(recordButton, &QPushButton::clicked, std::bind(&GUI::record, this));
// Add menu and view to main layout
QHBoxLayout* layout = new QHBoxLayout;
layout->addLayout(menuLayout);
layout->addLayout(viewLayout);
mWidget->setLayout(layout);
// Update messages frequently
QTimer* timer = new QTimer(this);
timer->start(1000/5); // in milliseconds
timer->setSingleShot(false);
QObject::connect(timer, &QTimer::timeout, std::bind(&GUI::updateMessages, this));
// Update streams info now and then
QTimer* timer2 = new QTimer(this);
timer2->start(1000); // in milliseconds
timer2->setSingleShot(false);
QObject::connect(timer2, &QTimer::timeout, std::bind(&GUI::refreshStreams, this));
QLabel* selectStreamLabel = new QLabel;
selectStreamLabel->setText("Active input stream");
menuLayout->addWidget(selectStreamLabel);
mSelectStream = new QComboBox;
mSelectStream->setFixedWidth(menuWidth);
menuLayout->addWidget(mSelectStream);
QObject::connect(mSelectStream, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated), std::bind(&GUI::selectStream, this));
QLabel* selectPipelineLabel = new QLabel;
selectPipelineLabel->setText("Active pipeline");
menuLayout->addWidget(selectPipelineLabel);
mSelectPipeline = new QComboBox;
mSelectPipeline->setFixedWidth(menuWidth);
mPipelines = getAvailablePipelines();
int index = 0;
int counter = 0;
for(auto pipeline : mPipelines) {
mSelectPipeline->addItem((pipeline.getName() + " (" + pipeline.getDescription() + ")").c_str());
if(pipeline.getName() == "Image renderer") {
index = counter;
}
++counter;
}
mSelectPipeline->setCurrentIndex(index);
menuLayout->addWidget(mSelectPipeline);
QObject::connect(mSelectPipeline, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated), std::bind(&GUI::selectPipeline, this));
connectButton->setFocus();
}
void GUI::selectPipeline() {
// Stop computation thread before removing renderers
stopComputationThread();
getView(0)->removeAllRenderers();
int selectedPipeline = mSelectPipeline->currentIndex();
Pipeline pipeline = mPipelines.at(selectedPipeline);
try {
std::vector<SharedPointer<Renderer>> renderers = pipeline.setup(mClient->getOutputPort());
for(auto renderer : renderers) {
// A hack for text renderer which needs a reference to the view
if(renderer->getNameOfClass() == "TextRenderer") {
TextRenderer::pointer textRenderer = renderer;
textRenderer->setView(getView(0));
}
getView(0)->addRenderer(renderer);
}
} catch(Exception &e) {
QMessageBox* message = new QMessageBox;
message->setWindowTitle("Error");
message->setText(e.what());
message->show();
}
startComputationThread();
recordButton->setFocus();
}
void GUI::selectStream() {
std::string streamName = mStreamNames[mSelectStream->currentIndex()];
reportInfo() << "Changing to " << streamName << " stream " << reportEnd();
// Stop computation thread before removing renderers
stopComputationThread();
getView(0)->removeAllRenderers();
mStreamer->stop(); // This should probably block until it has stopped
reportInfo() << "Disconnected" << reportEnd();
startComputationThread();
reportInfo() << "Trying to connect..." << reportEnd();
mStreamer = IGTLinkStreamer::New();
mStreamer->setConnectionAddress(mAddress->text().toStdString());
mStreamer->setConnectionPort(std::stoi(mPort->text().toStdString()));
mClient->setInputConnection(mStreamer->getOutputPort<Image>(streamName));
try {
mStreamer->update();
} catch(Exception &e) {
QMessageBox* message = new QMessageBox;
message->setWindowTitle("Error");
message->setText(e.what());
message->show();
return;
}
reportInfo() << "Connected to OpenIGTLink server." << reportEnd();
selectPipeline();
// This causes seg fault for some reason... wrong thread maybe?
//getView(0)->reinitialize();
recordButton->setFocus();
//refreshStreams();
}
void GUI::connect() {
if(mConnected) {
// Stop computation thread before removing renderers
stopComputationThread();
getView(0)->removeAllRenderers();
mStreamer->stop(); // This should probably block until it has stopped
reportInfo() << "Disconnected" << reportEnd();
startComputationThread();
connectButton->setText("Connect");
connectButton->setStyleSheet("QPushButton { background-color: green; color: white; }");
mAddress->setDisabled(false);
mPort->setDisabled(false);
mConnected = false;
connectButton->setFocus();
mSelectStream->clear();
} else {
reportInfo() << "Trying to connect..." << reportEnd();
mStreamer = IGTLinkStreamer::New();
mStreamer->setConnectionAddress(mAddress->text().toStdString());
mStreamer->setConnectionPort(std::stoi(mPort->text().toStdString()));
mClient->setInputConnection(mStreamer->getOutputPort());
try {
mStreamer->update();
} catch(Exception &e) {
QMessageBox* message = new QMessageBox;
message->setWindowTitle("Error");
message->setText(e.what());
message->show();
return;
}
reportInfo() << "Connected to OpenIGTLink server." << reportEnd();
ImageRenderer::pointer renderer = ImageRenderer::New();
renderer->addInputConnection(mClient->getOutputPort());
getView(0)->addRenderer(renderer);
getView(0)->reinitialize();
connectButton->setText("Disconnect");
connectButton->setStyleSheet("QPushButton { background-color: red; color: white; }");
mAddress->setDisabled(true);
mPort->setDisabled(true);
mConnected = true;
recordButton->setFocus();
//refreshStreams();
}
}
void GUI::refreshStreams() {// Get all stream names and put in select box
if(mConnected) {
int activeIndex = 0;
std::vector<std::string> activeStreams = mStreamer->getActiveImageStreamNames();
int counter = 0;
mStreamNames.clear();
mSelectStream->clear();
for(std::string streamName : mStreamer->getImageStreamNames()) {
mSelectStream->addItem((streamName + " (" + mStreamer->getStreamDescription(streamName) + ")").c_str());
mStreamNames.push_back(streamName);
if(streamName == activeStreams[0]) {
activeIndex = counter;
}
++counter;
}
mSelectStream->setCurrentIndex(activeIndex);
}
}
void GUI::record() {
if(!mConnected) {
// Can't record if not connected
QMessageBox* message = new QMessageBox;
message->setWindowTitle("Error");
message->setText("You have to connect to a server before recording.");
message->show();
return;
}
bool recording = mClient->toggleRecord(storageDir->text().toStdString());
if(recording) {
mRecordTimer->start();
std::string msg = "Recording to: " + mClient->getRecordingName();
recordingInformation->setText(msg.c_str());
// Start
recordButton->setText("Stop recording (spacebar)");
recordButton->setStyleSheet("QPushButton { background-color: red; color: white; }");
storageDir->setDisabled(true);
recordButton->setFocus();
} else {
// Stop
std::string msg = "Recording saved in: " + mClient->getRecordingName() + "\n";
msg += std::to_string(mClient->getFramesStored()) + " frames stored\n";
msg += format("%.1f seconds", (float)mRecordTimer->elapsed()/1000.0f);
recordingInformation->setText(msg.c_str());
recordButton->setText("Record (spacebar)");
recordButton->setStyleSheet("QPushButton { background-color: green; color: white; }");
storageDir->setDisabled(false);
recordButton->setFocus();
}
}
void GUI::updateMessages() {
if(mClient->isRecording()) {
std::string msg = "Recording to: " + mClient->getRecordingName() + "\n";
msg += std::to_string(mClient->getFramesStored()) + " frames stored\n";
msg += format("%.1f seconds", (float)mRecordTimer->elapsed()/1000.0f);
recordingInformation->setText(msg.c_str());
}
}
}
<|endoftext|> |
<commit_before>//===-- X86SelectionDAGInfo.cpp - X86 SelectionDAG Info -------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the X86SelectionDAGInfo class.
//
//===----------------------------------------------------------------------===//
#include "X86SelectionDAGInfo.h"
#include "X86ISelLowering.h"
#include "X86InstrInfo.h"
#include "X86RegisterInfo.h"
#include "X86Subtarget.h"
#include "llvm/CodeGen/SelectionDAG.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/IR/DerivedTypes.h"
using namespace llvm;
#define DEBUG_TYPE "x86-selectiondag-info"
bool X86SelectionDAGInfo::isBaseRegConflictPossible(
SelectionDAG &DAG, ArrayRef<MCPhysReg> ClobberSet) const {
// We cannot use TRI->hasBasePointer() until *after* we select all basic
// blocks. Legalization may introduce new stack temporaries with large
// alignment requirements. Fall back to generic code if there are any
// dynamic stack adjustments (hopefully rare) and the base pointer would
// conflict if we had to use it.
MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
if (!MFI.hasVarSizedObjects() && !MFI.hasOpaqueSPAdjustment())
return false;
const X86RegisterInfo *TRI = static_cast<const X86RegisterInfo *>(
DAG.getSubtarget().getRegisterInfo());
unsigned BaseReg = TRI->getBaseRegister();
for (unsigned R : ClobberSet)
if (BaseReg == R)
return true;
return false;
}
namespace {
// Represents a cover of a buffer of Size bytes with Count() blocks of type AVT
// (of size UBytes() bytes), as well as how many bytes remain (BytesLeft() is
// always smaller than the block size).
struct RepMovsRepeats {
RepMovsRepeats(uint64_t Size) : Size(Size) {}
uint64_t Count() const { return Size / UBytes(); }
uint64_t BytesLeft() const { return Size % UBytes(); }
uint64_t UBytes() const { return AVT.getSizeInBits() / 8; }
const uint64_t Size;
MVT AVT = MVT::i8;
};
} // namespace
SDValue X86SelectionDAGInfo::EmitTargetCodeForMemset(
SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Val,
SDValue Size, unsigned Align, bool isVolatile,
MachinePointerInfo DstPtrInfo) const {
ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
const X86Subtarget &Subtarget =
DAG.getMachineFunction().getSubtarget<X86Subtarget>();
#ifndef NDEBUG
// If the base register might conflict with our physical registers, bail out.
const MCPhysReg ClobberSet[] = {X86::RCX, X86::RAX, X86::RDI,
X86::ECX, X86::EAX, X86::EDI};
assert(!isBaseRegConflictPossible(DAG, ClobberSet));
#endif
// If to a segment-relative address space, use the default lowering.
if (DstPtrInfo.getAddrSpace() >= 256)
return SDValue();
// If not DWORD aligned or size is more than the threshold, call the library.
// The libc version is likely to be faster for these cases. It can use the
// address value and run time information about the CPU.
if ((Align & 3) != 0 || !ConstantSize ||
ConstantSize->getZExtValue() > Subtarget.getMaxInlineSizeThreshold()) {
// Check to see if there is a specialized entry-point for memory zeroing.
ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Val);
if (const char *bzeroName = (ValC && ValC->isNullValue())
? DAG.getTargetLoweringInfo().getLibcallName(RTLIB::BZERO)
: nullptr) {
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout());
Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
TargetLowering::ArgListTy Args;
TargetLowering::ArgListEntry Entry;
Entry.Node = Dst;
Entry.Ty = IntPtrTy;
Args.push_back(Entry);
Entry.Node = Size;
Args.push_back(Entry);
TargetLowering::CallLoweringInfo CLI(DAG);
CLI.setDebugLoc(dl)
.setChain(Chain)
.setLibCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
DAG.getExternalSymbol(bzeroName, IntPtr),
std::move(Args))
.setDiscardResult();
std::pair<SDValue,SDValue> CallResult = TLI.LowerCallTo(CLI);
return CallResult.second;
}
// Otherwise have the target-independent code call memset.
return SDValue();
}
uint64_t SizeVal = ConstantSize->getZExtValue();
SDValue InFlag;
EVT AVT;
SDValue Count;
ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Val);
unsigned BytesLeft = 0;
if (ValC) {
unsigned ValReg;
uint64_t Val = ValC->getZExtValue() & 255;
// If the value is a constant, then we can potentially use larger sets.
switch (Align & 3) {
case 2: // WORD aligned
AVT = MVT::i16;
ValReg = X86::AX;
Val = (Val << 8) | Val;
break;
case 0: // DWORD aligned
AVT = MVT::i32;
ValReg = X86::EAX;
Val = (Val << 8) | Val;
Val = (Val << 16) | Val;
if (Subtarget.is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
AVT = MVT::i64;
ValReg = X86::RAX;
Val = (Val << 32) | Val;
}
break;
default: // Byte aligned
AVT = MVT::i8;
ValReg = X86::AL;
Count = DAG.getIntPtrConstant(SizeVal, dl);
break;
}
if (AVT.bitsGT(MVT::i8)) {
unsigned UBytes = AVT.getSizeInBits() / 8;
Count = DAG.getIntPtrConstant(SizeVal / UBytes, dl);
BytesLeft = SizeVal % UBytes;
}
Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, dl, AVT),
InFlag);
InFlag = Chain.getValue(1);
} else {
AVT = MVT::i8;
Count = DAG.getIntPtrConstant(SizeVal, dl);
Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Val, InFlag);
InFlag = Chain.getValue(1);
}
bool Use64BitRegs = Subtarget.isTarget64BitLP64();
Chain = DAG.getCopyToReg(Chain, dl, Use64BitRegs ? X86::RCX : X86::ECX,
Count, InFlag);
InFlag = Chain.getValue(1);
Chain = DAG.getCopyToReg(Chain, dl, Use64BitRegs ? X86::RDI : X86::EDI,
Dst, InFlag);
InFlag = Chain.getValue(1);
SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops);
if (BytesLeft) {
// Handle the last 1 - 7 bytes.
unsigned Offset = SizeVal - BytesLeft;
EVT AddrVT = Dst.getValueType();
EVT SizeVT = Size.getValueType();
Chain = DAG.getMemset(Chain, dl,
DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
DAG.getConstant(Offset, dl, AddrVT)),
Val,
DAG.getConstant(BytesLeft, dl, SizeVT),
Align, isVolatile, false,
DstPtrInfo.getWithOffset(Offset));
}
// TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
return Chain;
}
SDValue X86SelectionDAGInfo::EmitTargetCodeForMemcpy(
SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
SDValue Size, unsigned Align, bool isVolatile, bool AlwaysInline,
MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo) const {
// This requires the copy size to be a constant, preferably
// within a subtarget-specific limit.
ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
const X86Subtarget &Subtarget =
DAG.getMachineFunction().getSubtarget<X86Subtarget>();
if (!ConstantSize)
return SDValue();
RepMovsRepeats Repeats(ConstantSize->getZExtValue());
if (!AlwaysInline && Repeats.Size > Subtarget.getMaxInlineSizeThreshold())
return SDValue();
/// If not DWORD aligned, it is more efficient to call the library. However
/// if calling the library is not allowed (AlwaysInline), then soldier on as
/// the code generated here is better than the long load-store sequence we
/// would otherwise get.
if (!AlwaysInline && (Align & 3) != 0)
return SDValue();
// If to a segment-relative address space, use the default lowering.
if (DstPtrInfo.getAddrSpace() >= 256 ||
SrcPtrInfo.getAddrSpace() >= 256)
return SDValue();
// If the base register might conflict with our physical registers, bail out.
const MCPhysReg ClobberSet[] = {X86::RCX, X86::RSI, X86::RDI,
X86::ECX, X86::ESI, X86::EDI};
if (isBaseRegConflictPossible(DAG, ClobberSet))
return SDValue();
// If the target has enhanced REPMOVSB, then it's at least as fast to use
// REP MOVSB instead of REP MOVS{W,D,Q}, and it avoids having to handle
// BytesLeft.
if (!Subtarget.hasERMSB() && !(Align & 1)) {
if (Align & 2)
// WORD aligned
Repeats.AVT = MVT::i16;
else if (Align & 4)
// DWORD aligned
Repeats.AVT = MVT::i32;
else
// QWORD aligned
Repeats.AVT = Subtarget.is64Bit() ? MVT::i64 : MVT::i32;
if (Repeats.BytesLeft() > 0 &&
DAG.getMachineFunction().getFunction().hasMinSize()) {
// When aggressively optimizing for size, avoid generating the code to
// handle BytesLeft.
Repeats.AVT = MVT::i8;
}
}
bool Use64BitRegs = Subtarget.isTarget64BitLP64();
SDValue InFlag;
Chain = DAG.getCopyToReg(Chain, dl, Use64BitRegs ? X86::RCX : X86::ECX,
DAG.getIntPtrConstant(Repeats.Count(), dl), InFlag);
InFlag = Chain.getValue(1);
Chain = DAG.getCopyToReg(Chain, dl, Use64BitRegs ? X86::RDI : X86::EDI,
Dst, InFlag);
InFlag = Chain.getValue(1);
Chain = DAG.getCopyToReg(Chain, dl, Use64BitRegs ? X86::RSI : X86::ESI,
Src, InFlag);
InFlag = Chain.getValue(1);
SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
SDValue Ops[] = { Chain, DAG.getValueType(Repeats.AVT), InFlag };
SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops);
SmallVector<SDValue, 4> Results;
Results.push_back(RepMovs);
if (Repeats.BytesLeft()) {
// Handle the last 1 - 7 bytes.
unsigned Offset = Repeats.Size - Repeats.BytesLeft();
EVT DstVT = Dst.getValueType();
EVT SrcVT = Src.getValueType();
EVT SizeVT = Size.getValueType();
Results.push_back(DAG.getMemcpy(Chain, dl,
DAG.getNode(ISD::ADD, dl, DstVT, Dst,
DAG.getConstant(Offset, dl,
DstVT)),
DAG.getNode(ISD::ADD, dl, SrcVT, Src,
DAG.getConstant(Offset, dl,
SrcVT)),
DAG.getConstant(Repeats.BytesLeft(), dl,
SizeVT),
Align, isVolatile, AlwaysInline, false,
DstPtrInfo.getWithOffset(Offset),
SrcPtrInfo.getWithOffset(Offset)));
}
return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Results);
}
<commit_msg>Modernize repmovsb implementation of x86 memcpy and allow runtime sizes.<commit_after>//===-- X86SelectionDAGInfo.cpp - X86 SelectionDAG Info -------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the X86SelectionDAGInfo class.
//
//===----------------------------------------------------------------------===//
#include "X86SelectionDAGInfo.h"
#include "X86ISelLowering.h"
#include "X86InstrInfo.h"
#include "X86RegisterInfo.h"
#include "X86Subtarget.h"
#include "llvm/CodeGen/SelectionDAG.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/IR/DerivedTypes.h"
using namespace llvm;
#define DEBUG_TYPE "x86-selectiondag-info"
bool X86SelectionDAGInfo::isBaseRegConflictPossible(
SelectionDAG &DAG, ArrayRef<MCPhysReg> ClobberSet) const {
// We cannot use TRI->hasBasePointer() until *after* we select all basic
// blocks. Legalization may introduce new stack temporaries with large
// alignment requirements. Fall back to generic code if there are any
// dynamic stack adjustments (hopefully rare) and the base pointer would
// conflict if we had to use it.
MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
if (!MFI.hasVarSizedObjects() && !MFI.hasOpaqueSPAdjustment())
return false;
const X86RegisterInfo *TRI = static_cast<const X86RegisterInfo *>(
DAG.getSubtarget().getRegisterInfo());
unsigned BaseReg = TRI->getBaseRegister();
for (unsigned R : ClobberSet)
if (BaseReg == R)
return true;
return false;
}
SDValue X86SelectionDAGInfo::EmitTargetCodeForMemset(
SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Val,
SDValue Size, unsigned Align, bool isVolatile,
MachinePointerInfo DstPtrInfo) const {
ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
const X86Subtarget &Subtarget =
DAG.getMachineFunction().getSubtarget<X86Subtarget>();
#ifndef NDEBUG
// If the base register might conflict with our physical registers, bail out.
const MCPhysReg ClobberSet[] = {X86::RCX, X86::RAX, X86::RDI,
X86::ECX, X86::EAX, X86::EDI};
assert(!isBaseRegConflictPossible(DAG, ClobberSet));
#endif
// If to a segment-relative address space, use the default lowering.
if (DstPtrInfo.getAddrSpace() >= 256)
return SDValue();
// If not DWORD aligned or size is more than the threshold, call the library.
// The libc version is likely to be faster for these cases. It can use the
// address value and run time information about the CPU.
if ((Align & 3) != 0 || !ConstantSize ||
ConstantSize->getZExtValue() > Subtarget.getMaxInlineSizeThreshold()) {
// Check to see if there is a specialized entry-point for memory zeroing.
ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Val);
if (const char *bzeroName = (ValC && ValC->isNullValue())
? DAG.getTargetLoweringInfo().getLibcallName(RTLIB::BZERO)
: nullptr) {
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout());
Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
TargetLowering::ArgListTy Args;
TargetLowering::ArgListEntry Entry;
Entry.Node = Dst;
Entry.Ty = IntPtrTy;
Args.push_back(Entry);
Entry.Node = Size;
Args.push_back(Entry);
TargetLowering::CallLoweringInfo CLI(DAG);
CLI.setDebugLoc(dl)
.setChain(Chain)
.setLibCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
DAG.getExternalSymbol(bzeroName, IntPtr),
std::move(Args))
.setDiscardResult();
std::pair<SDValue,SDValue> CallResult = TLI.LowerCallTo(CLI);
return CallResult.second;
}
// Otherwise have the target-independent code call memset.
return SDValue();
}
uint64_t SizeVal = ConstantSize->getZExtValue();
SDValue InFlag;
EVT AVT;
SDValue Count;
ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Val);
unsigned BytesLeft = 0;
if (ValC) {
unsigned ValReg;
uint64_t Val = ValC->getZExtValue() & 255;
// If the value is a constant, then we can potentially use larger sets.
switch (Align & 3) {
case 2: // WORD aligned
AVT = MVT::i16;
ValReg = X86::AX;
Val = (Val << 8) | Val;
break;
case 0: // DWORD aligned
AVT = MVT::i32;
ValReg = X86::EAX;
Val = (Val << 8) | Val;
Val = (Val << 16) | Val;
if (Subtarget.is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
AVT = MVT::i64;
ValReg = X86::RAX;
Val = (Val << 32) | Val;
}
break;
default: // Byte aligned
AVT = MVT::i8;
ValReg = X86::AL;
Count = DAG.getIntPtrConstant(SizeVal, dl);
break;
}
if (AVT.bitsGT(MVT::i8)) {
unsigned UBytes = AVT.getSizeInBits() / 8;
Count = DAG.getIntPtrConstant(SizeVal / UBytes, dl);
BytesLeft = SizeVal % UBytes;
}
Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, dl, AVT),
InFlag);
InFlag = Chain.getValue(1);
} else {
AVT = MVT::i8;
Count = DAG.getIntPtrConstant(SizeVal, dl);
Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Val, InFlag);
InFlag = Chain.getValue(1);
}
bool Use64BitRegs = Subtarget.isTarget64BitLP64();
Chain = DAG.getCopyToReg(Chain, dl, Use64BitRegs ? X86::RCX : X86::ECX,
Count, InFlag);
InFlag = Chain.getValue(1);
Chain = DAG.getCopyToReg(Chain, dl, Use64BitRegs ? X86::RDI : X86::EDI,
Dst, InFlag);
InFlag = Chain.getValue(1);
SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops);
if (BytesLeft) {
// Handle the last 1 - 7 bytes.
unsigned Offset = SizeVal - BytesLeft;
EVT AddrVT = Dst.getValueType();
EVT SizeVT = Size.getValueType();
Chain = DAG.getMemset(Chain, dl,
DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
DAG.getConstant(Offset, dl, AddrVT)),
Val,
DAG.getConstant(BytesLeft, dl, SizeVT),
Align, isVolatile, false,
DstPtrInfo.getWithOffset(Offset));
}
// TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
return Chain;
}
/// Emit a single REP MOVS{B,W,D,Q} instruction.
static SDValue emitRepmovs(const X86Subtarget &Subtarget, SelectionDAG &DAG,
const SDLoc &dl, SDValue Chain, SDValue Dst,
SDValue Src, SDValue Size, MVT AVT) {
const bool Use64BitRegs = Subtarget.isTarget64BitLP64();
const unsigned CX = Use64BitRegs ? X86::RCX : X86::ECX;
const unsigned DI = Use64BitRegs ? X86::RDI : X86::EDI;
const unsigned SI = Use64BitRegs ? X86::RSI : X86::ESI;
SDValue InFlag;
Chain = DAG.getCopyToReg(Chain, dl, CX, Size, InFlag);
InFlag = Chain.getValue(1);
Chain = DAG.getCopyToReg(Chain, dl, DI, Dst, InFlag);
InFlag = Chain.getValue(1);
Chain = DAG.getCopyToReg(Chain, dl, SI, Src, InFlag);
InFlag = Chain.getValue(1);
SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
SDValue Ops[] = {Chain, DAG.getValueType(AVT), InFlag};
return DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops);
}
/// Emit a single REP MOVSB instruction for a particular constant size.
static SDValue emitRepmovsB(const X86Subtarget &Subtarget, SelectionDAG &DAG,
const SDLoc &dl, SDValue Chain, SDValue Dst,
SDValue Src, uint64_t Size) {
return emitRepmovs(Subtarget, DAG, dl, Chain, Dst, Src,
DAG.getIntPtrConstant(Size, dl), MVT::i8);
}
/// Returns the best type to use with repmovs depending on alignment.
static MVT getOptimalRepmovsType(const X86Subtarget &Subtarget,
uint64_t Align) {
assert((Align != 0) && "Align is normalized");
assert(isPowerOf2_64(Align) && "Align is a power of 2");
switch (Align) {
case 1:
return MVT::i8;
case 2:
return MVT::i16;
case 4:
return MVT::i32;
default:
return Subtarget.is64Bit() ? MVT::i64 : MVT::i32;
}
}
/// Returns a REP MOVS instruction, possibly with a few load/stores to implement
/// a constant size memory copy. In some cases where we know REP MOVS is
/// inefficient we return an empty SDValue so the calling code can either
/// generate a load/store sequence or call the runtime memcpy function.
static SDValue emitConstantSizeRepmov(
SelectionDAG &DAG, const X86Subtarget &Subtarget, const SDLoc &dl,
SDValue Chain, SDValue Dst, SDValue Src, uint64_t Size, EVT SizeVT,
unsigned Align, bool isVolatile, bool AlwaysInline,
MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo) {
/// TODO: Revisit next line: big copy with ERMSB on march >= haswell are very
/// efficient.
if (!AlwaysInline && Size > Subtarget.getMaxInlineSizeThreshold())
return SDValue();
/// If we have enhanced repmovs we use it.
if (Subtarget.hasERMSB())
return emitRepmovsB(Subtarget, DAG, dl, Chain, Dst, Src, Size);
assert(!Subtarget.hasERMSB() && "No efficient RepMovs");
/// We assume runtime memcpy will do a better job for unaligned copies when
/// ERMS is not present.
if (!AlwaysInline && (Align & 3) != 0)
return SDValue();
const MVT BlockType = getOptimalRepmovsType(Subtarget, Align);
const uint64_t BlockBytes = BlockType.getSizeInBits() / 8;
const uint64_t BlockCount = Size / BlockBytes;
const uint64_t BytesLeft = Size % BlockBytes;
SDValue RepMovs =
emitRepmovs(Subtarget, DAG, dl, Chain, Dst, Src,
DAG.getIntPtrConstant(BlockCount, dl), BlockType);
/// RepMov can process the whole length.
if (BytesLeft == 0)
return RepMovs;
assert(BytesLeft && "We have leftover at this point");
/// In case we optimize for size we use repmovsb even if it's less efficient
/// so we can save the loads/stores of the leftover.
if (DAG.getMachineFunction().getFunction().hasMinSize())
return emitRepmovsB(Subtarget, DAG, dl, Chain, Dst, Src, Size);
// Handle the last 1 - 7 bytes.
SmallVector<SDValue, 4> Results;
Results.push_back(RepMovs);
unsigned Offset = Size - BytesLeft;
EVT DstVT = Dst.getValueType();
EVT SrcVT = Src.getValueType();
Results.push_back(DAG.getMemcpy(
Chain, dl,
DAG.getNode(ISD::ADD, dl, DstVT, Dst, DAG.getConstant(Offset, dl, DstVT)),
DAG.getNode(ISD::ADD, dl, SrcVT, Src, DAG.getConstant(Offset, dl, SrcVT)),
DAG.getConstant(BytesLeft, dl, SizeVT), Align, isVolatile,
/*AlwaysInline*/ true, /*isTailCall*/ false,
DstPtrInfo.getWithOffset(Offset), SrcPtrInfo.getWithOffset(Offset)));
return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Results);
}
SDValue X86SelectionDAGInfo::EmitTargetCodeForMemcpy(
SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
SDValue Size, unsigned Align, bool isVolatile, bool AlwaysInline,
MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo) const {
// If to a segment-relative address space, use the default lowering.
if (DstPtrInfo.getAddrSpace() >= 256 || SrcPtrInfo.getAddrSpace() >= 256)
return SDValue();
// If the base registers conflict with our physical registers, use the default
// lowering.
const MCPhysReg ClobberSet[] = {X86::RCX, X86::RSI, X86::RDI,
X86::ECX, X86::ESI, X86::EDI};
if (isBaseRegConflictPossible(DAG, ClobberSet))
return SDValue();
const X86Subtarget &Subtarget =
DAG.getMachineFunction().getSubtarget<X86Subtarget>();
/// Handle constant sizes,
if (ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size))
return emitConstantSizeRepmov(DAG, Subtarget, dl, Chain, Dst, Src,
ConstantSize->getZExtValue(),
Size.getValueType(), Align, isVolatile,
AlwaysInline, DstPtrInfo, SrcPtrInfo);
return SDValue();
}
<|endoftext|> |
<commit_before>#include "pyramid.h"
#include <iostream>
#include <cassert>
int main(int argc, const char* argv[]) {
{
Pyramid<int> a = {0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4};
assert(a[0][0] == 0);
assert(a[1][0] == 1);
assert(a[2][0] == 2);
assert(a[3][0] == 3);
assert(a[4][0] == 4);
assert(a[3][0] == 3);
assert(a[3][1] == 3);
assert(a[3][2] == 3);
assert(a[3][3] == 3);
}
}
<commit_msg>kanske borde testa modifiering..<commit_after>#include "pyramid.h"
#include <iostream>
#include <cassert>
int main(int argc, const char* argv[]) {
{
Pyramid<int> a = {0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4};
assert(a[0][0] == 0);
assert(a[1][0] == 1);
assert(a[2][0] == 2);
assert(a[3][0] == 3);
assert(a[4][0] == 4);
assert(a[3][0] == 3);
assert(a[3][1] == 3);
assert(a[3][2] == 3);
assert(a[3][3] == 3);
a[1][1] = 5;
assert(a[1][1] == 5);
assert(a[0][0] == 0);
assert(a[1][0] == 1);
assert(a[2][0] == 2);
assert(a[3][0] == 3);
assert(a[4][0] == 4);
assert(a[3][0] == 3);
assert(a[3][1] == 3);
assert(a[3][2] == 3);
assert(a[3][3] == 3);
}
}
<|endoftext|> |
<commit_before>// Copyright 2014 The Chromium Embedded Framework Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file.
#include "libcef/browser/window_delegate_view.h"
#include "content/public/browser/web_contents.h"
#include "ui/views/background.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/widget/widget.h"
CefWindowDelegateView::CefWindowDelegateView(SkColor background_color)
: background_color_(background_color),
web_view_(NULL) {
}
void CefWindowDelegateView::Init(
gfx::AcceleratedWidget parent_widget,
content::WebContents* web_contents,
const gfx::Rect& bounds) {
DCHECK(!web_view_);
web_view_ = new views::WebView(web_contents->GetBrowserContext());
web_view_->SetWebContents(web_contents);
web_view_->SetPreferredSize(bounds.size());
views::Widget* widget = new views::Widget;
// See CalculateWindowStylesFromInitParams in
// ui/views/widget/widget_hwnd_utils.cc for the conversion of |params| to
// Windows style flags.
views::Widget::InitParams params;
params.parent_widget = parent_widget;
params.bounds = bounds;
params.delegate = this;
// Set the WS_CHILD flag.
params.child = true;
// Set the WS_VISIBLE flag.
params.type = views::Widget::InitParams::TYPE_CONTROL;
// Don't set the WS_EX_COMPOSITED flag.
params.opacity = views::Widget::InitParams::OPAQUE_WINDOW;
// Results in a call to InitContent().
widget->Init(params);
// |widget| should now be associated with |this|.
DCHECK_EQ(widget, GetWidget());
// |widget| must be top-level for focus handling to work correctly.
DCHECK(widget->is_top_level());
}
void CefWindowDelegateView::InitContent() {
set_background(views::Background::CreateSolidBackground(background_color_));
SetLayoutManager(new views::FillLayout());
AddChildView(web_view_);
}
void CefWindowDelegateView::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
if (details.is_add && details.child == this)
InitContent();
}
<commit_msg>Windows: Don't draw a resize frame around the browser (issue #1401).<commit_after>// Copyright 2014 The Chromium Embedded Framework Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file.
#include "libcef/browser/window_delegate_view.h"
#include "content/public/browser/web_contents.h"
#include "ui/views/background.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/widget/widget.h"
CefWindowDelegateView::CefWindowDelegateView(SkColor background_color)
: background_color_(background_color),
web_view_(NULL) {
}
void CefWindowDelegateView::Init(
gfx::AcceleratedWidget parent_widget,
content::WebContents* web_contents,
const gfx::Rect& bounds) {
DCHECK(!web_view_);
web_view_ = new views::WebView(web_contents->GetBrowserContext());
web_view_->SetWebContents(web_contents);
web_view_->SetPreferredSize(bounds.size());
views::Widget* widget = new views::Widget;
// See CalculateWindowStylesFromInitParams in
// ui/views/widget/widget_hwnd_utils.cc for the conversion of |params| to
// Windows style flags.
views::Widget::InitParams params;
params.parent_widget = parent_widget;
params.bounds = bounds;
params.delegate = this;
// Set the WS_CHILD flag.
params.child = true;
// Set the WS_VISIBLE flag.
params.type = views::Widget::InitParams::TYPE_CONTROL;
// Don't set the WS_EX_COMPOSITED flag.
params.opacity = views::Widget::InitParams::OPAQUE_WINDOW;
// Tell Aura not to draw the window frame on resize.
params.remove_standard_frame = true;
// Results in a call to InitContent().
widget->Init(params);
// |widget| should now be associated with |this|.
DCHECK_EQ(widget, GetWidget());
// |widget| must be top-level for focus handling to work correctly.
DCHECK(widget->is_top_level());
}
void CefWindowDelegateView::InitContent() {
set_background(views::Background::CreateSolidBackground(background_color_));
SetLayoutManager(new views::FillLayout());
AddChildView(web_view_);
}
void CefWindowDelegateView::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
if (details.is_add && details.child == this)
InitContent();
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* libproxy - A library for proxy configuration
* Copyright (C) 2006 Nathaniel McCallum <nathaniel@natemccallum.com>
* Copyright (C) 2021 Zhaofeng Li <hello@zhaofeng.li>
*
* 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
******************************************************************************/
#include "../extension_pacrunner.hpp"
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
#else
#include <unistd.h> // gethostname
#endif
using namespace libproxy;
#include <duktape.h>
#include "pacutils.h"
static duk_ret_t dnsResolve(duk_context *ctx) {
if (duk_get_top(ctx) != 1) {
// Invalid number of arguments
return 0;
}
// We do not need to free the string - It's managed by Duktape.
const char *hostname = duk_get_string(ctx, 0);
if (!hostname) {
return 0;
}
// Look it up
struct addrinfo *info;
if (getaddrinfo(hostname, NULL, NULL, &info)) {
return 0;
}
// Try for IPv4
char tmp[INET6_ADDRSTRLEN+1];
if (getnameinfo(info->ai_addr, info->ai_addrlen,
tmp, INET6_ADDRSTRLEN+1,
NULL, 0,
NI_NUMERICHOST)) {
freeaddrinfo(info);
duk_push_null(ctx);
return 1;
}
freeaddrinfo(info);
// Create the return value
duk_push_string(ctx, tmp);
return 1;
}
static duk_ret_t myIpAddress(duk_context *ctx) {
char hostname[1024];
hostname[sizeof(hostname) - 1] = '\0';
if (!gethostname(hostname, sizeof(hostname) - 1)) {
duk_push_string(ctx, hostname);
return dnsResolve(ctx);
}
return duk_error(ctx, DUK_ERR_ERROR, "Unable to find hostname!");
}
class duktape_pacrunner : public pacrunner {
public:
duktape_pacrunner(string pac, const url& pacurl) : pacrunner(pac, pacurl) {
#ifdef _WIN32
// On windows, we need to initialize the winsock dll first.
WSADATA WsaData;
WSAStartup(MAKEWORD(2, 0), &WsaData);
#endif
this->ctx = duk_create_heap_default();
if (!this->ctx) goto error;
duk_push_c_function(this->ctx, dnsResolve, 1);
duk_put_global_string(this->ctx, "dnsResolve");
duk_push_c_function(this->ctx, myIpAddress, 1);
duk_put_global_string(this->ctx, "myIpAddress");
// Add other routines
duk_push_string(this->ctx, JAVASCRIPT_ROUTINES);
if (duk_peval_noresult(this->ctx)) {
goto error;
}
// Add the PAC into the context
duk_push_string(this->ctx, pac.c_str());
if (duk_peval_noresult(this->ctx)) {
goto error;
}
return;
error:
duk_destroy_heap(this->ctx);
throw bad_alloc();
}
~duktape_pacrunner() {
duk_destroy_heap(this->ctx);
#ifdef _WIN32
WSACleanup();
#endif
}
string run(const url& url_) override {
string url = url_.to_string();
string host = url_.get_host();
duk_get_global_string(this->ctx, "FindProxyForURL");
duk_push_string(this->ctx, url.c_str());
duk_push_string(this->ctx, host.c_str());
duk_int_t result = duk_pcall(this->ctx, 2);
if (result == 0) {
// Success
const char *proxy = duk_get_string(this->ctx, 0);
if (!proxy) {
duk_pop(this->ctx);
return "";
}
string proxyString = string(proxy);
duk_pop(this->ctx);
return proxyString;
} else {
// Something happened. The top of the stack is an error.
duk_pop(this->ctx);
return "";
}
}
private:
duk_context *ctx;
};
PX_PACRUNNER_MODULE_EZ(duktape, "duk_create_heap_default", "duktape");
<commit_msg>_WIN32 to WIN32 and remove already imported headers in windows<commit_after>/*******************************************************************************
* libproxy - A library for proxy configuration
* Copyright (C) 2006 Nathaniel McCallum <nathaniel@natemccallum.com>
* Copyright (C) 2021 Zhaofeng Li <hello@zhaofeng.li>
*
* 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
******************************************************************************/
#include "../extension_pacrunner.hpp"
#ifndef WIN32
#include <unistd.h> // gethostname
#endif
using namespace libproxy;
#include <duktape.h>
#include "pacutils.h"
static duk_ret_t dnsResolve(duk_context *ctx) {
if (duk_get_top(ctx) != 1) {
// Invalid number of arguments
return 0;
}
// We do not need to free the string - It's managed by Duktape.
const char *hostname = duk_get_string(ctx, 0);
if (!hostname) {
return 0;
}
// Look it up
struct addrinfo *info;
if (getaddrinfo(hostname, NULL, NULL, &info)) {
return 0;
}
// Try for IPv4
char tmp[INET6_ADDRSTRLEN+1];
if (getnameinfo(info->ai_addr, info->ai_addrlen,
tmp, INET6_ADDRSTRLEN+1,
NULL, 0,
NI_NUMERICHOST)) {
freeaddrinfo(info);
duk_push_null(ctx);
return 1;
}
freeaddrinfo(info);
// Create the return value
duk_push_string(ctx, tmp);
return 1;
}
static duk_ret_t myIpAddress(duk_context *ctx) {
char hostname[1024];
hostname[sizeof(hostname) - 1] = '\0';
if (!gethostname(hostname, sizeof(hostname) - 1)) {
duk_push_string(ctx, hostname);
return dnsResolve(ctx);
}
return duk_error(ctx, DUK_ERR_ERROR, "Unable to find hostname!");
}
class duktape_pacrunner : public pacrunner {
public:
duktape_pacrunner(string pac, const url& pacurl) : pacrunner(pac, pacurl) {
#ifdef WIN32
// On windows, we need to initialize the winsock dll first.
WSADATA WsaData;
WSAStartup(MAKEWORD(2, 0), &WsaData);
#endif
this->ctx = duk_create_heap_default();
if (!this->ctx) goto error;
duk_push_c_function(this->ctx, dnsResolve, 1);
duk_put_global_string(this->ctx, "dnsResolve");
duk_push_c_function(this->ctx, myIpAddress, 1);
duk_put_global_string(this->ctx, "myIpAddress");
// Add other routines
duk_push_string(this->ctx, JAVASCRIPT_ROUTINES);
if (duk_peval_noresult(this->ctx)) {
goto error;
}
// Add the PAC into the context
duk_push_string(this->ctx, pac.c_str());
if (duk_peval_noresult(this->ctx)) {
goto error;
}
return;
error:
duk_destroy_heap(this->ctx);
throw bad_alloc();
}
~duktape_pacrunner() {
duk_destroy_heap(this->ctx);
#ifdef WIN32
WSACleanup();
#endif
}
string run(const url& url_) override {
string url = url_.to_string();
string host = url_.get_host();
duk_get_global_string(this->ctx, "FindProxyForURL");
duk_push_string(this->ctx, url.c_str());
duk_push_string(this->ctx, host.c_str());
duk_int_t result = duk_pcall(this->ctx, 2);
if (result == 0) {
// Success
const char *proxy = duk_get_string(this->ctx, 0);
if (!proxy) {
duk_pop(this->ctx);
return "";
}
string proxyString = string(proxy);
duk_pop(this->ctx);
return proxyString;
} else {
// Something happened. The top of the stack is an error.
duk_pop(this->ctx);
return "";
}
}
private:
duk_context *ctx;
};
PX_PACRUNNER_MODULE_EZ(duktape, "duk_create_heap_default", "duktape");
<|endoftext|> |
<commit_before>/* Rapicorn
* Copyright (C) 2005 Tim Janik
*
* 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 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., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __RAPICORN_ITEM_HH_
#define __RAPICORN_ITEM_HH_
#include <rapicorn/events.hh>
#include <rapicorn/primitives.hh>
#include <rapicorn/commands.hh>
#include <rapicorn/properties.hh>
#include <rapicorn/appearance.hh>
namespace Rapicorn {
/* --- Item structures and forward decls --- */
struct Requisition {
double width, height;
Requisition () : width (0), height (0) {}
Requisition (double w, double h) : width (w), height (h) {}
};
struct Allocation {
int x, y, width, height;
Allocation() : x (0), y (0), width (0), height (0) {}
Allocation (int cx, int cy, int cwidth, int cheight) : x (cx), y (cy), width (cwidth), height (cheight) {}
bool operator== (const Allocation &other) { return other.x == x && other.y == y && other.width == width && other.height == height; }
bool operator!= (const Allocation &other) { return !operator== (other); }
};
class Item;
class Container;
class Root;
/* --- event handler --- */
class EventHandler : public virtual ReferenceCountImpl {
typedef Signal<EventHandler, bool (const Event&), CollectorWhile0<bool> > EventSignal;
protected:
virtual bool handle_event (const Event &event);
public:
explicit EventHandler ();
EventSignal sig_event;
typedef enum {
RESET_ALL
} ResetMode;
virtual void reset (ResetMode mode = RESET_ALL) = 0;
};
/* --- Item --- */
class Item : public virtual Convertible, public virtual DataListContainer, public virtual ReferenceCountImpl {
/*Copy*/ Item (const Item&);
Item& operator= (const Item&);
Item *m_parent; /* interface-inlined for fast read-out */
uint32 m_flags; /* interface-inlined for fast read-out */
Style *m_style;
friend class Container;
void propagate_flags ();
void propagate_style ();
protected:
/* flag handling */
bool change_flags_silently (uint32 mask, bool on);
enum {
ANCHORED = 1 << 0,
VISIBLE = 1 << 1,
HIDDEN_CHILD = 1 << 2,
SENSITIVE = 1 << 3,
PARENT_SENSITIVE = 1 << 4,
PRELIGHT = 1 << 5,
IMPRESSED = 1 << 6,
HAS_FOCUS = 1 << 7,
HAS_DEFAULT = 1 << 8,
/* REQUEST_DEFAULT = 1 << 8, */
INVALID_REQUISITION = 1 << 10,
INVALID_ALLOCATION = 1 << 11,
EXPOSE_ON_CHANGE = 1 << 12,
INVALIDATE_ON_CHANGE = 1 << 13,
HEXPAND = 1 << 14,
VEXPAND = 1 << 15,
HSPREAD = 1 << 16,
VSPREAD = 1 << 17,
HSPREAD_CONTAINER = 1 << 18,
VSPREAD_CONTAINER = 1 << 19,
POSITIVE_ALLOCATION = 1 << 20,
DEBUG = 1 << 21,
LAST_FLAG = 1 << 22
};
void set_flag (uint32 flag, bool on = true);
void unset_flag (uint32 flag) { set_flag (flag, false); }
bool test_flags (uint32 mask) const { return (m_flags & mask) == mask; }
bool test_any_flag (uint32 mask) const { return (m_flags & mask) != 0; }
/* size requisition and allocation */
virtual void size_request (Requisition &requisition) = 0;
virtual void size_allocate (Allocation area) = 0;
/* signal methods */
virtual bool match_interface (InterfaceMatch &imatch, const String &ident);
virtual void do_invalidate () = 0;
virtual void do_changed () = 0;
/* misc */
virtual ~Item ();
virtual void style (Style *st);
virtual void finalize ();
virtual void hierarchy_changed (Item *old_toplevel);
void anchored (bool b) { set_flag (ANCHORED, b); }
public:
explicit Item ();
bool anchored () const { return test_flags (ANCHORED); }
bool visible () const { return test_flags (VISIBLE) && !test_flags (HIDDEN_CHILD); }
void visible (bool b) { set_flag (VISIBLE, b); }
bool sensitive () const { return test_flags (SENSITIVE | PARENT_SENSITIVE); }
virtual void sensitive (bool b);
bool insensitive () const { return !sensitive(); }
void insensitive (bool b) { sensitive (!b); }
bool prelight () const { return test_flags (PRELIGHT); }
virtual void prelight (bool b);
bool branch_prelight () const;
bool impressed () const { return test_flags (IMPRESSED); }
virtual void impressed (bool b);
bool branch_impressed() const;
bool has_focus () const { return test_flags (HAS_FOCUS); }
bool grab_focus () const;
bool has_default () const { return test_flags (HAS_DEFAULT); }
bool grab_default () const;
bool hexpand () const { return test_any_flag (HEXPAND | HSPREAD | HSPREAD_CONTAINER); }
void hexpand (bool b) { set_flag (HEXPAND, b); }
bool vexpand () const { return test_any_flag (VEXPAND | VSPREAD | VSPREAD_CONTAINER); }
void vexpand (bool b) { set_flag (VEXPAND, b); }
bool hspread () const { return test_any_flag (HSPREAD | HSPREAD_CONTAINER); }
void hspread (bool b) { set_flag (HSPREAD, b); }
bool vspread () const { return test_any_flag (VSPREAD | VSPREAD_CONTAINER); }
void vspread (bool b) { set_flag (VSPREAD, b); }
bool drawable () const { return visible() && test_flags (POSITIVE_ALLOCATION); }
bool debug () const { return test_flags (DEBUG); }
void debug (bool f) { set_flag (DEBUG, f); }
virtual String name () const = 0;
virtual void name (const String &str) = 0;
/* properties */
void set_property (const String &property_name,
const String &value,
const nothrow_t &nt = dothrow);
String get_property (const String &property_name);
Property* lookup_property (const String &property_name);
virtual const PropertyList& list_properties ();
/* commands */
bool exec_command (const String &command_call_string,
const nothrow_t &nt = dothrow);
Command* lookup_command (const String &command_name);
virtual const CommandList& list_commands ();
/* parents */
virtual void set_parent (Item *parent);
Item* parent () const { return m_parent; }
Container* parent_container() const;
bool has_ancestor (const Item &ancestor) const;
Root* root ();
/* invalidation / changes */
void invalidate ();
void changed ();
virtual void expose (const Allocation &area) = 0;
void expose () { expose (allocation()); }
/* public signals */
SignalFinalize<Item> sig_finalize;
Signal<Item, void ()> sig_changed;
Signal<Item, void ()> sig_invalidate;
Signal<Item, void (Item *oldt)> sig_hierarchy_changed;
public:
/* event handling */
bool process_event (Event &event);
virtual bool point (double x, /* global coordinate system */
double y,
Affine affine) = 0;
/* public size accessors */
virtual const Requisition& size_request () = 0; /* re-request size */
const Requisition& requisition () { return size_request(); } /* cached requisition */
virtual void set_allocation (const Allocation &area) = 0; /* assign new allocation */
virtual const Allocation& allocation () = 0; /* current allocation */
/* display */
virtual void render (Display &display) = 0;
/* styles / appearance */
StateType state () const;
Style* style () { return m_style; }
Color foreground () { return style()->standard_color (state(), COLOR_FOREGROUND); }
Color background () { return style()->standard_color (state(), COLOR_BACKGROUND); }
Color selected_foreground () { return style()->selected_color (state(), COLOR_FOREGROUND); }
Color selected_background () { return style()->selected_color (state(), COLOR_BACKGROUND); }
Color focus_color () { return style()->standard_color (state(), COLOR_FOCUS); }
Color default_color () { return style()->standard_color (state(), COLOR_DEFAULT); }
Color light_glint () { return style()->standard_color (state(), COLOR_LIGHT_GLINT); }
Color light_shadow () { return style()->standard_color (state(), COLOR_LIGHT_SHADOW); }
Color dark_glint () { return style()->standard_color (state(), COLOR_DARK_GLINT); }
Color dark_shadow () { return style()->standard_color (state(), COLOR_DARK_SHADOW); }
Color white () { return style()->color_scheme (Style::STANDARD).generic_color (0xffffffff); }
Color black () { return style()->color_scheme (Style::STANDARD).generic_color (0xff000000); }
};
} // Rapicorn
#endif /* __RAPICORN_ITEM_HH_ */
<commit_msg>formatting fixes<commit_after>/* Rapicorn
* Copyright (C) 2005 Tim Janik
*
* 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 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., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __RAPICORN_ITEM_HH_
#define __RAPICORN_ITEM_HH_
#include <rapicorn/events.hh>
#include <rapicorn/primitives.hh>
#include <rapicorn/commands.hh>
#include <rapicorn/properties.hh>
#include <rapicorn/appearance.hh>
namespace Rapicorn {
/* --- Item structures and forward decls --- */
struct Requisition {
double width, height;
Requisition () : width (0), height (0) {}
Requisition (double w, double h) : width (w), height (h) {}
};
struct Allocation {
int x, y, width, height;
Allocation() : x (0), y (0), width (0), height (0) {}
Allocation (int cx, int cy, int cwidth, int cheight) : x (cx), y (cy), width (cwidth), height (cheight) {}
bool operator== (const Allocation &other) { return other.x == x && other.y == y && other.width == width && other.height == height; }
bool operator!= (const Allocation &other) { return !operator== (other); }
};
class Item;
class Container;
class Root;
/* --- event handler --- */
class EventHandler : public virtual ReferenceCountImpl {
typedef Signal<EventHandler, bool (const Event&), CollectorWhile0<bool> > EventSignal;
protected:
virtual bool handle_event (const Event &event);
public:
explicit EventHandler ();
EventSignal sig_event;
typedef enum {
RESET_ALL
} ResetMode;
virtual void reset (ResetMode mode = RESET_ALL) = 0;
};
/* --- Item --- */
class Item : public virtual Convertible, public virtual DataListContainer, public virtual ReferenceCountImpl {
/*Copy*/ Item (const Item&);
Item& operator= (const Item&);
Item *m_parent; /* interface-inlined for fast read-out */
uint32 m_flags; /* interface-inlined for fast read-out */
Style *m_style;
friend class Container;
void propagate_flags ();
void propagate_style ();
protected:
/* flag handling */
bool change_flags_silently (uint32 mask, bool on);
enum {
ANCHORED = 1 << 0,
VISIBLE = 1 << 1,
HIDDEN_CHILD = 1 << 2,
SENSITIVE = 1 << 3,
PARENT_SENSITIVE = 1 << 4,
PRELIGHT = 1 << 5,
IMPRESSED = 1 << 6,
HAS_FOCUS = 1 << 7,
HAS_DEFAULT = 1 << 8,
/* REQUEST_DEFAULT = 1 << 8, */
INVALID_REQUISITION = 1 << 10,
INVALID_ALLOCATION = 1 << 11,
EXPOSE_ON_CHANGE = 1 << 12,
INVALIDATE_ON_CHANGE = 1 << 13,
HEXPAND = 1 << 14,
VEXPAND = 1 << 15,
HSPREAD = 1 << 16,
VSPREAD = 1 << 17,
HSPREAD_CONTAINER = 1 << 18,
VSPREAD_CONTAINER = 1 << 19,
POSITIVE_ALLOCATION = 1 << 20,
DEBUG = 1 << 21,
LAST_FLAG = 1 << 22
};
void set_flag (uint32 flag, bool on = true);
void unset_flag (uint32 flag) { set_flag (flag, false); }
bool test_flags (uint32 mask) const { return (m_flags & mask) == mask; }
bool test_any_flag (uint32 mask) const { return (m_flags & mask) != 0; }
/* size requisition and allocation */
virtual void size_request (Requisition &requisition) = 0;
virtual void size_allocate (Allocation area) = 0;
/* signal methods */
virtual bool match_interface (InterfaceMatch &imatch, const String &ident);
virtual void do_invalidate () = 0;
virtual void do_changed () = 0;
/* misc */
virtual ~Item ();
virtual void style (Style *st);
virtual void finalize ();
virtual void hierarchy_changed (Item *old_toplevel);
void anchored (bool b) { set_flag (ANCHORED, b); }
public:
explicit Item ();
bool anchored () const { return test_flags (ANCHORED); }
bool visible () const { return test_flags (VISIBLE) && !test_flags (HIDDEN_CHILD); }
void visible (bool b) { set_flag (VISIBLE, b); }
bool sensitive () const { return test_flags (SENSITIVE | PARENT_SENSITIVE); }
virtual void sensitive (bool b);
bool insensitive () const { return !sensitive(); }
void insensitive (bool b) { sensitive (!b); }
bool prelight () const { return test_flags (PRELIGHT); }
virtual void prelight (bool b);
bool branch_prelight () const;
bool impressed () const { return test_flags (IMPRESSED); }
virtual void impressed (bool b);
bool branch_impressed () const;
bool has_focus () const { return test_flags (HAS_FOCUS); }
bool grab_focus () const;
bool has_default () const { return test_flags (HAS_DEFAULT); }
bool grab_default () const;
bool hexpand () const { return test_any_flag (HEXPAND | HSPREAD | HSPREAD_CONTAINER); }
void hexpand (bool b) { set_flag (HEXPAND, b); }
bool vexpand () const { return test_any_flag (VEXPAND | VSPREAD | VSPREAD_CONTAINER); }
void vexpand (bool b) { set_flag (VEXPAND, b); }
bool hspread () const { return test_any_flag (HSPREAD | HSPREAD_CONTAINER); }
void hspread (bool b) { set_flag (HSPREAD, b); }
bool vspread () const { return test_any_flag (VSPREAD | VSPREAD_CONTAINER); }
void vspread (bool b) { set_flag (VSPREAD, b); }
bool drawable () const { return visible() && test_flags (POSITIVE_ALLOCATION); }
bool debug () const { return test_flags (DEBUG); }
void debug (bool f) { set_flag (DEBUG, f); }
virtual String name () const = 0;
virtual void name (const String &str) = 0;
/* properties */
void set_property (const String &property_name,
const String &value,
const nothrow_t &nt = dothrow);
String get_property (const String &property_name);
Property* lookup_property (const String &property_name);
virtual const PropertyList& list_properties ();
/* commands */
bool exec_command (const String &command_call_string,
const nothrow_t &nt = dothrow);
Command* lookup_command (const String &command_name);
virtual const CommandList& list_commands ();
/* parents */
virtual void set_parent (Item *parent);
Item* parent () const { return m_parent; }
Container* parent_container () const;
bool has_ancestor (const Item &ancestor) const;
Root* root ();
/* invalidation / changes */
void invalidate ();
void changed ();
virtual void expose (const Allocation &area) = 0;
void expose () { expose (allocation()); }
/* public signals */
SignalFinalize<Item> sig_finalize;
Signal<Item, void ()> sig_changed;
Signal<Item, void ()> sig_invalidate;
Signal<Item, void (Item *oldt)> sig_hierarchy_changed;
public:
/* event handling */
bool process_event (Event &event);
virtual bool point (double x, /* global coordinate system */
double y,
Affine affine) = 0;
/* public size accessors */
virtual const Requisition& size_request () = 0; /* re-request size */
const Requisition& requisition () { return size_request(); } /* cached requisition */
virtual void set_allocation (const Allocation &area) = 0; /* assign new allocation */
virtual const Allocation& allocation () = 0; /* current allocation */
/* display */
virtual void render (Display &display) = 0;
/* styles / appearance */
StateType state () const;
Style* style () { return m_style; }
Color foreground () { return style()->standard_color (state(), COLOR_FOREGROUND); }
Color background () { return style()->standard_color (state(), COLOR_BACKGROUND); }
Color selected_foreground () { return style()->selected_color (state(), COLOR_FOREGROUND); }
Color selected_background () { return style()->selected_color (state(), COLOR_BACKGROUND); }
Color focus_color () { return style()->standard_color (state(), COLOR_FOCUS); }
Color default_color () { return style()->standard_color (state(), COLOR_DEFAULT); }
Color light_glint () { return style()->standard_color (state(), COLOR_LIGHT_GLINT); }
Color light_shadow () { return style()->standard_color (state(), COLOR_LIGHT_SHADOW); }
Color dark_glint () { return style()->standard_color (state(), COLOR_DARK_GLINT); }
Color dark_shadow () { return style()->standard_color (state(), COLOR_DARK_SHADOW); }
Color white () { return style()->color_scheme (Style::STANDARD).generic_color (0xffffffff); }
Color black () { return style()->color_scheme (Style::STANDARD).generic_color (0xff000000); }
};
} // Rapicorn
#endif /* __RAPICORN_ITEM_HH_ */
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/debug_util.h"
#include <unistd.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "base/logging.h"
#include "base/string_piece.h"
bool DebugUtil::SpawnDebuggerOnProcess(unsigned /* process_id */) {
NOTIMPLEMENTED();
return false;
}
#if defined(OS_MACOSX)
// http://developer.apple.com/qa/qa2004/qa1361.html
bool DebugUtil::BeingDebugged() {
NOTIMPLEMENTED();
return false;
}
#elif defined(OS_LINUX)
// We can look in /proc/self/status for TracerPid. We are likely used in crash
// handling, so we are careful not to use the heap or have side effects.
// Another option that is common is to try to ptrace yourself, but then we
// can't detach without forking(), and that's not so great.
bool DebugUtil::BeingDebugged() {
int status_fd = open("/proc/self/status", O_RDONLY);
if (status_fd == -1)
return false;
// We assume our line will be in the first 1024 characters and that we can
// read this much all at once. In practice this will generally be true.
// This simplifies and speeds up things considerably.
char buf[1024];
ssize_t num_read = read(status_fd, buf, sizeof(buf));
close(status_fd);
if (num_read <= 0)
return false;
StringPiece status(buf, num_read);
StringPiece tracer("TracerPid:\t");
StringPiece::size_type pid_index = status.find(tracer);
if (pid_index == StringPiece::npos)
return false;
// Our pid is 0 without a debugger, assume this for any pid starting with 0.
pid_index += tracer.size();
return pid_index < status.size() && status[pid_index] != '0';
}
#endif
// static
void DebugUtil::BreakDebugger() {
asm ("int3");
}
<commit_msg>Add Mac BeingDebugged implementation Review URL: http://codereview.chromium.org/6582<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/debug_util.h"
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <unistd.h>
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/string_piece.h"
// static
bool DebugUtil::SpawnDebuggerOnProcess(unsigned /* process_id */) {
NOTIMPLEMENTED();
return false;
}
#if defined(OS_MACOSX)
// Based on Apple's recommended method as described in
// http://developer.apple.com/qa/qa2004/qa1361.html
// static
bool DebugUtil::BeingDebugged() {
// Initialize mib, which tells sysctl what info we want. In this case,
// we're looking for information about a specific process ID.
int mib[] = {
CTL_KERN,
KERN_PROC,
KERN_PROC_PID,
getpid()
};
// Caution: struct kinfo_proc is marked __APPLE_API_UNSTABLE. The source and
// binary interfaces may change.
struct kinfo_proc info;
size_t info_size = sizeof(info);
int sysctl_result = sysctl(mib, arraysize(mib), &info, &info_size, NULL, 0);
DCHECK(sysctl_result == 0);
if (sysctl_result != 0)
return false;
// This process is being debugged if the P_TRACED flag is set.
return (info.kp_proc.p_flag & P_TRACED) != 0;
}
#elif defined(OS_LINUX)
// We can look in /proc/self/status for TracerPid. We are likely used in crash
// handling, so we are careful not to use the heap or have side effects.
// Another option that is common is to try to ptrace yourself, but then we
// can't detach without forking(), and that's not so great.
// static
bool DebugUtil::BeingDebugged() {
int status_fd = open("/proc/self/status", O_RDONLY);
if (status_fd == -1)
return false;
// We assume our line will be in the first 1024 characters and that we can
// read this much all at once. In practice this will generally be true.
// This simplifies and speeds up things considerably.
char buf[1024];
ssize_t num_read = read(status_fd, buf, sizeof(buf));
close(status_fd);
if (num_read <= 0)
return false;
StringPiece status(buf, num_read);
StringPiece tracer("TracerPid:\t");
StringPiece::size_type pid_index = status.find(tracer);
if (pid_index == StringPiece::npos)
return false;
// Our pid is 0 without a debugger, assume this for any pid starting with 0.
pid_index += tracer.size();
return pid_index < status.size() && status[pid_index] != '0';
}
#endif // OS_LINUX
// static
void DebugUtil::BreakDebugger() {
asm ("int3");
}
<|endoftext|> |
<commit_before>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <limits>
#include <vector>
using namespace std;
extern "C" {
#include "clhash.h"
#include "cw-trick.h"
#include "multiply-shift.h"
#include "tabulated.h"
}
inline uint64_t RDTSC_START() {
unsigned cyc_high, cyc_low;
__asm volatile("cpuid\n\t"
"rdtsc\n\t"
"mov %%edx, %0\n\t"
"mov %%eax, %1\n\t"
: "=r"(cyc_high), "=r"(cyc_low)::"%rax", "%rbx", "%rcx",
"%rdx");
return ((uint64_t)cyc_high << 32) | cyc_low;
}
inline uint64_t RDTSC_FINAL() {
unsigned cyc_high, cyc_low;
__asm volatile("rdtscp\n\t"
"mov %%edx, %0\n\t"
"mov %%eax, %1\n\t"
"cpuid\n\t"
: "=r"(cyc_high), "=r"(cyc_low)::"%rax", "%rbx", "%rcx",
"%rdx");
return ((uint64_t)cyc_high << 32) | cyc_low;
}
static __attribute__((noinline)) uint64_t rdtsc_overhead_func(uint64_t dummy) {
return dummy;
}
uint64_t global_rdtsc_overhead = (uint64_t)UINT64_MAX;
void RDTSC_SET_OVERHEAD(int repeat) {
uint64_t cycles_start, cycles_final, cycles_diff;
uint64_t min_diff = UINT64_MAX;
for (int i = 0; i < repeat; i++) {
__asm volatile("" ::: /* pretend to clobber */ "memory");
cycles_start = RDTSC_START();
rdtsc_overhead_func(1);
cycles_final = RDTSC_FINAL();
cycles_diff = (cycles_final - cycles_start);
if (cycles_diff < min_diff)
min_diff = cycles_diff;
}
global_rdtsc_overhead = min_diff;
printf("rdtsc_overhead set to %d\n", (int)global_rdtsc_overhead);
}
typedef struct timing_stat_s {
double min_opc;// minimal number of operations per cycle
double max_opc;// maximal number of operations per cycle
double avg_opc; // average number of operations per cycle
bool wrong_answer;
} timing_stat_t;
/*
* Prints the best number of operations per cycle where
* test is the function call, repeat is the number of times we should repeat
* and size is the
* number of operations represented by test.
*/
template <typename T>
inline timing_stat_t BEST_TIME(const T &hasher, int repeat, size_t size) {
uint64_t cycles_start, cycles_final, cycles_diff;
uint64_t min_diff = (uint64_t)-1;
uint64_t max_diff = 0;
uint64_t sum_diff = 0;
bool wrong_answer = false;
for (int i = 0; i < repeat; i++) {
__asm volatile("" ::: /* pretend to clobber */ "memory");
hasher.Restart();
cycles_start = RDTSC_START();
if (hasher.Hash() != hasher.expected_)
wrong_answer = true;
cycles_final = RDTSC_FINAL();
cycles_diff = (cycles_final - cycles_start);
if (cycles_diff < min_diff)
min_diff = cycles_diff;
if (cycles_diff > max_diff)
max_diff = cycles_diff;
sum_diff += cycles_diff;
}
timing_stat_t stat;
stat.wrong_answer = wrong_answer;
stat.min_opc = min_diff / (double) size;
stat.max_opc = max_diff / (double)size;
stat.avg_opc = sum_diff / (double) ( repeat * size );
return stat;
}
void cache_flush(const void *b, size_t length) {
if (nullptr == b) return;
char *B = (char *)b;
for (uint32_t k = 0; k < length; k += 64) {
__builtin_ia32_clflush(B + k);
}
}
template <typename HashDataType, typename HashValueType,
HashValueType HashFunction(HashValueType, const HashDataType *)>
struct HashBench {
inline void Restart() const {
cache_flush(k_, sizeof(*k_));
}
inline HashValueType Hash() const {
HashValueType sum = 0;
for (uint32_t x = 0; x < length_; ++x) {
sum += HashFunction(array_[x], k_);
}
return sum;
}
HashBench(const HashValueType *const array, const uint32_t length,
const HashDataType *const k)
: array_(array), length_(length), k_(k) {
expected_ = Hash();
}
const HashValueType * const array_;
const uint32_t length_;
const HashDataType * const k_;
HashValueType expected_;
};
static const int FIRST_FIELD_WIDTH = 20;
static const int FIELD_WIDTH = 16;
static inline uint32_t intlog(uint32_t x) {
if(x == 0) return 32;
return 32 - __builtin_clzl(x);
}
template <typename T>
inline timing_stat_t Bench(const typename T::Word *input, uint32_t length, int repeat) {
typename T::Randomness * randomness = new typename T::Randomness();
if(randomness == NULL) std::cerr << "Failure to allocate" << std::endl;
T::InitRandomness(randomness);
repeat = std::max(UINT32_C(1),repeat / intlog(length));
HashBench<typename T::Randomness, typename T::Word, &T::HashFunction> demo(
input, length, randomness);
timing_stat_t answer = BEST_TIME(demo, repeat, length);
delete randomness;
return answer;
}
template <typename WordP, typename RandomnessP,
void (*InitRandomnessP)(RandomnessP *),
WordP (*HashFunctionP)(WordP, const RandomnessP *)>
struct GenericPack {
typedef WordP Word;
typedef RandomnessP Randomness;
static inline void InitRandomness(Randomness *r) { InitRandomnessP(r); }
static inline Word HashFunction(Word x, const Randomness *r) {
return HashFunctionP(x, r);
}
};
struct Zobrist64Pack
: public GenericPack<uint64_t, zobrist_t, zobrist_init, zobrist> {
static constexpr auto NAME = "Zobrist64";
};
struct ThorupZhang64Pack
: public GenericPack<uint64_t, thorupzhang_t, thorupzhang_init, thorupzhang> {
static constexpr auto NAME = "ThorupZhang64";
};
struct ZobristTranspose64Pack
: public GenericPack<uint64_t, zobrist_flat_t, zobrist_flat_init,
zobrist_flat_transpose> {
static constexpr auto NAME = "Transposed64";
};
struct ClLinear64Pack
: public GenericPack<uint64_t, cl_linear_t, cl_linear_init, cl_linear> {
static constexpr auto NAME = "ClLinear64";
};
struct MultiplyShift64Pack
: public GenericPack<uint64_t, MultiplyShift64Randomness,
MultiplyShift64Init, MultiplyShift64> {
static constexpr auto NAME = "MultiplyShift64";
};
struct ClQuadratic64Pack : public GenericPack<uint64_t, cl_quadratic_t,
cl_quadratic_init, cl_quadratic> {
static constexpr auto NAME = "ClQuadratic64";
};
struct ClCubic64Pack
: public GenericPack<uint64_t, cl_cubic_t, cl_cubic_init, cl_cubic> {
static constexpr auto NAME = "ClCubic64";
};
struct ThorupZhangCWCubic64Pack
: public GenericPack<uint64_t, ThorupZhangCWCubic64_t, ThorupZhangCWCubic64Init, ThorupZhangCWCubic64> {
static constexpr auto NAME = "ThorupCWCubic64";
};
struct ClQuartic64Pack
: public GenericPack<uint64_t, cl_quartic_t, cl_quartic_init, cl_quartic> {
static constexpr auto NAME = "ClQuartic64";
};
struct Zobrist32Pack
: public GenericPack<uint32_t, zobrist32_t, zobrist32_init, zobrist32> {
static constexpr auto NAME = "Zobrist32";
};
struct ThorupZhang32Pack
: public GenericPack<uint32_t, thorupzhang32_t, thorupzhang32_init, thorupzhang32> {
static constexpr auto NAME = "ThorupZhang32";
};
struct ClLinear32Pack
: public GenericPack<uint32_t, cl_linear_t, cl_linear32_init, cl_linear32> {
static constexpr auto NAME = "ClLinear32";
};
struct MultiplyShift32Pack
: public GenericPack<uint32_t, MultiplyShift32Randomness,
MultiplyShift32Init, MultiplyShift32> {
static constexpr auto NAME = "MultiplyShift32";
};
struct ClQuadratic32Pack
: public GenericPack<uint32_t, cl_quadratic_t, cl_quadratic32_init,
cl_quadratic32> {
static constexpr auto NAME = "ClQuadratic32";
};
struct ClCubic32Pack
: public GenericPack<uint32_t, cl_cubic_t, cl_cubic32_init,
cl_cubic32> {
static constexpr auto NAME = "ClCubic32";
};
struct ClQuartic32Pack
: public GenericPack<uint32_t, cl_quartic_t, cl_quartic32_init,
cl_quartic32> {
static constexpr auto NAME = "ClQuartic32";
};
struct CWQuad32Pack
: public GenericPack<uint32_t, CWRandomQuad32, CWRandomQuad32Init,
CWQuad32> {
static constexpr auto NAME = "CWQuad32";
};
struct ThorupZhangCWCubic32Pack
: public GenericPack<uint32_t, ThorupZhangCWCubic32_t, ThorupZhangCWCubic32Init, ThorupZhangCWCubic32> {
static constexpr auto NAME = "ThorupCWCubic32";
};
template <typename... Pack> inline void BenchPack(...) { cout << endl; }
template <typename Pack, typename... Rest>
inline void BenchPack(const typename Pack::Word *input, uint32_t length,
int repeat) {
timing_stat_t t = Bench<Pack>(&input[0], length, repeat);
if(t.wrong_answer) {
cout << "BUG";
} else {
cout << setw(FIELD_WIDTH) << fixed << setprecision(2) << t.avg_opc ;
}
BenchPack<Rest...>(input, length, repeat);
}
template <typename... Pack> inline void NamePack(...) { cout << endl; }
template <typename Pack, typename... Rest>
inline void NamePack(typename Pack::Word dummy) {
cout << setw(FIELD_WIDTH) << Pack::NAME;
NamePack<Rest...>(dummy);
}
template <typename... Pack> inline void SizePack(...) { cout << endl; }
template <typename Pack, typename... Rest>
inline void SizePack(typename Pack::Word dummy) {
cout << setw(FIELD_WIDTH) << sizeof(typename Pack::Randomness);
SizePack<Rest...>(dummy);
}
template <typename Pack, typename... Packs>
void RunSizedBench(uint32_t length, int repeat) {
vector<typename Pack::Word> input(length);
for (auto &i : input) {
i = get64rand();
}
cout << setw(FIRST_FIELD_WIDTH) << length;
BenchPack<Pack, Packs...>(&input[0], length, repeat);
}
template <typename Pack, typename... Packs>
void basic(const vector<uint32_t> &lengths, int repeat) {
cout << numeric_limits<typename Pack::Word>::digits << " bit hash functions"
<< endl;
cout << setw(FIRST_FIELD_WIDTH) << "size \\ hash fn";
NamePack<Pack, Packs...>(0);
cout << setw(FIRST_FIELD_WIDTH) << "rand size";
SizePack<Pack, Packs...>(0);
for (const auto length : lengths) {
RunSizedBench<Pack, Packs...>(length, repeat);
}
}
#include <sys/resource.h>
int main() {
int repeat = 1000;
if (global_rdtsc_overhead == UINT64_MAX) {
RDTSC_SET_OVERHEAD(repeat);
}
printf("We report the time (in cycles) necessary to hash a word.\n");
printf("Size is reported in bytes.\n");
printf("zobrist is 3-wise ind., linear is 2-wise ind., quadratic is 3-wise "
"ind., cubic is 4-wise ind.\n");
printf("Keys are flushed at the beginning of each run.\n");
const vector<uint32_t> sizes{10, 20, 100, 1000, 10000, 100000,1000000};
basic<Zobrist64Pack, ZobristTranspose64Pack, ThorupZhang64Pack, MultiplyShift64Pack,
ClLinear64Pack, ClQuadratic64Pack, ClCubic64Pack, ClQuartic64Pack, ThorupZhangCWCubic64Pack>(sizes, repeat);
basic<Zobrist32Pack, ThorupZhang32Pack, MultiplyShift32Pack, ClLinear32Pack, ClQuadratic32Pack, ClCubic32Pack,
ClQuartic32Pack, CWQuad32Pack, ThorupZhangCWCubic32Pack>(sizes, repeat);
printf("Large runs are beneficial to tabulation-based hashing because they "
"amortize cache faults.\n");
}
<commit_msg>Issue https://github.com/speedyhash/shorthash/issues/2<commit_after>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <limits>
#include <vector>
using namespace std;
extern "C" {
#include "clhash.h"
#include "cw-trick.h"
#include "multiply-shift.h"
#include "tabulated.h"
}
inline uint64_t RDTSC_START() {
unsigned cyc_high, cyc_low;
__asm volatile("cpuid\n\t"
"rdtsc\n\t"
"mov %%edx, %0\n\t"
"mov %%eax, %1\n\t"
: "=r"(cyc_high), "=r"(cyc_low)::"%rax", "%rbx", "%rcx",
"%rdx");
return ((uint64_t)cyc_high << 32) | cyc_low;
}
inline uint64_t RDTSC_FINAL() {
unsigned cyc_high, cyc_low;
__asm volatile("rdtscp\n\t"
"mov %%edx, %0\n\t"
"mov %%eax, %1\n\t"
"cpuid\n\t"
: "=r"(cyc_high), "=r"(cyc_low)::"%rax", "%rbx", "%rcx",
"%rdx");
return ((uint64_t)cyc_high << 32) | cyc_low;
}
static __attribute__((noinline)) uint64_t rdtsc_overhead_func(uint64_t dummy) {
return dummy;
}
uint64_t global_rdtsc_overhead = (uint64_t)UINT64_MAX;
void RDTSC_SET_OVERHEAD(int repeat) {
uint64_t cycles_start, cycles_final, cycles_diff;
uint64_t min_diff = UINT64_MAX;
for (int i = 0; i < repeat; i++) {
__asm volatile("" ::: /* pretend to clobber */ "memory");
cycles_start = RDTSC_START();
rdtsc_overhead_func(1);
cycles_final = RDTSC_FINAL();
cycles_diff = (cycles_final - cycles_start);
if (cycles_diff < min_diff)
min_diff = cycles_diff;
}
global_rdtsc_overhead = min_diff;
printf("rdtsc_overhead set to %d\n", (int)global_rdtsc_overhead);
}
typedef struct timing_stat_s {
double min_opc;// minimal number of operations per cycle
double max_opc;// maximal number of operations per cycle
double avg_opc; // average number of operations per cycle
bool wrong_answer;
} timing_stat_t;
/*
* Prints the best number of operations per cycle where
* test is the function call, repeat is the number of times we should repeat
* and size is the
* number of operations represented by test.
*/
template <typename T>
inline timing_stat_t BEST_TIME(const T &hasher, int repeat, size_t size) {
uint64_t cycles_start, cycles_final, cycles_diff;
uint64_t min_diff = (uint64_t)-1;
uint64_t max_diff = 0;
uint64_t sum_diff = 0;
bool wrong_answer = false;
for (int i = 0; i < repeat; i++) {
__asm volatile("" ::: /* pretend to clobber */ "memory");
hasher.Restart();
cycles_start = RDTSC_START();
if (hasher.Hash() != hasher.expected_)
wrong_answer = true;
cycles_final = RDTSC_FINAL();
cycles_diff = (cycles_final - cycles_start) - global_rdtsc_overhead;
if (cycles_diff < min_diff)
min_diff = cycles_diff;
if (cycles_diff > max_diff)
max_diff = cycles_diff;
sum_diff += cycles_diff;
}
timing_stat_t stat;
stat.wrong_answer = wrong_answer;
stat.min_opc = min_diff / (double) size;
stat.max_opc = max_diff / (double)size;
stat.avg_opc = sum_diff / (double) ( repeat * size );
return stat;
}
void cache_flush(const void *b, size_t length) {
if (nullptr == b) return;
char *B = (char *)b;
for (uint32_t k = 0; k < length; k += 64) {
__builtin_ia32_clflush(B + k);
}
}
template <typename HashDataType, typename HashValueType,
HashValueType HashFunction(HashValueType, const HashDataType *)>
struct HashBench {
inline void Restart() const {
cache_flush(k_, sizeof(*k_));
}
inline HashValueType Hash() const {
HashValueType sum = 0;
for (uint32_t x = 0; x < length_; ++x) {
sum += HashFunction(array_[x], k_);
}
return sum;
}
HashBench(const HashValueType *const array, const uint32_t length,
const HashDataType *const k)
: array_(array), length_(length), k_(k) {
expected_ = Hash();
}
const HashValueType * const array_;
const uint32_t length_;
const HashDataType * const k_;
HashValueType expected_;
};
static const int FIRST_FIELD_WIDTH = 20;
static const int FIELD_WIDTH = 16;
static inline uint32_t intlog(uint32_t x) {
if(x == 0) return 32;
return 32 - __builtin_clzl(x);
}
template <typename T>
inline timing_stat_t Bench(const typename T::Word *input, uint32_t length, int repeat) {
typename T::Randomness * randomness = new typename T::Randomness();
if(randomness == NULL) std::cerr << "Failure to allocate" << std::endl;
T::InitRandomness(randomness);
repeat = std::max(UINT32_C(1),repeat / intlog(length));
HashBench<typename T::Randomness, typename T::Word, &T::HashFunction> demo(
input, length, randomness);
timing_stat_t answer = BEST_TIME(demo, repeat, length);
delete randomness;
return answer;
}
template <typename WordP, typename RandomnessP,
void (*InitRandomnessP)(RandomnessP *),
WordP (*HashFunctionP)(WordP, const RandomnessP *)>
struct GenericPack {
typedef WordP Word;
typedef RandomnessP Randomness;
static inline void InitRandomness(Randomness *r) { InitRandomnessP(r); }
static inline Word HashFunction(Word x, const Randomness *r) {
return HashFunctionP(x, r);
}
};
struct Zobrist64Pack
: public GenericPack<uint64_t, zobrist_t, zobrist_init, zobrist> {
static constexpr auto NAME = "Zobrist64";
};
struct ThorupZhang64Pack
: public GenericPack<uint64_t, thorupzhang_t, thorupzhang_init, thorupzhang> {
static constexpr auto NAME = "ThorupZhang64";
};
struct ZobristTranspose64Pack
: public GenericPack<uint64_t, zobrist_flat_t, zobrist_flat_init,
zobrist_flat_transpose> {
static constexpr auto NAME = "Transposed64";
};
struct ClLinear64Pack
: public GenericPack<uint64_t, cl_linear_t, cl_linear_init, cl_linear> {
static constexpr auto NAME = "ClLinear64";
};
struct MultiplyShift64Pack
: public GenericPack<uint64_t, MultiplyShift64Randomness,
MultiplyShift64Init, MultiplyShift64> {
static constexpr auto NAME = "MultiplyShift64";
};
struct ClQuadratic64Pack : public GenericPack<uint64_t, cl_quadratic_t,
cl_quadratic_init, cl_quadratic> {
static constexpr auto NAME = "ClQuadratic64";
};
struct ClCubic64Pack
: public GenericPack<uint64_t, cl_cubic_t, cl_cubic_init, cl_cubic> {
static constexpr auto NAME = "ClCubic64";
};
struct ThorupZhangCWCubic64Pack
: public GenericPack<uint64_t, ThorupZhangCWCubic64_t, ThorupZhangCWCubic64Init, ThorupZhangCWCubic64> {
static constexpr auto NAME = "ThorupCWCubic64";
};
struct ClQuartic64Pack
: public GenericPack<uint64_t, cl_quartic_t, cl_quartic_init, cl_quartic> {
static constexpr auto NAME = "ClQuartic64";
};
struct Zobrist32Pack
: public GenericPack<uint32_t, zobrist32_t, zobrist32_init, zobrist32> {
static constexpr auto NAME = "Zobrist32";
};
struct ThorupZhang32Pack
: public GenericPack<uint32_t, thorupzhang32_t, thorupzhang32_init, thorupzhang32> {
static constexpr auto NAME = "ThorupZhang32";
};
struct ClLinear32Pack
: public GenericPack<uint32_t, cl_linear_t, cl_linear32_init, cl_linear32> {
static constexpr auto NAME = "ClLinear32";
};
struct MultiplyShift32Pack
: public GenericPack<uint32_t, MultiplyShift32Randomness,
MultiplyShift32Init, MultiplyShift32> {
static constexpr auto NAME = "MultiplyShift32";
};
struct ClQuadratic32Pack
: public GenericPack<uint32_t, cl_quadratic_t, cl_quadratic32_init,
cl_quadratic32> {
static constexpr auto NAME = "ClQuadratic32";
};
struct ClCubic32Pack
: public GenericPack<uint32_t, cl_cubic_t, cl_cubic32_init,
cl_cubic32> {
static constexpr auto NAME = "ClCubic32";
};
struct ClQuartic32Pack
: public GenericPack<uint32_t, cl_quartic_t, cl_quartic32_init,
cl_quartic32> {
static constexpr auto NAME = "ClQuartic32";
};
struct CWQuad32Pack
: public GenericPack<uint32_t, CWRandomQuad32, CWRandomQuad32Init,
CWQuad32> {
static constexpr auto NAME = "CWQuad32";
};
struct ThorupZhangCWCubic32Pack
: public GenericPack<uint32_t, ThorupZhangCWCubic32_t, ThorupZhangCWCubic32Init, ThorupZhangCWCubic32> {
static constexpr auto NAME = "ThorupCWCubic32";
};
template <typename... Pack> inline void BenchPack(...) { cout << endl; }
template <typename Pack, typename... Rest>
inline void BenchPack(const typename Pack::Word *input, uint32_t length,
int repeat) {
timing_stat_t t = Bench<Pack>(&input[0], length, repeat);
if(t.wrong_answer) {
cout << "BUG";
} else {
cout << setw(FIELD_WIDTH) << fixed << setprecision(2) << t.avg_opc ;
}
BenchPack<Rest...>(input, length, repeat);
}
template <typename... Pack> inline void NamePack(...) { cout << endl; }
template <typename Pack, typename... Rest>
inline void NamePack(typename Pack::Word dummy) {
cout << setw(FIELD_WIDTH) << Pack::NAME;
NamePack<Rest...>(dummy);
}
template <typename... Pack> inline void SizePack(...) { cout << endl; }
template <typename Pack, typename... Rest>
inline void SizePack(typename Pack::Word dummy) {
cout << setw(FIELD_WIDTH) << sizeof(typename Pack::Randomness);
SizePack<Rest...>(dummy);
}
template <typename Pack, typename... Packs>
void RunSizedBench(uint32_t length, int repeat) {
vector<typename Pack::Word> input(length);
for (auto &i : input) {
i = get64rand();
}
cout << setw(FIRST_FIELD_WIDTH) << length;
BenchPack<Pack, Packs...>(&input[0], length, repeat);
}
template <typename Pack, typename... Packs>
void basic(const vector<uint32_t> &lengths, int repeat) {
cout << numeric_limits<typename Pack::Word>::digits << " bit hash functions"
<< endl;
cout << setw(FIRST_FIELD_WIDTH) << "size \\ hash fn";
NamePack<Pack, Packs...>(0);
cout << setw(FIRST_FIELD_WIDTH) << "rand size";
SizePack<Pack, Packs...>(0);
for (const auto length : lengths) {
RunSizedBench<Pack, Packs...>(length, repeat);
}
}
#include <sys/resource.h>
int main() {
int repeat = 1000;
if (global_rdtsc_overhead == UINT64_MAX) {
RDTSC_SET_OVERHEAD(repeat);
}
printf("We report the time (in cycles) necessary to hash a word.\n");
printf("Size is reported in bytes.\n");
printf("zobrist is 3-wise ind., linear is 2-wise ind., quadratic is 3-wise "
"ind., cubic is 4-wise ind.\n");
printf("Keys are flushed at the beginning of each run.\n");
const vector<uint32_t> sizes{10, 20, 100, 1000, 10000, 100000,1000000};
basic<Zobrist64Pack, ZobristTranspose64Pack, ThorupZhang64Pack, MultiplyShift64Pack,
ClLinear64Pack, ClQuadratic64Pack, ClCubic64Pack, ClQuartic64Pack, ThorupZhangCWCubic64Pack>(sizes, repeat);
basic<Zobrist32Pack, ThorupZhang32Pack, MultiplyShift32Pack, ClLinear32Pack, ClQuadratic32Pack, ClCubic32Pack,
ClQuartic32Pack, CWQuad32Pack, ThorupZhangCWCubic32Pack>(sizes, repeat);
printf("Large runs are beneficial to tabulation-based hashing because they "
"amortize cache faults.\n");
}
<|endoftext|> |
<commit_before>//---------------------------------------------------------------------------//
/*!
* \file DataTransferKit_CopyOperator_Def.hpp
* \author Stuart Slattery
* \brief CopyOperator template member definitions.
*/
//---------------------------------------------------------------------------//
#ifndef DTK_COPYOPERATOR_DEF_HPP
#define DTK_COPYOPERATOR_DEF_HPP
#include <algorithm>
#include <vector>
#include "DataTransferKit_Exception.hpp"
#include "DataTransferKit_SerializationTraits.hpp"
#include <Teuchos_ENull.hpp>
#include <Teuchos_CommHelpers.hpp>
#include <Teuchos_ArrayRCP.hpp>
#include <Teuchos_TestForException.hpp>
#include <Tpetra_Vector.hpp>
namespace DataTransferKit
{
//---------------------------------------------------------------------------//
/*!
* \brief Constructor.
* \param source_field_name The name of the field supplied by the data
* source. Required by the DataTransferKit_DataSource interface to check field
* support.
* \param target_field_name The name of the field supplied by the data
* target. Required by the DataTransferKit_DataTarget interface to check field
* support.
* \param source DataTransferKit_DataSource implementation that will serve as the
* data source for this field.
* \param target DataTransferKit_DataTarget implementation that will serve as the
* target for this field.
* \param scalar Set to true if this field is scalar, false if distributed.
*/
template<class DataType, class HandleType, class CoordinateType, int DIM>
CopyOperator<DataType,HandleType,CoordinateType,DIM>::CopyOperator(
RCP_Communicator comm_global,
const std::string &source_field_name,
const std::string &target_field_name,
RCP_DataSource source,
RCP_DataTarget target,
bool global_data )
: d_comm( comm_global )
, d_source_field_name( source_field_name )
, d_target_field_name( target_field_name )
, d_source( source )
, d_target( target )
, d_global_data( global_data )
, d_mapped( false )
, d_active_source( false )
, d_active_target( false )
{
if ( d_source != Teuchos::null )
{
TEUCHOS_TEST_FOR_EXCEPTION(
!d_source->is_field_supported(d_source_field_name),
PreconditionException,
"Source field not supported by the source interface" << std::endl );
d_active_source = true;
}
if ( d_target != Teuchos::null )
{
TEUCHOS_TEST_FOR_EXCEPTION(
!d_target->is_field_supported(d_target_field_name),
PreconditionException,
"Target field not supported by the target interface" << std::endl );
d_active_target = true;
}
}
//---------------------------------------------------------------------------//
/*!
* \brief Destructor.
*/
template<class DataType, class HandleType, class CoordinateType, int DIM>
CopyOperator<DataType,HandleType,CoordinateType,DIM>::~CopyOperator()
{ /* ... */ }
//---------------------------------------------------------------------------//
// PUBLIC
//---------------------------------------------------------------------------//
/*!
* \brief Transfer data from the data source to the data target.
*/
template<class DataType, class HandleType, class CoordinateType, int DIM>
void
CopyOperator<DataType,HandleType,CoordinateType,DIM>::create_copy_mapping()
{
if ( d_active_source || d_active_target )
{
if ( !d_global_data )
{
point_map();
d_mapped = true;
}
}
}
//---------------------------------------------------------------------------//
/*!
* \brief Transfer data from the data source to the data target.
*/
template<class DataType, class HandleType, class CoordinateType, int DIM>
void CopyOperator<DataType,HandleType,CoordinateType,DIM>::copy()
{
if ( d_active_source || d_active_target )
{
if ( d_global_data )
{
global_copy();
}
else
{
TEUCHOS_TEST_FOR_EXCEPTION(
!d_mapped,
PreconditionException,
"Source not mapped to target prior to copy operation" << std::endl );
distributed_copy();
}
}
}
//---------------------------------------------------------------------------//
// PRIVATE
//---------------------------------------------------------------------------//
/*!
* \brief Generate topology map for this field based on point mapping.
*/
template<class DataType, class HandleType, class CoordinateType, int DIM>
void CopyOperator<DataType,HandleType,CoordinateType,DIM>::point_map()
{
// Extract the local list of target handles. These are the global indices
// for the target Tpetra map.
Teuchos::ArrayView<PointType> target_points;
std::vector<HandleType> target_handles(0);
typename Teuchos::ArrayView<PointType>::const_iterator target_point_it;
if ( d_active_target )
{
target_points = Teuchos::ArrayView<PointType>(
d_target->get_target_points( d_target_field_name ) );
target_handles.resize( target_points.size() );
typename std::vector<HandleType>::iterator target_handle_it;
for (target_handle_it = target_handles.begin(),
target_point_it = target_points.begin();
target_handle_it != target_handles.end();
++target_handle_it, ++target_point_it)
{
*target_handle_it = target_point_it->getHandle();
}
}
const Teuchos::ArrayView<const HandleType>
target_handles_view(target_handles);
d_target_map =
Tpetra::createNonContigMap<HandleType>( target_handles_view, d_comm );
TEUCHOS_TEST_FOR_EXCEPTION( d_target_map == Teuchos::null,
PostconditionException,
"Error creating target map" << std::endl );
d_comm->barrier();
// Generate a target point buffer to send to the source. Pad the rest of
// the buffer with null points. This is using -1 as the handle for a
// null point here. This is OK as tpetra requires ordinals to be equal to
// or greater than 0.
int local_size = target_points.size();
int global_max = 0;
Teuchos::reduceAll<OrdinalType,int>( *d_comm,
Teuchos::REDUCE_MAX,
int(1),
&local_size,
&global_max );
HandleType null_handle = -1;
CoordinateType null_coords[DIM];
for ( int n = 0; n < DIM; ++n )
{
null_coords[n] = 0.0;
}
PointType null_point;
null_point.setHandle( null_handle );
null_point.setCoords( null_coords );
std::vector<PointType> send_points( global_max, null_point );
typename std::vector<PointType>::iterator send_point_it;
for (send_point_it = send_points.begin(),
target_point_it = target_points.begin();
target_point_it != target_points.end();
++send_point_it, ++target_point_it)
{
*send_point_it = *target_point_it;
}
d_comm->barrier();
// Communicate local points to all processes to finish the map.
std::vector<HandleType> source_handles(0);
std::vector<PointType> receive_points(global_max);
typename std::vector<PointType>::const_iterator receive_points_it;
Teuchos::ArrayRCP<bool> local_queries;
Teuchos::ArrayRCP<bool>::const_iterator local_queries_it;
for ( int i = 0; i < d_comm->getSize(); ++i )
{
if ( d_comm->getRank() == i )
{
receive_points = send_points;
}
d_comm->barrier();
Teuchos::broadcast<OrdinalType,PointType>( *d_comm,
i,
global_max,
&receive_points[0]);
if ( d_active_source )
{
local_queries = d_source->are_local_points(
Teuchos::ArrayView<PointType>(receive_points) );
for ( local_queries_it = local_queries.begin(),
receive_points_it = receive_points.begin();
local_queries_it != local_queries.end();
++local_queries_it, ++receive_points_it )
{
if ( receive_points_it->getHandle() != -1 )
{
if ( *local_queries_it )
{
source_handles.push_back( receive_points_it->getHandle() );
}
}
}
}
}
d_comm->barrier();
const Teuchos::ArrayView<const HandleType>
source_handles_view(source_handles);
d_source_map =
Tpetra::createNonContigMap<HandleType>( source_handles_view, d_comm );
TEUCHOS_TEST_FOR_EXCEPTION( d_source_map == Teuchos::null,
PostconditionException,
"Error creating source map" << std::endl );
d_export = Teuchos::rcp(
new Tpetra::Export<HandleType>(d_source_map, d_target_map) );
TEUCHOS_TEST_FOR_EXCEPTION( d_export == Teuchos::null,
PostconditionException,
"Error creating exporter" << std::endl );
}
//---------------------------------------------------------------------------//
/*!
* \brief Perform global scalar copy.
*/
template<class DataType, class HandleType, class CoordinateType, int DIM>
void CopyOperator<DataType,HandleType,CoordinateType,DIM>::global_copy()
{
DataType global_value =
d_source->get_global_source_data( d_source_field_name );
d_target->set_global_target_data( d_target_field_name, global_value );
}
//---------------------------------------------------------------------------//
/*!
* \brief Perform distributed copy.
*/
template<class DataType, class HandleType, class CoordinateType, int DIM>
void CopyOperator<DataType,HandleType,CoordinateType,DIM>::distributed_copy()
{
Teuchos::ArrayView<DataType> source_data;
if ( d_active_source )
{
source_data = Teuchos::ArrayView<DataType>(
d_source->get_source_data(d_source_field_name) );
}
d_comm->barrier();
Tpetra::Vector<DataType> data_source_vector( d_source_map, source_data );
Tpetra::Vector<DataType> data_target_vector( d_target_map );
data_target_vector.doExport(data_source_vector, *d_export, Tpetra::INSERT);
if ( d_active_target )
{
data_target_vector.get1dCopy(
d_target->get_target_data_space(d_target_field_name) );
}
d_comm->barrier();
}
//---------------------------------------------------------------------------//
} // end namespace DataTransferKit
#endif // DTK_COPYOPERATOR_DEF_HPP
//---------------------------------------------------------------------------//
// end of DataTransferKit_CopyOperator_Def.hpp
//---------------------------------------------------------------------------//
<commit_msg>Fixed spacing<commit_after>//---------------------------------------------------------------------------//
/*!
* \file DataTransferKit_CopyOperator_Def.hpp
* \author Stuart Slattery
* \brief CopyOperator template member definitions.
*/
//---------------------------------------------------------------------------//
#ifndef DTK_COPYOPERATOR_DEF_HPP
#define DTK_COPYOPERATOR_DEF_HPP
#include <algorithm>
#include <vector>
#include "DataTransferKit_Exception.hpp"
#include "DataTransferKit_SerializationTraits.hpp"
#include <Teuchos_ENull.hpp>
#include <Teuchos_CommHelpers.hpp>
#include <Teuchos_ArrayRCP.hpp>
#include <Teuchos_TestForException.hpp>
#include <Tpetra_Vector.hpp>
namespace DataTransferKit
{
//---------------------------------------------------------------------------//
/*!
* \brief Constructor.
* \param source_field_name The name of the field supplied by the data
* source. Required by the DataTransferKit_DataSource interface to check field
* support.
* \param target_field_name The name of the field supplied by the data
* target. Required by the DataTransferKit_DataTarget interface to check field
* support.
* \param source DataTransferKit_DataSource implementation that will serve as the
* data source for this field.
* \param target DataTransferKit_DataTarget implementation that will serve as the
* target for this field.
* \param scalar Set to true if this field is scalar, false if distributed.
*/
template<class DataType, class HandleType, class CoordinateType, int DIM>
CopyOperator<DataType,HandleType,CoordinateType,DIM>::CopyOperator(
RCP_Communicator comm_global,
const std::string &source_field_name,
const std::string &target_field_name,
RCP_DataSource source,
RCP_DataTarget target,
bool global_data )
: d_comm( comm_global )
, d_source_field_name( source_field_name )
, d_target_field_name( target_field_name )
, d_source( source )
, d_target( target )
, d_global_data( global_data )
, d_mapped( false )
, d_active_source( false )
, d_active_target( false )
{
if ( d_source != Teuchos::null )
{
TEUCHOS_TEST_FOR_EXCEPTION(
!d_source->is_field_supported(d_source_field_name),
PreconditionException,
"Source field not supported by the source interface" << std::endl );
d_active_source = true;
}
if ( d_target != Teuchos::null )
{
TEUCHOS_TEST_FOR_EXCEPTION(
!d_target->is_field_supported(d_target_field_name),
PreconditionException,
"Target field not supported by the target interface" << std::endl );
d_active_target = true;
}
}
//---------------------------------------------------------------------------//
/*!
* \brief Destructor.
*/
template<class DataType, class HandleType, class CoordinateType, int DIM>
CopyOperator<DataType,HandleType,CoordinateType,DIM>::~CopyOperator()
{ /* ... */ }
//---------------------------------------------------------------------------//
// PUBLIC
//---------------------------------------------------------------------------//
/*!
* \brief Transfer data from the data source to the data target.
*/
template<class DataType, class HandleType, class CoordinateType, int DIM>
void
CopyOperator<DataType,HandleType,CoordinateType,DIM>::create_copy_mapping()
{
if ( d_active_source || d_active_target )
{
if ( !d_global_data )
{
point_map();
d_mapped = true;
}
}
}
//---------------------------------------------------------------------------//
/*!
* \brief Transfer data from the data source to the data target.
*/
template<class DataType, class HandleType, class CoordinateType, int DIM>
void CopyOperator<DataType,HandleType,CoordinateType,DIM>::copy()
{
if ( d_active_source || d_active_target )
{
if ( d_global_data )
{
global_copy();
}
else
{
TEUCHOS_TEST_FOR_EXCEPTION(
!d_mapped,
PreconditionException,
"Source not mapped to target prior to copy operation" << std::endl );
distributed_copy();
}
}
}
//---------------------------------------------------------------------------//
// PRIVATE
//---------------------------------------------------------------------------//
/*!
* \brief Generate topology map for this field based on point mapping.
*/
template<class DataType, class HandleType, class CoordinateType, int DIM>
void CopyOperator<DataType,HandleType,CoordinateType,DIM>::point_map()
{
// Extract the local list of target handles. These are the global indices
// for the target Tpetra map.
Teuchos::ArrayView<PointType> target_points;
std::vector<HandleType> target_handles(0);
typename Teuchos::ArrayView<PointType>::const_iterator target_point_it;
if ( d_active_target )
{
target_points = Teuchos::ArrayView<PointType>(
d_target->get_target_points( d_target_field_name ) );
target_handles.resize( target_points.size() );
typename std::vector<HandleType>::iterator target_handle_it;
for (target_handle_it = target_handles.begin(),
target_point_it = target_points.begin();
target_handle_it != target_handles.end();
++target_handle_it, ++target_point_it)
{
*target_handle_it = target_point_it->getHandle();
}
}
const Teuchos::ArrayView<const HandleType>
target_handles_view(target_handles);
d_target_map =
Tpetra::createNonContigMap<HandleType>( target_handles_view, d_comm );
TEUCHOS_TEST_FOR_EXCEPTION( d_target_map == Teuchos::null,
PostconditionException,
"Error creating target map" << std::endl );
d_comm->barrier();
// Generate a target point buffer to send to the source. Pad the rest of
// the buffer with null points. This is using -1 as the handle for a
// null point here. This is OK as tpetra requires ordinals to be equal to
// or greater than 0.
int local_size = target_points.size();
int global_max = 0;
Teuchos::reduceAll<OrdinalType,int>( *d_comm,
Teuchos::REDUCE_MAX,
int(1),
&local_size,
&global_max );
HandleType null_handle = -1;
CoordinateType null_coords[DIM];
for ( int n = 0; n < DIM; ++n )
{
null_coords[n] = 0.0;
}
PointType null_point;
null_point.setHandle( null_handle );
null_point.setCoords( null_coords );
std::vector<PointType> send_points( global_max, null_point );
typename std::vector<PointType>::iterator send_point_it;
for (send_point_it = send_points.begin(),
target_point_it = target_points.begin();
target_point_it != target_points.end();
++send_point_it, ++target_point_it)
{
*send_point_it = *target_point_it;
}
d_comm->barrier();
// Communicate local points to all processes to finish the map.
std::vector<HandleType> source_handles(0);
std::vector<PointType> receive_points(global_max);
typename std::vector<PointType>::const_iterator receive_points_it;
Teuchos::ArrayRCP<bool> local_queries;
Teuchos::ArrayRCP<bool>::const_iterator local_queries_it;
for ( int i = 0; i < d_comm->getSize(); ++i )
{
if ( d_comm->getRank() == i )
{
receive_points = send_points;
}
d_comm->barrier();
Teuchos::broadcast<OrdinalType,PointType>( *d_comm,
i,
global_max,
&receive_points[0]);
if ( d_active_source )
{
local_queries = d_source->are_local_points(
Teuchos::ArrayView<PointType>(receive_points) );
for ( local_queries_it = local_queries.begin(),
receive_points_it = receive_points.begin();
local_queries_it != local_queries.end();
++local_queries_it, ++receive_points_it )
{
if ( receive_points_it->getHandle() != -1 )
{
if ( *local_queries_it )
{
source_handles.push_back( receive_points_it->getHandle() );
}
}
}
}
}
d_comm->barrier();
const Teuchos::ArrayView<const HandleType>
source_handles_view(source_handles);
d_source_map =
Tpetra::createNonContigMap<HandleType>( source_handles_view, d_comm );
TEUCHOS_TEST_FOR_EXCEPTION( d_source_map == Teuchos::null,
PostconditionException,
"Error creating source map" << std::endl );
d_export = Teuchos::rcp(
new Tpetra::Export<HandleType>(d_source_map, d_target_map) );
TEUCHOS_TEST_FOR_EXCEPTION( d_export == Teuchos::null,
PostconditionException,
"Error creating exporter" << std::endl );
}
//---------------------------------------------------------------------------//
/*!
* \brief Perform global scalar copy.
*/
template<class DataType, class HandleType, class CoordinateType, int DIM>
void CopyOperator<DataType,HandleType,CoordinateType,DIM>::global_copy()
{
DataType global_value =
d_source->get_global_source_data( d_source_field_name );
d_target->set_global_target_data( d_target_field_name, global_value );
}
//---------------------------------------------------------------------------//
/*!
* \brief Perform distributed copy.
*/
template<class DataType, class HandleType, class CoordinateType, int DIM>
void CopyOperator<DataType,HandleType,CoordinateType,DIM>::distributed_copy()
{
Teuchos::ArrayView<DataType> source_data;
if ( d_active_source )
{
source_data = Teuchos::ArrayView<DataType>(
d_source->get_source_data(d_source_field_name) );
}
d_comm->barrier();
Tpetra::Vector<DataType> data_source_vector( d_source_map, source_data );
Tpetra::Vector<DataType> data_target_vector( d_target_map );
data_target_vector.doExport(data_source_vector, *d_export, Tpetra::INSERT);
if ( d_active_target )
{
data_target_vector.get1dCopy(
d_target->get_target_data_space(d_target_field_name) );
}
d_comm->barrier();
}
//---------------------------------------------------------------------------//
} // end namespace DataTransferKit
#endif // DTK_COPYOPERATOR_DEF_HPP
//---------------------------------------------------------------------------//
// end of DataTransferKit_CopyOperator_Def.hpp
//---------------------------------------------------------------------------//
<|endoftext|> |
<commit_before>//EtherEvent - Easy to use password authenticated network communication between Arduinos and EventGhost Network Event Sender/Receiver plugin, EventGhost TCPEvents plugin, Girder, and NetRemote http://github.com/per1234/EtherEvent
#include <Arduino.h>
#include "EtherEvent.h"
#include <SPI.h>
#include <Ethernet.h> //change to UIPEthernet.h(http://github.com/ntruchsess/arduino_uip) if using the ENC28J60 ethernet module
#include "MD5.h" //http://github.com/mrparp/ArduinoMD5
//Uncomment the next line if you have the Entropy library installed. Warning, not using the library will save memory at the expense of authentication security.
//#include "Entropy.h" //http://sites.google.com/site/astudyofentropy/file-cabinet
//this will disable the compiler warning for F()
#ifdef PROGMEM
#undef PROGMEM
#define PROGMEM __attribute__((section(".progmem.data")))
#endif
#define DEBUG 0 // (0==serial debug output off, 1==serial debug output on)The serial debug output will greatly increase communication time.
#define Serial if(DEBUG)Serial
//#define SENDERIP_ENABLE //Uncomment this line if the ethernet library has been modified to return the client IP address via the remoteIP function. Modification instructions here: http://forum.arduino.cc/index.php?topic=82416.0
#define MAGIC_WORD "quintessence\n\r" //word used to trigger the cookie send from the receiver. I had to #define this instead of const because find() didn't like the const
#define ACCEPT_MESSAGE "accept\n" //authentication success message. I had to #define this instead of const because find() didn't like the const
const boolean randomCookie=0; //Set to 1 to use the entropy random function for the cookie instead of the arduino random function for added security. This will increase the time required for the availableEvent() function to receive a new message and use more memory
const char withoutRelease[]="withoutRelease"; //eg sends this every time and EtherEvent filters it out
const byte withoutReleaseLength=14;
const char payloadSeparator[]="payload "; //indicates payload
const byte payloadSeparatorLength=8; //includes space at the end
const char closeMessage[]="close\n"; //sender sends this message to the receiver to close the connection
const unsigned int timeoutDefault=300; //(200)(ms)Timeout duration for each ethernet read/find of the availableEvent or sendEvent functions.
const unsigned int listenTimeoutDefault=600; //(400)(us)max time to wait for another char to be available from the client.read function during the availableEvent event/payload read - it was getting ahead of the stream and stopping before getting the whole message. This delay will be on every event receipt so it's important to make it as small as possible
const byte cookieLengthMax=6; //EtherEvent sends a 6 digit cookie(5 digit number and negative sign), eg seems to be a 4 digit cookie(socket), but it can be set larger if needed
const byte availableEventMessageLengthMax=payloadSeparatorLength+withoutReleaseLength+1+payloadSeparatorLength+etherEvent_payloadLengthMax+1+etherEvent_eventLengthMax; //I'm using globals for these 2 so I can just calculate the buffer size in the setup() instead of every time the functions is called
void EtherEventClass::begin(const char pass[]){
strcpy(EEpassword,pass); //store the password
timeout=timeoutDefault;
listenTimeout=listenTimeoutDefault;
#ifdef Entropy_h //the Entropy library is in use
Entropy.initialize(); //gets truly random numbers from the timer jitter
if(randomCookie==0){ //randomSeed is not needed if the entropy random function is used for every cookie instead of just the randomSeed
randomSeed(Entropy.random()); //Initialize the random function with a truly random value from the entropy library
}
#endif
byte maxInput=payloadSeparatorLength+withoutReleaseLength; //calculate the size of the payload/event buffer
availableEventSubmessageLengthMax=max(etherEvent_eventLengthMax,maxInput);
maxInput=payloadSeparatorLength+etherEvent_payloadLengthMax;
availableEventSubmessageLengthMax=max(availableEventSubmessageLengthMax,maxInput);
availableEventSubmessageLengthMax++; //null terminator
}
byte EtherEventClass::availableEvent(EthernetServer ðernetServer){ //checks for senders, connects, authenticates, reads the event and payload into the buffer and returns the number of bytes of the most recently received event are left in the buffer
if(byte length=strlen(receivedEvent)){ //strlen(receivedEvent)>0
return length+1; //number of bytes including the null terminator remaining to be read of the event
}
if(availablePayload()>0){ //don't get another event until the last is fully read or flushed
return 0;
}
if(EthernetClient ethernetClient = ethernetServer.available() ){ //connect to the client
Serial.println(F("EtherEvent.availableEvent: connected--------------"));
ethernetClient.setTimeout(timeout); //timeout on read/readUntil/find/findUntil/etc
if(ethernetClient.find(MAGIC_WORD)==1){ //magic word correct
Serial.println(F("EtherEvent.availableEvent: magic word received"));
int cookieInt;
#ifdef Entropy_h
if(randomCookie==1){
Serial.println(F("EtherEvent.availableEvent: RANDOM_COOKIE"));
cookieInt=Entropy.random(65536); //true random cookie for highest security
}
else{
#endif
//int cookieInt=random(65536); //make random 5 digit number to use as cookie and send to the sender
cookieInt=random(10000,32768); //using this to force a 5 digit cookie so I don't have to find the number of digits of the cookie for faster performance
#ifdef Entropy_h
}
#endif
char cookieChar[6]; //max 5 digits + minus + null terminator
itoa(cookieInt,cookieChar,10);
Serial.print(F("EtherEvent.availableEvent: cookieChar="));
Serial.println(cookieChar);
cookieChar[5]=0; //apparently itoa doesn't add a null terminator? the authentication gets all messed up without this
ethernetClient.print(cookieChar); //using ln because the cookie can be different lengths eg will take this also without the ln
char cookiePassword[max(cookieLengthMax,5)+1+strlen(EEpassword)+1]; //cookie + password separator + Password + null terminator
strcpy(cookiePassword,cookieChar); //create the hashword to compare to the received one
strcat(cookiePassword,":"); //create the hashword to compare to the received one
strcat(cookiePassword,EEpassword);
Serial.print(F("EtherEvent.availableEvent: cookiePassword="));
Serial.println(cookiePassword);
unsigned char* cookiePasswordHash=MD5::make_hash(cookiePassword);
char *cookiePasswordMD5 = MD5::make_digest(cookiePasswordHash, 16);
free(cookiePasswordHash);
Serial.print(F("EtherEvent.availableEvent: cookiePasswordMD5="));
Serial.println(cookiePasswordMD5);
if(ethernetClient.find(cookiePasswordMD5)==1){ //authentication successful
ethernetClient.flush(); //clear the \n or it will cause a null message in the payload/event message read
Serial.println(F("EtherEvent.availableEvent: authentication successful"));
ethernetClient.print(ACCEPT_MESSAGE);
free(cookiePasswordMD5);
Serial.println(F("EtherEvent.availableEvent: payload/event handler start"));
unsigned long timeStamp=millis();
byte availableLength=0;
while(availableLength<2){ //wait for a message. I have to do this because available() doesn't have a timeout, it just gives the currently available
availableLength=ethernetClient.available();
if(millis() - timeStamp > timeout){ //timeout
Serial.println(F("EtherEvent.availableEvent: timeout"));
etherEventStop(ethernetClient);
return 0;
}
}
timeStamp=micros(); //reusing this variable for both wait loops
do{ //it takes a bit of time for the full message to come through so it has to wait for the available to be final
if(availableLength>=availableEventMessageLengthMax+1){ //break out of the loop if it has enough
availableLength=availableEventMessageLengthMax+1;
break;
}
if(availableLength<ethernetClient.available()){
timeStamp=micros();
availableLength=ethernetClient.available();
}
}while(micros() - timeStamp < listenTimeout);
Serial.print(F("EtherEvent.availableEvent: availableLength="));
Serial.println(availableLength);
for(;;){
Serial.println(F("EtherEvent.availableEvent: payload/event for loop"));
byte receivedMessageSize=min(availableLength,availableEventSubmessageLengthMax); //determine the max buffer size required
char receivedMessage[receivedMessageSize]; //initialize the buffer to read into
byte bytesRead=0;
do{
bytesRead=ethernetClient.readBytesUntil(10,receivedMessage,receivedMessageSize); //put the incoming data up to the newline into receivedMessage
availableLength=availableLength-bytesRead; //used to reduce the buffer size on the next loop
receivedMessage[bytesRead]=0; //add a null terminator
Serial.print(F("EtherEvent.availableEvent: bytesRead="));
Serial.println(bytesRead);
}while(bytesRead==0);
if(strncmp(receivedMessage, payloadSeparator, payloadSeparatorLength)==0){ //received message is a payload
Serial.println(F("EtherEvent.availableEvent: payload separator received"));
if(bytesRead>payloadSeparatorLength+1){ //there is a payload
byte receivedPayloadLength=bytesRead-payloadSeparatorLength+1; //including the null terminator
Serial.print(F("EtherEvent.availableEvent: payload length(including null terminator)="));
Serial.println(receivedPayloadLength);
byte payloadCount=0;
char receivedPayloadTemp[etherEvent_payloadLengthMax+1];
for(payloadCount=0;payloadCount<receivedPayloadLength;payloadCount++){
receivedPayloadTemp[payloadCount]=receivedMessage[payloadCount+payloadSeparatorLength];
}
receivedPayloadTemp[payloadCount+1]=0;
if(strncmp(receivedPayloadTemp, withoutRelease, withoutReleaseLength)==0){
Serial.println(F("EtherEvent.availableEvent: withoutRelease"));
receivedPayloadTemp[0]=0; //delete the withoutRelease from the payload so it will be blank if there is no payload
continue;
}
strcpy(receivedPayload, receivedPayloadTemp);
Serial.print(F("EtherEvent.availableEvent: payload="));
Serial.println(receivedPayload);
}
else{ //no payload
Serial.println(F("EtherEvent.availableEvent: no payload"));
}
continue;
}
else{
Serial.print(F("EtherEvent.availableEvent: event length="));
Serial.println(bytesRead);
if(strncmp(receivedMessage,closeMessage,5)==0){
Serial.println(F("EtherEvent.availableEvent: close received, no event"));
break;
}
strncpy(receivedEvent,receivedMessage,etherEvent_eventLengthMax);
receivedEvent[bytesRead]=0;
Serial.print(F("EtherEvent.availableEvent: event received="));
Serial.println(receivedEvent);
#ifdef SENDERIP_ENABLE
byte tempIP[4];
ethernetClient.getRemoteIP(tempIP); //Save the IP address of the sender. Requires modified ethernet library
fromIP=tempIP;
#endif
break; //exit the payload/event message handler loop
}
}
}
else{
free(cookiePasswordMD5);
Serial.println(F("EtherEvent.availableEvent: authentication failed"));
}
}
etherEventStop(ethernetClient);
if(byte length=strlen(receivedEvent)){ //there is an event
return length+1;
}
}
return 0; //no event
}
byte EtherEventClass::availablePayload(){ //returns the number of chars in the payload including the null terminator if there is one
if(byte length=strlen(receivedPayload)){ //strlen(receivedPayload)>0
return length+1; //length of the payload + null terminator
}
return 0;
}
void EtherEventClass::readEvent(char eventBuffer[]){
strcpy(eventBuffer,receivedEvent);
eventBuffer[strlen(receivedEvent)]=0; //null terminator - is this needed?
receivedEvent[0]=0; //reset the event buffer
}
void EtherEventClass::readPayload(char payloadBuffer[]){
strcpy(payloadBuffer,receivedPayload);
payloadBuffer[strlen(receivedPayload)]=0; //null terminator - is this needed?
receivedPayload[0]=0; //reset the payload buffer
}
void EtherEventClass::flushReceiver(){ //dump the last message received so another one can be received
Serial.println(F("EtherEvent.flushReceiver: start"));
receivedEvent[0]=0; //reset the event buffer
receivedPayload[0]=0; //reset the payload buffer
}
IPAddress EtherEventClass::senderIP(){ //returns the ip address the current event was sent from. Requires modified ethernet library, thus the preprocesser direcive system
return fromIP;
}
boolean EtherEventClass::send(EthernetClient ðernetClient, const IPAddress sendIP, unsigned int sendPort, const char sendEvent[], const char sendPayload[]){
Serial.println(F("EtherEvent.sendEvent: attempting connection---------------"));
ethernetClient.setTimeout(timeout); //timeout on read/readUntil/find/findUntil/etc
byte sendEventSuccess=0;
if(ethernetClient.connect(sendIP,sendPort)){ //connected to receiver
Serial.println(F("EtherEvent.sendEvent: connected, sending magic word"));
ethernetClient.print(MAGIC_WORD); //send the magic word to the receiver so it will send the cookie
char receivedMessage[cookieLengthMax+1];
byte bytesRead;
if(bytesRead=ethernetClient.readBytesUntil(10,receivedMessage,cookieLengthMax)){
receivedMessage[bytesRead]=0;
char cookiePassword[bytesRead+1+strlen(EEpassword)+1]; //cookie, password separator(:), password, null terminator
strcpy(cookiePassword,receivedMessage);
strcat(cookiePassword,":"); //add the password separator to the cookie
strcat(cookiePassword,EEpassword); //add password to the cookie
Serial.print(F("EtherEvent.sendEvent: cookiePassword="));
Serial.println(cookiePassword);
unsigned char* cookiePasswordHash=MD5::make_hash(cookiePassword);
char *cookiePasswordMD5 = MD5::make_digest(cookiePasswordHash, 16);
free(cookiePasswordHash);
Serial.print(F("EtherEvent.sendEvent: hashWordMD5="));
Serial.println(cookiePasswordMD5);
cookiePasswordMD5[32]=10; //add /n - it fails the authentication with eg without this
cookiePasswordMD5[33]=0; //add the null terminator(otherwise it will keep printing garbage after the end of the string and the /n
ethernetClient.print(cookiePasswordMD5); //send the MD5 of the hashword
free(cookiePasswordMD5);
if(ethernetClient.find(ACCEPT_MESSAGE)==1){
Serial.print(F("EtherEvent.sendEvent: Payload="));
Serial.println(sendPayload);
Serial.print(F("EtherEvent.sendEvent: event="));
Serial.println(sendEvent);
if(sendPayload[0]!=0){ //check if there is a payload
ethernetClient.print(payloadSeparator);
ethernetClient.print(sendPayload);
ethernetClient.write(10);
}
ethernetClient.print(sendEvent);
ethernetClient.write(10);
sendEventSuccess=1;
}
}
etherEventStop(ethernetClient); //close the connection
}
else{
Serial.println(F("EtherEvent.sendEvent connection failed"));
}
return sendEventSuccess; //send finished
}
void EtherEventClass::setTimeout(unsigned int timeoutNew, unsigned int timeoutListenNew){
timeout=timeoutNew;
listenTimeout=timeoutListenNew;
}
void EtherEventClass::etherEventStop(EthernetClient ðernetClient){
Serial.println(F("EtherEvent.etherEventStop: stopping..."));
ethernetClient.print(closeMessage); //tell the receiver to close
ethernetClient.stop();
Serial.println(F("EtherEvent.etherEventStop: stopped"));
}
EtherEventClass EtherEvent; //This sets up a single global instance of the library so the class doesn't need to be declared in the user sketch and multiple instances are not necessary in this case.
<commit_msg>availableEvent() null message handling<commit_after>//EtherEvent - Easy to use password authenticated network communication between Arduinos and EventGhost Network Event Sender/Receiver plugin, EventGhost TCPEvents plugin, Girder, and NetRemote http://github.com/per1234/EtherEvent
#include <Arduino.h>
#include "EtherEvent.h"
#include <SPI.h>
#include <Ethernet.h> //change to UIPEthernet.h(http://github.com/ntruchsess/arduino_uip) if using the ENC28J60 ethernet module
#include "MD5.h" //http://github.com/mrparp/ArduinoMD5
//Uncomment the next line if you have the Entropy library installed. Warning, not using the library will save memory at the expense of authentication security.
//#include "Entropy.h" //http://sites.google.com/site/astudyofentropy/file-cabinet
//this will disable the compiler warning for F()
#ifdef PROGMEM
#undef PROGMEM
#define PROGMEM __attribute__((section(".progmem.data")))
#endif
#define DEBUG 0 // (0==serial debug output off, 1==serial debug output on)The serial debug output will greatly increase communication time.
#define Serial if(DEBUG)Serial
//#define SENDERIP_ENABLE //Uncomment this line if the ethernet library has been modified to return the client IP address via the remoteIP function. Modification instructions here: http://forum.arduino.cc/index.php?topic=82416.0
#define MAGIC_WORD "quintessence\n\r" //word used to trigger the cookie send from the receiver. I had to #define this instead of const because find() didn't like the const
#define ACCEPT_MESSAGE "accept\n" //authentication success message. I had to #define this instead of const because find() didn't like the const
const boolean randomCookie=0; //Set to 1 to use the entropy random function for the cookie instead of the arduino random function for added security. This will increase the time required for the availableEvent() function to receive a new message and use more memory
const char withoutRelease[]="withoutRelease"; //eg sends this every time and EtherEvent filters it out
const byte withoutReleaseLength=14;
const char payloadSeparator[]="payload "; //indicates payload
const byte payloadSeparatorLength=8; //includes space at the end
const char closeMessage[]="close\n"; //sender sends this message to the receiver to close the connection
const unsigned int timeoutDefault=300; //(200)(ms)Timeout duration for each ethernet read/find of the availableEvent or sendEvent functions.
const unsigned int listenTimeoutDefault=600; //(400)(us)max time to wait for another char to be available from the client.read function during the availableEvent event/payload read - it was getting ahead of the stream and stopping before getting the whole message. This delay will be on every event receipt so it's important to make it as small as possible
const byte cookieLengthMax=6; //EtherEvent sends a 6 digit cookie(5 digit number and negative sign), eg seems to be a 4 digit cookie(socket), but it can be set larger if needed
const byte availableEventMessageLengthMax=payloadSeparatorLength+withoutReleaseLength+1+payloadSeparatorLength+etherEvent_payloadLengthMax+1+etherEvent_eventLengthMax; //I'm using globals for these 2 so I can just calculate the buffer size in the setup() instead of every time the functions is called
void EtherEventClass::begin(const char pass[]){
strcpy(EEpassword,pass); //store the password
timeout=timeoutDefault;
listenTimeout=listenTimeoutDefault;
#ifdef Entropy_h //the Entropy library is in use
Entropy.initialize(); //gets truly random numbers from the timer jitter
if(randomCookie==0){ //randomSeed is not needed if the entropy random function is used for every cookie instead of just the randomSeed
randomSeed(Entropy.random()); //Initialize the random function with a truly random value from the entropy library
}
#endif
byte maxInput=payloadSeparatorLength+withoutReleaseLength; //calculate the size of the payload/event buffer
availableEventSubmessageLengthMax=max(etherEvent_eventLengthMax,maxInput);
maxInput=payloadSeparatorLength+etherEvent_payloadLengthMax;
availableEventSubmessageLengthMax=max(availableEventSubmessageLengthMax,maxInput);
availableEventSubmessageLengthMax++; //null terminator
}
byte EtherEventClass::availableEvent(EthernetServer ðernetServer){ //checks for senders, connects, authenticates, reads the event and payload into the buffer and returns the number of bytes of the most recently received event are left in the buffer
if(byte length=strlen(receivedEvent)){ //strlen(receivedEvent)>0
return length+1; //number of bytes including the null terminator remaining to be read of the event
}
if(availablePayload()>0){ //don't get another event until the last is fully read or flushed
return 0;
}
if(EthernetClient ethernetClient = ethernetServer.available() ){ //connect to the client
Serial.println(F("EtherEvent.availableEvent: connected--------------"));
ethernetClient.setTimeout(timeout); //timeout on read/readUntil/find/findUntil/etc
if(ethernetClient.find(MAGIC_WORD)==1){ //magic word correct
Serial.println(F("EtherEvent.availableEvent: magic word received"));
int cookieInt;
#ifdef Entropy_h
if(randomCookie==1){
Serial.println(F("EtherEvent.availableEvent: RANDOM_COOKIE"));
cookieInt=Entropy.random(65536); //true random cookie for highest security
}
else{
#endif
//int cookieInt=random(65536); //make random 5 digit number to use as cookie and send to the sender
cookieInt=random(10000,32768); //using this to force a 5 digit cookie so I don't have to find the number of digits of the cookie for faster performance
#ifdef Entropy_h
}
#endif
char cookieChar[6]; //max 5 digits + minus + null terminator
itoa(cookieInt,cookieChar,10);
Serial.print(F("EtherEvent.availableEvent: cookieChar="));
Serial.println(cookieChar);
cookieChar[5]=0; //apparently itoa doesn't add a null terminator? the authentication gets all messed up without this
ethernetClient.print(cookieChar); //using ln because the cookie can be different lengths eg will take this also without the ln
char cookiePassword[max(cookieLengthMax,5)+1+strlen(EEpassword)+1]; //cookie + password separator + Password + null terminator
strcpy(cookiePassword,cookieChar); //create the hashword to compare to the received one
strcat(cookiePassword,":"); //create the hashword to compare to the received one
strcat(cookiePassword,EEpassword);
Serial.print(F("EtherEvent.availableEvent: cookiePassword="));
Serial.println(cookiePassword);
unsigned char* cookiePasswordHash=MD5::make_hash(cookiePassword);
char *cookiePasswordMD5 = MD5::make_digest(cookiePasswordHash, 16);
free(cookiePasswordHash);
Serial.print(F("EtherEvent.availableEvent: cookiePasswordMD5="));
Serial.println(cookiePasswordMD5);
if(ethernetClient.find(cookiePasswordMD5)==1){ //authentication successful
ethernetClient.flush(); //clear the \n or it will cause a null message in the payload/event message read
Serial.println(F("EtherEvent.availableEvent: authentication successful"));
ethernetClient.print(ACCEPT_MESSAGE);
free(cookiePasswordMD5);
Serial.println(F("EtherEvent.availableEvent: payload/event handler start"));
unsigned long timeStamp=millis();
byte availableLength=0;
while(availableLength<2){ //wait for a message. I have to do this because available() doesn't have a timeout, it just gives the currently available
availableLength=ethernetClient.available();
if(millis() - timeStamp > timeout){ //timeout
Serial.println(F("EtherEvent.availableEvent: timeout"));
etherEventStop(ethernetClient);
return 0;
}
}
timeStamp=micros(); //reusing this variable for both wait loops
do{ //it takes a bit of time for the full message to come through so it has to wait for the available to be final
if(availableLength>=availableEventMessageLengthMax+1){ //break out of the loop if it has enough
availableLength=availableEventMessageLengthMax+1;
break;
}
if(availableLength<ethernetClient.available()){
timeStamp=micros();
availableLength=ethernetClient.available();
}
}while(micros() - timeStamp < listenTimeout);
Serial.print(F("EtherEvent.availableEvent: availableLength="));
Serial.println(availableLength);
for(byte count=0;count<20;count++){ //the count stuff is just to make sure it will never go into an infinite loop
Serial.println(F("EtherEvent.availableEvent: payload/event for loop"));
byte receivedMessageSize=min(availableLength,availableEventSubmessageLengthMax); //determine the max buffer size required
char receivedMessage[receivedMessageSize]; //initialize the buffer to read into
byte bytesRead=0;
bytesRead=ethernetClient.readBytesUntil(10,receivedMessage,receivedMessageSize); //put the incoming data up to the newline into receivedMessage
availableLength=availableLength-bytesRead; //used to reduce the buffer size on the next loop
receivedMessage[bytesRead]=0; //add a null terminator
Serial.print(F("EtherEvent.availableEvent: bytesRead="));
Serial.println(bytesRead);
if(bytesRead==0){ //with Arduino 1.5 there is a leading char(10) for some reason(maybe flush() doesn't work and it's still left over from the last message?). This will handle null messages
continue;
}
if(strncmp(receivedMessage, payloadSeparator, payloadSeparatorLength)==0){ //received message is a payload
Serial.println(F("EtherEvent.availableEvent: payload separator received"));
if(bytesRead>payloadSeparatorLength+1){ //there is a payload
byte receivedPayloadLength=bytesRead-payloadSeparatorLength+1; //including the null terminator
Serial.print(F("EtherEvent.availableEvent: payload length(including null terminator)="));
Serial.println(receivedPayloadLength);
byte payloadCount=0;
char receivedPayloadTemp[etherEvent_payloadLengthMax+1];
for(payloadCount=0;payloadCount<receivedPayloadLength;payloadCount++){
receivedPayloadTemp[payloadCount]=receivedMessage[payloadCount+payloadSeparatorLength];
}
receivedPayloadTemp[payloadCount+1]=0;
if(strncmp(receivedPayloadTemp, withoutRelease, withoutReleaseLength)==0){
Serial.println(F("EtherEvent.availableEvent: withoutRelease"));
receivedPayloadTemp[0]=0; //delete the withoutRelease from the payload so it will be blank if there is no payload
continue;
}
strcpy(receivedPayload, receivedPayloadTemp);
Serial.print(F("EtherEvent.availableEvent: payload="));
Serial.println(receivedPayload);
}
else{ //no payload
Serial.println(F("EtherEvent.availableEvent: no payload"));
}
continue;
}
else{
Serial.print(F("EtherEvent.availableEvent: event length="));
Serial.println(bytesRead);
if(strncmp(receivedMessage,closeMessage,5)==0){
Serial.println(F("EtherEvent.availableEvent: close received, no event"));
break;
}
strncpy(receivedEvent,receivedMessage,etherEvent_eventLengthMax);
receivedEvent[bytesRead]=0;
Serial.print(F("EtherEvent.availableEvent: event received="));
Serial.println(receivedEvent);
#ifdef SENDERIP_ENABLE
byte tempIP[4];
ethernetClient.getRemoteIP(tempIP); //Save the IP address of the sender. Requires modified ethernet library
fromIP=tempIP;
#endif
break; //exit the payload/event message handler loop
}
}
}
else{
free(cookiePasswordMD5);
Serial.println(F("EtherEvent.availableEvent: authentication failed"));
}
}
etherEventStop(ethernetClient);
if(byte length=strlen(receivedEvent)){ //there is an event
return length+1;
}
}
return 0; //no event
}
byte EtherEventClass::availablePayload(){ //returns the number of chars in the payload including the null terminator if there is one
if(byte length=strlen(receivedPayload)){ //strlen(receivedPayload)>0
return length+1; //length of the payload + null terminator
}
return 0;
}
void EtherEventClass::readEvent(char eventBuffer[]){
strcpy(eventBuffer,receivedEvent);
eventBuffer[strlen(receivedEvent)]=0; //null terminator - is this needed?
receivedEvent[0]=0; //reset the event buffer
}
void EtherEventClass::readPayload(char payloadBuffer[]){
strcpy(payloadBuffer,receivedPayload);
payloadBuffer[strlen(receivedPayload)]=0; //null terminator - is this needed?
receivedPayload[0]=0; //reset the payload buffer
}
void EtherEventClass::flushReceiver(){ //dump the last message received so another one can be received
Serial.println(F("EtherEvent.flushReceiver: start"));
receivedEvent[0]=0; //reset the event buffer
receivedPayload[0]=0; //reset the payload buffer
}
IPAddress EtherEventClass::senderIP(){ //returns the ip address the current event was sent from. Requires modified ethernet library, thus the preprocesser direcive system
return fromIP;
}
boolean EtherEventClass::send(EthernetClient ðernetClient, const IPAddress sendIP, unsigned int sendPort, const char sendEvent[], const char sendPayload[]){
Serial.println(F("EtherEvent.sendEvent: attempting connection---------------"));
ethernetClient.setTimeout(timeout); //timeout on read/readUntil/find/findUntil/etc
byte sendEventSuccess=0;
if(ethernetClient.connect(sendIP,sendPort)){ //connected to receiver
Serial.println(F("EtherEvent.sendEvent: connected, sending magic word"));
ethernetClient.print(MAGIC_WORD); //send the magic word to the receiver so it will send the cookie
char receivedMessage[cookieLengthMax+1];
byte bytesRead;
if(bytesRead=ethernetClient.readBytesUntil(10,receivedMessage,cookieLengthMax)){
receivedMessage[bytesRead]=0;
char cookiePassword[bytesRead+1+strlen(EEpassword)+1]; //cookie, password separator(:), password, null terminator
strcpy(cookiePassword,receivedMessage);
strcat(cookiePassword,":"); //add the password separator to the cookie
strcat(cookiePassword,EEpassword); //add password to the cookie
Serial.print(F("EtherEvent.sendEvent: cookiePassword="));
Serial.println(cookiePassword);
unsigned char* cookiePasswordHash=MD5::make_hash(cookiePassword);
char *cookiePasswordMD5 = MD5::make_digest(cookiePasswordHash, 16);
free(cookiePasswordHash);
Serial.print(F("EtherEvent.sendEvent: hashWordMD5="));
Serial.println(cookiePasswordMD5);
cookiePasswordMD5[32]=10; //add /n - it fails the authentication with eg without this
cookiePasswordMD5[33]=0; //add the null terminator(otherwise it will keep printing garbage after the end of the string and the /n
ethernetClient.print(cookiePasswordMD5); //send the MD5 of the hashword
free(cookiePasswordMD5);
if(ethernetClient.find(ACCEPT_MESSAGE)==1){
Serial.print(F("EtherEvent.sendEvent: Payload="));
Serial.println(sendPayload);
Serial.print(F("EtherEvent.sendEvent: event="));
Serial.println(sendEvent);
if(sendPayload[0]!=0){ //check if there is a payload
ethernetClient.print(payloadSeparator);
ethernetClient.print(sendPayload);
ethernetClient.write(10);
}
ethernetClient.print(sendEvent);
ethernetClient.write(10);
sendEventSuccess=1;
}
}
etherEventStop(ethernetClient); //close the connection
}
else{
Serial.println(F("EtherEvent.sendEvent connection failed"));
}
return sendEventSuccess; //send finished
}
void EtherEventClass::setTimeout(unsigned int timeoutNew, unsigned int timeoutListenNew){
timeout=timeoutNew;
listenTimeout=timeoutListenNew;
}
void EtherEventClass::etherEventStop(EthernetClient ðernetClient){
Serial.println(F("EtherEvent.etherEventStop: stopping..."));
ethernetClient.print(closeMessage); //tell the receiver to close
ethernetClient.stop();
Serial.println(F("EtherEvent.etherEventStop: stopped"));
}
EtherEventClass EtherEvent; //This sets up a single global instance of the library so the class doesn't need to be declared in the user sketch and multiple instances are not necessary in this case.
<|endoftext|> |
<commit_before>
#include <adios2/common/ADIOSMPI.h>
#include <memory>
#include "SstParamParser.h"
#include "adios2/helper/adiosFunctions.h"
#include "adios2/toolkit/sst/sst.h"
using namespace adios2::core;
void SstParamParser::ParseParams(IO &io, struct _SstParams &Params)
{
auto lf_SetBoolParameter = [&](const std::string key, int ¶meter) {
auto itKey = io.m_Parameters.find(key);
if (itKey != io.m_Parameters.end())
{
if (itKey->second == "yes" || itKey->second == "true")
{
parameter = 1;
}
else if (itKey->second == "no" || itKey->second == "false")
{
parameter = 0;
}
}
};
auto lf_SetIntParameter = [&](const std::string key, int ¶meter) {
auto itKey = io.m_Parameters.find(key);
if (itKey != io.m_Parameters.end())
{
parameter = std::stoi(itKey->second);
return true;
}
return false;
};
auto lf_SetStringParameter = [&](const std::string key, char *¶meter) {
auto itKey = io.m_Parameters.find(key);
if (itKey != io.m_Parameters.end())
{
parameter = strdup(itKey->second.c_str());
return true;
}
return false;
};
auto lf_SetRegMethodParameter = [&](const std::string key,
size_t ¶meter) {
auto itKey = io.m_Parameters.find(key);
if (itKey != io.m_Parameters.end())
{
std::string method = itKey->second;
std::transform(method.begin(), method.end(), method.begin(),
::tolower);
if (method == "file")
{
parameter = SstRegisterFile;
}
else if (method == "screen")
{
parameter = SstRegisterScreen;
}
else if (method == "cloud")
{
parameter = SstRegisterCloud;
throw std::invalid_argument("ERROR: Sst RegistrationMethod "
"\"cloud\" not yet implemented");
}
else
{
throw std::invalid_argument(
"ERROR: Unknown Sst RegistrationMethod parameter \"" +
method + "\"");
}
return true;
}
return false;
};
auto lf_SetCompressionMethodParameter = [&](const std::string key,
size_t ¶meter) {
auto itKey = io.m_Parameters.find(key);
if (itKey != io.m_Parameters.end())
{
std::string method = itKey->second;
std::transform(method.begin(), method.end(), method.begin(),
::tolower);
if (method == "zfp")
{
parameter = SstCompressZFP;
}
else if (method == "none")
{
parameter = SstCompressNone;
}
else
{
throw std::invalid_argument(
"ERROR: Unknown Sst CompressionMethod parameter \"" +
method + "\"");
}
return true;
}
return false;
};
// not really a parameter, but a convenient way to pass this around
auto lf_SetIsRowMajorParameter = [&](const std::string key,
int ¶meter) {
parameter = adios2::helper::IsRowMajor(io.m_HostLanguage);
return true;
};
auto lf_SetMarshalMethodParameter = [&](const std::string key,
size_t ¶meter) {
auto itKey = io.m_Parameters.find(key);
if (itKey != io.m_Parameters.end())
{
std::string method = itKey->second;
std::transform(method.begin(), method.end(), method.begin(),
::tolower);
if (method == "ffs")
{
parameter = SstMarshalFFS;
}
else if (method == "bp")
{
parameter = SstMarshalBP;
}
else
{
throw std::invalid_argument(
"ERROR: Unknown Sst MarshalMethod parameter \"" + method +
"\"");
}
return true;
}
return false;
};
auto lf_SetCPCommPatternParameter = [&](const std::string key,
size_t ¶meter) {
auto itKey = io.m_Parameters.find(key);
if (itKey != io.m_Parameters.end())
{
std::string method = itKey->second;
std::transform(method.begin(), method.end(), method.begin(),
::tolower);
if (method == "min")
{
parameter = SstCPCommMin;
}
else if (method == "peer")
{
parameter = SstCPCommPeer;
}
else
{
throw std::invalid_argument(
"ERROR: Unknown Sst MarshalMethod parameter \"" + method +
"\"");
}
return true;
}
return false;
};
auto lf_SetQueueFullPolicyParameter = [&](const std::string key,
size_t ¶meter) {
auto itKey = io.m_Parameters.find(key);
if (itKey != io.m_Parameters.end())
{
std::string method = itKey->second;
std::transform(method.begin(), method.end(), method.begin(),
::tolower);
if (method == "block")
{
parameter = SstQueueFullBlock;
}
else if (method == "discard")
{
parameter = SstQueueFullDiscard;
}
else
{
throw std::invalid_argument(
"ERROR: Unknown Sst MarshalMethod parameter \"" + method +
"\"");
}
return true;
}
return false;
};
#define get_params(Param, Type, Typedecl, Default) \
Params.Param = Default; \
lf_Set##Type##Parameter(#Param, Params.Param);
SST_FOREACH_PARAMETER_TYPE_4ARGS(get_params);
#undef get_params
}
<commit_msg>Fix incorrect error message in SST<commit_after>
#include <adios2/common/ADIOSMPI.h>
#include <memory>
#include "SstParamParser.h"
#include "adios2/helper/adiosFunctions.h"
#include "adios2/toolkit/sst/sst.h"
using namespace adios2::core;
void SstParamParser::ParseParams(IO &io, struct _SstParams &Params)
{
auto lf_SetBoolParameter = [&](const std::string key, int ¶meter) {
auto itKey = io.m_Parameters.find(key);
if (itKey != io.m_Parameters.end())
{
if (itKey->second == "yes" || itKey->second == "true")
{
parameter = 1;
}
else if (itKey->second == "no" || itKey->second == "false")
{
parameter = 0;
}
}
};
auto lf_SetIntParameter = [&](const std::string key, int ¶meter) {
auto itKey = io.m_Parameters.find(key);
if (itKey != io.m_Parameters.end())
{
parameter = std::stoi(itKey->second);
return true;
}
return false;
};
auto lf_SetStringParameter = [&](const std::string key, char *¶meter) {
auto itKey = io.m_Parameters.find(key);
if (itKey != io.m_Parameters.end())
{
parameter = strdup(itKey->second.c_str());
return true;
}
return false;
};
auto lf_SetRegMethodParameter = [&](const std::string key,
size_t ¶meter) {
auto itKey = io.m_Parameters.find(key);
if (itKey != io.m_Parameters.end())
{
std::string method = itKey->second;
std::transform(method.begin(), method.end(), method.begin(),
::tolower);
if (method == "file")
{
parameter = SstRegisterFile;
}
else if (method == "screen")
{
parameter = SstRegisterScreen;
}
else if (method == "cloud")
{
parameter = SstRegisterCloud;
throw std::invalid_argument("ERROR: Sst RegistrationMethod "
"\"cloud\" not yet implemented");
}
else
{
throw std::invalid_argument(
"ERROR: Unknown Sst RegistrationMethod parameter \"" +
method + "\"");
}
return true;
}
return false;
};
auto lf_SetCompressionMethodParameter = [&](const std::string key,
size_t ¶meter) {
auto itKey = io.m_Parameters.find(key);
if (itKey != io.m_Parameters.end())
{
std::string method = itKey->second;
std::transform(method.begin(), method.end(), method.begin(),
::tolower);
if (method == "zfp")
{
parameter = SstCompressZFP;
}
else if (method == "none")
{
parameter = SstCompressNone;
}
else
{
throw std::invalid_argument(
"ERROR: Unknown Sst CompressionMethod parameter \"" +
method + "\"");
}
return true;
}
return false;
};
// not really a parameter, but a convenient way to pass this around
auto lf_SetIsRowMajorParameter = [&](const std::string key,
int ¶meter) {
parameter = adios2::helper::IsRowMajor(io.m_HostLanguage);
return true;
};
auto lf_SetMarshalMethodParameter = [&](const std::string key,
size_t ¶meter) {
auto itKey = io.m_Parameters.find(key);
if (itKey != io.m_Parameters.end())
{
std::string method = itKey->second;
std::transform(method.begin(), method.end(), method.begin(),
::tolower);
if (method == "ffs")
{
parameter = SstMarshalFFS;
}
else if (method == "bp")
{
parameter = SstMarshalBP;
}
else
{
throw std::invalid_argument(
"ERROR: Unknown Sst MarshalMethod parameter \"" + method +
"\"");
}
return true;
}
return false;
};
auto lf_SetCPCommPatternParameter = [&](const std::string key,
size_t ¶meter) {
auto itKey = io.m_Parameters.find(key);
if (itKey != io.m_Parameters.end())
{
std::string method = itKey->second;
std::transform(method.begin(), method.end(), method.begin(),
::tolower);
if (method == "min")
{
parameter = SstCPCommMin;
}
else if (method == "peer")
{
parameter = SstCPCommPeer;
}
else
{
throw std::invalid_argument(
"ERROR: Unknown Sst CPCommPattern parameter \"" + method +
"\"");
}
return true;
}
return false;
};
auto lf_SetQueueFullPolicyParameter = [&](const std::string key,
size_t ¶meter) {
auto itKey = io.m_Parameters.find(key);
if (itKey != io.m_Parameters.end())
{
std::string method = itKey->second;
std::transform(method.begin(), method.end(), method.begin(),
::tolower);
if (method == "block")
{
parameter = SstQueueFullBlock;
}
else if (method == "discard")
{
parameter = SstQueueFullDiscard;
}
else
{
throw std::invalid_argument(
"ERROR: Unknown Sst QueueFullPolicy parameter \"" + method +
"\"");
}
return true;
}
return false;
};
#define get_params(Param, Type, Typedecl, Default) \
Params.Param = Default; \
lf_Set##Type##Parameter(#Param, Params.Param);
SST_FOREACH_PARAMETER_TYPE_4ARGS(get_params);
#undef get_params
}
<|endoftext|> |
<commit_before>/**
* \file
* \brief SerialPort class implementation
*
* \author Copyright (C) 2016 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/devices/communication/SerialPort.hpp"
#include "distortos/internal/devices/UartLowLevel.hpp"
#include "distortos/architecture/InterruptMaskingLock.hpp"
#include "distortos/Semaphore.hpp"
#include "estd/ScopeGuard.hpp"
#include <cstring>
namespace distortos
{
namespace devices
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Reads data from ring buffer.
*
* \param [in] ringBuffer is a reference to ring buffer from which the data will be read
* \param [out] buffer is a buffer to which the data will be written
* \param [in] size is the size of \a buffer, bytes
*
* \return number of bytes read from \a ringBuffer and written to \a buffer
*/
size_t readFromRingBuffer(SerialPort::RingBuffer& ringBuffer, uint8_t* const buffer, const size_t size)
{
decltype(ringBuffer.getReadBlock()) readBlock;
size_t bytesRead {};
while (readBlock = ringBuffer.getReadBlock(), readBlock.second != 0 && bytesRead != size)
{
const auto copySize = std::min(readBlock.second, size - bytesRead);
memcpy(buffer + bytesRead, readBlock.first, copySize);
ringBuffer.increaseReadPosition(copySize);
bytesRead += copySize;
}
return bytesRead;
}
/**
* \brief Writes data to ring buffer.
*
* \param [in] buffer is a buffer from which the data will be read
* \param [in] size is the size of \a buffer, bytes
* \param [in] ringBuffer is a reference to ring buffer to which the data will be written
*
* \return number of bytes read from \a buffer and written to \a ringBuffer
*/
size_t writeToRingBuffer(const uint8_t* const buffer, const size_t size, SerialPort::RingBuffer& ringBuffer)
{
decltype(ringBuffer.getWriteBlock()) writeBlock;
size_t bytesWritten {};
while (writeBlock = ringBuffer.getWriteBlock(), writeBlock.second != 0 && bytesWritten != size)
{
const auto copySize = std::min(writeBlock.second, size - bytesWritten);
memcpy(writeBlock.first, buffer + bytesWritten, copySize);
ringBuffer.increaseWritePosition(copySize);
bytesWritten += copySize;
}
return bytesWritten;
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| SerialPort::RingBuffer public functions
+---------------------------------------------------------------------------------------------------------------------*/
std::pair<const uint8_t*, size_t> SerialPort::RingBuffer::getReadBlock() const
{
const auto readPosition = readPosition_;
const auto writePosition = writePosition_;
return {buffer_ + readPosition, (writePosition >= readPosition ? writePosition : size_) - readPosition};
}
std::pair<uint8_t*, size_t> SerialPort::RingBuffer::getWriteBlock() const
{
const auto readPosition = readPosition_;
const auto writePosition = writePosition_;
const auto freeBytes = (readPosition > writePosition ? readPosition - writePosition :
size_ - writePosition + readPosition) - 2;
const auto writeBlockSize = (readPosition > writePosition ? readPosition : size_) - writePosition;
return {buffer_ + writePosition, std::min(freeBytes, writeBlockSize)};
}
/*---------------------------------------------------------------------------------------------------------------------+
| public functions
+---------------------------------------------------------------------------------------------------------------------*/
SerialPort::~SerialPort()
{
if (openCount_ == 0)
return;
readMutex_.lock();
writeMutex_.lock();
const auto readWriteMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
writeMutex_.unlock();
readMutex_.unlock();
});
uart_.stopRead();
uart_.stopWrite();
uart_.stop();
}
int SerialPort::close()
{
readMutex_.lock();
writeMutex_.lock();
const auto readWriteMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
writeMutex_.unlock();
readMutex_.unlock();
});
if (openCount_ == 0) // device is not open anymore?
return EBADF;
if (openCount_ == 1) // last close?
{
while (transmitInProgress_ == true) // wait for physical end of write operation
{
Semaphore semaphore {0};
transmitSemaphore_ = &semaphore;
const auto transmitSemaphoreScopeGuard = estd::makeScopeGuard(
[this]()
{
transmitSemaphore_ = {};
});
if (transmitInProgress_ == true)
{
const auto ret = semaphore.wait();
if (ret != 0)
return ret;
}
}
uart_.stopRead();
const auto ret = uart_.stop();
if (ret != 0)
return ret;
readBuffer_.clear();
writeBuffer_.clear();
}
--openCount_;
return 0;
}
int SerialPort::open(const uint32_t baudRate, const uint8_t characterLength, const devices::UartParity parity,
const bool _2StopBits)
{
readMutex_.lock();
writeMutex_.lock();
const auto readWriteMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
writeMutex_.unlock();
readMutex_.unlock();
});
if (openCount_ == std::numeric_limits<decltype(openCount_)>::max()) // device is already opened too many times?
return EMFILE;
if (openCount_ == 0) // first open?
{
if (readBuffer_.getSize() < 4 || writeBuffer_.getSize() < 4)
return ENOBUFS;
{
const auto ret = uart_.start(*this, baudRate, characterLength, parity, _2StopBits);
if (ret.first != 0)
return ret.first;
}
{
const auto ret = startReadWrapper(SIZE_MAX);
if (ret != 0)
return ret;
}
baudRate_ = baudRate;
characterLength_ = characterLength;
parity_ = parity;
_2StopBits_ = _2StopBits;
}
else // if (openCount_ != 0)
{
// provided arguments don't match current configuration of already opened device?
if (baudRate_ != baudRate || characterLength_ != characterLength || parity_ != parity ||
_2StopBits_ != _2StopBits)
return EINVAL;
}
++openCount_;
return 0;
}
std::pair<int, size_t> SerialPort::read(void* const buffer, const size_t size)
{
if (buffer == nullptr || size == 0)
return {EINVAL, {}};
readMutex_.lock();
const auto readMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
readMutex_.unlock();
});
if (openCount_ == 0)
return {EBADF, {}};
if (characterLength_ > 8 && size % 2 != 0)
return {EINVAL, {}};
const size_t minSize = characterLength_ <= 8 ? 1 : 2;
const auto bufferUint8 = static_cast<uint8_t*>(buffer);
size_t bytesRead {};
while (bytesRead < minSize)
{
bytesRead += readFromRingBuffer(readBuffer_, bufferUint8 + bytesRead, size - bytesRead);
if (bytesRead == size) // buffer already full?
return {{}, bytesRead};
Semaphore semaphore {0};
readSemaphore_ = &semaphore;
const auto readSemaphoreScopeGuard = estd::makeScopeGuard(
[this]()
{
readSemaphore_ = {};
});
{
// stop and restart the read operation to get the characters that were already received;
architecture::InterruptMaskingLock interruptMaskingLock;
const auto bytesReceived = uart_.stopRead();
readBuffer_.increaseWritePosition(bytesReceived);
// limit of new read operation is selected to have a notification when requested minimum will be received
const auto ret = startReadWrapper(minSize > bytesRead + bytesReceived ?
minSize - bytesRead - bytesReceived : SIZE_MAX);
if (ret != 0)
return {ret, bytesRead};
}
bytesRead += readFromRingBuffer(readBuffer_, bufferUint8 + bytesRead, size - bytesRead);
if (bytesRead < minSize) // wait for data only if requested minimum is not already read
{
const auto ret = semaphore.wait();
if (ret != 0)
return {ret, bytesRead};
}
}
return {{}, bytesRead};
}
std::pair<int, size_t> SerialPort::write(const void* const buffer, const size_t size)
{
if (buffer == nullptr || size == 0)
return {EINVAL, {}};
writeMutex_.lock();
const auto writeMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
writeMutex_.unlock();
});
if (openCount_ == 0)
return {EBADF, {}};
if (characterLength_ > 8 && size % 2 != 0)
return {EINVAL, {}};
const auto bufferUint8 = static_cast<const uint8_t*>(buffer);
size_t bytesWritten {};
while (bytesWritten < size)
{
Semaphore semaphore {0};
writeSemaphore_ = &semaphore;
const auto writeSemaphoreScopeGuard = estd::makeScopeGuard(
[this]()
{
writeSemaphore_ = {};
});
bytesWritten += writeToRingBuffer(bufferUint8 + bytesWritten, size - bytesWritten, writeBuffer_);
// restart write operation if it is not currently in progress and the write buffer is not already empty
if (writeInProgress_ == false && writeBuffer_.isEmpty() == false)
{
const auto ret = startWriteWrapper();
if (ret != 0)
return {ret, bytesWritten};
}
// wait for free space only if write operation is in progress and there is still some data left to write
else if (bytesWritten != size)
{
const auto ret = semaphore.wait();
if (ret != 0)
return {ret, bytesWritten};
}
}
return {{}, bytesWritten};
}
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
void SerialPort::readCompleteEvent(const size_t bytesRead)
{
readBuffer_.increaseWritePosition(bytesRead);
if (readSemaphore_ != nullptr)
{
readSemaphore_->post();
readSemaphore_ = {};
}
if (readBuffer_.isFull() == true)
return;
startReadWrapper(SIZE_MAX);
}
void SerialPort::receiveErrorEvent(ErrorSet)
{
}
int SerialPort::startReadWrapper(const size_t limit)
{
const auto writeBlock = readBuffer_.getWriteBlock();
return uart_.startRead(writeBlock.first, std::min({writeBlock.second, readBuffer_.getSize() / 2, limit}));
}
int SerialPort::startWriteWrapper()
{
transmitInProgress_ = true;
writeInProgress_ = true;
const auto outBlock = writeBuffer_.getReadBlock();
return uart_.startWrite(outBlock.first, outBlock.second);
}
void SerialPort::transmitCompleteEvent()
{
if (transmitSemaphore_ != nullptr)
{
transmitSemaphore_->post();
transmitSemaphore_ = {};
}
transmitInProgress_ = false;
}
void SerialPort::writeCompleteEvent(const size_t bytesWritten)
{
writeBuffer_.increaseReadPosition(bytesWritten);
if (writeSemaphore_ != nullptr)
{
writeSemaphore_->post();
writeSemaphore_ = {};
}
if (writeBuffer_.isEmpty() == true)
{
writeInProgress_ = false;
return;
}
startWriteWrapper();
}
} // namespace devices
} // namespace distortos
<commit_msg>Fix compilation of SerialPort.cpp in GCC 4.9 with older newlib<commit_after>/**
* \file
* \brief SerialPort class implementation
*
* \author Copyright (C) 2016 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/devices/communication/SerialPort.hpp"
#include "distortos/internal/devices/UartLowLevel.hpp"
#include "distortos/architecture/InterruptMaskingLock.hpp"
#include "distortos/Semaphore.hpp"
#include "estd/ScopeGuard.hpp"
#include <cerrno>
#include <cstring>
namespace distortos
{
namespace devices
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Reads data from ring buffer.
*
* \param [in] ringBuffer is a reference to ring buffer from which the data will be read
* \param [out] buffer is a buffer to which the data will be written
* \param [in] size is the size of \a buffer, bytes
*
* \return number of bytes read from \a ringBuffer and written to \a buffer
*/
size_t readFromRingBuffer(SerialPort::RingBuffer& ringBuffer, uint8_t* const buffer, const size_t size)
{
decltype(ringBuffer.getReadBlock()) readBlock;
size_t bytesRead {};
while (readBlock = ringBuffer.getReadBlock(), readBlock.second != 0 && bytesRead != size)
{
const auto copySize = std::min(readBlock.second, size - bytesRead);
memcpy(buffer + bytesRead, readBlock.first, copySize);
ringBuffer.increaseReadPosition(copySize);
bytesRead += copySize;
}
return bytesRead;
}
/**
* \brief Writes data to ring buffer.
*
* \param [in] buffer is a buffer from which the data will be read
* \param [in] size is the size of \a buffer, bytes
* \param [in] ringBuffer is a reference to ring buffer to which the data will be written
*
* \return number of bytes read from \a buffer and written to \a ringBuffer
*/
size_t writeToRingBuffer(const uint8_t* const buffer, const size_t size, SerialPort::RingBuffer& ringBuffer)
{
decltype(ringBuffer.getWriteBlock()) writeBlock;
size_t bytesWritten {};
while (writeBlock = ringBuffer.getWriteBlock(), writeBlock.second != 0 && bytesWritten != size)
{
const auto copySize = std::min(writeBlock.second, size - bytesWritten);
memcpy(writeBlock.first, buffer + bytesWritten, copySize);
ringBuffer.increaseWritePosition(copySize);
bytesWritten += copySize;
}
return bytesWritten;
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| SerialPort::RingBuffer public functions
+---------------------------------------------------------------------------------------------------------------------*/
std::pair<const uint8_t*, size_t> SerialPort::RingBuffer::getReadBlock() const
{
const auto readPosition = readPosition_;
const auto writePosition = writePosition_;
return {buffer_ + readPosition, (writePosition >= readPosition ? writePosition : size_) - readPosition};
}
std::pair<uint8_t*, size_t> SerialPort::RingBuffer::getWriteBlock() const
{
const auto readPosition = readPosition_;
const auto writePosition = writePosition_;
const auto freeBytes = (readPosition > writePosition ? readPosition - writePosition :
size_ - writePosition + readPosition) - 2;
const auto writeBlockSize = (readPosition > writePosition ? readPosition : size_) - writePosition;
return {buffer_ + writePosition, std::min(freeBytes, writeBlockSize)};
}
/*---------------------------------------------------------------------------------------------------------------------+
| public functions
+---------------------------------------------------------------------------------------------------------------------*/
SerialPort::~SerialPort()
{
if (openCount_ == 0)
return;
readMutex_.lock();
writeMutex_.lock();
const auto readWriteMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
writeMutex_.unlock();
readMutex_.unlock();
});
uart_.stopRead();
uart_.stopWrite();
uart_.stop();
}
int SerialPort::close()
{
readMutex_.lock();
writeMutex_.lock();
const auto readWriteMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
writeMutex_.unlock();
readMutex_.unlock();
});
if (openCount_ == 0) // device is not open anymore?
return EBADF;
if (openCount_ == 1) // last close?
{
while (transmitInProgress_ == true) // wait for physical end of write operation
{
Semaphore semaphore {0};
transmitSemaphore_ = &semaphore;
const auto transmitSemaphoreScopeGuard = estd::makeScopeGuard(
[this]()
{
transmitSemaphore_ = {};
});
if (transmitInProgress_ == true)
{
const auto ret = semaphore.wait();
if (ret != 0)
return ret;
}
}
uart_.stopRead();
const auto ret = uart_.stop();
if (ret != 0)
return ret;
readBuffer_.clear();
writeBuffer_.clear();
}
--openCount_;
return 0;
}
int SerialPort::open(const uint32_t baudRate, const uint8_t characterLength, const devices::UartParity parity,
const bool _2StopBits)
{
readMutex_.lock();
writeMutex_.lock();
const auto readWriteMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
writeMutex_.unlock();
readMutex_.unlock();
});
if (openCount_ == std::numeric_limits<decltype(openCount_)>::max()) // device is already opened too many times?
return EMFILE;
if (openCount_ == 0) // first open?
{
if (readBuffer_.getSize() < 4 || writeBuffer_.getSize() < 4)
return ENOBUFS;
{
const auto ret = uart_.start(*this, baudRate, characterLength, parity, _2StopBits);
if (ret.first != 0)
return ret.first;
}
{
const auto ret = startReadWrapper(SIZE_MAX);
if (ret != 0)
return ret;
}
baudRate_ = baudRate;
characterLength_ = characterLength;
parity_ = parity;
_2StopBits_ = _2StopBits;
}
else // if (openCount_ != 0)
{
// provided arguments don't match current configuration of already opened device?
if (baudRate_ != baudRate || characterLength_ != characterLength || parity_ != parity ||
_2StopBits_ != _2StopBits)
return EINVAL;
}
++openCount_;
return 0;
}
std::pair<int, size_t> SerialPort::read(void* const buffer, const size_t size)
{
if (buffer == nullptr || size == 0)
return {EINVAL, {}};
readMutex_.lock();
const auto readMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
readMutex_.unlock();
});
if (openCount_ == 0)
return {EBADF, {}};
if (characterLength_ > 8 && size % 2 != 0)
return {EINVAL, {}};
const size_t minSize = characterLength_ <= 8 ? 1 : 2;
const auto bufferUint8 = static_cast<uint8_t*>(buffer);
size_t bytesRead {};
while (bytesRead < minSize)
{
bytesRead += readFromRingBuffer(readBuffer_, bufferUint8 + bytesRead, size - bytesRead);
if (bytesRead == size) // buffer already full?
return {{}, bytesRead};
Semaphore semaphore {0};
readSemaphore_ = &semaphore;
const auto readSemaphoreScopeGuard = estd::makeScopeGuard(
[this]()
{
readSemaphore_ = {};
});
{
// stop and restart the read operation to get the characters that were already received;
architecture::InterruptMaskingLock interruptMaskingLock;
const auto bytesReceived = uart_.stopRead();
readBuffer_.increaseWritePosition(bytesReceived);
// limit of new read operation is selected to have a notification when requested minimum will be received
const auto ret = startReadWrapper(minSize > bytesRead + bytesReceived ?
minSize - bytesRead - bytesReceived : SIZE_MAX);
if (ret != 0)
return {ret, bytesRead};
}
bytesRead += readFromRingBuffer(readBuffer_, bufferUint8 + bytesRead, size - bytesRead);
if (bytesRead < minSize) // wait for data only if requested minimum is not already read
{
const auto ret = semaphore.wait();
if (ret != 0)
return {ret, bytesRead};
}
}
return {{}, bytesRead};
}
std::pair<int, size_t> SerialPort::write(const void* const buffer, const size_t size)
{
if (buffer == nullptr || size == 0)
return {EINVAL, {}};
writeMutex_.lock();
const auto writeMutexScopeGuard = estd::makeScopeGuard(
[this]()
{
writeMutex_.unlock();
});
if (openCount_ == 0)
return {EBADF, {}};
if (characterLength_ > 8 && size % 2 != 0)
return {EINVAL, {}};
const auto bufferUint8 = static_cast<const uint8_t*>(buffer);
size_t bytesWritten {};
while (bytesWritten < size)
{
Semaphore semaphore {0};
writeSemaphore_ = &semaphore;
const auto writeSemaphoreScopeGuard = estd::makeScopeGuard(
[this]()
{
writeSemaphore_ = {};
});
bytesWritten += writeToRingBuffer(bufferUint8 + bytesWritten, size - bytesWritten, writeBuffer_);
// restart write operation if it is not currently in progress and the write buffer is not already empty
if (writeInProgress_ == false && writeBuffer_.isEmpty() == false)
{
const auto ret = startWriteWrapper();
if (ret != 0)
return {ret, bytesWritten};
}
// wait for free space only if write operation is in progress and there is still some data left to write
else if (bytesWritten != size)
{
const auto ret = semaphore.wait();
if (ret != 0)
return {ret, bytesWritten};
}
}
return {{}, bytesWritten};
}
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
void SerialPort::readCompleteEvent(const size_t bytesRead)
{
readBuffer_.increaseWritePosition(bytesRead);
if (readSemaphore_ != nullptr)
{
readSemaphore_->post();
readSemaphore_ = {};
}
if (readBuffer_.isFull() == true)
return;
startReadWrapper(SIZE_MAX);
}
void SerialPort::receiveErrorEvent(ErrorSet)
{
}
int SerialPort::startReadWrapper(const size_t limit)
{
const auto writeBlock = readBuffer_.getWriteBlock();
return uart_.startRead(writeBlock.first, std::min({writeBlock.second, readBuffer_.getSize() / 2, limit}));
}
int SerialPort::startWriteWrapper()
{
transmitInProgress_ = true;
writeInProgress_ = true;
const auto outBlock = writeBuffer_.getReadBlock();
return uart_.startWrite(outBlock.first, outBlock.second);
}
void SerialPort::transmitCompleteEvent()
{
if (transmitSemaphore_ != nullptr)
{
transmitSemaphore_->post();
transmitSemaphore_ = {};
}
transmitInProgress_ = false;
}
void SerialPort::writeCompleteEvent(const size_t bytesWritten)
{
writeBuffer_.increaseReadPosition(bytesWritten);
if (writeSemaphore_ != nullptr)
{
writeSemaphore_->post();
writeSemaphore_ = {};
}
if (writeBuffer_.isEmpty() == true)
{
writeInProgress_ = false;
return;
}
startWriteWrapper();
}
} // namespace devices
} // namespace distortos
<|endoftext|> |
<commit_before>#include <boost/test/minimal.hpp>
#include <trance/local_function.hpp>
int
test_main( int, char *[] )
{
TRANCE_LOCAL_FUNCTION( int, inc, ( int _n ),
{
return _n + 1;
} );
BOOST_REQUIRE( 1 == inc( 0 ) );
TRANCE_LOCAL_FUNCTION( int, dec, ( int _n ),
{
return _n - 1;
} );
BOOST_REQUIRE( 0 == dec( 1 ) );
}
<commit_msg>Prevent warnings in test.<commit_after>#include <boost/test/minimal.hpp>
#include <trance/local_function.hpp>
int
test_main( int, char *[] )
{
TRANCE_LOCAL_FUNCTION( int, inc, ( int _n ),
{
return _n + 1;
} );
BOOST_REQUIRE( 1 == inc( 0 ) );
TRANCE_LOCAL_FUNCTION( int, dec, ( int _n ),
{
return _n - 1;
} );
BOOST_REQUIRE( 0 == dec( 1 ) );
return 0;
}
<|endoftext|> |
<commit_before>#include "musicnetworkthread.h"
#include "musicconnectionpool.h"
#include "musicsettingmanager.h"
#include <QHostInfo>
MusicNetworkThread::MusicNetworkThread()
: QObject(nullptr), m_networkState(true)
{
M_CONNECTION_PTR->setValue(getClassName(), this);
connect(&m_timer, SIGNAL(timeout()), SLOT(networkStateChanged()));
}
MusicNetworkThread::~MusicNetworkThread()
{
m_timer.stop();
}
QString MusicNetworkThread::getClassName()
{
return staticMetaObject.className();
}
void MusicNetworkThread::start()
{
M_LOGGER_INFO("Load NetworkThread");
m_timer.start(NETWORK_DETECT_INTERVAL);
}
void MusicNetworkThread::setBlockNetWork(int block)
{
M_SETTING_PTR->setValue(MusicSettingManager::CloseNetWorkChoiced, block);
}
void MusicNetworkThread::networkStateChanged()
{
bool block = M_SETTING_PTR->value(MusicSettingManager::CloseNetWorkChoiced).toBool();
QHostInfo info = QHostInfo::fromName(NETWORK_REQUEST_ADDRESS);
m_networkState = !info.addresses().isEmpty();
m_networkState = block ? false : m_networkState;
emit networkConnectionStateChanged(m_networkState);
}
<commit_msg>#45 oprimzied the current network checking[153032]<commit_after>#include "musicnetworkthread.h"
#include "musicconnectionpool.h"
#include "musicsettingmanager.h"
#include <QHostInfo>
#ifdef MUSIC_GREATER_NEW
# include <QtConcurrent/QtConcurrent>
#else
# include <QtConcurrentRun>
#endif
MusicNetworkThread::MusicNetworkThread()
: QObject(nullptr), m_networkState(true)
{
M_CONNECTION_PTR->setValue(getClassName(), this);
connect(&m_timer, SIGNAL(timeout()), SLOT(networkStateChanged()));
}
MusicNetworkThread::~MusicNetworkThread()
{
m_timer.stop();
}
QString MusicNetworkThread::getClassName()
{
return staticMetaObject.className();
}
void MusicNetworkThread::start()
{
M_LOGGER_INFO("Load NetworkThread");
m_timer.start(NETWORK_DETECT_INTERVAL);
}
void MusicNetworkThread::setBlockNetWork(int block)
{
M_SETTING_PTR->setValue(MusicSettingManager::CloseNetWorkChoiced, block);
}
void MusicNetworkThread::networkStateChanged()
{
QtConcurrent::run([&]
{
bool block = M_SETTING_PTR->value(MusicSettingManager::CloseNetWorkChoiced).toBool();
QHostInfo info = QHostInfo::fromName(NETWORK_REQUEST_ADDRESS);
m_networkState = !info.addresses().isEmpty();
m_networkState = block ? false : m_networkState;
emit networkConnectionStateChanged(m_networkState);
});
}
<|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$ */
//_________________________________________________________________________
// PHOS digit: Id
// energy
// 3 identifiers for the primary particle(s) at the origine of the digit
// The digits are made in FinishEvent() by summing all the hits in a single PHOS crystal or PPSD gas cell
//
//*-- Author: Laurent Aphecetche & Yves Schutz (SUBATECH) & Dmitri Peressounko (RRC KI & SUBATECH)
// --- ROOT system ---
// --- Standard library ---
// --- AliRoot header files ---
#include "AliPHOSDigit.h"
ClassImp(AliPHOSDigit)
//____________________________________________________________________________
AliPHOSDigit::AliPHOSDigit()
{
// default ctor
fIndexInList = -1 ;
fNprimary = 0 ;
fNMaxPrimary = 5 ;
}
//____________________________________________________________________________
AliPHOSDigit::AliPHOSDigit(Int_t primary, Int_t id, Int_t digEnergy, Float_t time, Int_t index)
{
// ctor with all data
fNMaxPrimary = 5 ;
fAmp = digEnergy ;
fTime = time ;
fId = id ;
fIndexInList = index ;
if( primary != -1){
fNprimary = 1 ;
fPrimary[0] = primary ;
}
else{ //If the contribution of this primary smaller than fDigitThreshold (AliPHOSv1)
fNprimary = 0 ;
fPrimary[0] = -1 ;
}
Int_t i ;
for ( i = 1; i < fNMaxPrimary ; i++)
fPrimary[i] = -1 ;
}
//____________________________________________________________________________
AliPHOSDigit::AliPHOSDigit(const AliPHOSDigit & digit)
{
// copy ctor
fNMaxPrimary = digit.fNMaxPrimary ;
Int_t i ;
for ( i = 0; i < fNMaxPrimary ; i++)
fPrimary[i] = digit.fPrimary[i] ;
fAmp = digit.fAmp ;
fTime = digit.fTime ;
fId = digit.fId;
fIndexInList = digit.fIndexInList ;
fNprimary = digit.fNprimary ;
}
//____________________________________________________________________________
AliPHOSDigit::~AliPHOSDigit()
{
// Delete array of primiries if any
}
//____________________________________________________________________________
Int_t AliPHOSDigit::Compare(const TObject * obj) const
{
// Compares two digits with respect to its Id
// to sort according increasing Id
Int_t rv ;
AliPHOSDigit * digit = (AliPHOSDigit *)obj ;
Int_t iddiff = fId - digit->GetId() ;
if ( iddiff > 0 )
rv = 1 ;
else if ( iddiff < 0 )
rv = -1 ;
else
rv = 0 ;
return rv ;
}
//____________________________________________________________________________
Int_t AliPHOSDigit::GetPrimary(Int_t index) const
{
// retrieves the primary particle number given its index in the list
Int_t rv = -1 ;
if ( index <= fNprimary && index > 0){
rv = fPrimary[index-1] ;
}
return rv ;
}
//____________________________________________________________________________
void AliPHOSDigit::Print(Option_t *option) const
{
printf("PHOS digit: Amp=%d, Id=%d\n",fAmp,fId);
}
//____________________________________________________________________________
void AliPHOSDigit::ShiftPrimary(Int_t shift)
{
//shifts primary number to BIG offset, to separate primary in different TreeK
Int_t index ;
for(index = 0; index <fNprimary; index ++ ){
fPrimary[index] = fPrimary[index]+ shift ;
}
}
//____________________________________________________________________________
Bool_t AliPHOSDigit::operator==(AliPHOSDigit const & digit) const
{
// Two digits are equal if they have the same Id
if ( fId == digit.fId )
return kTRUE ;
else
return kFALSE ;
}
//____________________________________________________________________________
AliPHOSDigit& AliPHOSDigit::operator+(AliPHOSDigit const & digit)
{
// Adds the amplitude of digits and completes the list of primary particles
// if amplitude is larger than
Int_t toAdd = fNprimary ;
if(digit.fNprimary>0){
if(fAmp < digit.fAmp){//most energetic primary in second digit => first primaries in list from second digit
for (Int_t index = 0 ; index < digit.fNprimary ; index++){
for (Int_t old = 0 ; old < fNprimary ; old++) { //already have this primary?
if(fPrimary[old] == (digit.fPrimary)[index]){
fPrimary[old] = -1 ; //removed
toAdd-- ;
break ;
}
}
}
Int_t nNewPrimaries = digit.fNprimary+toAdd ;
if(nNewPrimaries >fNMaxPrimary) //Do not change primary list
Error("Operator +", "Increase NMaxPrimary") ;
else{
for(Int_t index = fNprimary-1 ; index >=0 ; index--){ //move old primaries
if(fPrimary[index]>-1){
fPrimary[fNprimary+toAdd]=fPrimary[index] ;
toAdd-- ;
}
}
//copy new primaries
for(Int_t index = 0; index < digit.fNprimary ; index++){
fPrimary[index] = (digit.fPrimary)[index] ;
}
fNprimary = nNewPrimaries ;
}
}
else{ //add new primaries to the end
for(Int_t index = 0 ; index < digit.fNprimary ; index++){
Bool_t deja = kTRUE ;
for(Int_t old = 0 ; old < fNprimary; old++) { //already have this primary?
if(fPrimary[old] == (digit.fPrimary)[index]){
deja = kFALSE;
break ;
}
}
if(deja){
fPrimary[fNprimary] = (digit.fPrimary)[index] ;
fNprimary++ ;
if(fNprimary>fNMaxPrimary) {
Error("Operator +", "Increase NMaxPrimary") ;
break ;
}
}
}
}
}
fAmp += digit.fAmp ;
if(fTime > digit.fTime)
fTime = digit.fTime ;
return *this ;
}
//____________________________________________________________________________
ostream& operator << ( ostream& out , const AliPHOSDigit & digit)
{
// Prints the data of the digit
// out << "ID " << digit.fId << " Energy = " << digit.fAmp << " Time = " << digit.fTime << endl ;
// Int_t i ;
// for(i=0;i<digit.fNprimary;i++)
// out << "Primary " << i+1 << " = " << digit.fPrimary[i] << endl ;
// out << "Position in list = " << digit.fIndexInList << endl ;
digit.Warning("operator <<", "Implement differently") ;
return out ;
}
<commit_msg>Coping primaries corrected<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$ */
//_________________________________________________________________________
// PHOS digit: Id
// energy
// 3 identifiers for the primary particle(s) at the origine of the digit
// The digits are made in FinishEvent() by summing all the hits in a single PHOS crystal or PPSD gas cell
//
//*-- Author: Laurent Aphecetche & Yves Schutz (SUBATECH) & Dmitri Peressounko (RRC KI & SUBATECH)
// --- ROOT system ---
// --- Standard library ---
// --- AliRoot header files ---
#include "AliPHOSDigit.h"
ClassImp(AliPHOSDigit)
//____________________________________________________________________________
AliPHOSDigit::AliPHOSDigit()
{
// default ctor
fIndexInList = -1 ;
fNprimary = 0 ;
fNMaxPrimary = 5 ;
}
//____________________________________________________________________________
AliPHOSDigit::AliPHOSDigit(Int_t primary, Int_t id, Int_t digEnergy, Float_t time, Int_t index)
{
// ctor with all data
fNMaxPrimary = 5 ;
fAmp = digEnergy ;
fTime = time ;
fId = id ;
fIndexInList = index ;
if( primary != -1){
fNprimary = 1 ;
fPrimary[0] = primary ;
}
else{ //If the contribution of this primary smaller than fDigitThreshold (AliPHOSv1)
fNprimary = 0 ;
fPrimary[0] = -1 ;
}
Int_t i ;
for ( i = 1; i < fNMaxPrimary ; i++)
fPrimary[i] = -1 ;
}
//____________________________________________________________________________
AliPHOSDigit::AliPHOSDigit(const AliPHOSDigit & digit)
{
// copy ctor
fNMaxPrimary = digit.fNMaxPrimary ;
Int_t i ;
for ( i = 0; i < fNMaxPrimary ; i++)
fPrimary[i] = digit.fPrimary[i] ;
fAmp = digit.fAmp ;
fTime = digit.fTime ;
fId = digit.fId;
fIndexInList = digit.fIndexInList ;
fNprimary = digit.fNprimary ;
}
//____________________________________________________________________________
AliPHOSDigit::~AliPHOSDigit()
{
// Delete array of primiries if any
}
//____________________________________________________________________________
Int_t AliPHOSDigit::Compare(const TObject * obj) const
{
// Compares two digits with respect to its Id
// to sort according increasing Id
Int_t rv ;
AliPHOSDigit * digit = (AliPHOSDigit *)obj ;
Int_t iddiff = fId - digit->GetId() ;
if ( iddiff > 0 )
rv = 1 ;
else if ( iddiff < 0 )
rv = -1 ;
else
rv = 0 ;
return rv ;
}
//____________________________________________________________________________
Int_t AliPHOSDigit::GetPrimary(Int_t index) const
{
// retrieves the primary particle number given its index in the list
Int_t rv = -1 ;
if ( index <= fNprimary && index > 0){
rv = fPrimary[index-1] ;
}
return rv ;
}
//____________________________________________________________________________
void AliPHOSDigit::Print(Option_t *option) const
{
printf("PHOS digit: Amp=%d, Id=%d\n",fAmp,fId);
}
//____________________________________________________________________________
void AliPHOSDigit::ShiftPrimary(Int_t shift)
{
//shifts primary number to BIG offset, to separate primary in different TreeK
Int_t index ;
for(index = 0; index <fNprimary; index ++ ){
fPrimary[index] = fPrimary[index]+ shift ;
}
}
//____________________________________________________________________________
Bool_t AliPHOSDigit::operator==(AliPHOSDigit const & digit) const
{
// Two digits are equal if they have the same Id
if ( fId == digit.fId )
return kTRUE ;
else
return kFALSE ;
}
//____________________________________________________________________________
AliPHOSDigit& AliPHOSDigit::operator+(AliPHOSDigit const & digit)
{
// Adds the amplitude of digits and completes the list of primary particles
// if amplitude is larger than
Int_t toAdd = fNprimary ;
if(digit.fNprimary>0){
if(fAmp < digit.fAmp){//most energetic primary in second digit => first primaries in list from second digit
for (Int_t index = 0 ; index < digit.fNprimary ; index++){
for (Int_t old = 0 ; old < fNprimary ; old++) { //already have this primary?
if(fPrimary[old] == (digit.fPrimary)[index]){
fPrimary[old] = -1 ; //removed
toAdd-- ;
break ;
}
}
}
Int_t nNewPrimaries = digit.fNprimary+toAdd ;
if(nNewPrimaries >fNMaxPrimary) //Do not change primary list
Error("Operator +", "Increase NMaxPrimary") ;
else{
for(Int_t index = fNprimary-1 ; index >=0 ; index--){ //move old primaries
if(fPrimary[index]>-1){
toAdd-- ;
fPrimary[fNprimary+toAdd]=fPrimary[index] ;
}
}
//copy new primaries
for(Int_t index = 0; index < digit.fNprimary ; index++){
fPrimary[index] = (digit.fPrimary)[index] ;
}
fNprimary = nNewPrimaries ;
}
}
else{ //add new primaries to the end
for(Int_t index = 0 ; index < digit.fNprimary ; index++){
Bool_t deja = kTRUE ;
for(Int_t old = 0 ; old < fNprimary; old++) { //already have this primary?
if(fPrimary[old] == (digit.fPrimary)[index]){
deja = kFALSE;
break ;
}
}
if(deja){
fPrimary[fNprimary] = (digit.fPrimary)[index] ;
fNprimary++ ;
if(fNprimary>fNMaxPrimary) {
Error("Operator +", "Increase NMaxPrimary") ;
break ;
}
}
}
}
}
fAmp += digit.fAmp ;
if(fTime > digit.fTime)
fTime = digit.fTime ;
return *this ;
}
//____________________________________________________________________________
ostream& operator << ( ostream& out , const AliPHOSDigit & digit)
{
// Prints the data of the digit
// out << "ID " << digit.fId << " Energy = " << digit.fAmp << " Time = " << digit.fTime << endl ;
// Int_t i ;
// for(i=0;i<digit.fNprimary;i++)
// out << "Primary " << i+1 << " = " << digit.fPrimary[i] << endl ;
// out << "Position in list = " << digit.fIndexInList << endl ;
digit.Warning("operator <<", "Implement differently") ;
return out ;
}
<|endoftext|> |
<commit_before>#include "GameScreenState.h"
#include <algorithm>
#include <SFML/Graphics.hpp>
//const int TOP = 1;
//const int BOTTOM = 2;
//const int LEFT = 4;
//const int RIGHT = 8;
const unsigned char TOP = 0;
const unsigned char BOTTOM = 1;
const unsigned char LEFT = 2;
const unsigned char RIGHT = 3;
GameScreenState::GameScreenState() {
pos = sf::Vector2f(300, 100);
velocity = sf::Vector2f(0, 0);
acceleration = sf::Vector2f(0, 0);
for (unsigned char i = 0; i < 4; i++) touching_walls[i] = 0;
level.push_back(rectangle(sf::Vector2f(200, 400), sf::Vector2f(400, 450), 2));
level.push_back(rectangle(sf::Vector2f(400, 260), sf::Vector2f(450, 450), 3));
level.push_back(rectangle(sf::Vector2f(100, 200), sf::Vector2f(200, 450), 1));
updateSprites();
}
void GameScreenState::event(const sf::Event& event) {
}
void GameScreenState::updateSprites() {
sprites.clear();
sprites.resize(level.size() + 1);
static sf::Color colors[4] = {sf::Color::White, sf::Color::Blue, sf::Color::Black, sf::Color::Yellow};
for (unsigned int i = 0; i < level.size(); i++) {
sf::RectangleShape sprite;
//sf::Sprite sprite;
//sf::Texture tex;
sprite.setSize(level[i].maxp - level[i].minp);
sprite.setFillColor(colors[level[i].color]);
//sprite.setTextureRect(sf::IntRect(0, 0,
// (int)(level[i].maxp.x - level[i].minp.x),
// (int)(level[i].maxp.y - level[i].minp.y)));
//tex.create((int)(level[i].maxp.x - level[i].minp.x),
// (int)(level[i].maxp.y - level[i].minp.y));
//sprite.setTexture(tex);
sprite.setPosition(level[i].minp);
sprites.push_back(sprite);
}
sf::RectangleShape sprite;
sprite.setSize(sf::Vector2f(40, 40));
sprite.setFillColor(sf::Color::Red);
sprite.setPosition(pos - sf::Vector2f(20, 20));
sprites.push_back(sprite);
}
void GameScreenState::render(sf::RenderTarget& target) {
updateSprites();
target.clear(sf::Color::White);
for (unsigned int i = 0; i < sprites.size(); i++) {
target.draw(sprites[i]);
}
}
void GameScreenState::update(const sf::Time& time) {
float s = time.asSeconds();
pos += velocity * s;
sf::Vector2f oldv = velocity;
velocity += s * acceleration;
acceleration = sf::Vector2f(0, 80);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
velocity.x = std::min(velocity.x + 200 * s, (float)100);
} else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
velocity.x = std::max(velocity.x - 200 * s, (float)-100);
} else {
//velocity.x = 0;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
if (touching_walls[BOTTOM]) velocity.y = -150;
}
rectangle me_ex = rectangle(pos - sf::Vector2f(20, 19.9), pos + sf::Vector2f(20, 19.9));
rectangle me_ey = rectangle(pos - sf::Vector2f(19.9, 20), pos + sf::Vector2f(19.9, 20));
for (unsigned char i = 0; i < 4; i++) touching_walls[i] = 0;
for (unsigned int i = 0; i < level.size(); i++) {
if (level[i].color < 2) continue; // Not solid
if (level[i].intersects(me_ex)) {
if (me_ey.minp.x >= level[i].minp.x) {
if (me_ey.minp.x >= level[i].maxp.x + oldv.x * s) {
float d = std::max(level[i].maxp.x - me_ex.minp.x, (float)0);
pos.x += d;
me_ex.movex(d);
me_ey.movex(d);
}
}
if (me_ey.maxp.x <= level[i].maxp.x) {
if (me_ey.maxp.x <= level[i].minp.x + oldv.x * s) {
float d = std::min(level[i].minp.x - me_ex.maxp.x, (float)0);
pos.x += d;
me_ex.movex(d);
me_ey.movex(d);
}
}
}
if (level[i].intersects(me_ey)) {
if (me_ex.minp.y >= level[i].minp.y) {
if (me_ex.minp.y >= level[i].maxp.y + oldv.y * s) {
float d = std::max(level[i].maxp.y - me_ey.minp.y, (float)0);
pos.y += d;
me_ex.movey(d);
me_ey.movey(d);
}
}
if (me_ex.maxp.y <= level[i].maxp.y) {
if (me_ex.maxp.y <= level[i].minp.y + oldv.y * s) {
float d = std::min(level[i].minp.y - me_ey.maxp.y, (float)0);
pos.y += d;
me_ex.movey(d);
me_ey.movey(d);
}
}
}
}
for (unsigned int i = 0; i < level.size(); i++) {
if (level[i].intersects(me_ex)) {
if (me_ey.minp.x >= level[i].minp.x) {
touching_walls[LEFT] = std::max(touching_walls[LEFT], level[i].color);
}
if (me_ey.maxp.x <= level[i].maxp.x) {
touching_walls[RIGHT] = std::max(touching_walls[RIGHT], level[i].color);
}
}
if (level[i].intersects(me_ey)) {
if (me_ex.minp.y >= level[i].minp.y) {
touching_walls[TOP] = std::max(touching_walls[TOP], level[i].color);
}
if (me_ex.maxp.y <= level[i].maxp.y) {
touching_walls[BOTTOM] = std::max(touching_walls[BOTTOM], level[i].color);
}
}
}
float visc = 0.01;
switch (touching_walls[LEFT]) {
case 1:
if (velocity.x < 0) velocity.x *= pow(visc, s);
break;
case 2:
velocity.x = std::max(velocity.x, (float)0);
acceleration.x = std::max(acceleration.x, (float)0);
break;
case 3:
velocity.x = std::max(velocity.x, -velocity.x);
acceleration.x = std::max(acceleration.x, (float)0);
break;
default: break;
}
switch (touching_walls[RIGHT]) {
case 1:
if (velocity.x > 0) velocity.x *= pow(visc, s);
break;
case 2:
velocity.x = std::min(velocity.x, (float)0);
acceleration.x = std::min(acceleration.x, (float)0);
break;
case 3:
velocity.x = std::min(velocity.x, -velocity.x);
acceleration.x = std::min(acceleration.x, (float)0);
break;
default: break;
}
switch (touching_walls[TOP]) {
case 1:
if (velocity.y < 0) velocity.y *= pow(visc, s);
break;
case 2:
velocity.y = std::max(velocity.y, (float)0);
acceleration.y = std::max(acceleration.y, (float)0);
break;
case 3:
velocity.y = std::max(velocity.y, -velocity.y);
acceleration.y = std::max(acceleration.y, (float)0);
break;
default: break;
}
switch (touching_walls[BOTTOM]) {
case 1:
if (velocity.y > 0) velocity.y *= pow(visc, s);
break;
case 2:
velocity.y = std::min(velocity.y, (float)0);
acceleration.y = std::min(acceleration.y, (float)0);
break;
case 3:
velocity.y = std::min(velocity.y, -velocity.y);
acceleration.y = std::min(acceleration.y, (float)0);
break;
default: break;
}
}
<commit_msg>Physics part V: lightspeed<commit_after>#include "GameScreenState.h"
#include <algorithm>
#include <SFML/Graphics.hpp>
//const int TOP = 1;
//const int BOTTOM = 2;
//const int LEFT = 4;
//const int RIGHT = 8;
const unsigned char TOP = 0;
const unsigned char BOTTOM = 1;
const unsigned char LEFT = 2;
const unsigned char RIGHT = 3;
GameScreenState::GameScreenState() {
pos = sf::Vector2f(300, 100);
velocity = sf::Vector2f(0, 0);
acceleration = sf::Vector2f(0, 0);
for (unsigned char i = 0; i < 4; i++) touching_walls[i] = 0;
level.push_back(rectangle(sf::Vector2f(200, 400), sf::Vector2f(400, 450), 2));
level.push_back(rectangle(sf::Vector2f(400, 260), sf::Vector2f(450, 450), 3));
level.push_back(rectangle(sf::Vector2f(100, 200), sf::Vector2f(200, 450), 1));
level.push_back(rectangle(sf::Vector2f(0, 0), sf::Vector2f(600, 2), 3));
level.push_back(rectangle(sf::Vector2f(0, 0), sf::Vector2f(2, 600), 3));
level.push_back(rectangle(sf::Vector2f(600, 0), sf::Vector2f(602, 600), 3));
level.push_back(rectangle(sf::Vector2f(0, 600), sf::Vector2f(600, 602), 3));
updateSprites();
}
void GameScreenState::event(const sf::Event& event) {
}
void GameScreenState::updateSprites() {
sprites.clear();
sprites.resize(level.size() + 1);
static sf::Color colors[4] = {sf::Color::White, sf::Color::Blue, sf::Color::Black, sf::Color::Yellow};
for (unsigned int i = 0; i < level.size(); i++) {
sf::RectangleShape sprite;
//sf::Sprite sprite;
//sf::Texture tex;
sprite.setSize(level[i].maxp - level[i].minp);
sprite.setFillColor(colors[level[i].color]);
//sprite.setTextureRect(sf::IntRect(0, 0,
// (int)(level[i].maxp.x - level[i].minp.x),
// (int)(level[i].maxp.y - level[i].minp.y)));
//tex.create((int)(level[i].maxp.x - level[i].minp.x),
// (int)(level[i].maxp.y - level[i].minp.y));
//sprite.setTexture(tex);
sprite.setPosition(level[i].minp);
sprites.push_back(sprite);
}
sf::RectangleShape sprite;
sprite.setSize(sf::Vector2f(40, 40));
sprite.setFillColor(sf::Color::Red);
sprite.setPosition(pos - sf::Vector2f(20, 20));
sprites.push_back(sprite);
}
void GameScreenState::render(sf::RenderTarget& target) {
updateSprites();
target.clear(sf::Color::White);
for (unsigned int i = 0; i < sprites.size(); i++) {
target.draw(sprites[i]);
}
}
void GameScreenState::update(const sf::Time& time) {
float s = time.asSeconds();
pos += velocity * s;
sf::Vector2f oldv = velocity;
velocity += s * acceleration;
acceleration = sf::Vector2f(0, 240);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
velocity.x = std::min(velocity.x + 400 * s, (float)200);
} else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
velocity.x = std::max(velocity.x - 400 * s, (float)-200);
} else {
//velocity.x = 0;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
switch (touching_walls[BOTTOM]) {
case 1:
velocity.y -= 500 * s;
break;
case 2:
case 3:
velocity.y = std::max(velocity.y - 150, (float)-1000);
}
}
rectangle me_ex = rectangle(pos - sf::Vector2f(20, 19.9), pos + sf::Vector2f(20, 19.9));
rectangle me_ey = rectangle(pos - sf::Vector2f(19.9, 20), pos + sf::Vector2f(19.9, 20));
for (unsigned char i = 0; i < 4; i++) touching_walls[i] = 0;
for (unsigned int i = 0; i < level.size(); i++) {
if (level[i].color < 2) continue; // Not solid
if (level[i].intersects(me_ex)) {
if (me_ey.maxp.x >= level[i].maxp.x) {
if (me_ey.minp.x >= level[i].maxp.x + oldv.x * s) {
float d = std::max(level[i].maxp.x - me_ex.minp.x, (float)0);
pos.x += d;
me_ex.movex(d);
me_ey.movex(d);
}
}
if (me_ey.minp.x <= level[i].minp.x) {
if (me_ey.maxp.x <= level[i].minp.x + oldv.x * s) {
float d = std::min(level[i].minp.x - me_ex.maxp.x, (float)0);
pos.x += d;
me_ex.movex(d);
me_ey.movex(d);
}
}
}
if (level[i].intersects(me_ey)) {
if (me_ex.maxp.y >= level[i].maxp.y) {
if (me_ex.minp.y >= level[i].maxp.y + oldv.y * s) {
float d = std::max(level[i].maxp.y - me_ey.minp.y, (float)0);
pos.y += d;
me_ex.movey(d);
me_ey.movey(d);
}
}
if (me_ex.minp.y <= level[i].minp.y) {
if (me_ex.maxp.y <= level[i].minp.y + oldv.y * s) {
float d = std::min(level[i].minp.y - me_ey.maxp.y, (float)0);
pos.y += d;
me_ex.movey(d);
me_ey.movey(d);
}
}
}
}
for (unsigned int i = 0; i < level.size(); i++) {
if (level[i].intersects(me_ex)) {
if (me_ey.minp.x >= level[i].minp.x) {
touching_walls[LEFT] = std::max(touching_walls[LEFT], level[i].color);
}
if (me_ey.maxp.x <= level[i].maxp.x) {
touching_walls[RIGHT] = std::max(touching_walls[RIGHT], level[i].color);
}
}
if (level[i].intersects(me_ey)) {
if (me_ex.minp.y >= level[i].minp.y) {
touching_walls[TOP] = std::max(touching_walls[TOP], level[i].color);
}
if (me_ex.maxp.y <= level[i].maxp.y) {
touching_walls[BOTTOM] = std::max(touching_walls[BOTTOM], level[i].color);
}
}
}
float visc = 0.01;
switch (touching_walls[LEFT]) {
case 1:
if (velocity.x < 0) velocity.x *= pow(visc, s);
break;
case 2:
velocity.x = std::max(velocity.x, (float)0);
acceleration.x = std::max(acceleration.x, (float)0);
break;
case 3:
velocity.x = std::max(velocity.x, -velocity.x);
acceleration.x = std::max(acceleration.x, (float)0);
break;
default: break;
}
switch (touching_walls[RIGHT]) {
case 1:
if (velocity.x > 0) velocity.x *= pow(visc, s);
break;
case 2:
velocity.x = std::min(velocity.x, (float)0);
acceleration.x = std::min(acceleration.x, (float)0);
break;
case 3:
velocity.x = std::min(velocity.x, -velocity.x);
acceleration.x = std::min(acceleration.x, (float)0);
break;
default: break;
}
switch (touching_walls[TOP]) {
case 1:
if (velocity.y < 0) velocity.y *= pow(visc, s);
break;
case 2:
velocity.y = std::max(velocity.y, (float)0);
acceleration.y = std::max(acceleration.y, (float)0);
break;
case 3:
velocity.y = std::max(velocity.y, -velocity.y);
acceleration.y = std::max(acceleration.y, (float)0);
break;
default: break;
}
switch (touching_walls[BOTTOM]) {
case 1:
if (velocity.y > 0) velocity.y *= pow(visc, s);
break;
case 2:
velocity.y = std::min(velocity.y, (float)0);
acceleration.y = std::min(acceleration.y, (float)0);
break;
case 3:
velocity.y = std::min(velocity.y, -velocity.y);
acceleration.y = std::min(acceleration.y, (float)0);
break;
default: break;
}
}
<|endoftext|> |
<commit_before>//
// ByteOrder.cpp
//
// Copyright (c) 2001-2004 Virtual Terrain Project.
// Free for all uses, see license.txt for details.
//
#include "ByteOrder.h"
static int GetDataTypeSize( DataType type )
{
switch ( type )
{
case DT_SHORT: return sizeof(short); break;
case DT_INT: return sizeof(int); break;
case DT_LONG: return sizeof(long); break;
case DT_FLOAT: return sizeof(float); break;
case DT_DOUBLE: return sizeof(double); break;
}
assert(false);
return 1;
}
/**
* If the byte orders differ, swap bytes; if not, don't; return the result.
* This is the memory buffer version of the SwapBytes() macros, and as such
* supports an array of data. It also parametizes the element type to avoid
* function explosion.
* \param items the data items to order
* \param type the type of each item in the array
* \param nitems the number if items in the array
* \param data_order the byte order of the data
* \param desired_order the desired byte ordering
*
*/
void SwapMemBytes( void *items, DataType type, size_t nitems,
ByteOrder data_order, ByteOrder desired_order )
{
if ( data_order == BO_MACHINE ) data_order = NativeByteOrder();
if ( desired_order == BO_MACHINE ) desired_order = NativeByteOrder();
if ( data_order == desired_order )
return;
size_t tsize = GetDataTypeSize( type );
char *base = (char *) items, *p;
switch ( type )
{
case DT_SHORT :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(short *)p = SwapShort( *(short *)p );
break;
case DT_INT :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(int *)p = SwapInt( *(int *)p );
break;
case DT_LONG :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(long *)p = SwapLong( *(long *)p );
break;
case DT_FLOAT :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(float *)p = SwapFloat( *(float *)p );
break;
case DT_DOUBLE :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(double *)p = SwapDouble( *(double *)p );
break;
default:
assert(false);
}
}
/**
* Like stdio's fread(), but adds an optional byte swapping phase for
* the data read.
* \param ptr data buffer to read items into
* \param type the data type of items to be read
* \param nitems the number of items to read
* \param stream the stdio stream open for read
* \param file_order the byte ordering of data read from the file
* \param desired_order the desired byte ordering
* \return fread() return value (num items read, or negative for error)
*
*/
size_t FRead( void *ptr, DataType type, size_t nitems, FILE *stream,
ByteOrder file_order, ByteOrder desired_order )
{
int tsize = GetDataTypeSize( type );
// returned value is the number of "items" read
size_t ret = fread( ptr, tsize, nitems, stream );
if ( (int)ret >= 0 )
SwapMemBytes( ptr, type, ret, file_order, desired_order );
return ret;
}
/**
* Like stdio's fread(), but adds an optional byte swapping phase for
* the data read. File access is done via zlib's gzip IO routines to
* be compatible with gzopen(), etc.
* \param ptr data buffer to read items into
* \param type the data type of items to be read
* \param nitems the number of items to read
* \param stream the stdio stream open for read
* \param file_order the byte ordering of data read from the file
* \param desired_order the desired byte ordering
* \return fread() return value (Number of items read, or negative for error)
*
*/
size_t GZFRead( void *ptr, DataType type, size_t nitems, gzFile gzstream,
ByteOrder file_order, ByteOrder desired_order )
{
int tsize = GetDataTypeSize( type );
size_t ret = gzread(gzstream, ptr, tsize * nitems) / tsize;
if ( (int)ret >= 0 )
SwapMemBytes( ptr, type, ret/tsize, file_order, desired_order );
return ret;
}
/**
* Just like stdio's fwrite(), but adds an optional byte swapping phase for
* the data write.
* \param ptr data buffer to write items from
* \param type the data type of items to be written
* \param nitems the number of items to written
* \param stream the stdio stream open for writing
* \param file_order the byte ordering of data written to the file
* \param data_order the byte ordering of data in the buffer
* \return fwrite() return value (Number of items read, or negative for error)
*
*/
size_t FWrite( void *ptr, DataType type, size_t nitems, FILE *stream,
ByteOrder file_order, ByteOrder data_order )
{
// If we need to swap bytes, we have two options:
// 1. create a temporary buffer with the swapped values, write it
// 2. swap, write, swap back again
// The second approach is implemented here
SwapMemBytes( ptr, type, nitems, file_order, data_order );
int tsize = GetDataTypeSize( type );
size_t ret = fwrite(ptr, tsize, nitems, stream);
SwapMemBytes( ptr, type, nitems, file_order, data_order );
return ret;
}
/**
* Just like stdio's fwrite(), but adds an optional byte swapping phase for
* the data write. File access is done via zlib's gzip IO routines to
* be compatible with gzopen(), etc.
* \param ptr data buffer to write items from
* \param type the data type of items to be written
* \param nitems the number of items to written
* \param stream the stdio stream open for writing
* \param file_order the byte ordering of data written to the file
* \param data_order the byte ordering of data in the buffer
* \return fwrite() return value (num items written, or negative for error)
*
*/
size_t GZFWrite( void *ptr, DataType type, size_t nitems, gzFile gzstream,
ByteOrder file_order, ByteOrder data_order )
{
// If we need to swap bytes, we have two options:
// 1. create a temporary buffer with the swapped values, write it
// 2. swap, write, swap back again
// The second approach is implemented here
SwapMemBytes( ptr, type, nitems, file_order, data_order );
int tsize = GetDataTypeSize( type );
size_t ret = gzwrite(gzstream, ptr, tsize * nitems);
SwapMemBytes( ptr, type, nitems, file_order, data_order );
return ret;
}
<commit_msg>swapping fix in GZFRead<commit_after>//
// ByteOrder.cpp
//
// Copyright (c) 2001-2004 Virtual Terrain Project.
// Free for all uses, see license.txt for details.
//
#include "ByteOrder.h"
static int GetDataTypeSize( DataType type )
{
switch ( type )
{
case DT_SHORT: return sizeof(short); break;
case DT_INT: return sizeof(int); break;
case DT_LONG: return sizeof(long); break;
case DT_FLOAT: return sizeof(float); break;
case DT_DOUBLE: return sizeof(double); break;
}
assert(false);
return 1;
}
/**
* If the byte orders differ, swap bytes; if not, don't; return the result.
* This is the memory buffer version of the SwapBytes() macros, and as such
* supports an array of data. It also parametizes the element type to avoid
* function explosion.
* \param items the data items to order
* \param type the type of each item in the array
* \param nitems the number if items in the array
* \param data_order the byte order of the data
* \param desired_order the desired byte ordering
*
*/
void SwapMemBytes( void *items, DataType type, size_t nitems,
ByteOrder data_order, ByteOrder desired_order )
{
if ( data_order == BO_MACHINE ) data_order = NativeByteOrder();
if ( desired_order == BO_MACHINE ) desired_order = NativeByteOrder();
if ( data_order == desired_order )
return;
size_t tsize = GetDataTypeSize( type );
char *base = (char *) items, *p;
switch ( type )
{
case DT_SHORT :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(short *)p = SwapShort( *(short *)p );
break;
case DT_INT :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(int *)p = SwapInt( *(int *)p );
break;
case DT_LONG :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(long *)p = SwapLong( *(long *)p );
break;
case DT_FLOAT :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(float *)p = SwapFloat( *(float *)p );
break;
case DT_DOUBLE :
for ( p = base + (nitems-1) * tsize; p >= base; p -= tsize )
*(double *)p = SwapDouble( *(double *)p );
break;
default:
assert(false);
}
}
/**
* Like stdio's fread(), but adds an optional byte swapping phase for
* the data read.
* \param ptr data buffer to read items into
* \param type the data type of items to be read
* \param nitems the number of items to read
* \param stream the stdio stream open for read
* \param file_order the byte ordering of data read from the file
* \param desired_order the desired byte ordering
* \return fread() return value (num items read, or negative for error)
*
*/
size_t FRead( void *ptr, DataType type, size_t nitems, FILE *stream,
ByteOrder file_order, ByteOrder desired_order )
{
int tsize = GetDataTypeSize( type );
// returned value is the number of "items" read
size_t ret = fread( ptr, tsize, nitems, stream );
if ( (int)ret >= 0 )
SwapMemBytes( ptr, type, ret, file_order, desired_order );
return ret;
}
/**
* Like stdio's fread(), but adds an optional byte swapping phase for
* the data read. File access is done via zlib's gzip IO routines to
* be compatible with gzopen(), etc.
* \param ptr data buffer to read items into
* \param type the data type of items to be read
* \param nitems the number of items to read
* \param stream the stdio stream open for read
* \param file_order the byte ordering of data read from the file
* \param desired_order the desired byte ordering
* \return fread() return value (Number of items read, or negative for error)
*
*/
size_t GZFRead( void *ptr, DataType type, size_t nitems, gzFile gzstream,
ByteOrder file_order, ByteOrder desired_order )
{
int tsize = GetDataTypeSize( type );
// returned value is the number of "items" read
size_t ret = gzread(gzstream, ptr, tsize * nitems) / tsize;
if ( (int)ret >= 0 )
SwapMemBytes( ptr, type, ret, file_order, desired_order );
return ret;
}
/**
* Just like stdio's fwrite(), but adds an optional byte swapping phase for
* the data write.
* \param ptr data buffer to write items from
* \param type the data type of items to be written
* \param nitems the number of items to written
* \param stream the stdio stream open for writing
* \param file_order the byte ordering of data written to the file
* \param data_order the byte ordering of data in the buffer
* \return fwrite() return value (Number of items read, or negative for error)
*
*/
size_t FWrite( void *ptr, DataType type, size_t nitems, FILE *stream,
ByteOrder file_order, ByteOrder data_order )
{
// If we need to swap bytes, we have two options:
// 1. create a temporary buffer with the swapped values, write it
// 2. swap, write, swap back again
// The second approach is implemented here
SwapMemBytes( ptr, type, nitems, file_order, data_order );
int tsize = GetDataTypeSize( type );
size_t ret = fwrite(ptr, tsize, nitems, stream);
SwapMemBytes( ptr, type, nitems, file_order, data_order );
return ret;
}
/**
* Just like stdio's fwrite(), but adds an optional byte swapping phase for
* the data write. File access is done via zlib's gzip IO routines to
* be compatible with gzopen(), etc.
* \param ptr data buffer to write items from
* \param type the data type of items to be written
* \param nitems the number of items to written
* \param stream the stdio stream open for writing
* \param file_order the byte ordering of data written to the file
* \param data_order the byte ordering of data in the buffer
* \return fwrite() return value (num items written, or negative for error)
*
*/
size_t GZFWrite( void *ptr, DataType type, size_t nitems, gzFile gzstream,
ByteOrder file_order, ByteOrder data_order )
{
// If we need to swap bytes, we have two options:
// 1. create a temporary buffer with the swapped values, write it
// 2. swap, write, swap back again
// The second approach is implemented here
SwapMemBytes( ptr, type, nitems, file_order, data_order );
int tsize = GetDataTypeSize( type );
size_t ret = gzwrite(gzstream, ptr, tsize * nitems);
SwapMemBytes( ptr, type, nitems, file_order, data_order );
return ret;
}
<|endoftext|> |
<commit_before>/*
digital.c - wiring digital implementation for esp8266
Copyright (c) 2015 Hristo Gochkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
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
*/
#define ARDUINO_MAIN
#include "wiring_private.h"
#include "pins_arduino.h"
#include "c_types.h"
#include "eagle_soc.h"
#include "ets_sys.h"
#include "user_interface.h"
#include "core_esp8266_waveform.h"
extern "C" {
uint8_t esp8266_gpioToFn[16] = {0x34, 0x18, 0x38, 0x14, 0x3C, 0x40, 0x1C, 0x20, 0x24, 0x28, 0x2C, 0x30, 0x04, 0x08, 0x0C, 0x10};
extern void __pinMode(uint8_t pin, uint8_t mode) {
if(pin < 16){
if(mode == SPECIAL){
GPC(pin) = (GPC(pin) & (0xF << GPCI)); //SOURCE(GPIO) | DRIVER(NORMAL) | INT_TYPE(UNCHANGED) | WAKEUP_ENABLE(DISABLED)
GPEC = (1 << pin); //Disable
GPF(pin) = GPFFS(GPFFS_BUS(pin));//Set mode to BUS (RX0, TX0, TX1, SPI, HSPI or CLK depending in the pin)
if(pin == 3) GPF(pin) |= (1 << GPFPU);//enable pullup on RX
} else if(mode & FUNCTION_0){
GPC(pin) = (GPC(pin) & (0xF << GPCI)); //SOURCE(GPIO) | DRIVER(NORMAL) | INT_TYPE(UNCHANGED) | WAKEUP_ENABLE(DISABLED)
GPEC = (1 << pin); //Disable
GPF(pin) = GPFFS((mode >> 4) & 0x07);
if(pin == 13 && mode == FUNCTION_4) GPF(pin) |= (1 << GPFPU);//enable pullup on RX
} else if(mode == OUTPUT || mode == OUTPUT_OPEN_DRAIN){
GPF(pin) = GPFFS(GPFFS_GPIO(pin));//Set mode to GPIO
GPC(pin) = (GPC(pin) & (0xF << GPCI)); //SOURCE(GPIO) | DRIVER(NORMAL) | INT_TYPE(UNCHANGED) | WAKEUP_ENABLE(DISABLED)
if(mode == OUTPUT_OPEN_DRAIN) GPC(pin) |= (1 << GPCD);
GPES = (1 << pin); //Enable
} else if(mode == INPUT || mode == INPUT_PULLUP){
GPF(pin) = GPFFS(GPFFS_GPIO(pin));//Set mode to GPIO
GPEC = (1 << pin); //Disable
GPC(pin) = (GPC(pin) & (0xF << GPCI)) | (1 << GPCD); //SOURCE(GPIO) | DRIVER(OPEN_DRAIN) | INT_TYPE(UNCHANGED) | WAKEUP_ENABLE(DISABLED)
if(mode == INPUT_PULLUP) {
GPF(pin) |= (1 << GPFPU); // Enable Pullup
}
} else if(mode == WAKEUP_PULLUP || mode == WAKEUP_PULLDOWN){
GPF(pin) = GPFFS(GPFFS_GPIO(pin));//Set mode to GPIO
GPEC = (1 << pin); //Disable
if(mode == WAKEUP_PULLUP) {
GPF(pin) |= (1 << GPFPU); // Enable Pullup
GPC(pin) = (1 << GPCD) | (4 << GPCI) | (1 << GPCWE); //SOURCE(GPIO) | DRIVER(OPEN_DRAIN) | INT_TYPE(LOW) | WAKEUP_ENABLE(ENABLED)
} else {
GPF(pin) |= (1 << GPFPD); // Enable Pulldown
GPC(pin) = (1 << GPCD) | (5 << GPCI) | (1 << GPCWE); //SOURCE(GPIO) | DRIVER(OPEN_DRAIN) | INT_TYPE(HIGH) | WAKEUP_ENABLE(ENABLED)
}
}
} else if(pin == 16){
GPF16 = GP16FFS(GPFFS_GPIO(pin));//Set mode to GPIO
GPC16 = 0;
if(mode == INPUT || mode == INPUT_PULLDOWN_16){
if(mode == INPUT_PULLDOWN_16){
GPF16 |= (1 << GP16FPD);//Enable Pulldown
}
GP16E &= ~1;
} else if(mode == OUTPUT){
GP16E |= 1;
}
}
}
extern void ICACHE_RAM_ATTR __digitalWrite(uint8_t pin, uint8_t val) {
stopWaveform(pin);
if(pin < 16){
if(val) GPOS = (1 << pin);
else GPOC = (1 << pin);
} else if(pin == 16){
if(val) GP16O |= 1;
else GP16O &= ~1;
}
}
extern int ICACHE_RAM_ATTR __digitalRead(uint8_t pin) {
if(pin < 16){
return GPIP(pin);
} else if(pin == 16){
return GP16I & 0x01;
}
return 0;
}
/*
GPIO INTERRUPTS
*/
typedef void (*voidFuncPtr)(void);
typedef void (*voidFuncPtrArg)(void*);
typedef struct {
uint8_t mode;
void (*fn)(void);
void * arg;
} interrupt_handler_t;
//duplicate from functionalInterrupt.h keep in sync
typedef struct InterruptInfo {
uint8_t pin;
uint8_t value;
uint32_t micro;
} InterruptInfo;
typedef struct {
InterruptInfo* interruptInfo;
void* functionInfo;
} ArgStructure;
static interrupt_handler_t interrupt_handlers[16];
static uint32_t interrupt_reg = 0;
void ICACHE_RAM_ATTR interrupt_handler(void *arg) {
(void) arg;
uint32_t status = GPIE;
GPIEC = status;//clear them interrupts
uint32_t levels = GPI;
if(status == 0 || interrupt_reg == 0) return;
ETS_GPIO_INTR_DISABLE();
int i = 0;
uint32_t changedbits = status & interrupt_reg;
while(changedbits){
while(!(changedbits & (1 << i))) i++;
changedbits &= ~(1 << i);
interrupt_handler_t *handler = &interrupt_handlers[i];
if (handler->fn &&
(handler->mode == CHANGE ||
(handler->mode & 1) == !!(levels & (1 << i)))) {
// to make ISR compatible to Arduino AVR model where interrupts are disabled
// we disable them before we call the client ISR
uint32_t savedPS = xt_rsil(15); // stop other interrupts
ArgStructure* localArg = (ArgStructure*)handler->arg;
if (localArg && localArg->interruptInfo)
{
localArg->interruptInfo->pin = i;
localArg->interruptInfo->value = __digitalRead(i);
localArg->interruptInfo->micro = micros();
}
if (handler->arg)
{
((voidFuncPtrArg)handler->fn)(handler->arg);
}
else
{
handler->fn();
}
xt_wsr_ps(savedPS);
}
}
ETS_GPIO_INTR_ENABLE();
}
extern void cleanupFunctional(void* arg);
extern void ICACHE_RAM_ATTR __attachInterruptArg(uint8_t pin, voidFuncPtr userFunc, void *arg, int mode) {
if(pin < 16) {
ETS_GPIO_INTR_DISABLE();
interrupt_handler_t *handler = &interrupt_handlers[pin];
handler->mode = mode;
handler->fn = userFunc;
if (handler->arg) // Clean when new attach without detach
{
cleanupFunctional(handler->arg);
}
handler->arg = arg;
interrupt_reg |= (1 << pin);
GPC(pin) &= ~(0xF << GPCI);//INT mode disabled
GPIEC = (1 << pin); //Clear Interrupt for this pin
GPC(pin) |= ((mode & 0xF) << GPCI);//INT mode "mode"
ETS_GPIO_INTR_ATTACH(interrupt_handler, &interrupt_reg);
ETS_GPIO_INTR_ENABLE();
}
}
extern void ICACHE_RAM_ATTR __attachInterrupt(uint8_t pin, voidFuncPtr userFunc, int mode )
{
__attachInterruptArg (pin, userFunc, 0, mode);
}
extern void ICACHE_RAM_ATTR __detachInterrupt(uint8_t pin) {
if(pin < 16) {
ETS_GPIO_INTR_DISABLE();
GPC(pin) &= ~(0xF << GPCI);//INT mode disabled
GPIEC = (1 << pin); //Clear Interrupt for this pin
interrupt_reg &= ~(1 << pin);
interrupt_handler_t *handler = &interrupt_handlers[pin];
handler->mode = 0;
handler->fn = 0;
if (handler->arg)
{
cleanupFunctional(handler->arg);
}
handler->arg = 0;
if (interrupt_reg)
ETS_GPIO_INTR_ENABLE();
}
}
void initPins() {
//Disable UART interrupts
system_set_os_print(0);
U0IE = 0;
U1IE = 0;
for (int i = 0; i <= 5; ++i) {
pinMode(i, INPUT);
}
// pins 6-11 are used for the SPI flash interface
for (int i = 12; i <= 16; ++i) {
pinMode(i, INPUT);
}
}
extern void pinMode(uint8_t pin, uint8_t mode) __attribute__ ((weak, alias("__pinMode")));
extern void digitalWrite(uint8_t pin, uint8_t val) __attribute__ ((weak, alias("__digitalWrite")));
extern int digitalRead(uint8_t pin) __attribute__ ((weak, alias("__digitalRead")));
extern void attachInterrupt(uint8_t pin, voidFuncPtr handler, int mode) __attribute__ ((weak, alias("__attachInterrupt")));
extern void detachInterrupt(uint8_t pin) __attribute__ ((weak, alias("__detachInterrupt")));
};
<commit_msg>ISR: check for address in IRAM (#5995)<commit_after>/*
digital.c - wiring digital implementation for esp8266
Copyright (c) 2015 Hristo Gochkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
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
*/
#define ARDUINO_MAIN
#include "wiring_private.h"
#include "pins_arduino.h"
#include "c_types.h"
#include "eagle_soc.h"
#include "ets_sys.h"
#include "user_interface.h"
#include "core_esp8266_waveform.h"
extern "C" {
uint8_t esp8266_gpioToFn[16] = {0x34, 0x18, 0x38, 0x14, 0x3C, 0x40, 0x1C, 0x20, 0x24, 0x28, 0x2C, 0x30, 0x04, 0x08, 0x0C, 0x10};
extern void __pinMode(uint8_t pin, uint8_t mode) {
if(pin < 16){
if(mode == SPECIAL){
GPC(pin) = (GPC(pin) & (0xF << GPCI)); //SOURCE(GPIO) | DRIVER(NORMAL) | INT_TYPE(UNCHANGED) | WAKEUP_ENABLE(DISABLED)
GPEC = (1 << pin); //Disable
GPF(pin) = GPFFS(GPFFS_BUS(pin));//Set mode to BUS (RX0, TX0, TX1, SPI, HSPI or CLK depending in the pin)
if(pin == 3) GPF(pin) |= (1 << GPFPU);//enable pullup on RX
} else if(mode & FUNCTION_0){
GPC(pin) = (GPC(pin) & (0xF << GPCI)); //SOURCE(GPIO) | DRIVER(NORMAL) | INT_TYPE(UNCHANGED) | WAKEUP_ENABLE(DISABLED)
GPEC = (1 << pin); //Disable
GPF(pin) = GPFFS((mode >> 4) & 0x07);
if(pin == 13 && mode == FUNCTION_4) GPF(pin) |= (1 << GPFPU);//enable pullup on RX
} else if(mode == OUTPUT || mode == OUTPUT_OPEN_DRAIN){
GPF(pin) = GPFFS(GPFFS_GPIO(pin));//Set mode to GPIO
GPC(pin) = (GPC(pin) & (0xF << GPCI)); //SOURCE(GPIO) | DRIVER(NORMAL) | INT_TYPE(UNCHANGED) | WAKEUP_ENABLE(DISABLED)
if(mode == OUTPUT_OPEN_DRAIN) GPC(pin) |= (1 << GPCD);
GPES = (1 << pin); //Enable
} else if(mode == INPUT || mode == INPUT_PULLUP){
GPF(pin) = GPFFS(GPFFS_GPIO(pin));//Set mode to GPIO
GPEC = (1 << pin); //Disable
GPC(pin) = (GPC(pin) & (0xF << GPCI)) | (1 << GPCD); //SOURCE(GPIO) | DRIVER(OPEN_DRAIN) | INT_TYPE(UNCHANGED) | WAKEUP_ENABLE(DISABLED)
if(mode == INPUT_PULLUP) {
GPF(pin) |= (1 << GPFPU); // Enable Pullup
}
} else if(mode == WAKEUP_PULLUP || mode == WAKEUP_PULLDOWN){
GPF(pin) = GPFFS(GPFFS_GPIO(pin));//Set mode to GPIO
GPEC = (1 << pin); //Disable
if(mode == WAKEUP_PULLUP) {
GPF(pin) |= (1 << GPFPU); // Enable Pullup
GPC(pin) = (1 << GPCD) | (4 << GPCI) | (1 << GPCWE); //SOURCE(GPIO) | DRIVER(OPEN_DRAIN) | INT_TYPE(LOW) | WAKEUP_ENABLE(ENABLED)
} else {
GPF(pin) |= (1 << GPFPD); // Enable Pulldown
GPC(pin) = (1 << GPCD) | (5 << GPCI) | (1 << GPCWE); //SOURCE(GPIO) | DRIVER(OPEN_DRAIN) | INT_TYPE(HIGH) | WAKEUP_ENABLE(ENABLED)
}
}
} else if(pin == 16){
GPF16 = GP16FFS(GPFFS_GPIO(pin));//Set mode to GPIO
GPC16 = 0;
if(mode == INPUT || mode == INPUT_PULLDOWN_16){
if(mode == INPUT_PULLDOWN_16){
GPF16 |= (1 << GP16FPD);//Enable Pulldown
}
GP16E &= ~1;
} else if(mode == OUTPUT){
GP16E |= 1;
}
}
}
extern void ICACHE_RAM_ATTR __digitalWrite(uint8_t pin, uint8_t val) {
stopWaveform(pin);
if(pin < 16){
if(val) GPOS = (1 << pin);
else GPOC = (1 << pin);
} else if(pin == 16){
if(val) GP16O |= 1;
else GP16O &= ~1;
}
}
extern int ICACHE_RAM_ATTR __digitalRead(uint8_t pin) {
if(pin < 16){
return GPIP(pin);
} else if(pin == 16){
return GP16I & 0x01;
}
return 0;
}
/*
GPIO INTERRUPTS
*/
typedef void (*voidFuncPtr)(void);
typedef void (*voidFuncPtrArg)(void*);
typedef struct {
uint8_t mode;
void (*fn)(void);
void * arg;
} interrupt_handler_t;
//duplicate from functionalInterrupt.h keep in sync
typedef struct InterruptInfo {
uint8_t pin;
uint8_t value;
uint32_t micro;
} InterruptInfo;
typedef struct {
InterruptInfo* interruptInfo;
void* functionInfo;
} ArgStructure;
static interrupt_handler_t interrupt_handlers[16];
static uint32_t interrupt_reg = 0;
void ICACHE_RAM_ATTR interrupt_handler(void *arg) {
(void) arg;
uint32_t status = GPIE;
GPIEC = status;//clear them interrupts
uint32_t levels = GPI;
if(status == 0 || interrupt_reg == 0) return;
ETS_GPIO_INTR_DISABLE();
int i = 0;
uint32_t changedbits = status & interrupt_reg;
while(changedbits){
while(!(changedbits & (1 << i))) i++;
changedbits &= ~(1 << i);
interrupt_handler_t *handler = &interrupt_handlers[i];
if (handler->fn &&
(handler->mode == CHANGE ||
(handler->mode & 1) == !!(levels & (1 << i)))) {
// to make ISR compatible to Arduino AVR model where interrupts are disabled
// we disable them before we call the client ISR
uint32_t savedPS = xt_rsil(15); // stop other interrupts
ArgStructure* localArg = (ArgStructure*)handler->arg;
if (localArg && localArg->interruptInfo)
{
localArg->interruptInfo->pin = i;
localArg->interruptInfo->value = __digitalRead(i);
localArg->interruptInfo->micro = micros();
}
if (handler->arg)
{
((voidFuncPtrArg)handler->fn)(handler->arg);
}
else
{
handler->fn();
}
xt_wsr_ps(savedPS);
}
}
ETS_GPIO_INTR_ENABLE();
}
extern void cleanupFunctional(void* arg);
extern void ICACHE_RAM_ATTR __attachInterruptArg(uint8_t pin, voidFuncPtr userFunc, void *arg, int mode) {
// #5780
// https://github.com/esp8266/esp8266-wiki/wiki/Memory-Map
if ((uint32_t)userFunc >= 0x40200000)
{
// ISR not in IRAM
::printf((PGM_P)F("ISR not in IRAM!\r\n"));
abort();
}
if(pin < 16) {
ETS_GPIO_INTR_DISABLE();
interrupt_handler_t *handler = &interrupt_handlers[pin];
handler->mode = mode;
handler->fn = userFunc;
if (handler->arg) // Clean when new attach without detach
{
cleanupFunctional(handler->arg);
}
handler->arg = arg;
interrupt_reg |= (1 << pin);
GPC(pin) &= ~(0xF << GPCI);//INT mode disabled
GPIEC = (1 << pin); //Clear Interrupt for this pin
GPC(pin) |= ((mode & 0xF) << GPCI);//INT mode "mode"
ETS_GPIO_INTR_ATTACH(interrupt_handler, &interrupt_reg);
ETS_GPIO_INTR_ENABLE();
}
}
extern void ICACHE_RAM_ATTR __attachInterrupt(uint8_t pin, voidFuncPtr userFunc, int mode )
{
__attachInterruptArg (pin, userFunc, 0, mode);
}
extern void ICACHE_RAM_ATTR __detachInterrupt(uint8_t pin) {
if(pin < 16) {
ETS_GPIO_INTR_DISABLE();
GPC(pin) &= ~(0xF << GPCI);//INT mode disabled
GPIEC = (1 << pin); //Clear Interrupt for this pin
interrupt_reg &= ~(1 << pin);
interrupt_handler_t *handler = &interrupt_handlers[pin];
handler->mode = 0;
handler->fn = 0;
if (handler->arg)
{
cleanupFunctional(handler->arg);
}
handler->arg = 0;
if (interrupt_reg)
ETS_GPIO_INTR_ENABLE();
}
}
void initPins() {
//Disable UART interrupts
system_set_os_print(0);
U0IE = 0;
U1IE = 0;
for (int i = 0; i <= 5; ++i) {
pinMode(i, INPUT);
}
// pins 6-11 are used for the SPI flash interface
for (int i = 12; i <= 16; ++i) {
pinMode(i, INPUT);
}
}
extern void pinMode(uint8_t pin, uint8_t mode) __attribute__ ((weak, alias("__pinMode")));
extern void digitalWrite(uint8_t pin, uint8_t val) __attribute__ ((weak, alias("__digitalWrite")));
extern int digitalRead(uint8_t pin) __attribute__ ((weak, alias("__digitalRead")));
extern void attachInterrupt(uint8_t pin, voidFuncPtr handler, int mode) __attribute__ ((weak, alias("__attachInterrupt")));
extern void detachInterrupt(uint8_t pin) __attribute__ ((weak, alias("__detachInterrupt")));
};
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2019 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <seastar/core/shared_ptr.hh>
#include <seastar/core/file.hh>
#include "seastarx.hh"
#include "db/timeout_clock.hh"
struct reader_resources {
int count = 0;
ssize_t memory = 0;
static reader_resources with_memory(ssize_t memory) { return reader_resources(0, memory); }
reader_resources() = default;
reader_resources(int count, ssize_t memory)
: count(count)
, memory(memory) {
}
bool operator>=(const reader_resources& other) const {
return count >= other.count && memory >= other.memory;
}
reader_resources operator-(const reader_resources& other) const {
return reader_resources{count - other.count, memory - other.memory};
}
reader_resources& operator-=(const reader_resources& other) {
count -= other.count;
memory -= other.memory;
return *this;
}
reader_resources operator+(const reader_resources& other) const {
return reader_resources{count + other.count, memory + other.memory};
}
reader_resources& operator+=(const reader_resources& other) {
count += other.count;
memory += other.memory;
return *this;
}
explicit operator bool() const {
return count > 0 || memory > 0;
}
};
class reader_concurrency_semaphore;
/// A permit for a specific read.
///
/// Used to track the read's resource consumption and wait for admission to read
/// from the disk.
/// Use `consume_memory()` to register memory usage. Use `wait_admission()` to
/// wait for admission, before reading from the disk. Both methods return a
/// `resource_units` RAII object that should be held onto while the respective
/// resources are in use.
class reader_permit {
friend class reader_concurrency_semaphore;
public:
class resource_units;
private:
class impl;
shared_ptr<impl> _impl;
private:
explicit reader_permit(reader_concurrency_semaphore& semaphore);
void on_admission();
public:
~reader_permit();
reader_permit(const reader_permit&) = default;
reader_permit(reader_permit&&) = default;
reader_permit& operator=(const reader_permit&) = default;
reader_permit& operator=(reader_permit&&) = default;
bool operator==(const reader_permit& o) const {
return _impl == o._impl;
}
reader_concurrency_semaphore& semaphore();
future<resource_units> wait_admission(size_t memory, db::timeout_clock::time_point timeout);
void consume(reader_resources res);
void signal(reader_resources res);
resource_units consume_memory(size_t memory = 0);
resource_units consume_resources(reader_resources res);
};
class reader_permit::resource_units {
reader_permit _permit;
reader_resources _resources;
friend class reader_permit;
friend class reader_concurrency_semaphore;
private:
resource_units(reader_permit permit, reader_resources res) noexcept;
public:
resource_units(const resource_units&) = delete;
resource_units(resource_units&&) noexcept;
~resource_units();
resource_units& operator=(const resource_units&) = delete;
resource_units& operator=(resource_units&&) noexcept;
void add(resource_units&& o);
void reset(reader_resources res = {});
reader_permit permit() const { return _permit; }
reader_resources resources() const { return _resources; }
};
template <typename Char>
temporary_buffer<Char> make_tracked_temporary_buffer(temporary_buffer<Char> buf, reader_permit& permit) {
return temporary_buffer<Char>(buf.get_write(), buf.size(),
make_deleter(buf.release(), [units = permit.consume_memory(buf.size())] () mutable { units.reset(); }));
}
file make_tracked_file(file f, reader_permit p);
template <typename T>
class tracking_allocator {
public:
using value_type = T;
using propagate_on_container_move_assignment = std::true_type;
using is_always_equal = std::false_type;
private:
reader_permit _permit;
std::allocator<T> _alloc;
public:
tracking_allocator(reader_permit permit) noexcept : _permit(std::move(permit)) { }
T* allocate(size_t n) {
auto p = _alloc.allocate(n);
_permit.consume(reader_resources::with_memory(n * sizeof(T)));
return p;
}
void deallocate(T* p, size_t n) {
_alloc.deallocate(p, n);
if (n) {
_permit.signal(reader_resources::with_memory(n * sizeof(T)));
}
}
template <typename U>
friend bool operator==(const tracking_allocator<U>& a, const tracking_allocator<U>& b);
};
template <typename T>
bool operator==(const tracking_allocator<T>& a, const tracking_allocator<T>& b) {
return a._semaphore == b._semaphore;
}
<commit_msg>reader_permit: reader_resources: add operator==<commit_after>/*
* Copyright (C) 2019 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla 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.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <seastar/core/shared_ptr.hh>
#include <seastar/core/file.hh>
#include "seastarx.hh"
#include "db/timeout_clock.hh"
struct reader_resources {
int count = 0;
ssize_t memory = 0;
static reader_resources with_memory(ssize_t memory) { return reader_resources(0, memory); }
reader_resources() = default;
reader_resources(int count, ssize_t memory)
: count(count)
, memory(memory) {
}
bool operator>=(const reader_resources& other) const {
return count >= other.count && memory >= other.memory;
}
reader_resources operator-(const reader_resources& other) const {
return reader_resources{count - other.count, memory - other.memory};
}
reader_resources& operator-=(const reader_resources& other) {
count -= other.count;
memory -= other.memory;
return *this;
}
reader_resources operator+(const reader_resources& other) const {
return reader_resources{count + other.count, memory + other.memory};
}
reader_resources& operator+=(const reader_resources& other) {
count += other.count;
memory += other.memory;
return *this;
}
explicit operator bool() const {
return count > 0 || memory > 0;
}
};
inline bool operator==(const reader_resources& a, const reader_resources& b) {
return a.count == b.count && a.memory == b.memory;
}
class reader_concurrency_semaphore;
/// A permit for a specific read.
///
/// Used to track the read's resource consumption and wait for admission to read
/// from the disk.
/// Use `consume_memory()` to register memory usage. Use `wait_admission()` to
/// wait for admission, before reading from the disk. Both methods return a
/// `resource_units` RAII object that should be held onto while the respective
/// resources are in use.
class reader_permit {
friend class reader_concurrency_semaphore;
public:
class resource_units;
private:
class impl;
shared_ptr<impl> _impl;
private:
explicit reader_permit(reader_concurrency_semaphore& semaphore);
void on_admission();
public:
~reader_permit();
reader_permit(const reader_permit&) = default;
reader_permit(reader_permit&&) = default;
reader_permit& operator=(const reader_permit&) = default;
reader_permit& operator=(reader_permit&&) = default;
bool operator==(const reader_permit& o) const {
return _impl == o._impl;
}
reader_concurrency_semaphore& semaphore();
future<resource_units> wait_admission(size_t memory, db::timeout_clock::time_point timeout);
void consume(reader_resources res);
void signal(reader_resources res);
resource_units consume_memory(size_t memory = 0);
resource_units consume_resources(reader_resources res);
};
class reader_permit::resource_units {
reader_permit _permit;
reader_resources _resources;
friend class reader_permit;
friend class reader_concurrency_semaphore;
private:
resource_units(reader_permit permit, reader_resources res) noexcept;
public:
resource_units(const resource_units&) = delete;
resource_units(resource_units&&) noexcept;
~resource_units();
resource_units& operator=(const resource_units&) = delete;
resource_units& operator=(resource_units&&) noexcept;
void add(resource_units&& o);
void reset(reader_resources res = {});
reader_permit permit() const { return _permit; }
reader_resources resources() const { return _resources; }
};
template <typename Char>
temporary_buffer<Char> make_tracked_temporary_buffer(temporary_buffer<Char> buf, reader_permit& permit) {
return temporary_buffer<Char>(buf.get_write(), buf.size(),
make_deleter(buf.release(), [units = permit.consume_memory(buf.size())] () mutable { units.reset(); }));
}
file make_tracked_file(file f, reader_permit p);
template <typename T>
class tracking_allocator {
public:
using value_type = T;
using propagate_on_container_move_assignment = std::true_type;
using is_always_equal = std::false_type;
private:
reader_permit _permit;
std::allocator<T> _alloc;
public:
tracking_allocator(reader_permit permit) noexcept : _permit(std::move(permit)) { }
T* allocate(size_t n) {
auto p = _alloc.allocate(n);
_permit.consume(reader_resources::with_memory(n * sizeof(T)));
return p;
}
void deallocate(T* p, size_t n) {
_alloc.deallocate(p, n);
if (n) {
_permit.signal(reader_resources::with_memory(n * sizeof(T)));
}
}
template <typename U>
friend bool operator==(const tracking_allocator<U>& a, const tracking_allocator<U>& b);
};
template <typename T>
bool operator==(const tracking_allocator<T>& a, const tracking_allocator<T>& b) {
return a._semaphore == b._semaphore;
}
<|endoftext|> |
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
#ident "Copyright (c) 2007-2012 Tokutek Inc. All rights reserved."
#ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it."
#include "locktree_unit_test.h"
#include <toku_time.h>
__attribute__((__unused__))
static long current_time_usec(void) {
struct timeval t;
gettimeofday(&t, NULL);
return t.tv_usec + t.tv_sec * 1000000;
}
namespace toku {
// test simple, non-overlapping read locks and then write locks
void locktree_unit_test::test_simple_lock(void) {
locktree::manager mgr;
mgr.create(nullptr, nullptr);
DESCRIPTOR desc = nullptr;
DICTIONARY_ID dict_id = { 1 };
locktree *lt = mgr.get_lt(dict_id, desc, compare_dbts, nullptr);
int r;
TXNID txnid_a = 1001;
TXNID txnid_b = 2001;
TXNID txnid_c = 3001;
TXNID txnid_d = 4001;
const DBT *one = get_dbt(1);
const DBT *two = get_dbt(2);
const DBT *three = get_dbt(3);
const DBT *four = get_dbt(4);
for (int test_run = 0; test_run < 2; test_run++) {
// test_run == 0 means test with read lock
// test_run == 1 means test with write lock
#define ACQUIRE_LOCK(txn, left, right, conflicts) \
test_run == 0 ? lt->acquire_read_lock(txn, left, right, conflicts) \
: lt->acquire_write_lock(txn, left, right, conflicts)
// four txns, four points
r = ACQUIRE_LOCK(txnid_a, one, one, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 1);
r = ACQUIRE_LOCK(txnid_b, two, two, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 2);
r = ACQUIRE_LOCK(txnid_c, three, three, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 3);
r = ACQUIRE_LOCK(txnid_d, four, four, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 4);
lt->remove_overlapping_locks_for_txnid(txnid_a, one, one);
invariant(num_row_locks(lt) == 3);
lt->remove_overlapping_locks_for_txnid(txnid_b, two, two);
invariant(num_row_locks(lt) == 2);
lt->remove_overlapping_locks_for_txnid(txnid_c, three, three);
invariant(num_row_locks(lt) == 1);
lt->remove_overlapping_locks_for_txnid(txnid_d, four, four);
invariant(num_row_locks(lt) == 0);
// two txns, two ranges
r = ACQUIRE_LOCK(txnid_c, one, two, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 1);
r = ACQUIRE_LOCK(txnid_b, three, four, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 2);
lt->remove_overlapping_locks_for_txnid(txnid_c, one, two);
invariant(num_row_locks(lt) == 1);
lt->remove_overlapping_locks_for_txnid(txnid_b, three, four);
invariant(num_row_locks(lt) == 0);
// one txn, one range, one point
r = ACQUIRE_LOCK(txnid_a, two, three, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 1);
r = ACQUIRE_LOCK(txnid_a, four, four, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 2);
lt->remove_overlapping_locks_for_txnid(txnid_a, two, three);
invariant(num_row_locks(lt) == 1);
lt->remove_overlapping_locks_for_txnid(txnid_a, four, four);
invariant(num_row_locks(lt) == 0);
// two txns, one range, one point
r = ACQUIRE_LOCK(txnid_c, three, four, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 1);
r = ACQUIRE_LOCK(txnid_d, one, one, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 2);
lt->remove_overlapping_locks_for_txnid(txnid_c, three, four);
invariant(num_row_locks(lt) == 1);
lt->remove_overlapping_locks_for_txnid(txnid_d, one, one);
invariant(num_row_locks(lt) == 0);
#undef ACQUIRE_LOCK
}
// TODO: test read locks from different txns that overlap!
#if 0
const int64_t num_locks = 1000000;
#else
const int64_t num_locks = 10000;
#endif
long t0, t1;
int64_t *keys = (int64_t *) toku_malloc(num_locks * sizeof(int64_t));
for (int64_t i = 0; i < num_locks; i++) {
keys[i] = i;
}
for (int64_t i = 0; i < num_locks; i++) {
int64_t k = rand() % num_locks;
int64_t tmp = keys[k];
keys[k] = keys[i];
keys[i] = tmp;
}
r = mgr.set_max_lock_memory((num_locks + 1) * 500);
invariant_zero(r);
DBT k;
k.ulen = 0;
k.size = sizeof(keys[0]);
k.flags = DB_DBT_USERMEM;
t0 = current_time_usec();
for (int64_t i = 0; i < num_locks; i++) {
k.data = (void *) &keys[i];
r = lt->acquire_read_lock(txnid_a, &k, &k, nullptr);
invariant(r == 0);
}
t1 = current_time_usec();
t0 = current_time_usec();
for (int64_t i = 0; i < num_locks; i++) {
k.data = (void *) &keys[i];
lt->remove_overlapping_locks_for_txnid(txnid_a, &k, &k);
}
t1 = current_time_usec();
toku_free(keys);
mgr.release_lt(lt);
mgr.destroy();
}
} /* namespace toku */
int main(void) {
toku::locktree_unit_test test;
test.test_simple_lock();
return 0;
}
<commit_msg>refs #5351 fix test<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
#ident "Copyright (c) 2007-2012 Tokutek Inc. All rights reserved."
#ident "The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11/760379 and to the patents and/or patent applications resulting from it."
#include "locktree_unit_test.h"
#include <toku_time.h>
__attribute__((__unused__))
static long current_time_usec(void) {
struct timeval t;
gettimeofday(&t, NULL);
return t.tv_usec + t.tv_sec * 1000000;
}
namespace toku {
// test simple, non-overlapping read locks and then write locks
void locktree_unit_test::test_simple_lock(void) {
locktree::manager mgr;
mgr.create(nullptr, nullptr);
DESCRIPTOR desc = nullptr;
DICTIONARY_ID dict_id = { 1 };
locktree *lt = mgr.get_lt(dict_id, desc, compare_dbts, nullptr);
int r;
TXNID txnid_a = 1001;
TXNID txnid_b = 2001;
TXNID txnid_c = 3001;
TXNID txnid_d = 4001;
const DBT *one = get_dbt(1);
const DBT *two = get_dbt(2);
const DBT *three = get_dbt(3);
const DBT *four = get_dbt(4);
for (int test_run = 0; test_run < 2; test_run++) {
// test_run == 0 means test with read lock
// test_run == 1 means test with write lock
#define ACQUIRE_LOCK(txn, left, right, conflicts) \
test_run == 0 ? lt->acquire_read_lock(txn, left, right, conflicts) \
: lt->acquire_write_lock(txn, left, right, conflicts)
// four txns, four points
r = ACQUIRE_LOCK(txnid_a, one, one, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 1);
r = ACQUIRE_LOCK(txnid_b, two, two, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 2);
r = ACQUIRE_LOCK(txnid_c, three, three, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 3);
r = ACQUIRE_LOCK(txnid_d, four, four, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 4);
lt->remove_overlapping_locks_for_txnid(txnid_a, one, one);
invariant(num_row_locks(lt) == 3);
lt->remove_overlapping_locks_for_txnid(txnid_b, two, two);
invariant(num_row_locks(lt) == 2);
lt->remove_overlapping_locks_for_txnid(txnid_c, three, three);
invariant(num_row_locks(lt) == 1);
lt->remove_overlapping_locks_for_txnid(txnid_d, four, four);
invariant(num_row_locks(lt) == 0);
// two txns, two ranges
r = ACQUIRE_LOCK(txnid_c, one, two, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 1);
r = ACQUIRE_LOCK(txnid_b, three, four, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 2);
lt->remove_overlapping_locks_for_txnid(txnid_c, one, two);
invariant(num_row_locks(lt) == 1);
lt->remove_overlapping_locks_for_txnid(txnid_b, three, four);
invariant(num_row_locks(lt) == 0);
// one txn, one range, one point
r = ACQUIRE_LOCK(txnid_a, two, three, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 1);
r = ACQUIRE_LOCK(txnid_a, four, four, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 2);
lt->remove_overlapping_locks_for_txnid(txnid_a, two, three);
invariant(num_row_locks(lt) == 1);
lt->remove_overlapping_locks_for_txnid(txnid_a, four, four);
invariant(num_row_locks(lt) == 0);
// two txns, one range, one point
r = ACQUIRE_LOCK(txnid_c, three, four, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 1);
r = ACQUIRE_LOCK(txnid_d, one, one, nullptr);
invariant(r == 0);
invariant(num_row_locks(lt) == 2);
lt->remove_overlapping_locks_for_txnid(txnid_c, three, four);
invariant(num_row_locks(lt) == 1);
lt->remove_overlapping_locks_for_txnid(txnid_d, one, one);
invariant(num_row_locks(lt) == 0);
#undef ACQUIRE_LOCK
}
const int64_t num_locks = 10000;
int64_t *keys = (int64_t *) toku_malloc(num_locks * sizeof(int64_t));
for (int64_t i = 0; i < num_locks; i++) {
keys[i] = i;
}
for (int64_t i = 0; i < num_locks; i++) {
int64_t k = rand() % num_locks;
int64_t tmp = keys[k];
keys[k] = keys[i];
keys[i] = tmp;
}
r = mgr.set_max_lock_memory((num_locks + 1) * 500);
invariant_zero(r);
DBT k;
k.ulen = 0;
k.size = sizeof(keys[0]);
k.flags = DB_DBT_USERMEM;
for (int64_t i = 0; i < num_locks; i++) {
k.data = (void *) &keys[i];
r = lt->acquire_read_lock(txnid_a, &k, &k, nullptr);
invariant(r == 0);
}
for (int64_t i = 0; i < num_locks; i++) {
k.data = (void *) &keys[i];
lt->remove_overlapping_locks_for_txnid(txnid_a, &k, &k);
}
toku_free(keys);
mgr.release_lt(lt);
mgr.destroy();
}
} /* namespace toku */
int main(void) {
toku::locktree_unit_test test;
test.test_simple_lock();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "miopen_common.h"
#include "gsl/gsl"
#include "core/providers/cpu/tensor/utils.h"
#include "core/providers/rocm/shared_inc/rocm_call.h"
namespace onnxruntime {
namespace rocm {
MiopenTensor::MiopenTensor()
: tensor_(nullptr) {
}
MiopenTensor::~MiopenTensor() {
if (tensor_ != nullptr) {
miopenDestroyTensorDescriptor(tensor_);
tensor_ = nullptr;
}
}
Status MiopenTensor::CreateTensorIfNeeded() {
if (!tensor_)
MIOPEN_RETURN_IF_ERROR(miopenCreateTensorDescriptor(&tensor_));
return Status::OK();
}
Status MiopenTensor::Set(gsl::span<const int64_t> input_dims, miopenDataType_t dataType) {
ORT_RETURN_IF_ERROR(CreateTensorIfNeeded());
int rank = gsl::narrow_cast<int>(input_dims.size());
TensorPitches pitches(input_dims);
InlinedVector<int> dims(rank);
InlinedVector<int> strides(rank);
for (int i = 0; i < rank; i++) {
dims[i] = gsl::narrow_cast<int>(input_dims[i]);
strides[i] = gsl::narrow_cast<int>(pitches[i]);
}
MIOPEN_RETURN_IF_ERROR(miopenSetTensorDescriptor(tensor_, dataType, static_cast<int>(rank), dims.data(), strides.data()));
return Status::OK();
}
Status MiopenTensor::Set(const MiopenTensor& x_desc, miopenBatchNormMode_t mode) {
ORT_RETURN_IF_ERROR(CreateTensorIfNeeded());
MIOPEN_RETURN_IF_ERROR(miopenDeriveBNTensorDescriptor(tensor_, x_desc, mode));
return Status::OK();
}
MiopenTensorDescriptor::MiopenTensorDescriptor() : desc_(nullptr) {
miopenCreateTensorDescriptor(&desc_);
}
MiopenTensorDescriptor::~MiopenTensorDescriptor() {
if (desc_ != nullptr) {
miopenCreateTensorDescriptor(&desc_);
desc_ = nullptr;
}
}
Status MiopenTensorDescriptor::Set(gsl::span<const int64_t> filter_dims, miopenDataType_t data_type) {
if (!desc_)
MIOPEN_RETURN_IF_ERROR(miopenCreateTensorDescriptor(&desc_));
int rank = gsl::narrow_cast<int>(filter_dims.size());
InlinedVector<int> w_dims(rank);
for (int i = 0; i < rank; i++) {
w_dims[i] = gsl::narrow_cast<int>(filter_dims[i]);
}
MIOPEN_RETURN_IF_ERROR(miopenSetTensorDescriptor(desc_,
data_type,
rank,
w_dims.data(),
nullptr));
return Status::OK();
}
template <typename ElemType>
miopenDataType_t MiopenTensor::GetDataType() {
ORT_THROW("miopen engine currently supports only single/half/int32/int8 precision data types.");
}
template<>
miopenDataType_t MiopenTensor::GetDataType<double>() {
return miopenDouble;
}
template<>
miopenDataType_t MiopenTensor::GetDataType<float>() {
return miopenFloat;
}
template <>
miopenDataType_t MiopenTensor::GetDataType<half>() {
return miopenHalf;
}
template <>
miopenDataType_t MiopenTensor::GetDataType<BFloat16>() {
ORT_THROW("miopen doesn't support BFloat16.");
return miopenFloat;
}
template <>
miopenDataType_t MiopenTensor::GetDataType<int32_t>() {
return miopenInt32;
}
template <>
miopenDataType_t MiopenTensor::GetDataType<int8_t>() {
return miopenInt8;
}
template <>
const float Consts<float>::One = 1;
template <>
const double Consts<double>::One = 1;
template <>
const float Consts<float>::Zero = 0;
template <>
const double Consts<double>::Zero = 0;
const float Consts<half>::Zero = 0;
const float Consts<half>::One = 1;
const float Consts<BFloat16>::Zero = 0;
const float Consts<BFloat16>::One = 1;
#if ROCM_VERSION >= 40300
const float ReduceConsts<half>::One = 1;
const float ReduceConsts<half>::Zero = 0;
const float ReduceConsts<BFloat16>::One = 1;
const float ReduceConsts<BFloat16>::Zero = 0;
#else
// Up until ROCm 4.2, miopenReduceTensor() required alpha/beta to be the same data
// type as the input type. This differs from cudnnReduceTensor() and other
// MIOpen/cuDNN APIs where alpha/beta are float when input type is half (float16).
template <>
const half ReduceConsts<half>::One = 1.f;
template <>
const half ReduceConsts<half>::Zero = 0.f;
template <>
const BFloat16 ReduceConsts<BFloat16>::One = 1.f;
template <>
const BFloat16 ReduceConsts<BFloat16>::Zero = 0.f;
#endif
template <>
const float ReduceConsts<float>::One = 1;
template <>
const double ReduceConsts<double>::One = 1;
template <>
const float ReduceConsts<float>::Zero = 0;
template <>
const double ReduceConsts<double>::Zero = 0;
} // namespace rocm
} // namespace onnxruntime
<commit_msg>Fix Python Packaging CI (Rocm) (#12477)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "miopen_common.h"
#include "gsl/gsl"
#include "core/providers/cpu/tensor/utils.h"
#include "core/providers/rocm/shared_inc/rocm_call.h"
namespace onnxruntime {
namespace rocm {
MiopenTensor::MiopenTensor()
: tensor_(nullptr) {
}
MiopenTensor::~MiopenTensor() {
if (tensor_ != nullptr) {
miopenDestroyTensorDescriptor(tensor_);
tensor_ = nullptr;
}
}
Status MiopenTensor::CreateTensorIfNeeded() {
if (!tensor_)
MIOPEN_RETURN_IF_ERROR(miopenCreateTensorDescriptor(&tensor_));
return Status::OK();
}
Status MiopenTensor::Set(gsl::span<const int64_t> input_dims, miopenDataType_t dataType) {
ORT_RETURN_IF_ERROR(CreateTensorIfNeeded());
int rank = gsl::narrow_cast<int>(input_dims.size());
TensorPitches pitches(input_dims);
InlinedVector<int> dims(rank);
InlinedVector<int> strides(rank);
for (int i = 0; i < rank; i++) {
dims[i] = gsl::narrow_cast<int>(input_dims[i]);
strides[i] = gsl::narrow_cast<int>(pitches[i]);
}
MIOPEN_RETURN_IF_ERROR(miopenSetTensorDescriptor(tensor_, dataType, static_cast<int>(rank), dims.data(), strides.data()));
return Status::OK();
}
Status MiopenTensor::Set(const MiopenTensor& x_desc, miopenBatchNormMode_t mode) {
ORT_RETURN_IF_ERROR(CreateTensorIfNeeded());
MIOPEN_RETURN_IF_ERROR(miopenDeriveBNTensorDescriptor(tensor_, x_desc, mode));
return Status::OK();
}
MiopenTensorDescriptor::MiopenTensorDescriptor() : desc_(nullptr) {
miopenCreateTensorDescriptor(&desc_);
}
MiopenTensorDescriptor::~MiopenTensorDescriptor() {
if (desc_ != nullptr) {
miopenCreateTensorDescriptor(&desc_);
desc_ = nullptr;
}
}
Status MiopenTensorDescriptor::Set(gsl::span<const int64_t> filter_dims, miopenDataType_t data_type) {
if (!desc_)
MIOPEN_RETURN_IF_ERROR(miopenCreateTensorDescriptor(&desc_));
int rank = gsl::narrow_cast<int>(filter_dims.size());
InlinedVector<int> w_dims(rank);
for (int i = 0; i < rank; i++) {
w_dims[i] = gsl::narrow_cast<int>(filter_dims[i]);
}
MIOPEN_RETURN_IF_ERROR(miopenSetTensorDescriptor(desc_,
data_type,
rank,
w_dims.data(),
nullptr));
return Status::OK();
}
template <typename ElemType>
miopenDataType_t MiopenTensor::GetDataType() {
ORT_THROW("miopen engine currently supports only single/half/int32/int8 precision data types.");
}
#if ROCM_VERSION >= 50000
template<>
miopenDataType_t MiopenTensor::GetDataType<double>() {
return miopenDouble;
}
#endif
template<>
miopenDataType_t MiopenTensor::GetDataType<float>() {
return miopenFloat;
}
template <>
miopenDataType_t MiopenTensor::GetDataType<half>() {
return miopenHalf;
}
template <>
miopenDataType_t MiopenTensor::GetDataType<BFloat16>() {
ORT_THROW("miopen doesn't support BFloat16.");
return miopenFloat;
}
template <>
miopenDataType_t MiopenTensor::GetDataType<int32_t>() {
return miopenInt32;
}
template <>
miopenDataType_t MiopenTensor::GetDataType<int8_t>() {
return miopenInt8;
}
template <>
const float Consts<float>::One = 1;
template <>
const double Consts<double>::One = 1;
template <>
const float Consts<float>::Zero = 0;
template <>
const double Consts<double>::Zero = 0;
const float Consts<half>::Zero = 0;
const float Consts<half>::One = 1;
const float Consts<BFloat16>::Zero = 0;
const float Consts<BFloat16>::One = 1;
#if ROCM_VERSION >= 40300
const float ReduceConsts<half>::One = 1;
const float ReduceConsts<half>::Zero = 0;
const float ReduceConsts<BFloat16>::One = 1;
const float ReduceConsts<BFloat16>::Zero = 0;
#else
// Up until ROCm 4.2, miopenReduceTensor() required alpha/beta to be the same data
// type as the input type. This differs from cudnnReduceTensor() and other
// MIOpen/cuDNN APIs where alpha/beta are float when input type is half (float16).
template <>
const half ReduceConsts<half>::One = 1.f;
template <>
const half ReduceConsts<half>::Zero = 0.f;
template <>
const BFloat16 ReduceConsts<BFloat16>::One = 1.f;
template <>
const BFloat16 ReduceConsts<BFloat16>::Zero = 0.f;
#endif
template <>
const float ReduceConsts<float>::One = 1;
template <>
const double ReduceConsts<double>::One = 1;
template <>
const float ReduceConsts<float>::Zero = 0;
template <>
const double ReduceConsts<double>::Zero = 0;
} // namespace rocm
} // namespace onnxruntime
<|endoftext|> |
<commit_before>// Copyright (c) 2009 hp-FEM group at the University of Nevada, Reno (UNR).
// Distributed under the terms of the BSD license (see the LICENSE
// file for the exact terms).
// Email: hermes1d@googlegroups.com, home page: http://hpfem.org/
#include "matrix.h"
#include "solvers.h"
#ifdef COMMON_WITH_UMFPACK
#include <umfpack.h>
double control_array[UMFPACK_CONTROL];
double info_array[UMFPACK_INFO];
void print_status(int status)
{
switch (status)
{
case UMFPACK_OK:
break;
case UMFPACK_WARNING_singular_matrix:
_error("UMFPACK: singular stiffness matrix!");
break;
case UMFPACK_ERROR_out_of_memory: _error("UMFPACK: out of memory!");
case UMFPACK_ERROR_argument_missing: _error("UMFPACK: argument missing");
case UMFPACK_ERROR_invalid_Symbolic_object: _error("UMFPACK: invalid Symbolic object");
case UMFPACK_ERROR_invalid_Numeric_object: _error("UMFPACK: invalid Numeric object");
case UMFPACK_ERROR_different_pattern: _error("UMFPACK: different pattern");
case UMFPACK_ERROR_invalid_system: _error("UMFPACK: invalid system");
case UMFPACK_ERROR_n_nonpositive: _error("UMFPACK: n nonpositive");
case UMFPACK_ERROR_invalid_matrix: _error("UMFPACK: invalid matrix");
case UMFPACK_ERROR_internal_error: _error("UMFPACK: internal error");
default: _error("UMFPACK: unknown error");
}
}
bool CommonSolverUmfpack::solve(Matrix *mat, double *res)
{
printf("UMFPACK solver\n");
CSCMatrix *Acsc = NULL;
if (CooMatrix *mcoo = dynamic_cast<CooMatrix*>(mat))
Acsc = new CSCMatrix(mcoo);
else if (CSCMatrix *mcsc = dynamic_cast<CSCMatrix*>(mat))
Acsc = mcsc;
else if (CSRMatrix *mcsr = dynamic_cast<CSRMatrix*>(mat))
Acsc = new CSCMatrix(mcsr);
else
_error("Matrix type not supported.");
int nnz = Acsc->get_nnz();
int size = Acsc->get_size();
// solve
umfpack_di_defaults(control_array);
/* symbolic analysis */
void *symbolic, *numeric;
int status_symbolic = umfpack_di_symbolic(size, size,
Acsc->get_Ap(), Acsc->get_Ai(), NULL, &symbolic,
control_array, info_array);
print_status(status_symbolic);
/* LU factorization */
int status_numeric = umfpack_di_numeric(Acsc->get_Ap(), Acsc->get_Ai(), Acsc->get_Ax(), symbolic, &numeric,
control_array, info_array);
print_status(status_numeric);
umfpack_di_free_symbolic(&symbolic);
double *x;
x = (double*) malloc(size * sizeof(double));
/* solve system */
int status_solve = umfpack_di_solve(UMFPACK_A,
Acsc->get_Ap(), Acsc->get_Ai(), Acsc->get_Ax(), x, res, numeric,
control_array, info_array);
print_status(status_solve);
umfpack_di_free_numeric(&numeric);
if (symbolic) umfpack_di_free_symbolic(&symbolic);
if (numeric) umfpack_di_free_numeric(&numeric);
memcpy(res, x, size*sizeof(double));
delete[] x;
if (!dynamic_cast<CSCMatrix*>(mat))
delete Acsc;
}
bool CommonSolverUmfpack::solve(Matrix *mat, cplx *res)
{
printf("UMFPACK solver - cplx\n");
CSCMatrix *Acsc = NULL;
if (CooMatrix *mcoo = dynamic_cast<CooMatrix*>(mat))
Acsc = new CSCMatrix(mcoo);
else if (CSCMatrix *mcsc = dynamic_cast<CSCMatrix*>(mat))
Acsc = mcsc;
else if (CSRMatrix *mcsr = dynamic_cast<CSRMatrix*>(mat))
Acsc = new CSCMatrix(mcsr);
else
_error("Matrix type not supported.");
int nnz = Acsc->get_nnz();
int size = Acsc->get_size();
// complex components
double *Axr = new double[nnz];
double *Axi = new double[nnz];
cplx *Ax = Acsc->get_Ax_cplx();
for (int i = 0; i < nnz; i++)
{
Axr[i] = Ax[i].real();
Axi[i] = Ax[i].imag();
}
umfpack_zi_defaults(control_array);
/* symbolic analysis */
void *symbolic, *numeric;
int status_symbolic = umfpack_zi_symbolic(size, size,
Acsc->get_Ap(), Acsc->get_Ai(), NULL, NULL, &symbolic,
control_array, info_array);
print_status(status_symbolic);
/* LU factorization */
int status_numeric = umfpack_zi_numeric(Acsc->get_Ap(), Acsc->get_Ai(), Axr, Axi, symbolic, &numeric,
control_array, info_array);
print_status(status_numeric);
umfpack_zi_free_symbolic(&symbolic);
double *xr, *xi;
xr = (double*) malloc(size * sizeof(double));
xi = (double*) malloc(size * sizeof(double));
double *resr = new double[size];
double *resi = new double[size];
for (int i = 0; i < size; i++)
{
resr[i] = res[i].real();
resi[i] = res[i].imag();
}
/* solve system */
int status_solve = umfpack_zi_solve(UMFPACK_A,
Acsc->get_Ap(), Acsc->get_Ai(), Axr, Axi, xr, xi, resr, resi, numeric,
control_array, info_array);
print_status(status_solve);
umfpack_zi_free_numeric(&numeric);
delete[] resr;
delete[] resi;
delete[] Axr;
delete[] Axi;
if (symbolic) umfpack_di_free_symbolic(&symbolic);
if (numeric) umfpack_di_free_numeric(&numeric);
for (int i = 0; i < Acsc->get_size(); i++)
res[i] = cplx(xr[i], xi[i]);
delete xr;
delete xi;
if (!dynamic_cast<CSCMatrix*>(mat))
delete Acsc;
}
#else
bool CommonSolverUmfpack::solve(Matrix *mat, double *res)
{
_error("CommonSolverUmfpack::solve(Matrix *mat, double *res) not implemented.");
}
bool CommonSolverUmfpack::solve(Matrix *mat, cplx *res)
{
_error("CommonSolverUmfpack::solve(Matrix *mat, cplx *res) not implemented.");
}
#endif
<commit_msg>Fixed free memory in umfpack_solver<commit_after>// Copyright (c) 2009 hp-FEM group at the University of Nevada, Reno (UNR).
// Distributed under the terms of the BSD license (see the LICENSE
// file for the exact terms).
// Email: hermes1d@googlegroups.com, home page: http://hpfem.org/
#include "matrix.h"
#include "solvers.h"
#ifdef COMMON_WITH_UMFPACK
#include <umfpack.h>
double control_array[UMFPACK_CONTROL];
double info_array[UMFPACK_INFO];
void print_status(int status)
{
switch (status)
{
case UMFPACK_OK:
break;
case UMFPACK_WARNING_singular_matrix:
_error("UMFPACK: singular stiffness matrix!");
break;
case UMFPACK_ERROR_out_of_memory: _error("UMFPACK: out of memory!");
case UMFPACK_ERROR_argument_missing: _error("UMFPACK: argument missing");
case UMFPACK_ERROR_invalid_Symbolic_object: _error("UMFPACK: invalid Symbolic object");
case UMFPACK_ERROR_invalid_Numeric_object: _error("UMFPACK: invalid Numeric object");
case UMFPACK_ERROR_different_pattern: _error("UMFPACK: different pattern");
case UMFPACK_ERROR_invalid_system: _error("UMFPACK: invalid system");
case UMFPACK_ERROR_n_nonpositive: _error("UMFPACK: n nonpositive");
case UMFPACK_ERROR_invalid_matrix: _error("UMFPACK: invalid matrix");
case UMFPACK_ERROR_internal_error: _error("UMFPACK: internal error");
default: _error("UMFPACK: unknown error");
}
}
bool CommonSolverUmfpack::solve(Matrix *mat, double *res)
{
printf("UMFPACK solver\n");
CSCMatrix *Acsc = NULL;
if (CooMatrix *mcoo = dynamic_cast<CooMatrix*>(mat))
Acsc = new CSCMatrix(mcoo);
else if (CSCMatrix *mcsc = dynamic_cast<CSCMatrix*>(mat))
Acsc = mcsc;
else if (CSRMatrix *mcsr = dynamic_cast<CSRMatrix*>(mat))
Acsc = new CSCMatrix(mcsr);
else
_error("Matrix type not supported.");
int nnz = Acsc->get_nnz();
int size = Acsc->get_size();
// solve
umfpack_di_defaults(control_array);
/* symbolic analysis */
void *symbolic, *numeric;
int status_symbolic = umfpack_di_symbolic(size, size,
Acsc->get_Ap(), Acsc->get_Ai(), NULL, &symbolic,
control_array, info_array);
print_status(status_symbolic);
/* LU factorization */
int status_numeric = umfpack_di_numeric(Acsc->get_Ap(), Acsc->get_Ai(), Acsc->get_Ax(), symbolic, &numeric,
control_array, info_array);
print_status(status_numeric);
umfpack_di_free_symbolic(&symbolic);
double *x = new double[size];
/* solve system */
int status_solve = umfpack_di_solve(UMFPACK_A,
Acsc->get_Ap(), Acsc->get_Ai(), Acsc->get_Ax(), x, res, numeric,
control_array, info_array);
print_status(status_solve);
umfpack_di_free_numeric(&numeric);
if (symbolic) umfpack_di_free_symbolic(&symbolic);
if (numeric) umfpack_di_free_numeric(&numeric);
memcpy(res, x, size*sizeof(double));
delete[] x;
if (!dynamic_cast<CSCMatrix*>(mat))
delete Acsc;
}
bool CommonSolverUmfpack::solve(Matrix *mat, cplx *res)
{
printf("UMFPACK solver - cplx\n");
CSCMatrix *Acsc = NULL;
if (CooMatrix *mcoo = dynamic_cast<CooMatrix*>(mat))
Acsc = new CSCMatrix(mcoo);
else if (CSCMatrix *mcsc = dynamic_cast<CSCMatrix*>(mat))
Acsc = mcsc;
else if (CSRMatrix *mcsr = dynamic_cast<CSRMatrix*>(mat))
Acsc = new CSCMatrix(mcsr);
else
_error("Matrix type not supported.");
int nnz = Acsc->get_nnz();
int size = Acsc->get_size();
// complex components
double *Axr = new double[nnz];
double *Axi = new double[nnz];
cplx *Ax = Acsc->get_Ax_cplx();
for (int i = 0; i < nnz; i++)
{
Axr[i] = Ax[i].real();
Axi[i] = Ax[i].imag();
}
umfpack_zi_defaults(control_array);
/* symbolic analysis */
void *symbolic, *numeric;
int status_symbolic = umfpack_zi_symbolic(size, size,
Acsc->get_Ap(), Acsc->get_Ai(), NULL, NULL, &symbolic,
control_array, info_array);
print_status(status_symbolic);
/* LU factorization */
int status_numeric = umfpack_zi_numeric(Acsc->get_Ap(), Acsc->get_Ai(), Axr, Axi, symbolic, &numeric,
control_array, info_array);
print_status(status_numeric);
umfpack_zi_free_symbolic(&symbolic);
double *xr = new double[size];
double *xi = new double[size];
double *resr = new double[size];
double *resi = new double[size];
for (int i = 0; i < size; i++)
{
resr[i] = res[i].real();
resi[i] = res[i].imag();
}
/* solve system */
int status_solve = umfpack_zi_solve(UMFPACK_A,
Acsc->get_Ap(), Acsc->get_Ai(), Axr, Axi, xr, xi, resr, resi, numeric,
control_array, info_array);
print_status(status_solve);
umfpack_zi_free_numeric(&numeric);
delete[] resr;
delete[] resi;
delete[] Axr;
delete[] Axi;
if (symbolic) umfpack_di_free_symbolic(&symbolic);
if (numeric) umfpack_di_free_numeric(&numeric);
for (int i = 0; i < Acsc->get_size(); i++)
res[i] = cplx(xr[i], xi[i]);
delete[] xr;
delete[] xi;
if (!dynamic_cast<CSCMatrix*>(mat))
delete Acsc;
}
#else
bool CommonSolverUmfpack::solve(Matrix *mat, double *res)
{
_error("CommonSolverUmfpack::solve(Matrix *mat, double *res) not implemented.");
}
bool CommonSolverUmfpack::solve(Matrix *mat, cplx *res)
{
_error("CommonSolverUmfpack::solve(Matrix *mat, cplx *res) not implemented.");
}
#endif
<|endoftext|> |
<commit_before>static int cmp(int a, int b);
#include "../src/vector_brodnik.h"
#include "../src/vector_bagwell.h"
#include "../src/vector_block.h"
#include "../src/vector_realloc.h"
#include "../src/vector_malloc.h"
#include "../src/losertree.h"
#include "../src/routines.h"
#include "../src/util/insertion_sort.h"
#include <iostream>
#include <array>
#include <vector>
#include <utility>
#undef NDEBUG
#include <cassert>
template <typename Container>
void test_basics()
{
std::cerr<<__PRETTY_FUNCTION__<<std::endl;
{
Container v;
assert(v.size()==0);
}
{
Container v;
v.push_back(1);
assert(v.size()==1);
assert(v[0]==1);
}
{
Container v;
const unsigned N=1000000;
for (unsigned i=0; i < N; ++i) {
assert(v.size()==i);
v.push_back(i);
assert(unsigned(v[i])==i);
}
assert(v.size()==N);
}
{
Container v;
const unsigned N=1000000;
for (unsigned i=0; i < N; ++i) v.push_back(i);
for (unsigned i=0; i < N; ++i) assert(unsigned(v[i])==i);
v.clear();
assert(v.size()==0);
for (unsigned i=0; i < N; ++i) v.push_back(i);
for (unsigned i=0; i < N; ++i) assert(unsigned(v[i])==i);
v.clear();
assert(v.size()==0);
for (unsigned i=0; i < N; ++i) v.push_back(i);
for (unsigned i=0; i < N; ++i) assert(unsigned(v[i])==i);
v.clear();
assert(v.size()==0);
}
}
static int cmp(int a, int b)
{
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
static void
test_loser_tree()
{
std::cerr<<__PRETTY_FUNCTION__<<std::endl;
{
std::array<int, 5> seq1 = { 2, 4, 6, 8, 10 };
std::array<int, 5> seq2 = { 3, 5, 7, 9, 11 };
std::vector<std::pair<int*, size_t> > seqs;
seqs.push_back(std::make_pair(seq1.data(), 5));
seqs.push_back(std::make_pair(seq2.data(), 5));
loser_tree<int> tree(seqs.begin(), seqs.end());
assert(tree._nonempty_streams == 2);
assert(tree.min() == 2); assert(tree._nonempty_streams == 2);
assert(tree.min() == 3); assert(tree._nonempty_streams == 2);
assert(tree.min() == 4); assert(tree._nonempty_streams == 2);
assert(tree.min() == 5); assert(tree._nonempty_streams == 2);
assert(tree.min() == 6); assert(tree._nonempty_streams == 2);
assert(tree.min() == 7); assert(tree._nonempty_streams == 2);
assert(tree.min() == 8); assert(tree._nonempty_streams == 2);
assert(tree.min() == 9); assert(tree._nonempty_streams == 2);
assert(tree.min() == 10); assert(tree._nonempty_streams == 1);
assert(tree.min() == 11); assert(tree._nonempty_streams == 0);
}
{
std::array<int, 3> seq1 = { 2, 5, 8 };
std::array<int, 3> seq2 = { 3, 6, 9 };
std::array<int, 3> seq3 = { 4, 7, 10 };
std::vector<std::pair<int*, size_t> > seqs;
seqs.push_back(std::make_pair(seq1.data(), 3));
seqs.push_back(std::make_pair(seq2.data(), 3));
seqs.push_back(std::make_pair(seq3.data(), 3));
loser_tree<int> tree(seqs.begin(), seqs.end());
assert(tree._nonempty_streams == 3);
assert(tree.min() == 2); assert(tree._nonempty_streams == 3);
assert(tree.min() == 3); assert(tree._nonempty_streams == 3);
assert(tree.min() == 4); assert(tree._nonempty_streams == 3);
assert(tree.min() == 5); assert(tree._nonempty_streams == 3);
assert(tree.min() == 6); assert(tree._nonempty_streams == 3);
assert(tree.min() == 7); assert(tree._nonempty_streams == 3);
assert(tree.min() == 8); assert(tree._nonempty_streams == 2);
assert(tree.min() == 9); assert(tree._nonempty_streams == 1);
assert(tree.min() == 10); assert(tree._nonempty_streams == 0);
}
{
std::array<int, 3> seq1 = { 2, 5, 8 };
std::array<int, 3> seq2 = { 3, 6, 9 };
std::array<int, 3> seq3 = { 4, 7, 10 };
std::vector<std::pair<int*, size_t> > seqs;
seqs.push_back(std::make_pair(seq3.data(), 3));
seqs.push_back(std::make_pair(seq2.data(), 3));
seqs.push_back(std::make_pair(seq1.data(), 3));
loser_tree<int> tree(seqs.begin(), seqs.end());
assert(tree._nonempty_streams == 3);
assert(tree.min() == 2); assert(tree._nonempty_streams == 3);
assert(tree.min() == 3); assert(tree._nonempty_streams == 3);
assert(tree.min() == 4); assert(tree._nonempty_streams == 3);
assert(tree.min() == 5); assert(tree._nonempty_streams == 3);
assert(tree.min() == 6); assert(tree._nonempty_streams == 3);
assert(tree.min() == 7); assert(tree._nonempty_streams == 3);
assert(tree.min() == 8); assert(tree._nonempty_streams == 2);
assert(tree.min() == 9); assert(tree._nonempty_streams == 1);
assert(tree.min() == 10); assert(tree._nonempty_streams == 0);
}
{
const unsigned items = 32;
std::vector<std::vector<int> > data(25000);
for (unsigned i=0; i < data.size(); ++i) {
for (unsigned j=0; j < items; ++j) {
data[i].push_back(j);
}
}
std::vector<std::pair<int*, size_t> > seqs;
for (unsigned i=0; i < data.size(); ++i) {
seqs.push_back(std::make_pair(data[i].data(), items));
}
loser_tree<int> tree(seqs.begin(), seqs.end());
assert(tree._nonempty_streams == data.size());
for (unsigned i=0; i < items; ++i) {
for (unsigned j=0; j < data.size(); ++j) {
assert(tree.min() == int(i));
}
}
assert(tree._nonempty_streams == 0);
}
}
static void
test_insertion_sort()
{
std::cerr<<__PRETTY_FUNCTION__<<std::endl;
{
std::array<const char *, 0> input;
insertion_sort((unsigned char **)input.data(), input.size(), 0);
}
{
std::array<const char *, 1> input = {""};
insertion_sort((unsigned char **)input.data(), input.size(), 0);
}
{
std::array<const char *, 5> input = {
"c",
"",
"bbaaa",
"aaaaa",
"bbbbb",
};
insertion_sort((unsigned char **)input.data(), input.size(), 0);
assert(strcmp(input[0], "") == 0);
assert(strcmp(input[1], "aaaaa") == 0);
assert(strcmp(input[2], "bbaaa") == 0);
assert(strcmp(input[3], "bbbbb") == 0);
assert(strcmp(input[4], "c") == 0);
insertion_sort((unsigned char **)input.data(), input.size(), 0);
assert(strcmp(input[0], "") == 0);
assert(strcmp(input[1], "aaaaa") == 0);
assert(strcmp(input[2], "bbaaa") == 0);
assert(strcmp(input[3], "bbbbb") == 0);
assert(strcmp(input[4], "c") == 0);
}
{
std::array<const char *, 3> input = {
"bbbb1",
"aaaa3",
"aaaa2",
};
insertion_sort((unsigned char **)input.data(), input.size(), 4);
assert(strcmp(input[0], "bbbb1") == 0);
assert(strcmp(input[1], "aaaa2") == 0);
assert(strcmp(input[2], "aaaa3") == 0);
}
}
static void
test_routines()
{
std::cerr<<__PRETTY_FUNCTION__<<std::endl;
const struct routine **routines;
unsigned routines_cnt;
routine_get_all(&routines, &routines_cnt);
for (unsigned i=0; i < routines_cnt; ++i) {
std::cerr << __PRETTY_FUNCTION__
<< " [" << routines[i]->name << ']' << std::endl;
for (size_t k=1; k < 2000; k += 200) {
std::vector<char *> input;
for (size_t i=0; i < k; ++i)
input.push_back(strdup("aaa"));
const size_t n = input.size();
routines[i]->f((unsigned char **)input.data(), n);
for (size_t i=0; i < n; ++i)
assert(strcmp(input[i], "aaa") == 0);
assert(check_result((unsigned char**)input.data(), n) == 0);
for (size_t i=0; i < n; ++i)
free(input[i]);
}
for (size_t k=1; k < 1000; k += 200) {
std::vector<char *> input;
for (size_t i=0; i < k; ++i) {
input.push_back(strdup("bb"));
input.push_back(strdup("a"));
input.push_back(strdup("bbb"));
}
const size_t n = input.size();
routines[i]->f((unsigned char **)input.data(), n);
for (size_t i=0*(n/3); i < 1*(n/3); ++i)
assert(strcmp(input[i], "a") == 0);
for (size_t i=1*(n/3); i < 2*(n/3); ++i)
assert(strcmp(input[i], "bb") == 0);
for (size_t i=2*(n/3); i < 3*(n/3); ++i)
assert(strcmp(input[i], "bbb") == 0);
assert(check_result((unsigned char**)input.data(), n) == 0);
for (size_t i=0; i < n; ++i)
free(input[i]);
}
for (size_t k=1; k < 10000; k += 2000) {
std::vector<char *> input;
for (size_t i=0; i < k; ++i) {
char buf[10];
memset(buf, 'a'+(i%30), sizeof(buf)-1);
buf[sizeof(buf)-1] = 0;
input.push_back(strdup(buf));
}
const size_t n = input.size();
routines[i]->f((unsigned char **)input.data(), n);
// for (size_t i=0; i < n; ++i) std::cerr<<input[i]<<'\n';
assert(check_result((unsigned char**)input.data(), n) == 0);
for (size_t i=0; i < n; ++i)
free(input[i]);
}
}
}
struct OK { ~OK() { std::cerr << "*** All OK ***\n"; } };
int main()
{
OK ok;
test_loser_tree();
test_basics<vector_brodnik<int> >();
test_basics<vector_bagwell<int> >();
test_basics<vector_block<int> >();
test_basics<vector_malloc<int> >();
test_basics<vector_malloc_counter_clear<int> >();
test_basics<vector_realloc<int> >();
test_basics<vector_realloc_counter_clear<int> >();
test_basics<vector_realloc_shrink_clear<int> >();
test_basics<vector_brodnik<uint64_t> >();
test_basics<vector_bagwell<uint64_t> >();
test_basics<vector_block<uint64_t> >();
test_basics<vector_malloc<uint64_t> >();
test_basics<vector_malloc_counter_clear<uint64_t> >();
test_basics<vector_realloc<uint64_t> >();
test_basics<vector_realloc_counter_clear<uint64_t> >();
test_basics<vector_realloc_shrink_clear<uint64_t> >();
test_insertion_sort();
test_routines();
}
<commit_msg>Fix unit-test insertion sort assertion failures<commit_after>static int cmp(int a, int b);
#include "../src/vector_brodnik.h"
#include "../src/vector_bagwell.h"
#include "../src/vector_block.h"
#include "../src/vector_realloc.h"
#include "../src/vector_malloc.h"
#include "../src/losertree.h"
#include "../src/routines.h"
#include "../src/util/insertion_sort.h"
#include <iostream>
#include <array>
#include <vector>
#include <utility>
#undef NDEBUG
#include <cassert>
template <typename Ch1, typename Ch2>
static int strcmp_u(Ch1 *a, Ch2 *b)
{
return strcmp((const char*)a, (const char*)b);
}
template <typename Container>
void test_basics()
{
std::cerr<<__PRETTY_FUNCTION__<<std::endl;
{
Container v;
assert(v.size()==0);
}
{
Container v;
v.push_back(1);
assert(v.size()==1);
assert(v[0]==1);
}
{
Container v;
const unsigned N=1000000;
for (unsigned i=0; i < N; ++i) {
assert(v.size()==i);
v.push_back(i);
assert(unsigned(v[i])==i);
}
assert(v.size()==N);
}
{
Container v;
const unsigned N=1000000;
for (unsigned i=0; i < N; ++i) v.push_back(i);
for (unsigned i=0; i < N; ++i) assert(unsigned(v[i])==i);
v.clear();
assert(v.size()==0);
for (unsigned i=0; i < N; ++i) v.push_back(i);
for (unsigned i=0; i < N; ++i) assert(unsigned(v[i])==i);
v.clear();
assert(v.size()==0);
for (unsigned i=0; i < N; ++i) v.push_back(i);
for (unsigned i=0; i < N; ++i) assert(unsigned(v[i])==i);
v.clear();
assert(v.size()==0);
}
}
static int cmp(int a, int b)
{
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
static void
test_loser_tree()
{
std::cerr<<__PRETTY_FUNCTION__<<std::endl;
{
std::array<int, 5> seq1 = { 2, 4, 6, 8, 10 };
std::array<int, 5> seq2 = { 3, 5, 7, 9, 11 };
std::vector<std::pair<int*, size_t> > seqs;
seqs.push_back(std::make_pair(seq1.data(), 5));
seqs.push_back(std::make_pair(seq2.data(), 5));
loser_tree<int> tree(seqs.begin(), seqs.end());
assert(tree._nonempty_streams == 2);
assert(tree.min() == 2); assert(tree._nonempty_streams == 2);
assert(tree.min() == 3); assert(tree._nonempty_streams == 2);
assert(tree.min() == 4); assert(tree._nonempty_streams == 2);
assert(tree.min() == 5); assert(tree._nonempty_streams == 2);
assert(tree.min() == 6); assert(tree._nonempty_streams == 2);
assert(tree.min() == 7); assert(tree._nonempty_streams == 2);
assert(tree.min() == 8); assert(tree._nonempty_streams == 2);
assert(tree.min() == 9); assert(tree._nonempty_streams == 2);
assert(tree.min() == 10); assert(tree._nonempty_streams == 1);
assert(tree.min() == 11); assert(tree._nonempty_streams == 0);
}
{
std::array<int, 3> seq1 = { 2, 5, 8 };
std::array<int, 3> seq2 = { 3, 6, 9 };
std::array<int, 3> seq3 = { 4, 7, 10 };
std::vector<std::pair<int*, size_t> > seqs;
seqs.push_back(std::make_pair(seq1.data(), 3));
seqs.push_back(std::make_pair(seq2.data(), 3));
seqs.push_back(std::make_pair(seq3.data(), 3));
loser_tree<int> tree(seqs.begin(), seqs.end());
assert(tree._nonempty_streams == 3);
assert(tree.min() == 2); assert(tree._nonempty_streams == 3);
assert(tree.min() == 3); assert(tree._nonempty_streams == 3);
assert(tree.min() == 4); assert(tree._nonempty_streams == 3);
assert(tree.min() == 5); assert(tree._nonempty_streams == 3);
assert(tree.min() == 6); assert(tree._nonempty_streams == 3);
assert(tree.min() == 7); assert(tree._nonempty_streams == 3);
assert(tree.min() == 8); assert(tree._nonempty_streams == 2);
assert(tree.min() == 9); assert(tree._nonempty_streams == 1);
assert(tree.min() == 10); assert(tree._nonempty_streams == 0);
}
{
std::array<int, 3> seq1 = { 2, 5, 8 };
std::array<int, 3> seq2 = { 3, 6, 9 };
std::array<int, 3> seq3 = { 4, 7, 10 };
std::vector<std::pair<int*, size_t> > seqs;
seqs.push_back(std::make_pair(seq3.data(), 3));
seqs.push_back(std::make_pair(seq2.data(), 3));
seqs.push_back(std::make_pair(seq1.data(), 3));
loser_tree<int> tree(seqs.begin(), seqs.end());
assert(tree._nonempty_streams == 3);
assert(tree.min() == 2); assert(tree._nonempty_streams == 3);
assert(tree.min() == 3); assert(tree._nonempty_streams == 3);
assert(tree.min() == 4); assert(tree._nonempty_streams == 3);
assert(tree.min() == 5); assert(tree._nonempty_streams == 3);
assert(tree.min() == 6); assert(tree._nonempty_streams == 3);
assert(tree.min() == 7); assert(tree._nonempty_streams == 3);
assert(tree.min() == 8); assert(tree._nonempty_streams == 2);
assert(tree.min() == 9); assert(tree._nonempty_streams == 1);
assert(tree.min() == 10); assert(tree._nonempty_streams == 0);
}
{
const unsigned items = 32;
std::vector<std::vector<int> > data(25000);
for (unsigned i=0; i < data.size(); ++i) {
for (unsigned j=0; j < items; ++j) {
data[i].push_back(j);
}
}
std::vector<std::pair<int*, size_t> > seqs;
for (unsigned i=0; i < data.size(); ++i) {
seqs.push_back(std::make_pair(data[i].data(), items));
}
loser_tree<int> tree(seqs.begin(), seqs.end());
assert(tree._nonempty_streams == data.size());
for (unsigned i=0; i < items; ++i) {
for (unsigned j=0; j < data.size(); ++j) {
assert(tree.min() == int(i));
}
}
assert(tree._nonempty_streams == 0);
}
}
static void
test_insertion_sort()
{
std::cerr<<__PRETTY_FUNCTION__<<std::endl;
{
std::array<const char *, 0> input;
insertion_sort((unsigned char **)input.data(), input.size(), 0);
}
{
std::array<const unsigned char *, 1> input { (const unsigned char *)"" };
insertion_sort((unsigned char **)input.data(), input.size(), 0);
}
{
std::array<const unsigned char *, 5> input {
(const unsigned char *)"c",
(const unsigned char *)"",
(const unsigned char *)"bbaaa",
(const unsigned char *)"aaaaa",
(const unsigned char *)"bbbbb",
};
insertion_sort((unsigned char **)input.data(), input.size(), 0);
assert(strcmp_u(input[0], "") == 0);
assert(strcmp_u(input[1], "aaaaa") == 0);
assert(strcmp_u(input[2], "bbaaa") == 0);
assert(strcmp_u(input[3], "bbbbb") == 0);
assert(strcmp_u(input[4], "c") == 0);
insertion_sort((unsigned char **)input.data(), input.size(), 0);
assert(strcmp_u(input[0], "") == 0);
assert(strcmp_u(input[1], "aaaaa") == 0);
assert(strcmp_u(input[2], "bbaaa") == 0);
assert(strcmp_u(input[3], "bbbbb") == 0);
assert(strcmp_u(input[4], "c") == 0);
}
{
std::array<const unsigned char *, 3> input {
(const unsigned char *)"bbbb1",
(const unsigned char *)"aaaa3",
(const unsigned char *)"aaaa2",
};
insertion_sort((unsigned char **)input.data(), input.size(), 4);
assert(strcmp_u(input[0], "bbbb1") == 0);
assert(strcmp_u(input[1], "aaaa2") == 0);
assert(strcmp_u(input[2], "aaaa3") == 0);
}
}
static void
test_routines()
{
std::cerr<<__PRETTY_FUNCTION__<<std::endl;
const struct routine **routines;
unsigned routines_cnt;
routine_get_all(&routines, &routines_cnt);
for (unsigned i=0; i < routines_cnt; ++i) {
std::cerr << __PRETTY_FUNCTION__
<< " [" << routines[i]->name << ']' << std::endl;
for (size_t k=1; k < 2000; k += 200) {
std::vector<char *> input;
for (size_t i=0; i < k; ++i)
input.push_back(strdup("aaa"));
const size_t n = input.size();
routines[i]->f((unsigned char **)input.data(), n);
for (size_t i=0; i < n; ++i)
assert(strcmp(input[i], "aaa") == 0);
assert(check_result((unsigned char**)input.data(), n) == 0);
for (size_t i=0; i < n; ++i)
free(input[i]);
}
for (size_t k=1; k < 1000; k += 200) {
std::vector<char *> input;
for (size_t i=0; i < k; ++i) {
input.push_back(strdup("bb"));
input.push_back(strdup("a"));
input.push_back(strdup("bbb"));
}
const size_t n = input.size();
routines[i]->f((unsigned char **)input.data(), n);
for (size_t i=0*(n/3); i < 1*(n/3); ++i)
assert(strcmp(input[i], "a") == 0);
for (size_t i=1*(n/3); i < 2*(n/3); ++i)
assert(strcmp(input[i], "bb") == 0);
for (size_t i=2*(n/3); i < 3*(n/3); ++i)
assert(strcmp(input[i], "bbb") == 0);
assert(check_result((unsigned char**)input.data(), n) == 0);
for (size_t i=0; i < n; ++i)
free(input[i]);
}
for (size_t k=1; k < 10000; k += 2000) {
std::vector<char *> input;
for (size_t i=0; i < k; ++i) {
char buf[10];
memset(buf, 'a'+(i%30), sizeof(buf)-1);
buf[sizeof(buf)-1] = 0;
input.push_back(strdup(buf));
}
const size_t n = input.size();
routines[i]->f((unsigned char **)input.data(), n);
// for (size_t i=0; i < n; ++i) std::cerr<<input[i]<<'\n';
assert(check_result((unsigned char**)input.data(), n) == 0);
for (size_t i=0; i < n; ++i)
free(input[i]);
}
}
}
struct OK { ~OK() { std::cerr << "*** All OK ***\n"; } };
int main()
{
OK ok;
test_loser_tree();
test_basics<vector_brodnik<int> >();
test_basics<vector_bagwell<int> >();
test_basics<vector_block<int> >();
test_basics<vector_malloc<int> >();
test_basics<vector_malloc_counter_clear<int> >();
test_basics<vector_realloc<int> >();
test_basics<vector_realloc_counter_clear<int> >();
test_basics<vector_realloc_shrink_clear<int> >();
test_basics<vector_brodnik<uint64_t> >();
test_basics<vector_bagwell<uint64_t> >();
test_basics<vector_block<uint64_t> >();
test_basics<vector_malloc<uint64_t> >();
test_basics<vector_malloc_counter_clear<uint64_t> >();
test_basics<vector_realloc<uint64_t> >();
test_basics<vector_realloc_counter_clear<uint64_t> >();
test_basics<vector_realloc_shrink_clear<uint64_t> >();
test_insertion_sort();
test_routines();
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkGEAdwImageIO.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#include "itkGEAdwImageIO.h"
#include "itkIOCommon.h"
#include <itksys/SystemTools.hxx>
#include "itkExceptionObject.h"
#include "itkByteSwapper.h"
#include "itkGEImageHeader.h"
#include "itkDirectory.h"
#include <iostream>
#include <fstream>
#include <string.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <string>
//From uiig library "The University of Iowa Imaging Group-UIIG"
namespace itk
{
// Default constructor
GEAdwImageIO::GEAdwImageIO()
{
//Purposefully left blank
}
GEAdwImageIO::~GEAdwImageIO()
{
//Purposefully left blank
}
bool GEAdwImageIO::CanReadFile( const char* FileNameToRead )
{
size_t imageSize;
short matrixX;
short matrixY;
int varHdrSize;
//this->SetFileName(FileNameToRead);
//
// Can you open it?
std::ifstream f(FileNameToRead,std::ios::binary | std::ios::in);
if(!f.is_open())
return false;
//
// This test basically snoops out the image dimensions, and the
// length of the variable-length part of the header, and computes
// the size the file should be and compares it with the actual size.
// if it's not reading a GEAdw file, chances are overwhelmingly good
// that this operation will fail somewhere along the line.
if(this->GetShortAt(f,GE_ADW_IM_IMATRIX_X,&matrixX,false) != 0)
return false;
if(this->GetShortAt(f,GE_ADW_IM_IMATRIX_Y,&matrixY,false) != 0)
return false;
if(this->GetIntAt(f,GE_ADW_VARIABLE_HDR_LENGTH,&varHdrSize,false) != 0)
return false;
imageSize = varHdrSize + GE_ADW_FIXED_HDR_LENGTH + (matrixX * matrixY * sizeof(short));
if ( imageSize != itksys::SystemTools::FileLength(FileNameToRead) )
{
return false;
}
return true;
}
struct GEImageHeader *GEAdwImageIO::ReadHeader(const char *FileNameToRead)
{
char tmpbuf[1024];
if(!this->CanReadFile(FileNameToRead))
RAISE_EXCEPTION();
GEImageHeader *hdr = new struct GEImageHeader;
if(hdr == 0)
RAISE_EXCEPTION();
//
// Next, can you open it?
std::ifstream f(FileNameToRead,std::ios::binary | std::ios::in);
if(!f.is_open())
RAISE_EXCEPTION();
sprintf(hdr->scanner,"GE-ADW");
this->GetStringAt(f,GE_ADW_EX_PATID,tmpbuf,12);
tmpbuf[12] = '\0';
hdr->patientId[0] = '\0';
for(char *ptr = strtok(tmpbuf,"-"); ptr != NULL; ptr = strtok(NULL,"-"))
{
strcat(hdr->patientId,ptr);
}
this->GetStringAt(f,GE_ADW_EX_PATNAME,hdr->name,GE_ADW_EX_PATNAME_LEN);
hdr->name[GE_ADW_EX_PATNAME_LEN] = '\0';
this->GetStringAt(f,GE_ADW_EX_HOSPNAME,hdr->hospital,34);
hdr->hospital[33] = '\0';
int timeStamp;
this->GetIntAt(f,GE_ADW_EX_DATETIME,&timeStamp);
this->statTimeToAscii(&timeStamp,hdr->date);
this->GetStringAt(f,GE_ADW_SU_PRODID,hdr->scanner,13);
hdr->scanner[13] = '\0';
this->GetShortAt(f,GE_ADW_SE_NO,&(hdr->seriesNumber));
this->GetShortAt(f,GE_ADW_IM_NO,&(hdr->imageNumber));
this->GetShortAt(f,GE_ADW_IM_CPHASENUM,&(hdr->imagesPerSlice));
this->GetShortAt(f,GE_ADW_IM_CPHASENUM,&(hdr->turboFactor));
this->GetFloatAt(f,GE_ADW_IM_SLTHICK,&(hdr->sliceThickness));
hdr->sliceGap = 0.0;
this->GetShortAt(f,GE_ADW_IM_IMATRIX_X,&(hdr->imageXsize));
this->GetShortAt(f,GE_ADW_IM_IMATRIX_Y,&(hdr->imageYsize));
hdr->acqXsize = hdr->imageXsize;
hdr->acqYsize = hdr->imageYsize;
this->GetFloatAt(f,GE_ADW_IM_DFOV,&hdr->xFOV);
hdr->yFOV = hdr->xFOV;
this->GetFloatAt(f,GE_ADW_IM_PIXSIZE_X,&hdr->imageXres);
this->GetFloatAt(f,GE_ADW_IM_PIXSIZE_Y,&hdr->imageYres);
short tmpShort;
this->GetShortAt(f,GE_ADW_IM_PLANE,&tmpShort);
switch (tmpShort)
{
case GE_CORONAL:
//hdr->imagePlane = itk::IOCommon::ITK_ANALYZE_ORIENTATION_IRP_CORONAL;
//hdr->origin = itk::IOCommon::ITK_ORIGIN_SLA;
hdr->coordinateOrientation = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RSP;
break;
case GE_SAGITTAL:
//hdr->imagePlane = itk::SpatialOrientation::ITK_ANALYZE_ORIENTATION_IRP_SAGITTAL;
//hdr->origin = itk::SpatialOrientation::ITK_ORIGIN_SLA;
hdr->coordinateOrientation = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_AIR;
break;
case GE_AXIAL:
//hdr->imagePlane = itk::SpatialOrientation::ITK_ANALYZE_ORIENTATION_IRP_TRANSVERSE;
//hdr->origin = itk::SpatialOrientation::ITK_ORIGIN_SLA;
hdr->coordinateOrientation = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RAI;
break;
default:
//hdr->imagePlane = itk::SpatialOrientation::ITK_ANALYZE_ORIENTATION_IRP_CORONAL;
//hdr->origin = itk::SpatialOrientation::ITK_ORIGIN_SLA;
hdr->coordinateOrientation = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RSP;
break;
}
this->GetFloatAt(f,GE_ADW_IM_LOC,&(hdr->sliceLocation));
int tmpInt;
this->GetIntAt(f,GE_ADW_IM_TR,&tmpInt);
hdr->TR = (float) tmpInt / 1000.0;
this->GetIntAt(f,GE_ADW_IM_TI,&tmpInt);
hdr->TI = (float) tmpInt / 1000.0;
this->GetIntAt(f,GE_ADW_IM_TE,&tmpInt);
hdr->TE = (float) tmpInt / 1000.0;
this->GetShortAt(f, GE_ADW_IM_NUMECHO,&(hdr->numberOfEchoes));
this->GetShortAt(f, GE_ADW_IM_ECHONUM,&(hdr->echoNumber));
float tmpFloat;
this->GetFloatAt(f,GE_ADW_IM_NEX,&tmpFloat);
hdr->NEX = (int) tmpFloat;
this->GetShortAt(f,GE_ADW_IM_MR_FLIP,&hdr->flipAngle);
this->GetStringAt(f,GE_ADW_IM_PSDNAME, hdr->pulseSequence, 31);
hdr->pulseSequence[31] = '\0';
this->GetShortAt(f,GE_ADW_IM_SLQUANT,&(hdr->numberOfSlices));
this->GetIntAt(f,GE_ADW_VARIABLE_HDR_LENGTH,&tmpInt);
hdr->offset = GE_ADW_FIXED_HDR_LENGTH + tmpInt;
strncpy (hdr->filename, FileNameToRead, IOCommon::ITK_MAXPATHLEN);
hdr->filename[IOCommon::ITK_MAXPATHLEN] = '\0';
return hdr;
}
} // end namespace itk
<commit_msg>COMP: style.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkGEAdwImageIO.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#include "itkGEAdwImageIO.h"
#include "itkIOCommon.h"
#include <itksys/SystemTools.hxx>
#include "itkExceptionObject.h"
#include "itkByteSwapper.h"
#include "itkGEImageHeader.h"
#include "itkDirectory.h"
#include <iostream>
#include <fstream>
#include <string.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <string>
//From uiig library "The University of Iowa Imaging Group-UIIG"
namespace itk
{
// Default constructor
GEAdwImageIO::GEAdwImageIO()
{
//Purposefully left blank
}
GEAdwImageIO::~GEAdwImageIO()
{
//Purposefully left blank
}
bool GEAdwImageIO::CanReadFile( const char* FileNameToRead )
{
size_t imageSize;
short matrixX;
short matrixY;
int varHdrSize;
//this->SetFileName(FileNameToRead);
//
// Can you open it?
std::ifstream f(FileNameToRead,std::ios::binary | std::ios::in);
if(!f.is_open())
{
return false;
}
//
// This test basically snoops out the image dimensions, and the
// length of the variable-length part of the header, and computes
// the size the file should be and compares it with the actual size.
// if it's not reading a GEAdw file, chances are overwhelmingly good
// that this operation will fail somewhere along the line.
if(this->GetShortAt(f,GE_ADW_IM_IMATRIX_X,&matrixX,false) != 0)
{
return false;
}
if(this->GetShortAt(f,GE_ADW_IM_IMATRIX_Y,&matrixY,false) != 0)
{
return false;
}
if(this->GetIntAt(f,GE_ADW_VARIABLE_HDR_LENGTH,&varHdrSize,false) != 0)
{
return false;
}
imageSize = varHdrSize + GE_ADW_FIXED_HDR_LENGTH + (matrixX * matrixY * sizeof(short));
if ( imageSize != itksys::SystemTools::FileLength(FileNameToRead) )
{
return false;
}
return true;
}
struct GEImageHeader *GEAdwImageIO::ReadHeader(const char *FileNameToRead)
{
char tmpbuf[1024];
if(!this->CanReadFile(FileNameToRead))
{
RAISE_EXCEPTION();
}
GEImageHeader *hdr = new struct GEImageHeader;
if(hdr == 0)
{
RAISE_EXCEPTION();
}
//
// Next, can you open it?
std::ifstream f(FileNameToRead,std::ios::binary | std::ios::in);
if(!f.is_open())
{
RAISE_EXCEPTION();
}
sprintf(hdr->scanner,"GE-ADW");
this->GetStringAt(f,GE_ADW_EX_PATID,tmpbuf,12);
tmpbuf[12] = '\0';
hdr->patientId[0] = '\0';
for(char *ptr = strtok(tmpbuf,"-"); ptr != NULL; ptr = strtok(NULL,"-"))
{
strcat(hdr->patientId,ptr);
}
this->GetStringAt(f,GE_ADW_EX_PATNAME,hdr->name,GE_ADW_EX_PATNAME_LEN);
hdr->name[GE_ADW_EX_PATNAME_LEN] = '\0';
this->GetStringAt(f,GE_ADW_EX_HOSPNAME,hdr->hospital,34);
hdr->hospital[33] = '\0';
int timeStamp;
this->GetIntAt(f,GE_ADW_EX_DATETIME,&timeStamp);
this->statTimeToAscii(&timeStamp,hdr->date);
this->GetStringAt(f,GE_ADW_SU_PRODID,hdr->scanner,13);
hdr->scanner[13] = '\0';
this->GetShortAt(f,GE_ADW_SE_NO,&(hdr->seriesNumber));
this->GetShortAt(f,GE_ADW_IM_NO,&(hdr->imageNumber));
this->GetShortAt(f,GE_ADW_IM_CPHASENUM,&(hdr->imagesPerSlice));
this->GetShortAt(f,GE_ADW_IM_CPHASENUM,&(hdr->turboFactor));
this->GetFloatAt(f,GE_ADW_IM_SLTHICK,&(hdr->sliceThickness));
hdr->sliceGap = 0.0;
this->GetShortAt(f,GE_ADW_IM_IMATRIX_X,&(hdr->imageXsize));
this->GetShortAt(f,GE_ADW_IM_IMATRIX_Y,&(hdr->imageYsize));
hdr->acqXsize = hdr->imageXsize;
hdr->acqYsize = hdr->imageYsize;
this->GetFloatAt(f,GE_ADW_IM_DFOV,&hdr->xFOV);
hdr->yFOV = hdr->xFOV;
this->GetFloatAt(f,GE_ADW_IM_PIXSIZE_X,&hdr->imageXres);
this->GetFloatAt(f,GE_ADW_IM_PIXSIZE_Y,&hdr->imageYres);
short tmpShort;
this->GetShortAt(f,GE_ADW_IM_PLANE,&tmpShort);
switch (tmpShort)
{
case GE_CORONAL:
//hdr->imagePlane = itk::IOCommon::ITK_ANALYZE_ORIENTATION_IRP_CORONAL;
//hdr->origin = itk::IOCommon::ITK_ORIGIN_SLA;
hdr->coordinateOrientation = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RSP;
break;
case GE_SAGITTAL:
//hdr->imagePlane = itk::SpatialOrientation::ITK_ANALYZE_ORIENTATION_IRP_SAGITTAL;
//hdr->origin = itk::SpatialOrientation::ITK_ORIGIN_SLA;
hdr->coordinateOrientation = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_AIR;
break;
case GE_AXIAL:
//hdr->imagePlane = itk::SpatialOrientation::ITK_ANALYZE_ORIENTATION_IRP_TRANSVERSE;
//hdr->origin = itk::SpatialOrientation::ITK_ORIGIN_SLA;
hdr->coordinateOrientation = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RAI;
break;
default:
//hdr->imagePlane = itk::SpatialOrientation::ITK_ANALYZE_ORIENTATION_IRP_CORONAL;
//hdr->origin = itk::SpatialOrientation::ITK_ORIGIN_SLA;
hdr->coordinateOrientation = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RSP;
break;
}
this->GetFloatAt(f,GE_ADW_IM_LOC,&(hdr->sliceLocation));
int tmpInt;
this->GetIntAt(f,GE_ADW_IM_TR,&tmpInt);
hdr->TR = (float) tmpInt / 1000.0;
this->GetIntAt(f,GE_ADW_IM_TI,&tmpInt);
hdr->TI = (float) tmpInt / 1000.0;
this->GetIntAt(f,GE_ADW_IM_TE,&tmpInt);
hdr->TE = (float) tmpInt / 1000.0;
this->GetShortAt(f, GE_ADW_IM_NUMECHO,&(hdr->numberOfEchoes));
this->GetShortAt(f, GE_ADW_IM_ECHONUM,&(hdr->echoNumber));
float tmpFloat;
this->GetFloatAt(f,GE_ADW_IM_NEX,&tmpFloat);
hdr->NEX = (int) tmpFloat;
this->GetShortAt(f,GE_ADW_IM_MR_FLIP,&hdr->flipAngle);
this->GetStringAt(f,GE_ADW_IM_PSDNAME, hdr->pulseSequence, 31);
hdr->pulseSequence[31] = '\0';
this->GetShortAt(f,GE_ADW_IM_SLQUANT,&(hdr->numberOfSlices));
this->GetIntAt(f,GE_ADW_VARIABLE_HDR_LENGTH,&tmpInt);
hdr->offset = GE_ADW_FIXED_HDR_LENGTH + tmpInt;
strncpy (hdr->filename, FileNameToRead, IOCommon::ITK_MAXPATHLEN);
hdr->filename[IOCommon::ITK_MAXPATHLEN] = '\0';
return hdr;
}
} // end namespace itk
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief RL78/G13 グループ・システム・レジスター定義 @n
Copyright 2016 Kunihito Hiramatsu
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "common/io_utils.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief クロック動作モード制御レジスタ(CMC)
@param[in] T アクセス・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class T>
struct cmc_t : public T {
using T::operator ();
bit_rw_t<T, 7> EXCLK; ///< 高速システム・クロック端子の動作モード
bit_rw_t<T, 6> OSCSEL; ///< 高速システム・クロック端子の動作モード
bit_rw_t<T, 5> EXCLKS; ///< サブシステム・クロック端子の動作モード
bit_rw_t<T, 4> OSCSELS; ///< サブシステム・クロック端子の動作モード
bit_rw_t<T, 2> AMPHS1; ///< XT1発振回路の発振モード選択 1
bit_rw_t<T, 1> AMPHS0; ///< XT1発振回路の発振モード選択 0
bits_rw_t<T, 1, 2> AMPHS; ///< XT1発振回路の発振モード選択
bit_rw_t<T, 0> AMPH; ///< X1クロック発振周波数の制御
};
static cmc_t< rw8_t<0xFFFA0> > CMC;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief クロック動作ステータス制御レジスタ(CKC)
@param[in] T アクセス・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class T>
struct ckc_t : public T {
using T::operator ();
bit_rw_t<T, 7> CLS; ///< CPU/周辺ハードウエア・クロック(f CLK )のステータス
bit_rw_t<T, 6> CSS; ///< CPU/周辺ハードウエア・クロック(f CLK )の選択
bit_rw_t<T, 5> MCS; ///< メイン・システム・クロック(f MAIN )のステータス
bit_rw_t<T, 4> MCM0; ///< メイン・システム・クロック(f MAIN )の動作制御
};
static ckc_t< rw8_t<0xFFFA4> > CKC;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief クロック動作ステータス制御レジスタ(CSC)
@param[in] T アクセス・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class T>
struct csc_t : public T {
using T::operator ();
bit_rw_t<T, 7> MSTOP; ///< 高速システム・クロックの動作制御
bit_rw_t<T, 6> XTSTOP; ///< サブシステム・クロックの動作制御
bit_rw_t<T, 0> MIOSTOP; ///< 高速オンチップ・オシレータ・クロックの動作制御
};
static csc_t< rw8_t<0xFFFA1> > CSC;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 発振安定時間カウンタ状態レジスタ(OSTC)
@param[in] T アクセス・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class T>
struct ostc_t : public T {
using T::operator ();
/// ro8_t<T::address> MOST; ///< 発振安定時間のステータス
bit_ro_t<T, 7> MOST8;
bit_ro_t<T, 6> MOST9;
bit_ro_t<T, 5> MOST10;
bit_ro_t<T, 4> MOST11;
bit_ro_t<T, 3> MOST13;
bit_ro_t<T, 2> MOST15;
bit_ro_t<T, 1> MOST17;
bit_ro_t<T, 0> MOST18;
};
static ostc_t< ro8_t<0xFFFA2> > OSTC;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 発振安定時間選択レジスタ(OSTS)
@param[in] T アクセス・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class T>
struct osts_t : public T {
using T::operator =;
using T::operator ();
using T::operator |=;
using T::operator &=;
bits_rw_t<T, 0, 3> OSTS; ///< 発振安定時間の選択
bit_rw_t<T, 2> OSTS2;
bit_rw_t<T, 1> OSTS1;
bit_rw_t<T, 0> OSTS0;
};
static osts_t< rw8_t<0xFFFA3> > OSTS;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 周辺イネーブル・レジスタ0(PER0) @n
リセット時:00H
@param[in] T アクセス・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class T>
struct per0_t : public T {
using T::operator =;
using T::operator ();
using T::operator |=;
using T::operator &=;
bit_rw_t<T, 7> RTCEN; ///< リアルタイム・クロック、インターバル・タイマの入力クロック供給の制御
bit_rw_t<T, 6> IICA1EN; ///< シリアル・インタフェース1の入力クロック供給の制御
bit_rw_t<T, 5> ADCEN; ///< A/Dコンバータの入力クロックの制御
bit_rw_t<T, 4> IICA0EN; ///< シリアル・インタフェース0の入力クロック供給の制御
bit_rw_t<T, 3> SAU1EN; ///< シリアル・アレイ・ユニット1の入力クロック供給の制御
bit_rw_t<T, 2> SAU0EN; ///< シリアル・アレイ・ユニット0の入力クロック供給の制御
bit_rw_t<T, 1> TAU1EN; ///< タイマ・アレイ・ユニット1の入力クロック供給の制御
bit_rw_t<T, 0> TAU0EN; ///< タイマ・アレイ・ユニット0の入力クロック供給の制御
};
static per0_t< rw8_t<0xF00F0> > PER0;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief サブシステム・クロック供給モード制御レジスタ(OSMC)
@param[in] T アクセス・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class T>
struct osmc_t : public T {
using T::operator =;
using T::operator ();
using T::operator |=;
using T::operator &=;
bit_rw_t<T, 7> RTCLPC; ///< STOPモード時およびサブシステム・クロックでCPU動作中のHALTモード時の設定
bit_rw_t<T, 4> WUTMMCK0; ///< リアルタイム・クロック,インターバル・タイマの動作クロックの選択
};
static osmc_t< rw8_t<0xF00F3> > OSMC;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 高速オンチップ・オシレータ周波数選択レジスタ(HOCODIV)
@param[in] T アクセス・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class T>
struct hocodiv_t : public T {
using T::operator =;
using T::operator ();
using T::operator |=;
using T::operator &=;
bits_rw_t<T, 0, 3> HOCODIV;
bit_rw_t<T, 2> HOCODIV2;
bit_rw_t<T, 1> HOCODIV1;
bit_rw_t<T, 0> HOCODIV0;
};
static hocodiv_t< rw8_t<0xF00A8> > HOCODIV; ///< 高速オンチップ・オシレータ・クロック周波数の選択
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 高速オンチップ・オシレータ・トリミング・レジスタ(HIOTRM)
@param[in] T アクセス・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class T>
struct hiotrm_t : public T {
using T::operator =;
using T::operator ();
using T::operator |=;
using T::operator &=;
bits_rw_t<T, 0, 6> HIOTRM; ///< 高速オンチップ・オシレータ
bit_rw_t<T, 5> HIOTRM5;
bit_rw_t<T, 4> HIOTRM4;
bit_rw_t<T, 3> HIOTRM3;
bit_rw_t<T, 2> HIOTRM2;
bit_rw_t<T, 1> HIOTRM1;
bit_rw_t<T, 0> HIOTRM0;
};
static hiotrm_t< rw8_t<0xF00A0> > HIOTRM;
}
<commit_msg>fix operator<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief RL78/G13 グループ・システム・レジスター定義 @n
Copyright 2016 Kunihito Hiramatsu
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "common/io_utils.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief クロック動作モード制御レジスタ(CMC)
@param[in] T アクセス・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class T>
struct cmc_t : public T {
using T::operator =;
using T::operator ();
using T::operator |=;
using T::operator &=;
bit_rw_t<T, 7> EXCLK; ///< 高速システム・クロック端子の動作モード
bit_rw_t<T, 6> OSCSEL; ///< 高速システム・クロック端子の動作モード
bit_rw_t<T, 5> EXCLKS; ///< サブシステム・クロック端子の動作モード
bit_rw_t<T, 4> OSCSELS; ///< サブシステム・クロック端子の動作モード
bit_rw_t<T, 2> AMPHS1; ///< XT1発振回路の発振モード選択 1
bit_rw_t<T, 1> AMPHS0; ///< XT1発振回路の発振モード選択 0
bits_rw_t<T, 1, 2> AMPHS; ///< XT1発振回路の発振モード選択
bit_rw_t<T, 0> AMPH; ///< X1クロック発振周波数の制御
};
static cmc_t< rw8_t<0xFFFA0> > CMC;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief クロック動作ステータス制御レジスタ(CKC)
@param[in] T アクセス・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class T>
struct ckc_t : public T {
using T::operator =;
using T::operator ();
using T::operator |=;
using T::operator &=;
bit_rw_t<T, 7> CLS; ///< CPU/周辺ハードウエア・クロック(f CLK )のステータス
bit_rw_t<T, 6> CSS; ///< CPU/周辺ハードウエア・クロック(f CLK )の選択
bit_rw_t<T, 5> MCS; ///< メイン・システム・クロック(f MAIN )のステータス
bit_rw_t<T, 4> MCM0; ///< メイン・システム・クロック(f MAIN )の動作制御
};
static ckc_t< rw8_t<0xFFFA4> > CKC;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief クロック動作ステータス制御レジスタ(CSC)
@param[in] T アクセス・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class T>
struct csc_t : public T {
using T::operator =;
using T::operator ();
using T::operator |=;
using T::operator &=;
bit_rw_t<T, 7> MSTOP; ///< 高速システム・クロックの動作制御
bit_rw_t<T, 6> XTSTOP; ///< サブシステム・クロックの動作制御
bit_rw_t<T, 0> MIOSTOP; ///< 高速オンチップ・オシレータ・クロックの動作制御
};
static csc_t< rw8_t<0xFFFA1> > CSC;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 発振安定時間カウンタ状態レジスタ(OSTC)
@param[in] T アクセス・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class T>
struct ostc_t : public T {
using T::operator ();
/// ro8_t<T::address> MOST; ///< 発振安定時間のステータス
bit_ro_t<T, 7> MOST8;
bit_ro_t<T, 6> MOST9;
bit_ro_t<T, 5> MOST10;
bit_ro_t<T, 4> MOST11;
bit_ro_t<T, 3> MOST13;
bit_ro_t<T, 2> MOST15;
bit_ro_t<T, 1> MOST17;
bit_ro_t<T, 0> MOST18;
};
static ostc_t< ro8_t<0xFFFA2> > OSTC;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 発振安定時間選択レジスタ(OSTS)
@param[in] T アクセス・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class T>
struct osts_t : public T {
using T::operator =;
using T::operator ();
using T::operator |=;
using T::operator &=;
bits_rw_t<T, 0, 3> OSTS; ///< 発振安定時間の選択
bit_rw_t<T, 2> OSTS2;
bit_rw_t<T, 1> OSTS1;
bit_rw_t<T, 0> OSTS0;
};
static osts_t< rw8_t<0xFFFA3> > OSTS;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 周辺イネーブル・レジスタ0(PER0) @n
リセット時:00H
@param[in] T アクセス・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class T>
struct per0_t : public T {
using T::operator =;
using T::operator ();
using T::operator |=;
using T::operator &=;
bit_rw_t<T, 7> RTCEN; ///< リアルタイム・クロック、インターバル・タイマの入力クロック供給の制御
bit_rw_t<T, 6> IICA1EN; ///< シリアル・インタフェース1の入力クロック供給の制御
bit_rw_t<T, 5> ADCEN; ///< A/Dコンバータの入力クロックの制御
bit_rw_t<T, 4> IICA0EN; ///< シリアル・インタフェース0の入力クロック供給の制御
bit_rw_t<T, 3> SAU1EN; ///< シリアル・アレイ・ユニット1の入力クロック供給の制御
bit_rw_t<T, 2> SAU0EN; ///< シリアル・アレイ・ユニット0の入力クロック供給の制御
bit_rw_t<T, 1> TAU1EN; ///< タイマ・アレイ・ユニット1の入力クロック供給の制御
bit_rw_t<T, 0> TAU0EN; ///< タイマ・アレイ・ユニット0の入力クロック供給の制御
};
static per0_t< rw8_t<0xF00F0> > PER0;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief サブシステム・クロック供給モード制御レジスタ(OSMC)
@param[in] T アクセス・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class T>
struct osmc_t : public T {
using T::operator =;
using T::operator ();
using T::operator |=;
using T::operator &=;
bit_rw_t<T, 7> RTCLPC; ///< STOPモード時およびサブシステム・クロックでCPU動作中のHALTモード時の設定
bit_rw_t<T, 4> WUTMMCK0; ///< リアルタイム・クロック,インターバル・タイマの動作クロックの選択
};
static osmc_t< rw8_t<0xF00F3> > OSMC;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 高速オンチップ・オシレータ周波数選択レジスタ(HOCODIV)
@param[in] T アクセス・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class T>
struct hocodiv_t : public T {
using T::operator =;
using T::operator ();
using T::operator |=;
using T::operator &=;
bits_rw_t<T, 0, 3> HOCODIV;
bit_rw_t<T, 2> HOCODIV2;
bit_rw_t<T, 1> HOCODIV1;
bit_rw_t<T, 0> HOCODIV0;
};
static hocodiv_t< rw8_t<0xF00A8> > HOCODIV; ///< 高速オンチップ・オシレータ・クロック周波数の選択
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 高速オンチップ・オシレータ・トリミング・レジスタ(HIOTRM)
@param[in] T アクセス・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class T>
struct hiotrm_t : public T {
using T::operator =;
using T::operator ();
using T::operator |=;
using T::operator &=;
bits_rw_t<T, 0, 6> HIOTRM; ///< 高速オンチップ・オシレータ
bit_rw_t<T, 5> HIOTRM5;
bit_rw_t<T, 4> HIOTRM4;
bit_rw_t<T, 3> HIOTRM3;
bit_rw_t<T, 2> HIOTRM2;
bit_rw_t<T, 1> HIOTRM1;
bit_rw_t<T, 0> HIOTRM0;
};
static hiotrm_t< rw8_t<0xF00A0> > HIOTRM;
}
<|endoftext|> |
<commit_before>/*
Copyright 2008 Brain Research Institute, Melbourne, Australia
Written by Robert E. Smith, 31/07/13.
This file is part of MRtrix.
MRtrix is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MRtrix is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "image/format/mrtrix_utils.h"
namespace MR
{
namespace Image
{
namespace Format
{
bool next_keyvalue (File::KeyValue& kv, std::string& key, std::string& value)
{
key.clear(); value.clear();
if (!kv.next())
return false;
key = kv.key();
value = kv.value();
return true;
}
bool next_keyvalue (File::GZ& gz, std::string& key, std::string& value)
{
key.clear(); value.clear();
std::string line = gz.getline();
line = strip (line.substr (0, line.find_first_of ('#')));
if (line.empty() || line == "END")
return false;
size_t colon = line.find_first_of (':');
if (colon == std::string::npos) {
INFO ("malformed key/value entry (\"" + line + "\") in file \"" + gz.name() + "\" - ignored");
} else {
key = strip (line.substr (0, colon));
value = strip (line.substr (colon+1));
if (key.empty() || value.empty()) {
INFO ("malformed key/value entry (\"" + line + "\") in file \"" + gz.name() + "\" - ignored");
key.clear();
value.clear();
}
}
return true;
}
void get_mrtrix_file_path (Header& H, const std::string& flag, std::string& fname, size_t& offset)
{
Header::iterator i = H.find (flag);
if (i == H.end())
throw Exception ("missing \"" + flag + "\" specification for MRtrix image \"" + H.name() + "\"");
const std::string path = i->second;
H.erase (i);
std::istringstream file_stream (path);
file_stream >> fname;
offset = 0;
if (file_stream.good()) {
try {
file_stream >> offset;
}
catch (...) {
throw Exception ("invalid offset specified for file \"" + fname
+ "\" in MRtrix image header \"" + H.name() + "\"");
}
}
if (fname == ".") {
if (offset == 0)
throw Exception ("invalid offset specified for embedded MRtrix image \"" + H.name() + "\"");
fname = H.name();
} else {
fname = Path::join (Path::dirname (H.name()), fname);
}
}
}
}
}
<commit_msg>mih format: handle cases where the file is specified as an absolute path<commit_after>/*
Copyright 2008 Brain Research Institute, Melbourne, Australia
Written by Robert E. Smith, 31/07/13.
This file is part of MRtrix.
MRtrix is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MRtrix is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include "image/format/mrtrix_utils.h"
namespace MR
{
namespace Image
{
namespace Format
{
bool next_keyvalue (File::KeyValue& kv, std::string& key, std::string& value)
{
key.clear(); value.clear();
if (!kv.next())
return false;
key = kv.key();
value = kv.value();
return true;
}
bool next_keyvalue (File::GZ& gz, std::string& key, std::string& value)
{
key.clear(); value.clear();
std::string line = gz.getline();
line = strip (line.substr (0, line.find_first_of ('#')));
if (line.empty() || line == "END")
return false;
size_t colon = line.find_first_of (':');
if (colon == std::string::npos) {
INFO ("malformed key/value entry (\"" + line + "\") in file \"" + gz.name() + "\" - ignored");
} else {
key = strip (line.substr (0, colon));
value = strip (line.substr (colon+1));
if (key.empty() || value.empty()) {
INFO ("malformed key/value entry (\"" + line + "\") in file \"" + gz.name() + "\" - ignored");
key.clear();
value.clear();
}
}
return true;
}
void get_mrtrix_file_path (Header& H, const std::string& flag, std::string& fname, size_t& offset)
{
Header::iterator i = H.find (flag);
if (i == H.end())
throw Exception ("missing \"" + flag + "\" specification for MRtrix image \"" + H.name() + "\"");
const std::string path = i->second;
H.erase (i);
std::istringstream file_stream (path);
file_stream >> fname;
offset = 0;
if (file_stream.good()) {
try {
file_stream >> offset;
}
catch (...) {
throw Exception ("invalid offset specified for file \"" + fname
+ "\" in MRtrix image header \"" + H.name() + "\"");
}
}
if (fname == ".") {
if (offset == 0)
throw Exception ("invalid offset specified for embedded MRtrix image \"" + H.name() + "\"");
fname = H.name();
} else {
if (fname[0] != PATH_SEPARATOR[0]
#ifdef MRTRIX_WINDOWS
&& fname[0] != PATH_SEPARATOR[1]
#endif
)
fname = Path::join (Path::dirname (H.name()), fname);
}
}
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include "webkit/appcache/appcache.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "webkit/appcache/appcache_group.h"
#include "webkit/appcache/appcache_host.h"
#include "webkit/appcache/appcache_interfaces.h"
#include "webkit/appcache/appcache_service.h"
#include "webkit/appcache/appcache_storage.h"
namespace appcache {
AppCache::AppCache(AppCacheService *service, int64 cache_id)
: cache_id_(cache_id),
owning_group_(NULL),
online_whitelist_all_(false),
is_complete_(false),
cache_size_(0),
service_(service) {
service_->storage()->working_set()->AddCache(this);
}
AppCache::~AppCache() {
DCHECK(associated_hosts_.empty());
if (owning_group_) {
DCHECK(is_complete_);
owning_group_->RemoveCache(this);
}
DCHECK(!owning_group_);
service_->storage()->working_set()->RemoveCache(this);
}
void AppCache::UnassociateHost(AppCacheHost* host) {
associated_hosts_.erase(host);
}
void AppCache::AddEntry(const GURL& url, const AppCacheEntry& entry) {
DCHECK(entries_.find(url) == entries_.end());
entries_.insert(EntryMap::value_type(url, entry));
cache_size_ += entry.response_size();
}
bool AppCache::AddOrModifyEntry(const GURL& url, const AppCacheEntry& entry) {
std::pair<EntryMap::iterator, bool> ret =
entries_.insert(EntryMap::value_type(url, entry));
// Entry already exists. Merge the types of the new and existing entries.
if (!ret.second)
ret.first->second.add_types(entry.types());
else
cache_size_ += entry.response_size(); // New entry. Add to cache size.
return ret.second;
}
void AppCache::RemoveEntry(const GURL& url) {
EntryMap::iterator found = entries_.find(url);
DCHECK(found != entries_.end());
cache_size_ -= found->second.response_size();
entries_.erase(found);
}
AppCacheEntry* AppCache::GetEntry(const GURL& url) {
EntryMap::iterator it = entries_.find(url);
return (it != entries_.end()) ? &(it->second) : NULL;
}
GURL AppCache::GetFallbackEntryUrl(const GURL& namespace_url) const {
size_t count = fallback_namespaces_.size();
for (size_t i = 0; i < count; ++i) {
if (fallback_namespaces_[i].first == namespace_url)
return fallback_namespaces_[i].second;
}
NOTREACHED();
return GURL();
}
namespace {
bool SortByLength(
const FallbackNamespace& lhs, const FallbackNamespace& rhs) {
return lhs.first.spec().length() > rhs.first.spec().length();
}
}
void AppCache::InitializeWithManifest(Manifest* manifest) {
DCHECK(manifest);
fallback_namespaces_.swap(manifest->fallback_namespaces);
online_whitelist_namespaces_.swap(manifest->online_whitelist_namespaces);
online_whitelist_all_ = manifest->online_whitelist_all;
// Sort the fallback namespaces by url string length, longest to shortest,
// since longer matches trump when matching a url to a namespace.
std::sort(fallback_namespaces_.begin(), fallback_namespaces_.end(),
SortByLength);
}
void AppCache::InitializeWithDatabaseRecords(
const AppCacheDatabase::CacheRecord& cache_record,
const std::vector<AppCacheDatabase::EntryRecord>& entries,
const std::vector<AppCacheDatabase::FallbackNameSpaceRecord>& fallbacks,
const std::vector<AppCacheDatabase::OnlineWhiteListRecord>& whitelists) {
DCHECK(cache_id_ == cache_record.cache_id);
online_whitelist_all_ = cache_record.online_wildcard;
update_time_ = cache_record.update_time;
for (size_t i = 0; i < entries.size(); ++i) {
const AppCacheDatabase::EntryRecord& entry = entries.at(i);
AddEntry(entry.url, AppCacheEntry(entry.flags, entry.response_id,
entry.response_size));
}
DCHECK(cache_size_ == cache_record.cache_size);
for (size_t i = 0; i < fallbacks.size(); ++i) {
const AppCacheDatabase::FallbackNameSpaceRecord& fallback = fallbacks.at(i);
fallback_namespaces_.push_back(
FallbackNamespace(fallback.namespace_url, fallback.fallback_entry_url));
}
// Sort the fallback namespaces by url string length, longest to shortest,
// since longer matches trump when matching a url to a namespace.
std::sort(fallback_namespaces_.begin(), fallback_namespaces_.end(),
SortByLength);
if (!online_whitelist_all_) {
for (size_t i = 0; i < whitelists.size(); ++i) {
online_whitelist_namespaces_.push_back(whitelists.at(i).namespace_url);
}
}
}
void AppCache::ToDatabaseRecords(
const AppCacheGroup* group,
AppCacheDatabase::CacheRecord* cache_record,
std::vector<AppCacheDatabase::EntryRecord>* entries,
std::vector<AppCacheDatabase::FallbackNameSpaceRecord>* fallbacks,
std::vector<AppCacheDatabase::OnlineWhiteListRecord>* whitelists) {
DCHECK(group && cache_record && entries && fallbacks && whitelists);
DCHECK(entries->empty() && fallbacks->empty() && whitelists->empty());
cache_record->cache_id = cache_id_;
cache_record->group_id = group->group_id();
cache_record->online_wildcard = online_whitelist_all_;
cache_record->update_time = update_time_;
cache_record->cache_size = 0;
for (EntryMap::const_iterator iter = entries_.begin();
iter != entries_.end(); ++iter) {
entries->push_back(AppCacheDatabase::EntryRecord());
AppCacheDatabase::EntryRecord& record = entries->back();
record.url = iter->first;
record.cache_id = cache_id_;
record.flags = iter->second.types();
record.response_id = iter->second.response_id();
record.response_size = iter->second.response_size();
cache_record->cache_size += record.response_size;
}
GURL origin = group->manifest_url().GetOrigin();
for (size_t i = 0; i < fallback_namespaces_.size(); ++i) {
fallbacks->push_back(AppCacheDatabase::FallbackNameSpaceRecord());
AppCacheDatabase::FallbackNameSpaceRecord& record = fallbacks->back();
record.cache_id = cache_id_;
record.origin = origin;
record.namespace_url = fallback_namespaces_[i].first;
record.fallback_entry_url = fallback_namespaces_[i].second;
}
if (!online_whitelist_all_) {
for (size_t i = 0; i < online_whitelist_namespaces_.size(); ++i) {
whitelists->push_back(AppCacheDatabase::OnlineWhiteListRecord());
AppCacheDatabase::OnlineWhiteListRecord& record = whitelists->back();
record.cache_id = cache_id_;
record.namespace_url = online_whitelist_namespaces_[i];
}
}
}
bool AppCache::FindResponseForRequest(const GURL& url,
AppCacheEntry* found_entry, AppCacheEntry* found_fallback_entry,
GURL* found_fallback_namespace, bool* found_network_namespace) {
// Ignore fragments when looking up URL in the cache.
GURL url_no_ref;
if (url.has_ref()) {
GURL::Replacements replacements;
replacements.ClearRef();
url_no_ref = url.ReplaceComponents(replacements);
} else {
url_no_ref = url;
}
// 6.6.6 Changes to the networking model
AppCacheEntry* entry = GetEntry(url_no_ref);
if (entry) {
*found_entry = *entry;
return true;
}
if (*found_network_namespace =
IsInNetworkNamespace(url_no_ref, online_whitelist_namespaces_)) {
return true;
}
FallbackNamespace* fallback_namespace = FindFallbackNamespace(url_no_ref);
if (fallback_namespace) {
entry = GetEntry(fallback_namespace->second);
DCHECK(entry);
*found_fallback_entry = *entry;
*found_fallback_namespace = fallback_namespace->first;
return true;
}
*found_network_namespace = online_whitelist_all_;
return *found_network_namespace;
}
FallbackNamespace* AppCache::FindFallbackNamespace(const GURL& url) {
size_t count = fallback_namespaces_.size();
for (size_t i = 0; i < count; ++i) {
if (StartsWithASCII(
url.spec(), fallback_namespaces_[i].first.spec(), true)) {
return &fallback_namespaces_[i];
}
}
return NULL;
}
// static
bool AppCache::IsInNetworkNamespace(
const GURL& url,
const std::vector<GURL> &namespaces) {
// TODO(michaeln): There are certainly better 'prefix matching'
// structures and algorithms that can be applied here and above.
size_t count = namespaces.size();
for (size_t i = 0; i < count; ++i) {
if (StartsWithASCII(url.spec(), namespaces[i].spec(), true))
return true;
}
return false;
}
} // namespace appcache
<commit_msg>Fix busted build.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include "webkit/appcache/appcache.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "webkit/appcache/appcache_group.h"
#include "webkit/appcache/appcache_host.h"
#include "webkit/appcache/appcache_interfaces.h"
#include "webkit/appcache/appcache_service.h"
#include "webkit/appcache/appcache_storage.h"
namespace appcache {
AppCache::AppCache(AppCacheService *service, int64 cache_id)
: cache_id_(cache_id),
owning_group_(NULL),
online_whitelist_all_(false),
is_complete_(false),
cache_size_(0),
service_(service) {
service_->storage()->working_set()->AddCache(this);
}
AppCache::~AppCache() {
DCHECK(associated_hosts_.empty());
if (owning_group_) {
DCHECK(is_complete_);
owning_group_->RemoveCache(this);
}
DCHECK(!owning_group_);
service_->storage()->working_set()->RemoveCache(this);
}
void AppCache::UnassociateHost(AppCacheHost* host) {
associated_hosts_.erase(host);
}
void AppCache::AddEntry(const GURL& url, const AppCacheEntry& entry) {
DCHECK(entries_.find(url) == entries_.end());
entries_.insert(EntryMap::value_type(url, entry));
cache_size_ += entry.response_size();
}
bool AppCache::AddOrModifyEntry(const GURL& url, const AppCacheEntry& entry) {
std::pair<EntryMap::iterator, bool> ret =
entries_.insert(EntryMap::value_type(url, entry));
// Entry already exists. Merge the types of the new and existing entries.
if (!ret.second)
ret.first->second.add_types(entry.types());
else
cache_size_ += entry.response_size(); // New entry. Add to cache size.
return ret.second;
}
void AppCache::RemoveEntry(const GURL& url) {
EntryMap::iterator found = entries_.find(url);
DCHECK(found != entries_.end());
cache_size_ -= found->second.response_size();
entries_.erase(found);
}
AppCacheEntry* AppCache::GetEntry(const GURL& url) {
EntryMap::iterator it = entries_.find(url);
return (it != entries_.end()) ? &(it->second) : NULL;
}
GURL AppCache::GetFallbackEntryUrl(const GURL& namespace_url) const {
size_t count = fallback_namespaces_.size();
for (size_t i = 0; i < count; ++i) {
if (fallback_namespaces_[i].first == namespace_url)
return fallback_namespaces_[i].second;
}
NOTREACHED();
return GURL();
}
namespace {
bool SortByLength(
const FallbackNamespace& lhs, const FallbackNamespace& rhs) {
return lhs.first.spec().length() > rhs.first.spec().length();
}
}
void AppCache::InitializeWithManifest(Manifest* manifest) {
DCHECK(manifest);
fallback_namespaces_.swap(manifest->fallback_namespaces);
online_whitelist_namespaces_.swap(manifest->online_whitelist_namespaces);
online_whitelist_all_ = manifest->online_whitelist_all;
// Sort the fallback namespaces by url string length, longest to shortest,
// since longer matches trump when matching a url to a namespace.
std::sort(fallback_namespaces_.begin(), fallback_namespaces_.end(),
SortByLength);
}
void AppCache::InitializeWithDatabaseRecords(
const AppCacheDatabase::CacheRecord& cache_record,
const std::vector<AppCacheDatabase::EntryRecord>& entries,
const std::vector<AppCacheDatabase::FallbackNameSpaceRecord>& fallbacks,
const std::vector<AppCacheDatabase::OnlineWhiteListRecord>& whitelists) {
DCHECK(cache_id_ == cache_record.cache_id);
online_whitelist_all_ = cache_record.online_wildcard;
update_time_ = cache_record.update_time;
for (size_t i = 0; i < entries.size(); ++i) {
const AppCacheDatabase::EntryRecord& entry = entries.at(i);
AddEntry(entry.url, AppCacheEntry(entry.flags, entry.response_id,
entry.response_size));
}
DCHECK(cache_size_ == cache_record.cache_size);
for (size_t i = 0; i < fallbacks.size(); ++i) {
const AppCacheDatabase::FallbackNameSpaceRecord& fallback = fallbacks.at(i);
fallback_namespaces_.push_back(
FallbackNamespace(fallback.namespace_url, fallback.fallback_entry_url));
}
// Sort the fallback namespaces by url string length, longest to shortest,
// since longer matches trump when matching a url to a namespace.
std::sort(fallback_namespaces_.begin(), fallback_namespaces_.end(),
SortByLength);
if (!online_whitelist_all_) {
for (size_t i = 0; i < whitelists.size(); ++i) {
online_whitelist_namespaces_.push_back(whitelists.at(i).namespace_url);
}
}
}
void AppCache::ToDatabaseRecords(
const AppCacheGroup* group,
AppCacheDatabase::CacheRecord* cache_record,
std::vector<AppCacheDatabase::EntryRecord>* entries,
std::vector<AppCacheDatabase::FallbackNameSpaceRecord>* fallbacks,
std::vector<AppCacheDatabase::OnlineWhiteListRecord>* whitelists) {
DCHECK(group && cache_record && entries && fallbacks && whitelists);
DCHECK(entries->empty() && fallbacks->empty() && whitelists->empty());
cache_record->cache_id = cache_id_;
cache_record->group_id = group->group_id();
cache_record->online_wildcard = online_whitelist_all_;
cache_record->update_time = update_time_;
cache_record->cache_size = 0;
for (EntryMap::const_iterator iter = entries_.begin();
iter != entries_.end(); ++iter) {
entries->push_back(AppCacheDatabase::EntryRecord());
AppCacheDatabase::EntryRecord& record = entries->back();
record.url = iter->first;
record.cache_id = cache_id_;
record.flags = iter->second.types();
record.response_id = iter->second.response_id();
record.response_size = iter->second.response_size();
cache_record->cache_size += record.response_size;
}
GURL origin = group->manifest_url().GetOrigin();
for (size_t i = 0; i < fallback_namespaces_.size(); ++i) {
fallbacks->push_back(AppCacheDatabase::FallbackNameSpaceRecord());
AppCacheDatabase::FallbackNameSpaceRecord& record = fallbacks->back();
record.cache_id = cache_id_;
record.origin = origin;
record.namespace_url = fallback_namespaces_[i].first;
record.fallback_entry_url = fallback_namespaces_[i].second;
}
if (!online_whitelist_all_) {
for (size_t i = 0; i < online_whitelist_namespaces_.size(); ++i) {
whitelists->push_back(AppCacheDatabase::OnlineWhiteListRecord());
AppCacheDatabase::OnlineWhiteListRecord& record = whitelists->back();
record.cache_id = cache_id_;
record.namespace_url = online_whitelist_namespaces_[i];
}
}
}
bool AppCache::FindResponseForRequest(const GURL& url,
AppCacheEntry* found_entry, AppCacheEntry* found_fallback_entry,
GURL* found_fallback_namespace, bool* found_network_namespace) {
// Ignore fragments when looking up URL in the cache.
GURL url_no_ref;
if (url.has_ref()) {
GURL::Replacements replacements;
replacements.ClearRef();
url_no_ref = url.ReplaceComponents(replacements);
} else {
url_no_ref = url;
}
// 6.6.6 Changes to the networking model
AppCacheEntry* entry = GetEntry(url_no_ref);
if (entry) {
*found_entry = *entry;
return true;
}
if ((*found_network_namespace =
IsInNetworkNamespace(url_no_ref, online_whitelist_namespaces_))) {
return true;
}
FallbackNamespace* fallback_namespace = FindFallbackNamespace(url_no_ref);
if (fallback_namespace) {
entry = GetEntry(fallback_namespace->second);
DCHECK(entry);
*found_fallback_entry = *entry;
*found_fallback_namespace = fallback_namespace->first;
return true;
}
*found_network_namespace = online_whitelist_all_;
return *found_network_namespace;
}
FallbackNamespace* AppCache::FindFallbackNamespace(const GURL& url) {
size_t count = fallback_namespaces_.size();
for (size_t i = 0; i < count; ++i) {
if (StartsWithASCII(
url.spec(), fallback_namespaces_[i].first.spec(), true)) {
return &fallback_namespaces_[i];
}
}
return NULL;
}
// static
bool AppCache::IsInNetworkNamespace(
const GURL& url,
const std::vector<GURL> &namespaces) {
// TODO(michaeln): There are certainly better 'prefix matching'
// structures and algorithms that can be applied here and above.
size_t count = namespaces.size();
for (size_t i = 0; i < count; ++i) {
if (StartsWithASCII(url.spec(), namespaces[i].spec(), true))
return true;
}
return false;
}
} // namespace appcache
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/test/vcm_capturer.h"
#include "webrtc/modules/video_capture/video_capture_factory.h"
#include "webrtc/video_send_stream.h"
namespace webrtc {
namespace test {
VcmCapturer::VcmCapturer() : started_(false), sink_(nullptr), vcm_(NULL) {}
bool VcmCapturer::Init(size_t width, size_t height, size_t target_fps) {
VideoCaptureModule::DeviceInfo* device_info =
VideoCaptureFactory::CreateDeviceInfo(42); // Any ID (42) will do.
char device_name[256];
char unique_name[256];
if (device_info->GetDeviceName(0, device_name, sizeof(device_name),
unique_name, sizeof(unique_name)) !=
0) {
Destroy();
return false;
}
vcm_ = webrtc::VideoCaptureFactory::Create(0, unique_name);
vcm_->RegisterCaptureDataCallback(*this);
device_info->GetCapability(vcm_->CurrentDeviceName(), 0, capability_);
delete device_info;
capability_.width = static_cast<int32_t>(width);
capability_.height = static_cast<int32_t>(height);
capability_.maxFPS = static_cast<int32_t>(target_fps);
capability_.rawType = kVideoI420;
if (vcm_->StartCapture(capability_) != 0) {
Destroy();
return false;
}
assert(vcm_->CaptureStarted());
return true;
}
VcmCapturer* VcmCapturer::Create(size_t width,
size_t height,
size_t target_fps) {
VcmCapturer* vcm_capturer = new VcmCapturer();
if (!vcm_capturer->Init(width, height, target_fps)) {
// TODO(pbos): Log a warning that this failed.
delete vcm_capturer;
return NULL;
}
return vcm_capturer;
}
void VcmCapturer::Start() {
rtc::CritScope lock(&crit_);
started_ = true;
}
void VcmCapturer::Stop() {
rtc::CritScope lock(&crit_);
started_ = false;
}
void VcmCapturer::AddOrUpdateSink(rtc::VideoSinkInterface<VideoFrame>* sink,
const rtc::VideoSinkWants& wants) {
rtc::CritScope lock(&crit_);
RTC_CHECK(!sink_);
sink_ = sink;
}
void VcmCapturer::RemoveSink(rtc::VideoSinkInterface<VideoFrame>* sink) {
rtc::CritScope lock(&crit_);
RTC_CHECK(sink_ == sink);
sink_ = nullptr;
}
void VcmCapturer::Destroy() {
if (!vcm_)
return;
vcm_->StopCapture();
vcm_->DeRegisterCaptureDataCallback();
// Release reference to VCM.
vcm_ = nullptr;
}
VcmCapturer::~VcmCapturer() { Destroy(); }
void VcmCapturer::OnIncomingCapturedFrame(const int32_t id,
const VideoFrame& frame) {
rtc::CritScope lock(&crit_);
if (started_ && sink_)
sink_->OnFrame(frame);
}
void VcmCapturer::OnCaptureDelayChanged(const int32_t id, const int32_t delay) {
}
} // test
} // webrtc
<commit_msg>Allow webrtc::test::VcmCapturer to be updated with its current sink.<commit_after>/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/test/vcm_capturer.h"
#include "webrtc/modules/video_capture/video_capture_factory.h"
#include "webrtc/video_send_stream.h"
namespace webrtc {
namespace test {
VcmCapturer::VcmCapturer() : started_(false), sink_(nullptr), vcm_(NULL) {}
bool VcmCapturer::Init(size_t width, size_t height, size_t target_fps) {
VideoCaptureModule::DeviceInfo* device_info =
VideoCaptureFactory::CreateDeviceInfo(42); // Any ID (42) will do.
char device_name[256];
char unique_name[256];
if (device_info->GetDeviceName(0, device_name, sizeof(device_name),
unique_name, sizeof(unique_name)) !=
0) {
Destroy();
return false;
}
vcm_ = webrtc::VideoCaptureFactory::Create(0, unique_name);
vcm_->RegisterCaptureDataCallback(*this);
device_info->GetCapability(vcm_->CurrentDeviceName(), 0, capability_);
delete device_info;
capability_.width = static_cast<int32_t>(width);
capability_.height = static_cast<int32_t>(height);
capability_.maxFPS = static_cast<int32_t>(target_fps);
capability_.rawType = kVideoI420;
if (vcm_->StartCapture(capability_) != 0) {
Destroy();
return false;
}
assert(vcm_->CaptureStarted());
return true;
}
VcmCapturer* VcmCapturer::Create(size_t width,
size_t height,
size_t target_fps) {
VcmCapturer* vcm_capturer = new VcmCapturer();
if (!vcm_capturer->Init(width, height, target_fps)) {
// TODO(pbos): Log a warning that this failed.
delete vcm_capturer;
return NULL;
}
return vcm_capturer;
}
void VcmCapturer::Start() {
rtc::CritScope lock(&crit_);
started_ = true;
}
void VcmCapturer::Stop() {
rtc::CritScope lock(&crit_);
started_ = false;
}
void VcmCapturer::AddOrUpdateSink(rtc::VideoSinkInterface<VideoFrame>* sink,
const rtc::VideoSinkWants& wants) {
rtc::CritScope lock(&crit_);
RTC_CHECK(!sink_ || sink_ == sink);
sink_ = sink;
}
void VcmCapturer::RemoveSink(rtc::VideoSinkInterface<VideoFrame>* sink) {
rtc::CritScope lock(&crit_);
RTC_CHECK(sink_ == sink);
sink_ = nullptr;
}
void VcmCapturer::Destroy() {
if (!vcm_)
return;
vcm_->StopCapture();
vcm_->DeRegisterCaptureDataCallback();
// Release reference to VCM.
vcm_ = nullptr;
}
VcmCapturer::~VcmCapturer() { Destroy(); }
void VcmCapturer::OnIncomingCapturedFrame(const int32_t id,
const VideoFrame& frame) {
rtc::CritScope lock(&crit_);
if (started_ && sink_)
sink_->OnFrame(frame);
}
void VcmCapturer::OnCaptureDelayChanged(const int32_t id, const int32_t delay) {
}
} // test
} // webrtc
<|endoftext|> |
<commit_before>//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include <string.h>
#include <cassert>
#include <vector>
#include "EGLWindow.h"
#include "OSWindow.h"
#ifdef _WIN32
#elif __linux__
#else
#error unsupported OS.
#endif
EGLPlatformParameters::EGLPlatformParameters()
: renderer(EGL_PLATFORM_ANGLE_TYPE_DEFAULT_ANGLE),
majorVersion(EGL_DONT_CARE),
minorVersion(EGL_DONT_CARE),
deviceType(EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE)
{
}
EGLPlatformParameters::EGLPlatformParameters(EGLint renderer)
: renderer(renderer),
majorVersion(EGL_DONT_CARE),
minorVersion(EGL_DONT_CARE),
deviceType(EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE)
{
}
EGLPlatformParameters::EGLPlatformParameters(EGLint renderer, EGLint majorVersion, EGLint minorVersion, EGLint useWarp)
: renderer(renderer),
majorVersion(majorVersion),
minorVersion(minorVersion),
deviceType(useWarp)
{
}
EGLWindow::EGLWindow(size_t width, size_t height, EGLint glesMajorVersion, const EGLPlatformParameters &platform)
: mSurface(EGL_NO_SURFACE),
mContext(EGL_NO_CONTEXT),
mDisplay(EGL_NO_DISPLAY),
mClientVersion(glesMajorVersion),
mPlatform(platform),
mWidth(width),
mHeight(height),
mRedBits(-1),
mGreenBits(-1),
mBlueBits(-1),
mAlphaBits(-1),
mDepthBits(-1),
mStencilBits(-1),
mMultisample(false),
mSwapInterval(-1)
{
}
EGLWindow::~EGLWindow()
{
destroyGL();
}
void EGLWindow::swap()
{
eglSwapBuffers(mDisplay, mSurface);
}
EGLConfig EGLWindow::getConfig() const
{
return mConfig;
}
EGLDisplay EGLWindow::getDisplay() const
{
return mDisplay;
}
EGLSurface EGLWindow::getSurface() const
{
return mSurface;
}
EGLContext EGLWindow::getContext() const
{
return mContext;
}
bool EGLWindow::initializeGL(OSWindow *osWindow)
{
PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(eglGetProcAddress("eglGetPlatformDisplayEXT"));
if (!eglGetPlatformDisplayEXT)
{
return false;
}
std::vector<EGLint> displayAttributes;
displayAttributes.push_back(EGL_PLATFORM_ANGLE_TYPE_ANGLE);
displayAttributes.push_back(mPlatform.renderer);
displayAttributes.push_back(EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE);
displayAttributes.push_back(mPlatform.majorVersion);
displayAttributes.push_back(EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE);
displayAttributes.push_back(mPlatform.minorVersion);
if (mPlatform.renderer == EGL_PLATFORM_ANGLE_TYPE_D3D9_ANGLE || mPlatform.renderer == EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE)
{
displayAttributes.push_back(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE);
displayAttributes.push_back(mPlatform.deviceType);
}
displayAttributes.push_back(EGL_NONE);
mDisplay = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, osWindow->getNativeDisplay(), displayAttributes.data());
if (mDisplay == EGL_NO_DISPLAY)
{
destroyGL();
return false;
}
EGLint majorVersion, minorVersion;
if (!eglInitialize(mDisplay, &majorVersion, &minorVersion))
{
destroyGL();
return false;
}
eglBindAPI(EGL_OPENGL_ES_API);
if (eglGetError() != EGL_SUCCESS)
{
destroyGL();
return false;
}
const EGLint configAttributes[] =
{
EGL_RED_SIZE, (mRedBits >= 0) ? mRedBits : EGL_DONT_CARE,
EGL_GREEN_SIZE, (mGreenBits >= 0) ? mGreenBits : EGL_DONT_CARE,
EGL_BLUE_SIZE, (mBlueBits >= 0) ? mBlueBits : EGL_DONT_CARE,
EGL_ALPHA_SIZE, (mAlphaBits >= 0) ? mAlphaBits : EGL_DONT_CARE,
EGL_DEPTH_SIZE, (mDepthBits >= 0) ? mDepthBits : EGL_DONT_CARE,
EGL_STENCIL_SIZE, (mStencilBits >= 0) ? mStencilBits : EGL_DONT_CARE,
EGL_SAMPLE_BUFFERS, mMultisample ? 1 : 0,
EGL_NONE
};
EGLint configCount;
if (!eglChooseConfig(mDisplay, configAttributes, &mConfig, 1, &configCount) || (configCount != 1))
{
destroyGL();
return false;
}
eglGetConfigAttrib(mDisplay, mConfig, EGL_RED_SIZE, &mRedBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_GREEN_SIZE, &mGreenBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_BLUE_SIZE, &mBlueBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_ALPHA_SIZE, &mBlueBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_DEPTH_SIZE, &mDepthBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_STENCIL_SIZE, &mStencilBits);
std::vector<EGLint> surfaceAttributes;
if (strstr(eglQueryString(mDisplay, EGL_EXTENSIONS), "EGL_NV_post_sub_buffer") != nullptr)
{
surfaceAttributes.push_back(EGL_POST_SUB_BUFFER_SUPPORTED_NV);
surfaceAttributes.push_back(EGL_TRUE);
}
surfaceAttributes.push_back(EGL_NONE);
surfaceAttributes.push_back(EGL_NONE);
mSurface = eglCreateWindowSurface(mDisplay, mConfig, osWindow->getNativeWindow(), &surfaceAttributes[0]);
if (mSurface == EGL_NO_SURFACE)
{
eglGetError(); // Clear error and try again
mSurface = eglCreateWindowSurface(mDisplay, mConfig, NULL, NULL);
}
if (eglGetError() != EGL_SUCCESS)
{
destroyGL();
return false;
}
EGLint contextAttibutes[] =
{
EGL_CONTEXT_CLIENT_VERSION, mClientVersion,
EGL_NONE
};
mContext = eglCreateContext(mDisplay, mConfig, NULL, contextAttibutes);
if (eglGetError() != EGL_SUCCESS)
{
destroyGL();
return false;
}
eglMakeCurrent(mDisplay, mSurface, mSurface, mContext);
if (eglGetError() != EGL_SUCCESS)
{
destroyGL();
return false;
}
if (mSwapInterval != -1)
{
eglSwapInterval(mDisplay, mSwapInterval);
}
return true;
}
void EGLWindow::destroyGL()
{
if (mSurface != EGL_NO_SURFACE)
{
assert(mDisplay != EGL_NO_DISPLAY);
eglDestroySurface(mDisplay, mSurface);
mSurface = EGL_NO_SURFACE;
}
if (mContext != EGL_NO_CONTEXT)
{
assert(mDisplay != EGL_NO_DISPLAY);
eglDestroyContext(mDisplay, mContext);
mContext = EGL_NO_CONTEXT;
}
if (mDisplay != EGL_NO_DISPLAY)
{
eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglTerminate(mDisplay);
mDisplay = EGL_NO_DISPLAY;
}
}
bool EGLWindow::isGLInitialized() const
{
return mSurface != EGL_NO_SURFACE &&
mContext != EGL_NO_CONTEXT &&
mDisplay != EGL_NO_DISPLAY;
}
<commit_msg>Revert "EGLWindow: specify the device type only on d3d platform"<commit_after>//
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include <string.h>
#include <cassert>
#include <vector>
#include "EGLWindow.h"
#include "OSWindow.h"
#ifdef _WIN32
#elif __linux__
#else
#error unsupported OS.
#endif
EGLPlatformParameters::EGLPlatformParameters()
: renderer(EGL_PLATFORM_ANGLE_TYPE_DEFAULT_ANGLE),
majorVersion(EGL_DONT_CARE),
minorVersion(EGL_DONT_CARE),
deviceType(EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE)
{
}
EGLPlatformParameters::EGLPlatformParameters(EGLint renderer)
: renderer(renderer),
majorVersion(EGL_DONT_CARE),
minorVersion(EGL_DONT_CARE),
deviceType(EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE)
{
}
EGLPlatformParameters::EGLPlatformParameters(EGLint renderer, EGLint majorVersion, EGLint minorVersion, EGLint useWarp)
: renderer(renderer),
majorVersion(majorVersion),
minorVersion(minorVersion),
deviceType(useWarp)
{
}
EGLWindow::EGLWindow(size_t width, size_t height, EGLint glesMajorVersion, const EGLPlatformParameters &platform)
: mSurface(EGL_NO_SURFACE),
mContext(EGL_NO_CONTEXT),
mDisplay(EGL_NO_DISPLAY),
mClientVersion(glesMajorVersion),
mPlatform(platform),
mWidth(width),
mHeight(height),
mRedBits(-1),
mGreenBits(-1),
mBlueBits(-1),
mAlphaBits(-1),
mDepthBits(-1),
mStencilBits(-1),
mMultisample(false),
mSwapInterval(-1)
{
}
EGLWindow::~EGLWindow()
{
destroyGL();
}
void EGLWindow::swap()
{
eglSwapBuffers(mDisplay, mSurface);
}
EGLConfig EGLWindow::getConfig() const
{
return mConfig;
}
EGLDisplay EGLWindow::getDisplay() const
{
return mDisplay;
}
EGLSurface EGLWindow::getSurface() const
{
return mSurface;
}
EGLContext EGLWindow::getContext() const
{
return mContext;
}
bool EGLWindow::initializeGL(OSWindow *osWindow)
{
PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(eglGetProcAddress("eglGetPlatformDisplayEXT"));
if (!eglGetPlatformDisplayEXT)
{
return false;
}
const EGLint displayAttributes[] =
{
EGL_PLATFORM_ANGLE_TYPE_ANGLE, mPlatform.renderer,
EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, mPlatform.majorVersion,
EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, mPlatform.minorVersion,
EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE, mPlatform.deviceType,
EGL_NONE,
};
mDisplay = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, osWindow->getNativeDisplay(), displayAttributes);
if (mDisplay == EGL_NO_DISPLAY)
{
destroyGL();
return false;
}
EGLint majorVersion, minorVersion;
if (!eglInitialize(mDisplay, &majorVersion, &minorVersion))
{
destroyGL();
return false;
}
eglBindAPI(EGL_OPENGL_ES_API);
if (eglGetError() != EGL_SUCCESS)
{
destroyGL();
return false;
}
const EGLint configAttributes[] =
{
EGL_RED_SIZE, (mRedBits >= 0) ? mRedBits : EGL_DONT_CARE,
EGL_GREEN_SIZE, (mGreenBits >= 0) ? mGreenBits : EGL_DONT_CARE,
EGL_BLUE_SIZE, (mBlueBits >= 0) ? mBlueBits : EGL_DONT_CARE,
EGL_ALPHA_SIZE, (mAlphaBits >= 0) ? mAlphaBits : EGL_DONT_CARE,
EGL_DEPTH_SIZE, (mDepthBits >= 0) ? mDepthBits : EGL_DONT_CARE,
EGL_STENCIL_SIZE, (mStencilBits >= 0) ? mStencilBits : EGL_DONT_CARE,
EGL_SAMPLE_BUFFERS, mMultisample ? 1 : 0,
EGL_NONE
};
EGLint configCount;
if (!eglChooseConfig(mDisplay, configAttributes, &mConfig, 1, &configCount) || (configCount != 1))
{
destroyGL();
return false;
}
eglGetConfigAttrib(mDisplay, mConfig, EGL_RED_SIZE, &mRedBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_GREEN_SIZE, &mGreenBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_BLUE_SIZE, &mBlueBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_ALPHA_SIZE, &mBlueBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_DEPTH_SIZE, &mDepthBits);
eglGetConfigAttrib(mDisplay, mConfig, EGL_STENCIL_SIZE, &mStencilBits);
std::vector<EGLint> surfaceAttributes;
if (strstr(eglQueryString(mDisplay, EGL_EXTENSIONS), "EGL_NV_post_sub_buffer") != nullptr)
{
surfaceAttributes.push_back(EGL_POST_SUB_BUFFER_SUPPORTED_NV);
surfaceAttributes.push_back(EGL_TRUE);
}
surfaceAttributes.push_back(EGL_NONE);
surfaceAttributes.push_back(EGL_NONE);
mSurface = eglCreateWindowSurface(mDisplay, mConfig, osWindow->getNativeWindow(), &surfaceAttributes[0]);
if (mSurface == EGL_NO_SURFACE)
{
eglGetError(); // Clear error and try again
mSurface = eglCreateWindowSurface(mDisplay, mConfig, NULL, NULL);
}
if (eglGetError() != EGL_SUCCESS)
{
destroyGL();
return false;
}
EGLint contextAttibutes[] =
{
EGL_CONTEXT_CLIENT_VERSION, mClientVersion,
EGL_NONE
};
mContext = eglCreateContext(mDisplay, mConfig, NULL, contextAttibutes);
if (eglGetError() != EGL_SUCCESS)
{
destroyGL();
return false;
}
eglMakeCurrent(mDisplay, mSurface, mSurface, mContext);
if (eglGetError() != EGL_SUCCESS)
{
destroyGL();
return false;
}
if (mSwapInterval != -1)
{
eglSwapInterval(mDisplay, mSwapInterval);
}
return true;
}
void EGLWindow::destroyGL()
{
if (mSurface != EGL_NO_SURFACE)
{
assert(mDisplay != EGL_NO_DISPLAY);
eglDestroySurface(mDisplay, mSurface);
mSurface = EGL_NO_SURFACE;
}
if (mContext != EGL_NO_CONTEXT)
{
assert(mDisplay != EGL_NO_DISPLAY);
eglDestroyContext(mDisplay, mContext);
mContext = EGL_NO_CONTEXT;
}
if (mDisplay != EGL_NO_DISPLAY)
{
eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglTerminate(mDisplay);
mDisplay = EGL_NO_DISPLAY;
}
}
bool EGLWindow::isGLInitialized() const
{
return mSurface != EGL_NO_SURFACE &&
mContext != EGL_NO_CONTEXT &&
mDisplay != EGL_NO_DISPLAY;
}
<|endoftext|> |
<commit_before>/*
* RemoteHttpResource.cpp
*
* Created on: Feb 22, 2013
* Author: ndp
*/
#include <sstream>
#include <GNURegex.h>
#include "util.h"
#include "debug.h"
#include "Error.h"
#include "BESSyntaxUserError.h"
#include "BESInternalError.h"
#include "BESError.h"
#include "BESRegex.h"
#include "TheBESKeys.h"
#include "GatewayUtils.h"
#include "curl_utils.h"
#include "RemoteHttpResource.h"
using namespace std;
static string long_to_string(unsigned long value)
{
std::ostringstream stream;
stream << value;
return stream.str();
}
namespace gateway {
RemoteHttpResource::RemoteHttpResource() {
d_fd = 0;
d_fstrm = 0;
d_curl = 0;
d_resourceCacheFileName.clear();
d_response_headers = 0;
d_request_headers = 0;
_initialized = false;
}
RemoteHttpResource::~RemoteHttpResource() {
BESDEBUG("gateway", "~RemoteHttpResource() - BEGIN resourceURL: " << d_remoteResourceUrl << endl);
if(d_response_headers){
delete d_response_headers;
d_response_headers = 0;
BESDEBUG("gateway", "~RemoteHttpResource() - Deleted d_response_headers." << endl);
}
if(d_request_headers){
delete d_request_headers;
d_request_headers = 0;
BESDEBUG("gateway", "~RemoteHttpResource() - Deleted d_request_headers." << endl);
}
//@TODO Do we need to check for open files somewhere? OR is this all good?
// It seems like that when we call cache->create_and_lock(d_resourceCacheFileName, fd)
// or cache->get_read_lock(d_resourceCacheFileName, fd) we open a file (using open) and we
// get back the integer valued file descriptor and a cache file name. Then we are very careful
// to rewind the file stream thingy and to leave the file open. I'm thinking that we rewind it
// to be good citizens so to speak - that way if a down stream piece of code does choose to
// utilize the open file descriptor or FILE * then it's all ready.
//
// BUT - The old code in gateway_module never utilized the file pointer. It just gets the
// cache file name string and then I think, opens it AGAIN somewhere downstream in BES land
// and reads the data from the cached file.
//
// Does calling unlock_and_close() below close all those files up? Is keeping the file open
// part of the trick to make the cache work? It uses a file locking thingy?
if(!d_resourceCacheFileName.empty()){
BESCache3::get_instance()->unlock_and_close(d_resourceCacheFileName);
BESDEBUG("gateway", "~RemoteHttpResource() - Closed and unlocked "<< d_resourceCacheFileName << endl);
d_resourceCacheFileName.clear();
}
if(d_curl!=0){
curl_easy_cleanup(d_curl);
BESDEBUG("gateway", "~RemoteHttpResource() - Called curl_easy_cleanup()." << endl);
}
d_curl = 0;
BESDEBUG("gateway", "~RemoteHttpResource() - END resourceURL: " << d_remoteResourceUrl << endl);
d_remoteResourceUrl.clear();
}
RemoteHttpResource::RemoteHttpResource(const string &url)
{
_initialized = false;
d_fd = 0;
d_fstrm = 0;
d_curl = 0;
d_resourceCacheFileName.clear();
d_response_headers = new vector<string>();
d_request_headers = new vector<string>();
if( url.empty() )
{
string err = "RemoteHttpResource(): Remote resource URL is empty" ;
throw BESInternalError( err, __FILE__, __LINE__ ) ;
}
d_remoteResourceUrl = url;
BESDEBUG("gateway", "RemoteHttpResource() - URL: " << d_remoteResourceUrl << endl);
/*
*
*
* EXAMPLE: returned value parameter for CURL *
*
CURL *www_lib_init(CURL **curl); // function type signature
CURL *pvparam = 0; // passed value parameter
result = www_lib_init(&pvparam); // the call to the method
*/
d_curl = gateway::www_lib_init(d_remoteResourceUrl, d_error_buffer); // This may throw either Error or InternalErr
BESDEBUG("gateway", "RemoteHttpResource() - d_curl: " << d_curl << endl);
}
void RemoteHttpResource::retrieveResource()
{
BESDEBUG("gateway", "RemoteHttpResource::retrieveResource() - BEGIN resourceURL: " << d_remoteResourceUrl << endl);
if(_initialized){
BESDEBUG("gateway", "RemoteHttpResource::retrieveResource() - END Already initialized." << endl);
return;
}
// Get a pointer to the singleton cache instance for this process.
BESCache3 *cache = BESCache3::get_instance(TheBESKeys::TheKeys(), (string)"BES.CacheDir",
(string)"BES.CachePrefix", (string)"BES.CacheSize");
// Get the name of the file in the cache (either the code finds this file or
// or it makes it).
// @TODO Fix BESCache3 so that you can ask it to NOT strip the suffix which is some kind of funky
// Uncompress feature that should be controllable and probably driven by a regex. Then we can stop
// adding our own suffix so that BESCache3 can remove it.
d_resourceCacheFileName = cache->get_cache_file_name(d_remoteResourceUrl+".gateway");
BESDEBUG("gateway", "RemoteHttpResource::retrieveResource() - d_resourceCacheFileName: " << d_resourceCacheFileName << endl);
// @TODO MAKE THIS RETRIEVE THE CACHED DATA TYPE IF THE CACHED RESPONSE IF FOUND
// We need to know the type of the resource. HTTP headers are the preferred way to determine the type.
// Unfortunately, the current code losses both the HTTP headers sent from the request and the derived type
// to subsequent accesses of the cached object. Since we have to have a type, for now we just set the type
// from the url. If down below we DO an HTTP GET then the headers will be evaluated and the type set by setType()
// But really - we gotta fix this.
GatewayUtils::Get_type_from_url( d_remoteResourceUrl, d_type );
BESDEBUG("gateway", "RemoteHttpResource::retrieveResource() - d_type: " << d_type << endl);
try {
if (cache->get_read_lock(d_resourceCacheFileName, d_fd)) {
BESDEBUG( "gateway", "RemoteHttpResource::retrieveResource() - Remote resource is already in cache. cache_file_name: "
<< d_resourceCacheFileName << endl );
_initialized = true;
return;
}
// Now we actually need to reach out across the interwebs and retrieve the remote resource and put it's
// content into a local cache file, given that it's no in the cache.
// First make an empty file and get an exclusive lock on it.
if (cache->create_and_lock(d_resourceCacheFileName, d_fd)) {
// Write the remote resource to the cache file. Save the returned FILE * cached in the member variable
// * d_fstrm where it can be accessed via the getFileStream() method.
d_fstrm = writeResourceToFile(d_fd);
// Change the exclusive lock on the new file to a shared lock. This keeps
// other processes from purging the new file and ensures that the reading
// process can use it.
cache->exclusive_to_shared_lock(d_fd);
BESDEBUG( "gateway", "RemoteHttpResource::retrieveResource() - Converted exclusive cache lock to shared lock." << endl );
// I think right here is where I would be able to cache the data type/response headers.
// Now update the total cache size info and purge if needed. The new file's
// name is passed into the purge method because this process cannot detect its
// own lock on the file.
unsigned long long size = cache->update_cache_info(d_resourceCacheFileName);
BESDEBUG( "gateway", "RemoteHttpResource::retrieveResource() - Updated cache info" << endl );
if (cache->cache_too_big(size)){
cache->update_and_purge(d_resourceCacheFileName);
BESDEBUG( "gateway", "RemoteHttpResource::retrieveResource() - Updated and purged cache." << endl );
}
BESDEBUG( "gateway", "RemoteHttpResource::retrieveResource() - END" << endl );
_initialized = true;
return;
}
else {
if (cache->get_read_lock(d_resourceCacheFileName, d_fd)) {
BESDEBUG( "gateway", "RemoteHttpResource::retrieveResource() - Remote resource is in cache. cache_file_name: "
<< d_resourceCacheFileName << endl );
_initialized = true;
return;
}
}
string msg = "RemoteHttpResource::retrieveResource() - Failed to acquire cache read lock for remote resource: '";
msg += d_remoteResourceUrl + "\n";
throw libdap::Error(msg);
}
catch (...) {
BESDEBUG( "gateway", "RemoteHttpResource::retrieveResource() - Caught exception, unlocking cache and re-throw." << endl );
cache->unlock_cache();
throw;
}
}
/**
*
* Retrieves the remote resource and write it the the open file associated with the open file
* descriptor parameter 'fd'. In the process of caching the file a FILE * is fdopen'd from 'fd' and that is used buy
* curl to write the content. At the end the stream is rewound and the FILE * pointer is returned.
*
* @param fd An open file descriptor the is associated with the target file.
*/
FILE *RemoteHttpResource::writeResourceToFile(int fd) {
BESDEBUG( "gateway", "RemoteHttpResource::writeResourceToFile() - Saving resource " << d_remoteResourceUrl << " to cache file " << d_resourceCacheFileName << endl );
// fdopen the file using the file descriptor fd so we can pass a FILE * into libcurl
// @TODO JAMES - I know I'm not supposed to close(fd), but what about stream? Is it enough to rewind it?
FILE* stream = fdopen(fd, "w");
int status = -1;
try {
status = gateway::read_url(d_curl, d_remoteResourceUrl, stream, d_response_headers, d_request_headers, d_error_buffer); // Throws Error.
if (status >= 400) {
BESDEBUG( "gateway", "RemoteHttpResource::writeResourceToFile() - HTTP returned an error status: " << status << endl );
// delete resp_hdrs; resp_hdrs = 0;
string msg = "Error while reading the URL: '";
msg += d_remoteResourceUrl;
msg += "'The HTTP request returned a status of " + long_to_string(status) + " which means '";
msg += http_status_to_string(status) + "' \n";
throw libdap::Error(msg);
}
BESDEBUG( "gateway", "RemoteHttpResource::writeResourceToFile() - Resourced saved. Evaluating HTTP Headers... " << d_remoteResourceUrl << " to cache file " << d_resourceCacheFileName << endl );
// @TODO CACHE THE DATA TYPE OR THE HTTP HEADERS SO WHEN WE ARE RETRIEVING THE CACHED OBJECT WE CAN GET THE CORRECT TYPE
setType(d_response_headers);
}
catch (libdap::Error &e) {
throw;
}
BESDEBUG( "gateway", "RemoteHttpResource::writeResourceToFile() - Cached resource" << endl );
rewind(stream);
BESDEBUG( "gateway", "RemoteHttpResource::writeResourceToFile() - Rewound File *stream" << endl );
// Return open FILE * for later use.
return stream;
// @TODO Why don't we close this file? We don't ever hand back a FILE * or file descriptor integer, and the way that
// the gateway used HTTPConnect didn't utilize the file descriptor that was handed back by HTTPConnect...
}
void RemoteHttpResource::setType(const vector<string> *resp_hdrs)
{
BESDEBUG("gateway", "RemoteHttpResource::setType() - BEGIN" << endl);
string type = "";
// Try and figure out the file type first from the
// Content-Disposition in the http header response.
string disp ;
string ctype ;
if( resp_hdrs )
{
vector<string>::const_iterator i = resp_hdrs->begin() ;
vector<string>::const_iterator e = resp_hdrs->end() ;
for( ; i != e; i++ )
{
string hdr_line = (*i) ;
BESDEBUG("gateway", "RemoteHttpResource::setType() - Evaluating header: " << hdr_line << endl);
hdr_line = BESUtil::lowercase( hdr_line ) ;
string colon_space = ": ";
int index = hdr_line.find(colon_space);
string hdr_name = hdr_line.substr(0,index);
string hdr_value = hdr_line.substr(index + colon_space.length());
BESDEBUG("gateway", "RemoteHttpResource::setType() - hdr_name: '" << hdr_name << "' hdr_value: '" <<hdr_value << "' "<< endl);
if( hdr_name.find( "content-disposition" ) != string::npos )
{
// Content disposition exists
BESDEBUG("gateway", "RemoteHttpResource::setType() - Located content-disposition header." << endl);
disp = hdr_value ;
}
if( hdr_name.find( "content-type" ) != string::npos )
{
BESDEBUG("gateway", "RemoteHttpResource::setType() - Located content-type header." << endl);
ctype = hdr_value;
}
}
}
if( !disp.empty() )
{
// Content disposition exists, grab the filename
// attribute
GatewayUtils::Get_type_from_disposition( disp, type ) ;
BESDEBUG( "gateway", "RemoteHttpResource::setType() - Evaluated content-disposition '" << disp
<< "' matched type: \"" << type
<< "\"" << endl ) ;
}
// still haven't figured out the type. Check the content-type
// next, translate to the BES module name. It's also possible
// that even though Content-disposition was available, we could
// not determine the type of the file.
if( type.empty() && !ctype.empty() )
{
GatewayUtils::Get_type_from_content_type( ctype, type ) ;
BESDEBUG( "gateway", "RemoteHttpResource::setType() - Evaluated content-type '" << ctype << "' matched type \"" << type << "\"" << endl ) ;
}
// still haven't figured out the type. Now check the actual URL
// and see if we can't match the URL to a module name
if( type.empty() )
{
GatewayUtils::Get_type_from_url( d_remoteResourceUrl, type ) ;
BESDEBUG( "gateway", "RemoteHttpResource::setType() - Evaluated url '" << d_remoteResourceUrl
<< "' matched type: \"" << type
<< "\"" << endl ) ;
}
// still couldn't figure it out ... throw an exception
if( type.empty() )
{
string err = (string)"RemoteHttpResource::setType() - Unable to determine the type of data"
+ " returned from " + d_remoteResourceUrl ;
throw BESSyntaxUserError( err, __FILE__, __LINE__ ) ;
}
// @TODO CACHE THE DATA TYPE OR THE HTTP HEADERS SO WHEN WE ARE RETRIEVING THE CACHED OBJECT WE CAN GET THE CORRECT TYPE
d_type = type;
BESDEBUG("gateway", "RemoteHttpResource::setType() - END" << endl);
}
} /* namespace gateway */
<commit_msg>gateway_module: stuff<commit_after>/*
* RemoteHttpResource.cpp
*
* Created on: Feb 22, 2013
* Author: ndp
*/
#include <sstream>
#include <GNURegex.h>
#include "util.h"
#include "debug.h"
#include "Error.h"
#include "BESSyntaxUserError.h"
#include "BESInternalError.h"
#include "BESError.h"
#include "BESRegex.h"
#include "TheBESKeys.h"
#include "GatewayUtils.h"
#include "curl_utils.h"
#include "RemoteHttpResource.h"
using namespace std;
static string long_to_string(unsigned long value)
{
std::ostringstream stream;
stream << value;
return stream.str();
}
namespace gateway {
RemoteHttpResource::RemoteHttpResource() {
d_fd = 0;
d_fstrm = 0;
d_curl = 0;
d_resourceCacheFileName.clear();
d_response_headers = 0;
d_request_headers = 0;
_initialized = false;
}
RemoteHttpResource::~RemoteHttpResource() {
BESDEBUG("gateway", "~RemoteHttpResource() - BEGIN resourceURL: " << d_remoteResourceUrl << endl);
if(d_response_headers){
delete d_response_headers;
d_response_headers = 0;
BESDEBUG("gateway", "~RemoteHttpResource() - Deleted d_response_headers." << endl);
}
if(d_request_headers){
delete d_request_headers;
d_request_headers = 0;
BESDEBUG("gateway", "~RemoteHttpResource() - Deleted d_request_headers." << endl);
}
//@TODO Do we need to check for open files somewhere? OR is this all good?
// It seems like that when we call cache->create_and_lock(d_resourceCacheFileName, fd)
// or cache->get_read_lock(d_resourceCacheFileName, fd) we open a file (using open) and we
// get back the integer valued file descriptor and a cache file name. Then we are very careful
// to rewind the file stream thingy and to leave the file open. I'm thinking that we rewind it
// to be good citizens so to speak - that way if a down stream piece of code does choose to
// utilize the open file descriptor or FILE * then it's all ready.
//
// BUT - The old code in gateway_module never utilized the file pointer. It just gets the
// cache file name string and then I think, opens it AGAIN somewhere downstream in BES land
// and reads the data from the cached file.
//
// Does calling unlock_and_close() below close all those files up? Is keeping the file open
// part of the trick to make the cache work? It uses a file locking thingy?
if(!d_resourceCacheFileName.empty()){
BESCache3::get_instance()->unlock_and_close(d_resourceCacheFileName);
BESDEBUG("gateway", "~RemoteHttpResource() - Closed and unlocked "<< d_resourceCacheFileName << endl);
d_resourceCacheFileName.clear();
}
if(d_curl!=0){
curl_easy_cleanup(d_curl);
BESDEBUG("gateway", "~RemoteHttpResource() - Called curl_easy_cleanup()." << endl);
}
d_curl = 0;
BESDEBUG("gateway", "~RemoteHttpResource() - END resourceURL: " << d_remoteResourceUrl << endl);
d_remoteResourceUrl.clear();
}
RemoteHttpResource::RemoteHttpResource(const string &url)
{
_initialized = false;
d_fd = 0;
d_fstrm = 0;
d_curl = 0;
d_resourceCacheFileName.clear();
d_response_headers = new vector<string>();
d_request_headers = new vector<string>();
if( url.empty() )
{
string err = "RemoteHttpResource(): Remote resource URL is empty" ;
throw BESInternalError( err, __FILE__, __LINE__ ) ;
}
d_remoteResourceUrl = url;
BESDEBUG("gateway", "RemoteHttpResource() - URL: " << d_remoteResourceUrl << endl);
/*
*
*
* EXAMPLE: returned value parameter for CURL *
*
CURL *www_lib_init(CURL **curl); // function type signature
CURL *pvparam = 0; // passed value parameter
result = www_lib_init(&pvparam); // the call to the method
*/
d_curl = gateway::www_lib_init(d_remoteResourceUrl, d_error_buffer); // This may throw either Error or InternalErr
BESDEBUG("gateway", "RemoteHttpResource() - d_curl: " << d_curl << endl);
}
void RemoteHttpResource::retrieveResource()
{
BESDEBUG("gateway", "RemoteHttpResource::retrieveResource() - BEGIN resourceURL: " << d_remoteResourceUrl << endl);
if(_initialized){
BESDEBUG("gateway", "RemoteHttpResource::retrieveResource() - END Already initialized." << endl);
return;
}
// Get a pointer to the singleton cache instance for this process.
BESCache3 *cache = BESCache3::get_instance(TheBESKeys::TheKeys(), (string)"BES.CacheDir",
(string)"BES.CachePrefix", (string)"BES.CacheSize");
// Get the name of the file in the cache (either the code finds this file or
// or it makes it).
// @TODO Fix BESCache3 so that you can ask it to NOT strip the suffix which is some kind of funky
// Uncompress feature that should be controllable and probably driven by a regex. Then we can stop
// adding our own suffix so that BESCache3 can remove it.
d_resourceCacheFileName = cache->get_cache_file_name(d_remoteResourceUrl+".gateway");
BESDEBUG("gateway", "RemoteHttpResource::retrieveResource() - d_resourceCacheFileName: " << d_resourceCacheFileName << endl);
// @TODO MAKE THIS RETRIEVE THE CACHED DATA TYPE IF THE CACHED RESPONSE IF FOUND
// We need to know the type of the resource. HTTP headers are the preferred way to determine the type.
// Unfortunately, the current code losses both the HTTP headers sent from the request and the derived type
// to subsequent accesses of the cached object. Since we have to have a type, for now we just set the type
// from the url. If down below we DO an HTTP GET then the headers will be evaluated and the type set by setType()
// But really - we gotta fix this.
GatewayUtils::Get_type_from_url( d_remoteResourceUrl, d_type );
BESDEBUG("gateway", "RemoteHttpResource::retrieveResource() - d_type: " << d_type << endl);
try {
if (cache->get_read_lock(d_resourceCacheFileName, d_fd)) {
BESDEBUG( "gateway", "RemoteHttpResource::retrieveResource() - Remote resource is already in cache. cache_file_name: "
<< d_resourceCacheFileName << endl );
_initialized = true;
return;
}
// Now we actually need to reach out across the interwebs and retrieve the remote resource and put it's
// content into a local cache file, given that it's no in the cache.
// First make an empty file and get an exclusive lock on it.
if (cache->create_and_lock(d_resourceCacheFileName, d_fd)) {
// Write the remote resource to the cache file. Save the returned FILE * cached in the member variable
// * d_fstrm where it can be accessed via the getFileStream() method.
d_fstrm = writeResourceToFile(d_fd);
// Change the exclusive lock on the new file to a shared lock. This keeps
// other processes from purging the new file and ensures that the reading
// process can use it.
cache->exclusive_to_shared_lock(d_fd);
BESDEBUG( "gateway", "RemoteHttpResource::retrieveResource() - Converted exclusive cache lock to shared lock." << endl );
// I think right here is where I would be able to cache the data type/response headers.
// Now update the total cache size info and purge if needed. The new file's
// name is passed into the purge method because this process cannot detect its
// own lock on the file.
unsigned long long size = cache->update_cache_info(d_resourceCacheFileName);
BESDEBUG( "gateway", "RemoteHttpResource::retrieveResource() - Updated cache info" << endl );
if (cache->cache_too_big(size)){
cache->update_and_purge(d_resourceCacheFileName);
BESDEBUG( "gateway", "RemoteHttpResource::retrieveResource() - Updated and purged cache." << endl );
}
BESDEBUG( "gateway", "RemoteHttpResource::retrieveResource() - END" << endl );
_initialized = true;
return;
}
else {
if (cache->get_read_lock(d_resourceCacheFileName, d_fd)) {
BESDEBUG( "gateway", "RemoteHttpResource::retrieveResource() - Remote resource is in cache. cache_file_name: "
<< d_resourceCacheFileName << endl );
_initialized = true;
return;
}
}
string msg = "RemoteHttpResource::retrieveResource() - Failed to acquire cache read lock for remote resource: '";
msg += d_remoteResourceUrl + "\n";
throw libdap::Error(msg);
}
catch (...) {
BESDEBUG( "gateway", "RemoteHttpResource::retrieveResource() - Caught exception, unlocking cache and re-throw." << endl );
cache->unlock_cache();
throw;
}
}
/**
*
* Retrieves the remote resource and write it the the open file associated with the open file
* descriptor parameter 'fd'. In the process of caching the file a FILE * is fdopen'd from 'fd' and that is used buy
* curl to write the content. At the end the stream is rewound and the FILE * pointer is returned.
*
* @param fd An open file descriptor the is associated with the target file.
*/
FILE *RemoteHttpResource::writeResourceToFile(int fd) {
BESDEBUG( "gateway", "RemoteHttpResource::writeResourceToFile() - Saving resource " << d_remoteResourceUrl << " to cache file " << d_resourceCacheFileName << endl );
// fdopen the file using the file descriptor fd so we can pass a FILE * into libcurl
// @TODO JAMES - I know I'm not supposed to close(fd), but what about stream? Is it enough to rewind it?
FILE* stream = fdopen(fd, "w");
int status = -1;
try {
status = gateway::read_url(d_curl, d_remoteResourceUrl, stream, d_response_headers, d_request_headers, d_error_buffer); // Throws Error.
if (status >= 400) {
BESDEBUG( "gateway", "RemoteHttpResource::writeResourceToFile() - HTTP returned an error status: " << status << endl );
// delete resp_hdrs; resp_hdrs = 0;
string msg = "Error while reading the URL: '";
msg += d_remoteResourceUrl;
msg += "'The HTTP request returned a status of " + long_to_string(status) + " which means '";
msg += http_status_to_string(status) + "' \n";
throw libdap::Error(msg);
}
BESDEBUG( "gateway", "RemoteHttpResource::writeResourceToFile() - Resourced saved. Evaluating HTTP Headers... " << d_remoteResourceUrl << " to cache file " << d_resourceCacheFileName << endl );
// @TODO CACHE THE DATA TYPE OR THE HTTP HEADERS SO WHEN WE ARE RETRIEVING THE CACHED OBJECT WE CAN GET THE CORRECT TYPE
setType(d_response_headers);
}
catch (libdap::Error &e) {
throw;
}
BESDEBUG( "gateway", "RemoteHttpResource::writeResourceToFile() - Cached resource" << endl );
rewind(stream);
BESDEBUG( "gateway", "RemoteHttpResource::writeResourceToFile() - Rewound File *stream" << endl );
// Return open FILE * for later use.
return stream;
// @TODO Why don't we close this file? We don't ever hand back a FILE * or file descriptor integer, and the way that
// the gateway used HTTPConnect didn't utilize the file descriptor that was handed back by HTTPConnect...
}
void RemoteHttpResource::setType(const vector<string> *resp_hdrs)
{
BESDEBUG("gateway", "RemoteHttpResource::setType() - BEGIN" << endl);
string type = "";
// Try and figure out the file type first from the
// Content-Disposition in the http header response.
string disp ;
string ctype ;
if( resp_hdrs )
{
vector<string>::const_iterator i = resp_hdrs->begin() ;
vector<string>::const_iterator e = resp_hdrs->end() ;
for( ; i != e; i++ )
{
string hdr_line = (*i) ;
BESDEBUG("gateway", "RemoteHttpResource::setType() - Evaluating header: " << hdr_line << endl);
hdr_line = BESUtil::lowercase( hdr_line ) ;
string colon_space = ": ";
int index = hdr_line.find(colon_space);
string hdr_name = hdr_line.substr(0,index);
string hdr_value = hdr_line.substr(index + colon_space.length());
BESDEBUG("gateway", "RemoteHttpResource::setType() - hdr_name: '" << hdr_name << "' hdr_value: '" <<hdr_value << "' "<< endl);
if( hdr_name.find( "content-disposition" ) != string::npos )
{
// Content disposition exists
BESDEBUG("gateway", "RemoteHttpResource::setType() - Located content-disposition header." << endl);
disp = hdr_value ;
}
if( hdr_name.find( "content-type" ) != string::npos )
{
BESDEBUG("gateway", "RemoteHttpResource::setType() - Located content-type header." << endl);
ctype = hdr_value;
}
}
}
if( !disp.empty() )
{
// Content disposition exists, grab the filename
// attribute
GatewayUtils::Get_type_from_disposition( disp, type ) ;
BESDEBUG( "gateway", "RemoteHttpResource::setType() - Evaluated content-disposition '" << disp
<< "' matched type: \"" << type
<< "\"" << endl ) ;
}
// still haven't figured out the type. Check the content-type
// next, translate to the BES module name. It's also possible
// that even though Content-disposition was available, we could
// not determine the type of the file.
if( type.empty() && !ctype.empty() )
{
GatewayUtils::Get_type_from_content_type( ctype, type ) ;
BESDEBUG( "gateway", "RemoteHttpResource::setType() - Evaluated content-type '" << ctype << "' matched type \"" << type << "\"" << endl ) ;
}
// still haven't figured out the type. Now check the actual URL
// and see if we can't match the URL to a module name
if( type.empty() )
{
GatewayUtils::Get_type_from_url( d_remoteResourceUrl, type ) ;
BESDEBUG( "gateway", "RemoteHttpResource::setType() - Evaluated url '" << d_remoteResourceUrl
<< "' matched type: \"" << type
<< "\"" << endl ) ;
}
// still couldn't figure it out ... throw an exception
if( type.empty() )
{
string err = (string)"RemoteHttpResource::setType() - Unable to determine the type of data"
+ " returned from '" + d_remoteResourceUrl +"' Setting type to 'unknown'" ;
BESDEBUG("gateway", err);
type = "unknown";
//throw BESSyntaxUserError( err, __FILE__, __LINE__ ) ;
}
// @TODO CACHE THE DATA TYPE OR THE HTTP HEADERS SO WHEN WE ARE RETRIEVING THE CACHED OBJECT WE CAN GET THE CORRECT TYPE
d_type = type;
BESDEBUG("gateway", "RemoteHttpResource::setType() - END" << endl);
}
} /* namespace gateway */
<|endoftext|> |
<commit_before>/*
* drakeUtil.cpp
*
* Created on: Jun 19, 2013
* Author: russt
*/
#include "drakeUtil.h"
#include <string.h>
#include <string>
#include <math.h>
#include <limits>
#include <Eigen/Dense>
using namespace std;
bool isa(const mxArray* mxa, const char* class_str)
// mxIsClass seems to not be able to handle derived classes. so i'll implement what I need by calling back to matlab
{
mxArray* plhs;
mxArray* prhs[2];
prhs[0] = const_cast<mxArray*>(mxa);
prhs[1] = mxCreateString(class_str);
mexCallMATLAB(1, &plhs, 2, prhs, "isa");
bool tf = *mxGetLogicals(plhs);
mxDestroyArray(plhs);
mxDestroyArray(prhs[1]);
return tf;
}
bool mexCallMATLABsafe(int nlhs, mxArray* plhs[], int nrhs, mxArray* prhs[], const char* filename)
{
int i;
mxArray* ex = mexCallMATLABWithTrap(nlhs, plhs, nrhs, prhs, filename);
if (ex) {
mexPrintf("DrakeSystem S-Function: error when calling ''%s'' with the following arguments:\n", filename);
for (i = 0; i < nrhs; i++)
mexCallMATLAB(0, NULL, 1, &prhs[i], "disp");
mxArray *report;
mexCallMATLAB(1, &report, 1, &ex, "getReport");
char *errmsg = mxArrayToString(report);
mexPrintf(errmsg);
mxFree(errmsg);
mxDestroyArray(report);
mexErrMsgIdAndTxt("Drake:mexCallMATLABsafe:CallbackError", "Error in MATLAB callback.\nSee additional debugging information above");
mxDestroyArray(ex);
return true;
}
for (i = 0; i < nlhs; i++)
if (!plhs[i]) {
mexPrintf("Drake mexCallMATLABsafe: error when calling ''%s'' with the following arguments:\n", filename);
for (i = 0; i < nrhs; i++)
mexCallMATLAB(0, NULL, 1, &prhs[i], "disp");
mexErrMsgIdAndTxt("Drake:mexCallMATLABsafe:NotEnoughOutputs", "Asked for %d outputs, but function only returned %d\n", nrhs, i);
return true;
}
return false;
}
/*
* @param subclass_name (optional) if you want to call a class that derives from
* DrakeMexPointer (e.g. so that you can refer to it as something more specific in
* your matlab code), then you can pass in the alternative name here. The constructor
* for this class must take the same inputs as the DrakeMexPointer constructor.
*/
mxArray* createDrakeMexPointer(void* ptr, const char* name, int num_additional_inputs, mxArray* delete_fcn_additional_inputs[], const char* subclass_name)
{
mxClassID cid;
if (sizeof(ptr) == 4) cid = mxUINT32_CLASS;
else if (sizeof(ptr) == 8) cid = mxUINT64_CLASS;
else mexErrMsgIdAndTxt("Drake:constructDrakeMexPointer:PointerSize", "Are you on a 32-bit machine or 64-bit machine??");
int nrhs = 3 + num_additional_inputs;
mxArray *plhs[1];
mxArray **prhs;
prhs = new mxArray*[nrhs];
prhs[0] = mxCreateNumericMatrix(1, 1, cid, mxREAL);
memcpy(mxGetData(prhs[0]), &ptr, sizeof(ptr));
prhs[1] = mxCreateString(mexFunctionName());
prhs[2] = mxCreateString(name);
for (int i = 0; i < num_additional_inputs; i++)
prhs[3+i] = delete_fcn_additional_inputs[i];
// mexPrintf("deleteMethod = %s\n name =%s\n", deleteMethod,name);
// call matlab to construct mex pointer object
if (subclass_name) {
mexCallMATLABsafe(1, plhs, nrhs, prhs, subclass_name);
if (!isa(plhs[0], "DrakeMexPointer")) {
mxDestroyArray(plhs[0]);
mexErrMsgIdAndTxt("Drake:createDrakeMexPointer:InvalidSubclass", "subclass_name is not a valid subclass of DrakeMexPointer");
}
}
else
mexCallMATLABsafe(1, plhs, nrhs, prhs, "DrakeMexPointer");
mexLock();
// mexPrintf("incrementing lock count\n");
delete[] prhs;
return plhs[0];
}
void* getDrakeMexPointer(const mxArray* mx)
{
void* ptr = NULL;
// todo: optimize this by caching the pointer values, as described in
// http://groups.csail.mit.edu/locomotion/bugs/show_bug.cgi?id=1590
mxArray* ptrArray = mxGetProperty(mx, 0, "ptr");
if (!ptrArray)
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs", "cannot retrieve 'ptr' field from this mxArray. are you sure it's a valid DrakeMexPointer object?");
switch (sizeof(void*)) {
case 4:
if (!mxIsUint32(ptrArray))
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadPointerSize", "DrakeMexPointer expected a 32-bit ptr field but got something else");
break;
case 8:
if (!mxIsUint64(ptrArray))
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadPointerSize", "DrakeMexPointer expected a 64-bit ptr field but got something else");
break;
default:
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadPointerSize", "DrakeMexPointer got a pointer that was neither 32-bit nor 64-bit.");
}
if (!mxIsNumeric(ptrArray) || mxGetNumberOfElements(ptrArray) != 1)
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs","the ptr property of this DrakeMexPointer does not appear to contain a valid pointer");
memcpy(&ptr, mxGetData(ptrArray), sizeof(ptr)); // note: could use a reinterpret_cast here instead
return ptr;
}
double angleAverage(double theta1, double theta2) {
// Computes the average between two angles by averaging points on the unit
// circle and taking the arctan of the result.
// see: http://en.wikipedia.org/wiki/Mean_of_circular_quantities
// theta1 is a scalar or column vector of angles (rad)
// theta2 is a scalar or column vector of angles (rad)
double x_mean = 0.5 * (cos(theta1) + cos(theta2));
double y_mean = 0.5 * (sin(theta1) + sin(theta2));
double angle_mean = atan2(y_mean, x_mean);
return angle_mean;
}
std::pair<Eigen::Vector3d, double> resolveCenterOfPressure(Eigen::Vector3d torque, Eigen::Vector3d force, Eigen::Vector3d normal, Eigen::Vector3d point_on_contact_plane)
{
// TODO: implement multi-column version
using namespace Eigen;
if (abs(normal.squaredNorm() - 1.0) > 1e-12) {
mexErrMsgIdAndTxt("Drake:resolveCenterOfPressure:BadInputs", "normal should be a unit vector");
}
Vector3d cop;
double normal_torque_at_cop;
double fz = normal.dot(force);
bool cop_exists = abs(fz) > 1e-12;
if (cop_exists) {
auto torque_at_point_on_contact_plane = torque - point_on_contact_plane.cross(force);
double normal_torque_at_point_on_contact_plane = normal.dot(torque_at_point_on_contact_plane);
auto tangential_torque = torque_at_point_on_contact_plane - normal * normal_torque_at_point_on_contact_plane;
cop = normal.cross(tangential_torque) / fz + point_on_contact_plane;
auto torque_at_cop = torque - cop.cross(force);
normal_torque_at_cop = normal.dot(torque_at_cop);
}
else {
cop.setConstant(std::numeric_limits<double>::quiet_NaN());
normal_torque_at_cop = std::numeric_limits<double>::quiet_NaN();
}
return std::pair<Vector3d, double>(cop, normal_torque_at_cop);
}
double * mxGetPrSafe(const mxArray *pobj) {
if (!mxIsDouble(pobj)) mexErrMsgIdAndTxt("Drake:mxGetPrSafe:BadInputs", "mxGetPr can only be called on arguments which correspond to Matlab doubles");
return mxGetPr(pobj);
}
mxArray* mxGetFieldSafe(const mxArray* array, size_t index, std::string const& field_name)
{
mxArray* ret = mxGetField(array, index, field_name.c_str());
if (!ret)
{
mexErrMsgIdAndTxt("Drake::mxGetFieldSafe", ("Field not found: " + field_name).c_str());
}
return ret;
}
void mxSetFieldSafe(mxArray* array, size_t index, std::string const & fieldname, mxArray* data)
{
int fieldnum;
fieldnum = mxGetFieldNumber(array, fieldname.c_str());
if (fieldnum < 0) {
fieldnum = mxAddField(array, fieldname.c_str());
}
mxSetFieldByNumber(array, index, fieldnum, data);
}
const std::vector<double> matlabToStdVector(const mxArray* in) {
// works for both row vectors and column vectors
if (mxGetM(in) != 1 && mxGetN(in) != 1)
throw runtime_error("Not a vector");
double* data = mxGetPrSafe(in);
return std::vector<double>(data, data + mxGetM(in) * mxGetN(in));
}
int sub2ind(mwSize ndims, const mwSize* dims, const mwSize* sub) {
int stride = 1;
int ret = 0;
for (int i = 0; i < ndims; i++) {
ret += sub[i] * stride;
stride *= dims[i];
}
return ret;
}
void sizecheck(const mxArray* mat, int M, int N) {
if (mxGetM(mat) != M) {
mexErrMsgIdAndTxt("Drake:WrongSize", "wrong number of rows. Expected: %d but got: %d", M, mxGetM(mat));
}
if (mxGetN(mat) != N) {
mexErrMsgIdAndTxt("Drake:WrongSize", "wrong number of columns. Expected: %d but got: %d", N, mxGetN(mat));
}
return;
}
<commit_msg>used mxGetNumberOfElements instead of product of sizes<commit_after>/*
* drakeUtil.cpp
*
* Created on: Jun 19, 2013
* Author: russt
*/
#include "drakeUtil.h"
#include <string.h>
#include <string>
#include <math.h>
#include <limits>
#include <Eigen/Dense>
using namespace std;
bool isa(const mxArray* mxa, const char* class_str)
// mxIsClass seems to not be able to handle derived classes. so i'll implement what I need by calling back to matlab
{
mxArray* plhs;
mxArray* prhs[2];
prhs[0] = const_cast<mxArray*>(mxa);
prhs[1] = mxCreateString(class_str);
mexCallMATLAB(1, &plhs, 2, prhs, "isa");
bool tf = *mxGetLogicals(plhs);
mxDestroyArray(plhs);
mxDestroyArray(prhs[1]);
return tf;
}
bool mexCallMATLABsafe(int nlhs, mxArray* plhs[], int nrhs, mxArray* prhs[], const char* filename)
{
int i;
mxArray* ex = mexCallMATLABWithTrap(nlhs, plhs, nrhs, prhs, filename);
if (ex) {
mexPrintf("DrakeSystem S-Function: error when calling ''%s'' with the following arguments:\n", filename);
for (i = 0; i < nrhs; i++)
mexCallMATLAB(0, NULL, 1, &prhs[i], "disp");
mxArray *report;
mexCallMATLAB(1, &report, 1, &ex, "getReport");
char *errmsg = mxArrayToString(report);
mexPrintf(errmsg);
mxFree(errmsg);
mxDestroyArray(report);
mexErrMsgIdAndTxt("Drake:mexCallMATLABsafe:CallbackError", "Error in MATLAB callback.\nSee additional debugging information above");
mxDestroyArray(ex);
return true;
}
for (i = 0; i < nlhs; i++)
if (!plhs[i]) {
mexPrintf("Drake mexCallMATLABsafe: error when calling ''%s'' with the following arguments:\n", filename);
for (i = 0; i < nrhs; i++)
mexCallMATLAB(0, NULL, 1, &prhs[i], "disp");
mexErrMsgIdAndTxt("Drake:mexCallMATLABsafe:NotEnoughOutputs", "Asked for %d outputs, but function only returned %d\n", nrhs, i);
return true;
}
return false;
}
/*
* @param subclass_name (optional) if you want to call a class that derives from
* DrakeMexPointer (e.g. so that you can refer to it as something more specific in
* your matlab code), then you can pass in the alternative name here. The constructor
* for this class must take the same inputs as the DrakeMexPointer constructor.
*/
mxArray* createDrakeMexPointer(void* ptr, const char* name, int num_additional_inputs, mxArray* delete_fcn_additional_inputs[], const char* subclass_name)
{
mxClassID cid;
if (sizeof(ptr) == 4) cid = mxUINT32_CLASS;
else if (sizeof(ptr) == 8) cid = mxUINT64_CLASS;
else mexErrMsgIdAndTxt("Drake:constructDrakeMexPointer:PointerSize", "Are you on a 32-bit machine or 64-bit machine??");
int nrhs = 3 + num_additional_inputs;
mxArray *plhs[1];
mxArray **prhs;
prhs = new mxArray*[nrhs];
prhs[0] = mxCreateNumericMatrix(1, 1, cid, mxREAL);
memcpy(mxGetData(prhs[0]), &ptr, sizeof(ptr));
prhs[1] = mxCreateString(mexFunctionName());
prhs[2] = mxCreateString(name);
for (int i = 0; i < num_additional_inputs; i++)
prhs[3+i] = delete_fcn_additional_inputs[i];
// mexPrintf("deleteMethod = %s\n name =%s\n", deleteMethod,name);
// call matlab to construct mex pointer object
if (subclass_name) {
mexCallMATLABsafe(1, plhs, nrhs, prhs, subclass_name);
if (!isa(plhs[0], "DrakeMexPointer")) {
mxDestroyArray(plhs[0]);
mexErrMsgIdAndTxt("Drake:createDrakeMexPointer:InvalidSubclass", "subclass_name is not a valid subclass of DrakeMexPointer");
}
}
else
mexCallMATLABsafe(1, plhs, nrhs, prhs, "DrakeMexPointer");
mexLock();
// mexPrintf("incrementing lock count\n");
delete[] prhs;
return plhs[0];
}
void* getDrakeMexPointer(const mxArray* mx)
{
void* ptr = NULL;
// todo: optimize this by caching the pointer values, as described in
// http://groups.csail.mit.edu/locomotion/bugs/show_bug.cgi?id=1590
mxArray* ptrArray = mxGetProperty(mx, 0, "ptr");
if (!ptrArray)
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs", "cannot retrieve 'ptr' field from this mxArray. are you sure it's a valid DrakeMexPointer object?");
switch (sizeof(void*)) {
case 4:
if (!mxIsUint32(ptrArray))
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadPointerSize", "DrakeMexPointer expected a 32-bit ptr field but got something else");
break;
case 8:
if (!mxIsUint64(ptrArray))
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadPointerSize", "DrakeMexPointer expected a 64-bit ptr field but got something else");
break;
default:
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadPointerSize", "DrakeMexPointer got a pointer that was neither 32-bit nor 64-bit.");
}
if (!mxIsNumeric(ptrArray) || mxGetNumberOfElements(ptrArray) != 1)
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs","the ptr property of this DrakeMexPointer does not appear to contain a valid pointer");
memcpy(&ptr, mxGetData(ptrArray), sizeof(ptr)); // note: could use a reinterpret_cast here instead
return ptr;
}
double angleAverage(double theta1, double theta2) {
// Computes the average between two angles by averaging points on the unit
// circle and taking the arctan of the result.
// see: http://en.wikipedia.org/wiki/Mean_of_circular_quantities
// theta1 is a scalar or column vector of angles (rad)
// theta2 is a scalar or column vector of angles (rad)
double x_mean = 0.5 * (cos(theta1) + cos(theta2));
double y_mean = 0.5 * (sin(theta1) + sin(theta2));
double angle_mean = atan2(y_mean, x_mean);
return angle_mean;
}
std::pair<Eigen::Vector3d, double> resolveCenterOfPressure(Eigen::Vector3d torque, Eigen::Vector3d force, Eigen::Vector3d normal, Eigen::Vector3d point_on_contact_plane)
{
// TODO: implement multi-column version
using namespace Eigen;
if (abs(normal.squaredNorm() - 1.0) > 1e-12) {
mexErrMsgIdAndTxt("Drake:resolveCenterOfPressure:BadInputs", "normal should be a unit vector");
}
Vector3d cop;
double normal_torque_at_cop;
double fz = normal.dot(force);
bool cop_exists = abs(fz) > 1e-12;
if (cop_exists) {
auto torque_at_point_on_contact_plane = torque - point_on_contact_plane.cross(force);
double normal_torque_at_point_on_contact_plane = normal.dot(torque_at_point_on_contact_plane);
auto tangential_torque = torque_at_point_on_contact_plane - normal * normal_torque_at_point_on_contact_plane;
cop = normal.cross(tangential_torque) / fz + point_on_contact_plane;
auto torque_at_cop = torque - cop.cross(force);
normal_torque_at_cop = normal.dot(torque_at_cop);
}
else {
cop.setConstant(std::numeric_limits<double>::quiet_NaN());
normal_torque_at_cop = std::numeric_limits<double>::quiet_NaN();
}
return std::pair<Vector3d, double>(cop, normal_torque_at_cop);
}
double * mxGetPrSafe(const mxArray *pobj) {
if (!mxIsDouble(pobj)) mexErrMsgIdAndTxt("Drake:mxGetPrSafe:BadInputs", "mxGetPr can only be called on arguments which correspond to Matlab doubles");
return mxGetPr(pobj);
}
mxArray* mxGetFieldSafe(const mxArray* array, size_t index, std::string const& field_name)
{
mxArray* ret = mxGetField(array, index, field_name.c_str());
if (!ret)
{
mexErrMsgIdAndTxt("Drake::mxGetFieldSafe", ("Field not found: " + field_name).c_str());
}
return ret;
}
void mxSetFieldSafe(mxArray* array, size_t index, std::string const & fieldname, mxArray* data)
{
int fieldnum;
fieldnum = mxGetFieldNumber(array, fieldname.c_str());
if (fieldnum < 0) {
fieldnum = mxAddField(array, fieldname.c_str());
}
mxSetFieldByNumber(array, index, fieldnum, data);
}
const std::vector<double> matlabToStdVector(const mxArray* in) {
// works for both row vectors and column vectors
if (mxGetM(in) != 1 && mxGetN(in) != 1)
throw runtime_error("Not a vector");
double* data = mxGetPrSafe(in);
return std::vector<double>(data, data + mxGetNumberOfElements(in));
}
int sub2ind(mwSize ndims, const mwSize* dims, const mwSize* sub) {
int stride = 1;
int ret = 0;
for (int i = 0; i < ndims; i++) {
ret += sub[i] * stride;
stride *= dims[i];
}
return ret;
}
void sizecheck(const mxArray* mat, int M, int N) {
if (mxGetM(mat) != M) {
mexErrMsgIdAndTxt("Drake:WrongSize", "wrong number of rows. Expected: %d but got: %d", M, mxGetM(mat));
}
if (mxGetN(mat) != N) {
mexErrMsgIdAndTxt("Drake:WrongSize", "wrong number of columns. Expected: %d but got: %d", N, mxGetN(mat));
}
return;
}
<|endoftext|> |
<commit_before>// main.cc for FbRun
// Copyright (c) 2002-2003 Henrik Kinnunen (fluxgen(at)linuxmail.org)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// $Id: main.cc,v 1.13 2004/09/12 09:42:43 akir Exp $
#include "FbRun.hh"
#include "App.hh"
#include "StringUtil.hh"
#include "Color.hh"
#include <string>
#include <iostream>
using namespace std;
void showUsage(const char *progname) {
cerr<<"fbrun 1.1.3 : (c) 2002-2003 Henrik Kinnunen"<<endl;
cerr<<"Usage: "<<
progname<<" [arguments]"<<endl<<
"Arguments: "<<endl<<
" -font [font name] Text font"<<endl<<
" -title [title name] Set title"<<endl<<
" -text [text] Text input"<<endl<<
" -w [width] Window width in pixels"<<endl<<
" -h [height] Window height in pixels"<<endl<<
" -display [display string] Display name"<<endl<<
" -pos [x] [y] Window position in pixels"<<endl<<
" -nearmouse Window position near mouse"<<endl<<
" -fg [color name] Foreground text color"<<endl<<
" -bg [color name] Background color"<<endl<<
" -na Disable antialias"<<endl<<
" -hf [history file] History file to load (default ~/.fluxbox/fbrun_history)"<<endl<<
" -help Show this help"<<endl<<endl<<
"Example: fbrun -fg black -bg white -text xterm -title \"run xterm\""<<endl;
}
int main(int argc, char **argv) {
int x = 0, y = 0; // default pos of window
size_t width = 200, height = 32; // default size of window
bool set_height = false, set_width=false; // use height/width of font by default
bool set_pos = false; // set position
bool near_mouse = false; // popup near mouse
bool antialias = true; // antialias text
string fontname; // font name
string title("Run program"); // default title
string text; // default input text
string foreground("black"); // text color
string background("white"); // text background color
string display_name; // name of the display connection
string history_file("~/.fluxbox/fbrun_history"); // command history file
// parse arguments
for (int i=1; i<argc; i++) {
if (strcmp(argv[i], "-font") == 0 && i+1 < argc) {
fontname = argv[++i];
} else if (strcmp(argv[i], "-title") == 0 && i+1 < argc) {
title = argv[++i];
} else if (strcmp(argv[i], "-text") == 0 && i+1 < argc) {
text = argv[++i];
} else if (strcmp(argv[i], "-w") == 0 && i+1 < argc) {
width = atoi(argv[++i]);
set_width = true;
} else if (strcmp(argv[i], "-h") == 0 && i+1 < argc) {
height = atoi(argv[++i]);
set_height = true; // mark true else the height of font will be used
} else if (strcmp(argv[i], "-display") == 0 && i+1 < argc) {
display_name = argv[++i];
} else if (strcmp(argv[i], "-pos") == 0 && i+2 < argc) {
x = atoi(argv[++i]);
y = atoi(argv[++i]);
set_pos = true;
} else if (strcmp(argv[i], "-nearmouse") == 0) {
set_pos = true;
near_mouse = true;
i++;
} else if (strcmp(argv[i], "-fg") == 0 && i+1 < argc) {
foreground = argv[++i];
} else if (strcmp(argv[i], "-bg") == 0 && i+1 < argc) {
background = argv[++i];
} else if (strcmp(argv[i], "-na") == 0) {
antialias = false;
} else if (strcmp(argv[i], "-hf") == 0 && i+1 < argc) {
history_file = argv[++i];
} else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-help") == 0) {
showUsage(argv[0]);
exit(0);
} else {
cerr<<"Invalid argument: "<<argv[i]<<endl;
showUsage(argv[0]);
exit(0);
}
}
try {
FbTk::App application(display_name.c_str());
FbRun fbrun;
fbrun.setAntialias(antialias);
if (fontname.size() != 0) {
if (!fbrun.loadFont(fontname.c_str())) {
cerr<<"Failed to load font: "<<fontname<<endl;
cerr<<"Falling back to \"fixed\""<<endl;
}
}
// get color
XColor xc_foreground, xc_background;
FbTk::Color fg_color(foreground.c_str(), 0);
FbTk::Color bg_color(background.c_str(), 0);
fbrun.setForegroundColor(fg_color);
fbrun.setBackgroundColor(bg_color);
if (set_height)
fbrun.resize(fbrun.width(), height);
if (set_width)
fbrun.resize(width, fbrun.height());
if (antialias)
fbrun.setAntialias(antialias);
// expand and load command history
string expanded_filename = FbTk::StringUtil::expandFilename(history_file);
if (!fbrun.loadHistory(expanded_filename.c_str()))
cerr<<"FbRun Warning: Failed to load history file: "<<expanded_filename<<endl;
fbrun.setTitle(title);
fbrun.setText(text);
fbrun.show();
if (near_mouse) {
int wx, wy;
unsigned int mask;
Window ret_win;
Window child_win;
Display* dpy = FbTk::App::instance()->display();
if (XQueryPointer(dpy, DefaultRootWindow(dpy),
&ret_win, &child_win,
&x, &y, &wx, &wy, &mask)) {
if ( x - (fbrun.width()/2) > 0 )
x-= fbrun.width()/2;
if ( y - (fbrun.height()/2) > 0 )
y-= fbrun.height()/2;
}
}
if (set_pos)
fbrun.move(x, y);
application.eventLoop();
} catch (string errstr) {
cerr<<"Error: "<<errstr<<endl;
}
}
<commit_msg>tiny fix for -nearmouse<commit_after>// main.cc for FbRun
// Copyright (c) 2002-2003 Henrik Kinnunen (fluxgen(at)linuxmail.org)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// $Id: main.cc,v 1.14 2004/09/12 10:01:46 akir Exp $
#include "FbRun.hh"
#include "App.hh"
#include "StringUtil.hh"
#include "Color.hh"
#include <string>
#include <iostream>
using namespace std;
void showUsage(const char *progname) {
cerr<<"fbrun 1.1.3 : (c) 2002-2003 Henrik Kinnunen"<<endl;
cerr<<"Usage: "<<
progname<<" [arguments]"<<endl<<
"Arguments: "<<endl<<
" -font [font name] Text font"<<endl<<
" -title [title name] Set title"<<endl<<
" -text [text] Text input"<<endl<<
" -w [width] Window width in pixels"<<endl<<
" -h [height] Window height in pixels"<<endl<<
" -display [display string] Display name"<<endl<<
" -pos [x] [y] Window position in pixels"<<endl<<
" -nearmouse Window position near mouse"<<endl<<
" -fg [color name] Foreground text color"<<endl<<
" -bg [color name] Background color"<<endl<<
" -na Disable antialias"<<endl<<
" -hf [history file] History file to load (default ~/.fluxbox/fbrun_history)"<<endl<<
" -help Show this help"<<endl<<endl<<
"Example: fbrun -fg black -bg white -text xterm -title \"run xterm\""<<endl;
}
int main(int argc, char **argv) {
int x = 0, y = 0; // default pos of window
size_t width = 200, height = 32; // default size of window
bool set_height = false, set_width=false; // use height/width of font by default
bool set_pos = false; // set position
bool near_mouse = false; // popup near mouse
bool antialias = true; // antialias text
string fontname; // font name
string title("Run program"); // default title
string text; // default input text
string foreground("black"); // text color
string background("white"); // text background color
string display_name; // name of the display connection
string history_file("~/.fluxbox/fbrun_history"); // command history file
// parse arguments
for (int i=1; i<argc; i++) {
if (strcmp(argv[i], "-font") == 0 && i+1 < argc) {
fontname = argv[++i];
} else if (strcmp(argv[i], "-title") == 0 && i+1 < argc) {
title = argv[++i];
} else if (strcmp(argv[i], "-text") == 0 && i+1 < argc) {
text = argv[++i];
} else if (strcmp(argv[i], "-w") == 0 && i+1 < argc) {
width = atoi(argv[++i]);
set_width = true;
} else if (strcmp(argv[i], "-h") == 0 && i+1 < argc) {
height = atoi(argv[++i]);
set_height = true; // mark true else the height of font will be used
} else if (strcmp(argv[i], "-display") == 0 && i+1 < argc) {
display_name = argv[++i];
} else if (strcmp(argv[i], "-pos") == 0 && i+2 < argc) {
x = atoi(argv[++i]);
y = atoi(argv[++i]);
set_pos = true;
} else if (strcmp(argv[i], "-nearmouse") == 0) {
set_pos = true;
near_mouse = true;
} else if (strcmp(argv[i], "-fg") == 0 && i+1 < argc) {
foreground = argv[++i];
} else if (strcmp(argv[i], "-bg") == 0 && i+1 < argc) {
background = argv[++i];
} else if (strcmp(argv[i], "-na") == 0) {
antialias = false;
} else if (strcmp(argv[i], "-hf") == 0 && i+1 < argc) {
history_file = argv[++i];
} else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-help") == 0) {
showUsage(argv[0]);
exit(0);
} else {
cerr<<"Invalid argument: "<<argv[i]<<endl;
showUsage(argv[0]);
exit(0);
}
}
try {
FbTk::App application(display_name.c_str());
FbRun fbrun;
fbrun.setAntialias(antialias);
if (fontname.size() != 0) {
if (!fbrun.loadFont(fontname.c_str())) {
cerr<<"Failed to load font: "<<fontname<<endl;
cerr<<"Falling back to \"fixed\""<<endl;
}
}
// get color
XColor xc_foreground, xc_background;
FbTk::Color fg_color(foreground.c_str(), 0);
FbTk::Color bg_color(background.c_str(), 0);
fbrun.setForegroundColor(fg_color);
fbrun.setBackgroundColor(bg_color);
if (set_height)
fbrun.resize(fbrun.width(), height);
if (set_width)
fbrun.resize(width, fbrun.height());
if (antialias)
fbrun.setAntialias(antialias);
// expand and load command history
string expanded_filename = FbTk::StringUtil::expandFilename(history_file);
if (!fbrun.loadHistory(expanded_filename.c_str()))
cerr<<"FbRun Warning: Failed to load history file: "<<expanded_filename<<endl;
fbrun.setTitle(title);
fbrun.setText(text);
fbrun.show();
if (near_mouse) {
int wx, wy;
unsigned int mask;
Window ret_win;
Window child_win;
Display* dpy = FbTk::App::instance()->display();
if (XQueryPointer(dpy, DefaultRootWindow(dpy),
&ret_win, &child_win,
&x, &y, &wx, &wy, &mask)) {
if ( x - (fbrun.width()/2) > 0 )
x-= fbrun.width()/2;
if ( y - (fbrun.height()/2) > 0 )
y-= fbrun.height()/2;
}
}
if (set_pos)
fbrun.move(x, y);
application.eventLoop();
} catch (string errstr) {
cerr<<"Error: "<<errstr<<endl;
}
}
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "RexUUID.h"
#include <iomanip>
using namespace std;
/// Converts a single char to a value of 0-15. (4 bits)
namespace
{
static uint8_t CharToNibble(char c)
{
if (isdigit(c))
return c - '0';
if (c >= 'a' && c <= 'f')
return 0xA + c - 'a';
if (c >= 'A' && c <= 'F')
return 0xA + c - 'A';
// Invalid octet.
return 0xFF;
}
/// @return The first two characters of the given string converted to a byte: "B9" -> 0xB9.
static uint8_t StringToByte(const char *str)
{
return (CharToNibble(str[0]) << 4) | CharToNibble(str[1]);
}
}
namespace RexTypes
{
RexUUID::RexUUID()
{
SetNull();
}
RexUUID::RexUUID(const char *str)
{
if (str)
FromString(str);
else
SetNull();
}
RexUUID::RexUUID(const std::string &str)
{
FromString(str.c_str());
}
void RexUUID::SetNull()
{
for(int i = 0; i < cSizeBytes; ++i)
data[i] = 0;
}
bool RexUUID::IsNull() const
{
for(int i = 0; i < cSizeBytes; ++i)
if (data[i] != 0)
return false;
return true;
}
void RexUUID::Random()
{
for (int i = 0; i < cSizeBytes; ++i)
data[i] = rand() & 0xff;
}
bool RexUUID::IsValid(const char *str)
{
if (!str) return false;
int valid_nibbles = 0;
while (*str)
{
if (CharToNibble(*str) <= 0xf)
valid_nibbles++;
str++;
}
return (valid_nibbles == cSizeBytes * 2);
}
/// Converts a C string representing a RexUUID to a uint8_t array.
/// Supports either the format "1c1bbda2-304b-4cbf-ba3f-75324b044c73" or "1c1bbda2304b4cbfba3f75324b044c73".
/// If the inputted string is zero, or if the length is zero, or if a parsing error occurs, the UUID will be
/// set to null.
void RexUUID::FromString(const char *str)
{
const int strLen = (str == 0) ? 0 : strlen(str);
if (strLen == 0)
{
SetNull();
return;
}
int curIndex = 0;
for(int i = 0; i < cSizeBytes; ++i)
{
if (curIndex >= strLen)
{
SetNull();
return;
}
while(!(isalpha(str[curIndex]) || isdigit(str[curIndex]) || str[curIndex] == '\0'))
++curIndex;
if (curIndex >= strLen)
{
SetNull();
return;
}
data[i] = StringToByte(str + curIndex);
curIndex += 2;
}
}
std::string RexUUID::ToString() const
{
stringstream str;
int i = 0;
for(int j = 0; j < 4; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];
str << "-";
for(int j = 0; j < 2; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];
str << "-";
for(int j = 0; j < 2; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];
str << "-";
for(int j = 0; j < 2; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];
str << "-";
for(int j = 0; j < 6; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];
return str.str();
}
/* void RexUUID::operator =(const RexUUID &rhs)
{
if (this != &rhs)
for(int i = 0; i < cSizeBytes; ++i)
data[i] = rhs.data[i];
}*/
bool RexUUID::operator ==(const RexUUID &rhs) const
{
for(int i = 0; i < cSizeBytes; ++i)
if (data[i] != rhs.data[i])
return false;
return true;
}
bool RexUUID::operator !=(const RexUUID &rhs) const
{
for(int i = 0; i < cSizeBytes; ++i)
if (data[i] != rhs.data[i])
return true;
return false;
}
bool RexUUID::operator <(const RexUUID &rhs) const
{
for(int i = 0; i < cSizeBytes; ++i)
if (data[i] < rhs.data[i])
return true;
else if (data[i] > rhs.data[i])
return false;
return false;
}
}<commit_msg>Fixed the UUID parsing a bit more, added a reminder.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "RexUUID.h"
#include <iomanip>
using namespace std;
/// Converts a single char to a value of 0-15. (4 bits)
namespace
{
static uint8_t CharToNibble(char c)
{
if (isdigit(c))
return c - '0';
if (c >= 'a' && c <= 'f')
return 0xA + c - 'a';
if (c >= 'A' && c <= 'F')
return 0xA + c - 'A';
// Invalid octet.
return 0xFF;
}
/// @return The first two characters of the given string converted to a byte: "B9" -> 0xB9.
static uint8_t StringToByte(const char *str)
{
return (CharToNibble(str[0]) << 4) | CharToNibble(str[1]);
}
}
namespace RexTypes
{
RexUUID::RexUUID()
{
SetNull();
}
RexUUID::RexUUID(const char *str)
{
if (str)
FromString(str);
else
SetNull();
}
RexUUID::RexUUID(const std::string &str)
{
FromString(str.c_str());
}
void RexUUID::SetNull()
{
for(int i = 0; i < cSizeBytes; ++i)
data[i] = 0;
}
bool RexUUID::IsNull() const
{
for(int i = 0; i < cSizeBytes; ++i)
if (data[i] != 0)
return false;
return true;
}
void RexUUID::Random()
{
for (int i = 0; i < cSizeBytes; ++i)
data[i] = rand() & 0xff;
}
bool RexUUID::IsValid(const char *str)
{
if (!str) return false;
int valid_nibbles = 0;
while (*str)
{
if (CharToNibble(*str) <= 0xf)
valid_nibbles++;
str++;
}
return (valid_nibbles == cSizeBytes * 2);
}
/// Converts a C string representing a RexUUID to a uint8_t array.
/// Supports either the format "1c1bbda2-304b-4cbf-ba3f-75324b044c73" or "1c1bbda2304b4cbfba3f75324b044c73".
/// If the inputted string is zero, or if the length is zero, or if a parsing error occurs, the UUID will be
/// set to null.
void RexUUID::FromString(const char *str)
{
const int strLen = (str == 0) ? 0 : strlen(str);
if (strLen == 0)
{
SetNull();
return;
}
int curIndex = 0;
for(int i = 0; i < cSizeBytes; ++i)
{
if (curIndex >= strLen)
{
SetNull();
return;
}
///\todo Tighten parsing, now accepts all characters, like 'g' or 'Y'.
while(!isalpha(str[curIndex]) && !isdigit(str[curIndex]) && !str[curIndex] == '\0')
++curIndex;
// The following parse needs to read two characters from the string, hence the +1.
if (curIndex + 1 >= strLen)
{
SetNull();
return;
}
data[i] = StringToByte(str + curIndex);
curIndex += 2;
}
}
std::string RexUUID::ToString() const
{
stringstream str;
int i = 0;
for(int j = 0; j < 4; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];
str << "-";
for(int j = 0; j < 2; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];
str << "-";
for(int j = 0; j < 2; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];
str << "-";
for(int j = 0; j < 2; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];
str << "-";
for(int j = 0; j < 6; ++j) str << hex << setw(2) << setfill('0') << (int)data[i++];
return str.str();
}
/* void RexUUID::operator =(const RexUUID &rhs)
{
if (this != &rhs)
for(int i = 0; i < cSizeBytes; ++i)
data[i] = rhs.data[i];
}*/
bool RexUUID::operator ==(const RexUUID &rhs) const
{
for(int i = 0; i < cSizeBytes; ++i)
if (data[i] != rhs.data[i])
return false;
return true;
}
bool RexUUID::operator !=(const RexUUID &rhs) const
{
for(int i = 0; i < cSizeBytes; ++i)
if (data[i] != rhs.data[i])
return true;
return false;
}
bool RexUUID::operator <(const RexUUID &rhs) const
{
for(int i = 0; i < cSizeBytes; ++i)
if (data[i] < rhs.data[i])
return true;
else if (data[i] > rhs.data[i])
return false;
return false;
}
}<|endoftext|> |
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, ETH Zurich
** 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 ETH Zurich 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
/***********************************************************************************************************************
* Scene.cpp
*
* Created on: Dec 6, 2010
* Author: Dimitar Asenov
**********************************************************************************************************************/
#include "Scene.h"
#include "VisualizationManager.h"
#include "items/Item.h"
#include "items/SceneHandlerItem.h"
#include "items/SelectedItem.h"
#include "renderer/ModelRenderer.h"
#include "cursor/Cursor.h"
#include "CustomSceneEvent.h"
#include "ModelBase/src/nodes/Node.h"
#include "ModelBase/src/model/Model.h"
namespace Visualization {
class UpdateSceneEvent : public QEvent
{
public:
static const QEvent::Type EventType;
UpdateSceneEvent() : QEvent(EventType){};
};
const QEvent::Type UpdateSceneEvent::EventType = static_cast<QEvent::Type> (QEvent::registerEventType());
Scene::Scene()
: QGraphicsScene(VisualizationManager::instance().getMainWindow()), needsUpdate_(false),
renderer_(defaultRenderer()), sceneHandlerItem_(new SceneHandlerItem(this)), mainCursor_(nullptr),
mainCursorsJustSet_(false), inEventHandler_(false), inAnUpdate_(false), hiddenItemCategories_(NoItemCategory)
{
}
Scene::~Scene()
{
for (Item* i : topLevelItems_) SAFE_DELETE_ITEM(i);
topLevelItems_.clear();
for (SelectedItem* si : selections_) SAFE_DELETE_ITEM(si);
selections_.clear();
SAFE_DELETE(mainCursor_);
SAFE_DELETE_ITEM(sceneHandlerItem_);
if (renderer_ != defaultRenderer()) SAFE_DELETE(renderer_);
else renderer_ = nullptr;
}
ModelRenderer* Scene::defaultRenderer()
{
static ModelRenderer defaultRenderer_;
return &defaultRenderer_;
}
void Scene::addTopLevelItem(Item* item)
{
topLevelItems_.append(item);
addItem(item);
scheduleUpdate();
}
void Scene::removeTopLevelItem(Item* item)
{
topLevelItems_.removeAll(item);
removeItem(item);
scheduleUpdate();
}
void Scene::scheduleUpdate()
{
if (!needsUpdate_)
{
needsUpdate_ = true;
if (!inEventHandler_) QApplication::postEvent(this, new UpdateSceneEvent());
}
}
void Scene::updateItems()
{
inAnUpdate_ = true;
// Update Top level items
for (int i = 0; i<topLevelItems_.size(); ++i)
topLevelItems_.at(i)->updateSubtree();
// Update Selections
// TODO do not recreate all items all the time.
for (int i = 0; i<selections_.size(); i++) SAFE_DELETE_ITEM(selections_[i]);
QList<QGraphicsItem *> selected = selectedItems();
// Only display a selection when there are multiple selected items or no cursor
bool draw_selections = selected.size() !=1 || mainCursor_ == nullptr || mainCursor_->visualization() == nullptr;
if (!draw_selections)
{
// There is exactly one item and it has a cursor visualization
auto selectable = mainCursor_->owner();
while (selectable && ! (selectable->flags() & QGraphicsItem::ItemIsSelectable))
selectable = selectable->parent();
draw_selections = !selectable || selectable != selected.first();
}
if (draw_selections && !(selected.size() == 1 && selected.first() == sceneHandlerItem_))
{
for (int i = 0; i<selected.size(); ++i)
{
Item* s = static_cast<Item*> (selected[i]);
selections_.append(new SelectedItem(s));
addItem(selections_.last());
selections_.last()->updateSubtree();
}
}
// Update the main cursor
if (mainCursor_ && mainCursor_->visualization())
{
if (mainCursor_->visualization()->scene() != this) addItem(mainCursor_->visualization());
mainCursor_->visualization()->updateSubtree();
}
computeSceneRect();
needsUpdate_ = false;
inAnUpdate_ = false;
}
void Scene::listenToModel(Model::Model* model)
{
connect(model, SIGNAL(nodesModified(QList<Node*>)), this, SLOT(nodesUpdated(QList<Node*>)), Qt::QueuedConnection);
}
void Scene::nodesUpdated(QList<Node*> nodes)
{
// TODO implement this in a more efficient way.
for (QGraphicsItem* graphics_item : items())
{
Item* item = static_cast<Item*> ( graphics_item );
if (item->hasNode() && nodes.contains(item->node())) item->setUpdateNeeded(Item::StandardUpdate);
}
scheduleUpdate();
}
void Scene::customEvent(QEvent *event)
{
if ( event->type() == UpdateSceneEvent::EventType ) updateItems();
else if (auto e = dynamic_cast<CustomSceneEvent*>(event))
{
e->execute();
}
else
QGraphicsScene::customEvent(event);
}
bool Scene::event(QEvent *event)
{
if (inAnUpdate_) return QGraphicsScene::event(event);
inEventHandler_ = true;
bool result = false;
if (event->type() != UpdateSceneEvent::EventType &&
event->type() != QEvent::MetaCall &&
event->type() != QEvent::GraphicsSceneMouseMove &&
event->type() != QEvent::GraphicsSceneHoverMove
)
scheduleUpdate();
// Always move the scene handler item to the location of the last mouse click.
// This assures that even if the user presses somewhere in the empty space of the scene, the scene handler item will
// be selected.
if (event->type() == QEvent::GraphicsSceneMousePress)
{
auto e = static_cast<QGraphicsSceneMouseEvent*>(event);
sceneHandlerItem_->setPos(e->scenePos() - QPointF(1,1));
}
if (event->type() == QEvent::KeyPress)
{
//Circumvent the standard TAB handling of the scene.
keyPressEvent(static_cast<QKeyEvent *>(event));
result = true;
}
else result = QGraphicsScene::event(event);
inEventHandler_ = false;
if (needsUpdate_) updateItems();
for(auto e : postEventActions_)
{
customEvent(e);
SAFE_DELETE(e);
}
postEventActions_.clear();
// On keyboard events, make sure the cursor is visible
if (mainCursorsJustSet_ && mainCursor_ && mainCursor_->visualization()
&& mainCursor_->visualization()->boundingRect().isValid() )
{
for (auto view : views())
if (view->isActiveWindow())
{
auto vis = mainCursor_->visualization();
view->ensureVisible( vis->boundingRect().translated(vis->scenePos()), 5, 5);
mainCursorsJustSet_ = false;
}
}
return result;
}
void Scene::addPostEventAction(QEvent* action)
{
if (inEventHandler_)
postEventActions_.append(action);
else throw VisualizationException("Can not add post event actions when not in event!");
}
void Scene::setMainCursor(Cursor* cursor)
{
SAFE_DELETE(mainCursor_);
mainCursor_ = cursor;
mainCursorsJustSet_ = true;
}
void Scene::computeSceneRect()
{
QRectF r;
for (auto i: topLevelItems_)
{
if (i->itemCategory() != MenuItemCategory && i->itemCategory() != CursorItemCategory)
{
QRectF br = i->boundingRect().translated(i->pos());
r = r.united(br);
}
}
r.adjust(-20,-20,20,20); // Add some margin
setSceneRect(r);
}
}
<commit_msg>Include all top-level items when computing sceneRect (also menu items)<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, ETH Zurich
** 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 ETH Zurich 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
/***********************************************************************************************************************
* Scene.cpp
*
* Created on: Dec 6, 2010
* Author: Dimitar Asenov
**********************************************************************************************************************/
#include "Scene.h"
#include "VisualizationManager.h"
#include "items/Item.h"
#include "items/SceneHandlerItem.h"
#include "items/SelectedItem.h"
#include "renderer/ModelRenderer.h"
#include "cursor/Cursor.h"
#include "CustomSceneEvent.h"
#include "ModelBase/src/nodes/Node.h"
#include "ModelBase/src/model/Model.h"
namespace Visualization {
class UpdateSceneEvent : public QEvent
{
public:
static const QEvent::Type EventType;
UpdateSceneEvent() : QEvent(EventType){};
};
const QEvent::Type UpdateSceneEvent::EventType = static_cast<QEvent::Type> (QEvent::registerEventType());
Scene::Scene()
: QGraphicsScene(VisualizationManager::instance().getMainWindow()), needsUpdate_(false),
renderer_(defaultRenderer()), sceneHandlerItem_(new SceneHandlerItem(this)), mainCursor_(nullptr),
mainCursorsJustSet_(false), inEventHandler_(false), inAnUpdate_(false), hiddenItemCategories_(NoItemCategory)
{
}
Scene::~Scene()
{
for (Item* i : topLevelItems_) SAFE_DELETE_ITEM(i);
topLevelItems_.clear();
for (SelectedItem* si : selections_) SAFE_DELETE_ITEM(si);
selections_.clear();
SAFE_DELETE(mainCursor_);
SAFE_DELETE_ITEM(sceneHandlerItem_);
if (renderer_ != defaultRenderer()) SAFE_DELETE(renderer_);
else renderer_ = nullptr;
}
ModelRenderer* Scene::defaultRenderer()
{
static ModelRenderer defaultRenderer_;
return &defaultRenderer_;
}
void Scene::addTopLevelItem(Item* item)
{
topLevelItems_.append(item);
addItem(item);
scheduleUpdate();
}
void Scene::removeTopLevelItem(Item* item)
{
topLevelItems_.removeAll(item);
removeItem(item);
scheduleUpdate();
}
void Scene::scheduleUpdate()
{
if (!needsUpdate_)
{
needsUpdate_ = true;
if (!inEventHandler_) QApplication::postEvent(this, new UpdateSceneEvent());
}
}
void Scene::updateItems()
{
inAnUpdate_ = true;
// Update Top level items
for (int i = 0; i<topLevelItems_.size(); ++i)
topLevelItems_.at(i)->updateSubtree();
// Update Selections
// TODO do not recreate all items all the time.
for (int i = 0; i<selections_.size(); i++) SAFE_DELETE_ITEM(selections_[i]);
QList<QGraphicsItem *> selected = selectedItems();
// Only display a selection when there are multiple selected items or no cursor
bool draw_selections = selected.size() !=1 || mainCursor_ == nullptr || mainCursor_->visualization() == nullptr;
if (!draw_selections)
{
// There is exactly one item and it has a cursor visualization
auto selectable = mainCursor_->owner();
while (selectable && ! (selectable->flags() & QGraphicsItem::ItemIsSelectable))
selectable = selectable->parent();
draw_selections = !selectable || selectable != selected.first();
}
if (draw_selections && !(selected.size() == 1 && selected.first() == sceneHandlerItem_))
{
for (int i = 0; i<selected.size(); ++i)
{
Item* s = static_cast<Item*> (selected[i]);
selections_.append(new SelectedItem(s));
addItem(selections_.last());
selections_.last()->updateSubtree();
}
}
// Update the main cursor
if (mainCursor_ && mainCursor_->visualization())
{
if (mainCursor_->visualization()->scene() != this) addItem(mainCursor_->visualization());
mainCursor_->visualization()->updateSubtree();
}
computeSceneRect();
needsUpdate_ = false;
inAnUpdate_ = false;
}
void Scene::listenToModel(Model::Model* model)
{
connect(model, SIGNAL(nodesModified(QList<Node*>)), this, SLOT(nodesUpdated(QList<Node*>)), Qt::QueuedConnection);
}
void Scene::nodesUpdated(QList<Node*> nodes)
{
// TODO implement this in a more efficient way.
for (QGraphicsItem* graphics_item : items())
{
Item* item = static_cast<Item*> ( graphics_item );
if (item->hasNode() && nodes.contains(item->node())) item->setUpdateNeeded(Item::StandardUpdate);
}
scheduleUpdate();
}
void Scene::customEvent(QEvent *event)
{
if ( event->type() == UpdateSceneEvent::EventType ) updateItems();
else if (auto e = dynamic_cast<CustomSceneEvent*>(event))
{
e->execute();
}
else
QGraphicsScene::customEvent(event);
}
bool Scene::event(QEvent *event)
{
if (inAnUpdate_) return QGraphicsScene::event(event);
inEventHandler_ = true;
bool result = false;
if (event->type() != UpdateSceneEvent::EventType &&
event->type() != QEvent::MetaCall &&
event->type() != QEvent::GraphicsSceneMouseMove &&
event->type() != QEvent::GraphicsSceneHoverMove
)
scheduleUpdate();
// Always move the scene handler item to the location of the last mouse click.
// This assures that even if the user presses somewhere in the empty space of the scene, the scene handler item will
// be selected.
if (event->type() == QEvent::GraphicsSceneMousePress)
{
auto e = static_cast<QGraphicsSceneMouseEvent*>(event);
sceneHandlerItem_->setPos(e->scenePos() - QPointF(1,1));
}
if (event->type() == QEvent::KeyPress)
{
//Circumvent the standard TAB handling of the scene.
keyPressEvent(static_cast<QKeyEvent *>(event));
result = true;
}
else result = QGraphicsScene::event(event);
inEventHandler_ = false;
if (needsUpdate_) updateItems();
for(auto e : postEventActions_)
{
customEvent(e);
SAFE_DELETE(e);
}
postEventActions_.clear();
// On keyboard events, make sure the cursor is visible
if (mainCursorsJustSet_ && mainCursor_ && mainCursor_->visualization()
&& mainCursor_->visualization()->boundingRect().isValid() )
{
for (auto view : views())
if (view->isActiveWindow())
{
auto vis = mainCursor_->visualization();
view->ensureVisible( vis->boundingRect().translated(vis->scenePos()), 5, 5);
mainCursorsJustSet_ = false;
}
}
return result;
}
void Scene::addPostEventAction(QEvent* action)
{
if (inEventHandler_)
postEventActions_.append(action);
else throw VisualizationException("Can not add post event actions when not in event!");
}
void Scene::setMainCursor(Cursor* cursor)
{
SAFE_DELETE(mainCursor_);
mainCursor_ = cursor;
mainCursorsJustSet_ = true;
}
void Scene::computeSceneRect()
{
QRectF r;
for (auto i: topLevelItems_)
{
QRectF br = i->boundingRect().translated(i->pos());
r = r.united(br);
}
r.adjust(-20,-20,20,20); // Add some margin
setSceneRect(r);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2011-2013 Intel Corporation
* Modifications Copyright 2014, Blender Foundation.
*
* 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 "util_simd.h"
CCL_NAMESPACE_BEGIN
#ifdef WITH_KERNEL_SSE2
const __m128 _mm_lookupmask_ps[16] = {
_mm_castsi128_ps(_mm_set_epi32( 0, 0, 0, 0)),
_mm_castsi128_ps(_mm_set_epi32( 0, 0, 0,-1)),
_mm_castsi128_ps(_mm_set_epi32( 0, 0,-1, 0)),
_mm_castsi128_ps(_mm_set_epi32( 0, 0,-1,-1)),
_mm_castsi128_ps(_mm_set_epi32( 0,-1, 0, 0)),
_mm_castsi128_ps(_mm_set_epi32( 0,-1, 0,-1)),
_mm_castsi128_ps(_mm_set_epi32( 0,-1,-1, 0)),
_mm_castsi128_ps(_mm_set_epi32( 0,-1,-1,-1)),
_mm_castsi128_ps(_mm_set_epi32(-1, 0, 0, 0)),
_mm_castsi128_ps(_mm_set_epi32(-1, 0, 0,-1)),
_mm_castsi128_ps(_mm_set_epi32(-1, 0,-1, 0)),
_mm_castsi128_ps(_mm_set_epi32(-1, 0,-1,-1)),
_mm_castsi128_ps(_mm_set_epi32(-1,-1, 0, 0)),
_mm_castsi128_ps(_mm_set_epi32(-1,-1, 0,-1)),
_mm_castsi128_ps(_mm_set_epi32(-1,-1,-1, 0)),
_mm_castsi128_ps(_mm_set_epi32(-1,-1,-1,-1))
};
#endif // WITH_KERNEL_SSE2
CCL_NAMESPACE_END
<commit_msg>Cycles: Fix compilation error on 32bit platforms<commit_after>/*
* Copyright 2011-2013 Intel Corporation
* Modifications Copyright 2014, Blender Foundation.
*
* 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
*/
/* SSE optimization disabled for now on 32 bit, see bug #36316 */
#if !(defined(__GNUC__) && (defined(i386) || defined(_M_IX86)))
#include "util_simd.h"
CCL_NAMESPACE_BEGIN
#ifdef WITH_KERNEL_SSE2
const __m128 _mm_lookupmask_ps[16] = {
_mm_castsi128_ps(_mm_set_epi32( 0, 0, 0, 0)),
_mm_castsi128_ps(_mm_set_epi32( 0, 0, 0,-1)),
_mm_castsi128_ps(_mm_set_epi32( 0, 0,-1, 0)),
_mm_castsi128_ps(_mm_set_epi32( 0, 0,-1,-1)),
_mm_castsi128_ps(_mm_set_epi32( 0,-1, 0, 0)),
_mm_castsi128_ps(_mm_set_epi32( 0,-1, 0,-1)),
_mm_castsi128_ps(_mm_set_epi32( 0,-1,-1, 0)),
_mm_castsi128_ps(_mm_set_epi32( 0,-1,-1,-1)),
_mm_castsi128_ps(_mm_set_epi32(-1, 0, 0, 0)),
_mm_castsi128_ps(_mm_set_epi32(-1, 0, 0,-1)),
_mm_castsi128_ps(_mm_set_epi32(-1, 0,-1, 0)),
_mm_castsi128_ps(_mm_set_epi32(-1, 0,-1,-1)),
_mm_castsi128_ps(_mm_set_epi32(-1,-1, 0, 0)),
_mm_castsi128_ps(_mm_set_epi32(-1,-1, 0,-1)),
_mm_castsi128_ps(_mm_set_epi32(-1,-1,-1, 0)),
_mm_castsi128_ps(_mm_set_epi32(-1,-1,-1,-1))
};
#endif // WITH_KERNEL_SSE2
CCL_NAMESPACE_END
#endif
<|endoftext|> |
<commit_before>/* vim: set sw=4 ts=4: */
/*
* clay-bindgen.cpp
* This program generates clay bindings for C source files.
* This file wraps around the "BindingsConverter" ASTConsumer which does all
* conversion.
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <cstdlib>
using namespace std;
#include "clang/Basic/Builtins.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Parse/ParseAST.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclGroup.h"
#include "llvm/ADT/Triple.h"
#include "PPContext.h"
#include "BindingsConverter.h"
using namespace clang;
void usage(char *argv0) {
cerr << "clay-bindgen: Generates clay bindings for C libraries\n";
cerr << "Usage: " << argv0 << " <options> <headerfile>\n";
cerr << "options:\n";
cerr << " -o <file> - write generated bindings to file (default stdout)\n";
cerr << " -target <tgt> - target platform for which to predefine macros\n";
cerr << " -isysroot <dir> - use <dir> as system root for includes search\n";
#ifdef __APPLE__
cerr << " -arch <arch> - predefine macros for Darwin architecture <arch>\n";
cerr << " (only one -arch allowed)\n";
cerr << " -F<dir> - add <dir> to framework search path\n";
#endif
cerr << " -I<dir> - add <dir> to header search path\n";
cerr << " -x <lang> - parse headers for language <lang> (default c).\n";
cerr << " Only \"c\" and \"objective-c\" supported.\n";
cerr << " -match <string> - only generate bindings for definitions from files\n";
cerr << " whose full pathname contains <string>.\n";
cerr << " If multiple -match parameters are given, then\n";
cerr << " bindings are generated from files with pathnames\n";
cerr << " containing any of the specified <string>s.\n";
cerr << " By default bindings are generated for all parsed\n";
cerr << " definitions.\n";
cerr << " -import <module> - Add an \"import <module>.*;\" statement to the\n";
cerr << " - generated output\n";
exit(EXIT_FAILURE);
}
int main(int argc, char* argv[]) {
if(argc < 2 || !strcmp(argv[1], "--help") || !strcmp(argv[1], "/?")) {
usage(argv[0]);
}
std::string filename;
std::string outfilename;
std::string target = LLVM_HOSTTRIPLE;
std::string isysroot;
std::vector<std::string> frameworkDirs;
std::vector<std::string> headerDirs;
std::string language = "c";
std::vector<std::string> matchNames;
std::vector<std::string> importNames;
int i = 1;
for (; i < argc; ++i) {
if (!strcmp(argv[i], "-o")) {
++i;
if (i >= argc) {
cerr << "No filename given after -o\n";
usage(argv[0]);
}
outfilename = argv[i];
} else if (!strcmp(argv[i], "-target")) {
++i;
if (i >= argc) {
cerr << "No target given after -target\n";
usage(argv[0]);
}
target = argv[i];
} else if (!strcmp(argv[i], "-isysroot")) {
++i;
if (i >= argc) {
cerr << "No path given after -isysroot\n";
usage(argv[0]);
}
isysroot = argv[i];
#ifdef __APPLE__
} else if (!strcmp(argv[i], "-arch")) {
++i;
if (i >= argc) {
cerr << "No architecture given after -arch\n";
usage(argv[0]);
}
if (!strcmp(argv[i], "i386"))
target = "i386-apple-darwin10";
else if (!strcmp(argv[i], "x86_64"))
target = "x86_64-apple-darwin10";
else if (!strcmp(argv[i], "ppc"))
target = "powerpc-apple-darwin10";
else if (!strcmp(argv[i], "ppc64"))
target = "powerpc64-apple-darwin10";
else if (!strcmp(argv[i], "armv6"))
target = "armv6-apple-darwin4.1-iphoneos";
else if (!strcmp(argv[i], "armv7"))
target = "thumbv7-apple-darwin4.1-iphoneos";
else {
cerr << "Unrecognized -arch value " << argv[i] << "\n";
usage(argv[0]);
}
} else if (!strncmp(argv[i], "-F", strlen("-F"))) {
string frameworkDir = argv[i] + 2;
if (frameworkDir.empty()) {
++i;
if (i >= argc) {
cerr << "No path given after -F\n";
usage(argv[0]);
}
frameworkDir = argv[i];
}
frameworkDirs.push_back(frameworkDir);
#endif
} else if (!strncmp(argv[i], "-I", strlen("-I"))) {
string headerDir = argv[i] + 2;
if (headerDir.empty()) {
++i;
if (i >= argc) {
cerr << "No path given after -I\n";
usage(argv[0]);
}
headerDir = argv[i];
}
headerDirs.push_back(headerDir);
} else if (!strcmp(argv[i], "-x")) {
++i;
if (i >= argc) {
cerr << "No language name given after -x\n";
usage(argv[0]);
}
if (strcmp(argv[i], "c") && strcmp(argv[i], "objective-c")) {
cerr << "Unsupported language " << argv[i] << "\n";
usage(argv[0]);
}
language = argv[i];
} else if (!strcmp(argv[i], "-match")) {
++i;
if (i >= argc) {
cerr << "No string given after -match\n";
usage(argv[0]);
}
matchNames.push_back(std::string(argv[i]));
} else if (!strcmp(argv[i], "-import")) {
++i;
if (i >= argc) {
cerr << "No string given after -import\n";
usage(argv[0]);
}
importNames.push_back(std::string(argv[i]));
} else if (!strcmp(argv[i], "--")) {
++i;
if (!filename.empty()) {
if (i != argc) {
cerr << "Only one input file may be given\n";
usage(argv[0]);
}
break;
} else {
if (i != argc - 1) {
cerr << "Only one input file may be given\n";
usage(argv[0]);
}
filename = argv[i];
break;
}
} else if (argv[i][0] != '-') {
if (!filename.empty()) {
cerr << "Only one input file may be given\n";
usage(argv[0]);
}
filename = argv[i];
} else {
cerr << "Unrecognized option " << argv[i] << "\n";
usage(argv[0]);
}
}
std::ofstream *outfilestream = NULL;
if (!outfilename.empty() && outfilename != "-") {
outfilestream = new ofstream(outfilename.c_str());
if (outfilestream->fail()) {
cerr << "Unable to open " << outfilename << " for writing\n";
return EXIT_FAILURE;
}
}
std::ostream &outstream =
outfilestream ? *outfilestream : std::cout;
llvm::Triple triple(target);
// Setup clang
clang::TargetOptions targetOpts;
targetOpts.Triple = triple.str();
// MacOS X headers assume SSE is available
if (triple.getOS() == llvm::Triple::Darwin && triple.getArch() == llvm::Triple::x86)
targetOpts.Features.push_back("+sse2");
clang::DiagnosticOptions diagOpts;
BindingsConverter *converter = new BindingsConverter(
outstream,
diagOpts,
language,
matchNames,
importNames
);
// Create a preprocessor context
clang::LangOptions langOpts;
langOpts.Blocks = 1; // for recent OS X/iOS headers
langOpts.C99 = 1;
if (language == "objective-c") {
langOpts.ObjC1 = 1;
langOpts.ObjC2 = 1;
}
PPContext context(
targetOpts, converter, langOpts,
isysroot, frameworkDirs, headerDirs
);
// Add input file
const FileEntry* file = context.fm.getFile(filename);
if (!file) {
cerr << "Failed to open \'" << argv[1] << "\'";
return EXIT_FAILURE;
}
context.sm.createMainFileID(file);
// Initialize ASTContext
Builtin::Context builtins(*context.target);
builtins.InitializeBuiltins(context.pp.getIdentifierTable());
ASTContext astContext(context.opts, context.sm, *context.target,
context.pp.getIdentifierTable(),
context.pp.getSelectorTable(),
builtins, 0);
// Parse it
converter->BeginSourceFile(langOpts, &context.pp);
ParseAST(context.pp, converter, astContext); // calls pp.EnterMainSourceFile() for us
converter->EndSourceFile();
converter->generate();
if (outfilestream)
outfilestream->close();
return 0;
}
<commit_msg>misc/bindgen: stray bullet in usage message<commit_after>/* vim: set sw=4 ts=4: */
/*
* clay-bindgen.cpp
* This program generates clay bindings for C source files.
* This file wraps around the "BindingsConverter" ASTConsumer which does all
* conversion.
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <cstdlib>
using namespace std;
#include "clang/Basic/Builtins.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Parse/ParseAST.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclGroup.h"
#include "llvm/ADT/Triple.h"
#include "PPContext.h"
#include "BindingsConverter.h"
using namespace clang;
void usage(char *argv0) {
cerr << "clay-bindgen: Generates clay bindings for C libraries\n";
cerr << "Usage: " << argv0 << " <options> <headerfile>\n";
cerr << "options:\n";
cerr << " -o <file> - write generated bindings to file (default stdout)\n";
cerr << " -target <tgt> - target platform for which to predefine macros\n";
cerr << " -isysroot <dir> - use <dir> as system root for includes search\n";
#ifdef __APPLE__
cerr << " -arch <arch> - predefine macros for Darwin architecture <arch>\n";
cerr << " (only one -arch allowed)\n";
cerr << " -F<dir> - add <dir> to framework search path\n";
#endif
cerr << " -I<dir> - add <dir> to header search path\n";
cerr << " -x <lang> - parse headers for language <lang> (default c).\n";
cerr << " Only \"c\" and \"objective-c\" supported.\n";
cerr << " -match <string> - only generate bindings for definitions from files\n";
cerr << " whose full pathname contains <string>.\n";
cerr << " If multiple -match parameters are given, then\n";
cerr << " bindings are generated from files with pathnames\n";
cerr << " containing any of the specified <string>s.\n";
cerr << " By default bindings are generated for all parsed\n";
cerr << " definitions.\n";
cerr << " -import <module> - Add an \"import <module>.*;\" statement to the\n";
cerr << " generated output\n";
exit(EXIT_FAILURE);
}
int main(int argc, char* argv[]) {
if(argc < 2 || !strcmp(argv[1], "--help") || !strcmp(argv[1], "/?")) {
usage(argv[0]);
}
std::string filename;
std::string outfilename;
std::string target = LLVM_HOSTTRIPLE;
std::string isysroot;
std::vector<std::string> frameworkDirs;
std::vector<std::string> headerDirs;
std::string language = "c";
std::vector<std::string> matchNames;
std::vector<std::string> importNames;
int i = 1;
for (; i < argc; ++i) {
if (!strcmp(argv[i], "-o")) {
++i;
if (i >= argc) {
cerr << "No filename given after -o\n";
usage(argv[0]);
}
outfilename = argv[i];
} else if (!strcmp(argv[i], "-target")) {
++i;
if (i >= argc) {
cerr << "No target given after -target\n";
usage(argv[0]);
}
target = argv[i];
} else if (!strcmp(argv[i], "-isysroot")) {
++i;
if (i >= argc) {
cerr << "No path given after -isysroot\n";
usage(argv[0]);
}
isysroot = argv[i];
#ifdef __APPLE__
} else if (!strcmp(argv[i], "-arch")) {
++i;
if (i >= argc) {
cerr << "No architecture given after -arch\n";
usage(argv[0]);
}
if (!strcmp(argv[i], "i386"))
target = "i386-apple-darwin10";
else if (!strcmp(argv[i], "x86_64"))
target = "x86_64-apple-darwin10";
else if (!strcmp(argv[i], "ppc"))
target = "powerpc-apple-darwin10";
else if (!strcmp(argv[i], "ppc64"))
target = "powerpc64-apple-darwin10";
else if (!strcmp(argv[i], "armv6"))
target = "armv6-apple-darwin4.1-iphoneos";
else if (!strcmp(argv[i], "armv7"))
target = "thumbv7-apple-darwin4.1-iphoneos";
else {
cerr << "Unrecognized -arch value " << argv[i] << "\n";
usage(argv[0]);
}
} else if (!strncmp(argv[i], "-F", strlen("-F"))) {
string frameworkDir = argv[i] + 2;
if (frameworkDir.empty()) {
++i;
if (i >= argc) {
cerr << "No path given after -F\n";
usage(argv[0]);
}
frameworkDir = argv[i];
}
frameworkDirs.push_back(frameworkDir);
#endif
} else if (!strncmp(argv[i], "-I", strlen("-I"))) {
string headerDir = argv[i] + 2;
if (headerDir.empty()) {
++i;
if (i >= argc) {
cerr << "No path given after -I\n";
usage(argv[0]);
}
headerDir = argv[i];
}
headerDirs.push_back(headerDir);
} else if (!strcmp(argv[i], "-x")) {
++i;
if (i >= argc) {
cerr << "No language name given after -x\n";
usage(argv[0]);
}
if (strcmp(argv[i], "c") && strcmp(argv[i], "objective-c")) {
cerr << "Unsupported language " << argv[i] << "\n";
usage(argv[0]);
}
language = argv[i];
} else if (!strcmp(argv[i], "-match")) {
++i;
if (i >= argc) {
cerr << "No string given after -match\n";
usage(argv[0]);
}
matchNames.push_back(std::string(argv[i]));
} else if (!strcmp(argv[i], "-import")) {
++i;
if (i >= argc) {
cerr << "No string given after -import\n";
usage(argv[0]);
}
importNames.push_back(std::string(argv[i]));
} else if (!strcmp(argv[i], "--")) {
++i;
if (!filename.empty()) {
if (i != argc) {
cerr << "Only one input file may be given\n";
usage(argv[0]);
}
break;
} else {
if (i != argc - 1) {
cerr << "Only one input file may be given\n";
usage(argv[0]);
}
filename = argv[i];
break;
}
} else if (argv[i][0] != '-') {
if (!filename.empty()) {
cerr << "Only one input file may be given\n";
usage(argv[0]);
}
filename = argv[i];
} else {
cerr << "Unrecognized option " << argv[i] << "\n";
usage(argv[0]);
}
}
std::ofstream *outfilestream = NULL;
if (!outfilename.empty() && outfilename != "-") {
outfilestream = new ofstream(outfilename.c_str());
if (outfilestream->fail()) {
cerr << "Unable to open " << outfilename << " for writing\n";
return EXIT_FAILURE;
}
}
std::ostream &outstream =
outfilestream ? *outfilestream : std::cout;
llvm::Triple triple(target);
// Setup clang
clang::TargetOptions targetOpts;
targetOpts.Triple = triple.str();
// MacOS X headers assume SSE is available
if (triple.getOS() == llvm::Triple::Darwin && triple.getArch() == llvm::Triple::x86)
targetOpts.Features.push_back("+sse2");
clang::DiagnosticOptions diagOpts;
BindingsConverter *converter = new BindingsConverter(
outstream,
diagOpts,
language,
matchNames,
importNames
);
// Create a preprocessor context
clang::LangOptions langOpts;
langOpts.Blocks = 1; // for recent OS X/iOS headers
langOpts.C99 = 1;
if (language == "objective-c") {
langOpts.ObjC1 = 1;
langOpts.ObjC2 = 1;
}
PPContext context(
targetOpts, converter, langOpts,
isysroot, frameworkDirs, headerDirs
);
// Add input file
const FileEntry* file = context.fm.getFile(filename);
if (!file) {
cerr << "Failed to open \'" << argv[1] << "\'";
return EXIT_FAILURE;
}
context.sm.createMainFileID(file);
// Initialize ASTContext
Builtin::Context builtins(*context.target);
builtins.InitializeBuiltins(context.pp.getIdentifierTable());
ASTContext astContext(context.opts, context.sm, *context.target,
context.pp.getIdentifierTable(),
context.pp.getSelectorTable(),
builtins, 0);
// Parse it
converter->BeginSourceFile(langOpts, &context.pp);
ParseAST(context.pp, converter, astContext); // calls pp.EnterMainSourceFile() for us
converter->EndSourceFile();
converter->generate();
if (outfilestream)
outfilestream->close();
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>PWGPP-571, PWGPP-529 -TStatToolkit::MakePDFMap() - memory leak fix<commit_after><|endoftext|> |
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3122
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3122 to 3123<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3123
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>#include <Zmey/EngineLoop.h>
#include <iostream>
#include <Zmey/Memory/Allocator.h>
#include <Zmey/Memory/MemoryManagement.h>
#include <Zmey/Logging.h>
namespace Zmey
{
class MallocAllocator : public Zmey::IAllocator
{
public:
virtual void* Malloc(size_t size, unsigned)
{
return std::malloc(size);
}
virtual void Free(void* ptr)
{
std::free(ptr);
}
virtual void* Realloc(void* ptr, size_t newSize)
{
return std::realloc(ptr, newSize);
}
};
class StdOutLogHandler : public Zmey::ILogHandler
{
private:
const char* StringifySeverity(LogSeverity severity)
{
switch (severity)
{
case LogSeverity::Debug: return "Debug";
case LogSeverity::Trace: return "Trace";
case LogSeverity::Info: return "Info";
case LogSeverity::Warning: return "Warning";
case LogSeverity::Error: return "Error";
case LogSeverity::Fatal: return "Fatal";
default:
return "Unknown severity";
}
}
public:
virtual void WriteLog(LogSeverity severity, const char* message)
{
printf("Zmey [%s]: %s\r\n", StringifySeverity(severity), message);
}
};
EngineLoop::EngineLoop()
{
Zmey::GAllocator = StaticAlloc<MallocAllocator>();
Zmey::GLogHandler = StaticAlloc<StdOutLogHandler>();
}
void EngineLoop::Run()
{
while (1)
{
LOG(Info, "HEEEY");
}
}
EngineLoop::~EngineLoop()
{}
}<commit_msg>Added an example usage of the task system.<commit_after>#include <Zmey/EngineLoop.h>
#include <iostream>
#include <Zmey/Memory/Allocator.h>
#include <Zmey/Memory/MemoryManagement.h>
#include <Zmey/Logging.h>
#include <Zmey/Tasks/TaskSystem.h>
namespace Zmey
{
class MallocAllocator : public Zmey::IAllocator
{
public:
virtual void* Malloc(size_t size, unsigned)
{
return std::malloc(size);
}
virtual void Free(void* ptr)
{
std::free(ptr);
}
virtual void* Realloc(void* ptr, size_t newSize)
{
return std::realloc(ptr, newSize);
}
};
class StdOutLogHandler : public Zmey::ILogHandler
{
private:
const char* StringifySeverity(LogSeverity severity)
{
switch (severity)
{
case LogSeverity::Debug: return "Debug";
case LogSeverity::Trace: return "Trace";
case LogSeverity::Info: return "Info";
case LogSeverity::Warning: return "Warning";
case LogSeverity::Error: return "Error";
case LogSeverity::Fatal: return "Fatal";
default:
return "Unknown severity";
}
}
public:
virtual void WriteLog(LogSeverity severity, const char* message)
{
printf("Zmey [%s]: %s\r\n", StringifySeverity(severity), message);
}
};
EngineLoop::EngineLoop()
{
Zmey::GAllocator = StaticAlloc<MallocAllocator>();
Zmey::GLogHandler = StaticAlloc<StdOutLogHandler>();
}
void EngineLoop::Run()
{
TaskSystem<4> taskSystem;
auto lambda = []()
{
FORMAT_LOG(Info, "from thread %d", std::this_thread::get_id());
};
while (1)
{
taskSystem.SpawnTask("Log", lambda);
taskSystem.SpawnTask("Log", lambda);
taskSystem.SpawnTask("Log", lambda);
taskSystem.SpawnTask("Log", lambda);
}
}
EngineLoop::~EngineLoop()
{}
}<|endoftext|> |
<commit_before>#include "Path.hpp"
#ifdef _WIN32
#include <algorithm>
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <direct.h>
#elif __linux__
#include <dirent.h>
#include <limits.h>
#include <stdlib.h>
// Very beautiful.
#define MAX_PATH 4096
#else
#error "This no work on OS X :("
#endif
void Util::setSaneCWD()
{
#ifdef _WIN32
char buffer[MAX_PATH];
GetModuleFileNameA(NULL, buffer, MAX_PATH);
std::string path = buffer;
size_t loc = path.find_last_of('\\');
if (loc != std::string::npos)
path.erase(loc, path.size() - loc);
_chdir(path.c_str());
#else
#endif
}
#ifdef _WIN32
std::string Util::getAbsolutePath(const std::string& inp)
{
std::string path = inp;
#ifdef _WIN32
std::replace(path.begin(), path.end(), '/', '\\');
#endif
char temp[_MAX_PATH];
return (_fullpath(temp, path.c_str(), _MAX_PATH) ? std::string(temp) : std::string());
}
#else
std::string Util::getAbsolutePath(const std::string& path)
{
char temp[PATH_MAX];
return (realpath(path.c_str(), temp) ? std::string(temp) : std::string());
}
#endif
std::list<std::string> Util::getFilesInDir(const std::string& relative)
{
std::string path = getAbsolutePath(relative);
std::list<std::string> ret;
#ifdef _WIN32
WIN32_FIND_DATA findData;
HANDLE findHandle = FindFirstFile((path + "\\*").c_str(), &findData);
if (findHandle == INVALID_HANDLE_VALUE)
return ret;
do
{
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
continue;
ret.push_back(relative + "/" + findData.cFileName);
} while (FindNextFile(findHandle, &findData) != 0);
FindClose(findHandle);
#else
DIR *pDIR;
struct dirent *entry;
if (!(pDIR = opendir(path.c_str())))
return ret;
while (entry = readdir(pDIR))
{
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
ret.push_back(repative + "/" + entry->d_name);
}
closedir(pDIR);
#endif
return ret;
}
<commit_msg>Oops, a few misses on the linux implementation for this<commit_after>#include "Path.hpp"
#ifdef _WIN32
#include <algorithm>
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <direct.h>
#elif __linux__
#include <dirent.h>
#include <climits>
#include <cstdlib>
#include <cstring>
// Very beautiful.
#define MAX_PATH 4096
#else
#error "This no work on OS X :("
#endif
void Util::setSaneCWD()
{
#ifdef _WIN32
char buffer[MAX_PATH];
GetModuleFileNameA(NULL, buffer, MAX_PATH);
std::string path = buffer;
size_t loc = path.find_last_of('\\');
if (loc != std::string::npos)
path.erase(loc, path.size() - loc);
_chdir(path.c_str());
#else
#endif
}
#ifdef _WIN32
std::string Util::getAbsolutePath(const std::string& inp)
{
std::string path = inp;
#ifdef _WIN32
std::replace(path.begin(), path.end(), '/', '\\');
#endif
char temp[_MAX_PATH];
return (_fullpath(temp, path.c_str(), _MAX_PATH) ? std::string(temp) : std::string());
}
#else
std::string Util::getAbsolutePath(const std::string& path)
{
char temp[PATH_MAX];
return (realpath(path.c_str(), temp) ? std::string(temp) : std::string());
}
#endif
std::list<std::string> Util::getFilesInDir(const std::string& relative)
{
std::string path = getAbsolutePath(relative);
std::list<std::string> ret;
#ifdef _WIN32
WIN32_FIND_DATA findData;
HANDLE findHandle = FindFirstFile((path + "\\*").c_str(), &findData);
if (findHandle == INVALID_HANDLE_VALUE)
return ret;
do
{
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
continue;
ret.push_back(relative + "/" + findData.cFileName);
} while (FindNextFile(findHandle, &findData) != 0);
FindClose(findHandle);
#else
DIR *pDIR;
struct dirent *entry;
if (!(pDIR = opendir(path.c_str())))
return ret;
while (entry = readdir(pDIR))
{
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
ret.push_back(relative + "/" + entry->d_name);
}
closedir(pDIR);
#endif
return ret;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <conio.h>
#include <string>
#include <sstream>
#include "world.h"
using namespace std;
int main() {
string userInput;
World theShip;
char inputKey;
vector<string> tokens;
std::cout << "Welcome to Swashbuckler! - The true pirates Zork-like game" << std::endl;
std::cout << "---------------------------------------------" << std::endl;
std::cout << "You wake up on the ship, in the middle of the night, with a sound different than the usual snoring of the crew. Steps." << std::endl;
std::cout << "With a glance, you see the Captain passing silently between everyone. You notice a small letter with the navy seal falling from his pocket. THE NAVY SEAL?!" << std::endl;
std::cout << "You wait until the captain goes back to his room and check the letter. Bad news. Very, very bad news." << std::endl;
std::cout << "A true pirate would fight the Captain to take command of the ship and save your crew. A true pirate." << std::endl;
std::cout << "A pity that you're just a novice! YOU BETTER GET OUT OF HERE SOON, LAD!!" << std::endl;
std::cout << "---------------------------------------------" << std::endl << ">";
theShip.worldTimer = clock();
while (1)
{
//User Input loop
if (_kbhit())
{
inputKey = _getch();
if (inputKey == '\b')
{
if (userInput.size() > 0) userInput.pop_back();
std::cout << '\b';
std::cout << ' ';
std::cout << '\b';
}
else if (inputKey == '\r')
{
string buf;
stringstream ss(userInput);
while (ss >> buf)
tokens.push_back(buf);
userInput.clear();
}
else
{
userInput = userInput + inputKey;
std::cout << inputKey;
}
}
//Update the world turn (Affects NPC behaviour)
if (theShip.worldTurn(tokens))
{
tokens.clear();
}
//Ending step (Good or Bad)
if (theShip.mainguy->escaped || theShip.badguy->shot)
{
theShip.ending();
break;
}
}
std::cout << "---------------------------------------------" << std::endl;
std::cout << "Thanks for playing Swashbuckler!" << endl << "See ya soon, landlubber!" << std::endl;
std::cout << "Xavier (Zelleryon) Bravo" << std::endl;
_getch();
return 0;
}<commit_msg>Generic output modified<commit_after>#include <iostream>
#include <conio.h>
#include <string>
#include <sstream>
#include "world.h"
using namespace std;
int main() {
string userInput;
World theShip;
char inputKey;
vector<string> tokens;
std::cout << "Welcome to SWASHBUCKLER! - The true pirates Zork-like game" << std::endl;
std::cout << "---------------------------------------------" << std::endl;
std::cout << "You wake up on the ship, in the middle of the night, with a sound different than the usual snoring of the crew. Steps." << std::endl;
std::cout << "With a glance, you see the Captain passing silently between everyone. You notice a small letter with the navy seal falling from his pocket. THE NAVY SEAL?!" << std::endl;
std::cout << "You wait until the captain goes back to his room and check the letter. Bad news. Very, very bad news." << std::endl;
std::cout << "A true pirate would fight the Captain to take command of the ship and save your crew. A true pirate." << std::endl;
std::cout << "A pity that you're just a novice! YOU BETTER GET OUT OF HERE SOON, LAD!!" << std::endl;
std::cout << "---------------------------------------------" << std::endl << ">";
theShip.worldTimer = clock();
while (1)
{
//User Input loop
if (_kbhit())
{
inputKey = _getch();
if (inputKey == '\b')
{
if (userInput.size() > 0) userInput.pop_back();
std::cout << '\b';
std::cout << ' ';
std::cout << '\b';
}
else if (inputKey == '\r')
{
string buf;
stringstream ss(userInput);
while (ss >> buf)
tokens.push_back(buf);
userInput.clear();
}
else
{
userInput = userInput + inputKey;
std::cout << inputKey;
}
}
//Update the world turn (Affects NPC behaviour)
if (theShip.worldTurn(tokens))
{
tokens.clear();
}
//Ending step (Good or Bad)
if (theShip.mainguy->escaped || theShip.badguy->shot)
{
theShip.ending();
break;
}
}
std::cout << "---------------------------------------------" << std::endl;
std::cout << "Thanks for playing Swashbuckler!" << endl << "See ya soon, landlubber!" << std::endl;
std::cout << "Xavier (Zelleryon) Bravo" << std::endl;
_getch();
return 0;
}<|endoftext|> |
<commit_before>/**
* @file game.cpp
* @brief Purpose: Contains methods that create and specify a hitbox.
*
* MIT License
* Copyright (c) 2017 MindScape
*
* https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
*/
#include "game.hpp"
#include <unistd.h>
#include "log.hpp"
using namespace engine;
Game* Game::instance = NULL; /**< initialization of the game instance singleton */
/**
* @brief shows which function has an error and exits.
*
* @params function that has an error.
* @return void.
*/
void throw_error(const char* function) {
WARN(("Something's wrong in %s\n", function));
exit(-1);
}
/**
* @brief Checks if an instance was created.
*
* In cases when dont have an instance created, it is alerted to create one and exits.
*
* @return Returns the instance.
*/
Game& Game::get_instance() {
DEBUG("Getting instance of game");
if (!instance) {
/* if the instance is null */
WARN("Instance is null. Exiting.");
exit(1);
}
else {
/*Do nothing*/
}
return *instance;
}
/**
* @brief Initializes an instance if one does not exist.
*
* @params p_name name of the game.
* @params p_dimensions dimensions of the window.
* @return Returns an instance created.
*/
Game& Game::initialize(std::string p_name, std::pair<int, int> p_dimensions) {
if (!instance) {
/* if the instance is null */
instance = new Game();
instance->set_information(p_name, p_dimensions);
instance->init();
}
else {
/*Do nothing*/
}
return *instance;
}
/**
* @brief Initializes the game.
*
* initializes all that need in background,
* video, audio before the start the window. And treats the erros.
*
* @return void.
*/
void Game::init() {
int img_flags = IMG_INIT_PNG; /**< flags for sdl image lib */
if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) < 0) {
/* if the initialization of the video and audio doesn't work properly */
WARN("Audio and video not initialized properly");
throw_error("SDL_Init");
}
else {
/*Do nothing*/
}
img_flags = IMG_INIT_PNG;
if (!(IMG_Init(IMG_INIT_PNG) & img_flags)) {
/* if the initialization of sdl img is not working properly */
WARN("SDL IMG not initialized properly");
throw_error("IMG_Init");
}
else {
/*Do nothing*/
}
if (Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 512 ) < 0 ) {
/* if the mix audio sdl lib is not working properly */
WARN(("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError()));
}
else {
/*Do nothing*/
}
if (TTF_Init() == -1) {
/* if the ttf sdl lib is not working properly */
WARN("TTF SDL lib not initialized properly");
throw_error("TTF_Init");
}
else {
/*Do nothing*/
}
window = SDL_CreateWindow(name.c_str(),SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,window_dimensions.first,
window_dimensions.second,SDL_WINDOW_SHOWN);
if (!window) {
/* if the window is null it means it didnt work well */
WARN("Window not created");
throw_error("SDL_CreateWindow");
}
else {
/*Do nothing*/
}
renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED
| SDL_RENDERER_PRESENTVSYNC);
if (!renderer) {
/* if renderer is null then it was not instantiated correctly */
WARN("Renderer is null");
throw_error("SDL_CreateRenderer");
}
else {
/*Do nothing*/
}
}
/**
* @brief Load the media based its scene.
*
* @return void.
*/
void Game::load_media() {
actual_scene->load();
loaded_media = true;
}
/**
* @brief This method is a test to know if media is loaded.
*
* @return Returns the situation of media.
*/
bool Game::is_media_loaded() {
return loaded_media;
}
/**
* @brief Closes the game.
*
* Closes the game, destroying its renderer, window, functions of the game and medias.
*
* @return void.
*/
void Game::close() {
DEBUG("Attempting to close game");
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
renderer = NULL;
window = NULL;
IMG_Quit();
SDL_Quit();
}
void Game::run() {
state = RUNNING;
DEBUG("Game is running");
if (is_media_loaded()) {
DEBUG("Game media is loaded");
/* if the media is already loaded */
SDL_Event e;
EventHandler event_handler = EventHandler();
Time::init();
while (state != QUIT) {
/* while the state is not quit */
unsigned now = Time::time_elapsed();
event_handler.dispatch_pending_events(now);
if (state != PAUSED) {
/* if the state is different from pause state */
actual_scene->update();
}
else {
/*Do nothing*/
}
SDL_SetRenderDrawColor(renderer, 0xE2, 0xAC, 0xF3, 0x00);
SDL_RenderClear(renderer);
actual_scene->draw();
SDL_RenderPresent(renderer);
}
}
else {
/* print if the medias were not yet loaded */
WARN("Medias could not be loaded\n");
}
close();
}
/**
* @brief Sets the name and the dimensions of the window.
*
* @params p_name the name of the game.
* @params p_dimensions this params refers to a dimension os the window.
* @return void.
*/
void Game::set_information(std::string p_name,std::pair<int,int> p_dimensions) {
set_name(p_name);
set_window_dimensions(p_dimensions);
}
/**
* @brief Changes the scene.
*
* Changes the scene based in its level and in its actual scene.
* Loads the media based in this.
*
* @params level pointer to know which scene will be loaded.
* @return void.
*/
void Game::change_scene(Scene *level) {
DEBUG("Changing scene");
if (actual_scene) {
/* if actual scene is not null */
actual_scene->deactivate();
actual_scene->free();
delete actual_scene;
}
else {
/*Do nothing*/
}
level->activate();
actual_scene = level;
load_media();
}
/**
* @brief This method get the current scene of the game.
*
* It is important to load the media of the game
*
*
*/
Scene* Game::get_actual_scene() {
return actual_scene;
}
/**
* @brief This Routine set the game background color.
*
* It is important to use RGBA to change the opacity of the background.
* R (red) G (green) B (blue) is the regular colors and the A is the opacity nivel.
*
* @param integer containing the quantity of the red color to be set to the background.
* @param integer containing the quantity of the green color to be set to the background.
* @param integer containing the quantity of the blue color to be set to the background.
* @param integer containing the quantity of the Alpha (A) opacity to be set to the background.
* @return void.
*/
void Game::set_game_background_color(int R, int G, int B, int A) {
/*Ensures that the color values given are valid*/
bool color_is_valid = true;
if (R < 0 || R > 255) {
/*Given value for red channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else if (G < 0 || G > 255) {
/*Given value for green channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else if (B < 0 || B > 255) {
/*Given value for blue channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else if (A < 0 || A > 255) {
/*Given value for alpha channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else {
/*All values are valid*/
}
if (color_is_valid) {
game_background_color = Color(R, G, B, A);
}
}
/**
* @brief This Routine set the name of the game.
*
* @param string containing the game name to be set.
* @return void.
*/
void Game::set_name(std::string p_name) {
name = p_name;
}
/**
* @brief This method get the current game name.
*
* @return string that contains the game name.
*/
std::string Game::get_name() {
return name;
}
/**
* @brief This method set the window dimensions.
*
* it is important to scale the window on the player screen and no errors happen.
*
* @param map that contains two integer that will set the width and the height.
* @return void.
*/
void Game::set_window_dimensions(std::pair<int, int> p_window_dimensions) {
window_dimensions = p_window_dimensions;
}
/**
* @brief This method get the window dimensions.
*
* It is important to resize the window dimensions accordingly the dimensions that need to run the game without bugs.
* @return map that contains the window dimensions.
*/
std::pair<int, int> Game::get_window_dimensions() {
return window_dimensions;
}
/**
* @brief This method set the current game state.
*
* @param state that contains the game state.
* @return void.
*/
void Game::set_state(State p_state) {
state = p_state;
}
/**
* @brief This method get the current game state.
*
* It is important to know what the game state to run the game.
*
* @return state of the game.
*/
Game::State Game::get_state() {
return state;
}
/**
* @brief This method get the renderer of the game.
*
* it is most important because it's the contact of the software with the user.
* It is one the principals parts to load and close the game.
*
* @return renderer of the game.
*/
SDL_Renderer * Game::get_renderer() {
return renderer;
}
<commit_msg>[DECOMPOSITION IN ATOMIC FUNCTIONS] Apply technique in game.cpp<commit_after>/**
* @file game.cpp
* @brief Purpose: Contains methods that create and specify a hitbox.
*
* MIT License
* Copyright (c) 2017 MindScape
*
* https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
*/
#include "game.hpp"
#include <unistd.h>
#include "log.hpp"
using namespace engine;
Game* Game::instance = NULL; /**< initialization of the game instance singleton */
/**
* @brief shows which function has an error and exits.
*
* @params function that has an error.
* @return void.
*/
void throw_error(const char* function) {
WARN(("Something's wrong in %s\n", function));
exit(-1);
}
/**
* @brief Checks if an instance was created.
*
* In cases when dont have an instance created, it is alerted to create one and exits.
*
* @return Returns the instance.
*/
Game& Game::get_instance() {
DEBUG("Getting instance of game");
if (!instance) {
/* if the instance is null */
WARN("Instance is null. Exiting.");
exit(1);
}
else {
/*Do nothing*/
}
return *instance;
}
/**
* @brief Initializes an instance if one does not exist.
*
* @params p_name name of the game.
* @params p_dimensions dimensions of the window.
* @return Returns an instance created.
*/
Game& Game::initialize(std::string p_name, std::pair<int, int> p_dimensions) {
if (!instance) {
/* if the instance is null */
instance = new Game();
instance->set_information(p_name, p_dimensions);
instance->init();
}
else {
/*Do nothing*/
}
return *instance;
}
/**
* @brief Initializes the game.
*
* initializes all that need in background,
* video, audio before the start the window. And treats the erros.
*
* @return void.
*/
void Game::init() {
int img_flags = IMG_INIT_PNG; /**< flags for sdl image lib */
if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) < 0) {
/* if the initialization of the video and audio doesn't work properly */
WARN("Audio and video not initialized properly");
throw_error("SDL_Init");
}
else {
/*Do nothing*/
}
img_flags = IMG_INIT_PNG;
if (!(IMG_Init(IMG_INIT_PNG) & img_flags)) {
/* if the initialization of sdl img is not working properly */
WARN("SDL IMG not initialized properly");
throw_error("IMG_Init");
}
else {
/*Do nothing*/
}
if (Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 512 ) < 0 ) {
/* if the mix audio sdl lib is not working properly */
WARN(("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError()));
}
else {
/*Do nothing*/
}
if (TTF_Init() == -1) {
/* if the ttf sdl lib is not working properly */
WARN("TTF SDL lib not initialized properly");
throw_error("TTF_Init");
}
else {
/*Do nothing*/
}
window = SDL_CreateWindow(name.c_str(),SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,window_dimensions.first,
window_dimensions.second,SDL_WINDOW_SHOWN);
if (!window) {
/* if the window is null it means it didnt work well */
WARN("Window not created");
throw_error("SDL_CreateWindow");
}
else {
/*Do nothing*/
}
renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED
| SDL_RENDERER_PRESENTVSYNC);
if (!renderer) {
/* if renderer is null then it was not instantiated correctly */
WARN("Renderer is null");
throw_error("SDL_CreateRenderer");
}
else {
/*Do nothing*/
}
}
/**
* @brief Load the media based its scene.
*
* @return void.
*/
void Game::load_media() {
actual_scene->load();
loaded_media = true;
}
/**
* @brief This method is a test to know if media is loaded.
*
* @return Returns the situation of media.
*/
bool Game::is_media_loaded() {
return loaded_media;
}
/**
* @brief Closes the game.
*
* Closes the game, destroying its renderer, window, functions of the game and medias.
*
* @return void.
*/
void Game::close() {
DEBUG("Attempting to close game");
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
renderer = NULL;
window = NULL;
IMG_Quit();
SDL_Quit();
}
void Game::run() {
state = RUNNING;
DEBUG("Game is running");
if (is_media_loaded()) {
DEBUG("Game media is loaded");
/* if the media is already loaded */
SDL_Event e;
EventHandler event_handler = EventHandler();
Time::init();
while (state != QUIT) {
/* while the state is not quit */
unsigned now = Time::time_elapsed();
event_handler.dispatch_pending_events(now);
if (state != PAUSED) {
/* if the state is different from pause state */
actual_scene->update();
}
else {
/*Do nothing*/
}
SDL_SetRenderDrawColor(renderer, 0xE2, 0xAC, 0xF3, 0x00);
SDL_RenderClear(renderer);
actual_scene->draw();
SDL_RenderPresent(renderer);
}
}
else {
/* print if the medias were not yet loaded */
WARN("Medias could not be loaded\n");
}
close();
}
/**
* @brief Sets the name and the dimensions of the window.
*
* @params p_name the name of the game.
* @params p_dimensions this params refers to a dimension os the window.
* @return void.
*/
void Game::set_information(std::string p_name,std::pair<int,int> p_dimensions) {
set_name(p_name);
set_window_dimensions(p_dimensions);
}
/**
* @brief Changes the scene.
*
* Changes the scene based in its level and in its actual scene.
* Loads the media based in this.
*
* @params level pointer to know which scene will be loaded.
* @return void.
*/
void Game::change_scene(Scene *level) {
DEBUG("Changing scene");
if (actual_scene) {
/* if actual scene is not null */
actual_scene->deactivate();
actual_scene->free();
delete actual_scene;
}
else {
/*Do nothing*/
}
level->activate();
actual_scene = level;
load_media();
}
/**
* @brief This method get the current scene of the game.
*
* It is important to load the media of the game
*
*
*/
Scene* Game::get_actual_scene() {
return actual_scene;
}
/**
* @brief This routine validates an RGBA color.
*
* It is important to use RGBA to change the opacity of the background.
* R (red) G (green) B (blue) is the regular colors and the A is the opacity nivel.
*
* @param integer containing the quantity of the red color.
* @param integer containing the quantity of the green color.
* @param integer containing the quantity of the blue color.
* @param integer containing the quantity of the Alpha (A) opacity.
* @return void.
*/
bool RGBA_color_is_valid(int R, int G, int B, int A) {
bool color_is_valid = true;
if (R < 0 || R > 255) {
/*Given value for red channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else if (G < 0 || G > 255) {
/*Given value for green channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else if (B < 0 || B > 255) {
/*Given value for blue channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else if (A < 0 || A > 255) {
/*Given value for alpha channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else {
/*All values are valid*/
}
return color_is_valid;
}
/**
* @brief This Routine set the game background color.
*
* It is important to use RGBA to change the opacity of the background.
* R (red) G (green) B (blue) is the regular colors and the A is the opacity nivel.
*
* @param integer containing the quantity of the red color to be set to the background.
* @param integer containing the quantity of the green color to be set to the background.
* @param integer containing the quantity of the blue color to be set to the background.
* @param integer containing the quantity of the Alpha (A) opacity to be set to the background.
* @return void.
*/
void Game::set_game_background_color(int R, int G, int B, int A) {
if (RGBA_color_is_valid(R, G, B, A)) {
/*Ensures that the color values given are valid*/
game_background_color = Color(R, G, B, A);
}
}
/**
* @brief This Routine set the name of the game.
*
* @param string containing the game name to be set.
* @return void.
*/
void Game::set_name(std::string p_name) {
name = p_name;
}
/**
* @brief This method get the current game name.
*
* @return string that contains the game name.
*/
std::string Game::get_name() {
return name;
}
/**
* @brief This method set the window dimensions.
*
* it is important to scale the window on the player screen and no errors happen.
*
* @param map that contains two integer that will set the width and the height.
* @return void.
*/
void Game::set_window_dimensions(std::pair<int, int> p_window_dimensions) {
window_dimensions = p_window_dimensions;
}
/**
* @brief This method get the window dimensions.
*
* It is important to resize the window dimensions accordingly the dimensions that need to run the game without bugs.
* @return map that contains the window dimensions.
*/
std::pair<int, int> Game::get_window_dimensions() {
return window_dimensions;
}
/**
* @brief This method set the current game state.
*
* @param state that contains the game state.
* @return void.
*/
void Game::set_state(State p_state) {
state = p_state;
}
/**
* @brief This method get the current game state.
*
* It is important to know what the game state to run the game.
*
* @return state of the game.
*/
Game::State Game::get_state() {
return state;
}
/**
* @brief This method get the renderer of the game.
*
* it is most important because it's the contact of the software with the user.
* It is one the principals parts to load and close the game.
*
* @return renderer of the game.
*/
SDL_Renderer * Game::get_renderer() {
return renderer;
}
<|endoftext|> |
<commit_before>/**
* @file game.cpp
* @brief Purpose: Contains methods that create and specify a hitbox.
*
* MIT License
* Copyright (c) 2017 MindScape
*
* https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
*/
#include "game.hpp"
#include <unistd.h>
#include "log.hpp"
using namespace engine;
Game* Game::instance = NULL; /**< initialization of the game instance singleton */
/**
* @brief shows which function has an error and exits.
*
* @params function that has an error.
* @return void.
*/
void throw_error(const char* function) {
WARN(("Something's wrong in %s\n", function));
exit(-1);
}
/**
* @brief Checks if an instance was created.
*
* In cases when dont have an instance created, it is alerted to create one and exits.
*
* @return Returns the instance.
*/
Game& Game::get_instance() {
DEBUG("Getting instance of game");
if (!instance) {
/* if the instance is null */
WARN("Instance is null. Exiting.");
exit(1);
}
else {
/*Do nothing*/
}
return *instance;
}
/**
* @brief Initializes an instance if one does not exist.
*
* @params p_name name of the game.
* @params p_dimensions dimensions of the window.
* @return Returns an instance created.
*/
Game& Game::initialize(std::string p_name, std::pair<int, int> p_dimensions) {
if (!instance) {
/* if the instance is null */
instance = new Game();
instance->set_information(p_name, p_dimensions);
instance->init();
}
else {
/*Do nothing*/
}
return *instance;
}
/**
* @brief Initializes the game.
*
* initializes all that need in background,
* video, audio before the start the window. And treats the erros.
*
* @return void.
*/
void Game::init() {
int img_flags = IMG_INIT_PNG; /**< flags for sdl image lib */
if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) < 0) {
/* if the initialization of the video and audio doesn't work properly */
WARN("Audio and video not initialized properly");
throw_error("SDL_Init");
}
else {
/*Do nothing*/
}
img_flags = IMG_INIT_PNG;
if (!(IMG_Init(IMG_INIT_PNG) & img_flags)) {
/* if the initialization of sdl img is not working properly */
WARN("SDL IMG not initialized properly");
throw_error("IMG_Init");
}
else {
/*Do nothing*/
}
if (Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 512 ) < 0 ) {
/* if the mix audio sdl lib is not working properly */
WARN(("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError()));
}
else {
/*Do nothing*/
}
if (TTF_Init() == -1) {
/* if the ttf sdl lib is not working properly */
WARN("TTF SDL lib not initialized properly");
throw_error("TTF_Init");
}
else {
/*Do nothing*/
}
window = SDL_CreateWindow(name.c_str(),SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,window_dimensions.first,
window_dimensions.second,SDL_WINDOW_SHOWN);
if (!window) {
/* if the window is null it means it didnt work well */
WARN("Window not created");
throw_error("SDL_CreateWindow");
}
else {
/*Do nothing*/
}
renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED
| SDL_RENDERER_PRESENTVSYNC);
if (!renderer) {
/* if renderer is null then it was not instantiated correctly */
WARN("Renderer is null");
throw_error("SDL_CreateRenderer");
}
else {
/*Do nothing*/
}
}
/**
* @brief Load the media based its scene.
*
* @return void.
*/
void Game::load_media() {
actual_scene->load();
loaded_media = true;
}
/**
* @brief This method is a test to know if media is loaded.
*
* @return Returns the situation of media.
*/
bool Game::is_media_loaded() {
return loaded_media;
}
/**
* @brief Closes the game.
*
* Closes the game, destroying its renderer, window, functions of the game and medias.
*
* @return void.
*/
void Game::close() {
DEBUG("Attempting to close game");
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
renderer = NULL;
window = NULL;
IMG_Quit();
SDL_Quit();
}
/**
* @brief Renders a given scene.
*
* Given a scene, it replaces the previous with the given.
*
* @params SDL_Renderer* renderer that will render the new scene.
* @params Scene* actual_scene that is the scene that will be updated.
*
* @return void.
*/
void renderScreen(SDL_Renderer* renderer, Scene* actual_scene) {
const Uint8 r_value = 0xE2;
const Uint8 g_value = 0xAC;
const Uint8 b_value = 0xF3;
const Uint8 a_value = 0x00;
SDL_SetRenderDrawColor(renderer, r_value, g_value, b_value, a_value);
SDL_RenderClear(renderer);
actual_scene->draw();
SDL_RenderPresent(renderer);
}
/**
* @brief Runs the game.
*
* Runs the game updating the scenes and verifying the states.
*
* @return void.
*/
void Game::run() {
state = RUNNING;
DEBUG("Game is running");
if (is_media_loaded()) {
DEBUG("Game media is loaded");
/* if the media is already loaded */
SDL_Event e;
EventHandler event_handler = EventHandler();
Time::init();
while (state != QUIT) {
/* while the state is not quit */
unsigned now = Time::time_elapsed();
event_handler.dispatch_pending_events(now);
if (state != PAUSED) {
/* if the state is different from pause state */
actual_scene->update();
}
else {
/*Do nothing*/
}
renderScreen(renderer, actual_scene);
}
}
else {
/* print if the medias were not yet loaded */
WARN("Medias could not be loaded\n");
}
close();
}
/**
* @brief Sets the name and the dimensions of the window.
*
* @params p_name the name of the game.
* @params p_dimensions this params refers to a dimension os the window.
* @return void.
*/
void Game::set_information(std::string p_name,std::pair<int,int> p_dimensions) {
set_name(p_name);
set_window_dimensions(p_dimensions);
}
/**
* @brief Changes the scene.
*
* Changes the scene based in its level and in its actual scene.
* Loads the media based in this.
*
* @params level pointer to know which scene will be loaded.
* @return void.
*/
void Game::change_scene(Scene *level) {
DEBUG("Changing scene");
if (actual_scene) {
/* if actual scene is not null */
actual_scene->deactivate();
actual_scene->free();
delete actual_scene;
}
else {
/*Do nothing*/
}
level->activate();
actual_scene = level;
load_media();
}
/**
* @brief This method get the current scene of the game.
*
* It is important to load the media of the game
*
*
*/
Scene* Game::get_actual_scene() {
return actual_scene;
}
/**
* @brief This routine validates an RGBA color.
*
* It is important to use RGBA to change the opacity of the background.
* R (red) G (green) B (blue) is the regular colors and the A is the opacity nivel.
*
* @param integer containing the quantity of the red color.
* @param integer containing the quantity of the green color.
* @param integer containing the quantity of the blue color.
* @param integer containing the quantity of the Alpha (A) opacity.
* @return void.
*/
bool RGBA_color_is_valid(int R, int G, int B, int A) {
bool color_is_valid = true;
if (R < 0 || R > 255) {
/*Given value for red channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else if (G < 0 || G > 255) {
/*Given value for green channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else if (B < 0 || B > 255) {
/*Given value for blue channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else if (A < 0 || A > 255) {
/*Given value for alpha channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else {
/*All values are valid*/
}
return color_is_valid;
}
/**
* @brief This Routine set the game background color.
*
* It is important to use RGBA to change the opacity of the background.
* R (red) G (green) B (blue) is the regular colors and the A is the opacity nivel.
*
* @param integer containing the quantity of the red color to be set to the background.
* @param integer containing the quantity of the green color to be set to the background.
* @param integer containing the quantity of the blue color to be set to the background.
* @param integer containing the quantity of the Alpha (A) opacity to be set to the background.
* @return void.
*/
void Game::set_game_background_color(int R, int G, int B, int A) {
if (RGBA_color_is_valid(R, G, B, A)) {
/*Ensures that the color values given are valid*/
game_background_color = Color(R, G, B, A);
}
}
/**
* @brief This Routine set the name of the game.
*
* @param string containing the game name to be set.
* @return void.
*/
void Game::set_name(std::string p_name) {
name = p_name;
}
/**
* @brief This method get the current game name.
*
* @return string that contains the game name.
*/
std::string Game::get_name() {
return name;
}
/**
* @brief This method set the window dimensions.
*
* it is important to scale the window on the player screen and no errors happen.
*
* @param map that contains two integer that will set the width and the height.
* @return void.
*/
void Game::set_window_dimensions(std::pair<int, int> p_window_dimensions) {
window_dimensions = p_window_dimensions;
}
/**
* @brief This method get the window dimensions.
*
* It is important to resize the window dimensions accordingly the dimensions that need to run the game without bugs.
* @return map that contains the window dimensions.
*/
std::pair<int, int> Game::get_window_dimensions() {
return window_dimensions;
}
/**
* @brief This method set the current game state.
*
* @param state that contains the game state.
* @return void.
*/
void Game::set_state(State p_state) {
state = p_state;
}
/**
* @brief This method get the current game state.
*
* It is important to know what the game state to run the game.
*
* @return state of the game.
*/
Game::State Game::get_state() {
return state;
}
/**
* @brief This method get the renderer of the game.
*
* it is most important because it's the contact of the software with the user.
* It is one the principals parts to load and close the game.
*
* @return renderer of the game.
*/
SDL_Renderer * Game::get_renderer() {
return renderer;
}
<commit_msg>[ASSERT] Apply technique in game.cpp<commit_after>/**
* @file game.cpp
* @brief Purpose: Contains methods that create and specify a hitbox.
*
* MIT License
* Copyright (c) 2017 MindScape
*
* https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
*/
#include "game.hpp"
#include <unistd.h>
#include "log.hpp"
#include <assert.h>
using namespace engine;
Game* Game::instance = NULL; /**< initialization of the game instance singleton */
/**
* @brief shows which function has an error and exits.
*
* @params function that has an error.
* @return void.
*/
void throw_error(const char* function) {
assert(function);
WARN(("Something's wrong in %s\n", function));
exit(-1);
}
/**
* @brief Checks if an instance was created.
*
* In cases when dont have an instance created, it is alerted to create one and exits.
*
* @return Returns the instance.
*/
Game& Game::get_instance() {
DEBUG("Getting instance of game");
assert(instance);
return *instance;
}
/**
* @brief Initializes an instance if one does not exist.
*
* @params p_name name of the game.
* @params p_dimensions dimensions of the window.
* @return Returns an instance created.
*/
Game& Game::initialize(std::string p_name, std::pair<int, int> p_dimensions) {
if (!instance) {
/* if the instance is null */
instance = new Game();
instance->set_information(p_name, p_dimensions);
instance->init();
}
else {
/*Do nothing*/
}
return *instance;
}
/**
* @brief Initializes the game.
*
* initializes all that need in background,
* video, audio before the start the window. And treats the erros.
*
* @return void.
*/
void Game::init() {
int img_flags = IMG_INIT_PNG; /**< flags for sdl image lib */
if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) < 0) {
/* if the initialization of the video and audio doesn't work properly */
WARN("Audio and video not initialized properly");
throw_error("SDL_Init");
}
else {
/*Do nothing*/
}
img_flags = IMG_INIT_PNG;
if (!(IMG_Init(IMG_INIT_PNG) & img_flags)) {
/* if the initialization of sdl img is not working properly */
WARN("SDL IMG not initialized properly");
throw_error("IMG_Init");
}
else {
/*Do nothing*/
}
if (Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 512 ) < 0 ) {
/* if the mix audio sdl lib is not working properly */
WARN(("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError()));
}
else {
/*Do nothing*/
}
if (TTF_Init() == -1) {
/* if the ttf sdl lib is not working properly */
WARN("TTF SDL lib not initialized properly");
throw_error("TTF_Init");
}
else {
/*Do nothing*/
}
window = SDL_CreateWindow(name.c_str(),SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,window_dimensions.first,
window_dimensions.second,SDL_WINDOW_SHOWN);
if (!window) {
/* if the window is null it means it didnt work well */
WARN("Window not created");
throw_error("SDL_CreateWindow");
}
else {
/*Do nothing*/
}
renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED
| SDL_RENDERER_PRESENTVSYNC);
if (!renderer) {
/* if renderer is null then it was not instantiated correctly */
WARN("Renderer is null");
throw_error("SDL_CreateRenderer");
}
else {
/*Do nothing*/
}
}
/**
* @brief Load the media based its scene.
*
* @return void.
*/
void Game::load_media() {
actual_scene->load();
loaded_media = true;
}
/**
* @brief This method is a test to know if media is loaded.
*
* @return Returns the situation of media.
*/
bool Game::is_media_loaded() {
return loaded_media;
}
/**
* @brief Closes the game.
*
* Closes the game, destroying its renderer, window, functions of the game and medias.
*
* @return void.
*/
void Game::close() {
DEBUG("Attempting to close game");
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
renderer = NULL;
window = NULL;
IMG_Quit();
SDL_Quit();
}
/**
* @brief Renders a given scene.
*
* Given a scene, it replaces the previous with the given.
*
* @params SDL_Renderer* renderer that will render the new scene.
* @params Scene* actual_scene that is the scene that will be updated.
*
* @return void.
*/
void renderScreen(SDL_Renderer* renderer, Scene* actual_scene) {
assert(renderer);
assert(actual_scene);
const Uint8 r_value = 0xE2;
const Uint8 g_value = 0xAC;
const Uint8 b_value = 0xF3;
const Uint8 a_value = 0x00;
SDL_SetRenderDrawColor(renderer, r_value, g_value, b_value, a_value);
SDL_RenderClear(renderer);
actual_scene->draw();
SDL_RenderPresent(renderer);
}
/**
* @brief Runs the game.
*
* Runs the game updating the scenes and verifying the states.
*
* @return void.
*/
void Game::run() {
state = RUNNING;
DEBUG("Game is running");
if (is_media_loaded()) {
DEBUG("Game media is loaded");
/* if the media is already loaded */
SDL_Event e;
EventHandler event_handler = EventHandler();
Time::init();
while (state != QUIT) {
/* while the state is not quit */
unsigned now = Time::time_elapsed();
event_handler.dispatch_pending_events(now);
if (state != PAUSED) {
/* if the state is different from pause state */
actual_scene->update();
}
else {
/*Do nothing*/
}
renderScreen(renderer, actual_scene);
}
}
else {
/* print if the medias were not yet loaded */
WARN("Medias could not be loaded\n");
}
close();
}
/**
* @brief Sets the name and the dimensions of the window.
*
* @params p_name the name of the game.
* @params p_dimensions this params refers to a dimension os the window.
* @return void.
*/
void Game::set_information(std::string p_name,std::pair<int,int> p_dimensions) {
assert(p_dimensions.first >= 0 && p_dimensions.second >= 0);
set_name(p_name);
set_window_dimensions(p_dimensions);
}
/**
* @brief Changes the scene.
*
* Changes the scene based in its level and in its actual scene.
* Loads the media based in this.
*
* @params level pointer to know which scene will be loaded.
* @return void.
*/
void Game::change_scene(Scene *level) {
DEBUG("Changing scene");
if (actual_scene) {
/* if actual scene is not null */
actual_scene->deactivate();
actual_scene->free();
delete actual_scene;
}
else {
/*Do nothing*/
}
level->activate();
actual_scene = level;
load_media();
}
/**
* @brief This method get the current scene of the game.
*
* It is important to load the media of the game
*
*
*/
Scene* Game::get_actual_scene() {
return actual_scene;
}
/**
* @brief This routine validates an RGBA color.
*
* It is important to use RGBA to change the opacity of the background.
* R (red) G (green) B (blue) is the regular colors and the A is the opacity nivel.
*
* @param integer containing the quantity of the red color.
* @param integer containing the quantity of the green color.
* @param integer containing the quantity of the blue color.
* @param integer containing the quantity of the Alpha (A) opacity.
* @return void.
*/
bool RGBA_color_is_valid(int R, int G, int B, int A) {
bool color_is_valid = true;
if (R < 0 || R > 255) {
/*Given value for red channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else if (G < 0 || G > 255) {
/*Given value for green channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else if (B < 0 || B > 255) {
/*Given value for blue channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else if (A < 0 || A > 255) {
/*Given value for alpha channel is out of limits, therefore, invalid*/
color_is_valid = false;
}
else {
/*All values are valid*/
}
return color_is_valid;
}
/**
* @brief This Routine set the game background color.
*
* It is important to use RGBA to change the opacity of the background.
* R (red) G (green) B (blue) is the regular colors and the A is the opacity nivel.
*
* @param integer containing the quantity of the red color to be set to the background.
* @param integer containing the quantity of the green color to be set to the background.
* @param integer containing the quantity of the blue color to be set to the background.
* @param integer containing the quantity of the Alpha (A) opacity to be set to the background.
* @return void.
*/
void Game::set_game_background_color(int R, int G, int B, int A) {
if (RGBA_color_is_valid(R, G, B, A)) {
/*Ensures that the color values given are valid*/
game_background_color = Color(R, G, B, A);
}
}
/**
* @brief This Routine set the name of the game.
*
* @param string containing the game name to be set.
* @return void.
*/
void Game::set_name(std::string p_name) {
name = p_name;
}
/**
* @brief This method get the current game name.
*
* @return string that contains the game name.
*/
std::string Game::get_name() {
return name;
}
/**
* @brief This method set the window dimensions.
*
* it is important to scale the window on the player screen and no errors happen.
*
* @param map that contains two integer that will set the width and the height.
* @return void.
*/
void Game::set_window_dimensions(std::pair<int, int> p_window_dimensions) {
window_dimensions = p_window_dimensions;
}
/**
* @brief This method get the window dimensions.
*
* It is important to resize the window dimensions accordingly the dimensions that need to run the game without bugs.
* @return map that contains the window dimensions.
*/
std::pair<int, int> Game::get_window_dimensions() {
return window_dimensions;
}
/**
* @brief This method set the current game state.
*
* @param state that contains the game state.
* @return void.
*/
void Game::set_state(State p_state) {
state = p_state;
}
/**
* @brief This method get the current game state.
*
* It is important to know what the game state to run the game.
*
* @return state of the game.
*/
Game::State Game::get_state() {
return state;
}
/**
* @brief This method get the renderer of the game.
*
* it is most important because it's the contact of the software with the user.
* It is one the principals parts to load and close the game.
*
* @return renderer of the game.
*/
SDL_Renderer * Game::get_renderer() {
return renderer;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "libcef/browser/browser_context.h"
#include <map>
#include "libcef/browser/browser_host_impl.h"
#include "libcef/browser/context.h"
#include "libcef/browser/download_manager_delegate.h"
#include "libcef/browser/resource_context.h"
#include "libcef/browser/thread_util.h"
#include "libcef/browser/url_request_context_getter.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/threading/thread.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/geolocation_permission_context.h"
#include "content/public/browser/speech_recognition_preferences.h"
using content::BrowserThread;
namespace {
class CefGeolocationPermissionContext
: public content::GeolocationPermissionContext {
public:
// CefGeolocationCallback implementation.
class CallbackImpl : public CefGeolocationCallback {
public:
typedef base::Callback<void(bool)> // NOLINT(readability/function)
CallbackType;
explicit CallbackImpl(
CefGeolocationPermissionContext* context,
int bridge_id,
const CallbackType& callback)
: context_(context),
bridge_id_(bridge_id),
callback_(callback) {}
virtual void Continue(bool allow) OVERRIDE {
if (CEF_CURRENTLY_ON_IOT()) {
if (!callback_.is_null()) {
// Callback must be executed on the UI thread.
CEF_POST_TASK(CEF_UIT,
base::Bind(&CallbackImpl::Run, callback_, allow));
context_->RemoveCallback(bridge_id_);
}
} else {
CEF_POST_TASK(CEF_IOT,
base::Bind(&CallbackImpl::Continue, this, allow));
}
}
void Disconnect() {
callback_.Reset();
context_ = NULL;
}
private:
static void Run(const CallbackType& callback, bool allow) {
CEF_REQUIRE_UIT();
callback.Run(allow);
}
CefGeolocationPermissionContext* context_;
int bridge_id_;
CallbackType callback_;
IMPLEMENT_REFCOUNTING(CallbackImpl);
};
CefGeolocationPermissionContext() {}
virtual void RequestGeolocationPermission(
int render_process_id,
int render_view_id,
int bridge_id,
const GURL& requesting_frame,
base::Callback<void(bool)> callback) // NOLINT(readability/function)
OVERRIDE {
CEF_REQUIRE_IOT();
CefRefPtr<CefBrowserHostImpl> browser =
CefBrowserHostImpl::GetBrowserByRoutingID(render_process_id,
render_view_id);
if (browser.get()) {
CefRefPtr<CefClient> client = browser->GetClient();
if (client.get()) {
CefRefPtr<CefGeolocationHandler> handler =
client->GetGeolocationHandler();
if (handler.get()) {
CefRefPtr<CallbackImpl> callbackPtr(
new CallbackImpl(this, bridge_id, callback));
// Add the callback reference to the map.
callback_map_.insert(std::make_pair(bridge_id, callbackPtr));
// Notify the handler.
handler->OnRequestGeolocationPermission(browser.get(),
requesting_frame.spec(), bridge_id, callbackPtr.get());
return;
}
}
}
// Disallow geolocation access by default.
callback.Run(false);
}
virtual void CancelGeolocationPermissionRequest(
int render_process_id,
int render_view_id,
int bridge_id,
const GURL& requesting_frame) OVERRIDE {
RemoveCallback(bridge_id);
CefRefPtr<CefBrowserHostImpl> browser =
CefBrowserHostImpl::GetBrowserByRoutingID(render_process_id,
render_view_id);
if (browser.get()) {
CefRefPtr<CefClient> client = browser->GetClient();
if (client.get()) {
CefRefPtr<CefGeolocationHandler> handler =
client->GetGeolocationHandler();
if (handler.get()) {
// Notify the handler.
handler->OnCancelGeolocationPermission(browser.get(),
requesting_frame.spec(), bridge_id);
}
}
}
}
void RemoveCallback(int bridge_id) {
CEF_REQUIRE_IOT();
// Disconnect the callback and remove the reference from the map.
CallbackMap::iterator it = callback_map_.find(bridge_id);
if (it != callback_map_.end()) {
it->second->Disconnect();
callback_map_.erase(it);
}
}
private:
// Map of bridge ids to callback references.
typedef std::map<int, CefRefPtr<CallbackImpl> > CallbackMap;
CallbackMap callback_map_;
DISALLOW_COPY_AND_ASSIGN(CefGeolocationPermissionContext);
};
class CefSpeechRecognitionPreferences
: public content::SpeechRecognitionPreferences {
public:
CefSpeechRecognitionPreferences() {
}
// Overridden from SpeechRecognitionPreferences:
virtual bool FilterProfanities() const OVERRIDE {
return false;
}
private:
DISALLOW_COPY_AND_ASSIGN(CefSpeechRecognitionPreferences);
};
} // namespace
CefBrowserContext::CefBrowserContext()
: use_osr_next_contents_view_(false) {
// Initialize the request context getter.
url_request_getter_ = new CefURLRequestContextGetter(
false,
GetPath(),
BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::IO),
BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::FILE));
}
CefBrowserContext::~CefBrowserContext() {
// Delete the download manager delegate here because otherwise we'll crash
// when it's accessed from the content::BrowserContext destructor.
if (download_manager_delegate_.get())
download_manager_delegate_.reset(NULL);
if (resource_context_.get()) {
BrowserThread::DeleteSoon(
BrowserThread::IO, FROM_HERE, resource_context_.release());
}
}
FilePath CefBrowserContext::GetPath() {
return _Context->cache_path();
}
bool CefBrowserContext::IsOffTheRecord() const {
return false;
}
content::DownloadManagerDelegate*
CefBrowserContext::GetDownloadManagerDelegate() {
DCHECK(!download_manager_delegate_.get());
content::DownloadManager* manager = BrowserContext::GetDownloadManager(this);
download_manager_delegate_.reset(new CefDownloadManagerDelegate(manager));
return download_manager_delegate_.get();
}
net::URLRequestContextGetter* CefBrowserContext::GetRequestContext() {
return url_request_getter_;
}
net::URLRequestContextGetter*
CefBrowserContext::GetRequestContextForRenderProcess(
int renderer_child_id) {
CefRefPtr<CefBrowserHostImpl> browser =
CefBrowserHostImpl::GetBrowserByChildID(renderer_child_id);
if (browser.get())
return browser->GetRequestContext();
return GetRequestContext();
}
net::URLRequestContextGetter*
CefBrowserContext::GetMediaRequestContext() {
return GetRequestContext();
}
net::URLRequestContextGetter*
CefBrowserContext::GetMediaRequestContextForRenderProcess(
int renderer_child_id) {
return GetRequestContext();
}
net::URLRequestContextGetter*
CefBrowserContext::GetMediaRequestContextForStoragePartition(
const FilePath& partition_path,
bool in_memory) {
return GetRequestContext();
}
net::URLRequestContextGetter*
CefBrowserContext::GetRequestContextForStoragePartition(
const FilePath& partition_path,
bool in_memory) {
return NULL;
}
content::ResourceContext* CefBrowserContext::GetResourceContext() {
if (!resource_context_.get()) {
resource_context_.reset(new CefResourceContext(
static_cast<CefURLRequestContextGetter*>(GetRequestContext())));
}
return resource_context_.get();
}
content::GeolocationPermissionContext*
CefBrowserContext::GetGeolocationPermissionContext() {
if (!geolocation_permission_context_) {
geolocation_permission_context_ =
new CefGeolocationPermissionContext();
}
return geolocation_permission_context_;
}
content::SpeechRecognitionPreferences*
CefBrowserContext::GetSpeechRecognitionPreferences() {
if (!speech_recognition_preferences_.get())
speech_recognition_preferences_ = new CefSpeechRecognitionPreferences();
return speech_recognition_preferences_.get();
}
quota::SpecialStoragePolicy* CefBrowserContext::GetSpecialStoragePolicy() {
return NULL;
}
bool CefBrowserContext::use_osr_next_contents_view() const {
return use_osr_next_contents_view_;
}
void CefBrowserContext::set_use_osr_next_contents_view(bool override) {
use_osr_next_contents_view_ = override;
}
<commit_msg>Fix assertion when returning NULL from CefClient::GetGeolocationHandler (issue #857).<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "libcef/browser/browser_context.h"
#include <map>
#include "libcef/browser/browser_host_impl.h"
#include "libcef/browser/context.h"
#include "libcef/browser/download_manager_delegate.h"
#include "libcef/browser/resource_context.h"
#include "libcef/browser/thread_util.h"
#include "libcef/browser/url_request_context_getter.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/threading/thread.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/geolocation_permission_context.h"
#include "content/public/browser/speech_recognition_preferences.h"
using content::BrowserThread;
namespace {
class CefGeolocationPermissionContext
: public content::GeolocationPermissionContext {
public:
// CefGeolocationCallback implementation.
class CallbackImpl : public CefGeolocationCallback {
public:
typedef base::Callback<void(bool)> // NOLINT(readability/function)
CallbackType;
explicit CallbackImpl(
CefGeolocationPermissionContext* context,
int bridge_id,
const CallbackType& callback)
: context_(context),
bridge_id_(bridge_id),
callback_(callback) {}
virtual void Continue(bool allow) OVERRIDE {
if (CEF_CURRENTLY_ON_IOT()) {
if (!callback_.is_null()) {
// Callback must be executed on the UI thread.
CEF_POST_TASK(CEF_UIT,
base::Bind(&CallbackImpl::Run, callback_, allow));
context_->RemoveCallback(bridge_id_);
}
} else {
CEF_POST_TASK(CEF_IOT,
base::Bind(&CallbackImpl::Continue, this, allow));
}
}
void Disconnect() {
callback_.Reset();
context_ = NULL;
}
private:
static void Run(const CallbackType& callback, bool allow) {
CEF_REQUIRE_UIT();
callback.Run(allow);
}
CefGeolocationPermissionContext* context_;
int bridge_id_;
CallbackType callback_;
IMPLEMENT_REFCOUNTING(CallbackImpl);
};
CefGeolocationPermissionContext() {}
virtual void RequestGeolocationPermission(
int render_process_id,
int render_view_id,
int bridge_id,
const GURL& requesting_frame,
base::Callback<void(bool)> callback) // NOLINT(readability/function)
OVERRIDE {
CEF_REQUIRE_IOT();
CefRefPtr<CefBrowserHostImpl> browser =
CefBrowserHostImpl::GetBrowserByRoutingID(render_process_id,
render_view_id);
if (browser.get()) {
CefRefPtr<CefClient> client = browser->GetClient();
if (client.get()) {
CefRefPtr<CefGeolocationHandler> handler =
client->GetGeolocationHandler();
if (handler.get()) {
CefRefPtr<CallbackImpl> callbackPtr(
new CallbackImpl(this, bridge_id, callback));
// Add the callback reference to the map.
callback_map_.insert(std::make_pair(bridge_id, callbackPtr));
// Notify the handler.
handler->OnRequestGeolocationPermission(browser.get(),
requesting_frame.spec(), bridge_id, callbackPtr.get());
return;
}
}
}
// Disallow geolocation access by default.
CEF_POST_TASK(CEF_UIT, base::Bind(callback, false));
}
virtual void CancelGeolocationPermissionRequest(
int render_process_id,
int render_view_id,
int bridge_id,
const GURL& requesting_frame) OVERRIDE {
RemoveCallback(bridge_id);
CefRefPtr<CefBrowserHostImpl> browser =
CefBrowserHostImpl::GetBrowserByRoutingID(render_process_id,
render_view_id);
if (browser.get()) {
CefRefPtr<CefClient> client = browser->GetClient();
if (client.get()) {
CefRefPtr<CefGeolocationHandler> handler =
client->GetGeolocationHandler();
if (handler.get()) {
// Notify the handler.
handler->OnCancelGeolocationPermission(browser.get(),
requesting_frame.spec(), bridge_id);
}
}
}
}
void RemoveCallback(int bridge_id) {
CEF_REQUIRE_IOT();
// Disconnect the callback and remove the reference from the map.
CallbackMap::iterator it = callback_map_.find(bridge_id);
if (it != callback_map_.end()) {
it->second->Disconnect();
callback_map_.erase(it);
}
}
private:
// Map of bridge ids to callback references.
typedef std::map<int, CefRefPtr<CallbackImpl> > CallbackMap;
CallbackMap callback_map_;
DISALLOW_COPY_AND_ASSIGN(CefGeolocationPermissionContext);
};
class CefSpeechRecognitionPreferences
: public content::SpeechRecognitionPreferences {
public:
CefSpeechRecognitionPreferences() {
}
// Overridden from SpeechRecognitionPreferences:
virtual bool FilterProfanities() const OVERRIDE {
return false;
}
private:
DISALLOW_COPY_AND_ASSIGN(CefSpeechRecognitionPreferences);
};
} // namespace
CefBrowserContext::CefBrowserContext()
: use_osr_next_contents_view_(false) {
// Initialize the request context getter.
url_request_getter_ = new CefURLRequestContextGetter(
false,
GetPath(),
BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::IO),
BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::FILE));
}
CefBrowserContext::~CefBrowserContext() {
// Delete the download manager delegate here because otherwise we'll crash
// when it's accessed from the content::BrowserContext destructor.
if (download_manager_delegate_.get())
download_manager_delegate_.reset(NULL);
if (resource_context_.get()) {
BrowserThread::DeleteSoon(
BrowserThread::IO, FROM_HERE, resource_context_.release());
}
}
FilePath CefBrowserContext::GetPath() {
return _Context->cache_path();
}
bool CefBrowserContext::IsOffTheRecord() const {
return false;
}
content::DownloadManagerDelegate*
CefBrowserContext::GetDownloadManagerDelegate() {
DCHECK(!download_manager_delegate_.get());
content::DownloadManager* manager = BrowserContext::GetDownloadManager(this);
download_manager_delegate_.reset(new CefDownloadManagerDelegate(manager));
return download_manager_delegate_.get();
}
net::URLRequestContextGetter* CefBrowserContext::GetRequestContext() {
return url_request_getter_;
}
net::URLRequestContextGetter*
CefBrowserContext::GetRequestContextForRenderProcess(
int renderer_child_id) {
CefRefPtr<CefBrowserHostImpl> browser =
CefBrowserHostImpl::GetBrowserByChildID(renderer_child_id);
if (browser.get())
return browser->GetRequestContext();
return GetRequestContext();
}
net::URLRequestContextGetter*
CefBrowserContext::GetMediaRequestContext() {
return GetRequestContext();
}
net::URLRequestContextGetter*
CefBrowserContext::GetMediaRequestContextForRenderProcess(
int renderer_child_id) {
return GetRequestContext();
}
net::URLRequestContextGetter*
CefBrowserContext::GetMediaRequestContextForStoragePartition(
const FilePath& partition_path,
bool in_memory) {
return GetRequestContext();
}
net::URLRequestContextGetter*
CefBrowserContext::GetRequestContextForStoragePartition(
const FilePath& partition_path,
bool in_memory) {
return NULL;
}
content::ResourceContext* CefBrowserContext::GetResourceContext() {
if (!resource_context_.get()) {
resource_context_.reset(new CefResourceContext(
static_cast<CefURLRequestContextGetter*>(GetRequestContext())));
}
return resource_context_.get();
}
content::GeolocationPermissionContext*
CefBrowserContext::GetGeolocationPermissionContext() {
if (!geolocation_permission_context_) {
geolocation_permission_context_ =
new CefGeolocationPermissionContext();
}
return geolocation_permission_context_;
}
content::SpeechRecognitionPreferences*
CefBrowserContext::GetSpeechRecognitionPreferences() {
if (!speech_recognition_preferences_.get())
speech_recognition_preferences_ = new CefSpeechRecognitionPreferences();
return speech_recognition_preferences_.get();
}
quota::SpecialStoragePolicy* CefBrowserContext::GetSpecialStoragePolicy() {
return NULL;
}
bool CefBrowserContext::use_osr_next_contents_view() const {
return use_osr_next_contents_view_;
}
void CefBrowserContext::set_use_osr_next_contents_view(bool override) {
use_osr_next_contents_view_ = override;
}
<|endoftext|> |
<commit_before>#include "memstorage.h"
#include "../utils/utils.h"
#include "../compression.h"
#include "../flags.h"
#include "subscribe.h"
#include "chunk.h"
#include "../timeutil.h"
#include "inner_readers.h"
#include <limits>
#include <algorithm>
#include <map>
#include <tuple>
#include <assert.h>
#include <mutex>
using namespace dariadb;
using namespace dariadb::compression;
using namespace dariadb::storage;
typedef std::map<Id, ChuncksList> ChunkMap;
class MemoryStorage::Private
{
public:
Private(size_t size) :
_size(size),
_min_time(std::numeric_limits<dariadb::Time>::max()),
_max_time(std::numeric_limits<dariadb::Time>::min()),
_subscribe_notify(new SubscribeNotificator)
{
_subscribe_notify->start();
}
~Private() {
_subscribe_notify->stop();
_chuncks.clear();
}
Time minTime() { return _min_time; }
Time maxTime() { return _max_time; }
Chunk_Ptr getFreeChunk(dariadb::Id id) {
Chunk_Ptr resulted_chunk = nullptr;
auto ch_iter = _free_chunks.find(id);
if (ch_iter != _free_chunks.end()) {
if (!ch_iter->second->is_full()) {
return ch_iter->second;
}
}
return resulted_chunk;
}
Chunk_Ptr make_chunk(dariadb::Meas first) {
auto ptr = new Chunk(_size, first);
auto chunk = Chunk_Ptr{ ptr };
this->_chuncks[first.id].push_back(chunk);
this->_free_chunks[first.id] = chunk;
return chunk;
}
append_result append(const Meas& value) {
std::lock_guard<std::mutex> lg(_mutex);
Chunk_Ptr chunk = this->getFreeChunk(value.id);
if (chunk == nullptr) {
chunk=make_chunk(value);
}
else {
//std::cout<<"append new "<<chunk->count<< " chunks: "<<this->chunks_total_size()<<std::endl;
if (!chunk->append(value)) {
assert(chunk->is_full());
chunk = make_chunk(value);
}
}
assert(chunk->last.time == value.time);
_min_time = std::min(_min_time, value.time);
_max_time = std::max(_max_time, value.time);
_subscribe_notify->on_append(value);
return dariadb::append_result(1, 0);
}
append_result append(const Meas::PMeas begin, const size_t size) {
dariadb::append_result result{};
for (size_t i = 0; i < size; i++) {
result = result + append(begin[i]);
}
return result;
}
size_t size()const { return _size; }
size_t chunks_size()const { return _chuncks.size(); }
size_t chunks_total_size()const {
size_t result = 0;
for (auto kv : _chuncks) {
result += kv.second.size();
}
return result;
}
void subscribe(const IdArray&ids, const Flag& flag, const ReaderClb_ptr &clbk) {
auto new_s = std::make_shared<SubscribeInfo>(ids, flag, clbk);
_subscribe_notify->add(new_s);
}
Reader_ptr currentValue(const IdArray&ids, const Flag& flag) {
std::lock_guard<std::mutex> lg(_mutex_tp);
auto res_raw = new InnerCurrentValuesReader();
Reader_ptr res{ res_raw };
for (auto &kv : _free_chunks) {
auto l = kv.second->last;
if ((ids.size() != 0) && (std::find(ids.begin(), ids.end(), l.id) == ids.end())) {
continue;
}
if ((flag == 0) || (l.flag == flag)) {
res_raw->_cur_values.push_back(l);
}
}
return res;
}
dariadb::storage::ChuncksList drop_old_chunks(const dariadb::Time min_time) {
std::lock_guard<std::mutex> lg(_mutex_tp);
ChuncksList result;
auto now = dariadb::timeutil::current_time();
for (auto& kv : _chuncks) {
while ((kv.second.size() > 0)) {
auto past = (now - min_time);
if ((kv.second.front()->maxTime < past)&&(kv.second.front()->is_full())) {
auto chunk = kv.second.front();
result.push_back(chunk);
kv.second.pop_front();
if (this->_free_chunks[kv.first] == chunk) {
this->_free_chunks.erase(kv.first);
}
}else {
break;
}
}
}
//update min max
update_max_min_after_drop();
return result;
}
//by memory limit
ChuncksList drop_old_chunks_by_limit(const size_t max_limit) {
std::lock_guard<std::mutex> lg(_mutex_tp);
ChuncksList result{};
if(chunks_total_size()>max_limit) {
while ((chunks_total_size() > (max_limit-size_t(max_limit/3)))){
for (auto& kv : _chuncks) {
if ((kv.second.size() > 1)) {
dariadb::storage::Chunk_Ptr chunk = kv.second.front();
if (chunk->is_full()) {
result.push_back(chunk);
kv.second.pop_front();
}
}
}
}
assert(result.size() > size_t(0));
//update min max
update_max_min_after_drop();
}
return result;
}
void update_max_min_after_drop() {
this->_min_time = std::numeric_limits<dariadb::Time>::max();
this->_max_time = std::numeric_limits<dariadb::Time>::min();
for (auto& kv : _chuncks) {
for (auto &c : kv.second) {
_min_time = std::min(c->minTime, _min_time);
_max_time = std::max(c->maxTime, _max_time);
}
}
}
dariadb::storage::ChuncksList drop_all() {
std::lock_guard<std::mutex> lg(_mutex_tp);
ChuncksList result;
for (auto& kv : _chuncks) {
for (auto chunk : kv.second) {
result.push_back(chunk);
}
}
this->_free_chunks.clear();
this->_chuncks.clear();
//update min max
this->_min_time = std::numeric_limits<dariadb::Time>::max();
this->_max_time = std::numeric_limits<dariadb::Time>::min();
return result;
}
ChuncksList chunksByIterval(const IdArray &ids, Flag flag, Time from, Time to) {
ChuncksList result{};
for (auto ch : _chuncks) {
if ((ids.size() != 0) && (std::find(ids.begin(), ids.end(), ch.first) == ids.end())) {
continue;
}
for (auto &cur_chunk : ch.second) {
if (flag != 0) {
if (!cur_chunk->check_flag(flag)) {
continue;
}
}
if ((utils::inInterval(from, to, cur_chunk->minTime)) || (utils::inInterval(from, to, cur_chunk->maxTime))) {
result.push_back(cur_chunk);
}
}
}
return result;
}
IdToChunkMap chunksBeforeTimePoint(const IdArray &ids, Flag flag, Time timePoint) {
IdToChunkMap result;
for (auto ch : _chuncks) {
if ((ids.size() != 0) && (std::find(ids.begin(), ids.end(), ch.first) == ids.end())) {
continue;
}
auto chunks = &ch.second;
for (auto it = chunks->rbegin(); it != chunks->crend(); ++it) {
auto cur_chunk = *it;
if (!cur_chunk->check_flag(flag)) {
continue;
}
if (cur_chunk->minTime <= timePoint) {
result[ch.first] = cur_chunk;
break;
}
}
}
return result;
}
dariadb::IdArray getIds()const {
dariadb::IdArray result;
result.resize(_chuncks.size());
size_t pos = 0;
for (auto&kv : _chuncks) {
result[pos] = kv.first;
pos++;
}
return result;
}
void add_chunks(const ChuncksList&clist) {
for (auto c : clist) {
_chuncks[c->first.id].push_back(c);
auto search_res = _free_chunks.find(c->first.id);
if (search_res == _free_chunks.end()) {
_free_chunks[c->first.id] = c;
}
else {
assert(false);
}
}
}
protected:
size_t _size;
ChunkMap _chuncks;
IdToChunkMap _free_chunks;
Time _min_time, _max_time;
std::unique_ptr<SubscribeNotificator> _subscribe_notify;
std::mutex _mutex;
std::mutex _mutex_tp;
};
MemoryStorage::MemoryStorage(size_t size)
:_Impl(new MemoryStorage::Private(size)) {
}
MemoryStorage::~MemoryStorage() {
}
Time MemoryStorage::minTime() {
return _Impl->minTime();
}
Time MemoryStorage::maxTime() {
return _Impl->maxTime();
}
append_result MemoryStorage::append(const dariadb::Meas &value) {
return _Impl->append(value);
}
append_result MemoryStorage::append(const dariadb::Meas::PMeas begin, const size_t size) {
return _Impl->append(begin, size);
}
size_t MemoryStorage::size()const {
return _Impl->size();
}
size_t MemoryStorage::chunks_size()const {
return _Impl->chunks_size();
}
size_t MemoryStorage::chunks_total_size()const {
return _Impl->chunks_total_size();
}
void MemoryStorage::subscribe(const IdArray&ids, const Flag& flag, const ReaderClb_ptr &clbk) {
return _Impl->subscribe(ids, flag, clbk);
}
Reader_ptr MemoryStorage::currentValue(const IdArray&ids, const Flag& flag) {
return _Impl->currentValue(ids, flag);
}
void MemoryStorage::flush()
{
}
dariadb::storage::ChuncksList MemoryStorage::drop_old_chunks(const dariadb::Time min_time){
return _Impl->drop_old_chunks(min_time);
}
dariadb::storage::ChuncksList MemoryStorage::drop_old_chunks_by_limit(const size_t max_limit) {
return _Impl->drop_old_chunks_by_limit(max_limit);
}
dariadb::storage::ChuncksList MemoryStorage::drop_all()
{
return _Impl->drop_all();
}
ChuncksList MemoryStorage::chunksByIterval(const IdArray &ids, Flag flag, Time from, Time to) {
return _Impl->chunksByIterval(ids, flag, from, to);
}
IdToChunkMap MemoryStorage::chunksBeforeTimePoint(const IdArray &ids, Flag flag, Time timePoint) {
return _Impl->chunksBeforeTimePoint(ids, flag, timePoint);
}
dariadb::IdArray MemoryStorage::getIds()const {
return _Impl->getIds();
}
void MemoryStorage::add_chunks(const ChuncksList&clist) {
return _Impl->add_chunks(clist);
}
<commit_msg>memstorage: new lock model.<commit_after>#include "memstorage.h"
#include "../utils/utils.h"
#include "../compression.h"
#include "../flags.h"
#include "subscribe.h"
#include "chunk.h"
#include "../timeutil.h"
#include "inner_readers.h"
#include <limits>
#include <algorithm>
#include <map>
#include <tuple>
#include <assert.h>
#include <mutex>
using namespace dariadb;
using namespace dariadb::compression;
using namespace dariadb::storage;
typedef std::map<Id, ChuncksList> ChunkMap;
class MemoryStorage::Private
{
public:
Private(size_t size) :
_size(size),
_min_time(std::numeric_limits<dariadb::Time>::max()),
_max_time(std::numeric_limits<dariadb::Time>::min()),
_subscribe_notify(new SubscribeNotificator)
{
_subscribe_notify->start();
}
~Private() {
_subscribe_notify->stop();
_chuncks.clear();
}
Time minTime() { return _min_time; }
Time maxTime() { return _max_time; }
Chunk_Ptr getFreeChunk(dariadb::Id id) {
Chunk_Ptr resulted_chunk = nullptr;
auto ch_iter = _free_chunks.find(id);
if (ch_iter != _free_chunks.end()) {
if (!ch_iter->second->is_full()) {
return ch_iter->second;
}
}
return resulted_chunk;
}
Chunk_Ptr make_chunk(dariadb::Meas first) {
auto ptr = new Chunk(_size, first);
auto chunk = Chunk_Ptr{ ptr };
this->_chuncks[first.id].push_back(chunk);
this->_free_chunks[first.id] = chunk;
return chunk;
}
append_result append(const Meas& value) {
std::lock_guard<std::mutex> lg(_mutex);
Chunk_Ptr chunk = this->getFreeChunk(value.id);
if (chunk == nullptr) {
chunk=make_chunk(value);
}
else {
//std::cout<<"append new "<<chunk->count<< " chunks: "<<this->chunks_total_size()<<std::endl;
if (!chunk->append(value)) {
assert(chunk->is_full());
chunk = make_chunk(value);
}
}
assert(chunk->last.time == value.time);
_min_time = std::min(_min_time, value.time);
_max_time = std::max(_max_time, value.time);
_subscribe_notify->on_append(value);
return dariadb::append_result(1, 0);
}
append_result append(const Meas::PMeas begin, const size_t size) {
dariadb::append_result result{};
for (size_t i = 0; i < size; i++) {
result = result + append(begin[i]);
}
return result;
}
size_t size()const { return _size; }
size_t chunks_size()const { return _chuncks.size(); }
size_t chunks_total_size()const {
size_t result = 0;
for (auto kv : _chuncks) {
result += kv.second.size();
}
return result;
}
void subscribe(const IdArray&ids, const Flag& flag, const ReaderClb_ptr &clbk) {
auto new_s = std::make_shared<SubscribeInfo>(ids, flag, clbk);
_subscribe_notify->add(new_s);
}
Reader_ptr currentValue(const IdArray&ids, const Flag& flag) {
std::lock_guard<std::mutex> lg(_mutex);
auto res_raw = new InnerCurrentValuesReader();
Reader_ptr res{ res_raw };
for (auto &kv : _free_chunks) {
auto l = kv.second->last;
if ((ids.size() != 0) && (std::find(ids.begin(), ids.end(), l.id) == ids.end())) {
continue;
}
if ((flag == 0) || (l.flag == flag)) {
res_raw->_cur_values.push_back(l);
}
}
return res;
}
dariadb::storage::ChuncksList drop_old_chunks(const dariadb::Time min_time) {
std::lock_guard<std::mutex> lg(_mutex_drop);
ChuncksList result;
auto now = dariadb::timeutil::current_time();
for (auto& kv : _chuncks) {
while ((kv.second.size() > 0)) {
auto past = (now - min_time);
if ((kv.second.front()->maxTime < past)&&(kv.second.front()->is_full())) {
auto chunk = kv.second.front();
result.push_back(chunk);
kv.second.pop_front();
if (this->_free_chunks[kv.first] == chunk) {
this->_free_chunks.erase(kv.first);
}
}else {
break;
}
}
}
//update min max
update_max_min_after_drop();
return result;
}
//by memory limit
ChuncksList drop_old_chunks_by_limit(const size_t max_limit) {
ChuncksList result{};
if(chunks_total_size()>max_limit) {
std::lock_guard<std::mutex> lg(_mutex_drop);
while ((chunks_total_size() > (max_limit-size_t(max_limit/3)))){
for (auto& kv : _chuncks) {
if ((kv.second.size() > 1)) {
dariadb::storage::Chunk_Ptr chunk = kv.second.front();
if (chunk->is_full()) {
// _mutex.lock();
result.push_back(chunk);
kv.second.pop_front();
// _mutex.unlock();
}
}
if((chunks_total_size() <= (max_limit-size_t(max_limit/3)))){
break;
}
}
}
assert(result.size() > size_t(0));
//update min max
update_max_min_after_drop();
}
return result;
}
void update_max_min_after_drop() {
this->_min_time = std::numeric_limits<dariadb::Time>::max();
this->_max_time = std::numeric_limits<dariadb::Time>::min();
for (auto& kv : _chuncks) {
for (auto &c : kv.second) {
_min_time = std::min(c->minTime, _min_time);
_max_time = std::max(c->maxTime, _max_time);
}
}
}
dariadb::storage::ChuncksList drop_all() {
std::lock_guard<std::mutex> lg(_mutex_drop);
ChuncksList result;
for (auto& kv : _chuncks) {
for (auto chunk : kv.second) {
result.push_back(chunk);
}
}
this->_free_chunks.clear();
this->_chuncks.clear();
//update min max
this->_min_time = std::numeric_limits<dariadb::Time>::max();
this->_max_time = std::numeric_limits<dariadb::Time>::min();
return result;
}
ChuncksList chunksByIterval(const IdArray &ids, Flag flag, Time from, Time to) {
ChuncksList result{};
for (auto ch : _chuncks) {
if ((ids.size() != 0) && (std::find(ids.begin(), ids.end(), ch.first) == ids.end())) {
continue;
}
for (auto &cur_chunk : ch.second) {
if (flag != 0) {
if (!cur_chunk->check_flag(flag)) {
continue;
}
}
if ((utils::inInterval(from, to, cur_chunk->minTime)) || (utils::inInterval(from, to, cur_chunk->maxTime))) {
result.push_back(cur_chunk);
}
}
}
return result;
}
IdToChunkMap chunksBeforeTimePoint(const IdArray &ids, Flag flag, Time timePoint) {
IdToChunkMap result;
for (auto ch : _chuncks) {
if ((ids.size() != 0) && (std::find(ids.begin(), ids.end(), ch.first) == ids.end())) {
continue;
}
auto chunks = &ch.second;
for (auto it = chunks->rbegin(); it != chunks->crend(); ++it) {
auto cur_chunk = *it;
if (!cur_chunk->check_flag(flag)) {
continue;
}
if (cur_chunk->minTime <= timePoint) {
result[ch.first] = cur_chunk;
break;
}
}
}
return result;
}
dariadb::IdArray getIds()const {
dariadb::IdArray result;
result.resize(_chuncks.size());
size_t pos = 0;
for (auto&kv : _chuncks) {
result[pos] = kv.first;
pos++;
}
return result;
}
void add_chunks(const ChuncksList&clist) {
for (auto c : clist) {
_chuncks[c->first.id].push_back(c);
auto search_res = _free_chunks.find(c->first.id);
if (search_res == _free_chunks.end()) {
_free_chunks[c->first.id] = c;
}
else {
assert(false);
}
}
}
protected:
size_t _size;
ChunkMap _chuncks;
IdToChunkMap _free_chunks;
Time _min_time, _max_time;
std::unique_ptr<SubscribeNotificator> _subscribe_notify;
std::mutex _mutex;
std::mutex _mutex_drop;
};
MemoryStorage::MemoryStorage(size_t size)
:_Impl(new MemoryStorage::Private(size)) {
}
MemoryStorage::~MemoryStorage() {
}
Time MemoryStorage::minTime() {
return _Impl->minTime();
}
Time MemoryStorage::maxTime() {
return _Impl->maxTime();
}
append_result MemoryStorage::append(const dariadb::Meas &value) {
return _Impl->append(value);
}
append_result MemoryStorage::append(const dariadb::Meas::PMeas begin, const size_t size) {
return _Impl->append(begin, size);
}
size_t MemoryStorage::size()const {
return _Impl->size();
}
size_t MemoryStorage::chunks_size()const {
return _Impl->chunks_size();
}
size_t MemoryStorage::chunks_total_size()const {
return _Impl->chunks_total_size();
}
void MemoryStorage::subscribe(const IdArray&ids, const Flag& flag, const ReaderClb_ptr &clbk) {
return _Impl->subscribe(ids, flag, clbk);
}
Reader_ptr MemoryStorage::currentValue(const IdArray&ids, const Flag& flag) {
return _Impl->currentValue(ids, flag);
}
void MemoryStorage::flush()
{
}
dariadb::storage::ChuncksList MemoryStorage::drop_old_chunks(const dariadb::Time min_time){
return _Impl->drop_old_chunks(min_time);
}
dariadb::storage::ChuncksList MemoryStorage::drop_old_chunks_by_limit(const size_t max_limit) {
return _Impl->drop_old_chunks_by_limit(max_limit);
}
dariadb::storage::ChuncksList MemoryStorage::drop_all()
{
return _Impl->drop_all();
}
ChuncksList MemoryStorage::chunksByIterval(const IdArray &ids, Flag flag, Time from, Time to) {
return _Impl->chunksByIterval(ids, flag, from, to);
}
IdToChunkMap MemoryStorage::chunksBeforeTimePoint(const IdArray &ids, Flag flag, Time timePoint) {
return _Impl->chunksBeforeTimePoint(ids, flag, timePoint);
}
dariadb::IdArray MemoryStorage::getIds()const {
return _Impl->getIds();
}
void MemoryStorage::add_chunks(const ChuncksList&clist) {
return _Impl->add_chunks(clist);
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* baseConvert.c++
*****************************************************************************
* Unit tests for the baseConvert() functions.
*****************************************************************************/
// Standard includes.
#include <string>
#include <iostream>
#include <limits>
#include <vector>
// Internal includes.
#include "demangle.h++"
#include "to_string.h++"
#include "build_edges.h++"
// Testing include.
#include "baseConvert.h++"
// Bring in namespaces.
using namespace std;
using namespace DAC;
/*****************************************************************************/
// Declarations.
// Run test suite on a given type.
template <class T> int test ();
/*****************************************************************************/
// Definitions.
/*
* Run test suite on a given type.
*/
template <class T> int test () {
{
string tmpstr;
cout << "Testing type " << demangle<T>(tmpstr) << "..." << endl;
}
vector<T> edges;
build_edges(edges);
for (vector<T>::const_iterator frombase
// All tests passed.
return 0;
}
/*
* This is it.
*/
int main () {
// Test types.
if (test<bool >()) { return 1; }
if (test<char >()) { return 1; }
if (test<signed char >()) { return 1; }
if (test<unsigned char >()) { return 1; }
if (test<wchar_t >()) { return 1; }
if (test<short >()) { return 1; }
if (test<unsigned short>()) { return 1; }
if (test<int >()) { return 1; }
if (test<unsigned int >()) { return 1; }
if (test<long >()) { return 1; }
if (test<unsigned long >()) { return 1; }
// All tests passed.
return 0;
}
<commit_msg>Forgot one.<commit_after>/*****************************************************************************
* baseConvert.c++
*****************************************************************************
* Unit tests for the baseConvert() functions.
*****************************************************************************/
// Standard includes.
#include <string>
#include <iostream>
#include <limits>
#include <vector>
// Internal includes.
#include "demangle.h++"
#include "to_string.h++"
#include "testcommon.h++"
// Testing include.
#include "baseConvert.h++"
// Bring in namespaces.
using namespace std;
using namespace DAC;
/*****************************************************************************/
// Declarations.
// Run test suite on a given type.
template <class T> int test ();
/*****************************************************************************/
// Definitions.
/*
* Run test suite on a given type.
*/
template <class T> int test () {
{
string tmpstr;
cout << "Testing type " << demangle<T>(tmpstr) << "..." << endl;
}
vector<T> edges;
build_edges(edges);
for (vector<T>::const_iterator frombase
// All tests passed.
return 0;
}
/*
* This is it.
*/
int main () {
// Test types.
if (test<bool >()) { return 1; }
if (test<char >()) { return 1; }
if (test<signed char >()) { return 1; }
if (test<unsigned char >()) { return 1; }
if (test<wchar_t >()) { return 1; }
if (test<short >()) { return 1; }
if (test<unsigned short>()) { return 1; }
if (test<int >()) { return 1; }
if (test<unsigned int >()) { return 1; }
if (test<long >()) { return 1; }
if (test<unsigned long >()) { return 1; }
// All tests passed.
return 0;
}
<|endoftext|> |
<commit_before>#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
#include <nvs_flash.h>
#include "Motors_Controller.h"
#include "MPU9250.h"
#include "MPU6050.h"
#include "Mahony_Filter.h"
#include "Complementary_Filter.h"
#include "WiFi_Controller.h"
#include "CRC.h"
#include "LEDs.h"
using namespace flyhero;
Motors_Controller& motors_controller = Motors_Controller::Instance();
QueueHandle_t euler_queue;
void wifi_task(void *args);
void imu_task(void *args);
void wifi_parser(uint8_t *buffer, uint8_t received_length);
extern "C" void app_main(void) {
// Initialize NVS
esp_err_t nvs_status = nvs_flash_init();
if (nvs_status == ESP_ERR_NVS_NO_FREE_PAGES) {
ESP_ERROR_CHECK(nvs_flash_erase());
nvs_status = nvs_flash_init();
}
ESP_ERROR_CHECK(nvs_status);
LEDs::Init();
euler_queue = xQueueCreate(20, sizeof(IMU::Euler_Angles));
xTaskCreatePinnedToCore(wifi_task, "WiFi task", 4096, NULL, 2, NULL, 0);
xTaskCreatePinnedToCore(imu_task, "IMU task", 4096, NULL, 2, NULL, 1);
while (true);
}
void imu_task(void *args) {
IMU::Sensor_Data accel, gyro;
IMU::Euler_Angles euler;
//MPU9250& mpu = MPU9250::Instance();
MPU6050& mpu = MPU6050::Instance();
//Mahony_Filter mahony(2, 0.1f, 1000);
Complementary_Filter complementary(0.995f, 1000);
motors_controller.Init();
mpu.Init();
uint8_t i = 0;
while (true) {
if (mpu.Data_Ready()) {
mpu.Read_Data(accel, gyro);
//mahony.Compute(accel, gyro, euler);
complementary.Compute(accel, gyro, euler);
i++;
if (i == 100) {
xQueueSend(euler_queue, &euler, 0);
i = 0;
}
motors_controller.Update_Motors(euler);
}
}
}
void wifi_task(void *args) {
const uint8_t BUFFER_SIZE = 200;
WiFi_Controller& wifi = WiFi_Controller::Instance();
uint8_t buffer[BUFFER_SIZE];
uint8_t received_length;
IMU::Euler_Angles euler;
wifi.Init();
while (true) {
if (wifi.Receive(buffer, BUFFER_SIZE, received_length)) {
// wrong length
if (buffer[0] != received_length)
continue;
uint16_t crc;
crc = buffer[received_length - 1] << 8;
crc |= buffer[received_length - 2];
// wrong crc
if (crc != CRC::CRC16(buffer, received_length - 2))
continue;
wifi_parser(buffer, received_length);
}
if (xQueueReceive(euler_queue, &euler, 0) == pdTRUE) {
uint8_t *roll, *pitch, *yaw;
roll = (uint8_t*)&euler.roll;
pitch = (uint8_t*)&euler.pitch;
yaw = (uint8_t*)&euler.yaw;
uint8_t data[16];
data[0] = 16;
data[1] = 0x00;
data[2] = roll[3];
data[3] = roll[2];
data[4] = roll[1];
data[5] = roll[0];
data[6] = pitch[3];
data[7] = pitch[2];
data[8] = pitch[1];
data[9] = pitch[0];
data[10] = yaw[3];
data[11] = yaw[2];
data[12] = yaw[1];
data[13] = yaw[0];
uint16_t crc = CRC::CRC16(data, 14);
data[14] = crc & 0xFF;
data[15] = crc >> 8;
wifi.Send(data, 16);
}
}
}
void wifi_parser(uint8_t *buffer, uint8_t received_length) {
switch (buffer[1]) {
case 0x00:
uint16_t throttle;
throttle = buffer[3] << 8;
throttle |= buffer[2];
//std::cout << "t: " << throttle << std::endl;
motors_controller.Set_Throttle(throttle);
motors_controller.Set_PID_Constants(Roll, 1, 0, 0);
motors_controller.Set_PID_Constants(Pitch, 1, 0, 0);
break;
}
}
<commit_msg>(The Eye): implement logging multiple sets of euler data<commit_after>#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
#include <nvs_flash.h>
#include "Motors_Controller.h"
#include "MPU9250.h"
#include "MPU6050.h"
#include "Mahony_Filter.h"
#include "Complementary_Filter.h"
#include "WiFi_Controller.h"
#include "CRC.h"
#include "LEDs.h"
using namespace flyhero;
Motors_Controller& motors_controller = Motors_Controller::Instance();
QueueHandle_t euler_queue;
void wifi_task(void *args);
void imu_task(void *args);
void wifi_parser(uint8_t *buffer, uint8_t received_length);
const uint8_t FUSION_ALGORITHMS_USED = 2;
extern "C" void app_main(void) {
// Initialize NVS
esp_err_t nvs_status = nvs_flash_init();
if (nvs_status == ESP_ERR_NVS_NO_FREE_PAGES) {
ESP_ERROR_CHECK(nvs_flash_erase());
nvs_status = nvs_flash_init();
}
ESP_ERROR_CHECK(nvs_status);
LEDs::Init();
euler_queue = xQueueCreate(20, sizeof(IMU::Euler_Angles[FUSION_ALGORITHMS_USED]));
xTaskCreatePinnedToCore(wifi_task, "WiFi task", 4096, NULL, 2, NULL, 0);
xTaskCreatePinnedToCore(imu_task, "IMU task", 4096, NULL, 2, NULL, 1);
while (true);
}
void imu_task(void *args) {
IMU::Sensor_Data accel, gyro;
IMU::Euler_Angles mahony_euler, complementary_euler;
//MPU9250& mpu = MPU9250::Instance();
MPU6050& mpu = MPU6050::Instance();
Mahony_Filter mahony(2, 0.1f, 1000);
Complementary_Filter complementary(0.995f, 1000);
motors_controller.Init();
mpu.Init();
IMU::Euler_Angles queue_data[FUSION_ALGORITHMS_USED];
uint8_t i = 0;
while (true) {
if (mpu.Data_Ready()) {
mpu.Read_Data(accel, gyro);
mahony.Compute(accel, gyro, mahony_euler);
complementary.Compute(accel, gyro, complementary_euler);
i++;
if (i == 100) {
queue_data[0] = mahony_euler;
queue_data[1] = complementary_euler;
xQueueSend(euler_queue, &queue_data, 0);
i = 0;
}
motors_controller.Update_Motors(mahony_euler);
}
}
}
void wifi_task(void *args) {
const uint8_t BUFFER_SIZE = 200;
WiFi_Controller& wifi = WiFi_Controller::Instance();
uint8_t buffer[BUFFER_SIZE];
uint8_t received_length;
IMU::Euler_Angles euler[FUSION_ALGORITHMS_USED];
wifi.Init();
while (true) {
if (wifi.Receive(buffer, BUFFER_SIZE, received_length)) {
// wrong length
if (buffer[0] != received_length)
continue;
uint16_t crc;
crc = buffer[received_length - 1] << 8;
crc |= buffer[received_length - 2];
// wrong crc
if (crc != CRC::CRC16(buffer, received_length - 2))
continue;
wifi_parser(buffer, received_length);
}
if (xQueueReceive(euler_queue, &euler, 0) == pdTRUE) {
uint8_t *roll, *pitch, *yaw;
// 1 (data size) + 1 (datagram type) + 12 * #_fusion_algorithms_used + 2 (crc)
const uint8_t DATA_SIZE = 4 + 12 * FUSION_ALGORITHMS_USED;
uint8_t data[DATA_SIZE];
data[0] = DATA_SIZE;
data[1] = 0x00;
for (uint8_t i = 0; i < FUSION_ALGORITHMS_USED; i++) {
roll = (uint8_t *) &(euler[i].roll);
pitch = (uint8_t *) &(euler[i].pitch);
yaw = (uint8_t *) &(euler[i].yaw);
data[2 + i * 12] = roll[3];
data[3 + i * 12] = roll[2];
data[4 + i * 12] = roll[1];
data[5 + i * 12] = roll[0];
data[6 + i * 12] = pitch[3];
data[7 + i * 12] = pitch[2];
data[8 + i * 12] = pitch[1];
data[9 + i * 12] = pitch[0];
data[10 + i * 12] = yaw[3];
data[11 + i * 12] = yaw[2];
data[12 + i * 12] = yaw[1];
data[13 + i * 12] = yaw[0];
}
uint16_t crc = CRC::CRC16(data, DATA_SIZE - 2);
data[DATA_SIZE - 2] = crc & 0xFF;
data[DATA_SIZE - 1] = crc >> 8;
wifi.Send(data, DATA_SIZE);
}
}
}
void wifi_parser(uint8_t *buffer, uint8_t received_length) {
switch (buffer[1]) {
case 0x00:
uint16_t throttle;
throttle = buffer[3] << 8;
throttle |= buffer[2];
//std::cout << "t: " << throttle << std::endl;
motors_controller.Set_Throttle(throttle);
motors_controller.Set_PID_Constants(Roll, 1, 0, 0);
motors_controller.Set_PID_Constants(Pitch, 1, 0, 0);
break;
}
}
<|endoftext|> |
<commit_before>#include "_global.h"
void* RtlAllocateMemory(bool InZeroMemory, SIZE_T InSize)
{
void* Result = ExAllocatePoolWithTag(NonPagedPool, InSize, 'HIDE');
if(InZeroMemory && (Result != NULL))
RtlZeroMemory(Result, InSize);
return Result;
}
void RtlFreeMemory(void* InPointer)
{
ExFreePool(InPointer);
}
//Based on: http://leguanyuan.blogspot.nl/2013/09/x64-inline-hook-zwcreatesection.html
NTSTATUS RtlSuperCopyMemory(IN VOID UNALIGNED* Destination, IN CONST VOID UNALIGNED* Source, IN ULONG Length)
{
//Change memory properties.
PMDL g_pmdl = IoAllocateMdl(Destination, Length, 0, 0, NULL);
if(!g_pmdl)
return STATUS_UNSUCCESSFUL;
MmBuildMdlForNonPagedPool(g_pmdl);
unsigned int* Mapped = (unsigned int*)MmMapLockedPages(g_pmdl, KernelMode);
if(!Mapped)
{
IoFreeMdl(g_pmdl);
return STATUS_UNSUCCESSFUL;
}
KIRQL kirql = KeRaiseIrqlToDpcLevel();
RtlCopyMemory(Mapped, Source, Length);
KeLowerIrql(kirql);
//Restore memory properties.
MmUnmapLockedPages((PVOID)Mapped, g_pmdl);
IoFreeMdl(g_pmdl);
return STATUS_SUCCESS;
}<commit_msg>Rewrite RtlSuperCopyMemory<commit_after>#include "_global.h"
void* RtlAllocateMemory(bool InZeroMemory, SIZE_T InSize)
{
void* Result = ExAllocatePoolWithTag(NonPagedPool, InSize, 'HIDE');
if(InZeroMemory && (Result != NULL))
RtlZeroMemory(Result, InSize);
return Result;
}
void RtlFreeMemory(void* InPointer)
{
ExFreePool(InPointer);
}
NTSTATUS RtlSuperCopyMemory(IN VOID UNALIGNED* Destination, IN CONST VOID UNALIGNED* Source, IN ULONG Length)
{
const KIRQL Irql = KeRaiseIrqlToDpcLevel();
PMDL Mdl = IoAllocateMdl(Destination, Length, 0, 0, nullptr);
if(Mdl == nullptr)
{
KeLowerIrql(Irql);
return STATUS_NO_MEMORY;
}
MmBuildMdlForNonPagedPool(Mdl);
// Hack: prevent bugcheck from Driver Verifier and possible future versions of Windows
#pragma prefast(push)
#pragma prefast(disable:__WARNING_MODIFYING_MDL, "Trust me I'm a scientist")
const CSHORT OriginalMdlFlags = Mdl->MdlFlags;
Mdl->MdlFlags |= MDL_PAGES_LOCKED;
Mdl->MdlFlags &= ~MDL_SOURCE_IS_NONPAGED_POOL;
// Map pages and do the copy
const PVOID Mapped = MmMapLockedPagesSpecifyCache(Mdl, KernelMode, MmCached, nullptr, FALSE, HighPagePriority);
if(Mapped == nullptr)
{
Mdl->MdlFlags = OriginalMdlFlags;
IoFreeMdl(Mdl);
KeLowerIrql(Irql);
return STATUS_NONE_MAPPED;
}
RtlCopyMemory(Mapped, Source, Length);
MmUnmapLockedPages(Mapped, Mdl);
Mdl->MdlFlags = OriginalMdlFlags;
#pragma prefast(pop)
IoFreeMdl(Mdl);
KeLowerIrql(Irql);
return STATUS_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "BoardMarker.hpp"
BoardMarker::BoardMarker (void) : m(NONE), c(' ') {}
bool BoardMarker::apply_modifier(Modifier& m) {
if (this->m != NONE) {
return false;
}
this->m = m;
return true;
}
bool BoardMarker::set_char(char& c) {
if (this->c != ' ') {
return false;
}
this->c = toupper(c);
return true;
}
void BoardMarker::print_marker(void) {
string pre = " ";
string col = "";
string post = " ";
if (this->m != NONE) {
pre = " \033[";
post = "\033[0m ";
switch (this->m) {
case DOUBLE_L:
col = "1;43;37m";
break;
case DOUBLE_W:
col = "1;42;37m";
break;
case TRIPLE_L:
col = "1;44;37m";
break;
case TRIPLE_W:
col = "1;41;37m";
break;
case NONE:
cout << "Shouldn't reach this line!" << endl;
}
}
cout << pre << col << this->c << post;
}
<commit_msg>Allow set_char when char is the same - updating words<commit_after>#include "BoardMarker.hpp"
BoardMarker::BoardMarker (void) : m(NONE), c(' ') {}
bool BoardMarker::apply_modifier(Modifier& m) {
if (this->m != NONE) {
return false;
}
this->m = m;
return true;
}
bool BoardMarker::set_char(char& c) {
if (this->c != ' ') {
return this->c == c;
}
this->c = toupper(c);
return true;
}
void BoardMarker::print_marker(void) {
string pre = " ";
string col = "";
string post = " ";
if (this->m != NONE) {
pre = " \033[";
post = "\033[0m ";
switch (this->m) {
case DOUBLE_L:
col = "1;43;37m";
break;
case DOUBLE_W:
col = "1;42;37m";
break;
case TRIPLE_L:
col = "1;44;37m";
break;
case TRIPLE_W:
col = "1;41;37m";
break;
case NONE:
cout << "Shouldn't reach this line!" << endl;
}
}
cout << pre << col << this->c << post;
}
<|endoftext|> |
<commit_before>/*"name": "sensorflare",
Author: "LPFraile <lidiapf0@gmail.com>",
License: "BSD",
Version: "0.0.1",
Description: "Include your Particle Core on Sensorflare"
File: Example: Control trough your Sensorflare account the PWM outputs on your Particle Core
*/
//Include the SensorFlare library
#include "sensorflare/sensorflare.h"
//Initialize objects from the library
//One object of the class "PWMOut" is initialized for
//every PWM output that will be remote control
SensorFlare::PWMOut pwm(A0);
void setup() {
// Call the begin() functions for every object of the classes "DigitalOut" and
//"PWMout" to be wired up correct and available.
pwm.begin();
}
void loop() {
}
<commit_msg>Update sensorflare-pwm.cpp<commit_after>/*"name": "sensorflare",
Author: "LPFraile <lidiapf0@gmail.com>",
License: "BSD",
Version: "0.0.1",
Description: "Include your Particle Core on Sensorflare"
File: Example: Control trough your Sensorflare account the PWM outputs on your Particle Core
*/
//Include the Sensorflare library
#include "sensorflare/sensorflare.h"
//Initialize objects from the library
//One object of the class "PWMOut" is initialized for
//every PWM output that will be remote control
SensorFlare::PWMOut pwm(A0);
void setup() {
// Call the begin() functions for every object of the classes "DigitalOut" and
//"PWMout" to be wired up correct and available.
pwm.begin();
}
void loop() {
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkLabelOverlayImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkCommand.h"
#include "itkSimpleFilterWatcher.h"
#include "itkLabelOverlayImageFilter.h"
int itkLabelOverlayImageFilterTest(int argc, char * argv[])
{
const int Dimension = 2;
if( argc < 5 )
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " InputImage LabelImage Opacity OutputImage" << std::endl;
return 1;
}
typedef unsigned char PType;
typedef itk::Image< PType, Dimension > IType;
typedef itk::RGBPixel<unsigned char> CPType;
typedef itk::Image< CPType, Dimension > CIType;
typedef itk::ImageFileReader< IType > ReaderType;
//Read in the input image
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
//Read in the label image
ReaderType::Pointer reader2 = ReaderType::New();
reader2->SetFileName( argv[2] );
//Instantiate the filter
typedef itk::LabelOverlayImageFilter< IType, IType, CIType> FilterType;
FilterType::Pointer filter = FilterType::New();
//Use the background
filter->SetUseBackground( true );
//Set the filter input and label images
filter->SetInput( reader->GetOutput() );
filter->SetLabelImage( reader2->GetOutput() );
//Set opacity
filter->SetOpacity( atof(argv[3]) );
itk::SimpleFilterWatcher watcher(filter, "filter");
//Instantiate output image
typedef itk::ImageFileWriter< CIType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( filter->GetOutput() );
writer->SetFileName( argv[4] );
writer->Update();
return EXIT_SUCCESS;
}
<commit_msg>ENH: Adding code for exercising all the methods. It should get close to 100% code coverage now.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkLabelOverlayImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkCommand.h"
#include "itkSimpleFilterWatcher.h"
#include "itkLabelOverlayImageFilter.h"
int itkLabelOverlayImageFilterTest(int argc, char * argv[])
{
const int Dimension = 2;
if( argc < 5 )
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " InputImage LabelImage Opacity OutputImage" << std::endl;
return 1;
}
typedef unsigned char PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::RGBPixel<unsigned char> ColorPixelType;
typedef itk::Image< ColorPixelType, Dimension > ColorImageType;
typedef itk::ImageFileReader< ImageType > ReaderType;
//Read in the input image
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
//Read in the label image
ReaderType::Pointer reader2 = ReaderType::New();
reader2->SetFileName( argv[2] );
//Instantiate the filter
typedef itk::LabelOverlayImageFilter<
ImageType, ImageType, ColorImageType> FilterType;
FilterType::Pointer filter = FilterType::New();
//Use the background
filter->SetUseBackground( true );
if( filter->GetUseBackground() != true )
{
std::cerr << "UseBackground Set/Get Problem" << std::endl;
return EXIT_FAILURE;
}
filter->SetUseBackground( false );
if( filter->GetUseBackground() != false )
{
std::cerr << "UseBackground Set/Get Problem" << std::endl;
return EXIT_FAILURE;
}
filter->UseBackgroundOn();
if( filter->GetUseBackground() != true )
{
std::cerr << "UseBackground Set/Get Problem" << std::endl;
return EXIT_FAILURE;
}
filter->UseBackgroundOff();
if( filter->GetUseBackground() != false )
{
std::cerr << "UseBackground Set/Get Problem" << std::endl;
return EXIT_FAILURE;
}
filter->SetUseBackground( true );
// Exercising Background Value methods
filter->SetBackgroundValue( 200 );
if( filter->GetUseBackground() != true )
{
std::cerr << "UseBackground Set/Get Problem" << std::endl;
return EXIT_FAILURE;
}
//Set the filter input and label images
filter->SetInput( reader->GetOutput() );
filter->SetLabelImage( reader2->GetOutput() );
filter->SetOpacity( 2 );
if( filter->GetOpacity() != 2 )
{
std::cerr << "Opacity Set/Get Problem" << std::endl;
return EXIT_FAILURE;
}
filter->SetOpacity( 3 );
if( filter->GetOpacity() != 3 )
{
std::cerr << "Opacity Set/Get Problem" << std::endl;
return EXIT_FAILURE;
}
//Set opacity
filter->SetOpacity( atof(argv[3]) );
itk::SimpleFilterWatcher watcher(filter, "filter");
//Instantiate output image
typedef itk::ImageFileWriter< ColorImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( filter->GetOutput() );
writer->SetFileName( argv[4] );
try
{
writer->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "Priority.hpp"
#include "But/Log/Backend/FieldInfo.hpp"
using But::Log::Field::Priority;
namespace
{
struct ButLogFieldPriority: public testing::Test
{ };
TEST_F(ButLogFieldPriority, ConvertingToString)
{
EXPECT_EQ( toString(Priority::debug), "debug" );
EXPECT_EQ( toString(Priority::info), "info" );
EXPECT_EQ( toString(Priority::warning), "warning" );
EXPECT_EQ( toString(Priority::error), "error" );
}
TEST_F(ButLogFieldPriority, ConvertingToStringOfConstantLength)
{
EXPECT_EQ( toStringConstLen(Priority::debug), "debug " );
EXPECT_EQ( toStringConstLen(Priority::info), "info " );
EXPECT_EQ( toStringConstLen(Priority::warning), "warning" );
EXPECT_EQ( toStringConstLen(Priority::error), "error " );
}
TEST_F(ButLogFieldPriority, ConvertingToEntry)
{
const auto fi = But::Log::Backend::FieldInfo{Priority::info};
EXPECT_EQ( fi.type(), "But::Log::Field::Priority" );
EXPECT_EQ( fi.value(), "info" );
}
}
<commit_msg>fixed test name<commit_after>#include "gtest/gtest.h"
#include "Priority.hpp"
#include "But/Log/Backend/FieldInfo.hpp"
using But::Log::Field::Priority;
namespace
{
struct ButLogFieldPriority: public testing::Test
{ };
TEST_F(ButLogFieldPriority, ConvertingToString)
{
EXPECT_EQ( toString(Priority::debug), "debug" );
EXPECT_EQ( toString(Priority::info), "info" );
EXPECT_EQ( toString(Priority::warning), "warning" );
EXPECT_EQ( toString(Priority::error), "error" );
}
TEST_F(ButLogFieldPriority, ConvertingToStringOfConstantLength)
{
EXPECT_EQ( toStringConstLen(Priority::debug), "debug " );
EXPECT_EQ( toStringConstLen(Priority::info), "info " );
EXPECT_EQ( toStringConstLen(Priority::warning), "warning" );
EXPECT_EQ( toStringConstLen(Priority::error), "error " );
}
TEST_F(ButLogFieldPriority, ConvertingToFieldInfo)
{
const auto fi = But::Log::Backend::FieldInfo{Priority::info};
EXPECT_EQ( fi.type(), "But::Log::Field::Priority" );
EXPECT_EQ( fi.value(), "info" );
}
}
<|endoftext|> |
<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "proximitylist_api.h"
#include "type/pb_converter.h"
#include "utils/paginate.h"
namespace navitia {
namespace proximitylist {
/**
* se charge de remplir l'objet protocolbuffer autocomplete passé en paramètre
*
*/
using t_result =
std::tuple<nt::idx_t, nt::GeographicalCoord, float, nt::Type_e, std::vector<std::tuple<nt::idx_t, float>>>;
using idx_coord_distance = std::tuple<nt::idx_t, nt::GeographicalCoord, float>;
using Vector_idx_coord_distance = std::vector<idx_coord_distance>;
static void make_pb(navitia::PbCreator& pb_creator,
const std::vector<t_result>& result,
uint32_t depth,
const nt::Data& data,
type::GeographicalCoord coord) {
for (auto result_item : result) {
pbnavitia::PtObject* place = pb_creator.add_places_nearby();
auto idx = std::get<0>(result_item);
auto coord_item = std::get<1>(result_item);
auto distance = sqrt(std::get<2>(result_item));
auto type = std::get<3>(result_item);
auto stop_points_nearby_idx_distance = std::get<4>(result_item);
switch (type) {
case nt::Type_e::StopArea:
pb_creator.fill(data.pt_data->stop_areas[idx], place, depth);
place->set_distance(distance);
break;
case nt::Type_e::StopPoint:
pb_creator.fill(data.pt_data->stop_points[idx], place, depth);
place->set_distance(distance);
break;
case nt::Type_e::POI:
pb_creator.fill(data.geo_ref->pois[idx], place, depth);
place->set_distance(distance);
break;
case nt::Type_e::Address: {
const auto& way_coord = navitia::WayCoord(data.geo_ref->ways[idx], coord,
data.geo_ref->ways[idx]->nearest_number(coord).first);
pb_creator.fill(&way_coord, place, depth);
place->set_distance(coord.distance_to(coord_item));
break;
}
default:
break;
}
// add stop points nearby into response
for (const auto& sp_idx_distance : stop_points_nearby_idx_distance) {
pbnavitia::PtObject* pt_obj = place->add_stop_points_nearby();
pb_creator.fill(data.pt_data->stop_points[std::get<0>(sp_idx_distance)], pt_obj, depth);
pt_obj->set_distance(std::get<1>(sp_idx_distance));
}
}
}
static void cut(Vector_idx_coord_distance& idx_coord_distance, const size_t end_pagination) {
const auto nb_sort = std::min(idx_coord_distance.size(), end_pagination);
idx_coord_distance.resize(nb_sort);
}
void find(navitia::PbCreator& pb_creator,
const type::GeographicalCoord& coord,
const double limit,
const std::vector<nt::Type_e>& types,
const std::string& filter,
const uint32_t depth,
const uint32_t count,
const uint32_t start_page,
const type::Data& data,
const bool find_stop_points_nearby) {
int total_result = 0;
std::vector<t_result> result;
auto end_pagination = (start_page + 1) * count;
for (nt::Type_e type : types) {
if (type == nt::Type_e::Address) {
// for addresses we use the street network
try {
auto nb_w = pb_creator.data->geo_ref->nearest_addr(coord);
// we'll regenerate the good number in make_pb
result.emplace_back(nb_w.second->idx, std::move(coord), 0, type,
std::move(std::vector<std::tuple<nt::idx_t, float>>()));
++total_result;
} catch (const proximitylist::NotFound&) {
}
continue;
}
Vector_idx_coord_distance vector_idx_coord_distance;
type::Indexes indexes;
if (!filter.empty()) {
try {
indexes = ptref::make_query(type, filter, *pb_creator.data);
} catch (const ptref::parsing_error& parse_error) {
pb_creator.fill_pb_error(pbnavitia::Error::unable_to_parse,
"Problem while parsing the query:" + parse_error.more);
return;
} catch (const ptref::ptref_error& pt_error) {
pb_creator.fill_pb_error(pbnavitia::Error::bad_filter, "ptref : " + pt_error.more);
return;
}
}
// We have to find all objects within distance, then apply the filter
int search_count = -1;
switch (type) {
case nt::Type_e::StopArea:
vector_idx_coord_distance =
pb_creator.data->pt_data->stop_area_proximity_list.find_within<IndexCoordDistance>(coord, limit,
search_count);
break;
case nt::Type_e::StopPoint:
vector_idx_coord_distance =
pb_creator.data->pt_data->stop_point_proximity_list.find_within<IndexCoordDistance>(coord, limit,
search_count);
break;
case nt::Type_e::POI:
vector_idx_coord_distance =
pb_creator.data->geo_ref->poi_proximity_list.find_within<IndexCoordDistance>(coord, limit,
search_count);
break;
default:
break;
}
Vector_idx_coord_distance final_vector_idx_coord_distance;
if (filter.empty()) {
final_vector_idx_coord_distance = vector_idx_coord_distance;
} else {
for (const auto& element : vector_idx_coord_distance) {
auto idx = std::get<0>(element);
if (indexes.find(idx) != indexes.cend()) {
final_vector_idx_coord_distance.push_back(element);
}
}
}
total_result += final_vector_idx_coord_distance.size();
cut(final_vector_idx_coord_distance, end_pagination);
for (const auto& elem : final_vector_idx_coord_distance) {
auto idx = std::get<0>(elem);
auto coord = std::get<1>(elem);
auto distance = std::get<2>(elem);
std::vector<std::tuple<nt::idx_t, float>> stop_points_nearby_idx_distance;
// for each result found, we perform a new proximity research for stop point type.
if (find_stop_points_nearby) {
auto stop_points_nearby_idx_coord_distance =
pb_creator.data->pt_data->stop_point_proximity_list.find_within<IndexCoordDistance>(
std::get<1>(elem), limit, search_count);
stop_points_nearby_idx_distance.reserve(stop_points_nearby_idx_coord_distance.size());
for (const auto& sp_idx : stop_points_nearby_idx_coord_distance) {
stop_points_nearby_idx_distance.emplace_back(std::get<0>(sp_idx), std::get<2>(sp_idx));
}
}
result.emplace_back(idx, std::move(coord), distance, type, std::move(stop_points_nearby_idx_distance));
}
}
result = paginate(result, count, start_page);
make_pb(pb_creator, result, depth, data, coord);
pb_creator.make_paginate(total_result, start_page, count, result.size());
}
} // namespace proximitylist
} // namespace navitia
<commit_msg>comment<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved.
This file is part of Navitia,
the software to build cool stuff with public transport.
Hope you'll enjoy and contribute to this project,
powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
a non ending quest to the responsive locomotion way of traveling!
LICENCE: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Stay tuned using
twitter @navitia
channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "proximitylist_api.h"
#include "type/pb_converter.h"
#include "utils/paginate.h"
namespace navitia {
namespace proximitylist {
/**
* se charge de remplir l'objet protocolbuffer autocomplete passé en paramètre
*
*/
using t_result =
std::tuple<nt::idx_t, nt::GeographicalCoord, float, nt::Type_e, std::vector<std::tuple<nt::idx_t, float>>>;
using idx_coord_distance = std::tuple<nt::idx_t, nt::GeographicalCoord, float>;
using Vector_idx_coord_distance = std::vector<idx_coord_distance>;
static void make_pb(navitia::PbCreator& pb_creator,
const std::vector<t_result>& result,
uint32_t depth,
const nt::Data& data,
type::GeographicalCoord coord) {
for (auto result_item : result) {
pbnavitia::PtObject* place = pb_creator.add_places_nearby();
auto idx = std::get<0>(result_item);
auto coord_item = std::get<1>(result_item);
auto distance = sqrt(std::get<2>(result_item));
auto type = std::get<3>(result_item);
auto stop_points_nearby_idx_distance = std::get<4>(result_item);
switch (type) {
case nt::Type_e::StopArea:
pb_creator.fill(data.pt_data->stop_areas[idx], place, depth);
place->set_distance(distance);
break;
case nt::Type_e::StopPoint:
pb_creator.fill(data.pt_data->stop_points[idx], place, depth);
place->set_distance(distance);
break;
case nt::Type_e::POI:
pb_creator.fill(data.geo_ref->pois[idx], place, depth);
place->set_distance(distance);
break;
case nt::Type_e::Address: {
const auto& way_coord = navitia::WayCoord(data.geo_ref->ways[idx], coord,
data.geo_ref->ways[idx]->nearest_number(coord).first);
pb_creator.fill(&way_coord, place, depth);
place->set_distance(coord.distance_to(coord_item));
break;
}
default:
break;
}
// add stop points nearby (PtObject) into response
for (const auto& sp_idx_distance : stop_points_nearby_idx_distance) {
pbnavitia::PtObject* pt_obj = place->add_stop_points_nearby();
pb_creator.fill(data.pt_data->stop_points[std::get<0>(sp_idx_distance)], pt_obj, depth);
pt_obj->set_distance(std::get<1>(sp_idx_distance));
}
}
}
static void cut(Vector_idx_coord_distance& idx_coord_distance, const size_t end_pagination) {
const auto nb_sort = std::min(idx_coord_distance.size(), end_pagination);
idx_coord_distance.resize(nb_sort);
}
void find(navitia::PbCreator& pb_creator,
const type::GeographicalCoord& coord,
const double limit,
const std::vector<nt::Type_e>& types,
const std::string& filter,
const uint32_t depth,
const uint32_t count,
const uint32_t start_page,
const type::Data& data,
const bool find_stop_points_nearby) {
int total_result = 0;
std::vector<t_result> result;
auto end_pagination = (start_page + 1) * count;
for (nt::Type_e type : types) {
if (type == nt::Type_e::Address) {
// for addresses we use the street network
try {
auto nb_w = pb_creator.data->geo_ref->nearest_addr(coord);
// we'll regenerate the good number in make_pb
result.emplace_back(nb_w.second->idx, std::move(coord), 0, type,
std::move(std::vector<std::tuple<nt::idx_t, float>>()));
++total_result;
} catch (const proximitylist::NotFound&) {
}
continue;
}
Vector_idx_coord_distance vector_idx_coord_distance;
type::Indexes indexes;
if (!filter.empty()) {
try {
indexes = ptref::make_query(type, filter, *pb_creator.data);
} catch (const ptref::parsing_error& parse_error) {
pb_creator.fill_pb_error(pbnavitia::Error::unable_to_parse,
"Problem while parsing the query:" + parse_error.more);
return;
} catch (const ptref::ptref_error& pt_error) {
pb_creator.fill_pb_error(pbnavitia::Error::bad_filter, "ptref : " + pt_error.more);
return;
}
}
// We have to find all objects within distance, then apply the filter
int search_count = -1;
switch (type) {
case nt::Type_e::StopArea:
vector_idx_coord_distance =
pb_creator.data->pt_data->stop_area_proximity_list.find_within<IndexCoordDistance>(coord, limit,
search_count);
break;
case nt::Type_e::StopPoint:
vector_idx_coord_distance =
pb_creator.data->pt_data->stop_point_proximity_list.find_within<IndexCoordDistance>(coord, limit,
search_count);
break;
case nt::Type_e::POI:
vector_idx_coord_distance =
pb_creator.data->geo_ref->poi_proximity_list.find_within<IndexCoordDistance>(coord, limit,
search_count);
break;
default:
break;
}
Vector_idx_coord_distance final_vector_idx_coord_distance;
if (filter.empty()) {
final_vector_idx_coord_distance = vector_idx_coord_distance;
} else {
for (const auto& element : vector_idx_coord_distance) {
auto idx = std::get<0>(element);
if (indexes.find(idx) != indexes.cend()) {
final_vector_idx_coord_distance.push_back(element);
}
}
}
total_result += final_vector_idx_coord_distance.size();
cut(final_vector_idx_coord_distance, end_pagination);
for (const auto& elem : final_vector_idx_coord_distance) {
auto idx = std::get<0>(elem);
auto coord = std::get<1>(elem);
auto distance = std::get<2>(elem);
std::vector<std::tuple<nt::idx_t, float>> stop_points_nearby_idx_distance;
// for each result found, we perform a new proximity research for stop point type.
if (find_stop_points_nearby) {
auto stop_points_nearby_idx_coord_distance =
pb_creator.data->pt_data->stop_point_proximity_list.find_within<IndexCoordDistance>(
std::get<1>(elem), limit, search_count);
stop_points_nearby_idx_distance.reserve(stop_points_nearby_idx_coord_distance.size());
for (const auto& sp_idx : stop_points_nearby_idx_coord_distance) {
stop_points_nearby_idx_distance.emplace_back(std::get<0>(sp_idx), std::get<2>(sp_idx));
}
}
result.emplace_back(idx, std::move(coord), distance, type, std::move(stop_points_nearby_idx_distance));
}
}
result = paginate(result, count, start_page);
make_pb(pb_creator, result, depth, data, coord);
pb_creator.make_paginate(total_result, start_page, count, result.size());
}
} // namespace proximitylist
} // namespace navitia
<|endoftext|> |
<commit_before>#include <exodus/program.h>
programinit()
function main() {
var dbname2 = COMMAND.a(2);
var filenames = COMMAND.field(FM, 3, 999999);
if (not dbname2) {
var syntax =
"dbattach - Attach other database files into the current/default database\n"
"\n"
"Syntax is dbattach TARGETDB [FILENAME,...] {OPTION...}\n"
"\n"
"Options:\n"
"\n"
" F means forcibly delete any normal files in the current/default database.\n"
"\n"
" R means remove the current file attachments.\n"
" RR means remove the current user/database connection map.\n"
" RRR means remove all connections and attachments.\n"
"\n"
"If no filenames are provided then a database connection is created.\n"
"This is *required* before filenames can be provided and attached.\n"
"\n"
"Any existing files will be DELETED.\n"
"\n"
"Note that any secondary indexes on the attached files are ineffective.\n"
"\n"
"Attachments are permanent until re-attached or removed.";
abort(syntax);
}
var dbuser1 = "exodus";
var dbname1 = osgetenv("EXO_DATA");
if (not dbname1)
dbname1 = "exodus";
var dbuser2 = dbuser1;
var dbpass2 = "somesillysecret";
var conn1;
if (not conn1.connect())
abort(conn1.lasterror());
var sql;
////////////////////////////////////////////////////////////////////////////
// Create an interdb connection from default database to the target database
////////////////////////////////////////////////////////////////////////////
// If no filenames are provided then just setup the interdb connection
if (not filenames) {
/////////////////////////////////////////////////////////////////////////
// Must be done as a superuser eg postgres or exodus with superuser power
/////////////////////////////////////////////////////////////////////////
// Check we are a superuser
sql = "ALTER USER " ^ dbuser1 ^ " WITH SUPERUSER";
if (not conn1.sqlexec(sql))
abort(conn1.lasterror());
// Reset all interdb connections
if (OPTIONS.index("RRR")) {
if (not conn1.sqlexec("DROP EXTENSION IF EXISTS postgres_fdw CASCADE"))
abort(conn1.lasterror());
stop();
}
// Install extension required to establish interdb connections
if (not conn1.sqlexec("CREATE EXTENSION IF NOT EXISTS postgres_fdw WITH SCHEMA public"))
abort(conn1.lasterror());
// Reset the interdb connection to the target db. Remove all connected tables.
if (not conn1.sqlexec("DROP SERVER IF EXISTS " ^ dbname2 ^ " CASCADE"))
abort(conn1.lasterror());
// Create an interdb connection to the target server
if (OPTIONS.index("RR"))
exit(0);
if (not conn1.sqlexec("CREATE SERVER IF NOT EXISTS " ^ dbname2 ^ " FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host 'localhost', dbname '" ^ dbname2 ^ "', port '5432')"))
abort(conn1.lasterror());
// Allow current user to use the interdb connection
if (not conn1.sqlexec("GRANT USAGE ON FOREIGN SERVER " ^ dbname2 ^ " TO " ^ dbuser1))
abort(conn1.lasterror());
// Remove any existing user/connection configuration
if (not conn1.sqlexec("DROP USER MAPPING IF EXISTS FOR " ^ dbuser1 ^ " SERVER " ^ dbname2))
abort(conn1.lasterror());
if (OPTIONS.index("R"))
exit(0);
// Configure user/connection parameters. Target dbuser and dbpass.
if (not conn1.sqlexec("CREATE USER MAPPING FOR " ^ dbuser1 ^ " SERVER " ^ dbname2 ^ " OPTIONS (user '" ^ dbuser2 ^ "', password '" ^dbpass2 ^ "')"))
abort(conn1.lasterror());
printl("OK user " ^ dbuser1 ^ " in db " ^ dbname1 ^ " now has access to db " ^ dbname2);
return 0;
}
///////////////////////////////////////////////////////////////////
// Attach target db files as apparent files in the default database
///////////////////////////////////////////////////////////////////
// Remainder must be done as operating user eg exodus
//\psql -h localhost -p 5432 adlinec3 exodus
// Convert filenames to a comma separated list
filenames.converter(",", FM).trimmer(FM);
for (var filename : filenames) {
if (conn1.open(filename)) {
// Option to forcibly delete any existing files in the default database
if (OPTIONS.index("F")) {
//logputl("Remove any existing table " ^ filename);
//if (not conn1.sqlexec("DROP TABLE IF EXISTS " ^ filenames.swap(","," ")))
// abort(conn1.lasterror());
if (not conn1.deletefile(filename))
{};//logputl(conn1.lasterror());
}
//logputl("Remove any existing connected foreign table " ^ filename);
if (conn1.open(filename) and not conn1.sqlexec("DROP FOREIGN TABLE IF EXISTS " ^ filename))
{};//abort(conn1.lasterror());
}
//logputl("Connect to the foreign table " ^ filename);
if (not conn1.sqlexec("IMPORT FOREIGN SCHEMA public LIMIT TO (" ^ filename ^ ")"
" FROM SERVER " ^ dbname2 ^ " INTO public"))
abort(conn1.lasterror());
}
return 0;
}
programexit()
<commit_msg>add (L)ist option to dbattach<commit_after>#include <exodus/program.h>
programinit()
function main() {
var dbname2 = COMMAND.a(2);
var filenames = COMMAND.field(FM, 3, 999999);
if (not dbname2 and not OPTIONS) {
var syntax =
"dbattach - Attach other database files into the current/default database\n"
"\n"
"Syntax is dbattach TARGETDB [FILENAME,...] {OPTION...}\n"
"\n"
"Options:\n"
"\n"
" F Forcibly delete any normal files in the current/default database.\n"
"\n"
" R Remove the current file attachments.\n"
" RR Remove the current user/database connection map.\n"
" RRR Remove all connections and attachments.\n"
"\n"
" L List attached foreign files in the current/default database\n"
"\n"
"If no filenames are provided then a database connection is created.\n"
"This is *required* before filenames can be provided and attached.\n"
"\n"
"Any existing files will be DELETED.\n"
"\n"
"Note that any secondary indexes on the attached files are ineffective.\n"
"\n"
"Attachments are permanent until re-attached or removed.";
abort(syntax);
}
var dbuser1 = "exodus";
var dbname1 = osgetenv("EXO_DATA");
if (not dbname1)
dbname1 = "exodus";
var dbuser2 = dbuser1;
var dbpass2 = "somesillysecret";
var conn1;
if (not conn1.connect())
abort(conn1.lasterror());
var sql;
if (OPTIONS.index("L")) {
sql = "select foreign_server_name, foreign_table_name from information_schema.foreign_tables;";
var result;
if (not conn1.sqlexec(sql, result))
abort(conn1.lasterror());
// change RM to FM etc. and remove column headings
result.lowerer();
result.remover(1);
//format for printing
result.converter(FM, "\n");
result.converter(VM, " ");
printl(result);
stop();
}
////////////////////////////////////////////////////////////////////////////
// Create an interdb connection from default database to the target database
////////////////////////////////////////////////////////////////////////////
// If no filenames are provided then just setup the interdb connection
if (not filenames) {
/////////////////////////////////////////////////////////////////////////
// Must be done as a superuser eg postgres or exodus with superuser power
/////////////////////////////////////////////////////////////////////////
// Check we are a superuser
sql = "ALTER USER " ^ dbuser1 ^ " WITH SUPERUSER";
if (not conn1.sqlexec(sql))
abort(conn1.lasterror());
// Reset all interdb connections
if (OPTIONS.index("RRR")) {
if (not conn1.sqlexec("DROP EXTENSION IF EXISTS postgres_fdw CASCADE"))
abort(conn1.lasterror());
stop();
}
// Install extension required to establish interdb connections
if (not conn1.sqlexec("CREATE EXTENSION IF NOT EXISTS postgres_fdw WITH SCHEMA public"))
abort(conn1.lasterror());
if (not dbname2)
stop();
// Reset the interdb connection to the target db. Remove all connected tables.
if (not conn1.sqlexec("DROP SERVER IF EXISTS " ^ dbname2 ^ " CASCADE"))
abort(conn1.lasterror());
// Create an interdb connection to the target server
if (OPTIONS.index("RR"))
exit(0);
if (not conn1.sqlexec("CREATE SERVER IF NOT EXISTS " ^ dbname2 ^ " FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host 'localhost', dbname '" ^ dbname2 ^ "', port '5432')"))
abort(conn1.lasterror());
// Allow current user to use the interdb connection
if (not conn1.sqlexec("GRANT USAGE ON FOREIGN SERVER " ^ dbname2 ^ " TO " ^ dbuser1))
abort(conn1.lasterror());
// Remove any existing user/connection configuration
if (not conn1.sqlexec("DROP USER MAPPING IF EXISTS FOR " ^ dbuser1 ^ " SERVER " ^ dbname2))
abort(conn1.lasterror());
if (OPTIONS.index("R"))
exit(0);
// Configure user/connection parameters. Target dbuser and dbpass.
if (not conn1.sqlexec("CREATE USER MAPPING FOR " ^ dbuser1 ^ " SERVER " ^ dbname2 ^ " OPTIONS (user '" ^ dbuser2 ^ "', password '" ^dbpass2 ^ "')"))
abort(conn1.lasterror());
printl("OK user " ^ dbuser1 ^ " in db " ^ dbname1 ^ " now has access to db " ^ dbname2);
return 0;
}
///////////////////////////////////////////////////////////////////
// Attach target db files as apparent files in the default database
///////////////////////////////////////////////////////////////////
// Remainder must be done as operating user eg exodus
//\psql -h localhost -p 5432 adlinec3 exodus
// Convert filenames to a comma separated list
filenames.converter(",", FM).trimmer(FM);
for (var filename : filenames) {
if (not filename)
continue;
if (conn1.open(filename)) {
// Option to forcibly delete any existing files in the default database
if (OPTIONS.index("F")) {
//logputl("Remove any existing table " ^ filename);
//if (not conn1.sqlexec("DROP TABLE IF EXISTS " ^ filenames.swap(","," ")))
// abort(conn1.lasterror());
if (not conn1.deletefile(filename))
{};//logputl(conn1.lasterror());
}
//logputl("Remove any existing connected foreign table " ^ filename);
if (conn1.open(filename) and not conn1.sqlexec("DROP FOREIGN TABLE IF EXISTS " ^ filename))
{};//abort(conn1.lasterror());
}
//logputl("Connect to the foreign table " ^ filename);
if (not conn1.sqlexec("IMPORT FOREIGN SCHEMA public LIMIT TO (" ^ filename ^ ")"
" FROM SERVER " ^ dbname2 ^ " INTO public"))
abort(conn1.lasterror());
}
return 0;
}
programexit()
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkImportImageTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
#include "itkImage.h"
#include "itkImageRegionIterator.h"
#include "itkShrinkImageFilter.h"
#include "itkImportImageFilter.h"
int itkImportImageTest(int, char* [] )
{
// Create a C-array to hold an image
short *rawImage = new short[8*12];
for (int i=0; i < 8*12; i++)
{
rawImage[i] = i;
}
// typdefs to simplify the syntax
typedef itk::ImportImageFilter<short, 2> ImportImageFilter;
typedef itk::Image<short, 2> ShortImage;
// Create an ImportImageFilter filter
ImportImageFilter::Pointer import;
import = ImportImageFilter::New();
itk::ImageRegion<2> region;
itk::ImageRegion<2>::IndexType index = {{0, 0}};
itk::ImageRegion<2>::SizeType size = {{8, 12}};
region.SetSize( size );
region.SetIndex( index );
import->SetRegion( region );
import->SetImportPointer( rawImage, 8*12, true);
// Create another filter
itk::ShrinkImageFilter<ImportImageFilter::OutputImageType, ShortImage >::Pointer shrink;
shrink = itk::ShrinkImageFilter<ImportImageFilter::OutputImageType, ShortImage>::New();
shrink->SetInput( import->GetOutput() );
shrink->SetShrinkFactors(2);
try
{
shrink->Update();
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception detected: " << e.GetDescription();
return EXIT_FAILURE;
}
// Test the SetVectorMacros and GetVectorMacros
const double data[2] = {1.0,1.0};
import->SetSpacing(data);
const float data2[2] = {1.0,1.0};
import->SetSpacing(data2);
const double * spacingValue = import->GetSpacing();
std::cout << "import->GetSpacing(): " << spacingValue << std::endl;
const double data3[2] = {1.0,1.0};
import->SetOrigin(data3);
const float data4[2] = {1.0,1.0};
import->SetOrigin(data4);
const double * originValue = import->GetOrigin();
std::cout << "import->GetOrigin(): " << originValue << std::endl;
//
// The rest of this code determines whether the shrink code produced
// the image we expected.
//
ShortImage::RegionType requestedRegion;
requestedRegion = shrink->GetOutput()->GetRequestedRegion();
itk::ImageRegionIterator<ShortImage>
iterator2(shrink->GetOutput(), requestedRegion);
bool passed = true;
for (; !iterator2.IsAtEnd(); ++iterator2)
{
std::cout << "Pixel " << iterator2.GetIndex() << " = " << iterator2.Get() << std::endl;
#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY
if ( iterator2.Get() !=
itk::Math::RoundHalfIntegerUp( static_cast<float>((shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[0])
+(region.GetSize()[0]
* shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[1]))))
{
passed = false;
}
#else
if ( iterator2.Get() !=
static_cast<long>( (shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[0])
+(region.GetSize()[0]
* shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[1])))
{
passed = false;
}
#endif
}
if (passed)
{
std::cout << "ImportImageFilter test passed." << std::endl;
return EXIT_SUCCESS;
}
else
{
std::cout << "ImportImageFilter test failed." << std::endl;
return EXIT_FAILURE;
}
}
<commit_msg>BUG: 6558. Fix for failing ImportImageTest for pixel-centered coordintes. Offset adjusted based on this new centering.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkImportImageTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
#include "itkImage.h"
#include "itkImageRegionIterator.h"
#include "itkShrinkImageFilter.h"
#include "itkImportImageFilter.h"
int itkImportImageTest(int, char* [] )
{
// Create a C-array to hold an image
short *rawImage = new short[8*12];
for (int i=0; i < 8*12; i++)
{
rawImage[i] = i;
}
// typdefs to simplify the syntax
typedef itk::ImportImageFilter<short, 2> ImportImageFilter;
typedef itk::Image<short, 2> ShortImage;
// Create an ImportImageFilter filter
ImportImageFilter::Pointer import;
import = ImportImageFilter::New();
itk::ImageRegion<2> region;
itk::ImageRegion<2>::IndexType index = {{0, 0}};
itk::ImageRegion<2>::SizeType size = {{8, 12}};
region.SetSize( size );
region.SetIndex( index );
import->SetRegion( region );
import->SetImportPointer( rawImage, 8*12, true);
// Create another filter
itk::ShrinkImageFilter<ImportImageFilter::OutputImageType, ShortImage >::Pointer shrink;
shrink = itk::ShrinkImageFilter<ImportImageFilter::OutputImageType, ShortImage>::New();
shrink->SetInput( import->GetOutput() );
shrink->SetShrinkFactors(2); //Also tested with factors 3 and 4, with 12x12 image
try
{
shrink->Update();
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception detected: " << e.GetDescription();
return EXIT_FAILURE;
}
// Test the SetVectorMacros and GetVectorMacros
const double data[2] = {1.0,1.0};
import->SetSpacing(data);
const float data2[2] = {1.0,1.0};
import->SetSpacing(data2);
const double * spacingValue = import->GetSpacing();
std::cout << "import->GetSpacing(): " << spacingValue << std::endl;
const double data3[2] = {1.0,1.0};
import->SetOrigin(data3);
const float data4[2] = {1.0,1.0};
import->SetOrigin(data4);
const double * originValue = import->GetOrigin();
std::cout << "import->GetOrigin(): " << originValue << std::endl;
//
// The rest of this code determines whether the shrink code produced
// the image we expected.
//
ShortImage::RegionType requestedRegion;
requestedRegion = shrink->GetOutput()->GetRequestedRegion();
itk::ImageRegionIterator<ShortImage>
iterator2(shrink->GetOutput(), requestedRegion);
bool passed = true;
for (; !iterator2.IsAtEnd(); ++iterator2)
{
std::cout << "Pixel " << iterator2.GetIndex() << " = " << iterator2.Get() << std::endl;
#ifdef ITK_USE_CENTERED_PIXEL_COORDINATES_CONSISTENTLY
if ( iterator2.Get() !=
itk::Math::RoundHalfIntegerUp(
static_cast<float>( (shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[0] +
shrink->GetShrinkFactors()[0]/2) +
(region.GetSize()[0] * ((shrink->GetShrinkFactors()[1]/2) +
(shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[1]))))))
{
std::cout << " iterator2.GetIndex() Get() " << iterator2.GetIndex() << " " << iterator2.Get()
<< " compare value " << itk::Math::RoundHalfIntegerUp(
static_cast<float>( (shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[0] +
shrink->GetShrinkFactors()[0]/2) +
(region.GetSize()[0] * ((shrink->GetShrinkFactors()[1]/2) +
(shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[1]))))) << "\n";
passed = false;
}
#else
if ( iterator2.Get() !=
static_cast<long>( (shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[0] * factor
)
+(region.GetSize()[0]
* shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[1])))
{
std::cout << " iterator2.GetIndex() Get() " << iterator2.GetIndex() << " " << iterator2.Get()
<< " compare value " << static_cast<long>( (shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[0])
+(region.GetSize()[0]
* shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[1])) << "\n";
passed = false;
}
#endif
}
if (passed)
{
std::cout << "ImportImageFilter test passed." << std::endl;
return EXIT_SUCCESS;
}
else
{
std::cout << "ImportImageFilter test failed." << std::endl;
return EXIT_FAILURE;
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkNonUniformBSplineTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkNonUniformBSpline.h"
/*
* This test exercises the NonUniformBSpline class.
*/
int itkNonUniformBSplineTest(int, char* [] )
{
typedef itk::NonUniformBSpline<3> SplineType;
SplineType::Pointer mySpline = SplineType::New();
typedef SplineType::PointListType PointListType;
typedef SplineType::PointType PointType;
typedef SplineType::KnotListType KnotListType;
typedef SplineType::ControlPointListType ControlPointListType;
const unsigned int orderA = 1;
mySpline->SetSplineOrder( orderA );
const unsigned int returnedOrderA =
mySpline->GetSplineOrder();
if( returnedOrderA != orderA )
{
std::cerr << "Error in Set/GetSplineOrder() " << std::endl;
return EXIT_FAILURE;
}
const unsigned int orderB = 3;
mySpline->SetSplineOrder( orderB );
const unsigned int returnedOrderB =
mySpline->GetSplineOrder();
if( returnedOrderB != orderB )
{
std::cerr << "Error in Set/GetSplineOrder() " << std::endl;
return EXIT_FAILURE;
}
PointListType pointList;
// Generate a list of points along the Z axis
PointType point;
const unsigned int numberOfPoints = 10;
const unsigned int Zorigin = 0.0;
const unsigned int Zspacing = 1.5;
for(unsigned int i = 0; i < numberOfPoints; i++ )
{
const double Z = i * Zspacing + Zorigin;
point[0] = 0.0;
point[1] = 0.0;
point[2] = Z;
pointList.push_back( point );
}
mySpline->SetPoints( pointList );
const PointListType & returnedPointList = mySpline->GetPoints();
PointListType::const_iterator pitr = pointList.begin();
PointListType::const_iterator pend = pointList.end();
PointListType::const_iterator rpitr = returnedPointList.begin();
while ( pitr != pend )
{
if( *pitr != *rpitr )
{
std::cerr << "Error in Set/GetPoints() " << std::endl;
return EXIT_FAILURE;
}
++pitr;
++rpitr;
}
KnotListType knotList;
// Generate a list of knots (non-uniformly spaced)
// Purposely set them between 0.0 and 1.0 so that
// they don't get to be rescaled.
knotList.push_back( 0.0 );
knotList.push_back( 0.3 );
knotList.push_back( 0.7 );
knotList.push_back( 0.11 );
knotList.push_back( 0.29 );
knotList.push_back( 1.00 );
mySpline->SetKnots( knotList );
const KnotListType & returnedKnotList = mySpline->GetKnots();
KnotListType::const_iterator kitr = knotList.begin();
KnotListType::const_iterator kend = knotList.end();
KnotListType::const_iterator rkitr = returnedKnotList.begin();
while ( kitr != kend )
{
if( vnl_math_abs( *kitr - *rkitr ) > vnl_math::eps )
{
std::cerr << "Error in Set/GetKnots() " << std::endl;
std::cerr << "Expected = " << *kitr << std::endl;
std::cerr << "Received = " << *rkitr << std::endl;
return EXIT_FAILURE;
}
++kitr;
++rkitr;
}
try
{
mySpline->ComputeChordLengths();
}
catch( itk::ExceptionObject & excp )
{
std::cout << excp << std::endl;
return EXIT_FAILURE;
}
try
{
mySpline->ComputeControlPoints();
}
catch( itk::ExceptionObject & excp )
{
std::cout << excp << std::endl;
return EXIT_FAILURE;
}
PointType p1 = mySpline->EvaluateSpline( 0.5 );
// FIXME: Validate the return value in p1
itk::Array<double> pp(3);
pp.Fill( 0.5);
PointType p2 = mySpline->EvaluateSpline( pp );
// FIXME: Validate the return value in p2
ControlPointListType controlPointList;
// Generate a list of knots (non-uniformly spaced)
// Purposely set them between 0.0 and 1.0 so that
// they don't get to be rescaled.
const unsigned int numberOfControlPoints = 5;
const unsigned int Corigin = 0.0;
const unsigned int Cspacing = 1.5;
for(unsigned int i = 0; i < numberOfControlPoints; i++ )
{
const double Z = i * Cspacing + Corigin;
point[0] = 0.0;
point[1] = 0.0;
point[2] = Z;
controlPointList.push_back( point );
}
mySpline->SetControlPoints( controlPointList );
const ControlPointListType & returnedControlPointsList =
mySpline->GetControlPoints();
ControlPointListType::const_iterator citr = controlPointList.begin();
ControlPointListType::const_iterator cend = controlPointList.end();
ControlPointListType::const_iterator rcitr = returnedControlPointsList.begin();
while ( citr != cend )
{
if ( *citr != *rcitr )
{
std::cerr << "Error in Set/GetControlPoints() " << std::endl;
std::cerr << "Expected = " << *citr << std::endl;
std::cerr << "Received = " << *rcitr << std::endl;
return EXIT_FAILURE;
}
++citr;
++rcitr;
}
const unsigned int numberOfEvaluations = 10;
const unsigned int basisFunctionNumber = 1;
const double TOrigin = 0.0;
const double TSpacing = 0.1;
for( unsigned px = 0; px < numberOfEvaluations; px++ )
{
double t = px * TSpacing + TOrigin;
double value =
mySpline->NonUniformBSplineFunctionRecursive( orderB, basisFunctionNumber, t);
std::cout << t << " -> " << value << std::endl;
}
std::cout << "Test passed. " << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>COMP: Fixed warnings about initializing integer variables with doubles.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkNonUniformBSplineTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkNonUniformBSpline.h"
/*
* This test exercises the NonUniformBSpline class.
*/
int itkNonUniformBSplineTest(int, char* [] )
{
typedef itk::NonUniformBSpline<3> SplineType;
SplineType::Pointer mySpline = SplineType::New();
typedef SplineType::PointListType PointListType;
typedef SplineType::PointType PointType;
typedef SplineType::KnotListType KnotListType;
typedef SplineType::ControlPointListType ControlPointListType;
const unsigned int orderA = 1;
mySpline->SetSplineOrder( orderA );
const unsigned int returnedOrderA =
mySpline->GetSplineOrder();
if( returnedOrderA != orderA )
{
std::cerr << "Error in Set/GetSplineOrder() " << std::endl;
return EXIT_FAILURE;
}
const unsigned int orderB = 3;
mySpline->SetSplineOrder( orderB );
const unsigned int returnedOrderB =
mySpline->GetSplineOrder();
if( returnedOrderB != orderB )
{
std::cerr << "Error in Set/GetSplineOrder() " << std::endl;
return EXIT_FAILURE;
}
PointListType pointList;
// Generate a list of points along the Z axis
PointType point;
const unsigned int numberOfPoints = 10;
const double Zorigin = 0.0;
const double Zspacing = 1.5;
for(unsigned int i = 0; i < numberOfPoints; i++ )
{
const double Z = i * Zspacing + Zorigin;
point[0] = 0.0;
point[1] = 0.0;
point[2] = Z;
pointList.push_back( point );
}
mySpline->SetPoints( pointList );
const PointListType & returnedPointList = mySpline->GetPoints();
PointListType::const_iterator pitr = pointList.begin();
PointListType::const_iterator pend = pointList.end();
PointListType::const_iterator rpitr = returnedPointList.begin();
while ( pitr != pend )
{
if( *pitr != *rpitr )
{
std::cerr << "Error in Set/GetPoints() " << std::endl;
return EXIT_FAILURE;
}
++pitr;
++rpitr;
}
KnotListType knotList;
// Generate a list of knots (non-uniformly spaced)
// Purposely set them between 0.0 and 1.0 so that
// they don't get to be rescaled.
knotList.push_back( 0.0 );
knotList.push_back( 0.3 );
knotList.push_back( 0.7 );
knotList.push_back( 0.11 );
knotList.push_back( 0.29 );
knotList.push_back( 1.00 );
mySpline->SetKnots( knotList );
const KnotListType & returnedKnotList = mySpline->GetKnots();
KnotListType::const_iterator kitr = knotList.begin();
KnotListType::const_iterator kend = knotList.end();
KnotListType::const_iterator rkitr = returnedKnotList.begin();
while ( kitr != kend )
{
if( vnl_math_abs( *kitr - *rkitr ) > vnl_math::eps )
{
std::cerr << "Error in Set/GetKnots() " << std::endl;
std::cerr << "Expected = " << *kitr << std::endl;
std::cerr << "Received = " << *rkitr << std::endl;
return EXIT_FAILURE;
}
++kitr;
++rkitr;
}
try
{
mySpline->ComputeChordLengths();
}
catch( itk::ExceptionObject & excp )
{
std::cout << excp << std::endl;
return EXIT_FAILURE;
}
try
{
mySpline->ComputeControlPoints();
}
catch( itk::ExceptionObject & excp )
{
std::cout << excp << std::endl;
return EXIT_FAILURE;
}
PointType p1 = mySpline->EvaluateSpline( 0.5 );
// FIXME: Validate the return value in p1
itk::Array<double> pp(3);
pp.Fill( 0.5);
PointType p2 = mySpline->EvaluateSpline( pp );
// FIXME: Validate the return value in p2
ControlPointListType controlPointList;
// Generate a list of knots (non-uniformly spaced)
// Purposely set them between 0.0 and 1.0 so that
// they don't get to be rescaled.
const unsigned int numberOfControlPoints = 5;
const double Corigin = 0.0;
const double Cspacing = 1.5;
for(unsigned int i = 0; i < numberOfControlPoints; i++ )
{
const double Z = i * Cspacing + Corigin;
point[0] = 0.0;
point[1] = 0.0;
point[2] = Z;
controlPointList.push_back( point );
}
mySpline->SetControlPoints( controlPointList );
const ControlPointListType & returnedControlPointsList =
mySpline->GetControlPoints();
ControlPointListType::const_iterator citr = controlPointList.begin();
ControlPointListType::const_iterator cend = controlPointList.end();
ControlPointListType::const_iterator rcitr = returnedControlPointsList.begin();
while ( citr != cend )
{
if ( *citr != *rcitr )
{
std::cerr << "Error in Set/GetControlPoints() " << std::endl;
std::cerr << "Expected = " << *citr << std::endl;
std::cerr << "Received = " << *rcitr << std::endl;
return EXIT_FAILURE;
}
++citr;
++rcitr;
}
const unsigned int numberOfEvaluations = 10;
const unsigned int basisFunctionNumber = 1;
const double TOrigin = 0.0;
const double TSpacing = 0.1;
for( unsigned px = 0; px < numberOfEvaluations; px++ )
{
double t = px * TSpacing + TOrigin;
double value =
mySpline->NonUniformBSplineFunctionRecursive( orderB, basisFunctionNumber, t);
std::cout << t << " -> " << value << std::endl;
}
std::cout << "Test passed. " << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "transformer_memcpy.h"
#include "core/framework/kernel_registry_manager.h"
#include "core/framework/execution_providers.h"
using namespace ONNX_NAMESPACE;
namespace onnxruntime {
// implements MemCpy node insertion in graph transform
// note that GraphTransformer::Apply() is supposed to be stateless, so this cannot derive from GraphTranformer
class TransformerMemcpyImpl {
public:
TransformerMemcpyImpl(onnxruntime::Graph& graph, const std::string& provider)
: graph_(graph), provider_(provider) {}
bool ModifyGraph(const KernelRegistryManager& schema_registries);
private:
void ProcessDefs(onnxruntime::Node& node, const KernelRegistryManager& kernel_registries);
void BuildDefsMapping(const onnxruntime::NodeArg* arg, const KernelRegistryManager& kernel_registries);
void AddCopyNode(onnxruntime::NodeArg* arg, bool is_input);
void ProcessInitializers();
private:
ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(TransformerMemcpyImpl);
// use value-based compare to make sure transformer output order is consistent
struct NodeCompare {
bool operator()(const onnxruntime::Node* lhs, const onnxruntime::Node* rhs) const {
return lhs->Index() < rhs->Index();
}
};
// use value-based compare to make sure transformer output order is consistent
struct NodeArgCompare {
bool operator()(const onnxruntime::NodeArg* lhs, const onnxruntime::NodeArg* rhs) const {
return lhs->Name() < rhs->Name();
}
};
std::set<onnxruntime::Node*, NodeCompare> provider_nodes_;
std::set<const onnxruntime::NodeArg*, NodeArgCompare> non_provider_input_defs_; // all input defs of non-provider nodes
std::set<onnxruntime::NodeArg*, NodeArgCompare> non_provider_output_defs_; // all output defs of non-provider nodes
std::set<const onnxruntime::NodeArg*, NodeArgCompare> provider_input_defs_; // all input defs of provider nodes that should be in provider allocator
std::set<onnxruntime::NodeArg*, NodeArgCompare> provider_output_defs_; // all output defs of provider nodes that should be in provider allocator
std::map<const onnxruntime::NodeArg*, std::set<onnxruntime::Node*, NodeCompare>> provider_input_nodes_;
std::map<const onnxruntime::NodeArg*, std::set<onnxruntime::Node*, NodeCompare>> provider_output_nodes_;
onnxruntime::Graph& graph_;
std::string provider_;
};
// very simple GraphTransformer that uses TransformerMemcpyImpl for each graph
// and mainly provides the subgraph recursion functionality
common::Status MemcpyTransformer::ApplyImpl(Graph& graph, bool& modified, int graph_level) const {
for (auto& provider : provider_types_) {
if (provider != onnxruntime::kCpuExecutionProvider &&
provider != onnxruntime::kMklDnnExecutionProvider &&
provider != onnxruntime::kNupharExecutionProvider &&
provider != onnxruntime::kTensorrtExecutionProvider) {
TransformerMemcpyImpl copy_impl(graph, provider);
modified = copy_impl.ModifyGraph(registry_manager_);
}
}
// TODO: We probably need to do the recursion inline when processing the main graph in order to maximise efficiency.
// e.g. data on GPU prior to an 'If' node. The 'If' must run on CPU, but if the subgraph is GPU based it could
// consume the data from GPU and we shouldn't insert a memcpy from GPU to CPU prior to the If node, and one from
// CPU back to GPU when beginning execution of the subgraph. To do that requires inspecting the subgraph (and any
// nested subgraphs) when deciding whether to insert a memcpy in the parent graph, and may need to be fully done
// within TransformerMemcpyImpl instead of via this simple GraphTransformer.
// handle any subgraphs in nodes
for (auto& node : graph.Nodes()) {
ORT_RETURN_IF_ERROR(Recurse(node, modified, graph_level));
}
return Status::OK();
}
/*
Overview: The transformer transforms the input graph as follows:
(1) For every initializer W that is referenced by both provider and non-provider nodes,
we create a duplicate initializer W2 and change all provider nodes to reference this
duplicate copy.
(2) For every ml-value X that is computed by a provider node and referenced by a
non-provider node, we introduce a new ml-value X2. We replace all references to X
in provider nodes by X2, and introduce a copy from X2 to X. (All graph outputs
are considered as non-provider references here.)
(3 For every ml-value X that is computed by a non-provider node and referenced by
a provider node, we introduce a new ml-value X2. We replace all references to X in
provider nodes by X2, and introduce a copy from X to X2. (All graph inputs are
considered to be non-provider here.)
Note that every ml-value is computed at a unique point (either provider or non-provider),
but it may be referenced and used at multiple points (by both provider and non-provider).
This transformer does not currently optimize copies between, e.g., two different GPU devices, etc.
*/
bool TransformerMemcpyImpl::ModifyGraph(const KernelRegistryManager& kernel_registries) {
bool modified = false;
// find defs that require copy
for (auto& node : graph_.Nodes()) {
//don't need to do node placement here now, onnxruntime will do it according to registered kernels.
ProcessDefs(node, kernel_registries);
}
// for initializers shared by different providers, create dups
ProcessInitializers();
for (auto arg : graph_.GetInputs())
BuildDefsMapping(arg, kernel_registries);
for (auto arg : non_provider_input_defs_)
BuildDefsMapping(arg, kernel_registries);
for (auto arg : non_provider_output_defs_)
BuildDefsMapping(arg, kernel_registries);
for (auto arg : graph_.GetInputs())
// For inputs we need to create a copy node only when the input is connected to both provider
// and non-provider nodes. Otherwise utils::CopyInputsAcrossDevices() will do the job.
if (provider_input_defs_.count(arg) && non_provider_input_defs_.count(arg)) {
AddCopyNode(const_cast<onnxruntime::NodeArg*>(arg), true);
modified = true;
}
for (auto arg : non_provider_output_defs_)
if (provider_input_defs_.count(arg)) {
AddCopyNode(arg, true);
modified = true;
}
for (auto arg : provider_output_defs_)
if (non_provider_input_defs_.count(arg)) {
AddCopyNode(arg, false);
modified = true;
}
return modified;
}
void TransformerMemcpyImpl::ProcessDefs(onnxruntime::Node& node, const KernelRegistryManager& kernel_registries) {
if (node.GetExecutionProviderType() == provider_) {
provider_nodes_.insert(&node);
// note KernelCreateInfo might be nullptr for custom kernel
const KernelCreateInfo* kci = nullptr;
kernel_registries.SearchKernelRegistry(node, &kci);
ORT_ENFORCE(onnxruntime::Node::ForEachWithIndex(
node.InputDefs(),
[this, &kci](const onnxruntime::NodeArg& arg, size_t index) {
if (kci && MemTypeOnCpuExplicitly(kci->kernel_def->InputMemoryType(index)))
non_provider_input_defs_.insert(&arg);
else
provider_input_defs_.insert(&arg);
return Status::OK();
})
.IsOK());
// we don't need to handle implicit input here as provider_ is never kCpuExecutionProvider, all control flow
// nodes are CPU based, and only control flow nodes have implicit inputs.
auto& output_defs = node.MutableOutputDefs();
for (size_t i = 0; i < output_defs.size(); ++i) {
auto arg = output_defs[i];
if (!arg->Exists())
continue;
if (kci && MemTypeOnCpuExplicitly(kci->kernel_def->OutputMemoryType(i)))
non_provider_output_defs_.insert(arg);
else
provider_output_defs_.insert(arg);
}
} else {
// TODO: copy between devices? i.e. multiple GPUs
if (node.GetExecutionProviderType() != onnxruntime::kCpuExecutionProvider && node.GetExecutionProviderType() != onnxruntime::kTensorrtExecutionProvider &&
!node.GetExecutionProviderType().empty()) {
ORT_THROW("Execution type '", node.GetExecutionProviderType(), "' doesn't support memcpy ");
}
for (const auto* arg : node.InputDefs()) {
if (arg->Exists())
non_provider_input_defs_.insert(arg);
}
for (const auto* arg : node.ImplicitInputDefs()) {
if (arg->Exists())
non_provider_input_defs_.insert(arg);
}
for (auto* arg : node.MutableOutputDefs()) {
if (arg->Exists())
non_provider_output_defs_.insert(arg);
}
}
}
//for non_provider defs, collect the nodes that expect it is provider tensor as input/output.
void TransformerMemcpyImpl::BuildDefsMapping(const onnxruntime::NodeArg* arg, const KernelRegistryManager& kernel_registries) {
for (auto it = graph_.Nodes().begin(); it != graph_.Nodes().end(); it++) {
if (it->OpType() == "MemcpyFromHost" || it->OpType() == "MemcpyToHost")
continue;
auto input_it = std::find(it->MutableInputDefs().begin(), it->MutableInputDefs().end(), const_cast<onnxruntime::NodeArg*>(arg));
auto output_it = std::find(it->MutableOutputDefs().begin(), it->MutableOutputDefs().end(), const_cast<onnxruntime::NodeArg*>(arg));
int arg_input_index = input_it != it->MutableInputDefs().end() ? static_cast<int>(input_it - it->MutableInputDefs().begin()) : -1;
int arg_output_index = output_it != it->MutableOutputDefs().end() ? static_cast<int>(output_it - it->MutableOutputDefs().begin()) : -1;
if (arg_input_index == -1 && arg_output_index == -1)
continue;
if (it->GetExecutionProviderType() == provider_) {
const KernelCreateInfo* kci = nullptr;
kernel_registries.SearchKernelRegistry(*it, &kci);
if (arg_input_index != -1) {
if (!kci || !MemTypeOnCpuExplicitly(kci->kernel_def->InputMemoryType(arg_input_index)))
provider_input_nodes_[arg].insert(&*it);
}
if (arg_output_index != -1) {
if (!kci || !MemTypeOnCpuExplicitly(kci->kernel_def->OutputMemoryType(arg_output_index)))
provider_output_nodes_[arg].insert(&*it);
}
}
}
}
void TransformerMemcpyImpl::AddCopyNode(onnxruntime::NodeArg* arg, bool is_input) {
// create unique name for new def
std::string new_def_name = graph_.GenerateNodeArgName(arg->Name() + "_" + provider_);
auto* new_arg = &graph_.GetOrCreateNodeArg(new_def_name, arg->TypeAsProto());
auto* src_arg = is_input ? arg : new_arg;
auto* dst_arg = is_input ? new_arg : arg;
// create unique name for copy node
std::string new_node_name = graph_.GenerateNodeName("Memcpy");
const auto op_name = is_input ? "MemcpyFromHost" : "MemcpyToHost";
auto& new_node = graph_.AddNode(new_node_name, op_name, "Copy from/to host memory",
std::vector<onnxruntime::NodeArg*>{src_arg},
std::vector<onnxruntime::NodeArg*>{dst_arg});
new_node.SetExecutionProviderType(provider_);
std::map<const onnxruntime::NodeArg*, onnxruntime::NodeArg*> map = {{arg, new_arg}};
auto it = provider_input_nodes_.find(arg);
if (it != provider_input_nodes_.end()) {
for (auto* node : it->second)
node->ReplaceDefs(map);
}
it = provider_output_nodes_.find(arg);
if (it != provider_output_nodes_.end()) {
for (auto* node : it->second)
node->ReplaceDefs(map);
}
}
template <typename NodeArgSetType>
static const onnxruntime::NodeArg* FindNodeArg(const NodeArgSetType& def_set, const std::string& name) {
NodeArg def(name, nullptr);
auto it = def_set.find(&def); // this works since we use name to compare NodeArg
if (it != def_set.end())
return *it;
return nullptr;
}
// We duplicate any initializer that is used by both provider nodes and non-provider nodes
// to ensure that provider nodes and non-provider nodes don't share initializers, as they
// need to stay in different memory locations.
void TransformerMemcpyImpl::ProcessInitializers() {
std::map<const onnxruntime::NodeArg*, onnxruntime::NodeArg*> replacements;
for (const auto& pair : graph_.GetAllInitializedTensors()) {
const auto& name = pair.first;
const onnxruntime::NodeArg* provider_def = FindNodeArg(provider_input_defs_, name);
const onnxruntime::NodeArg* non_provider_def = FindNodeArg(non_provider_input_defs_, name);
if (provider_def != nullptr && non_provider_def != nullptr) {
std::string new_def_name = graph_.GenerateNodeArgName(name);
auto& new_def = graph_.GetOrCreateNodeArg(new_def_name, provider_def->TypeAsProto());
const TensorProto* tensor_proto = nullptr;
bool found = graph_.GetInitializedTensor(name, tensor_proto);
ORT_ENFORCE(found, "Failed to get initialized tensor ", name);
TensorProto new_tensor_proto = *tensor_proto;
*(new_tensor_proto.mutable_name()) = new_def_name;
graph_.AddInitializedTensor(new_tensor_proto);
replacements.insert(std::make_pair(provider_def, &new_def));
}
}
for (auto p_node : provider_nodes_) {
p_node->ReplaceDefs(replacements);
}
}
} // namespace onnxruntime
<commit_msg>Fix node def replacement by checking memory location (#623)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "transformer_memcpy.h"
#include "core/framework/kernel_registry_manager.h"
#include "core/framework/execution_providers.h"
using namespace ONNX_NAMESPACE;
namespace onnxruntime {
// implements MemCpy node insertion in graph transform
// note that GraphTransformer::Apply() is supposed to be stateless, so this cannot derive from GraphTranformer
class TransformerMemcpyImpl {
public:
TransformerMemcpyImpl(onnxruntime::Graph& graph, const std::string& provider)
: graph_(graph), provider_(provider) {}
bool ModifyGraph(const KernelRegistryManager& schema_registries);
private:
void ProcessDefs(onnxruntime::Node& node, const KernelRegistryManager& kernel_registries);
void BuildDefsMapping(const onnxruntime::NodeArg* arg, const KernelRegistryManager& kernel_registries);
void AddCopyNode(onnxruntime::NodeArg* arg, bool is_input);
void ProcessInitializers(const KernelRegistryManager& kernel_registries);
private:
ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(TransformerMemcpyImpl);
// use value-based compare to make sure transformer output order is consistent
struct NodeCompare {
bool operator()(const onnxruntime::Node* lhs, const onnxruntime::Node* rhs) const {
return lhs->Index() < rhs->Index();
}
};
// use value-based compare to make sure transformer output order is consistent
struct NodeArgCompare {
bool operator()(const onnxruntime::NodeArg* lhs, const onnxruntime::NodeArg* rhs) const {
return lhs->Name() < rhs->Name();
}
};
std::set<onnxruntime::Node*, NodeCompare> provider_nodes_;
std::set<const onnxruntime::NodeArg*, NodeArgCompare> non_provider_input_defs_; // all input defs of non-provider nodes
std::set<onnxruntime::NodeArg*, NodeArgCompare> non_provider_output_defs_; // all output defs of non-provider nodes
std::set<const onnxruntime::NodeArg*, NodeArgCompare> provider_input_defs_; // all input defs of provider nodes that should be in provider allocator
std::set<onnxruntime::NodeArg*, NodeArgCompare> provider_output_defs_; // all output defs of provider nodes that should be in provider allocator
std::map<const onnxruntime::NodeArg*, std::set<onnxruntime::Node*, NodeCompare>> provider_input_nodes_;
std::map<const onnxruntime::NodeArg*, std::set<onnxruntime::Node*, NodeCompare>> provider_output_nodes_;
onnxruntime::Graph& graph_;
std::string provider_;
};
// very simple GraphTransformer that uses TransformerMemcpyImpl for each graph
// and mainly provides the subgraph recursion functionality
common::Status MemcpyTransformer::ApplyImpl(Graph& graph, bool& modified, int graph_level) const {
for (auto& provider : provider_types_) {
if (provider != onnxruntime::kCpuExecutionProvider &&
provider != onnxruntime::kMklDnnExecutionProvider &&
provider != onnxruntime::kNupharExecutionProvider &&
provider != onnxruntime::kTensorrtExecutionProvider) {
TransformerMemcpyImpl copy_impl(graph, provider);
modified = copy_impl.ModifyGraph(registry_manager_);
}
}
// TODO: We probably need to do the recursion inline when processing the main graph in order to maximise efficiency.
// e.g. data on GPU prior to an 'If' node. The 'If' must run on CPU, but if the subgraph is GPU based it could
// consume the data from GPU and we shouldn't insert a memcpy from GPU to CPU prior to the If node, and one from
// CPU back to GPU when beginning execution of the subgraph. To do that requires inspecting the subgraph (and any
// nested subgraphs) when deciding whether to insert a memcpy in the parent graph, and may need to be fully done
// within TransformerMemcpyImpl instead of via this simple GraphTransformer.
// handle any subgraphs in nodes
for (auto& node : graph.Nodes()) {
ORT_RETURN_IF_ERROR(Recurse(node, modified, graph_level));
}
return Status::OK();
}
/*
Overview: The transformer transforms the input graph as follows:
(1) For every initializer W that is referenced by both provider and non-provider nodes,
we create a duplicate initializer W2 and change all provider nodes to reference this
duplicate copy.
(2) For every ml-value X that is computed by a provider node and referenced by a
non-provider node, we introduce a new ml-value X2. We replace all references to X
in provider nodes by X2, and introduce a copy from X2 to X. (All graph outputs
are considered as non-provider references here.)
(3 For every ml-value X that is computed by a non-provider node and referenced by
a provider node, we introduce a new ml-value X2. We replace all references to X in
provider nodes by X2, and introduce a copy from X to X2. (All graph inputs are
considered to be non-provider here.)
Note that every ml-value is computed at a unique point (either provider or non-provider),
but it may be referenced and used at multiple points (by both provider and non-provider).
This transformer does not currently optimize copies between, e.g., two different GPU devices, etc.
*/
bool TransformerMemcpyImpl::ModifyGraph(const KernelRegistryManager& kernel_registries) {
bool modified = false;
// find defs that require copy
for (auto& node : graph_.Nodes()) {
//don't need to do node placement here now, onnxruntime will do it according to registered kernels.
ProcessDefs(node, kernel_registries);
}
// for initializers shared by different providers, create dups
ProcessInitializers(kernel_registries);
for (auto arg : graph_.GetInputs())
BuildDefsMapping(arg, kernel_registries);
for (auto arg : non_provider_input_defs_)
BuildDefsMapping(arg, kernel_registries);
for (auto arg : non_provider_output_defs_)
BuildDefsMapping(arg, kernel_registries);
for (auto arg : graph_.GetInputs())
// For inputs we need to create a copy node only when the input is connected to both provider
// and non-provider nodes. Otherwise utils::CopyInputsAcrossDevices() will do the job.
if (provider_input_defs_.count(arg) && non_provider_input_defs_.count(arg)) {
AddCopyNode(const_cast<onnxruntime::NodeArg*>(arg), true);
modified = true;
}
for (auto arg : non_provider_output_defs_)
if (provider_input_defs_.count(arg)) {
AddCopyNode(arg, true);
modified = true;
}
for (auto arg : provider_output_defs_)
if (non_provider_input_defs_.count(arg)) {
AddCopyNode(arg, false);
modified = true;
}
return modified;
}
void TransformerMemcpyImpl::ProcessDefs(onnxruntime::Node& node, const KernelRegistryManager& kernel_registries) {
if (node.GetExecutionProviderType() == provider_) {
provider_nodes_.insert(&node);
// note KernelCreateInfo might be nullptr for custom kernel
const KernelCreateInfo* kci = nullptr;
kernel_registries.SearchKernelRegistry(node, &kci);
ORT_ENFORCE(onnxruntime::Node::ForEachWithIndex(
node.InputDefs(),
[this, &kci](const onnxruntime::NodeArg& arg, size_t index) {
if (kci && MemTypeOnCpuExplicitly(kci->kernel_def->InputMemoryType(index)))
non_provider_input_defs_.insert(&arg);
else
provider_input_defs_.insert(&arg);
return Status::OK();
})
.IsOK());
// we don't need to handle implicit input here as provider_ is never kCpuExecutionProvider, all control flow
// nodes are CPU based, and only control flow nodes have implicit inputs.
auto& output_defs = node.MutableOutputDefs();
for (size_t i = 0; i < output_defs.size(); ++i) {
auto arg = output_defs[i];
if (!arg->Exists())
continue;
if (kci && MemTypeOnCpuExplicitly(kci->kernel_def->OutputMemoryType(i)))
non_provider_output_defs_.insert(arg);
else
provider_output_defs_.insert(arg);
}
} else {
// TODO: copy between devices? i.e. multiple GPUs
if (node.GetExecutionProviderType() != onnxruntime::kCpuExecutionProvider && node.GetExecutionProviderType() != onnxruntime::kTensorrtExecutionProvider &&
!node.GetExecutionProviderType().empty()) {
ORT_THROW("Execution type '", node.GetExecutionProviderType(), "' doesn't support memcpy ");
}
for (const auto* arg : node.InputDefs()) {
if (arg->Exists())
non_provider_input_defs_.insert(arg);
}
for (const auto* arg : node.ImplicitInputDefs()) {
if (arg->Exists())
non_provider_input_defs_.insert(arg);
}
for (auto* arg : node.MutableOutputDefs()) {
if (arg->Exists())
non_provider_output_defs_.insert(arg);
}
}
}
//for non_provider defs, collect the nodes that expect it is provider tensor as input/output.
void TransformerMemcpyImpl::BuildDefsMapping(const onnxruntime::NodeArg* arg, const KernelRegistryManager& kernel_registries) {
for (auto it = graph_.Nodes().begin(); it != graph_.Nodes().end(); it++) {
if (it->OpType() == "MemcpyFromHost" || it->OpType() == "MemcpyToHost")
continue;
auto input_it = std::find(it->MutableInputDefs().begin(), it->MutableInputDefs().end(), const_cast<onnxruntime::NodeArg*>(arg));
auto output_it = std::find(it->MutableOutputDefs().begin(), it->MutableOutputDefs().end(), const_cast<onnxruntime::NodeArg*>(arg));
int arg_input_index = input_it != it->MutableInputDefs().end() ? static_cast<int>(input_it - it->MutableInputDefs().begin()) : -1;
int arg_output_index = output_it != it->MutableOutputDefs().end() ? static_cast<int>(output_it - it->MutableOutputDefs().begin()) : -1;
if (arg_input_index == -1 && arg_output_index == -1)
continue;
if (it->GetExecutionProviderType() == provider_) {
const KernelCreateInfo* kci = nullptr;
kernel_registries.SearchKernelRegistry(*it, &kci);
if (arg_input_index != -1) {
if (!kci || !MemTypeOnCpuExplicitly(kci->kernel_def->InputMemoryType(arg_input_index)))
provider_input_nodes_[arg].insert(&*it);
}
if (arg_output_index != -1) {
if (!kci || !MemTypeOnCpuExplicitly(kci->kernel_def->OutputMemoryType(arg_output_index)))
provider_output_nodes_[arg].insert(&*it);
}
}
}
}
void TransformerMemcpyImpl::AddCopyNode(onnxruntime::NodeArg* arg, bool is_input) {
// create unique name for new def
std::string new_def_name = graph_.GenerateNodeArgName(arg->Name() + "_" + provider_);
auto* new_arg = &graph_.GetOrCreateNodeArg(new_def_name, arg->TypeAsProto());
auto* src_arg = is_input ? arg : new_arg;
auto* dst_arg = is_input ? new_arg : arg;
// create unique name for copy node
std::string new_node_name = graph_.GenerateNodeName("Memcpy");
const auto op_name = is_input ? "MemcpyFromHost" : "MemcpyToHost";
auto& new_node = graph_.AddNode(new_node_name, op_name, "Copy from/to host memory",
std::vector<onnxruntime::NodeArg*>{src_arg},
std::vector<onnxruntime::NodeArg*>{dst_arg});
new_node.SetExecutionProviderType(provider_);
std::map<const onnxruntime::NodeArg*, onnxruntime::NodeArg*> map = {{arg, new_arg}};
auto it = provider_input_nodes_.find(arg);
if (it != provider_input_nodes_.end()) {
for (auto* node : it->second)
node->ReplaceDefs(map);
}
it = provider_output_nodes_.find(arg);
if (it != provider_output_nodes_.end()) {
for (auto* node : it->second)
node->ReplaceDefs(map);
}
}
template <typename NodeArgSetType>
static const onnxruntime::NodeArg* FindNodeArg(const NodeArgSetType& def_set, const std::string& name) {
NodeArg def(name, nullptr);
auto it = def_set.find(&def); // this works since we use name to compare NodeArg
if (it != def_set.end())
return *it;
return nullptr;
}
// We duplicate any initializer that is used by both provider nodes and non-provider nodes
// to ensure that provider nodes and non-provider nodes don't share initializers, as they
// need to stay in different memory locations.
void TransformerMemcpyImpl::ProcessInitializers(const KernelRegistryManager& kernel_registries) {
std::map<const onnxruntime::NodeArg*, onnxruntime::NodeArg*> replacements;
for (const auto& pair : graph_.GetAllInitializedTensors()) {
const auto& name = pair.first;
const onnxruntime::NodeArg* provider_def = FindNodeArg(provider_input_defs_, name);
const onnxruntime::NodeArg* non_provider_def = FindNodeArg(non_provider_input_defs_, name);
if (provider_def != nullptr && non_provider_def != nullptr) {
std::string new_def_name = graph_.GenerateNodeArgName(name);
auto& new_def = graph_.GetOrCreateNodeArg(new_def_name, provider_def->TypeAsProto());
const TensorProto* tensor_proto = nullptr;
bool found = graph_.GetInitializedTensor(name, tensor_proto);
ORT_ENFORCE(found, "Failed to get initialized tensor ", name);
TensorProto new_tensor_proto = *tensor_proto;
*(new_tensor_proto.mutable_name()) = new_def_name;
graph_.AddInitializedTensor(new_tensor_proto);
replacements.insert(std::make_pair(provider_def, &new_def));
}
}
for (auto p_node : provider_nodes_) {
// make a copy of replacement map as the node may exclude mapping for InputDefs with MemTypeOnCpuExplicitly
auto dup_replacements = replacements;
const KernelCreateInfo* kci = nullptr;
kernel_registries.SearchKernelRegistry(*p_node, &kci);
p_node->ForEachWithIndex(
p_node->InputDefs(),
[kci, &dup_replacements](const onnxruntime::NodeArg& arg, size_t index) {
if (kci && MemTypeOnCpuExplicitly(kci->kernel_def->InputMemoryType(index)))
dup_replacements.erase(&arg);
return Status::OK();
});
// normally initializers are only inputs, but things may change with ops like assign
p_node->ForEachWithIndex(
p_node->OutputDefs(),
[kci, &dup_replacements](const onnxruntime::NodeArg& arg, size_t index) {
if (kci && MemTypeOnCpuExplicitly(kci->kernel_def->OutputMemoryType(index))) {
ORT_ENFORCE(dup_replacements.find(&arg) == dup_replacements.end());
}
return Status::OK();
});
p_node->ReplaceDefs(dup_replacements);
}
}
} // namespace onnxruntime
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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 "otbVectorDataFileReader.h"
#include "otbImageFileWriter.h"
#include "otbVectorData.h"
#include "otbVectorDataProjectionFilter.h"
#include <fstream>
#include <iostream>
#include "itkRGBAPixel.h"
#include "otbImage.h"
#include "otbVectorDataToMapFilter.h"
int otbVectorDataToMapFilter(int itkNotUsed(argc), char * itkNotUsed(argv) [])
{
if (argc < 4)
{
std::cout << argv[0] << " <input vector filename> <input image filename> <font filename>" << std::endl;
return EXIT_FAILURE;
}
//Read the vector data
typedef otb::VectorData<> VectorDataType;
typedef otb::VectorDataFileReader<VectorDataType> VectorDataFileReaderType;
VectorDataFileReaderType::Pointer reader = VectorDataFileReaderType::New();
reader->SetFileName(argv[1]);
//Reproject the vector data in the proper projection
typedef otb::VectorDataProjectionFilter<VectorDataType, VectorDataType> ProjectionFilterType;
ProjectionFilterType::Pointer projection = ProjectionFilterType::New();
projection->SetInput(reader->GetOutput());
std::string projectionRefWkt =
"PROJCS[\"UTM Zone 31, Northern Hemisphere\", GEOGCS[\"WGS 84\", DATUM[\"WGS_1984\", SPHEROID[\"WGS 84\", 6378137, 298.257223563, AUTHORITY[\"EPSG\",\"7030\"]], TOWGS84[0, 0, 0, 0, 0, 0, 0], AUTHORITY[\"EPSG\",\"6326\"]], PRIMEM[\"Greenwich\", 0, AUTHORITY[\"EPSG\",\"8901\"]], UNIT[\"degree\", 0.0174532925199433, AUTHORITY[\"EPSG\",\"9108\"]], AXIS[\"Lat\", NORTH], AXIS[\"Long\", EAST], AUTHORITY[\"EPSG\",\"4326\"]], PROJECTION[\"Transverse_Mercator\"], PARAMETER[\"latitude_of_origin\", 0], PARAMETER[\"central_meridian\", 3], PARAMETER[\"scale_factor\", 0.9996], PARAMETER[\"false_easting\", 500000], PARAMETER[\"false_northing\", 0], UNIT[\"Meter\", 1]]";
projection->SetOutputProjectionRef(projectionRefWkt);
//Convert the vector data into an image
typedef itk::RGBAPixel<unsigned char> PixelType;
typedef otb::Image<PixelType, 2> ImageType;
ImageType::SizeType size;
size[0] = 500;
size[1] = 500;
ImageType::PointType origin;
origin[0] = 374149.980555821; //UL easting
origin[1] = 4829183.99443839; //UL northing
ImageType::SpacingType spacing;
spacing[0] = 0.6;
spacing[1] = -0.6;
typedef otb::RemoteSensingRegion<double> RegionType;
RegionType region;
RegionType::SizeType sizeInUnit;
sizeInUnit[0] = size[0] * spacing[0];
sizeInUnit[1] = size[1] * spacing[1];
region.SetSize(sizeInUnit);
region.SetOrigin(origin);
region.SetRegionProjection(projectionRefWkt);
typedef otb::VectorDataExtractROI<VectorDataType> ExtractROIType;
ExtractROIType::Pointer extractROI = ExtractROIType::New();
extractROI->SetRegion(region);
extractROI->SetInput(projection->GetOutput());
typedef otb::VectorDataToMapFilter<VectorDataType, ImageType> VectorDataToMapFilterType;
VectorDataToMapFilterType::Pointer vectorDataRendering = VectorDataToMapFilterType::New();
vectorDataRendering->SetInput(extractROI->GetOutput());
vectorDataRendering->SetSize(size);
vectorDataRendering->SetOrigin(origin);
vectorDataRendering->SetSpacing(spacing);
vectorDataRendering->SetFontFileName(argv[3]);
vectorDataRendering->AddStyle("minor-roads-casing");
vectorDataRendering->AddStyle("roads-text");
//Save the image in a file
typedef otb::ImageFileWriter<ImageType> WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput(vectorDataRendering->GetOutput());
writer->SetFileName(argv[2]);
writer->Update();
return EXIT_SUCCESS;
}
int otbVectorDataToMapFilterBinary(int itkNotUsed(argc), char * itkNotUsed(argv) [])
{
if (argc < 3)
{
std::cout << argv[0] << " <input vector filename> <input image filename>" << std::endl;
return EXIT_FAILURE;
}
//Read the vector data
typedef otb::VectorData<> VectorDataType;
typedef otb::VectorDataFileReader<VectorDataType> VectorDataFileReaderType;
VectorDataFileReaderType::Pointer reader = VectorDataFileReaderType::New();
reader->SetFileName(argv[1]);
//Reproject the vector data in the proper projection
typedef otb::VectorDataProjectionFilter<VectorDataType, VectorDataType> ProjectionFilterType;
ProjectionFilterType::Pointer projection = ProjectionFilterType::New();
projection->SetInput(reader->GetOutput());
std::string projectionRefWkt =
"PROJCS[\"UTM Zone 31, Northern Hemisphere\", GEOGCS[\"WGS 84\", DATUM[\"WGS_1984\", SPHEROID[\"WGS 84\", 6378137, 298.257223563, AUTHORITY[\"EPSG\",\"7030\"]], TOWGS84[0, 0, 0, 0, 0, 0, 0], AUTHORITY[\"EPSG\",\"6326\"]], PRIMEM[\"Greenwich\", 0, AUTHORITY[\"EPSG\",\"8901\"]], UNIT[\"degree\", 0.0174532925199433, AUTHORITY[\"EPSG\",\"9108\"]], AXIS[\"Lat\", NORTH], AXIS[\"Long\", EAST], AUTHORITY[\"EPSG\",\"4326\"]], PROJECTION[\"Transverse_Mercator\"], PARAMETER[\"latitude_of_origin\", 0], PARAMETER[\"central_meridian\", 3], PARAMETER[\"scale_factor\", 0.9996], PARAMETER[\"false_easting\", 500000], PARAMETER[\"false_northing\", 0], UNIT[\"Meter\", 1]]";
projection->SetOutputProjectionRef(projectionRefWkt);
//Convert the vector data into an image
typedef itk::RGBAPixel<unsigned char> PixelType;
typedef otb::Image<PixelType, 2> ImageType;
ImageType::SizeType size;
size[0] = 500;
size[1] = 500;
ImageType::PointType origin;
origin[0] = 374149.980555821; //UL easting
origin[1] = 4829183.99443839; //UL northing
ImageType::SpacingType spacing;
spacing[0] = 0.6;
spacing[1] = -0.6;
typedef otb::RemoteSensingRegion<double> RegionType;
RegionType region;
RegionType::SizeType sizeInUnit;
sizeInUnit[0] = size[0] * spacing[0];
sizeInUnit[1] = size[1] * spacing[1];
region.SetSize(sizeInUnit);
region.SetOrigin(origin);
region.SetRegionProjection(projectionRefWkt);
typedef otb::VectorDataExtractROI<VectorDataType> ExtractROIType;
ExtractROIType::Pointer extractROI = ExtractROIType::New();
extractROI->SetRegion(region);
extractROI->SetInput(projection->GetOutput());
typedef otb::VectorDataToMapFilter<VectorDataType, ImageType> VectorDataToMapFilterType;
VectorDataToMapFilterType::Pointer vectorDataRendering = VectorDataToMapFilterType::New();
vectorDataRendering->SetInput(extractROI->GetOutput());
vectorDataRendering->SetSize(size);
vectorDataRendering->SetOrigin(origin);
vectorDataRendering->SetSpacing(spacing);
vectorDataRendering->SetRenderingStyleType(VectorDataToMapFilterType::Binary);
//Save the image in a file
typedef otb::ImageFileWriter<ImageType> WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput(vectorDataRendering->GetOutput());
writer->SetFileName(argv[2]);
writer->Update();
return EXIT_SUCCESS;
}
<commit_msg>BUG: remove itkNotUsed as the arguments are really used<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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 "otbVectorDataFileReader.h"
#include "otbImageFileWriter.h"
#include "otbVectorData.h"
#include "otbVectorDataProjectionFilter.h"
#include <fstream>
#include <iostream>
#include "itkRGBAPixel.h"
#include "otbImage.h"
#include "otbVectorDataToMapFilter.h"
int otbVectorDataToMapFilter(int argc, char* argv [])
{
if (argc < 4)
{
std::cout << argv[0] << " <input vector filename> <input image filename> <font filename>" << std::endl;
return EXIT_FAILURE;
}
//Read the vector data
typedef otb::VectorData<> VectorDataType;
typedef otb::VectorDataFileReader<VectorDataType> VectorDataFileReaderType;
VectorDataFileReaderType::Pointer reader = VectorDataFileReaderType::New();
reader->SetFileName(argv[1]);
//Reproject the vector data in the proper projection
typedef otb::VectorDataProjectionFilter<VectorDataType, VectorDataType> ProjectionFilterType;
ProjectionFilterType::Pointer projection = ProjectionFilterType::New();
projection->SetInput(reader->GetOutput());
std::string projectionRefWkt =
"PROJCS[\"UTM Zone 31, Northern Hemisphere\", GEOGCS[\"WGS 84\", DATUM[\"WGS_1984\", SPHEROID[\"WGS 84\", 6378137, 298.257223563, AUTHORITY[\"EPSG\",\"7030\"]], TOWGS84[0, 0, 0, 0, 0, 0, 0], AUTHORITY[\"EPSG\",\"6326\"]], PRIMEM[\"Greenwich\", 0, AUTHORITY[\"EPSG\",\"8901\"]], UNIT[\"degree\", 0.0174532925199433, AUTHORITY[\"EPSG\",\"9108\"]], AXIS[\"Lat\", NORTH], AXIS[\"Long\", EAST], AUTHORITY[\"EPSG\",\"4326\"]], PROJECTION[\"Transverse_Mercator\"], PARAMETER[\"latitude_of_origin\", 0], PARAMETER[\"central_meridian\", 3], PARAMETER[\"scale_factor\", 0.9996], PARAMETER[\"false_easting\", 500000], PARAMETER[\"false_northing\", 0], UNIT[\"Meter\", 1]]";
projection->SetOutputProjectionRef(projectionRefWkt);
//Convert the vector data into an image
typedef itk::RGBAPixel<unsigned char> PixelType;
typedef otb::Image<PixelType, 2> ImageType;
ImageType::SizeType size;
size[0] = 500;
size[1] = 500;
ImageType::PointType origin;
origin[0] = 374149.980555821; //UL easting
origin[1] = 4829183.99443839; //UL northing
ImageType::SpacingType spacing;
spacing[0] = 0.6;
spacing[1] = -0.6;
typedef otb::RemoteSensingRegion<double> RegionType;
RegionType region;
RegionType::SizeType sizeInUnit;
sizeInUnit[0] = size[0] * spacing[0];
sizeInUnit[1] = size[1] * spacing[1];
region.SetSize(sizeInUnit);
region.SetOrigin(origin);
region.SetRegionProjection(projectionRefWkt);
typedef otb::VectorDataExtractROI<VectorDataType> ExtractROIType;
ExtractROIType::Pointer extractROI = ExtractROIType::New();
extractROI->SetRegion(region);
extractROI->SetInput(projection->GetOutput());
typedef otb::VectorDataToMapFilter<VectorDataType, ImageType> VectorDataToMapFilterType;
VectorDataToMapFilterType::Pointer vectorDataRendering = VectorDataToMapFilterType::New();
vectorDataRendering->SetInput(extractROI->GetOutput());
vectorDataRendering->SetSize(size);
vectorDataRendering->SetOrigin(origin);
vectorDataRendering->SetSpacing(spacing);
vectorDataRendering->SetFontFileName(argv[3]);
vectorDataRendering->AddStyle("minor-roads-casing");
vectorDataRendering->AddStyle("roads-text");
//Save the image in a file
typedef otb::ImageFileWriter<ImageType> WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput(vectorDataRendering->GetOutput());
writer->SetFileName(argv[2]);
writer->Update();
return EXIT_SUCCESS;
}
int otbVectorDataToMapFilterBinary(int argc, char* argv [])
{
if (argc < 3)
{
std::cout << argv[0] << " <input vector filename> <input image filename>" << std::endl;
return EXIT_FAILURE;
}
//Read the vector data
typedef otb::VectorData<> VectorDataType;
typedef otb::VectorDataFileReader<VectorDataType> VectorDataFileReaderType;
VectorDataFileReaderType::Pointer reader = VectorDataFileReaderType::New();
reader->SetFileName(argv[1]);
//Reproject the vector data in the proper projection
typedef otb::VectorDataProjectionFilter<VectorDataType, VectorDataType> ProjectionFilterType;
ProjectionFilterType::Pointer projection = ProjectionFilterType::New();
projection->SetInput(reader->GetOutput());
std::string projectionRefWkt =
"PROJCS[\"UTM Zone 31, Northern Hemisphere\", GEOGCS[\"WGS 84\", DATUM[\"WGS_1984\", SPHEROID[\"WGS 84\", 6378137, 298.257223563, AUTHORITY[\"EPSG\",\"7030\"]], TOWGS84[0, 0, 0, 0, 0, 0, 0], AUTHORITY[\"EPSG\",\"6326\"]], PRIMEM[\"Greenwich\", 0, AUTHORITY[\"EPSG\",\"8901\"]], UNIT[\"degree\", 0.0174532925199433, AUTHORITY[\"EPSG\",\"9108\"]], AXIS[\"Lat\", NORTH], AXIS[\"Long\", EAST], AUTHORITY[\"EPSG\",\"4326\"]], PROJECTION[\"Transverse_Mercator\"], PARAMETER[\"latitude_of_origin\", 0], PARAMETER[\"central_meridian\", 3], PARAMETER[\"scale_factor\", 0.9996], PARAMETER[\"false_easting\", 500000], PARAMETER[\"false_northing\", 0], UNIT[\"Meter\", 1]]";
projection->SetOutputProjectionRef(projectionRefWkt);
//Convert the vector data into an image
typedef itk::RGBAPixel<unsigned char> PixelType;
typedef otb::Image<PixelType, 2> ImageType;
ImageType::SizeType size;
size[0] = 500;
size[1] = 500;
ImageType::PointType origin;
origin[0] = 374149.980555821; //UL easting
origin[1] = 4829183.99443839; //UL northing
ImageType::SpacingType spacing;
spacing[0] = 0.6;
spacing[1] = -0.6;
typedef otb::RemoteSensingRegion<double> RegionType;
RegionType region;
RegionType::SizeType sizeInUnit;
sizeInUnit[0] = size[0] * spacing[0];
sizeInUnit[1] = size[1] * spacing[1];
region.SetSize(sizeInUnit);
region.SetOrigin(origin);
region.SetRegionProjection(projectionRefWkt);
typedef otb::VectorDataExtractROI<VectorDataType> ExtractROIType;
ExtractROIType::Pointer extractROI = ExtractROIType::New();
extractROI->SetRegion(region);
extractROI->SetInput(projection->GetOutput());
typedef otb::VectorDataToMapFilter<VectorDataType, ImageType> VectorDataToMapFilterType;
VectorDataToMapFilterType::Pointer vectorDataRendering = VectorDataToMapFilterType::New();
vectorDataRendering->SetInput(extractROI->GetOutput());
vectorDataRendering->SetSize(size);
vectorDataRendering->SetOrigin(origin);
vectorDataRendering->SetSpacing(spacing);
vectorDataRendering->SetRenderingStyleType(VectorDataToMapFilterType::Binary);
//Save the image in a file
typedef otb::ImageFileWriter<ImageType> WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput(vectorDataRendering->GetOutput());
writer->SetFileName(argv[2]);
writer->Update();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: ThinPlateSplinesApplication.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#include "ThinPlateSplinesApplication.h"
ThinPlateSplinesApplication
::ThinPlateSplinesApplication()
{
}
ThinPlateSplinesApplication
::~ThinPlateSplinesApplication()
{
}
void
ThinPlateSplinesApplication
::CreateLandMarks()
{
this->ThinPlateSplinesApplicationBase::CreateLandMarks();
targetLandMarkIdCounter->range( 0, m_TargetLandMarks.size()-1 );
sourceLandMarkIdCounter->range( 0, m_TargetLandMarks.size()-1 );
}
void
ThinPlateSplinesApplication
::MapPoints()
{
this->ThinPlateSplinesApplicationBase::MapPoints();
this->DisplayPoints();
m_FlRenderWindowInteractor->redraw();
Fl::check();
}
void
ThinPlateSplinesApplication
::DisplayLandMarks()
{
this->ThinPlateSplinesApplicationBase::DisplayLandMarks();
m_FlRenderWindowInteractor->redraw();
Fl::check();
}
void
ThinPlateSplinesApplication
::UpdateSelectedTargetLandMark()
{
const unsigned int landMarkId = targetLandMarkIdCounter->value();
const CoordinateRepresentationType x = xTargetValueInput->value();
const CoordinateRepresentationType y = yTargetValueInput->value();
const CoordinateRepresentationType z = zTargetValueInput->value();
m_TargetLandMarks[ landMarkId ][0] = x;
m_TargetLandMarks[ landMarkId ][1] = y;
m_TargetLandMarks[ landMarkId ][2] = z;
this->DisplayLandMarks();
m_FlRenderWindowInteractor->redraw();
Fl::check();
}
void
ThinPlateSplinesApplication
::SelectTargetLandMark()
{
const unsigned int landMarkId = targetLandMarkIdCounter->value();
const CoordinateRepresentationType x = m_TargetLandMarks[ landMarkId ][0];
const CoordinateRepresentationType y = m_TargetLandMarks[ landMarkId ][1];
const CoordinateRepresentationType z = m_TargetLandMarks[ landMarkId ][2];
xTargetValueInput->value( x );
yTargetValueInput->value( y );
zTargetValueInput->value( z );
Fl::check();
}
void
ThinPlateSplinesApplication
::UpdateSelectedSourceLandMark()
{
const unsigned int landMarkId = sourceLandMarkIdCounter->value();
const CoordinateRepresentationType x = xSourceValueInput->value();
const CoordinateRepresentationType y = ySourceValueInput->value();
const CoordinateRepresentationType z = zSourceValueInput->value();
m_SourceLandMarks[ landMarkId ][0] = x;
m_SourceLandMarks[ landMarkId ][1] = y;
m_SourceLandMarks[ landMarkId ][2] = z;
this->DisplayLandMarks();
m_FlRenderWindowInteractor->redraw();
Fl::check();
}
void
ThinPlateSplinesApplication
::SelectSourceLandMark()
{
const unsigned int landMarkId = sourceLandMarkIdCounter->value();
const CoordinateRepresentationType x = m_SourceLandMarks[ landMarkId ][0];
const CoordinateRepresentationType y = m_SourceLandMarks[ landMarkId ][1];
const CoordinateRepresentationType z = m_SourceLandMarks[ landMarkId ][2];
xSourceValueInput->value( x );
ySourceValueInput->value( y );
zSourceValueInput->value( z );
Fl::check();
}
<commit_msg>ENH: cast from double to unsigned int added.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: ThinPlateSplinesApplication.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#include "ThinPlateSplinesApplication.h"
ThinPlateSplinesApplication
::ThinPlateSplinesApplication()
{
}
ThinPlateSplinesApplication
::~ThinPlateSplinesApplication()
{
}
void
ThinPlateSplinesApplication
::CreateLandMarks()
{
this->ThinPlateSplinesApplicationBase::CreateLandMarks();
targetLandMarkIdCounter->range( 0, m_TargetLandMarks.size()-1 );
sourceLandMarkIdCounter->range( 0, m_TargetLandMarks.size()-1 );
}
void
ThinPlateSplinesApplication
::MapPoints()
{
this->ThinPlateSplinesApplicationBase::MapPoints();
this->DisplayPoints();
m_FlRenderWindowInteractor->redraw();
Fl::check();
}
void
ThinPlateSplinesApplication
::DisplayLandMarks()
{
this->ThinPlateSplinesApplicationBase::DisplayLandMarks();
m_FlRenderWindowInteractor->redraw();
Fl::check();
}
void
ThinPlateSplinesApplication
::UpdateSelectedTargetLandMark()
{
const unsigned int landMarkId =
static_cast<unsigned int>( targetLandMarkIdCounter->value() );
const CoordinateRepresentationType x = xTargetValueInput->value();
const CoordinateRepresentationType y = yTargetValueInput->value();
const CoordinateRepresentationType z = zTargetValueInput->value();
m_TargetLandMarks[ landMarkId ][0] = x;
m_TargetLandMarks[ landMarkId ][1] = y;
m_TargetLandMarks[ landMarkId ][2] = z;
this->DisplayLandMarks();
m_FlRenderWindowInteractor->redraw();
Fl::check();
}
void
ThinPlateSplinesApplication
::SelectTargetLandMark()
{
const unsigned int landMarkId = targetLandMarkIdCounter->value();
const CoordinateRepresentationType x = m_TargetLandMarks[ landMarkId ][0];
const CoordinateRepresentationType y = m_TargetLandMarks[ landMarkId ][1];
const CoordinateRepresentationType z = m_TargetLandMarks[ landMarkId ][2];
xTargetValueInput->value( x );
yTargetValueInput->value( y );
zTargetValueInput->value( z );
Fl::check();
}
void
ThinPlateSplinesApplication
::UpdateSelectedSourceLandMark()
{
const unsigned int landMarkId = sourceLandMarkIdCounter->value();
const CoordinateRepresentationType x = xSourceValueInput->value();
const CoordinateRepresentationType y = ySourceValueInput->value();
const CoordinateRepresentationType z = zSourceValueInput->value();
m_SourceLandMarks[ landMarkId ][0] = x;
m_SourceLandMarks[ landMarkId ][1] = y;
m_SourceLandMarks[ landMarkId ][2] = z;
this->DisplayLandMarks();
m_FlRenderWindowInteractor->redraw();
Fl::check();
}
void
ThinPlateSplinesApplication
::SelectSourceLandMark()
{
const unsigned int landMarkId = sourceLandMarkIdCounter->value();
const CoordinateRepresentationType x = m_SourceLandMarks[ landMarkId ][0];
const CoordinateRepresentationType y = m_SourceLandMarks[ landMarkId ][1];
const CoordinateRepresentationType z = m_SourceLandMarks[ landMarkId ][2];
xSourceValueInput->value( x );
ySourceValueInput->value( y );
zSourceValueInput->value( z );
Fl::check();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: vclxaccessiblebutton.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2007-06-27 15:37:06 $
*
* 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_accessibility.hxx"
// includes --------------------------------------------------------------
#ifndef ACCESSIBILITY_STANDARD_VCLXACCESSIBLEBUTTON_HXX
#include <accessibility/standard/vclxaccessiblebutton.hxx>
#endif
#ifndef ACCESSIBILITY_HELPER_TKARESMGR_HXX
#include <accessibility/helper/accresmgr.hxx>
#endif
#ifndef ACCESSIBILITY_HELPER_ACCESSIBLESTRINGS_HRC_
#include <accessibility/helper/accessiblestrings.hrc>
#endif
#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX
#include <unotools/accessiblestatesethelper.hxx>
#endif
#ifndef COMPHELPER_ACCESSIBLE_KEYBINDING_HELPER_HXX
#include <comphelper/accessiblekeybindinghelper.hxx>
#endif
#ifndef _COM_SUN_STAR_AWT_KEYMODIFIER_HPP_
#include <com/sun/star/awt/KeyModifier.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_STANDARD_ACCESSIBLESTATETYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_STANDARD_ACCESSIBLEEVENTID_HPP_
#include <com/sun/star/accessibility/AccessibleEventId.hpp>
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX
#include <comphelper/sequence.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::accessibility;
using namespace ::comphelper;
// -----------------------------------------------------------------------------
// VCLXAccessibleButton
// -----------------------------------------------------------------------------
VCLXAccessibleButton::VCLXAccessibleButton( VCLXWindow* pVCLWindow )
:VCLXAccessibleTextComponent( pVCLWindow )
{
}
// -----------------------------------------------------------------------------
VCLXAccessibleButton::~VCLXAccessibleButton()
{
}
// -----------------------------------------------------------------------------
void VCLXAccessibleButton::ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent )
{
switch ( rVclWindowEvent.GetId() )
{
case VCLEVENT_PUSHBUTTON_TOGGLE:
{
Any aOldValue;
Any aNewValue;
PushButton* pButton = (PushButton*) GetWindow();
if ( pButton && pButton->GetState() == STATE_CHECK )
aNewValue <<= AccessibleStateType::CHECKED;
else
aOldValue <<= AccessibleStateType::CHECKED;
NotifyAccessibleEvent( AccessibleEventId::STATE_CHANGED, aOldValue, aNewValue );
}
break;
default:
VCLXAccessibleTextComponent::ProcessWindowEvent( rVclWindowEvent );
}
}
// -----------------------------------------------------------------------------
void VCLXAccessibleButton::FillAccessibleStateSet( utl::AccessibleStateSetHelper& rStateSet )
{
VCLXAccessibleTextComponent::FillAccessibleStateSet( rStateSet );
PushButton* pButton = (PushButton*) GetWindow();
if ( pButton )
{
rStateSet.AddState( AccessibleStateType::FOCUSABLE );
if ( pButton->GetState() == STATE_CHECK )
rStateSet.AddState( AccessibleStateType::CHECKED );
if ( pButton->IsPressed() )
rStateSet.AddState( AccessibleStateType::PRESSED );
}
}
// -----------------------------------------------------------------------------
// XInterface
// -----------------------------------------------------------------------------
IMPLEMENT_FORWARD_XINTERFACE2( VCLXAccessibleButton, VCLXAccessibleTextComponent, VCLXAccessibleButton_BASE )
// -----------------------------------------------------------------------------
// XTypeProvider
// -----------------------------------------------------------------------------
IMPLEMENT_FORWARD_XTYPEPROVIDER2( VCLXAccessibleButton, VCLXAccessibleTextComponent, VCLXAccessibleButton_BASE )
// -----------------------------------------------------------------------------
// XServiceInfo
// -----------------------------------------------------------------------------
::rtl::OUString VCLXAccessibleButton::getImplementationName() throw (RuntimeException)
{
return ::rtl::OUString::createFromAscii( "com.sun.star.comp.toolkit.AccessibleButton" );
}
// -----------------------------------------------------------------------------
Sequence< ::rtl::OUString > VCLXAccessibleButton::getSupportedServiceNames() throw (RuntimeException)
{
Sequence< ::rtl::OUString > aNames(1);
aNames[0] = ::rtl::OUString::createFromAscii( "com.sun.star.awt.AccessibleButton" );
return aNames;
}
// -----------------------------------------------------------------------------
// XAccessibleContext
// -----------------------------------------------------------------------------
::rtl::OUString VCLXAccessibleButton::getAccessibleName( ) throw (RuntimeException)
{
OExternalLockGuard aGuard( this );
::rtl::OUString aName( VCLXAccessibleTextComponent::getAccessibleName() );
sal_Int32 nLength = aName.getLength();
if ( nLength >= 3 && aName.matchAsciiL( RTL_CONSTASCII_STRINGPARAM("..."), nLength - 3 ) )
{
if ( nLength == 3 )
{
// it's a browse button
aName = ::rtl::OUString( TK_RES_STRING( RID_STR_ACC_NAME_BROWSEBUTTON ) );
}
else
{
// remove the three trailing dots
aName = aName.copy( 0, nLength - 3 );
}
}
else if ( nLength >= 3 && aName.matchAsciiL( RTL_CONSTASCII_STRINGPARAM("<< "), 0 ) )
{
// remove the leading symbols
aName = aName.copy( 3, nLength - 3 );
}
else if ( nLength >= 3 && aName.matchAsciiL( RTL_CONSTASCII_STRINGPARAM(" >>"), nLength - 3 ) )
{
// remove the trailing symbols
aName = aName.copy( 0, nLength - 3 );
}
return aName;
}
// -----------------------------------------------------------------------------
// XAccessibleAction
// -----------------------------------------------------------------------------
sal_Int32 VCLXAccessibleButton::getAccessibleActionCount( ) throw (RuntimeException)
{
OExternalLockGuard aGuard( this );
return 1;
}
// -----------------------------------------------------------------------------
sal_Bool VCLXAccessibleButton::doAccessibleAction ( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException)
{
OExternalLockGuard aGuard( this );
if ( nIndex < 0 || nIndex >= getAccessibleActionCount() )
throw IndexOutOfBoundsException();
PushButton* pButton = (PushButton*) GetWindow();
if ( pButton )
pButton->Click();
return sal_True;
}
// -----------------------------------------------------------------------------
::rtl::OUString VCLXAccessibleButton::getAccessibleActionDescription ( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException)
{
OExternalLockGuard aGuard( this );
if ( nIndex < 0 || nIndex >= getAccessibleActionCount() )
throw IndexOutOfBoundsException();
return ::rtl::OUString( TK_RES_STRING( RID_STR_ACC_ACTION_CLICK ) );
}
// -----------------------------------------------------------------------------
Reference< XAccessibleKeyBinding > VCLXAccessibleButton::getAccessibleActionKeyBinding( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException)
{
OExternalLockGuard aGuard( this );
if ( nIndex < 0 || nIndex >= getAccessibleActionCount() )
throw IndexOutOfBoundsException();
OAccessibleKeyBindingHelper* pKeyBindingHelper = new OAccessibleKeyBindingHelper();
Reference< XAccessibleKeyBinding > xKeyBinding = pKeyBindingHelper;
Window* pWindow = GetWindow();
if ( pWindow )
{
KeyEvent aKeyEvent = pWindow->GetActivationKey();
KeyCode aKeyCode = aKeyEvent.GetKeyCode();
if ( aKeyCode.GetCode() != 0 )
{
awt::KeyStroke aKeyStroke;
aKeyStroke.Modifiers = 0;
if ( aKeyCode.IsShift() )
aKeyStroke.Modifiers |= awt::KeyModifier::SHIFT;
if ( aKeyCode.IsMod1() )
aKeyStroke.Modifiers |= awt::KeyModifier::MOD1;
if ( aKeyCode.IsMod2() )
aKeyStroke.Modifiers |= awt::KeyModifier::MOD2;
aKeyStroke.KeyCode = aKeyCode.GetCode();
aKeyStroke.KeyChar = aKeyEvent.GetCharCode();
aKeyStroke.KeyFunc = static_cast< sal_Int16 >( aKeyCode.GetFunction() );
pKeyBindingHelper->AddKeyBinding( aKeyStroke );
}
}
return xKeyBinding;
}
// -----------------------------------------------------------------------------
// XAccessibleValue
// -----------------------------------------------------------------------------
Any VCLXAccessibleButton::getCurrentValue( ) throw (RuntimeException)
{
OExternalLockGuard aGuard( this );
Any aValue;
PushButton* pButton = (PushButton*) GetWindow();
if ( pButton )
aValue <<= (sal_Int32) pButton->IsPressed();
return aValue;
}
// -----------------------------------------------------------------------------
sal_Bool VCLXAccessibleButton::setCurrentValue( const Any& aNumber ) throw (RuntimeException)
{
OExternalLockGuard aGuard( this );
sal_Bool bReturn = sal_False;
PushButton* pButton = (PushButton*) GetWindow();
if ( pButton )
{
sal_Int32 nValue = 0;
OSL_VERIFY( aNumber >>= nValue );
if ( nValue < 0 )
nValue = 0;
else if ( nValue > 1 )
nValue = 1;
pButton->SetPressed( (BOOL) nValue );
bReturn = sal_True;
}
return bReturn;
}
// -----------------------------------------------------------------------------
Any VCLXAccessibleButton::getMaximumValue( ) throw (RuntimeException)
{
OExternalLockGuard aGuard( this );
Any aValue;
aValue <<= (sal_Int32) 1;
return aValue;
}
// -----------------------------------------------------------------------------
Any VCLXAccessibleButton::getMinimumValue( ) throw (RuntimeException)
{
OExternalLockGuard aGuard( this );
Any aValue;
aValue <<= (sal_Int32) 0;
return aValue;
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS changefileheader (1.2.44); FILE MERGED 2008/04/01 19:53:11 thb 1.2.44.4: #i85898# Stripping all external header guards, now manually fixing misspelled ones and other compile-time breakage 2008/04/01 14:58:58 thb 1.2.44.3: #i85898# Stripping all external header guards 2008/04/01 10:45:56 thb 1.2.44.2: #i85898# Stripping all external header guards 2008/03/28 15:57:53 rt 1.2.44.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: vclxaccessiblebutton.cxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_accessibility.hxx"
// includes --------------------------------------------------------------
#include <accessibility/standard/vclxaccessiblebutton.hxx>
#include <accessibility/helper/accresmgr.hxx>
#include <accessibility/helper/accessiblestrings.hrc>
#include <unotools/accessiblestatesethelper.hxx>
#include <comphelper/accessiblekeybindinghelper.hxx>
#include <com/sun/star/awt/KeyModifier.hpp>
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#include <com/sun/star/accessibility/AccessibleEventId.hpp>
#include <cppuhelper/typeprovider.hxx>
#include <comphelper/sequence.hxx>
#include <vcl/button.hxx>
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::accessibility;
using namespace ::comphelper;
// -----------------------------------------------------------------------------
// VCLXAccessibleButton
// -----------------------------------------------------------------------------
VCLXAccessibleButton::VCLXAccessibleButton( VCLXWindow* pVCLWindow )
:VCLXAccessibleTextComponent( pVCLWindow )
{
}
// -----------------------------------------------------------------------------
VCLXAccessibleButton::~VCLXAccessibleButton()
{
}
// -----------------------------------------------------------------------------
void VCLXAccessibleButton::ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent )
{
switch ( rVclWindowEvent.GetId() )
{
case VCLEVENT_PUSHBUTTON_TOGGLE:
{
Any aOldValue;
Any aNewValue;
PushButton* pButton = (PushButton*) GetWindow();
if ( pButton && pButton->GetState() == STATE_CHECK )
aNewValue <<= AccessibleStateType::CHECKED;
else
aOldValue <<= AccessibleStateType::CHECKED;
NotifyAccessibleEvent( AccessibleEventId::STATE_CHANGED, aOldValue, aNewValue );
}
break;
default:
VCLXAccessibleTextComponent::ProcessWindowEvent( rVclWindowEvent );
}
}
// -----------------------------------------------------------------------------
void VCLXAccessibleButton::FillAccessibleStateSet( utl::AccessibleStateSetHelper& rStateSet )
{
VCLXAccessibleTextComponent::FillAccessibleStateSet( rStateSet );
PushButton* pButton = (PushButton*) GetWindow();
if ( pButton )
{
rStateSet.AddState( AccessibleStateType::FOCUSABLE );
if ( pButton->GetState() == STATE_CHECK )
rStateSet.AddState( AccessibleStateType::CHECKED );
if ( pButton->IsPressed() )
rStateSet.AddState( AccessibleStateType::PRESSED );
}
}
// -----------------------------------------------------------------------------
// XInterface
// -----------------------------------------------------------------------------
IMPLEMENT_FORWARD_XINTERFACE2( VCLXAccessibleButton, VCLXAccessibleTextComponent, VCLXAccessibleButton_BASE )
// -----------------------------------------------------------------------------
// XTypeProvider
// -----------------------------------------------------------------------------
IMPLEMENT_FORWARD_XTYPEPROVIDER2( VCLXAccessibleButton, VCLXAccessibleTextComponent, VCLXAccessibleButton_BASE )
// -----------------------------------------------------------------------------
// XServiceInfo
// -----------------------------------------------------------------------------
::rtl::OUString VCLXAccessibleButton::getImplementationName() throw (RuntimeException)
{
return ::rtl::OUString::createFromAscii( "com.sun.star.comp.toolkit.AccessibleButton" );
}
// -----------------------------------------------------------------------------
Sequence< ::rtl::OUString > VCLXAccessibleButton::getSupportedServiceNames() throw (RuntimeException)
{
Sequence< ::rtl::OUString > aNames(1);
aNames[0] = ::rtl::OUString::createFromAscii( "com.sun.star.awt.AccessibleButton" );
return aNames;
}
// -----------------------------------------------------------------------------
// XAccessibleContext
// -----------------------------------------------------------------------------
::rtl::OUString VCLXAccessibleButton::getAccessibleName( ) throw (RuntimeException)
{
OExternalLockGuard aGuard( this );
::rtl::OUString aName( VCLXAccessibleTextComponent::getAccessibleName() );
sal_Int32 nLength = aName.getLength();
if ( nLength >= 3 && aName.matchAsciiL( RTL_CONSTASCII_STRINGPARAM("..."), nLength - 3 ) )
{
if ( nLength == 3 )
{
// it's a browse button
aName = ::rtl::OUString( TK_RES_STRING( RID_STR_ACC_NAME_BROWSEBUTTON ) );
}
else
{
// remove the three trailing dots
aName = aName.copy( 0, nLength - 3 );
}
}
else if ( nLength >= 3 && aName.matchAsciiL( RTL_CONSTASCII_STRINGPARAM("<< "), 0 ) )
{
// remove the leading symbols
aName = aName.copy( 3, nLength - 3 );
}
else if ( nLength >= 3 && aName.matchAsciiL( RTL_CONSTASCII_STRINGPARAM(" >>"), nLength - 3 ) )
{
// remove the trailing symbols
aName = aName.copy( 0, nLength - 3 );
}
return aName;
}
// -----------------------------------------------------------------------------
// XAccessibleAction
// -----------------------------------------------------------------------------
sal_Int32 VCLXAccessibleButton::getAccessibleActionCount( ) throw (RuntimeException)
{
OExternalLockGuard aGuard( this );
return 1;
}
// -----------------------------------------------------------------------------
sal_Bool VCLXAccessibleButton::doAccessibleAction ( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException)
{
OExternalLockGuard aGuard( this );
if ( nIndex < 0 || nIndex >= getAccessibleActionCount() )
throw IndexOutOfBoundsException();
PushButton* pButton = (PushButton*) GetWindow();
if ( pButton )
pButton->Click();
return sal_True;
}
// -----------------------------------------------------------------------------
::rtl::OUString VCLXAccessibleButton::getAccessibleActionDescription ( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException)
{
OExternalLockGuard aGuard( this );
if ( nIndex < 0 || nIndex >= getAccessibleActionCount() )
throw IndexOutOfBoundsException();
return ::rtl::OUString( TK_RES_STRING( RID_STR_ACC_ACTION_CLICK ) );
}
// -----------------------------------------------------------------------------
Reference< XAccessibleKeyBinding > VCLXAccessibleButton::getAccessibleActionKeyBinding( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException)
{
OExternalLockGuard aGuard( this );
if ( nIndex < 0 || nIndex >= getAccessibleActionCount() )
throw IndexOutOfBoundsException();
OAccessibleKeyBindingHelper* pKeyBindingHelper = new OAccessibleKeyBindingHelper();
Reference< XAccessibleKeyBinding > xKeyBinding = pKeyBindingHelper;
Window* pWindow = GetWindow();
if ( pWindow )
{
KeyEvent aKeyEvent = pWindow->GetActivationKey();
KeyCode aKeyCode = aKeyEvent.GetKeyCode();
if ( aKeyCode.GetCode() != 0 )
{
awt::KeyStroke aKeyStroke;
aKeyStroke.Modifiers = 0;
if ( aKeyCode.IsShift() )
aKeyStroke.Modifiers |= awt::KeyModifier::SHIFT;
if ( aKeyCode.IsMod1() )
aKeyStroke.Modifiers |= awt::KeyModifier::MOD1;
if ( aKeyCode.IsMod2() )
aKeyStroke.Modifiers |= awt::KeyModifier::MOD2;
aKeyStroke.KeyCode = aKeyCode.GetCode();
aKeyStroke.KeyChar = aKeyEvent.GetCharCode();
aKeyStroke.KeyFunc = static_cast< sal_Int16 >( aKeyCode.GetFunction() );
pKeyBindingHelper->AddKeyBinding( aKeyStroke );
}
}
return xKeyBinding;
}
// -----------------------------------------------------------------------------
// XAccessibleValue
// -----------------------------------------------------------------------------
Any VCLXAccessibleButton::getCurrentValue( ) throw (RuntimeException)
{
OExternalLockGuard aGuard( this );
Any aValue;
PushButton* pButton = (PushButton*) GetWindow();
if ( pButton )
aValue <<= (sal_Int32) pButton->IsPressed();
return aValue;
}
// -----------------------------------------------------------------------------
sal_Bool VCLXAccessibleButton::setCurrentValue( const Any& aNumber ) throw (RuntimeException)
{
OExternalLockGuard aGuard( this );
sal_Bool bReturn = sal_False;
PushButton* pButton = (PushButton*) GetWindow();
if ( pButton )
{
sal_Int32 nValue = 0;
OSL_VERIFY( aNumber >>= nValue );
if ( nValue < 0 )
nValue = 0;
else if ( nValue > 1 )
nValue = 1;
pButton->SetPressed( (BOOL) nValue );
bReturn = sal_True;
}
return bReturn;
}
// -----------------------------------------------------------------------------
Any VCLXAccessibleButton::getMaximumValue( ) throw (RuntimeException)
{
OExternalLockGuard aGuard( this );
Any aValue;
aValue <<= (sal_Int32) 1;
return aValue;
}
// -----------------------------------------------------------------------------
Any VCLXAccessibleButton::getMinimumValue( ) throw (RuntimeException)
{
OExternalLockGuard aGuard( this );
Any aValue;
aValue <<= (sal_Int32) 0;
return aValue;
}
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>#include "mount.hpp"
#include <server/path.hpp>
#include <fuse.h>
namespace fileserver
{
namespace
{
char const * const hello_path = "/hello";
char const * const hello_str = "Hello, fuse!\n";
int hello_getattr(const char *path, struct stat *stbuf)
{
int res = 0;
memset(stbuf, 0, sizeof(struct stat));
if (strcmp(path, "/") == 0) {
stbuf->st_mode = S_IFDIR | 0755;
stbuf->st_nlink = 2;
} else if (strcmp(path, hello_path) == 0) {
stbuf->st_mode = S_IFREG | 0444;
stbuf->st_nlink = 1;
stbuf->st_size = strlen(hello_str);
} else
res = -ENOENT;
return res;
}
static int hello_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
off_t offset, struct fuse_file_info *fi)
{
(void) offset;
(void) fi;
if (strcmp(path, "/") != 0)
return -ENOENT;
filler(buf, ".", NULL, 0);
filler(buf, "..", NULL, 0);
filler(buf, hello_path + 1, NULL, 0);
return 0;
}
static int hello_open(const char *path, struct fuse_file_info *fi)
{
if (strcmp(path, hello_path) != 0)
return -ENOENT;
if ((fi->flags & 3) != O_RDONLY)
return -EACCES;
return 0;
}
static int hello_read(const char *path, char *buf, size_t size, off_t offset,
struct fuse_file_info *fi)
{
size_t len;
(void) fi;
if(strcmp(path, hello_path) != 0)
return -ENOENT;
len = strlen(hello_str);
if (static_cast<size_t>(offset) < len) {
if (offset + size > len)
size = len - offset;
memcpy(buf, hello_str + offset, size);
} else
size = 0;
return static_cast<int>(size);
}
struct user_data_for_fuse
{
};
struct chan_deleter
{
fileserver::path mount_point;
void operator()(fuse_chan *chan) const
{
fuse_unmount(mount_point.c_str(), chan);
}
};
struct fuse_deleter
{
void operator()(fuse *f) const
{
fuse_destroy(f);
}
};
}
void mount_directory(fileserver::unknown_digest const &root_digest, boost::filesystem::path const &mount_point)
{
chan_deleter deleter;
deleter.mount_point = fileserver::path(mount_point);
fuse_args args{};
std::unique_ptr<fuse_chan, chan_deleter> chan(fuse_mount(mount_point.c_str(), &args), std::move(deleter));
if (!chan)
{
throw std::runtime_error("fuse_mount failure");
}
fuse_operations operations{};
operations.getattr = hello_getattr;
operations.readdir = hello_readdir;
operations.open = hello_open;
operations.read = hello_read;
user_data_for_fuse user_data;
std::unique_ptr<fuse, fuse_deleter> const f(fuse_new(chan.get(), &args, &operations, sizeof(operations), &user_data));
if (!f)
{
throw std::runtime_error("fuse_new failure");
}
//fuse_new seems to take ownership of the fuse_chan
chan.release();
fuse_loop(f.get());
}
}
<commit_msg>begin to design a http downloader<commit_after>#include "mount.hpp"
#include <silicium/ptr_observable.hpp>
#include <silicium/error_or.hpp>
#include <silicium/connecting_observable.hpp>
#include <silicium/coroutine.hpp>
#include <silicium/virtualized_observable.hpp>
#include <server/path.hpp>
#include <fuse.h>
namespace fileserver
{
namespace
{
using file_offset = std::intmax_t;
struct random_access_file
{
virtual ~random_access_file();
virtual Si::unique_observable<Si::error_or<std::vector<byte>>> read(file_offset begin, file_offset end) = 0;
};
random_access_file::~random_access_file()
{
}
struct file_service
{
virtual ~file_service();
virtual Si::unique_observable<Si::error_or<std::unique_ptr<random_access_file>>> open(digest const &name) = 0;
};
file_service::~file_service()
{
}
struct http_random_access_file : random_access_file
{
explicit http_random_access_file(std::unique_ptr<boost::asio::ip::tcp::socket> connection, digest const &name)
: connection(std::move(connection))
, name(name)
{
}
virtual Si::unique_observable<Si::error_or<std::vector<byte>>> read(file_offset begin, file_offset end) SILICIUM_OVERRIDE
{
throw std::logic_error("todo");
}
private:
std::unique_ptr<boost::asio::ip::tcp::socket> connection;
digest name;
};
struct http_file_service : file_service
{
explicit http_file_service(boost::asio::io_service &io, boost::asio::ip::tcp::endpoint server)
: io(&io)
, server(server)
{
}
virtual Si::unique_observable<Si::error_or<std::unique_ptr<random_access_file>>> open(digest const &name) SILICIUM_OVERRIDE
{
return Si::erase_unique(Si::make_coroutine<Si::error_or<std::unique_ptr<random_access_file>>>(std::bind(&http_file_service::open_impl, this, std::placeholders::_1, name)));
}
private:
boost::asio::io_service *io = nullptr;
boost::asio::ip::tcp::endpoint server;
void open_impl(
Si::yield_context<Si::error_or<std::unique_ptr<random_access_file>>> yield,
digest const &requested_name)
{
auto socket = Si::make_unique<boost::asio::ip::tcp::socket>(*io);
Si::connecting_observable connector(*socket, server);
boost::optional<boost::system::error_code> const ec = yield.get_one(connector);
assert(ec);
if (*ec)
{
return yield(*ec);
}
std::unique_ptr<random_access_file> file = Si::make_unique<http_random_access_file>(std::move(socket), requested_name);
yield(std::move(file));
}
};
char const * const hello_path = "/hello";
char const * const hello_str = "Hello, fuse!\n";
int hello_getattr(const char *path, struct stat *stbuf)
{
int res = 0;
memset(stbuf, 0, sizeof(struct stat));
if (strcmp(path, "/") == 0) {
stbuf->st_mode = S_IFDIR | 0755;
stbuf->st_nlink = 2;
} else if (strcmp(path, hello_path) == 0) {
stbuf->st_mode = S_IFREG | 0444;
stbuf->st_nlink = 1;
stbuf->st_size = strlen(hello_str);
} else
res = -ENOENT;
return res;
}
static int hello_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
off_t offset, struct fuse_file_info *fi)
{
(void) offset;
(void) fi;
if (strcmp(path, "/") != 0)
return -ENOENT;
filler(buf, ".", NULL, 0);
filler(buf, "..", NULL, 0);
filler(buf, hello_path + 1, NULL, 0);
return 0;
}
static int hello_open(const char *path, struct fuse_file_info *fi)
{
if (strcmp(path, hello_path) != 0)
return -ENOENT;
if ((fi->flags & 3) != O_RDONLY)
return -EACCES;
return 0;
}
static int hello_read(const char *path, char *buf, size_t size, off_t offset,
struct fuse_file_info *fi)
{
size_t len;
(void) fi;
if(strcmp(path, hello_path) != 0)
return -ENOENT;
len = strlen(hello_str);
if (static_cast<size_t>(offset) < len) {
if (offset + size > len)
size = len - offset;
memcpy(buf, hello_str + offset, size);
} else
size = 0;
return static_cast<int>(size);
}
struct user_data_for_fuse
{
};
struct chan_deleter
{
fileserver::path mount_point;
void operator()(fuse_chan *chan) const
{
fuse_unmount(mount_point.c_str(), chan);
}
};
struct fuse_deleter
{
void operator()(fuse *f) const
{
fuse_destroy(f);
}
};
}
void mount_directory(fileserver::unknown_digest const &root_digest, boost::filesystem::path const &mount_point)
{
chan_deleter deleter;
deleter.mount_point = fileserver::path(mount_point);
fuse_args args{};
std::unique_ptr<fuse_chan, chan_deleter> chan(fuse_mount(mount_point.c_str(), &args), std::move(deleter));
if (!chan)
{
throw std::runtime_error("fuse_mount failure");
}
fuse_operations operations{};
operations.getattr = hello_getattr;
operations.readdir = hello_readdir;
operations.open = hello_open;
operations.read = hello_read;
user_data_for_fuse user_data;
std::unique_ptr<fuse, fuse_deleter> const f(fuse_new(chan.get(), &args, &operations, sizeof(operations), &user_data));
if (!f)
{
throw std::runtime_error("fuse_new failure");
}
//fuse_new seems to take ownership of the fuse_chan
chan.release();
fuse_loop(f.get());
}
}
<|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 "ActiveMQCPP.h"
#include <decaf/lang/Runtime.h>
#include <activemq/wireformat/WireFormatRegistry.h>
#include <activemq/transport/TransportRegistry.h>
#include <activemq/transport/discovery/DiscoveryAgentRegistry.h>
#include <activemq/util/IdGenerator.h>
#include <activemq/wireformat/stomp/StompWireFormatFactory.h>
#include <activemq/wireformat/openwire/OpenWireFormatFactory.h>
#include <activemq/transport/mock/MockTransportFactory.h>
#include <activemq/transport/tcp/TcpTransportFactory.h>
#include <activemq/transport/tcp/SslTransportFactory.h>
#include <activemq/transport/failover/FailoverTransportFactory.h>
#include <activemq/transport/discovery/DiscoveryTransportFactory.h>
#include <activemq/transport/discovery/http/HttpDiscoveryAgentFactory.h>
using namespace activemq;
using namespace activemq::library;
using namespace activemq::util;
using namespace activemq::transport;
using namespace activemq::transport::tcp;
using namespace activemq::transport::mock;
using namespace activemq::transport::failover;
using namespace activemq::transport::discovery;
using namespace activemq::transport::discovery::http;
using namespace activemq::wireformat;
////////////////////////////////////////////////////////////////////////////////
ActiveMQCPP::ActiveMQCPP() {
}
////////////////////////////////////////////////////////////////////////////////
ActiveMQCPP::~ActiveMQCPP() {
}
////////////////////////////////////////////////////////////////////////////////
void ActiveMQCPP::initializeLibrary(int argc, char** argv) {
// Initialize the Decaf Library by requesting its runtime.
decaf::lang::Runtime::initializeRuntime(argc, argv);
// Register all WireFormats
ActiveMQCPP::registerWireFormats();
// Register all Transports
ActiveMQCPP::registerTransports();
// Start the IdGenerator Kernel
IdGenerator::initialize();
}
////////////////////////////////////////////////////////////////////////////////
void ActiveMQCPP::initializeLibrary() {
ActiveMQCPP::initializeLibrary(0, NULL);
}
////////////////////////////////////////////////////////////////////////////////
void ActiveMQCPP::shutdownLibrary() {
// Shutdown the IdGenerator Kernel
IdGenerator::shutdown();
WireFormatRegistry::shutdown();
TransportRegistry::shutdown();
DiscoveryAgentRegistry::shutdown();
// Now it should be safe to shutdown Decaf.
decaf::lang::Runtime::shutdownRuntime();
}
////////////////////////////////////////////////////////////////////////////////
void ActiveMQCPP::registerWireFormats() {
// Each of the internally implemented WireFormat's is registered here
// with the WireFormat Registry
WireFormatRegistry::initialize();
WireFormatRegistry::getInstance().registerFactory("openwire", new wireformat::openwire::OpenWireFormatFactory());
WireFormatRegistry::getInstance().registerFactory("stomp", new wireformat::stomp::StompWireFormatFactory());
}
////////////////////////////////////////////////////////////////////////////////
void ActiveMQCPP::registerTransports() {
// Each of the internally implemented Transports is registered here
TransportRegistry::initialize();
TransportRegistry::getInstance().registerFactory("tcp", new TcpTransportFactory());
TransportRegistry::getInstance().registerFactory("ssl", new SslTransportFactory());
TransportRegistry::getInstance().registerFactory("mock", new MockTransportFactory());
TransportRegistry::getInstance().registerFactory("failover", new FailoverTransportFactory());
TransportRegistry::getInstance().registerFactory("discovery", new DiscoveryTransportFactory());
// Each discovery agent implemented in this library must be registered here.
DiscoveryAgentRegistry::initialize();
DiscoveryAgentRegistry::getInstance().registerFactory("http", new HttpDiscoveryAgentFactory);
}
<commit_msg>https://issues.apache.org/jira/browse/AMQCPP-525<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 "ActiveMQCPP.h"
#include <decaf/lang/Runtime.h>
#include <activemq/wireformat/WireFormatRegistry.h>
#include <activemq/transport/TransportRegistry.h>
#include <activemq/transport/discovery/DiscoveryAgentRegistry.h>
#include <activemq/util/IdGenerator.h>
#include <activemq/wireformat/stomp/StompWireFormatFactory.h>
#include <activemq/wireformat/openwire/OpenWireFormatFactory.h>
#include <activemq/transport/mock/MockTransportFactory.h>
#include <activemq/transport/tcp/TcpTransportFactory.h>
#include <activemq/transport/tcp/SslTransportFactory.h>
#include <activemq/transport/failover/FailoverTransportFactory.h>
#include <activemq/transport/discovery/DiscoveryTransportFactory.h>
#include <activemq/transport/discovery/http/HttpDiscoveryAgentFactory.h>
using namespace activemq;
using namespace activemq::library;
using namespace activemq::util;
using namespace activemq::transport;
using namespace activemq::transport::tcp;
using namespace activemq::transport::mock;
using namespace activemq::transport::failover;
using namespace activemq::transport::discovery;
using namespace activemq::transport::discovery::http;
using namespace activemq::wireformat;
////////////////////////////////////////////////////////////////////////////////
ActiveMQCPP::ActiveMQCPP() {
}
////////////////////////////////////////////////////////////////////////////////
ActiveMQCPP::~ActiveMQCPP() {
}
////////////////////////////////////////////////////////////////////////////////
void ActiveMQCPP::initializeLibrary(int argc, char** argv) {
// Initialize the Decaf Library by requesting its runtime.
decaf::lang::Runtime::initializeRuntime(argc, argv);
// Register all WireFormats
ActiveMQCPP::registerWireFormats();
// Register all Transports
ActiveMQCPP::registerTransports();
// Start the IdGenerator Kernel
IdGenerator::initialize();
}
////////////////////////////////////////////////////////////////////////////////
void ActiveMQCPP::initializeLibrary() {
ActiveMQCPP::initializeLibrary(0, NULL);
}
////////////////////////////////////////////////////////////////////////////////
void ActiveMQCPP::shutdownLibrary() {
// Shutdown the IdGenerator Kernel
IdGenerator::shutdown();
WireFormatRegistry::shutdown();
TransportRegistry::shutdown();
DiscoveryAgentRegistry::shutdown();
// Now it should be safe to shutdown Decaf.
decaf::lang::Runtime::shutdownRuntime();
}
////////////////////////////////////////////////////////////////////////////////
void ActiveMQCPP::registerWireFormats() {
// Each of the internally implemented WireFormat's is registered here
// with the WireFormat Registry
WireFormatRegistry::initialize();
WireFormatRegistry::getInstance().registerFactory("openwire", new wireformat::openwire::OpenWireFormatFactory());
WireFormatRegistry::getInstance().registerFactory("stomp", new wireformat::stomp::StompWireFormatFactory());
}
////////////////////////////////////////////////////////////////////////////////
void ActiveMQCPP::registerTransports() {
// Each of the internally implemented Transports is registered here
TransportRegistry::initialize();
TransportRegistry::getInstance().registerFactory("tcp", new TcpTransportFactory());
TransportRegistry::getInstance().registerFactory("ssl", new SslTransportFactory());
TransportRegistry::getInstance().registerFactory("nio", new TcpTransportFactory());
TransportRegistry::getInstance().registerFactory("nio+ssl", new SslTransportFactory());
TransportRegistry::getInstance().registerFactory("mock", new MockTransportFactory());
TransportRegistry::getInstance().registerFactory("failover", new FailoverTransportFactory());
TransportRegistry::getInstance().registerFactory("discovery", new DiscoveryTransportFactory());
// Each discovery agent implemented in this library must be registered here.
DiscoveryAgentRegistry::initialize();
DiscoveryAgentRegistry::getInstance().registerFactory("http", new HttpDiscoveryAgentFactory);
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2014 Sadman Kazi, Wojciech Swiderski, Serge Babayan, Shan Phylim
This file is part of MyoPad.
MyoPad is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyoPad is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with MyoPad. If not, see <http://www.gnu.org/licenses/>.
*/
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
#include <iomanip>
#include <stdexcept>
#include <string>
#include <algorithm>
#include "filter.h"
// The only file that needs to be included to use the Myo C++ SDK is myo.hpp.
#include <myo/myo.hpp>
Filter::Filter()
: onArm(false), currentPose(), quatX(0), quatY(0), quatZ(0), quatW(0)
{
}
void Filter::onPose(myo::Myo* myo, uint64_t timestamp, myo::Pose pose)
{
currentPose = pose;
}
// onUnpair() is called whenever the Myo is disconnected from Myo Connect by the user.
void Filter::onUnpair(myo::Myo* myo, uint64_t timestamp)
{
onArm = false;
}
// onOrientationData() is called whenever the Myo device provides its current orientation, which is represented
// as a unit quaternion.
void Filter::onOrientationData(myo::Myo* myo, uint64_t timestamp, const myo::Quaternion<float>& quat)
{
quatX = quat.x(); //Return the x-component of this quaternion's vector
quatY = quat.y(); //Return the y -component of this quaternion's vector
quatZ = quat.z(); //Return the z-component of this quaternion's vector
quatW = quat.w(); //Return the w-component (scalar) of this quaternion's vector
using std::atan2;
using std::asin;
using std::sqrt;
using std::cos;
using std::sin;
using std::max;
using std::min;
roll = -1 * atan2(2.0f * (quat.w() * quat.z() + quat.x() * quat.y()),
1.0f - 2.0f * (quat.y() * quat.y() + quat.z() * quat.z()));
pitch = -1 * atan2(2.0f * (quat.w() * quat.x() + quat.y() * quat.z()),
1.0f - 2.0f * (quat.x() * quat.x() + quat.y() * quat.y()));
yaw = -1 * asin(max(-1.0f, min(1.0f, 2.0f * (quat.w() * quat.y() - quat.z() * quat.x()))));
}
void Filter::onAccelerometerData(myo::Myo *myo, uint64_t timestamp, const myo::Vector3< float > &accel){
accelX_old = accelX;
accelY_old = accelY;
accelZ_old = accelZ;
using std::atan2;
using std::asin;
using std::sqrt;
using std::cos;
using std::sin;
using std::max;
using std::min;
//shift the coordinate system in order to cancel out gravity in the right axis
//roll = roll - roll_i;
//pitch = pitch - pitch_i;
//yaw = yaw - yaw_i;
//accelX = -1 * accel.y();
//accelY = -1 * accel.z();
//accelZ = accel.x();
// pitch = alpha
// yaw = beta
// roll = gamma
//accelX *= cos(yaw) * cos(roll) + cos(yaw) * sin(roll) - sin(yaw);
//accelY *= cos(roll) * sin(pitch) * sin(yaw) - cos(pitch) * sin(roll) + cos(pitch) * cos(roll) + sin(pitch) * sin(yaw) * sin(roll) + cos(yaw) * sin(pitch);
//accelZ *= cos(pitch) * cos(roll) * sin(yaw) + sin(pitch) * sin(roll) - cos(roll) * sin(pitch) + cos(pitch) * sin(yaw) * sin(roll) + cos(pitch) * cos(yaw);
if (fabs(accel.x() - accelX_old) > 0.01)
accelX = accel.x();
if (fabs(accel.y() - accelY_old) > 0.01)
accelY = accel.y();
if (fabs(accel.z() - accelZ_old) > 0.01)
accelZ = accel.z() - 1;
}
// We define this function to print the current values that were updated by the on...() functions above.
<commit_msg>Update filter.cpp<commit_after>/*
Copyright (C) 2016 Abhinav Narayanan
This file is part of MyoPad.
MyoPad is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyoPad is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with MyoPad. If not, see <http://www.gnu.org/licenses/>.
*/
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
#include <iomanip>
#include <stdexcept>
#include <string>
#include <algorithm>
#include "filter.h"
// The only file that needs to be included to use the Myo C++ SDK is myo.hpp.
#include <myo/myo.hpp>
Filter::Filter()
: onArm(false), currentPose(), quatX(0), quatY(0), quatZ(0), quatW(0)
{
}
void Filter::onPose(myo::Myo* myo, uint64_t timestamp, myo::Pose pose)
{
currentPose = pose;
}
// onUnpair() is called whenever the Myo is disconnected from Myo Connect by the user.
void Filter::onUnpair(myo::Myo* myo, uint64_t timestamp)
{
onArm = false;
}
// onOrientationData() is called whenever the Myo device provides its current orientation, which is represented
// as a unit quaternion.
void Filter::onOrientationData(myo::Myo* myo, uint64_t timestamp, const myo::Quaternion<float>& quat)
{
quatX = quat.x(); //Return the x-component of this quaternion's vector
quatY = quat.y(); //Return the y -component of this quaternion's vector
quatZ = quat.z(); //Return the z-component of this quaternion's vector
quatW = quat.w(); //Return the w-component (scalar) of this quaternion's vector
using std::atan2;
using std::asin;
using std::sqrt;
using std::cos;
using std::sin;
using std::max;
using std::min;
roll = -1 * atan2(2.0f * (quat.w() * quat.z() + quat.x() * quat.y()),
1.0f - 2.0f * (quat.y() * quat.y() + quat.z() * quat.z()));
pitch = -1 * atan2(2.0f * (quat.w() * quat.x() + quat.y() * quat.z()),
1.0f - 2.0f * (quat.x() * quat.x() + quat.y() * quat.y()));
yaw = -1 * asin(max(-1.0f, min(1.0f, 2.0f * (quat.w() * quat.y() - quat.z() * quat.x()))));
}
void Filter::onAccelerometerData(myo::Myo *myo, uint64_t timestamp, const myo::Vector3< float > &accel){
accelX_old = accelX;
accelY_old = accelY;
accelZ_old = accelZ;
using std::atan2;
using std::asin;
using std::sqrt;
using std::cos;
using std::sin;
using std::max;
using std::min;
//shift the coordinate system in order to cancel out gravity in the right axis
//roll = roll - roll_i;
//pitch = pitch - pitch_i;
//yaw = yaw - yaw_i;
//accelX = -1 * accel.y();
//accelY = -1 * accel.z();
//accelZ = accel.x();
// pitch = alpha
// yaw = beta
// roll = gamma
//accelX *= cos(yaw) * cos(roll) + cos(yaw) * sin(roll) - sin(yaw);
//accelY *= cos(roll) * sin(pitch) * sin(yaw) - cos(pitch) * sin(roll) + cos(pitch) * cos(roll) + sin(pitch) * sin(yaw) * sin(roll) + cos(yaw) * sin(pitch);
//accelZ *= cos(pitch) * cos(roll) * sin(yaw) + sin(pitch) * sin(roll) - cos(roll) * sin(pitch) + cos(pitch) * sin(yaw) * sin(roll) + cos(pitch) * cos(yaw);
if (fabs(accel.x() - accelX_old) > 0.01)
accelX = accel.x();
if (fabs(accel.y() - accelY_old) > 0.01)
accelY = accel.y();
if (fabs(accel.z() - accelZ_old) > 0.01)
accelZ = accel.z() - 1;
}
// We define this function to print the current values that were updated by the on...() functions above.
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed in accordance with the terms specified in
* the LICENSE file found in the root directory of this source tree.
*/
#include <osquery/tables.h>
#include "osquery/core/windows/wmi.h"
namespace osquery {
namespace tables {
QueryData genLogicalDrives(QueryContext& context) {
QueryData results;
const WmiRequest wmiLogicalDiskReq(
"select DeviceID, Description, FreeSpace, Size, FileSystem from "
"Win32_LogicalDisk");
auto const& logicalDisks = wmiLogicalDiskReq.results();
for (const auto& logicalDisk : logicalDisks) {
Row r;
std::string deviceId;
logicalDisk.GetString("DeviceID", deviceId);
logicalDisk.GetString("Description", r["description"]);
logicalDisk.GetString("FreeSpace", r["free_space"]);
logicalDisk.GetString("Size", r["size"]);
logicalDisk.GetString("FileSystem", r["file_system"]);
if (r["free_space"].empty()) {
r["free_space"] = "-1";
}
if (r["size"].empty()) {
r["size"] = "-1";
}
// NOTE(ww): Previous versions of this table used the type
// column to provide a non-canonical description of the drive.
// However, a bug in WMI marshalling caused the type to always
// return "Unknown". That behavior is preserved here.
r["type"] = "Unknown";
r["device_id"] = deviceId;
r["boot_partition"] = INTEGER(0);
std::string assocQuery =
std::string("Associators of {Win32_LogicalDisk.DeviceID='") + deviceId +
"'} where AssocClass=Win32_LogicalDiskToPartition";
const WmiRequest wmiLogicalDiskToPartitionReq(assocQuery);
auto const& wmiLogicalDiskToPartitionResults =
wmiLogicalDiskToPartitionReq.results();
if (wmiLogicalDiskToPartitionResults.empty()) {
results.push_back(r);
continue;
}
std::string partitionDeviceId;
wmiLogicalDiskToPartitionResults[0].GetString("DeviceID",
partitionDeviceId);
std::string partitionQuery =
std::string(
"SELECT BootPartition FROM Win32_DiskPartition WHERE DeviceID='") +
partitionDeviceId + '\'';
const WmiRequest wmiPartitionReq(partitionQuery);
auto const& wmiPartitionResults = wmiPartitionReq.results();
if (wmiPartitionResults.empty()) {
results.push_back(r);
continue;
}
bool bootPartition = false;
wmiPartitionResults[0].GetBool("BootPartition", bootPartition);
r["boot_partition"] = bootPartition ? INTEGER(1) : INTEGER(0);
results.push_back(r);
}
return results;
}
} // namespace tables
} // namespace osquery
<commit_msg>windows/logical_drives: Fix boot partition detection (#5477)<commit_after>/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed in accordance with the terms specified in
* the LICENSE file found in the root directory of this source tree.
*/
#include <unordered_set>
#include "osquery/core/windows/wmi.h"
#include <osquery/tables.h>
namespace osquery {
namespace tables {
QueryData genLogicalDrives(QueryContext& context) {
QueryData results;
const WmiRequest wmiLogicalDiskReq(
"select DeviceID, Description, FreeSpace, Size, FileSystem from "
"Win32_LogicalDisk");
auto const& logicalDisks = wmiLogicalDiskReq.results();
const WmiRequest wmiBootConfigurationReq(
"select BootDirectory from Win32_BootConfiguration");
auto const& bootConfigurations = wmiBootConfigurationReq.results();
std::unordered_set<char> bootDeviceIds;
for (const auto& bootConfiguration : bootConfigurations) {
std::string bootDirectory;
bootConfiguration.GetString("BootDirectory", bootDirectory);
bootDeviceIds.insert(bootDirectory.at(0));
}
for (const auto& logicalDisk : logicalDisks) {
Row r;
std::string deviceId;
logicalDisk.GetString("DeviceID", deviceId);
logicalDisk.GetString("Description", r["description"]);
logicalDisk.GetString("FreeSpace", r["free_space"]);
logicalDisk.GetString("Size", r["size"]);
logicalDisk.GetString("FileSystem", r["file_system"]);
if (r["free_space"].empty()) {
r["free_space"] = "-1";
}
if (r["size"].empty()) {
r["size"] = "-1";
}
// NOTE(ww): Previous versions of this table used the type
// column to provide a non-canonical description of the drive.
// However, a bug in WMI marshalling caused the type to always
// return "Unknown". That behavior is preserved here.
r["type"] = "Unknown";
r["device_id"] = deviceId;
r["boot_partition"] = INTEGER(bootDeviceIds.count(deviceId.at(0)));
results.push_back(std::move(r));
}
return results;
}
} // namespace tables
} // namespace osquery
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: token.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: pjunck $ $Date: 2004-11-02 11:57:04 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _TOKEN_HXX
#define _TOKEN_HXX
#ifndef _SCANNER_HXX
#include "scanner.hxx"
#endif
#ifndef _SBDEF_HXX
#include "sbdef.hxx"
#endif
#if defined( SHARED )
#define SbiTokenSHAREDTMPUNDEF
#undef SHARED
#endif
// Der Tokenizer ist stand-alone, d.h. er kann von ueberallher verwendet
// werden. Eine BASIC-Instanz ist fuer Fehlermeldungen notwendig. Ohne
// BASIC werden die Fehler nur gezaehlt. Auch ist Basic notwendig, wenn
// eine erweiterte SBX-Variable zur Erkennung von Datentypen etc. verwendet
// werden soll.
enum SbiToken {
NIL = 0,
// Token zwischen 0x20 und 0x3F sind Literale:
LPAREN = '(', RPAREN = ')', COMMA = ',', DOT = '.', EXCLAM = '!',
HASH = '#', SEMICOLON = ';',
// Anweisungen:
FIRSTKWD = 0x40,
AS = FIRSTKWD, ALIAS, ASSIGN,
CALL, CASE, CLOSE, COMPARE, _CONST_,
DECLARE, DIM, DO,
// in der Reihenfolge der Datentyp-Enums!
DEFINT, DEFLNG, DEFSNG, DEFDBL, DEFCUR, DEFDATE, DEFSTR, DEFOBJ,
DEFERR, DEFBOOL, DEFVAR,
// in der Reihenfolge der Datentyp-Enums!
DATATYPE1,
TINTEGER = DATATYPE1,
TLONG, TSINGLE, TDOUBLE, TCURRENCY, TDATE, TSTRING, TOBJECT,
_ERROR_, TBOOLEAN, TVARIANT,
DATATYPE2 = TVARIANT,
EACH, ELSE, ELSEIF, END, ERASE, EXIT,
FOR, FUNCTION,
GET, GLOBAL, GOSUB, GOTO,
IF, _IN_, INPUT,
LET, LINE, LINEINPUT, LOCAL, LOOP, LPRINT, LSET,
NAME, NEW, NEXT,
ON, OPEN, OPTION,
PRINT, PRIVATE, PROPERTY, PUBLIC,
REDIM, REM, RESUME, RETURN, RSET,
SELECT, SET, SHARED, STATIC, STEP, STOP, SUB,
TEXT, THEN, TO, TYPE,
UNTIL,
WEND, WHILE, WITH, WRITE,
ENDIF, ENDFUNC, ENDPROPERTY, ENDSUB, ENDTYPE, ENDSELECT, ENDWITH,
// Ende aller Keywords
LASTKWD = ENDWITH,
// Statement-Ende
EOS, EOLN,
// Operatoren:
EXPON, NEG, MUL,
DIV, IDIV, MOD, PLUS, MINUS,
EQ, NE, LT, GT, LE, GE,
NOT, AND, OR, XOR, EQV,
IMP, CAT, LIKE, IS,
// Sonstiges:
FIRSTEXTRA,
NUMBER=FIRSTEXTRA, FIXSTRING, SYMBOL, _CDECL_, BYVAL, BYREF,
OUTPUT, RANDOM, APPEND, BINARY, ACCESS,
LOCK, READ, PRESERVE, BASE, ANY, LIB, _OPTIONAL_,
EXPLICIT, COMPATIBLE, CLASSMODULE,
// Ab hier kommen JavaScript-Tokens (gleiches enum, damit gleicher Typ)
FIRSTJAVA,
JS_BREAK=FIRSTJAVA, JS_CONTINUE, JS_FOR, JS_FUNCTION, JS_IF, JS_NEW,
JS_RETURN, JS_THIS, JS_VAR, JS_WHILE, JS_WITH,
// JavaScript-Operatoren
// _ASS_ = Assignment
JS_COMMA, JS_ASSIGNMENT, JS_ASS_PLUS, JS_ASS_MINUS, JS_ASS_MUL,
JS_ASS_DIV, JS_ASS_MOD, JS_ASS_LSHIFT, JS_ASS_RSHIFT, JS_ASS_RSHIFT_Z,
JS_ASS_AND, JS_ASS_XOR, JS_ASS_OR,
JS_COND_QUEST, JS_COND_SEL, JS_LOG_OR, JS_LOG_AND, JS_BIT_OR,
JS_BIT_XOR, JS_BIT_AND, JS_EQ, JS_NE, JS_LT, JS_LE,
JS_GT, JS_GE, JS_LSHIFT, JS_RSHIFT, JS_RSHIFT_Z,
JS_PLUS, JS_MINUS, JS_MUL, JS_DIV, JS_MOD, JS_LOG_NOT, JS_BIT_NOT,
JS_INC, JS_DEC, JS_LPAREN, JS_RPAREN, JS_LINDEX, JS_RINDEX
};
#ifdef SbiTokenSHAREDTMPUNDEF
#define SHARED
#undef SbiTokenSHAREDTMPUNDEF
#endif
class SbiTokenizer : public SbiScanner {
protected:
SbiToken eCurTok; // aktuelles Token
SbiToken ePush; // Pushback-Token
USHORT nPLine, nPCol1, nPCol2; // Pushback-Location
BOOL bEof; // TRUE bei Dateiende
BOOL bEos; // TRUE bei Statement-Ende
BOOL bKeywords; // TRUE, falls Keywords geparst werden
BOOL bAs; // letztes Keyword war AS
public:
SbiTokenizer( const ::rtl::OUString&, StarBASIC* = NULL );
~SbiTokenizer();
inline BOOL IsEof() { return bEof; }
inline BOOL IsEos() { return bEos; }
void Push( SbiToken ); // Pushback eines Tokens
const String& Symbol( SbiToken );// Rueckumwandlung
SbiToken Peek(); // das naechste Token lesen
SbiToken Next(); // Ein Token lesen
BOOL MayBeLabel( BOOL= FALSE ); // Kann es ein Label sein?
void Hilite( SbTextPortions& ); // Syntax-Highlighting
void Error( SbError c ) { GenError( c ); }
void Error( SbError, SbiToken );
void Error( SbError, const char* );
void Error( SbError, String );
void Keywords( BOOL b ) { bKeywords = b; }
static BOOL IsEoln( SbiToken t )
{ return BOOL( t == EOS || t == EOLN || t == REM ); }
static BOOL IsKwd( SbiToken t )
{ return BOOL( t >= FIRSTKWD && t <= LASTKWD ); }
static BOOL IsExtra( SbiToken t )
{ return BOOL( t >= FIRSTEXTRA ); }
};
#endif
<commit_msg>INTEGRATION: CWS texteng03 (1.3.58); FILE MERGED 2004/10/29 13:11:20 ab 1.3.58.1: #111742# Enum support<commit_after>/*************************************************************************
*
* $RCSfile: token.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2004-11-15 16:42:52 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _TOKEN_HXX
#define _TOKEN_HXX
#ifndef _SCANNER_HXX
#include "scanner.hxx"
#endif
#ifndef _SBDEF_HXX
#include "sbdef.hxx"
#endif
#if defined( SHARED )
#define SbiTokenSHAREDTMPUNDEF
#undef SHARED
#endif
// Der Tokenizer ist stand-alone, d.h. er kann von ueberallher verwendet
// werden. Eine BASIC-Instanz ist fuer Fehlermeldungen notwendig. Ohne
// BASIC werden die Fehler nur gezaehlt. Auch ist Basic notwendig, wenn
// eine erweiterte SBX-Variable zur Erkennung von Datentypen etc. verwendet
// werden soll.
enum SbiToken {
NIL = 0,
// Token zwischen 0x20 und 0x3F sind Literale:
LPAREN = '(', RPAREN = ')', COMMA = ',', DOT = '.', EXCLAM = '!',
HASH = '#', SEMICOLON = ';',
// Anweisungen:
FIRSTKWD = 0x40,
AS = FIRSTKWD, ALIAS, ASSIGN,
CALL, CASE, CLOSE, COMPARE, _CONST_,
DECLARE, DIM, DO,
// in der Reihenfolge der Datentyp-Enums!
DEFINT, DEFLNG, DEFSNG, DEFDBL, DEFCUR, DEFDATE, DEFSTR, DEFOBJ,
DEFERR, DEFBOOL, DEFVAR,
// in der Reihenfolge der Datentyp-Enums!
DATATYPE1,
TINTEGER = DATATYPE1,
TLONG, TSINGLE, TDOUBLE, TCURRENCY, TDATE, TSTRING, TOBJECT,
_ERROR_, TBOOLEAN, TVARIANT,
DATATYPE2 = TVARIANT,
EACH, ELSE, ELSEIF, END, ERASE, EXIT,
FOR, FUNCTION,
GET, GLOBAL, GOSUB, GOTO,
IF, _IN_, INPUT,
LET, LINE, LINEINPUT, LOCAL, LOOP, LPRINT, LSET,
NAME, NEW, NEXT,
ON, OPEN, OPTION,
PRINT, PRIVATE, PROPERTY, PUBLIC,
REDIM, REM, RESUME, RETURN, RSET,
SELECT, SET, SHARED, STATIC, STEP, STOP, SUB,
TEXT, THEN, TO, TYPE, ENUM,
UNTIL,
WEND, WHILE, WITH, WRITE,
ENDENUM, ENDIF, ENDFUNC, ENDPROPERTY, ENDSUB, ENDTYPE, ENDSELECT, ENDWITH,
// Ende aller Keywords
LASTKWD = ENDWITH,
// Statement-Ende
EOS, EOLN,
// Operatoren:
EXPON, NEG, MUL,
DIV, IDIV, MOD, PLUS, MINUS,
EQ, NE, LT, GT, LE, GE,
NOT, AND, OR, XOR, EQV,
IMP, CAT, LIKE, IS,
// Sonstiges:
FIRSTEXTRA,
NUMBER=FIRSTEXTRA, FIXSTRING, SYMBOL, _CDECL_, BYVAL, BYREF,
OUTPUT, RANDOM, APPEND, BINARY, ACCESS,
LOCK, READ, PRESERVE, BASE, ANY, LIB, _OPTIONAL_,
EXPLICIT, COMPATIBLE, CLASSMODULE,
// Ab hier kommen JavaScript-Tokens (gleiches enum, damit gleicher Typ)
FIRSTJAVA,
JS_BREAK=FIRSTJAVA, JS_CONTINUE, JS_FOR, JS_FUNCTION, JS_IF, JS_NEW,
JS_RETURN, JS_THIS, JS_VAR, JS_WHILE, JS_WITH,
// JavaScript-Operatoren
// _ASS_ = Assignment
JS_COMMA, JS_ASSIGNMENT, JS_ASS_PLUS, JS_ASS_MINUS, JS_ASS_MUL,
JS_ASS_DIV, JS_ASS_MOD, JS_ASS_LSHIFT, JS_ASS_RSHIFT, JS_ASS_RSHIFT_Z,
JS_ASS_AND, JS_ASS_XOR, JS_ASS_OR,
JS_COND_QUEST, JS_COND_SEL, JS_LOG_OR, JS_LOG_AND, JS_BIT_OR,
JS_BIT_XOR, JS_BIT_AND, JS_EQ, JS_NE, JS_LT, JS_LE,
JS_GT, JS_GE, JS_LSHIFT, JS_RSHIFT, JS_RSHIFT_Z,
JS_PLUS, JS_MINUS, JS_MUL, JS_DIV, JS_MOD, JS_LOG_NOT, JS_BIT_NOT,
JS_INC, JS_DEC, JS_LPAREN, JS_RPAREN, JS_LINDEX, JS_RINDEX
};
#ifdef SbiTokenSHAREDTMPUNDEF
#define SHARED
#undef SbiTokenSHAREDTMPUNDEF
#endif
class SbiTokenizer : public SbiScanner {
protected:
SbiToken eCurTok; // aktuelles Token
SbiToken ePush; // Pushback-Token
USHORT nPLine, nPCol1, nPCol2; // Pushback-Location
BOOL bEof; // TRUE bei Dateiende
BOOL bEos; // TRUE bei Statement-Ende
BOOL bKeywords; // TRUE, falls Keywords geparst werden
BOOL bAs; // letztes Keyword war AS
public:
SbiTokenizer( const ::rtl::OUString&, StarBASIC* = NULL );
~SbiTokenizer();
inline BOOL IsEof() { return bEof; }
inline BOOL IsEos() { return bEos; }
void Push( SbiToken ); // Pushback eines Tokens
const String& Symbol( SbiToken );// Rueckumwandlung
SbiToken Peek(); // das naechste Token lesen
SbiToken Next(); // Ein Token lesen
BOOL MayBeLabel( BOOL= FALSE ); // Kann es ein Label sein?
void Hilite( SbTextPortions& ); // Syntax-Highlighting
void Error( SbError c ) { GenError( c ); }
void Error( SbError, SbiToken );
void Error( SbError, const char* );
void Error( SbError, String );
void Keywords( BOOL b ) { bKeywords = b; }
static BOOL IsEoln( SbiToken t )
{ return BOOL( t == EOS || t == EOLN || t == REM ); }
static BOOL IsKwd( SbiToken t )
{ return BOOL( t >= FIRSTKWD && t <= LASTKWD ); }
static BOOL IsExtra( SbiToken t )
{ return BOOL( t >= FIRSTEXTRA ); }
};
#endif
<|endoftext|> |
<commit_before>#ifndef SOLARIZED_HPP
#define SOLARIZED_HPP
#include <wx/colour.h>
#include "ColorScheme/ColorSchemeBase.hpp"
namespace Slic3r { namespace GUI {
/// S O L A R I Z E
/// http://ethanschoonover.com/solarized
///
/// Implements a colorscheme lookup of wxColors
class Solarized : public ColorScheme {
public:
const wxColour SELECTED_COLOR() const { return COLOR_MAGENTA; }
const wxColour HOVER_COLOR() const { return COLOR_VIOLET; }
const wxColour SUPPORT_COLOR() const { return COLOR_VIOLET; }
const wxColour BACKGROUND_COLOR() const { return COLOR_BASE3; }
private:
const wxColour COLOR_BASE0() const {wxColour(255*0.51373,255*0.58039,255*0.58824)};
const wxColour COLOR_BASE00() const {wxColour(255*0.39608,255*0.48235,255*0.51373)};
const wxColour COLOR_BASE01() const {wxColour(255*0.34510,255*0.43137,255*0.45882)};
const wxColour COLOR_BASE02() const {wxColour(255*0.02745,255*0.21176,255*0.25882)};
const wxColour COLOR_BASE03() const {wxColour(255*0.00000,255*0.16863,255*0.21176)};
const wxColour COLOR_BASE1() const {wxColour(255*0.57647,255*0.63137,255*0.63137)};
const wxColour COLOR_BASE2() const {wxColour(255*0.93333,255*0.90980,255*0.83529)};
const wxColour COLOR_BASE3() const {wxColour(255*0.99216,255*0.96471,255*0.89020)};
const wxColour COLOR_BLUE() const {wxColour(255*0.14902,255*0.54510,255*0.82353)};
const wxColour COLOR_CYAN() const {wxColour(255*0.16471,255*0.63137,255*0.59608)};
const wxColour COLOR_GREEN() const {wxColour(255*0.52157,255*0.60000,255*0.00000)};
const wxColour COLOR_MAGENTA() const {wxColour(255*0.82745,255*0.21176,255*0.50980)};
const wxColour COLOR_ORANGE() const {wxColour(255*0.79608,255*0.29412,255*0.08627)};
const wxColour COLOR_RED() const {wxColour(255*0.86275,255*0.19608,255*0.18431)};
const wxColour COLOR_VIOLET() const {wxColour(255*0.42353,255*0.44314,255*0.76863)};
const wxColour COLOR_YELLOW() const {wxColour(255*0.70980,255*0.53725,255*0.00000)};
};
}} // namespace Slic3r::GUI
#endif // SOLARIZED_HPP
<commit_msg>actually do functions right<commit_after>#ifndef SOLARIZED_HPP
#define SOLARIZED_HPP
#include <wx/colour.h>
#include "ColorScheme/ColorSchemeBase.hpp"
namespace Slic3r { namespace GUI {
/// S O L A R I Z E
/// http://ethanschoonover.com/solarized
///
/// Implements a colorscheme lookup of wxColors
class Solarized : public ColorScheme {
public:
const wxColour SELECTED_COLOR() const { return COLOR_MAGENTA(); }
const wxColour HOVER_COLOR() const { return COLOR_VIOLET(); }
const wxColour SUPPORT_COLOR() const { return COLOR_VIOLET(); }
const wxColour BACKGROUND_COLOR() const { return COLOR_BASE3(); }
private:
const wxColour COLOR_BASE0() const {return wxColour(255*0.51373,255*0.58039,255*0.58824);}
const wxColour COLOR_BASE00() const {return wxColour(255*0.39608,255*0.48235,255*0.51373);}
const wxColour COLOR_BASE01() const {return wxColour(255*0.34510,255*0.43137,255*0.45882);}
const wxColour COLOR_BASE02() const {return wxColour(255*0.02745,255*0.21176,255*0.25882);}
const wxColour COLOR_BASE03() const {return wxColour(255*0.00000,255*0.16863,255*0.21176);}
const wxColour COLOR_BASE1() const {return wxColour(255*0.57647,255*0.63137,255*0.63137);}
const wxColour COLOR_BASE2() const {return wxColour(255*0.93333,255*0.90980,255*0.83529);}
const wxColour COLOR_BASE3() const {return wxColour(255*0.99216,255*0.96471,255*0.89020);}
const wxColour COLOR_BLUE() const {return wxColour(255*0.14902,255*0.54510,255*0.82353);}
const wxColour COLOR_CYAN() const {return wxColour(255*0.16471,255*0.63137,255*0.59608);}
const wxColour COLOR_GREEN() const {return wxColour(255*0.52157,255*0.60000,255*0.00000);}
const wxColour COLOR_MAGENTA() const {return wxColour(255*0.82745,255*0.21176,255*0.50980);}
const wxColour COLOR_ORANGE() const {return wxColour(255*0.79608,255*0.29412,255*0.08627);}
const wxColour COLOR_RED() const {return wxColour(255*0.86275,255*0.19608,255*0.18431);}
const wxColour COLOR_VIOLET() const {return wxColour(255*0.42353,255*0.44314,255*0.76863);}
const wxColour COLOR_YELLOW() const {return wxColour(255*0.70980,255*0.53725,255*0.00000);}
};
}} // namespace Slic3r::GUI
#endif // SOLARIZED_HPP
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012, John Haddon. All rights reserved.
// Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/format.hpp"
#include "ai.h"
#include "IECore/MessageHandler.h"
#include "IECore/LRUCache.h"
#include "IECoreArnold/UniverseBlock.h"
#include "Gaffer/NumericPlug.h"
#include "Gaffer/CompoundNumericPlug.h"
#include "Gaffer/StringPlug.h"
#include "GafferArnold/ArnoldShader.h"
#include "GafferArnold/ParameterHandler.h"
using namespace std;
using namespace boost;
using namespace Imath;
using namespace IECore;
using namespace GafferScene;
using namespace GafferArnold;
using namespace Gaffer;
IE_CORE_DEFINERUNTIMETYPED( ArnoldShader );
ArnoldShader::ArnoldShader( const std::string &name )
: GafferScene::Shader( name )
{
}
ArnoldShader::~ArnoldShader()
{
}
Gaffer::Plug *ArnoldShader::correspondingInput( const Gaffer::Plug *output )
{
// better to do a few harmless casts than manage a duplicate implementation
return const_cast<Gaffer::Plug *>(
const_cast<const ArnoldShader *>( this )->correspondingInput( output )
);
}
const Gaffer::Plug *ArnoldShader::correspondingInput( const Gaffer::Plug *output ) const
{
if( output != outPlug() )
{
return Shader::correspondingInput( output );
}
const CompoundData *metadata = ArnoldShader::metadata();
if( !metadata )
{
return NULL;
}
const StringData *primaryInput = static_cast<const StringData*>( metadata->member<IECore::CompoundData>( "shader" )->member<IECore::Data>( "primaryInput" ) );
if( !primaryInput )
{
return NULL;
}
const Plug *result = parametersPlug()->getChild<Plug>( primaryInput->readable() );
if( !result )
{
IECore::msg( IECore::Msg::Error, "ArnoldShader::correspondingInput", boost::format( "Parameter \"%s\" does not exist" ) % primaryInput->readable() );
return NULL;
}
return result;
}
void ArnoldShader::loadShader( const std::string &shaderName, bool keepExistingValues )
{
IECoreArnold::UniverseBlock arnoldUniverse( /* writable = */ false );
const AtNodeEntry *shader = AiNodeEntryLookUp( shaderName.c_str() );
if( !shader )
{
throw Exception( str( format( "Shader \"%s\" not found" ) % shaderName ) );
}
if( !keepExistingValues )
{
parametersPlug()->clearChildren();
if( Plug *out = outPlug() )
{
removeChild( out );
}
}
const bool isLightShader = AiNodeEntryGetType( shader ) == AI_NODE_LIGHT;
namePlug()->setValue( AiNodeEntryGetName( shader ) );
typePlug()->setValue(
isLightShader ? "ai:light" : "ai:surface"
);
ParameterHandler::setupPlugs( shader, parametersPlug() );
ParameterHandler::setupPlug( "out", isLightShader ? AI_TYPE_POINTER : AiNodeEntryGetOutputType( shader ), this, Plug::Out );
}
//////////////////////////////////////////////////////////////////////////
// Metadata loading code
//////////////////////////////////////////////////////////////////////////
static IECore::ConstCompoundDataPtr metadataGetter( const std::string &key, size_t &cost )
{
IECoreArnold::UniverseBlock arnoldUniverse( /* writable = */ false );
const AtNodeEntry *shader = AiNodeEntryLookUp( key.c_str() );
if( !shader )
{
throw Exception( str( format( "Shader \"%s\" not found" ) % key ) );
}
CompoundDataPtr metadata = new CompoundData;
CompoundDataPtr shaderMetadata = new CompoundData;
metadata->writable()["shader"] = shaderMetadata;
// Currently we don't store metadata for parameters.
// We add the "parameter" CompoundData mainly so that we are consistent with the OSLShader.
// Eventually we will load all metadata here and access it from ArnoldShaderUI.
CompoundDataPtr parameterMetadata = new CompoundData;
metadata->writable()["parameter"] = parameterMetadata;
const char* value;
if( AiMetaDataGetStr( shader, /* look up metadata on node, not on parameter */ NULL , "primaryInput", &value ) )
{
shaderMetadata->writable()["primaryInput"] = new StringData( value );
}
const char* shaderType;
if( AiMetaDataGetStr( shader, /* look up metadata on node, not on parameter */ NULL , "shaderType", &shaderType ) )
{
shaderMetadata->writable()["shaderType"] = new StringData( shaderType );
}
return metadata;
}
typedef LRUCache<std::string, IECore::ConstCompoundDataPtr> MetadataCache;
MetadataCache g_arnoldMetadataCache( metadataGetter, 10000 );
const IECore::CompoundData *ArnoldShader::metadata() const
{
if( m_metadata )
{
return m_metadata.get();
}
m_metadata = g_arnoldMetadataCache.get( namePlug()->getValue() );
return m_metadata.get();
}
<commit_msg>ArnoldShader: handle lightfilters and add out plug<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012, John Haddon. All rights reserved.
// Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/format.hpp"
#include "ai.h"
#include "IECore/MessageHandler.h"
#include "IECore/LRUCache.h"
#include "IECoreArnold/UniverseBlock.h"
#include "Gaffer/NumericPlug.h"
#include "Gaffer/CompoundNumericPlug.h"
#include "Gaffer/StringPlug.h"
#include "GafferArnold/ArnoldShader.h"
#include "GafferArnold/ParameterHandler.h"
using namespace std;
using namespace boost;
using namespace Imath;
using namespace IECore;
using namespace GafferScene;
using namespace GafferArnold;
using namespace Gaffer;
IE_CORE_DEFINERUNTIMETYPED( ArnoldShader );
ArnoldShader::ArnoldShader( const std::string &name )
: GafferScene::Shader( name )
{
}
ArnoldShader::~ArnoldShader()
{
}
Gaffer::Plug *ArnoldShader::correspondingInput( const Gaffer::Plug *output )
{
// better to do a few harmless casts than manage a duplicate implementation
return const_cast<Gaffer::Plug *>(
const_cast<const ArnoldShader *>( this )->correspondingInput( output )
);
}
const Gaffer::Plug *ArnoldShader::correspondingInput( const Gaffer::Plug *output ) const
{
if( output != outPlug() )
{
return Shader::correspondingInput( output );
}
const CompoundData *metadata = ArnoldShader::metadata();
if( !metadata )
{
return NULL;
}
const StringData *primaryInput = static_cast<const StringData*>( metadata->member<IECore::CompoundData>( "shader" )->member<IECore::Data>( "primaryInput" ) );
if( !primaryInput )
{
return NULL;
}
const Plug *result = parametersPlug()->getChild<Plug>( primaryInput->readable() );
if( !result )
{
IECore::msg( IECore::Msg::Error, "ArnoldShader::correspondingInput", boost::format( "Parameter \"%s\" does not exist" ) % primaryInput->readable() );
return NULL;
}
return result;
}
void ArnoldShader::loadShader( const std::string &shaderName, bool keepExistingValues )
{
IECoreArnold::UniverseBlock arnoldUniverse( /* writable = */ false );
const AtNodeEntry *shader = AiNodeEntryLookUp( shaderName.c_str() );
if( !shader )
{
throw Exception( str( format( "Shader \"%s\" not found" ) % shaderName ) );
}
if( !keepExistingValues )
{
parametersPlug()->clearChildren();
if( Plug *out = outPlug() )
{
removeChild( out );
}
}
const bool isLightShader = AiNodeEntryGetType( shader ) == AI_NODE_LIGHT;
namePlug()->setValue( AiNodeEntryGetName( shader ) );
int aiOutputType = AI_TYPE_POINTER;
string type = "ai:light";
if( !isLightShader )
{
const CompoundData *metadata = ArnoldShader::metadata();
const StringData *shaderTypeData = static_cast<const StringData*>( metadata->member<IECore::CompoundData>( "shader" )->member<IECore::Data>( "shaderType" ) );
if( shaderTypeData )
{
type = "ai:" + shaderTypeData->readable();
}
else
{
type = "ai:surface";
}
if( type == "ai:surface" )
{
aiOutputType = AiNodeEntryGetOutputType( shader );
}
}
if( !keepExistingValues && type == "ai:lightFilter" )
{
attributeSuffixPlug()->setValue( shaderName );
}
typePlug()->setValue( type );
ParameterHandler::setupPlugs( shader, parametersPlug() );
ParameterHandler::setupPlug( "out", aiOutputType, this, Plug::Out );
}
//////////////////////////////////////////////////////////////////////////
// Metadata loading code
//////////////////////////////////////////////////////////////////////////
static IECore::ConstCompoundDataPtr metadataGetter( const std::string &key, size_t &cost )
{
IECoreArnold::UniverseBlock arnoldUniverse( /* writable = */ false );
const AtNodeEntry *shader = AiNodeEntryLookUp( key.c_str() );
if( !shader )
{
throw Exception( str( format( "Shader \"%s\" not found" ) % key ) );
}
CompoundDataPtr metadata = new CompoundData;
CompoundDataPtr shaderMetadata = new CompoundData;
metadata->writable()["shader"] = shaderMetadata;
// Currently we don't store metadata for parameters.
// We add the "parameter" CompoundData mainly so that we are consistent with the OSLShader.
// Eventually we will load all metadata here and access it from ArnoldShaderUI.
CompoundDataPtr parameterMetadata = new CompoundData;
metadata->writable()["parameter"] = parameterMetadata;
const char* value;
if( AiMetaDataGetStr( shader, /* look up metadata on node, not on parameter */ NULL , "primaryInput", &value ) )
{
shaderMetadata->writable()["primaryInput"] = new StringData( value );
}
const char* shaderType;
if( AiMetaDataGetStr( shader, /* look up metadata on node, not on parameter */ NULL , "shaderType", &shaderType ) )
{
shaderMetadata->writable()["shaderType"] = new StringData( shaderType );
}
return metadata;
}
typedef LRUCache<std::string, IECore::ConstCompoundDataPtr> MetadataCache;
MetadataCache g_arnoldMetadataCache( metadataGetter, 10000 );
const IECore::CompoundData *ArnoldShader::metadata() const
{
if( m_metadata )
{
return m_metadata.get();
}
m_metadata = g_arnoldMetadataCache.get( namePlug()->getValue() );
return m_metadata.get();
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2013 Jrgen Riegel <juergen.riegel@web.de> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QApplication>
# include <QClipboard>
#endif
#include "DlgUnitsCalculatorImp.h"
using namespace Gui::Dialog;
/* TRANSLATOR Gui::Dialog::DlgUnitsCalculator */
/**
* Constructs a DlgUnitsCalculator which is a child of 'parent', with the
* name 'name' and widget flags set to 'f'
*
* The dialog will by default be modeless, unless you set 'modal' to
* TRUE to construct a modal dialog.
*/
DlgUnitsCalculator::DlgUnitsCalculator( QWidget* parent, Qt::WFlags fl )
: QDialog( parent, fl )
{
// create widgets
setupUi(this);
this->setAttribute(Qt::WA_DeleteOnClose);
connect(this->ValueInput, SIGNAL(valueChanged(Base::Quantity)), this, SLOT(valueChanged(Base::Quantity)));
connect(this->UnitInput, SIGNAL(valueChanged(Base::Quantity)), this, SLOT(unitValueChanged(Base::Quantity)));
connect(this->pushButton_Help, SIGNAL(pressed()), this, SLOT(help()));
connect(this->pushButton_Close, SIGNAL(pressed()), this, SLOT(accept()));
connect(this->pushButton_Copy, SIGNAL(pressed()), this, SLOT(copy()));
connect(this->ValueInput, SIGNAL(parseError(QString)), this, SLOT(parseError(QString)));
connect(this->UnitInput, SIGNAL(parseError(QString)), this, SLOT(parseError(QString)));
actUnit.setInvalid();
}
/** Destroys the object and frees any allocated resources */
DlgUnitsCalculator::~DlgUnitsCalculator()
{
}
void DlgUnitsCalculator::accept()
{
QDialog::accept();
}
void DlgUnitsCalculator::reject()
{
QDialog::reject();
}
void DlgUnitsCalculator::unitValueChanged(const Base::Quantity& unit)
{
actUnit = unit;
valueChanged(actValue);
}
void DlgUnitsCalculator::valueChanged(const Base::Quantity& quant)
{
if(actUnit.isValid()){
if(actUnit.getUnit() != quant.getUnit()){
QPalette palette;
palette.setColor(QPalette::Base,QColor(255,200,200));
this->ValueOutput->setPalette(palette);
this->ValueOutput->setText(QString());
this->ValueOutput->setToolTip(QString::fromAscii("Unit missmatch"));
}else{
double value = quant.getValue()/actUnit.getValue();
QString out(QString::fromAscii("%1 %2"));
out = out.arg(value).arg(this->UnitInput->text());
this->ValueOutput->setText(out);
QPalette palette;
palette.setColor(QPalette::Base,QColor(200,255,200));
this->ValueOutput->setPalette(palette);
}
}else{
//this->ValueOutput->setValue(quant);
this->ValueOutput->setText(QString::fromAscii(quant.getUserString().c_str()));
QPalette palette;
palette.setColor(QPalette::Base,QColor(200,255,200));
this->ValueOutput->setPalette(palette);
}
actValue = quant;
}
void DlgUnitsCalculator::parseError(const QString& errorText)
{
QPalette palette;
palette.setColor(QPalette::Base,QColor(255,200,200));
this->ValueOutput->setPalette(palette);
this->ValueOutput->setText(QString());
}
void DlgUnitsCalculator::copy(void)
{
QClipboard *cb = QApplication::clipboard();
cb->setText(ValueOutput->text());
}
void DlgUnitsCalculator::help(void)
{
//TODO: call help page Std_UnitsCalculator
}
#include "moc_DlgUnitsCalculatorImp.cpp"
<commit_msg>+ Fix signal connections of buttons in units calculator<commit_after>/***************************************************************************
* Copyright (c) 2013 Jrgen Riegel <juergen.riegel@web.de> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QApplication>
# include <QClipboard>
#endif
#include "DlgUnitsCalculatorImp.h"
using namespace Gui::Dialog;
/* TRANSLATOR Gui::Dialog::DlgUnitsCalculator */
/**
* Constructs a DlgUnitsCalculator which is a child of 'parent', with the
* name 'name' and widget flags set to 'f'
*
* The dialog will by default be modeless, unless you set 'modal' to
* TRUE to construct a modal dialog.
*/
DlgUnitsCalculator::DlgUnitsCalculator( QWidget* parent, Qt::WFlags fl )
: QDialog( parent, fl )
{
// create widgets
setupUi(this);
this->setAttribute(Qt::WA_DeleteOnClose);
connect(this->ValueInput, SIGNAL(valueChanged(Base::Quantity)), this, SLOT(valueChanged(Base::Quantity)));
connect(this->UnitInput, SIGNAL(valueChanged(Base::Quantity)), this, SLOT(unitValueChanged(Base::Quantity)));
connect(this->pushButton_Help, SIGNAL(clicked()), this, SLOT(help()));
connect(this->pushButton_Close, SIGNAL(clicked()), this, SLOT(accept()));
connect(this->pushButton_Copy, SIGNAL(clicked()), this, SLOT(copy()));
connect(this->ValueInput, SIGNAL(parseError(QString)), this, SLOT(parseError(QString)));
connect(this->UnitInput, SIGNAL(parseError(QString)), this, SLOT(parseError(QString)));
actUnit.setInvalid();
}
/** Destroys the object and frees any allocated resources */
DlgUnitsCalculator::~DlgUnitsCalculator()
{
}
void DlgUnitsCalculator::accept()
{
QDialog::accept();
}
void DlgUnitsCalculator::reject()
{
QDialog::reject();
}
void DlgUnitsCalculator::unitValueChanged(const Base::Quantity& unit)
{
actUnit = unit;
valueChanged(actValue);
}
void DlgUnitsCalculator::valueChanged(const Base::Quantity& quant)
{
if(actUnit.isValid()){
if(actUnit.getUnit() != quant.getUnit()){
QPalette palette;
palette.setColor(QPalette::Base,QColor(255,200,200));
this->ValueOutput->setPalette(palette);
this->ValueOutput->setText(QString());
this->ValueOutput->setToolTip(QString::fromAscii("Unit missmatch"));
}else{
double value = quant.getValue()/actUnit.getValue();
QString out(QString::fromAscii("%1 %2"));
out = out.arg(value).arg(this->UnitInput->text());
this->ValueOutput->setText(out);
QPalette palette;
palette.setColor(QPalette::Base,QColor(200,255,200));
this->ValueOutput->setPalette(palette);
}
}else{
//this->ValueOutput->setValue(quant);
this->ValueOutput->setText(QString::fromAscii(quant.getUserString().c_str()));
QPalette palette;
palette.setColor(QPalette::Base,QColor(200,255,200));
this->ValueOutput->setPalette(palette);
}
actValue = quant;
}
void DlgUnitsCalculator::parseError(const QString& errorText)
{
QPalette palette;
palette.setColor(QPalette::Base,QColor(255,200,200));
this->ValueOutput->setPalette(palette);
this->ValueOutput->setText(QString());
}
void DlgUnitsCalculator::copy(void)
{
QClipboard *cb = QApplication::clipboard();
cb->setText(ValueOutput->text());
}
void DlgUnitsCalculator::help(void)
{
//TODO: call help page Std_UnitsCalculator
}
#include "moc_DlgUnitsCalculatorImp.cpp"
<|endoftext|> |
<commit_before>/*
Copyright 2011 StormMQ 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 <TestHarness.h>
#include "Buffer/BufferTestSupport.h"
#include "Context/ErrorHandling.h"
#include "debug_helper.h"
SUITE(Buffer)
{
unsigned char simple_test_data[] = {
0x70, 0x10, 0x07, 0x03, 0x01
};
class LoadedBufferFixture : public BufferFixture
{
public:
LoadedBufferFixture()
{
load_buffer(simple_test_data, sizeof(simple_test_data));
}
~LoadedBufferFixture()
{
}
public:
};
TEST_FIXTURE(BufferFixture, allocation)
{
CHECK_EQUAL(1UL, pool.stats.outstanding_allocations);
CHECK_EQUAL(1UL, pool.stats.total_allocation_calls);
// break_one();
amqp_deallocate(&pool, buffer);
buffer = 0;
CHECK_EQUAL(0UL, pool.stats.outstanding_allocations);
CHECK_EQUAL(1UL, pool.stats.total_allocation_calls);
}
TEST_FIXTURE(LoadedBufferFixture, amqp_buffer_wrap_array)
{
CHECK_EQUAL(buffer->limit.index, (size_t) 0);
CHECK_EQUAL(buffer->limit.size, sizeof(simple_test_data));
for (size_t i = 0; i < sizeof(simple_test_data); i++)
{
CHECK_EQUAL(buffer->bytes[i], simple_test_data[i]);
}
}
TEST_FIXTURE(LoadedBufferFixture, amqp_buffer_at_end)
{
amqp_buffer_reset(buffer);
CHECK(amqp_buffer_at_end(buffer));
}
TEST_FIXTURE(LoadedBufferFixture, getc)
{
CHECK_EQUAL(amqp_buffer_getc(buffer), 0x70);
CHECK_EQUAL(amqp_buffer_getc(buffer), 0x10);
CHECK_EQUAL(amqp_buffer_getc(buffer), 0x07);
CHECK_EQUAL(amqp_buffer_getc(buffer), 0x03);
CHECK_EQUAL(amqp_buffer_getc(buffer), 0x01);
CHECK(amqp_buffer_at_end(buffer));
CHECK_EQUAL(amqp_buffer_getc(buffer), -1);
}
TEST_FIXTURE(BufferFixture, amqp_ntoh_16_unsigned)
{
uint16_t v;
unsigned char data[] = { 0x01, 0x02 };
load_buffer(data, sizeof(data));
v = amqp_ntoh_16(buffer, 0)._ushort;
CHECK_EQUAL(0x0102, v);
}
TEST_FIXTURE(BufferFixture, amqp_ntoh_16)
{
int16_t v;
unsigned char data[] = { 0xff, 0xfe };
load_buffer(data, sizeof(data));
v = amqp_ntoh_16(buffer, 0)._short;
CHECK_EQUAL(-2, v);
}
TEST_FIXTURE(BufferFixture, amqp_ntoh_32)
{
uint32_t v;
unsigned char data[] = { 0x01, 0x02, 0x04, 0x08 };
load_buffer(data, sizeof(data));
v = amqp_ntoh_32(buffer, 0)._uint;
CHECK_EQUAL(0x01020408U, v);
}
TEST_FIXTURE(BufferFixture, amqp_ntoh_64)
{
unsigned char data[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
load_buffer(data, sizeof(data));
amqp_eight_byte_t v;
amqp_ntoh_64(&v, buffer, 0);
CHECK_EQUAL(0x0102040810204080ULL, v._ulong);
}
TEST_FIXTURE(BufferFixture, amqp_hton_16)
{
amqp_two_byte_t v;
v._short = -2;
amqp_hton_16(buffer, v);
CHECK_EQUAL((size_t) 0, buffer->limit.index);
CHECK_EQUAL((size_t) 2, buffer->limit.size);
CHECK_EQUAL(0xfe, buffer->bytes[1]);
CHECK_EQUAL(-2, amqp_ntoh_16(buffer, 0)._short);
}
TEST_FIXTURE(BufferFixture, amqp_hton_32)
{
amqp_four_byte_t v;
v._int = -2;
amqp_hton_32(buffer, v);
CHECK_EQUAL((size_t) 0, buffer->limit.index);
CHECK_EQUAL((size_t) 4, buffer->limit.size);
CHECK_EQUAL(0xfe, buffer->bytes[3]);
CHECK_EQUAL(-2, amqp_ntoh_32(buffer, 0)._int);
}
TEST_FIXTURE(BufferFixture, amqp_hton_64)
{
amqp_eight_byte_t v;
v._long = -2;
amqp_hton_64(buffer, v);
CHECK_EQUAL((size_t) 0, buffer->limit.index);
CHECK_EQUAL((size_t) 8, buffer->limit.size);
CHECK_EQUAL(0xfe, buffer->bytes[7]);
amqp_eight_byte_t verify;
amqp_ntoh_64(&verify, buffer, 0);
CHECK_EQUAL(-2, verify._long);
}
TEST_FIXTURE(BufferFixture, amqp_buffer_read_size_one)
{
unsigned char data[] = { 0x01, 0x02, 0x0a, 0x0e };
load_buffer(data, sizeof(data));
CHECK_EQUAL(1U, amqp_buffer_read_size(buffer, 1));
CHECK_EQUAL(2U, amqp_buffer_read_size(buffer, 1));
CHECK_EQUAL(10U, amqp_buffer_read_size(buffer, 1));
CHECK_EQUAL(14U, amqp_buffer_read_size(buffer, 1));
CHECK_EQUAL(-1U, amqp_buffer_read_size(buffer, 1));
}
TEST_FIXTURE(BufferFixture, amqp_buffer_read_size_four)
{
unsigned char data[] = { 0, 0, 0, 0x0e, 0, 0, 2, 1 };
load_buffer(data, sizeof(data));
CHECK_EQUAL(14U, amqp_buffer_read_size(buffer, 4));
CHECK_EQUAL(513U, amqp_buffer_read_size(buffer, 4));
CHECK_EQUAL(-1U, amqp_buffer_read_size(buffer, 4));
}
TEST_FIXTURE(BufferFixture, amqp_buffer_read_size_bad)
{
unsigned char data[] = { 0, 0,0x0e};
load_buffer(data, sizeof(data));
CHECK_EQUAL(-1U, amqp_buffer_read_size(buffer, 4));
}
}
<commit_msg>Cleanup windows build warnings.<commit_after>/*
Copyright 2011 StormMQ 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 <TestHarness.h>
#include "Buffer/BufferTestSupport.h"
#include "Context/ErrorHandling.h"
#include "debug_helper.h"
SUITE(Buffer)
{
unsigned char simple_test_data[] = {
0x70, 0x10, 0x07, 0x03, 0x01
};
class LoadedBufferFixture : public BufferFixture
{
public:
LoadedBufferFixture()
{
load_buffer(simple_test_data, sizeof(simple_test_data));
}
~LoadedBufferFixture()
{
}
public:
};
TEST_FIXTURE(BufferFixture, allocation)
{
CHECK_EQUAL(1UL, pool.stats.outstanding_allocations);
CHECK_EQUAL(1UL, pool.stats.total_allocation_calls);
// break_one();
amqp_deallocate(&pool, buffer);
buffer = 0;
CHECK_EQUAL(0UL, pool.stats.outstanding_allocations);
CHECK_EQUAL(1UL, pool.stats.total_allocation_calls);
}
TEST_FIXTURE(LoadedBufferFixture, amqp_buffer_wrap_array)
{
CHECK_EQUAL(buffer->limit.index, (size_t) 0);
CHECK_EQUAL(buffer->limit.size, sizeof(simple_test_data));
for (size_t i = 0; i < sizeof(simple_test_data); i++)
{
CHECK_EQUAL(buffer->bytes[i], simple_test_data[i]);
}
}
TEST_FIXTURE(LoadedBufferFixture, amqp_buffer_at_end)
{
amqp_buffer_reset(buffer);
CHECK(amqp_buffer_at_end(buffer));
}
TEST_FIXTURE(LoadedBufferFixture, getc)
{
CHECK_EQUAL(amqp_buffer_getc(buffer), 0x70);
CHECK_EQUAL(amqp_buffer_getc(buffer), 0x10);
CHECK_EQUAL(amqp_buffer_getc(buffer), 0x07);
CHECK_EQUAL(amqp_buffer_getc(buffer), 0x03);
CHECK_EQUAL(amqp_buffer_getc(buffer), 0x01);
CHECK(amqp_buffer_at_end(buffer));
CHECK_EQUAL(amqp_buffer_getc(buffer), -1);
}
TEST_FIXTURE(BufferFixture, amqp_ntoh_16_unsigned)
{
uint16_t v;
unsigned char data[] = { 0x01, 0x02 };
load_buffer(data, sizeof(data));
v = amqp_ntoh_16(buffer, 0)._ushort;
CHECK_EQUAL(0x0102, v);
}
TEST_FIXTURE(BufferFixture, amqp_ntoh_16)
{
int16_t v;
unsigned char data[] = { 0xff, 0xfe };
load_buffer(data, sizeof(data));
v = amqp_ntoh_16(buffer, 0)._short;
CHECK_EQUAL(-2, v);
}
TEST_FIXTURE(BufferFixture, amqp_ntoh_32)
{
uint32_t v;
unsigned char data[] = { 0x01, 0x02, 0x04, 0x08 };
load_buffer(data, sizeof(data));
v = amqp_ntoh_32(buffer, 0)._uint;
CHECK_EQUAL(0x01020408U, v);
}
TEST_FIXTURE(BufferFixture, amqp_ntoh_64)
{
unsigned char data[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
load_buffer(data, sizeof(data));
amqp_eight_byte_t v;
amqp_ntoh_64(&v, buffer, 0);
CHECK_EQUAL(0x0102040810204080ULL, v._ulong);
}
TEST_FIXTURE(BufferFixture, amqp_hton_16)
{
amqp_two_byte_t v;
v._short = -2;
amqp_hton_16(buffer, v);
CHECK_EQUAL((size_t) 0, buffer->limit.index);
CHECK_EQUAL((size_t) 2, buffer->limit.size);
CHECK_EQUAL(0xfe, buffer->bytes[1]);
CHECK_EQUAL(-2, amqp_ntoh_16(buffer, 0)._short);
}
TEST_FIXTURE(BufferFixture, amqp_hton_32)
{
amqp_four_byte_t v;
v._int = -2;
amqp_hton_32(buffer, v);
CHECK_EQUAL((size_t) 0, buffer->limit.index);
CHECK_EQUAL((size_t) 4, buffer->limit.size);
CHECK_EQUAL(0xfe, buffer->bytes[3]);
CHECK_EQUAL(-2, amqp_ntoh_32(buffer, 0)._int);
}
TEST_FIXTURE(BufferFixture, amqp_hton_64)
{
amqp_eight_byte_t v;
v._long = -2;
amqp_hton_64(buffer, v);
CHECK_EQUAL((size_t) 0, buffer->limit.index);
CHECK_EQUAL((size_t) 8, buffer->limit.size);
CHECK_EQUAL(0xfe, buffer->bytes[7]);
amqp_eight_byte_t verify;
amqp_ntoh_64(&verify, buffer, 0);
CHECK_EQUAL(-2, verify._long);
}
TEST_FIXTURE(BufferFixture, amqp_buffer_read_size_one)
{
unsigned char data[] = { 0x01, 0x02, 0x0a, 0x0e };
load_buffer(data, sizeof(data));
CHECK_EQUAL(1U, amqp_buffer_read_size(buffer, 1));
CHECK_EQUAL(2U, amqp_buffer_read_size(buffer, 1));
CHECK_EQUAL(10U, amqp_buffer_read_size(buffer, 1));
CHECK_EQUAL(14U, amqp_buffer_read_size(buffer, 1));
CHECK_EQUAL((uint32_t) -1, amqp_buffer_read_size(buffer, 1));
}
TEST_FIXTURE(BufferFixture, amqp_buffer_read_size_four)
{
unsigned char data[] = { 0, 0, 0, 0x0e, 0, 0, 2, 1 };
load_buffer(data, sizeof(data));
CHECK_EQUAL(14U, amqp_buffer_read_size(buffer, 4));
CHECK_EQUAL(513U, amqp_buffer_read_size(buffer, 4));
CHECK_EQUAL((uint32_t) -1, amqp_buffer_read_size(buffer, 4));
}
TEST_FIXTURE(BufferFixture, amqp_buffer_read_size_bad)
{
unsigned char data[] = { 0, 0,0x0e};
load_buffer(data, sizeof(data));
CHECK_EQUAL((uint32_t) -1, amqp_buffer_read_size(buffer, 4));
}
}
<|endoftext|> |
<commit_before>#include "cld2wrapper.h"
CLD2Wrapper::CLD2Wrapper()
{
}
const char* CLD2Wrapper::detect(const char* &buffer) {
int FLAGS_repeat = 1;
bool FLAGS_plain = false;
// Detect language
const char* tldhint = "";
int enchint = UNKNOWN_ENCODING;
CLD2::Language langhint = CLD2::UNKNOWN_LANGUAGE;
int flags = 0;
bool is_reliable;
// Full-blown flag-bit and hints interface
bool allow_extended_lang = true;
CLD2::Language plus_one = CLD2::UNKNOWN_LANGUAGE;
int n = strlen(buffer);
// Detect language
CLD2::Language summary_lang = CLD2::UNKNOWN_LANGUAGE;
CLD2::Language language3[3];
int percent3[3];
double normalized_score3[3];
CLD2::ResultChunkVector resultchunkvector;
bool is_plain_text = FLAGS_plain;
int text_bytes;
CLD2::CLDHints cldhints = { NULL, tldhint, enchint, langhint };
for (int i = 0; i < FLAGS_repeat; ++i) {
summary_lang = CLD2::DetectLanguageSummaryV2(buffer, n, is_plain_text,
&cldhints, allow_extended_lang, flags, plus_one, language3,
percent3, normalized_score3,
NULL, &text_bytes, &is_reliable);
}
return CLD2::LanguageName(summary_lang);
}
<commit_msg>converted tabs<commit_after>#include "cld2wrapper.h"
CLD2Wrapper::CLD2Wrapper()
{
}
const char* CLD2Wrapper::detect(const char* &buffer) {
int FLAGS_repeat = 1;
bool FLAGS_plain = false;
// Detect language
const char* tldhint = "";
int enchint = UNKNOWN_ENCODING;
CLD2::Language langhint = CLD2::UNKNOWN_LANGUAGE;
int flags = 0;
bool is_reliable;
// Full-blown flag-bit and hints interface
bool allow_extended_lang = true;
CLD2::Language plus_one = CLD2::UNKNOWN_LANGUAGE;
int n = strlen(buffer);
// Detect language
CLD2::Language summary_lang = CLD2::UNKNOWN_LANGUAGE;
CLD2::Language language3[3];
int percent3[3];
double normalized_score3[3];
CLD2::ResultChunkVector resultchunkvector;
bool is_plain_text = FLAGS_plain;
int text_bytes;
CLD2::CLDHints cldhints = { NULL, tldhint, enchint, langhint };
for (int i = 0; i < FLAGS_repeat; ++i) {
summary_lang = CLD2::DetectLanguageSummaryV2(buffer, n, is_plain_text,
&cldhints, allow_extended_lang, flags, plus_one, language3,
percent3, normalized_score3,
NULL, &text_bytes, &is_reliable);
}
return CLD2::LanguageName(summary_lang);
}
<|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/>.
*/
#if !defined(STLHELPERS_HEADER_GUARD_1357924680)
#define STLHELPERS_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include "PlatformSupportDefinitions.hpp"
#include <functional>
/**
* Functor to delete objects, used in STL iteration algorithms.
*/
template <class T>
#if defined(XALAN_NO_NAMESPACES)
struct DeleteFunctor : public unary_function<const T*, void>
#else
struct DeleteFunctor : public std::unary_function<const T*, void>
#endif
{
/**
* Delete the object pointed to by argument.
*
* @param thePointer pointer to object to be deleted
*/
typename result_type
operator()(typename argument_type thePointer) const
{
delete thePointer;
}
};
template<class T>
class array_auto_ptr
{
public:
array_auto_ptr(T* thePointer) :
m_pointer(thePointer)
{
}
~array_auto_ptr()
{
delete [] m_pointer;
}
T*
get() const
{
return m_pointer;
}
T*
release()
{
T* const temp = m_pointer;
m_pointer = 0;
return temp;
}
private:
T* m_pointer;
};
#if ! defined(__GNUC__)
/**
* Functor to retrieve the key of a key-value pair in a map, used in STL
* iteration algorithms.
*/
template <class PairType>
#if defined(XALAN_NO_NAMESPACES)
struct select1st : public unary_function<PairType, PairType::first_type>
#else
struct select1st : public std::unary_function<PairType, PairType::first_type>
#endif
{
typedef typename PairType value_type;
/**
* Retrieve the key of a key-value pair.
*
* @param thePair key-value pair
* @return key
*/
typename result_type
operator()(const typename argument_type& thePair) const
{
return thePair.first;
}
};
/**
* Functor to retrieve the value of a key-value pair in a map, used in STL
* iteration algorithms.
*/
template <class PairType>
#if defined(XALAN_NO_NAMESPACES)
struct select2nd : public unary_function<PairType, PairType::second_type>
#else
struct select2nd : public std::unary_function<PairType, PairType::second_type>
#endif
{
typedef typename PairType value_type;
/**
* Retrieve the value of a key-value pair.
*
* @param thePair key-value pair
* @return value
*/
typename result_type
operator()(const typename argument_type& thePair)
{
return thePair.second;
}
};
#endif
/**
* Functor to delete value objects in maps, used in STL iteration algorithms.
*/
template <class T>
#if defined(XALAN_NO_NAMESPACES)
struct MapValueDeleteFunctor : public unary_function<const T::value_type&, void>
#else
struct MapValueDeleteFunctor : public std::unary_function<const typename T::value_type&, void>
#endif
{
/**
* Delete the value object in a map value pair. The value of the pair must
* be of pointer type.
*
* @param thePair key-value pair
*/
typename result_type
operator()(typename argument_type thePair)
{
delete thePair.second;
}
};
template<class T>
MapValueDeleteFunctor<T>
makeMapValueDeleteFunctor(const T& /* theMap */)
{
return MapValueDeleteFunctor<T>();
}
template <class T>
#if defined(XALAN_NO_NAMESPACES)
struct MapKeyDeleteFunctor : public unary_function<const T::value_type&, void>
#else
struct MapKeyDeleteFunctor : public std::unary_function<const typename T::value_type&, void>
#endif
{
/**
* Delete the value object in a map value pair. The value of the pair must
* be of pointer type.
*
* @param thePair key-value pair
*/
typename result_type
operator()(typename argument_type thePair)
{
delete thePair.first;
}
};
template<class T>
MapKeyDeleteFunctor<T>
makeMapKeyDeleteFunctor(const T& /* theMap */)
{
return MapKeyDeleteFunctor<T>();
}
/**
* Template allows nested execution of for_each algorithm by defining a unary
* functor that takes a container object as an argument, allowing iteration
* through the container.
*/
template<class T, class Functor>
#if defined(XALAN_NO_NAMESPACES)
struct nested_for_each_functor : public unary_function<const T::value_type&, Functor>
#else
struct nested_for_each_functor : public std::unary_function<const typename T::value_type&, Functor>
#endif
{
/**
* Construct a nested_for_each_functor instance.
*
* @param theFunctor functor to use as return type
*/
nested_for_each_functor(Functor theFunctor) :
m_functor(theFunctor)
{
}
/**
* Execute the () operator, with the side effect of calling for_each on
* each element in the container argument with the functor member.
*
* @param theContainer container object
*/
typename T::result_type
operator()(typename argument_type theContainer)
{
return for_each(theContainer.begin(),
theContainer.end(),
m_functor);
}
private:
Functor m_functor;
};
/**
* This functor is designed to compare 0-terminated arrays. It substitutes
* for the default less<type*> so that pointers to arrays can be compared,
* rather than copies of arrays. For example, you might want to use C-style
* strings as keys in a map, rather than string objects. The default
* algorithm less<const char*> would just compare the pointers, and not the
* vector of characters to which it points. Using this algorithm instead of
* the default will allow the map to work as expected.
*/
template<class T>
#if defined(XALAN_NO_NAMESPACES)
struct less_null_terminated_arrays : public binary_function<const T*, const T*, bool>
#else
struct less_null_terminated_arrays : public std::binary_function<const T*, const T*, bool>
#endif
{
/**
* Compare the values of two objects.
*
*
* @param theLHS first object to compare
* @param theRHS second object to compare
* @return true if objects are the same
*/
typename result_type
operator()(typename first_argument_type theLHS,
typename second_argument_type theRHS) const
{
while(*theLHS && *theRHS)
{
if (*theLHS != *theRHS)
{
break;
}
else
{
theLHS++;
theRHS++;
}
}
return *theLHS < *theRHS ? true : false;
}
};
#endif // STLHELPERS_HEADER_GUARD_1357924680
<commit_msg>Removed use of typename, which was confusing gcc.<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/>.
*/
#if !defined(STLHELPERS_HEADER_GUARD_1357924680)
#define STLHELPERS_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include "PlatformSupportDefinitions.hpp"
#include <functional>
/**
* Functor to delete objects, used in STL iteration algorithms.
*/
template <class T>
#if defined(XALAN_NO_NAMESPACES)
struct DeleteFunctor : public unary_function<const T*, void>
#else
struct DeleteFunctor : public std::unary_function<const T*, void>
#endif
{
/**
* Delete the object pointed to by argument.
*
* @param thePointer pointer to object to be deleted
*/
result_type
operator()(argument_type thePointer) const
{
delete thePointer;
}
};
template<class T>
class array_auto_ptr
{
public:
array_auto_ptr(T* thePointer) :
m_pointer(thePointer)
{
}
~array_auto_ptr()
{
delete [] m_pointer;
}
T*
get() const
{
return m_pointer;
}
T*
release()
{
T* const temp = m_pointer;
m_pointer = 0;
return temp;
}
private:
T* m_pointer;
};
#if !defined(XALAN_SGI_BASED_STL)
/**
* Functor to retrieve the key of a key-value pair in a map, used in STL
* iteration algorithms.
*/
template <class PairType>
#if defined(XALAN_NO_NAMESPACES)
struct select1st : public unary_function<PairType, PairType::first_type>
#else
struct select1st : public std::unary_function<PairType, PairType::first_type>
#endif
{
typedef typename PairType value_type;
/**
* Retrieve the key of a key-value pair.
*
* @param thePair key-value pair
* @return key
*/
typename result_type
operator()(const typename argument_type& thePair) const
{
return thePair.first;
}
};
/**
* Functor to retrieve the value of a key-value pair in a map, used in STL
* iteration algorithms.
*/
template <class PairType>
#if defined(XALAN_NO_NAMESPACES)
struct select2nd : public unary_function<PairType, PairType::second_type>
#else
struct select2nd : public std::unary_function<PairType, PairType::second_type>
#endif
{
typedef typename PairType value_type;
/**
* Retrieve the value of a key-value pair.
*
* @param thePair key-value pair
* @return value
*/
typename result_type
operator()(const typename argument_type& thePair) const
{
return thePair.second;
}
};
#endif
/**
* Functor to delete value objects in maps, used in STL iteration algorithms.
*/
template <class T>
#if defined(XALAN_NO_NAMESPACES)
struct MapValueDeleteFunctor : public unary_function<const T::value_type&, void>
#else
struct MapValueDeleteFunctor : public std::unary_function<const typename T::value_type&, void>
#endif
{
/**
* Delete the value object in a map value pair. The value of the pair must
* be of pointer type.
*
* @param thePair key-value pair
*/
result_type
operator()(argument_type thePair) const
{
delete thePair.second;
}
};
template<class T>
MapValueDeleteFunctor<T>
makeMapValueDeleteFunctor(const T& /* theMap */)
{
return MapValueDeleteFunctor<T>();
}
template <class T>
#if defined(XALAN_NO_NAMESPACES)
struct MapKeyDeleteFunctor : public unary_function<const T::value_type&, void>
#else
struct MapKeyDeleteFunctor : public std::unary_function<const typename T::value_type&, void>
#endif
{
/**
* Delete the value object in a map value pair. The value of the pair must
* be of pointer type.
*
* @param thePair key-value pair
*/
result_type
operator()(argument_type thePair)
{
delete thePair.first;
}
};
template<class T>
MapKeyDeleteFunctor<T>
makeMapKeyDeleteFunctor(const T& /* theMap */)
{
return MapKeyDeleteFunctor<T>();
}
/**
* This functor is designed to compare 0-terminated arrays. It substitutes
* for the default less<type*> so that pointers to arrays can be compared,
* rather than copies of arrays. For example, you might want to use C-style
* strings as keys in a map, rather than string objects. The default
* algorithm less<const char*> would just compare the pointers, and not the
* vector of characters to which it points. Using this algorithm instead of
* the default will allow the map to work as expected.
*/
template<class T>
#if defined(XALAN_NO_NAMESPACES)
struct less_null_terminated_arrays : public binary_function<const T*, const T*, bool>
#else
struct less_null_terminated_arrays : public std::binary_function<const T*, const T*, bool>
#endif
{
/**
* Compare the values of two objects.
*
*
* @param theLHS first object to compare
* @param theRHS second object to compare
* @return true if objects are the same
*/
result_type
operator()(
first_argument_type theLHS,
second_argument_type theRHS) const
{
while(*theLHS && *theRHS)
{
if (*theLHS != *theRHS)
{
break;
}
else
{
theLHS++;
theRHS++;
}
}
return *theLHS < *theRHS ? true : false;
}
};
#endif // STLHELPERS_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "CppUTest/TestHarness.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/TestRegistry.h"
#include "CppUTest/TestTestingFixture.h"
static bool afterCheck;
TEST_GROUP(UtestShell)
{
TestTestingFixture* fixture;
void setup()
{
fixture = new TestTestingFixture();
afterCheck = false;
}
void teardown()
{
delete fixture;
}
void testFailureWith(void(*method)())
{
fixture->setTestFunction(method);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
CHECK(!afterCheck);
}
void testFailureWithMethodShouldContain(void(*method)(), const char * expected)
{
fixture->setTestFunction(method);
fixture->runAllTests();
fixture->assertPrintContains(expected);
LONGS_EQUAL(1, fixture->getFailureCount());
CHECK(!afterCheck);
}
};
static void _passMethod()
{
CHECK(true);
afterCheck = true;
}
static void _passPrint()
{
UT_PRINT("Hello World!");
}
static void _passPrintF()
{
UT_PRINT(StringFromFormat("Hello %s %d", "World!", 2009));
}
static void _failMethod()
{
FAIL("This test fails");
afterCheck = true;
}
static void _failMethodFAIL_TEST()
{
FAIL_TEST("This test fails");
afterCheck = true;
}
static void _failMethodCHECK()
{
CHECK(false);
afterCheck = true;
}
static void _failMethodCHECK_TRUE()
{
CHECK_TRUE(false);
afterCheck = true;
}
static void _failMethodCHECK_FALSE()
{
CHECK_FALSE(true);
afterCheck = true;
}
static void _failMethodCHECK_EQUAL()
{
CHECK_EQUAL(1, 2);
afterCheck = true;
}
static void _failMethodSTRCMP_CONTAINS()
{
STRCMP_CONTAINS("hello", "world");
afterCheck = true;
}
static void _failMethodSTRCMP_NOCASE_CONTAINS()
{
STRCMP_NOCASE_CONTAINS("hello", "WORLD");
afterCheck = true;
}
static void _failMethodLONGS_EQUAL()
{
LONGS_EQUAL(1, 0xff);
afterCheck = true;
}
static void _failMethodBYTES_EQUAL()
{
BYTES_EQUAL('a', 'b');
afterCheck = true;
}
static void _failMethodPOINTERS_EQUAL()
{
POINTERS_EQUAL((void*)0xa5a5, (void*)0xf0f0);
afterCheck = true;
}
static void _failMethodDOUBLES_EQUAL()
{
DOUBLES_EQUAL(0.12, 44.1, 0.3);
afterCheck = true;
}
TEST(UtestShell, FailurePrintsSomething)
{
testFailureWith(_failMethod);
fixture->assertPrintContains(__FILE__);
fixture->assertPrintContains("This test fails");
}
TEST(UtestShell, FailureWithFailTest)
{
testFailureWith(_failMethodFAIL_TEST);
}
TEST(UtestShell, FailurePrintHexOutputForLongInts)
{
testFailureWith(_failMethodLONGS_EQUAL);
fixture->assertPrintContains("expected < 1 0x01>");
fixture->assertPrintContains("but was <255 0xff>");
}
TEST(UtestShell, FailurePrintHexOutputForPointers)
{
testFailureWith(_failMethodPOINTERS_EQUAL);
fixture->assertPrintContains("expected <0xa5a5>");
fixture->assertPrintContains("but was <0xf0f0>");
}
TEST(UtestShell, FailureWithDOUBLES_EQUAL)
{
testFailureWith(_failMethodDOUBLES_EQUAL);
}
#include "CppUTest/PlatformSpecificFunctions.h"
TEST(UtestShell, compareDoubles)
{
double zero = 0.0;
double not_a_number = zero / zero;
CHECK(doubles_equal(1.0, 1.001, 0.01));
CHECK(!doubles_equal(not_a_number, 1.001, 0.01));
CHECK(!doubles_equal(1.0, not_a_number, 0.01));
CHECK(!doubles_equal(1.0, 1.001, not_a_number));
CHECK(!doubles_equal(1.0, 1.1, 0.05));
double a = 1.2345678;
CHECK(doubles_equal(a, a, 0.000000001));
}
TEST(UtestShell, FailureWithCHECK)
{
testFailureWith(_failMethodCHECK);
}
TEST(UtestShell, FailureWithCHECK_TRUE)
{
testFailureWith(_failMethodCHECK_TRUE);
fixture->assertPrintContains("CHECK_TRUE");
}
TEST(UtestShell, FailureWithCHECK_FALSE)
{
testFailureWith(_failMethodCHECK_FALSE);
fixture->assertPrintContains("CHECK_FALSE");
}
TEST(UtestShell, FailureWithCHECK_EQUAL)
{
testFailureWith(_failMethodCHECK_EQUAL);
}
TEST(UtestShell, FailureWithSTRCMP_CONTAINS)
{
testFailureWith(_failMethodSTRCMP_CONTAINS);
}
TEST(UtestShell, FailureWithSTRCMP_NOCASE_CONTAINS)
{
testFailureWith(_failMethodSTRCMP_NOCASE_CONTAINS);
}
TEST(UtestShell, FailureWithBYTES_EQUAL)
{
testFailureWith(_failMethodBYTES_EQUAL);
}
TEST(UtestShell, SuccessPrintsNothing)
{
fixture->setTestFunction(_passMethod);
fixture->runAllTests();
LONGS_EQUAL(0, fixture->getFailureCount());
fixture->assertPrintContains(".\nOK (1 tests");
CHECK(afterCheck);
}
TEST(UtestShell, PrintPrintsWhateverPrintPrints)
{
fixture->setTestFunction(_passPrint);
fixture->runAllTests();
LONGS_EQUAL(0, fixture->getFailureCount());
fixture->assertPrintContains("Hello World!");
fixture->assertPrintContains(__FILE__);
}
TEST(UtestShell, PrintPrintsPrintf)
{
fixture->setTestFunction(_passPrintF);
fixture->runAllTests();
LONGS_EQUAL(0, fixture->getFailureCount());
fixture->assertPrintContains("Hello World! 2009");
}
TEST(UtestShell, allMacros)
{
CHECK(0 == 0);
LONGS_EQUAL(1,1);
BYTES_EQUAL(0xab,0xab);
CHECK_EQUAL(100,100);
STRCMP_EQUAL("THIS", "THIS");
STRCMP_CONTAINS("THIS", "THISTHAT");
STRCMP_NOCASE_EQUAL("this", "THIS");
STRCMP_NOCASE_CONTAINS("this", "THISTHAT");
DOUBLES_EQUAL(1.0, 1.0, .01);
POINTERS_EQUAL(this, this);
}
static int functionThatReturnsAValue()
{
CHECK(0 == 0);
LONGS_EQUAL(1,1);
BYTES_EQUAL(0xab,0xab);
CHECK_EQUAL(100,100);
STRCMP_EQUAL("THIS", "THIS");
DOUBLES_EQUAL(1.0, 1.0, .01);
POINTERS_EQUAL(0, 0);
return 0;
}
TEST(UtestShell, allMacrosFromFunctionThatReturnsAValue)
{
functionThatReturnsAValue();
}
TEST(UtestShell, AssertsActLikeStatements)
{
if (fixture != 0) CHECK(true)
else CHECK(false)
if (fixture != 0) CHECK_EQUAL(true, true)
else CHECK_EQUAL(false, false)
if (fixture != 0) STRCMP_EQUAL("", "")
else STRCMP_EQUAL("", " ")
if (fixture != 0)
STRCMP_CONTAINS("con", "contains")
else
STRCMP_CONTAINS("hello", "world")
if (fixture != 0)
LONGS_EQUAL(1, 1)
else
LONGS_EQUAL(1, 0)
if (fixture != 0)
DOUBLES_EQUAL(1, 1, 0.01)
else
DOUBLES_EQUAL(1, 0, 0.01)
if (false)
FAIL("")
else CHECK(true);;
if (true) ;
else
FAIL("")
}
IGNORE_TEST(UtestShell, IgnoreTestSupportsAllMacros)
{
CHECK(true);
CHECK_EQUAL(true, true);
STRCMP_EQUAL("", "");
LONGS_EQUAL(1, 1);
DOUBLES_EQUAL(1, 1, 0.01);
FAIL("");
}
IGNORE_TEST(UtestShell, IgnoreTestAccessingFixture)
{
CHECK(fixture != 0);
}
TEST(UtestShell, MacrosUsedInSetup)
{
IGNORE_ALL_LEAKS_IN_TEST();
fixture->setSetup(_failMethod);
fixture->setTestFunction(_passMethod);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
}
TEST(UtestShell, MacrosUsedInTearDown)
{
IGNORE_ALL_LEAKS_IN_TEST();
fixture->setTeardown(_failMethod);
fixture->setTestFunction(_passMethod);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
}
static int teardownCalled = 0;
static void _teardownMethod()
{
teardownCalled++;
}
TEST(UtestShell, TeardownCalledAfterTestFailure)
{
teardownCalled = 0;
IGNORE_ALL_LEAKS_IN_TEST();
fixture->setTeardown(_teardownMethod);
fixture->setTestFunction(_failMethod);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
LONGS_EQUAL(1, teardownCalled);
}
static int stopAfterFailure = 0;
static void _stopAfterFailureMethod()
{
FAIL("fail");
stopAfterFailure++;
}
TEST(UtestShell, TestStopsAfterTestFailure)
{
IGNORE_ALL_LEAKS_IN_TEST();
stopAfterFailure = 0;
fixture->setTestFunction(_stopAfterFailureMethod);
fixture->runAllTests();
LONGS_EQUAL(1, fixture->getFailureCount());
LONGS_EQUAL(0, stopAfterFailure);
}
TEST(UtestShell, TestStopsAfterSetupFailure)
{
stopAfterFailure = 0;
fixture->setSetup(_stopAfterFailureMethod);
fixture->setTeardown(_stopAfterFailureMethod);
fixture->setTestFunction(_failMethod);
fixture->runAllTests();
LONGS_EQUAL(2, fixture->getFailureCount());
LONGS_EQUAL(0, stopAfterFailure);
}
#if CPPUTEST_USE_STD_CPP_LIB
static bool destructorWasCalledOnFailedTest = false;
class DestructorOughtToBeCalled
{
public:
virtual ~DestructorOughtToBeCalled()
{
destructorWasCalledOnFailedTest = true;
}
};
static void _destructorCalledForLocalObjects()
{
DestructorOughtToBeCalled pleaseCallTheDestructor;
destructorWasCalledOnFailedTest = false;
FAIL("fail");
}
TEST(UtestShell, DestructorIsCalledForLocalObjectsWhenTheTestFails)
{
fixture->setTestFunction(_destructorCalledForLocalObjects);
fixture->runAllTests();
CHECK(destructorWasCalledOnFailedTest);
}
#endif
TEST_BASE(MyOwnTest)
{
MyOwnTest() :
inTest(false)
{
}
bool inTest;
void setup()
{
CHECK(!inTest);
inTest = true;
}
void teardown()
{
CHECK(inTest);
inTest = false;
}
};
TEST_GROUP_BASE(UtestMyOwn, MyOwnTest)
{
};
TEST(UtestMyOwn, test)
{
CHECK(inTest);
}
class NullParameterTest: public UtestShell
{
};
TEST(UtestMyOwn, NullParameters)
{
NullParameterTest nullTest; /* Bug fix tests for creating a test without a name, fix in SimpleString */
TestRegistry* reg = TestRegistry::getCurrentRegistry();
nullTest.shouldRun(reg->getGroupFilter(), reg->getNameFilter());
}
class AllocateAndDeallocateInConstructorAndDestructor
{
char* memory_;
char* morememory_;
public:
AllocateAndDeallocateInConstructorAndDestructor()
{
memory_ = new char[100];
morememory_ = NULL;
}
void allocateMoreMemory()
{
morememory_ = new char[123];
}
~AllocateAndDeallocateInConstructorAndDestructor()
{
delete [] memory_;
delete [] morememory_;
}
};
TEST_GROUP(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks)
{
AllocateAndDeallocateInConstructorAndDestructor dummy;
};
TEST(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks, testInTestGroupName)
{
dummy.allocateMoreMemory();
}
<commit_msg>Removed redundant platforms/c2000/UTestTest.cpp.<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 <cmath>
#include <iomanip>
#include <ios>
#include <locale>
#include "vast/logger.hpp"
#include <caf/all.hpp>
#include "vast/concept/printable/stream.hpp"
#include "vast/concept/printable/vast/filesystem.hpp"
#include "vast/error.hpp"
#include "vast/system/accountant.hpp"
#include "vast/detail/coding.hpp"
#include "vast/detail/fill_status_map.hpp"
namespace vast {
namespace system {
namespace {
using accountant_actor = accountant_type::stateful_base<accountant_state>;
constexpr std::chrono::seconds overview_delay(5);
void init(accountant_actor* self, const path& filename) {
if (!exists(filename.parent())) {
auto t = mkdir(filename.parent());
if (!t) {
VAST_ERROR(self, to_string(t.error()));
self->quit(t.error());
return;
}
}
VAST_DEBUG(self, "opens log file:", filename.trim(-4));
auto& file = self->state.file;
file.open(filename.str());
if (!file.is_open()) {
VAST_ERROR(self, "failed to open file:", filename);
auto e = make_error(ec::filesystem_error, "failed to open file:", filename);
self->quit(e);
return;
}
file << "host\tpid\taid\tkey\tvalue\n";
if (!file)
self->quit(make_error(ec::filesystem_error));
VAST_DEBUG(self, "kicks off flush loop");
self->send(self, flush_atom::value);
#if VAST_LOG_LEVEL >= CAF_LOG_LEVEL_INFO
self->delayed_send(self, overview_delay, telemetry_atom::value);
#endif
}
template <class T>
void record(accountant_actor* self, const std::string& key, T x) {
using namespace std::chrono;
auto aid = self->current_sender()->id();
auto node = self->current_sender()->node();
auto& st = self->state;
for (auto byte : node.host_id())
st.file << static_cast<int>(byte);
st.file << std::dec << '\t' << node.process_id() << '\t' << aid << '\t'
<< st.actor_map[aid] << '\t' << key << '\t' << std::setprecision(6)
<< x << '\n';
// Flush after at most 10 seconds.
if (!st.flush_pending) {
st.flush_pending = true;
self->delayed_send(self, 10s, flush_atom::value);
}
}
void record(accountant_actor* self, const std::string& key, timespan x) {
using namespace std::chrono;
auto us = duration_cast<microseconds>(x).count();
record(self, key, us);
}
void record(accountant_actor* self, const std::string& key, timestamp x) {
using namespace std::chrono;
record(self, key, x.time_since_epoch());
}
// Calculate rate in seconds resolution from nanosecond duration.
double calc_rate(const measurement& m) {
if (m.duration.count() > 0)
return m.events * 1'000'000'000 / m.duration.count();
else
return std::numeric_limits<double>::quiet_NaN();
}
} // namespace <anonymous>
void accountant_state::command_line_heartbeat() {
auto logger = caf::logger::current_logger();
if (logger && logger->verbosity() >= CAF_LOG_LEVEL_INFO
&& accumulator.node.events > 0) {
std::ostringstream oss;
oss.imbue(std::locale(""));
auto node_rate = std::round(calc_rate(accumulator.node));
oss << "ingested " << accumulator.node.events << " events"
<< " at a rate of " << node_rate << " events/sec";
VAST_INFO_ANON(oss.str());
}
accumulator = {};
}
accountant_type::behavior_type accountant(accountant_actor* self,
const path& filename) {
using namespace std::chrono;
init(self, filename);
self->set_exit_handler(
[=](const caf::exit_msg& msg) {
self->state.file.flush();
self->quit(msg.reason);
}
);
self->set_down_handler(
[=](const caf::down_msg& msg) {
VAST_DEBUG(self, "received DOWN from", msg.source);
self->state.actor_map.erase(msg.source.id());
}
);
return {[=](announce_atom, const std::string& name) {
self->state.actor_map[self->current_sender()->id()] = name;
self->monitor(self->current_sender());
},
[=](const std::string& key, const std::string& value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
// Helpers to avoid to_string(..) in sender context.
[=](const std::string& key, timespan value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const std::string& key, timestamp value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const std::string& key, int64_t value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const std::string& key, uint64_t value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const std::string& key, double value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const report& r) {
VAST_TRACE(self, "received a report from", self->current_sender());
for (const auto& [key, value] : r) {
caf::visit([&,
key = key](const auto& x) { record(self, key, x); },
value);
}
},
[=](const performance_report& r) {
VAST_TRACE(self, "received a performance report from",
self->current_sender());
for (const auto& [key, value] : r) {
record(self, key + ".events", value.events);
record(self, key + ".duration", value.duration);
auto rate = calc_rate(value);
if (std::isfinite(rate))
record(self, key + ".rate", static_cast<uint64_t>(rate));
else
record(self, key + ".rate", "NaN");
#if VAST_LOG_LEVEL >= CAF_LOG_LEVEL_INFO
auto logger = caf::logger::current_logger();
if (logger && logger->verbosity() >= CAF_LOG_LEVEL_INFO)
if (key == "node_throughput")
self->state.accumulator.node += value;
#endif
}
},
[=](flush_atom) {
if (self->state.file)
self->state.file.flush();
self->state.flush_pending = false;
},
[=](status_atom) {
using caf::put_dictionary;
caf::dictionary<caf::config_value> result;
auto& known = put_dictionary(result, "known-actors");
for (const auto& [aid, name] : self->state.actor_map) {
known.emplace(name, aid);
}
detail::fill_status_map(result, self);
return result;
},
[=](telemetry_atom) {
self->state.command_line_heartbeat();
self->delayed_send(self, overview_delay, telemetry_atom::value);
}};
}
} // namespace system
} // namespace vast
<commit_msg>Use a single contiguous string in ostream output<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 <cmath>
#include <iomanip>
#include <ios>
#include <locale>
#include "vast/logger.hpp"
#include <caf/all.hpp>
#include "vast/concept/printable/stream.hpp"
#include "vast/concept/printable/vast/filesystem.hpp"
#include "vast/error.hpp"
#include "vast/system/accountant.hpp"
#include "vast/detail/coding.hpp"
#include "vast/detail/fill_status_map.hpp"
namespace vast {
namespace system {
namespace {
using accountant_actor = accountant_type::stateful_base<accountant_state>;
constexpr std::chrono::seconds overview_delay(5);
void init(accountant_actor* self, const path& filename) {
if (!exists(filename.parent())) {
auto t = mkdir(filename.parent());
if (!t) {
VAST_ERROR(self, to_string(t.error()));
self->quit(t.error());
return;
}
}
VAST_DEBUG(self, "opens log file:", filename.trim(-4));
auto& file = self->state.file;
file.open(filename.str());
if (!file.is_open()) {
VAST_ERROR(self, "failed to open file:", filename);
auto e = make_error(ec::filesystem_error, "failed to open file:", filename);
self->quit(e);
return;
}
file << "host\tpid\taid\tkey\tvalue\n";
if (!file)
self->quit(make_error(ec::filesystem_error));
VAST_DEBUG(self, "kicks off flush loop");
self->send(self, flush_atom::value);
#if VAST_LOG_LEVEL >= CAF_LOG_LEVEL_INFO
self->delayed_send(self, overview_delay, telemetry_atom::value);
#endif
}
template <class T>
void record(accountant_actor* self, const std::string& key, T x) {
using namespace std::chrono;
auto aid = self->current_sender()->id();
auto node = self->current_sender()->node();
auto& st = self->state;
for (auto byte : node.host_id())
st.file << static_cast<int>(byte);
st.file << std::dec << '\t' << node.process_id() << '\t' << aid << '\t'
<< st.actor_map[aid] << '\t' << key << '\t' << std::setprecision(6)
<< x << '\n';
// Flush after at most 10 seconds.
if (!st.flush_pending) {
st.flush_pending = true;
self->delayed_send(self, 10s, flush_atom::value);
}
}
void record(accountant_actor* self, const std::string& key, timespan x) {
using namespace std::chrono;
auto us = duration_cast<microseconds>(x).count();
record(self, key, us);
}
void record(accountant_actor* self, const std::string& key, timestamp x) {
using namespace std::chrono;
record(self, key, x.time_since_epoch());
}
// Calculate rate in seconds resolution from nanosecond duration.
double calc_rate(const measurement& m) {
if (m.duration.count() > 0)
return m.events * 1'000'000'000 / m.duration.count();
else
return std::numeric_limits<double>::quiet_NaN();
}
} // namespace <anonymous>
void accountant_state::command_line_heartbeat() {
auto logger = caf::logger::current_logger();
if (logger && logger->verbosity() >= CAF_LOG_LEVEL_INFO
&& accumulator.node.events > 0) {
std::ostringstream oss;
oss.imbue(std::locale(""));
auto node_rate = std::round(calc_rate(accumulator.node));
oss << "ingested " << accumulator.node.events << " events at a rate of "
<< node_rate << " events/sec";
VAST_INFO_ANON(oss.str());
}
accumulator = {};
}
accountant_type::behavior_type accountant(accountant_actor* self,
const path& filename) {
using namespace std::chrono;
init(self, filename);
self->set_exit_handler(
[=](const caf::exit_msg& msg) {
self->state.file.flush();
self->quit(msg.reason);
}
);
self->set_down_handler(
[=](const caf::down_msg& msg) {
VAST_DEBUG(self, "received DOWN from", msg.source);
self->state.actor_map.erase(msg.source.id());
}
);
return {[=](announce_atom, const std::string& name) {
self->state.actor_map[self->current_sender()->id()] = name;
self->monitor(self->current_sender());
},
[=](const std::string& key, const std::string& value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
// Helpers to avoid to_string(..) in sender context.
[=](const std::string& key, timespan value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const std::string& key, timestamp value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const std::string& key, int64_t value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const std::string& key, uint64_t value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const std::string& key, double value) {
VAST_TRACE(self, "received", key, "from", self->current_sender());
record(self, key, value);
},
[=](const report& r) {
VAST_TRACE(self, "received a report from", self->current_sender());
for (const auto& [key, value] : r) {
caf::visit([&,
key = key](const auto& x) { record(self, key, x); },
value);
}
},
[=](const performance_report& r) {
VAST_TRACE(self, "received a performance report from",
self->current_sender());
for (const auto& [key, value] : r) {
record(self, key + ".events", value.events);
record(self, key + ".duration", value.duration);
auto rate = calc_rate(value);
if (std::isfinite(rate))
record(self, key + ".rate", static_cast<uint64_t>(rate));
else
record(self, key + ".rate", "NaN");
#if VAST_LOG_LEVEL >= CAF_LOG_LEVEL_INFO
auto logger = caf::logger::current_logger();
if (logger && logger->verbosity() >= CAF_LOG_LEVEL_INFO)
if (key == "node_throughput")
self->state.accumulator.node += value;
#endif
}
},
[=](flush_atom) {
if (self->state.file)
self->state.file.flush();
self->state.flush_pending = false;
},
[=](status_atom) {
using caf::put_dictionary;
caf::dictionary<caf::config_value> result;
auto& known = put_dictionary(result, "known-actors");
for (const auto& [aid, name] : self->state.actor_map) {
known.emplace(name, aid);
}
detail::fill_status_map(result, self);
return result;
},
[=](telemetry_atom) {
self->state.command_line_heartbeat();
self->delayed_send(self, overview_delay, telemetry_atom::value);
}};
}
} // namespace system
} // namespace vast
<|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/ids.hpp"
#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/expression.hpp"
#include "vast/system/partition.hpp"
#include "vast/system/task.hpp"
#define SUITE system
#include "test.hpp"
#include "fixtures/actor_system_and_events.hpp"
using namespace caf;
using namespace vast;
using namespace std::chrono;
namespace {
struct partition_fixture : fixtures::actor_system_and_events {
partition_fixture() {
directory /= "partition";
MESSAGE("ingesting conn.log");
partition = self->spawn(system::partition, directory);
self->send(partition, bro_conn_log);
MESSAGE("ingesting http.log");
self->send(partition, bro_http_log);
MESSAGE("ingesting bgpdump log");
self->send(partition, bgpdump_txt);
MESSAGE("completed ingestion");
}
~partition_fixture() {
self->send(partition, system::shutdown_atom::value);
self->wait_for(partition);
}
ids query(const std::string& str) {
MESSAGE("sending query");
auto expr = to<expression>(str);
REQUIRE(expr);
ids result;
self->request(partition, infinite, *expr).receive(
[&](ids& hits) {
result = std::move(hits);
},
error_handler()
);
MESSAGE("shutting down partition");
self->send(partition, system::shutdown_atom::value);
self->wait_for(partition);
REQUIRE(exists(directory));
REQUIRE(exists(directory / "547119946" / "data" / "id" / "orig_h"));
REQUIRE(exists(directory / "547119946" / "meta" / "time"));
REQUIRE(exists(directory / "547119946" / "meta" / "type"));
MESSAGE("respawning partition and sending query again");
partition = self->spawn(system::partition, directory);
self->request(partition, infinite, *expr).receive(
[&](const ids& hits) {
REQUIRE_EQUAL(hits, result);
},
error_handler()
);
return result;
}
actor partition;
};
} // namespace <anonymous>
FIXTURE_SCOPE(partition_tests, partition_fixture)
TEST(partition queries - type extractors) {
auto hits = query(":string == \"SF\" && :port == 443/?");
CHECK_EQUAL(rank(hits), 38u);
hits = query(":subnet in 86.111.146.0/23");
CHECK_EQUAL(rank(hits), 72u);
}
TEST(partition queries - key extractors) {
auto hits = query("conn_state == \"SF\" && id.resp_p == 443/?");
CHECK_EQUAL(rank(hits), 38u);
}
TEST(partition queries - attribute extractors) {
MESSAGE("&type");
auto hits = query("&type == \"bro::http\"");
CHECK_EQUAL(rank(hits), 4896u);
hits = query("&type == \"bro::conn\"");
CHECK_EQUAL(rank(hits), 8462u);
MESSAGE("&time");
hits = query("&time > 1970-01-01");
CHECK_EQUAL(rank(hits), 4896u + 8462u);
}
TEST(partition queries - mixed) {
auto hits = query("service == \"http\" && :addr == 212.227.96.110");
CHECK_EQUAL(rank(hits), 28u);
}
FIXTURE_SCOPE_END()
<commit_msg>Fix broken partition unit test<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/ids.hpp"
#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/expression.hpp"
#include "vast/system/partition.hpp"
#include "vast/system/task.hpp"
#define SUITE system
#include "test.hpp"
#include "fixtures/actor_system_and_events.hpp"
using namespace caf;
using namespace vast;
using namespace std::chrono;
namespace {
struct partition_fixture : fixtures::actor_system_and_events {
partition_fixture() {
directory /= "partition";
MESSAGE("ingesting conn.log");
partition = self->spawn(system::partition, directory);
self->send(partition, bro_conn_log);
MESSAGE("ingesting http.log");
self->send(partition, bro_http_log);
MESSAGE("ingesting bgpdump log");
self->send(partition, bgpdump_txt);
MESSAGE("completed ingestion");
}
~partition_fixture() {
self->send(partition, system::shutdown_atom::value);
self->wait_for(partition);
}
ids query(const std::string& str) {
MESSAGE("sending query");
auto expr = to<expression>(str);
REQUIRE(expr);
ids result;
self->request(partition, infinite, *expr).receive(
[&](ids& hits) {
result = std::move(hits);
},
error_handler()
);
MESSAGE("shutting down partition");
self->send(partition, system::shutdown_atom::value);
self->wait_for(partition);
REQUIRE(exists(directory));
REQUIRE(exists(directory / "547119946" / "data" / "id" / "orig_h"));
REQUIRE(exists(directory / "547119946" / "meta" / "time"));
REQUIRE(exists(directory / "547119946" / "meta" / "type"));
MESSAGE("respawning partition and sending query again");
partition = self->spawn(system::partition, directory);
self->request(partition, infinite, *expr).receive(
[&](const ids& hits) {
REQUIRE_EQUAL(hits, result);
},
error_handler()
);
return result;
}
actor partition;
};
} // namespace <anonymous>
FIXTURE_SCOPE(partition_tests, partition_fixture)
TEST(partition queries - type extractors) {
auto hits = query(":string == \"SF\" && :port == 443/?");
CHECK_EQUAL(rank(hits), 38u);
hits = query(":subnet in 86.111.146.0/23");
CHECK_EQUAL(rank(hits), 72u);
}
TEST(partition queries - key extractors) {
auto hits = query("conn_state == \"SF\" && id.resp_p == 443/?");
CHECK_EQUAL(rank(hits), 38u);
}
TEST(partition queries - attribute extractors) {
MESSAGE("&type");
auto hits = query("&type == \"bro::http\"");
CHECK_EQUAL(rank(hits), bro_http_log.size());
hits = query("&type == \"bro::conn\"");
CHECK_EQUAL(rank(hits), bro_conn_log.size());
MESSAGE("&time");
hits = query("&time > 1970-01-01");
auto all = bro_http_log.size() + bro_conn_log.size() + bgpdump_txt.size();
CHECK_EQUAL(rank(hits), all);
}
TEST(partition queries - mixed) {
auto hits = query("service == \"http\" && :addr == 212.227.96.110");
CHECK_EQUAL(rank(hits), 28u);
}
FIXTURE_SCOPE_END()
<|endoftext|> |
<commit_before>#include "NdefRecord.h"
NdefRecord::NdefRecord()
{
//Serial.println("NdefRecord Constructor 1");
_tnf = 0;
_typeLength = 0;
_payloadLength = 0;
_idLength = 0;
_type = (byte *)NULL;
_payload = (byte *)NULL;
_id = (byte *)NULL;
}
NdefRecord::NdefRecord(const NdefRecord& rhs)
{
//Serial.println("NdefRecord Constructor 2 (copy)");
_tnf = rhs._tnf;
_typeLength = rhs._typeLength;
_payloadLength = rhs._payloadLength;
_idLength = rhs._idLength;
_type = (byte *)NULL;
_payload = (byte *)NULL;
_id = (byte *)NULL;
if (_typeLength)
{
_type = (byte*)malloc(_typeLength);
memcpy(_type, rhs._type, _typeLength);
}
if (_payloadLength)
{
_payload = (byte*)malloc(_payloadLength);
memcpy(_payload, rhs._payload, _payloadLength);
}
if (_idLength)
{
_id = (byte*)malloc(_idLength);
memcpy(_id, rhs._id, _idLength);
}
}
// TODO NdefRecord::NdefRecord(tnf, type, payload, id)
NdefRecord::~NdefRecord()
{
//Serial.println("NdefRecord Destructor");
if (_typeLength)
{
free(_type);
}
if (_payloadLength)
{
free(_payload);
}
if (_idLength)
{
free(_id);
}
}
NdefRecord& NdefRecord::operator=(const NdefRecord& rhs)
{
//Serial.println("NdefRecord ASSIGN");
if (this != &rhs)
{
// free existing
if (_typeLength)
{
free(_type);
}
if (_payloadLength)
{
free(_payload);
}
if (_idLength)
{
free(_id);
}
_tnf = rhs._tnf;
_typeLength = rhs._typeLength;
_payloadLength = rhs._payloadLength;
_idLength = rhs._idLength;
if (_typeLength)
{
_type = (byte*)malloc(_typeLength);
memcpy(_type, rhs._type, _typeLength);
}
if (_payloadLength)
{
_payload = (byte*)malloc(_payloadLength);
memcpy(_payload, rhs._payload, _payloadLength);
}
if (_idLength)
{
_id = (byte*)malloc(_idLength);
memcpy(_id, rhs._id, _idLength);
}
}
return *this;
}
// size of records in bytes
int NdefRecord::getEncodedSize()
{
int size = 2; // tnf + typeLength
if (_payloadLength > 0xFF)
{
size += 4;
}
else
{
size += 1;
}
if (_idLength)
{
size += 1;
}
size += (_typeLength + _payloadLength + _idLength);
return size;
}
void NdefRecord::encode(byte *data, bool firstRecord, bool lastRecord)
{
// assert data > getEncodedSize()
uint8_t* data_ptr = &data[0];
*data_ptr = getTnfByte(firstRecord, lastRecord);
data_ptr += 1;
*data_ptr = _typeLength;
data_ptr += 1;
if (_payloadLength <= 0xFF) { // short record
*data_ptr = _payloadLength;
data_ptr += 1;
} else { // long format
// 4 bytes but we store length as an int
data_ptr[0] = 0x0; // (_payloadLength >> 24) & 0xFF;
data_ptr[1] = 0x0; // (_payloadLength >> 16) & 0xFF;
data_ptr[2] = (_payloadLength >> 8) & 0xFF;
data_ptr[3] = _payloadLength & 0xFF;
data_ptr += 4;
}
if (_idLength)
{
*data_ptr = _idLength;
data_ptr += 1;
}
//Serial.println(2);
memcpy(data_ptr, _type, _typeLength);
data_ptr += _typeLength;
memcpy(data_ptr, _payload, _payloadLength);
data_ptr += _payloadLength;
if (_idLength)
{
memcpy(data_ptr, _id, _idLength);
data_ptr += _idLength;
}
}
byte NdefRecord::getTnfByte(bool firstRecord, bool lastRecord)
{
int value = _tnf;
if (firstRecord) { // mb
value = value | 0x80;
}
if (lastRecord) { //
value = value | 0x40;
}
// chunked flag is always false for now
// if (cf) {
// value = value | 0x20;
// }
if (_payloadLength <= 0xFF) {
value = value | 0x10;
}
if (_idLength) {
value = value | 0x8;
}
return value;
}
byte NdefRecord::getTnf()
{
return _tnf;
}
void NdefRecord::setTnf(byte tnf)
{
_tnf = tnf;
}
unsigned int NdefRecord::getTypeLength()
{
return _typeLength;
}
int NdefRecord::getPayloadLength()
{
return _payloadLength;
}
unsigned int NdefRecord::getIdLength()
{
return _idLength;
}
String NdefRecord::getType()
{
String typeString = "";
for (int c = 0; c < _typeLength; c++) {
typeString += (char)_type[c];
}
return typeString;
}
// this assumes the caller created type correctly
void NdefRecord::getType(uint8_t* type)
{
memcpy(type, _type, _typeLength);
}
void NdefRecord::setType(const byte * type, const unsigned int numBytes)
{
if(_typeLength)
{
free(_type);
}
_type = (uint8_t*)malloc(numBytes);
memcpy(_type, type, numBytes);
_typeLength = numBytes;
}
// assumes the caller sized payload properly
void NdefRecord::getPayload(byte *payload)
{
memcpy(payload, _payload, _payloadLength);
}
void NdefRecord::setPayload(const byte * payload, const int numBytes)
{
if (_payloadLength)
{
free(_payload);
}
_payload = (byte*)malloc(numBytes);
memcpy(_payload, payload, numBytes);
_payloadLength = numBytes;
}
String NdefRecord::getId()
{
String idString = "";
for (int c = 0; c < _idLength; c++) {
idString += (char)_id[c];
}
return idString;
}
void NdefRecord::getId(byte *id)
{
memcpy(id, _id, _idLength);
}
void NdefRecord::setId(const byte * id, const unsigned int numBytes)
{
if (_idLength)
{
free(_id);
}
_id = (byte*)malloc(numBytes);
memcpy(_id, id, numBytes);
_idLength = numBytes;
}
void NdefRecord::print()
{
Serial.println(F(" NDEF Record"));
Serial.print(F(" TNF 0x"));Serial.print(_tnf, HEX);Serial.print(" ");
switch (_tnf) {
case TNF_EMPTY:
Serial.println(F("Empty"));
break;
case TNF_WELL_KNOWN:
Serial.println(F("Well Known"));
break;
case TNF_MIME_MEDIA:
Serial.println(F("Mime Media"));
break;
case TNF_ABSOLUTE_URI:
Serial.println(F("Absolute URI"));
break;
case TNF_EXTERNAL_TYPE:
Serial.println(F("External"));
break;
case TNF_UNKNOWN:
Serial.println(F("Unknown"));
break;
case TNF_UNCHANGED:
Serial.println(F("Unchanged"));
break;
case TNF_RESERVED:
Serial.println(F("Reserved"));
break;
default:
Serial.println();
}
Serial.print(F(" Type Length 0x"));Serial.print(_typeLength, HEX);Serial.print(" ");Serial.println(_typeLength);
Serial.print(F(" Payload Length 0x"));Serial.print(_payloadLength, HEX);;Serial.print(" ");Serial.println(_payloadLength);
if (_idLength)
{
Serial.print(F(" Id Length 0x"));Serial.println(_idLength, HEX);
}
Serial.print(F(" Type "));PrintHexChar(_type, _typeLength);
// TODO chunk large payloads so this is readable
Serial.print(F(" Payload "));PrintHexChar(_payload, _payloadLength);
if (_idLength)
{
Serial.print(F(" Id "));PrintHexChar(_id, _idLength);
}
Serial.print(F(" Record is "));Serial.print(getEncodedSize());Serial.println(" bytes");
}<commit_msg>re-implement getType() getId()<commit_after>#include "NdefRecord.h"
NdefRecord::NdefRecord()
{
//Serial.println("NdefRecord Constructor 1");
_tnf = 0;
_typeLength = 0;
_payloadLength = 0;
_idLength = 0;
_type = (byte *)NULL;
_payload = (byte *)NULL;
_id = (byte *)NULL;
}
NdefRecord::NdefRecord(const NdefRecord& rhs)
{
//Serial.println("NdefRecord Constructor 2 (copy)");
_tnf = rhs._tnf;
_typeLength = rhs._typeLength;
_payloadLength = rhs._payloadLength;
_idLength = rhs._idLength;
_type = (byte *)NULL;
_payload = (byte *)NULL;
_id = (byte *)NULL;
if (_typeLength)
{
_type = (byte*)malloc(_typeLength);
memcpy(_type, rhs._type, _typeLength);
}
if (_payloadLength)
{
_payload = (byte*)malloc(_payloadLength);
memcpy(_payload, rhs._payload, _payloadLength);
}
if (_idLength)
{
_id = (byte*)malloc(_idLength);
memcpy(_id, rhs._id, _idLength);
}
}
// TODO NdefRecord::NdefRecord(tnf, type, payload, id)
NdefRecord::~NdefRecord()
{
//Serial.println("NdefRecord Destructor");
if (_typeLength)
{
free(_type);
}
if (_payloadLength)
{
free(_payload);
}
if (_idLength)
{
free(_id);
}
}
NdefRecord& NdefRecord::operator=(const NdefRecord& rhs)
{
//Serial.println("NdefRecord ASSIGN");
if (this != &rhs)
{
// free existing
if (_typeLength)
{
free(_type);
}
if (_payloadLength)
{
free(_payload);
}
if (_idLength)
{
free(_id);
}
_tnf = rhs._tnf;
_typeLength = rhs._typeLength;
_payloadLength = rhs._payloadLength;
_idLength = rhs._idLength;
if (_typeLength)
{
_type = (byte*)malloc(_typeLength);
memcpy(_type, rhs._type, _typeLength);
}
if (_payloadLength)
{
_payload = (byte*)malloc(_payloadLength);
memcpy(_payload, rhs._payload, _payloadLength);
}
if (_idLength)
{
_id = (byte*)malloc(_idLength);
memcpy(_id, rhs._id, _idLength);
}
}
return *this;
}
// size of records in bytes
int NdefRecord::getEncodedSize()
{
int size = 2; // tnf + typeLength
if (_payloadLength > 0xFF)
{
size += 4;
}
else
{
size += 1;
}
if (_idLength)
{
size += 1;
}
size += (_typeLength + _payloadLength + _idLength);
return size;
}
void NdefRecord::encode(byte *data, bool firstRecord, bool lastRecord)
{
// assert data > getEncodedSize()
uint8_t* data_ptr = &data[0];
*data_ptr = getTnfByte(firstRecord, lastRecord);
data_ptr += 1;
*data_ptr = _typeLength;
data_ptr += 1;
if (_payloadLength <= 0xFF) { // short record
*data_ptr = _payloadLength;
data_ptr += 1;
} else { // long format
// 4 bytes but we store length as an int
data_ptr[0] = 0x0; // (_payloadLength >> 24) & 0xFF;
data_ptr[1] = 0x0; // (_payloadLength >> 16) & 0xFF;
data_ptr[2] = (_payloadLength >> 8) & 0xFF;
data_ptr[3] = _payloadLength & 0xFF;
data_ptr += 4;
}
if (_idLength)
{
*data_ptr = _idLength;
data_ptr += 1;
}
//Serial.println(2);
memcpy(data_ptr, _type, _typeLength);
data_ptr += _typeLength;
memcpy(data_ptr, _payload, _payloadLength);
data_ptr += _payloadLength;
if (_idLength)
{
memcpy(data_ptr, _id, _idLength);
data_ptr += _idLength;
}
}
byte NdefRecord::getTnfByte(bool firstRecord, bool lastRecord)
{
int value = _tnf;
if (firstRecord) { // mb
value = value | 0x80;
}
if (lastRecord) { //
value = value | 0x40;
}
// chunked flag is always false for now
// if (cf) {
// value = value | 0x20;
// }
if (_payloadLength <= 0xFF) {
value = value | 0x10;
}
if (_idLength) {
value = value | 0x8;
}
return value;
}
byte NdefRecord::getTnf()
{
return _tnf;
}
void NdefRecord::setTnf(byte tnf)
{
_tnf = tnf;
}
unsigned int NdefRecord::getTypeLength()
{
return _typeLength;
}
int NdefRecord::getPayloadLength()
{
return _payloadLength;
}
unsigned int NdefRecord::getIdLength()
{
return _idLength;
}
String NdefRecord::getType()
{
char type[_typeLength + 1];
memcpy(type, _type, _typeLength);
type[_typeLength] = '\0'; // null terminate
return String(type);
}
// this assumes the caller created type correctly
void NdefRecord::getType(uint8_t* type)
{
memcpy(type, _type, _typeLength);
}
void NdefRecord::setType(const byte * type, const unsigned int numBytes)
{
if(_typeLength)
{
free(_type);
}
_type = (uint8_t*)malloc(numBytes);
memcpy(_type, type, numBytes);
_typeLength = numBytes;
}
// assumes the caller sized payload properly
void NdefRecord::getPayload(byte *payload)
{
memcpy(payload, _payload, _payloadLength);
}
void NdefRecord::setPayload(const byte * payload, const int numBytes)
{
if (_payloadLength)
{
free(_payload);
}
_payload = (byte*)malloc(numBytes);
memcpy(_payload, payload, numBytes);
_payloadLength = numBytes;
}
String NdefRecord::getId()
{
char id[_idLength + 1];
memcpy(id, _id, _idLength);
id[_idLength] = '\0'; // null terminate
return String(id);
}
void NdefRecord::getId(byte *id)
{
memcpy(id, _id, _idLength);
}
void NdefRecord::setId(const byte * id, const unsigned int numBytes)
{
if (_idLength)
{
free(_id);
}
_id = (byte*)malloc(numBytes);
memcpy(_id, id, numBytes);
_idLength = numBytes;
}
void NdefRecord::print()
{
Serial.println(F(" NDEF Record"));
Serial.print(F(" TNF 0x"));Serial.print(_tnf, HEX);Serial.print(" ");
switch (_tnf) {
case TNF_EMPTY:
Serial.println(F("Empty"));
break;
case TNF_WELL_KNOWN:
Serial.println(F("Well Known"));
break;
case TNF_MIME_MEDIA:
Serial.println(F("Mime Media"));
break;
case TNF_ABSOLUTE_URI:
Serial.println(F("Absolute URI"));
break;
case TNF_EXTERNAL_TYPE:
Serial.println(F("External"));
break;
case TNF_UNKNOWN:
Serial.println(F("Unknown"));
break;
case TNF_UNCHANGED:
Serial.println(F("Unchanged"));
break;
case TNF_RESERVED:
Serial.println(F("Reserved"));
break;
default:
Serial.println();
}
Serial.print(F(" Type Length 0x"));Serial.print(_typeLength, HEX);Serial.print(" ");Serial.println(_typeLength);
Serial.print(F(" Payload Length 0x"));Serial.print(_payloadLength, HEX);;Serial.print(" ");Serial.println(_payloadLength);
if (_idLength)
{
Serial.print(F(" Id Length 0x"));Serial.println(_idLength, HEX);
}
Serial.print(F(" Type "));PrintHexChar(_type, _typeLength);
// TODO chunk large payloads so this is readable
Serial.print(F(" Payload "));PrintHexChar(_payload, _payloadLength);
if (_idLength)
{
Serial.print(F(" Id "));PrintHexChar(_id, _idLength);
}
Serial.print(F(" Record is "));Serial.print(getEncodedSize());Serial.println(" bytes");
}<|endoftext|> |
<commit_before>/*
* Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia 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 (FSF), 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 General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "pitchyin.h"
#include "essentiamath.h"
using namespace std;
using namespace essentia;
using namespace standard;
const char* PitchYin::name = "PitchYin";
const char* PitchYin::description = DOC("This algorithm estimates the fundamental frequency from a given spectrum. It is an implementation of Yin algorithm [1], for computations in the time domain.\n"
"\n"
"An exception is thrown if an empty signal is provided.\n"
"\n"
"Please note that if \"pitchConfidence\" is zero, \"pitch\" is undefined and should not be used for other algorithms.\n"
"Also note that a null \"pitch\" is never ouput by the algorithm and that \"pitchConfidence\" must always be checked out.\n"
"\n"
"References:\n"
//TODO
//" [1] P. M. Brossier, \"Automatic Annotation of Musical Audio for Interactive\n"
//" Applications,” QMUL, London, UK, 2007.\n\n"
" [2] Pitch detection algorithm - Wikipedia, the free encyclopedia\n"
" http://en.wikipedia.org/wiki/Pitch_detection_algorithm");
void PitchYin::configure() {
_frameSize = parameter("frameSize").toInt();
_sampleRate = parameter("sampleRate").toReal();
_tolerance = parameter("tolerance").toReal();
_interpolate = parameter("interpolate").toBool();
_yin.resize(_frameSize/2+1);
_tauMax = min(int(ceil(_sampleRate / parameter("minFrequency").toReal())), _frameSize/2);
_tauMin = min(int(floor(_sampleRate / parameter("maxFrequency").toReal())), _frameSize/2);
if (_tauMax <= _tauMin) {
throw EssentiaException("PitchYin: maxFrequency is lower than minFrequency, or they are too close, or they are out of the interval of detectable frequencies with respect to the specified frameSize.");
}
_peakDetectLocal->configure("interpolate", _interpolate,
"range", _frameSize/2+1,
"maxPeaks", 1,
"minPosition", _tauMin,
"maxPosition", _tauMax,
"orderBy", "position",
"threshold", -1 * _tolerance);
_peakDetectGlobal->configure("interpolate", _interpolate,
"range", _frameSize/2+1,
"maxPeaks", 1,
"minPosition", _tauMin,
"maxPosition", _tauMax,
"orderBy", "amplitude");
}
void PitchYin::compute() {
const vector<Real>& signal = _signal.get();
if (signal.empty()) {
throw EssentiaException("PitchYin: Cannot compute pitch detection on empty signal frame.");
}
Real& pitch = _pitch.get();
Real& pitchConfidence = _pitchConfidence.get();
_yin[0] = 1.;
// Compute difference function
for (int tau=1; tau < (int) _yin.size(); ++tau) {
_yin[tau] = 0.;
for (int j=0; j < (int) _yin.size(); ++j) {
_yin[tau] += pow(signal[j] - signal[j+tau], 2);
}
}
// Compute a cumulative mean normalized difference function
Real sum = 0.;
for (int tau=1; tau < (int) _yin.size(); ++tau) {
sum += _yin[tau];
_yin[tau] = _yin[tau] * tau / sum;
}
// Detect best period
int period = 0;
int yinMin = 0.;
// Select the local minima below the absolute threshold with the smallest
// period value. Use global minimum if no minimas were found below threshold.
// invert yin values because we want to detect the minima while PeakDetection
// detects the maxima
for(int tau=0; tau < (int) _yin.size(); ++tau) {
_yin[tau] = -_yin[tau];
}
_peakDetectLocal->input("array").set(_yin);
_peakDetectLocal->output("positions").set(_positions);
_peakDetectLocal->output("amplitudes").set(_amplitudes);
_peakDetectLocal->compute();
if (_positions.size()) {
period = _positions[0];
yinMin = -_amplitudes[0];
}
else {
// no minima found below the threshold --> find the global minima
_peakDetectGlobal->input("array").set(_yin);
_peakDetectGlobal->output("positions").set(_positions);
_peakDetectGlobal->output("amplitudes").set(_amplitudes);
_peakDetectGlobal->compute();
try {
period = _positions[0];
yinMin = -_amplitudes[0];
}
catch (const EssentiaException&) {
throw EssentiaException("PitchYin: it appears that no peaks were found by PeakDetection. If you read this message, PLEASE, report this issue to the developers with an example of audio on which it happened.");
}
}
// NOTE: not sure if it is faster to run peak detection once to detect many
// peaks and process the values manually instead of running peak detection
// twice and detecting only two peaks.
/*
for (int tau=1; tau < _yin.size(); ++tau) {
if (_yin[ŧau] < _threshold) {
// Check if this is a local minima
if (tau < _yin.size()-1 && _yin[ŧau] < _yin[tau+1] || tau = _yin.size()-1) {
period = tau;
}
}
}
if(!period) {
period = argmin(_yin);
}
*/
// TODO: how to compute confidence?
// Aubio computes it as 1 - min(_yin), but this does not correspond to the peak
// dound by peakDetectLocal
if (period != 0.0) {
pitch = _sampleRate / period;
pitchConfidence = 1. - yinMin;
}
else {
pitch = 0.0;
pitchConfidence = 0.0;
}
}
<commit_msg>Use real instead of int to not loose the precision of perido after interpolation<commit_after>/*
* Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia 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 (FSF), 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 General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "pitchyin.h"
#include "essentiamath.h"
using namespace std;
using namespace essentia;
using namespace standard;
const char* PitchYin::name = "PitchYin";
const char* PitchYin::description = DOC("This algorithm estimates the fundamental frequency from a given spectrum. It is an implementation of Yin algorithm [1], for computations in the time domain.\n"
"\n"
"An exception is thrown if an empty signal is provided.\n"
"\n"
"Please note that if \"pitchConfidence\" is zero, \"pitch\" is undefined and should not be used for other algorithms.\n"
"Also note that a null \"pitch\" is never ouput by the algorithm and that \"pitchConfidence\" must always be checked out.\n"
"\n"
"References:\n"
//TODO
//" [1] P. M. Brossier, \"Automatic Annotation of Musical Audio for Interactive\n"
//" Applications,” QMUL, London, UK, 2007.\n\n"
" [2] Pitch detection algorithm - Wikipedia, the free encyclopedia\n"
" http://en.wikipedia.org/wiki/Pitch_detection_algorithm");
void PitchYin::configure() {
_frameSize = parameter("frameSize").toInt();
_sampleRate = parameter("sampleRate").toReal();
_tolerance = parameter("tolerance").toReal();
_interpolate = parameter("interpolate").toBool();
_yin.resize(_frameSize/2+1);
_tauMax = min(int(ceil(_sampleRate / parameter("minFrequency").toReal())), _frameSize/2);
_tauMin = min(int(floor(_sampleRate / parameter("maxFrequency").toReal())), _frameSize/2);
if (_tauMax <= _tauMin) {
throw EssentiaException("PitchYin: maxFrequency is lower than minFrequency, or they are too close, or they are out of the interval of detectable frequencies with respect to the specified frameSize.");
}
_peakDetectLocal->configure("interpolate", _interpolate,
"range", _frameSize/2+1,
"maxPeaks", 1,
"minPosition", _tauMin,
"maxPosition", _tauMax,
"orderBy", "position",
"threshold", -1 * _tolerance);
_peakDetectGlobal->configure("interpolate", _interpolate,
"range", _frameSize/2+1,
"maxPeaks", 1,
"minPosition", _tauMin,
"maxPosition", _tauMax,
"orderBy", "amplitude");
}
void PitchYin::compute() {
const vector<Real>& signal = _signal.get();
if (signal.empty()) {
throw EssentiaException("PitchYin: Cannot compute pitch detection on empty signal frame.");
}
Real& pitch = _pitch.get();
Real& pitchConfidence = _pitchConfidence.get();
_yin[0] = 1.;
// Compute difference function
for (int tau=1; tau < (int) _yin.size(); ++tau) {
_yin[tau] = 0.;
for (int j=0; j < (int) _yin.size(); ++j) {
_yin[tau] += pow(signal[j] - signal[j+tau], 2);
}
}
// Compute a cumulative mean normalized difference function
Real sum = 0.;
for (int tau=1; tau < (int) _yin.size(); ++tau) {
sum += _yin[tau];
_yin[tau] = _yin[tau] * tau / sum;
}
// Detect best period
Real period = 0.;
int yinMin = 0.;
// Select the local minima below the absolute threshold with the smallest
// period value. Use global minimum if no minimas were found below threshold.
// invert yin values because we want to detect the minima while PeakDetection
// detects the maxima
for(int tau=0; tau < (int) _yin.size(); ++tau) {
_yin[tau] = -_yin[tau];
}
_peakDetectLocal->input("array").set(_yin);
_peakDetectLocal->output("positions").set(_positions);
_peakDetectLocal->output("amplitudes").set(_amplitudes);
_peakDetectLocal->compute();
if (_positions.size()) {
period = _positions[0];
yinMin = -_amplitudes[0];
}
else {
// no minima found below the threshold --> find the global minima
_peakDetectGlobal->input("array").set(_yin);
_peakDetectGlobal->output("positions").set(_positions);
_peakDetectGlobal->output("amplitudes").set(_amplitudes);
_peakDetectGlobal->compute();
try {
period = _positions[0];
yinMin = -_amplitudes[0];
}
catch (const EssentiaException&) {
throw EssentiaException("PitchYin: it appears that no peaks were found by PeakDetection. If you read this message, PLEASE, report this issue to the developers with an example of audio on which it happened.");
}
}
// NOTE: not sure if it is faster to run peak detection once to detect many
// peaks and process the values manually instead of running peak detection
// twice and detecting only two peaks.
/*
for (int tau=1; tau < _yin.size(); ++tau) {
if (_yin[ŧau] < _threshold) {
// Check if this is a local minima
if (tau < _yin.size()-1 && _yin[ŧau] < _yin[tau+1] || tau = _yin.size()-1) {
period = tau;
}
}
}
if(!period) {
period = argmin(_yin);
}
*/
// TODO: how to compute confidence?
// Aubio computes it as 1 - min(_yin), but this does not correspond to the peak
// dound by peakDetectLocal
if (period) {
pitch = _sampleRate / period;
pitchConfidence = 1. - yinMin;
}
else {
pitch = 0.0;
pitchConfidence = 0.0;
}
}
<|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$ */
///////////////////////////////////////////////////////////////////////////////
// //
// class for ITS reconstruction //
// //
///////////////////////////////////////////////////////////////////////////////
#include "Riostream.h"
#include "AliITSReconstructor.h"
#include "AliRun.h"
#include "AliRunLoader.h"
#include "AliRawReader.h"
#include "AliITSDetTypeRec.h"
#include "AliITSLoader.h"
#include "AliITStrackerMI.h"
#include "AliITStrackerV2.h"
#include "AliITStrackerSA.h"
#include "AliITSVertexerIons.h"
#include "AliITSVertexerFast.h"
#include "AliITSVertexer3D.h"
#include "AliITSVertexerZ.h"
#include "AliITSVertexerCosmics.h"
#include "AliESDEvent.h"
#include "AliITSpidESD.h"
#include "AliITSpidESD1.h"
#include "AliITSpidESD2.h"
#include "AliITSInitGeometry.h"
ClassImp(AliITSReconstructor)
AliITSRecoParam *AliITSReconstructor::fgkRecoParam =0; // reconstruction parameters
//___________________________________________________________________________
AliITSReconstructor::AliITSReconstructor() : AliReconstructor(),
fItsPID(0)
{
// Default constructor
if (!fgkRecoParam) {
AliError("The Reconstruction parameters nonitialized - Used default one");
fgkRecoParam = AliITSRecoParam::GetHighFluxParam();
}
}
//___________________________________________________________________________
AliITSReconstructor::~AliITSReconstructor(){
// destructor
delete fItsPID;
if(fgkRecoParam) delete fgkRecoParam;
}
//______________________________________________________________________
AliITSReconstructor::AliITSReconstructor(const AliITSReconstructor &ob) :AliReconstructor(ob),
fItsPID(ob.fItsPID)
{
// Copy constructor
}
//______________________________________________________________________
AliITSReconstructor& AliITSReconstructor::operator=(const AliITSReconstructor& ob ){
// Assignment operator
this->~AliITSReconstructor();
new(this) AliITSReconstructor(ob);
return *this;
}
//______________________________________________________________________
void AliITSReconstructor::Init(AliRunLoader *runLoader) const{
// Initalize this constructor bet getting/creating the objects
// nesseary for a proper ITS reconstruction.
// Inputs:
// AliRunLoader *runLoader Pointer to the run loader to allow
// the getting of files/folders data
// needed to do reconstruction
// Output:
// none.
// Return:
// none.
AliITSInitGeometry initgeom;
AliITSgeom *geom = initgeom.CreateAliITSgeom();
AliInfo(Form("Geometry name: %s",(initgeom.GetGeometryName()).Data()));
AliITSLoader* loader = static_cast<AliITSLoader*>
(runLoader->GetLoader("ITSLoader"));
if (!loader) {
Error("Init", "ITS loader not found");
return;
}
loader->SetITSgeom(geom);
return;
}
//_____________________________________________________________________________
void AliITSReconstructor::Reconstruct(AliRunLoader* runLoader) const
{
// reconstruct clusters
AliITSLoader* loader = static_cast<AliITSLoader*>(runLoader->GetLoader("ITSLoader"));
if (!loader) {
Error("Reconstruct", "ITS loader not found");
return;
}
AliITSDetTypeRec* rec = new AliITSDetTypeRec(loader);
rec->SetDefaults();
loader->LoadRecPoints("recreate");
loader->LoadDigits("read");
runLoader->LoadKinematics();
TString option = GetOption();
Bool_t clusfinder=kTRUE; // Default: V2 cluster finder
if(option.Contains("OrigCF"))clusfinder=kFALSE;
Int_t nEvents = runLoader->GetNumberOfEvents();
for (Int_t iEvent = 0; iEvent < nEvents; iEvent++) {
runLoader->GetEvent(iEvent);
if(loader->TreeR()==0x0) loader->MakeTree("R");
rec->MakeBranch("R");
rec->SetTreeAddress();
rec->DigitsToRecPoints(iEvent,0,"All",clusfinder);
}
loader->UnloadRecPoints();
loader->UnloadDigits();
runLoader->UnloadKinematics();
}
//_________________________________________________________________
void AliITSReconstructor::Reconstruct(AliRunLoader* runLoader,
AliRawReader* rawReader) const
{
// reconstruct clusters
AliITSLoader* loader = static_cast<AliITSLoader*>(runLoader->GetLoader("ITSLoader"));
if (!loader) {
Error("Reconstruct", "ITS loader not found");
return;
}
AliITSDetTypeRec* rec = new AliITSDetTypeRec(loader);
rec->SetDefaults();
rec->SetDefaultClusterFindersV2(kTRUE);
loader->LoadRecPoints("recreate");
Int_t iEvent = 0;
while(rawReader->NextEvent()) {
runLoader->GetEvent(iEvent++);
if(loader->TreeR()==0x0) loader->MakeTree("R");
rec->DigitsToRecPoints(rawReader);
}
loader->UnloadRecPoints();
}
//_____________________________________________________________________________
AliTracker* AliITSReconstructor::CreateTracker(AliRunLoader* runLoader)const
{
// create a ITS tracker
TString selectedTracker = GetOption();
AliTracker* tracker;
if (selectedTracker.Contains("MI")) {
tracker = new AliITStrackerMI(0);
}
else if (selectedTracker.Contains("V2")) {
tracker = new AliITStrackerV2(0);
}
else {
tracker = new AliITStrackerSA(0); // inherits from AliITStrackerMI
AliITStrackerSA *sat=(AliITStrackerSA*)tracker;
if(selectedTracker.Contains("onlyITS"))sat->SetSAFlag(kTRUE);
if(sat->GetSAFlag())AliDebug(1,"Tracking Performed in ITS only\n");
if(selectedTracker.Contains("cosmics")||selectedTracker.Contains("COSMICS"))
sat->SetOuterStartLayer(AliITSgeomTGeo::GetNLayers()-2);
}
TString selectedPIDmethod = GetOption();
AliITSLoader *loader = (AliITSLoader*)runLoader->GetLoader("ITSLoader");
if (!loader) {
Error("CreateTracker", "ITS loader not found");
}
if(selectedPIDmethod.Contains("LandauFitPID")){
loader->AdoptITSpid(new AliITSpidESD2((AliITStrackerMI*)tracker,loader));
}
else{
Double_t parITS[] = {0.15, 10.}; //PH positions of the MIP peak
loader->AdoptITSpid(new AliITSpidESD1(parITS));
}
return tracker;
}
//_____________________________________________________________________________
AliVertexer* AliITSReconstructor::CreateVertexer(AliRunLoader* /*runLoader*/) const
{
// create a ITS vertexer
TString selectedVertexer = GetOption();
if(selectedVertexer.Contains("ions") || selectedVertexer.Contains("IONS")){
Info("CreateVertexer","a AliITSVertexerIons object has been selected\n");
return new AliITSVertexerIons("null");
}
if(selectedVertexer.Contains("smear") || selectedVertexer.Contains("SMEAR")){
Double_t smear[3]={0.005,0.005,0.01};
Info("CreateVertexer","a AliITSVertexerFast object has been selected\n");
return new AliITSVertexerFast(smear);
}
if(selectedVertexer.Contains("3d") || selectedVertexer.Contains("3D")){
Info("CreateVertexer","a AliITSVertexer3D object has been selected\n");
return new AliITSVertexer3D("null");
}
if(selectedVertexer.Contains("cosmics") || selectedVertexer.Contains("COSMICS")){
Info("CreateVertexer","a AliITSVertexerCosmics object has been selected\n");
return new AliITSVertexerCosmics();
}
// by default an AliITSVertexerZ object is instatiated
Info("CreateVertexer","a AliITSVertexerZ object has been selected\n");
return new AliITSVertexerZ("null");
}
//_____________________________________________________________________________
void AliITSReconstructor::FillESD(AliRunLoader* runLoader,
AliESDEvent* esd) const
{
// make PID, find V0s and cascade
AliITSLoader *loader = (AliITSLoader*)runLoader->GetLoader("ITSLoader");
AliITSpidESD *pidESD = 0;
TString selectedPIDmethod = GetOption();
if(selectedPIDmethod.Contains("LandauFitPID")){
Info("FillESD","ITS LandauFitPID option has been selected\n");
pidESD=loader->GetITSpid();
}
else{
Info("FillESD","ITS default PID\n");
pidESD=loader->GetITSpid();
}
if(pidESD!=0){
pidESD->MakePID(esd);
}
else {
Error("FillESD","!! cannot do the PID !!\n");
}
}
//_____________________________________________________________________________
AliITSgeom* AliITSReconstructor::GetITSgeom(AliRunLoader* runLoader) const
{
// get the ITS geometry
if (!runLoader->GetAliRun()) runLoader->LoadgAlice();
if (!runLoader->GetAliRun()) {
Error("GetITSgeom", "couldn't get AliRun object");
return NULL;
}
AliITSLoader *loader = (AliITSLoader*)runLoader->GetLoader("ITSLoader");
AliITSgeom* geom = (AliITSgeom*)loader->GetITSgeom();
if(!geom){
Error("GetITSgeom","no ITS geometry available");
return NULL;
}
return geom;
}
<commit_msg>Unload raw clusters and delete AliITSDetTypeRec object to avoid memory leaks (Marco)<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$ */
///////////////////////////////////////////////////////////////////////////////
// //
// class for ITS reconstruction //
// //
///////////////////////////////////////////////////////////////////////////////
#include "Riostream.h"
#include "AliITSReconstructor.h"
#include "AliRun.h"
#include "AliRunLoader.h"
#include "AliRawReader.h"
#include "AliITSDetTypeRec.h"
#include "AliITSLoader.h"
#include "AliITStrackerMI.h"
#include "AliITStrackerV2.h"
#include "AliITStrackerSA.h"
#include "AliITSVertexerIons.h"
#include "AliITSVertexerFast.h"
#include "AliITSVertexer3D.h"
#include "AliITSVertexerZ.h"
#include "AliITSVertexerCosmics.h"
#include "AliESDEvent.h"
#include "AliITSpidESD.h"
#include "AliITSpidESD1.h"
#include "AliITSpidESD2.h"
#include "AliITSInitGeometry.h"
ClassImp(AliITSReconstructor)
AliITSRecoParam *AliITSReconstructor::fgkRecoParam =0; // reconstruction parameters
//___________________________________________________________________________
AliITSReconstructor::AliITSReconstructor() : AliReconstructor(),
fItsPID(0)
{
// Default constructor
if (!fgkRecoParam) {
AliError("The Reconstruction parameters nonitialized - Used default one");
fgkRecoParam = AliITSRecoParam::GetHighFluxParam();
}
}
//___________________________________________________________________________
AliITSReconstructor::~AliITSReconstructor(){
// destructor
delete fItsPID;
if(fgkRecoParam) delete fgkRecoParam;
}
//______________________________________________________________________
AliITSReconstructor::AliITSReconstructor(const AliITSReconstructor &ob) :AliReconstructor(ob),
fItsPID(ob.fItsPID)
{
// Copy constructor
}
//______________________________________________________________________
AliITSReconstructor& AliITSReconstructor::operator=(const AliITSReconstructor& ob ){
// Assignment operator
this->~AliITSReconstructor();
new(this) AliITSReconstructor(ob);
return *this;
}
//______________________________________________________________________
void AliITSReconstructor::Init(AliRunLoader *runLoader) const{
// Initalize this constructor bet getting/creating the objects
// nesseary for a proper ITS reconstruction.
// Inputs:
// AliRunLoader *runLoader Pointer to the run loader to allow
// the getting of files/folders data
// needed to do reconstruction
// Output:
// none.
// Return:
// none.
AliITSInitGeometry initgeom;
AliITSgeom *geom = initgeom.CreateAliITSgeom();
AliInfo(Form("Geometry name: %s",(initgeom.GetGeometryName()).Data()));
AliITSLoader* loader = static_cast<AliITSLoader*>
(runLoader->GetLoader("ITSLoader"));
if (!loader) {
Error("Init", "ITS loader not found");
return;
}
loader->SetITSgeom(geom);
return;
}
//_____________________________________________________________________________
void AliITSReconstructor::Reconstruct(AliRunLoader* runLoader) const
{
// reconstruct clusters
AliITSLoader* loader = static_cast<AliITSLoader*>(runLoader->GetLoader("ITSLoader"));
if (!loader) {
Error("Reconstruct", "ITS loader not found");
return;
}
AliITSDetTypeRec* rec = new AliITSDetTypeRec(loader);
rec->SetDefaults();
loader->LoadRecPoints("recreate");
loader->LoadDigits("read");
runLoader->LoadKinematics();
TString option = GetOption();
Bool_t clusfinder=kTRUE; // Default: V2 cluster finder
if(option.Contains("OrigCF"))clusfinder=kFALSE;
Int_t nEvents = runLoader->GetNumberOfEvents();
for (Int_t iEvent = 0; iEvent < nEvents; iEvent++) {
runLoader->GetEvent(iEvent);
if(loader->TreeR()==0x0) loader->MakeTree("R");
rec->MakeBranch("R");
rec->SetTreeAddress();
rec->DigitsToRecPoints(iEvent,0,"All",clusfinder);
}
loader->UnloadRecPoints();
loader->UnloadDigits();
loader->UnloadRawClusters();
runLoader->UnloadKinematics();
delete rec;
}
//_________________________________________________________________
void AliITSReconstructor::Reconstruct(AliRunLoader* runLoader,
AliRawReader* rawReader) const
{
// reconstruct clusters
AliITSLoader* loader = static_cast<AliITSLoader*>(runLoader->GetLoader("ITSLoader"));
if (!loader) {
Error("Reconstruct", "ITS loader not found");
return;
}
AliITSDetTypeRec* rec = new AliITSDetTypeRec(loader);
rec->SetDefaults();
rec->SetDefaultClusterFindersV2(kTRUE);
loader->LoadRecPoints("recreate");
Int_t iEvent = 0;
while(rawReader->NextEvent()) {
runLoader->GetEvent(iEvent++);
if(loader->TreeR()==0x0) loader->MakeTree("R");
rec->DigitsToRecPoints(rawReader);
}
loader->UnloadRecPoints();
loader->UnloadRawClusters();
delete rec;
}
//_____________________________________________________________________________
AliTracker* AliITSReconstructor::CreateTracker(AliRunLoader* runLoader)const
{
// create a ITS tracker
TString selectedTracker = GetOption();
AliTracker* tracker;
if (selectedTracker.Contains("MI")) {
tracker = new AliITStrackerMI(0);
}
else if (selectedTracker.Contains("V2")) {
tracker = new AliITStrackerV2(0);
}
else {
tracker = new AliITStrackerSA(0); // inherits from AliITStrackerMI
AliITStrackerSA *sat=(AliITStrackerSA*)tracker;
if(selectedTracker.Contains("onlyITS"))sat->SetSAFlag(kTRUE);
if(sat->GetSAFlag())AliDebug(1,"Tracking Performed in ITS only\n");
if(selectedTracker.Contains("cosmics")||selectedTracker.Contains("COSMICS"))
sat->SetOuterStartLayer(AliITSgeomTGeo::GetNLayers()-2);
}
TString selectedPIDmethod = GetOption();
AliITSLoader *loader = (AliITSLoader*)runLoader->GetLoader("ITSLoader");
if (!loader) {
Error("CreateTracker", "ITS loader not found");
}
if(selectedPIDmethod.Contains("LandauFitPID")){
loader->AdoptITSpid(new AliITSpidESD2((AliITStrackerMI*)tracker,loader));
}
else{
Double_t parITS[] = {0.15, 10.}; //PH positions of the MIP peak
loader->AdoptITSpid(new AliITSpidESD1(parITS));
}
return tracker;
}
//_____________________________________________________________________________
AliVertexer* AliITSReconstructor::CreateVertexer(AliRunLoader* /*runLoader*/) const
{
// create a ITS vertexer
TString selectedVertexer = GetOption();
if(selectedVertexer.Contains("ions") || selectedVertexer.Contains("IONS")){
Info("CreateVertexer","a AliITSVertexerIons object has been selected\n");
return new AliITSVertexerIons("null");
}
if(selectedVertexer.Contains("smear") || selectedVertexer.Contains("SMEAR")){
Double_t smear[3]={0.005,0.005,0.01};
Info("CreateVertexer","a AliITSVertexerFast object has been selected\n");
return new AliITSVertexerFast(smear);
}
if(selectedVertexer.Contains("3d") || selectedVertexer.Contains("3D")){
Info("CreateVertexer","a AliITSVertexer3D object has been selected\n");
return new AliITSVertexer3D("null");
}
if(selectedVertexer.Contains("cosmics") || selectedVertexer.Contains("COSMICS")){
Info("CreateVertexer","a AliITSVertexerCosmics object has been selected\n");
return new AliITSVertexerCosmics();
}
// by default an AliITSVertexerZ object is instatiated
Info("CreateVertexer","a AliITSVertexerZ object has been selected\n");
return new AliITSVertexerZ("null");
}
//_____________________________________________________________________________
void AliITSReconstructor::FillESD(AliRunLoader* runLoader,
AliESDEvent* esd) const
{
// make PID, find V0s and cascade
AliITSLoader *loader = (AliITSLoader*)runLoader->GetLoader("ITSLoader");
AliITSpidESD *pidESD = 0;
TString selectedPIDmethod = GetOption();
if(selectedPIDmethod.Contains("LandauFitPID")){
Info("FillESD","ITS LandauFitPID option has been selected\n");
pidESD=loader->GetITSpid();
}
else{
Info("FillESD","ITS default PID\n");
pidESD=loader->GetITSpid();
}
if(pidESD!=0){
pidESD->MakePID(esd);
}
else {
Error("FillESD","!! cannot do the PID !!\n");
}
}
//_____________________________________________________________________________
AliITSgeom* AliITSReconstructor::GetITSgeom(AliRunLoader* runLoader) const
{
// get the ITS geometry
if (!runLoader->GetAliRun()) runLoader->LoadgAlice();
if (!runLoader->GetAliRun()) {
Error("GetITSgeom", "couldn't get AliRun object");
return NULL;
}
AliITSLoader *loader = (AliITSLoader*)runLoader->GetLoader("ITSLoader");
AliITSgeom* geom = (AliITSgeom*)loader->GetITSgeom();
if(!geom){
Error("GetITSgeom","no ITS geometry available");
return NULL;
}
return geom;
}
<|endoftext|> |
<commit_before>#include "physics/Environment.hpp"
#include "SimulatorWindow.hpp"
#include "SimulatorGLUTThread.hpp"
#include <QApplication>
#include <QFile>
#include <QThread>
#include <stdio.h>
#include <signal.h>
using namespace std;
void quit(int signal)
{
fprintf(stderr, "Exiting due to signal %d\n", signal);
exit(0);
}
void usage(const char* prog)
{
fprintf(stderr, "usage: %s [-c <config file>] [--glut] [--sv]\n", prog);
fprintf(stderr, "\t--help Show usage message\n");
fprintf(stderr, "\t--sv Use shared vision multicast port\n");
fprintf(stderr, "\t--headless Run the simulator in headless mode (without a GUI)\n");
}
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
Field_Dimensions::Current_Dimensions = Field_Dimensions::Single_Field_Dimensions * scaling;
QString configFile = "simulator.cfg";
bool sendShared = false;
bool headless = false;
//loop arguments and look for config file
for (int i=1 ; i<argc ; ++i)
{
if (strcmp(argv[i], "--help") == 0)
{
usage(argv[0]);
return 1;
} else if (strcmp(argv[i], "--sv") == 0)
{
sendShared = true;
} else if (strcmp(argv[i], "-c") == 0)
{
++i;
if (i < argc)
{
configFile = argv[i];
}
else
{
printf ("Expected config file after -c parameter\n");
return 1;
}
} else if ((strcmp(argv[i], "--h") == 0) || (strcmp(argv[i], "--help") == 0))
{
usage(argv[0]);
return 0;
} else if (strcmp(argv[i], "--headless") == 0) {
headless = true;
} else {
printf("%s is not recognized as a valid flag\n", argv[i]);
return 1;
}
}
// create the thread for simulation
SimulatorGLUTThread sim_thread(argc, argv, configFile, sendShared, !headless);
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_handler = quit;
sigaction(SIGINT, &act, 0);
// Create and initialize GUI with environment information
if (!headless) {
SimulatorWindow win(sim_thread.env());
win.show();
}
// initialize socket connections separately
sim_thread.env()->connectSockets();
// start up threads
sim_thread.start();
int ret = app.exec();
// shut down sim_thread
sim_thread.stop();
sim_thread.wait();
return 0;//ret;
}
<commit_msg>brought back simulator config window. closes #238<commit_after>#include "physics/Environment.hpp"
#include "SimulatorWindow.hpp"
#include "SimulatorGLUTThread.hpp"
#include <QApplication>
#include <QFile>
#include <QThread>
#include <stdio.h>
#include <signal.h>
using namespace std;
void quit(int signal)
{
fprintf(stderr, "Exiting due to signal %d\n", signal);
exit(0);
}
void usage(const char* prog)
{
fprintf(stderr, "usage: %s [-c <config file>] [--sv]\n", prog);
fprintf(stderr, "\t--help Show usage message\n");
fprintf(stderr, "\t--sv Use shared vision multicast port\n");
fprintf(stderr, "\t--headless Run the simulator in headless mode (without a GUI)\n");
}
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
Field_Dimensions::Current_Dimensions = Field_Dimensions::Single_Field_Dimensions * scaling;
QString configFile = "simulator.cfg";
bool sendShared = false;
bool headless = false;
//loop arguments and look for config file
for (int i=1 ; i<argc ; ++i)
{
if (strcmp(argv[i], "--help") == 0)
{
usage(argv[0]);
return 1;
} else if (strcmp(argv[i], "--sv") == 0)
{
sendShared = true;
} else if (strcmp(argv[i], "-c") == 0)
{
++i;
if (i < argc)
{
configFile = argv[i];
}
else
{
printf ("Expected config file after -c parameter\n");
return 1;
}
} else if ((strcmp(argv[i], "--h") == 0) || (strcmp(argv[i], "--help") == 0))
{
usage(argv[0]);
return 0;
} else if (strcmp(argv[i], "--headless") == 0) {
headless = true;
} else {
printf("%s is not recognized as a valid flag\n", argv[i]);
return 1;
}
}
// create the thread for simulation
SimulatorGLUTThread sim_thread(argc, argv, configFile, sendShared, !headless);
struct sigaction act;
memset(&act, 0, sizeof(act));
act.sa_handler = quit;
sigaction(SIGINT, &act, 0);
// Create and initialize GUI with environment information
SimulatorWindow win(sim_thread.env());
if (!headless) {
win.show();
}
// initialize socket connections separately
sim_thread.env()->connectSockets();
// start up threads
sim_thread.start();
int ret = app.exec();
// shut down sim_thread
sim_thread.stop();
sim_thread.wait();
return 0;//ret;
}
<|endoftext|> |
<commit_before>/*************************************************************************/
/* base_object_glue.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "base_object_glue.h"
#ifdef MONO_GLUE_ENABLED
#include "core/reference.h"
#include "core/string_name.h"
#include "../csharp_script.h"
#include "../mono_gd/gd_mono_class.h"
#include "../mono_gd/gd_mono_internals.h"
#include "../mono_gd/gd_mono_utils.h"
#include "../signal_awaiter_utils.h"
#include "arguments_vector.h"
Object *godot_icall_Object_Ctor(MonoObject *p_obj) {
Object *instance = memnew(Object);
GDMonoInternals::tie_managed_to_unmanaged(p_obj, instance);
return instance;
}
void godot_icall_Object_Disposed(MonoObject *p_obj, Object *p_ptr) {
#ifdef DEBUG_ENABLED
CRASH_COND(p_ptr == NULL);
#endif
if (p_ptr->get_script_instance()) {
CSharpInstance *cs_instance = CAST_CSHARP_INSTANCE(p_ptr->get_script_instance());
if (cs_instance) {
if (!cs_instance->is_destructing_script_instance()) {
cs_instance->mono_object_disposed(p_obj);
p_ptr->set_script_instance(NULL);
}
return;
}
}
void *data = p_ptr->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index());
if (data) {
CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
if (script_binding.inited) {
Ref<MonoGCHandle> &gchandle = script_binding.gchandle;
if (gchandle.is_valid()) {
CSharpLanguage::release_script_gchandle(p_obj, gchandle);
}
}
}
}
void godot_icall_Reference_Disposed(MonoObject *p_obj, Object *p_ptr, MonoBoolean p_is_finalizer) {
#ifdef DEBUG_ENABLED
CRASH_COND(p_ptr == NULL);
// This is only called with Reference derived classes
CRASH_COND(!Object::cast_to<Reference>(p_ptr));
#endif
Reference *ref = static_cast<Reference *>(p_ptr);
if (ref->get_script_instance()) {
CSharpInstance *cs_instance = CAST_CSHARP_INSTANCE(ref->get_script_instance());
if (cs_instance) {
if (!cs_instance->is_destructing_script_instance()) {
bool delete_owner;
bool remove_script_instance;
cs_instance->mono_object_disposed_baseref(p_obj, p_is_finalizer, delete_owner, remove_script_instance);
if (delete_owner) {
memdelete(ref);
} else if (remove_script_instance) {
ref->set_script_instance(NULL);
}
}
return;
}
}
// Unsafe refcount decrement. The managed instance also counts as a reference.
// See: CSharpLanguage::alloc_instance_binding_data(Object *p_object)
if (ref->unreference()) {
memdelete(ref);
} else {
void *data = ref->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index());
if (data) {
CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
if (script_binding.inited) {
Ref<MonoGCHandle> &gchandle = script_binding.gchandle;
if (gchandle.is_valid()) {
CSharpLanguage::release_script_gchandle(p_obj, gchandle);
}
}
}
}
}
MethodBind *godot_icall_Object_ClassDB_get_method(MonoString *p_type, MonoString *p_method) {
StringName type(GDMonoMarshal::mono_string_to_godot(p_type));
StringName method(GDMonoMarshal::mono_string_to_godot(p_method));
return ClassDB::get_method(type, method);
}
MonoObject *godot_icall_Object_weakref(Object *p_obj) {
if (!p_obj)
return NULL;
Ref<WeakRef> wref;
Reference *ref = Object::cast_to<Reference>(p_obj);
if (ref) {
REF r = ref;
if (!r.is_valid())
return NULL;
wref.instance();
wref->set_ref(r);
} else {
wref.instance();
wref->set_obj(p_obj);
}
return GDMonoUtils::unmanaged_get_managed(wref.ptr());
}
Error godot_icall_SignalAwaiter_connect(Object *p_source, MonoString *p_signal, Object *p_target, MonoObject *p_awaiter) {
String signal = GDMonoMarshal::mono_string_to_godot(p_signal);
return SignalAwaiterUtils::connect_signal_awaiter(p_source, signal, p_target, p_awaiter);
}
MonoArray *godot_icall_DynamicGodotObject_SetMemberList(Object *p_ptr) {
List<PropertyInfo> property_list;
p_ptr->get_property_list(&property_list);
MonoArray *result = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(String), property_list.size());
int i = 0;
for (List<PropertyInfo>::Element *E = property_list.front(); E; E = E->next()) {
MonoString *boxed = GDMonoMarshal::mono_string_from_godot(E->get().name);
mono_array_setref(result, i, boxed);
i++;
}
return result;
}
MonoBoolean godot_icall_DynamicGodotObject_InvokeMember(Object *p_ptr, MonoString *p_name, MonoArray *p_args, MonoObject **r_result) {
String name = GDMonoMarshal::mono_string_to_godot(p_name);
int argc = mono_array_length(p_args);
ArgumentsVector<Variant> arg_store(argc);
ArgumentsVector<const Variant *> args(argc);
for (int i = 0; i < argc; i++) {
MonoObject *elem = mono_array_get(p_args, MonoObject *, i);
arg_store.set(i, GDMonoMarshal::mono_object_to_variant(elem));
args.set(i, &arg_store.get(i));
}
Variant::CallError error;
Variant result = p_ptr->call(StringName(name), args.ptr(), argc, error);
*r_result = GDMonoMarshal::variant_to_mono_object(result);
return error.error == Variant::CallError::CALL_OK;
}
MonoBoolean godot_icall_DynamicGodotObject_GetMember(Object *p_ptr, MonoString *p_name, MonoObject **r_result) {
String name = GDMonoMarshal::mono_string_to_godot(p_name);
bool valid;
Variant value = p_ptr->get(StringName(name), &valid);
if (valid) {
*r_result = GDMonoMarshal::variant_to_mono_object(value);
}
return valid;
}
MonoBoolean godot_icall_DynamicGodotObject_SetMember(Object *p_ptr, MonoString *p_name, MonoObject *p_value) {
String name = GDMonoMarshal::mono_string_to_godot(p_name);
Variant value = GDMonoMarshal::mono_object_to_variant(p_value);
bool valid;
p_ptr->set(StringName(name), value, &valid);
return valid;
}
MonoString *godot_icall_Object_ToString(Object *p_ptr) {
return GDMonoMarshal::mono_string_from_godot(Variant(p_ptr).operator String());
}
void godot_register_object_icalls() {
mono_add_internal_call("Godot.Object::godot_icall_Object_Ctor", (void *)godot_icall_Object_Ctor);
mono_add_internal_call("Godot.Object::godot_icall_Object_Disposed", (void *)godot_icall_Object_Disposed);
mono_add_internal_call("Godot.Object::godot_icall_Reference_Disposed", (void *)godot_icall_Reference_Disposed);
mono_add_internal_call("Godot.Object::godot_icall_Object_ClassDB_get_method", (void *)godot_icall_Object_ClassDB_get_method);
mono_add_internal_call("Godot.Object::godot_icall_Object_ToString", (void *)godot_icall_Object_ToString);
mono_add_internal_call("Godot.Object::godot_icall_Object_weakref", (void *)godot_icall_Object_weakref);
mono_add_internal_call("Godot.SignalAwaiter::godot_icall_SignalAwaiter_connect", (void *)godot_icall_SignalAwaiter_connect);
mono_add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_SetMemberList", (void *)godot_icall_DynamicGodotObject_SetMemberList);
mono_add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_InvokeMember", (void *)godot_icall_DynamicGodotObject_InvokeMember);
mono_add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_GetMember", (void *)godot_icall_DynamicGodotObject_GetMember);
mono_add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_SetMember", (void *)godot_icall_DynamicGodotObject_SetMember);
}
#endif // MONO_GLUE_ENABLED
<commit_msg>Fix Godot.Object.ToString() infinite recursion<commit_after>/*************************************************************************/
/* base_object_glue.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "base_object_glue.h"
#ifdef MONO_GLUE_ENABLED
#include "core/reference.h"
#include "core/string_name.h"
#include "../csharp_script.h"
#include "../mono_gd/gd_mono_class.h"
#include "../mono_gd/gd_mono_internals.h"
#include "../mono_gd/gd_mono_utils.h"
#include "../signal_awaiter_utils.h"
#include "arguments_vector.h"
Object *godot_icall_Object_Ctor(MonoObject *p_obj) {
Object *instance = memnew(Object);
GDMonoInternals::tie_managed_to_unmanaged(p_obj, instance);
return instance;
}
void godot_icall_Object_Disposed(MonoObject *p_obj, Object *p_ptr) {
#ifdef DEBUG_ENABLED
CRASH_COND(p_ptr == NULL);
#endif
if (p_ptr->get_script_instance()) {
CSharpInstance *cs_instance = CAST_CSHARP_INSTANCE(p_ptr->get_script_instance());
if (cs_instance) {
if (!cs_instance->is_destructing_script_instance()) {
cs_instance->mono_object_disposed(p_obj);
p_ptr->set_script_instance(NULL);
}
return;
}
}
void *data = p_ptr->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index());
if (data) {
CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
if (script_binding.inited) {
Ref<MonoGCHandle> &gchandle = script_binding.gchandle;
if (gchandle.is_valid()) {
CSharpLanguage::release_script_gchandle(p_obj, gchandle);
}
}
}
}
void godot_icall_Reference_Disposed(MonoObject *p_obj, Object *p_ptr, MonoBoolean p_is_finalizer) {
#ifdef DEBUG_ENABLED
CRASH_COND(p_ptr == NULL);
// This is only called with Reference derived classes
CRASH_COND(!Object::cast_to<Reference>(p_ptr));
#endif
Reference *ref = static_cast<Reference *>(p_ptr);
if (ref->get_script_instance()) {
CSharpInstance *cs_instance = CAST_CSHARP_INSTANCE(ref->get_script_instance());
if (cs_instance) {
if (!cs_instance->is_destructing_script_instance()) {
bool delete_owner;
bool remove_script_instance;
cs_instance->mono_object_disposed_baseref(p_obj, p_is_finalizer, delete_owner, remove_script_instance);
if (delete_owner) {
memdelete(ref);
} else if (remove_script_instance) {
ref->set_script_instance(NULL);
}
}
return;
}
}
// Unsafe refcount decrement. The managed instance also counts as a reference.
// See: CSharpLanguage::alloc_instance_binding_data(Object *p_object)
if (ref->unreference()) {
memdelete(ref);
} else {
void *data = ref->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index());
if (data) {
CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
if (script_binding.inited) {
Ref<MonoGCHandle> &gchandle = script_binding.gchandle;
if (gchandle.is_valid()) {
CSharpLanguage::release_script_gchandle(p_obj, gchandle);
}
}
}
}
}
MethodBind *godot_icall_Object_ClassDB_get_method(MonoString *p_type, MonoString *p_method) {
StringName type(GDMonoMarshal::mono_string_to_godot(p_type));
StringName method(GDMonoMarshal::mono_string_to_godot(p_method));
return ClassDB::get_method(type, method);
}
MonoObject *godot_icall_Object_weakref(Object *p_obj) {
if (!p_obj)
return NULL;
Ref<WeakRef> wref;
Reference *ref = Object::cast_to<Reference>(p_obj);
if (ref) {
REF r = ref;
if (!r.is_valid())
return NULL;
wref.instance();
wref->set_ref(r);
} else {
wref.instance();
wref->set_obj(p_obj);
}
return GDMonoUtils::unmanaged_get_managed(wref.ptr());
}
Error godot_icall_SignalAwaiter_connect(Object *p_source, MonoString *p_signal, Object *p_target, MonoObject *p_awaiter) {
String signal = GDMonoMarshal::mono_string_to_godot(p_signal);
return SignalAwaiterUtils::connect_signal_awaiter(p_source, signal, p_target, p_awaiter);
}
MonoArray *godot_icall_DynamicGodotObject_SetMemberList(Object *p_ptr) {
List<PropertyInfo> property_list;
p_ptr->get_property_list(&property_list);
MonoArray *result = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(String), property_list.size());
int i = 0;
for (List<PropertyInfo>::Element *E = property_list.front(); E; E = E->next()) {
MonoString *boxed = GDMonoMarshal::mono_string_from_godot(E->get().name);
mono_array_setref(result, i, boxed);
i++;
}
return result;
}
MonoBoolean godot_icall_DynamicGodotObject_InvokeMember(Object *p_ptr, MonoString *p_name, MonoArray *p_args, MonoObject **r_result) {
String name = GDMonoMarshal::mono_string_to_godot(p_name);
int argc = mono_array_length(p_args);
ArgumentsVector<Variant> arg_store(argc);
ArgumentsVector<const Variant *> args(argc);
for (int i = 0; i < argc; i++) {
MonoObject *elem = mono_array_get(p_args, MonoObject *, i);
arg_store.set(i, GDMonoMarshal::mono_object_to_variant(elem));
args.set(i, &arg_store.get(i));
}
Variant::CallError error;
Variant result = p_ptr->call(StringName(name), args.ptr(), argc, error);
*r_result = GDMonoMarshal::variant_to_mono_object(result);
return error.error == Variant::CallError::CALL_OK;
}
MonoBoolean godot_icall_DynamicGodotObject_GetMember(Object *p_ptr, MonoString *p_name, MonoObject **r_result) {
String name = GDMonoMarshal::mono_string_to_godot(p_name);
bool valid;
Variant value = p_ptr->get(StringName(name), &valid);
if (valid) {
*r_result = GDMonoMarshal::variant_to_mono_object(value);
}
return valid;
}
MonoBoolean godot_icall_DynamicGodotObject_SetMember(Object *p_ptr, MonoString *p_name, MonoObject *p_value) {
String name = GDMonoMarshal::mono_string_to_godot(p_name);
Variant value = GDMonoMarshal::mono_object_to_variant(p_value);
bool valid;
p_ptr->set(StringName(name), value, &valid);
return valid;
}
MonoString *godot_icall_Object_ToString(Object *p_ptr) {
#ifdef DEBUG_ENABLED
// Cannot happen in C#; would get an ObjectDisposedException instead.
CRASH_COND(p_ptr == NULL);
if (ScriptDebugger::get_singleton() && !Object::cast_to<Reference>(p_ptr)) { // Only if debugging!
// Cannot happen either in C#; the handle is nullified when the object is destroyed
CRASH_COND(!ObjectDB::instance_validate(p_ptr));
}
#endif
String result = "[" + p_ptr->get_class() + ":" + itos(p_ptr->get_instance_id()) + "]";
return GDMonoMarshal::mono_string_from_godot(result);
}
void godot_register_object_icalls() {
mono_add_internal_call("Godot.Object::godot_icall_Object_Ctor", (void *)godot_icall_Object_Ctor);
mono_add_internal_call("Godot.Object::godot_icall_Object_Disposed", (void *)godot_icall_Object_Disposed);
mono_add_internal_call("Godot.Object::godot_icall_Reference_Disposed", (void *)godot_icall_Reference_Disposed);
mono_add_internal_call("Godot.Object::godot_icall_Object_ClassDB_get_method", (void *)godot_icall_Object_ClassDB_get_method);
mono_add_internal_call("Godot.Object::godot_icall_Object_ToString", (void *)godot_icall_Object_ToString);
mono_add_internal_call("Godot.Object::godot_icall_Object_weakref", (void *)godot_icall_Object_weakref);
mono_add_internal_call("Godot.SignalAwaiter::godot_icall_SignalAwaiter_connect", (void *)godot_icall_SignalAwaiter_connect);
mono_add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_SetMemberList", (void *)godot_icall_DynamicGodotObject_SetMemberList);
mono_add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_InvokeMember", (void *)godot_icall_DynamicGodotObject_InvokeMember);
mono_add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_GetMember", (void *)godot_icall_DynamicGodotObject_GetMember);
mono_add_internal_call("Godot.DynamicGodotObject::godot_icall_DynamicGodotObject_SetMember", (void *)godot_icall_DynamicGodotObject_SetMember);
}
#endif // MONO_GLUE_ENABLED
<|endoftext|> |
<commit_before>/**********************************************************************************/
/* godotsharp_editor.cpp */
/**********************************************************************************/
/* The MIT License (MIT) */
/* */
/* Copyright (c) 2016 Ignacio Etcheverry */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining a copy */
/* of this software and associated documentation files (the "Software"), to deal */
/* in the Software without restriction, including without limitation the rights */
/* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell */
/* copies of the Software, and to permit persons to whom the Software is */
/* furnished to do so, subject to the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be included in all */
/* copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR */
/* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, */
/* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE */
/* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER */
/* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, */
/* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */
/* SOFTWARE. */
/**********************************************************************************/
#include "godotsharp_editor.h"
#include "scene/gui/control.h"
#include "scene/main/node.h"
#include "../csharp_script.h"
#include "../godotsharp_dirs.h"
#include "bindings_generator.h"
#include "csharp_project.h"
#include "net_solution.h"
#ifdef WINDOWS_ENABLED
#include "../utils/mono_reg_utils.h"
#endif
class MonoReloadNode : public Node {
GDCLASS(MonoReloadNode, Node)
protected:
void _notification(int p_what) {
switch (p_what) {
case MainLoop::NOTIFICATION_WM_FOCUS_IN: {
CSharpLanguage::get_singleton()->reload_assemblies_if_needed(true);
} break;
default: {
} break;
};
}
};
GodotSharpEditor *GodotSharpEditor::singleton = NULL;
bool GodotSharpEditor::_create_project_solution() {
EditorProgress pr("create_csharp_solution", "Generating solution...", 2);
pr.step("Generating C# project...");
String path = OS::get_singleton()->get_resource_dir();
String name = ProjectSettings::get_singleton()->get("application/config/name");
String guid = CSharpProject::generate_game_project(path, name);
if (guid.length()) {
NETSolution solution(name);
if (!solution.set_path(path)) {
show_error("Failed to create solution.");
return false;
}
Vector<String> extra_configs;
extra_configs.push_back("Tools");
solution.add_new_project(name, guid, extra_configs);
Error sln_error = solution.save();
if (sln_error != OK) {
show_error("Failed to save solution.");
return false;
}
if (!GodotSharpBuilds::make_api_sln(GodotSharpBuilds::API_CORE))
return false;
if (!GodotSharpBuilds::make_api_sln(GodotSharpBuilds::API_EDITOR))
return false;
call_deferred("_remove_create_sln_menu_option");
} else {
show_error("Failed to create C# project.");
}
pr.step("Done");
return true;
}
void GodotSharpEditor::_remove_create_sln_menu_option() {
menu_popup->remove_item(menu_popup->get_item_index(MENU_CREATE_SLN));
if (menu_popup->get_item_count() == 0)
menu_button->hide();
}
void GodotSharpEditor::_menu_option_pressed(int p_id) {
switch (p_id) {
case MENU_CREATE_SLN: {
_create_project_solution();
} break;
default:
ERR_FAIL();
}
}
void GodotSharpEditor::_bind_methods() {
ClassDB::bind_method(D_METHOD("_create_project_solution"), &GodotSharpEditor::_create_project_solution);
ClassDB::bind_method(D_METHOD("_remove_create_sln_menu_option"), &GodotSharpEditor::_remove_create_sln_menu_option);
ClassDB::bind_method(D_METHOD("_menu_option_pressed", "id"), &GodotSharpEditor::_menu_option_pressed);
}
void GodotSharpEditor::show_error(const String &p_message, const String &p_title) {
error_dialog->set_title(p_title);
error_dialog->set_text(p_message);
error_dialog->popup_centered_minsize();
}
GodotSharpEditor::GodotSharpEditor(EditorNode *p_editor) {
singleton = this;
editor = p_editor;
menu_button = memnew(MenuButton);
menu_button->set_text("Mono");
menu_popup = menu_button->get_popup();
if (!FileAccess::exists(GodotSharpDirs::get_project_sln_path())) {
menu_popup->add_item("Create C# solution", MENU_CREATE_SLN);
}
menu_popup->connect("id_pressed", this, "_menu_option_pressed");
if (menu_popup->get_item_count() == 0)
menu_button->hide();
editor->get_menu_hb()->add_child(menu_button);
error_dialog = memnew(AcceptDialog);
editor->get_gui_base()->add_child(error_dialog);
editor->add_bottom_panel_item("Mono", memnew(MonoBottomPanel(editor)));
godotsharp_builds = memnew(GodotSharpBuilds);
editor->add_child(memnew(MonoReloadNode));
}
GodotSharpEditor::~GodotSharpEditor() {
singleton = NULL;
memdelete(godotsharp_builds);
}
<commit_msg>Fixes (maybe) #46<commit_after>/**********************************************************************************/
/* godotsharp_editor.cpp */
/**********************************************************************************/
/* The MIT License (MIT) */
/* */
/* Copyright (c) 2016 Ignacio Etcheverry */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining a copy */
/* of this software and associated documentation files (the "Software"), to deal */
/* in the Software without restriction, including without limitation the rights */
/* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell */
/* copies of the Software, and to permit persons to whom the Software is */
/* furnished to do so, subject to the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be included in all */
/* copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR */
/* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, */
/* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE */
/* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER */
/* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, */
/* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */
/* SOFTWARE. */
/**********************************************************************************/
#include "godotsharp_editor.h"
#include "scene/gui/control.h"
#include "scene/main/node.h"
#include "../csharp_script.h"
#include "../godotsharp_dirs.h"
#include "bindings_generator.h"
#include "csharp_project.h"
#include "net_solution.h"
#ifdef WINDOWS_ENABLED
#include "../utils/mono_reg_utils.h"
#endif
class MonoReloadNode : public Node {
GDCLASS(MonoReloadNode, Node)
protected:
void _notification(int p_what) {
switch (p_what) {
case MainLoop::NOTIFICATION_WM_FOCUS_IN: {
CSharpLanguage::get_singleton()->reload_assemblies_if_needed(true);
} break;
default: {
} break;
};
}
};
GodotSharpEditor *GodotSharpEditor::singleton = NULL;
bool GodotSharpEditor::_create_project_solution() {
EditorProgress pr("create_csharp_solution", "Generating solution...", 2);
pr.step("Generating C# project...");
String path = OS::get_singleton()->get_resource_dir();
String name = ProjectSettings::get_singleton()->get("application/config/name");
String guid = CSharpProject::generate_game_project(path, name);
if (guid.length()) {
NETSolution solution(name);
if (!solution.set_path(path)) {
show_error("Failed to create solution.");
return false;
}
Vector<String> extra_configs;
extra_configs.push_back("Tools");
solution.add_new_project(name, guid, extra_configs);
Error sln_error = solution.save();
if (sln_error != OK) {
show_error("Failed to save solution.");
return false;
}
if (!GodotSharpBuilds::make_api_sln(GodotSharpBuilds::API_CORE))
return false;
if (!GodotSharpBuilds::make_api_sln(GodotSharpBuilds::API_EDITOR))
return false;
call_deferred("_remove_create_sln_menu_option");
} else {
show_error("Failed to create C# project.");
}
pr.step("Done");
return true;
}
void GodotSharpEditor::_remove_create_sln_menu_option() {
menu_popup->remove_item(menu_popup->get_item_index(MENU_CREATE_SLN));
if (menu_popup->get_item_count() == 0)
menu_button->hide();
}
void GodotSharpEditor::_menu_option_pressed(int p_id) {
switch (p_id) {
case MENU_CREATE_SLN: {
_create_project_solution();
} break;
default:
ERR_FAIL();
}
}
void GodotSharpEditor::_bind_methods() {
ClassDB::bind_method(D_METHOD("_create_project_solution"), &GodotSharpEditor::_create_project_solution);
ClassDB::bind_method(D_METHOD("_remove_create_sln_menu_option"), &GodotSharpEditor::_remove_create_sln_menu_option);
ClassDB::bind_method(D_METHOD("_menu_option_pressed", "id"), &GodotSharpEditor::_menu_option_pressed);
}
void GodotSharpEditor::show_error(const String &p_message, const String &p_title) {
error_dialog->set_title(p_title);
error_dialog->set_text(p_message);
error_dialog->popup_centered_minsize();
}
GodotSharpEditor::GodotSharpEditor(EditorNode *p_editor) {
singleton = this;
editor = p_editor;
menu_button = memnew(MenuButton);
menu_button->set_text("Mono");
menu_popup = menu_button->get_popup();
if (!FileAccess::exists(GodotSharpDirs::get_project_sln_path())) {
menu_popup->add_item("Create C# solution", MENU_CREATE_SLN);
}
menu_popup->connect("id_pressed", this, "_menu_option_pressed", varray(), CONNECT_DEFERRED);
if (menu_popup->get_item_count() == 0)
menu_button->hide();
editor->get_menu_hb()->add_child(menu_button);
error_dialog = memnew(AcceptDialog);
editor->get_gui_base()->add_child(error_dialog);
editor->add_bottom_panel_item("Mono", memnew(MonoBottomPanel(editor)));
godotsharp_builds = memnew(GodotSharpBuilds);
editor->add_child(memnew(MonoReloadNode));
}
GodotSharpEditor::~GodotSharpEditor() {
singleton = NULL;
memdelete(godotsharp_builds);
}
<|endoftext|> |
<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetEventTest
#include <boost/test/unit_test.hpp>
#include "../JPetEvent/JPetEvent.h"
BOOST_AUTO_TEST_SUITE(FirstSuite)
BOOST_AUTO_TEST_CASE( default_constructor )
{
JPetEvent event;
BOOST_REQUIRE(event.getHits().empty());
}
BOOST_AUTO_TEST_CASE(constructor)
{
JPetBarrelSlot slot1(43, true, "", 0, 43);
JPetBarrelSlot slot2(44, true, "", 0, 44);
JPetHit firstHit;
JPetHit secondHit;
firstHit.setBarrelSlot(slot1);
secondHit.setBarrelSlot(slot2);
JPetEvent event({firstHit, secondHit}, JPetEventType::kUnknown);
BOOST_REQUIRE(!event.getHits().empty());
BOOST_REQUIRE_EQUAL(event.getHits().size(), 2);
}
BOOST_AUTO_TEST_CASE(constructor_orderedHits)
{
std::vector<JPetHit> hits(4);
hits[0].setTime(2);
hits[1].setTime(1);
hits[2].setTime(4);
hits[3].setTime(3);
JPetEvent event(hits, JPetEventType::kUnknown);
auto results = event.getHits();
BOOST_REQUIRE_EQUAL(results[0].getTime(), 1);
BOOST_REQUIRE_EQUAL(results[1].getTime(), 2);
BOOST_REQUIRE_EQUAL(results[2].getTime(), 3);
BOOST_REQUIRE_EQUAL(results[3].getTime(), 4);
}
BOOST_AUTO_TEST_CASE(constructor_unorderedHits)
{
std::vector<JPetHit> hits(4);
hits[0].setTime(2);
hits[1].setTime(1);
hits[2].setTime(4);
hits[3].setTime(3);
JPetEvent event(hits, JPetEventType::kUnknown, false);
auto results = event.getHits();
BOOST_REQUIRE_EQUAL(results[0].getTime(), 2);
BOOST_REQUIRE_EQUAL(results[1].getTime(), 1);
BOOST_REQUIRE_EQUAL(results[2].getTime(), 4);
BOOST_REQUIRE_EQUAL(results[3].getTime(), 3);
}
BOOST_AUTO_TEST_CASE(set_unorderedHits)
{
JPetEvent event;
std::vector<JPetHit> hits(4);
hits[0].setTime(2);
hits[1].setTime(1);
hits[2].setTime(4);
hits[3].setTime(3);
event.setHits(hits, false);
auto results = event.getHits();
BOOST_REQUIRE_EQUAL(results[0].getTime(), 2);
BOOST_REQUIRE_EQUAL(results[1].getTime(), 1);
BOOST_REQUIRE_EQUAL(results[2].getTime(), 4);
BOOST_REQUIRE_EQUAL(results[3].getTime(), 3);
}
BOOST_AUTO_TEST_CASE(set_orderedHits)
{
JPetEvent event;
std::vector<JPetHit> hits(4);
hits[0].setTime(2);
hits[1].setTime(1);
hits[2].setTime(4);
hits[3].setTime(3);
event.setHits(hits);
auto results = event.getHits();
BOOST_REQUIRE_EQUAL(results[0].getTime(), 1);
BOOST_REQUIRE_EQUAL(results[1].getTime(), 2);
BOOST_REQUIRE_EQUAL(results[2].getTime(), 3);
BOOST_REQUIRE_EQUAL(results[3].getTime(), 4);
}
BOOST_AUTO_TEST_CASE(addHit)
{
JPetEvent event;
JPetHit firstHit;
JPetHit secondHit;
JPetHit thirdHit;
event.setHits( {firstHit, secondHit});
BOOST_REQUIRE(!event.getHits().empty());
BOOST_REQUIRE_EQUAL(event.getHits().size(), 2);
event.addHit(thirdHit);
BOOST_REQUIRE_EQUAL(event.getHits().size(), 3);
}
BOOST_AUTO_TEST_CASE(eventTypes)
{
JPetEvent event;
auto type = event.getEventType();
BOOST_REQUIRE((type & JPetEventType::kUnknown) == JPetEventType::kUnknown);
BOOST_REQUIRE((type & JPetEventType::k2Gamma) != JPetEventType::k2Gamma);
BOOST_REQUIRE((type & JPetEventType::k3Gamma) != JPetEventType::k3Gamma);
BOOST_REQUIRE((type & JPetEventType::kPrompt) != JPetEventType::kPrompt);
BOOST_REQUIRE((type & JPetEventType::kScattered) != JPetEventType::kScattered);
}
BOOST_AUTO_TEST_CASE(eventTypes2)
{
JPetHit firstHit;
JPetEvent event( {firstHit}, JPetEventType::kPrompt);
auto type = event.getEventType();
BOOST_REQUIRE((type & JPetEventType::kPrompt) == JPetEventType::kPrompt);
BOOST_REQUIRE((type & JPetEventType::kUnknown) != JPetEventType::kUnknown);
BOOST_REQUIRE((type & JPetEventType::k2Gamma) != JPetEventType::k2Gamma);
BOOST_REQUIRE((type & JPetEventType::k3Gamma) != JPetEventType::k3Gamma);
BOOST_REQUIRE((type & JPetEventType::kScattered) != JPetEventType::kScattered);
}
BOOST_AUTO_TEST_CASE(eventTypes3)
{
JPetHit firstHit;
JPetEvent event( {firstHit}, static_cast<JPetEventType>(JPetEventType::kPrompt | JPetEventType::k2Gamma));
auto type = event.getEventType();
BOOST_REQUIRE((type & JPetEventType::kPrompt) == JPetEventType::kPrompt);
BOOST_REQUIRE((type & JPetEventType::k2Gamma) == JPetEventType::k2Gamma);
BOOST_REQUIRE((type & JPetEventType::kUnknown) != JPetEventType::kUnknown);
BOOST_REQUIRE((type & JPetEventType::k3Gamma) != JPetEventType::k3Gamma);
BOOST_REQUIRE((type & JPetEventType::kScattered) != JPetEventType::kScattered);
}
BOOST_AUTO_TEST_CASE(isTypeOf)
{
JPetHit firstHit;
JPetEvent event( {firstHit}, static_cast<JPetEventType>(JPetEventType::kPrompt | JPetEventType::k2Gamma));
BOOST_REQUIRE(event.isTypeOf(JPetEventType::k2Gamma));
BOOST_REQUIRE(!event.isTypeOf(JPetEventType::k3Gamma));
BOOST_REQUIRE(event.isTypeOf(JPetEventType::kPrompt));
BOOST_REQUIRE(!event.isTypeOf(JPetEventType::kUnknown));
BOOST_REQUIRE(!event.isTypeOf(JPetEventType::kScattered));
}
BOOST_AUTO_TEST_CASE(isOnlyTypeOf)
{
JPetHit firstHit;
JPetEvent event( {firstHit}, static_cast<JPetEventType>(JPetEventType::kPrompt | JPetEventType::k2Gamma));
BOOST_REQUIRE(!event.isOnlyTypeOf(JPetEventType::k2Gamma));
BOOST_REQUIRE(!event.isOnlyTypeOf(JPetEventType::k3Gamma));
BOOST_REQUIRE(!event.isOnlyTypeOf(JPetEventType::kPrompt));
BOOST_REQUIRE(!event.isOnlyTypeOf(JPetEventType::kUnknown));
BOOST_REQUIRE(!event.isOnlyTypeOf(JPetEventType::kScattered));
BOOST_REQUIRE(event.isOnlyTypeOf(static_cast<JPetEventType>(JPetEventType::kPrompt | JPetEventType::k2Gamma)));
JPetEvent event2;
event2.addEventType(JPetEventType::kPrompt);
BOOST_REQUIRE(event2.isOnlyTypeOf(JPetEventType::kPrompt));
BOOST_REQUIRE(!event2.isOnlyTypeOf(JPetEventType::k2Gamma));
BOOST_REQUIRE(!event2.isOnlyTypeOf(JPetEventType::k3Gamma));
BOOST_REQUIRE(!event2.isOnlyTypeOf(JPetEventType::kUnknown));
BOOST_REQUIRE(!event2.isOnlyTypeOf(JPetEventType::kScattered));
}
BOOST_AUTO_TEST_CASE(setGetType)
{
JPetHit firstHit;
JPetEvent event( {firstHit}, JPetEventType::kPrompt);
event.setEventType(static_cast<JPetEventType>(JPetEventType::k2Gamma | JPetEventType::k3Gamma));
auto type = event.getEventType();
BOOST_REQUIRE((type & JPetEventType::kPrompt) != JPetEventType::kPrompt);
BOOST_REQUIRE((type & JPetEventType::kUnknown) != JPetEventType::kUnknown);
BOOST_REQUIRE((type & JPetEventType::k2Gamma) == JPetEventType::k2Gamma);
BOOST_REQUIRE((type & JPetEventType::k3Gamma) == JPetEventType::k3Gamma);
BOOST_REQUIRE((type & JPetEventType::kScattered) != JPetEventType::kScattered);
}
BOOST_AUTO_TEST_CASE(addEventType)
{
JPetHit firstHit;
JPetEvent event( {firstHit}, JPetEventType::kPrompt);
event.addEventType(JPetEventType::k2Gamma);
auto type = event.getEventType();
BOOST_REQUIRE((type & JPetEventType::kPrompt) == JPetEventType::kPrompt);
BOOST_REQUIRE((type & JPetEventType::k2Gamma) == JPetEventType::k2Gamma);
BOOST_REQUIRE((type & JPetEventType::kUnknown) != JPetEventType::kUnknown);
BOOST_REQUIRE((type & JPetEventType::k3Gamma) != JPetEventType::k3Gamma);
BOOST_REQUIRE((type & JPetEventType::kScattered) != JPetEventType::kScattered);
}
BOOST_AUTO_TEST_CASE(addEventType2)
{
JPetEvent event; /// default is kUnknown
event.addEventType(JPetEventType::k2Gamma);
auto type = event.getEventType();
BOOST_REQUIRE((type & JPetEventType::k2Gamma) == JPetEventType::k2Gamma);
BOOST_REQUIRE((type & JPetEventType::kUnknown) != JPetEventType::kUnknown);
BOOST_REQUIRE((type & JPetEventType::k3Gamma) != JPetEventType::k3Gamma);
BOOST_REQUIRE((type & JPetEventType::kPrompt) != JPetEventType::kPrompt);
BOOST_REQUIRE((type & JPetEventType::kScattered) != JPetEventType::kScattered);
}
BOOST_AUTO_TEST_CASE(addEventType3)
{
JPetEvent event; /// default is kUnknown
event.addEventType(JPetEventType::k2Gamma);
auto type = event.getEventType();
BOOST_REQUIRE((type & JPetEventType::k2Gamma) == JPetEventType::k2Gamma);
BOOST_REQUIRE((type & JPetEventType::kUnknown) != JPetEventType::kUnknown);
BOOST_REQUIRE((type & JPetEventType::k3Gamma) != JPetEventType::k3Gamma);
BOOST_REQUIRE((type & JPetEventType::kPrompt) != JPetEventType::kPrompt);
BOOST_REQUIRE((type & JPetEventType::kScattered) != JPetEventType::kScattered);
event.addEventType(JPetEventType::k3Gamma);
BOOST_REQUIRE((type & JPetEventType::k2Gamma) == JPetEventType::k2Gamma);
BOOST_REQUIRE((type & JPetEventType::k3Gamma) == JPetEventType::k3Gamma);
BOOST_REQUIRE((type & JPetEventType::kUnknown) != JPetEventType::kUnknown);
BOOST_REQUIRE((type & JPetEventType::kPrompt) != JPetEventType::kPrompt);
BOOST_REQUIRE((type & JPetEventType::kScattered) != JPetEventType::kScattered);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Remove small error in the JPetEventTest<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetEventTest
#include <boost/test/unit_test.hpp>
#include "../JPetEvent/JPetEvent.h"
BOOST_AUTO_TEST_SUITE(FirstSuite)
BOOST_AUTO_TEST_CASE( default_constructor )
{
JPetEvent event;
BOOST_REQUIRE(event.getHits().empty());
}
BOOST_AUTO_TEST_CASE(constructor)
{
JPetBarrelSlot slot1(43, true, "", 0, 43);
JPetBarrelSlot slot2(44, true, "", 0, 44);
JPetHit firstHit;
JPetHit secondHit;
firstHit.setBarrelSlot(slot1);
secondHit.setBarrelSlot(slot2);
JPetEvent event({firstHit, secondHit}, JPetEventType::kUnknown);
BOOST_REQUIRE(!event.getHits().empty());
BOOST_REQUIRE_EQUAL(event.getHits().size(), 2);
}
BOOST_AUTO_TEST_CASE(constructor_orderedHits)
{
std::vector<JPetHit> hits(4);
hits[0].setTime(2);
hits[1].setTime(1);
hits[2].setTime(4);
hits[3].setTime(3);
JPetEvent event(hits, JPetEventType::kUnknown);
auto results = event.getHits();
BOOST_REQUIRE_EQUAL(results[0].getTime(), 1);
BOOST_REQUIRE_EQUAL(results[1].getTime(), 2);
BOOST_REQUIRE_EQUAL(results[2].getTime(), 3);
BOOST_REQUIRE_EQUAL(results[3].getTime(), 4);
}
BOOST_AUTO_TEST_CASE(constructor_unorderedHits)
{
std::vector<JPetHit> hits(4);
hits[0].setTime(2);
hits[1].setTime(1);
hits[2].setTime(4);
hits[3].setTime(3);
JPetEvent event(hits, JPetEventType::kUnknown, false);
auto results = event.getHits();
BOOST_REQUIRE_EQUAL(results[0].getTime(), 2);
BOOST_REQUIRE_EQUAL(results[1].getTime(), 1);
BOOST_REQUIRE_EQUAL(results[2].getTime(), 4);
BOOST_REQUIRE_EQUAL(results[3].getTime(), 3);
}
BOOST_AUTO_TEST_CASE(set_unorderedHits)
{
JPetEvent event;
std::vector<JPetHit> hits(4);
hits[0].setTime(2);
hits[1].setTime(1);
hits[2].setTime(4);
hits[3].setTime(3);
event.setHits(hits, false);
auto results = event.getHits();
BOOST_REQUIRE_EQUAL(results[0].getTime(), 2);
BOOST_REQUIRE_EQUAL(results[1].getTime(), 1);
BOOST_REQUIRE_EQUAL(results[2].getTime(), 4);
BOOST_REQUIRE_EQUAL(results[3].getTime(), 3);
}
BOOST_AUTO_TEST_CASE(set_orderedHits)
{
JPetEvent event;
std::vector<JPetHit> hits(4);
hits[0].setTime(2);
hits[1].setTime(1);
hits[2].setTime(4);
hits[3].setTime(3);
event.setHits(hits);
auto results = event.getHits();
BOOST_REQUIRE_EQUAL(results[0].getTime(), 1);
BOOST_REQUIRE_EQUAL(results[1].getTime(), 2);
BOOST_REQUIRE_EQUAL(results[2].getTime(), 3);
BOOST_REQUIRE_EQUAL(results[3].getTime(), 4);
}
BOOST_AUTO_TEST_CASE(addHit)
{
JPetEvent event;
JPetHit firstHit;
JPetHit secondHit;
JPetHit thirdHit;
event.setHits( {firstHit, secondHit});
BOOST_REQUIRE(!event.getHits().empty());
BOOST_REQUIRE_EQUAL(event.getHits().size(), 2);
event.addHit(thirdHit);
BOOST_REQUIRE_EQUAL(event.getHits().size(), 3);
}
BOOST_AUTO_TEST_CASE(eventTypes)
{
JPetEvent event;
auto type = event.getEventType();
BOOST_REQUIRE((type & JPetEventType::kUnknown) == JPetEventType::kUnknown);
BOOST_REQUIRE((type & JPetEventType::k2Gamma) != JPetEventType::k2Gamma);
BOOST_REQUIRE((type & JPetEventType::k3Gamma) != JPetEventType::k3Gamma);
BOOST_REQUIRE((type & JPetEventType::kPrompt) != JPetEventType::kPrompt);
BOOST_REQUIRE((type & JPetEventType::kScattered) != JPetEventType::kScattered);
}
BOOST_AUTO_TEST_CASE(eventTypes2)
{
JPetHit firstHit;
JPetEvent event( {firstHit}, JPetEventType::kPrompt);
auto type = event.getEventType();
BOOST_REQUIRE((type & JPetEventType::kPrompt) == JPetEventType::kPrompt);
BOOST_REQUIRE((type & JPetEventType::kUnknown) != JPetEventType::kUnknown);
BOOST_REQUIRE((type & JPetEventType::k2Gamma) != JPetEventType::k2Gamma);
BOOST_REQUIRE((type & JPetEventType::k3Gamma) != JPetEventType::k3Gamma);
BOOST_REQUIRE((type & JPetEventType::kScattered) != JPetEventType::kScattered);
}
BOOST_AUTO_TEST_CASE(eventTypes3)
{
JPetHit firstHit;
JPetEvent event( {firstHit}, static_cast<JPetEventType>(JPetEventType::kPrompt | JPetEventType::k2Gamma));
auto type = event.getEventType();
BOOST_REQUIRE((type & JPetEventType::kPrompt) == JPetEventType::kPrompt);
BOOST_REQUIRE((type & JPetEventType::k2Gamma) == JPetEventType::k2Gamma);
BOOST_REQUIRE((type & JPetEventType::kUnknown) != JPetEventType::kUnknown);
BOOST_REQUIRE((type & JPetEventType::k3Gamma) != JPetEventType::k3Gamma);
BOOST_REQUIRE((type & JPetEventType::kScattered) != JPetEventType::kScattered);
}
BOOST_AUTO_TEST_CASE(isTypeOf)
{
JPetHit firstHit;
JPetEvent event( {firstHit}, static_cast<JPetEventType>(JPetEventType::kPrompt | JPetEventType::k2Gamma));
BOOST_REQUIRE(event.isTypeOf(JPetEventType::k2Gamma));
BOOST_REQUIRE(!event.isTypeOf(JPetEventType::k3Gamma));
BOOST_REQUIRE(event.isTypeOf(JPetEventType::kPrompt));
BOOST_REQUIRE(!event.isTypeOf(JPetEventType::kUnknown));
BOOST_REQUIRE(!event.isTypeOf(JPetEventType::kScattered));
}
BOOST_AUTO_TEST_CASE(isOnlyTypeOf)
{
JPetHit firstHit;
JPetEvent event( {firstHit}, static_cast<JPetEventType>(JPetEventType::kPrompt | JPetEventType::k2Gamma));
BOOST_REQUIRE(!event.isOnlyTypeOf(JPetEventType::k2Gamma));
BOOST_REQUIRE(!event.isOnlyTypeOf(JPetEventType::k3Gamma));
BOOST_REQUIRE(!event.isOnlyTypeOf(JPetEventType::kPrompt));
BOOST_REQUIRE(!event.isOnlyTypeOf(JPetEventType::kUnknown));
BOOST_REQUIRE(!event.isOnlyTypeOf(JPetEventType::kScattered));
BOOST_REQUIRE(event.isOnlyTypeOf(static_cast<JPetEventType>(JPetEventType::kPrompt | JPetEventType::k2Gamma)));
JPetEvent event2;
event2.addEventType(JPetEventType::kPrompt);
BOOST_REQUIRE(event2.isOnlyTypeOf(JPetEventType::kPrompt));
BOOST_REQUIRE(!event2.isOnlyTypeOf(JPetEventType::k2Gamma));
BOOST_REQUIRE(!event2.isOnlyTypeOf(JPetEventType::k3Gamma));
BOOST_REQUIRE(!event2.isOnlyTypeOf(JPetEventType::kUnknown));
BOOST_REQUIRE(!event2.isOnlyTypeOf(JPetEventType::kScattered));
}
BOOST_AUTO_TEST_CASE(setGetType)
{
JPetHit firstHit;
JPetEvent event( {firstHit}, JPetEventType::kPrompt);
event.setEventType(static_cast<JPetEventType>(JPetEventType::k2Gamma | JPetEventType::k3Gamma));
auto type = event.getEventType();
BOOST_REQUIRE((type & JPetEventType::kPrompt) != JPetEventType::kPrompt);
BOOST_REQUIRE((type & JPetEventType::kUnknown) != JPetEventType::kUnknown);
BOOST_REQUIRE((type & JPetEventType::k2Gamma) == JPetEventType::k2Gamma);
BOOST_REQUIRE((type & JPetEventType::k3Gamma) == JPetEventType::k3Gamma);
BOOST_REQUIRE((type & JPetEventType::kScattered) != JPetEventType::kScattered);
}
BOOST_AUTO_TEST_CASE(addEventType)
{
JPetHit firstHit;
JPetEvent event( {firstHit}, JPetEventType::kPrompt);
event.addEventType(JPetEventType::k2Gamma);
auto type = event.getEventType();
BOOST_REQUIRE((type & JPetEventType::kPrompt) == JPetEventType::kPrompt);
BOOST_REQUIRE((type & JPetEventType::k2Gamma) == JPetEventType::k2Gamma);
BOOST_REQUIRE((type & JPetEventType::kUnknown) != JPetEventType::kUnknown);
BOOST_REQUIRE((type & JPetEventType::k3Gamma) != JPetEventType::k3Gamma);
BOOST_REQUIRE((type & JPetEventType::kScattered) != JPetEventType::kScattered);
}
BOOST_AUTO_TEST_CASE(addEventType2)
{
JPetEvent event; /// default is kUnknown
event.addEventType(JPetEventType::k2Gamma);
auto type = event.getEventType();
BOOST_REQUIRE((type & JPetEventType::k2Gamma) == JPetEventType::k2Gamma);
BOOST_REQUIRE((type & JPetEventType::kUnknown) != JPetEventType::kUnknown);
BOOST_REQUIRE((type & JPetEventType::k3Gamma) != JPetEventType::k3Gamma);
BOOST_REQUIRE((type & JPetEventType::kPrompt) != JPetEventType::kPrompt);
BOOST_REQUIRE((type & JPetEventType::kScattered) != JPetEventType::kScattered);
}
BOOST_AUTO_TEST_CASE(addEventType3)
{
JPetEvent event; /// default is kUnknown
event.addEventType(JPetEventType::k2Gamma);
auto type = event.getEventType();
BOOST_REQUIRE((type & JPetEventType::k2Gamma) == JPetEventType::k2Gamma);
BOOST_REQUIRE((type & JPetEventType::kUnknown) != JPetEventType::kUnknown);
BOOST_REQUIRE((type & JPetEventType::k3Gamma) != JPetEventType::k3Gamma);
BOOST_REQUIRE((type & JPetEventType::kPrompt) != JPetEventType::kPrompt);
BOOST_REQUIRE((type & JPetEventType::kScattered) != JPetEventType::kScattered);
event.addEventType(JPetEventType::k3Gamma);
type = event.getEventType();
BOOST_REQUIRE((type & JPetEventType::k2Gamma) == JPetEventType::k2Gamma);
BOOST_REQUIRE((type & JPetEventType::k3Gamma) == JPetEventType::k3Gamma);
BOOST_REQUIRE((type & JPetEventType::kUnknown) != JPetEventType::kUnknown);
BOOST_REQUIRE((type & JPetEventType::kPrompt) != JPetEventType::kPrompt);
BOOST_REQUIRE((type & JPetEventType::kScattered) != JPetEventType::kScattered);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include <cmath>
#include <cstdio>
#include <omp.h>
#include <mpi.h>
#include <cassert>
// (Sub-optimum) Array of Structure - good OOP. Bad Performance.
// Structure of individual particle
//struct ParticleType {
// float x, y, z;
// float vx, vy, vz;
//};
// (Optimum) Structure of Array - bad OOP. Good performance.
struct ParticleSetType {
float *x, *y, *z;
float *vx, *vy, *vz;
};
// define a function that moves each particle due to interaction with other particles
void MoveParticles(const int nParticles, ParticleSetType & particle, const float dt,
const int mpiRank, const int mpiWorldSize, const int myParticles) {
const int TILE = 16; // optimized for KNL
// redefine the start and end particle bucket for the ii loop tiling loop
const int startParticle = (mpiRank )*myParticles;
const int endParticle = (mpiRank + 1)*myParticles;
assert(myParticles % TILE == 0);
#pragma omp parallel for schedule(guided)
// Loop over particles that experience force
for (int ii = startParticle; ii < endParticle; ii+=TILE) {
// Components of the gravity force on particle i
float Fx[TILE], Fy[TILE], Fz[TILE];
Fx[:] = Fy[:] = Fz[:] = 0.0f;
// Avoid singularity and interaction with self
const float softening = 1e-20;
// Loop over particles that exert force: vectorization expected here
#pragma unroll(TILE)
for (int j = 0; j < nParticles; j++) {
#pragma vector aligned
// How much data in this tiled loop?
// 16 (particles in a tile) * 3 floats * 4 bytes per floats = 192 bytes
// enough to fit in the L1 Cache registery
for (int i = ii; i < ii+TILE; i++) {
// Newton's law of universal gravity
const float dx = particle.x[j] - particle.x[i];
const float dy = particle.y[j] - particle.y[i];
const float dz = particle.z[j] - particle.z[i];
const float drSquared = dx*dx + dy*dy + dz*dz + softening;
const float oodr = 1.0f/sqrtf(drSquared);
const float drPowerN3 = oodr*oodr*oodr;
// Calculate the net force
// Assume mass is 1 (for ease of computation)
// F = ma = 1*a = a
Fx[i-ii] += dx * drPowerN3; // scalar tuning
Fy[i-ii] += dy * drPowerN3; // scalar tuning
Fz[i-ii] += dz * drPowerN3; // scalar tuning
}
}
// Accelerate particles in response to the gravitational force
// Note: 1st order Euler Approximation.
// http://spiff.rit.edu/classes/phys317/lectures/euler.html
particle.vx[ii:TILE] += dt*Fx[0:TILE];
particle.vy[ii:TILE] += dt*Fy[0:TILE];
particle.vz[ii:TILE] += dt*Fz[0:TILE];
}
//#pragma omp parallel for schedule(guided)
// Move particles according to their velocities
// O(N) work, so using a serial loop
#pragma simd
#pragma vector aligned
// Move particles according to their velocities
for (int i = 0 ; i < nParticles; i++) {
particle.x[i] += particle.vx[i]*dt;
particle.y[i] += particle.vy[i]*dt;
particle.z[i] += particle.vz[i]*dt;
}
// Propagate results across the cluster
MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, particle.x, myParticles, MPI_FLOAT, MPI_COMM_WORLD);
MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, particle.y, myParticles, MPI_FLOAT, MPI_COMM_WORLD);
MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, particle.z, myParticles, MPI_FLOAT, MPI_COMM_WORLD);
}
// Do it!
int main(const int argc, const char *argv[]) {
// Initialize MPI and query my place in it
MPI_Init((int*)&argc, (char***)&argv);
int mpiWorldSize, mpiRank;
MPI_Comm_size(MPI_COMM_WORLD, &mpiWorldSize);
MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank);
// Problem size and other parameters
const int nParticles = (argc > 1 ? atoi(argv[1]) : 16384);
//const int nNodes = (argc > 1 ? atoi(argv[2]) : 1); // number of nodes we are distributing across
assert(nParticles%mpiWorldSize == 0);
// distribute particles to many buckets run by different machines
const int myParticles = nParticles/mpiWorldSize;
const int nSteps = 10; // Duration of test
const float dt = 0.01f; // Particle propagation time step
// Particle data stored as an Array of Structures (AoS)
// this is good object-oriented programming style,
// but inefficient for the purposes of vectorization
//ParticleType *particle = new ParticleType[nParticles];
// Structure of Array (SoA) style
// bad OOP style. But very efficient in terms of performance.
ParticleSetType particle;
// use Intel _mm_malloc to create objects that are stored on aligned memory.
// For KNL, needs to align to start at multiple of 64 bytes.
// use _mm_free to deallocate
particle.x = (float*) _mm_malloc(sizeof(float)*nParticles, 64);
particle.y = (float*) _mm_malloc(sizeof(float)*nParticles, 64);;
particle.z = (float*) _mm_malloc(sizeof(float)*nParticles, 64);;
particle.vx = (float*) _mm_malloc(sizeof(float)*nParticles, 64);;
particle.vy = (float*) _mm_malloc(sizeof(float)*nParticles, 64);;
particle.vz = (float*) _mm_malloc(sizeof(float)*nParticles, 64);;
// Initialize random number generator and particles
srand(0);
for(int i = 0; i < nParticles; i++) {
particle.x[i] = rand()/RAND_MAX;
particle.y[i] = rand()/RAND_MAX;
particle.z[i] = rand()/RAND_MAX;
particle.vx[i] = rand()/RAND_MAX;
particle.vy[i] = rand()/RAND_MAX;
particle.vz[i] = rand()/RAND_MAX;
}
// Make sure that all MPI processes have the same initial conditions
MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, particle.x, myParticles, MPI_FLOAT, MPI_COMM_WORLD);
MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, particle.y, myParticles, MPI_FLOAT, MPI_COMM_WORLD);
MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, particle.z, myParticles, MPI_FLOAT, MPI_COMM_WORLD);
MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, particle.vx, myParticles, MPI_FLOAT, MPI_COMM_WORLD);
MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, particle.vy, myParticles, MPI_FLOAT, MPI_COMM_WORLD);
MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, particle.vz, myParticles, MPI_FLOAT, MPI_COMM_WORLD);
// Perform benchmark
// only rank 0 prints to log
if (mpiRank == 0) {
const int version = 11; // implementation version - update as needed
printf("\n\033[1mNBODY Version %d\033[0m\n", version);
const int num_threads = omp_get_max_threads();
printf("\nPropagating %d particles using %d threads, distributed across %d nodes on %s...\n\n",
nParticles, num_threads, mpiWorldSize,
#ifndef __MIC__
"CPU"
#else
"MIC"
#endif
);
}
// rate and duration are for computing overall average performance and duration
// dRate and dDuration are for computing the short-cut standard diviation later.
double rate = 0, dRate = 0, duration = 0, dDuration = 0;
// Skip first few steps in the computation of average performance. Likely warm-up on Xeon Phi processor
const int skipSteps = 3;
// only rank 0 prints to log
if (mpiRank == 0) {
printf("\033[1m%5s %10s %10s %8s\033[0m\n", "Step", "Time, s", "Interact/s", "GFLOP/s");
fflush(stdout);
}
for (int step = 1; step <= nSteps; step++) {
const double tStart = omp_get_wtime(); // Start timing
MoveParticles(nParticles, particle, dt, mpiRank, mpiWorldSize, myParticles);
const double tEnd = omp_get_wtime(); // End timing
// Estimate total interactions and GFLOPS consumed
const float HztoInts = float(nParticles)*float(nParticles-1) ;
const float HztoGFLOPs = 20.0*1e-9*float(nParticles)*float(nParticles-1);
// For average performance and short-cut method standard deviation computation
if (step > skipSteps) { // Collect statistics
rate += HztoGFLOPs/(tEnd - tStart);
dRate += HztoGFLOPs*HztoGFLOPs/((tEnd - tStart)*(tEnd-tStart));
duration += (tEnd - tStart);
dDuration += (tEnd - tStart)*(tEnd - tStart);
}
// only rank 0 prints
if (mpiRank==0) {
printf("%5d %10.3e %10.3e %8.1f %s\n",
step, (tEnd-tStart), HztoInts/(tEnd-tStart), HztoGFLOPs/(tEnd-tStart), (step<=skipSteps?"*":""));
}
fflush(stdout);
}
// Compute the short-cut method standard deviaion.
rate/=(double)(nSteps-skipSteps);
dRate=sqrt(dRate/(double)(nSteps-skipSteps)-rate*rate);
duration/=(double)(nSteps-skipSteps);
dDuration=sqrt(dDuration/(double)(nSteps-skipSteps)-duration*duration);
// only rank 0 prints
if (mpiRank==0) {
printf("-----------------------------------------------------\n");
printf("\033[1m%s %4s \033[42m%10.1f +- %.1f GFLOP/s\033[0m\n",
"Average performance:", "", rate, dRate);
printf("\033[1m%s %4s \033[42m%10.3e +- %10.3e s\033[0m\n",
"Average duration:", "", duration, dDuration);
printf("\033[1m%s %4s \033[42m%.3f +- %.3f ms\033[0m\n",
"Average duration:", "", duration*1000.0, dDuration*1000.0);
printf("-----------------------------------------------------\n");
printf("* - warm-up, not included in average\n\n");
}
// free memory
_mm_free(particle.x);
_mm_free(particle.y);
_mm_free(particle.z);
_mm_free(particle.vx);
_mm_free(particle.vy);
_mm_free(particle.vz);
// MPI - done
MPI_Finalize();
}
<commit_msg>Update nbody.cc<commit_after>#include <cmath>
#include <cstdio>
#include <omp.h>
#include <mpi.h>
#include <cassert>
// (Sub-optimum) Array of Structure - good OOP. Bad Performance.
// Structure of individual particle
//struct ParticleType {
// float x, y, z;
// float vx, vy, vz;
//};
// (Optimum) Structure of Array - bad OOP. Good performance.
struct ParticleSetType {
float *x, *y, *z;
float *vx, *vy, *vz;
};
// define a function that moves each particle due to interaction with other particles
void MoveParticles(const int nParticles, ParticleSetType & particle, const float dt,
const int mpiRank, const int mpiWorldSize, const int myParticles) {
const int TILE = 16; // optimized for KNL
// redefine the start and end particle bucket for the ii loop tiling loop
const int startParticle = (mpiRank )*myParticles;
const int endParticle = (mpiRank + 1)*myParticles;
assert(myParticles % TILE == 0);
#pragma omp parallel for
// Loop over particles that experience force
for (int ii = startParticle; ii < endParticle; ii+=TILE) {
// Components of the gravity force on particle i
float Fx[TILE], Fy[TILE], Fz[TILE];
Fx[:] = Fy[:] = Fz[:] = 0.0f;
// Avoid singularity and interaction with self
const float softening = 1e-20;
// Loop over particles that exert force: vectorization expected here
#pragma unroll(TILE)
for (int j = 0; j < nParticles; j++) {
#pragma vector aligned
// How much data in this tiled loop?
// 16 (particles in a tile) * 3 floats * 4 bytes per floats = 192 bytes
// enough to fit in the L1 Cache registery
for (int i = ii; i < ii+TILE; i++) {
// Newton's law of universal gravity
const float dx = particle.x[j] - particle.x[i];
const float dy = particle.y[j] - particle.y[i];
const float dz = particle.z[j] - particle.z[i];
const float drSquared = dx*dx + dy*dy + dz*dz + softening;
const float oodr = 1.0f/sqrtf(drSquared);
const float drPowerN3 = oodr*oodr*oodr;
// Calculate the net force
// Assume mass is 1 (for ease of computation)
// F = ma = 1*a = a
Fx[i-ii] += dx * drPowerN3; // scalar tuning
Fy[i-ii] += dy * drPowerN3; // scalar tuning
Fz[i-ii] += dz * drPowerN3; // scalar tuning
}
}
// Accelerate particles in response to the gravitational force
// Note: 1st order Euler Approximation.
// http://spiff.rit.edu/classes/phys317/lectures/euler.html
particle.vx[ii:TILE] += dt*Fx[0:TILE];
particle.vy[ii:TILE] += dt*Fy[0:TILE];
particle.vz[ii:TILE] += dt*Fz[0:TILE];
}
#pragma omp parallel for
#pragma vector aligned
// Move particles according to their velocities
for (int i = 0 ; i < nParticles; i++) {
particle.x[i] += particle.vx[i]*dt;
particle.y[i] += particle.vy[i]*dt;
particle.z[i] += particle.vz[i]*dt;
}
// Propagate results across the cluster
MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, particle.x, myParticles, MPI_FLOAT, MPI_COMM_WORLD);
MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, particle.y, myParticles, MPI_FLOAT, MPI_COMM_WORLD);
MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, particle.z, myParticles, MPI_FLOAT, MPI_COMM_WORLD);
}
// Do it!
int main(const int argc, const char *argv[]) {
// Initialize MPI and query my place in it
MPI_Init((int*)&argc, (char***)&argv);
int mpiWorldSize, mpiRank;
MPI_Comm_size(MPI_COMM_WORLD, &mpiWorldSize);
MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank);
// Problem size and other parameters
const int nParticles = (argc > 1 ? atoi(argv[1]) : 16384);
//const int nNodes = (argc > 1 ? atoi(argv[2]) : 1); // number of nodes we are distributing across
assert(nParticles%mpiWorldSize == 0);
// distribute particles to many buckets run by different machines
const int myParticles = nParticles/mpiWorldSize;
const int nSteps = 10; // Duration of test
const float dt = 0.01f; // Particle propagation time step
// Particle data stored as an Array of Structures (AoS)
// this is good object-oriented programming style,
// but inefficient for the purposes of vectorization
//ParticleType *particle = new ParticleType[nParticles];
// Structure of Array (SoA) style
// bad OOP style. But very efficient in terms of performance.
ParticleSetType particle;
// use Intel _mm_malloc to create objects that are stored on aligned memory.
// For KNL, needs to align to start at multiple of 64 bytes.
// use _mm_free to deallocate
particle.x = (float*) _mm_malloc(sizeof(float)*nParticles, 64);
particle.y = (float*) _mm_malloc(sizeof(float)*nParticles, 64);;
particle.z = (float*) _mm_malloc(sizeof(float)*nParticles, 64);;
particle.vx = (float*) _mm_malloc(sizeof(float)*nParticles, 64);;
particle.vy = (float*) _mm_malloc(sizeof(float)*nParticles, 64);;
particle.vz = (float*) _mm_malloc(sizeof(float)*nParticles, 64);;
// Initialize random number generator and particles
srand(0);
for(int i = 0; i < nParticles; i++) {
particle.x[i] = rand()/RAND_MAX;
particle.y[i] = rand()/RAND_MAX;
particle.z[i] = rand()/RAND_MAX;
particle.vx[i] = rand()/RAND_MAX;
particle.vy[i] = rand()/RAND_MAX;
particle.vz[i] = rand()/RAND_MAX;
}
// Make sure that all MPI processes have the same initial conditions
MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, particle.x, myParticles, MPI_FLOAT, MPI_COMM_WORLD);
MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, particle.y, myParticles, MPI_FLOAT, MPI_COMM_WORLD);
MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, particle.z, myParticles, MPI_FLOAT, MPI_COMM_WORLD);
MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, particle.vx, myParticles, MPI_FLOAT, MPI_COMM_WORLD);
MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, particle.vy, myParticles, MPI_FLOAT, MPI_COMM_WORLD);
MPI_Allgather(MPI_IN_PLACE, 0, MPI_DATATYPE_NULL, particle.vz, myParticles, MPI_FLOAT, MPI_COMM_WORLD);
// Perform benchmark
// only rank 0 prints to log
if (mpiRank == 0) {
const int version = 11; // implementation version - update as needed
printf("\n\033[1mNBODY Version %d\033[0m\n", version);
const int num_threads = omp_get_max_threads();
printf("\nPropagating %d particles using %d threads, distributed across %d nodes on %s...\n\n",
nParticles, num_threads, mpiWorldSize,
#ifndef __MIC__
"CPU"
#else
"MIC"
#endif
);
}
// rate and duration are for computing overall average performance and duration
// dRate and dDuration are for computing the short-cut standard diviation later.
double rate = 0, dRate = 0, duration = 0, dDuration = 0;
// Skip first few steps in the computation of average performance. Likely warm-up on Xeon Phi processor
const int skipSteps = 3;
// only rank 0 prints to log
if (mpiRank == 0) {
printf("\033[1m%5s %10s %10s %8s\033[0m\n", "Step", "Time, s", "Interact/s", "GFLOP/s");
fflush(stdout);
}
for (int step = 1; step <= nSteps; step++) {
const double tStart = omp_get_wtime(); // Start timing
MoveParticles(nParticles, particle, dt, mpiRank, mpiWorldSize, myParticles);
const double tEnd = omp_get_wtime(); // End timing
// Estimate total interactions and GFLOPS consumed
const float HztoInts = float(nParticles)*float(nParticles-1) ;
const float HztoGFLOPs = 20.0*1e-9*float(nParticles)*float(nParticles-1);
// For average performance and short-cut method standard deviation computation
if (step > skipSteps) { // Collect statistics
rate += HztoGFLOPs/(tEnd - tStart);
dRate += HztoGFLOPs*HztoGFLOPs/((tEnd - tStart)*(tEnd-tStart));
duration += (tEnd - tStart);
dDuration += (tEnd - tStart)*(tEnd - tStart);
}
// only rank 0 prints
if (mpiRank==0) {
printf("%5d %10.3e %10.3e %8.1f %s\n",
step, (tEnd-tStart), HztoInts/(tEnd-tStart), HztoGFLOPs/(tEnd-tStart), (step<=skipSteps?"*":""));
}
fflush(stdout);
}
// Compute the short-cut method standard deviaion.
rate/=(double)(nSteps-skipSteps);
dRate=sqrt(dRate/(double)(nSteps-skipSteps)-rate*rate);
duration/=(double)(nSteps-skipSteps);
dDuration=sqrt(dDuration/(double)(nSteps-skipSteps)-duration*duration);
// only rank 0 prints
if (mpiRank==0) {
printf("-----------------------------------------------------\n");
printf("\033[1m%s %4s \033[42m%10.1f +- %.1f GFLOP/s\033[0m\n",
"Average performance:", "", rate, dRate);
printf("\033[1m%s %4s \033[42m%10.3e +- %10.3e s\033[0m\n",
"Average duration:", "", duration, dDuration);
printf("\033[1m%s %4s \033[42m%.3f +- %.3f ms\033[0m\n",
"Average duration:", "", duration*1000.0, dDuration*1000.0);
printf("-----------------------------------------------------\n");
printf("* - warm-up, not included in average\n\n");
}
// free memory
_mm_free(particle.x);
_mm_free(particle.y);
_mm_free(particle.z);
_mm_free(particle.vx);
_mm_free(particle.vy);
_mm_free(particle.vz);
// MPI - done
MPI_Finalize();
}
<|endoftext|> |
<commit_before>/* Copyright 2010 Jukka Jylnki
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
/** @file Clock.cpp
@brief */
#if defined(__unix__) || defined(__native_client__) || defined(EMSCRIPTEN) || defined(ANDROID) || defined(__APPLE__) || defined (__CYGWIN__)
#include <time.h>
#include <errno.h>
#include <string.h>
#include <sys/time.h>
#endif
#ifdef WIN32
#define NOMINMAX
#include <windows.h>
#endif
#ifdef EMSCRIPTEN
#include <emscripten.h>
#endif
#include "kNet/Clock.h"
#include "kNet/NetworkLogging.h"
namespace kNet
{
#ifdef WIN32
LARGE_INTEGER Clock::ddwTimerFrequency;
#endif
tick_t Clock::appStartTime = 0;
Clock impl;
void Clock::InitClockData()
{
if (appStartTime == 0)
appStartTime = Tick();
#ifdef WIN32
if (!QueryPerformanceFrequency(&ddwTimerFrequency))
{
LOG(LogError, "The system doesn't support high-resolution timers!");
ddwTimerFrequency.HighPart = (unsigned long)-1;
ddwTimerFrequency.LowPart = (unsigned long)-1;
}
if (ddwTimerFrequency.HighPart > 0)
LOG(LogError, "Warning: Clock::TicksPerSec will yield invalid timing data!");
if (appStartTime == 0)
{
#if WINVER >= 0x0600
appStartTime = (tick_t)GetTickCount64();
#else
appStartTime = (tick_t)GetTickCount();
#endif
}
///\todo Test here that the return values of QueryPerformanceCounter is nondecreasing.
#endif
}
Clock::Clock()
{
InitClockData();
}
void Clock::Sleep(int milliseconds)
{
#ifdef WIN8RT
#pragma WARNING(Clock::Sleep has not been implemented!)
#elif defined(WIN32)
::Sleep(milliseconds);
#elif !defined(__native_client__) && !defined(EMSCRIPTEN) && !defined(__APPLE__)
// http://linux.die.net/man/2/nanosleep
timespec ts;
ts.tv_sec = milliseconds / 1000;
ts.tv_nsec = (milliseconds - ts.tv_sec * 1000) * 1000 * 1000;
int ret = nanosleep(&ts, NULL);
if (ret == -1)
LOG(LogError, "nanosleep returned -1! Reason: %s(%d).", strerror(errno), (int)errno);
#else
#warning Clock::Sleep has not been implemented!
#endif
}
int Clock::Year()
{
#ifdef WIN32
SYSTEMTIME s;
GetSystemTime(&s);
return s.wYear;
#else
///\todo.
return 0;
#endif
}
int Clock::Month()
{
#ifdef WIN32
SYSTEMTIME s;
GetSystemTime(&s);
return s.wMonth;
#else
///\todo.
return 0;
#endif
}
int Clock::Day()
{
#ifdef WIN32
SYSTEMTIME s;
GetSystemTime(&s);
return s.wDay;
#else
///\todo.
return 0;
#endif
}
int Clock::Hour()
{
#ifdef WIN32
SYSTEMTIME s;
GetSystemTime(&s);
return s.wHour;
#else
///\todo.
return 0;
#endif
}
int Clock::Min()
{
#ifdef WIN32
SYSTEMTIME s;
GetSystemTime(&s);
return s.wMinute;
#else
///\todo.
return 0;
#endif
}
int Clock::Sec()
{
#ifdef WIN32
SYSTEMTIME s;
GetSystemTime(&s);
return s.wSecond;
#else
///\todo.
return 0;
#endif
}
unsigned long Clock::SystemTime()
{
#ifdef WIN32
#if WINVER >= 0x0600
return (unsigned long)GetTickCount64();
#else
return (unsigned long)GetTickCount();
#endif
#else
return TickU32();
#endif
}
/*
tick_t Clock::ApplicationStartupTick()
{
return appStartTime;
}
*/
unsigned long Clock::Time()
{
return (unsigned long)(Tick() - appStartTime);
}
tick_t Clock::Tick()
{
#if defined(ANDROID)
struct timespec res;
clock_gettime(CLOCK_REALTIME, &res);
return 1000000000ULL*res.tv_sec + (tick_t)res.tv_nsec;
#elif defined(EMSCRIPTEN)
// emscripten_get_now() returns a wallclock time as a float in milliseconds (1e-3).
// scale it to microseconds (1e-6) and return as a tick.
return (tick_t)(((double)emscripten_get_now()) * 1e3);
// return (tick_t)clock();
#elif defined(WIN32)
LARGE_INTEGER ddwTimer;
QueryPerformanceCounter(&ddwTimer);
return ddwTimer.QuadPart;
#elif defined(_POSIX_MONOTONIC_CLOCK)
timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return (tick_t)t.tv_sec * 1000 * 1000 * 1000 + (tick_t)t.tv_nsec;
#elif defined(_POSIX_C_SOURCE) || defined(__APPLE__)
timeval t;
gettimeofday(&t, NULL);
return (tick_t)t.tv_sec * 1000 * 1000 + (tick_t)t.tv_usec;
#else
return (tick_t)clock();
#endif
}
unsigned long Clock::TickU32()
{
#ifdef WIN32
LARGE_INTEGER ddwTimer;
QueryPerformanceCounter(&ddwTimer);
return ddwTimer.LowPart;
#else
return (unsigned long)Tick();
#endif
}
tick_t Clock::TicksPerSec()
{
#if defined(ANDROID)
return 1000000000ULL; // 1e9 == nanoseconds.
#elif defined(EMSCRIPTEN)
return 1000000ULL; // 1e6 == microseconds.
// return CLOCKS_PER_SEC;
#elif defined(WIN32)
return ddwTimerFrequency.QuadPart;
#elif defined(_POSIX_MONOTONIC_CLOCK)
return 1000 * 1000 * 1000;
#elif defined(_POSIX_C_SOURCE) || defined(__APPLE__)
return 1000 * 1000;
#else
return CLOCKS_PER_SEC;
#endif
}
} // ~kNet
<commit_msg>Avoid using GetTickCount64 if building for XP support.<commit_after>/* Copyright 2010 Jukka Jylnki
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
/** @file Clock.cpp
@brief */
#if defined(__unix__) || defined(__native_client__) || defined(EMSCRIPTEN) || defined(ANDROID) || defined(__APPLE__) || defined (__CYGWIN__)
#include <time.h>
#include <errno.h>
#include <string.h>
#include <sys/time.h>
#endif
#ifdef WIN32
#define NOMINMAX
#include <windows.h>
#endif
#ifdef EMSCRIPTEN
#include <emscripten.h>
#endif
#include "kNet/Clock.h"
#include "kNet/NetworkLogging.h"
namespace kNet
{
#ifdef WIN32
LARGE_INTEGER Clock::ddwTimerFrequency;
#endif
tick_t Clock::appStartTime = 0;
Clock impl;
void Clock::InitClockData()
{
if (appStartTime == 0)
appStartTime = Tick();
#ifdef WIN32
if (!QueryPerformanceFrequency(&ddwTimerFrequency))
{
LOG(LogError, "The system doesn't support high-resolution timers!");
ddwTimerFrequency.HighPart = (unsigned long)-1;
ddwTimerFrequency.LowPart = (unsigned long)-1;
}
if (ddwTimerFrequency.HighPart > 0)
LOG(LogError, "Warning: Clock::TicksPerSec will yield invalid timing data!");
if (appStartTime == 0)
{
#if WINVER >= 0x0600 && !defined(KNET_ENABLE_WINXP_SUPPORT)
appStartTime = (tick_t)GetTickCount64();
#else
appStartTime = (tick_t)GetTickCount();
#endif
}
///\todo Test here that the return values of QueryPerformanceCounter is nondecreasing.
#endif
}
Clock::Clock()
{
InitClockData();
}
void Clock::Sleep(int milliseconds)
{
#ifdef WIN8RT
#pragma WARNING(Clock::Sleep has not been implemented!)
#elif defined(WIN32)
::Sleep(milliseconds);
#elif !defined(__native_client__) && !defined(EMSCRIPTEN) && !defined(__APPLE__)
// http://linux.die.net/man/2/nanosleep
timespec ts;
ts.tv_sec = milliseconds / 1000;
ts.tv_nsec = (milliseconds - ts.tv_sec * 1000) * 1000 * 1000;
int ret = nanosleep(&ts, NULL);
if (ret == -1)
LOG(LogError, "nanosleep returned -1! Reason: %s(%d).", strerror(errno), (int)errno);
#else
#warning Clock::Sleep has not been implemented!
#endif
}
int Clock::Year()
{
#ifdef WIN32
SYSTEMTIME s;
GetSystemTime(&s);
return s.wYear;
#else
///\todo.
return 0;
#endif
}
int Clock::Month()
{
#ifdef WIN32
SYSTEMTIME s;
GetSystemTime(&s);
return s.wMonth;
#else
///\todo.
return 0;
#endif
}
int Clock::Day()
{
#ifdef WIN32
SYSTEMTIME s;
GetSystemTime(&s);
return s.wDay;
#else
///\todo.
return 0;
#endif
}
int Clock::Hour()
{
#ifdef WIN32
SYSTEMTIME s;
GetSystemTime(&s);
return s.wHour;
#else
///\todo.
return 0;
#endif
}
int Clock::Min()
{
#ifdef WIN32
SYSTEMTIME s;
GetSystemTime(&s);
return s.wMinute;
#else
///\todo.
return 0;
#endif
}
int Clock::Sec()
{
#ifdef WIN32
SYSTEMTIME s;
GetSystemTime(&s);
return s.wSecond;
#else
///\todo.
return 0;
#endif
}
unsigned long Clock::SystemTime()
{
#ifdef WIN32
#if WINVER >= 0x0600 && !defined(KNET_ENABLE_WINXP_SUPPORT)
return (unsigned long)GetTickCount64();
#else
return (unsigned long)GetTickCount();
#endif
#else
return TickU32();
#endif
}
/*
tick_t Clock::ApplicationStartupTick()
{
return appStartTime;
}
*/
unsigned long Clock::Time()
{
return (unsigned long)(Tick() - appStartTime);
}
tick_t Clock::Tick()
{
#if defined(ANDROID)
struct timespec res;
clock_gettime(CLOCK_REALTIME, &res);
return 1000000000ULL*res.tv_sec + (tick_t)res.tv_nsec;
#elif defined(EMSCRIPTEN)
// emscripten_get_now() returns a wallclock time as a float in milliseconds (1e-3).
// scale it to microseconds (1e-6) and return as a tick.
return (tick_t)(((double)emscripten_get_now()) * 1e3);
// return (tick_t)clock();
#elif defined(WIN32)
LARGE_INTEGER ddwTimer;
QueryPerformanceCounter(&ddwTimer);
return ddwTimer.QuadPart;
#elif defined(_POSIX_MONOTONIC_CLOCK)
timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return (tick_t)t.tv_sec * 1000 * 1000 * 1000 + (tick_t)t.tv_nsec;
#elif defined(_POSIX_C_SOURCE) || defined(__APPLE__)
timeval t;
gettimeofday(&t, NULL);
return (tick_t)t.tv_sec * 1000 * 1000 + (tick_t)t.tv_usec;
#else
return (tick_t)clock();
#endif
}
unsigned long Clock::TickU32()
{
#ifdef WIN32
LARGE_INTEGER ddwTimer;
QueryPerformanceCounter(&ddwTimer);
return ddwTimer.LowPart;
#else
return (unsigned long)Tick();
#endif
}
tick_t Clock::TicksPerSec()
{
#if defined(ANDROID)
return 1000000000ULL; // 1e9 == nanoseconds.
#elif defined(EMSCRIPTEN)
return 1000000ULL; // 1e6 == microseconds.
// return CLOCKS_PER_SEC;
#elif defined(WIN32)
return ddwTimerFrequency.QuadPart;
#elif defined(_POSIX_MONOTONIC_CLOCK)
return 1000 * 1000 * 1000;
#elif defined(_POSIX_C_SOURCE) || defined(__APPLE__)
return 1000 * 1000;
#else
return CLOCKS_PER_SEC;
#endif
}
} // ~kNet
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
#include "opencv2/photo.hpp"
#include "seamless_cloning.hpp"
using namespace std;
using namespace cv;
static Mat checkMask(InputArray _mask, Size size)
{
Mat mask = _mask.getMat();
Mat gray;
if (mask.channels() == 3)
cvtColor(mask, gray, COLOR_BGR2GRAY);
else
{
if (mask.empty())
gray = Mat(size.height, size.width, CV_8UC1, Scalar(255));
else
mask.copyTo(gray);
}
return gray;
}
void cv::seamlessClone(InputArray _src, InputArray _dst, InputArray _mask, Point p, OutputArray _blend, int flags)
{
CV_INSTRUMENT_REGION();
const Mat src = _src.getMat();
const Mat dest = _dst.getMat();
Mat mask = checkMask(_mask, src.size());
dest.copyTo(_blend);
Mat blend = _blend.getMat();
Mat mask_inner = mask(Rect(1, 1, mask.cols - 2, mask.rows - 2));
copyMakeBorder(mask_inner, mask, 1, 1, 1, 1, BORDER_ISOLATED | BORDER_CONSTANT, Scalar(0));
Rect roi_s = boundingRect(mask);
if (roi_s.empty()) return;
Rect roi_d(p.x - roi_s.width / 2, p.y - roi_s.height / 2, roi_s.width, roi_s.height);
Mat destinationROI = dest(roi_d).clone();
Mat sourceROI = Mat::zeros(roi_s.height, roi_s.width, src.type());
src(roi_s).copyTo(sourceROI,mask(roi_s));
Mat maskROI = mask(roi_s);
Mat recoveredROI = blend(roi_d);
Cloning obj;
obj.normalClone(destinationROI,sourceROI,maskROI,recoveredROI,flags);
}
void cv::colorChange(InputArray _src, InputArray _mask, OutputArray _dst, float red, float green, float blue)
{
CV_INSTRUMENT_REGION();
Mat src = _src.getMat();
Mat mask = checkMask(_mask, src.size());
_dst.create(src.size(), src.type());
Mat blend = _dst.getMat();
Mat cs_mask = Mat::zeros(src.size(), src.type());
src.copyTo(cs_mask, mask);
Cloning obj;
obj.localColorChange(src, cs_mask, mask, blend, red, green, blue);
}
void cv::illuminationChange(InputArray _src, InputArray _mask, OutputArray _dst, float alpha, float beta)
{
CV_INSTRUMENT_REGION();
Mat src = _src.getMat();
Mat mask = checkMask(_mask, src.size());
_dst.create(src.size(), src.type());
Mat blend = _dst.getMat();
Mat cs_mask = Mat::zeros(src.size(), src.type());
src.copyTo(cs_mask, mask);
Cloning obj;
obj.illuminationChange(src, cs_mask, mask, blend, alpha, beta);
}
void cv::textureFlattening(InputArray _src, InputArray _mask, OutputArray _dst,
float low_threshold, float high_threshold, int kernel_size)
{
CV_INSTRUMENT_REGION();
Mat src = _src.getMat();
Mat mask = checkMask(_mask, src.size());
_dst.create(src.size(), src.type());
Mat blend = _dst.getMat();
Mat cs_mask = Mat::zeros(src.size(), src.type());
src.copyTo(cs_mask, mask);
Cloning obj;
obj.textureFlatten(src, cs_mask, mask, low_threshold, high_threshold, kernel_size, blend);
}
<commit_msg>Update seamless_cloning.cpp<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
#include "opencv2/photo.hpp"
#include "seamless_cloning.hpp"
using namespace std;
using namespace cv;
static Mat checkMask(InputArray _mask, Size size)
{
Mat mask = _mask.getMat();
Mat gray;
if (mask.channels() > 1)
cvtColor(mask, gray, COLOR_BGRA2GRAY);
else
{
if (mask.empty())
gray = Mat(size.height, size.width, CV_8UC1, Scalar(255));
else
mask.copyTo(gray);
}
return gray;
}
void cv::seamlessClone(InputArray _src, InputArray _dst, InputArray _mask, Point p, OutputArray _blend, int flags)
{
CV_INSTRUMENT_REGION();
const Mat src = _src.getMat();
const Mat dest = _dst.getMat();
Mat mask = checkMask(_mask, src.size());
dest.copyTo(_blend);
Mat blend = _blend.getMat();
Mat mask_inner = mask(Rect(1, 1, mask.cols - 2, mask.rows - 2));
copyMakeBorder(mask_inner, mask, 1, 1, 1, 1, BORDER_ISOLATED | BORDER_CONSTANT, Scalar(0));
Rect roi_s = boundingRect(mask);
if (roi_s.empty()) return;
Rect roi_d(p.x - roi_s.width / 2, p.y - roi_s.height / 2, roi_s.width, roi_s.height);
Mat destinationROI = dest(roi_d).clone();
Mat sourceROI = Mat::zeros(roi_s.height, roi_s.width, src.type());
src(roi_s).copyTo(sourceROI,mask(roi_s));
Mat maskROI = mask(roi_s);
Mat recoveredROI = blend(roi_d);
Cloning obj;
obj.normalClone(destinationROI,sourceROI,maskROI,recoveredROI,flags);
}
void cv::colorChange(InputArray _src, InputArray _mask, OutputArray _dst, float red, float green, float blue)
{
CV_INSTRUMENT_REGION();
Mat src = _src.getMat();
Mat mask = checkMask(_mask, src.size());
_dst.create(src.size(), src.type());
Mat blend = _dst.getMat();
Mat cs_mask = Mat::zeros(src.size(), src.type());
src.copyTo(cs_mask, mask);
Cloning obj;
obj.localColorChange(src, cs_mask, mask, blend, red, green, blue);
}
void cv::illuminationChange(InputArray _src, InputArray _mask, OutputArray _dst, float alpha, float beta)
{
CV_INSTRUMENT_REGION();
Mat src = _src.getMat();
Mat mask = checkMask(_mask, src.size());
_dst.create(src.size(), src.type());
Mat blend = _dst.getMat();
Mat cs_mask = Mat::zeros(src.size(), src.type());
src.copyTo(cs_mask, mask);
Cloning obj;
obj.illuminationChange(src, cs_mask, mask, blend, alpha, beta);
}
void cv::textureFlattening(InputArray _src, InputArray _mask, OutputArray _dst,
float low_threshold, float high_threshold, int kernel_size)
{
CV_INSTRUMENT_REGION();
Mat src = _src.getMat();
Mat mask = checkMask(_mask, src.size());
_dst.create(src.size(), src.type());
Mat blend = _dst.getMat();
Mat cs_mask = Mat::zeros(src.size(), src.type());
src.copyTo(cs_mask, mask);
Cloning obj;
obj.textureFlatten(src, cs_mask, mask, low_threshold, high_threshold, kernel_size, blend);
}
<|endoftext|> |
<commit_before>/**
* @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file JPetManager.cpp
*/
#include "./JPetManager.h"
#include <cassert>
#include <string>
#include <exception>
#include "../JPetLoggerInclude.h"
#include "../JPetCommonTools/JPetCommonTools.h"
#include "../DBHandler/HeaderFiles/DBHandler.h"
#include "../JPetCmdParser/JPetCmdParser.h"
#include "../JPetScopeLoader/JPetScopeLoader.h"
#include "../JPetUnzipAndUnpackTask/JPetUnzipAndUnpackTask.h"
#include "../JPetOptionsGenerator/JPetOptionsGenerator.h"
#include <TThread.h>
using namespace jpet_options_tools;
JPetManager::JPetManager()
{
fTaskGeneratorChain = new TaskGeneratorChain;
}
JPetManager& JPetManager::getManager()
{
static JPetManager instance;
return instance;
}
bool JPetManager::areThreadsEnabled() const
{
return fThreadsEnabled;
}
void JPetManager::setThreadsEnabled(bool enable)
{
fThreadsEnabled = enable;
}
bool JPetManager::run(int argc, const char** argv)
{
if (!parseCmdLine(argc, argv)) {
ERROR("While parsing command line arguments");
return false;
}
INFO( "======== Starting processing all tasks: " + JPetCommonTools::getTimeString() + " ========\n" );
std::vector<JPetTaskChainExecutor*> executors;
std::vector<TThread*> threads;
auto inputDataSeq = 0;
/// For every input option, new TaskChainExecutor is created, which creates the chain of previously
/// registered tasks. The inputDataSeq is the identifier of given chain.
for (auto opt : fOptions) {
JPetTaskChainExecutor* executor = new JPetTaskChainExecutor(fTaskGeneratorChain, inputDataSeq, opt.second);
executors.push_back(executor);
if (areThreadsEnabled()) {
auto thr = executor->run();
if (thr) {
threads.push_back(thr);
} else {
ERROR("thread pointer is null");
}
} else {
if (!executor->process()) {
ERROR("While running process");
return false;
}
}
inputDataSeq++;
}
if (areThreadsEnabled()) {
for (auto thread : threads) {
assert(thread);
thread->Join();
}
}
for (auto& executor : executors) {
if (executor) {
delete executor;
executor = 0;
}
}
INFO( "======== Finished processing all tasks: " + JPetCommonTools::getTimeString() + " ========\n" );
return true;
}
bool JPetManager::parseCmdLine(int argc, const char** argv)
{
//auto addDefaultTasksFromOptions = [&](const boost::program_options::variables_map & optionsFromCmdLine) {
//auto it = optionsFromCmdLine.find("type");
//if (it != optionsFromCmdLine.end()) {
//if (boost::any_cast<std::string>(it->second.value()) == "scope") {
//auto task = []() {
//return new JPetScopeLoader(std::unique_ptr<JPetScopeTask>(new JPetScopeTask("JPetScopeReader")));
//};
//fTaskGeneratorChain->push_back(task);
//}
//}
//};
auto addDefaultTasksFromOptions = [&](const std::map<std::string, boost::any>& options) {
/// add task to unzip or unpack if needed
auto task = []() {
return new JPetUnzipAndUnpackTask("UnpackerAndUnzipper");
};
fTaskGeneratorChain->push_back(task);
auto fileType = FileTypeChecker::getInputFileType(options);
if (fileType == FileTypeChecker::kScope) {
auto task2 = []() {
return new JPetScopeLoader(std::unique_ptr<JPetScopeTask>(new JPetScopeTask("JPetScopeReader")));
};
fTaskGeneratorChain->push_back(task2);
}
};
try {
JPetOptionsGenerator optionsGenerator;
JPetCmdParser parser;
auto optionsFromCmdLine = parser.parseCmdLineArgs(argc, argv);
/// A map of all options
auto allValidatedOptions = optionsGenerator.generateAndValidateOptions(optionsFromCmdLine);
addDefaultTasksFromOptions(allValidatedOptions);
//addDefaultTasksFromOptions(optionsFromCmdLine); /// Currently only scope task can be added.
int numberOfRegisteredTasks = 1;
if (fTaskGeneratorChain) {
numberOfRegisteredTasks = fTaskGeneratorChain->size();
}
fOptions = optionsGenerator.generateOptionsForTasks(allValidatedOptions, numberOfRegisteredTasks);
} catch (std::exception& e) {
ERROR(e.what());
return false;
}
return true;
}
//
JPetManager::~JPetManager()
{
/// delete shared caches for paramBanks
/// @todo I think that should be changed
JPetDBParamGetter::clearParamCache();
}
void JPetManager::registerTask(const TaskGenerator& taskGen)
{
assert(fTaskGeneratorChain);
fTaskGeneratorChain->push_back(taskGen);
}
JPetManager::Options JPetManager::getOptions() const
{
return fOptions;
}
/**
* @brief Initialize connection to database if such connection is necessary
*
* @param configFilePath path to the config file with database connection details
*
* @return true if database connection was required and initialization was called,
* false if database connection was not required and its initialization was skipped
*
* Database connection is only initialized if the user provided the run number
* ("-i" option) and did not provide local database ("-l") at the same time.
*/
bool JPetManager::initDBConnection(const char* configFilePath)
{
bool isDBrequired = false;
if (fOptions.size() > 0) { // If at least one input file to process.
auto optsVect = fOptions.begin()->second;
if (optsVect.size() > 0) {
auto opt = optsVect.front();
if (getRunNumber(opt) >= 0) { // if run number is not default -1
if (!isLocalDB(opt)) { // unless local DB file was provided
isDBrequired = true;
}
}
}
}
if (isDBrequired) {
INFO("Attempting to set up connection to the database.");
DB::SERVICES::DBHandler::createDBConnection(configFilePath);
} else {
INFO("Setting connection to database skipped.");
}
return isDBrequired;
}
<commit_msg>Add unpacking task to the beginning of task chain<commit_after>/**
* @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file JPetManager.cpp
*/
#include "./JPetManager.h"
#include <cassert>
#include <string>
#include <exception>
#include "../JPetLoggerInclude.h"
#include "../JPetCommonTools/JPetCommonTools.h"
#include "../DBHandler/HeaderFiles/DBHandler.h"
#include "../JPetCmdParser/JPetCmdParser.h"
#include "../JPetScopeLoader/JPetScopeLoader.h"
#include "../JPetUnzipAndUnpackTask/JPetUnzipAndUnpackTask.h"
#include "../JPetOptionsGenerator/JPetOptionsGenerator.h"
#include <TThread.h>
using namespace jpet_options_tools;
JPetManager::JPetManager()
{
fTaskGeneratorChain = new TaskGeneratorChain;
}
JPetManager& JPetManager::getManager()
{
static JPetManager instance;
return instance;
}
bool JPetManager::areThreadsEnabled() const
{
return fThreadsEnabled;
}
void JPetManager::setThreadsEnabled(bool enable)
{
fThreadsEnabled = enable;
}
bool JPetManager::run(int argc, const char** argv)
{
if (!parseCmdLine(argc, argv)) {
ERROR("While parsing command line arguments");
return false;
}
INFO( "======== Starting processing all tasks: " + JPetCommonTools::getTimeString() + " ========\n" );
std::vector<JPetTaskChainExecutor*> executors;
std::vector<TThread*> threads;
auto inputDataSeq = 0;
/// For every input option, new TaskChainExecutor is created, which creates the chain of previously
/// registered tasks. The inputDataSeq is the identifier of given chain.
for (auto opt : fOptions) {
JPetTaskChainExecutor* executor = new JPetTaskChainExecutor(fTaskGeneratorChain, inputDataSeq, opt.second);
executors.push_back(executor);
if (areThreadsEnabled()) {
auto thr = executor->run();
if (thr) {
threads.push_back(thr);
} else {
ERROR("thread pointer is null");
}
} else {
if (!executor->process()) {
ERROR("While running process");
return false;
}
}
inputDataSeq++;
}
if (areThreadsEnabled()) {
for (auto thread : threads) {
assert(thread);
thread->Join();
}
}
for (auto& executor : executors) {
if (executor) {
delete executor;
executor = 0;
}
}
INFO( "======== Finished processing all tasks: " + JPetCommonTools::getTimeString() + " ========\n" );
return true;
}
bool JPetManager::parseCmdLine(int argc, const char** argv)
{
auto addDefaultTasksFromOptions = [&](const std::map<std::string, boost::any>& options) {
auto fileType = FileTypeChecker::getInputFileType(options);
if (fileType == FileTypeChecker::kScope) {
auto task2 = []() {
return new JPetScopeLoader(std::unique_ptr<JPetScopeTask>(new JPetScopeTask("JPetScopeReader")));
};
fTaskGeneratorChain->insert(fTaskGeneratorChain->begin(), task2);
}
/// add task to unzip or unpack if needed
auto task = []() {
return new JPetUnzipAndUnpackTask("UnpackerAndUnzipper");
};
fTaskGeneratorChain->insert(fTaskGeneratorChain->begin(), task);
};
try {
JPetOptionsGenerator optionsGenerator;
JPetCmdParser parser;
auto optionsFromCmdLine = parser.parseCmdLineArgs(argc, argv);
/// A map of all options
auto allValidatedOptions = optionsGenerator.generateAndValidateOptions(optionsFromCmdLine);
addDefaultTasksFromOptions(allValidatedOptions);
//addDefaultTasksFromOptions(optionsFromCmdLine); /// Currently only scope task can be added.
int numberOfRegisteredTasks = 1;
if (fTaskGeneratorChain) {
numberOfRegisteredTasks = fTaskGeneratorChain->size();
}
fOptions = optionsGenerator.generateOptionsForTasks(allValidatedOptions, numberOfRegisteredTasks);
} catch (std::exception& e) {
ERROR(e.what());
return false;
}
return true;
}
//
JPetManager::~JPetManager()
{
/// delete shared caches for paramBanks
/// @todo I think that should be changed
JPetDBParamGetter::clearParamCache();
}
void JPetManager::registerTask(const TaskGenerator& taskGen)
{
assert(fTaskGeneratorChain);
fTaskGeneratorChain->push_back(taskGen);
}
JPetManager::Options JPetManager::getOptions() const
{
return fOptions;
}
/**
* @brief Initialize connection to database if such connection is necessary
*
* @param configFilePath path to the config file with database connection details
*
* @return true if database connection was required and initialization was called,
* false if database connection was not required and its initialization was skipped
*
* Database connection is only initialized if the user provided the run number
* ("-i" option) and did not provide local database ("-l") at the same time.
*/
bool JPetManager::initDBConnection(const char* configFilePath)
{
bool isDBrequired = false;
if (fOptions.size() > 0) { // If at least one input file to process.
auto optsVect = fOptions.begin()->second;
if (optsVect.size() > 0) {
auto opt = optsVect.front();
if (getRunNumber(opt) >= 0) { // if run number is not default -1
if (!isLocalDB(opt)) { // unless local DB file was provided
isDBrequired = true;
}
}
}
}
if (isDBrequired) {
INFO("Attempting to set up connection to the database.");
DB::SERVICES::DBHandler::createDBConnection(configFilePath);
} else {
INFO("Setting connection to database skipped.");
}
return isDBrequired;
}
<|endoftext|> |
<commit_before>#pragma once
#include <stdint.h>
#include <array>
#include <bitset>
#include <Memory.hpp>
// The NES CPU, the 2A03 (or 2A07 for PAL), is based on the 6502.
class CPU {
public:
CPU(Memory* mem);
// Initialize registers to their power on state.
void powerOn();
// Handle any interrupt and execute next opcode.
void step();
private:
// Positions of status register flags. See status register comments.
static constexpr int CARRY_FLAG = 0,
ZERO_FLAG = 1,
INTERRUPT_DISABLE = 2,
DECIMAL_MODE = 3,
BREAK_MODE_FLAG = 4,
UNUSED_BIT = 5,
OVERFLOW_FLAG = 6,
NEGATIVE_FLAG = 7;
// Execute opcode instruction.
void execute(const uint8_t& opcode);
// Returns value at address in the program counter (PC), then increments the PC.
uint8_t fetch();
// Returns 16-bit value, concatenated (in little endian order)
// from 8-bit values located at addresses PC+1 and PC.
uint16_t fetch16();
// Push value on the stack and decrement stack pointer.
void push(const uint8_t& value);
// Increment stack pointer and pop value from the stack.
uint8_t pop();
// Returns 16-bit value, concatenated (in little endian order)
// from 8-bit values located at address+1 and address.
uint16_t read16(const uint16_t& address);
// Splits 16-bit value into two 8-bit values and push them to stack.
void push16(const uint16_t& value);
// Pops two 8-bit values and returns them concatenated as a 16-bit value.
uint16_t pop16();
void setZeroFlag(const uint8_t& value);
void setNegativeFlag(const uint8_t& value);
Memory* memory;
// Tracks number of emulated cycles.
int cycles;
// Accumulator. Used for arithmethical and logical operations.
uint8_t r_a;
// Index registers. Used for indexed addressing.
uint8_t r_x, // Can directly alter stack pointer, unlike register Y.
r_y;
// Program Counter. Contains the memory address of the next instruction to be executed.
uint16_t pc;
// Stack Pointer. Points to the next empty location on the stack. Counts downward.
uint8_t sp;
// Status register. Each bit is a boolean flag.
// Enumerating the bits (0 being the least significant):
// 7654 3210
// NV-B DIZC
// 0: Carry Flag. 1 if last addition or shift resulted in a carry,
// or if last subtraction resulted in no borrow.
// 1: Zero Flag. Set if the result of the last instruction was 0.
// 2: Interrupt Disable. Disables response to maskable Interrupt Requests (IRQs).
// Doesn't affect Non-Maskable Interrupts (NMIs)
// 3: Decimal Mode. Would enable BCD (Binary Coded Decimal) mode, but it's disabled on the 2A03.
// 4: Break Command. Set when a BRK instruction has been executed and an interrupt has been generated to process it.
// 5: Unused. Always set.
// 6: Overflow Flag. Set when a signed arithmetic operation results in an invalid (overflowed) value. (e.g. 127+127 = -2).
// 7: Negative Flag. Set if the result of the last operation had bit 7 (the leftmost) set to a one,
// denoting negativity in a signed binary number.
std::bitset<8> r_p;
typedef void (CPU::*Instruction)(const uint16_t&);
// Addressing Modes. Gives an address to an instruction.
// Many instructions have multiple opcodes, for each addressing mode they use.
// Operand is an 8-bit constant value.
void immediate(Instruction instruction) {
const uint16_t address = pc;
++pc;
(this->*instruction)(address);
}
// Operand is an 8-bit address, addressing only the first 0x100 bytes of memory.
void zeroPage(Instruction instruction) {
const uint16_t address = fetch();
(this->*instruction)(address);
}
// Like Zero Page, but adds X register to the address.
void zeroPageX(Instruction instruction) {
const uint16_t address = fetch() + r_x;
(this->*instruction)(address);
}
// Like Zero Page, but adds Y register to the address.
void zeroPageY(Instruction instruction) {
const uint16_t address = fetch() + r_y;
(this->*instruction)(address);
}
// Corresponds to branch instructions. The (signed) 8-bit operand is an offset,
// to be added to the PC if the condition is true, or ignored if false.
void relative(Instruction instruction) {
const uint16_t address = pc;
++pc;
(this->*instruction)(address);
}
// Operand is a full 16-bit address.
void absolute(Instruction instruction) {
const uint16_t address = fetch16();
(this->*instruction)(address);
}
// Like Absolute, but adds X register to the address.
void absoluteX(Instruction instruction) {
const uint16_t address = fetch16() + r_x;
(this->*instruction)(address);
}
// Like Absolute, but adds Y register to the address.
void absoluteY(Instruction instruction) {
const uint16_t address = fetch16() + r_y;
(this->*instruction)(address);
}
// Operand is a 16-bit address points to another address.
void indirect(Instruction instruction) {
const uint16_t firstAddress = fetch16();
const uint16_t secondAddress = read16(firstAddress);
(this->*instruction)(secondAddress);
}
// Operand is an 8-bit address to which the X register is added,
// pointing to another address.
void indexedIndirect(Instruction instruction) {
const uint16_t firstAddress = fetch() + r_x;
const uint16_t secondAddress = read16(firstAddress);
(this->*instruction)(secondAddress);
}
// Operand is an 8-bit address pointing to another address,
// (the latter) to which the Y register is added.
void indirectIndexed(Instruction instruction) {
const uint16_t firstAddress = fetch();
const uint16_t secondAddress = read16(firstAddress) + r_y;
(this->*instruction)(secondAddress);
}
//// No operands. All the necessary information is in the opcode.
//void implied(void (CPU::*instruction)()) {
// (this->*instruction)();
//}
//// Special type of Implied, operating directing on the accumulator register. May be unnecessary.
//void accumulator(void (CPU::*instruction)()) {
// (this->*instruction)();
//}
// Instructions
void ADC(const uint16_t& address); // Add with Carry
void AND(const uint16_t& address); // Logical AND
void ASL(); // Arithmetic Shift Left (Accumulator)
void ASL(const uint16_t& address); // Arithmetic Shift Left
void BCC(const uint16_t& address); // Branch if Carry Clear
void BCS(const uint16_t& address); // Branch if Carry Set
void BEQ(const uint16_t& address); // Branch if Equal
void BIT(const uint16_t& address); // Bit Test
void BMI(const uint16_t& address); // Branch if Minus
void BNE(const uint16_t& address); // Branch if Not Equal
void BPL(const uint16_t& address); // Branch if Positive
void BRK(); // Force Interrupt
void BVC(const uint16_t& address); // Branch if Overflow Clear
void BVS(const uint16_t& address); // Branch if Overflow Set
void CLC(); // Clear Carry Flag
void CLD(); // Clear Decimal Mode
void CLI(); // Clear Interrupt Disable
void CLV(); // Clear Overflow Flag
void CMP(const uint16_t& address); // Compare
void CPX(const uint16_t& address); // Compare X Register
void CPY(const uint16_t& address); // Compare Y Register
void DEC(const uint16_t& address); // Decrement Memory
void DEX(); // Decrement X Register
void DEY(); // Decrement Y Register
void EOR(const uint16_t& address); // Exclusive OR
void INC(const uint16_t& address); // Increment Memory
void INX(); // Increment X Register
void INY(); // Increment Y Register
void JMP(const uint16_t& address); // Jump
void JSR(const uint16_t& address); // Jump to Subroutine
void LDA(const uint16_t& address); // Load Accumulator
void LDX(const uint16_t& address); // Load X Register
void LDY(const uint16_t& address); // Load Y Register
void LSR(); // Logical Shift Right (Accumulator)
void LSR(const uint16_t& address); // Logical Shift Right
void NOP(); // No Operation
void ORA(const uint16_t& address); // Logical Inclusive OR
void PHA(); // Push Accumulator
void PHP(); // Push Processor Status
void PLA(); // Pull Accumulator
void PLP(); // Pull Processor Status
void ROL(); // Rotate Left (Accumulator)
void ROL(const uint16_t& address); // Rotate Left
void ROR(); // Rotate Right (Accumulator)
void ROR(const uint16_t& address); // Rotate Right
void RTI(); // Return from Interrupt
void RTS(); // Return from Subroutine
void SBC(const uint16_t& address); // Subtract with Carry
void SEC(); // Set Carry Flag
void SED(); // Set Decimal Flag
void SEI(); // Set Interrupt Disable
void STA(const uint16_t& address); // Store Accumulator
void STX(const uint16_t& address); // Store X Register
void STY(const uint16_t& address); // Store Y Register
void TAX(); // Transfer Accumulator to X
void TAY(); // Transfer Accumulator to Y
void TSX(); // Transfer Stack Pointer to X
void TXA(); // Transfer X to Accumulator
void TXS(); // Transfer X to Stack Pointer
void TYA(); // Transfer Y to Accumulator
};<commit_msg>(Minor change:) Align CPU instruction declaration comments<commit_after>#pragma once
#include <stdint.h>
#include <array>
#include <bitset>
#include <Memory.hpp>
// The NES CPU, the 2A03 (or 2A07 for PAL), is based on the 6502.
class CPU {
public:
CPU(Memory* mem);
// Initialize registers to their power on state.
void powerOn();
// Handle any interrupt and execute next opcode.
void step();
private:
// Positions of status register flags. See status register comments.
static constexpr int CARRY_FLAG = 0,
ZERO_FLAG = 1,
INTERRUPT_DISABLE = 2,
DECIMAL_MODE = 3,
BREAK_MODE_FLAG = 4,
UNUSED_BIT = 5,
OVERFLOW_FLAG = 6,
NEGATIVE_FLAG = 7;
// Execute opcode instruction.
void execute(const uint8_t& opcode);
// Returns value at address in the program counter (PC), then increments the PC.
uint8_t fetch();
// Returns 16-bit value, concatenated (in little endian order)
// from 8-bit values located at addresses PC+1 and PC.
uint16_t fetch16();
// Push value on the stack and decrement stack pointer.
void push(const uint8_t& value);
// Increment stack pointer and pop value from the stack.
uint8_t pop();
// Returns 16-bit value, concatenated (in little endian order)
// from 8-bit values located at address+1 and address.
uint16_t read16(const uint16_t& address);
// Splits 16-bit value into two 8-bit values and push them to stack.
void push16(const uint16_t& value);
// Pops two 8-bit values and returns them concatenated as a 16-bit value.
uint16_t pop16();
void setZeroFlag(const uint8_t& value);
void setNegativeFlag(const uint8_t& value);
Memory* memory;
// Tracks number of emulated cycles.
int cycles;
// Accumulator. Used for arithmethical and logical operations.
uint8_t r_a;
// Index registers. Used for indexed addressing.
uint8_t r_x, // Can directly alter stack pointer, unlike register Y.
r_y;
// Program Counter. Contains the memory address of the next instruction to be executed.
uint16_t pc;
// Stack Pointer. Points to the next empty location on the stack. Counts downward.
uint8_t sp;
// Status register. Each bit is a boolean flag.
// Enumerating the bits (0 being the least significant):
// 7654 3210
// NV-B DIZC
// 0: Carry Flag. 1 if last addition or shift resulted in a carry,
// or if last subtraction resulted in no borrow.
// 1: Zero Flag. Set if the result of the last instruction was 0.
// 2: Interrupt Disable. Disables response to maskable Interrupt Requests (IRQs).
// Doesn't affect Non-Maskable Interrupts (NMIs)
// 3: Decimal Mode. Would enable BCD (Binary Coded Decimal) mode, but it's disabled on the 2A03.
// 4: Break Command. Set when a BRK instruction has been executed and an interrupt has been generated to process it.
// 5: Unused. Always set.
// 6: Overflow Flag. Set when a signed arithmetic operation results in an invalid (overflowed) value. (e.g. 127+127 = -2).
// 7: Negative Flag. Set if the result of the last operation had bit 7 (the leftmost) set to a one,
// denoting negativity in a signed binary number.
std::bitset<8> r_p;
typedef void (CPU::*Instruction)(const uint16_t&);
// Addressing Modes. Gives an address to an instruction.
// Many instructions have multiple opcodes, for each addressing mode they use.
// Operand is an 8-bit constant value.
void immediate(Instruction instruction) {
const uint16_t address = pc;
++pc;
(this->*instruction)(address);
}
// Operand is an 8-bit address, addressing only the first 0x100 bytes of memory.
void zeroPage(Instruction instruction) {
const uint16_t address = fetch();
(this->*instruction)(address);
}
// Like Zero Page, but adds X register to the address.
void zeroPageX(Instruction instruction) {
const uint16_t address = fetch() + r_x;
(this->*instruction)(address);
}
// Like Zero Page, but adds Y register to the address.
void zeroPageY(Instruction instruction) {
const uint16_t address = fetch() + r_y;
(this->*instruction)(address);
}
// Corresponds to branch instructions. The (signed) 8-bit operand is an offset,
// to be added to the PC if the condition is true, or ignored if false.
void relative(Instruction instruction) {
const uint16_t address = pc;
++pc;
(this->*instruction)(address);
}
// Operand is a full 16-bit address.
void absolute(Instruction instruction) {
const uint16_t address = fetch16();
(this->*instruction)(address);
}
// Like Absolute, but adds X register to the address.
void absoluteX(Instruction instruction) {
const uint16_t address = fetch16() + r_x;
(this->*instruction)(address);
}
// Like Absolute, but adds Y register to the address.
void absoluteY(Instruction instruction) {
const uint16_t address = fetch16() + r_y;
(this->*instruction)(address);
}
// Operand is a 16-bit address points to another address.
void indirect(Instruction instruction) {
const uint16_t firstAddress = fetch16();
const uint16_t secondAddress = read16(firstAddress);
(this->*instruction)(secondAddress);
}
// Operand is an 8-bit address to which the X register is added,
// pointing to another address.
void indexedIndirect(Instruction instruction) {
const uint16_t firstAddress = fetch() + r_x;
const uint16_t secondAddress = read16(firstAddress);
(this->*instruction)(secondAddress);
}
// Operand is an 8-bit address pointing to another address,
// (the latter) to which the Y register is added.
void indirectIndexed(Instruction instruction) {
const uint16_t firstAddress = fetch();
const uint16_t secondAddress = read16(firstAddress) + r_y;
(this->*instruction)(secondAddress);
}
//// No operands. All the necessary information is in the opcode.
//void implied(void (CPU::*instruction)()) {
// (this->*instruction)();
//}
//// Special type of Implied, operating directing on the accumulator register. May be unnecessary.
//void accumulator(void (CPU::*instruction)()) {
// (this->*instruction)();
//}
// Instructions
void ADC(const uint16_t& address); // Add with Carry
void AND(const uint16_t& address); // Logical AND
void ASL(); // Arithmetic Shift Left (Accumulator)
void ASL(const uint16_t& address); // Arithmetic Shift Left
void BCC(const uint16_t& address); // Branch if Carry Clear
void BCS(const uint16_t& address); // Branch if Carry Set
void BEQ(const uint16_t& address); // Branch if Equal
void BIT(const uint16_t& address); // Bit Test
void BMI(const uint16_t& address); // Branch if Minus
void BNE(const uint16_t& address); // Branch if Not Equal
void BPL(const uint16_t& address); // Branch if Positive
void BRK(); // Force Interrupt
void BVC(const uint16_t& address); // Branch if Overflow Clear
void BVS(const uint16_t& address); // Branch if Overflow Set
void CLC(); // Clear Carry Flag
void CLD(); // Clear Decimal Mode
void CLI(); // Clear Interrupt Disable
void CLV(); // Clear Overflow Flag
void CMP(const uint16_t& address); // Compare
void CPX(const uint16_t& address); // Compare X Register
void CPY(const uint16_t& address); // Compare Y Register
void DEC(const uint16_t& address); // Decrement Memory
void DEX(); // Decrement X Register
void DEY(); // Decrement Y Register
void EOR(const uint16_t& address); // Exclusive OR
void INC(const uint16_t& address); // Increment Memory
void INX(); // Increment X Register
void INY(); // Increment Y Register
void JMP(const uint16_t& address); // Jump
void JSR(const uint16_t& address); // Jump to Subroutine
void LDA(const uint16_t& address); // Load Accumulator
void LDX(const uint16_t& address); // Load X Register
void LDY(const uint16_t& address); // Load Y Register
void LSR(); // Logical Shift Right (Accumulator)
void LSR(const uint16_t& address); // Logical Shift Right
void NOP(); // No Operation
void ORA(const uint16_t& address); // Logical Inclusive OR
void PHA(); // Push Accumulator
void PHP(); // Push Processor Status
void PLA(); // Pull Accumulator
void PLP(); // Pull Processor Status
void ROL(); // Rotate Left (Accumulator)
void ROL(const uint16_t& address); // Rotate Left
void ROR(); // Rotate Right (Accumulator)
void ROR(const uint16_t& address); // Rotate Right
void RTI(); // Return from Interrupt
void RTS(); // Return from Subroutine
void SBC(const uint16_t& address); // Subtract with Carry
void SEC(); // Set Carry Flag
void SED(); // Set Decimal Flag
void SEI(); // Set Interrupt Disable
void STA(const uint16_t& address); // Store Accumulator
void STX(const uint16_t& address); // Store X Register
void STY(const uint16_t& address); // Store Y Register
void TAX(); // Transfer Accumulator to X
void TAY(); // Transfer Accumulator to Y
void TSX(); // Transfer Stack Pointer to X
void TXA(); // Transfer X to Accumulator
void TXS(); // Transfer X to Stack Pointer
void TYA(); // Transfer Y to Accumulator
};<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/tcp_client_socket.h"
#include "base/memory_debug.h"
#include "base/string_util.h"
#include "base/trace_event.h"
#include "net/base/net_errors.h"
#include "net/base/winsock_init.h"
namespace net {
//-----------------------------------------------------------------------------
static int MapWinsockError(DWORD err) {
// There are numerous Winsock error codes, but these are the ones we thus far
// find interesting.
switch (err) {
case WSAENETDOWN:
return ERR_INTERNET_DISCONNECTED;
case WSAETIMEDOUT:
return ERR_TIMED_OUT;
case WSAECONNRESET:
case WSAENETRESET: // Related to keep-alive
return ERR_CONNECTION_RESET;
case WSAECONNABORTED:
return ERR_CONNECTION_ABORTED;
case WSAECONNREFUSED:
return ERR_CONNECTION_REFUSED;
case WSAEDISCON:
// Returned by WSARecv or WSARecvFrom for message-oriented sockets (where
// a return value of zero means a zero-byte message) to indicate graceful
// connection shutdown. We should not ever see this error code for TCP
// sockets, which are byte stream oriented.
NOTREACHED();
return ERR_CONNECTION_CLOSED;
case WSAEHOSTUNREACH:
case WSAENETUNREACH:
return ERR_ADDRESS_UNREACHABLE;
case WSAEADDRNOTAVAIL:
return ERR_ADDRESS_INVALID;
case WSA_IO_INCOMPLETE:
return ERR_UNEXPECTED;
case ERROR_SUCCESS:
return OK;
default:
LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED";
return ERR_FAILED;
}
}
//-----------------------------------------------------------------------------
TCPClientSocket::TCPClientSocket(const AddressList& addresses)
: socket_(INVALID_SOCKET),
addresses_(addresses),
current_ai_(addresses_.head()),
wait_state_(NOT_WAITING),
callback_(NULL) {
memset(&overlapped_, 0, sizeof(overlapped_));
EnsureWinsockInit();
}
TCPClientSocket::~TCPClientSocket() {
Disconnect();
}
int TCPClientSocket::Connect(CompletionCallback* callback) {
// If already connected, then just return OK.
if (socket_ != INVALID_SOCKET)
return OK;
TRACE_EVENT_BEGIN("socket.connect", this, "");
const struct addrinfo* ai = current_ai_;
DCHECK(ai);
int rv = CreateSocket(ai);
if (rv != OK)
return rv;
// WSACreateEvent creates a manual-reset event object.
overlapped_.hEvent = WSACreateEvent();
// WSAEventSelect sets the socket to non-blocking mode as a side effect.
// Our connect() and recv() calls require that the socket be non-blocking.
WSAEventSelect(socket_, overlapped_.hEvent, FD_CONNECT);
if (!connect(socket_, ai->ai_addr, static_cast<int>(ai->ai_addrlen))) {
// Connected without waiting!
CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_OBJECT_0);
BOOL ok = WSAResetEvent(overlapped_.hEvent);
CHECK(ok);
TRACE_EVENT_END("socket.connect", this, "");
return OK;
}
DWORD err = WSAGetLastError();
if (err != WSAEWOULDBLOCK) {
LOG(ERROR) << "connect failed: " << err;
return MapWinsockError(err);
}
watcher_.StartWatching(overlapped_.hEvent, this);
wait_state_ = WAITING_CONNECT;
callback_ = callback;
return ERR_IO_PENDING;
}
int TCPClientSocket::ReconnectIgnoringLastError(CompletionCallback* callback) {
// No ignorable errors!
return ERR_UNEXPECTED;
}
void TCPClientSocket::Disconnect() {
if (socket_ == INVALID_SOCKET)
return;
TRACE_EVENT_INSTANT("socket.disconnect", this, "");
// Make sure the message loop is not watching this object anymore.
watcher_.StopWatching();
// Cancel any pending IO and wait for it to be aborted.
if (wait_state_ == WAITING_READ || wait_state_ == WAITING_WRITE) {
CancelIo(reinterpret_cast<HANDLE>(socket_));
WaitForSingleObject(overlapped_.hEvent, INFINITE);
wait_state_ = NOT_WAITING;
}
// In most socket implementations, closing a socket results in a graceful
// connection shutdown, but in Winsock we have to call shutdown explicitly.
// See the MSDN page "Graceful Shutdown, Linger Options, and Socket Closure"
// at http://msdn.microsoft.com/en-us/library/ms738547.aspx
shutdown(socket_, SD_SEND);
closesocket(socket_);
socket_ = INVALID_SOCKET;
WSACloseEvent(overlapped_.hEvent);
memset(&overlapped_, 0, sizeof(overlapped_));
// Reset for next time.
current_ai_ = addresses_.head();
}
bool TCPClientSocket::IsConnected() const {
if (socket_ == INVALID_SOCKET || wait_state_ == WAITING_CONNECT)
return false;
// Check if connection is alive.
char c;
int rv = recv(socket_, &c, 1, MSG_PEEK);
if (rv == 0)
return false;
if (rv == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
return false;
return true;
}
int TCPClientSocket::Read(char* buf,
int buf_len,
CompletionCallback* callback) {
DCHECK(socket_ != INVALID_SOCKET);
DCHECK(wait_state_ == NOT_WAITING);
DCHECK(!callback_);
buffer_.len = buf_len;
buffer_.buf = buf;
TRACE_EVENT_BEGIN("socket.read", this, "");
// TODO(wtc): Remove the CHECKs after enough testing.
CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_TIMEOUT);
DWORD num, flags = 0;
int rv = WSARecv(socket_, &buffer_, 1, &num, &flags, &overlapped_, NULL);
if (rv == 0) {
CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_OBJECT_0);
BOOL ok = WSAResetEvent(overlapped_.hEvent);
CHECK(ok);
TRACE_EVENT_END("socket.read", this, StringPrintf("%d bytes", num));
// Because of how WSARecv fills memory when used asynchronously, Purify
// isn't able to detect that it's been initialized, so it scans for 0xcd
// in the buffer and reports UMRs (uninitialized memory reads) for those
// individual bytes. We override that in PURIFY builds to avoid the false
// error reports.
// See bug 5297.
base::MemoryDebug::MarkAsInitialized(buffer_.buf, num);
return static_cast<int>(num);
}
int err = WSAGetLastError();
if (err == WSA_IO_PENDING) {
watcher_.StartWatching(overlapped_.hEvent, this);
wait_state_ = WAITING_READ;
callback_ = callback;
return ERR_IO_PENDING;
}
return MapWinsockError(err);
}
int TCPClientSocket::Write(const char* buf,
int buf_len,
CompletionCallback* callback) {
DCHECK(socket_ != INVALID_SOCKET);
DCHECK(wait_state_ == NOT_WAITING);
DCHECK(!callback_);
buffer_.len = buf_len;
buffer_.buf = const_cast<char*>(buf);
TRACE_EVENT_BEGIN("socket.write", this, "");
// TODO(wtc): Remove the CHECKs after enough testing.
CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_TIMEOUT);
DWORD num;
int rv = WSASend(socket_, &buffer_, 1, &num, 0, &overlapped_, NULL);
if (rv == 0) {
// TODO(wtc): These temporary CHECKs are intended to determine the return
// value and error code of the WaitForSingleObject call if it doesn't
// return the expected WAIT_OBJECT_0. See http://crbug.com/6500.
DWORD wait_rv = WaitForSingleObject(overlapped_.hEvent, 0);
if (wait_rv != WAIT_OBJECT_0) {
if (wait_rv == WAIT_ABANDONED) {
CHECK(false);
} else if (wait_rv == WAIT_TIMEOUT) {
CHECK(false);
} else if (wait_rv == WAIT_FAILED) {
DWORD wait_error = GetLastError();
if (wait_error == ERROR_INVALID_HANDLE) {
CHECK(false);
} else {
CHECK(false);
}
} else {
CHECK(false);
}
}
BOOL ok = WSAResetEvent(overlapped_.hEvent);
CHECK(ok);
TRACE_EVENT_END("socket.write", this, StringPrintf("%d bytes", num));
return static_cast<int>(num);
}
int err = WSAGetLastError();
if (err == WSA_IO_PENDING) {
watcher_.StartWatching(overlapped_.hEvent, this);
wait_state_ = WAITING_WRITE;
callback_ = callback;
return ERR_IO_PENDING;
}
return MapWinsockError(err);
}
int TCPClientSocket::CreateSocket(const struct addrinfo* ai) {
socket_ = WSASocket(ai->ai_family, ai->ai_socktype, ai->ai_protocol, NULL, 0,
WSA_FLAG_OVERLAPPED);
if (socket_ == INVALID_SOCKET) {
DWORD err = WSAGetLastError();
LOG(ERROR) << "WSASocket failed: " << err;
return MapWinsockError(err);
}
// Increase the socket buffer sizes from the default sizes.
// In performance testing, there is substantial benefit by increasing
// from 8KB to 32KB. I tested 64, 128, and 256KB as well, but did not
// see additional performance benefit (will be network dependent).
// See also:
// http://support.microsoft.com/kb/823764/EN-US
// On XP, the default buffer sizes are 8KB.
const int kSocketBufferSize = 32 * 1024;
int rv = setsockopt(socket_, SOL_SOCKET, SO_SNDBUF,
reinterpret_cast<const char*>(&kSocketBufferSize),
sizeof(kSocketBufferSize));
DCHECK(!rv) << "Could not set socket send buffer size";
rv = setsockopt(socket_, SOL_SOCKET, SO_RCVBUF,
reinterpret_cast<const char*>(&kSocketBufferSize),
sizeof(kSocketBufferSize));
DCHECK(!rv) << "Could not set socket receive buffer size";
// Disable Nagle.
// The Nagle implementation on windows is governed by RFC 896. The idea
// behind Nagle is to reduce small packets on the network. When Nagle is
// enabled, if a partial packet has been sent, the TCP stack will disallow
// further *partial* packets until an ACK has been received from the other
// side. Good applications should always strive to send as much data as
// possible and avoid partial-packet sends. However, in most real world
// applications, there are edge cases where this does not happen, and two
// partil packets may be sent back to back. For a browser, it is NEVER
// a benefit to delay for an RTT before the second packet is sent.
//
// As a practical example in Chromium today, consider the case of a small
// POST. I have verified this:
// Client writes 649 bytes of header (partial packet #1)
// Client writes 50 bytes of POST data (partial packet #2)
// In the above example, with Nagle, a RTT delay is inserted between these
// two sends due to nagle. RTTs can easily be 100ms or more. The best
// fix is to make sure that for POSTing data, we write as much data as
// possible and minimize partial packets. We will fix that. But disabling
// Nagle also ensure we don't run into this delay in other edge cases.
// See also:
// http://technet.microsoft.com/en-us/library/bb726981.aspx
const BOOL kDisableNagle = TRUE;
rv = setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY,
reinterpret_cast<const char*>(&kDisableNagle), sizeof(kDisableNagle));
DCHECK(!rv) << "Could not disable nagle";
return OK;
}
void TCPClientSocket::DoCallback(int rv) {
DCHECK(rv != ERR_IO_PENDING);
DCHECK(callback_);
// since Run may result in Read being called, clear callback_ up front.
CompletionCallback* c = callback_;
callback_ = NULL;
c->Run(rv);
}
void TCPClientSocket::DidCompleteConnect() {
int result;
TRACE_EVENT_END("socket.connect", this, "");
wait_state_ = NOT_WAITING;
WSANETWORKEVENTS events;
int rv = WSAEnumNetworkEvents(socket_, overlapped_.hEvent, &events);
if (rv == SOCKET_ERROR) {
NOTREACHED();
result = MapWinsockError(WSAGetLastError());
} else if (events.lNetworkEvents & FD_CONNECT) {
wait_state_ = NOT_WAITING;
DWORD error_code = static_cast<DWORD>(events.iErrorCode[FD_CONNECT_BIT]);
if (current_ai_->ai_next && (
error_code == WSAEADDRNOTAVAIL ||
error_code == WSAEAFNOSUPPORT ||
error_code == WSAECONNREFUSED ||
error_code == WSAENETUNREACH ||
error_code == WSAEHOSTUNREACH ||
error_code == WSAETIMEDOUT)) {
// Try using the next address.
const struct addrinfo* next = current_ai_->ai_next;
Disconnect();
current_ai_ = next;
result = Connect(callback_);
} else {
result = MapWinsockError(error_code);
}
} else {
NOTREACHED();
result = ERR_UNEXPECTED;
}
if (result != ERR_IO_PENDING)
DoCallback(result);
}
void TCPClientSocket::DidCompleteIO() {
DWORD num_bytes, flags;
BOOL ok = WSAGetOverlappedResult(
socket_, &overlapped_, &num_bytes, FALSE, &flags);
WSAResetEvent(overlapped_.hEvent);
if (wait_state_ == WAITING_READ) {
TRACE_EVENT_END("socket.read", this, StringPrintf("%d bytes", num_bytes));
} else {
TRACE_EVENT_END("socket.write", this, StringPrintf("%d bytes", num_bytes));
}
wait_state_ = NOT_WAITING;
DoCallback(ok ? num_bytes : MapWinsockError(WSAGetLastError()));
}
void TCPClientSocket::OnObjectSignaled(HANDLE object) {
DCHECK(object == overlapped_.hEvent);
switch (wait_state_) {
case WAITING_CONNECT:
DidCompleteConnect();
break;
case WAITING_READ:
case WAITING_WRITE:
DidCompleteIO();
break;
default:
NOTREACHED();
break;
}
}
} // namespace net
<commit_msg>Add a dummy function CrashBug6500 so that the return value and error code of the WaitForSingleObject call are captured as function arguments in the crash dumps.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/tcp_client_socket.h"
#include "base/memory_debug.h"
#include "base/string_util.h"
#include "base/trace_event.h"
#include "net/base/net_errors.h"
#include "net/base/winsock_init.h"
namespace net {
//-----------------------------------------------------------------------------
static int MapWinsockError(DWORD err) {
// There are numerous Winsock error codes, but these are the ones we thus far
// find interesting.
switch (err) {
case WSAENETDOWN:
return ERR_INTERNET_DISCONNECTED;
case WSAETIMEDOUT:
return ERR_TIMED_OUT;
case WSAECONNRESET:
case WSAENETRESET: // Related to keep-alive
return ERR_CONNECTION_RESET;
case WSAECONNABORTED:
return ERR_CONNECTION_ABORTED;
case WSAECONNREFUSED:
return ERR_CONNECTION_REFUSED;
case WSAEDISCON:
// Returned by WSARecv or WSARecvFrom for message-oriented sockets (where
// a return value of zero means a zero-byte message) to indicate graceful
// connection shutdown. We should not ever see this error code for TCP
// sockets, which are byte stream oriented.
NOTREACHED();
return ERR_CONNECTION_CLOSED;
case WSAEHOSTUNREACH:
case WSAENETUNREACH:
return ERR_ADDRESS_UNREACHABLE;
case WSAEADDRNOTAVAIL:
return ERR_ADDRESS_INVALID;
case WSA_IO_INCOMPLETE:
return ERR_UNEXPECTED;
case ERROR_SUCCESS:
return OK;
default:
LOG(WARNING) << "Unknown error " << err << " mapped to net::ERR_FAILED";
return ERR_FAILED;
}
}
//-----------------------------------------------------------------------------
TCPClientSocket::TCPClientSocket(const AddressList& addresses)
: socket_(INVALID_SOCKET),
addresses_(addresses),
current_ai_(addresses_.head()),
wait_state_(NOT_WAITING),
callback_(NULL) {
memset(&overlapped_, 0, sizeof(overlapped_));
EnsureWinsockInit();
}
TCPClientSocket::~TCPClientSocket() {
Disconnect();
}
int TCPClientSocket::Connect(CompletionCallback* callback) {
// If already connected, then just return OK.
if (socket_ != INVALID_SOCKET)
return OK;
TRACE_EVENT_BEGIN("socket.connect", this, "");
const struct addrinfo* ai = current_ai_;
DCHECK(ai);
int rv = CreateSocket(ai);
if (rv != OK)
return rv;
// WSACreateEvent creates a manual-reset event object.
overlapped_.hEvent = WSACreateEvent();
// WSAEventSelect sets the socket to non-blocking mode as a side effect.
// Our connect() and recv() calls require that the socket be non-blocking.
WSAEventSelect(socket_, overlapped_.hEvent, FD_CONNECT);
if (!connect(socket_, ai->ai_addr, static_cast<int>(ai->ai_addrlen))) {
// Connected without waiting!
CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_OBJECT_0);
BOOL ok = WSAResetEvent(overlapped_.hEvent);
CHECK(ok);
TRACE_EVENT_END("socket.connect", this, "");
return OK;
}
DWORD err = WSAGetLastError();
if (err != WSAEWOULDBLOCK) {
LOG(ERROR) << "connect failed: " << err;
return MapWinsockError(err);
}
watcher_.StartWatching(overlapped_.hEvent, this);
wait_state_ = WAITING_CONNECT;
callback_ = callback;
return ERR_IO_PENDING;
}
int TCPClientSocket::ReconnectIgnoringLastError(CompletionCallback* callback) {
// No ignorable errors!
return ERR_UNEXPECTED;
}
void TCPClientSocket::Disconnect() {
if (socket_ == INVALID_SOCKET)
return;
TRACE_EVENT_INSTANT("socket.disconnect", this, "");
// Make sure the message loop is not watching this object anymore.
watcher_.StopWatching();
// Cancel any pending IO and wait for it to be aborted.
if (wait_state_ == WAITING_READ || wait_state_ == WAITING_WRITE) {
CancelIo(reinterpret_cast<HANDLE>(socket_));
WaitForSingleObject(overlapped_.hEvent, INFINITE);
wait_state_ = NOT_WAITING;
}
// In most socket implementations, closing a socket results in a graceful
// connection shutdown, but in Winsock we have to call shutdown explicitly.
// See the MSDN page "Graceful Shutdown, Linger Options, and Socket Closure"
// at http://msdn.microsoft.com/en-us/library/ms738547.aspx
shutdown(socket_, SD_SEND);
closesocket(socket_);
socket_ = INVALID_SOCKET;
WSACloseEvent(overlapped_.hEvent);
memset(&overlapped_, 0, sizeof(overlapped_));
// Reset for next time.
current_ai_ = addresses_.head();
}
bool TCPClientSocket::IsConnected() const {
if (socket_ == INVALID_SOCKET || wait_state_ == WAITING_CONNECT)
return false;
// Check if connection is alive.
char c;
int rv = recv(socket_, &c, 1, MSG_PEEK);
if (rv == 0)
return false;
if (rv == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
return false;
return true;
}
int TCPClientSocket::Read(char* buf,
int buf_len,
CompletionCallback* callback) {
DCHECK(socket_ != INVALID_SOCKET);
DCHECK(wait_state_ == NOT_WAITING);
DCHECK(!callback_);
buffer_.len = buf_len;
buffer_.buf = buf;
TRACE_EVENT_BEGIN("socket.read", this, "");
// TODO(wtc): Remove the CHECKs after enough testing.
CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_TIMEOUT);
DWORD num, flags = 0;
int rv = WSARecv(socket_, &buffer_, 1, &num, &flags, &overlapped_, NULL);
if (rv == 0) {
CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_OBJECT_0);
BOOL ok = WSAResetEvent(overlapped_.hEvent);
CHECK(ok);
TRACE_EVENT_END("socket.read", this, StringPrintf("%d bytes", num));
// Because of how WSARecv fills memory when used asynchronously, Purify
// isn't able to detect that it's been initialized, so it scans for 0xcd
// in the buffer and reports UMRs (uninitialized memory reads) for those
// individual bytes. We override that in PURIFY builds to avoid the false
// error reports.
// See bug 5297.
base::MemoryDebug::MarkAsInitialized(buffer_.buf, num);
return static_cast<int>(num);
}
int err = WSAGetLastError();
if (err == WSA_IO_PENDING) {
watcher_.StartWatching(overlapped_.hEvent, this);
wait_state_ = WAITING_READ;
callback_ = callback;
return ERR_IO_PENDING;
}
return MapWinsockError(err);
}
// TODO(wtc): This temporary function is intended to determine the return
// value and error code of the WaitForSingleObject call in
// TCPClientSocket::Write if it doesn't return the expected WAIT_OBJECT_0.
// See http://crbug.com/6500.
static void CrashBug6500(DWORD wait_rv, DWORD wait_error) {
// wait_error is meaningful only if wait_rv is WAIT_FAILED.
CHECK(false) << wait_rv << wait_error;
}
int TCPClientSocket::Write(const char* buf,
int buf_len,
CompletionCallback* callback) {
DCHECK(socket_ != INVALID_SOCKET);
DCHECK(wait_state_ == NOT_WAITING);
DCHECK(!callback_);
buffer_.len = buf_len;
buffer_.buf = const_cast<char*>(buf);
TRACE_EVENT_BEGIN("socket.write", this, "");
// TODO(wtc): Remove the CHECKs after enough testing.
CHECK(WaitForSingleObject(overlapped_.hEvent, 0) == WAIT_TIMEOUT);
DWORD num;
int rv = WSASend(socket_, &buffer_, 1, &num, 0, &overlapped_, NULL);
if (rv == 0) {
DWORD wait_rv = WaitForSingleObject(overlapped_.hEvent, 0);
if (wait_rv != WAIT_OBJECT_0) {
DWORD wait_error = GetLastError();
CrashBug6500(wait_rv, wait_error);
}
BOOL ok = WSAResetEvent(overlapped_.hEvent);
CHECK(ok);
TRACE_EVENT_END("socket.write", this, StringPrintf("%d bytes", num));
return static_cast<int>(num);
}
int err = WSAGetLastError();
if (err == WSA_IO_PENDING) {
watcher_.StartWatching(overlapped_.hEvent, this);
wait_state_ = WAITING_WRITE;
callback_ = callback;
return ERR_IO_PENDING;
}
return MapWinsockError(err);
}
int TCPClientSocket::CreateSocket(const struct addrinfo* ai) {
socket_ = WSASocket(ai->ai_family, ai->ai_socktype, ai->ai_protocol, NULL, 0,
WSA_FLAG_OVERLAPPED);
if (socket_ == INVALID_SOCKET) {
DWORD err = WSAGetLastError();
LOG(ERROR) << "WSASocket failed: " << err;
return MapWinsockError(err);
}
// Increase the socket buffer sizes from the default sizes.
// In performance testing, there is substantial benefit by increasing
// from 8KB to 32KB. I tested 64, 128, and 256KB as well, but did not
// see additional performance benefit (will be network dependent).
// See also:
// http://support.microsoft.com/kb/823764/EN-US
// On XP, the default buffer sizes are 8KB.
const int kSocketBufferSize = 32 * 1024;
int rv = setsockopt(socket_, SOL_SOCKET, SO_SNDBUF,
reinterpret_cast<const char*>(&kSocketBufferSize),
sizeof(kSocketBufferSize));
DCHECK(!rv) << "Could not set socket send buffer size";
rv = setsockopt(socket_, SOL_SOCKET, SO_RCVBUF,
reinterpret_cast<const char*>(&kSocketBufferSize),
sizeof(kSocketBufferSize));
DCHECK(!rv) << "Could not set socket receive buffer size";
// Disable Nagle.
// The Nagle implementation on windows is governed by RFC 896. The idea
// behind Nagle is to reduce small packets on the network. When Nagle is
// enabled, if a partial packet has been sent, the TCP stack will disallow
// further *partial* packets until an ACK has been received from the other
// side. Good applications should always strive to send as much data as
// possible and avoid partial-packet sends. However, in most real world
// applications, there are edge cases where this does not happen, and two
// partil packets may be sent back to back. For a browser, it is NEVER
// a benefit to delay for an RTT before the second packet is sent.
//
// As a practical example in Chromium today, consider the case of a small
// POST. I have verified this:
// Client writes 649 bytes of header (partial packet #1)
// Client writes 50 bytes of POST data (partial packet #2)
// In the above example, with Nagle, a RTT delay is inserted between these
// two sends due to nagle. RTTs can easily be 100ms or more. The best
// fix is to make sure that for POSTing data, we write as much data as
// possible and minimize partial packets. We will fix that. But disabling
// Nagle also ensure we don't run into this delay in other edge cases.
// See also:
// http://technet.microsoft.com/en-us/library/bb726981.aspx
const BOOL kDisableNagle = TRUE;
rv = setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY,
reinterpret_cast<const char*>(&kDisableNagle), sizeof(kDisableNagle));
DCHECK(!rv) << "Could not disable nagle";
return OK;
}
void TCPClientSocket::DoCallback(int rv) {
DCHECK(rv != ERR_IO_PENDING);
DCHECK(callback_);
// since Run may result in Read being called, clear callback_ up front.
CompletionCallback* c = callback_;
callback_ = NULL;
c->Run(rv);
}
void TCPClientSocket::DidCompleteConnect() {
int result;
TRACE_EVENT_END("socket.connect", this, "");
wait_state_ = NOT_WAITING;
WSANETWORKEVENTS events;
int rv = WSAEnumNetworkEvents(socket_, overlapped_.hEvent, &events);
if (rv == SOCKET_ERROR) {
NOTREACHED();
result = MapWinsockError(WSAGetLastError());
} else if (events.lNetworkEvents & FD_CONNECT) {
wait_state_ = NOT_WAITING;
DWORD error_code = static_cast<DWORD>(events.iErrorCode[FD_CONNECT_BIT]);
if (current_ai_->ai_next && (
error_code == WSAEADDRNOTAVAIL ||
error_code == WSAEAFNOSUPPORT ||
error_code == WSAECONNREFUSED ||
error_code == WSAENETUNREACH ||
error_code == WSAEHOSTUNREACH ||
error_code == WSAETIMEDOUT)) {
// Try using the next address.
const struct addrinfo* next = current_ai_->ai_next;
Disconnect();
current_ai_ = next;
result = Connect(callback_);
} else {
result = MapWinsockError(error_code);
}
} else {
NOTREACHED();
result = ERR_UNEXPECTED;
}
if (result != ERR_IO_PENDING)
DoCallback(result);
}
void TCPClientSocket::DidCompleteIO() {
DWORD num_bytes, flags;
BOOL ok = WSAGetOverlappedResult(
socket_, &overlapped_, &num_bytes, FALSE, &flags);
WSAResetEvent(overlapped_.hEvent);
if (wait_state_ == WAITING_READ) {
TRACE_EVENT_END("socket.read", this, StringPrintf("%d bytes", num_bytes));
} else {
TRACE_EVENT_END("socket.write", this, StringPrintf("%d bytes", num_bytes));
}
wait_state_ = NOT_WAITING;
DoCallback(ok ? num_bytes : MapWinsockError(WSAGetLastError()));
}
void TCPClientSocket::OnObjectSignaled(HANDLE object) {
DCHECK(object == overlapped_.hEvent);
switch (wait_state_) {
case WAITING_CONNECT:
DidCompleteConnect();
break;
case WAITING_READ:
case WAITING_WRITE:
DidCompleteIO();
break;
default:
NOTREACHED();
break;
}
}
} // namespace net
<|endoftext|> |
<commit_before>#include "lwtnn/Graph.hh"
#include "lwtnn/Exceptions.hh"
#include "lwtnn/Stack.hh"
namespace lwt {
// Sources
VectorSource::VectorSource(const std::vector<VectorXd>&& vv):
m_inputs(std::move(vv))
{
}
VectorXd VectorSource::at(size_t index) const {
if (index >= m_inputs.size()) {
throw NNEvaluationException(
"VectorSource: no source vector defined at " + std::to_string(index));
}
return m_inputs.at(index);
};
DummySource::DummySource(const std::vector<size_t>& input_sizes):
m_sizes(input_sizes)
{
}
VectorXd DummySource::at(size_t index) const {
if (index >= m_sizes.size()) {
throw NNEvaluationException(
"Dummy Source: no size defined at " + std::to_string(index));
}
size_t n_entries = m_sizes.at(index);
VectorXd vec(n_entries);
for (int iii = 0; iii < n_entries; iii++) {
vec(iii) = iii;
}
return vec;
}
// Nodes
InputNode::InputNode(size_t index, size_t n_outputs):
m_index(index),
m_n_outputs(n_outputs)
{
}
VectorXd InputNode::compute(const ISource& source) const {
VectorXd output = source.at(m_index);
if (output.rows() != m_n_outputs) {
std::string len = std::to_string(output.rows());
std::string found = std::to_string(m_n_outputs);
throw NNEvaluationException(
"Found vector of length " + len + ", expected " + found);
}
return output;
}
size_t InputNode::n_outputs() const {
return m_n_outputs;
}
FeedForwardNode::FeedForwardNode(const Stack* stack, const INode* source):
m_stack(stack),
m_source(source)
{
}
VectorXd FeedForwardNode::compute(const ISource& source) const {
return m_stack->compute(m_source->compute(source));
}
size_t FeedForwardNode::n_outputs() const {
return m_stack->n_outputs();
}
ConcatenateNode::ConcatenateNode(const std::vector<const INode*>& sources):
m_sources(sources),
m_n_outputs(0)
{
for (const auto source: sources) {
m_n_outputs += source->n_outputs();
}
}
VectorXd ConcatenateNode::compute(const ISource& source) const {
VectorXd output(m_n_outputs);
size_t offset = 0;
for (const auto node: m_sources) {
VectorXd input = node->compute(source);
size_t n_elements = input.rows();
assert(n_elements == node->n_outputs());
output.segment(offset, n_elements) = input;
offset += n_elements;
}
assert(offset = m_n_outputs);
return output;
}
size_t ConcatenateNode::n_outputs() const {
return m_n_outputs;
}
}
namespace {
using namespace lwt;
void throw_cfg(std::string msg, size_t index) {
throw NNConfigurationException(msg + " " + std::to_string(index));
}
void build_node(size_t iii,
const std::vector<Node>& nodes,
const std::vector<LayerConfig>& layers,
std::vector<INode*>& m_nodes,
std::vector<Stack*>& m_stacks,
std::map<size_t, INode*>& node_map,
std::map<size_t, Stack*>& stack_map) {
if (node_map.count(iii)) return;
if (iii >= nodes.size()) throw_cfg("no node index", iii);
const Node& node = nodes.at(iii);
// if it's an input, build and return
if (node.type == Node::Type::INPUT) {
m_nodes.push_back(new InputNode(node.index, node.size));
node_map[iii] = m_nodes.back();
return;
}
// otherwise build all the inputs first
for (size_t source_node: node.in_node_indices) {
build_node(source_node, nodes, layers,
m_nodes, m_stacks, node_map, stack_map);
}
// build feed forward layer
if (node.type == Node::Type::FEED_FORWARD) {
size_t layer_n = node.index;
if (layer_n >= layers.size()) throw_cfg("no layer number", layer_n);
size_t n_source = node.in_node_indices.size();
if (n_source != 1) throw_cfg("need one source, found", n_source);
INode* source = node_map.at(node.in_node_indices.at(0));
if (!stack_map.count(layer_n)) {
m_stacks.push_back(
new Stack(source->n_outputs(), {layers.at(layer_n)}));
stack_map[layer_n] = m_stacks.back();
}
m_nodes.push_back(new FeedForwardNode(stack_map.at(layer_n), source));
node_map[iii] = m_nodes.back();
return;
}
// build concatenate layer
if (node.type == Node::Type::CONCATENATE) {
std::vector<const INode*> in_nodes;
for (size_t source_node: node.in_node_indices) {
in_nodes.push_back(node_map.at(source_node));
}
m_nodes.push_back(new ConcatenateNode(in_nodes));
node_map[iii] = m_nodes.back();
return;
}
throw NNConfigurationException("unknown node type");
}
}
namespace lwt {
// graph
Graph::Graph() {
m_stacks.push_back(new Stack);
Stack* stack = m_stacks.back();
m_nodes.push_back(new InputNode(0, 2));
INode* source1 = m_nodes.back();
m_nodes.push_back(new InputNode(1, 2));
INode* source2 = m_nodes.back();
m_nodes.push_back(new ConcatenateNode({source1, source2}));
INode* cat = m_nodes.back();
m_nodes.push_back(new FeedForwardNode(stack, cat));
}
Graph::Graph(const std::vector<Node>& nodes,
const std::vector<LayerConfig>& layers) {
std::map<size_t, INode*> node_map;
std::map<size_t, Stack*> stack_map;
for (size_t iii = 0; iii < nodes.size(); iii++) {
build_node(iii, nodes, layers,
m_nodes, m_stacks,
node_map, stack_map);
}
assert(node_map.size() == nodes.size());
}
Graph::~Graph() {
for (auto node: m_nodes) {
delete node;
node = 0;
}
for (auto stack: m_stacks) {
delete stack;
stack = 0;
}
}
VectorXd Graph::compute(const ISource& source, size_t node_number) const {
if (node_number >= m_nodes.size()) {
throw NNEvaluationException(
"Graph: no node at " + std::to_string(node_number));
}
return m_nodes.at(node_number)->compute(source);
}
VectorXd Graph::compute(const ISource& source) const {
assert(m_nodes.size() > 0);
return m_nodes.back()->compute(source);
}
}
<commit_msg>Add cycle check to graph node builder<commit_after>#include "lwtnn/Graph.hh"
#include "lwtnn/Exceptions.hh"
#include "lwtnn/Stack.hh"
#include <set>
namespace lwt {
// Sources
VectorSource::VectorSource(const std::vector<VectorXd>&& vv):
m_inputs(std::move(vv))
{
}
VectorXd VectorSource::at(size_t index) const {
if (index >= m_inputs.size()) {
throw NNEvaluationException(
"VectorSource: no source vector defined at " + std::to_string(index));
}
return m_inputs.at(index);
};
DummySource::DummySource(const std::vector<size_t>& input_sizes):
m_sizes(input_sizes)
{
}
VectorXd DummySource::at(size_t index) const {
if (index >= m_sizes.size()) {
throw NNEvaluationException(
"Dummy Source: no size defined at " + std::to_string(index));
}
size_t n_entries = m_sizes.at(index);
VectorXd vec(n_entries);
for (int iii = 0; iii < n_entries; iii++) {
vec(iii) = iii;
}
return vec;
}
// Nodes
InputNode::InputNode(size_t index, size_t n_outputs):
m_index(index),
m_n_outputs(n_outputs)
{
}
VectorXd InputNode::compute(const ISource& source) const {
VectorXd output = source.at(m_index);
if (output.rows() != m_n_outputs) {
std::string len = std::to_string(output.rows());
std::string found = std::to_string(m_n_outputs);
throw NNEvaluationException(
"Found vector of length " + len + ", expected " + found);
}
return output;
}
size_t InputNode::n_outputs() const {
return m_n_outputs;
}
FeedForwardNode::FeedForwardNode(const Stack* stack, const INode* source):
m_stack(stack),
m_source(source)
{
}
VectorXd FeedForwardNode::compute(const ISource& source) const {
return m_stack->compute(m_source->compute(source));
}
size_t FeedForwardNode::n_outputs() const {
return m_stack->n_outputs();
}
ConcatenateNode::ConcatenateNode(const std::vector<const INode*>& sources):
m_sources(sources),
m_n_outputs(0)
{
for (const auto source: sources) {
m_n_outputs += source->n_outputs();
}
}
VectorXd ConcatenateNode::compute(const ISource& source) const {
VectorXd output(m_n_outputs);
size_t offset = 0;
for (const auto node: m_sources) {
VectorXd input = node->compute(source);
size_t n_elements = input.rows();
assert(n_elements == node->n_outputs());
output.segment(offset, n_elements) = input;
offset += n_elements;
}
assert(offset = m_n_outputs);
return output;
}
size_t ConcatenateNode::n_outputs() const {
return m_n_outputs;
}
}
namespace {
using namespace lwt;
void throw_cfg(std::string msg, size_t index) {
throw NNConfigurationException(msg + " " + std::to_string(index));
}
void build_node(size_t iii,
const std::vector<Node>& nodes,
const std::vector<LayerConfig>& layers,
std::vector<INode*>& m_nodes,
std::vector<Stack*>& m_stacks,
std::map<size_t, INode*>& node_map,
std::map<size_t, Stack*>& stack_map,
std::set<size_t> cycle_check = {}) {
if (node_map.count(iii)) return;
if (iii >= nodes.size()) throw_cfg("no node index", iii);
const Node& node = nodes.at(iii);
// if it's an input, build and return
if (node.type == Node::Type::INPUT) {
m_nodes.push_back(new InputNode(node.index, node.size));
node_map[iii] = m_nodes.back();
return;
}
// otherwise build all the inputs first
if (cycle_check.count(iii)) {
throw NNConfigurationException("found cycle in graph");
}
cycle_check.insert(iii);
for (size_t source_node: node.in_node_indices) {
build_node(source_node, nodes, layers,
m_nodes, m_stacks, node_map, stack_map, cycle_check);
}
// build feed forward layer
if (node.type == Node::Type::FEED_FORWARD) {
size_t layer_n = node.index;
if (layer_n >= layers.size()) throw_cfg("no layer number", layer_n);
size_t n_source = node.in_node_indices.size();
if (n_source != 1) throw_cfg("need one source, found", n_source);
INode* source = node_map.at(node.in_node_indices.at(0));
if (!stack_map.count(layer_n)) {
m_stacks.push_back(
new Stack(source->n_outputs(), {layers.at(layer_n)}));
stack_map[layer_n] = m_stacks.back();
}
m_nodes.push_back(new FeedForwardNode(stack_map.at(layer_n), source));
node_map[iii] = m_nodes.back();
return;
}
// build concatenate layer
if (node.type == Node::Type::CONCATENATE) {
std::vector<const INode*> in_nodes;
for (size_t source_node: node.in_node_indices) {
in_nodes.push_back(node_map.at(source_node));
}
m_nodes.push_back(new ConcatenateNode(in_nodes));
node_map[iii] = m_nodes.back();
return;
}
throw NNConfigurationException("unknown node type");
}
}
namespace lwt {
// graph
Graph::Graph() {
m_stacks.push_back(new Stack);
Stack* stack = m_stacks.back();
m_nodes.push_back(new InputNode(0, 2));
INode* source1 = m_nodes.back();
m_nodes.push_back(new InputNode(1, 2));
INode* source2 = m_nodes.back();
m_nodes.push_back(new ConcatenateNode({source1, source2}));
INode* cat = m_nodes.back();
m_nodes.push_back(new FeedForwardNode(stack, cat));
}
Graph::Graph(const std::vector<Node>& nodes,
const std::vector<LayerConfig>& layers) {
std::map<size_t, INode*> node_map;
std::map<size_t, Stack*> stack_map;
for (size_t iii = 0; iii < nodes.size(); iii++) {
build_node(iii, nodes, layers,
m_nodes, m_stacks,
node_map, stack_map);
}
assert(node_map.size() == nodes.size());
}
Graph::~Graph() {
for (auto node: m_nodes) {
delete node;
node = 0;
}
for (auto stack: m_stacks) {
delete stack;
stack = 0;
}
}
VectorXd Graph::compute(const ISource& source, size_t node_number) const {
if (node_number >= m_nodes.size()) {
throw NNEvaluationException(
"Graph: no node at " + std::to_string(node_number));
}
return m_nodes.at(node_number)->compute(source);
}
VectorXd Graph::compute(const ISource& source) const {
assert(m_nodes.size() > 0);
return m_nodes.back()->compute(source);
}
}
<|endoftext|> |
<commit_before>#include"../header/IQBit.hpp"
#include<ostream>
using namespace std;
namespace nQCircuit
{
IQBit::~IQBit(){}
ostream& operator<<(ostream &os,const IQBit &val)
{
return val.print(os);
}
ostream& Q_empty_bit::print(ostream &os) const
{
return os<<"q";
}
ostream& Q_not_bit::print(ostream &os) const
{
return os<<"";
}
ostream& Q_controlled_not_bit::print(ostream &os) const
{
return os<<"";
}
ostream& Q_white_controlled_not_bit::print(ostream &os) const
{
return os<<"";
}
//this is an example to help you understand how to use IQBit correctly
//bool Q_or_bit::is_valid(const CQGate &gate,const std::vector<Boolean> &bit,size_t subscript) const
//{
// for(size_t i{0};i!=gate.gate_size();++i)
// if(gate[i]->info()==QBIT::OR&&bit[i])
// return true;
// return false;
//}
}<commit_msg>fix output message<commit_after>#include"../header/IQBit.hpp"
#include<ostream>
using namespace std;
namespace nQCircuit
{
IQBit::~IQBit()=default;
ostream& operator<<(ostream &os,const IQBit &val)
{
return val.print(os);
}
ostream& Q_empty_bit::print(ostream &os) const
{
return os<<"\u253c";
}
ostream& Q_not_bit::print(ostream &os) const
{
return os<<"\u2295";
}
ostream& Q_controlled_not_bit::print(ostream &os) const
{
return os<<"\u25cf";
}
ostream& Q_white_controlled_not_bit::print(ostream &os) const
{
return os<<"\u25cb";
}
//this is an example to help you understand how to use IQBit correctly
//bool Q_or_bit::is_valid(const CQGate &gate,const std::vector<Boolean> &bit,size_t subscript) const
//{
// for(size_t i{0};i!=gate.gate_size();++i)
// if(gate[i]->info()==QBIT::OR&&bit[i])
// return true;
// return false;
//}
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
//--- standard modules used ----------------------------------------------------
#include "AppBooter.h"
//--- c-library modules used ---------------------------------------------------
//---- main ----
int main(int argc, const char *argv[])
{
int result = AppBooter().Run(argc, argv);
return result;
}
<commit_msg>added setting of default locale<commit_after>/*
* Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
//--- standard modules used ----------------------------------------------------
#include "AppBooter.h"
#include <locale>
//--- c-library modules used ---------------------------------------------------
//---- main ----
int main(int argc, const char *argv[])
{
// initialize locale aspects to default locale -> 'C'
std::locale::global(std::locale::classic());
int result = AppBooter().Run(argc, argv);
return result;
}
<|endoftext|> |
<commit_before>#include "Common.h"
#include "Input.h"
#include "Window.h"
//#include <CEGUI/System.h>
//#include <CEGUI/GUIContext.h>
//#include <CEGUI/InjectedInputReceiver.h>
Input :: Input(Window* window):
m_pWindow(window)
{
m_DummySwitch.make_dummy();
m_bRelMouse = !m_bRelMouse; // undo initial state
relative_mouse(!m_bRelMouse); // redo initial state change
//SDL_SetRelativeMouseMode(SDL_TRUE);
//SDL_SetWindowGrab(SDL_GL_GetCurrentWindow(), SDL_TRUE);
for(unsigned i=0; i<SDL_NumJoysticks(); ++i)
{
m_Joysticks.push_back(SDL_JoystickOpen(i));
}
SDL_JoystickEventState(SDL_ENABLE);
}
Input :: ~Input()
{
for(auto*& j: m_Joysticks)
{
SDL_JoystickClose(j);
j = nullptr;
}
m_Joysticks.clear();
}
void Input :: Switch :: trigger()
{
// TODO: add flag to method for overwriting history or modifying front?
m_Records.push_back(Record());
//m_Records.emplace_back();
for(auto& c: m_Controllers)
if(!c.expired())
{
auto s = c.lock();
if(s)
s->trigger();
else
c.reset();
}
}
void Input :: logic(Freq::Time t)
{
SDL_Event ev;
//auto& gui = CEGUI::System::getSingleton().getDefaultGUIContext();
//CEGUI::System::getSingleton().injectTimePulse(t.s());
//gui.injectTimePulse(t.s());
m_MouseRel = glm::ivec2();
while(SDL_PollEvent(&ev))
{
switch(ev.type)
{
case SDL_QUIT:
m_bQuit = true;
break;
case SDL_WINDOWEVENT:
if(ev.window.event == SDL_WINDOWEVENT_RESIZED)
m_pWindow->on_resize(glm::ivec2(ev.window.data1, ev.window.data2));
break;
case SDL_KEYDOWN:
m_Devices[KEYBOARD][0][ev.key.keysym.sym] = true;
//gui.injectKeyDown((CEGUI::Key::Scan)ev.key.keysym.scancode);
break;
case SDL_KEYUP:
m_Devices[KEYBOARD][0][ev.key.keysym.sym] = false;
//gui.injectKeyUp((CEGUI::Key::Scan)ev.key.keysym.scancode);
break;
case SDL_DROPFILE:
// string fn = ev.drop.file;
// SDL_free(ev.drop.file);
break;
case SDL_JOYHATMOTION:
{
// 8 bits for hat id, 4 bits for each direction
// yes, we could store dirs in just 2 bits, but they wouldn't
// have button-compatible mappings
// direction bits are stored in this order:
// 0 - left
// 1 - right
// 2 - up
// 3 - down
//unsigned id = (1<<12) + (unsigned(ev.jhat.hat) << 4);
unsigned id = gamepad_hat_id(ev.jhat.hat << 4);
//if(ev.jhat.value == SDL_HAT_CENTERED)
//{
//// centering invalidates all other directions
//for(unsigned i=0; i<4; ++i) {
// auto& dir = m_Devices[GAMEPAD][ev.jhat.which][id+i];
// if(dir) dir = false;
//}
//}
//else
//{
//LOGf("gamepad%s %s = %s", int(ev.jhat.which) % id % unsigned(ev.jhat.value));
auto& left = m_Devices[GAMEPAD][ev.jhat.which][id];
auto& right = m_Devices[GAMEPAD][ev.jhat.which][id+1];
auto& up = m_Devices[GAMEPAD][ev.jhat.which][id+2];
auto& down = m_Devices[GAMEPAD][ev.jhat.which][id+3];
if(ev.jhat.value & SDL_HAT_LEFT)
left = true;
else if(left)
left = false;
if(ev.jhat.value & SDL_HAT_RIGHT)
right = true;
else if(right)
right = false;
if(ev.jhat.value & SDL_HAT_UP)
up = true;
else if(up)
up = false;
if(ev.jhat.value & SDL_HAT_DOWN)
down = true;
else if(down)
down = false;
//}
break;
}
case SDL_JOYAXISMOTION:
{
float val = (((int)ev.jaxis.value + 32768) + 0.5f) / 32767.0f - 1.0f;
unsigned id = gamepad_analog_id(ev.jaxis.axis << 1);
if(val >= 0.0f)
{
//LOGf("pressure: %s", val);
m_Devices[GAMEPAD][ev.jaxis.which][id] = false;
m_Devices[GAMEPAD][ev.jaxis.which][id+1].pressure(val);
}
else
{
//LOGf("pressure: %s", -val);
m_Devices[GAMEPAD][ev.jaxis.which][id].pressure(-val);
m_Devices[GAMEPAD][ev.jaxis.which][id+1] = false;
}
break;
}
case SDL_JOYBUTTONDOWN:
//LOGf("gamepad%s %s", int(ev.jbutton.which) % int(ev.jbutton.button))
m_Devices[GAMEPAD][ev.jbutton.which][ev.jbutton.button] = true;
break;
case SDL_JOYBUTTONUP:
m_Devices[GAMEPAD][ev.jbutton.which][ev.jbutton.button] = false;
break;
case SDL_TEXTINPUT:
{
unsigned idx=0;
//while(ev.text.text[idx++])
//gui.injectChar(ev.text.text[idx]);
break;
}
case SDL_MOUSEMOTION:
if(m_bRelMouse)
m_MouseRel += glm::vec2(ev.motion.xrel, ev.motion.yrel);
else
m_MouseRel = m_MousePos;
m_MousePos = glm::vec2(ev.motion.x, -ev.motion.y);
if(!m_bRelMouse)
m_MouseRel = m_MousePos - m_MouseRel; // simulate mouse rel
//gui.injectMousePosition(
// static_cast<float>(ev.motion.x),
// static_cast<float>(ev.motion.y)
//);
break;
case SDL_MOUSEBUTTONDOWN:
{
if(ev.button.button == SDL_BUTTON_LEFT) {
m_Devices[MOUSE][0][0] = true;
//gui.injectMouseButtonDown(CEGUI::MouseButton::LeftButton);
}
else if(ev.button.button == SDL_BUTTON_RIGHT){
m_Devices[MOUSE][0][1] = true;
//gui.injectMouseButtonDown(CEGUI::MouseButton::RightButton);
}
else if(ev.button.button == SDL_BUTTON_MIDDLE){
m_Devices[MOUSE][0][2] = true;
//gui.injectMouseButtonDown(CEGUI::MouseButton::MiddleButton);
}
break;
}
case SDL_MOUSEBUTTONUP:
{
if(ev.button.button == SDL_BUTTON_LEFT){
m_Devices[MOUSE][0][0] = false;
//gui.injectMouseButtonUp(CEGUI::MouseButton::LeftButton);
}
else if(ev.button.button == SDL_BUTTON_RIGHT){
m_Devices[MOUSE][0][1] = false;
//gui.injectMouseButtonUp(CEGUI::MouseButton::RightButton);
}
else if(ev.button.button == SDL_BUTTON_MIDDLE){
m_Devices[MOUSE][0][2] = false;
//gui.injectMouseButtonUp(CEGUI::MouseButton::MiddleButton);
}
break;
}
//case SDL_WINDOWEVENT_RESIZED:
// break;
}
}
for(auto& types: m_Devices)
for(auto& devs: types.second)
for(auto& c: devs.second)
c.second.logic(t);
//for(auto& c: m_Mouse)
// c.second.logic(t);
//for(auto& c: m_Devices[KEYBOARD][0])
// c.second.logic(t);
for(auto& c: m_Controllers)
{
if(c.second->triggered())
{
c.second->event();
c.second->untrigger();
}
c.second->logic(t);
}
if(m_bRelMouse)
SDL_WarpMouseInWindow(
m_pWindow->sdl_window(),
m_pWindow->center().x/2,
m_pWindow->center().y/2
);
}
unsigned int Input :: bind(
std::string s,
const std::shared_ptr<Controller>& controller
){
// first token might be device name
// if not, device is keyboard
std::string device = s.substr(0,s.find(' '));
if(device == "mouse")
{
std::string button = s.substr(device.length()+1);
button = button.substr(0, button.find(' '));
unsigned id = 0;
if(button == "left")
id = 0;
else if(button == "right")
id = 1;
else if(button == "middle")
id = 2;
else
{
// use number
id = boost::lexical_cast<unsigned>(button);
}
m_Binds.push_back(Bind(MOUSE, 0, id));
m_Devices[MOUSE][0][id].plug(controller);
}
else if(device == "gamepad")
{
bool analog = false;
bool hat = false;
std::string button = s.substr(device.length()+1);
if(boost::starts_with(button,"analog")){
LOG("analog");
analog = true;
button = button.substr(strlen("analog")+1);
}else if(boost::starts_with(button,"hat")){
LOG("hat");
hat = true;
button = button.substr(strlen("hat")+1);
}
LOGf("button %s", button);
unsigned id = boost::lexical_cast<unsigned>(button);
if(analog) id = Input::gamepad_analog_id(id);
if(hat) id = Input::gamepad_hat_id(id);
m_Binds.push_back(Bind(GAMEPAD, 0, id));
m_Devices[GAMEPAD][0][id].plug(controller);
}
else
{
unsigned int id = SDL_GetKeyFromName(s.c_str());
if(id == SDLK_UNKNOWN)
ERRORf(ACTION, "bind key %s", s)
m_Binds.push_back(id);
m_Devices[KEYBOARD][0][id].plug(controller);
}
return m_Binds.size()-1;
}
unsigned Input :: gamepad_analog_id(unsigned id)
{
return (1<<12) + id;
}
unsigned Input :: gamepad_hat_id(unsigned id)
{
return (1<<16) + id;
}
void Controller :: rumble(float magnitude, Freq::Time t)
{
// TODO: add rumble support
// http://wiki.libsdl.org/moin.cgi/CategoryForceFeedback
//SDL_HapticRumblePlay(m_pHaptic, magnitude, t.ms());
}
<commit_msg>removed some logging<commit_after>#include "Common.h"
#include "Input.h"
#include "Window.h"
//#include <CEGUI/System.h>
//#include <CEGUI/GUIContext.h>
//#include <CEGUI/InjectedInputReceiver.h>
Input :: Input(Window* window):
m_pWindow(window)
{
m_DummySwitch.make_dummy();
m_bRelMouse = !m_bRelMouse; // undo initial state
relative_mouse(!m_bRelMouse); // redo initial state change
//SDL_SetRelativeMouseMode(SDL_TRUE);
//SDL_SetWindowGrab(SDL_GL_GetCurrentWindow(), SDL_TRUE);
for(unsigned i=0; i<SDL_NumJoysticks(); ++i)
{
m_Joysticks.push_back(SDL_JoystickOpen(i));
}
SDL_JoystickEventState(SDL_ENABLE);
}
Input :: ~Input()
{
for(auto*& j: m_Joysticks)
{
SDL_JoystickClose(j);
j = nullptr;
}
m_Joysticks.clear();
}
void Input :: Switch :: trigger()
{
// TODO: add flag to method for overwriting history or modifying front?
m_Records.push_back(Record());
//m_Records.emplace_back();
for(auto& c: m_Controllers)
if(!c.expired())
{
auto s = c.lock();
if(s)
s->trigger();
else
c.reset();
}
}
void Input :: logic(Freq::Time t)
{
SDL_Event ev;
//auto& gui = CEGUI::System::getSingleton().getDefaultGUIContext();
//CEGUI::System::getSingleton().injectTimePulse(t.s());
//gui.injectTimePulse(t.s());
m_MouseRel = glm::ivec2();
while(SDL_PollEvent(&ev))
{
switch(ev.type)
{
case SDL_QUIT:
m_bQuit = true;
break;
case SDL_WINDOWEVENT:
if(ev.window.event == SDL_WINDOWEVENT_RESIZED)
m_pWindow->on_resize(glm::ivec2(ev.window.data1, ev.window.data2));
break;
case SDL_KEYDOWN:
m_Devices[KEYBOARD][0][ev.key.keysym.sym] = true;
//gui.injectKeyDown((CEGUI::Key::Scan)ev.key.keysym.scancode);
break;
case SDL_KEYUP:
m_Devices[KEYBOARD][0][ev.key.keysym.sym] = false;
//gui.injectKeyUp((CEGUI::Key::Scan)ev.key.keysym.scancode);
break;
case SDL_DROPFILE:
// string fn = ev.drop.file;
// SDL_free(ev.drop.file);
break;
case SDL_JOYHATMOTION:
{
// 8 bits for hat id, 4 bits for each direction
// yes, we could store dirs in just 2 bits, but they wouldn't
// have button-compatible mappings
// direction bits are stored in this order:
// 0 - left
// 1 - right
// 2 - up
// 3 - down
//unsigned id = (1<<12) + (unsigned(ev.jhat.hat) << 4);
unsigned id = gamepad_hat_id(ev.jhat.hat << 4);
//if(ev.jhat.value == SDL_HAT_CENTERED)
//{
//// centering invalidates all other directions
//for(unsigned i=0; i<4; ++i) {
// auto& dir = m_Devices[GAMEPAD][ev.jhat.which][id+i];
// if(dir) dir = false;
//}
//}
//else
//{
//LOGf("gamepad%s %s = %s", int(ev.jhat.which) % id % unsigned(ev.jhat.value));
auto& left = m_Devices[GAMEPAD][ev.jhat.which][id];
auto& right = m_Devices[GAMEPAD][ev.jhat.which][id+1];
auto& up = m_Devices[GAMEPAD][ev.jhat.which][id+2];
auto& down = m_Devices[GAMEPAD][ev.jhat.which][id+3];
if(ev.jhat.value & SDL_HAT_LEFT)
left = true;
else if(left)
left = false;
if(ev.jhat.value & SDL_HAT_RIGHT)
right = true;
else if(right)
right = false;
if(ev.jhat.value & SDL_HAT_UP)
up = true;
else if(up)
up = false;
if(ev.jhat.value & SDL_HAT_DOWN)
down = true;
else if(down)
down = false;
//}
break;
}
case SDL_JOYAXISMOTION:
{
float val = (((int)ev.jaxis.value + 32768) + 0.5f) / 32767.0f - 1.0f;
unsigned id = gamepad_analog_id(ev.jaxis.axis << 1);
if(val >= 0.0f)
{
//LOGf("pressure: %s", val);
m_Devices[GAMEPAD][ev.jaxis.which][id] = false;
m_Devices[GAMEPAD][ev.jaxis.which][id+1].pressure(val);
}
else
{
//LOGf("pressure: %s", -val);
m_Devices[GAMEPAD][ev.jaxis.which][id].pressure(-val);
m_Devices[GAMEPAD][ev.jaxis.which][id+1] = false;
}
break;
}
case SDL_JOYBUTTONDOWN:
//LOGf("gamepad%s %s", int(ev.jbutton.which) % int(ev.jbutton.button))
m_Devices[GAMEPAD][ev.jbutton.which][ev.jbutton.button] = true;
break;
case SDL_JOYBUTTONUP:
m_Devices[GAMEPAD][ev.jbutton.which][ev.jbutton.button] = false;
break;
case SDL_TEXTINPUT:
{
unsigned idx=0;
//while(ev.text.text[idx++])
//gui.injectChar(ev.text.text[idx]);
break;
}
case SDL_MOUSEMOTION:
if(m_bRelMouse)
m_MouseRel += glm::vec2(ev.motion.xrel, ev.motion.yrel);
else
m_MouseRel = m_MousePos;
m_MousePos = glm::vec2(ev.motion.x, -ev.motion.y);
if(!m_bRelMouse)
m_MouseRel = m_MousePos - m_MouseRel; // simulate mouse rel
//gui.injectMousePosition(
// static_cast<float>(ev.motion.x),
// static_cast<float>(ev.motion.y)
//);
break;
case SDL_MOUSEBUTTONDOWN:
{
if(ev.button.button == SDL_BUTTON_LEFT) {
m_Devices[MOUSE][0][0] = true;
//gui.injectMouseButtonDown(CEGUI::MouseButton::LeftButton);
}
else if(ev.button.button == SDL_BUTTON_RIGHT){
m_Devices[MOUSE][0][1] = true;
//gui.injectMouseButtonDown(CEGUI::MouseButton::RightButton);
}
else if(ev.button.button == SDL_BUTTON_MIDDLE){
m_Devices[MOUSE][0][2] = true;
//gui.injectMouseButtonDown(CEGUI::MouseButton::MiddleButton);
}
break;
}
case SDL_MOUSEBUTTONUP:
{
if(ev.button.button == SDL_BUTTON_LEFT){
m_Devices[MOUSE][0][0] = false;
//gui.injectMouseButtonUp(CEGUI::MouseButton::LeftButton);
}
else if(ev.button.button == SDL_BUTTON_RIGHT){
m_Devices[MOUSE][0][1] = false;
//gui.injectMouseButtonUp(CEGUI::MouseButton::RightButton);
}
else if(ev.button.button == SDL_BUTTON_MIDDLE){
m_Devices[MOUSE][0][2] = false;
//gui.injectMouseButtonUp(CEGUI::MouseButton::MiddleButton);
}
break;
}
//case SDL_WINDOWEVENT_RESIZED:
// break;
}
}
for(auto& types: m_Devices)
for(auto& devs: types.second)
for(auto& c: devs.second)
c.second.logic(t);
//for(auto& c: m_Mouse)
// c.second.logic(t);
//for(auto& c: m_Devices[KEYBOARD][0])
// c.second.logic(t);
for(auto& c: m_Controllers)
{
if(c.second->triggered())
{
c.second->event();
c.second->untrigger();
}
c.second->logic(t);
}
if(m_bRelMouse)
SDL_WarpMouseInWindow(
m_pWindow->sdl_window(),
m_pWindow->center().x/2,
m_pWindow->center().y/2
);
}
unsigned int Input :: bind(
std::string s,
const std::shared_ptr<Controller>& controller
){
// first token might be device name
// if not, device is keyboard
std::string device = s.substr(0,s.find(' '));
if(device == "mouse")
{
std::string button = s.substr(device.length()+1);
button = button.substr(0, button.find(' '));
unsigned id = 0;
if(button == "left")
id = 0;
else if(button == "right")
id = 1;
else if(button == "middle")
id = 2;
else
{
// use number
id = boost::lexical_cast<unsigned>(button);
}
m_Binds.push_back(Bind(MOUSE, 0, id));
m_Devices[MOUSE][0][id].plug(controller);
}
else if(device == "gamepad")
{
bool analog = false;
bool hat = false;
std::string button = s.substr(device.length()+1);
if(boost::starts_with(button,"analog")){
//LOG("analog");
analog = true;
button = button.substr(strlen("analog")+1);
}else if(boost::starts_with(button,"hat")){
//LOG("hat");
hat = true;
button = button.substr(strlen("hat")+1);
}
//LOGf("button %s", button);
unsigned id = boost::lexical_cast<unsigned>(button);
if(analog) id = Input::gamepad_analog_id(id);
if(hat) id = Input::gamepad_hat_id(id);
m_Binds.push_back(Bind(GAMEPAD, 0, id));
m_Devices[GAMEPAD][0][id].plug(controller);
}
else
{
unsigned int id = SDL_GetKeyFromName(s.c_str());
if(id == SDLK_UNKNOWN)
ERRORf(ACTION, "bind key %s", s)
m_Binds.push_back(id);
m_Devices[KEYBOARD][0][id].plug(controller);
}
return m_Binds.size()-1;
}
unsigned Input :: gamepad_analog_id(unsigned id)
{
return (1<<12) + id;
}
unsigned Input :: gamepad_hat_id(unsigned id)
{
return (1<<16) + id;
}
void Controller :: rumble(float magnitude, Freq::Time t)
{
// TODO: add rumble support
// http://wiki.libsdl.org/moin.cgi/CategoryForceFeedback
//SDL_HapticRumblePlay(m_pHaptic, magnitude, t.ms());
}
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
bool two(int number){
if (number % 2 != 0 || number == 2)
return false;
return true;
}
int main(){
int n;
cin >> n;
if (two(n))
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
<commit_msg>Refatorando método.<commit_after>#include <iostream>
using namespace std;
bool two(int number){
return number % 2 == 0 || number != 2;
}
int main(){
int n;
cin >> n;
if (two(n))
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
<|endoftext|> |
<commit_before>#include "Level.h"
#include <OgreManualObject.h>
#include <OgreRenderOperation.h>
#include <iostream>
using namespace std;
#include "PolyVox/SurfaceExtractor.h"
#include "PolyVox/SurfaceMesh.h"
using namespace PolyVox;
#include "SurfacePatchRenderable.h"
#include "Burrower.h"
#include "VoxelVolume.h"
Level::Level(Ogre::SceneManager* manager)
: mSceneManager(manager),
mBaseLevelNode(0),
mVolume(0)
{
}
void Level::generate() {
clearExisting();
mBaseLevelNode = mSceneManager->getRootSceneNode()->createChildSceneNode("VoxelLevel");
createVoxelVolume();
buildRenderable();
}
void Level::clearExisting() {
if(mVolume) {
delete mVolume;
mVolume = 0;
}
if(mBaseLevelNode) {
mSceneManager->destroySceneNode("VoxelLevel");
mBaseLevelNode = 0;
}
mSceneManager->destroyMovableObject("VoxelRenderable",
SurfacePatchRenderableFactory::FACTORY_TYPE_NAME);
}
/**
* The following is taken from various parts of PolyVox
* and the Thermite3D engine.
*/
void Level::createVoxelVolume() {
mVolume = new VoxelVolume(128, 32, 128, 0);
Burrower burrower(mVolume);
int depth = mVolume->getDepth(),
width = mVolume->getWidth(),
height = mVolume->getHeight();
Voxel voxel;
uint8_t density = Voxel::getMaxDensity();
// TODO FIXME
// Need to find out how I can default the volume
// to be full. For now, fill the volume for the
// burrower
for(int x = 0; x < width; x++) {
for(int y = 0; y < height; y++) {
for(int z = 0; z < depth; z++) {
//Get the old voxel
voxel = mVolume->getVoxelAt(x,y,z);
voxel.setDensity(density);
//Wrte the voxel value into the volume
mVolume->setVoxelAt(x, y, z, voxel);
}
}
}
// Start the burrower half way in the field
burrower.burrow(4, 4);
}
/*
void createSphere() {
int radius = 10;
//This vector hold the position of the center of the volume
Vector3DFloat volumeCenter(mVolume->getWidth() / 2, mVolume->getHeight() / 2, mVolume->getDepth() / 2);
//This three-level for loop iterates over every voxel in the volume
for (int z = 0; z < mVolume->getWidth(); z++)
{
for (int y = 0; y < mVolume->getHeight(); y++)
{
for (int x = 0; x < mVolume->getDepth(); x++)
{
//Store our current position as a vector...
Vector3DFloat currentPos(x,y,z);
//And compute how far the current position is from the center of the volume
float distToCenter = (currentPos - volumeCenter).length();
//If the current voxel is less than 'radius' units from the center then we make it solid.
if(distToCenter <= radius)
{
//Our new density value
uint8_t density = MaterialDensityPair44::getMaxDensity();
//Get the old voxel
MaterialDensityPair44 voxel = mVolume->getVoxelAt(x,y,z);
//Modify the density
voxel.setDensity(density);
//Wrte the voxel value into the volume
mVolume->setVoxelAt(x, y, z, voxel);
}
}
}
}
}
*/
void Level::buildRenderable() {
// Extract the data to build our render node
SurfaceMesh mesh;
SurfaceExtractor<Voxel> extractor(mVolume, mVolume->getEnclosingRegion(), &mesh);
extractor.execute();
SurfacePatchRenderable* renderable = dynamic_cast<SurfacePatchRenderable*>(
mSceneManager->createMovableObject("VoxelRenderable", SurfacePatchRenderableFactory::FACTORY_TYPE_NAME));
renderable->setMaterial("BaseWhiteNoLighting");
mBaseLevelNode->attachObject(renderable);
renderable->buildRenderOperationFrom(mesh, true);
mBaseLevelNode->setPosition(0.0f, 0.0f, 0.0f);
mBaseLevelNode->setScale(100, 100, 100);
}
<commit_msg>Flip the whole thing so the coordinates make sense<commit_after>#include "Level.h"
#include <OgreManualObject.h>
#include <OgreRenderOperation.h>
#include <iostream>
using namespace std;
#include "PolyVox/SurfaceExtractor.h"
#include "PolyVox/SurfaceMesh.h"
using namespace PolyVox;
#include "SurfacePatchRenderable.h"
#include "Burrower.h"
#include "VoxelVolume.h"
Level::Level(Ogre::SceneManager* manager)
: mSceneManager(manager),
mBaseLevelNode(0),
mVolume(0)
{
}
void Level::generate() {
clearExisting();
mBaseLevelNode = mSceneManager->getRootSceneNode()->createChildSceneNode("VoxelLevel");
createVoxelVolume();
buildRenderable();
}
void Level::clearExisting() {
if(mVolume) {
delete mVolume;
mVolume = 0;
}
if(mBaseLevelNode) {
mSceneManager->destroySceneNode("VoxelLevel");
mBaseLevelNode = 0;
}
mSceneManager->destroyMovableObject("VoxelRenderable",
SurfacePatchRenderableFactory::FACTORY_TYPE_NAME);
}
/**
* The following is taken from various parts of PolyVox
* and the Thermite3D engine.
*/
void Level::createVoxelVolume() {
mVolume = new VoxelVolume(128, 32, 128, 0);
Burrower burrower(mVolume);
int depth = mVolume->getDepth(),
width = mVolume->getWidth(),
height = mVolume->getHeight();
Voxel voxel;
uint8_t density = Voxel::getMaxDensity();
// TODO FIXME
// Need to find out how I can default the volume
// to be full. For now, fill the volume for the
// burrower
for(int x = 0; x < width; x++) {
for(int y = 0; y < height; y++) {
for(int z = 0; z < depth; z++) {
//Get the old voxel
voxel = mVolume->getVoxelAt(x,y,z);
voxel.setDensity(density);
//Wrte the voxel value into the volume
mVolume->setVoxelAt(x, y, z, voxel);
}
}
}
// Start the burrower half way in the field
burrower.burrow(4, 4);
}
/*
void createSphere() {
int radius = 10;
//This vector hold the position of the center of the volume
Vector3DFloat volumeCenter(mVolume->getWidth() / 2, mVolume->getHeight() / 2, mVolume->getDepth() / 2);
//This three-level for loop iterates over every voxel in the volume
for (int z = 0; z < mVolume->getWidth(); z++)
{
for (int y = 0; y < mVolume->getHeight(); y++)
{
for (int x = 0; x < mVolume->getDepth(); x++)
{
//Store our current position as a vector...
Vector3DFloat currentPos(x,y,z);
//And compute how far the current position is from the center of the volume
float distToCenter = (currentPos - volumeCenter).length();
//If the current voxel is less than 'radius' units from the center then we make it solid.
if(distToCenter <= radius)
{
//Our new density value
uint8_t density = MaterialDensityPair44::getMaxDensity();
//Get the old voxel
MaterialDensityPair44 voxel = mVolume->getVoxelAt(x,y,z);
//Modify the density
voxel.setDensity(density);
//Wrte the voxel value into the volume
mVolume->setVoxelAt(x, y, z, voxel);
}
}
}
}
}
*/
void Level::buildRenderable() {
// Extract the data to build our render node
SurfaceMesh mesh;
SurfaceExtractor<Voxel> extractor(mVolume, mVolume->getEnclosingRegion(), &mesh);
extractor.execute();
SurfacePatchRenderable* renderable = dynamic_cast<SurfacePatchRenderable*>(
mSceneManager->createMovableObject("VoxelRenderable", SurfacePatchRenderableFactory::FACTORY_TYPE_NAME));
renderable->setMaterial("BaseWhiteNoLighting");
mBaseLevelNode->attachObject(renderable);
renderable->buildRenderOperationFrom(mesh, true);
mBaseLevelNode->setPosition(0.0f, 0.0f, 0.0f);
mBaseLevelNode->setScale(-100, -100, -100);
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.