text
stringlengths 54
60.6k
|
|---|
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Razor team
* Authors:
* Alexander Sokoloff <sokoloff.a@gmail.com>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "razorcpuload.h"
#include "razorcpuloadconfiguration.h"
#include <QtCore>
#include <QPainter>
#include <QLinearGradient>
extern "C" {
#include <statgrab.h>
}
EXPORT_RAZOR_PANEL_PLUGIN_CPP(RazorCpuLoad)
RazorCpuLoad::RazorCpuLoad(const RazorPanelPluginStartInfo* startInfo, QWidget* parent):
RazorPanelPlugin(startInfo, parent),
m_showText(false)
{
setObjectName("CpuLoad");
addWidget(&m_stuff);
/* Initialise statgrab */
sg_init();
/* Drop setuid/setgid privileges. */
if (sg_drop_privileges() != 0) {
perror("Error. Failed to drop privileges");
}
m_font.setPointSizeF(8);
startTimer(500);
settigsChanged();
}
RazorCpuLoad::~RazorCpuLoad()
{
}
void RazorCpuLoad::resizeEvent(QResizeEvent *)
{
if( panel()->isHorizontal() )
{
m_stuff.setMinimumWidth(m_stuff.height() * 0.5);
m_stuff.setMinimumHeight(0);
} else
{
m_stuff.setMinimumHeight(m_stuff.width() * 2.0);
m_stuff.setMinimumWidth(0);
}
update();
}
double RazorCpuLoad::getLoadCpu() const
{
sg_cpu_percents* cur = sg_get_cpu_percents();
return (cur->user + cur->kernel + cur->nice);
}
void RazorCpuLoad::timerEvent(QTimerEvent *event)
{
double avg = getLoadCpu();
if ( qAbs(m_avg-avg)>1 )
{
m_avg = avg;
setToolTip(tr("Cpu load %1%").arg(m_avg));
update();
}
}
void RazorCpuLoad::paintEvent ( QPaintEvent * )
{
QPainter p(this);
QPen pen;
pen.setWidth(2);
p.setPen(pen);
p.setRenderHint(QPainter::Antialiasing, true);
p.setFont(m_font);
QLinearGradient shade(0, 0, width(), 0);
shade.setSpread(QLinearGradient::ReflectSpread);
shade.setColorAt(0, QColor(0, 196, 0, 128));
shade.setColorAt(0.5, QColor(0, 128, 0, 255) );
shade.setColorAt(1, QColor(0, 196, 0 , 128));
QRectF r = rect();
float o = r.height()*(1-m_avg*0.01);
QRectF r1(r.left(), r.top()+o, r.width(), r.height()-o );
p.fillRect(r1, shade);
if( m_showText )
p.drawText(rect(), Qt::AlignCenter, QString::number(m_avg));
}
void RazorCpuLoad::showConfigureDialog()
{
RazorCpuLoadConfiguration *confWindow =
this->findChild<RazorCpuLoadConfiguration*>("RazorCpuLoadConfigurationWindow");
if (!confWindow)
{
confWindow = new RazorCpuLoadConfiguration(settings(), this);
}
confWindow->show();
confWindow->raise();
confWindow->activateWindow();
}
void RazorCpuLoad::settigsChanged()
{
m_showText = settings().value("showText", false).toBool();
update();
}
<commit_msg>Improve size of cpu monitor on change of pannel orientation.<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Razor team
* Authors:
* Alexander Sokoloff <sokoloff.a@gmail.com>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "razorcpuload.h"
#include "razorcpuloadconfiguration.h"
#include <QtCore>
#include <QPainter>
#include <QLinearGradient>
extern "C" {
#include <statgrab.h>
}
EXPORT_RAZOR_PANEL_PLUGIN_CPP(RazorCpuLoad)
RazorCpuLoad::RazorCpuLoad(const RazorPanelPluginStartInfo* startInfo, QWidget* parent):
RazorPanelPlugin(startInfo, parent),
m_showText(false)
{
setObjectName("CpuLoad");
addWidget(&m_stuff);
/* Initialise statgrab */
sg_init();
/* Drop setuid/setgid privileges. */
if (sg_drop_privileges() != 0) {
perror("Error. Failed to drop privileges");
}
m_font.setPointSizeF(8);
startTimer(500);
settigsChanged();
}
RazorCpuLoad::~RazorCpuLoad()
{
}
void RazorCpuLoad::resizeEvent(QResizeEvent *)
{
m_stuff.setMinimumWidth(18);
m_stuff.setMaximumWidth(18);
m_stuff.setMinimumHeight(24);
update();
}
double RazorCpuLoad::getLoadCpu() const
{
sg_cpu_percents* cur = sg_get_cpu_percents();
return (cur->user + cur->kernel + cur->nice);
}
void RazorCpuLoad::timerEvent(QTimerEvent *event)
{
double avg = getLoadCpu();
if ( qAbs(m_avg-avg)>1 )
{
m_avg = avg;
setToolTip(tr("Cpu load %1%").arg(m_avg));
update();
}
}
void RazorCpuLoad::paintEvent ( QPaintEvent * )
{
QPainter p(this);
QPen pen;
pen.setWidth(2);
p.setPen(pen);
p.setRenderHint(QPainter::Antialiasing, true);
const double w = 20;
p.setFont(m_font);
QRectF r = rect();
float vo = r.height()*(1-m_avg*0.01);
float ho = (r.width() - w )/2.0;
QRectF r1(r.left()+ho, r.top()+vo, r.width()-2*ho, r.height()-vo );
QLinearGradient shade(0, 0, r1.width(), 0);
shade.setSpread(QLinearGradient::ReflectSpread);
shade.setColorAt(0, QColor(0, 196, 0, 128));
shade.setColorAt(0.5, QColor(0, 128, 0, 255) );
shade.setColorAt(1, QColor(0, 196, 0 , 128));
p.fillRect(r1, shade);
if( m_showText )
p.drawText(rect(), Qt::AlignCenter, QString::number(m_avg));
}
void RazorCpuLoad::showConfigureDialog()
{
RazorCpuLoadConfiguration *confWindow =
this->findChild<RazorCpuLoadConfiguration*>("RazorCpuLoadConfigurationWindow");
if (!confWindow)
{
confWindow = new RazorCpuLoadConfiguration(settings(), this);
}
confWindow->show();
confWindow->raise();
confWindow->activateWindow();
}
void RazorCpuLoad::settigsChanged()
{
m_showText = settings().value("showText", false).toBool();
update();
}
<|endoftext|>
|
<commit_before>#include "vtkConditionVariable.h"
#include "vtkMultiThreader.h"
#include <stdlib.h>
// For vtkSleep
#include "vtkWindows.h"
#include <ctype.h>
#include <time.h>
// Cross platform sleep (horked from vtkGeoTerrain.cxx)
inline void vtkSleep( double duration )
{
duration = duration; // avoid warnings
// sleep according to OS preference
#ifdef _WIN32
Sleep( (int)( 1000 * duration ) );
#elif defined(__FreeBSD__) || defined(__linux__) || defined(sgi)
struct timespec sleep_time, dummy;
sleep_time.tv_sec = static_cast<int>( duration );
sleep_time.tv_nsec = static_cast<int>( 1000000000 * ( duration - sleep_time.tv_sec ) );
nanosleep( &sleep_time, &dummy );
#endif
}
typedef struct {
vtkMutexLock* Lock;
vtkConditionVariable* Condition;
int Done;
int NumberOfWorkers;
} vtkThreadUserData;
VTK_THREAD_RETURN_TYPE vtkTestCondVarThread( void* arg )
{
int threadId = static_cast<vtkMultiThreader::ThreadInfo*>(arg)->ThreadID;
int threadCount = static_cast<vtkMultiThreader::ThreadInfo*>(arg)->NumberOfThreads;
vtkThreadUserData* td = static_cast<vtkThreadUserData*>(
static_cast<vtkMultiThreader::ThreadInfo*>(arg)->UserData );
if ( td )
{
if ( threadId == 0 )
{
td->Done = 0;
td->Lock->Lock();
cout << "Thread " << ( threadId + 1 ) << " of " << threadCount << " initializing.\n";
cout.flush();
td->Lock->Unlock();
int i;
for ( i = 0; i < 2 * threadCount; ++ i )
{
td->Lock->Lock();
cout << "Signaling (count " << i << ")...\n";
cout.flush();
td->Lock->Unlock();
td->Condition->Signal();
//sleep( 1 );
}
i = 0;
do
{
td->Lock->Lock();
td->Done = 1;
cout << "Broadcasting...\n";
cout.flush();
td->Lock->Unlock();
td->Condition->Broadcast();
vtkSleep( 0.2 ); // 0.2 s between broadcasts
}
while ( td->NumberOfWorkers > 0 && ( i ++ < 1000 ) );
if ( i >= 1000 )
{
exit( 2 );
}
}
else
{
// Wait for thread 0 to initialize... Ugly but effective
while ( td->Done < 0 )
{
vtkSleep( 0.2 ); // 0.2 s between checking
}
// Wait for the condition and then note we were signaled.
while ( td->Done <= 0 )
{
td->Lock->Lock();
cout << " Thread " << ( threadId + 1 ) << " waiting.\n";
cout.flush();
td->Condition->Wait( td->Lock );
cout << " Thread " << ( threadId + 1 ) << " responded.\n";
cout.flush();
td->Lock->Unlock();
}
td->Lock->Lock();
-- td->NumberOfWorkers;
td->Lock->Unlock();
}
td->Lock->Lock();
cout << " Thread " << ( threadId + 1 ) << " of " << threadCount << " exiting.\n";
cout.flush();
td->Lock->Unlock();
}
else
{
cout << "No thread data!\n";
cout << " Thread " << ( threadId + 1 ) << " of " << threadCount << " exiting.\n";
-- td->NumberOfWorkers;
cout.flush();
}
return VTK_THREAD_RETURN_VALUE;
}
int TestConditionVariable( int, char*[] )
{
vtkMultiThreader* threader = vtkMultiThreader::New();
int numThreads = threader->GetNumberOfThreads();
vtkThreadUserData data;
data.Lock = vtkMutexLock::New();
data.Condition = vtkConditionVariable::New();
data.Done = -1;
data.NumberOfWorkers = numThreads - 1;
threader->SetNumberOfThreads( numThreads );
threader->SetSingleMethod( vtkTestCondVarThread, &data );
threader->SingleMethodExecute();
cout << "Done with threader.\n";
cout.flush();
vtkIndent indent;
indent = indent.GetNextIndent();
data.Condition->PrintSelf( cout, indent );
data.Lock->Delete();
data.Condition->Delete();
threader->Delete();
return 0;
}
<commit_msg>BUG:Try to fix the test on dashmacmini2 (unix/release). lock/unlock where misplaced, now it really looks like a Hansen Monitor implementation.<commit_after>#include "vtkConditionVariable.h"
#include "vtkMultiThreader.h"
#include <stdlib.h>
// For vtkSleep
#include "vtkWindows.h"
#include <ctype.h>
#include <time.h>
// Cross platform sleep (horked from vtkGeoTerrain.cxx)
inline void vtkSleep( double duration )
{
duration = duration; // avoid warnings
// sleep according to OS preference
#ifdef _WIN32
Sleep( (int)( 1000 * duration ) );
#elif defined(__FreeBSD__) || defined(__linux__) || defined(sgi)
struct timespec sleep_time, dummy;
sleep_time.tv_sec = static_cast<int>( duration );
sleep_time.tv_nsec = static_cast<int>( 1000000000 * ( duration - sleep_time.tv_sec ) );
nanosleep( &sleep_time, &dummy );
#endif
}
typedef struct {
vtkMutexLock* Lock;
vtkConditionVariable* Condition;
int Done;
int NumberOfWorkers;
} vtkThreadUserData;
VTK_THREAD_RETURN_TYPE vtkTestCondVarThread( void* arg )
{
int threadId = static_cast<vtkMultiThreader::ThreadInfo*>(arg)->ThreadID;
int threadCount = static_cast<vtkMultiThreader::ThreadInfo*>(arg)->NumberOfThreads;
vtkThreadUserData* td = static_cast<vtkThreadUserData*>(
static_cast<vtkMultiThreader::ThreadInfo*>(arg)->UserData );
if ( td )
{
if ( threadId == 0 )
{
td->Done = 0;
td->Lock->Lock();
cout << "Thread " << ( threadId + 1 ) << " of " << threadCount << " initializing.\n";
cout.flush();
td->Lock->Unlock();
int i;
for ( i = 0; i < 2 * threadCount; ++ i )
{
td->Lock->Lock();
cout << "Signaling (count " << i << ")...\n";
cout.flush();
td->Lock->Unlock();
td->Condition->Signal();
//sleep( 1 );
}
i = 0;
do
{
td->Lock->Lock();
td->Done = 1;
cout << "Broadcasting...\n";
cout.flush();
td->Lock->Unlock();
td->Condition->Broadcast();
vtkSleep( 0.2 ); // 0.2 s between broadcasts
}
while ( td->NumberOfWorkers > 0 && ( i ++ < 1000 ) );
if ( i >= 1000 )
{
exit( 2 );
}
}
else
{
// Wait for thread 0 to initialize... Ugly but effective
while ( td->Done < 0 )
{
vtkSleep( 0.2 ); // 0.2 s between checking
}
// Wait for the condition and then note we were signaled.
// This part looks like a Hansen Monitor:
// ref: http://www.cs.utexas.edu/users/lorenzo/corsi/cs372h/07S/notes/Lecture12.pdf (page 2/5), code on Tradeoff slide.
td->Lock->Lock();
while ( td->Done <= 0 )
{
cout << " Thread " << ( threadId + 1 ) << " waiting.\n";
cout.flush();
// Wait() performs an Unlock internally.
td->Condition->Wait( td->Lock );
// Once Wait() returns, the lock is locked again.
cout << " Thread " << ( threadId + 1 ) << " responded.\n";
cout.flush();
}
-- td->NumberOfWorkers;
td->Lock->Unlock();
}
td->Lock->Lock();
cout << " Thread " << ( threadId + 1 ) << " of " << threadCount << " exiting.\n";
cout.flush();
td->Lock->Unlock();
}
else
{
cout << "No thread data!\n";
cout << " Thread " << ( threadId + 1 ) << " of " << threadCount << " exiting.\n";
-- td->NumberOfWorkers;
cout.flush();
}
return VTK_THREAD_RETURN_VALUE;
}
int TestConditionVariable( int, char*[] )
{
vtkMultiThreader* threader = vtkMultiThreader::New();
int numThreads = threader->GetNumberOfThreads();
vtkThreadUserData data;
data.Lock = vtkMutexLock::New();
data.Condition = vtkConditionVariable::New();
data.Done = -1;
data.NumberOfWorkers = numThreads - 1;
threader->SetNumberOfThreads( numThreads );
threader->SetSingleMethod( vtkTestCondVarThread, &data );
threader->SingleMethodExecute();
cout << "Done with threader.\n";
cout.flush();
vtkIndent indent;
indent = indent.GetNextIndent();
data.Condition->PrintSelf( cout, indent );
data.Lock->Delete();
data.Condition->Delete();
threader->Delete();
return 0;
}
<|endoftext|>
|
<commit_before>/*******************************************************
* Copyright (c) 2015, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <af/defines.h>
#include <Array.hpp>
#include <complex>
namespace cpu
{
namespace kernel
{
template<typename T> T
conj(T x) { return x; }
template<> cfloat conj<cfloat> (cfloat c) { return std::conj(c); }
template<> cdouble conj<cdouble>(cdouble c) { return std::conj(c); }
template<typename T, bool conjugate, bool both_conjugate>
void dot(Array<T> output, const Array<T> &lhs, const Array<T> &rhs,
af_mat_prop optLhs, af_mat_prop optRhs)
{
int N = lhs.dims()[0];
T out = 0;
const T *pL = lhs.get();
const T *pR = rhs.get();
for(int i = 0; i < N; i++)
out += (conjugate ? kernel::conj(pL[i]) : pL[i]) * pR[i];
if(both_conjugate) out = kernel::conj(out);
*output.get() = out;
}
}
}
<commit_msg>fixed cpu::kernel::dot fn signature<commit_after>/*******************************************************
* Copyright (c) 2015, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <af/defines.h>
#include <Array.hpp>
#include <complex>
namespace cpu
{
namespace kernel
{
template<typename T> T
conj(T x) { return x; }
template<> cfloat conj<cfloat> (cfloat c) { return std::conj(c); }
template<> cdouble conj<cdouble>(cdouble c) { return std::conj(c); }
template<typename T, bool conjugate, bool both_conjugate>
void dot(Array<T> output, const Array<T> lhs, const Array<T> rhs,
af_mat_prop optLhs, af_mat_prop optRhs)
{
int N = lhs.dims()[0];
T out = 0;
const T *pL = lhs.get();
const T *pR = rhs.get();
for(int i = 0; i < N; i++)
out += (conjugate ? kernel::conj(pL[i]) : pL[i]) * pR[i];
if(both_conjugate) out = kernel::conj(out);
*output.get() = out;
}
}
}
<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "vtkMitkRectangleProp.h"
#include <vtkObjectFactory.h>
#include <vtkCellArray.h>
#include <vtkPoints.h>
#include <vtkLine.h>
#include <vtkPolyData.h>
#include <vtkSmartPointer.h>
#include <vtkProperty2D.h>
#include <vtkActor2D.h>
#include <vtkPolyDataMapper2D.h>
vtkStandardNewMacro(vtkMitkRectangleProp);
vtkMitkRectangleProp::vtkMitkRectangleProp()
{
vtkSmartPointer<vtkPolyDataMapper2D> mapper = vtkSmartPointer<vtkPolyDataMapper2D>::New();
m_RectangleActor = vtkSmartPointer<vtkActor2D>::New();
m_PolyData = vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New();
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
m_PolyData->SetPoints(points);
m_PolyData->SetLines(lines);
this->CreateRectangle();
mapper->SetInputData(m_PolyData);
m_RectangleActor->SetMapper(mapper);
}
vtkMitkRectangleProp::~vtkMitkRectangleProp()
{
}
int vtkMitkRectangleProp::RenderOverlay(vtkViewport* viewport)
{
double right = m_RenderWindow->GetSize()[0];
double top = m_RenderWindow->GetSize()[1];
double bottom = 0.5;
double left = 0.5;
double defaultDepth = 0.0;
vtkSmartPointer<vtkPoints> points = m_PolyData->GetPoints();
//change the corners to adapt the size of the renderwindow was resized
points->SetPoint(m_BottomLeft, left, bottom, defaultDepth);
points->SetPoint(m_TopLeft, left, top, defaultDepth);
points->SetPoint(m_TopRight, right, top, defaultDepth);
points->SetPoint(m_BottomRight, right, bottom, defaultDepth);
//adapt color
m_RectangleActor->GetProperty()->SetColor( m_Color[0], m_Color[1], m_Color[2]);
//render the actor
m_RectangleActor->RenderOverlay(viewport);
return 1;
}
void vtkMitkRectangleProp::CreateRectangle()
{
vtkSmartPointer<vtkPoints> points = m_PolyData->GetPoints();
vtkSmartPointer<vtkCellArray> lines = m_PolyData->GetLines();
double bottom = 0.5;
double left = 0.5;
double right = 199.0;
double top = 199.0;
double defaultDepth = 0.0;
//4 corner points
m_BottomLeft = points->InsertNextPoint(left, bottom, defaultDepth);
m_BottomRight = points->InsertNextPoint(right, bottom, defaultDepth);
m_TopLeft = points->InsertNextPoint(left, top, defaultDepth);
m_TopRight = points->InsertNextPoint(right, top, defaultDepth);
vtkSmartPointer<vtkLine> lineVtk = vtkSmartPointer<vtkLine>::New();
lineVtk->GetPointIds()->SetNumberOfIds(5);
//connect the lines
lineVtk->GetPointIds()->SetId(0,m_BottomLeft);
lineVtk->GetPointIds()->SetId(1,m_BottomRight);
lineVtk->GetPointIds()->SetId(2,m_TopRight);
lineVtk->GetPointIds()->SetId(3,m_TopLeft);
lineVtk->GetPointIds()->SetId(4,m_BottomLeft);
lines->InsertNextCell(lineVtk);
}
void vtkMitkRectangleProp::SetRenderWindow(vtkSmartPointer<vtkRenderWindow> renWin)
{
m_RenderWindow = renWin;
}
void vtkMitkRectangleProp::SetColor(float col1, float col2, float col3)
{
m_Color[0] = col1;
m_Color[1] = col2;
m_Color[2] = col3;
}
<commit_msg>Rectangle prop now correctly uses the viewport.<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "vtkMitkRectangleProp.h"
#include <vtkObjectFactory.h>
#include <vtkCellArray.h>
#include <vtkPoints.h>
#include <vtkLine.h>
#include <vtkPolyData.h>
#include <vtkSmartPointer.h>
#include <vtkProperty2D.h>
#include <vtkActor2D.h>
#include <vtkPolyDataMapper2D.h>
#include <vtkViewport.h>
vtkStandardNewMacro(vtkMitkRectangleProp);
vtkMitkRectangleProp::vtkMitkRectangleProp()
{
vtkSmartPointer<vtkPolyDataMapper2D> mapper = vtkSmartPointer<vtkPolyDataMapper2D>::New();
m_RectangleActor = vtkSmartPointer<vtkActor2D>::New();
m_PolyData = vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New();
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
m_PolyData->SetPoints(points);
m_PolyData->SetLines(lines);
this->CreateRectangle();
mapper->SetInputData(m_PolyData);
m_RectangleActor->SetMapper(mapper);
}
vtkMitkRectangleProp::~vtkMitkRectangleProp()
{
}
int vtkMitkRectangleProp::RenderOverlay(vtkViewport* viewport)
{
double right = viewport->GetSize()[0];
double top = viewport->GetSize()[1];
// double bottom = 0.0;
double left = viewport->GetOrigin()[0] + 0.5;
double bottom = viewport->GetOrigin()[1] + 0.5;
// double left = 0.0;
double defaultDepth = 0.0;
vtkSmartPointer<vtkPoints> points = m_PolyData->GetPoints();
//change the corners to adapt the size of the renderwindow was resized
points->SetPoint(m_BottomLeft, left, bottom, defaultDepth);
points->SetPoint(m_TopLeft, left, top, defaultDepth);
points->SetPoint(m_TopRight, right, top, defaultDepth);
points->SetPoint(m_BottomRight, right, bottom, defaultDepth);
//adapt color
m_RectangleActor->GetProperty()->SetColor( m_Color[0], m_Color[1], m_Color[2]);
//render the actor
m_RectangleActor->RenderOverlay(viewport);
return 1;
}
void vtkMitkRectangleProp::CreateRectangle()
{
vtkSmartPointer<vtkPoints> points = m_PolyData->GetPoints();
vtkSmartPointer<vtkCellArray> lines = m_PolyData->GetLines();
//just some default values until a renderwindow/viewport is initialized
double bottom = 0.0;
double left = 0.0;
double right = 200.0;
double top = 200.0;
double defaultDepth = 0.0;
//4 corner points
m_BottomLeft = points->InsertNextPoint(left, bottom, defaultDepth);
m_BottomRight = points->InsertNextPoint(right, bottom, defaultDepth);
m_TopLeft = points->InsertNextPoint(left, top, defaultDepth);
m_TopRight = points->InsertNextPoint(right, top, defaultDepth);
vtkSmartPointer<vtkLine> lineVtk = vtkSmartPointer<vtkLine>::New();
lineVtk->GetPointIds()->SetNumberOfIds(5);
//connect the lines
lineVtk->GetPointIds()->SetId(0,m_BottomLeft);
lineVtk->GetPointIds()->SetId(1,m_BottomRight);
lineVtk->GetPointIds()->SetId(2,m_TopRight);
lineVtk->GetPointIds()->SetId(3,m_TopLeft);
lineVtk->GetPointIds()->SetId(4,m_BottomLeft);
lines->InsertNextCell(lineVtk);
}
void vtkMitkRectangleProp::SetRenderWindow(vtkSmartPointer<vtkRenderWindow> renWin)
{
m_RenderWindow = renWin;
}
void vtkMitkRectangleProp::SetColor(float col1, float col2, float col3)
{
m_Color[0] = col1;
m_Color[1] = col2;
m_Color[2] = col3;
}
<|endoftext|>
|
<commit_before>#include <iostream>
int main(int argc, char* argv[])
{
}
<commit_msg>Random numbers example compiles and runs<commit_after>#include <iostream>
#include <random>
#include <functional>
int main(int argc, char* argv[])
{
std::uniform_int_distribution<int> distribution(0,99);
std::mt19937 engine;
auto generator = std::bind(distribution,engine);
for ( int i=0; i<50; ++i )
{
int random = generator();
std::cout << random << " ";
}
std::cout << std::endl;
}
<|endoftext|>
|
<commit_before>// bslmf_assert.t.cpp -*-C++-*-
#include <bslmf_assert.h>
#include <bsls_bsltestutil.h>
#include <bsls_compilerfeatures.h>
#include <bsls_platform.h>
#include <stdio.h> // printf
#include <stdlib.h> // atoi
//=============================================================================
// TEST PLAN
//-----------------------------------------------------------------------------
// Overview
// --------
//-----------------------------------------------------------------------------
// [ 1] BSLMF_ASSERT(expr)i
// ----------------------------------------------------------------------------
// [ ] USAGE EXAMPLE
// [ 2] CONCERN: BSLMF_ASSERT in non-instantiated template classes
//=============================================================================
//
// STANDARD BDE ASSERT TEST MACRO
//-----------------------------------------------------------------------------
// NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY
// FUNCTIONS, INCLUDING IOSTREAMS.
static int testStatus = 0;
void aSsErT(bool b, const char *s, int i)
{
if (b) {
printf("Error " __FILE__ "(%d): %s (failed)\n", i, s);
if (testStatus >= 0 && testStatus <= 100) ++testStatus;
}
}
# define ASSERT(X) { aSsErT(!(X), #X, __LINE__); }
//=============================================================================
// STANDARD BDE TEST DRIVER MACROS
//-----------------------------------------------------------------------------
#define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT
#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT
#define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally.
#define P BSLS_BSLTESTUTIL_P // Print identifier and value.
#define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'.
#define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline).
#define L_ BSLS_BSLTESTUTIL_L_ // current Line number
//=============================================================================
// GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
//-----------------------------------------------------------------------------
namespace BloombergLP {
namespace bslmftest {
// ======================
// class SomeTemplateType
// ======================
template <class SOME_TYPE>
class SomeTemplateType {
// This specialization of 'SomeTemplateType' defines an alias 'Type' for a
// functor that delegates to a function pointer matching the parameterized
// 'SOME_TYPE' type.
BSLMF_ASSERT(4 == sizeof(SOME_TYPE));
// This 'BSLMF_ASSERT' statement ensures that the parameter 'SOME_TYPE'
// must be a function pointer.
};
} // close package namespace
} // close enterprise namespace
// namespace scope
BSLMF_ASSERT(sizeof(int) >= sizeof(char));
// un-named namespace
namespace {
BSLMF_ASSERT(1);
#if defined(BSLS_PLATFORM_CMP_SUN)
BSLMF_ASSERT(1);
#else
BSLMF_ASSERT(1); BSLMF_ASSERT(1); // not class scope
#endif
} // close unnamed namespace
namespace {
BSLMF_ASSERT(1);
} // close unnamed namespace
namespace Bar {
BSLMF_ASSERT(1);
#if defined(BSLS_PLATFORM_CMP_SUN)
BSLMF_ASSERT(1);
#else
BSLMF_ASSERT(1); BSLMF_ASSERT(1); // not class scope
#endif
} // close namespace Bar
class MyType {
// class scope
BSLMF_ASSERT(sizeof(int) >= sizeof(char));
BSLMF_ASSERT(sizeof(int) >= sizeof(char));
public:
int d_data;
void foo();
};
void MyType::foo()
{
// function scope
BSLMF_ASSERT(sizeof(int) >= sizeof(char));
BSLMF_ASSERT(1);
using namespace BloombergLP;
BSLMF_ASSERT(1);
}
//=============================================================================
// MAIN PROGRAM
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? atoi(argv[1]) : 0;
bool verbose = argc > 2;
// bool veryVerbose = argc > 3;
printf("TEST " __FILE__ " CASE %d\n", test);
switch (test) { case 0: // Zero is always the leading case.
case 2: {
// --------------------------------------------------------------------
// BSLMF_ASSERT MACRO WITHIN TEMPLATE CLASS
// Sun Studio has historically required a special implementation of
// 'BSMF_ASSERT'. According to DRQS 79918675, starting with Sun
// Studio 12.4 the special implementation causes build failures by
// its mere presence in a templatized class, even if that class is
// never instantiated. On the other hand, Sun Studio 12.4 has
// improved template instantiation, and therefore does not need the
// special implementation. This test case checks that the case
// reported in DRQS 79918675 is fixed by switching to the standard
// implementation on versions 12.4 and better.
//
// Concerns:
// 1 Uses of BSLMF_ASSERT in non-instantiated templates does not cause
// a build failure when the assertion depends on a template
// parameter.
//
// Plan:
// 1 Create a template class having an assertion dependent on the
// template parameter, but do not instantiate the class. If the code
// builds on Sun Studio 12.4, the test passes. (C-1)
//
// Testing:
// CONCERN: BSLMF_ASSERT in non-instantiated template classes
// --------------------------------------------------------------------
if (verbose) printf("\nBSLMF_ASSERT MACRO WITHIN TEMPLATE CLASS"
"\n========================================\n");
// Do nothing. The test is entirely encapsulated in the definition of
// 'SomeTemplateType' above.
ASSERT(true);
} break;
case 1: {
// --------------------------------------------------------------------
// TESTING BSLMF_ASSERT MACRO
// We have the following concerns:
// 1. Works for all non-zero integral values.
// 2. Works in and out of class scope.
//
// Plan:
// Invoke the macro at namespace, class, and function scope (above)
// and verify that it does not cause a compiler error. Please see
// the 'ttt' test package group for test cases where the macro
// should cause a compile-time error.
//
// Testing:
// BSLMF_ASSERT(expr)
// --------------------------------------------------------------------
if (verbose) printf("\nBSLMF_ASSERT Macro"
"\n==================\n");
BSLMF_ASSERT(sizeof(int) >= sizeof(char));
BSLMF_ASSERT(sizeof(int) >= sizeof(char));
BSLMF_ASSERT(1); ASSERT(145 == __LINE__);
BSLMF_ASSERT(1); ASSERT(146 == __LINE__);
BSLMF_ASSERT(1 > 0 && 1);
// MSVC: __LINE__ macro breaks when /ZI is used (see Q199057 or KB199057)
// SUN: BSLMF_ASSERT is defined the way that breaks this test
// GCC: Declares a function, rather than a typedef, from v4.8.1
#if !defined(BSLS_COMPILERFEATURES_SUPPORT_STATIC_ASSERT) && \
!defined(BSLS_PLATFORM_CMP_MSVC) && \
!defined(BSLS_PLATFORM_CMP_SUN) && \
!(defined(BSLS_PLATFORM_CMP_GNU) && BSLS_PLATFORM_CMP_VER_MAJOR > 40800)
bslmf_Assert_145 t1; // test typedef name creation; matches above line
bslmf_Assert_146 t2; // test typedef name creation; matches above line
ASSERT(sizeof t1 == sizeof t2); // use t1 and t2
#endif
BSLMF_ASSERT(2);
BSLMF_ASSERT(-1);
#if defined(BSLS_PLATFORM_CMP_SUN)
BSLMF_ASSERT(1);
#else
BSLMF_ASSERT(1); BSLMF_ASSERT(1); // not class scope
#endif
} break;
default: {
fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test);
testStatus = -1;
}
}
if (testStatus > 0) {
fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus);
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright 2013 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>Update line numbers in bslmf_assert test driver<commit_after>// bslmf_assert.t.cpp -*-C++-*-
#include <bslmf_assert.h>
#include <bsls_bsltestutil.h>
#include <bsls_compilerfeatures.h>
#include <bsls_platform.h>
#include <stdio.h> // printf
#include <stdlib.h> // atoi
//=============================================================================
// TEST PLAN
//-----------------------------------------------------------------------------
// Overview
// --------
//-----------------------------------------------------------------------------
// [ 1] BSLMF_ASSERT(expr)i
// ----------------------------------------------------------------------------
// [ ] USAGE EXAMPLE
// [ 2] CONCERN: BSLMF_ASSERT in non-instantiated template classes
//=============================================================================
//
// STANDARD BDE ASSERT TEST MACRO
//-----------------------------------------------------------------------------
// NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY
// FUNCTIONS, INCLUDING IOSTREAMS.
static int testStatus = 0;
void aSsErT(bool b, const char *s, int i)
{
if (b) {
printf("Error " __FILE__ "(%d): %s (failed)\n", i, s);
if (testStatus >= 0 && testStatus <= 100) ++testStatus;
}
}
# define ASSERT(X) { aSsErT(!(X), #X, __LINE__); }
//=============================================================================
// STANDARD BDE TEST DRIVER MACROS
//-----------------------------------------------------------------------------
#define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT
#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT
#define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally.
#define P BSLS_BSLTESTUTIL_P // Print identifier and value.
#define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'.
#define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline).
#define L_ BSLS_BSLTESTUTIL_L_ // current Line number
//=============================================================================
// GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
//-----------------------------------------------------------------------------
namespace BloombergLP {
namespace bslmftest {
// ======================
// class SomeTemplateType
// ======================
template <class SOME_TYPE>
class SomeTemplateType {
// This specialization of 'SomeTemplateType' defines an alias 'Type' for a
// functor that delegates to a function pointer matching the parameterized
// 'SOME_TYPE' type.
BSLMF_ASSERT(4 == sizeof(SOME_TYPE));
// This 'BSLMF_ASSERT' statement ensures that the parameter 'SOME_TYPE'
// must be a function pointer.
};
} // close package namespace
} // close enterprise namespace
// namespace scope
BSLMF_ASSERT(sizeof(int) >= sizeof(char));
// un-named namespace
namespace {
BSLMF_ASSERT(1);
#if defined(BSLS_PLATFORM_CMP_SUN)
BSLMF_ASSERT(1);
#else
BSLMF_ASSERT(1); BSLMF_ASSERT(1); // not class scope
#endif
} // close unnamed namespace
namespace {
BSLMF_ASSERT(1);
} // close unnamed namespace
namespace Bar {
BSLMF_ASSERT(1);
#if defined(BSLS_PLATFORM_CMP_SUN)
BSLMF_ASSERT(1);
#else
BSLMF_ASSERT(1); BSLMF_ASSERT(1); // not class scope
#endif
} // close namespace Bar
class MyType {
// class scope
BSLMF_ASSERT(sizeof(int) >= sizeof(char));
BSLMF_ASSERT(sizeof(int) >= sizeof(char));
public:
int d_data;
void foo();
};
void MyType::foo()
{
// function scope
BSLMF_ASSERT(sizeof(int) >= sizeof(char));
BSLMF_ASSERT(1);
using namespace BloombergLP;
BSLMF_ASSERT(1);
}
//=============================================================================
// MAIN PROGRAM
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? atoi(argv[1]) : 0;
bool verbose = argc > 2;
// bool veryVerbose = argc > 3;
printf("TEST " __FILE__ " CASE %d\n", test);
switch (test) { case 0: // Zero is always the leading case.
case 2: {
// --------------------------------------------------------------------
// BSLMF_ASSERT MACRO WITHIN TEMPLATE CLASS
// Sun Studio has historically required a special implementation of
// 'BSMF_ASSERT'. According to DRQS 79918675, starting with Sun
// Studio 12.4 the special implementation causes build failures by
// its mere presence in a templatized class, even if that class is
// never instantiated. On the other hand, Sun Studio 12.4 has
// improved template instantiation, and therefore does not need the
// special implementation. This test case checks that the case
// reported in DRQS 79918675 is fixed by switching to the standard
// implementation on versions 12.4 and better.
//
// Concerns:
// 1 Uses of BSLMF_ASSERT in non-instantiated templates does not cause
// a build failure when the assertion depends on a template
// parameter.
//
// Plan:
// 1 Create a template class having an assertion dependent on the
// template parameter, but do not instantiate the class. If the code
// builds on Sun Studio 12.4, the test passes. (C-1)
//
// Testing:
// CONCERN: BSLMF_ASSERT in non-instantiated template classes
// --------------------------------------------------------------------
if (verbose) printf("\nBSLMF_ASSERT MACRO WITHIN TEMPLATE CLASS"
"\n========================================\n");
// Do nothing. The test is entirely encapsulated in the definition of
// 'SomeTemplateType' above.
ASSERT(true);
} break;
case 1: {
// --------------------------------------------------------------------
// TESTING BSLMF_ASSERT MACRO
// We have the following concerns:
// 1. Works for all non-zero integral values.
// 2. Works in and out of class scope.
//
// Plan:
// Invoke the macro at namespace, class, and function scope (above)
// and verify that it does not cause a compiler error. Please see
// the 'ttt' test package group for test cases where the macro
// should cause a compile-time error.
//
// Testing:
// BSLMF_ASSERT(expr)
// --------------------------------------------------------------------
if (verbose) printf("\nBSLMF_ASSERT Macro"
"\n==================\n");
BSLMF_ASSERT(sizeof(int) >= sizeof(char));
BSLMF_ASSERT(sizeof(int) >= sizeof(char));
BSLMF_ASSERT(1); ASSERT(202 == __LINE__);
BSLMF_ASSERT(1); ASSERT(203 == __LINE__);
BSLMF_ASSERT(1 > 0 && 1);
// MSVC: __LINE__ macro breaks when /ZI is used (see Q199057 or KB199057)
// SUN: BSLMF_ASSERT is defined the way that breaks this test
// GCC: Declares a function, rather than a typedef, from v4.8.1
#if !defined(BSLS_COMPILERFEATURES_SUPPORT_STATIC_ASSERT) && \
!defined(BSLS_PLATFORM_CMP_MSVC) && \
!defined(BSLS_PLATFORM_CMP_SUN) && \
!(defined(BSLS_PLATFORM_CMP_GNU) && BSLS_PLATFORM_CMP_VER_MAJOR > 40800)
bslmf_Assert_202 t1; // test typedef name creation; matches above line
bslmf_Assert_203 t2; // test typedef name creation; matches above line
ASSERT(sizeof t1 == sizeof t2); // use t1 and t2
#endif
BSLMF_ASSERT(2);
BSLMF_ASSERT(-1);
#if defined(BSLS_PLATFORM_CMP_SUN)
BSLMF_ASSERT(1);
#else
BSLMF_ASSERT(1); BSLMF_ASSERT(1); // not class scope
#endif
} break;
default: {
fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test);
testStatus = -1;
}
}
if (testStatus > 0) {
fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus);
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright 2013 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<|endoftext|>
|
<commit_before>// Copyright (c) 2013, Matthew Harvey. All rights reserved.
#ifndef GUARD_report_panel_hpp_8629163596140763
#define GUARD_report_panel_hpp_8629163596140763
#include "entry.hpp"
#include <boost/noncopyable.hpp>
#include <wx/combobox.h>
#include <wx/button.h>
#include <wx/event.h>
#include <wx/gbsizer.h>
#include <wx/panel.h>
#include <wx/window.h>
#include <vector>
namespace phatbooks
{
// Begin forward declarations
class Account;
class OrdinaryJournal;
class PhatbooksDatabaseConnection;
namespace gui
{
class DateCtrl;
class Report;
// End forward declarations
/**
* Panel for holding date-filtered balance sheet and profit-and-loss
* reports.
*
* @todo We can make things more straightforward and speed start-up times
* by having the date boxes start out blank. We can then have
* BalanceSheetReport initially just use the balance() of each Account
* simpliciter as "Closing balance" and "Movement", and use a
* \e nil amount for the "Opening balance" column. This can be written
* into the code for initializing the m_balance_map.
*
* @todo HIGH PRIORITY Make it so this only runs when "Run" is clicked, not
* automatically on creation.
*/
class ReportPanel: public wxPanel, private boost::noncopyable
{
public:
ReportPanel
( wxWindow* p_parent,
PhatbooksDatabaseConnection& p_database_connection
);
void update_for_new(OrdinaryJournal const& p_journal);
void update_for_amended(OrdinaryJournal const& p_journal);
void update_for_new(Account const& p_account);
void update_for_amended(Account const& p_account);
void update_for_deleted(std::vector<Entry::Id> const& p_doomed_ids);
private:
void on_run_button_click(wxCommandEvent& event);
void configure_top();
void configure_bottom();
account_super_type::AccountSuperType selected_account_super_type() const;
static int const s_min_date_ctrl_id = wxID_HIGHEST + 1;
static int const s_max_date_ctrl_id = s_min_date_ctrl_id + 1;
static int const s_run_button_id = s_max_date_ctrl_id + 1;
int m_next_row;
int m_client_size_aux;
int m_text_ctrl_height;
wxGridBagSizer* m_top_sizer;
wxComboBox* m_report_type_ctrl;
DateCtrl* m_min_date_ctrl;
DateCtrl* m_max_date_ctrl;
wxButton* m_run_button;
Report* m_report;
PhatbooksDatabaseConnection& m_database_connection;
DECLARE_EVENT_TABLE()
}; // class ReportPanel
} // namespace gui
} // namespace phatbooks
#endif // GUARD_report_panel_hpp_8629163596140763
<commit_msg>Update a TODO.<commit_after>// Copyright (c) 2013, Matthew Harvey. All rights reserved.
#ifndef GUARD_report_panel_hpp_8629163596140763
#define GUARD_report_panel_hpp_8629163596140763
#include "entry.hpp"
#include <boost/noncopyable.hpp>
#include <wx/combobox.h>
#include <wx/button.h>
#include <wx/event.h>
#include <wx/gbsizer.h>
#include <wx/panel.h>
#include <wx/window.h>
#include <vector>
namespace phatbooks
{
// Begin forward declarations
class Account;
class OrdinaryJournal;
class PhatbooksDatabaseConnection;
namespace gui
{
class DateCtrl;
class Report;
// End forward declarations
/**
* Panel for holding date-filtered balance sheet and profit-and-loss
* reports.
*
* @todo We can make things more straightforward and speed start-up times
* by having the date boxes start out blank. We can then have
* BalanceSheetReport initially just use the balance() of each Account
* simpliciter as "Closing balance" and "Movement", and use a
* \e nil amount for the "Opening balance" column. This can be written
* into the code for initializing the m_balance_map.
*/
class ReportPanel: public wxPanel, private boost::noncopyable
{
public:
ReportPanel
( wxWindow* p_parent,
PhatbooksDatabaseConnection& p_database_connection
);
void update_for_new(OrdinaryJournal const& p_journal);
void update_for_amended(OrdinaryJournal const& p_journal);
void update_for_new(Account const& p_account);
void update_for_amended(Account const& p_account);
void update_for_deleted(std::vector<Entry::Id> const& p_doomed_ids);
private:
void on_run_button_click(wxCommandEvent& event);
void configure_top();
void configure_bottom();
account_super_type::AccountSuperType selected_account_super_type() const;
static int const s_min_date_ctrl_id = wxID_HIGHEST + 1;
static int const s_max_date_ctrl_id = s_min_date_ctrl_id + 1;
static int const s_run_button_id = s_max_date_ctrl_id + 1;
int m_next_row;
int m_client_size_aux;
int m_text_ctrl_height;
wxGridBagSizer* m_top_sizer;
wxComboBox* m_report_type_ctrl;
DateCtrl* m_min_date_ctrl;
DateCtrl* m_max_date_ctrl;
wxButton* m_run_button;
Report* m_report;
PhatbooksDatabaseConnection& m_database_connection;
DECLARE_EVENT_TABLE()
}; // class ReportPanel
} // namespace gui
} // namespace phatbooks
#endif // GUARD_report_panel_hpp_8629163596140763
<|endoftext|>
|
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreConfigFile.h"
#include "OgreResourceGroupManager.h"
#include "OgreException.h"
#include <iostream>
namespace Ogre {
//-----------------------------------------------------------------------
ConfigFile::ConfigFile()
{
}
//-----------------------------------------------------------------------
ConfigFile::~ConfigFile()
{
SettingsBySection::iterator seci, secend;
secend = mSettings.end();
for (seci = mSettings.begin(); seci != secend; ++seci)
{
OGRE_DELETE_T(seci->second, SettingsMultiMap, MEMCATEGORY_GENERAL);
}
}
//-----------------------------------------------------------------------
void ConfigFile::clear(void)
{
for (SettingsBySection::iterator seci = mSettings.begin();
seci != mSettings.end(); ++seci)
{
OGRE_DELETE_T(seci->second, SettingsMultiMap, MEMCATEGORY_GENERAL);
}
mSettings.clear();
}
//-----------------------------------------------------------------------
void ConfigFile::load(const String& filename, const String& separators, bool trimWhitespace)
{
loadDirect(filename, separators, trimWhitespace);
}
//-----------------------------------------------------------------------
void ConfigFile::load(const String& filename, const String& resourceGroup,
const String& separators, bool trimWhitespace)
{
loadFromResourceSystem(filename, resourceGroup, separators, trimWhitespace);
}
//-----------------------------------------------------------------------
void ConfigFile::loadDirect(const String& filename, const String& separators,
bool trimWhitespace)
{
/* Open the configuration file */
std::ifstream fp;
// Always open in binary mode
fp.open(filename.c_str(), std::ios::in | std::ios::binary);
if(!fp)
OGRE_EXCEPT(
Exception::ERR_FILE_NOT_FOUND, "'" + filename + "' file not found!", "ConfigFile::load" );
// Wrap as a stream
DataStreamPtr stream(OGRE_NEW FileStreamDataStream(filename, &fp, false));
load(stream, separators, trimWhitespace);
}
//-----------------------------------------------------------------------
void ConfigFile::loadFromResourceSystem(const String& filename,
const String& resourceGroup, const String& separators, bool trimWhitespace)
{
DataStreamPtr stream =
ResourceGroupManager::getSingleton().openResource(filename, resourceGroup);
load(stream, separators, trimWhitespace);
}
//-----------------------------------------------------------------------
void ConfigFile::load(const DataStreamPtr& stream, const String& separators,
bool trimWhitespace)
{
/* Clear current settings map */
clear();
String currentSection = StringUtil::BLANK;
SettingsMultiMap* currentSettings = OGRE_NEW_T(SettingsMultiMap, MEMCATEGORY_GENERAL)();
mSettings[currentSection] = currentSettings;
/* Process the file line for line */
String line, optName, optVal;
while (!stream->eof())
{
line = stream->getLine();
/* Ignore comments & blanks */
if (line.length() > 0 && line.at(0) != '#' && line.at(0) != '@')
{
if (line.at(0) == '[' && line.at(line.length()-1) == ']')
{
// Section
currentSection = line.substr(1, line.length() - 2);
SettingsBySection::const_iterator seci = mSettings.find(currentSection);
if (seci == mSettings.end())
{
currentSettings = OGRE_NEW_T(SettingsMultiMap, MEMCATEGORY_GENERAL)();
mSettings[currentSection] = currentSettings;
}
else
{
currentSettings = seci->second;
}
}
else
{
/* Find the first seperator character and split the string there */
std::string::size_type separator_pos = line.find_first_of(separators, 0);
if (separator_pos != std::string::npos)
{
optName = line.substr(0, separator_pos);
/* Find the first non-seperator character following the name */
std::string::size_type nonseparator_pos = line.find_first_not_of(separators, separator_pos);
/* ... and extract the value */
/* Make sure we don't crash on an empty setting (it might be a valid value) */
optVal = (nonseparator_pos == std::string::npos) ? "" : line.substr(nonseparator_pos);
if (trimWhitespace)
{
StringUtil::trim(optVal);
StringUtil::trim(optName);
}
currentSettings->insert(std::multimap<String, String>::value_type(optName, optVal));
}
}
}
}
}
//-----------------------------------------------------------------------
String ConfigFile::getSetting(const String& key, const String& section, const String& defaultValue) const
{
SettingsBySection::const_iterator seci = mSettings.find(section);
if (seci == mSettings.end())
{
return defaultValue;
}
else
{
SettingsMultiMap::const_iterator i = seci->second->find(key);
if (i == seci->second->end())
{
return StringUtil::BLANK;
}
else
{
return i->second;
}
}
}
//-----------------------------------------------------------------------
StringVector ConfigFile::getMultiSetting(const String& key, const String& section) const
{
StringVector ret;
SettingsBySection::const_iterator seci = mSettings.find(section);
if (seci != mSettings.end())
{
SettingsMultiMap::const_iterator i;
i = seci->second->find(key);
// Iterate over matches
while (i != seci->second->end() && i->first == key)
{
ret.push_back(i->second);
++i;
}
}
return ret;
}
//-----------------------------------------------------------------------
ConfigFile::SettingsIterator ConfigFile::getSettingsIterator(const String& section)
{
SettingsBySection::const_iterator seci = mSettings.find(section);
if (seci == mSettings.end())
{
OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND,
"Cannot find section " + section,
"ConfigFile::getSettingsIterator");
}
else
{
return SettingsIterator(seci->second->begin(), seci->second->end());
}
}
//-----------------------------------------------------------------------
ConfigFile::SectionIterator ConfigFile::getSectionIterator(void)
{
return SectionIterator(mSettings.begin(), mSettings.end());
}
}
<commit_msg>Patch 2482278: return default value properly from ConfigFile::getSetting<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreConfigFile.h"
#include "OgreResourceGroupManager.h"
#include "OgreException.h"
#include <iostream>
namespace Ogre {
//-----------------------------------------------------------------------
ConfigFile::ConfigFile()
{
}
//-----------------------------------------------------------------------
ConfigFile::~ConfigFile()
{
SettingsBySection::iterator seci, secend;
secend = mSettings.end();
for (seci = mSettings.begin(); seci != secend; ++seci)
{
OGRE_DELETE_T(seci->second, SettingsMultiMap, MEMCATEGORY_GENERAL);
}
}
//-----------------------------------------------------------------------
void ConfigFile::clear(void)
{
for (SettingsBySection::iterator seci = mSettings.begin();
seci != mSettings.end(); ++seci)
{
OGRE_DELETE_T(seci->second, SettingsMultiMap, MEMCATEGORY_GENERAL);
}
mSettings.clear();
}
//-----------------------------------------------------------------------
void ConfigFile::load(const String& filename, const String& separators, bool trimWhitespace)
{
loadDirect(filename, separators, trimWhitespace);
}
//-----------------------------------------------------------------------
void ConfigFile::load(const String& filename, const String& resourceGroup,
const String& separators, bool trimWhitespace)
{
loadFromResourceSystem(filename, resourceGroup, separators, trimWhitespace);
}
//-----------------------------------------------------------------------
void ConfigFile::loadDirect(const String& filename, const String& separators,
bool trimWhitespace)
{
/* Open the configuration file */
std::ifstream fp;
// Always open in binary mode
fp.open(filename.c_str(), std::ios::in | std::ios::binary);
if(!fp)
OGRE_EXCEPT(
Exception::ERR_FILE_NOT_FOUND, "'" + filename + "' file not found!", "ConfigFile::load" );
// Wrap as a stream
DataStreamPtr stream(OGRE_NEW FileStreamDataStream(filename, &fp, false));
load(stream, separators, trimWhitespace);
}
//-----------------------------------------------------------------------
void ConfigFile::loadFromResourceSystem(const String& filename,
const String& resourceGroup, const String& separators, bool trimWhitespace)
{
DataStreamPtr stream =
ResourceGroupManager::getSingleton().openResource(filename, resourceGroup);
load(stream, separators, trimWhitespace);
}
//-----------------------------------------------------------------------
void ConfigFile::load(const DataStreamPtr& stream, const String& separators,
bool trimWhitespace)
{
/* Clear current settings map */
clear();
String currentSection = StringUtil::BLANK;
SettingsMultiMap* currentSettings = OGRE_NEW_T(SettingsMultiMap, MEMCATEGORY_GENERAL)();
mSettings[currentSection] = currentSettings;
/* Process the file line for line */
String line, optName, optVal;
while (!stream->eof())
{
line = stream->getLine();
/* Ignore comments & blanks */
if (line.length() > 0 && line.at(0) != '#' && line.at(0) != '@')
{
if (line.at(0) == '[' && line.at(line.length()-1) == ']')
{
// Section
currentSection = line.substr(1, line.length() - 2);
SettingsBySection::const_iterator seci = mSettings.find(currentSection);
if (seci == mSettings.end())
{
currentSettings = OGRE_NEW_T(SettingsMultiMap, MEMCATEGORY_GENERAL)();
mSettings[currentSection] = currentSettings;
}
else
{
currentSettings = seci->second;
}
}
else
{
/* Find the first seperator character and split the string there */
std::string::size_type separator_pos = line.find_first_of(separators, 0);
if (separator_pos != std::string::npos)
{
optName = line.substr(0, separator_pos);
/* Find the first non-seperator character following the name */
std::string::size_type nonseparator_pos = line.find_first_not_of(separators, separator_pos);
/* ... and extract the value */
/* Make sure we don't crash on an empty setting (it might be a valid value) */
optVal = (nonseparator_pos == std::string::npos) ? "" : line.substr(nonseparator_pos);
if (trimWhitespace)
{
StringUtil::trim(optVal);
StringUtil::trim(optName);
}
currentSettings->insert(std::multimap<String, String>::value_type(optName, optVal));
}
}
}
}
}
//-----------------------------------------------------------------------
String ConfigFile::getSetting(const String& key, const String& section, const String& defaultValue) const
{
SettingsBySection::const_iterator seci = mSettings.find(section);
if (seci == mSettings.end())
{
return defaultValue;
}
else
{
SettingsMultiMap::const_iterator i = seci->second->find(key);
if (i == seci->second->end())
{
return defaultValue;
}
else
{
return i->second;
}
}
}
//-----------------------------------------------------------------------
StringVector ConfigFile::getMultiSetting(const String& key, const String& section) const
{
StringVector ret;
SettingsBySection::const_iterator seci = mSettings.find(section);
if (seci != mSettings.end())
{
SettingsMultiMap::const_iterator i;
i = seci->second->find(key);
// Iterate over matches
while (i != seci->second->end() && i->first == key)
{
ret.push_back(i->second);
++i;
}
}
return ret;
}
//-----------------------------------------------------------------------
ConfigFile::SettingsIterator ConfigFile::getSettingsIterator(const String& section)
{
SettingsBySection::const_iterator seci = mSettings.find(section);
if (seci == mSettings.end())
{
OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND,
"Cannot find section " + section,
"ConfigFile::getSettingsIterator");
}
else
{
return SettingsIterator(seci->second->begin(), seci->second->end());
}
}
//-----------------------------------------------------------------------
ConfigFile::SectionIterator ConfigFile::getSectionIterator(void)
{
return SectionIterator(mSettings.begin(), mSettings.end());
}
}
<|endoftext|>
|
<commit_before>#include "DDR.h"
#include "VirtualMemory.h"
#include "sim/config.h"
#include "sim/log2.h"
#include <sstream>
#include <limits>
#include <cstdio>
namespace Simulator
{
template <typename T>
static T GET_BITS(const T& value, unsigned int offset, unsigned int size)
{
return (value >> offset) & ((T(1) << size) - 1);
}
static const unsigned long INVALID_ROW = std::numeric_limits<unsigned long>::max();
bool DDRChannel::Read(MemAddr address, MemSize size)
{
if (m_busy.IsSet())
{
// We're still busy
return false;
}
// Accept request
COMMIT
{
m_request.address = address;
m_request.offset = 0;
m_request.data.size = size;
m_request.write = false;
m_next_command = 0;
}
// Get the actual data
m_memory.Read(address, m_request.data.data, size);
if (!m_busy.Set())
{
return false;
}
return true;
}
bool DDRChannel::Write(MemAddr address, const void* data, MemSize size)
{
if (m_busy.IsSet())
{
// We're still busy
return false;
}
// Accept request
COMMIT
{
m_request.address = address;
m_request.offset = 0;
m_request.data.size = size;
m_request.write = true;
m_next_command = 0;
}
// Write the actual data
m_memory.Write(address, data, size);
if (!m_busy.Set())
{
return false;
}
return true;
}
// Main process for timing the current active request
Result DDRChannel::DoRequest()
{
assert(m_busy.IsSet());
const CycleNo now = GetClock().GetCycleNo();
if (now < m_next_command)
{
// Can't continue yet
return SUCCESS;
}
// We read from m_nDevicesPerRank devices, each providing m_nBurstLength bytes in the burst.
const unsigned burst_size = m_ddrconfig.m_nBurstSize;
// Decode the burst address and offset-within-burst
const MemAddr address = (m_request.address + m_request.offset) / burst_size;
const unsigned int offset = (m_request.address + m_request.offset) % burst_size;
const unsigned int rank = GET_BITS(address, m_ddrconfig.m_nRankStart, m_ddrconfig.m_nRankBits),
row = GET_BITS(address, m_ddrconfig.m_nRowStart, m_ddrconfig.m_nRowBits);
if (m_currentRow[rank] != row)
{
if (m_currentRow[rank] != INVALID_ROW)
{
// Precharge (close) the currently active row
COMMIT
{
m_next_command = std::max(m_next_precharge, now) + m_ddrconfig.m_tRP;
m_currentRow[rank] = INVALID_ROW;
}
return SUCCESS;
}
// Activate (open) the desired row
COMMIT
{
m_next_command = now + m_ddrconfig.m_tRCD;
m_next_precharge = now + m_ddrconfig.m_tRAS;
m_currentRow[rank] = row;
}
return SUCCESS;
}
// Process a single burst
unsigned int remainder = m_request.data.size - m_request.offset;
unsigned int size = std::min(burst_size - offset, remainder);
if (m_request.write)
{
COMMIT
{
// Update address to reflect written portion
m_request.offset += size;
m_next_command = now + m_ddrconfig.m_tCWL;
m_next_precharge = now + m_ddrconfig.m_tWR;
}
if (size < remainder)
{
// We're not done yet
return SUCCESS;
}
}
else
{
COMMIT
{
// Update address to reflect read portion
m_request.offset += size;
m_request.done = now + m_ddrconfig.m_tCL;
// Schedule next read
m_next_command = now + m_ddrconfig.m_tCCD;
}
if (size < remainder)
{
// We're not done yet
return SUCCESS;
}
// We're done with this read; queue it into the pipeline
if (!m_pipeline.Push(m_request))
{
// The read pipeline should be big enough
assert(false);
return FAILED;
}
}
// We've completed this request
if (!m_busy.Clear())
{
return FAILED;
}
return SUCCESS;
}
Result DDRChannel::DoPipeline()
{
assert(!m_pipeline.Empty());
const CycleNo now = GetClock().GetCycleNo();
const Request& request = m_pipeline.Front();
if (request.done >= now)
{
// The last burst has completed, send the assembled data back
assert(!request.write);
if (!m_callback->OnReadCompleted(request.address, request.data))
{
return FAILED;
}
m_pipeline.Pop();
}
return SUCCESS;
}
DDRChannel::DDRConfig::DDRConfig(const std::string& name, Object& parent, Clock& clock, Config& config)
: Object(name, parent, clock)
{
// DDR 3
m_nBurstLength = config.getValue<size_t> (*this, "BurstLength");
if (m_nBurstLength != 8)
throw SimulationException(*this, "This implementation only supports m_nBurstLength = 8");
size_t cellsize = config.getValue<size_t> (*this, "CellSize");
if (cellsize != 8)
throw SimulationException(*this, "This implementation only supports CellSize = 8");
m_tCL = config.getValue<unsigned> (*this, "tCL");
m_tRCD = config.getValue<unsigned> (*this, "tRCD");
m_tRP = config.getValue<unsigned> (*this, "tRP");
m_tRAS = config.getValue<unsigned> (*this, "tRAS");
m_tCWL = config.getValue<unsigned> (*this, "tCWL");
m_tCCD = config.getValue<unsigned> (*this, "tCCD");
// tWR is expressed in DDR specs in nanoseconds, see
// http://www.samsung.com/global/business/semiconductor/products/dram/downloads/applicationnote/tWR.pdf
// Frequency is in MHz.
m_tWR = config.getValue<unsigned> (*this, "tWR") / 1e3 * clock.GetFrequency();
// Address bit mapping.
// One row bit added for a 4GB DIMM with ECC.
m_nDevicesPerRank = config.getValue<size_t> (*this, "DevicesPerRank");
m_nRankBits = ilog2(config.getValue<size_t> (*this, "Ranks"));
m_nRowBits = config.getValue<size_t> (*this, "RowBits");
m_nColumnBits = config.getValue<size_t> (*this, "ColumnBits");
m_nBurstSize = m_nDevicesPerRank * m_nBurstLength;
// ordering of bits in address:
m_nColumnStart = 0;
m_nRowStart = m_nColumnStart + m_nColumnBits;
m_nRankStart = m_nRowStart + m_nRowBits;
}
DDRChannel::DDRChannel(const std::string& name, Object& parent, Clock& clock, VirtualMemory& memory, Config& config)
: Object(name, parent, clock),
m_registry(config),
m_ddrconfig("config", *this, clock, config),
// Initialize each rank at 'no row selected'
m_currentRow(1 << m_ddrconfig.m_nRankBits, INVALID_ROW),
m_memory(memory),
m_callback(0),
m_pipeline("b_pipeline", *this, clock, m_ddrconfig.m_tCL),
m_busy("f_busy", *this, clock, false),
m_next_command(0),
m_next_precharge(0),
p_Request (*this, "request", delegate::create<DDRChannel, &DDRChannel::DoRequest >(*this)),
p_Pipeline(*this, "pipeline", delegate::create<DDRChannel, &DDRChannel::DoPipeline>(*this))
{
m_busy.Sensitive(p_Request);
m_pipeline.Sensitive(p_Pipeline);
config.registerObject(*this, "ddr");
config.registerProperty(*this, "CL", (uint32_t)m_ddrconfig.m_tCL);
config.registerProperty(*this, "RCD", (uint32_t)m_ddrconfig.m_tRCD);
config.registerProperty(*this, "RP", (uint32_t)m_ddrconfig.m_tRP);
config.registerProperty(*this, "RAS", (uint32_t)m_ddrconfig.m_tRAS);
config.registerProperty(*this, "CWL", (uint32_t)m_ddrconfig.m_tCWL);
config.registerProperty(*this, "CCD", (uint32_t)m_ddrconfig.m_tCCD);
config.registerProperty(*this, "WR", (uint32_t)m_ddrconfig.m_tWR);
config.registerProperty(*this, "chips/rank", (uint32_t)m_ddrconfig.m_nDevicesPerRank);
config.registerProperty(*this, "ranks", (uint32_t)(1UL<<m_ddrconfig.m_nRankBits));
config.registerProperty(*this, "rows", (uint32_t)(1UL<<m_ddrconfig.m_nRowBits));
config.registerProperty(*this, "columns", (uint32_t)(1UL<<m_ddrconfig.m_nColumnBits));
config.registerProperty(*this, "freq", (uint32_t)clock.GetFrequency());
}
void DDRChannel::SetClient(ICallback& cb, StorageTraceSet& sts, const StorageTraceSet& storages)
{
if (m_callback != NULL)
{
throw InvalidArgumentException(*this, "DDR channel can be connected to at most one root directory.");
}
m_callback = &cb;
sts = m_busy;
p_Request.SetStorageTraces(opt(m_pipeline));
p_Pipeline.SetStorageTraces(opt(storages));
m_registry.registerBidiRelation(*this, cb, "ddr");
}
DDRChannel::~DDRChannel()
{
}
DDRChannelRegistry::DDRChannelRegistry(const std::string& name, Object& parent, VirtualMemory& memory, Config& config)
: Object(name, parent)
{
size_t numChannels = config.getValueOrDefault<size_t>(*this, "NumChannels",
config.getValue<size_t>(parent, "NumRootDirectories"));
for (size_t i = 0; i < numChannels; ++i)
{
std::stringstream ss;
ss << "channel" << i;
Clock &ddrclock = GetKernel()->CreateClock(config.getValue<size_t>(*this, ss.str(), "Freq"));
this->push_back(new DDRChannel(ss.str(), *this, ddrclock, memory, config));
}
}
DDRChannelRegistry::~DDRChannelRegistry()
{
for (size_t i = 0; i < size(); ++i)
delete (*this)[i];
}
}
<commit_msg>[mgsim] Fixed read completion timing bug in DDR.<commit_after>#include "DDR.h"
#include "VirtualMemory.h"
#include "sim/config.h"
#include "sim/log2.h"
#include <sstream>
#include <limits>
#include <cstdio>
namespace Simulator
{
template <typename T>
static T GET_BITS(const T& value, unsigned int offset, unsigned int size)
{
return (value >> offset) & ((T(1) << size) - 1);
}
static const unsigned long INVALID_ROW = std::numeric_limits<unsigned long>::max();
bool DDRChannel::Read(MemAddr address, MemSize size)
{
if (m_busy.IsSet())
{
// We're still busy
return false;
}
// Accept request
COMMIT
{
m_request.address = address;
m_request.offset = 0;
m_request.data.size = size;
m_request.write = false;
m_next_command = 0;
}
// Get the actual data
m_memory.Read(address, m_request.data.data, size);
if (!m_busy.Set())
{
return false;
}
return true;
}
bool DDRChannel::Write(MemAddr address, const void* data, MemSize size)
{
if (m_busy.IsSet())
{
// We're still busy
return false;
}
// Accept request
COMMIT
{
m_request.address = address;
m_request.offset = 0;
m_request.data.size = size;
m_request.write = true;
m_next_command = 0;
}
// Write the actual data
m_memory.Write(address, data, size);
if (!m_busy.Set())
{
return false;
}
return true;
}
// Main process for timing the current active request
Result DDRChannel::DoRequest()
{
assert(m_busy.IsSet());
const CycleNo now = GetClock().GetCycleNo();
if (now < m_next_command)
{
// Can't continue yet
return SUCCESS;
}
// We read from m_nDevicesPerRank devices, each providing m_nBurstLength bytes in the burst.
const unsigned burst_size = m_ddrconfig.m_nBurstSize;
// Decode the burst address and offset-within-burst
const MemAddr address = (m_request.address + m_request.offset) / burst_size;
const unsigned int offset = (m_request.address + m_request.offset) % burst_size;
const unsigned int rank = GET_BITS(address, m_ddrconfig.m_nRankStart, m_ddrconfig.m_nRankBits),
row = GET_BITS(address, m_ddrconfig.m_nRowStart, m_ddrconfig.m_nRowBits);
if (m_currentRow[rank] != row)
{
if (m_currentRow[rank] != INVALID_ROW)
{
// Precharge (close) the currently active row
COMMIT
{
m_next_command = std::max(m_next_precharge, now) + m_ddrconfig.m_tRP;
m_currentRow[rank] = INVALID_ROW;
}
return SUCCESS;
}
// Activate (open) the desired row
COMMIT
{
m_next_command = now + m_ddrconfig.m_tRCD;
m_next_precharge = now + m_ddrconfig.m_tRAS;
m_currentRow[rank] = row;
}
return SUCCESS;
}
// Process a single burst
unsigned int remainder = m_request.data.size - m_request.offset;
unsigned int size = std::min(burst_size - offset, remainder);
if (m_request.write)
{
COMMIT
{
// Update address to reflect written portion
m_request.offset += size;
m_next_command = now + m_ddrconfig.m_tCWL;
m_next_precharge = now + m_ddrconfig.m_tWR;
}
if (size < remainder)
{
// We're not done yet
return SUCCESS;
}
}
else
{
COMMIT
{
// Update address to reflect read portion
m_request.offset += size;
m_request.done = now + m_ddrconfig.m_tCL;
// Schedule next read
m_next_command = now + m_ddrconfig.m_tCCD;
}
if (size < remainder)
{
// We're not done yet
return SUCCESS;
}
// We're done with this read; queue it into the pipeline
if (!m_pipeline.Push(m_request))
{
// The read pipeline should be big enough
assert(false);
return FAILED;
}
}
// We've completed this request
if (!m_busy.Clear())
{
return FAILED;
}
return SUCCESS;
}
Result DDRChannel::DoPipeline()
{
assert(!m_pipeline.Empty());
const CycleNo now = GetClock().GetCycleNo();
const Request& request = m_pipeline.Front();
if (now >= request.done)
{
// The last burst has completed, send the assembled data back
assert(!request.write);
if (!m_callback->OnReadCompleted(request.address, request.data))
{
return FAILED;
}
m_pipeline.Pop();
}
return SUCCESS;
}
DDRChannel::DDRConfig::DDRConfig(const std::string& name, Object& parent, Clock& clock, Config& config)
: Object(name, parent, clock)
{
// DDR 3
m_nBurstLength = config.getValue<size_t> (*this, "BurstLength");
if (m_nBurstLength != 8)
throw SimulationException(*this, "This implementation only supports m_nBurstLength = 8");
size_t cellsize = config.getValue<size_t> (*this, "CellSize");
if (cellsize != 8)
throw SimulationException(*this, "This implementation only supports CellSize = 8");
m_tCL = config.getValue<unsigned> (*this, "tCL");
m_tRCD = config.getValue<unsigned> (*this, "tRCD");
m_tRP = config.getValue<unsigned> (*this, "tRP");
m_tRAS = config.getValue<unsigned> (*this, "tRAS");
m_tCWL = config.getValue<unsigned> (*this, "tCWL");
m_tCCD = config.getValue<unsigned> (*this, "tCCD");
// tWR is expressed in DDR specs in nanoseconds, see
// http://www.samsung.com/global/business/semiconductor/products/dram/downloads/applicationnote/tWR.pdf
// Frequency is in MHz.
m_tWR = config.getValue<unsigned> (*this, "tWR") / 1e3 * clock.GetFrequency();
// Address bit mapping.
// One row bit added for a 4GB DIMM with ECC.
m_nDevicesPerRank = config.getValue<size_t> (*this, "DevicesPerRank");
m_nRankBits = ilog2(config.getValue<size_t> (*this, "Ranks"));
m_nRowBits = config.getValue<size_t> (*this, "RowBits");
m_nColumnBits = config.getValue<size_t> (*this, "ColumnBits");
m_nBurstSize = m_nDevicesPerRank * m_nBurstLength;
// ordering of bits in address:
m_nColumnStart = 0;
m_nRowStart = m_nColumnStart + m_nColumnBits;
m_nRankStart = m_nRowStart + m_nRowBits;
}
DDRChannel::DDRChannel(const std::string& name, Object& parent, Clock& clock, VirtualMemory& memory, Config& config)
: Object(name, parent, clock),
m_registry(config),
m_ddrconfig("config", *this, clock, config),
// Initialize each rank at 'no row selected'
m_currentRow(1 << m_ddrconfig.m_nRankBits, INVALID_ROW),
m_memory(memory),
m_callback(0),
m_pipeline("b_pipeline", *this, clock, m_ddrconfig.m_tCL),
m_busy("f_busy", *this, clock, false),
m_next_command(0),
m_next_precharge(0),
p_Request (*this, "request", delegate::create<DDRChannel, &DDRChannel::DoRequest >(*this)),
p_Pipeline(*this, "pipeline", delegate::create<DDRChannel, &DDRChannel::DoPipeline>(*this))
{
m_busy.Sensitive(p_Request);
m_pipeline.Sensitive(p_Pipeline);
config.registerObject(*this, "ddr");
config.registerProperty(*this, "CL", (uint32_t)m_ddrconfig.m_tCL);
config.registerProperty(*this, "RCD", (uint32_t)m_ddrconfig.m_tRCD);
config.registerProperty(*this, "RP", (uint32_t)m_ddrconfig.m_tRP);
config.registerProperty(*this, "RAS", (uint32_t)m_ddrconfig.m_tRAS);
config.registerProperty(*this, "CWL", (uint32_t)m_ddrconfig.m_tCWL);
config.registerProperty(*this, "CCD", (uint32_t)m_ddrconfig.m_tCCD);
config.registerProperty(*this, "WR", (uint32_t)m_ddrconfig.m_tWR);
config.registerProperty(*this, "chips/rank", (uint32_t)m_ddrconfig.m_nDevicesPerRank);
config.registerProperty(*this, "ranks", (uint32_t)(1UL<<m_ddrconfig.m_nRankBits));
config.registerProperty(*this, "rows", (uint32_t)(1UL<<m_ddrconfig.m_nRowBits));
config.registerProperty(*this, "columns", (uint32_t)(1UL<<m_ddrconfig.m_nColumnBits));
config.registerProperty(*this, "freq", (uint32_t)clock.GetFrequency());
}
void DDRChannel::SetClient(ICallback& cb, StorageTraceSet& sts, const StorageTraceSet& storages)
{
if (m_callback != NULL)
{
throw InvalidArgumentException(*this, "DDR channel can be connected to at most one root directory.");
}
m_callback = &cb;
sts = m_busy;
p_Request.SetStorageTraces(opt(m_pipeline));
p_Pipeline.SetStorageTraces(opt(storages));
m_registry.registerBidiRelation(*this, cb, "ddr");
}
DDRChannel::~DDRChannel()
{
}
DDRChannelRegistry::DDRChannelRegistry(const std::string& name, Object& parent, VirtualMemory& memory, Config& config)
: Object(name, parent)
{
size_t numChannels = config.getValueOrDefault<size_t>(*this, "NumChannels",
config.getValue<size_t>(parent, "NumRootDirectories"));
for (size_t i = 0; i < numChannels; ++i)
{
std::stringstream ss;
ss << "channel" << i;
Clock &ddrclock = GetKernel()->CreateClock(config.getValue<size_t>(*this, ss.str(), "Freq"));
this->push_back(new DDRChannel(ss.str(), *this, ddrclock, memory, config));
}
}
DDRChannelRegistry::~DDRChannelRegistry()
{
for (size_t i = 0; i < size(); ++i)
delete (*this)[i];
}
}
<|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 <limits>
#include "chrome/browser/jankometer.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/metrics/stats_counters.h"
#include "base/ref_counted.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "base/time.h"
#include "base/watchdog.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/common/chrome_switches.h"
#if defined(TOOLKIT_USES_GTK)
#include "chrome/browser/gtk/gtk_util.h"
#endif
using base::TimeDelta;
using base::TimeTicks;
namespace {
// The maximum threshold of delay of the message before considering it a delay.
// For a debug build, you may want to set IO delay around 500ms.
// For a release build, setting it around 350ms is sensible.
// Visit about:histograms to see what the distribution is on your system, with
// your build. Be sure to do some work to get interesting stats.
// The numbers below came from a warm start (you'll get about 5-10 alarms with
// a cold start), and running the page-cycler for 5 rounds.
#ifdef NDEBUG
const int kMaxUIMessageDelayMs = 350;
const int kMaxIOMessageDelayMs = 200;
#else
const int kMaxUIMessageDelayMs = 500;
const int kMaxIOMessageDelayMs = 400;
#endif
// Maximum processing time (excluding queueing delay) for a message before
// considering it delayed.
const int kMaxMessageProcessingMs = 100;
// TODO(brettw) Consider making this a pref.
const bool kPlaySounds = false;
//------------------------------------------------------------------------------
// Provide a special watchdog to make it easy to set the breakpoint on this
// class only.
class JankWatchdog : public Watchdog {
public:
JankWatchdog(const TimeDelta& duration,
const std::string& thread_watched_name,
bool enabled)
: Watchdog(duration, thread_watched_name, enabled),
thread_name_watched_(thread_watched_name),
alarm_count_(0) {
}
virtual ~JankWatchdog() {}
virtual void Alarm() {
// Put break point here if you want to stop threads and look at what caused
// the jankiness.
alarm_count_++;
Watchdog::Alarm();
}
private:
std::string thread_name_watched_;
int alarm_count_;
DISALLOW_COPY_AND_ASSIGN(JankWatchdog);
};
class JankObserverHelper {
public:
JankObserverHelper(const std::string& thread_name,
const TimeDelta& excessive_duration,
bool watchdog_enable);
~JankObserverHelper();
void StartProcessingTimers(const TimeDelta& queueing_time);
void EndProcessingTimers();
// Indicate if we will bother to measuer this message.
bool MessageWillBeMeasured();
static void SetDefaultMessagesToSkip(int count) { discard_count_ = count; }
private:
const TimeDelta max_message_delay_;
// Indicate if we'll bother measuring this message.
bool measure_current_message_;
// Down counter which will periodically hit 0, and only then bother to measure
// the corresponding message.
int events_till_measurement_;
// The value to re-initialize events_till_measurement_ after it reaches 0.
static int discard_count_;
// Time at which the current message processing began.
TimeTicks begin_process_message_;
// Time the current message spent in the queue -- delta between message
// construction time and message processing time.
TimeDelta queueing_time_;
// Counters for the two types of jank we measure.
base::StatsCounter slow_processing_counter_; // Msgs w/ long proc time.
base::StatsCounter queueing_delay_counter_; // Msgs w/ long queueing delay.
scoped_refptr<base::Histogram> process_times_; // Time spent proc. task.
scoped_refptr<base::Histogram> total_times_; // Total queueing plus proc.
JankWatchdog total_time_watchdog_; // Watching for excessive total_time.
DISALLOW_COPY_AND_ASSIGN(JankObserverHelper);
};
JankObserverHelper::JankObserverHelper(
const std::string& thread_name,
const TimeDelta& excessive_duration,
bool watchdog_enable)
: max_message_delay_(excessive_duration),
measure_current_message_(true),
events_till_measurement_(0),
slow_processing_counter_(std::string("Chrome.SlowMsg") + thread_name),
queueing_delay_counter_(std::string("Chrome.DelayMsg") + thread_name),
total_time_watchdog_(excessive_duration, thread_name, watchdog_enable) {
process_times_ = base::Histogram::FactoryGet(
std::string("Chrome.ProcMsgL ") + thread_name,
1, 3600000, 50, base::Histogram::kUmaTargetedHistogramFlag);
total_times_ = base::Histogram::FactoryGet(
std::string("Chrome.TotalMsgL ") + thread_name,
1, 3600000, 50, base::Histogram::kUmaTargetedHistogramFlag);
if (discard_count_ > 0) {
// Select a vaguely random sample-start-point.
events_till_measurement_ =
(TimeTicks::Now() - TimeTicks()).InSeconds() % (discard_count_ + 1);
}
}
JankObserverHelper::~JankObserverHelper() {}
// Called when a message has just begun processing, initializes
// per-message variables and timers.
void JankObserverHelper::StartProcessingTimers(const TimeDelta& queueing_time) {
DCHECK(measure_current_message_);
begin_process_message_ = TimeTicks::Now();
queueing_time_ = queueing_time;
// Simulate arming when the message entered the queue.
total_time_watchdog_.ArmSomeTimeDeltaAgo(queueing_time_);
if (queueing_time_ > max_message_delay_) {
// Message is too delayed.
queueing_delay_counter_.Increment();
#if defined(OS_WIN)
if (kPlaySounds)
MessageBeep(MB_ICONASTERISK);
#endif
}
}
// Called when a message has just finished processing, finalizes
// per-message variables and timers.
void JankObserverHelper::EndProcessingTimers() {
if (!measure_current_message_)
return;
total_time_watchdog_.Disarm();
TimeTicks now = TimeTicks::Now();
if (begin_process_message_ != TimeTicks()) {
TimeDelta processing_time = now - begin_process_message_;
process_times_->AddTime(processing_time);
total_times_->AddTime(queueing_time_ + processing_time);
}
if (now - begin_process_message_ >
TimeDelta::FromMilliseconds(kMaxMessageProcessingMs)) {
// Message took too long to process.
slow_processing_counter_.Increment();
#if defined(OS_WIN)
if (kPlaySounds)
MessageBeep(MB_ICONHAND);
#endif
}
// Reset message specific times.
begin_process_message_ = base::TimeTicks();
queueing_time_ = base::TimeDelta();
}
bool JankObserverHelper::MessageWillBeMeasured() {
measure_current_message_ = events_till_measurement_ <= 0;
if (!measure_current_message_)
--events_till_measurement_;
else
events_till_measurement_ = discard_count_;
return measure_current_message_;
}
// static
int JankObserverHelper::discard_count_ = 99; // Measure only 1 in 100.
//------------------------------------------------------------------------------
class IOJankObserver : public base::RefCountedThreadSafe<IOJankObserver>,
public MessageLoopForIO::IOObserver,
public MessageLoop::TaskObserver {
public:
IOJankObserver(const char* thread_name,
TimeDelta excessive_duration,
bool watchdog_enable)
: helper_(thread_name, excessive_duration, watchdog_enable) {}
~IOJankObserver() {}
// Attaches the observer to the current thread's message loop. You can only
// attach to the current thread, so this function can be invoked on another
// thread to attach it.
void AttachToCurrentThread() {
MessageLoop::current()->AddTaskObserver(this);
MessageLoopForIO::current()->AddIOObserver(this);
}
// Detaches the observer to the current thread's message loop.
void DetachFromCurrentThread() {
MessageLoopForIO::current()->RemoveIOObserver(this);
MessageLoop::current()->RemoveTaskObserver(this);
}
virtual void WillProcessIOEvent() {
if (!helper_.MessageWillBeMeasured())
return;
helper_.StartProcessingTimers(base::TimeDelta());
}
virtual void DidProcessIOEvent() {
helper_.EndProcessingTimers();
}
virtual void WillProcessTask(const Task* task) {
if (!helper_.MessageWillBeMeasured())
return;
base::TimeTicks now = base::TimeTicks::Now();
const base::TimeDelta queueing_time = now - task->tracked_birth_time();
helper_.StartProcessingTimers(queueing_time);
}
virtual void DidProcessTask(const Task* task) {
helper_.EndProcessingTimers();
}
private:
friend class base::RefCountedThreadSafe<IOJankObserver>;
JankObserverHelper helper_;
DISALLOW_COPY_AND_ASSIGN(IOJankObserver);
};
//------------------------------------------------------------------------------
class UIJankObserver : public base::RefCountedThreadSafe<UIJankObserver>,
public MessageLoop::TaskObserver,
public MessageLoopForUI::Observer {
public:
UIJankObserver(const char* thread_name,
TimeDelta excessive_duration,
bool watchdog_enable)
: helper_(thread_name, excessive_duration, watchdog_enable) {}
// Attaches the observer to the current thread's message loop. You can only
// attach to the current thread, so this function can be invoked on another
// thread to attach it.
void AttachToCurrentThread() {
DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI);
MessageLoopForUI::current()->AddObserver(this);
MessageLoop::current()->AddTaskObserver(this);
}
// Detaches the observer to the current thread's message loop.
void DetachFromCurrentThread() {
DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI);
MessageLoop::current()->RemoveTaskObserver(this);
MessageLoopForUI::current()->RemoveObserver(this);
}
virtual void WillProcessTask(const Task* task) {
if (!helper_.MessageWillBeMeasured())
return;
base::TimeTicks now = base::TimeTicks::Now();
const base::TimeDelta queueing_time = now - task->tracked_birth_time();
helper_.StartProcessingTimers(queueing_time);
}
virtual void DidProcessTask(const Task* task) {
helper_.EndProcessingTimers();
}
#if defined(OS_WIN)
virtual void WillProcessMessage(const MSG& msg) {
if (!helper_.MessageWillBeMeasured())
return;
// GetMessageTime returns a LONG (signed 32-bit) and GetTickCount returns
// a DWORD (unsigned 32-bit). They both wrap around when the time is longer
// than they can hold. I'm not sure if GetMessageTime wraps around to 0,
// or if the original time comes from GetTickCount, it might wrap around
// to -1.
//
// Therefore, I cast to DWORD so if it wraps to -1 we will correct it. If
// it doesn't, then our time delta will be negative if a message happens
// to straddle the wraparound point, it will still be OK.
DWORD cur_message_issue_time = static_cast<DWORD>(msg.time);
DWORD cur_time = GetTickCount();
base::TimeDelta queueing_time =
base::TimeDelta::FromMilliseconds(cur_time - cur_message_issue_time);
helper_.StartProcessingTimers(queueing_time);
}
virtual void DidProcessMessage(const MSG& msg) {
helper_.EndProcessingTimers();
}
#elif defined(TOOLKIT_USES_GTK)
virtual void WillProcessEvent(GdkEvent* event) {
if (!helper_.MessageWillBeMeasured())
return;
// TODO(evanm): we want to set queueing_time_ using
// gdk_event_get_time, but how do you convert that info
// into a delta?
// guint event_time = gdk_event_get_time(event);
base::TimeDelta queueing_time = base::TimeDelta::FromMilliseconds(0);
helper_.StartProcessingTimers(queueing_time);
}
virtual void DidProcessEvent(GdkEvent* event) {
helper_.EndProcessingTimers();
}
#endif
private:
friend class base::RefCountedThreadSafe<UIJankObserver>;
~UIJankObserver() {}
JankObserverHelper helper_;
DISALLOW_COPY_AND_ASSIGN(UIJankObserver);
};
// These objects are created by InstallJankometer and leaked.
const scoped_refptr<UIJankObserver>* ui_observer = NULL;
const scoped_refptr<IOJankObserver>* io_observer = NULL;
} // namespace
void InstallJankometer(const CommandLine& parsed_command_line) {
if (ui_observer || io_observer) {
NOTREACHED() << "Initializing jank-o-meter twice";
return;
}
bool ui_watchdog_enabled = false;
bool io_watchdog_enabled = false;
if (parsed_command_line.HasSwitch(switches::kEnableWatchdog)) {
std::string list =
parsed_command_line.GetSwitchValueASCII(switches::kEnableWatchdog);
if (list.npos != list.find("ui"))
ui_watchdog_enabled = true;
if (list.npos != list.find("io"))
io_watchdog_enabled = true;
}
if (ui_watchdog_enabled || io_watchdog_enabled)
JankObserverHelper::SetDefaultMessagesToSkip(0); // Watch everything.
// Install on the UI thread.
ui_observer = new scoped_refptr<UIJankObserver>(
new UIJankObserver(
"UI",
TimeDelta::FromMilliseconds(kMaxUIMessageDelayMs),
ui_watchdog_enabled));
(*ui_observer)->AttachToCurrentThread();
// Now install on the I/O thread. Hiccups on that thread will block
// interaction with web pages. We must proxy to that thread before we can
// add our observer.
io_observer = new scoped_refptr<IOJankObserver>(
new IOJankObserver(
"IO",
TimeDelta::FromMilliseconds(kMaxIOMessageDelayMs),
io_watchdog_enabled));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(io_observer->get(),
&IOJankObserver::AttachToCurrentThread));
}
void UninstallJankometer() {
if (ui_observer) {
(*ui_observer)->DetachFromCurrentThread();
delete ui_observer;
ui_observer = NULL;
}
if (io_observer) {
// IO thread can't be running when we remove observers.
DCHECK((!g_browser_process) || !(g_browser_process->io_thread()));
delete io_observer;
io_observer = NULL;
}
}
<commit_msg>Add static cast to remove warning about loss of precision<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 <limits>
#include "chrome/browser/jankometer.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/metrics/stats_counters.h"
#include "base/ref_counted.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "base/time.h"
#include "base/watchdog.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/common/chrome_switches.h"
#if defined(TOOLKIT_USES_GTK)
#include "chrome/browser/gtk/gtk_util.h"
#endif
using base::TimeDelta;
using base::TimeTicks;
namespace {
// The maximum threshold of delay of the message before considering it a delay.
// For a debug build, you may want to set IO delay around 500ms.
// For a release build, setting it around 350ms is sensible.
// Visit about:histograms to see what the distribution is on your system, with
// your build. Be sure to do some work to get interesting stats.
// The numbers below came from a warm start (you'll get about 5-10 alarms with
// a cold start), and running the page-cycler for 5 rounds.
#ifdef NDEBUG
const int kMaxUIMessageDelayMs = 350;
const int kMaxIOMessageDelayMs = 200;
#else
const int kMaxUIMessageDelayMs = 500;
const int kMaxIOMessageDelayMs = 400;
#endif
// Maximum processing time (excluding queueing delay) for a message before
// considering it delayed.
const int kMaxMessageProcessingMs = 100;
// TODO(brettw) Consider making this a pref.
const bool kPlaySounds = false;
//------------------------------------------------------------------------------
// Provide a special watchdog to make it easy to set the breakpoint on this
// class only.
class JankWatchdog : public Watchdog {
public:
JankWatchdog(const TimeDelta& duration,
const std::string& thread_watched_name,
bool enabled)
: Watchdog(duration, thread_watched_name, enabled),
thread_name_watched_(thread_watched_name),
alarm_count_(0) {
}
virtual ~JankWatchdog() {}
virtual void Alarm() {
// Put break point here if you want to stop threads and look at what caused
// the jankiness.
alarm_count_++;
Watchdog::Alarm();
}
private:
std::string thread_name_watched_;
int alarm_count_;
DISALLOW_COPY_AND_ASSIGN(JankWatchdog);
};
class JankObserverHelper {
public:
JankObserverHelper(const std::string& thread_name,
const TimeDelta& excessive_duration,
bool watchdog_enable);
~JankObserverHelper();
void StartProcessingTimers(const TimeDelta& queueing_time);
void EndProcessingTimers();
// Indicate if we will bother to measuer this message.
bool MessageWillBeMeasured();
static void SetDefaultMessagesToSkip(int count) { discard_count_ = count; }
private:
const TimeDelta max_message_delay_;
// Indicate if we'll bother measuring this message.
bool measure_current_message_;
// Down counter which will periodically hit 0, and only then bother to measure
// the corresponding message.
int events_till_measurement_;
// The value to re-initialize events_till_measurement_ after it reaches 0.
static int discard_count_;
// Time at which the current message processing began.
TimeTicks begin_process_message_;
// Time the current message spent in the queue -- delta between message
// construction time and message processing time.
TimeDelta queueing_time_;
// Counters for the two types of jank we measure.
base::StatsCounter slow_processing_counter_; // Msgs w/ long proc time.
base::StatsCounter queueing_delay_counter_; // Msgs w/ long queueing delay.
scoped_refptr<base::Histogram> process_times_; // Time spent proc. task.
scoped_refptr<base::Histogram> total_times_; // Total queueing plus proc.
JankWatchdog total_time_watchdog_; // Watching for excessive total_time.
DISALLOW_COPY_AND_ASSIGN(JankObserverHelper);
};
JankObserverHelper::JankObserverHelper(
const std::string& thread_name,
const TimeDelta& excessive_duration,
bool watchdog_enable)
: max_message_delay_(excessive_duration),
measure_current_message_(true),
events_till_measurement_(0),
slow_processing_counter_(std::string("Chrome.SlowMsg") + thread_name),
queueing_delay_counter_(std::string("Chrome.DelayMsg") + thread_name),
total_time_watchdog_(excessive_duration, thread_name, watchdog_enable) {
process_times_ = base::Histogram::FactoryGet(
std::string("Chrome.ProcMsgL ") + thread_name,
1, 3600000, 50, base::Histogram::kUmaTargetedHistogramFlag);
total_times_ = base::Histogram::FactoryGet(
std::string("Chrome.TotalMsgL ") + thread_name,
1, 3600000, 50, base::Histogram::kUmaTargetedHistogramFlag);
if (discard_count_ > 0) {
// Select a vaguely random sample-start-point.
events_till_measurement_ = static_cast<int>(
(TimeTicks::Now() - TimeTicks()).InSeconds() % (discard_count_ + 1));
}
}
JankObserverHelper::~JankObserverHelper() {}
// Called when a message has just begun processing, initializes
// per-message variables and timers.
void JankObserverHelper::StartProcessingTimers(const TimeDelta& queueing_time) {
DCHECK(measure_current_message_);
begin_process_message_ = TimeTicks::Now();
queueing_time_ = queueing_time;
// Simulate arming when the message entered the queue.
total_time_watchdog_.ArmSomeTimeDeltaAgo(queueing_time_);
if (queueing_time_ > max_message_delay_) {
// Message is too delayed.
queueing_delay_counter_.Increment();
#if defined(OS_WIN)
if (kPlaySounds)
MessageBeep(MB_ICONASTERISK);
#endif
}
}
// Called when a message has just finished processing, finalizes
// per-message variables and timers.
void JankObserverHelper::EndProcessingTimers() {
if (!measure_current_message_)
return;
total_time_watchdog_.Disarm();
TimeTicks now = TimeTicks::Now();
if (begin_process_message_ != TimeTicks()) {
TimeDelta processing_time = now - begin_process_message_;
process_times_->AddTime(processing_time);
total_times_->AddTime(queueing_time_ + processing_time);
}
if (now - begin_process_message_ >
TimeDelta::FromMilliseconds(kMaxMessageProcessingMs)) {
// Message took too long to process.
slow_processing_counter_.Increment();
#if defined(OS_WIN)
if (kPlaySounds)
MessageBeep(MB_ICONHAND);
#endif
}
// Reset message specific times.
begin_process_message_ = base::TimeTicks();
queueing_time_ = base::TimeDelta();
}
bool JankObserverHelper::MessageWillBeMeasured() {
measure_current_message_ = events_till_measurement_ <= 0;
if (!measure_current_message_)
--events_till_measurement_;
else
events_till_measurement_ = discard_count_;
return measure_current_message_;
}
// static
int JankObserverHelper::discard_count_ = 99; // Measure only 1 in 100.
//------------------------------------------------------------------------------
class IOJankObserver : public base::RefCountedThreadSafe<IOJankObserver>,
public MessageLoopForIO::IOObserver,
public MessageLoop::TaskObserver {
public:
IOJankObserver(const char* thread_name,
TimeDelta excessive_duration,
bool watchdog_enable)
: helper_(thread_name, excessive_duration, watchdog_enable) {}
~IOJankObserver() {}
// Attaches the observer to the current thread's message loop. You can only
// attach to the current thread, so this function can be invoked on another
// thread to attach it.
void AttachToCurrentThread() {
MessageLoop::current()->AddTaskObserver(this);
MessageLoopForIO::current()->AddIOObserver(this);
}
// Detaches the observer to the current thread's message loop.
void DetachFromCurrentThread() {
MessageLoopForIO::current()->RemoveIOObserver(this);
MessageLoop::current()->RemoveTaskObserver(this);
}
virtual void WillProcessIOEvent() {
if (!helper_.MessageWillBeMeasured())
return;
helper_.StartProcessingTimers(base::TimeDelta());
}
virtual void DidProcessIOEvent() {
helper_.EndProcessingTimers();
}
virtual void WillProcessTask(const Task* task) {
if (!helper_.MessageWillBeMeasured())
return;
base::TimeTicks now = base::TimeTicks::Now();
const base::TimeDelta queueing_time = now - task->tracked_birth_time();
helper_.StartProcessingTimers(queueing_time);
}
virtual void DidProcessTask(const Task* task) {
helper_.EndProcessingTimers();
}
private:
friend class base::RefCountedThreadSafe<IOJankObserver>;
JankObserverHelper helper_;
DISALLOW_COPY_AND_ASSIGN(IOJankObserver);
};
//------------------------------------------------------------------------------
class UIJankObserver : public base::RefCountedThreadSafe<UIJankObserver>,
public MessageLoop::TaskObserver,
public MessageLoopForUI::Observer {
public:
UIJankObserver(const char* thread_name,
TimeDelta excessive_duration,
bool watchdog_enable)
: helper_(thread_name, excessive_duration, watchdog_enable) {}
// Attaches the observer to the current thread's message loop. You can only
// attach to the current thread, so this function can be invoked on another
// thread to attach it.
void AttachToCurrentThread() {
DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI);
MessageLoopForUI::current()->AddObserver(this);
MessageLoop::current()->AddTaskObserver(this);
}
// Detaches the observer to the current thread's message loop.
void DetachFromCurrentThread() {
DCHECK_EQ(MessageLoop::current()->type(), MessageLoop::TYPE_UI);
MessageLoop::current()->RemoveTaskObserver(this);
MessageLoopForUI::current()->RemoveObserver(this);
}
virtual void WillProcessTask(const Task* task) {
if (!helper_.MessageWillBeMeasured())
return;
base::TimeTicks now = base::TimeTicks::Now();
const base::TimeDelta queueing_time = now - task->tracked_birth_time();
helper_.StartProcessingTimers(queueing_time);
}
virtual void DidProcessTask(const Task* task) {
helper_.EndProcessingTimers();
}
#if defined(OS_WIN)
virtual void WillProcessMessage(const MSG& msg) {
if (!helper_.MessageWillBeMeasured())
return;
// GetMessageTime returns a LONG (signed 32-bit) and GetTickCount returns
// a DWORD (unsigned 32-bit). They both wrap around when the time is longer
// than they can hold. I'm not sure if GetMessageTime wraps around to 0,
// or if the original time comes from GetTickCount, it might wrap around
// to -1.
//
// Therefore, I cast to DWORD so if it wraps to -1 we will correct it. If
// it doesn't, then our time delta will be negative if a message happens
// to straddle the wraparound point, it will still be OK.
DWORD cur_message_issue_time = static_cast<DWORD>(msg.time);
DWORD cur_time = GetTickCount();
base::TimeDelta queueing_time =
base::TimeDelta::FromMilliseconds(cur_time - cur_message_issue_time);
helper_.StartProcessingTimers(queueing_time);
}
virtual void DidProcessMessage(const MSG& msg) {
helper_.EndProcessingTimers();
}
#elif defined(TOOLKIT_USES_GTK)
virtual void WillProcessEvent(GdkEvent* event) {
if (!helper_.MessageWillBeMeasured())
return;
// TODO(evanm): we want to set queueing_time_ using
// gdk_event_get_time, but how do you convert that info
// into a delta?
// guint event_time = gdk_event_get_time(event);
base::TimeDelta queueing_time = base::TimeDelta::FromMilliseconds(0);
helper_.StartProcessingTimers(queueing_time);
}
virtual void DidProcessEvent(GdkEvent* event) {
helper_.EndProcessingTimers();
}
#endif
private:
friend class base::RefCountedThreadSafe<UIJankObserver>;
~UIJankObserver() {}
JankObserverHelper helper_;
DISALLOW_COPY_AND_ASSIGN(UIJankObserver);
};
// These objects are created by InstallJankometer and leaked.
const scoped_refptr<UIJankObserver>* ui_observer = NULL;
const scoped_refptr<IOJankObserver>* io_observer = NULL;
} // namespace
void InstallJankometer(const CommandLine& parsed_command_line) {
if (ui_observer || io_observer) {
NOTREACHED() << "Initializing jank-o-meter twice";
return;
}
bool ui_watchdog_enabled = false;
bool io_watchdog_enabled = false;
if (parsed_command_line.HasSwitch(switches::kEnableWatchdog)) {
std::string list =
parsed_command_line.GetSwitchValueASCII(switches::kEnableWatchdog);
if (list.npos != list.find("ui"))
ui_watchdog_enabled = true;
if (list.npos != list.find("io"))
io_watchdog_enabled = true;
}
if (ui_watchdog_enabled || io_watchdog_enabled)
JankObserverHelper::SetDefaultMessagesToSkip(0); // Watch everything.
// Install on the UI thread.
ui_observer = new scoped_refptr<UIJankObserver>(
new UIJankObserver(
"UI",
TimeDelta::FromMilliseconds(kMaxUIMessageDelayMs),
ui_watchdog_enabled));
(*ui_observer)->AttachToCurrentThread();
// Now install on the I/O thread. Hiccups on that thread will block
// interaction with web pages. We must proxy to that thread before we can
// add our observer.
io_observer = new scoped_refptr<IOJankObserver>(
new IOJankObserver(
"IO",
TimeDelta::FromMilliseconds(kMaxIOMessageDelayMs),
io_watchdog_enabled));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(io_observer->get(),
&IOJankObserver::AttachToCurrentThread));
}
void UninstallJankometer() {
if (ui_observer) {
(*ui_observer)->DetachFromCurrentThread();
delete ui_observer;
ui_observer = NULL;
}
if (io_observer) {
// IO thread can't be running when we remove observers.
DCHECK((!g_browser_process) || !(g_browser_process->io_thread()));
delete io_observer;
io_observer = NULL;
}
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef STRING_H
#define STRING_H
#include <types.hpp>
#include <algorithms.hpp>
#include <vector.hpp>
namespace std {
inline uint64_t str_len(const char* a){
uint64_t length = 0;
while(*a++){
++length;
}
return length;
}
template<typename CharT>
struct basic_string {
public:
typedef CharT* iterator;
typedef const CharT* const_iterator;
private:
size_t _size;
size_t _capacity;
CharT* _data;
public:
//Constructors
basic_string() : _size(0), _capacity(1), _data(new CharT[1]) {
_data[0] = '\0';
}
basic_string(const CharT* s) : _size(str_len(s)), _capacity(_size + 1), _data(new CharT[_capacity]) {
std::copy_n(_data, s, _capacity);
}
explicit basic_string(size_t __capacity) : _size(0), _capacity(__capacity), _data(new CharT[_capacity]) {
_data[0] = '\0';
}
//Copy constructors
basic_string(const basic_string& rhs) : _size(rhs._size), _capacity(rhs._capacity), _data(new CharT[_capacity]) {
std::copy_n(_data, rhs._data, _size + 1);
}
basic_string& operator=(const basic_string& rhs){
if(this != &rhs){
if(_capacity < rhs._capacity || !_data){
if(_data){
delete[] _data;
}
_capacity = rhs._capacity;
_data = new CharT[_capacity];
}
_size = rhs._size;
std::copy_n(_data, rhs._data, _size + 1);
}
return *this;
}
//Move constructors
basic_string(basic_string&& rhs) : _size(rhs._size), _capacity(rhs._capacity), _data(rhs._data) {
rhs._size = 0;
rhs._capacity = 0;
rhs._data = nullptr;
}
basic_string& operator=(basic_string&& rhs){
if(_data){
delete[] _data;
}
_size = rhs._size;
_capacity = rhs._capacity;
_data = rhs._data;
rhs._size = 0;
rhs._capacity = 0;
rhs._data = nullptr;
return *this;
}
//Destructors
~basic_string(){
if(_data){
delete[] _data;
}
}
//Modifiers
void clear(){
_size = 0;
_data[0] = '\0';
}
void pop_back(){
_data[--_size] = '\0';
}
basic_string operator+(CharT c) const {
basic_string copy(*this);
copy += c;
return move(copy);
}
basic_string& operator+=(CharT c){
if(!_data || _capacity <= _size + 1){
_capacity = _capacity ? _capacity * 2 : 1;
auto new_data = new CharT[_capacity];
if(_data){
std::copy_n(new_data, _data, _size);
delete[] _data;
}
_data = new_data;
}
_data[_size] = c;
_data[++_size] = '\0';
return *this;
}
basic_string& operator+=(const char* rhs){
auto len = str_len(rhs);
if(!_data || _capacity <= _size + len){
_capacity = _capacity ? _capacity * 2 : 1;
if(_capacity < _size + len){
_capacity = _size + len + 1;
}
auto new_data = new CharT[_capacity];
if(_data){
std::copy_n(new_data, _data, _size);
delete[] _data;
}
_data = new_data;
}
std::copy_n(_data + _size, rhs, len);
_size += len;
_data[_size] = '\0';
return *this;
}
basic_string& operator+=(const basic_string& rhs){
if(!_data || _capacity <= _size + rhs.size()){
_capacity = _capacity ? _capacity * 2 : 1;
if(_capacity < _size + rhs.size()){
_capacity = _size + rhs.size() + 1;
}
auto new_data = new CharT[_capacity];
if(_data){
std::copy_n(new_data, _data, _size);
delete[] _data;
}
_data = new_data;
}
std::copy_n(_data + _size, rhs.c_str(), rhs.size());
_size += rhs.size();
_data[_size] = '\0';
return *this;
}
//Accessors
size_t size() const {
return _size;
}
size_t capacity() const {
return _capacity;
}
bool empty() const {
return !_size;
}
CharT* c_str(){
return _data;
}
const CharT* c_str() const {
return _data;
}
CharT& operator[](size_t i){
return _data[i];
}
const CharT& operator[](size_t i) const {
return _data[i];
}
//Operators
bool operator==(const CharT* s) const {
if(size() != str_len(s)){
return false;
}
for(size_t i = 0; i < size(); ++i){
if(_data[i] != s[i]){
return false;
}
}
return true;
}
bool operator==(const basic_string& rhs) const {
if(size() != rhs.size()){
return false;
}
for(size_t i = 0; i < size(); ++i){
if(_data[i] != rhs._data[i]){
return false;
}
}
return true;
}
//Iterators
iterator begin(){
return iterator(&_data[0]);
}
iterator end(){
return iterator(&_data[_size]);
}
const_iterator begin() const {
return const_iterator(&_data[0]);
}
const_iterator end() const {
return const_iterator(&_data[_size]);
}
};
typedef basic_string<char> string;
inline uint64_t parse(const char* it, const char* end){
int i = end - it - 1;
uint64_t factor = 1;
uint64_t acc = 0;
for(; i >= 0; --i){
acc += (it[i] - '0') * factor;
factor *= 10;
}
return acc;
}
inline uint64_t parse(const char* str){
int i = 0;
const char* it = str;
while(*++it){
++i;
}
uint64_t factor = 1;
uint64_t acc = 0;
for(; i >= 0; --i){
acc += (str[i] - '0') * factor;
factor *= 10;
}
return acc;
}
inline uint64_t parse(const string& str){
return parse(str.begin(), str.end());
}
template<typename N>
size_t digits(N number){
if(number < 10){
return 1;
}
size_t i = 0;
while(number != 0){
number /= 10;
++i;
}
return i;
}
template<typename Char>
std::vector<std::basic_string<Char>> split(const std::basic_string<Char>& s){
std::vector<std::basic_string<Char>> parts;
std::basic_string<Char> current(s.size());
for(char c : s){
if(c == ' ' && !current.empty()){
parts.push_back(current);
current.clear();
} else {
current += c;
}
}
if(!current.empty()){
parts.push_back(current);
}
return std::move(parts);
}
template<typename T>
std::string to_string(T value);
template<>
inline std::string to_string<uint64_t>(uint64_t value){
if(value == 0){
return "0";
}
std::string s;
char buffer[20];
int i = 0;
while(value != 0){
buffer[i++] = '0' + value % 10;
value /= 10;
}
--i;
for(; i >= 0; --i){
s += buffer[i];
}
return std::move(s);
}
template<>
inline std::string to_string<int64_t>(int64_t value){
if(value < 0){
std::string s("-");
s += to_string(static_cast<uint64_t>(value));
return std::move(s);
} else {
return to_string(static_cast<uint64_t>(value));
}
}
} //end of namespace std
#endif
<commit_msg>Review to_string<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef STRING_H
#define STRING_H
#include <types.hpp>
#include <algorithms.hpp>
#include <vector.hpp>
namespace std {
inline uint64_t str_len(const char* a){
uint64_t length = 0;
while(*a++){
++length;
}
return length;
}
template<typename CharT>
struct basic_string {
public:
typedef CharT* iterator;
typedef const CharT* const_iterator;
private:
size_t _size;
size_t _capacity;
CharT* _data;
public:
//Constructors
basic_string() : _size(0), _capacity(1), _data(new CharT[1]) {
_data[0] = '\0';
}
basic_string(const CharT* s) : _size(str_len(s)), _capacity(_size + 1), _data(new CharT[_capacity]) {
std::copy_n(_data, s, _capacity);
}
explicit basic_string(size_t __capacity) : _size(0), _capacity(__capacity), _data(new CharT[_capacity]) {
_data[0] = '\0';
}
//Copy constructors
basic_string(const basic_string& rhs) : _size(rhs._size), _capacity(rhs._capacity), _data(new CharT[_capacity]) {
std::copy_n(_data, rhs._data, _size + 1);
}
basic_string& operator=(const basic_string& rhs){
if(this != &rhs){
if(_capacity < rhs._capacity || !_data){
if(_data){
delete[] _data;
}
_capacity = rhs._capacity;
_data = new CharT[_capacity];
}
_size = rhs._size;
std::copy_n(_data, rhs._data, _size + 1);
}
return *this;
}
//Move constructors
basic_string(basic_string&& rhs) : _size(rhs._size), _capacity(rhs._capacity), _data(rhs._data) {
rhs._size = 0;
rhs._capacity = 0;
rhs._data = nullptr;
}
basic_string& operator=(basic_string&& rhs){
if(_data){
delete[] _data;
}
_size = rhs._size;
_capacity = rhs._capacity;
_data = rhs._data;
rhs._size = 0;
rhs._capacity = 0;
rhs._data = nullptr;
return *this;
}
//Destructors
~basic_string(){
if(_data){
delete[] _data;
}
}
//Modifiers
void clear(){
_size = 0;
_data[0] = '\0';
}
void pop_back(){
_data[--_size] = '\0';
}
basic_string operator+(CharT c) const {
basic_string copy(*this);
copy += c;
return move(copy);
}
basic_string& operator+=(CharT c){
if(!_data || _capacity <= _size + 1){
_capacity = _capacity ? _capacity * 2 : 1;
auto new_data = new CharT[_capacity];
if(_data){
std::copy_n(new_data, _data, _size);
delete[] _data;
}
_data = new_data;
}
_data[_size] = c;
_data[++_size] = '\0';
return *this;
}
basic_string& operator+=(const char* rhs){
auto len = str_len(rhs);
if(!_data || _capacity <= _size + len){
_capacity = _capacity ? _capacity * 2 : 1;
if(_capacity < _size + len){
_capacity = _size + len + 1;
}
auto new_data = new CharT[_capacity];
if(_data){
std::copy_n(new_data, _data, _size);
delete[] _data;
}
_data = new_data;
}
std::copy_n(_data + _size, rhs, len);
_size += len;
_data[_size] = '\0';
return *this;
}
basic_string& operator+=(const basic_string& rhs){
if(!_data || _capacity <= _size + rhs.size()){
_capacity = _capacity ? _capacity * 2 : 1;
if(_capacity < _size + rhs.size()){
_capacity = _size + rhs.size() + 1;
}
auto new_data = new CharT[_capacity];
if(_data){
std::copy_n(new_data, _data, _size);
delete[] _data;
}
_data = new_data;
}
std::copy_n(_data + _size, rhs.c_str(), rhs.size());
_size += rhs.size();
_data[_size] = '\0';
return *this;
}
//Accessors
size_t size() const {
return _size;
}
size_t capacity() const {
return _capacity;
}
bool empty() const {
return !_size;
}
CharT* c_str(){
return _data;
}
const CharT* c_str() const {
return _data;
}
CharT& operator[](size_t i){
return _data[i];
}
const CharT& operator[](size_t i) const {
return _data[i];
}
//Operators
bool operator==(const CharT* s) const {
if(size() != str_len(s)){
return false;
}
for(size_t i = 0; i < size(); ++i){
if(_data[i] != s[i]){
return false;
}
}
return true;
}
bool operator==(const basic_string& rhs) const {
if(size() != rhs.size()){
return false;
}
for(size_t i = 0; i < size(); ++i){
if(_data[i] != rhs._data[i]){
return false;
}
}
return true;
}
//Iterators
iterator begin(){
return iterator(&_data[0]);
}
iterator end(){
return iterator(&_data[_size]);
}
const_iterator begin() const {
return const_iterator(&_data[0]);
}
const_iterator end() const {
return const_iterator(&_data[_size]);
}
};
typedef basic_string<char> string;
inline uint64_t parse(const char* it, const char* end){
int i = end - it - 1;
uint64_t factor = 1;
uint64_t acc = 0;
for(; i >= 0; --i){
acc += (it[i] - '0') * factor;
factor *= 10;
}
return acc;
}
inline uint64_t parse(const char* str){
int i = 0;
const char* it = str;
while(*++it){
++i;
}
uint64_t factor = 1;
uint64_t acc = 0;
for(; i >= 0; --i){
acc += (str[i] - '0') * factor;
factor *= 10;
}
return acc;
}
inline uint64_t parse(const string& str){
return parse(str.begin(), str.end());
}
template<typename N>
size_t digits(N number){
if(number < 10){
return 1;
}
size_t i = 0;
while(number != 0){
number /= 10;
++i;
}
return i;
}
template<typename Char>
std::vector<std::basic_string<Char>> split(const std::basic_string<Char>& s){
std::vector<std::basic_string<Char>> parts;
std::basic_string<Char> current(s.size());
for(char c : s){
if(c == ' ' && !current.empty()){
parts.push_back(current);
current.clear();
} else {
current += c;
}
}
if(!current.empty()){
parts.push_back(current);
}
return std::move(parts);
}
template<typename T>
std::string to_string(const T& value);
template<>
inline std::string to_string<uint64_t>(const uint64_t& value){
if(value == 0){
return "0";
}
std::string s;
char buffer[20];
int i = 0;
auto rem = value;
while(rem != 0){
buffer[i++] = '0' + rem % 10;
rem /= 10;
}
--i;
for(; i >= 0; --i){
s += buffer[i];
}
return std::move(s);
}
template<>
inline std::string to_string<int64_t>(const int64_t& value){
if(value < 0){
std::string s("-");
s += to_string(static_cast<uint64_t>(value));
return std::move(s);
} else {
return to_string(static_cast<uint64_t>(value));
}
}
template<>
inline std::string to_string<unsigned int>(const unsigned int& value){
return to_string(static_cast<size_t>(value));
}
} //end of namespace std
#endif
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef STRING_H
#define STRING_H
#include <types.hpp>
#include <algorithms.hpp>
#include <vector.hpp>
#include <unique_ptr.hpp>
namespace std {
inline uint64_t str_len(const char* a){
uint64_t length = 0;
while(*a++){
++length;
}
return length;
}
template<typename CharT>
struct basic_string {
public:
typedef CharT* iterator;
typedef const CharT* const_iterator;
static constexpr const size_t npos = -1;
private:
size_t _size;
size_t _capacity;
unique_ptr<CharT[]> _data;
public:
//Constructors
basic_string() : _size(0), _capacity(1), _data(new CharT[1]) {
_data[0] = '\0';
}
basic_string(const CharT* s) : _size(str_len(s)), _capacity(_size + 1), _data(new CharT[_capacity]) {
std::copy_n(_data.get(), s, _capacity);
}
explicit basic_string(size_t __capacity) : _size(0), _capacity(__capacity), _data(new CharT[_capacity]) {
_data[0] = '\0';
}
//Copy constructors
basic_string(const basic_string& rhs) : _size(rhs._size), _capacity(rhs._capacity), _data() {
if(_capacity > 0){
_data.reset(new CharT[_capacity]);
std::copy_n(_data.get(), rhs._data.get(), _size + 1);
}
}
basic_string& operator=(const basic_string& rhs){
if(this != &rhs){
if(_capacity < rhs._capacity || !_data){
_capacity = rhs._capacity;
_data.reset(new CharT[_capacity]);
}
_size = rhs._size;
std::copy_n(_data.get(), rhs._data.get(), _size + 1);
}
return *this;
}
//Move constructors
basic_string(basic_string&& rhs) : _size(rhs._size), _capacity(rhs._capacity), _data(std::move(rhs._data)) {
rhs._size = 0;
rhs._capacity = 0;
//rhs._data = nullptr;
}
basic_string& operator=(basic_string&& rhs){
_size = rhs._size;
_capacity = rhs._capacity;
_data = std::move(rhs._data);
rhs._size = 0;
rhs._capacity = 0;
//rhs._data = nullptr;
return *this;
}
//Destructors
~basic_string() = default;
//Modifiers
void clear(){
_size = 0;
_data[0] = '\0';
}
void pop_back(){
_data[--_size] = '\0';
}
void reserve(size_t new_capacity){
ensure_capacity(new_capacity);
}
basic_string operator+(CharT c) const {
basic_string copy(*this);
copy += c;
return move(copy);
}
basic_string& operator+=(CharT c){
ensure_capacity(_size + 2);
_data[_size] = c;
_data[++_size] = '\0';
return *this;
}
void ensure_capacity(size_t new_capacity){
if(new_capacity > 0 && (!_data || _capacity < new_capacity)){
_capacity = _capacity ? _capacity * 2 : 1;
if(_capacity < new_capacity){
_capacity = new_capacity;
}
auto new_data = new CharT[_capacity];
std::copy_n(new_data, _data.get(), _size);
_data.reset(new_data);
}
}
basic_string& operator+=(const char* rhs){
auto len = str_len(rhs);
ensure_capacity(_size + len + 1);
std::copy_n(_data.get() + _size, rhs, len);
_size += len;
_data[_size] = '\0';
return *this;
}
basic_string& operator+=(const basic_string& rhs){
ensure_capacity(_size + rhs.size() + 1);
std::copy_n(_data.get() + _size, rhs.c_str(), rhs.size());
_size += rhs.size();
_data[_size] = '\0';
return *this;
}
//Accessors
size_t size() const {
return _size;
}
size_t capacity() const {
return _capacity;
}
bool empty() const {
return !_size;
}
CharT* c_str(){
return _data.get();
}
const CharT* c_str() const {
return _data.get();
}
CharT& operator[](size_t i){
return _data[i];
}
const CharT& operator[](size_t i) const {
return _data[i];
}
size_t find(char c) const {
for(size_t i = 0; i < size(); ++i){
if(_data[i] == c){
return i;
}
}
return npos;
}
//Operators
bool operator==(const CharT* s) const {
if(size() != str_len(s)){
return false;
}
for(size_t i = 0; i < size(); ++i){
if(_data[i] != s[i]){
return false;
}
}
return true;
}
bool operator!=(const CharT* s) const {
return !(*this == s);
}
bool operator==(const basic_string& rhs) const {
if(size() != rhs.size()){
return false;
}
for(size_t i = 0; i < size(); ++i){
if(_data[i] != rhs._data[i]){
return false;
}
}
return true;
}
bool operator!=(const basic_string& rhs) const {
return !(*this == rhs);
}
//Iterators
iterator begin(){
return iterator(&_data[0]);
}
iterator end(){
return iterator(&_data[_size]);
}
const_iterator begin() const {
return const_iterator(&_data[0]);
}
const_iterator end() const {
return const_iterator(&_data[_size]);
}
};
template<typename C>
basic_string<C> operator+(const basic_string<C>& lhs, const basic_string<C>& rhs){
basic_string<C> result;
result += lhs;
result += rhs;
return std::move(result);
}
template<typename C>
basic_string<C> operator+(const C* lhs, const basic_string<C>& rhs){
basic_string<C> result;
result += lhs;
result += rhs;
return std::move(result);
}
template<typename C>
basic_string<C> operator+(const basic_string<C>& lhs, const C* rhs){
basic_string<C> result;
result += lhs;
result += rhs;
return std::move(result);
}
typedef basic_string<char> string;
inline uint64_t parse(const char* it, const char* end){
int i = end - it - 1;
uint64_t factor = 1;
uint64_t acc = 0;
for(; i >= 0; --i){
acc += (it[i] - '0') * factor;
factor *= 10;
}
return acc;
}
inline uint64_t parse(const char* str){
int i = 0;
const char* it = str;
while(*++it){
++i;
}
uint64_t factor = 1;
uint64_t acc = 0;
for(; i >= 0; --i){
acc += (str[i] - '0') * factor;
factor *= 10;
}
return acc;
}
inline uint64_t parse(const string& str){
return parse(str.begin(), str.end());
}
template<typename N>
size_t digits(N number){
if(number < 10){
return 1;
}
size_t i = 0;
while(number != 0){
number /= 10;
++i;
}
return i;
}
template<typename Char>
std::vector<std::basic_string<Char>> split(const std::basic_string<Char>& s, char sep = ' '){
std::vector<std::basic_string<Char>> parts;
std::basic_string<Char> current(s.size());
for(char c : s){
if(c == sep && !current.empty()){
parts.push_back(current);
current.clear();
} else if(c == sep){
continue;
} else {
current += c;
}
}
if(!current.empty()){
parts.push_back(current);
}
return std::move(parts);
}
template<typename T>
std::string to_string(const T& value);
template<>
inline std::string to_string<uint64_t>(const uint64_t& value){
if(value == 0){
return "0";
}
std::string s;
char buffer[20];
int i = 0;
auto rem = value;
while(rem != 0){
buffer[i++] = '0' + rem % 10;
rem /= 10;
}
--i;
for(; i >= 0; --i){
s += buffer[i];
}
return std::move(s);
}
template<>
inline std::string to_string<int64_t>(const int64_t& value){
if(value < 0){
std::string s("-");
s += to_string(static_cast<uint64_t>(value));
return std::move(s);
} else {
return to_string(static_cast<uint64_t>(value));
}
}
template<>
inline std::string to_string<uint8_t>(const uint8_t& value){
return to_string(static_cast<uint64_t>(value));
}
template<>
inline std::string to_string<uint16_t>(const uint16_t& value){
return to_string(static_cast<uint64_t>(value));
}
template<>
inline std::string to_string<uint32_t>(const uint32_t& value){
return to_string(static_cast<uint64_t>(value));
}
template<>
inline std::string to_string<int8_t>(const int8_t& value){
return to_string(static_cast<int64_t>(value));
}
template<>
inline std::string to_string<int16_t>(const int16_t& value){
return to_string(static_cast<int64_t>(value));
}
template<>
inline std::string to_string<int32_t>(const int32_t& value){
return to_string(static_cast<int64_t>(value));
}
} //end of namespace std
#endif
<commit_msg>Start working on SSO<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef STRING_H
#define STRING_H
#include <types.hpp>
#include <algorithms.hpp>
#include <vector.hpp>
#include <unique_ptr.hpp>
namespace std {
inline uint64_t str_len(const char* a){
uint64_t length = 0;
while(*a++){
++length;
}
return length;
}
static constexpr const size_t SSO_SIZE = 16;
template<typename CharT>
struct base_small {
CharT data[SSO_SIZE];
};
template<typename CharT>
struct base_big {
size_t capacity;
unique_ptr<CharT[]> data;
base_big(size_t capacity, CharT* array) : capacity(capacity), data(array){
//Nothing to do
}
};
template<typename CharT>
union base_storage {
base_small<CharT> small;
base_big<CharT> big;
base_storage(){
//Default construction: Nothing to do
}
base_storage(size_t capacity, CharT* array) : big(capacity, array) {
//Default construction: Nothing to do
}
~base_storage() {}
};
static_assert(SSO_SIZE == sizeof(base_small<char>), "base_small must be the correct SSO size");
static_assert(SSO_SIZE == sizeof(base_big<char>), "base_big must be the correct SSO size");
template<typename CharT>
struct basic_string {
public:
typedef CharT* iterator;
typedef const CharT* const_iterator;
static constexpr const size_t npos = -1;
private:
size_t _size;
base_storage<CharT> storage;
bool is_small() const {
return _size < 16;
}
public:
//Constructors
basic_string() : _size(0){
storage.small.data[0] = '\0';
}
basic_string(const CharT* s) : _size(str_len(s)) {
auto capacity = _size + 1;
if(is_small()){
std::copy_n(&storage.small.data[0], s, capacity);
} else {
storage.big.capacity = capacity;
storage.big.data.reset(new CharT[capacity]);
std::copy_n(storage.big.data.get(), s, capacity);
}
}
explicit basic_string(size_t __capacity) : _size(0), _capacity(__capacity), _data(new CharT[_capacity]) {
_data[0] = '\0';
}
//Copy constructors
basic_string(const basic_string& rhs) : _size(rhs._size), _capacity(rhs._capacity), _data() {
if(_capacity > 0){
_data.reset(new CharT[_capacity]);
std::copy_n(_data.get(), rhs._data.get(), _size + 1);
}
}
basic_string& operator=(const basic_string& rhs){
if(this != &rhs){
if(_capacity < rhs._capacity || !_data){
_capacity = rhs._capacity;
_data.reset(new CharT[_capacity]);
}
_size = rhs._size;
std::copy_n(_data.get(), rhs._data.get(), _size + 1);
}
return *this;
}
//Move constructors
basic_string(basic_string&& rhs) : _size(rhs._size), _capacity(rhs._capacity), _data(std::move(rhs._data)) {
rhs._size = 0;
rhs._capacity = 0;
//rhs._data = nullptr;
}
basic_string& operator=(basic_string&& rhs){
_size = rhs._size;
_capacity = rhs._capacity;
_data = std::move(rhs._data);
rhs._size = 0;
rhs._capacity = 0;
//rhs._data = nullptr;
return *this;
}
//Destructors
~basic_string(){
if(!is_small()){
storage.big.~base_big();
}
}
//Modifiers
void clear(){
_size = 0;
_data[0] = '\0';
}
void pop_back(){
_data[--_size] = '\0';
}
void reserve(size_t new_capacity){
ensure_capacity(new_capacity);
}
basic_string operator+(CharT c) const {
basic_string copy(*this);
copy += c;
return move(copy);
}
basic_string& operator+=(CharT c){
ensure_capacity(_size + 2);
_data[_size] = c;
_data[++_size] = '\0';
return *this;
}
void ensure_capacity(size_t new_capacity){
if(new_capacity > 0 && (!_data || _capacity < new_capacity)){
_capacity = _capacity ? _capacity * 2 : 1;
if(_capacity < new_capacity){
_capacity = new_capacity;
}
auto new_data = new CharT[_capacity];
std::copy_n(new_data, _data.get(), _size);
_data.reset(new_data);
}
}
basic_string& operator+=(const char* rhs){
auto len = str_len(rhs);
ensure_capacity(_size + len + 1);
std::copy_n(_data.get() + _size, rhs, len);
_size += len;
_data[_size] = '\0';
return *this;
}
basic_string& operator+=(const basic_string& rhs){
ensure_capacity(_size + rhs.size() + 1);
std::copy_n(_data.get() + _size, rhs.c_str(), rhs.size());
_size += rhs.size();
_data[_size] = '\0';
return *this;
}
//Accessors
size_t size() const {
return _size;
}
size_t capacity() const {
return _capacity;
}
bool empty() const {
return !_size;
}
CharT* c_str(){
return _data.get();
}
const CharT* c_str() const {
return _data.get();
}
CharT& operator[](size_t i){
return _data[i];
}
const CharT& operator[](size_t i) const {
return _data[i];
}
size_t find(char c) const {
for(size_t i = 0; i < size(); ++i){
if(_data[i] == c){
return i;
}
}
return npos;
}
//Operators
bool operator==(const CharT* s) const {
if(size() != str_len(s)){
return false;
}
for(size_t i = 0; i < size(); ++i){
if(_data[i] != s[i]){
return false;
}
}
return true;
}
bool operator!=(const CharT* s) const {
return !(*this == s);
}
bool operator==(const basic_string& rhs) const {
if(size() != rhs.size()){
return false;
}
for(size_t i = 0; i < size(); ++i){
if(_data[i] != rhs._data[i]){
return false;
}
}
return true;
}
bool operator!=(const basic_string& rhs) const {
return !(*this == rhs);
}
//Iterators
iterator begin(){
return iterator(&_data[0]);
}
iterator end(){
return iterator(&_data[_size]);
}
const_iterator begin() const {
return const_iterator(&_data[0]);
}
const_iterator end() const {
return const_iterator(&_data[_size]);
}
};
template<typename C>
basic_string<C> operator+(const basic_string<C>& lhs, const basic_string<C>& rhs){
basic_string<C> result;
result += lhs;
result += rhs;
return std::move(result);
}
template<typename C>
basic_string<C> operator+(const C* lhs, const basic_string<C>& rhs){
basic_string<C> result;
result += lhs;
result += rhs;
return std::move(result);
}
template<typename C>
basic_string<C> operator+(const basic_string<C>& lhs, const C* rhs){
basic_string<C> result;
result += lhs;
result += rhs;
return std::move(result);
}
typedef basic_string<char> string;
static_assert(sizeof(string) == 24, "The size of a string must always be 24 bytes");
inline uint64_t parse(const char* it, const char* end){
int i = end - it - 1;
uint64_t factor = 1;
uint64_t acc = 0;
for(; i >= 0; --i){
acc += (it[i] - '0') * factor;
factor *= 10;
}
return acc;
}
inline uint64_t parse(const char* str){
int i = 0;
const char* it = str;
while(*++it){
++i;
}
uint64_t factor = 1;
uint64_t acc = 0;
for(; i >= 0; --i){
acc += (str[i] - '0') * factor;
factor *= 10;
}
return acc;
}
inline uint64_t parse(const string& str){
return parse(str.begin(), str.end());
}
template<typename N>
size_t digits(N number){
if(number < 10){
return 1;
}
size_t i = 0;
while(number != 0){
number /= 10;
++i;
}
return i;
}
template<typename Char>
std::vector<std::basic_string<Char>> split(const std::basic_string<Char>& s, char sep = ' '){
std::vector<std::basic_string<Char>> parts;
std::basic_string<Char> current(s.size());
for(char c : s){
if(c == sep && !current.empty()){
parts.push_back(current);
current.clear();
} else if(c == sep){
continue;
} else {
current += c;
}
}
if(!current.empty()){
parts.push_back(current);
}
return std::move(parts);
}
template<typename T>
std::string to_string(const T& value);
template<>
inline std::string to_string<uint64_t>(const uint64_t& value){
if(value == 0){
return "0";
}
std::string s;
char buffer[20];
int i = 0;
auto rem = value;
while(rem != 0){
buffer[i++] = '0' + rem % 10;
rem /= 10;
}
--i;
for(; i >= 0; --i){
s += buffer[i];
}
return std::move(s);
}
template<>
inline std::string to_string<int64_t>(const int64_t& value){
if(value < 0){
std::string s("-");
s += to_string(static_cast<uint64_t>(value));
return std::move(s);
} else {
return to_string(static_cast<uint64_t>(value));
}
}
template<>
inline std::string to_string<uint8_t>(const uint8_t& value){
return to_string(static_cast<uint64_t>(value));
}
template<>
inline std::string to_string<uint16_t>(const uint16_t& value){
return to_string(static_cast<uint64_t>(value));
}
template<>
inline std::string to_string<uint32_t>(const uint32_t& value){
return to_string(static_cast<uint64_t>(value));
}
template<>
inline std::string to_string<int8_t>(const int8_t& value){
return to_string(static_cast<int64_t>(value));
}
template<>
inline std::string to_string<int16_t>(const int16_t& value){
return to_string(static_cast<int64_t>(value));
}
template<>
inline std::string to_string<int32_t>(const int32_t& value){
return to_string(static_cast<int64_t>(value));
}
} //end of namespace std
#endif
<|endoftext|>
|
<commit_before>
#include <QDebug>
#include <QProcess>
#include <comboboxconfig.h>
PacmanPlugin::PacmanPlugin(QObject *parent) :
PackageManagerPlugin(parent)
{
}
void PacmanPlugin::initialize()
{
_settings = createSyncedSettings(this);
}
QList<PacmanPlugin::FilterInfo> PacmanPlugin::extraFilters()
{
QList<PacmanPlugin::FilterInfo> list;
list.append({QStringLiteral("&Explicitly installed"), QStringLiteral("Only explicitly installed packages"), false});
list.append({QStringLiteral("&Leaf packages"), QStringLiteral("Only leaf packages"), false});
list.append({QStringLiteral("&Foreign packages only"), QStringLiteral("Only packages that are not present in any mirror (includes AUR packages)"), false});
list.append({QStringLiteral("&Native packages only"), QStringLiteral("Only packages that are present in any mirror (excludes AUR packages)"), false});
return list;
}
QStringList PacmanPlugin::listAllPackages()
{
return listPackages({false, false, false, false});
}
QStringList PacmanPlugin::listPackages(QVector<bool> extraFilters)
{
if(extraFilters[2] && extraFilters[3])
return {};
auto queryString = QStringLiteral("-Qq");
if(extraFilters[0])
queryString += QLatin1Char('e');
if(extraFilters[1])
queryString += QStringLiteral("tt");
if(extraFilters[2])
queryString += QLatin1Char('m');
if(extraFilters[3])
queryString += QLatin1Char('n');
QProcess p;
p.start(QStringLiteral("pacman"), {queryString});
if(!p.waitForFinished(5000))
return {};
return QString::fromUtf8(p.readAll()).split(QStringLiteral("\n"), QString::SkipEmptyParts);
}
QString PacmanPlugin::installationCmd(const QStringList &packages)
{
auto f = _settings->value(QStringLiteral("frontend"), QStringLiteral("pacaur")).toString();
auto s = _settings->value(QStringLiteral("sudo")).toBool();
return ;
}
QString PacmanPlugin::uninstallationCmd(const QStringList &packages)
{
return {};
}
QList<PackageManagerPlugin::SettingsInfo> PacmanPlugin::listSettings()
{
return {
{
tr("Pacman &frontend"),
tr("Select a pacman frontend to be used for un/installation"),
QStringLiteral("frontend"),
qMetaTypeId<ComboboxConfig>(),
QVariant::fromValue<ComboboxConfig>({
{QStringLiteral("pacaur"), QStringLiteral("yaourt"), QStringLiteral("pacman")},
{},
QStringLiteral("pacaur"),
true
})
},
{
tr("Requires &root"),
tr("Specify if the frontend of your choice needs to be run as root"),
QStringLiteral("sudo"),
QMetaType::Bool
},
{
tr("&Install parameters"),
tr("The parameters to be used for installation. "
"%p is replaced by the list of packages (space seperated). "
"If missing, the packages are appended to the command line"),
QStringLiteral("instparams"),
QMetaType::QString,
QStringLiteral("-S %p")
},
{
tr("&Uninstall parameters"),
tr("The parameters to be used for uninstallation. "
"%p is replaced by the list of packages (space seperated). "
"If missing, the packages are appended to the command line"),
QStringLiteral("uninstparams"),
QMetaType::QString,
QStringLiteral("-R %p")
}
};
}
<commit_msg>fix stash fail<commit_after>#include "pacmanplugin.h"
#include <QDebug>
#include <QProcess>
#include <comboboxconfig.h>
PacmanPlugin::PacmanPlugin(QObject *parent) :
PackageManagerPlugin(parent)
{
}
void PacmanPlugin::initialize()
{
_settings = createSyncedSettings(this);
}
QList<PacmanPlugin::FilterInfo> PacmanPlugin::extraFilters()
{
QList<PacmanPlugin::FilterInfo> list;
list.append({QStringLiteral("&Explicitly installed"), QStringLiteral("Only explicitly installed packages"), false});
list.append({QStringLiteral("&Leaf packages"), QStringLiteral("Only leaf packages"), false});
list.append({QStringLiteral("&Foreign packages only"), QStringLiteral("Only packages that are not present in any mirror (includes AUR packages)"), false});
list.append({QStringLiteral("&Native packages only"), QStringLiteral("Only packages that are present in any mirror (excludes AUR packages)"), false});
return list;
}
QStringList PacmanPlugin::listAllPackages()
{
return listPackages({false, false, false, false});
}
QStringList PacmanPlugin::listPackages(QVector<bool> extraFilters)
{
if(extraFilters[2] && extraFilters[3])
return {};
auto queryString = QStringLiteral("-Qq");
if(extraFilters[0])
queryString += QLatin1Char('e');
if(extraFilters[1])
queryString += QStringLiteral("tt");
if(extraFilters[2])
queryString += QLatin1Char('m');
if(extraFilters[3])
queryString += QLatin1Char('n');
QProcess p;
p.start(QStringLiteral("pacman"), {queryString});
if(!p.waitForFinished(5000))
return {};
return QString::fromUtf8(p.readAll()).split(QStringLiteral("\n"), QString::SkipEmptyParts);
}
QString PacmanPlugin::installationCmd(const QStringList &packages)
{
auto f = _settings->value(QStringLiteral("frontend"), QStringLiteral("pacaur")).toString();
auto s = _settings->value(QStringLiteral("sudo")).toBool();
return ;
}
QString PacmanPlugin::uninstallationCmd(const QStringList &packages)
{
return {};
}
QList<PackageManagerPlugin::SettingsInfo> PacmanPlugin::listSettings()
{
return {
{
tr("Pacman &frontend"),
tr("Select a pacman frontend to be used for un/installation"),
QStringLiteral("frontend"),
qMetaTypeId<ComboboxConfig>(),
QVariant::fromValue<ComboboxConfig>({
{QStringLiteral("pacaur"), QStringLiteral("yaourt"), QStringLiteral("pacman")},
{},
QStringLiteral("pacaur"),
true
})
},
{
tr("Requires &root"),
tr("Specify if the frontend of your choice needs to be run as root"),
QStringLiteral("sudo"),
QMetaType::Bool
},
{
tr("&Install parameters"),
tr("The parameters to be used for installation. "
"%p is replaced by the list of packages (space seperated). "
"If missing, the packages are appended to the command line"),
QStringLiteral("instparams"),
QMetaType::QString,
QStringLiteral("-S %p")
},
{
tr("&Uninstall parameters"),
tr("The parameters to be used for uninstallation. "
"%p is replaced by the list of packages (space seperated). "
"If missing, the packages are appended to the command line"),
QStringLiteral("uninstparams"),
QMetaType::QString,
QStringLiteral("-R %p")
}
};
}
<|endoftext|>
|
<commit_before>#include <exotica/Exotica.h>
#undef NDEBUG
#include <pybind11/eigen.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <exotica_core_task_maps/CoM.h>
#include <exotica_core_task_maps/collision_distance.h>
#include <exotica_core_task_maps/continuous_collision.h>
#include <exotica_core_task_maps/distance.h>
#include <exotica_core_task_maps/eff_axis_alignment.h>
#include <exotica_core_task_maps/eff_frame.h>
#include <exotica_core_task_maps/eff_orientation.h>
#include <exotica_core_task_maps/eff_position.h>
#include <exotica_core_task_maps/identity.h>
#include <exotica_core_task_maps/interaction_mesh.h>
#include <exotica_core_task_maps/joint_acceleration_backward_difference.h>
#include <exotica_core_task_maps/joint_jerk_backward_difference.h>
#include <exotica_core_task_maps/joint_limit.h>
#include <exotica_core_task_maps/joint_velocity_backward_difference.h>
#include <exotica_core_task_maps/look_at.h>
#include <exotica_core_task_maps/point_to_line.h>
#include <exotica_core_task_maps/sphere_collision.h>
using namespace exotica;
namespace py = pybind11;
PYBIND11_MODULE(task_map_py, module)
{
module.doc() = "Exotica task map definitions";
py::module::import("pyexotica");
py::class_<EffFrame, std::shared_ptr<EffFrame>, TaskMap>(module, "EffFrame")
.def_readonly("rotation_type", &EffFrame::rotation_type_);
py::class_<EffPosition, std::shared_ptr<EffPosition>, TaskMap>(module, "EffPosition");
py::class_<EffOrientation, std::shared_ptr<EffOrientation>, TaskMap>(module, "EffOrientation")
.def_readonly("rotation_type", &EffOrientation::rotation_type_);
py::class_<EffAxisAlignment, std::shared_ptr<EffAxisAlignment>, TaskMap>(module, "EffAxisAlignment")
.def("get_axis", &EffAxisAlignment::get_axis)
.def("set_axis", &EffAxisAlignment::set_axis)
.def("get_direction", &EffAxisAlignment::get_direction)
.def("set_direction", &EffAxisAlignment::set_direction);
py::class_<LookAt, std::shared_ptr<LookAt>, TaskMap>(module, "LookAt")
.def("get_look_at_target_in_world", &LookAt::get_look_at_target_in_world);
py::class_<Point2Line, std::shared_ptr<Point2Line>, TaskMap>(module, "Point2Line")
.def_property("end_point", &Point2Line::getEndPoint, &Point2Line::setEndPoint);
py::class_<JointVelocityBackwardDifference, std::shared_ptr<JointVelocityBackwardDifference>, TaskMap>(module, "JointVelocityBackwardDifference")
.def("set_previous_joint_state", &JointVelocityBackwardDifference::set_previous_joint_state);
py::class_<JointAccelerationBackwardDifference, std::shared_ptr<JointAccelerationBackwardDifference>, TaskMap>(module, "JointAccelerationBackwardDifference")
.def("set_previous_joint_state", &JointAccelerationBackwardDifference::set_previous_joint_state);
py::class_<JointJerkBackwardDifference, std::shared_ptr<JointJerkBackwardDifference>, TaskMap>(module, "JointJerkBackwardDifference")
.def("set_previous_joint_state", &JointJerkBackwardDifference::set_previous_joint_state);
py::class_<CoM, std::shared_ptr<CoM>, TaskMap>(module, "CoM");
py::class_<Distance, std::shared_ptr<Distance>, TaskMap>(module, "Distance");
py::class_<Identity, std::shared_ptr<Identity>, TaskMap>(module, "Identity")
.def_readonly("N", &Identity::N_)
.def_readonly("joint_map", &Identity::joint_map_)
.def_readwrite("joint_ref", &Identity::joint_ref_);
py::class_<IMesh, std::shared_ptr<IMesh>, TaskMap>(module, "IMesh")
.def_property("W", &IMesh::get_weights, &IMesh::set_weights)
.def("set_weight", &IMesh::set_weight)
.def_static("compute_goal_laplace", [](const std::vector<KDL::Frame>& nodes, Eigen::MatrixXdRefConst weights) {
Eigen::VectorXd goal;
IMesh::compute_goal_laplace(nodes, goal, weights);
return goal;
})
.def_static("compute_laplace", [](Eigen::VectorXdRefConst eff_phi, Eigen::MatrixXdRefConst weights) {
return IMesh::compute_laplace(eff_phi, weights);
});
py::class_<JointLimit, std::shared_ptr<JointLimit>, TaskMap>(module, "JointLimit");
py::class_<SphereCollision, std::shared_ptr<SphereCollision>, TaskMap>(module, "SphereCollision");
py::class_<CollisionDistance, std::shared_ptr<CollisionDistance>, TaskMap>(module, "CollisionDistance")
.def("get_collision_proxies", &CollisionDistance::get_collision_proxies);
py::class_<ContinuousCollision, std::shared_ptr<ContinuousCollision>, TaskMap>(module, "ContinuousCollision")
.def("get_collision_proxies", &ContinuousCollision::get_collision_proxies)
.def("update_collision_objects", &ContinuousCollision::update_collision_objects);
}
<commit_msg>[exotica_core_task_maps] Fix exotica_core_task_map_py<commit_after>#include <exotica/Exotica.h>
#undef NDEBUG
#include <pybind11/eigen.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <exotica_core_task_maps/CoM.h>
#include <exotica_core_task_maps/collision_distance.h>
#include <exotica_core_task_maps/continuous_collision.h>
#include <exotica_core_task_maps/distance.h>
#include <exotica_core_task_maps/eff_axis_alignment.h>
#include <exotica_core_task_maps/eff_frame.h>
#include <exotica_core_task_maps/eff_orientation.h>
#include <exotica_core_task_maps/eff_position.h>
#include <exotica_core_task_maps/identity.h>
#include <exotica_core_task_maps/interaction_mesh.h>
#include <exotica_core_task_maps/joint_acceleration_backward_difference.h>
#include <exotica_core_task_maps/joint_jerk_backward_difference.h>
#include <exotica_core_task_maps/joint_limit.h>
#include <exotica_core_task_maps/joint_velocity_backward_difference.h>
#include <exotica_core_task_maps/look_at.h>
#include <exotica_core_task_maps/point_to_line.h>
#include <exotica_core_task_maps/sphere_collision.h>
using namespace exotica;
namespace py = pybind11;
PYBIND11_MODULE(exotica_core_task_maps_py, module)
{
module.doc() = "Exotica task map definitions";
py::module::import("pyexotica");
py::class_<EffFrame, std::shared_ptr<EffFrame>, TaskMap>(module, "EffFrame")
.def_readonly("rotation_type", &EffFrame::rotation_type_);
py::class_<EffPosition, std::shared_ptr<EffPosition>, TaskMap>(module, "EffPosition");
py::class_<EffOrientation, std::shared_ptr<EffOrientation>, TaskMap>(module, "EffOrientation")
.def_readonly("rotation_type", &EffOrientation::rotation_type_);
py::class_<EffAxisAlignment, std::shared_ptr<EffAxisAlignment>, TaskMap>(module, "EffAxisAlignment")
.def("get_axis", &EffAxisAlignment::get_axis)
.def("set_axis", &EffAxisAlignment::set_axis)
.def("get_direction", &EffAxisAlignment::get_direction)
.def("set_direction", &EffAxisAlignment::set_direction);
py::class_<LookAt, std::shared_ptr<LookAt>, TaskMap>(module, "LookAt")
.def("get_look_at_target_in_world", &LookAt::get_look_at_target_in_world);
py::class_<Point2Line, std::shared_ptr<Point2Line>, TaskMap>(module, "Point2Line")
.def_property("end_point", &Point2Line::getEndPoint, &Point2Line::setEndPoint);
py::class_<JointVelocityBackwardDifference, std::shared_ptr<JointVelocityBackwardDifference>, TaskMap>(module, "JointVelocityBackwardDifference")
.def("set_previous_joint_state", &JointVelocityBackwardDifference::set_previous_joint_state);
py::class_<JointAccelerationBackwardDifference, std::shared_ptr<JointAccelerationBackwardDifference>, TaskMap>(module, "JointAccelerationBackwardDifference")
.def("set_previous_joint_state", &JointAccelerationBackwardDifference::set_previous_joint_state);
py::class_<JointJerkBackwardDifference, std::shared_ptr<JointJerkBackwardDifference>, TaskMap>(module, "JointJerkBackwardDifference")
.def("set_previous_joint_state", &JointJerkBackwardDifference::set_previous_joint_state);
py::class_<CoM, std::shared_ptr<CoM>, TaskMap>(module, "CoM");
py::class_<Distance, std::shared_ptr<Distance>, TaskMap>(module, "Distance");
py::class_<Identity, std::shared_ptr<Identity>, TaskMap>(module, "Identity")
.def_readonly("N", &Identity::N_)
.def_readonly("joint_map", &Identity::joint_map_)
.def_readwrite("joint_ref", &Identity::joint_ref_);
py::class_<IMesh, std::shared_ptr<IMesh>, TaskMap>(module, "IMesh")
.def_property("W", &IMesh::get_weights, &IMesh::set_weights)
.def("set_weight", &IMesh::set_weight)
.def_static("compute_goal_laplace", [](const std::vector<KDL::Frame>& nodes, Eigen::MatrixXdRefConst weights) {
Eigen::VectorXd goal;
IMesh::compute_goal_laplace(nodes, goal, weights);
return goal;
})
.def_static("compute_laplace", [](Eigen::VectorXdRefConst eff_phi, Eigen::MatrixXdRefConst weights) {
return IMesh::compute_laplace(eff_phi, weights);
});
py::class_<JointLimit, std::shared_ptr<JointLimit>, TaskMap>(module, "JointLimit");
py::class_<SphereCollision, std::shared_ptr<SphereCollision>, TaskMap>(module, "SphereCollision");
py::class_<CollisionDistance, std::shared_ptr<CollisionDistance>, TaskMap>(module, "CollisionDistance")
.def("get_collision_proxies", &CollisionDistance::get_collision_proxies);
py::class_<ContinuousCollision, std::shared_ptr<ContinuousCollision>, TaskMap>(module, "ContinuousCollision")
.def("get_collision_proxies", &ContinuousCollision::get_collision_proxies)
.def("update_collision_objects", &ContinuousCollision::update_collision_objects);
}
<|endoftext|>
|
<commit_before>/**
* @file precipitation.cpp
*
* @date Jan 28, 2012
* @author partio
*/
#include "precipitation.h"
#include <iostream>
#include "plugin_factory.h"
#include "logger_factory.h"
#include <boost/lexical_cast.hpp>
#define HIMAN_AUXILIARY_INCLUDE
#include "fetcher.h"
#include "writer.h"
#include "neons.h"
#include "pcuda.h"
#undef HIMAN_AUXILIARY_INCLUDE
#ifdef DEBUG
#include "timer_factory.h"
#endif
using namespace std;
using namespace himan::plugin;
precipitation::precipitation() : itsUseCuda(false)
{
itsClearTextFormula = "RR = RR_cur - RR_prev";
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("precipitation"));
}
void precipitation::Process(std::shared_ptr<const plugin_configuration> conf)
{
unique_ptr<timer> initTimer;
if (conf->StatisticsEnabled())
{
initTimer = unique_ptr<timer> (timer_factory::Instance()->GetTimer());
initTimer->Start();
}
shared_ptr<plugin::pcuda> c = dynamic_pointer_cast<plugin::pcuda> (plugin_factory::Instance()->Plugin("pcuda"));
if (c->HaveCuda())
{
string msg = "I possess the powers of CUDA";
if (!conf->UseCuda())
{
msg += ", but I won't use them";
}
else
{
msg += ", and I'm not afraid to use them";
itsUseCuda = true;
}
itsLogger->Info(msg);
}
// Get number of threads to use
unsigned short threadCount = ThreadCount(conf->ThreadCount());
if (conf->StatisticsEnabled())
{
conf->Statistics()->UsedThreadCount(threadCount);
conf->Statistics()->UsedGPUCount(0);
}
boost::thread_group g;
shared_ptr<info> targetInfo = conf->Info();
/*
* Set target parameter to precipitation.
*
* We need to specify grib and querydata parameter information
* since we don't know which one will be the output format.
*
*/
vector<param> params;
//param requestedParam ("RR-1-MM", 353);
//param requestedParam ("RR-3-MM", 354);
param requestedParam ("RR-6-MM", 355);
// GRIB 1
if (conf->OutputFileType() == kGRIB1)
{
shared_ptr<neons> n = dynamic_pointer_cast<neons> (plugin_factory::Instance()->Plugin("neons"));
long parm_id = n->NeonsDB().GetGridParameterId(targetInfo->Producer().TableVersion(), requestedParam.Name());
requestedParam.GribIndicatorOfParameter(parm_id);
requestedParam.GribTableVersion(targetInfo->Producer().TableVersion());
}
params.push_back(requestedParam);
targetInfo->Params(params);
/*
* Create data structures.
*/
targetInfo->Create();
/*
* Initialize parent class functions for dimension handling
*/
Dimension(kLevelDimension);
FeederInfo(shared_ptr<info> (new info(*targetInfo)));
FeederInfo()->Param(requestedParam);
if (conf->StatisticsEnabled())
{
initTimer->Stop();
conf->Statistics()->AddToInitTime(initTimer->GetTime());
}
/*
* Each thread will have a copy of the target info.
*/
for (size_t i = 0; i < threadCount; i++)
{
itsLogger->Info("Thread " + boost::lexical_cast<string> (i + 1) + " starting");
boost::thread* t = new boost::thread(&precipitation::Run,
this,
shared_ptr<info> (new info(*targetInfo)),
conf,
i + 1);
g.add_thread(t);
}
g.join_all();
if (conf->FileWriteOption() == kSingleFile)
{
shared_ptr<writer> theWriter = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin("writer"));
string theOutputFile = conf->ConfigurationFile();
theWriter->ToFile(targetInfo, conf, theOutputFile);
}
}
void precipitation::Run(shared_ptr<info> myTargetInfo,
shared_ptr<const plugin_configuration> conf,
unsigned short threadIndex)
{
while (AdjustLeadingDimension(myTargetInfo))
{
Calculate(myTargetInfo, conf, threadIndex);
}
}
/*
* Calculate()
*
* This function does the actual calculation.
*/
void precipitation::Calculate(shared_ptr<info> myTargetInfo,
shared_ptr<const plugin_configuration> conf,
unsigned short threadIndex)
{
unique_ptr<logger> myThreadedLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("precipitationThread #" + boost::lexical_cast<string> (threadIndex)));
ResetNonLeadingDimension(myTargetInfo);
myTargetInfo->FirstParam();
long paramStep;
if (myTargetInfo->Param().Name() == "RR-1-MM")
{
paramStep = 1;
}
else if (myTargetInfo->Param().Name() == "RR-3-MM")
{
paramStep = 3;
}
else if (myTargetInfo->Param().Name() == "RR-6-MM")
{
paramStep = 6;
}
else if (myTargetInfo->Param().Name() == "RR-12-MM")
{
paramStep = 12;
}
else
{
throw runtime_error(ClassName() + ": Unsupported parameter: " + myTargetInfo->Param().Name());
}
shared_ptr<info> prevInfo;
bool dataFoundFromRRParam = true; // Assume that we have parameter RR-KGM2 present
while (AdjustNonLeadingDimension(myTargetInfo))
{
assert(myTargetInfo->Time().StepResolution() == kHourResolution);
shared_ptr<info> RRInfo;
try
{
if (!prevInfo || myTargetInfo->Time().Step() - prevInfo->Time().Step() != paramStep)
{
/*
* If this is the first time this loop executed, or if the previous data is not suitable
* for calculating against current time step data, fetch source data.
*/
forecast_time prevTimeStep = myTargetInfo->Time();
if (prevTimeStep.Step() >= paramStep)
{
prevTimeStep.ValidDateTime()->Adjust(kHourResolution, -paramStep);
prevInfo = FetchSourcePrecipitation(conf,prevTimeStep,myTargetInfo->Level(),dataFoundFromRRParam);
}
else
{
continue;
}
}
// Get data for current step
RRInfo = FetchSourcePrecipitation(conf,myTargetInfo->Time(),myTargetInfo->Level(),dataFoundFromRRParam);
}
catch (HPExceptionType e)
{
switch (e)
{
case kFileDataNotFound:
itsLogger->Info("Skipping step " + boost::lexical_cast<string> (myTargetInfo->Time().Step()) + ", level " + boost::lexical_cast<string> (myTargetInfo->Level().Value()));
myTargetInfo->Data()->Fill(kFloatMissing);
if (conf->StatisticsEnabled())
{
conf->Statistics()->AddToMissingCount(myTargetInfo->Grid()->Size());
conf->Statistics()->AddToValueCount(myTargetInfo->Grid()->Size());
}
continue;
break;
default:
throw runtime_error(ClassName() + ": Unable to proceed");
break;
}
}
unique_ptr<timer> processTimer = unique_ptr<timer> (timer_factory::Instance()->GetTimer());
if (conf->StatisticsEnabled())
{
processTimer->Start();
}
myThreadedLogger->Debug("Calculating time " + myTargetInfo->Time().ValidDateTime()->String("%Y%m%d%H") +
" level " + boost::lexical_cast<string> (myTargetInfo->Level().Value()));
shared_ptr<NFmiGrid> RRGrid(RRInfo->Grid()->ToNewbaseGrid());
shared_ptr<NFmiGrid> prevGrid(prevInfo->Grid()->ToNewbaseGrid());
shared_ptr<NFmiGrid> targetGrid(myTargetInfo->Grid()->ToNewbaseGrid());
int missingCount = 0;
int count = 0;
bool equalGrids = (*myTargetInfo->Grid() == *RRInfo->Grid());
string deviceType = "CPU";
{
assert(targetGrid->Size() == myTargetInfo->Data()->Size());
myTargetInfo->ResetLocation();
targetGrid->Reset();
prevGrid->Reset();
#ifdef DEBUG
unique_ptr<timer> t = unique_ptr<timer> (timer_factory::Instance()->GetTimer());
t->Start();
#endif
while (myTargetInfo->NextLocation() && targetGrid->Next() && prevGrid->Next())
{
count++;
double RRcur = kFloatMissing;
double RRprev = kFloatMissing;
InterpolateToPoint(targetGrid, RRGrid, equalGrids, RRcur);
InterpolateToPoint(targetGrid, prevGrid, equalGrids, RRprev);
if (RRcur == kFloatMissing || RRprev == kFloatMissing)
{
missingCount++;
myTargetInfo->Value(kFloatMissing);
continue;
}
double RR = RRcur - RRprev;
if (RR < 0)
{
RR = 0;
}
if (!myTargetInfo->Value(RR))
{
throw runtime_error(ClassName() + ": Failed to set value to matrix");
}
}
prevInfo = RRInfo;
/*
* Newbase normalizes scanning mode to bottom left -- if that's not what
* the target scanning mode is, we have to swap the data back.
*/
SwapTo(myTargetInfo, kBottomLeft);
}
if (conf->StatisticsEnabled())
{
processTimer->Stop();
conf->Statistics()->AddToProcessingTime(processTimer->GetTime());
#ifdef DEBUG
itsLogger->Debug("Calculation took " + boost::lexical_cast<string> (processTimer->GetTime()) + " microseconds on " + deviceType);
#endif
conf->Statistics()->AddToMissingCount(missingCount);
conf->Statistics()->AddToValueCount(count);
}
/*
* Now we are done for this level
*
* Clone info-instance to writer since it might change our descriptor places
*/
myThreadedLogger->Info("Missing values: " + boost::lexical_cast<string> (missingCount) + "/" + boost::lexical_cast<string> (count));
if (conf->FileWriteOption() == kNeons || conf->FileWriteOption() == kMultipleFiles)
{
shared_ptr<writer> w = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin("writer"));
w->ToFile(shared_ptr<info> (new info(*myTargetInfo)), conf);
}
}
}
shared_ptr<himan::info> precipitation::FetchSourcePrecipitation(shared_ptr<const plugin_configuration> conf, const forecast_time& wantedTime, const level& wantedLevel, bool& dataFoundFromRRParam)
{
try
{
if (dataFoundFromRRParam)
{
return FetchSourceRR(conf,
wantedTime,
wantedLevel);
}
else
{
return FetchSourceConvectiveAndLSRR(conf,
wantedTime,
wantedLevel);
}
}
catch (HPExceptionType e)
{
if (e == kFileDataNotFound && dataFoundFromRRParam)
{
try
{
shared_ptr<info> i = FetchSourceConvectiveAndLSRR(conf,
wantedTime,
wantedLevel);
dataFoundFromRRParam = false;
return i;
}
catch (HPExceptionType e)
{
throw e;
}
}
else
{
throw e;
}
}
throw runtime_error(ClassName() + ": We should never be here but compiler forces this statement");
}
shared_ptr<himan::info> precipitation::FetchSourceRR(shared_ptr<const plugin_configuration> conf, const forecast_time& wantedTime, const level& wantedLevel)
{
shared_ptr<fetcher> f = dynamic_pointer_cast <fetcher> (plugin_factory::Instance()->Plugin("fetcher"));
try
{
return f->Fetch(conf,
wantedTime,
wantedLevel,
param("RR-KGM2"));
}
catch (HPExceptionType e)
{
throw e;
}
}
shared_ptr<himan::info> precipitation::FetchSourceConvectiveAndLSRR(shared_ptr<const plugin_configuration> conf, const forecast_time& wantedTime, const level& wantedLevel)
{
shared_ptr<fetcher> f = dynamic_pointer_cast <fetcher> (plugin_factory::Instance()->Plugin("fetcher"));
shared_ptr<himan::info> ConvectiveInfo;
shared_ptr<himan::info> LSInfo;
shared_ptr<himan::info> RRInfo;
try
{
ConvectiveInfo = f->Fetch(conf,
wantedTime,
wantedLevel,
param("RRC-KGM2"));
LSInfo = f->Fetch(conf,
wantedTime,
wantedLevel,
param("RRR-KGM2"));
}
catch (HPExceptionType e)
{
throw e;
}
ConvectiveInfo->ResetLocation();
LSInfo->ResetLocation();
assert(*ConvectiveInfo->Grid() == *LSInfo->Grid());
RRInfo->Data()->Resize(ConvectiveInfo->Data()->SizeX(),LSInfo->Data()->SizeY());
while (ConvectiveInfo->NextLocation() && LSInfo->NextLocation() && RRInfo->NextLocation())
{
double C = ConvectiveInfo->Value();
double LS = LSInfo->Value();
RRInfo->Value(C+LS);
}
return RRInfo;
}
<commit_msg>Support RR parameters with different lengths<commit_after>/**
* @file precipitation.cpp
*
* @date Jan 28, 2012
* @author partio
*/
#include "precipitation.h"
#include <iostream>
#include "plugin_factory.h"
#include "logger_factory.h"
#include <boost/lexical_cast.hpp>
#define HIMAN_AUXILIARY_INCLUDE
#include "fetcher.h"
#include "writer.h"
#include "neons.h"
#include "pcuda.h"
#undef HIMAN_AUXILIARY_INCLUDE
#ifdef DEBUG
#include "timer_factory.h"
#endif
using namespace std;
using namespace himan::plugin;
precipitation::precipitation() : itsUseCuda(false)
{
itsClearTextFormula = "RR = RR_cur - RR_prev";
itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("precipitation"));
}
void precipitation::Process(std::shared_ptr<const plugin_configuration> conf)
{
unique_ptr<timer> initTimer;
if (conf->StatisticsEnabled())
{
initTimer = unique_ptr<timer> (timer_factory::Instance()->GetTimer());
initTimer->Start();
}
shared_ptr<plugin::pcuda> c = dynamic_pointer_cast<plugin::pcuda> (plugin_factory::Instance()->Plugin("pcuda"));
if (c->HaveCuda())
{
string msg = "I possess the powers of CUDA";
if (!conf->UseCuda())
{
msg += ", but I won't use them";
}
else
{
msg += ", and I'm not afraid to use them";
itsUseCuda = true;
}
itsLogger->Info(msg);
}
// Get number of threads to use
unsigned short threadCount = ThreadCount(conf->ThreadCount());
if (conf->StatisticsEnabled())
{
conf->Statistics()->UsedThreadCount(threadCount);
conf->Statistics()->UsedGPUCount(0);
}
boost::thread_group g;
shared_ptr<info> targetInfo = conf->Info();
/*
* Set target parameter to precipitation.
*
* We need to specify grib and querydata parameter information
* since we don't know which one will be the output format.
*
*/
vector<param> params;
param requestedParam ("RR-6-MM", 355);
if (conf->Exists("rr1h") && conf->GetValue("rr1h") == "true")
{
params.push_back(param("RR-1-MM", 353));
}
if (conf->Exists("rr3h") && conf->GetValue("rr3h") == "true")
{
params.push_back(param("RR-3-MM", 354));
}
if (conf->Exists("rr6h") && conf->GetValue("rr6h") == "true")
{
params.push_back(param("RR-6-MM", 355));
}
if (conf->Exists("rr12h") && conf->GetValue("rr12h") == "true")
{
params.push_back(param("RR-12-MM", 356));
}
if (params.empty())
{
itsLogger->Trace("No parameter definition given, defaulting to rr6h");
params.push_back(param("RR-6-MM", 355));
}
// GRIB 1
if (conf->OutputFileType() == kGRIB1)
{
shared_ptr<neons> n = dynamic_pointer_cast<neons> (plugin_factory::Instance()->Plugin("neons"));
for (size_t i = 0; i < params.size(); i++)
{
param p = params[i];
long parm_id = n->NeonsDB().GetGridParameterId(targetInfo->Producer().TableVersion(), p.Name());
p.GribIndicatorOfParameter(parm_id);
p.GribTableVersion(targetInfo->Producer().TableVersion());
params[i] = p;
}
}
targetInfo->Params(params);
/*
* Create data structures.
*/
targetInfo->Create();
/*
* Initialize parent class functions for dimension handling
*/
Dimension(conf->LeadingDimension());
FeederInfo(shared_ptr<info> (new info(*targetInfo)));
FeederInfo()->Param(requestedParam);
if (conf->StatisticsEnabled())
{
initTimer->Stop();
conf->Statistics()->AddToInitTime(initTimer->GetTime());
}
/*
* Each thread will have a copy of the target info.
*/
unique_ptr<timer> processTimer = unique_ptr<timer> (timer_factory::Instance()->GetTimer());
if (conf->StatisticsEnabled())
{
processTimer->Start();
}
for (size_t i = 0; i < threadCount; i++)
{
itsLogger->Info("Thread " + boost::lexical_cast<string> (i + 1) + " starting");
boost::thread* t = new boost::thread(&precipitation::Run,
this,
shared_ptr<info> (new info(*targetInfo)),
conf,
i + 1);
g.add_thread(t);
}
g.join_all();
if (conf->StatisticsEnabled())
{
processTimer->Stop();
conf->Statistics()->AddToProcessingTime(processTimer->GetTime());
}
if (conf->FileWriteOption() == kSingleFile)
{
shared_ptr<writer> theWriter = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin("writer"));
string theOutputFile = conf->ConfigurationFile();
theWriter->ToFile(targetInfo, conf, theOutputFile);
}
}
void precipitation::Run(shared_ptr<info> myTargetInfo,
shared_ptr<const plugin_configuration> conf,
unsigned short threadIndex)
{
while (AdjustLeadingDimension(myTargetInfo))
{
Calculate(myTargetInfo, conf, threadIndex);
}
}
/*
* Calculate()
*
* This function does the actual calculation.
*/
void precipitation::Calculate(shared_ptr<info> myTargetInfo,
shared_ptr<const plugin_configuration> conf,
unsigned short threadIndex)
{
unique_ptr<logger> myThreadedLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("precipitationThread #" + boost::lexical_cast<string> (threadIndex)));
ResetNonLeadingDimension(myTargetInfo);
myTargetInfo->FirstParam();
bool dataFoundFromRRParam = true; // Assume that we have parameter RR-KGM2 present
while (AdjustNonLeadingDimension(myTargetInfo))
{
shared_ptr<info> prevInfo;
assert(myTargetInfo->Time().StepResolution() == kHourResolution);
for (myTargetInfo->ResetParam(); myTargetInfo->NextParam(); )
{
shared_ptr<info> RRInfo;
long paramStep;
if (myTargetInfo->Param().Name() == "RR-1-MM")
{
paramStep = 1;
}
else if (myTargetInfo->Param().Name() == "RR-3-MM")
{
paramStep = 3;
}
else if (myTargetInfo->Param().Name() == "RR-6-MM")
{
paramStep = 6;
}
else if (myTargetInfo->Param().Name() == "RR-12-MM")
{
paramStep = 12;
}
else
{
throw runtime_error(ClassName() + ": Unsupported parameter: " + myTargetInfo->Param().Name());
}
myThreadedLogger->Warning("Calculating parameter " + myTargetInfo->Param().Name() + " time " + myTargetInfo->Time().ValidDateTime()->String("%Y%m%d%H") +
" level " + boost::lexical_cast<string> (myTargetInfo->Level().Value()));
try
{
if (!prevInfo || myTargetInfo->Time().Step() - prevInfo->Time().Step() != paramStep)
{
/*
* If this is the first time this loop executed, or if the previous data is not suitable
* for calculating against current time step data, fetch source data.
*/
forecast_time prevTimeStep = myTargetInfo->Time();
if (prevTimeStep.Step() >= paramStep)
{
prevTimeStep.ValidDateTime()->Adjust(kHourResolution, -paramStep);
prevInfo = FetchSourcePrecipitation(conf,prevTimeStep,myTargetInfo->Level(),dataFoundFromRRParam);
}
else
{
continue;
}
}
// Get data for current step
RRInfo = FetchSourcePrecipitation(conf,myTargetInfo->Time(),myTargetInfo->Level(),dataFoundFromRRParam);
}
catch (HPExceptionType e)
{
switch (e)
{
case kFileDataNotFound:
itsLogger->Info("Skipping step " + boost::lexical_cast<string> (myTargetInfo->Time().Step()) + ", level " + boost::lexical_cast<string> (myTargetInfo->Level().Value()));
myTargetInfo->Data()->Fill(kFloatMissing);
if (conf->StatisticsEnabled())
{
conf->Statistics()->AddToMissingCount(myTargetInfo->Grid()->Size());
conf->Statistics()->AddToValueCount(myTargetInfo->Grid()->Size());
}
continue;
break;
default:
throw runtime_error(ClassName() + ": Unable to proceed");
break;
}
}
myThreadedLogger->Debug("Calculating parameter " + myTargetInfo->Param().Name() + " time " + myTargetInfo->Time().ValidDateTime()->String("%Y%m%d%H") +
" level " + boost::lexical_cast<string> (myTargetInfo->Level().Value()));
shared_ptr<NFmiGrid> RRGrid(RRInfo->Grid()->ToNewbaseGrid());
shared_ptr<NFmiGrid> prevGrid(prevInfo->Grid()->ToNewbaseGrid());
shared_ptr<NFmiGrid> targetGrid(myTargetInfo->Grid()->ToNewbaseGrid());
int missingCount = 0;
int count = 0;
bool equalGrids = (*myTargetInfo->Grid() == *RRInfo->Grid());
string deviceType = "CPU";
{
assert(targetGrid->Size() == myTargetInfo->Data()->Size());
myTargetInfo->ResetLocation();
targetGrid->Reset();
prevGrid->Reset();
while (myTargetInfo->NextLocation() && targetGrid->Next() && prevGrid->Next())
{
count++;
double RRcur = kFloatMissing;
double RRprev = kFloatMissing;
InterpolateToPoint(targetGrid, RRGrid, equalGrids, RRcur);
InterpolateToPoint(targetGrid, prevGrid, equalGrids, RRprev);
if (RRcur == kFloatMissing || RRprev == kFloatMissing)
{
missingCount++;
myTargetInfo->Value(kFloatMissing);
continue;
}
double RR = RRcur - RRprev;
if (RR < 0)
{
RR = 0;
}
if (!myTargetInfo->Value(RR))
{
throw runtime_error(ClassName() + ": Failed to set value to matrix");
}
}
prevInfo = RRInfo;
/*
* Newbase normalizes scanning mode to bottom left -- if that's not what
* the target scanning mode is, we have to swap the data back.
*/
SwapTo(myTargetInfo, kBottomLeft);
}
if (conf->StatisticsEnabled())
{
conf->Statistics()->AddToMissingCount(missingCount);
conf->Statistics()->AddToValueCount(count);
}
/*
* Now we are done for this param for this level
*
* Clone info-instance to writer since it might change our descriptor places
*/
myThreadedLogger->Info("Missing values: " + boost::lexical_cast<string> (missingCount) + "/" + boost::lexical_cast<string> (count));
if (conf->FileWriteOption() == kNeons || conf->FileWriteOption() == kMultipleFiles)
{
shared_ptr<writer> w = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin("writer"));
shared_ptr<info> tempInfo(new info(*myTargetInfo));
for (tempInfo->ResetParam(); tempInfo->NextParam(); )
{
w->ToFile(tempInfo, conf);
}
}
}
}
}
shared_ptr<himan::info> precipitation::FetchSourcePrecipitation(shared_ptr<const plugin_configuration> conf, const forecast_time& wantedTime, const level& wantedLevel, bool& dataFoundFromRRParam)
{
try
{
if (dataFoundFromRRParam)
{
return FetchSourceRR(conf,
wantedTime,
wantedLevel);
}
else
{
return FetchSourceConvectiveAndLSRR(conf,
wantedTime,
wantedLevel);
}
}
catch (HPExceptionType e)
{
if (e == kFileDataNotFound && dataFoundFromRRParam)
{
try
{
shared_ptr<info> i = FetchSourceConvectiveAndLSRR(conf,
wantedTime,
wantedLevel);
dataFoundFromRRParam = false;
return i;
}
catch (HPExceptionType e)
{
throw e;
}
}
else
{
throw e;
}
}
throw runtime_error(ClassName() + ": We should never be here but compiler forces this statement");
}
shared_ptr<himan::info> precipitation::FetchSourceRR(shared_ptr<const plugin_configuration> conf, const forecast_time& wantedTime, const level& wantedLevel)
{
shared_ptr<fetcher> f = dynamic_pointer_cast <fetcher> (plugin_factory::Instance()->Plugin("fetcher"));
try
{
return f->Fetch(conf,
wantedTime,
wantedLevel,
param("RR-KGM2"));
}
catch (HPExceptionType e)
{
throw e;
}
}
shared_ptr<himan::info> precipitation::FetchSourceConvectiveAndLSRR(shared_ptr<const plugin_configuration> conf, const forecast_time& wantedTime, const level& wantedLevel)
{
shared_ptr<fetcher> f = dynamic_pointer_cast <fetcher> (plugin_factory::Instance()->Plugin("fetcher"));
shared_ptr<himan::info> ConvectiveInfo;
shared_ptr<himan::info> LSInfo;
shared_ptr<himan::info> RRInfo;
try
{
ConvectiveInfo = f->Fetch(conf,
wantedTime,
wantedLevel,
param("RRC-KGM2"));
LSInfo = f->Fetch(conf,
wantedTime,
wantedLevel,
param("RRR-KGM2"));
}
catch (HPExceptionType e)
{
throw e;
}
ConvectiveInfo->ResetLocation();
LSInfo->ResetLocation();
assert(*ConvectiveInfo->Grid() == *LSInfo->Grid());
RRInfo->Data()->Resize(ConvectiveInfo->Data()->SizeX(),LSInfo->Data()->SizeY());
while (ConvectiveInfo->NextLocation() && LSInfo->NextLocation() && RRInfo->NextLocation())
{
double C = ConvectiveInfo->Value();
double LS = LSInfo->Value();
RRInfo->Value(C+LS);
}
return RRInfo;
}
<|endoftext|>
|
<commit_before>#pragma once
#include "blackhole/logger.hpp"
namespace blackhole {
template<class Logger, class Mutex = std::mutex>
class synchronized {
public:
typedef Logger logger_type;
typedef Mutex mutex_type;
private:
logger_type logger;
mutable mutex_type mutex;
public:
synchronized() {}
explicit synchronized(logger_type&& logger) :
logger(std::move(logger))
{}
synchronized(synchronized&& other) {
*this = std::move(other);
}
synchronized& operator=(synchronized&& other) {
std::lock_guard<mutex_type>(other.mutex);
logger = std::move(other.logger);
return *this;
}
bool enabled() const {
std::lock_guard<mutex_type> lock(mutex);
return logger.enabled();
}
void enable() {
std::lock_guard<mutex_type> lock(mutex);
logger.enable();
}
void disable() {
std::lock_guard<mutex_type> lock(mutex);
logger.disable();
}
void set_filter(filter_t&& filter) {
std::lock_guard<mutex_type> lock(mutex);
logger.set_filter(std::move(filter));
}
void add_attribute(const log::attribute_pair_t& attr) {
std::lock_guard<mutex_type> lock(mutex);
logger.add_attribute(attr);
}
void add_frontend(std::unique_ptr<base_frontend_t> frontend) {
std::lock_guard<mutex_type> lock(mutex);
logger.add_frontend(std::move(frontend));
}
void set_exception_handler(log::exception_handler_t&& handler) {
std::lock_guard<mutex_type> lock(mutex);
logger.set_exception_handler(std::move(handler));
}
template<typename... Args>
log::record_t open_record(Args&&... args) const {
std::lock_guard<mutex_type> lock(mutex);
return logger.open_record(std::forward<Args>(args)...);
}
void push(log::record_t&& record) const {
std::lock_guard<mutex_type> lock(mutex);
logger.push(std::move(record));
}
};
} // namespace blackhole
<commit_msg>[Bug Fix] Acquiring both locks to prevent data race.<commit_after>#pragma once
#include "blackhole/logger.hpp"
namespace blackhole {
template<class Logger, class Mutex = std::mutex>
class synchronized {
public:
typedef Logger logger_type;
typedef Mutex mutex_type;
private:
logger_type logger;
mutable mutex_type mutex;
public:
synchronized() {}
explicit synchronized(logger_type&& logger) :
logger(std::move(logger))
{}
synchronized(synchronized&& other) {
*this = std::move(other);
}
synchronized& operator=(synchronized&& other) {
std::lock(mutex, other.mutex);
logger = std::move(other.logger);
return *this;
}
bool enabled() const {
std::lock_guard<mutex_type> lock(mutex);
return logger.enabled();
}
void enable() {
std::lock_guard<mutex_type> lock(mutex);
logger.enable();
}
void disable() {
std::lock_guard<mutex_type> lock(mutex);
logger.disable();
}
void set_filter(filter_t&& filter) {
std::lock_guard<mutex_type> lock(mutex);
logger.set_filter(std::move(filter));
}
void add_attribute(const log::attribute_pair_t& attr) {
std::lock_guard<mutex_type> lock(mutex);
logger.add_attribute(attr);
}
void add_frontend(std::unique_ptr<base_frontend_t> frontend) {
std::lock_guard<mutex_type> lock(mutex);
logger.add_frontend(std::move(frontend));
}
void set_exception_handler(log::exception_handler_t&& handler) {
std::lock_guard<mutex_type> lock(mutex);
logger.set_exception_handler(std::move(handler));
}
template<typename... Args>
log::record_t open_record(Args&&... args) const {
std::lock_guard<mutex_type> lock(mutex);
return logger.open_record(std::forward<Args>(args)...);
}
void push(log::record_t&& record) const {
std::lock_guard<mutex_type> lock(mutex);
logger.push(std::move(record));
}
};
} // namespace blackhole
<|endoftext|>
|
<commit_before>#ifndef LIGHTGBM_BOOSTING_SCORE_UPDATER_HPP_
#define LIGHTGBM_BOOSTING_SCORE_UPDATER_HPP_
#include <LightGBM/utils/openmp_wrapper.h>
#include <LightGBM/meta.h>
#include <LightGBM/dataset.h>
#include <LightGBM/tree.h>
#include <LightGBM/tree_learner.h>
#include <cstring>
namespace LightGBM {
/*!
* \brief Used to store and update score for data
*/
class ScoreUpdater {
public:
/*!
* \brief Constructor, will pass a const pointer of dataset
* \param data This class will bind with this data set
*/
ScoreUpdater(const Dataset* data, int num_tree_per_iteration) : data_(data) {
num_data_ = data->num_data();
int64_t total_size = static_cast<int64_t>(num_data_) * num_tree_per_iteration;
score_.resize(total_size);
// default start score is zero
#pragma omp parallel for schedule(static)
for (int64_t i = 0; i < total_size; ++i) {
score_[i] = 0.0f;
}
has_init_score_ = false;
const double* init_score = data->metadata().init_score();
// if exists initial score, will start from it
if (init_score != nullptr) {
if ((data->metadata().num_init_score() % num_data_) != 0
|| (data->metadata().num_init_score() / num_data_) != num_tree_per_iteration) {
Log::Fatal("number of class for initial score error");
}
has_init_score_ = true;
#pragma omp parallel for schedule(static)
for (int64_t i = 0; i < total_size; ++i) {
score_[i] = init_score[i];
}
}
}
/*! \brief Destructor */
~ScoreUpdater() {
}
inline bool has_init_score() const { return has_init_score_; }
inline void AddScore(double val, int cur_tree_id) {
int64_t offset = cur_tree_id * num_data_;
#pragma omp parallel for schedule(static)
for (int64_t i = 0; i < num_data_; ++i) {
score_[offset + i] += val;
}
}
/*!
* \brief Using tree model to get prediction number, then adding to scores for all data
* Note: this function generally will be used on validation data too.
* \param tree Trained tree model
* \param cur_tree_id Current tree for multiclass training
*/
inline void AddScore(const Tree* tree, int cur_tree_id) {
tree->AddPredictionToScore(data_, num_data_, score_.data() + cur_tree_id * num_data_);
}
/*!
* \brief Adding prediction score, only used for training data.
* The training data is partitioned into tree leaves after training
* Based on which We can get prediction quickly.
* \param tree_learner
* \param cur_tree_id Current tree for multiclass training
*/
inline void AddScore(const TreeLearner* tree_learner, const Tree* tree, int cur_tree_id) {
tree_learner->AddPredictionToScore(tree, score_.data() + cur_tree_id * num_data_);
}
/*!
* \brief Using tree model to get prediction number, then adding to scores for parts of data
* Used for prediction of training out-of-bag data
* \param tree Trained tree model
* \param data_indices Indices of data that will be processed
* \param data_cnt Number of data that will be processed
* \param cur_tree_id Current tree for multiclass training
*/
inline void AddScore(const Tree* tree, const data_size_t* data_indices,
data_size_t data_cnt, int cur_tree_id) {
tree->AddPredictionToScore(data_, data_indices, data_cnt, score_.data() + cur_tree_id * num_data_);
}
/*! \brief Pointer of score */
inline const double* score() const { return score_.data(); }
inline const data_size_t num_data() const { return num_data_; }
/*! \brief Disable copy */
ScoreUpdater& operator=(const ScoreUpdater&) = delete;
/*! \brief Disable copy */
ScoreUpdater(const ScoreUpdater&) = delete;
private:
/*! \brief Number of total data */
data_size_t num_data_;
/*! \brief Pointer of data set */
const Dataset* data_;
/*! \brief Scores for data set */
std::vector<double> score_;
bool has_init_score_;
};
} // namespace LightGBM
#endif // LightGBM_BOOSTING_SCORE_UPDATER_HPP_
<commit_msg>Shut up warning (#534)<commit_after>#ifndef LIGHTGBM_BOOSTING_SCORE_UPDATER_HPP_
#define LIGHTGBM_BOOSTING_SCORE_UPDATER_HPP_
#include <LightGBM/utils/openmp_wrapper.h>
#include <LightGBM/meta.h>
#include <LightGBM/dataset.h>
#include <LightGBM/tree.h>
#include <LightGBM/tree_learner.h>
#include <cstring>
namespace LightGBM {
/*!
* \brief Used to store and update score for data
*/
class ScoreUpdater {
public:
/*!
* \brief Constructor, will pass a const pointer of dataset
* \param data This class will bind with this data set
*/
ScoreUpdater(const Dataset* data, int num_tree_per_iteration) : data_(data) {
num_data_ = data->num_data();
int64_t total_size = static_cast<int64_t>(num_data_) * num_tree_per_iteration;
score_.resize(total_size);
// default start score is zero
#pragma omp parallel for schedule(static)
for (int64_t i = 0; i < total_size; ++i) {
score_[i] = 0.0f;
}
has_init_score_ = false;
const double* init_score = data->metadata().init_score();
// if exists initial score, will start from it
if (init_score != nullptr) {
if ((data->metadata().num_init_score() % num_data_) != 0
|| (data->metadata().num_init_score() / num_data_) != num_tree_per_iteration) {
Log::Fatal("number of class for initial score error");
}
has_init_score_ = true;
#pragma omp parallel for schedule(static)
for (int64_t i = 0; i < total_size; ++i) {
score_[i] = init_score[i];
}
}
}
/*! \brief Destructor */
~ScoreUpdater() {
}
inline bool has_init_score() const { return has_init_score_; }
inline void AddScore(double val, int cur_tree_id) {
int64_t offset = cur_tree_id * num_data_;
#pragma omp parallel for schedule(static)
for (int64_t i = 0; i < num_data_; ++i) {
score_[offset + i] += val;
}
}
/*!
* \brief Using tree model to get prediction number, then adding to scores for all data
* Note: this function generally will be used on validation data too.
* \param tree Trained tree model
* \param cur_tree_id Current tree for multiclass training
*/
inline void AddScore(const Tree* tree, int cur_tree_id) {
tree->AddPredictionToScore(data_, num_data_, score_.data() + cur_tree_id * num_data_);
}
/*!
* \brief Adding prediction score, only used for training data.
* The training data is partitioned into tree leaves after training
* Based on which We can get prediction quickly.
* \param tree_learner
* \param cur_tree_id Current tree for multiclass training
*/
inline void AddScore(const TreeLearner* tree_learner, const Tree* tree, int cur_tree_id) {
tree_learner->AddPredictionToScore(tree, score_.data() + cur_tree_id * num_data_);
}
/*!
* \brief Using tree model to get prediction number, then adding to scores for parts of data
* Used for prediction of training out-of-bag data
* \param tree Trained tree model
* \param data_indices Indices of data that will be processed
* \param data_cnt Number of data that will be processed
* \param cur_tree_id Current tree for multiclass training
*/
inline void AddScore(const Tree* tree, const data_size_t* data_indices,
data_size_t data_cnt, int cur_tree_id) {
tree->AddPredictionToScore(data_, data_indices, data_cnt, score_.data() + cur_tree_id * num_data_);
}
/*! \brief Pointer of score */
inline const double* score() const { return score_.data(); }
inline data_size_t num_data() const { return num_data_; }
/*! \brief Disable copy */
ScoreUpdater& operator=(const ScoreUpdater&) = delete;
/*! \brief Disable copy */
ScoreUpdater(const ScoreUpdater&) = delete;
private:
/*! \brief Number of total data */
data_size_t num_data_;
/*! \brief Pointer of data set */
const Dataset* data_;
/*! \brief Scores for data set */
std::vector<double> score_;
bool has_init_score_;
};
} // namespace LightGBM
#endif // LightGBM_BOOSTING_SCORE_UPDATER_HPP_
<|endoftext|>
|
<commit_before>#include <wayfire/plugin.hpp>
#include <wayfire/debug.hpp>
#include <wayfire/output.hpp>
#include <wayfire/core.hpp>
#include <wayfire/view.hpp>
#include <wayfire/workspace-manager.hpp>
#include <wayfire/render-manager.hpp>
#include <algorithm>
#include <cmath>
#include <linux/input-event-codes.h>
#include "wayfire/signal-definitions.hpp"
#include <wayfire/plugins/common/geometry-animation.hpp>
#include "snap_signal.hpp"
#include "../wobbly/wobbly-signal.hpp"
extern "C"
{
#include <wlr/util/edges.h>
}
const std::string grid_view_id = "grid-view";
class wayfire_grid_view_cdata : public wf::custom_data_t
{
bool is_active = true;
wayfire_view view;
wf::output_t *output;
wf::effect_hook_t pre_hook;
wf::signal_callback_t unmapped;
int32_t tiled_edges = -1;
const wf::plugin_grab_interface_uptr& iface;
wf::option_wrapper_t<std::string> animation_type{"grid/type"};
wf::option_wrapper_t<int> animation_duration{"grid/duration"};
wf::geometry_animation_t animation{animation_duration};
public:
wayfire_grid_view_cdata(wayfire_view view,
const wf::plugin_grab_interface_uptr& _iface)
: iface(_iface)
{
this->view = view;
this->output = view->get_output();
this->animation = wf::geometry_animation_t{animation_duration};
if (!view->get_output()->activate_plugin(iface,
wf::PLUGIN_ACTIVATE_ALLOW_MULTIPLE))
{
is_active = false;
return;
}
pre_hook = [=] () {
adjust_geometry();
};
output->render->add_effect(&pre_hook, wf::OUTPUT_EFFECT_PRE);
unmapped = [=] (wf::signal_data_t *data)
{
if (get_signaled_view(data) == view)
destroy();
};
output->render->set_redraw_always(true);
output->connect_signal("view-disappeared", &unmapped);
output->connect_signal("detach-view", &unmapped);
}
void destroy()
{
view->erase_data<wayfire_grid_view_cdata>();
}
void adjust_target_geometry(wf::geometry_t geometry, int32_t target_edges)
{
animation.set_start(view->get_wm_geometry());
animation.set_end(geometry);
/* Restore tiled edges if we don't need to set something special when
* grid is ready */
if (target_edges < 0) {
this->tiled_edges = view->tiled_edges;
} else {
this->tiled_edges = target_edges;
}
std::string type = animation_type;
if (view->get_transformer("wobbly") || !is_active)
type = "wobbly";
if (type == "none")
{
set_end_state(geometry, tiled_edges);
return destroy();
}
if (type == "wobbly")
{
/* Order is important here: first we set the view geometry, and
* after that we set the snap request. Otherwise the wobbly plugin
* will think the view actually moved */
set_end_state(geometry, tiled_edges);
activate_wobbly(view);
return destroy();
}
view->set_tiled(wf::TILED_EDGES_ALL);
view->set_moving(1);
view->set_resizing(1);
animation.start();
}
void set_end_state(wf::geometry_t geometry, int32_t edges)
{
view->set_geometry(geometry);
if (edges >= 0)
view->set_tiled(edges);
}
void adjust_geometry()
{
if (!animation.running())
{
set_end_state(animation, tiled_edges);
view->set_moving(0);
view->set_resizing(0);
return destroy();
}
view->set_geometry((wf::geometry_t) animation);
}
~wayfire_grid_view_cdata()
{
if (!is_active)
return;
output->render->rem_effect(&pre_hook);
output->deactivate_plugin(iface);
output->render->set_redraw_always(false);
output->disconnect_signal("view-disappeared", &unmapped);
output->disconnect_signal("detach-view", &unmapped);
}
};
class wf_grid_slot_data : public wf::custom_data_t
{
public:
int slot;
};
nonstd::observer_ptr<wayfire_grid_view_cdata> ensure_grid_view(wayfire_view view,
const wf::plugin_grab_interface_uptr& iface)
{
if (!view->has_data<wayfire_grid_view_cdata>())
{
view->store_data(
std::make_unique<wayfire_grid_view_cdata> (view, iface));
}
return view->get_data<wayfire_grid_view_cdata> ();
}
class wf_grid_saved_view_geometry : public wf::custom_data_t
{
public:
wf::geometry_t geometry;
uint32_t tiled_edges;
};
/*
* 7 8 9
* 4 5 6
* 1 2 3
*/
static uint32_t get_tiled_edges_for_slot(uint32_t slot)
{
if (slot == 0)
return 0;
uint32_t edges = wf::TILED_EDGES_ALL;
if (slot % 3 == 0)
edges &= ~WLR_EDGE_LEFT;
if (slot % 3 == 1)
edges &= ~WLR_EDGE_RIGHT;
if (slot <= 3)
edges &= ~WLR_EDGE_TOP;
if (slot >= 7)
edges &= ~WLR_EDGE_BOTTOM;
return edges;
}
static uint32_t get_slot_from_tiled_edges(uint32_t edges)
{
for (int slot = 0; slot <= 9; slot++)
{
if (get_tiled_edges_for_slot(slot) == edges)
return slot;
}
return 0;
}
class wayfire_grid : public wf::plugin_interface_t
{
std::vector<std::string> slots = {"unused", "bl", "b", "br", "l", "c", "r", "tl", "t", "tr"};
wf::activator_callback bindings[10];
wf::option_wrapper_t<wf::activatorbinding_t> keys[10];
wf::option_wrapper_t<wf::activatorbinding_t> restore_opt{"grid/restore"};
wf::activator_callback restore = [=] (wf::activator_source_t, uint32_t)
{
if (!output->can_activate_plugin(grab_interface))
return false;
auto view = output->get_active_view();
if (!view || view->role != wf::VIEW_ROLE_TOPLEVEL)
return false;
view->tile_request(0);
return true;
};
nonstd::observer_ptr<wayfire_grid_view_cdata>
ensure_grid_view(wayfire_view view)
{
return ::ensure_grid_view(view, grab_interface);
}
public:
void init() override
{
grab_interface->name = "grid";
grab_interface->capabilities = wf::CAPABILITY_MANAGE_DESKTOP;
for (int i = 1; i < 10; i++)
{
keys[i].load_option("grid/slot_" + slots[i]);
bindings[i] = [=] (wf::activator_source_t, uint32_t)
{
auto view = output->get_active_view();
if (!view || view->role != wf::VIEW_ROLE_TOPLEVEL)
return false;
handle_slot(view, i);
return true;
};
output->add_activator(keys[i], &bindings[i]);
}
output->add_activator(restore_opt, &restore);
output->connect_signal("reserved-workarea", &on_workarea_changed);
output->connect_signal("view-snap", &on_snap_signal);
output->connect_signal("query-snap-geometry", &on_snap_query);
output->connect_signal("view-maximized-request", &on_maximize_signal);
output->connect_signal("view-fullscreen-request", &on_fullscreen_signal);
}
bool can_adjust_view(wayfire_view view)
{
auto workspace_impl =
output->workspace->get_workspace_implementation();
return workspace_impl->view_movable(view) &&
workspace_impl->view_resizable(view);
}
void handle_slot(wayfire_view view, int slot, wf::point_t delta = {0, 0})
{
if (!can_adjust_view(view))
return;
view->get_data_safe<wf_grid_slot_data>()->slot = slot;
ensure_grid_view(view)->adjust_target_geometry(
get_slot_dimensions(slot) + delta,
get_tiled_edges_for_slot(slot));
}
/*
* 7 8 9
* 4 5 6
* 1 2 3
* */
wf::geometry_t get_slot_dimensions(int n)
{
auto area = output->workspace->get_workarea();
int w2 = area.width / 2;
int h2 = area.height / 2;
if (n % 3 == 1)
area.width = w2;
if (n % 3 == 0)
area.width = w2, area.x += w2;
if (n >= 7)
area.height = h2;
else if (n <= 3)
area.height = h2, area.y += h2;
return area;
}
wf::signal_callback_t on_workarea_changed = [=] (wf::signal_data_t *data)
{
auto ev = static_cast<reserved_workarea_signal*> (data);
for (auto& view : output->workspace->get_views_in_layer(wf::LAYER_WORKSPACE))
{
if (!view->is_mapped())
continue;
auto data = view->get_data_safe<wf_grid_slot_data>();
/* Detect if the view was maximized outside of the grid plugin */
auto wm = view->get_wm_geometry();
if (view->tiled_edges && wm.width == ev->old_workarea.width
&& wm.height == ev->old_workarea.height)
{
data->slot = SLOT_CENTER;
}
if (!data->slot)
continue;
/* Workarea changed, and we have a view which is tiled into some slot.
* We need to make sure it remains in its slot. So we calculate the
* viewport of the view, and tile it there */
auto output_geometry = output->get_relative_geometry();
int vx = std::floor(1.0 * wm.x / output_geometry.width);
int vy = std::floor(1.0 * wm.y / output_geometry.height);
handle_slot(view, data->slot,
{vx * output_geometry.width, vy * output_geometry.height});
}
};
wf::signal_callback_t on_snap_query = [=] (wf::signal_data_t *data)
{
auto query = dynamic_cast<snap_query_signal*> (data);
assert(query);
query->out_geometry = get_slot_dimensions(query->slot);
};
wf::signal_callback_t on_snap_signal = [=] (wf::signal_data_t *ddata)
{
snap_signal *data = dynamic_cast<snap_signal*>(ddata);
handle_slot(data->view, data->slot);
};
wf::signal_callback_t on_maximize_signal = [=] (wf::signal_data_t *ddata)
{
auto data = static_cast<view_tiled_signal*> (ddata);
if (data->carried_out || data->desired_size.width <= 0 ||
!can_adjust_view(data->view))
{
return;
}
data->carried_out = true;
uint32_t slot = get_slot_from_tiled_edges(data->edges);
if (slot > 0)
data->desired_size = get_slot_dimensions(slot);
data->view->get_data_safe<wf_grid_slot_data>()->slot = slot;
ensure_grid_view(data->view)->adjust_target_geometry(data->desired_size,
get_tiled_edges_for_slot(slot));
};
wf::signal_callback_t on_fullscreen_signal = [=] (wf::signal_data_t *ev)
{
auto data = static_cast<view_fullscreen_signal*> (ev);
static const std::string fs_data_name = "grid-saved-fs";
if (data->carried_out || data->desired_size.width <= 0 ||
!can_adjust_view(data->view))
{
return;
}
data->carried_out = true;
ensure_grid_view(data->view)->adjust_target_geometry(
data->desired_size, -1);
};
void fini() override
{
for (int i = 1; i < 10; i++)
output->rem_binding(&bindings[i]);
output->rem_binding(&restore);
output->disconnect_signal("reserved-workarea", &on_workarea_changed);
output->disconnect_signal("view-snap", &on_snap_signal);
output->disconnect_signal("query-snap-geometry", &on_snap_query);
output->disconnect_signal("view-maximized-request", &on_maximize_signal);
output->disconnect_signal("view-fullscreen-request", &on_fullscreen_signal);
}
};
DECLARE_WAYFIRE_PLUGIN(wayfire_grid);
<commit_msg>grid: set geometry after setting tiled edges<commit_after>#include <wayfire/plugin.hpp>
#include <wayfire/debug.hpp>
#include <wayfire/output.hpp>
#include <wayfire/core.hpp>
#include <wayfire/view.hpp>
#include <wayfire/workspace-manager.hpp>
#include <wayfire/render-manager.hpp>
#include <algorithm>
#include <cmath>
#include <linux/input-event-codes.h>
#include "wayfire/signal-definitions.hpp"
#include <wayfire/plugins/common/geometry-animation.hpp>
#include "snap_signal.hpp"
#include "../wobbly/wobbly-signal.hpp"
extern "C"
{
#include <wlr/util/edges.h>
}
const std::string grid_view_id = "grid-view";
class wayfire_grid_view_cdata : public wf::custom_data_t
{
bool is_active = true;
wayfire_view view;
wf::output_t *output;
wf::effect_hook_t pre_hook;
wf::signal_callback_t unmapped;
int32_t tiled_edges = -1;
const wf::plugin_grab_interface_uptr& iface;
wf::option_wrapper_t<std::string> animation_type{"grid/type"};
wf::option_wrapper_t<int> animation_duration{"grid/duration"};
wf::geometry_animation_t animation{animation_duration};
public:
wayfire_grid_view_cdata(wayfire_view view,
const wf::plugin_grab_interface_uptr& _iface)
: iface(_iface)
{
this->view = view;
this->output = view->get_output();
this->animation = wf::geometry_animation_t{animation_duration};
if (!view->get_output()->activate_plugin(iface,
wf::PLUGIN_ACTIVATE_ALLOW_MULTIPLE))
{
is_active = false;
return;
}
pre_hook = [=] () {
adjust_geometry();
};
output->render->add_effect(&pre_hook, wf::OUTPUT_EFFECT_PRE);
unmapped = [=] (wf::signal_data_t *data)
{
if (get_signaled_view(data) == view)
destroy();
};
output->render->set_redraw_always(true);
output->connect_signal("view-disappeared", &unmapped);
output->connect_signal("detach-view", &unmapped);
}
void destroy()
{
view->erase_data<wayfire_grid_view_cdata>();
}
void adjust_target_geometry(wf::geometry_t geometry, int32_t target_edges)
{
animation.set_start(view->get_wm_geometry());
animation.set_end(geometry);
/* Restore tiled edges if we don't need to set something special when
* grid is ready */
if (target_edges < 0) {
this->tiled_edges = view->tiled_edges;
} else {
this->tiled_edges = target_edges;
}
std::string type = animation_type;
if (view->get_transformer("wobbly") || !is_active)
type = "wobbly";
if (type == "none")
{
set_end_state(geometry, tiled_edges);
return destroy();
}
if (type == "wobbly")
{
/* Order is important here: first we set the view geometry, and
* after that we set the snap request. Otherwise the wobbly plugin
* will think the view actually moved */
set_end_state(geometry, tiled_edges);
activate_wobbly(view);
return destroy();
}
view->set_tiled(wf::TILED_EDGES_ALL);
view->set_moving(1);
view->set_resizing(1);
animation.start();
}
void set_end_state(wf::geometry_t geometry, int32_t edges)
{
if (edges >= 0)
view->set_tiled(edges);
view->set_geometry(geometry);
}
void adjust_geometry()
{
if (!animation.running())
{
set_end_state(animation, tiled_edges);
view->set_moving(0);
view->set_resizing(0);
return destroy();
}
view->set_geometry((wf::geometry_t) animation);
}
~wayfire_grid_view_cdata()
{
if (!is_active)
return;
output->render->rem_effect(&pre_hook);
output->deactivate_plugin(iface);
output->render->set_redraw_always(false);
output->disconnect_signal("view-disappeared", &unmapped);
output->disconnect_signal("detach-view", &unmapped);
}
};
class wf_grid_slot_data : public wf::custom_data_t
{
public:
int slot;
};
nonstd::observer_ptr<wayfire_grid_view_cdata> ensure_grid_view(wayfire_view view,
const wf::plugin_grab_interface_uptr& iface)
{
if (!view->has_data<wayfire_grid_view_cdata>())
{
view->store_data(
std::make_unique<wayfire_grid_view_cdata> (view, iface));
}
return view->get_data<wayfire_grid_view_cdata> ();
}
class wf_grid_saved_view_geometry : public wf::custom_data_t
{
public:
wf::geometry_t geometry;
uint32_t tiled_edges;
};
/*
* 7 8 9
* 4 5 6
* 1 2 3
*/
static uint32_t get_tiled_edges_for_slot(uint32_t slot)
{
if (slot == 0)
return 0;
uint32_t edges = wf::TILED_EDGES_ALL;
if (slot % 3 == 0)
edges &= ~WLR_EDGE_LEFT;
if (slot % 3 == 1)
edges &= ~WLR_EDGE_RIGHT;
if (slot <= 3)
edges &= ~WLR_EDGE_TOP;
if (slot >= 7)
edges &= ~WLR_EDGE_BOTTOM;
return edges;
}
static uint32_t get_slot_from_tiled_edges(uint32_t edges)
{
for (int slot = 0; slot <= 9; slot++)
{
if (get_tiled_edges_for_slot(slot) == edges)
return slot;
}
return 0;
}
class wayfire_grid : public wf::plugin_interface_t
{
std::vector<std::string> slots = {"unused", "bl", "b", "br", "l", "c", "r", "tl", "t", "tr"};
wf::activator_callback bindings[10];
wf::option_wrapper_t<wf::activatorbinding_t> keys[10];
wf::option_wrapper_t<wf::activatorbinding_t> restore_opt{"grid/restore"};
wf::activator_callback restore = [=] (wf::activator_source_t, uint32_t)
{
if (!output->can_activate_plugin(grab_interface))
return false;
auto view = output->get_active_view();
if (!view || view->role != wf::VIEW_ROLE_TOPLEVEL)
return false;
view->tile_request(0);
return true;
};
nonstd::observer_ptr<wayfire_grid_view_cdata>
ensure_grid_view(wayfire_view view)
{
return ::ensure_grid_view(view, grab_interface);
}
public:
void init() override
{
grab_interface->name = "grid";
grab_interface->capabilities = wf::CAPABILITY_MANAGE_DESKTOP;
for (int i = 1; i < 10; i++)
{
keys[i].load_option("grid/slot_" + slots[i]);
bindings[i] = [=] (wf::activator_source_t, uint32_t)
{
auto view = output->get_active_view();
if (!view || view->role != wf::VIEW_ROLE_TOPLEVEL)
return false;
handle_slot(view, i);
return true;
};
output->add_activator(keys[i], &bindings[i]);
}
output->add_activator(restore_opt, &restore);
output->connect_signal("reserved-workarea", &on_workarea_changed);
output->connect_signal("view-snap", &on_snap_signal);
output->connect_signal("query-snap-geometry", &on_snap_query);
output->connect_signal("view-maximized-request", &on_maximize_signal);
output->connect_signal("view-fullscreen-request", &on_fullscreen_signal);
}
bool can_adjust_view(wayfire_view view)
{
auto workspace_impl =
output->workspace->get_workspace_implementation();
return workspace_impl->view_movable(view) &&
workspace_impl->view_resizable(view);
}
void handle_slot(wayfire_view view, int slot, wf::point_t delta = {0, 0})
{
if (!can_adjust_view(view))
return;
view->get_data_safe<wf_grid_slot_data>()->slot = slot;
ensure_grid_view(view)->adjust_target_geometry(
get_slot_dimensions(slot) + delta,
get_tiled_edges_for_slot(slot));
}
/*
* 7 8 9
* 4 5 6
* 1 2 3
* */
wf::geometry_t get_slot_dimensions(int n)
{
auto area = output->workspace->get_workarea();
int w2 = area.width / 2;
int h2 = area.height / 2;
if (n % 3 == 1)
area.width = w2;
if (n % 3 == 0)
area.width = w2, area.x += w2;
if (n >= 7)
area.height = h2;
else if (n <= 3)
area.height = h2, area.y += h2;
return area;
}
wf::signal_callback_t on_workarea_changed = [=] (wf::signal_data_t *data)
{
auto ev = static_cast<reserved_workarea_signal*> (data);
for (auto& view : output->workspace->get_views_in_layer(wf::LAYER_WORKSPACE))
{
if (!view->is_mapped())
continue;
auto data = view->get_data_safe<wf_grid_slot_data>();
/* Detect if the view was maximized outside of the grid plugin */
auto wm = view->get_wm_geometry();
if (view->tiled_edges && wm.width == ev->old_workarea.width
&& wm.height == ev->old_workarea.height)
{
data->slot = SLOT_CENTER;
}
if (!data->slot)
continue;
/* Workarea changed, and we have a view which is tiled into some slot.
* We need to make sure it remains in its slot. So we calculate the
* viewport of the view, and tile it there */
auto output_geometry = output->get_relative_geometry();
int vx = std::floor(1.0 * wm.x / output_geometry.width);
int vy = std::floor(1.0 * wm.y / output_geometry.height);
handle_slot(view, data->slot,
{vx * output_geometry.width, vy * output_geometry.height});
}
};
wf::signal_callback_t on_snap_query = [=] (wf::signal_data_t *data)
{
auto query = dynamic_cast<snap_query_signal*> (data);
assert(query);
query->out_geometry = get_slot_dimensions(query->slot);
};
wf::signal_callback_t on_snap_signal = [=] (wf::signal_data_t *ddata)
{
snap_signal *data = dynamic_cast<snap_signal*>(ddata);
handle_slot(data->view, data->slot);
};
wf::signal_callback_t on_maximize_signal = [=] (wf::signal_data_t *ddata)
{
auto data = static_cast<view_tiled_signal*> (ddata);
if (data->carried_out || data->desired_size.width <= 0 ||
!can_adjust_view(data->view))
{
return;
}
data->carried_out = true;
uint32_t slot = get_slot_from_tiled_edges(data->edges);
if (slot > 0)
data->desired_size = get_slot_dimensions(slot);
data->view->get_data_safe<wf_grid_slot_data>()->slot = slot;
ensure_grid_view(data->view)->adjust_target_geometry(data->desired_size,
get_tiled_edges_for_slot(slot));
};
wf::signal_callback_t on_fullscreen_signal = [=] (wf::signal_data_t *ev)
{
auto data = static_cast<view_fullscreen_signal*> (ev);
static const std::string fs_data_name = "grid-saved-fs";
if (data->carried_out || data->desired_size.width <= 0 ||
!can_adjust_view(data->view))
{
return;
}
data->carried_out = true;
ensure_grid_view(data->view)->adjust_target_geometry(
data->desired_size, -1);
};
void fini() override
{
for (int i = 1; i < 10; i++)
output->rem_binding(&bindings[i]);
output->rem_binding(&restore);
output->disconnect_signal("reserved-workarea", &on_workarea_changed);
output->disconnect_signal("view-snap", &on_snap_signal);
output->disconnect_signal("query-snap-geometry", &on_snap_query);
output->disconnect_signal("view-maximized-request", &on_maximize_signal);
output->disconnect_signal("view-fullscreen-request", &on_fullscreen_signal);
}
};
DECLARE_WAYFIRE_PLUGIN(wayfire_grid);
<|endoftext|>
|
<commit_before>/*
Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>
This file is part of Magnum.
Magnum 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.
Magnum 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.
*/
#include "Camera.h"
#include "Scene.h"
using namespace std;
namespace Magnum {
Camera::Camera(Object* parent): Object(parent), _aspectRatioPolicy(Extend) {}
void Camera::setOrthographic(GLfloat size, GLfloat near, GLfloat far) {
_near = near;
_far = far;
/* Scale the volume down so it fits in (-1, 1) in all directions */
GLfloat xyScale = 2/size;
GLfloat zScale = 2/(far-near);
rawProjectionMatrix = Matrix4::scaling({xyScale, xyScale, -zScale});
/* Move the volume on z into (-1, 1) range */
rawProjectionMatrix = Matrix4::translation(Vector3::zAxis(-1-near*zScale))*rawProjectionMatrix;
fixAspectRatio();
}
void Camera::setPerspective(GLfloat fov, GLfloat near, GLfloat far) {
_near = near;
_far = far;
/* First move the volume on z in (-1, 1) range */
rawProjectionMatrix = Matrix4::translation(Vector3::zAxis(2*far*near/(far+near)));
/* Then apply magic perspective matrix (with reversed Z) */
static const Matrix4 a(1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, -1.0f, -1.0f,
0.0f, 0.0f, 0.0f, 0.0f);
rawProjectionMatrix = a*rawProjectionMatrix;
/* Then scale the volume down so it fits in (-1, 1) in all directions */
GLfloat xyScale = 1/tan(fov/2);
GLfloat zScale = 1+2*near/(far-near);
rawProjectionMatrix = Matrix4::scaling({xyScale, xyScale, zScale})*rawProjectionMatrix;
/* And... another magic */
rawProjectionMatrix[3][3] = 0;
fixAspectRatio();
}
void Camera::setViewport(const Math::Vector2<GLsizei>& size) {
glViewport(0, 0, size.x(), size.y());
_viewport = size;
fixAspectRatio();
}
void Camera::clean(const Matrix4& absoluteTransformation) {
Object::clean(absoluteTransformation);
_cameraMatrix = absoluteTransformation.inverted();
}
void Camera::fixAspectRatio() {
/* Don't divide by zero */
if(_viewport.x() == 0 || _viewport.y() == 0) {
_projectionMatrix = rawProjectionMatrix;
return;
}
/* Extend on larger side = scale larger side down */
if(_aspectRatioPolicy == Extend) {
_projectionMatrix = ((_viewport.x() > _viewport.y()) ?
Matrix4::scaling({GLfloat(_viewport.y())/_viewport.x(), 1, 1}) :
Matrix4::scaling({1, GLfloat(_viewport.x())/_viewport.y(), 1})
)*rawProjectionMatrix;
/* Clip on smaller side = scale smaller side up */
} else if(_aspectRatioPolicy == Clip) {
_projectionMatrix = ((_viewport.x() > _viewport.y()) ?
Matrix4::scaling({1, GLfloat(_viewport.x())/_viewport.y(), 1}) :
Matrix4::scaling({GLfloat(_viewport.y())/_viewport.x(), 1, 1})
)*rawProjectionMatrix;
/* Don't preserve anything */
} else _projectionMatrix = rawProjectionMatrix;
}
void Camera::setClearColor(const Magnum::Vector4& color) {
glClearColor(color.r(), color.g(), color.b(), color.a());
_clearColor = color;
}
void Camera::draw() {
/** @todo Clear only set features */
glClear(GL_COLOR_BUFFER_BIT|GL_STENCIL_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
/* Recursively draw child objects */
drawChildren(scene(), cameraMatrix());
}
void Camera::drawChildren(Object* object, const Matrix4& transformationMatrix) {
for(set<Object*>::const_iterator it = object->children().begin(); it != object->children().end(); ++it) {
/* Transformation matrix for the object */
Matrix4 matrix = transformationMatrix*(*it)->transformation();
/* Draw the object and its children */
(*it)->draw(matrix, this);
drawChildren(*it, matrix);
}
}
}
<commit_msg>Camera must be attached to scene when attempting to draw.<commit_after>/*
Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>
This file is part of Magnum.
Magnum 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.
Magnum 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.
*/
#include "Camera.h"
#include "Scene.h"
using namespace std;
namespace Magnum {
Camera::Camera(Object* parent): Object(parent), _aspectRatioPolicy(Extend) {}
void Camera::setOrthographic(GLfloat size, GLfloat near, GLfloat far) {
_near = near;
_far = far;
/* Scale the volume down so it fits in (-1, 1) in all directions */
GLfloat xyScale = 2/size;
GLfloat zScale = 2/(far-near);
rawProjectionMatrix = Matrix4::scaling({xyScale, xyScale, -zScale});
/* Move the volume on z into (-1, 1) range */
rawProjectionMatrix = Matrix4::translation(Vector3::zAxis(-1-near*zScale))*rawProjectionMatrix;
fixAspectRatio();
}
void Camera::setPerspective(GLfloat fov, GLfloat near, GLfloat far) {
_near = near;
_far = far;
/* First move the volume on z in (-1, 1) range */
rawProjectionMatrix = Matrix4::translation(Vector3::zAxis(2*far*near/(far+near)));
/* Then apply magic perspective matrix (with reversed Z) */
static const Matrix4 a(1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, -1.0f, -1.0f,
0.0f, 0.0f, 0.0f, 0.0f);
rawProjectionMatrix = a*rawProjectionMatrix;
/* Then scale the volume down so it fits in (-1, 1) in all directions */
GLfloat xyScale = 1/tan(fov/2);
GLfloat zScale = 1+2*near/(far-near);
rawProjectionMatrix = Matrix4::scaling({xyScale, xyScale, zScale})*rawProjectionMatrix;
/* And... another magic */
rawProjectionMatrix[3][3] = 0;
fixAspectRatio();
}
void Camera::setViewport(const Math::Vector2<GLsizei>& size) {
glViewport(0, 0, size.x(), size.y());
_viewport = size;
fixAspectRatio();
}
void Camera::clean(const Matrix4& absoluteTransformation) {
Object::clean(absoluteTransformation);
_cameraMatrix = absoluteTransformation.inverted();
}
void Camera::fixAspectRatio() {
/* Don't divide by zero */
if(_viewport.x() == 0 || _viewport.y() == 0) {
_projectionMatrix = rawProjectionMatrix;
return;
}
/* Extend on larger side = scale larger side down */
if(_aspectRatioPolicy == Extend) {
_projectionMatrix = ((_viewport.x() > _viewport.y()) ?
Matrix4::scaling({GLfloat(_viewport.y())/_viewport.x(), 1, 1}) :
Matrix4::scaling({1, GLfloat(_viewport.x())/_viewport.y(), 1})
)*rawProjectionMatrix;
/* Clip on smaller side = scale smaller side up */
} else if(_aspectRatioPolicy == Clip) {
_projectionMatrix = ((_viewport.x() > _viewport.y()) ?
Matrix4::scaling({1, GLfloat(_viewport.x())/_viewport.y(), 1}) :
Matrix4::scaling({GLfloat(_viewport.y())/_viewport.x(), 1, 1})
)*rawProjectionMatrix;
/* Don't preserve anything */
} else _projectionMatrix = rawProjectionMatrix;
}
void Camera::setClearColor(const Magnum::Vector4& color) {
glClearColor(color.r(), color.g(), color.b(), color.a());
_clearColor = color;
}
void Camera::draw() {
Scene* s = scene();
CORRADE_ASSERT(s, "Camera: cannot draw without camera attached to scene", )
/** @todo Clear only set features */
glClear(GL_COLOR_BUFFER_BIT|GL_STENCIL_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
/* Recursively draw child objects */
drawChildren(s, cameraMatrix());
}
void Camera::drawChildren(Object* object, const Matrix4& transformationMatrix) {
for(set<Object*>::const_iterator it = object->children().begin(); it != object->children().end(); ++it) {
/* Transformation matrix for the object */
Matrix4 matrix = transformationMatrix*(*it)->transformation();
/* Draw the object and its children */
(*it)->draw(matrix, this);
drawChildren(*it, matrix);
}
}
}
<|endoftext|>
|
<commit_before>/* Copyright 2016 Streampunk Media Ltd
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.
*/
/* -LICENSE-START-
** Copyright (c) 2010 Blackmagic Design
**
** Permission is hereby granted, free of charge, to any person or organization
** obtaining a copy of the software and accompanying documentation covered by
** this license (the "Software") to use, reproduce, display, distribute,
** execute, and transmit the Software, and to prepare derivative works of the
** Software, and to permit third-parties to whom the Software is furnished to
** do so, all subject to the following:
**
** The copyright notices in the Software and this entire statement, including
** the above license grant, this restriction and the following disclaimer,
** must be included in all copies of the Software, in whole or in part, and
** all derivative works of the Software, unless such copies or derivative
** works are solely in the form of machine-executable object code generated by
** a source language processor.
**
** 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
** DEALINGS IN THE SOFTWARE.
** -LICENSE-END-
*/
#include "Capture.h"
namespace streampunk {
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Value;
using v8::EscapableHandleScope;
using v8::HandleScope;
using v8::Exception;
Persistent<Function> Capture::constructor;
Capture::Capture(uint32_t deviceIndex, uint32_t displayMode,
uint32_t pixelFormat) : deviceIndex_(deviceIndex),
displayMode_(displayMode), pixelFormat_(pixelFormat), latestFrame_(NULL) {
async = new uv_async_t;
uv_async_init(uv_default_loop(), async, FrameCallback);
async->data = this;
}
Capture::~Capture() {
if (!captureCB_.IsEmpty())
captureCB_.Reset();
}
void Capture::Init(Local<Object> exports) {
Isolate* isolate = exports->GetIsolate();
#ifdef WIN32
HRESULT result;
result = CoInitialize(NULL);
if (FAILED(result))
{
fprintf(stderr, "Initialization of COM failed - result = %08x.\n", result);
}
#endif
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
tpl->SetClassName(String::NewFromUtf8(isolate, "Capture"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
NODE_SET_PROTOTYPE_METHOD(tpl, "init", BMInit);
NODE_SET_PROTOTYPE_METHOD(tpl, "doCapture", DoCapture);
NODE_SET_PROTOTYPE_METHOD(tpl, "stop", StopCapture);
constructor.Reset(isolate, tpl->GetFunction());
exports->Set(String::NewFromUtf8(isolate, "Capture"),
tpl->GetFunction());
}
void Capture::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (args.IsConstructCall()) {
// Invoked as constructor: `new Capture(...)`
double deviceIndex = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
double displayMode = args[1]->IsUndefined() ? 0 : args[1]->NumberValue();
double pixelFormat = args[2]->IsUndefined() ? 0 : args[2]->NumberValue();
Capture* obj = new Capture(deviceIndex, displayMode, pixelFormat);
obj->Wrap(args.This());
args.GetReturnValue().Set(args.This());
} else {
// Invoked as plain function `Capture(...)`, turn into construct call.
const int argc = 3;
Local<Value> argv[argc] = { args[0], args[1], args[2] };
Local<Function> cons = Local<Function>::New(isolate, constructor);
args.GetReturnValue().Set(cons->NewInstance(argc, argv));
}
}
void Capture::BMInit(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
IDeckLinkIterator* deckLinkIterator;
HRESULT result;
IDeckLinkAPIInformation *deckLinkAPIInformation;
IDeckLink* deckLink;
#ifdef WIN32
CoCreateInstance(CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**)&deckLinkIterator);
#else
deckLinkIterator = CreateDeckLinkIteratorInstance();
#endif
result = deckLinkIterator->QueryInterface(IID_IDeckLinkAPIInformation, (void**)&deckLinkAPIInformation);
if (result != S_OK) {
isolate->ThrowException(Exception::Error(
String::NewFromUtf8(isolate, "Error connecting to DeckLinkAPI.")));
}
Capture* obj = ObjectWrap::Unwrap<Capture>(args.Holder());
for ( uint32_t x = 0 ; x <= obj->deviceIndex_ ; x++ ) {
if (deckLinkIterator->Next(&deckLink) != S_OK) {
args.GetReturnValue().Set(Undefined(isolate));
return;
}
}
obj->m_deckLink = deckLink;
IDeckLinkInput *deckLinkInput;
if (deckLink->QueryInterface(IID_IDeckLinkInput, (void **)&deckLinkInput) != S_OK)
{
isolate->ThrowException(Exception::Error(
String::NewFromUtf8(isolate, "Could not obtain the DeckLink Input interface.")));
}
obj->m_deckLinkInput = deckLinkInput;
if (deckLinkInput)
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "made it!"));
else
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "sad :-("));
}
void Capture::DoCapture(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<Function> cb = Local<Function>::Cast(args[0]);
Capture* obj = ObjectWrap::Unwrap<Capture>(args.Holder());
obj->captureCB_.Reset(isolate, cb);
obj->setupDeckLinkInput();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "Capture started."));
}
void Capture::StopCapture(const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
Capture* obj = ObjectWrap::Unwrap<Capture>(args.Holder());
obj->cleanupDeckLinkInput();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "Capture stopped."));
}
// Stop video input
void Capture::cleanupDeckLinkInput()
{
m_deckLinkInput->StopStreams();
m_deckLinkInput->DisableVideoInput();
m_deckLinkInput->SetCallback(NULL);
}
bool Capture::setupDeckLinkInput() {
// bool result = false;
IDeckLinkDisplayModeIterator* displayModeIterator = NULL;
IDeckLinkDisplayMode* deckLinkDisplayMode = NULL;
m_width = -1;
// get frame scale and duration for the video mode
if (m_deckLinkInput->GetDisplayModeIterator(&displayModeIterator) != S_OK)
return false;
while (displayModeIterator->Next(&deckLinkDisplayMode) == S_OK)
{
if (deckLinkDisplayMode->GetDisplayMode() == displayMode_)
{
m_width = deckLinkDisplayMode->GetWidth();
m_height = deckLinkDisplayMode->GetHeight();
deckLinkDisplayMode->GetFrameRate(&m_frameDuration, &m_timeScale);
deckLinkDisplayMode->Release();
break;
}
deckLinkDisplayMode->Release();
}
printf("Width %li Height %li\n", m_width, m_height);
displayModeIterator->Release();
if (m_width == -1)
return false;
m_deckLinkInput->SetCallback(this);
if (m_deckLinkInput->EnableVideoInput((BMDDisplayMode) displayMode_, pixelFormat_, bmdVideoInputFlagDefault) != S_OK)
return false;
if (m_deckLinkInput->StartStreams() != S_OK)
return false;
return true;
}
HRESULT Capture::VideoInputFrameArrived (IDeckLinkVideoInputFrame* arrivedFrame, IDeckLinkAudioInputPacket*)
{
arrivedFrame->AddRef();
latestFrame_ = arrivedFrame;
uv_async_send(async);
return S_OK;
}
HRESULT Capture::VideoInputFormatChanged (BMDVideoInputFormatChangedEvents notificationEvents, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags detectedSignalFlags) {
return S_OK;
};
void Capture::TestUV() {
uv_async_send(async);
}
void FreeCallback(char* data, void* hint) {
Isolate* isolate = v8::Isolate::GetCurrent();
IDeckLinkVideoInputFrame* frame = static_cast<IDeckLinkVideoInputFrame*>(hint);
isolate->AdjustAmountOfExternalAllocatedMemory(-(frame->GetRowBytes() * frame->GetHeight()));
frame->Release();
}
void Capture::FrameCallback(uv_async_t *handle) {
Isolate* isolate = v8::Isolate::GetCurrent();
HandleScope scope(isolate);
Capture *capture = static_cast<Capture*>(handle->data);
Local<Function> cb = Local<Function>::New(isolate, capture->captureCB_);
char* new_data;
capture->latestFrame_->GetBytes((void**) &new_data);
long new_data_size = capture->latestFrame_->GetRowBytes() * capture->latestFrame_->GetHeight();
Local<Object> b = node::Buffer::New(isolate, new_data, new_data_size,
FreeCallback, capture->latestFrame_).ToLocalChecked();
long extSize = isolate->AdjustAmountOfExternalAllocatedMemory(new_data_size);
if (extSize > 100000000) {
isolate->LowMemoryNotification();
printf("Requesting bin collection.\n");
}
Local<Value> argv[1] = { b };
cb->Call(Null(isolate), 1, argv);
}
}
<commit_msg>Adding explict casts for one more enumeration required by Windows compiler.<commit_after>/* Copyright 2016 Streampunk Media Ltd
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.
*/
/* -LICENSE-START-
** Copyright (c) 2010 Blackmagic Design
**
** Permission is hereby granted, free of charge, to any person or organization
** obtaining a copy of the software and accompanying documentation covered by
** this license (the "Software") to use, reproduce, display, distribute,
** execute, and transmit the Software, and to prepare derivative works of the
** Software, and to permit third-parties to whom the Software is furnished to
** do so, all subject to the following:
**
** The copyright notices in the Software and this entire statement, including
** the above license grant, this restriction and the following disclaimer,
** must be included in all copies of the Software, in whole or in part, and
** all derivative works of the Software, unless such copies or derivative
** works are solely in the form of machine-executable object code generated by
** a source language processor.
**
** 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
** DEALINGS IN THE SOFTWARE.
** -LICENSE-END-
*/
#include "Capture.h"
namespace streampunk {
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Value;
using v8::EscapableHandleScope;
using v8::HandleScope;
using v8::Exception;
Persistent<Function> Capture::constructor;
Capture::Capture(uint32_t deviceIndex, uint32_t displayMode,
uint32_t pixelFormat) : deviceIndex_(deviceIndex),
displayMode_(displayMode), pixelFormat_(pixelFormat), latestFrame_(NULL) {
async = new uv_async_t;
uv_async_init(uv_default_loop(), async, FrameCallback);
async->data = this;
}
Capture::~Capture() {
if (!captureCB_.IsEmpty())
captureCB_.Reset();
}
void Capture::Init(Local<Object> exports) {
Isolate* isolate = exports->GetIsolate();
#ifdef WIN32
HRESULT result;
result = CoInitialize(NULL);
if (FAILED(result))
{
fprintf(stderr, "Initialization of COM failed - result = %08x.\n", result);
}
#endif
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
tpl->SetClassName(String::NewFromUtf8(isolate, "Capture"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
NODE_SET_PROTOTYPE_METHOD(tpl, "init", BMInit);
NODE_SET_PROTOTYPE_METHOD(tpl, "doCapture", DoCapture);
NODE_SET_PROTOTYPE_METHOD(tpl, "stop", StopCapture);
constructor.Reset(isolate, tpl->GetFunction());
exports->Set(String::NewFromUtf8(isolate, "Capture"),
tpl->GetFunction());
}
void Capture::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (args.IsConstructCall()) {
// Invoked as constructor: `new Capture(...)`
double deviceIndex = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
double displayMode = args[1]->IsUndefined() ? 0 : args[1]->NumberValue();
double pixelFormat = args[2]->IsUndefined() ? 0 : args[2]->NumberValue();
Capture* obj = new Capture(deviceIndex, displayMode, pixelFormat);
obj->Wrap(args.This());
args.GetReturnValue().Set(args.This());
} else {
// Invoked as plain function `Capture(...)`, turn into construct call.
const int argc = 3;
Local<Value> argv[argc] = { args[0], args[1], args[2] };
Local<Function> cons = Local<Function>::New(isolate, constructor);
args.GetReturnValue().Set(cons->NewInstance(argc, argv));
}
}
void Capture::BMInit(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
IDeckLinkIterator* deckLinkIterator;
HRESULT result;
IDeckLinkAPIInformation *deckLinkAPIInformation;
IDeckLink* deckLink;
#ifdef WIN32
CoCreateInstance(CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, (void**)&deckLinkIterator);
#else
deckLinkIterator = CreateDeckLinkIteratorInstance();
#endif
result = deckLinkIterator->QueryInterface(IID_IDeckLinkAPIInformation, (void**)&deckLinkAPIInformation);
if (result != S_OK) {
isolate->ThrowException(Exception::Error(
String::NewFromUtf8(isolate, "Error connecting to DeckLinkAPI.")));
}
Capture* obj = ObjectWrap::Unwrap<Capture>(args.Holder());
for ( uint32_t x = 0 ; x <= obj->deviceIndex_ ; x++ ) {
if (deckLinkIterator->Next(&deckLink) != S_OK) {
args.GetReturnValue().Set(Undefined(isolate));
return;
}
}
obj->m_deckLink = deckLink;
IDeckLinkInput *deckLinkInput;
if (deckLink->QueryInterface(IID_IDeckLinkInput, (void **)&deckLinkInput) != S_OK)
{
isolate->ThrowException(Exception::Error(
String::NewFromUtf8(isolate, "Could not obtain the DeckLink Input interface.")));
}
obj->m_deckLinkInput = deckLinkInput;
if (deckLinkInput)
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "made it!"));
else
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "sad :-("));
}
void Capture::DoCapture(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<Function> cb = Local<Function>::Cast(args[0]);
Capture* obj = ObjectWrap::Unwrap<Capture>(args.Holder());
obj->captureCB_.Reset(isolate, cb);
obj->setupDeckLinkInput();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "Capture started."));
}
void Capture::StopCapture(const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
Capture* obj = ObjectWrap::Unwrap<Capture>(args.Holder());
obj->cleanupDeckLinkInput();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "Capture stopped."));
}
// Stop video input
void Capture::cleanupDeckLinkInput()
{
m_deckLinkInput->StopStreams();
m_deckLinkInput->DisableVideoInput();
m_deckLinkInput->SetCallback(NULL);
}
bool Capture::setupDeckLinkInput() {
// bool result = false;
IDeckLinkDisplayModeIterator* displayModeIterator = NULL;
IDeckLinkDisplayMode* deckLinkDisplayMode = NULL;
m_width = -1;
// get frame scale and duration for the video mode
if (m_deckLinkInput->GetDisplayModeIterator(&displayModeIterator) != S_OK)
return false;
while (displayModeIterator->Next(&deckLinkDisplayMode) == S_OK)
{
if (deckLinkDisplayMode->GetDisplayMode() == displayMode_)
{
m_width = deckLinkDisplayMode->GetWidth();
m_height = deckLinkDisplayMode->GetHeight();
deckLinkDisplayMode->GetFrameRate(&m_frameDuration, &m_timeScale);
deckLinkDisplayMode->Release();
break;
}
deckLinkDisplayMode->Release();
}
printf("Width %li Height %li\n", m_width, m_height);
displayModeIterator->Release();
if (m_width == -1)
return false;
m_deckLinkInput->SetCallback(this);
if (m_deckLinkInput->EnableVideoInput((BMDDisplayMode) displayMode_, (BMDPixelFormat) pixelFormat_, bmdVideoInputFlagDefault) != S_OK)
return false;
if (m_deckLinkInput->StartStreams() != S_OK)
return false;
return true;
}
HRESULT Capture::VideoInputFrameArrived (IDeckLinkVideoInputFrame* arrivedFrame, IDeckLinkAudioInputPacket*)
{
arrivedFrame->AddRef();
latestFrame_ = arrivedFrame;
uv_async_send(async);
return S_OK;
}
HRESULT Capture::VideoInputFormatChanged (BMDVideoInputFormatChangedEvents notificationEvents, IDeckLinkDisplayMode* newDisplayMode, BMDDetectedVideoInputFormatFlags detectedSignalFlags) {
return S_OK;
};
void Capture::TestUV() {
uv_async_send(async);
}
void FreeCallback(char* data, void* hint) {
Isolate* isolate = v8::Isolate::GetCurrent();
IDeckLinkVideoInputFrame* frame = static_cast<IDeckLinkVideoInputFrame*>(hint);
isolate->AdjustAmountOfExternalAllocatedMemory(-(frame->GetRowBytes() * frame->GetHeight()));
frame->Release();
}
void Capture::FrameCallback(uv_async_t *handle) {
Isolate* isolate = v8::Isolate::GetCurrent();
HandleScope scope(isolate);
Capture *capture = static_cast<Capture*>(handle->data);
Local<Function> cb = Local<Function>::New(isolate, capture->captureCB_);
char* new_data;
capture->latestFrame_->GetBytes((void**) &new_data);
long new_data_size = capture->latestFrame_->GetRowBytes() * capture->latestFrame_->GetHeight();
Local<Object> b = node::Buffer::New(isolate, new_data, new_data_size,
FreeCallback, capture->latestFrame_).ToLocalChecked();
long extSize = isolate->AdjustAmountOfExternalAllocatedMemory(new_data_size);
if (extSize > 100000000) {
isolate->LowMemoryNotification();
printf("Requesting bin collection.\n");
}
Local<Value> argv[1] = { b };
cb->Call(Null(isolate), 1, argv);
}
}
<|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 "chrome/test/test_timeouts.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "chrome/test/test_switches.h"
namespace {
void InitializeTimeout(const char* switch_name, int* value) {
DCHECK(value);
if (CommandLine::ForCurrentProcess()->HasSwitch(switch_name)) {
std::string string_value(
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switch_name));
int timeout;
base::StringToInt(string_value, &timeout);
*value = std::max(*value, timeout);
}
}
} // namespace
// static
bool TestTimeouts::initialized_ = false;
// The timeout values should increase in the order they appear in this block.
// static
int TestTimeouts::action_timeout_ms_ = 2000;
int TestTimeouts::action_max_timeout_ms_ = 15000;
int TestTimeouts::medium_test_timeout_ms_ = 60 * 1000;
int TestTimeouts::large_test_timeout_ms_ = 10 * 60 * 1000;
// static
int TestTimeouts::sleep_timeout_ms_ = 2000;
// static
int TestTimeouts::command_execution_timeout_ms_ = 25000;
// static
int TestTimeouts::wait_for_terminate_timeout_ms_ = 15000;
// static
void TestTimeouts::Initialize() {
if (initialized_) {
NOTREACHED();
return;
}
initialized_ = true;
InitializeTimeout(switches::kUiTestActionTimeout, &action_timeout_ms_);
InitializeTimeout(switches::kUiTestActionMaxTimeout,
&action_max_timeout_ms_);
InitializeTimeout(switches::kMediumTestTimeout, &medium_test_timeout_ms_);
InitializeTimeout(switches::kUiTestTimeout, &large_test_timeout_ms_);
// The timeout values should be increasing in the right order.
CHECK(action_timeout_ms_ <= action_max_timeout_ms_);
CHECK(action_max_timeout_ms_ <= medium_test_timeout_ms_);
CHECK(medium_test_timeout_ms_ <= large_test_timeout_ms_);
InitializeTimeout(switches::kUiTestSleepTimeout, &sleep_timeout_ms_);
InitializeTimeout(switches::kUiTestCommandExecutionTimeout,
&command_execution_timeout_ms_);
InitializeTimeout(switches::kUiTestTerminateTimeout,
&wait_for_terminate_timeout_ms_);
}
<commit_msg>Revert 59421 - GTTF: Increase the timeout for medium tests to one minute.<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 "chrome/test/test_timeouts.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "chrome/test/test_switches.h"
namespace {
void InitializeTimeout(const char* switch_name, int* value) {
DCHECK(value);
if (CommandLine::ForCurrentProcess()->HasSwitch(switch_name)) {
std::string string_value(
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switch_name));
int timeout;
base::StringToInt(string_value, &timeout);
*value = std::max(*value, timeout);
}
}
} // namespace
// static
bool TestTimeouts::initialized_ = false;
// The timeout values should increase in the order they appear in this block.
// static
int TestTimeouts::action_timeout_ms_ = 2000;
int TestTimeouts::action_max_timeout_ms_ = 15000;
int TestTimeouts::medium_test_timeout_ms_ = 30 * 1000;
int TestTimeouts::large_test_timeout_ms_ = 10 * 60 * 1000;
// static
int TestTimeouts::sleep_timeout_ms_ = 2000;
// static
int TestTimeouts::command_execution_timeout_ms_ = 25000;
// static
int TestTimeouts::wait_for_terminate_timeout_ms_ = 15000;
// static
void TestTimeouts::Initialize() {
if (initialized_) {
NOTREACHED();
return;
}
initialized_ = true;
InitializeTimeout(switches::kUiTestActionTimeout, &action_timeout_ms_);
InitializeTimeout(switches::kUiTestActionMaxTimeout,
&action_max_timeout_ms_);
InitializeTimeout(switches::kMediumTestTimeout, &medium_test_timeout_ms_);
InitializeTimeout(switches::kUiTestTimeout, &large_test_timeout_ms_);
// The timeout values should be increasing in the right order.
CHECK(action_timeout_ms_ <= action_max_timeout_ms_);
CHECK(action_max_timeout_ms_ <= medium_test_timeout_ms_);
CHECK(medium_test_timeout_ms_ <= large_test_timeout_ms_);
InitializeTimeout(switches::kUiTestSleepTimeout, &sleep_timeout_ms_);
InitializeTimeout(switches::kUiTestCommandExecutionTimeout,
&command_execution_timeout_ms_);
InitializeTimeout(switches::kUiTestTerminateTimeout,
&wait_for_terminate_timeout_ms_);
}
<|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 <string>
#include "base/file_path.h"
#include "base/waitable_event.h"
#include "chrome_frame/cfproxy_private.h"
#include "chrome/test/automation/automation_messages.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gmock_mutant.h"
using testing::_;
using testing::DoAll;
using testing::NotNull;
using testing::Return;
using testing::StrictMock;
using testing::InvokeWithoutArgs;
using testing::WithoutArgs;
using testing::CreateFunctor;
// There is not much to test here since CFProxy is pretty dumb.
struct MockFactory : public ChromeProxyFactory {
MOCK_METHOD0(CreateProxy, ChromeProxy*());
};
struct MockChromeProxyDelegate : public ChromeProxyDelegate {
MOCK_METHOD1(Connected, void(ChromeProxy* proxy));
MOCK_METHOD2(PeerLost, void(ChromeProxy*, enum DisconnectReason reason));
MOCK_METHOD0(Disconnected, void());
MOCK_METHOD0(tab_handle, int());
MOCK_METHOD4(Completed_CreateTab, void(bool success, HWND chrome_wnd,
HWND tab_window, int tab_handle));
MOCK_METHOD4(Completed_ConnectToTab, void(bool success, HWND chrome_window,
HWND tab_window, int tab_handle));
MOCK_METHOD2(Completed_Navigate, void(bool success,
enum AutomationMsg_NavigationResponseValues res));
MOCK_METHOD3(Completed_InstallExtension, void(bool success,
enum AutomationMsg_ExtensionResponseValues res, SyncMessageContext* ctx));
MOCK_METHOD3(Completed_LoadExpandedExtension, void(bool success,
enum AutomationMsg_ExtensionResponseValues res, SyncMessageContext* ctx));
MOCK_METHOD2(Completed_GetEnabledExtensions, void(bool success,
const std::vector<FilePath>* v));
// Network requests from Chrome.
MOCK_METHOD2(Network_Start, void(int request_id,
const IPC::AutomationURLRequest& request_info));
MOCK_METHOD2(Network_Read, void(int request_id, int bytes_to_read));
MOCK_METHOD2(Network_End, void(int request_id, const URLRequestStatus& s));
MOCK_METHOD1(Network_DownloadInHost, void(int request_id));
MOCK_METHOD2(GetCookies, void(const GURL& url, int cookie_id));
MOCK_METHOD2(SetCookie, void(const GURL& url, const std::string& cookie));
// Navigation progress notifications.
MOCK_METHOD2(NavigationStateChanged, void(int flags,
const IPC::NavigationInfo& nav_info));
MOCK_METHOD1(UpdateTargetUrl, void(const std::wstring& url));
MOCK_METHOD2(NavigationFailed, void(int error_code, const GURL& gurl));
MOCK_METHOD1(DidNavigate, void(const IPC::NavigationInfo& navigation_info));
MOCK_METHOD1(TabLoaded, void(const GURL& url));
//
MOCK_METHOD3(OpenURL, void(const GURL& url_to_open, const GURL& referrer,
int open_disposition));
MOCK_METHOD1(GoToHistoryOffset, void(int offset));
MOCK_METHOD3(MessageToHost, void(const std::string& message,
const std::string& origin, const std::string& target));
// Misc. UI.
MOCK_METHOD1(HandleAccelerator, void(const MSG& accel_message));
MOCK_METHOD1(TabbedOut, void(bool reverse));
//
MOCK_METHOD0(TabClosed, void());
MOCK_METHOD1(AttachTab,
void(const IPC::AttachExternalTabParams& attach_params));
};
struct MockSender : public IPC::Message::Sender {
MOCK_METHOD1(Send, bool(IPC::Message* m));
};
struct MockCFProxyTraits : public CFProxyTraits {
MOCK_METHOD2(DoCreateChannel, IPC::Message::Sender*(const std::string& id,
IPC::Channel::Listener* l));
MOCK_METHOD1(CloseChannel, void(IPC::Message::Sender* s));
MOCK_METHOD1(LaunchApp, bool(const std::wstring& cmd_line));
// Forward the CreateChannel to DoCreateChannel, but save the ipc_thread
// and the listener (i.e. proxy implementation of Channel::Listener)
virtual IPC::Message::Sender* CreateChannel(const std::string& id,
IPC::Channel::Listener* l) {
ipc_loop = MessageLoop::current();
listener = l;
return this->DoCreateChannel(id, l);
}
// Simulate some activity in the IPC thread.
// You may find API_FIRE_XXXX macros (see below) handy instead.
void FireConnect(base::TimeDelta t) {
ASSERT_TRUE(ipc_loop != NULL);
ipc_loop->PostDelayedTask(FROM_HERE, NewRunnableMethod(listener,
&IPC::Channel::Listener::OnChannelConnected, 0), t.InMilliseconds());
}
void FireError(base::TimeDelta t) {
ASSERT_TRUE(ipc_loop != NULL);
ipc_loop->PostDelayedTask(FROM_HERE, NewRunnableMethod(listener,
&IPC::Channel::Listener::OnChannelError), t.InMilliseconds());
}
void FireMessage(const IPC::Message& m, base::TimeDelta t) {
ASSERT_TRUE(ipc_loop != NULL);
ipc_loop->PostDelayedTask(FROM_HERE, NewRunnableMethod(listener,
&IPC::Channel::Listener::OnMessageReceived, m), t.InMilliseconds());
}
MockCFProxyTraits() : ipc_loop(NULL) {}
MockSender sender;
private:
MessageLoop* ipc_loop;
IPC::Channel::Listener* listener;
};
// Handy macros when we want so similate something on the IPC thread.
#define API_FIRE_CONNECT(api, t) InvokeWithoutArgs(CreateFunctor(&api, \
&MockCFProxyTraits::FireConnect, t))
#define API_FIRE_ERROR(api, t) InvokeWithoutArgs(CreateFunctor(&api, \
&MockCFProxyTraits::FireError, t))
#define API_FIRE_MESSAGE(api, t) InvokeWithoutArgs(CreateFunctor(&api, \
&MockCFProxyTraits::FireMessage, t))
DISABLE_RUNNABLE_METHOD_REFCOUNT(IPC::Channel::Listener);
TEST(ChromeProxy, DelegateAddRemove) {
StrictMock<MockCFProxyTraits> api;
StrictMock<MockChromeProxyDelegate> delegate;
StrictMock<MockFactory> factory; // to be destroyed before other mocks
CFProxy* proxy = new CFProxy(&api);
EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));
EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));
EXPECT_CALL(api, LaunchApp(_)).WillOnce(Return(true));
EXPECT_CALL(api, CloseChannel(&api.sender));
EXPECT_CALL(delegate, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(delegate, Disconnected());
ProxyParams params;
params.profile = "Adam N. Epilinter";
params.timeout = base::TimeDelta::FromSeconds(4);
factory.GetProxy(&delegate, params);
factory.ReleaseProxy(&delegate, params.profile);
}
// Not very useful test. Just for illustration. :)
TEST(ChromeProxy, SharedProxy) {
base::WaitableEvent done1(false, false);
base::WaitableEvent done2(false, false);
StrictMock<MockCFProxyTraits> api;
StrictMock<MockChromeProxyDelegate> delegate1;
StrictMock<MockChromeProxyDelegate> delegate2;
StrictMock<MockFactory> factory;
CFProxy* proxy = new CFProxy(&api);
EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));
EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));
EXPECT_CALL(api, LaunchApp(_)).WillOnce(DoAll(
API_FIRE_CONNECT(api, base::TimeDelta::FromMilliseconds(150)),
Return(true)));
EXPECT_CALL(api, CloseChannel(&api.sender));
EXPECT_CALL(delegate1, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(delegate2, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(delegate1, Connected(proxy))
.WillOnce(InvokeWithoutArgs(&done1, &base::WaitableEvent::Signal));
EXPECT_CALL(delegate2, Connected(proxy))
.WillOnce(InvokeWithoutArgs(&done2, &base::WaitableEvent::Signal));
ProxyParams params;
params.profile = "Adam N. Epilinter";
params.timeout = base::TimeDelta::FromSeconds(4);
factory.GetProxy(&delegate1, params);
params.timeout = base::TimeDelta::FromSeconds(2);
factory.GetProxy(&delegate2, params);
EXPECT_TRUE(done1.TimedWait(base::TimeDelta::FromSeconds(1)));
EXPECT_TRUE(done2.TimedWait(base::TimeDelta::FromSeconds(1)));
EXPECT_CALL(delegate2, Disconnected());
EXPECT_CALL(delegate1, Disconnected());
factory.ReleaseProxy(&delegate2, params.profile);
factory.ReleaseProxy(&delegate1, params.profile);
}
TEST(ChromeProxy, LaunchTimeout) {
base::WaitableEvent done(true, false);
StrictMock<MockFactory> factory;
StrictMock<MockCFProxyTraits> api;
StrictMock<MockChromeProxyDelegate> delegate;
CFProxy* proxy = new CFProxy(&api);
EXPECT_CALL(delegate, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));
EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));
EXPECT_CALL(api, LaunchApp(_)).WillOnce(Return(true));
EXPECT_CALL(api, CloseChannel(&api.sender));
EXPECT_CALL(delegate, PeerLost(_,
ChromeProxyDelegate::CHROME_EXE_LAUNCH_TIMEOUT))
.WillOnce(InvokeWithoutArgs(&done, &base::WaitableEvent::Signal));
ProxyParams params;
params.profile = "Adam N. Epilinter";
params.timeout = base::TimeDelta::FromMilliseconds(300);
factory.GetProxy(&delegate, params);
EXPECT_TRUE(done.TimedWait(base::TimeDelta::FromSeconds(1)));
EXPECT_CALL(delegate, Disconnected());
factory.ReleaseProxy(&delegate, params.profile);
}
TEST(ChromeProxy, LaunchChrome) {
base::WaitableEvent connected(false, false);
StrictMock<MockChromeProxyDelegate> delegate;
ChromeProxyFactory factory;
ProxyParams params;
params.profile = "Adam N. Epilinter";
params.timeout = base::TimeDelta::FromSeconds(10);
EXPECT_CALL(delegate, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(delegate, Connected(NotNull()))
.WillOnce(InvokeWithoutArgs(&connected, &base::WaitableEvent::Signal));
factory.GetProxy(&delegate, params);
EXPECT_TRUE(connected.TimedWait(base::TimeDelta::FromSeconds(15)));
EXPECT_CALL(delegate, Disconnected());
factory.ReleaseProxy(&delegate, params.profile);
}
///////////////////////////////////////////////////////////////////////////////
namespace {
template <typename M, typename A>
inline IPC::Message* CreateReply(M* m, const A& a) {
IPC::Message* r = IPC::SyncMessage::GenerateReply(m);
if (r) {
M::WriteReplyParams(r, a);
}
return r;
}
template <typename M, typename A, typename B>
inline IPC::Message* CreateReply(M* m, const A& a, const B& b) {
IPC::Message* r = IPC::SyncMessage::GenerateReply(m);
if (r) {
M::WriteReplyParams(r, a, b);
}
return r;
}
template <typename M, typename A, typename B, typename C>
inline IPC::Message* CreateReply(M* m, const A& a, const B& b, const C& c) {
IPC::Message* r = IPC::SyncMessage::GenerateReply(m);
if (r) {
M::WriteReplyParams(r, a, b, c);
}
return r;
}
} // namespace
DISABLE_RUNNABLE_METHOD_REFCOUNT(SyncMsgSender);
TEST(SyncMsgSender, Deserialize) {
// Note the ipc thread is not actually needed, but we try to be close
// to real-world conditions - that SyncMsgSender works from multiple threads.
base::Thread ipc("ipc");
ipc.StartWithOptions(base::Thread::Options(MessageLoop::TYPE_IO, 0));
StrictMock<MockChromeProxyDelegate> d1;
TabsMap tab2delegate;
SyncMsgSender queue(&tab2delegate);
// Create some sync messages and their replies.
AutomationMsg_InstallExtension m1(0, FilePath(L"c:\\awesome.x"), 0);
AutomationMsg_CreateExternalTab m2(0, IPC::ExternalTabSettings(), 0, 0, 0);
scoped_ptr<IPC::Message> r1(CreateReply(&m1,
AUTOMATION_MSG_EXTENSION_INSTALL_SUCCEEDED));
scoped_ptr<IPC::Message> r2(CreateReply(&m2, (HWND)1, (HWND)2, 6));
queue.QueueSyncMessage(&m1, &d1, NULL);
queue.QueueSyncMessage(&m2, &d1, NULL);
testing::InSequence s;
EXPECT_CALL(d1, Completed_InstallExtension(true,
AUTOMATION_MSG_EXTENSION_INSTALL_SUCCEEDED, NULL));
EXPECT_CALL(d1, Completed_CreateTab(true, (HWND)1, (HWND)2, 6));
// Execute replies in a worker thread.
ipc.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(&queue,
&SyncMsgSender::OnReplyReceived, r1.get()));
ipc.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(&queue,
&SyncMsgSender::OnReplyReceived, r2.get()));
ipc.Stop();
// Expect that tab 6 has been associated with the delegate.
EXPECT_EQ(&d1, tab2delegate[6]);
}
TEST(SyncMsgSender, OnChannelClosed) {
// TODO(stoyan): implement.
}
<commit_msg>Fix the ChromeFrame Launch timeout test - mock destruction order. TBR=amit Review URL: http://codereview.chromium.org/3588010<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 <string>
#include "base/file_path.h"
#include "base/waitable_event.h"
#include "chrome_frame/cfproxy_private.h"
#include "chrome/test/automation/automation_messages.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gmock_mutant.h"
using testing::_;
using testing::DoAll;
using testing::NotNull;
using testing::Return;
using testing::StrictMock;
using testing::InvokeWithoutArgs;
using testing::WithoutArgs;
using testing::CreateFunctor;
// There is not much to test here since CFProxy is pretty dumb.
struct MockFactory : public ChromeProxyFactory {
MOCK_METHOD0(CreateProxy, ChromeProxy*());
};
struct MockChromeProxyDelegate : public ChromeProxyDelegate {
MOCK_METHOD1(Connected, void(ChromeProxy* proxy));
MOCK_METHOD2(PeerLost, void(ChromeProxy*, enum DisconnectReason reason));
MOCK_METHOD0(Disconnected, void());
MOCK_METHOD0(tab_handle, int());
MOCK_METHOD4(Completed_CreateTab, void(bool success, HWND chrome_wnd,
HWND tab_window, int tab_handle));
MOCK_METHOD4(Completed_ConnectToTab, void(bool success, HWND chrome_window,
HWND tab_window, int tab_handle));
MOCK_METHOD2(Completed_Navigate, void(bool success,
enum AutomationMsg_NavigationResponseValues res));
MOCK_METHOD3(Completed_InstallExtension, void(bool success,
enum AutomationMsg_ExtensionResponseValues res, SyncMessageContext* ctx));
MOCK_METHOD3(Completed_LoadExpandedExtension, void(bool success,
enum AutomationMsg_ExtensionResponseValues res, SyncMessageContext* ctx));
MOCK_METHOD2(Completed_GetEnabledExtensions, void(bool success,
const std::vector<FilePath>* v));
// Network requests from Chrome.
MOCK_METHOD2(Network_Start, void(int request_id,
const IPC::AutomationURLRequest& request_info));
MOCK_METHOD2(Network_Read, void(int request_id, int bytes_to_read));
MOCK_METHOD2(Network_End, void(int request_id, const URLRequestStatus& s));
MOCK_METHOD1(Network_DownloadInHost, void(int request_id));
MOCK_METHOD2(GetCookies, void(const GURL& url, int cookie_id));
MOCK_METHOD2(SetCookie, void(const GURL& url, const std::string& cookie));
// Navigation progress notifications.
MOCK_METHOD2(NavigationStateChanged, void(int flags,
const IPC::NavigationInfo& nav_info));
MOCK_METHOD1(UpdateTargetUrl, void(const std::wstring& url));
MOCK_METHOD2(NavigationFailed, void(int error_code, const GURL& gurl));
MOCK_METHOD1(DidNavigate, void(const IPC::NavigationInfo& navigation_info));
MOCK_METHOD1(TabLoaded, void(const GURL& url));
//
MOCK_METHOD3(OpenURL, void(const GURL& url_to_open, const GURL& referrer,
int open_disposition));
MOCK_METHOD1(GoToHistoryOffset, void(int offset));
MOCK_METHOD3(MessageToHost, void(const std::string& message,
const std::string& origin, const std::string& target));
// Misc. UI.
MOCK_METHOD1(HandleAccelerator, void(const MSG& accel_message));
MOCK_METHOD1(TabbedOut, void(bool reverse));
//
MOCK_METHOD0(TabClosed, void());
MOCK_METHOD1(AttachTab,
void(const IPC::AttachExternalTabParams& attach_params));
};
struct MockSender : public IPC::Message::Sender {
MOCK_METHOD1(Send, bool(IPC::Message* m));
};
struct MockCFProxyTraits : public CFProxyTraits {
MOCK_METHOD2(DoCreateChannel, IPC::Message::Sender*(const std::string& id,
IPC::Channel::Listener* l));
MOCK_METHOD1(CloseChannel, void(IPC::Message::Sender* s));
MOCK_METHOD1(LaunchApp, bool(const std::wstring& cmd_line));
// Forward the CreateChannel to DoCreateChannel, but save the ipc_thread
// and the listener (i.e. proxy implementation of Channel::Listener)
virtual IPC::Message::Sender* CreateChannel(const std::string& id,
IPC::Channel::Listener* l) {
ipc_loop = MessageLoop::current();
listener = l;
return this->DoCreateChannel(id, l);
}
// Simulate some activity in the IPC thread.
// You may find API_FIRE_XXXX macros (see below) handy instead.
void FireConnect(base::TimeDelta t) {
ASSERT_TRUE(ipc_loop != NULL);
ipc_loop->PostDelayedTask(FROM_HERE, NewRunnableMethod(listener,
&IPC::Channel::Listener::OnChannelConnected, 0), t.InMilliseconds());
}
void FireError(base::TimeDelta t) {
ASSERT_TRUE(ipc_loop != NULL);
ipc_loop->PostDelayedTask(FROM_HERE, NewRunnableMethod(listener,
&IPC::Channel::Listener::OnChannelError), t.InMilliseconds());
}
void FireMessage(const IPC::Message& m, base::TimeDelta t) {
ASSERT_TRUE(ipc_loop != NULL);
ipc_loop->PostDelayedTask(FROM_HERE, NewRunnableMethod(listener,
&IPC::Channel::Listener::OnMessageReceived, m), t.InMilliseconds());
}
MockCFProxyTraits() : ipc_loop(NULL) {}
MockSender sender;
private:
MessageLoop* ipc_loop;
IPC::Channel::Listener* listener;
};
// Handy macros when we want so similate something on the IPC thread.
#define API_FIRE_CONNECT(api, t) InvokeWithoutArgs(CreateFunctor(&api, \
&MockCFProxyTraits::FireConnect, t))
#define API_FIRE_ERROR(api, t) InvokeWithoutArgs(CreateFunctor(&api, \
&MockCFProxyTraits::FireError, t))
#define API_FIRE_MESSAGE(api, t) InvokeWithoutArgs(CreateFunctor(&api, \
&MockCFProxyTraits::FireMessage, t))
DISABLE_RUNNABLE_METHOD_REFCOUNT(IPC::Channel::Listener);
TEST(ChromeProxy, DelegateAddRemove) {
StrictMock<MockCFProxyTraits> api;
StrictMock<MockChromeProxyDelegate> delegate;
StrictMock<MockFactory> factory; // to be destroyed before other mocks
CFProxy* proxy = new CFProxy(&api);
EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));
EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));
EXPECT_CALL(api, LaunchApp(_)).WillOnce(Return(true));
EXPECT_CALL(api, CloseChannel(&api.sender));
EXPECT_CALL(delegate, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(delegate, Disconnected());
ProxyParams params;
params.profile = "Adam N. Epilinter";
params.timeout = base::TimeDelta::FromSeconds(4);
factory.GetProxy(&delegate, params);
factory.ReleaseProxy(&delegate, params.profile);
}
// Not very useful test. Just for illustration. :)
TEST(ChromeProxy, SharedProxy) {
base::WaitableEvent done1(false, false);
base::WaitableEvent done2(false, false);
StrictMock<MockCFProxyTraits> api;
StrictMock<MockChromeProxyDelegate> delegate1;
StrictMock<MockChromeProxyDelegate> delegate2;
StrictMock<MockFactory> factory;
CFProxy* proxy = new CFProxy(&api);
EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));
EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));
EXPECT_CALL(api, LaunchApp(_)).WillOnce(DoAll(
API_FIRE_CONNECT(api, base::TimeDelta::FromMilliseconds(150)),
Return(true)));
EXPECT_CALL(api, CloseChannel(&api.sender));
EXPECT_CALL(delegate1, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(delegate2, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(delegate1, Connected(proxy))
.WillOnce(InvokeWithoutArgs(&done1, &base::WaitableEvent::Signal));
EXPECT_CALL(delegate2, Connected(proxy))
.WillOnce(InvokeWithoutArgs(&done2, &base::WaitableEvent::Signal));
ProxyParams params;
params.profile = "Adam N. Epilinter";
params.timeout = base::TimeDelta::FromSeconds(4);
factory.GetProxy(&delegate1, params);
params.timeout = base::TimeDelta::FromSeconds(2);
factory.GetProxy(&delegate2, params);
EXPECT_TRUE(done1.TimedWait(base::TimeDelta::FromSeconds(1)));
EXPECT_TRUE(done2.TimedWait(base::TimeDelta::FromSeconds(1)));
EXPECT_CALL(delegate2, Disconnected());
EXPECT_CALL(delegate1, Disconnected());
factory.ReleaseProxy(&delegate2, params.profile);
factory.ReleaseProxy(&delegate1, params.profile);
}
TEST(ChromeProxy, LaunchTimeout) {
base::WaitableEvent done(true, false);
StrictMock<MockCFProxyTraits> api;
StrictMock<MockChromeProxyDelegate> delegate;
StrictMock<MockFactory> factory;
CFProxy* proxy = new CFProxy(&api);
EXPECT_CALL(delegate, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));
EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));
EXPECT_CALL(api, LaunchApp(_)).WillOnce(Return(true));
EXPECT_CALL(api, CloseChannel(&api.sender));
EXPECT_CALL(delegate, PeerLost(_,
ChromeProxyDelegate::CHROME_EXE_LAUNCH_TIMEOUT))
.WillOnce(InvokeWithoutArgs(&done, &base::WaitableEvent::Signal));
ProxyParams params;
params.profile = "Adam N. Epilinter";
params.timeout = base::TimeDelta::FromMilliseconds(300);
factory.GetProxy(&delegate, params);
EXPECT_TRUE(done.TimedWait(base::TimeDelta::FromSeconds(1)));
EXPECT_CALL(delegate, Disconnected());
factory.ReleaseProxy(&delegate, params.profile);
}
TEST(ChromeProxy, LaunchChrome) {
base::WaitableEvent connected(false, false);
StrictMock<MockChromeProxyDelegate> delegate;
ChromeProxyFactory factory;
ProxyParams params;
params.profile = "Adam N. Epilinter";
params.timeout = base::TimeDelta::FromSeconds(10);
EXPECT_CALL(delegate, tab_handle()).WillRepeatedly(Return(0));
EXPECT_CALL(delegate, Connected(NotNull()))
.WillOnce(InvokeWithoutArgs(&connected, &base::WaitableEvent::Signal));
factory.GetProxy(&delegate, params);
EXPECT_TRUE(connected.TimedWait(base::TimeDelta::FromSeconds(15)));
EXPECT_CALL(delegate, Disconnected());
factory.ReleaseProxy(&delegate, params.profile);
}
///////////////////////////////////////////////////////////////////////////////
namespace {
template <typename M, typename A>
inline IPC::Message* CreateReply(M* m, const A& a) {
IPC::Message* r = IPC::SyncMessage::GenerateReply(m);
if (r) {
M::WriteReplyParams(r, a);
}
return r;
}
template <typename M, typename A, typename B>
inline IPC::Message* CreateReply(M* m, const A& a, const B& b) {
IPC::Message* r = IPC::SyncMessage::GenerateReply(m);
if (r) {
M::WriteReplyParams(r, a, b);
}
return r;
}
template <typename M, typename A, typename B, typename C>
inline IPC::Message* CreateReply(M* m, const A& a, const B& b, const C& c) {
IPC::Message* r = IPC::SyncMessage::GenerateReply(m);
if (r) {
M::WriteReplyParams(r, a, b, c);
}
return r;
}
} // namespace
DISABLE_RUNNABLE_METHOD_REFCOUNT(SyncMsgSender);
TEST(SyncMsgSender, Deserialize) {
// Note the ipc thread is not actually needed, but we try to be close
// to real-world conditions - that SyncMsgSender works from multiple threads.
base::Thread ipc("ipc");
ipc.StartWithOptions(base::Thread::Options(MessageLoop::TYPE_IO, 0));
StrictMock<MockChromeProxyDelegate> d1;
TabsMap tab2delegate;
SyncMsgSender queue(&tab2delegate);
// Create some sync messages and their replies.
AutomationMsg_InstallExtension m1(0, FilePath(L"c:\\awesome.x"), 0);
AutomationMsg_CreateExternalTab m2(0, IPC::ExternalTabSettings(), 0, 0, 0);
scoped_ptr<IPC::Message> r1(CreateReply(&m1,
AUTOMATION_MSG_EXTENSION_INSTALL_SUCCEEDED));
scoped_ptr<IPC::Message> r2(CreateReply(&m2, (HWND)1, (HWND)2, 6));
queue.QueueSyncMessage(&m1, &d1, NULL);
queue.QueueSyncMessage(&m2, &d1, NULL);
testing::InSequence s;
EXPECT_CALL(d1, Completed_InstallExtension(true,
AUTOMATION_MSG_EXTENSION_INSTALL_SUCCEEDED, NULL));
EXPECT_CALL(d1, Completed_CreateTab(true, (HWND)1, (HWND)2, 6));
// Execute replies in a worker thread.
ipc.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(&queue,
&SyncMsgSender::OnReplyReceived, r1.get()));
ipc.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(&queue,
&SyncMsgSender::OnReplyReceived, r2.get()));
ipc.Stop();
// Expect that tab 6 has been associated with the delegate.
EXPECT_EQ(&d1, tab2delegate[6]);
}
TEST(SyncMsgSender, OnChannelClosed) {
// TODO(stoyan): implement.
}
<|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 "chrome_frame/module_utils.h"
#include <aclapi.h>
#include <atlbase.h>
#include <atlsecurity.h>
#include <sddl.h>
#include "base/file_path.h"
#include "base/file_version_info.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/shared_memory.h"
#include "base/sys_info.h"
#include "base/utf_string_conversions.h"
#include "base/version.h"
#include "chrome_frame/utils.h"
const wchar_t kSharedMemoryName[] = L"ChromeFrameVersionBeacon_";
const uint32 kSharedMemorySize = 128;
const uint32 kSharedMemoryLockTimeoutMs = 1000;
// static
DllRedirector::DllRedirector() : first_module_handle_(NULL) {
// TODO(robertshield): Allow for overrides to be taken from the environment.
std::wstring beacon_name(kSharedMemoryName);
beacon_name += GetHostProcessName(false);
shared_memory_.reset(new base::SharedMemory(beacon_name));
}
DllRedirector::DllRedirector(const char* shared_memory_name)
: shared_memory_name_(shared_memory_name), first_module_handle_(NULL) {
shared_memory_.reset(new base::SharedMemory(ASCIIToWide(shared_memory_name)));
}
DllRedirector::~DllRedirector() {
if (first_module_handle_) {
if (first_module_handle_ != reinterpret_cast<HMODULE>(&__ImageBase)) {
FreeLibrary(first_module_handle_);
}
first_module_handle_ = NULL;
}
UnregisterAsFirstCFModule();
}
bool DllRedirector::BuildSecurityAttributesForLock(
CSecurityAttributes* sec_attr) {
DCHECK(sec_attr);
int32 major_version, minor_version, fix_version;
base::SysInfo::OperatingSystemVersionNumbers(&major_version,
&minor_version,
&fix_version);
if (major_version < 6) {
// Don't bother with changing ACLs on pre-vista.
return false;
}
bool success = false;
// Fill out the rest of the security descriptor from the process token.
CAccessToken token;
if (token.GetProcessToken(TOKEN_QUERY)) {
CSecurityDesc security_desc;
// Set the SACL from an SDDL string that allows access to low-integrity
// processes. See http://msdn.microsoft.com/en-us/library/bb625958.aspx.
if (security_desc.FromString(L"S:(ML;;NW;;;LW)")) {
CSid sid_owner;
if (token.GetOwner(&sid_owner)) {
security_desc.SetOwner(sid_owner);
} else {
NOTREACHED() << "Could not get owner.";
}
CSid sid_group;
if (token.GetPrimaryGroup(&sid_group)) {
security_desc.SetGroup(sid_group);
} else {
NOTREACHED() << "Could not get group.";
}
CDacl dacl;
if (token.GetDefaultDacl(&dacl)) {
// Add an access control entry mask for the current user.
// This is what grants this user access from lower integrity levels.
CSid sid_user;
if (token.GetUser(&sid_user)) {
success = dacl.AddAllowedAce(sid_user, MUTEX_ALL_ACCESS);
security_desc.SetDacl(dacl);
sec_attr->Set(security_desc);
}
}
}
}
return success;
}
bool DllRedirector::SetFileMappingToReadOnly(base::SharedMemoryHandle mapping) {
bool success = false;
CAccessToken token;
if (token.GetProcessToken(TOKEN_QUERY)) {
CSid sid_user;
if (token.GetUser(&sid_user)) {
CDacl dacl;
dacl.AddAllowedAce(sid_user, STANDARD_RIGHTS_READ | FILE_MAP_READ);
success = AtlSetDacl(mapping, SE_KERNEL_OBJECT, dacl);
}
}
return success;
}
bool DllRedirector::RegisterAsFirstCFModule() {
DCHECK(first_module_handle_ == NULL);
// Build our own file version outside of the lock:
scoped_ptr<Version> our_version(GetCurrentModuleVersion());
// We sadly can't use the autolock here since we want to have a timeout.
// Be careful not to return while holding the lock. Also, attempt to do as
// little as possible while under this lock.
bool lock_acquired = false;
CSecurityAttributes sec_attr;
if (BuildSecurityAttributesForLock(&sec_attr)) {
lock_acquired = shared_memory_->Lock(kSharedMemoryLockTimeoutMs, &sec_attr);
} else {
lock_acquired = shared_memory_->Lock(kSharedMemoryLockTimeoutMs, NULL);
}
if (!lock_acquired) {
// We couldn't get the lock in a reasonable amount of time, so fall
// back to loading our current version. We return true to indicate that the
// caller should not attempt to delegate to an already loaded version.
dll_version_.swap(our_version);
first_module_handle_ = reinterpret_cast<HMODULE>(&__ImageBase);
return true;
}
bool created_beacon = true;
bool result = shared_memory_->CreateNamed(shared_memory_name_.c_str(),
false, // open_existing
kSharedMemorySize);
if (result) {
// We created the beacon, now we need to mutate the security attributes
// on the shared memory to allow read-only access and let low-integrity
// processes open it.
bool acls_set = SetFileMappingToReadOnly(shared_memory_->handle());
DCHECK(acls_set);
} else {
created_beacon = false;
// We failed to create the shared memory segment, suggesting it may already
// exist: try to create it read-only.
result = shared_memory_->Open(shared_memory_name_.c_str(),
true /* read_only */);
}
if (result) {
// Map in the whole thing.
result = shared_memory_->Map(0);
DCHECK(shared_memory_->memory());
if (result) {
// Either write our own version number or read it in if it was already
// present in the shared memory section.
if (created_beacon) {
dll_version_.swap(our_version);
lstrcpynA(reinterpret_cast<char*>(shared_memory_->memory()),
dll_version_->GetString().c_str(),
std::min(kSharedMemorySize,
dll_version_->GetString().length() + 1));
// Mark ourself as the first module in.
first_module_handle_ = reinterpret_cast<HMODULE>(&__ImageBase);
} else {
char buffer[kSharedMemorySize] = {0};
memcpy(buffer, shared_memory_->memory(), kSharedMemorySize - 1);
dll_version_.reset(Version::GetVersionFromString(buffer));
if (!dll_version_.get() || dll_version_->Equals(*our_version.get())) {
// If we either couldn't parse a valid version out of the shared
// memory or we did parse a version and it is the same as our own,
// then pretend we're first in to avoid trying to load any other DLLs.
dll_version_.reset(our_version.release());
first_module_handle_ = reinterpret_cast<HMODULE>(&__ImageBase);
created_beacon = true;
}
}
} else {
NOTREACHED() << "Failed to map in version beacon.";
}
} else {
NOTREACHED() << "Could not create file mapping for version beacon, gle: "
<< ::GetLastError();
}
// Matching Unlock.
shared_memory_->Unlock();
return created_beacon;
}
void DllRedirector::UnregisterAsFirstCFModule() {
if (base::SharedMemory::IsHandleValid(shared_memory_->handle())) {
bool lock_acquired = shared_memory_->Lock(kSharedMemoryLockTimeoutMs, NULL);
if (lock_acquired) {
// Free our handles. The last closed handle SHOULD result in it being
// deleted.
shared_memory_->Close();
shared_memory_->Unlock();
}
}
}
LPFNGETCLASSOBJECT DllRedirector::GetDllGetClassObjectPtr() {
HMODULE first_module_handle = GetFirstModule();
LPFNGETCLASSOBJECT proc_ptr = reinterpret_cast<LPFNGETCLASSOBJECT>(
GetProcAddress(first_module_handle, "DllGetClassObject"));
if (!proc_ptr) {
DPLOG(ERROR) << "DllRedirector: Could not get address of DllGetClassObject "
"from first loaded module.";
// Oh boink, the first module we loaded was somehow bogus, make ourselves
// the first module again.
first_module_handle = reinterpret_cast<HMODULE>(&__ImageBase);
}
return proc_ptr;
}
Version* DllRedirector::GetCurrentModuleVersion() {
scoped_ptr<FileVersionInfo> file_version_info(
FileVersionInfo::CreateFileVersionInfoForCurrentModule());
DCHECK(file_version_info.get());
Version* current_version = NULL;
if (file_version_info.get()) {
current_version = Version::GetVersionFromString(
file_version_info->file_version());
DCHECK(current_version);
}
return current_version;
}
HMODULE DllRedirector::GetFirstModule() {
DCHECK(dll_version_.get())
<< "Error: Did you call RegisterAsFirstCFModule() first?";
if (first_module_handle_ == NULL) {
first_module_handle_ = LoadVersionedModule(dll_version_.get());
if (!first_module_handle_) {
first_module_handle_ = reinterpret_cast<HMODULE>(&__ImageBase);
}
}
return first_module_handle_;
}
HMODULE DllRedirector::LoadVersionedModule(Version* version) {
DCHECK(version);
FilePath module_path;
PathService::Get(base::DIR_MODULE, &module_path);
DCHECK(!module_path.empty());
FilePath module_name = module_path.BaseName();
module_path = module_path.DirName()
.Append(ASCIIToWide(version->GetString()))
.Append(module_name);
HMODULE hmodule = LoadLibrary(module_path.value().c_str());
if (hmodule == NULL) {
DPLOG(ERROR) << "Could not load reported module version "
<< version->GetString();
}
return hmodule;
}
<commit_msg>Remove a DCHECK when failing to secure the shared memory used to hold the current version. This may well fail on older (read non-NTFS) systems since you can't secure file mappings without a securable file system underneath.<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 "chrome_frame/module_utils.h"
#include <aclapi.h>
#include <atlbase.h>
#include <atlsecurity.h>
#include <sddl.h>
#include "base/file_path.h"
#include "base/file_version_info.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/shared_memory.h"
#include "base/sys_info.h"
#include "base/utf_string_conversions.h"
#include "base/version.h"
#include "chrome_frame/utils.h"
const wchar_t kSharedMemoryName[] = L"ChromeFrameVersionBeacon_";
const uint32 kSharedMemorySize = 128;
const uint32 kSharedMemoryLockTimeoutMs = 1000;
// static
DllRedirector::DllRedirector() : first_module_handle_(NULL) {
// TODO(robertshield): Allow for overrides to be taken from the environment.
std::wstring beacon_name(kSharedMemoryName);
beacon_name += GetHostProcessName(false);
shared_memory_.reset(new base::SharedMemory(beacon_name));
}
DllRedirector::DllRedirector(const char* shared_memory_name)
: shared_memory_name_(shared_memory_name), first_module_handle_(NULL) {
shared_memory_.reset(new base::SharedMemory(ASCIIToWide(shared_memory_name)));
}
DllRedirector::~DllRedirector() {
if (first_module_handle_) {
if (first_module_handle_ != reinterpret_cast<HMODULE>(&__ImageBase)) {
FreeLibrary(first_module_handle_);
}
first_module_handle_ = NULL;
}
UnregisterAsFirstCFModule();
}
bool DllRedirector::BuildSecurityAttributesForLock(
CSecurityAttributes* sec_attr) {
DCHECK(sec_attr);
int32 major_version, minor_version, fix_version;
base::SysInfo::OperatingSystemVersionNumbers(&major_version,
&minor_version,
&fix_version);
if (major_version < 6) {
// Don't bother with changing ACLs on pre-vista.
return false;
}
bool success = false;
// Fill out the rest of the security descriptor from the process token.
CAccessToken token;
if (token.GetProcessToken(TOKEN_QUERY)) {
CSecurityDesc security_desc;
// Set the SACL from an SDDL string that allows access to low-integrity
// processes. See http://msdn.microsoft.com/en-us/library/bb625958.aspx.
if (security_desc.FromString(L"S:(ML;;NW;;;LW)")) {
CSid sid_owner;
if (token.GetOwner(&sid_owner)) {
security_desc.SetOwner(sid_owner);
} else {
NOTREACHED() << "Could not get owner.";
}
CSid sid_group;
if (token.GetPrimaryGroup(&sid_group)) {
security_desc.SetGroup(sid_group);
} else {
NOTREACHED() << "Could not get group.";
}
CDacl dacl;
if (token.GetDefaultDacl(&dacl)) {
// Add an access control entry mask for the current user.
// This is what grants this user access from lower integrity levels.
CSid sid_user;
if (token.GetUser(&sid_user)) {
success = dacl.AddAllowedAce(sid_user, MUTEX_ALL_ACCESS);
security_desc.SetDacl(dacl);
sec_attr->Set(security_desc);
}
}
}
}
return success;
}
bool DllRedirector::SetFileMappingToReadOnly(base::SharedMemoryHandle mapping) {
bool success = false;
CAccessToken token;
if (token.GetProcessToken(TOKEN_QUERY)) {
CSid sid_user;
if (token.GetUser(&sid_user)) {
CDacl dacl;
dacl.AddAllowedAce(sid_user, STANDARD_RIGHTS_READ | FILE_MAP_READ);
success = AtlSetDacl(mapping, SE_KERNEL_OBJECT, dacl);
}
}
return success;
}
bool DllRedirector::RegisterAsFirstCFModule() {
DCHECK(first_module_handle_ == NULL);
// Build our own file version outside of the lock:
scoped_ptr<Version> our_version(GetCurrentModuleVersion());
// We sadly can't use the autolock here since we want to have a timeout.
// Be careful not to return while holding the lock. Also, attempt to do as
// little as possible while under this lock.
bool lock_acquired = false;
CSecurityAttributes sec_attr;
if (BuildSecurityAttributesForLock(&sec_attr)) {
lock_acquired = shared_memory_->Lock(kSharedMemoryLockTimeoutMs, &sec_attr);
} else {
lock_acquired = shared_memory_->Lock(kSharedMemoryLockTimeoutMs, NULL);
}
if (!lock_acquired) {
// We couldn't get the lock in a reasonable amount of time, so fall
// back to loading our current version. We return true to indicate that the
// caller should not attempt to delegate to an already loaded version.
dll_version_.swap(our_version);
first_module_handle_ = reinterpret_cast<HMODULE>(&__ImageBase);
return true;
}
bool created_beacon = true;
bool result = shared_memory_->CreateNamed(shared_memory_name_.c_str(),
false, // open_existing
kSharedMemorySize);
if (result) {
// We created the beacon, now we need to mutate the security attributes
// on the shared memory to allow read-only access and let low-integrity
// processes open it. This will fail on FAT32 file systems.
if (!SetFileMappingToReadOnly(shared_memory_->handle())) {
DLOG(ERROR) << "Failed to set file mapping permissions.";
}
} else {
created_beacon = false;
// We failed to create the shared memory segment, suggesting it may already
// exist: try to create it read-only.
result = shared_memory_->Open(shared_memory_name_.c_str(),
true /* read_only */);
}
if (result) {
// Map in the whole thing.
result = shared_memory_->Map(0);
DCHECK(shared_memory_->memory());
if (result) {
// Either write our own version number or read it in if it was already
// present in the shared memory section.
if (created_beacon) {
dll_version_.swap(our_version);
lstrcpynA(reinterpret_cast<char*>(shared_memory_->memory()),
dll_version_->GetString().c_str(),
std::min(kSharedMemorySize,
dll_version_->GetString().length() + 1));
// Mark ourself as the first module in.
first_module_handle_ = reinterpret_cast<HMODULE>(&__ImageBase);
} else {
char buffer[kSharedMemorySize] = {0};
memcpy(buffer, shared_memory_->memory(), kSharedMemorySize - 1);
dll_version_.reset(Version::GetVersionFromString(buffer));
if (!dll_version_.get() || dll_version_->Equals(*our_version.get())) {
// If we either couldn't parse a valid version out of the shared
// memory or we did parse a version and it is the same as our own,
// then pretend we're first in to avoid trying to load any other DLLs.
dll_version_.reset(our_version.release());
first_module_handle_ = reinterpret_cast<HMODULE>(&__ImageBase);
created_beacon = true;
}
}
} else {
NOTREACHED() << "Failed to map in version beacon.";
}
} else {
NOTREACHED() << "Could not create file mapping for version beacon, gle: "
<< ::GetLastError();
}
// Matching Unlock.
shared_memory_->Unlock();
return created_beacon;
}
void DllRedirector::UnregisterAsFirstCFModule() {
if (base::SharedMemory::IsHandleValid(shared_memory_->handle())) {
bool lock_acquired = shared_memory_->Lock(kSharedMemoryLockTimeoutMs, NULL);
if (lock_acquired) {
// Free our handles. The last closed handle SHOULD result in it being
// deleted.
shared_memory_->Close();
shared_memory_->Unlock();
}
}
}
LPFNGETCLASSOBJECT DllRedirector::GetDllGetClassObjectPtr() {
HMODULE first_module_handle = GetFirstModule();
LPFNGETCLASSOBJECT proc_ptr = reinterpret_cast<LPFNGETCLASSOBJECT>(
GetProcAddress(first_module_handle, "DllGetClassObject"));
if (!proc_ptr) {
DPLOG(ERROR) << "DllRedirector: Could not get address of DllGetClassObject "
"from first loaded module.";
// Oh boink, the first module we loaded was somehow bogus, make ourselves
// the first module again.
first_module_handle = reinterpret_cast<HMODULE>(&__ImageBase);
}
return proc_ptr;
}
Version* DllRedirector::GetCurrentModuleVersion() {
scoped_ptr<FileVersionInfo> file_version_info(
FileVersionInfo::CreateFileVersionInfoForCurrentModule());
DCHECK(file_version_info.get());
Version* current_version = NULL;
if (file_version_info.get()) {
current_version = Version::GetVersionFromString(
file_version_info->file_version());
DCHECK(current_version);
}
return current_version;
}
HMODULE DllRedirector::GetFirstModule() {
DCHECK(dll_version_.get())
<< "Error: Did you call RegisterAsFirstCFModule() first?";
if (first_module_handle_ == NULL) {
first_module_handle_ = LoadVersionedModule(dll_version_.get());
if (!first_module_handle_) {
first_module_handle_ = reinterpret_cast<HMODULE>(&__ImageBase);
}
}
return first_module_handle_;
}
HMODULE DllRedirector::LoadVersionedModule(Version* version) {
DCHECK(version);
FilePath module_path;
PathService::Get(base::DIR_MODULE, &module_path);
DCHECK(!module_path.empty());
FilePath module_name = module_path.BaseName();
module_path = module_path.DirName()
.Append(ASCIIToWide(version->GetString()))
.Append(module_name);
HMODULE hmodule = LoadLibrary(module_path.value().c_str());
if (hmodule == NULL) {
DPLOG(ERROR) << "Could not load reported module version "
<< version->GetString();
}
return hmodule;
}
<|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 "ui/webui/web_ui_util.h"
#include <vector>
#include "base/base64.h"
#include "base/debug/trace_event.h"
#include "base/i18n/rtl.h"
#include "base/logging.h"
#include "base/memory/ref_counted_memory.h"
#include "base/strings/string_number_conversions.h"
#include "grit/app_locale_settings.h"
#include "net/base/escape.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/window_open_disposition.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/font.h"
#include "ui/gfx/image/image_skia.h"
#include "url/gurl.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
namespace webui {
std::string GetBitmapDataUrl(const SkBitmap& bitmap) {
TRACE_EVENT2("oobe", "GetImageDataUrl",
"width", bitmap.width(), "height", bitmap.height());
std::vector<unsigned char> output;
gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &output);
std::string str_url;
str_url.insert(str_url.end(), output.begin(), output.end());
base::Base64Encode(str_url, &str_url);
str_url.insert(0, "data:image/png;base64,");
return str_url;
}
std::string GetBitmapDataUrlFromResource(int res) {
// Load resource icon and covert to base64 encoded data url
base::RefCountedStaticMemory* icon_data =
ResourceBundle::GetSharedInstance().LoadDataResourceBytesForScale(
res, ui::SCALE_FACTOR_100P);
if (!icon_data)
return std::string();
scoped_refptr<base::RefCountedMemory> raw_icon(icon_data);
std::string str_url;
str_url.insert(str_url.end(),
raw_icon->front(),
raw_icon->front() + raw_icon->size());
base::Base64Encode(str_url, &str_url);
str_url.insert(0, "data:image/png;base64,");
return str_url;
}
WindowOpenDisposition GetDispositionFromClick(const base::ListValue* args,
int start_index) {
double button = 0.0;
bool alt_key = false;
bool ctrl_key = false;
bool meta_key = false;
bool shift_key = false;
CHECK(args->GetDouble(start_index++, &button));
CHECK(args->GetBoolean(start_index++, &alt_key));
CHECK(args->GetBoolean(start_index++, &ctrl_key));
CHECK(args->GetBoolean(start_index++, &meta_key));
CHECK(args->GetBoolean(start_index++, &shift_key));
return ui::DispositionFromClick(
button == 1.0, alt_key, ctrl_key, meta_key, shift_key);
}
bool ParseScaleFactor(const base::StringPiece& identifier,
ui::ScaleFactor* scale_factor) {
*scale_factor = ui::SCALE_FACTOR_100P;
if (identifier.empty()) {
LOG(ERROR) << "Invalid scale factor format: " << identifier;
return false;
}
if (*identifier.rbegin() != 'x') {
LOG(ERROR) << "Invalid scale factor format: " << identifier;
return false;
}
double scale = 0;
std::string stripped;
identifier.substr(0, identifier.length() - 1).CopyToString(&stripped);
if (!base::StringToDouble(stripped, &scale)) {
LOG(ERROR) << "Invalid scale factor format: " << identifier;
return false;
}
*scale_factor = ui::GetScaleFactorFromScale(static_cast<float>(scale));
return true;
}
void ParsePathAndScale(const GURL& url,
std::string* path,
ui::ScaleFactor* scale_factor) {
*path = net::UnescapeURLComponent(url.path().substr(1),
(net::UnescapeRule::URL_SPECIAL_CHARS |
net::UnescapeRule::SPACES));
if (scale_factor)
*scale_factor = ui::SCALE_FACTOR_100P;
// Detect and parse resource string ending in @<scale>x.
std::size_t pos = path->rfind('@');
if (pos != std::string::npos) {
base::StringPiece stripped_path(*path);
ui::ScaleFactor factor;
if (ParseScaleFactor(stripped_path.substr(
pos + 1, stripped_path.length() - pos - 1), &factor)) {
// Strip scale factor specification from path.
stripped_path.remove_suffix(stripped_path.length() - pos);
stripped_path.CopyToString(path);
}
if (scale_factor)
*scale_factor = factor;
}
}
// static
void SetFontAndTextDirection(base::DictionaryValue* localized_strings) {
int web_font_family_id = IDS_WEB_FONT_FAMILY;
int web_font_size_id = IDS_WEB_FONT_SIZE;
#if defined(OS_WIN)
// Vary font settings for Windows XP.
if (base::win::GetVersion() < base::win::VERSION_VISTA) {
web_font_family_id = IDS_WEB_FONT_FAMILY_XP;
web_font_size_id = IDS_WEB_FONT_SIZE_XP;
}
#endif
std::string font_family = l10n_util::GetStringUTF8(web_font_family_id);
#if defined(TOOLKIT_GTK)
// Use the system font on Linux/GTK. Keep the hard-coded font families as
// backup in case for some crazy reason this one isn't available.
font_family = ui::ResourceBundle::GetSharedInstance().GetFont(
ui::ResourceBundle::BaseFont).GetFontName() + ", " + font_family;
#endif
localized_strings->SetString("fontfamily", font_family);
localized_strings->SetString("fontsize",
l10n_util::GetStringUTF8(web_font_size_id));
localized_strings->SetString("textdirection",
base::i18n::IsRTL() ? "rtl" : "ltr");
}
} // namespace webui
<commit_msg>Downgrade ERROR to WARNING for invalid scale factor formats in ParseScaleFactor<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 "ui/webui/web_ui_util.h"
#include <vector>
#include "base/base64.h"
#include "base/debug/trace_event.h"
#include "base/i18n/rtl.h"
#include "base/logging.h"
#include "base/memory/ref_counted_memory.h"
#include "base/strings/string_number_conversions.h"
#include "grit/app_locale_settings.h"
#include "net/base/escape.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/window_open_disposition.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/font.h"
#include "ui/gfx/image/image_skia.h"
#include "url/gurl.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
namespace webui {
std::string GetBitmapDataUrl(const SkBitmap& bitmap) {
TRACE_EVENT2("oobe", "GetImageDataUrl",
"width", bitmap.width(), "height", bitmap.height());
std::vector<unsigned char> output;
gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &output);
std::string str_url;
str_url.insert(str_url.end(), output.begin(), output.end());
base::Base64Encode(str_url, &str_url);
str_url.insert(0, "data:image/png;base64,");
return str_url;
}
std::string GetBitmapDataUrlFromResource(int res) {
// Load resource icon and covert to base64 encoded data url
base::RefCountedStaticMemory* icon_data =
ResourceBundle::GetSharedInstance().LoadDataResourceBytesForScale(
res, ui::SCALE_FACTOR_100P);
if (!icon_data)
return std::string();
scoped_refptr<base::RefCountedMemory> raw_icon(icon_data);
std::string str_url;
str_url.insert(str_url.end(),
raw_icon->front(),
raw_icon->front() + raw_icon->size());
base::Base64Encode(str_url, &str_url);
str_url.insert(0, "data:image/png;base64,");
return str_url;
}
WindowOpenDisposition GetDispositionFromClick(const base::ListValue* args,
int start_index) {
double button = 0.0;
bool alt_key = false;
bool ctrl_key = false;
bool meta_key = false;
bool shift_key = false;
CHECK(args->GetDouble(start_index++, &button));
CHECK(args->GetBoolean(start_index++, &alt_key));
CHECK(args->GetBoolean(start_index++, &ctrl_key));
CHECK(args->GetBoolean(start_index++, &meta_key));
CHECK(args->GetBoolean(start_index++, &shift_key));
return ui::DispositionFromClick(
button == 1.0, alt_key, ctrl_key, meta_key, shift_key);
}
bool ParseScaleFactor(const base::StringPiece& identifier,
ui::ScaleFactor* scale_factor) {
*scale_factor = ui::SCALE_FACTOR_100P;
if (identifier.empty()) {
LOG(WARNING) << "Invalid scale factor format: " << identifier;
return false;
}
if (*identifier.rbegin() != 'x') {
LOG(WARNING) << "Invalid scale factor format: " << identifier;
return false;
}
double scale = 0;
std::string stripped;
identifier.substr(0, identifier.length() - 1).CopyToString(&stripped);
if (!base::StringToDouble(stripped, &scale)) {
LOG(WARNING) << "Invalid scale factor format: " << identifier;
return false;
}
*scale_factor = ui::GetScaleFactorFromScale(static_cast<float>(scale));
return true;
}
void ParsePathAndScale(const GURL& url,
std::string* path,
ui::ScaleFactor* scale_factor) {
*path = net::UnescapeURLComponent(url.path().substr(1),
(net::UnescapeRule::URL_SPECIAL_CHARS |
net::UnescapeRule::SPACES));
if (scale_factor)
*scale_factor = ui::SCALE_FACTOR_100P;
// Detect and parse resource string ending in @<scale>x.
std::size_t pos = path->rfind('@');
if (pos != std::string::npos) {
base::StringPiece stripped_path(*path);
ui::ScaleFactor factor;
if (ParseScaleFactor(stripped_path.substr(
pos + 1, stripped_path.length() - pos - 1), &factor)) {
// Strip scale factor specification from path.
stripped_path.remove_suffix(stripped_path.length() - pos);
stripped_path.CopyToString(path);
}
if (scale_factor)
*scale_factor = factor;
}
}
// static
void SetFontAndTextDirection(base::DictionaryValue* localized_strings) {
int web_font_family_id = IDS_WEB_FONT_FAMILY;
int web_font_size_id = IDS_WEB_FONT_SIZE;
#if defined(OS_WIN)
// Vary font settings for Windows XP.
if (base::win::GetVersion() < base::win::VERSION_VISTA) {
web_font_family_id = IDS_WEB_FONT_FAMILY_XP;
web_font_size_id = IDS_WEB_FONT_SIZE_XP;
}
#endif
std::string font_family = l10n_util::GetStringUTF8(web_font_family_id);
#if defined(TOOLKIT_GTK)
// Use the system font on Linux/GTK. Keep the hard-coded font families as
// backup in case for some crazy reason this one isn't available.
font_family = ui::ResourceBundle::GetSharedInstance().GetFont(
ui::ResourceBundle::BaseFont).GetFontName() + ", " + font_family;
#endif
localized_strings->SetString("fontfamily", font_family);
localized_strings->SetString("fontsize",
l10n_util::GetStringUTF8(web_font_size_id));
localized_strings->SetString("textdirection",
base::i18n::IsRTL() ? "rtl" : "ltr");
}
} // namespace webui
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkDataSetTriangleFilter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkDataSetTriangleFilter.h"
#include <assert.h>
#include "vtkCellData.h"
#include "vtkCellType.h"
#include "vtkGenericCell.h"
#include "vtkIdList.h"
#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkOrderedTriangulator.h"
#include "vtkPointData.h"
#include "vtkStructuredGrid.h"
#include "vtkStructuredPoints.h"
#include "vtkUnstructuredGrid.h"
#include "vtkRectilinearGrid.h"
#include "vtkUnsignedCharArray.h"
vtkStandardNewMacro(vtkDataSetTriangleFilter);
vtkDataSetTriangleFilter::vtkDataSetTriangleFilter()
{
this->Triangulator = vtkOrderedTriangulator::New();
this->Triangulator->PreSortedOff();
this->Triangulator->UseTemplatesOn();
this->TetrahedraOnly = 0;
}
vtkDataSetTriangleFilter::~vtkDataSetTriangleFilter()
{
this->Triangulator->Delete();
this->Triangulator = NULL;
}
int vtkDataSetTriangleFilter::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and output
vtkDataSet *input = vtkDataSet::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
if (input->IsA("vtkStructuredPoints") ||
input->IsA("vtkStructuredGrid") ||
input->IsA("vtkImageData") ||
input->IsA("vtkRectilinearGrid"))
{
this->StructuredExecute(input, output);
}
else
{
this->UnstructuredExecute(input, output);
}
vtkDebugMacro(<<"Produced " << this->GetOutput()->GetNumberOfCells() << " cells");
return 1;
}
void vtkDataSetTriangleFilter::StructuredExecute(vtkDataSet *input,
vtkUnstructuredGrid *output)
{
int dimensions[3], i, j, k, l, m;
vtkIdType newCellId, inId;
vtkGenericCell *cell = vtkGenericCell::New();
vtkCellData *inCD = input->GetCellData();
vtkCellData *outCD = output->GetCellData();
vtkPoints *cellPts = vtkPoints::New();
vtkPoints *newPoints = vtkPoints::New();
vtkIdList *cellPtIds = vtkIdList::New();
int numSimplices, numPts, dim, type;
vtkIdType pts[4], num;
// Create an array of points. This does an explicit creation
// of each point.
num = input->GetNumberOfPoints();
newPoints->SetNumberOfPoints(num);
for (i = 0; i < num; ++i)
{
newPoints->SetPoint(i,input->GetPoint(i));
}
outCD->CopyAllocate(inCD,input->GetNumberOfCells()*5);
output->Allocate(input->GetNumberOfCells()*5);
if (input->IsA("vtkStructuredPoints"))
{
static_cast<vtkStructuredPoints*>(input)->GetDimensions(dimensions);
}
else if (input->IsA("vtkStructuredGrid"))
{
static_cast<vtkStructuredGrid*>(input)->GetDimensions(dimensions);
}
else if (input->IsA("vtkImageData"))
{
static_cast<vtkImageData*>(input)->GetDimensions(dimensions);
}
else if (input->IsA("vtkRectilinearGrid"))
{
static_cast<vtkRectilinearGrid*>(input)->GetDimensions(dimensions);
}
else
{
assert(0);
}
dimensions[0] = dimensions[0] - 1;
dimensions[1] = dimensions[1] - 1;
dimensions[2] = dimensions[2] - 1;
vtkIdType numSlices = ( dimensions[2] > 0 ? dimensions[2] : 1 );
int abort=0;
for (k = 0; k < numSlices && !abort; k++)
{
this->UpdateProgress(static_cast<double>(k) / numSlices);
abort = this->GetAbortExecute();
for (j = 0; j < dimensions[1]; j++)
{
for (i = 0; i < dimensions[0]; i++)
{
inId = i+(j+(k*dimensions[1]))*dimensions[0];
input->GetCell(inId, cell);
if ((i+j+k)%2 == 0)
{
cell->Triangulate(0, cellPtIds, cellPts);
}
else
{
cell->Triangulate(1, cellPtIds, cellPts);
}
dim = cell->GetCellDimension() + 1;
numPts = cellPtIds->GetNumberOfIds();
numSimplices = numPts / dim;
type = 0;
switch (dim)
{
case 1:
type = VTK_VERTEX; break;
case 2:
type = VTK_LINE; break;
case 3:
type = VTK_TRIANGLE; break;
case 4:
type = VTK_TETRA; break;
}
if (!this->TetrahedraOnly || type == VTK_TETRA)
{
for (l = 0; l < numSimplices; l++ )
{
for (m = 0; m < dim; m++)
{
pts[m] = cellPtIds->GetId(dim*l+m);
}
// copy cell data
newCellId = output->InsertNextCell(type, dim, pts);
outCD->CopyData(inCD, inId, newCellId);
}//for all simplices
}
}//i dimension
}//j dimension
}//k dimension
// Update output
output->SetPoints(newPoints);
output->GetPointData()->PassData(input->GetPointData());
output->Squeeze();
cell->Delete();
newPoints->Delete();
cellPts->Delete();
cellPtIds->Delete();
}
// 3D cells use the ordered triangulator. The ordered triangulator is used
// to create templates on the fly. Once the templates are created then they
// are used to produce the final triangulation.
//
void vtkDataSetTriangleFilter::UnstructuredExecute(vtkDataSet *dataSetInput,
vtkUnstructuredGrid *output)
{
vtkPointSet *input = static_cast<vtkPointSet*>(dataSetInput); //has to be
vtkIdType numCells = input->GetNumberOfCells();
vtkGenericCell *cell;
vtkIdType newCellId, j;
int k;
vtkCellData *inCD=input->GetCellData();
vtkCellData *outCD=output->GetCellData();
vtkPoints *cellPts;
vtkIdList *cellPtIds;
vtkIdType ptId, numTets, ncells;
int numPts, type;
int numSimplices, dim;
vtkIdType pts[4];
double x[3];
if (numCells == 0)
{
return;
}
vtkUnstructuredGrid * inUgrid =
vtkUnstructuredGrid::SafeDownCast(dataSetInput);
if (inUgrid)
{
//avoid doing cell simplification if all cells are already simplices
vtkUnsignedCharArray* cellTypes = inUgrid->GetCellTypesArray();
if (cellTypes)
{
int allsimplices = 1;
for (vtkIdType cellId = 0; cellId < cellTypes->GetSize() && allsimplices; cellId++)
{
switch (cellTypes->GetValue(cellId))
{
case VTK_TETRA:
break;
case VTK_VERTEX:
case VTK_LINE:
case VTK_TRIANGLE:
if (this->TetrahedraOnly)
{
allsimplices = 0; //don't shallowcopy need to stip non tets
}
break;
default:
allsimplices = 0;
break;
}
}
if (allsimplices)
{
output->ShallowCopy(input);
return;
}
}
}
cell = vtkGenericCell::New();
cellPts = vtkPoints::New();
cellPtIds = vtkIdList::New();
// Create an array of points
vtkCellData *tempCD = vtkCellData::New();
tempCD->ShallowCopy(inCD);
tempCD->SetActiveGlobalIds(NULL);
outCD->CopyAllocate(tempCD, input->GetNumberOfCells()*5);
output->Allocate(input->GetNumberOfCells()*5);
// Points are passed through
output->SetPoints(input->GetPoints());
output->GetPointData()->PassData(input->GetPointData());
int abort=0;
vtkIdType updateTime = numCells/20 + 1; // update roughly every 5%
for (vtkIdType cellId=0; cellId < numCells && !abort; cellId++)
{
if ( !(cellId % updateTime) )
{
this->UpdateProgress(static_cast<double>(cellId) / numCells);
abort = this->GetAbortExecute();
}
input->GetCell(cellId, cell);
dim = cell->GetCellDimension();
if (cell->GetCellType() == VTK_POLYHEDRON) //polyhedron
{
dim = 4;
cell->Triangulate(0, cellPtIds, cellPts);
numPts = cellPtIds->GetNumberOfIds();
numSimplices = numPts / dim;
type = VTK_TETRA;
for ( j=0; j < numSimplices; j++ )
{
for (k=0; k<dim; k++)
{
pts[k] = cellPtIds->GetId(dim*j+k);
}
// copy cell data
newCellId = output->InsertNextCell(type, dim, pts);
outCD->CopyData(tempCD, cellId, newCellId);
}
}
else if ( dim == 3 ) //use ordered triangulation
{
numPts = cell->GetNumberOfPoints();
double *p, *pPtr=cell->GetParametricCoords();
this->Triangulator->InitTriangulation(0.0,1.0, 0.0,1.0, 0.0,1.0, numPts);
for (p=pPtr, j=0; j<numPts; j++, p+=3)
{
ptId = cell->PointIds->GetId(j);
cell->Points->GetPoint(j, x);
this->Triangulator->InsertPoint(ptId, x, p, 0);
}//for all cell points
if ( cell->IsPrimaryCell() ) //use templates if topology is fixed
{
int numEdges=cell->GetNumberOfEdges();
this->Triangulator->TemplateTriangulate(cell->GetCellType(),
numPts,numEdges);
}
else //use ordered triangulator
{
this->Triangulator->Triangulate();
}
ncells = output->GetNumberOfCells();
numTets = this->Triangulator->AddTetras(0,output);
for (j=0; j < numTets; j++)
{
outCD->CopyData(tempCD, cellId, ncells+j);
}
}
else if (!this->TetrahedraOnly) //2D or lower dimension
{
dim++;
cell->Triangulate(0, cellPtIds, cellPts);
numPts = cellPtIds->GetNumberOfIds();
numSimplices = numPts / dim;
type = 0;
switch (dim)
{
case 1:
type = VTK_VERTEX; break;
case 2:
type = VTK_LINE; break;
case 3:
type = VTK_TRIANGLE; break;
}
for ( j=0; j < numSimplices; j++ )
{
for (k=0; k<dim; k++)
{
pts[k] = cellPtIds->GetId(dim*j+k);
}
// copy cell data
newCellId = output->InsertNextCell(type, dim, pts);
outCD->CopyData(tempCD, cellId, newCellId);
}
} //if 2D or less cell
} //for all cells
// Update output
output->Squeeze();
tempCD->Delete();
cellPts->Delete();
cellPtIds->Delete();
cell->Delete();
}
int vtkDataSetTriangleFilter::FillInputPortInformation(int, vtkInformation *info)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet");
return 1;
}
void vtkDataSetTriangleFilter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "TetrahedraOnly: " << (this->TetrahedraOnly ? "On":"Off") << "\n";
}
<commit_msg>Replace unrecognized data set assert with a vtkErrorMacro.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkDataSetTriangleFilter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkDataSetTriangleFilter.h"
#include "vtkCellData.h"
#include "vtkCellType.h"
#include "vtkGenericCell.h"
#include "vtkIdList.h"
#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkOrderedTriangulator.h"
#include "vtkPointData.h"
#include "vtkStructuredGrid.h"
#include "vtkStructuredPoints.h"
#include "vtkUnstructuredGrid.h"
#include "vtkRectilinearGrid.h"
#include "vtkUnsignedCharArray.h"
vtkStandardNewMacro(vtkDataSetTriangleFilter);
vtkDataSetTriangleFilter::vtkDataSetTriangleFilter()
{
this->Triangulator = vtkOrderedTriangulator::New();
this->Triangulator->PreSortedOff();
this->Triangulator->UseTemplatesOn();
this->TetrahedraOnly = 0;
}
vtkDataSetTriangleFilter::~vtkDataSetTriangleFilter()
{
this->Triangulator->Delete();
this->Triangulator = NULL;
}
int vtkDataSetTriangleFilter::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and output
vtkDataSet *input = vtkDataSet::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
if (input->IsA("vtkStructuredPoints") ||
input->IsA("vtkStructuredGrid") ||
input->IsA("vtkImageData") ||
input->IsA("vtkRectilinearGrid"))
{
this->StructuredExecute(input, output);
}
else
{
this->UnstructuredExecute(input, output);
}
vtkDebugMacro(<<"Produced " << this->GetOutput()->GetNumberOfCells() << " cells");
return 1;
}
void vtkDataSetTriangleFilter::StructuredExecute(vtkDataSet *input,
vtkUnstructuredGrid *output)
{
int dimensions[3], i, j, k, l, m;
vtkIdType newCellId, inId;
vtkGenericCell *cell = vtkGenericCell::New();
vtkCellData *inCD = input->GetCellData();
vtkCellData *outCD = output->GetCellData();
vtkPoints *cellPts = vtkPoints::New();
vtkPoints *newPoints = vtkPoints::New();
vtkIdList *cellPtIds = vtkIdList::New();
int numSimplices, numPts, dim, type;
vtkIdType pts[4], num;
// Create an array of points. This does an explicit creation
// of each point.
num = input->GetNumberOfPoints();
newPoints->SetNumberOfPoints(num);
for (i = 0; i < num; ++i)
{
newPoints->SetPoint(i,input->GetPoint(i));
}
outCD->CopyAllocate(inCD,input->GetNumberOfCells()*5);
output->Allocate(input->GetNumberOfCells()*5);
if (input->IsA("vtkStructuredPoints"))
{
static_cast<vtkStructuredPoints*>(input)->GetDimensions(dimensions);
}
else if (input->IsA("vtkStructuredGrid"))
{
static_cast<vtkStructuredGrid*>(input)->GetDimensions(dimensions);
}
else if (input->IsA("vtkImageData"))
{
static_cast<vtkImageData*>(input)->GetDimensions(dimensions);
}
else if (input->IsA("vtkRectilinearGrid"))
{
static_cast<vtkRectilinearGrid*>(input)->GetDimensions(dimensions);
}
else
{
// Every kind of structured data is listed above, this should never happen.
// Report an error and produce no output.
vtkErrorMacro("Unrecognized data set " << input->GetClassName());
// Dimensions of 1x1x1 means a single point, i.e. dimensionality of zero.
dimensions[0] = 1;
dimensions[1] = 1;
dimensions[2] = 1;
}
dimensions[0] = dimensions[0] - 1;
dimensions[1] = dimensions[1] - 1;
dimensions[2] = dimensions[2] - 1;
vtkIdType numSlices = ( dimensions[2] > 0 ? dimensions[2] : 1 );
int abort=0;
for (k = 0; k < numSlices && !abort; k++)
{
this->UpdateProgress(static_cast<double>(k) / numSlices);
abort = this->GetAbortExecute();
for (j = 0; j < dimensions[1]; j++)
{
for (i = 0; i < dimensions[0]; i++)
{
inId = i+(j+(k*dimensions[1]))*dimensions[0];
input->GetCell(inId, cell);
if ((i+j+k)%2 == 0)
{
cell->Triangulate(0, cellPtIds, cellPts);
}
else
{
cell->Triangulate(1, cellPtIds, cellPts);
}
dim = cell->GetCellDimension() + 1;
numPts = cellPtIds->GetNumberOfIds();
numSimplices = numPts / dim;
type = 0;
switch (dim)
{
case 1:
type = VTK_VERTEX; break;
case 2:
type = VTK_LINE; break;
case 3:
type = VTK_TRIANGLE; break;
case 4:
type = VTK_TETRA; break;
}
if (!this->TetrahedraOnly || type == VTK_TETRA)
{
for (l = 0; l < numSimplices; l++ )
{
for (m = 0; m < dim; m++)
{
pts[m] = cellPtIds->GetId(dim*l+m);
}
// copy cell data
newCellId = output->InsertNextCell(type, dim, pts);
outCD->CopyData(inCD, inId, newCellId);
}//for all simplices
}
}//i dimension
}//j dimension
}//k dimension
// Update output
output->SetPoints(newPoints);
output->GetPointData()->PassData(input->GetPointData());
output->Squeeze();
cell->Delete();
newPoints->Delete();
cellPts->Delete();
cellPtIds->Delete();
}
// 3D cells use the ordered triangulator. The ordered triangulator is used
// to create templates on the fly. Once the templates are created then they
// are used to produce the final triangulation.
//
void vtkDataSetTriangleFilter::UnstructuredExecute(vtkDataSet *dataSetInput,
vtkUnstructuredGrid *output)
{
vtkPointSet *input = static_cast<vtkPointSet*>(dataSetInput); //has to be
vtkIdType numCells = input->GetNumberOfCells();
vtkGenericCell *cell;
vtkIdType newCellId, j;
int k;
vtkCellData *inCD=input->GetCellData();
vtkCellData *outCD=output->GetCellData();
vtkPoints *cellPts;
vtkIdList *cellPtIds;
vtkIdType ptId, numTets, ncells;
int numPts, type;
int numSimplices, dim;
vtkIdType pts[4];
double x[3];
if (numCells == 0)
{
return;
}
vtkUnstructuredGrid * inUgrid =
vtkUnstructuredGrid::SafeDownCast(dataSetInput);
if (inUgrid)
{
//avoid doing cell simplification if all cells are already simplices
vtkUnsignedCharArray* cellTypes = inUgrid->GetCellTypesArray();
if (cellTypes)
{
int allsimplices = 1;
for (vtkIdType cellId = 0; cellId < cellTypes->GetSize() && allsimplices; cellId++)
{
switch (cellTypes->GetValue(cellId))
{
case VTK_TETRA:
break;
case VTK_VERTEX:
case VTK_LINE:
case VTK_TRIANGLE:
if (this->TetrahedraOnly)
{
allsimplices = 0; //don't shallowcopy need to stip non tets
}
break;
default:
allsimplices = 0;
break;
}
}
if (allsimplices)
{
output->ShallowCopy(input);
return;
}
}
}
cell = vtkGenericCell::New();
cellPts = vtkPoints::New();
cellPtIds = vtkIdList::New();
// Create an array of points
vtkCellData *tempCD = vtkCellData::New();
tempCD->ShallowCopy(inCD);
tempCD->SetActiveGlobalIds(NULL);
outCD->CopyAllocate(tempCD, input->GetNumberOfCells()*5);
output->Allocate(input->GetNumberOfCells()*5);
// Points are passed through
output->SetPoints(input->GetPoints());
output->GetPointData()->PassData(input->GetPointData());
int abort=0;
vtkIdType updateTime = numCells/20 + 1; // update roughly every 5%
for (vtkIdType cellId=0; cellId < numCells && !abort; cellId++)
{
if ( !(cellId % updateTime) )
{
this->UpdateProgress(static_cast<double>(cellId) / numCells);
abort = this->GetAbortExecute();
}
input->GetCell(cellId, cell);
dim = cell->GetCellDimension();
if (cell->GetCellType() == VTK_POLYHEDRON) //polyhedron
{
dim = 4;
cell->Triangulate(0, cellPtIds, cellPts);
numPts = cellPtIds->GetNumberOfIds();
numSimplices = numPts / dim;
type = VTK_TETRA;
for ( j=0; j < numSimplices; j++ )
{
for (k=0; k<dim; k++)
{
pts[k] = cellPtIds->GetId(dim*j+k);
}
// copy cell data
newCellId = output->InsertNextCell(type, dim, pts);
outCD->CopyData(tempCD, cellId, newCellId);
}
}
else if ( dim == 3 ) //use ordered triangulation
{
numPts = cell->GetNumberOfPoints();
double *p, *pPtr=cell->GetParametricCoords();
this->Triangulator->InitTriangulation(0.0,1.0, 0.0,1.0, 0.0,1.0, numPts);
for (p=pPtr, j=0; j<numPts; j++, p+=3)
{
ptId = cell->PointIds->GetId(j);
cell->Points->GetPoint(j, x);
this->Triangulator->InsertPoint(ptId, x, p, 0);
}//for all cell points
if ( cell->IsPrimaryCell() ) //use templates if topology is fixed
{
int numEdges=cell->GetNumberOfEdges();
this->Triangulator->TemplateTriangulate(cell->GetCellType(),
numPts,numEdges);
}
else //use ordered triangulator
{
this->Triangulator->Triangulate();
}
ncells = output->GetNumberOfCells();
numTets = this->Triangulator->AddTetras(0,output);
for (j=0; j < numTets; j++)
{
outCD->CopyData(tempCD, cellId, ncells+j);
}
}
else if (!this->TetrahedraOnly) //2D or lower dimension
{
dim++;
cell->Triangulate(0, cellPtIds, cellPts);
numPts = cellPtIds->GetNumberOfIds();
numSimplices = numPts / dim;
type = 0;
switch (dim)
{
case 1:
type = VTK_VERTEX; break;
case 2:
type = VTK_LINE; break;
case 3:
type = VTK_TRIANGLE; break;
}
for ( j=0; j < numSimplices; j++ )
{
for (k=0; k<dim; k++)
{
pts[k] = cellPtIds->GetId(dim*j+k);
}
// copy cell data
newCellId = output->InsertNextCell(type, dim, pts);
outCD->CopyData(tempCD, cellId, newCellId);
}
} //if 2D or less cell
} //for all cells
// Update output
output->Squeeze();
tempCD->Delete();
cellPts->Delete();
cellPtIds->Delete();
cell->Delete();
}
int vtkDataSetTriangleFilter::FillInputPortInformation(int, vtkInformation *info)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet");
return 1;
}
void vtkDataSetTriangleFilter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "TetrahedraOnly: " << (this->TetrahedraOnly ? "On":"Off") << "\n";
}
<|endoftext|>
|
<commit_before>/*
* Author(s):
* - Cedric Gestes <gestes@aldebaran-robotics.com>
* - Chris Kilner <ckilner@aldebaran-robotics.com>
*
* Copyright (C) 2010 Aldebaran Robotics
*/
#include <qi/log.hpp>
#include "src/messaging/master_client.hpp"
#include <qimessaging/serialization.hpp>
#include "src/messaging/network/master_endpoint.hpp"
namespace qi {
namespace detail {
using qi::transport::Buffer;
using qi::Message;
static const std::string methodUnregisterEndpoint("master.unregisterEndpoint::v:s");
static const std::string methodRegisterTopic("master.registerTopic::v:sbs");
static const std::string methodUnregisterTopic("master.unregisterTopic::v:ss");
static const std::string methodGetNewPort("master.getNewPort::i:s");
static const std::string methodRegisterMachine("master.registerMachine::v:sssi");
static const std::string methodRegisterEndpoint("master.registerEndpoint::v:issssii");
static const std::string methodTopicExists("master.topicExists::b:s");
static const std::string methodLocateService("master.locateService::s:ss");
static const std::string methodRegisterService("master.registerService::v:ss");
static const std::string methodUnregisterService("master.unregisterService::v:s");
static const std::string methodLocateTopic("master.locateTopic::s:ss");
static const std::string methodRegisterTopicParticipant("master.registerTopicParticipant::v:ss");
MasterClient::~MasterClient() {
}
MasterClient::MasterClient(qi::Context *ctx)
: _isInitialized(false),
_qiContextPtr( (ctx == NULL)? getDefaultQiContextPtr() : ctx),
_transportClient(_qiContextPtr->getTransportContext())
{
}
void MasterClient::connect(const std::string masterAddress) {
_masterAddress = masterAddress;
std::pair<std::string, int> masterEndpointAndPort;
if (!qi::detail::validateMasterEndpoint(_masterAddress, masterEndpointAndPort)) {
_isInitialized = false;
qiLogError("qimessaging") << "Initialized with invalid master address: \""
<< _masterAddress << "\" All calls will fail." << std::endl;
return;
}
_isInitialized = _transportClient.connect(masterEndpointAndPort.first);
if (! _isInitialized ) {
qiLogError("qimessaging") << "Could not connect to master "
"at address \"" << masterEndpointAndPort.first << "\""
<< std::endl;
return;
}
}
bool MasterClient::isInitialized() const {
return _isInitialized;
}
const std::string& MasterClient::getMasterAddress() const {
return _masterAddress;
}
int MasterClient::getNewPort(const std::string& machineID) {
if (!_isInitialized) {
return 0;
}
Buffer ret;
Message msg;
msg.writeString(methodGetNewPort);
msg.writeString(machineID);
_transportClient.send(msg.str(), ret);
Message retSer(ret);
int port;
retSer.readInt(port);
return port;
}
void MasterClient::registerMachine(const qi::detail::MachineContext& m) {
if (!_isInitialized) {
return;
}
Buffer ret;
Message msg;
msg.writeString(methodRegisterMachine);
msg.writeString(m.hostName);
msg.writeString(m.machineID);
msg.writeString(m.publicIP);
msg.writeInt( m.platformID);
_transportClient.send(msg.str(), ret);
}
void MasterClient::registerEndpoint(const qi::detail::EndpointContext& e) {
if (!_isInitialized) {
return;
}
Buffer ret;
Message msg;
msg.writeString(methodRegisterEndpoint);
msg.writeInt((int)e.type);
msg.writeString(e.name);
msg.writeString(e.endpointID);
msg.writeString(e.contextID);
msg.writeString(e.machineID);
msg.writeInt( e.processID);
msg.writeInt( e.port);
_transportClient.send(msg.str(), ret);
}
void MasterClient::unregisterEndpoint(const qi::detail::EndpointContext& e) {
if (!_isInitialized) {
return;
}
Buffer ret;
Message msg;
msg.writeString(methodUnregisterEndpoint);
msg.writeString(e.endpointID);
_transportClient.send(msg.str(), ret);
}
std::string MasterClient::locateService(const std::string& methodSignature, const qi::detail::EndpointContext& e) {
if (!_isInitialized) {
return "";
}
Buffer ret;
Message msg;
msg.writeString(methodLocateService);
msg.writeString(methodSignature);
msg.writeString(e.endpointID);
_transportClient.send(msg.str(), ret);
Message retSer(ret);
std::string endpoint;
retSer.readString(endpoint);
return endpoint;
}
void MasterClient::registerService(
const std::string& methodSignature, const qi::detail::EndpointContext& e)
{
if (!_isInitialized) {
return;
}
Buffer ret;
Message msg;
msg.writeString(methodRegisterService);
msg.writeString(methodSignature);
msg.writeString(e.endpointID);
_transportClient.send(msg.str(), ret);
}
void MasterClient::unregisterService(const std::string& methodSignature)
{
if (!_isInitialized) {
return;
}
Buffer ret;
Message msg;
msg.writeString(methodUnregisterService);
msg.writeString(methodSignature);
_transportClient.send(msg.str(), ret);
}
std::string MasterClient::locateTopic(const std::string& methodSignature, const qi::detail::EndpointContext& e) {
if (!_isInitialized) {
return "";
}
Buffer ret;
Message msg;
msg.writeString(methodLocateTopic);
msg.writeString(methodSignature);
msg.writeString(e.endpointID);
_transportClient.send(msg.str(), ret);
Message retSer(ret);
std::string endpoint;
retSer.readString(endpoint);
return endpoint;
}
bool MasterClient::topicExists(const std::string& signature)
{
if (!_isInitialized) {
return false;
}
Buffer ret;
Message msg;
msg.writeString(methodTopicExists);
msg.writeString(signature);
_transportClient.send(msg.str(), ret);
Message retSer(ret);
bool exists;
retSer.readBool(exists);
return exists;
}
void MasterClient::registerTopic(
const std::string& signature, const bool& isManyToMany,
const qi::detail::EndpointContext& e)
{
if (!_isInitialized) {
return;
}
Buffer ret;
Message msg;
msg.writeString(methodRegisterTopic);
msg.writeString(signature);
msg.writeBool(isManyToMany);
msg.writeString(e.endpointID);
_transportClient.send(msg.str(), ret);
}
void MasterClient::registerTopicParticipant(
const std::string& signature,
const std::string& endpointID)
{
if (!_isInitialized) {
return;
}
Buffer ret;
Message msg;
msg.writeString(methodRegisterTopicParticipant);
msg.writeString(signature);
msg.writeString(endpointID);
_transportClient.send(msg.str(), ret);
}
void MasterClient::unregisterTopic(
const std::string& signature,
const qi::detail::EndpointContext& e)
{
if (!_isInitialized) {
return;
}
Buffer ret;
Message msg;
msg.writeString(methodUnregisterTopic);
msg.writeString(signature);
msg.writeString(e.endpointID);
_transportClient.send(msg.str(), ret);
}
}
}
<commit_msg>masterclient: signature have changed<commit_after>/*
* Author(s):
* - Cedric Gestes <gestes@aldebaran-robotics.com>
* - Chris Kilner <ckilner@aldebaran-robotics.com>
*
* Copyright (C) 2010 Aldebaran Robotics
*/
#include <qi/log.hpp>
#include "src/messaging/master_client.hpp"
#include <qimessaging/serialization.hpp>
#include "src/messaging/network/master_endpoint.hpp"
namespace qi {
namespace detail {
using qi::transport::Buffer;
using qi::Message;
static const std::string methodUnregisterEndpoint("master.unregisterEndpoint::v(s)");
static const std::string methodRegisterTopic("master.registerTopic::v(sbs)");
static const std::string methodUnregisterTopic("master.unregisterTopic::v(ss)");
static const std::string methodGetNewPort("master.getNewPort::i(s)");
static const std::string methodRegisterMachine("master.registerMachine::v(sssi)");
static const std::string methodRegisterEndpoint("master.registerEndpoint::v(issssii)");
static const std::string methodTopicExists("master.topicExists::b(s)");
static const std::string methodLocateService("master.locateService::s(ss)");
static const std::string methodRegisterService("master.registerService::v(ss)");
static const std::string methodUnregisterService("master.unregisterService::v(s)");
static const std::string methodLocateTopic("master.locateTopic::s(ss)");
static const std::string methodRegisterTopicParticipant("master.registerTopicParticipant::v(ss)");
MasterClient::~MasterClient() {
}
MasterClient::MasterClient(qi::Context *ctx)
: _isInitialized(false),
_qiContextPtr( (ctx == NULL)? getDefaultQiContextPtr() : ctx),
_transportClient(_qiContextPtr->getTransportContext())
{
}
void MasterClient::connect(const std::string masterAddress) {
_masterAddress = masterAddress;
std::pair<std::string, int> masterEndpointAndPort;
if (!qi::detail::validateMasterEndpoint(_masterAddress, masterEndpointAndPort)) {
_isInitialized = false;
qiLogError("qimessaging") << "Initialized with invalid master address: \""
<< _masterAddress << "\" All calls will fail." << std::endl;
return;
}
_isInitialized = _transportClient.connect(masterEndpointAndPort.first);
if (! _isInitialized ) {
qiLogError("qimessaging") << "Could not connect to master "
"at address \"" << masterEndpointAndPort.first << "\""
<< std::endl;
return;
}
}
bool MasterClient::isInitialized() const {
return _isInitialized;
}
const std::string& MasterClient::getMasterAddress() const {
return _masterAddress;
}
int MasterClient::getNewPort(const std::string& machineID) {
if (!_isInitialized) {
return 0;
}
Buffer ret;
Message msg;
msg.writeString(methodGetNewPort);
msg.writeString(machineID);
_transportClient.send(msg.str(), ret);
Message retSer(ret);
int port;
retSer.readInt(port);
return port;
}
void MasterClient::registerMachine(const qi::detail::MachineContext& m) {
if (!_isInitialized) {
return;
}
Buffer ret;
Message msg;
msg.writeString(methodRegisterMachine);
msg.writeString(m.hostName);
msg.writeString(m.machineID);
msg.writeString(m.publicIP);
msg.writeInt( m.platformID);
_transportClient.send(msg.str(), ret);
}
void MasterClient::registerEndpoint(const qi::detail::EndpointContext& e) {
if (!_isInitialized) {
return;
}
Buffer ret;
Message msg;
msg.writeString(methodRegisterEndpoint);
msg.writeInt((int)e.type);
msg.writeString(e.name);
msg.writeString(e.endpointID);
msg.writeString(e.contextID);
msg.writeString(e.machineID);
msg.writeInt( e.processID);
msg.writeInt( e.port);
_transportClient.send(msg.str(), ret);
}
void MasterClient::unregisterEndpoint(const qi::detail::EndpointContext& e) {
if (!_isInitialized) {
return;
}
Buffer ret;
Message msg;
msg.writeString(methodUnregisterEndpoint);
msg.writeString(e.endpointID);
_transportClient.send(msg.str(), ret);
}
std::string MasterClient::locateService(const std::string& methodSignature, const qi::detail::EndpointContext& e) {
if (!_isInitialized) {
return "";
}
Buffer ret;
Message msg;
msg.writeString(methodLocateService);
msg.writeString(methodSignature);
msg.writeString(e.endpointID);
_transportClient.send(msg.str(), ret);
Message retSer(ret);
std::string endpoint;
retSer.readString(endpoint);
return endpoint;
}
void MasterClient::registerService(
const std::string& methodSignature, const qi::detail::EndpointContext& e)
{
if (!_isInitialized) {
return;
}
Buffer ret;
Message msg;
msg.writeString(methodRegisterService);
msg.writeString(methodSignature);
msg.writeString(e.endpointID);
_transportClient.send(msg.str(), ret);
}
void MasterClient::unregisterService(const std::string& methodSignature)
{
if (!_isInitialized) {
return;
}
Buffer ret;
Message msg;
msg.writeString(methodUnregisterService);
msg.writeString(methodSignature);
_transportClient.send(msg.str(), ret);
}
std::string MasterClient::locateTopic(const std::string& methodSignature, const qi::detail::EndpointContext& e) {
if (!_isInitialized) {
return "";
}
Buffer ret;
Message msg;
msg.writeString(methodLocateTopic);
msg.writeString(methodSignature);
msg.writeString(e.endpointID);
_transportClient.send(msg.str(), ret);
Message retSer(ret);
std::string endpoint;
retSer.readString(endpoint);
return endpoint;
}
bool MasterClient::topicExists(const std::string& signature)
{
if (!_isInitialized) {
return false;
}
Buffer ret;
Message msg;
msg.writeString(methodTopicExists);
msg.writeString(signature);
_transportClient.send(msg.str(), ret);
Message retSer(ret);
bool exists;
retSer.readBool(exists);
return exists;
}
void MasterClient::registerTopic(
const std::string& signature, const bool& isManyToMany,
const qi::detail::EndpointContext& e)
{
if (!_isInitialized) {
return;
}
Buffer ret;
Message msg;
msg.writeString(methodRegisterTopic);
msg.writeString(signature);
msg.writeBool(isManyToMany);
msg.writeString(e.endpointID);
_transportClient.send(msg.str(), ret);
}
void MasterClient::registerTopicParticipant(
const std::string& signature,
const std::string& endpointID)
{
if (!_isInitialized) {
return;
}
Buffer ret;
Message msg;
msg.writeString(methodRegisterTopicParticipant);
msg.writeString(signature);
msg.writeString(endpointID);
_transportClient.send(msg.str(), ret);
}
void MasterClient::unregisterTopic(
const std::string& signature,
const qi::detail::EndpointContext& e)
{
if (!_isInitialized) {
return;
}
Buffer ret;
Message msg;
msg.writeString(methodUnregisterTopic);
msg.writeString(signature);
msg.writeString(e.endpointID);
_transportClient.send(msg.str(), ret);
}
}
}
<|endoftext|>
|
<commit_before>#include "EnvironmentNetworking.h"
#include <time.h>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <stdio.h>
#ifdef _WIN32
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#else
#include <sys/socket.h>
#include <arpa/inet.h>
#include <time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#endif
std::string EnvironmentNetworking::serializeMap(const hlt::Map & map)
{
std::string returnString = "";
std::ostringstream oss;
oss << map.map_width << " " << map.map_height << " ";
// Run-length encode of owners
unsigned short currentOwner = map.contents[0][0].owner;
unsigned short counter = 0;
for (int a = 0; a < map.contents.size(); ++a)
{
for (int b = 0; b < map.contents[a].size(); ++b)
{
if (map.contents[a][b].owner == currentOwner)
{
counter++;
}
else
{
oss << (unsigned short)counter << " " << (unsigned short)currentOwner << " ";
counter = 1;
currentOwner = map.contents[a][b].owner;
}
}
}
// Place the last run into the string
oss << (unsigned short)counter << " " << (unsigned short)currentOwner << " ";
// Encoding of ages
for (int a = 0; a < map.contents.size(); ++a)
{
for (int b = 0; b < map.contents[a].size(); ++b)
{
oss << (unsigned short)map.contents[a][b].strength << " ";
}
}
returnString = oss.str();
return returnString;
}
std::set<hlt::Move> EnvironmentNetworking::deserializeMoveSet(std::string & inputString)
{
std::set<hlt::Move> moves = std::set<hlt::Move>();
std::stringstream iss(inputString);
hlt::Location l;
int d;
while (iss >> l.x >> l.y >> d) moves.insert({ l, (unsigned char)d });
return moves;
}
std::string EnvironmentNetworking::serializeMessages(const std::vector<hlt::Message> &messages) {
std::ostringstream oss;
oss << messages.size() << " ";
for (int a = 0; a < messages.size(); a++)
{
hlt::Message message = messages[a];
oss << (unsigned short)message.type << " ";
oss << message.senderID << " " << message.recipientID << " " << message.targetID << " ";
}
return oss.str();
}
std::vector<hlt::Message> EnvironmentNetworking::deserializeMessages(const std::string &inputString)
{
std::vector<hlt::Message> messages = std::vector<hlt::Message>();
std::stringstream iss(inputString);
int numberOfMessages;
iss >> numberOfMessages;
for (int a = 0; a < numberOfMessages; a++)
{
hlt::Message message;
int messageTypeInt;
iss >> messageTypeInt;
message.type = static_cast<hlt::MessageType>(messageTypeInt);
iss >> message.senderID >> message.recipientID >> message.targetID;
messages.push_back(message);
}
return messages;
}
void EnvironmentNetworking::sendString(unsigned char playerTag, const std::string &sendString)
{
#ifdef _WIN32
#else
int connectionFd = connections[playerTag - 1];
uint32_t length = sendString.length();
// Copy the string into a buffer. May want to get rid of this operation for performance purposes
std::vector<char> buffer(sendString.begin(), sendString.end());
send(connectionFd, (char *)&length, sizeof(length), 0);
send(connectionFd, &buffer[0], buffer.size(), 0);
#endif
}
std::string EnvironmentNetworking::getString(unsigned char playerTag)
{
#ifdef _WIN32
#else
int connectionFd = connections[playerTag - 1];
uint32_t numChars;
recv(connectionFd, (char *)&numChars, sizeof(numChars), 0);
std::vector<char> buffer(numChars);
recv(connectionFd, &buffer[0], buffer.size(), 0);
// Copy the buffer into a string. May want to get rid of this for performance purposes
return std::string(buffer.begin(), buffer.end());
//return "Done";
#endif
}
void EnvironmentNetworking::createAndConnectSocket(int port)
{
#ifdef _WIN32
// stdin write - write to this
// stdout read - read from this
Connection connection;
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
bool success = CreateProcess(NULL,
"../Debug/ExampleBot.exe", // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
0, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
#else
std::cout << "Waiting for player to connect on port " << port << ".\n";
int socketFd = socket(AF_INET, SOCK_STREAM, 0);
if (socketFd < 0)
{
std::cout << "ERROR opening socket\n";
throw 1;
}
struct sockaddr_in serverAddr;
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(port);
if (bind(socketFd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0)
{
std::cout << "ERROR on binding to port number " << port << "\n";
throw 1;
}
listen(socketFd, 5);
struct sockaddr_in clientAddr;
socklen_t clientLength = sizeof(clientAddr);
int connectionFd = accept(socketFd, (struct sockaddr *)&clientAddr, &clientLength);
if (connectionFd < 0)
{
std::cout << "ERROR on accepting\n";
throw 1;
}
std::cout << "Connected.\n";
connections.push_back(connectionFd);
#endif
}
double EnvironmentNetworking::handleInitNetworking(unsigned char playerTag, std::string name, hlt::Map & m)
{
sendString(playerTag, std::to_string(playerTag));
sendString(playerTag, serializeMap(m));
std::string str = "Init Message sent to player " + name + "\n";
std::cout << str;
std::string receiveString = "";
clock_t initialTime = clock();
receiveString = getString(playerTag);
str = "Init Message received from player " + name + "\n";
std::cout << str;
clock_t finalTime = clock() - initialTime;
double timeElapsed = float(finalTime) / CLOCKS_PER_SEC;
if (receiveString != "Done") return FLT_MAX;
return timeElapsed;
}
double EnvironmentNetworking::handleFrameNetworking(unsigned char playerTag, const hlt::Map & m, const std::vector<hlt::Message> &messagesForThisBot, std::set<hlt::Move> * moves, std::vector<hlt::Message> * messagesFromThisBot)
{
// Send this bot the game map and the messages addressed to this bot
sendString(playerTag, serializeMap(m));
sendString(playerTag, serializeMessages(messagesForThisBot));
moves->clear();
clock_t initialTime = clock();
*moves = deserializeMoveSet(getString(playerTag));
*messagesFromThisBot = deserializeMessages(getString(playerTag));
clock_t finalTime = clock() - initialTime;
double timeElapsed = float(finalTime) / CLOCKS_PER_SEC;
return timeElapsed;
}
<commit_msg>Server windows networking<commit_after>#include "EnvironmentNetworking.h"
#include <time.h>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <stdio.h>
#ifdef _WIN32
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#else
#include <sys/socket.h>
#include <arpa/inet.h>
#include <time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#endif
std::string EnvironmentNetworking::serializeMap(const hlt::Map & map)
{
std::string returnString = "";
std::ostringstream oss;
oss << map.map_width << " " << map.map_height << " ";
// Run-length encode of owners
unsigned short currentOwner = map.contents[0][0].owner;
unsigned short counter = 0;
for (int a = 0; a < map.contents.size(); ++a)
{
for (int b = 0; b < map.contents[a].size(); ++b)
{
if (map.contents[a][b].owner == currentOwner)
{
counter++;
}
else
{
oss << (unsigned short)counter << " " << (unsigned short)currentOwner << " ";
counter = 1;
currentOwner = map.contents[a][b].owner;
}
}
}
// Place the last run into the string
oss << (unsigned short)counter << " " << (unsigned short)currentOwner << " ";
// Encoding of ages
for (int a = 0; a < map.contents.size(); ++a)
{
for (int b = 0; b < map.contents[a].size(); ++b)
{
oss << (unsigned short)map.contents[a][b].strength << " ";
}
}
returnString = oss.str();
return returnString;
}
std::set<hlt::Move> EnvironmentNetworking::deserializeMoveSet(std::string & inputString)
{
std::set<hlt::Move> moves = std::set<hlt::Move>();
std::stringstream iss(inputString);
hlt::Location l;
int d;
while (iss >> l.x >> l.y >> d) moves.insert({ l, (unsigned char)d });
return moves;
}
std::string EnvironmentNetworking::serializeMessages(const std::vector<hlt::Message> &messages) {
std::ostringstream oss;
oss << messages.size() << " ";
for (int a = 0; a < messages.size(); a++)
{
hlt::Message message = messages[a];
oss << (unsigned short)message.type << " ";
oss << message.senderID << " " << message.recipientID << " " << message.targetID << " ";
}
return oss.str();
}
std::vector<hlt::Message> EnvironmentNetworking::deserializeMessages(const std::string &inputString)
{
std::vector<hlt::Message> messages = std::vector<hlt::Message>();
std::stringstream iss(inputString);
int numberOfMessages;
iss >> numberOfMessages;
for (int a = 0; a < numberOfMessages; a++)
{
hlt::Message message;
int messageTypeInt;
iss >> messageTypeInt;
message.type = static_cast<hlt::MessageType>(messageTypeInt);
iss >> message.senderID >> message.recipientID >> message.targetID;
messages.push_back(message);
}
return messages;
}
void EnvironmentNetworking::sendString(unsigned char playerTag, const std::string &sendString)
{
#ifdef _WIN32
Connection connection = connections[playerTag - 1];
uint32_t length = sendString.length();
// Copy the string into a buffer. May want to get rid of this operation for performance purposes
std::vector<char> buffer(sendString.begin(), sendString.end());
DWORD charsWritten;
bool success;
success = WriteFile(connection.write, (char *)&length, sizeof(length), &charsWritten, NULL);
if (!success || charsWritten == 0) {
std::cout << "problem writing\n";
throw 1;
}
success = WriteFile(connection.write, &buffer[0], buffer.size(), &charsWritten, NULL);
if (!success || charsWritten == 0) {
std::cout << "problem writing\n";
throw 1;
}
#else
int connectionFd = connections[playerTag - 1];
uint32_t length = sendString.length();
// Copy the string into a buffer. May want to get rid of this operation for performance purposes
std::vector<char> buffer(sendString.begin(), sendString.end());
send(connectionFd, (char *)&length, sizeof(length), 0);
send(connectionFd, &buffer[0], buffer.size(), 0);
#endif
}
std::string EnvironmentNetworking::getString(unsigned char playerTag)
{
#ifdef _WIN32
Connection connection = connections[playerTag - 1];
DWORD charsRead;
bool success;
uint32_t numChars;
ReadFile(connection.read, (char *)&numChars, sizeof(numChars), &charsRead, NULL);
if (!success || charsRead == 0)
{
std::cout << "problem reading\n";
throw 1;
}
if (charsRead < sizeof(numChars))
{
std::cout << "Read too little. Read " << charsRead << " of " << sizeof(numChars) << "\n";
throw 1;
}
std::vector<char> buffer(numChars);
ReadFile(connection.read, &buffer[0], buffer.size(), &charsRead, NULL);
if (!success || charsRead == 0)
{
std::cout << "problem reading\n";
throw 1;
}
if (charsRead < buffer.size())
{
std::cout << "Read too little. Read " << charsRead << " of " << buffer.size() << "\n";
throw 1;
}
// Copy the buffer into a string. May want to get rid of this for performance purposes
return std::string(buffer.begin(), buffer.end());
#else
int connectionFd = connections[playerTag - 1];
uint32_t numChars;
recv(connectionFd, (char *)&numChars, sizeof(numChars), 0);
std::vector<char> buffer(numChars);
recv(connectionFd, &buffer[0], buffer.size(), 0);
// Copy the buffer into a string. May want to get rid of this for performance purposes
return std::string(buffer.begin(), buffer.end());
//return "Done";
#endif
}
void EnvironmentNetworking::createAndConnectSocket(int port)
{
#ifdef _WIN32
// stdin write - write to this
// stdout read - read from this
Connection parentConnection, childConnection;
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
// Child stdout pipe
if (!CreatePipe(&parentConnection.read, &childConnection.write, &saAttr, 0))
{
std::cout << "Could not create pipe\n";
throw 1;
}
if (!SetHandleInformation(parentConnection.read, HANDLE_FLAG_INHERIT, 0)) throw 1;
// Child stdin pipe
if (!CreatePipe(&childConnection.read, &parentConnection.write, &saAttr, 0))
{
std::cout << "Could not create pipe\n";
throw 1;
}
if (!SetHandleInformation(parentConnection.write, HANDLE_FLAG_INHERIT, 0)) throw 1;
// MAKE SURE THIS MEMORY IS ERASED
PROCESS_INFORMATION piProcInfo;
ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
STARTUPINFO siStartInfo;
ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdError = childConnection.write;
siStartInfo.hStdOutput = childConnection.write;
siStartInfo.hStdInput = childConnection.read;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
bool success = CreateProcess(
NULL,
"../Debug/ExampleBot.exe", // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
0, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo
); // receives PROCESS_INFORMATION
if(!success)
{
std::cout << "Could not start process\n";
throw 1;
}
else
{
CloseHandle(piProcInfo.hProcess);
CloseHandle(piProcInfo.hThread);
connections.push_back(parentConnection);
}
#else
std::cout << "Waiting for player to connect on port " << port << ".\n";
int socketFd = socket(AF_INET, SOCK_STREAM, 0);
if (socketFd < 0)
{
std::cout << "ERROR opening socket\n";
throw 1;
}
struct sockaddr_in serverAddr;
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(port);
if (bind(socketFd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0)
{
std::cout << "ERROR on binding to port number " << port << "\n";
throw 1;
}
listen(socketFd, 5);
struct sockaddr_in clientAddr;
socklen_t clientLength = sizeof(clientAddr);
int connectionFd = accept(socketFd, (struct sockaddr *)&clientAddr, &clientLength);
if (connectionFd < 0)
{
std::cout << "ERROR on accepting\n";
throw 1;
}
std::cout << "Connected.\n";
connections.push_back(connectionFd);
#endif
}
double EnvironmentNetworking::handleInitNetworking(unsigned char playerTag, std::string name, hlt::Map & m)
{
sendString(playerTag, std::to_string(playerTag));
sendString(playerTag, serializeMap(m));
std::string str = "Init Message sent to player " + name + "\n";
std::cout << str;
std::string receiveString = "";
clock_t initialTime = clock();
receiveString = getString(playerTag);
str = "Init Message received from player " + name + "\n";
std::cout << str;
clock_t finalTime = clock() - initialTime;
double timeElapsed = float(finalTime) / CLOCKS_PER_SEC;
if (receiveString != "Done") return FLT_MAX;
return timeElapsed;
}
double EnvironmentNetworking::handleFrameNetworking(unsigned char playerTag, const hlt::Map & m, const std::vector<hlt::Message> &messagesForThisBot, std::set<hlt::Move> * moves, std::vector<hlt::Message> * messagesFromThisBot)
{
// Send this bot the game map and the messages addressed to this bot
sendString(playerTag, serializeMap(m));
sendString(playerTag, serializeMessages(messagesForThisBot));
moves->clear();
clock_t initialTime = clock();
*moves = deserializeMoveSet(getString(playerTag));
*messagesFromThisBot = deserializeMessages(getString(playerTag));
clock_t finalTime = clock() - initialTime;
double timeElapsed = float(finalTime) / CLOCKS_PER_SEC;
return timeElapsed;
}
<|endoftext|>
|
<commit_before>// ------------------------------------------------------------------
// pion-platform: a C++ framework for building lightweight HTTP interfaces
// ------------------------------------------------------------------
// Copyright (C) 2007 Atomic Labs, Inc. (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file COPYING or copy at http://www.boost.org/LICENSE_1_0.txt
//
#ifndef _MSC_VER
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#endif
#include <iostream>
#include "PlatformConfig.hpp"
#include "../../net/utils/ShutdownManager.hpp"
using namespace std;
using namespace pion;
using namespace pion::net;
using namespace pion::platform;
using namespace pion::server;
// some forward declarations of functions used by main()
void daemonize_server(void);
void argument_error(void);
/// main control function
int main (int argc, char *argv[])
{
// get platform config file
bool verbose_logging = false;
bool run_as_daemon = false;
std::string platform_config_file("/etc/pion/platform.xml");
for (int argnum=1; argnum < argc; ++argnum) {
if (argv[argnum][0] == '-') {
if (argv[argnum][1] == 'v') {
verbose_logging = true;
} if (argv[argnum][1] == 'D') {
run_as_daemon = true;
} else if (argv[argnum][1] == 'c' && argv[argnum][2] == '\0' && argnum+1 < argc) {
platform_config_file = argv[++argnum];
} else {
argument_error();
return 1;
}
} else {
argument_error();
return 1;
}
}
/// become a daemon if the -D option is given
if (run_as_daemon)
daemonize_server();
// setup signal handler
#ifdef PION_WIN32
SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
#else
signal(SIGCHLD, SIG_IGN);
signal(SIGTSTP, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
signal(SIGHUP, SIG_IGN);
signal(SIGINT, handle_signal);
signal(SIGTERM, handle_signal);
#endif
// initialize log system (use simple configuration)
PionLogger pion_log(PION_GET_LOGGER("pion"));
if (verbose_logging) {
PION_LOG_SETLEVEL_DEBUG(pion_log);
} else {
PION_LOG_SETLEVEL_INFO(pion_log);
}
PION_LOG_CONFIG_BASIC;
PlatformConfig platform_cfg;
try {
// load the platform configuration
platform_cfg.setConfigFile(platform_config_file);
platform_cfg.openConfigFile();
// start the ReactionEngine
platform_cfg.getReactionEngine().start();
PION_LOG_INFO(pion_log, "Pion has started successfully");
// wait for shutdown
main_shutdown_manager.wait();
} catch (std::exception& e) {
PION_LOG_FATAL(pion_log, e.what());
}
PION_LOG_INFO(pion_log, "Pion is shutting down");
return 0;
}
/// run server as a daemon
void daemonize_server(void)
{
#ifndef _MSC_VER
// adopted from "Unix Daemon Server Programming"
// http://www.enderunix.org/docs/eng/daemon.php
// return early if already running as a daemon
if(getppid()==1) return;
// for out the process
int i = fork();
if (i<0) exit(1); // error forking
if (i>0) exit(0); // exit if parent
// child (daemon process) continues here after the fork...
// obtain a new process group
setsid();
// close all descriptors
for (i=getdtablesize();i>=0;--i) close(i);
// bind stdio to /dev/null
i=open("/dev/null",O_RDWR); dup(i); dup(i);
// restrict file creation mode to 0750
umask(027);
#endif
}
/// displays an error message if the arguments are invalid
void argument_error(void)
{
std::cerr << "usage: pion [-c SERVICE_CONFIG_FILE] [-D] [-v]" << std::endl;
}
<commit_msg>Removed 'verbose' command line option. (There was a bug in it, but after talking with Mike, it seemed best to just remove it, now that a logging configuration file is being used.)<commit_after>// ------------------------------------------------------------------
// pion-platform: a C++ framework for building lightweight HTTP interfaces
// ------------------------------------------------------------------
// Copyright (C) 2007 Atomic Labs, Inc. (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file COPYING or copy at http://www.boost.org/LICENSE_1_0.txt
//
#ifndef _MSC_VER
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#endif
#include <iostream>
#include "PlatformConfig.hpp"
#include "../../net/utils/ShutdownManager.hpp"
using namespace std;
using namespace pion;
using namespace pion::net;
using namespace pion::platform;
using namespace pion::server;
// some forward declarations of functions used by main()
void daemonize_server(void);
void argument_error(void);
/// main control function
int main (int argc, char *argv[])
{
// get platform config file
bool run_as_daemon = false;
std::string platform_config_file("/etc/pion/platform.xml");
for (int argnum=1; argnum < argc; ++argnum) {
if (argv[argnum][0] == '-') {
if (argv[argnum][1] == 'D') {
run_as_daemon = true;
} else if (argv[argnum][1] == 'c' && argv[argnum][2] == '\0' && argnum+1 < argc) {
platform_config_file = argv[++argnum];
} else {
argument_error();
return 1;
}
} else {
argument_error();
return 1;
}
}
/// become a daemon if the -D option is given
if (run_as_daemon)
daemonize_server();
// setup signal handler
#ifdef PION_WIN32
SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
#else
signal(SIGCHLD, SIG_IGN);
signal(SIGTSTP, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
signal(SIGHUP, SIG_IGN);
signal(SIGINT, handle_signal);
signal(SIGTERM, handle_signal);
#endif
// initialize log system (use simple configuration)
PionLogger pion_log(PION_GET_LOGGER("pion"));
// This level might be overridden if there is a LogConfig file specified in the platform
// configuration (and if using a logging library that supports logging configuration.)
PION_LOG_SETLEVEL_INFO(pion_log);
PION_LOG_CONFIG_BASIC;
PlatformConfig platform_cfg;
try {
// load the platform configuration
platform_cfg.setConfigFile(platform_config_file);
platform_cfg.openConfigFile();
// start the ReactionEngine
platform_cfg.getReactionEngine().start();
PION_LOG_INFO(pion_log, "Pion has started successfully");
// wait for shutdown
main_shutdown_manager.wait();
} catch (std::exception& e) {
PION_LOG_FATAL(pion_log, e.what());
}
PION_LOG_INFO(pion_log, "Pion is shutting down");
return 0;
}
/// run server as a daemon
void daemonize_server(void)
{
#ifndef _MSC_VER
// adopted from "Unix Daemon Server Programming"
// http://www.enderunix.org/docs/eng/daemon.php
// return early if already running as a daemon
if(getppid()==1) return;
// for out the process
int i = fork();
if (i<0) exit(1); // error forking
if (i>0) exit(0); // exit if parent
// child (daemon process) continues here after the fork...
// obtain a new process group
setsid();
// close all descriptors
for (i=getdtablesize();i>=0;--i) close(i);
// bind stdio to /dev/null
i=open("/dev/null",O_RDWR); dup(i); dup(i);
// restrict file creation mode to 0750
umask(027);
#endif
}
/// displays an error message if the arguments are invalid
void argument_error(void)
{
std::cerr << "usage: pion [-c SERVICE_CONFIG_FILE] [-D] [-v]" << std::endl;
}
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File: NekManager.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description:
//
///////////////////////////////////////////////////////////////////////////////
#ifndef NEKTAR_LIB_UTILITIES_BASIC_UTILS_NEK_MANAGER_HPP
#define NEKTAR_LIB_UTILITIES_BASIC_UTILS_NEK_MANAGER_HPP
#include <utility>
#include <vector>
#include <algorithm>
#include <map>
#include <functional> // for bind1st
#include <iostream>
#include <boost/mem_fn.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/call_traits.hpp>
#include <LibUtilities/BasicUtils/ErrorUtil.hpp>
using namespace std;
template <typename keyT, typename valueT,
typename valueContainer = std::map<keyT, valueT>,
typename creatorContainer = std::map<keyT, boost::function<valueT (const keyT& key)> > >
class NekManager
{
public:
typedef boost::function<valueT (const keyT& key)> CreateFunc;
NekManager() :
m_Values(),
m_CreateFuncs()
{
};
~NekManager() {}
void RegisterCreator(typename boost::call_traits<keyT>::const_reference key,
const CreateFunc& createFunc)
{
m_CreateFuncs[key] = createFunc;
}
void AddValue(typename boost::call_traits<keyT>::const_reference key,
typename boost::call_traits<valueT>::const_reference value)
{
typename valueContainer::iterator found = m_Values.find(key);
if( found == m_Values.end() )
{
m_Values[key] = value;
}
else
{
std::string errorMessage = "Adding an object for key " +
boost::lexical_cast<std::string>(key) +
" to a NekManager, but a value for this key already exists.";
throw std::runtime_error(errorMessage);
}
}
typename boost::call_traits<valueT>::reference
GetValue(typename boost::call_traits<keyT>::const_reference key)
{
typename valueContainer::iterator found = m_Values.find(key);
if( found == m_Values.end() )
{
// No object, create a new one.
typename creatorContainer::iterator keyFound = m_CreateFuncs.find(key);
if( keyFound != m_CreateFuncs.end() )
{
valueT newObj = (*keyFound).second(key);
m_Values[key] = newObj;
return m_Values[key];
}
else
{
std::string errorMessage = "Attempting to obtain an object for key " +
boost::lexical_cast<std::string>(key) +
" in a NekManager but no create function has been registered";
throw std::runtime_error(errorMessage);
}
}
else
{
return (*found).second;
}
}
private:
NekManager(const NekManager<keyT, valueT, valueContainer, creatorContainer>& rhs);
NekManager<keyT, valueT, valueContainer, creatorContainer>& operator=(const NekManager<keyT, valueT, valueContainer, creatorContainer>& rhs);
valueContainer m_Values;
creatorContainer m_CreateFuncs;
};
#endif //NEKTAR_LIB_UTILITIES_BASIC_UTILS_NEK_MANAGER_HPP
<commit_msg>Added a global create function - the key specific create function is now an optional feature.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File: NekManager.hpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description:
//
///////////////////////////////////////////////////////////////////////////////
#ifndef NEKTAR_LIB_UTILITIES_BASIC_UTILS_NEK_MANAGER_HPP
#define NEKTAR_LIB_UTILITIES_BASIC_UTILS_NEK_MANAGER_HPP
#include <algorithm>
#include <map>
#include <boost/function.hpp>
#include <boost/call_traits.hpp>
#include <LibUtilities/BasicUtils/ErrorUtil.hpp>
using namespace std;
template<typename KeyType, typename ValueType>
class NekManagerCreator
{
public:
ValueType operator()(const KeyType& key)
{
return ValueType::Create(key);
}
};
template <typename KeyType, typename ValueType>
class NekManager
{
public:
typedef boost::function<ValueType (const KeyType& key)> CreateFuncType;
typedef std::map<KeyType, ValueType> ValueContainer;
typedef std::map<KeyType, CreateFuncType> CreateFuncContainer;
NekManager() :
m_values(),
m_globalCreateFunc(NekManagerCreator<KeyType, ValueType>()),
m_keySpecificCreateFuncs()
{
};
explicit NekManager(CreateFuncType f) :
m_values(),
m_globalCreateFunc(f),
m_keySpecificCreateFuncs()
{
}
~NekManager() {}
void RegisterCreator(typename boost::call_traits<KeyType>::const_reference key,
const CreateFuncType& createFunc)
{
m_keySpecificCreateFuncs[key] = createFunc;
}
ValueType& operator[](typename boost::call_traits<KeyType>::const_reference key)
{
typename ValueContainer::iterator found = m_values.find(key);
if( found != m_values.end() )
{
return (*found).second;
}
else
{
// No object, create a new one.
CreateFuncType f = m_globalCreateFunc;
typename CreateFuncContainer::iterator keyFound = m_keySpecificCreateFuncs.find(key);
if( keyFound != m_keySpecificCreateFuncs.end() )
{
f = (*keyFound).second;
}
ValueType newObj = f(key);
m_values[key] = newObj;
return m_values[key];
}
}
private:
NekManager(const NekManager<KeyType, ValueType>& rhs);
NekManager<KeyType, ValueType>& operator=(const NekManager<KeyType, ValueType>& rhs);
ValueContainer m_values;
CreateFuncType m_globalCreateFunc;
CreateFuncContainer m_keySpecificCreateFuncs;
};
#endif //NEKTAR_LIB_UTILITIES_BASIC_UTILS_NEK_MANAGER_HPP
<|endoftext|>
|
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2019, Hamburg University
* 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 Hamburg University nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Jonas Tietz */
#include "tf_publisher_capability.h"
#include <moveit/utils/message_checks.h>
#include <moveit/move_group/capability_names.h>
#include <tf2_ros/transform_broadcaster.h>
#include <tf2_eigen/tf2_eigen.h>
#include <moveit/robot_state/robot_state.h>
#include <moveit/robot_state/attached_body.h>
namespace move_group
{
TfPublisher::TfPublisher() : MoveGroupCapability("TfPublisher")
{
}
TfPublisher::~TfPublisher()
{
keep_running_ = false;
thread_.join();
}
namespace
{
void publishSubframes(tf2_ros::TransformBroadcaster& broadcaster, const moveit::core::FixedTransformsMap& subframes,
const std::string& parent_object, const std::string& parent_frame, const ros::Time& stamp)
{
geometry_msgs::TransformStamped transform;
for (auto& subframe : subframes)
{
transform = tf2::eigenToTransform(subframe.second);
transform.child_frame_id = parent_object + "/" + subframe.first;
transform.header.stamp = stamp;
transform.header.frame_id = parent_frame;
broadcaster.sendTransform(transform);
}
}
} // namespace
void TfPublisher::publishPlanningSceneFrames()
{
tf2_ros::TransformBroadcaster broadcaster;
geometry_msgs::TransformStamped transform;
ros::Rate rate(rate_);
while (keep_running_)
{
{
ros::Time stamp = ros::Time::now();
planning_scene_monitor::LockedPlanningSceneRO locked_planning_scene(context_->planning_scene_monitor_);
collision_detection::WorldConstPtr world = locked_planning_scene->getWorld();
std::string planning_frame = locked_planning_scene->getPlanningFrame();
for (const auto& obj : *world)
{
std::string object_frame = prefix_ + obj.second->id_;
transform = tf2::eigenToTransform(obj.second->shape_poses_[0]);
transform.child_frame_id = object_frame;
transform.header.stamp = stamp;
transform.header.frame_id = planning_frame;
broadcaster.sendTransform(transform);
const moveit::core::FixedTransformsMap& subframes = obj.second->subframe_poses_;
publishSubframes(broadcaster, subframes, object_frame, planning_frame, stamp);
}
const moveit::core::RobotState& rs = locked_planning_scene->getCurrentState();
std::vector<const moveit::core::AttachedBody*> attached_collision_objects;
rs.getAttachedBodies(attached_collision_objects);
for (const moveit::core::AttachedBody* attached_body : attached_collision_objects)
{
std::string object_frame = prefix_ + attached_body->getName();
transform = tf2::eigenToTransform(attached_body->getFixedTransforms()[0]);
transform.child_frame_id = object_frame;
transform.header.stamp = stamp;
transform.header.frame_id = attached_body->getAttachedLinkName();
broadcaster.sendTransform(transform);
const moveit::core::FixedTransformsMap& subframes = attached_body->getSubframeTransforms();
publishSubframes(broadcaster, subframes, object_frame, object_frame, stamp);
}
}
rate.sleep();
}
}
void TfPublisher::initialize()
{
ros::NodeHandle nh = ros::NodeHandle("~");
std::string prefix = nh.getNamespace() + "/";
nh.param("planning_scene_frame_publishing_rate", rate_, 10);
nh.param("planning_scene_tf_prefix", prefix_, prefix);
keep_running_ = true;
ROS_INFO("Initializing MoveGroupTfPublisher with a frame publishing rate of %d", rate_);
thread_ = std::thread(&TfPublisher::publishPlanningSceneFrames, this);
}
} // namespace move_group
#include <class_loader/class_loader.hpp>
CLASS_LOADER_REGISTER_CLASS(move_group::TfPublisher, move_group::MoveGroupCapability)
<commit_msg>fixup! Fix TfPublisher subframe publishing<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2019, Hamburg University
* 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 Hamburg University nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Jonas Tietz */
#include "tf_publisher_capability.h"
#include <moveit/utils/message_checks.h>
#include <moveit/move_group/capability_names.h>
#include <tf2_ros/transform_broadcaster.h>
#include <tf2_eigen/tf2_eigen.h>
#include <moveit/robot_state/robot_state.h>
#include <moveit/robot_state/attached_body.h>
namespace move_group
{
TfPublisher::TfPublisher() : MoveGroupCapability("TfPublisher")
{
}
TfPublisher::~TfPublisher()
{
keep_running_ = false;
thread_.join();
}
namespace
{
void publishSubframes(tf2_ros::TransformBroadcaster& broadcaster, const moveit::core::FixedTransformsMap& subframes,
const std::string& parent_object, const std::string& parent_frame, const ros::Time& stamp)
{
geometry_msgs::TransformStamped transform;
for (auto& subframe : subframes)
{
transform = tf2::eigenToTransform(subframe.second);
transform.child_frame_id = parent_object + "/" + subframe.first;
transform.header.stamp = stamp;
transform.header.frame_id = parent_frame;
broadcaster.sendTransform(transform);
}
}
} // namespace
void TfPublisher::publishPlanningSceneFrames()
{
tf2_ros::TransformBroadcaster broadcaster;
geometry_msgs::TransformStamped transform;
ros::Rate rate(rate_);
while (keep_running_)
{
{
ros::Time stamp = ros::Time::now();
planning_scene_monitor::LockedPlanningSceneRO locked_planning_scene(context_->planning_scene_monitor_);
collision_detection::WorldConstPtr world = locked_planning_scene->getWorld();
std::string planning_frame = locked_planning_scene->getPlanningFrame();
for (const auto& obj : *world)
{
std::string object_frame = prefix_ + obj.second->id_;
transform = tf2::eigenToTransform(obj.second->shape_poses_[0]);
transform.child_frame_id = object_frame;
transform.header.stamp = stamp;
transform.header.frame_id = planning_frame;
broadcaster.sendTransform(transform);
const moveit::core::FixedTransformsMap& subframes = obj.second->subframe_poses_;
publishSubframes(broadcaster, subframes, object_frame, planning_frame, stamp);
}
const moveit::core::RobotState& rs = locked_planning_scene->getCurrentState();
std::vector<const moveit::core::AttachedBody*> attached_collision_objects;
rs.getAttachedBodies(attached_collision_objects);
for (const moveit::core::AttachedBody* attached_body : attached_collision_objects)
{
std::string object_frame = prefix_ + attached_body->getName();
transform = tf2::eigenToTransform(attached_body->getFixedTransforms()[0]);
transform.child_frame_id = object_frame;
transform.header.stamp = stamp;
transform.header.frame_id = attached_body->getAttachedLinkName();
broadcaster.sendTransform(transform);
const moveit::core::FixedTransformsMap& subframes = attached_body->getSubframeTransforms();
publishSubframes(broadcaster, subframes, object_frame, attached_body->getAttachedLinkName(), stamp);
}
}
rate.sleep();
}
}
void TfPublisher::initialize()
{
ros::NodeHandle nh = ros::NodeHandle("~");
std::string prefix = nh.getNamespace() + "/";
nh.param("planning_scene_frame_publishing_rate", rate_, 10);
nh.param("planning_scene_tf_prefix", prefix_, prefix);
keep_running_ = true;
ROS_INFO("Initializing MoveGroupTfPublisher with a frame publishing rate of %d", rate_);
thread_ = std::thread(&TfPublisher::publishPlanningSceneFrames, this);
}
} // namespace move_group
#include <class_loader/class_loader.hpp>
CLASS_LOADER_REGISTER_CLASS(move_group::TfPublisher, move_group::MoveGroupCapability)
<|endoftext|>
|
<commit_before>#include "P3dSymLoader.h"
#include "FilepathHelper.h"
#include "JsonSerializer.h"
#include "Exception.h"
#include "SymbolFactory.h"
#include <sm_const.h>
#include <ps_3d.h>
#include <sprite2/Particle3dSymbol.h>
#include <fstream>
namespace gum
{
void P3dSymLoader::Store(s2::Particle3dSymbol* sym) const
{
int sz = SIZEOF_P3D_EMITTER_CFG + SIZEOF_P3D_SYMBOL * components.size();
p3d_emitter_cfg* cfg = (p3d_emitter_cfg*) operator new(sz);
memset(cfg, 0, sz);
Store(cfg);
sym->SetEmitterCfg(cfg);
sym->SetLoop(loop);
sym->SetLocal(local);
}
void P3dSymLoader::Store(p3d_emitter_cfg* cfg) const
{
cfg->blend = blend;
cfg->static_mode = static_mode;
cfg->emission_time = emission_time;
cfg->count = count;
cfg->life = life * 0.001f;
cfg->life_var = life_var * 0.001f;
cfg->hori = hori;
cfg->hori_var = hori_var;
cfg->vert = vert;
cfg->vert_var = vert_var;
cfg->radial_spd = radial_spd;
cfg->radial_spd_var = radial_spd_var;
cfg->tangential_spd = tangential_spd;
cfg->tangential_spd_var = tangential_spd_var;
cfg->angular_spd = angular_spd;
cfg->angular_spd_var = angular_spd_var;
cfg->dis_region = dis_region;
cfg->dis_region_var = dis_region_var;
cfg->dis_spd = dis_spd;
cfg->dis_spd_var = dis_spd_var;
cfg->gravity = gravity;
cfg->linear_acc = linear_acc;
cfg->linear_acc_var = linear_acc_var;
cfg->fadeout_time = fadeout_time;
cfg->ground = ground;
cfg->start_radius = start_radius;
cfg->start_height = start_height;
cfg->orient_to_movement = orient_to_movement;
cfg->blend = blend;
// todo dir
cfg->dir.x = 0;
cfg->dir.y = 0;
cfg->dir.z = 1;
cfg->sym_count = components.size();
cfg->syms = (p3d_symbol*)(cfg+1);
for (int i = 0, n = components.size(); i < n; ++i) {
const P3dSymLoader::Component& src = components[i];
p3d_symbol& dst = cfg->syms[i];
dst.count = src.count;
dst.scale_start = src.scale_start * 0.01f;
dst.scale_end = src.scale_end * 0.01f;
dst.angle = src.angle;
dst.angle_var = src.angle_var;
memcpy(&dst.mul_col_begin.r, &src.mul_col_begin.r, sizeof(dst.mul_col_begin));
memcpy(&dst.mul_col_end.r, &src.mul_col_end.r, sizeof(dst.mul_col_end));
memcpy(&dst.add_col_begin.r, &src.add_col_begin.r, sizeof(dst.add_col_begin));
memcpy(&dst.add_col_end.r, &src.add_col_end.r, sizeof(dst.add_col_end));
// if (FilepathHelper::IsFileExist(src.bind_filepath)) {
// dst.bind_ps_cfg = PSConfigMgr::Instance()->GetConfig(src.bind_filepath);
// }
dst.ud = LoadSymbol(src.filepath);
if (!dst.ud) {
throw Exception("Symbol doesn't exist: %s", src.filepath.c_str());
}
}
}
void P3dSymLoader::LoadJson(const std::string& filepath)
{
Json::Value val;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, val);
fin.close();
name = val["name"].asString();
loop = val["loop"].asBool();
local = val["local"].asBool();
static_mode = val["static_mode"].asBool();
count = val["count"].asInt();
emission_time = val["emission_time"].asInt() * 0.001f;
if (val.isMember("life")) {
life = static_cast<float>(val["life"]["center"].asInt());
life_var = static_cast<float>(val["life"]["offset"].asInt());
} else {
int min = val["min_life"].asInt(),
max = val["max_life"].asInt();
life = (min + max) * 0.5f;
life_var = (max - min) * 0.5f;
}
int min, max;
min = val["min_hori"].asInt();
max = val["max_hori"].asInt();
hori = (min + max) * 0.5f * SM_DEG_TO_RAD;
hori_var = (max - min) * 0.5f * SM_DEG_TO_RAD;
min = val["min_vert"].asInt();
max = val["max_vert"].asInt();
vert = (min + max) * 0.5f * SM_DEG_TO_RAD;
vert_var = (max - min) * 0.5f * SM_DEG_TO_RAD;
if (val.isMember("radial_speed")) {
radial_spd = static_cast<float>(val["radial_speed"]["center"].asInt());
radial_spd_var = static_cast<float>(val["radial_speed"]["offset"].asInt());
} else if (val.isMember("speed")) {
radial_spd = static_cast<float>(val["speed"]["center"].asInt());
radial_spd_var = static_cast<float>(val["speed"]["offset"].asInt());
} else {
int min, max;
min = val["min_spd"].asInt();
max = val["max_spd"].asInt();
radial_spd = (min + max) * 0.5f;
radial_spd_var = (max - min) * 0.5f;
}
tangential_spd = static_cast<float>(val["tangential_spd"]["center"].asInt());
tangential_spd_var = static_cast<float>(val["tangential_spd"]["offset"].asInt());
// todo
radial_spd *= 0.25f;
radial_spd_var *= 0.25f;
if (val.isMember("angular_speed")) {
angular_spd = val["angular_speed"]["center"].asInt() * SM_DEG_TO_RAD;
angular_spd_var = val["angular_speed"]["offset"].asInt() * SM_DEG_TO_RAD;
} else {
int min, max;
min = val["min_angular_spd"].asInt();
max = val["max_angular_spd"].asInt();
angular_spd = (min + max) * 0.5f * SM_DEG_TO_RAD;
angular_spd_var = (max - min) * 0.5f * SM_DEG_TO_RAD;
}
dis_region = static_cast<float>(val["disturbance_radius"]["center"].asInt());
dis_region_var = static_cast<float>(val["disturbance_radius"]["offset"].asInt());
dis_spd = static_cast<float>(val["disturbance_spd"]["center"].asInt());
dis_spd_var = static_cast<float>(val["disturbance_spd"]["offset"].asInt());
gravity = static_cast<float>(val["gravity"].asInt());
// todo
gravity *= 0.3f;
linear_acc = static_cast<float>(val["linear_acc"]["center"].asInt());
linear_acc_var = static_cast<float>(val["linear_acc"]["offset"].asInt());
inertia = static_cast<float>(val["inertia"].asInt());
fadeout_time = val["fadeout_time"].asInt() * 0.001f;
if (!val.isMember("ground")) {
ground = P3D_GROUND_WITH_BOUNCE;
} else {
ground = val["ground"].asInt();
}
start_radius = abs(static_cast<float>(val["start_pos"]["radius"].asInt()));
start_height = static_cast<float>(val["start_pos"]["height"].asInt());
orient_to_movement = val["orient_to_movement"].asBool();
orient_to_parent = val["orient_to_parent"].asBool();
blend = val["blend"].asInt();
std::string dir = FilepathHelper::Dir(filepath);
for (int i = 0, n = val["components"].size(); i < n; ++i) {
LoadComponent(dir, val["components"][i]);
}
}
void P3dSymLoader::LoadComponent(const std::string& dir, const Json::Value& comp_val)
{
Component comp;
if (!comp_val.isMember("count")) {
comp.count = 0;
} else {
comp.count = comp_val["count"].asInt();
}
comp.filepath = comp_val["filepath"].asString();
comp.filepath = FilepathHelper::Absolute(dir, comp.filepath);
if (comp_val.isMember("bind ps filepath")) {
comp.bind_filepath = comp_val["bind ps filepath"].asString();
if (!comp.bind_filepath.empty()) {
comp.bind_filepath = FilepathHelper::Absolute(dir, comp.bind_filepath);
}
}
comp.name = comp_val["name"].asString();
if (comp_val.isMember("scale")) {
comp.scale_start = comp_val["scale"]["start"].asInt();
comp.scale_end = comp_val["scale"]["end"].asInt();
} else {
comp.scale_start = comp_val["start_scale"].asInt();
comp.scale_end = comp_val["end_scale"].asInt();
}
if (comp_val.isMember("rotate")) {
int min = comp_val["rotate"]["min"].asInt(),
max = comp_val["rotate"]["max"].asInt();
comp.angle = (min + max) * 0.5f;
comp.angle_var = (max - min) * 0.5f;
} else {
comp.angle = comp.angle_var = 0;
}
if (comp_val.isMember("mul_col")) {
comp.mul_col_begin.r = comp_val["mul_col"]["r"].asDouble() * 255;
comp.mul_col_begin.g = comp_val["mul_col"]["g"].asDouble() * 255;
comp.mul_col_begin.b = comp_val["mul_col"]["b"].asDouble() * 255;
comp.mul_col_begin.a = 255;
comp.mul_col_end = comp.mul_col_begin;
} else {
if (comp_val.isMember("mul_col_begin")) {
JsonSerializer::Load(comp_val["mul_col_begin"], comp.mul_col_begin);
} else {
comp.mul_col_begin.r = comp.mul_col_begin.g = comp.mul_col_begin.b = comp.mul_col_begin.a = 255;
}
if (comp_val.isMember("mul_col_end")) {
JsonSerializer::Load(comp_val["mul_col_end"], comp.mul_col_end);
} else {
comp.mul_col_end.r = comp.mul_col_end.g = comp.mul_col_end.b = comp.mul_col_end.a = 255;
}
}
if (comp_val.isMember("add_col")) {
comp.add_col_begin.r = comp_val["add_col"]["r"].asDouble() * 255;
comp.add_col_begin.g = comp_val["add_col"]["g"].asDouble() * 255;
comp.add_col_begin.b = comp_val["add_col"]["b"].asDouble() * 255;
comp.add_col_end = comp.add_col_begin;
} else {
if (comp_val.isMember("add_col_begin")) {
JsonSerializer::Load(comp_val["add_col_begin"], comp.add_col_begin);
} else {
comp.add_col_begin.r = comp.add_col_begin.g = comp.add_col_begin.b = comp.add_col_begin.a = 0;
}
if (comp_val.isMember("add_col_end")) {
JsonSerializer::Load(comp_val["add_col_end"], comp.add_col_end);
} else {
comp.add_col_end.r = comp.add_col_end.g = comp.add_col_end.b = comp.add_col_end.a = 0;
}
}
if (comp_val.isMember("alpha")) {
float start = comp_val["alpha"]["start"].asInt() * 0.01f;
float end = comp_val["alpha"]["end"].asInt() * 0.01f;
comp.mul_col_begin.a *= start;
comp.mul_col_end.a *= end;
comp.alpha_start = 255 * start;
comp.alpha_end = 255 * end;
}
if (comp_val.isMember("alpha2")) {
comp.alpha_start = comp_val["alpha2"]["start"].asInt();
comp.alpha_end = comp_val["alpha2"]["end"].asInt();
}
comp.start_z = comp_val["start_z"].asInt();
components.push_back(comp);
}
s2::Symbol* P3dSymLoader::LoadSymbol(const std::string& filepath) const
{
return SymbolFactory::Instance()->Create(filepath);
}
}<commit_msg>[FIXED] p3d sym loader<commit_after>#include "P3dSymLoader.h"
#include "FilepathHelper.h"
#include "JsonSerializer.h"
#include "Exception.h"
#include "SymbolFactory.h"
#include <sm_const.h>
#include <ps_3d.h>
#include <sprite2/Particle3dSymbol.h>
#include <fstream>
namespace gum
{
void P3dSymLoader::Store(s2::Particle3dSymbol* sym) const
{
int sz = SIZEOF_P3D_EMITTER_CFG + SIZEOF_P3D_SYMBOL * components.size();
p3d_emitter_cfg* cfg = (p3d_emitter_cfg*) operator new(sz);
memset(cfg, 0, sz);
Store(cfg);
sym->SetEmitterCfg(cfg);
sym->SetLoop(loop);
sym->SetLocal(local);
}
void P3dSymLoader::Store(p3d_emitter_cfg* cfg) const
{
cfg->blend = blend;
cfg->static_mode = static_mode;
cfg->emission_time = emission_time;
cfg->count = count;
cfg->life = life * 0.001f;
cfg->life_var = life_var * 0.001f;
cfg->hori = hori;
cfg->hori_var = hori_var;
cfg->vert = vert;
cfg->vert_var = vert_var;
cfg->radial_spd = radial_spd;
cfg->radial_spd_var = radial_spd_var;
cfg->tangential_spd = tangential_spd;
cfg->tangential_spd_var = tangential_spd_var;
cfg->angular_spd = angular_spd;
cfg->angular_spd_var = angular_spd_var;
cfg->dis_region = dis_region;
cfg->dis_region_var = dis_region_var;
cfg->dis_spd = dis_spd;
cfg->dis_spd_var = dis_spd_var;
cfg->gravity = gravity;
cfg->linear_acc = linear_acc;
cfg->linear_acc_var = linear_acc_var;
cfg->fadeout_time = fadeout_time;
cfg->ground = ground;
cfg->start_radius = start_radius;
cfg->start_height = start_height;
cfg->orient_to_movement = orient_to_movement;
cfg->blend = blend;
// todo dir
cfg->dir.x = 0;
cfg->dir.y = 0;
cfg->dir.z = 1;
cfg->sym_count = components.size();
cfg->syms = (p3d_symbol*)(cfg+1);
for (int i = 0, n = components.size(); i < n; ++i) {
const P3dSymLoader::Component& src = components[i];
p3d_symbol& dst = cfg->syms[i];
dst.count = src.count;
dst.scale_start = src.scale_start * 0.01f;
dst.scale_end = src.scale_end * 0.01f;
dst.angle = src.angle * SM_DEG_TO_RAD;
dst.angle_var = src.angle_var * SM_DEG_TO_RAD;
memcpy(&dst.mul_col_begin.r, &src.mul_col_begin.r, sizeof(dst.mul_col_begin));
memcpy(&dst.mul_col_end.r, &src.mul_col_end.r, sizeof(dst.mul_col_end));
memcpy(&dst.add_col_begin.r, &src.add_col_begin.r, sizeof(dst.add_col_begin));
memcpy(&dst.add_col_end.r, &src.add_col_end.r, sizeof(dst.add_col_end));
// if (FilepathHelper::IsFileExist(src.bind_filepath)) {
// dst.bind_ps_cfg = PSConfigMgr::Instance()->GetConfig(src.bind_filepath);
// }
dst.ud = LoadSymbol(src.filepath);
if (!dst.ud) {
throw Exception("Symbol doesn't exist: %s", src.filepath.c_str());
}
}
}
void P3dSymLoader::LoadJson(const std::string& filepath)
{
Json::Value val;
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filepath.c_str());
std::locale::global(std::locale("C"));
reader.parse(fin, val);
fin.close();
name = val["name"].asString();
loop = val["loop"].asBool();
local = val["local"].asBool();
static_mode = val["static_mode"].asBool();
count = val["count"].asInt();
emission_time = val["emission_time"].asInt() * 0.001f;
if (val.isMember("life")) {
life = static_cast<float>(val["life"]["center"].asInt());
life_var = static_cast<float>(val["life"]["offset"].asInt());
} else {
int min = val["min_life"].asInt(),
max = val["max_life"].asInt();
life = (min + max) * 0.5f;
life_var = (max - min) * 0.5f;
}
int min, max;
min = val["min_hori"].asInt();
max = val["max_hori"].asInt();
hori = (min + max) * 0.5f * SM_DEG_TO_RAD;
hori_var = (max - min) * 0.5f * SM_DEG_TO_RAD;
min = val["min_vert"].asInt();
max = val["max_vert"].asInt();
vert = (min + max) * 0.5f * SM_DEG_TO_RAD;
vert_var = (max - min) * 0.5f * SM_DEG_TO_RAD;
if (val.isMember("radial_speed")) {
radial_spd = static_cast<float>(val["radial_speed"]["center"].asInt());
radial_spd_var = static_cast<float>(val["radial_speed"]["offset"].asInt());
} else if (val.isMember("speed")) {
radial_spd = static_cast<float>(val["speed"]["center"].asInt());
radial_spd_var = static_cast<float>(val["speed"]["offset"].asInt());
} else {
int min, max;
min = val["min_spd"].asInt();
max = val["max_spd"].asInt();
radial_spd = (min + max) * 0.5f;
radial_spd_var = (max - min) * 0.5f;
}
tangential_spd = static_cast<float>(val["tangential_spd"]["center"].asInt());
tangential_spd_var = static_cast<float>(val["tangential_spd"]["offset"].asInt());
// todo
radial_spd *= 0.25f;
radial_spd_var *= 0.25f;
if (val.isMember("angular_speed")) {
angular_spd = val["angular_speed"]["center"].asInt() * SM_DEG_TO_RAD;
angular_spd_var = val["angular_speed"]["offset"].asInt() * SM_DEG_TO_RAD;
} else {
int min, max;
min = val["min_angular_spd"].asInt();
max = val["max_angular_spd"].asInt();
angular_spd = (min + max) * 0.5f * SM_DEG_TO_RAD;
angular_spd_var = (max - min) * 0.5f * SM_DEG_TO_RAD;
}
dis_region = static_cast<float>(val["disturbance_radius"]["center"].asInt());
dis_region_var = static_cast<float>(val["disturbance_radius"]["offset"].asInt());
dis_spd = static_cast<float>(val["disturbance_spd"]["center"].asInt());
dis_spd_var = static_cast<float>(val["disturbance_spd"]["offset"].asInt());
gravity = static_cast<float>(val["gravity"].asInt());
// todo
gravity *= 0.3f;
linear_acc = static_cast<float>(val["linear_acc"]["center"].asInt());
linear_acc_var = static_cast<float>(val["linear_acc"]["offset"].asInt());
inertia = static_cast<float>(val["inertia"].asInt());
fadeout_time = val["fadeout_time"].asInt() * 0.001f;
if (!val.isMember("ground")) {
ground = P3D_GROUND_WITH_BOUNCE;
} else {
ground = val["ground"].asInt();
}
start_radius = abs(static_cast<float>(val["start_pos"]["radius"].asInt()));
start_height = static_cast<float>(val["start_pos"]["height"].asInt());
orient_to_movement = val["orient_to_movement"].asBool();
orient_to_parent = val["orient_to_parent"].asBool();
blend = val["blend"].asInt();
std::string dir = FilepathHelper::Dir(filepath);
for (int i = 0, n = val["components"].size(); i < n; ++i) {
LoadComponent(dir, val["components"][i]);
}
}
void P3dSymLoader::LoadComponent(const std::string& dir, const Json::Value& comp_val)
{
Component comp;
if (!comp_val.isMember("count")) {
comp.count = 0;
} else {
comp.count = comp_val["count"].asInt();
}
comp.filepath = comp_val["filepath"].asString();
comp.filepath = FilepathHelper::Absolute(dir, comp.filepath);
if (comp_val.isMember("bind ps filepath")) {
comp.bind_filepath = comp_val["bind ps filepath"].asString();
if (!comp.bind_filepath.empty()) {
comp.bind_filepath = FilepathHelper::Absolute(dir, comp.bind_filepath);
}
}
comp.name = comp_val["name"].asString();
if (comp_val.isMember("scale")) {
comp.scale_start = comp_val["scale"]["start"].asInt();
comp.scale_end = comp_val["scale"]["end"].asInt();
} else {
comp.scale_start = comp_val["start_scale"].asInt();
comp.scale_end = comp_val["end_scale"].asInt();
}
if (comp_val.isMember("rotate")) {
int min = comp_val["rotate"]["min"].asInt(),
max = comp_val["rotate"]["max"].asInt();
comp.angle = (min + max) * 0.5f;
comp.angle_var = (max - min) * 0.5f;
} else {
comp.angle = comp.angle_var = 0;
}
if (comp_val.isMember("mul_col")) {
comp.mul_col_begin.r = comp_val["mul_col"]["r"].asDouble() * 255;
comp.mul_col_begin.g = comp_val["mul_col"]["g"].asDouble() * 255;
comp.mul_col_begin.b = comp_val["mul_col"]["b"].asDouble() * 255;
comp.mul_col_begin.a = 255;
comp.mul_col_end = comp.mul_col_begin;
} else {
if (comp_val.isMember("mul_col_begin")) {
JsonSerializer::Load(comp_val["mul_col_begin"], comp.mul_col_begin);
} else {
comp.mul_col_begin.r = comp.mul_col_begin.g = comp.mul_col_begin.b = comp.mul_col_begin.a = 255;
}
if (comp_val.isMember("mul_col_end")) {
JsonSerializer::Load(comp_val["mul_col_end"], comp.mul_col_end);
} else {
comp.mul_col_end.r = comp.mul_col_end.g = comp.mul_col_end.b = comp.mul_col_end.a = 255;
}
}
if (comp_val.isMember("add_col")) {
comp.add_col_begin.r = comp_val["add_col"]["r"].asDouble() * 255;
comp.add_col_begin.g = comp_val["add_col"]["g"].asDouble() * 255;
comp.add_col_begin.b = comp_val["add_col"]["b"].asDouble() * 255;
comp.add_col_end = comp.add_col_begin;
} else {
if (comp_val.isMember("add_col_begin")) {
JsonSerializer::Load(comp_val["add_col_begin"], comp.add_col_begin);
} else {
comp.add_col_begin.r = comp.add_col_begin.g = comp.add_col_begin.b = comp.add_col_begin.a = 0;
}
if (comp_val.isMember("add_col_end")) {
JsonSerializer::Load(comp_val["add_col_end"], comp.add_col_end);
} else {
comp.add_col_end.r = comp.add_col_end.g = comp.add_col_end.b = comp.add_col_end.a = 0;
}
}
if (comp_val.isMember("alpha")) {
float start = comp_val["alpha"]["start"].asInt() * 0.01f;
float end = comp_val["alpha"]["end"].asInt() * 0.01f;
comp.mul_col_begin.a *= start;
comp.mul_col_end.a *= end;
comp.alpha_start = 255 * start;
comp.alpha_end = 255 * end;
}
if (comp_val.isMember("alpha2")) {
comp.alpha_start = comp_val["alpha2"]["start"].asInt();
comp.alpha_end = comp_val["alpha2"]["end"].asInt();
}
comp.start_z = comp_val["start_z"].asInt();
components.push_back(comp);
}
s2::Symbol* P3dSymLoader::LoadSymbol(const std::string& filepath) const
{
return SymbolFactory::Instance()->Create(filepath);
}
}<|endoftext|>
|
<commit_before>/**
* @file device_properties.hxx
*
* @brief
*
*
*/
#pragma once
#include <gunrock/util/meta.hxx>
namespace gunrock {
namespace util {
/**
* @namespace properties
* CUDA device properties namespace.
*/
namespace properties {}
}
}<commit_msg>:wastebasket: Trashing my ideas for device_properties.hxx<commit_after>/**
* @file device_properties.hxx
*
* @brief
*
*
*/
#pragma once
#include <gunrock/util/meta.hxx>
#include <map>
namespace gunrock {
namespace util {
enum architecture_t
{
hopper = 900, // Unknown
ampere = 800, // (CUDA 11 and later)
turing = 750, // (CUDA 10 and later)
volta_j = 720, // Jetson
volta = 700, // (CUDA 9 and later)
pascal_j = 620, // Jetson
pascal_g = 610,
pascal = 600, // (CUDA 8 and later)
maxwell_j = 530, // Jetson
maxwell_g = 520, // GTX
maxwell = 500, // (CUDA 6 and later)
kepler_r = 370,
kepler_p = 350,
kepler_j = 320,
kepler = 300, // (CUDA 5 and later)
fermi_ = 210,
fermi = 200, // (CUDA 3.2 - CUDA 8) deprecated
def = 1,
unknown = 0
}; // enum architecture_t
/**
* @namespace properties
* CUDA device properties namespace.
*
* @todo Let's rely on #defines right now, till we find a better way.
*/
namespace properties {
typedef unsigned architecture_idx_t;
/**
* @todo there's no constexpr for std::map, I need to find a better way to do
* this. Right now, we are using hardcoded indexes for each architecture. But
* they are not intuitive. For example, pascal's major number is 6 and minor
* are 6.1, 6.2, but they are mapped to infex 10, 11 and 12.
*
*/
constexpr architecture_idx_t
get_current_arch_idx()
{
// architecture_t::default
architecture_idx_t gunrock_sm_idx = 1;
#ifdef __CUDA_ARCH__
#if GUNROCK_CUDA_ARCH == architecture_t::ampere;
gunrock_sm_idx = 16;
#elif GUNROCK_CUDA_ARCH == architecture_t::turing;
gunrock_sm_idx = 15;
#elif GUNROCK_CUDA_ARCH == architecture_t::volta_j;
gunrock_sm_idx = 14;
#elif GUNROCK_CUDA_ARCH >= architecture_t::volta;
gunrock_sm_idx = 13;
#elif GUNROCK_CUDA_ARCH == architecture_t::pascal_j;
gunrock_sm_idx = 12;
#elif GUNROCK_CUDA_ARCH >= architecture_t::pascal_g;
gunrock_sm_idx = 11;
#elif GUNROCK_CUDA_ARCH >= architecture_t::pascal;
gunrock_sm_idx = 10;
#elif GUNROCK_CUDA_ARCH == architecture_t::maxwell_j;
gunrock_sm_idx = 9;
#elif GUNROCK_CUDA_ARCH >= architecture_t::maxwell_g;
gunrock_sm_idx = 8;
#elif GUNROCK_CUDA_ARCH >= architecture_t::maxwell;
gunrock_sm_idx = 7;
#elif GUNROCK_CUDA_ARCH == architecture_t::kepler_r;
gunrock_sm_idx = 6;
#elif GUNROCK_CUDA_ARCH >= architecture_t::kepler_p;
gunrock_sm_idx = 5;
#elif GUNROCK_CUDA_ARCH >= architecture_t::kepler_j;
gunrock_sm_idx = 4;
#elif GUNROCK_CUDA_ARCH == architecture_t::kepler;
gunrock_sm_idx = 3;
#else
#error "Gunrock: SM arch 2.1 or below is unsupported."
#endif
#else // __CUDA_ARCH__
gunrock_sm_idx = 0;
#endif
return gunrock_sm_idx;
}
template<typename property_t, size_t N>
constexpr property_t
get_property(
const std::array<std::pair<const architecture_t, property_t>, N>& database,
architecture_t arch_idx = get_current_arch_idx())
{
return database[arch_idx].second;
}
constexpr unsigned
maximum_threads_per_warp()
{
const std::array<std::pair<const architecture_t, unsigned>, 1> max_threads{
{ { architecture_t::def, 32 } }
};
return get_property(max_threads, architecture_t::def);
}
constexpr size_t
sm_memory_bank_stride_size()
{
const std::array<std::pair<const architecture_t, size_t>, 1> strides{
{ { architecture_t::def, 4 } }
};
return get_property(strides, architecture_t::def);
}
constexpr unsigned
memory_banks_per_sm()
{
const std::array<std::pair<const architecture_t, unsigned>, 1> banks{
{ { architecture_t::def, 32 } }
};
return get_property(banks, architecture_t::def);
}
/**
* @todo how to handle configurable shmem?
*/
constexpr size_t
maximum_shared_memory_per_sm()
{
enum : size_t
{
KiB = 1024
};
const std::array<std::pair<const architecture_t, unsigned>, 14> shared_memory{
{ { architecture_t::ampere, 48 * KiB }, // XXX
{ architecture_t::turing, 64 * KiB },
{ architecture_t::volta_j, 96 * KiB }, // XXX
{ architecture_t::volta, 96 * KiB },
{ architecture_t::pascal_j, 96 * KiB }, // XXX
{ architecture_t::pascal_g, 96 * KiB },
{ architecture_t::pascal, 64 * KiB },
{ architecture_t::maxwell_j, 48 * KiB }, // XXX
{ architecture_t::maxwell_g, 96 * KiB },
{ architecture_t::maxwell, 64 * KiB },
{ architecture_t::kepler_r, 112 * KiB }, // Configurable?
{ architecture_t::kepler_p, 48 * KiB },
{ architecture_t::kepler_j, 48 * KiB }, // XXX
{ architecture_t::kepler, 48 * KiB } }
};
return get_property(shared_memory);
}
constexpr unsigned
physical_threads_per_sm()
{
const std::array<std::pair<const architecture_t, unsigned>, 14> threads_sm{
{ { architecture_t::ampere, 48 }, // XXX
{ architecture_t::turing, 1024 },
{ architecture_t::volta_j, 2048 }, // XXX
{ architecture_t::volta, 2048 },
{ architecture_t::pascal_j, 2048 }, // XXX
{ architecture_t::pascal_g, 2048 },
{ architecture_t::pascal, 2048 },
{ architecture_t::maxwell_j, 2048 }, // XXX
{ architecture_t::maxwell_g, 2048 },
{ architecture_t::maxwell, 2048 },
{ architecture_t::kepler_r, 2048 },
{ architecture_t::kepler_p, 2048 },
{ architecture_t::kepler_j, 2048 }, // XXX
{ architecture_t::kepler, 2048 } }
};
return get_property(threads_sm);
}
unsigned
maximum_threads_per_cta() const
{
static const std::map<architecture_t, unsigned> threads_cta{
{ architecture_t::def, 1024 }
};
return get_property(threads_cta, architecture_t::def);
}
unsigned
maximum_ctas_per_sm() const
{
static const std::map<architecture_t, unsigned> ctas{
{ architecture_t::ampere, 48 }, // XXX
{ architecture_t::turing, 16 },
{ architecture_t::volta_j, 32 }, // XXX
{ architecture_t::volta, 32 },
{ architecture_t::pascal_j, 32 }, // XXX
{ architecture_t::pascal_g, 32 }, { architecture_t::pascal, 32 },
{ architecture_t::maxwell_j, 32 }, // XXX
{ architecture_t::maxwell_g, 32 }, { architecture_t::maxwell, 32 },
{ architecture_t::kepler_r, 16 }, { architecture_t::kepler_p, 16 },
{ architecture_t::kepler_j, 16 }, // XXX
{ architecture_t::kepler, 16 }
};
return get_property(ctas);
}
unsigned
maximum_registers_per_sm() const
{
static const std::map<architecture_t, unsigned> registers{
{ architecture_t::def, 64 * 1024 }
};
return get_property(registers, architecture_t::def);
}
} // namespace properties
} // namespace util
} // namespace gunrock<|endoftext|>
|
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_EVALUATION_INTERFACE_HH
#define DUNE_GDT_EVALUATION_INTERFACE_HH
#include <memory>
#include <dune/stuff/common/disable_warnings.hh>
# include <dune/common/dynmatrix.hh>
# include <dune/common/fvector.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/common/crtp.hh>
namespace Dune {
namespace GDT {
namespace LocalEvaluation {
/**
* \brief Interface for local evaluations that depend on a codim 0 entity.
* \tparam numArguments The number of local bases.
* \note All evaluations have to be copyable!
*/
template< class Traits, int numArguments >
class Codim0Interface
{
static_assert(AlwaysFalse< Traits >::value, "There is no interface for this numArguments!");
};
/**
* \brief Interface for unary codim 0 evaluations.
*/
template< class Traits >
class Codim0Interface< Traits, 1 >
: public Stuff::CRTPInterface< Codim0Interface< Traits, 1 >, Traits >
{
public:
typedef typename Traits::derived_type derived_type;
typedef typename Traits::EntityType EntityType;
typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType;
typedef typename Traits::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = Traits::dimDomain;
LocalfunctionTupleType localFunctions(const EntityType& entity) const
{
CHECK_CRTP(this->as_imp(*this).localFunctions(entity));
return this->as_imp(*this).localFunctions(entity);
}
/**
* \brief Computes the needed integration order.
* \tparam R RangeFieldType
* \tparam r dimRange of the testBase
* \tparam rC dimRangeRows of the testBase
*/
template< class R, int r, int rC >
size_t order(const LocalfunctionTupleType& localFunctions,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, r, rC >& testBase) const
{
CHECK_CRTP(this->as_imp(*this).order(localFunctions, testBase));
return this->as_imp(*this).order(localFunctions, testBase);
}
/**
* \brief Computes a unary codim 0 evaluation.
* \tparam R RangeFieldType
* \tparam r dimRange of the testBase
* \tparam rC dimRangeRows of the testBase
* \attention ret is assumed to be zero!
*/
template< class R, int r, int rC >
void evaluate(const LocalfunctionTupleType& localFunctions,
const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, r, rC >& testBase,
const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,
Dune::DynamicVector< R >& ret) const
{
CHECK_AND_CALL_CRTP(this->as_imp(*this).evaluate(localFunctions, testBase, localPoint, ret));
}
}; // class Codim0Interface< Traits, 1 >
/**
* \brief Interface for binary codim 0 evaluations.
**/
template< class Traits >
class Codim0Interface< Traits, 2 >
: public Stuff::CRTPInterface< Codim0Interface< Traits, 2 >, Traits >
{
public:
typedef typename Traits::derived_type derived_type;
typedef typename Traits::EntityType EntityType;
typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType;
typedef typename Traits::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = Traits::dimDomain;
/**
* \brief Computes the needed integration order.
* \tparam R RangeFieldType
* \tparam r{T,A} dimRange of the {testBase,ansatzBase}
* \tparam rC{T,A} dimRangeRows of the {testBase,ansatzBase}
*/
template< class R, int rT, int rCT, int rA, int rCA >
size_t order(const LocalfunctionTupleType& localFunctions,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase) const
{
CHECK_CRTP(this->as_imp(*this).order(localFunctions, testBase, ansatzBase));
return this->as_imp(*this).order(localFunctions, testBase, ansatzBase);
}
/**
* \brief Computes a binary codim 0 evaluation.
* \tparam R RangeFieldType
* \tparam r{L,T,A} dimRange of the {localFunction,testBase,ansatzBase}
* \tparam rC{L,T,A} dimRangeRows of the {localFunction,testBase,ansatzBase}
* \attention ret is assumed to be zero!
*/
template< class R, int rT, int rCT, int rA, int rCA >
void evaluate(const LocalfunctionTupleType& localFunctions,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase,
const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,
Dune::DynamicMatrix< R >& ret) const
{
CHECK_AND_CALL_CRTP(this->as_imp(*this).evaluate(localFunctions, testBase, ansatzBase, localPoint, ret));
}
}; // class Codim0Interface< Traits, 2 >
/**
* \brief Interface for local evaluations that depend on an intersection.
* \tparam numArguments The number of local bases.
* \note All evaluations have to be copyable!
*/
template< class Traits, int numArguments >
class Codim1Interface
{
static_assert(AlwaysFalse< Traits >::value, "There is no interface for this numArguments!");
};
/**
* \brief Interface for unary codim 1 evaluations.
*/
template< class Traits >
class Codim1Interface< Traits, 1 >
: public Stuff::CRTPInterface< Codim1Interface< Traits, 1 >, Traits >
{
public:
typedef typename Traits::derived_type derived_type;
typedef typename Traits::EntityType EntityType;
typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType;
typedef typename Traits::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = Traits::dimDomain;
/**
* \brief Computes the needed integration order.
* \tparam R RangeFieldType
* \tparam r dimRange of the testBase
* \tparam rC dimRangeRows of the testBase
*/
template< class R, int r, int rC >
size_t order(const LocalfunctionTupleType& localFunctions,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, r, rC >& testBase) const
{
CHECK_CRTP(this->as_imp(*this).order(localFunctions, testBase));
return this->as_imp(*this).order(localFunctions, testBase);
}
/**
* \brief Computes a binary codim 1 evaluation.
* \tparam IntersectionType A model of Dune::Intersection< ... >
* \tparam R RangeFieldType
* \tparam r dimRange of the testBase
* \tparam rC dimRangeRows of the testBase
* \attention ret is assumed to be zero!
*/
template< class IntersectionType, class R, int r, int rC >
void evaluate(const LocalfunctionTupleType& localFunctions,
const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, r, rC >& testBase,
const IntersectionType& intersection,
const Dune::FieldVector< DomainFieldType, dimDomain - 1 >& localPoint,
Dune::DynamicVector< R >& ret) const
{
CHECK_AND_CALL_CRTP(this->as_imp(*this).evaluate(localFunctions, testBase, intersection, localPoint, ret));
}
}; // class Codim1Interface< Traits, 1 >
/**
* \brief Interface for binary codim 1 evaluations.
*/
template< class Traits >
class Codim1Interface< Traits, 2 >
: public Stuff::CRTPInterface< Codim1Interface< Traits, 2 >, Traits >
{
public:
typedef typename Traits::derived_type derived_type;
typedef typename Traits::EntityType EntityType;
typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType;
typedef typename Traits::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = Traits::dimDomain;
/**
* \brief Computes the needed integration order.
* \tparam R RangeFieldType
* \tparam r{T,A} dimRange of the {testBase,ansatzBase}
* \tparam rC{T,A} dimRangeRows of the {testBase,ansatzBase}
*/
template< class R, int rT, int rCT, int rA, int rCA >
size_t order(const LocalfunctionTupleType& localFunctions,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase) const
{
CHECK_CRTP(this->as_imp(*this).order(localFunctions, testBase, ansatzBase));
return this->as_imp(*this).order(localFunctions, testBase, ansatzBase);
}
/**
* \brief Computes a binary codim 1 evaluation.
* \tparam IntersectionType A model of Dune::Intersection< ... >
* \tparam R RangeFieldType
* \tparam r{T,A} dimRange of the {testBase*,ansatzBase*}
* \tparam rC{T,A} dimRangeRows of the {testBase*,ansatzBase*}
* \attention ret is assumed to be zero!
*/
template< class IntersectionType, class R, int rT, int rCT, int rA, int rCA >
void evaluate(const LocalfunctionTupleType& localFunctions,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase,
const IntersectionType& intersection,
const Dune::FieldVector< DomainFieldType, dimDomain - 1 >& localPoint,
Dune::DynamicMatrix< R >& ret) const
{
CHECK_AND_CALL_CRTP(this->as_imp(*this).evaluate(localFunctions, testBase, ansatzBase, intersection, localPoint,
ret));
}
}; // class Codim1Interface< Traits, 2 >
/**
* \brief Interface for quaternary codim 1 evaluations.
*/
template< class Traits >
class Codim1Interface< Traits, 4 >
: public Stuff::CRTPInterface< Codim1Interface< Traits, 4 >, Traits >
{
public:
typedef typename Traits::derived_type derived_type;
typedef typename Traits::EntityType EntityType;
typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType;
typedef typename Traits::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = Traits::dimDomain;
/**
* \brief Computes the needed integration order.
* \tparam R RangeFieldType
* \tparam r{T,A} dimRange of the {testBase*,ansatzBase*}
* \tparam rC{T,A} dimRangeRows of the {testBase*,ansatzBase*}
*/
template< class R, int rT, int rCT, int rA, int rCA >
size_t order(const LocalfunctionTupleType localFunctionsEntity,
const LocalfunctionTupleType localFunctionsNeighbor,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBaseEntity,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBaseEntity,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBaseNeighbor,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBaseNeighbor) const
{
CHECK_CRTP(this->as_imp(*this).order(localFunctionsEntity, localFunctionsNeighbor,
testBaseEntity, ansatzBaseEntity,
testBaseNeighbor, ansatzBaseNeighbor));
return this->as_imp(*this).order(localFunctionsEntity, localFunctionsNeighbor,
testBaseEntity, ansatzBaseEntity,
testBaseNeighbor, ansatzBaseNeighbor);
}
/**
* \brief Computes a quaternary codim 1 evaluation.
* \tparam IntersectionType A model of Dune::Intersection< ... >
* \tparam R RangeFieldType
* \tparam r{T,A} dimRange of the {testBase*,ansatzBase*}
* \tparam rC{T,A} dimRangeRows of the {testBase*,ansatzBase*}
* \attention entityEntityRet, entityEntityRet, entityEntityRet and neighborEntityRet are assumed to be zero!
*/
template< class IntersectionType, class R, int rT, int rCT, int rA, int rCA >
void evaluate(const LocalfunctionTupleType& localFunctionsEntity,
const LocalfunctionTupleType& localFunctionsNeighbor,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBaseEntity,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBaseEntity,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBaseNeighbor,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBaseNeighbor,
const IntersectionType& intersection,
const Dune::FieldVector< DomainFieldType, dimDomain - 1 >& localPoint,
Dune::DynamicMatrix< R >& entityEntityRet,
Dune::DynamicMatrix< R >& neighborNeighborRet,
Dune::DynamicMatrix< R >& entityNeighborRet,
Dune::DynamicMatrix< R >& neighborEntityRet) const
{
CHECK_AND_CALL_CRTP(this->as_imp(*this).evaluate(localFunctionsEntity,
localFunctionsNeighbor,
testBaseEntity, ansatzBaseEntity,
testBaseNeighbor, ansatzBaseNeighbor,
intersection,
localPoint,
entityEntityRet, neighborNeighborRet,
entityNeighborRet, neighborEntityRet));
}
}; // class Codim1Interface< Traits, 4 >
} // namespace LocalEvaluation
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_EVALUATION_INTERFACE_HH
<commit_msg>[localeval] more as_imp(*this) cleanups<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_EVALUATION_INTERFACE_HH
#define DUNE_GDT_EVALUATION_INTERFACE_HH
#include <memory>
#include <dune/stuff/common/disable_warnings.hh>
# include <dune/common/dynmatrix.hh>
# include <dune/common/fvector.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/common/crtp.hh>
namespace Dune {
namespace GDT {
namespace LocalEvaluation {
/**
* \brief Interface for local evaluations that depend on a codim 0 entity.
* \tparam numArguments The number of local bases.
* \note All evaluations have to be copyable!
*/
template< class Traits, int numArguments >
class Codim0Interface
{
static_assert(AlwaysFalse< Traits >::value, "There is no interface for this numArguments!");
};
/**
* \brief Interface for unary codim 0 evaluations.
*/
template< class Traits >
class Codim0Interface< Traits, 1 >
: public Stuff::CRTPInterface< Codim0Interface< Traits, 1 >, Traits >
{
public:
typedef typename Traits::derived_type derived_type;
typedef typename Traits::EntityType EntityType;
typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType;
typedef typename Traits::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = Traits::dimDomain;
LocalfunctionTupleType localFunctions(const EntityType& entity) const
{
CHECK_CRTP(this->as_imp().localFunctions(entity));
return this->as_imp().localFunctions(entity);
}
/**
* \brief Computes the needed integration order.
* \tparam R RangeFieldType
* \tparam r dimRange of the testBase
* \tparam rC dimRangeRows of the testBase
*/
template< class R, int r, int rC >
size_t order(const LocalfunctionTupleType& localFunctions,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, r, rC >& testBase) const
{
CHECK_CRTP(this->as_imp().order(localFunctions, testBase));
return this->as_imp().order(localFunctions, testBase);
}
/**
* \brief Computes a unary codim 0 evaluation.
* \tparam R RangeFieldType
* \tparam r dimRange of the testBase
* \tparam rC dimRangeRows of the testBase
* \attention ret is assumed to be zero!
*/
template< class R, int r, int rC >
void evaluate(const LocalfunctionTupleType& localFunctions,
const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, r, rC >& testBase,
const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,
Dune::DynamicVector< R >& ret) const
{
CHECK_AND_CALL_CRTP(this->as_imp().evaluate(localFunctions, testBase, localPoint, ret));
}
}; // class Codim0Interface< Traits, 1 >
/**
* \brief Interface for binary codim 0 evaluations.
**/
template< class Traits >
class Codim0Interface< Traits, 2 >
: public Stuff::CRTPInterface< Codim0Interface< Traits, 2 >, Traits >
{
public:
typedef typename Traits::derived_type derived_type;
typedef typename Traits::EntityType EntityType;
typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType;
typedef typename Traits::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = Traits::dimDomain;
/**
* \brief Computes the needed integration order.
* \tparam R RangeFieldType
* \tparam r{T,A} dimRange of the {testBase,ansatzBase}
* \tparam rC{T,A} dimRangeRows of the {testBase,ansatzBase}
*/
template< class R, int rT, int rCT, int rA, int rCA >
size_t order(const LocalfunctionTupleType& localFunctions,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase) const
{
CHECK_CRTP(this->as_imp().order(localFunctions, testBase, ansatzBase));
return this->as_imp().order(localFunctions, testBase, ansatzBase);
}
/**
* \brief Computes a binary codim 0 evaluation.
* \tparam R RangeFieldType
* \tparam r{L,T,A} dimRange of the {localFunction,testBase,ansatzBase}
* \tparam rC{L,T,A} dimRangeRows of the {localFunction,testBase,ansatzBase}
* \attention ret is assumed to be zero!
*/
template< class R, int rT, int rCT, int rA, int rCA >
void evaluate(const LocalfunctionTupleType& localFunctions,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase,
const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,
Dune::DynamicMatrix< R >& ret) const
{
CHECK_AND_CALL_CRTP(this->as_imp().evaluate(localFunctions, testBase, ansatzBase, localPoint, ret));
}
}; // class Codim0Interface< Traits, 2 >
/**
* \brief Interface for local evaluations that depend on an intersection.
* \tparam numArguments The number of local bases.
* \note All evaluations have to be copyable!
*/
template< class Traits, int numArguments >
class Codim1Interface
{
static_assert(AlwaysFalse< Traits >::value, "There is no interface for this numArguments!");
};
/**
* \brief Interface for unary codim 1 evaluations.
*/
template< class Traits >
class Codim1Interface< Traits, 1 >
: public Stuff::CRTPInterface< Codim1Interface< Traits, 1 >, Traits >
{
public:
typedef typename Traits::derived_type derived_type;
typedef typename Traits::EntityType EntityType;
typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType;
typedef typename Traits::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = Traits::dimDomain;
/**
* \brief Computes the needed integration order.
* \tparam R RangeFieldType
* \tparam r dimRange of the testBase
* \tparam rC dimRangeRows of the testBase
*/
template< class R, int r, int rC >
size_t order(const LocalfunctionTupleType& localFunctions,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, r, rC >& testBase) const
{
CHECK_CRTP(this->as_imp().order(localFunctions, testBase));
return this->as_imp().order(localFunctions, testBase);
}
/**
* \brief Computes a binary codim 1 evaluation.
* \tparam IntersectionType A model of Dune::Intersection< ... >
* \tparam R RangeFieldType
* \tparam r dimRange of the testBase
* \tparam rC dimRangeRows of the testBase
* \attention ret is assumed to be zero!
*/
template< class IntersectionType, class R, int r, int rC >
void evaluate(const LocalfunctionTupleType& localFunctions,
const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, r, rC >& testBase,
const IntersectionType& intersection,
const Dune::FieldVector< DomainFieldType, dimDomain - 1 >& localPoint,
Dune::DynamicVector< R >& ret) const
{
CHECK_AND_CALL_CRTP(this->as_imp().evaluate(localFunctions, testBase, intersection, localPoint, ret));
}
}; // class Codim1Interface< Traits, 1 >
/**
* \brief Interface for binary codim 1 evaluations.
*/
template< class Traits >
class Codim1Interface< Traits, 2 >
: public Stuff::CRTPInterface< Codim1Interface< Traits, 2 >, Traits >
{
public:
typedef typename Traits::derived_type derived_type;
typedef typename Traits::EntityType EntityType;
typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType;
typedef typename Traits::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = Traits::dimDomain;
/**
* \brief Computes the needed integration order.
* \tparam R RangeFieldType
* \tparam r{T,A} dimRange of the {testBase,ansatzBase}
* \tparam rC{T,A} dimRangeRows of the {testBase,ansatzBase}
*/
template< class R, int rT, int rCT, int rA, int rCA >
size_t order(const LocalfunctionTupleType& localFunctions,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase) const
{
CHECK_CRTP(this->as_imp().order(localFunctions, testBase, ansatzBase));
return this->as_imp().order(localFunctions, testBase, ansatzBase);
}
/**
* \brief Computes a binary codim 1 evaluation.
* \tparam IntersectionType A model of Dune::Intersection< ... >
* \tparam R RangeFieldType
* \tparam r{T,A} dimRange of the {testBase*,ansatzBase*}
* \tparam rC{T,A} dimRangeRows of the {testBase*,ansatzBase*}
* \attention ret is assumed to be zero!
*/
template< class IntersectionType, class R, int rT, int rCT, int rA, int rCA >
void evaluate(const LocalfunctionTupleType& localFunctions,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase,
const IntersectionType& intersection,
const Dune::FieldVector< DomainFieldType, dimDomain - 1 >& localPoint,
Dune::DynamicMatrix< R >& ret) const
{
CHECK_AND_CALL_CRTP(this->as_imp().evaluate(localFunctions, testBase, ansatzBase, intersection, localPoint,
ret));
}
}; // class Codim1Interface< Traits, 2 >
/**
* \brief Interface for quaternary codim 1 evaluations.
*/
template< class Traits >
class Codim1Interface< Traits, 4 >
: public Stuff::CRTPInterface< Codim1Interface< Traits, 4 >, Traits >
{
public:
typedef typename Traits::derived_type derived_type;
typedef typename Traits::EntityType EntityType;
typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType;
typedef typename Traits::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = Traits::dimDomain;
/**
* \brief Computes the needed integration order.
* \tparam R RangeFieldType
* \tparam r{T,A} dimRange of the {testBase*,ansatzBase*}
* \tparam rC{T,A} dimRangeRows of the {testBase*,ansatzBase*}
*/
template< class R, int rT, int rCT, int rA, int rCA >
size_t order(const LocalfunctionTupleType localFunctionsEntity,
const LocalfunctionTupleType localFunctionsNeighbor,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBaseEntity,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBaseEntity,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBaseNeighbor,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBaseNeighbor) const
{
CHECK_CRTP(this->as_imp().order(localFunctionsEntity, localFunctionsNeighbor,
testBaseEntity, ansatzBaseEntity,
testBaseNeighbor, ansatzBaseNeighbor));
return this->as_imp().order(localFunctionsEntity, localFunctionsNeighbor,
testBaseEntity, ansatzBaseEntity,
testBaseNeighbor, ansatzBaseNeighbor);
}
/**
* \brief Computes a quaternary codim 1 evaluation.
* \tparam IntersectionType A model of Dune::Intersection< ... >
* \tparam R RangeFieldType
* \tparam r{T,A} dimRange of the {testBase*,ansatzBase*}
* \tparam rC{T,A} dimRangeRows of the {testBase*,ansatzBase*}
* \attention entityEntityRet, entityEntityRet, entityEntityRet and neighborEntityRet are assumed to be zero!
*/
template< class IntersectionType, class R, int rT, int rCT, int rA, int rCA >
void evaluate(const LocalfunctionTupleType& localFunctionsEntity,
const LocalfunctionTupleType& localFunctionsNeighbor,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBaseEntity,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBaseEntity,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBaseNeighbor,
const Stuff::LocalfunctionSetInterface
< EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBaseNeighbor,
const IntersectionType& intersection,
const Dune::FieldVector< DomainFieldType, dimDomain - 1 >& localPoint,
Dune::DynamicMatrix< R >& entityEntityRet,
Dune::DynamicMatrix< R >& neighborNeighborRet,
Dune::DynamicMatrix< R >& entityNeighborRet,
Dune::DynamicMatrix< R >& neighborEntityRet) const
{
CHECK_AND_CALL_CRTP(this->as_imp().evaluate(localFunctionsEntity,
localFunctionsNeighbor,
testBaseEntity, ansatzBaseEntity,
testBaseNeighbor, ansatzBaseNeighbor,
intersection,
localPoint,
entityEntityRet, neighborNeighborRet,
entityNeighborRet, neighborEntityRet));
}
}; // class Codim1Interface< Traits, 4 >
} // namespace LocalEvaluation
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_EVALUATION_INTERFACE_HH
<|endoftext|>
|
<commit_before>#include <config.h>
#include <config.h>
#include <dune/stuff/test/test_common.hh>
#include <gtest.h>
#include <string>
#include <array>
#include <initializer_list>
#include <vector>
#include <dune/stuff/common/fixed_map.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/multiscale/common/main_init.hh>
#include <dune/multiscale/common/error_container.hh>
#include <dune/multiscale/msfem/algorithm.hh>
#include <dune/multiscale/problems/selector.hh>
#include <boost/filesystem.hpp>
using namespace Dune::Stuff::Common;
void set_param();
std::string prepend_test_dir(std::string fn)
{
boost::filesystem::path path(st_testdata_directory);
path /= fn;
return path.string();
}
TEST(MSFEM, All) {
using namespace Dune::Multiscale;
using namespace Dune::Multiscale::MsFEM;
int coarse_grid_level_ = 3;
int number_of_layers_ = 4;
int total_refinement_level_ = 5;
const std::string macroGridName = prepend_test_dir("compare_msfem.dgf");
set_param();
//! ---------------------- local error indicators --------------------------------
// ----- local error indicators (for each coarse grid element T) -------------
const int max_loop_number = 10;
ErrorContainer errors(max_loop_number);
unsigned int loop_number = 0;
while (algorithm(macroGridName, loop_number++, total_refinement_level_, coarse_grid_level_, number_of_layers_,
errors.locals, errors.totals, errors.total_estimated_H1_error_)) {
}
for (const auto total : errors.totals) {
for (auto error : *total) {
// fails iff 1e-2 <= error
EXPECT_GT(double(1e-2), error);
}
}
}
int main(int argc, char** argv) {
test_init(argc, argv);
return RUN_ALL_TESTS();
}
void set_param() {}
<commit_msg>make msfem test compile again<commit_after>#include <config.h>
#include <config.h>
#include <dune/stuff/test/test_common.hh>
#include <gtest.h>
#include <string>
#include <array>
#include <initializer_list>
#include <vector>
#include <dune/stuff/common/fixed_map.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/multiscale/common/main_init.hh>
#include <dune/multiscale/common/error_container.hh>
#include <dune/multiscale/msfem/algorithm.hh>
#include <dune/multiscale/problems/selector.hh>
#include <boost/filesystem.hpp>
using namespace Dune::Stuff::Common;
void set_param();
std::string prepend_test_dir(std::string fn)
{
boost::filesystem::path path(st_testdata_directory);
path /= fn;
return path.string();
}
TEST(MSFEM, All) {
using namespace Dune::Multiscale;
using namespace Dune::Multiscale::MsFEM;
set_param();
const auto errors = algorithm();
for (const auto& err : errors) {
// fails iff 1e-2 <= error
EXPECT_GT(double(1e-2), err.second);
}
}
int main(int argc, char** argv) {
test_init(argc, argv);
return RUN_ALL_TESTS();
}
void set_param() {
DSC_CONFIG.set("grids.macro_cells_per_dim", "[20;20;20]");
DSC_CONFIG.set("micro_cells_per_macrocell_dim", "[40;40;40]");
DSC_CONFIG.set("msfem.oversampling_layers", 4);
DSC_CONFIG.set("global.vtk_output", 0);
DSC_CONFIG.set("problem.name", "Nine");
}
<|endoftext|>
|
<commit_before>#ifndef DUNE_STUFF_GRID_PROVIDER_INTERFACE_HH
#define DUNE_STUFF_GRID_PROVIDER_INTERFACE_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#if HAVE_DUNE_GRID
#include <dune/common/fvector.hh>
#include <dune/common/shared_ptr.hh>
#include <dune/grid/common/mcmgmapper.hh>
#include <dune/grid/io/file/vtk/vtkwriter.hh>
#include <dune/grid/sgrid.hh>
namespace Dune {
namespace Stuff {
namespace Grid {
namespace Provider {
#if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridImp = Dune::GridSelector::GridType >
#else // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridImp = Dune::SGrid< 2, 2 > >
#endif // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
class Interface
{
public:
typedef GridImp GridType;
typedef Dune::FieldVector< typename GridType::ctype, GridType::dimension > CoordinateType;
static const unsigned int dim = GridType::dimension;
static const std::string id()
{
return "stuff.grid.provider";
}
virtual Dune::shared_ptr< GridType > grid() = 0;
virtual const Dune::shared_ptr< const GridType > grid() const = 0;
//! \todo TODO Remove me in the future (i.e. on 01.01.2013)!
Dune::shared_ptr< GridType > gridPtr() DUNE_DEPRECATED_MSG("Use grid() instead!")
{
return grid();
}
//! \todo TODO Remove me in the future (i.e. on 01.01.2013)!
const Dune::shared_ptr< const GridType > gridPtr() const DUNE_DEPRECATED_MSG("Use grid() instead!")
{
return grid();
}
private:
typedef typename GridType::LeafGridView GridViewType;
public:
void visualize(const std::string filename = id() + ".grid") const
{
// vtk writer
GridViewType gridView = grid()->leafView();
Dune::VTKWriter< GridViewType > vtkwriter(gridView);
// boundary id
std::vector< double > boundaryId = generateBoundaryIdVisualization(gridView);
vtkwriter.addCellData(boundaryId, "boundaryId");
// codim 0 entity id
std::vector< double > entityId = generateEntityVisualization(gridView);
vtkwriter.addCellData(entityId, "entityId");
// write
vtkwriter.write(filename, Dune::VTK::ascii);
} // void visualize(const std::string filename = id + ".grid") const
private:
std::vector< double > generateBoundaryIdVisualization(const GridViewType& gridView) const
{
typedef typename GridViewType::IndexSet::IndexType IndexType;
typedef typename GridViewType::template Codim< 0 >::Entity EntityType;
std::vector< double > data(gridView.indexSet().size(0));
// walk the grid
for (typename GridViewType::template Codim< 0 >::Iterator it = gridView.template begin< 0 >();
it != gridView.template end< 0 >();
++it)
{
const EntityType& entity = *it;
const IndexType& index = gridView.indexSet().index(entity);
data[index] = 0.0;
int numberOfBoundarySegments = 0;
bool isOnBoundary = false;
for (typename GridViewType::IntersectionIterator intersectionIt = gridView.ibegin(entity);
intersectionIt != gridView.iend(entity);
++intersectionIt) {
if (!intersectionIt->neighbor() && intersectionIt->boundary()){
isOnBoundary = true;
numberOfBoundarySegments += 1;
data[index] += double(intersectionIt->boundaryId());
}
}
if (isOnBoundary) {
data[index] /= double(numberOfBoundarySegments);
}
} // walk the grid
return data;
} // std::vector< double > generateBoundaryIdVisualization(const GridViewType& gridView) const
std::vector< double > generateEntityVisualization(const GridViewType& gridView) const
{
typedef typename GridViewType::IndexSet::IndexType IndexType;
typedef typename GridViewType::template Codim< 0 >::Entity EntityType;
std::vector< double > data(gridView.indexSet().size(0));
// walk the grid
for (typename GridViewType::template Codim< 0 >::Iterator it = gridView.template begin< 0 >();
it != gridView.template end< 0 >();
++it)
{
const EntityType& entity = *it;
const IndexType& index = gridView.indexSet().index(entity);
data[index] = double(index);
} // walk the grid
return data;
} // std::vector< double > generateEntityVisualization(const GridViewType& gridView) const
}; // class Interface
} // namespace Provider
} // namespace Grid
} // namespace Stuff
} // namespace Dune
#endif // HAVE_DUNE_GRID
#endif // DUNE_STUFF_GRID_PROVIDER_INTERFACE_HH
<commit_msg>[grid.provider] aded create()<commit_after>#ifndef DUNE_STUFF_GRID_PROVIDER_INTERFACE_HH
#define DUNE_STUFF_GRID_PROVIDER_INTERFACE_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#if HAVE_DUNE_GRID
#include <dune/common/fvector.hh>
#include <dune/common/shared_ptr.hh>
#include <dune/common/parametertree.hh>
#include <dune/grid/io/file/vtk/vtkwriter.hh>
#include <dune/grid/sgrid.hh>
namespace Dune {
namespace Stuff {
namespace Grid {
namespace Provider {
#if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridImp = Dune::GridSelector::GridType >
#else // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridImp = Dune::SGrid< 2, 2 > >
#endif // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
class Interface
{
public:
typedef GridImp GridType;
typedef Interface< GridType > ThisType;
typedef Dune::FieldVector< typename GridType::ctype, GridType::dimension > CoordinateType;
static const unsigned int dim = GridType::dimension;
static const std::string id()
{
return "stuff.grid.provider";
}
virtual Dune::shared_ptr< GridType > grid() = 0;
virtual const Dune::shared_ptr< const GridType > grid() const = 0;
//! \todo TODO Remove me in the future (i.e. on 01.01.2013)!
Dune::shared_ptr< GridType > gridPtr() DUNE_DEPRECATED_MSG("Use grid() instead!")
{
return grid();
}
//! \todo TODO Remove me in the future (i.e. on 01.01.2013)!
const Dune::shared_ptr< const GridType > gridPtr() const DUNE_DEPRECATED_MSG("Use grid() instead!")
{
return grid();
}
private:
typedef typename GridType::LeafGridView GridViewType;
public:
void visualize(const std::string filename = id()) const
{
// vtk writer
GridViewType gridView = grid()->leafView();
Dune::VTKWriter< GridViewType > vtkwriter(gridView);
// boundary id
std::vector< double > boundaryId = generateBoundaryIdVisualization(gridView);
vtkwriter.addCellData(boundaryId, "boundaryId");
// codim 0 entity id
std::vector< double > entityId = generateEntityVisualization(gridView);
vtkwriter.addCellData(entityId, "entityId");
// write
vtkwriter.write(filename, Dune::VTK::ascii);
} // void visualize(const std::string filename = id + ".grid") const
private:
std::vector< double > generateBoundaryIdVisualization(const GridViewType& gridView) const
{
typedef typename GridViewType::IndexSet::IndexType IndexType;
typedef typename GridViewType::template Codim< 0 >::Entity EntityType;
std::vector< double > data(gridView.indexSet().size(0));
// walk the grid
for (typename GridViewType::template Codim< 0 >::Iterator it = gridView.template begin< 0 >();
it != gridView.template end< 0 >();
++it)
{
const EntityType& entity = *it;
const IndexType& index = gridView.indexSet().index(entity);
data[index] = 0.0;
int numberOfBoundarySegments = 0;
bool isOnBoundary = false;
for (typename GridViewType::IntersectionIterator intersectionIt = gridView.ibegin(entity);
intersectionIt != gridView.iend(entity);
++intersectionIt) {
if (!intersectionIt->neighbor() && intersectionIt->boundary()){
isOnBoundary = true;
numberOfBoundarySegments += 1;
data[index] += double(intersectionIt->boundaryId());
}
}
if (isOnBoundary) {
data[index] /= double(numberOfBoundarySegments);
}
} // walk the grid
return data;
} // std::vector< double > generateBoundaryIdVisualization(const GridViewType& gridView) const
std::vector< double > generateEntityVisualization(const GridViewType& gridView) const
{
typedef typename GridViewType::IndexSet::IndexType IndexType;
typedef typename GridViewType::template Codim< 0 >::Entity EntityType;
std::vector< double > data(gridView.indexSet().size(0));
// walk the grid
for (typename GridViewType::template Codim< 0 >::Iterator it = gridView.template begin< 0 >();
it != gridView.template end< 0 >();
++it)
{
const EntityType& entity = *it;
const IndexType& index = gridView.indexSet().index(entity);
data[index] = double(index);
} // walk the grid
return data;
} // std::vector< double > generateEntityVisualization(const GridViewType& gridView) const
}; // class Interface
} // namespace Provider
} // namespace Grid
} // namespace Stuff
} // namespace Dune
#include "cube.hh"
#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG
#include "gmsh.hh"
#endif // HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG
namespace Dune {
namespace Stuff {
namespace Grid {
namespace Provider {
#if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridImp = Dune::GridSelector::GridType >
#else // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
template< class GridImp = Dune::SGrid< 2, 2 > >
#endif // defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG
Interface< GridImp >* create(const std::string& type, const Dune::ParameterTree paramTree = Dune::ParameterTree())
{
// choose provider
if (type == "stuff.grid.provider.cube") {
typedef Dune::Stuff::Grid::Provider::Cube<> CubeProviderType;
CubeProviderType* cubeProvider = new CubeProviderType(CubeProviderType::createFromParamTree(paramTree));
return cubeProvider;
#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG
} else if (type == "stuff.grid.provider.gmsh") {
typedef Dune::Stuff::Grid::Provider::Gmsh<> GmshProviderType;
GmshProviderType* gmshProvider = new GmshProviderType(GmshProviderType::createFromParamTree(paramTree));
return gmshProvider;
#endif // HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG
} else
DUNE_THROW(Dune::RangeError,
"\nError: unknown grid provider '" << type << "' requested");
} // Interface< GridImp >* create(const std::string& type, const Dune::ParameterTree paramTree = Dune::ParameterTree())
} // namespace Provider
} // namespace Grid
} // namespace Stuff
} // namespace Dune
#endif // HAVE_DUNE_GRID
#endif // DUNE_STUFF_GRID_PROVIDER_INTERFACE_HH
<|endoftext|>
|
<commit_before>#include "json_ui.hh"
#include "containers.hh"
#include "display_buffer.hh"
#include "keys.hh"
#include "file.hh"
#include "event_manager.hh"
#include "value.hh"
#include "unit_tests.hh"
#include <utility>
#include <unistd.h>
namespace Kakoune
{
template<typename T>
String to_json(ArrayView<const T> array)
{
String res;
for (auto& elem : array)
{
if (not res.empty())
res += ", ";
res += to_json(elem);
}
return "[" + res + "]";
}
template<typename T, MemoryDomain D>
String to_json(const Vector<T, D>& vec) { return to_json(ArrayView<const T>{vec}); }
String to_json(int i) { return to_string(i); }
String to_json(bool b) { return b ? "true" : "false"; }
String to_json(StringView str)
{
String res;
res.reserve(str.length() + 4);
res += '"';
for (auto it = str.begin(), end = str.end(); it != end; )
{
auto next = std::find_if(it, end, [](char c) {
return c == '\\' or c == '"' or (c >= 0 and c <= 0x1F);
});
res += StringView{it, next};
if (next == end)
break;
char buf[7] = {'\\', *next, 0};
if (*next >= 0 and *next <= 0x1F)
sprintf(buf, "\\u%04x", *next);
res += buf;
it = next+1;
}
res += '"';
return res;
}
String to_json(Color color)
{
if (color.color == Kakoune::Color::RGB)
{
char buffer[10];
sprintf(buffer, R"("#%02x%02x%02x")", color.r, color.g, color.b);
return buffer;
}
return to_json(color_to_str(color));
}
String to_json(Attribute attributes)
{
struct { Attribute attr; StringView name; }
attrs[] {
{ Attribute::Exclusive, "exclusive" },
{ Attribute::Underline, "underline" },
{ Attribute::Reverse, "reverse" },
{ Attribute::Blink, "blink" },
{ Attribute::Bold, "bold" },
{ Attribute::Dim, "dim" },
{ Attribute::Italic, "italic" },
};
String res;
for (auto& attr : attrs)
{
if (not (attributes & attr.attr))
continue;
if (not res.empty())
res += ", ";
res += to_json(attr.name);
}
return "[" + res + "]";
}
String to_json(Face face)
{
return format(R"(\{ "fg": {}, "bg": {}, "attributes": {} })",
to_json(face.fg), to_json(face.bg), to_json(face.attributes));
}
String to_json(const DisplayAtom& atom)
{
return format(R"(\{ "face": {}, "contents": {} })", to_json(atom.face), to_json(atom.content()));
}
String to_json(const DisplayLine& line)
{
return to_json(line.atoms());
}
String to_json(CharCoord coord)
{
return format(R"(\{ "line": {}, "column": {} })", coord.line, coord.column);
}
String to_json(MenuStyle style)
{
switch (style)
{
case MenuStyle::Prompt: return R"("prompt")";
case MenuStyle::Inline: return R"("inline")";
}
return "";
}
String to_json(InfoStyle style)
{
switch (style)
{
case InfoStyle::Prompt: return R"("prompt")";
case InfoStyle::Inline: return R"("inline")";
case InfoStyle::InlineAbove: return R"("inlineAbove")";
case InfoStyle::InlineBelow: return R"("inlineBelow")";
case InfoStyle::MenuDoc: return R"("menuDoc")";
}
return "";
}
String concat()
{
return "";
}
template<typename First, typename... Args>
String concat(First&& first, Args&&... args)
{
if (sizeof...(Args) != 0)
return to_json(first) + ", " + concat(args...);
return to_json(first);
}
template<typename... Args>
void rpc_call(StringView method, Args&&... args)
{
auto q = format(R"(\{ "jsonrpc": "2.0", "method": "{}", "params": [{}] }{})",
method, concat(std::forward<Args>(args)...), "\n");
write_stdout(q);
}
JsonUI::JsonUI()
: m_stdin_watcher{0, [this](FDWatcher&, EventMode mode) {
parse_requests(mode);
}}, m_dimensions{24, 80}
{
set_signal_handler(SIGINT, SIG_DFL);
}
void JsonUI::draw(const DisplayBuffer& display_buffer,
const Face& default_face, const Face& padding_face)
{
rpc_call("draw", display_buffer.lines(), default_face, padding_face);
}
void JsonUI::draw_status(const DisplayLine& status_line,
const DisplayLine& mode_line,
const Face& default_face)
{
rpc_call("draw_status", status_line, mode_line, default_face);
}
bool JsonUI::is_key_available()
{
return not m_pending_keys.empty();
}
Key JsonUI::get_key()
{
kak_assert(not m_pending_keys.empty());
Key key = m_pending_keys.front();
m_pending_keys.erase(m_pending_keys.begin());
return key;
}
void JsonUI::menu_show(ConstArrayView<DisplayLine> items,
CharCoord anchor, Face fg, Face bg,
MenuStyle style)
{
rpc_call("menu_show", items, anchor, fg, bg, style);
}
void JsonUI::menu_select(int selected)
{
rpc_call("menu_show", selected);
}
void JsonUI::menu_hide()
{
rpc_call("menu_hide");
}
void JsonUI::info_show(StringView title, StringView content,
CharCoord anchor, Face face,
InfoStyle style)
{
rpc_call("info_show", title, content, anchor, face, style);
}
void JsonUI::info_hide()
{
rpc_call("info_hide");
}
void JsonUI::refresh(bool force)
{
rpc_call("refresh", force);
}
void JsonUI::set_input_callback(InputCallback callback)
{
m_input_callback = std::move(callback);
}
void JsonUI::set_ui_options(const Options& options)
{
// rpc_call("set_ui_options", options);
}
CharCoord JsonUI::dimensions()
{
return m_dimensions;
}
using JsonArray = Vector<Value>;
using JsonObject = IdMap<Value>;
static bool is_digit(char c) { return c >= '0' and c <= '9'; }
std::tuple<Value, const char*>
parse_json(const char* pos, const char* end)
{
using Result = std::tuple<Value, const char*>;
if (not skip_while(pos, end, is_blank))
return {};
if (is_digit(*pos))
{
auto digit_end = pos;
skip_while(digit_end, end, is_digit);
return Result{ Value{str_to_int({pos, digit_end})}, digit_end };
}
if (end - pos > 4 and StringView{pos, pos+4} == "true")
return Result{ Value{true}, pos+4 };
if (end - pos > 5 and StringView{pos, pos+5} == "false")
return Result{ Value{false}, pos+5 };
if (*pos == '"')
{
String value;
bool escaped = false;
++pos;
for (auto string_end = pos; string_end != end; ++string_end)
{
if (escaped)
{
escaped = false;
value += StringView{pos, string_end};
value.back() = *string_end;
pos = string_end+1;
continue;
}
if (*string_end == '\\')
escaped = true;
if (*string_end == '"')
{
value += StringView{pos, string_end};
return Result{std::move(value), string_end+1};
}
}
return {};
}
if (*pos == '[')
{
JsonArray array;
if (*++pos == ']')
return Result{std::move(array), pos+1};
while (true)
{
Value element;
std::tie(element, pos) = parse_json(pos, end);
if (not element)
return {};
array.push_back(std::move(element));
if (not skip_while(pos, end, is_blank))
return {};
if (*pos == ',')
++pos;
else if (*pos == ']')
return Result{std::move(array), pos+1};
else
throw runtime_error("unable to parse array, expected ',' or ']'");
}
}
if (*pos == '{')
{
JsonObject object;
if (*++pos == '}')
return Result{std::move(object), pos+1};
while (true)
{
Value name_value;
std::tie(name_value, pos) = parse_json(pos, end);
if (not name_value)
return {};
String& name = name_value.as<String>();
if (not skip_while(pos, end, is_blank))
return {};
if (*pos++ != ':')
throw runtime_error("expected :");
Value element;
std::tie(element, pos) = parse_json(pos, end);
if (not element)
return {};
object.append({ std::move(name), std::move(element) });
if (not skip_while(pos, end, is_blank))
return {};
if (*pos == ',')
++pos;
else if (*pos == '}')
return Result{std::move(object), pos+1};
else
throw runtime_error("unable to parse object, expected ',' or '}'");
}
}
throw runtime_error("Could not parse json");
}
std::tuple<Value, const char*>
parse_json(StringView json) { return parse_json(json.begin(), json.end()); }
void JsonUI::eval_json(const Value& json)
{
if (not json.is_a<JsonObject>())
throw runtime_error("json request is not an object");
const JsonObject& object = json.as<JsonObject>();
auto json_it = object.find("jsonrpc");
if (json_it == object.end() or json_it->value.as<String>() != "2.0")
throw runtime_error("invalid json rpc request");
auto method_it = object.find("method");
if (method_it == object.end())
throw runtime_error("invalid json rpc request (method missing)");
StringView method = method_it->value.as<String>();
auto params_it = object.find("params");
if (params_it == object.end())
throw runtime_error("invalid json rpc request (params missing)");
const JsonArray& params = params_it->value.as<JsonArray>();
if (method == "keys")
{
for (auto& key_val : params)
{
for (auto& key : parse_keys(key_val.as<String>()))
m_pending_keys.push_back(key);
}
}
else if (method == "resize")
{
if (params.size() != 2)
throw runtime_error("resize expects 2 parameters");
CharCoord dim{params[0].as<int>(), params[1].as<int>()};
m_dimensions = dim;
m_pending_keys.push_back(resize(dim));
}
else
throw runtime_error("unknown method");
}
static bool stdin_ready()
{
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(0, &rfds);
timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
return select(1, &rfds, nullptr, nullptr, &tv) == 1;
}
void JsonUI::parse_requests(EventMode mode)
{
constexpr size_t bufsize = 1024;
char buf[bufsize];
while (stdin_ready())
{
ssize_t size = ::read(0, buf, bufsize);
if (size == -1 or size == 0)
break;
m_requests += StringView{buf, buf + size};
}
while (not m_requests.empty())
{
const char* pos = nullptr;
try
{
Value json;
std::tie(json, pos) = parse_json(m_requests);
if (json)
eval_json(json);
}
catch (runtime_error& error)
{
write_stderr(format("error while handling requests '{}': '{}'",
m_requests, error.what()));
// try to salvage request by dropping its first line
pos = std::min(m_requests.end(), find(m_requests, '\n')+1);
}
if (not pos)
break; // unterminated request ?
m_requests = String{pos, m_requests.end()};
}
while (m_input_callback and not m_pending_keys.empty())
m_input_callback(mode);
}
UnitTest test_json_parser{[]()
{
{
auto value = std::get<0>(parse_json(R"({ "jsonrpc": "2.0", "method": "keys", "params": [ "b", "l", "a", "h" ] })"));
kak_assert(value);
}
{
auto value = std::get<0>(parse_json("[10,20]"));
kak_assert(value and value.is_a<JsonArray>());
kak_assert(value.as<JsonArray>().at(1).as<int>() == 20);
}
{
auto value = std::get<0>(parse_json("{}"));
kak_assert(value and value.is_a<JsonObject>());
kak_assert(value.as<JsonObject>().empty());
}
}};
}
<commit_msg>Fix menu_select in the JSON ui<commit_after>#include "json_ui.hh"
#include "containers.hh"
#include "display_buffer.hh"
#include "keys.hh"
#include "file.hh"
#include "event_manager.hh"
#include "value.hh"
#include "unit_tests.hh"
#include <utility>
#include <unistd.h>
namespace Kakoune
{
template<typename T>
String to_json(ArrayView<const T> array)
{
String res;
for (auto& elem : array)
{
if (not res.empty())
res += ", ";
res += to_json(elem);
}
return "[" + res + "]";
}
template<typename T, MemoryDomain D>
String to_json(const Vector<T, D>& vec) { return to_json(ArrayView<const T>{vec}); }
String to_json(int i) { return to_string(i); }
String to_json(bool b) { return b ? "true" : "false"; }
String to_json(StringView str)
{
String res;
res.reserve(str.length() + 4);
res += '"';
for (auto it = str.begin(), end = str.end(); it != end; )
{
auto next = std::find_if(it, end, [](char c) {
return c == '\\' or c == '"' or (c >= 0 and c <= 0x1F);
});
res += StringView{it, next};
if (next == end)
break;
char buf[7] = {'\\', *next, 0};
if (*next >= 0 and *next <= 0x1F)
sprintf(buf, "\\u%04x", *next);
res += buf;
it = next+1;
}
res += '"';
return res;
}
String to_json(Color color)
{
if (color.color == Kakoune::Color::RGB)
{
char buffer[10];
sprintf(buffer, R"("#%02x%02x%02x")", color.r, color.g, color.b);
return buffer;
}
return to_json(color_to_str(color));
}
String to_json(Attribute attributes)
{
struct { Attribute attr; StringView name; }
attrs[] {
{ Attribute::Exclusive, "exclusive" },
{ Attribute::Underline, "underline" },
{ Attribute::Reverse, "reverse" },
{ Attribute::Blink, "blink" },
{ Attribute::Bold, "bold" },
{ Attribute::Dim, "dim" },
{ Attribute::Italic, "italic" },
};
String res;
for (auto& attr : attrs)
{
if (not (attributes & attr.attr))
continue;
if (not res.empty())
res += ", ";
res += to_json(attr.name);
}
return "[" + res + "]";
}
String to_json(Face face)
{
return format(R"(\{ "fg": {}, "bg": {}, "attributes": {} })",
to_json(face.fg), to_json(face.bg), to_json(face.attributes));
}
String to_json(const DisplayAtom& atom)
{
return format(R"(\{ "face": {}, "contents": {} })", to_json(atom.face), to_json(atom.content()));
}
String to_json(const DisplayLine& line)
{
return to_json(line.atoms());
}
String to_json(CharCoord coord)
{
return format(R"(\{ "line": {}, "column": {} })", coord.line, coord.column);
}
String to_json(MenuStyle style)
{
switch (style)
{
case MenuStyle::Prompt: return R"("prompt")";
case MenuStyle::Inline: return R"("inline")";
}
return "";
}
String to_json(InfoStyle style)
{
switch (style)
{
case InfoStyle::Prompt: return R"("prompt")";
case InfoStyle::Inline: return R"("inline")";
case InfoStyle::InlineAbove: return R"("inlineAbove")";
case InfoStyle::InlineBelow: return R"("inlineBelow")";
case InfoStyle::MenuDoc: return R"("menuDoc")";
}
return "";
}
String concat()
{
return "";
}
template<typename First, typename... Args>
String concat(First&& first, Args&&... args)
{
if (sizeof...(Args) != 0)
return to_json(first) + ", " + concat(args...);
return to_json(first);
}
template<typename... Args>
void rpc_call(StringView method, Args&&... args)
{
auto q = format(R"(\{ "jsonrpc": "2.0", "method": "{}", "params": [{}] }{})",
method, concat(std::forward<Args>(args)...), "\n");
write_stdout(q);
}
JsonUI::JsonUI()
: m_stdin_watcher{0, [this](FDWatcher&, EventMode mode) {
parse_requests(mode);
}}, m_dimensions{24, 80}
{
set_signal_handler(SIGINT, SIG_DFL);
}
void JsonUI::draw(const DisplayBuffer& display_buffer,
const Face& default_face, const Face& padding_face)
{
rpc_call("draw", display_buffer.lines(), default_face, padding_face);
}
void JsonUI::draw_status(const DisplayLine& status_line,
const DisplayLine& mode_line,
const Face& default_face)
{
rpc_call("draw_status", status_line, mode_line, default_face);
}
bool JsonUI::is_key_available()
{
return not m_pending_keys.empty();
}
Key JsonUI::get_key()
{
kak_assert(not m_pending_keys.empty());
Key key = m_pending_keys.front();
m_pending_keys.erase(m_pending_keys.begin());
return key;
}
void JsonUI::menu_show(ConstArrayView<DisplayLine> items,
CharCoord anchor, Face fg, Face bg,
MenuStyle style)
{
rpc_call("menu_show", items, anchor, fg, bg, style);
}
void JsonUI::menu_select(int selected)
{
rpc_call("menu_select", selected);
}
void JsonUI::menu_hide()
{
rpc_call("menu_hide");
}
void JsonUI::info_show(StringView title, StringView content,
CharCoord anchor, Face face,
InfoStyle style)
{
rpc_call("info_show", title, content, anchor, face, style);
}
void JsonUI::info_hide()
{
rpc_call("info_hide");
}
void JsonUI::refresh(bool force)
{
rpc_call("refresh", force);
}
void JsonUI::set_input_callback(InputCallback callback)
{
m_input_callback = std::move(callback);
}
void JsonUI::set_ui_options(const Options& options)
{
// rpc_call("set_ui_options", options);
}
CharCoord JsonUI::dimensions()
{
return m_dimensions;
}
using JsonArray = Vector<Value>;
using JsonObject = IdMap<Value>;
static bool is_digit(char c) { return c >= '0' and c <= '9'; }
std::tuple<Value, const char*>
parse_json(const char* pos, const char* end)
{
using Result = std::tuple<Value, const char*>;
if (not skip_while(pos, end, is_blank))
return {};
if (is_digit(*pos))
{
auto digit_end = pos;
skip_while(digit_end, end, is_digit);
return Result{ Value{str_to_int({pos, digit_end})}, digit_end };
}
if (end - pos > 4 and StringView{pos, pos+4} == "true")
return Result{ Value{true}, pos+4 };
if (end - pos > 5 and StringView{pos, pos+5} == "false")
return Result{ Value{false}, pos+5 };
if (*pos == '"')
{
String value;
bool escaped = false;
++pos;
for (auto string_end = pos; string_end != end; ++string_end)
{
if (escaped)
{
escaped = false;
value += StringView{pos, string_end};
value.back() = *string_end;
pos = string_end+1;
continue;
}
if (*string_end == '\\')
escaped = true;
if (*string_end == '"')
{
value += StringView{pos, string_end};
return Result{std::move(value), string_end+1};
}
}
return {};
}
if (*pos == '[')
{
JsonArray array;
if (*++pos == ']')
return Result{std::move(array), pos+1};
while (true)
{
Value element;
std::tie(element, pos) = parse_json(pos, end);
if (not element)
return {};
array.push_back(std::move(element));
if (not skip_while(pos, end, is_blank))
return {};
if (*pos == ',')
++pos;
else if (*pos == ']')
return Result{std::move(array), pos+1};
else
throw runtime_error("unable to parse array, expected ',' or ']'");
}
}
if (*pos == '{')
{
JsonObject object;
if (*++pos == '}')
return Result{std::move(object), pos+1};
while (true)
{
Value name_value;
std::tie(name_value, pos) = parse_json(pos, end);
if (not name_value)
return {};
String& name = name_value.as<String>();
if (not skip_while(pos, end, is_blank))
return {};
if (*pos++ != ':')
throw runtime_error("expected :");
Value element;
std::tie(element, pos) = parse_json(pos, end);
if (not element)
return {};
object.append({ std::move(name), std::move(element) });
if (not skip_while(pos, end, is_blank))
return {};
if (*pos == ',')
++pos;
else if (*pos == '}')
return Result{std::move(object), pos+1};
else
throw runtime_error("unable to parse object, expected ',' or '}'");
}
}
throw runtime_error("Could not parse json");
}
std::tuple<Value, const char*>
parse_json(StringView json) { return parse_json(json.begin(), json.end()); }
void JsonUI::eval_json(const Value& json)
{
if (not json.is_a<JsonObject>())
throw runtime_error("json request is not an object");
const JsonObject& object = json.as<JsonObject>();
auto json_it = object.find("jsonrpc");
if (json_it == object.end() or json_it->value.as<String>() != "2.0")
throw runtime_error("invalid json rpc request");
auto method_it = object.find("method");
if (method_it == object.end())
throw runtime_error("invalid json rpc request (method missing)");
StringView method = method_it->value.as<String>();
auto params_it = object.find("params");
if (params_it == object.end())
throw runtime_error("invalid json rpc request (params missing)");
const JsonArray& params = params_it->value.as<JsonArray>();
if (method == "keys")
{
for (auto& key_val : params)
{
for (auto& key : parse_keys(key_val.as<String>()))
m_pending_keys.push_back(key);
}
}
else if (method == "resize")
{
if (params.size() != 2)
throw runtime_error("resize expects 2 parameters");
CharCoord dim{params[0].as<int>(), params[1].as<int>()};
m_dimensions = dim;
m_pending_keys.push_back(resize(dim));
}
else
throw runtime_error("unknown method");
}
static bool stdin_ready()
{
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(0, &rfds);
timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
return select(1, &rfds, nullptr, nullptr, &tv) == 1;
}
void JsonUI::parse_requests(EventMode mode)
{
constexpr size_t bufsize = 1024;
char buf[bufsize];
while (stdin_ready())
{
ssize_t size = ::read(0, buf, bufsize);
if (size == -1 or size == 0)
break;
m_requests += StringView{buf, buf + size};
}
while (not m_requests.empty())
{
const char* pos = nullptr;
try
{
Value json;
std::tie(json, pos) = parse_json(m_requests);
if (json)
eval_json(json);
}
catch (runtime_error& error)
{
write_stderr(format("error while handling requests '{}': '{}'",
m_requests, error.what()));
// try to salvage request by dropping its first line
pos = std::min(m_requests.end(), find(m_requests, '\n')+1);
}
if (not pos)
break; // unterminated request ?
m_requests = String{pos, m_requests.end()};
}
while (m_input_callback and not m_pending_keys.empty())
m_input_callback(mode);
}
UnitTest test_json_parser{[]()
{
{
auto value = std::get<0>(parse_json(R"({ "jsonrpc": "2.0", "method": "keys", "params": [ "b", "l", "a", "h" ] })"));
kak_assert(value);
}
{
auto value = std::get<0>(parse_json("[10,20]"));
kak_assert(value and value.is_a<JsonArray>());
kak_assert(value.as<JsonArray>().at(1).as<int>() == 20);
}
{
auto value = std::get<0>(parse_json("{}"));
kak_assert(value and value.is_a<JsonObject>());
kak_assert(value.as<JsonObject>().empty());
}
}};
}
<|endoftext|>
|
<commit_before>#include "aerial_autonomy/controller_hardware_connectors/visual_servoing_controller_drone_connector.h"
PositionYaw VisualServoingControllerDroneConnector::extractSensorData() {
parsernode::common::quaddata quad_data;
drone_hardware_.getquaddata(quad_data);
tf::Vector3 tracking_position = getTrackingVectorGlobalFrame();
return PositionYaw(tracking_position.getX(), tracking_position.getY(),
tracking_position.getZ(), quad_data.rpydata.z);
}
void VisualServoingControllerDroneConnector::sendHardwareCommands(
VelocityYawRate controls) {
geometry_msgs::Vector3 velocity_cmd;
velocity_cmd.x = controls.x;
velocity_cmd.y = controls.y;
velocity_cmd.z = controls.z;
drone_hardware_.cmdvelguided(velocity_cmd, controls.yaw_rate);
}
tf::Vector3
VisualServoingControllerDroneConnector::getTrackingVectorGlobalFrame() {
Position object_position_cam;
if (!roi_to_position_converter_.getObjectPosition(object_position_cam)) {
/// \todo(Matt) handle case when cannot get object position
}
tf::Vector3 object_direction_cam(object_position_cam.x, object_position_cam.y,
object_position_cam.z);
// Convert from camera frame to global frame
return (getBodyFrameRotation() *
(camera_transform_.getBasis() * object_direction_cam))
.normalize();
}
tf::Matrix3x3 VisualServoingControllerDroneConnector::getBodyFrameRotation() {
parsernode::common::quaddata quad_data;
drone_hardware_.getquaddata(quad_data);
return tf::Matrix3x3(tf::createQuaternionFromRPY(
quad_data.rpydata.x, quad_data.rpydata.y, quad_data.rpydata.z));
}
<commit_msg>Add TODO<commit_after>#include "aerial_autonomy/controller_hardware_connectors/visual_servoing_controller_drone_connector.h"
PositionYaw VisualServoingControllerDroneConnector::extractSensorData() {
parsernode::common::quaddata quad_data;
drone_hardware_.getquaddata(quad_data);
tf::Vector3 tracking_position = getTrackingVectorGlobalFrame();
return PositionYaw(tracking_position.getX(), tracking_position.getY(),
tracking_position.getZ(), quad_data.rpydata.z);
}
void VisualServoingControllerDroneConnector::sendHardwareCommands(
VelocityYawRate controls) {
geometry_msgs::Vector3 velocity_cmd;
velocity_cmd.x = controls.x;
velocity_cmd.y = controls.y;
velocity_cmd.z = controls.z;
drone_hardware_.cmdvelguided(velocity_cmd, controls.yaw_rate);
/// \todo Gowtham Add function for commanding velocity with yaw rate
}
tf::Vector3
VisualServoingControllerDroneConnector::getTrackingVectorGlobalFrame() {
Position object_position_cam;
if (!roi_to_position_converter_.getObjectPosition(object_position_cam)) {
/// \todo(Matt) handle case when cannot get object position
}
tf::Vector3 object_direction_cam(object_position_cam.x, object_position_cam.y,
object_position_cam.z);
// Convert from camera frame to global frame
return (getBodyFrameRotation() *
(camera_transform_.getBasis() * object_direction_cam))
.normalize();
}
tf::Matrix3x3 VisualServoingControllerDroneConnector::getBodyFrameRotation() {
parsernode::common::quaddata quad_data;
drone_hardware_.getquaddata(quad_data);
return tf::Matrix3x3(tf::createQuaternionFromRPY(
quad_data.rpydata.x, quad_data.rpydata.y, quad_data.rpydata.z));
}
<|endoftext|>
|
<commit_before>// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "wfa/virtual_people/core/model/utils/distributed_consistent_hashing.h"
#include <cmath>
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "src/farmhash.h"
namespace wfa_virtual_people {
absl::StatusOr<std::unique_ptr<DistributedConsistentHashing>>
DistributedConsistentHashing::Build(
std::unique_ptr<std::vector<DistributionChoice>> distribution) {
if (distribution->empty()) {
return absl::InvalidArgumentError("The given distribution is empty.");
}
// Returns error status for any negative probability.
auto negative_probability_it = std::find_if(
distribution->begin(), distribution->end(),
[](const DistributionChoice& choice) {
return (choice.probability < 0);
});
if (negative_probability_it != distribution->end()) {
return absl::InvalidArgumentError("Negative probability is provided.");
}
// Gets sum of probabilities.
double probabilities_sum = 0.0;
std::for_each (distribution->begin(), distribution->end(),
[&probabilities_sum](const DistributionChoice& choice) {
probabilities_sum += choice.probability;
});
if (probabilities_sum <= 0) {
return absl::InvalidArgumentError("Probabilities sum is not positive.");
}
// Normalizes the probabilities.
std::for_each (distribution->begin(), distribution->end(),
[probabilities_sum](DistributionChoice& choice) {
choice.probability /= probabilities_sum;
});
return absl::make_unique<DistributedConsistentHashing>(
std::move(distribution));
}
std::string GetFullSeed(
absl::string_view random_seed, const int32_t choice) {
return absl::StrFormat("consistent-hashing-%s-%d", random_seed, choice);
}
inline double FloatHash(absl::string_view full_seed) {
return static_cast<double>(util::Fingerprint64(full_seed)) /
static_cast<double>(std::numeric_limits<uint64_t>::max());
}
double ComputeXi(
absl::string_view random_seed,
const int32_t choice, const double probability) {
return (-std::log(FloatHash(GetFullSeed(random_seed, choice))) /
probability);
}
// A C++ version of the Python function ConsistentHashing.hash in
// https://github.com/world-federation-of-advertisers/virtual_people_examples/blob/main/notebooks/Consistent_Hashing.ipynb
int32_t DistributedConsistentHashing::Hash(
absl::string_view random_seed) const {
auto it = distribution_->begin();
int32_t choice = it->choice_id;
double choice_xi = ComputeXi(random_seed, it->choice_id, it->probability);
for (++it; it != distribution_->end(); ++it) {
double xi = ComputeXi(random_seed, it->choice_id, it->probability);
if (choice_xi > xi) {
choice = it->choice_id;
choice_xi = xi;
}
}
return choice;
}
} // namespace wfa_virtual_people
<commit_msg>Use for-each loop instead of std::for_each and std::find_if.<commit_after>// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "wfa/virtual_people/core/model/utils/distributed_consistent_hashing.h"
#include <cmath>
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "src/farmhash.h"
namespace wfa_virtual_people {
absl::StatusOr<std::unique_ptr<DistributedConsistentHashing>>
DistributedConsistentHashing::Build(
std::unique_ptr<std::vector<DistributionChoice>> distribution) {
if (distribution->empty()) {
return absl::InvalidArgumentError("The given distribution is empty.");
}
// Returns error status for any negative probability, and gets sum of
// probabilities.
double probabilities_sum = 0.0;
for (const DistributionChoice& choice : *distribution) {
if (choice.probability < 0) {
return absl::InvalidArgumentError("Negative probability is provided.");
}
probabilities_sum += choice.probability;
}
if (probabilities_sum <= 0) {
return absl::InvalidArgumentError("Probabilities sum is not positive.");
}
// Normalizes the probabilities.
for (DistributionChoice& choice : *distribution) {
choice.probability /= probabilities_sum;
}
return absl::make_unique<DistributedConsistentHashing>(
std::move(distribution));
}
std::string GetFullSeed(
absl::string_view random_seed, const int32_t choice) {
return absl::StrFormat("consistent-hashing-%s-%d", random_seed, choice);
}
inline double FloatHash(absl::string_view full_seed) {
return static_cast<double>(util::Fingerprint64(full_seed)) /
static_cast<double>(std::numeric_limits<uint64_t>::max());
}
double ComputeXi(
absl::string_view random_seed,
const int32_t choice, const double probability) {
return (-std::log(FloatHash(GetFullSeed(random_seed, choice))) /
probability);
}
// A C++ version of the Python function ConsistentHashing.hash in
// https://github.com/world-federation-of-advertisers/virtual_people_examples/blob/main/notebooks/Consistent_Hashing.ipynb
int32_t DistributedConsistentHashing::Hash(
absl::string_view random_seed) const {
auto it = distribution_->begin();
int32_t choice = it->choice_id;
double choice_xi = ComputeXi(random_seed, it->choice_id, it->probability);
for (++it; it != distribution_->end(); ++it) {
double xi = ComputeXi(random_seed, it->choice_id, it->probability);
if (choice_xi > xi) {
choice = it->choice_id;
choice_xi = xi;
}
}
return choice;
}
} // namespace wfa_virtual_people
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2013 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.h"
#include <functional>
#include "ep_engine.h"
#include "flusher.h"
#include "kvshard.h"
KVShard::KVShard(uint16_t id, EventuallyPersistentStore &store) :
shardId(id), highPrioritySnapshot(false),
lowPrioritySnapshot(false),
kvConfig(store.getEPEngine().getConfiguration(), shardId),
highPriorityCount(0)
{
EPStats &stats = store.getEPEngine().getEpStats();
Configuration &config = store.getEPEngine().getConfiguration();
maxVbuckets = config.getMaxVbuckets();
vbuckets = new RCPtr<VBucket>[maxVbuckets];
std::string backend = kvConfig.getBackend();
uint16_t commitInterval = 1;
if (backend.compare("couchdb") == 0) {
rwUnderlying = KVStoreFactory::create(kvConfig, false);
roUnderlying = KVStoreFactory::create(kvConfig, true);
} else if (backend.compare("forestdb") == 0) {
rwUnderlying = KVStoreFactory::create(kvConfig);
roUnderlying = rwUnderlying;
commitInterval = config.getMaxVbuckets()/config.getMaxNumShards();
}
flusher = new Flusher(&store, this, commitInterval);
bgFetcher = new BgFetcher(&store, this, stats);
}
KVShard::~KVShard() {
if (flusher->state() != stopped) {
flusher->stop(true);
LOG(EXTENSION_LOG_WARNING, "Terminating flusher while it is in %s",
flusher->stateName());
}
delete flusher;
delete bgFetcher;
delete rwUnderlying;
/* Only couchstore has a read write store and a read only. ForestDB
* only has a read write store. Hence delete the read only store only
* in the case of couchstore.
*/
if (kvConfig.getBackend().compare("couchdb") == 0) {
delete roUnderlying;
}
delete[] vbuckets;
}
KVStore *KVShard::getRWUnderlying() {
return rwUnderlying;
}
KVStore *KVShard::getROUnderlying() {
return roUnderlying;
}
Flusher *KVShard::getFlusher() {
return flusher;
}
BgFetcher *KVShard::getBgFetcher() {
return bgFetcher;
}
void KVShard::notifyFlusher() {
flusher->notifyFlushEvent();
}
RCPtr<VBucket> KVShard::getBucket(uint16_t id) const {
if (id < maxVbuckets) {
return vbuckets[id];
} else {
return NULL;
}
}
void KVShard::setBucket(const RCPtr<VBucket> &vb) {
vbuckets[vb->getId()].reset(vb);
}
void KVShard::resetBucket(uint16_t id) {
vbuckets[id].reset();
}
std::vector<int> KVShard::getVBucketsSortedByState() {
std::vector<int> rv;
for (int state = vbucket_state_active;
state <= vbucket_state_dead;
++state) {
for (size_t i = 0; i < maxVbuckets; ++i) {
RCPtr<VBucket> b = vbuckets[i];
if (b && b->getState() == state) {
rv.push_back(b->getId());
}
}
}
return rv;
}
std::vector<int> KVShard::getVBuckets() {
std::vector<int> rv;
for (size_t i = 0; i < maxVbuckets; ++i) {
RCPtr<VBucket> b = vbuckets[i];
if (b) {
rv.push_back(b->getId());
}
}
return rv;
}
bool KVShard::setHighPriorityVbSnapshotFlag(bool highPriority) {
bool inverse = !highPriority;
return highPrioritySnapshot.compare_exchange_strong(inverse, highPriority);
}
bool KVShard::setLowPriorityVbSnapshotFlag(bool lowPriority) {
bool inverse = !lowPriority;
return lowPrioritySnapshot.compare_exchange_strong(inverse,
lowPrioritySnapshot);
}
void NotifyFlusherCB::callback(uint16_t &vb) {
if (shard->getBucket(vb)) {
shard->notifyFlusher();
}
}
<commit_msg>MB-15990: KVShard::setLowPriorityVbSnapshotFlag not working as expected.<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2013 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.h"
#include <functional>
#include "ep_engine.h"
#include "flusher.h"
#include "kvshard.h"
KVShard::KVShard(uint16_t id, EventuallyPersistentStore &store) :
shardId(id), highPrioritySnapshot(false),
lowPrioritySnapshot(false),
kvConfig(store.getEPEngine().getConfiguration(), shardId),
highPriorityCount(0)
{
EPStats &stats = store.getEPEngine().getEpStats();
Configuration &config = store.getEPEngine().getConfiguration();
maxVbuckets = config.getMaxVbuckets();
vbuckets = new RCPtr<VBucket>[maxVbuckets];
std::string backend = kvConfig.getBackend();
uint16_t commitInterval = 1;
if (backend.compare("couchdb") == 0) {
rwUnderlying = KVStoreFactory::create(kvConfig, false);
roUnderlying = KVStoreFactory::create(kvConfig, true);
} else if (backend.compare("forestdb") == 0) {
rwUnderlying = KVStoreFactory::create(kvConfig);
roUnderlying = rwUnderlying;
commitInterval = config.getMaxVbuckets()/config.getMaxNumShards();
}
flusher = new Flusher(&store, this, commitInterval);
bgFetcher = new BgFetcher(&store, this, stats);
}
KVShard::~KVShard() {
if (flusher->state() != stopped) {
flusher->stop(true);
LOG(EXTENSION_LOG_WARNING, "Terminating flusher while it is in %s",
flusher->stateName());
}
delete flusher;
delete bgFetcher;
delete rwUnderlying;
/* Only couchstore has a read write store and a read only. ForestDB
* only has a read write store. Hence delete the read only store only
* in the case of couchstore.
*/
if (kvConfig.getBackend().compare("couchdb") == 0) {
delete roUnderlying;
}
delete[] vbuckets;
}
KVStore *KVShard::getRWUnderlying() {
return rwUnderlying;
}
KVStore *KVShard::getROUnderlying() {
return roUnderlying;
}
Flusher *KVShard::getFlusher() {
return flusher;
}
BgFetcher *KVShard::getBgFetcher() {
return bgFetcher;
}
void KVShard::notifyFlusher() {
flusher->notifyFlushEvent();
}
RCPtr<VBucket> KVShard::getBucket(uint16_t id) const {
if (id < maxVbuckets) {
return vbuckets[id];
} else {
return NULL;
}
}
void KVShard::setBucket(const RCPtr<VBucket> &vb) {
vbuckets[vb->getId()].reset(vb);
}
void KVShard::resetBucket(uint16_t id) {
vbuckets[id].reset();
}
std::vector<int> KVShard::getVBucketsSortedByState() {
std::vector<int> rv;
for (int state = vbucket_state_active;
state <= vbucket_state_dead;
++state) {
for (size_t i = 0; i < maxVbuckets; ++i) {
RCPtr<VBucket> b = vbuckets[i];
if (b && b->getState() == state) {
rv.push_back(b->getId());
}
}
}
return rv;
}
std::vector<int> KVShard::getVBuckets() {
std::vector<int> rv;
for (size_t i = 0; i < maxVbuckets; ++i) {
RCPtr<VBucket> b = vbuckets[i];
if (b) {
rv.push_back(b->getId());
}
}
return rv;
}
bool KVShard::setHighPriorityVbSnapshotFlag(bool highPriority) {
bool inverse = !highPriority;
return highPrioritySnapshot.compare_exchange_strong(inverse, highPriority);
}
bool KVShard::setLowPriorityVbSnapshotFlag(bool lowPriority) {
bool inverse = !lowPriority;
return lowPrioritySnapshot.compare_exchange_strong(inverse, lowPriority);
}
void NotifyFlusherCB::callback(uint16_t &vb) {
if (shard->getBucket(vb)) {
shard->notifyFlusher();
}
}
<|endoftext|>
|
<commit_before>#include "Gearbox.h"
#define CHECK_EMPTY if(m_hValue.IsEmpty())from(undefined)
namespace Gearbox {
//void ValueList::push(Value that) {
// push(that.operator v8::Handle<v8::Value>());
//}
Value::~Value() {
if(!m_hValue.IsEmpty())
m_hValue.MakeWeak(0, weakCallback);
}
void Value::from(const Value &that) {
if(that.m_hValue.IsEmpty())
from(that.m_pValue);
else
from(that.m_hValue);
}
void Value::from(v8::Handle<v8::Value> that) {
//INSIDE(Value::from(v8::Handle<v8::Value>));
if(that.IsEmpty())
from(undefined);
else if(that->IsNumber() || that->IsUint32() || that->IsInt32() || that->IsUndefined() || that->IsNull() || that->IsBoolean()) {
m_hValue.Clear();
m_pValue.from(that);
}
else
m_hValue = v8::Persistent<v8::Value>::New(that);
}
void Value::from(Primitive that) {
m_hValue.Clear();
m_pValue = that;
}
String Value::to(Type<String>) {
v8::String::Utf8Value stringValue(m_hValue.IsEmpty() ? m_pValue.operator v8::Handle<v8::Value>() : m_hValue);
return String(*stringValue /*? *stringValue : "<string conversion failed>"*/);
}
int64_t Value::to(Type<int64_t>) {
if(m_hValue.IsEmpty()) {
if(m_pValue.m_Kind == Primitive::Number)return m_pValue.m_dValue;
else if(m_pValue.m_Kind == Primitive::True)return 1;
else if(m_pValue.m_Kind == Primitive::Integer)return m_pValue.m_iValue;
return 0;
}
return m_hValue->IntegerValue();
}
double Value::to(Type<double>) {
if(m_hValue.IsEmpty()) {
if(m_pValue.m_Kind == Primitive::Number)return m_pValue.m_dValue;
else if(m_pValue.m_Kind == Primitive::True)return 1;
else if(m_pValue.m_Kind == Primitive::Integer)return m_pValue.m_iValue;
return 0;
}
return m_hValue->NumberValue();
}
bool Value::to(Type<bool>) {
if(m_hValue.IsEmpty()) {
if(m_pValue.m_Kind == Primitive::Number)return m_pValue.m_dValue;
else if(m_pValue.m_Kind == Primitive::True)return true;
else if(m_pValue.m_Kind == Primitive::Integer)return m_pValue.m_iValue;
return false;
}
return m_hValue->BooleanValue();
}
Value::operator v8::Handle<v8::Value>() {
//INSIDE(Value::operator v8::Handle<v8::Value>);
if(m_hValue.IsEmpty())
return m_pValue;
else
return m_hValue;//::Local<v8::Value>::New(m_hValue);
}
int Value::length() {
if(m_hValue.IsEmpty())
return 0;
if(m_hValue->IsArray())
return v8::Handle<v8::Array>::Cast(m_hValue)->Length();
if(m_hValue->IsString())
return m_hValue->ToString()->Length();
return 0;
}
void Value::weakCallback(v8::Persistent<v8::Value> that, void*) {
if(that->IsExternal() || that->ToObject()->HasIndexedPropertiesInExternalArrayData())
printf("TODO: need to delete user-related stuff on disposal\n");
that.Dispose();
}
}<commit_msg>Gearbox: Removed an unused macro.<commit_after>#include "Gearbox.h"
namespace Gearbox {
//void ValueList::push(Value that) {
// push(that.operator v8::Handle<v8::Value>());
//}
Value::~Value() {
if(!m_hValue.IsEmpty())
m_hValue.MakeWeak(0, weakCallback);
}
void Value::from(const Value &that) {
if(that.m_hValue.IsEmpty())
from(that.m_pValue);
else
from(that.m_hValue);
}
void Value::from(v8::Handle<v8::Value> that) {
//INSIDE(Value::from(v8::Handle<v8::Value>));
if(that.IsEmpty())
from(undefined);
else if(that->IsNumber() || that->IsUint32() || that->IsInt32() || that->IsUndefined() || that->IsNull() || that->IsBoolean()) {
m_hValue.Clear();
m_pValue.from(that);
}
else
m_hValue = v8::Persistent<v8::Value>::New(that);
}
void Value::from(Primitive that) {
m_hValue.Clear();
m_pValue = that;
}
String Value::to(Type<String>) {
v8::String::Utf8Value stringValue(m_hValue.IsEmpty() ? m_pValue.operator v8::Handle<v8::Value>() : m_hValue);
return String(*stringValue /*? *stringValue : "<string conversion failed>"*/);
}
int64_t Value::to(Type<int64_t>) {
if(m_hValue.IsEmpty()) {
if(m_pValue.m_Kind == Primitive::Number)return m_pValue.m_dValue;
else if(m_pValue.m_Kind == Primitive::True)return 1;
else if(m_pValue.m_Kind == Primitive::Integer)return m_pValue.m_iValue;
return 0;
}
return m_hValue->IntegerValue();
}
double Value::to(Type<double>) {
if(m_hValue.IsEmpty()) {
if(m_pValue.m_Kind == Primitive::Number)return m_pValue.m_dValue;
else if(m_pValue.m_Kind == Primitive::True)return 1;
else if(m_pValue.m_Kind == Primitive::Integer)return m_pValue.m_iValue;
return 0;
}
return m_hValue->NumberValue();
}
bool Value::to(Type<bool>) {
if(m_hValue.IsEmpty()) {
if(m_pValue.m_Kind == Primitive::Number)return m_pValue.m_dValue;
else if(m_pValue.m_Kind == Primitive::True)return true;
else if(m_pValue.m_Kind == Primitive::Integer)return m_pValue.m_iValue;
return false;
}
return m_hValue->BooleanValue();
}
Value::operator v8::Handle<v8::Value>() {
//INSIDE(Value::operator v8::Handle<v8::Value>);
if(m_hValue.IsEmpty())
return m_pValue;
else
return m_hValue;//::Local<v8::Value>::New(m_hValue);
}
int Value::length() {
if(m_hValue.IsEmpty())
return 0;
if(m_hValue->IsArray())
return v8::Handle<v8::Array>::Cast(m_hValue)->Length();
if(m_hValue->IsString())
return m_hValue->ToString()->Length();
return 0;
}
void Value::weakCallback(v8::Persistent<v8::Value> that, void*) {
if(that->IsExternal() || that->ToObject()->HasIndexedPropertiesInExternalArrayData())
printf("TODO: need to delete user-related stuff on disposal\n");
that.Dispose();
}
}<|endoftext|>
|
<commit_before>// Scintilla source code edit control
/** @file KeyMap.cxx
** Defines a mapping between keystrokes and commands.
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include "Platform.h"
#include "Scintilla.h"
#include "KeyMap.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
KeyMap::KeyMap() : kmap(0), len(0), alloc(0) {
for (int i = 0; MapDefault[i].key; i++) {
AssignCmdKey(MapDefault[i].key,
MapDefault[i].modifiers,
MapDefault[i].msg);
}
}
KeyMap::~KeyMap() {
Clear();
}
void KeyMap::Clear() {
delete []kmap;
kmap = 0;
len = 0;
alloc = 0;
}
void KeyMap::AssignCmdKey(int key, int modifiers, unsigned int msg) {
if ((len+1) >= alloc) {
KeyToCommand *ktcNew = new KeyToCommand[alloc + 5];
if (!ktcNew)
return;
for (int k = 0; k < len; k++)
ktcNew[k] = kmap[k];
alloc += 5;
delete []kmap;
kmap = ktcNew;
}
for (int keyIndex = 0; keyIndex < len; keyIndex++) {
if ((key == kmap[keyIndex].key) && (modifiers == kmap[keyIndex].modifiers)) {
kmap[keyIndex].msg = msg;
return;
}
}
kmap[len].key = key;
kmap[len].modifiers = modifiers;
kmap[len].msg = msg;
len++;
}
unsigned int KeyMap::Find(int key, int modifiers) {
for (int i = 0; i < len; i++) {
if ((key == kmap[i].key) && (modifiers == kmap[i].modifiers)) {
return kmap[i].msg;
}
}
return 0;
}
const KeyToCommand KeyMap::MapDefault[] = {
{SCK_DOWN, SCI_NORM, SCI_LINEDOWN},
{SCK_DOWN, SCI_SHIFT, SCI_LINEDOWNEXTEND},
{SCK_DOWN, SCI_CTRL, SCI_LINESCROLLDOWN},
{SCK_DOWN, SCI_ASHIFT, SCI_LINEDOWNRECTEXTEND},
{SCK_UP, SCI_NORM, SCI_LINEUP},
{SCK_UP, SCI_SHIFT, SCI_LINEUPEXTEND},
{SCK_UP, SCI_CTRL, SCI_LINESCROLLUP},
{SCK_UP, SCI_ASHIFT, SCI_LINEUPRECTEXTEND},
{'[', SCI_CTRL, SCI_PARAUP},
{'[', SCI_CSHIFT, SCI_PARAUPEXTEND},
{']', SCI_CTRL, SCI_PARADOWN},
{']', SCI_CSHIFT, SCI_PARADOWNEXTEND},
{SCK_LEFT, SCI_NORM, SCI_CHARLEFT},
{SCK_LEFT, SCI_SHIFT, SCI_CHARLEFTEXTEND},
{SCK_LEFT, SCI_CTRL, SCI_WORDLEFT},
{SCK_LEFT, SCI_CSHIFT, SCI_WORDLEFTEXTEND},
{SCK_LEFT, SCI_ASHIFT, SCI_CHARLEFTRECTEXTEND},
{SCK_RIGHT, SCI_NORM, SCI_CHARRIGHT},
{SCK_RIGHT, SCI_SHIFT, SCI_CHARRIGHTEXTEND},
{SCK_RIGHT, SCI_CTRL, SCI_WORDRIGHT},
{SCK_RIGHT, SCI_CSHIFT, SCI_WORDRIGHTEXTEND},
{SCK_RIGHT, SCI_ASHIFT, SCI_CHARRIGHTRECTEXTEND},
{'/', SCI_CTRL, SCI_WORDPARTLEFT},
{'/', SCI_CSHIFT, SCI_WORDPARTLEFTEXTEND},
{'\\', SCI_CTRL, SCI_WORDPARTRIGHT},
{'\\', SCI_CSHIFT, SCI_WORDPARTRIGHTEXTEND},
{SCK_HOME, SCI_NORM, SCI_VCHOME},
{SCK_HOME, SCI_SHIFT, SCI_VCHOMEEXTEND},
{SCK_HOME, SCI_CTRL, SCI_DOCUMENTSTART},
{SCK_HOME, SCI_CSHIFT, SCI_DOCUMENTSTARTEXTEND},
{SCK_HOME, SCI_ALT, SCI_HOMEDISPLAY},
// {SCK_HOME, SCI_ASHIFT, SCI_HOMEDISPLAYEXTEND},
{SCK_HOME, SCI_ASHIFT, SCI_VCHOMERECTEXTEND},
{SCK_END, SCI_NORM, SCI_LINEEND},
{SCK_END, SCI_SHIFT, SCI_LINEENDEXTEND},
{SCK_END, SCI_CTRL, SCI_DOCUMENTEND},
{SCK_END, SCI_CSHIFT, SCI_DOCUMENTENDEXTEND},
{SCK_END, SCI_ALT, SCI_LINEENDDISPLAY},
// {SCK_END, SCI_ASHIFT, SCI_LINEENDDISPLAYEXTEND},
{SCK_END, SCI_ASHIFT, SCI_LINEENDRECTEXTEND},
{SCK_PRIOR, SCI_NORM, SCI_PAGEUP},
{SCK_PRIOR, SCI_SHIFT, SCI_PAGEUPEXTEND},
{SCK_PRIOR, SCI_ASHIFT, SCI_PAGEUPRECTEXTEND},
{SCK_NEXT, SCI_NORM, SCI_PAGEDOWN},
{SCK_NEXT, SCI_SHIFT, SCI_PAGEDOWNEXTEND},
{SCK_NEXT, SCI_ASHIFT, SCI_PAGEDOWNRECTEXTEND},
{SCK_DELETE, SCI_NORM, SCI_CLEAR},
{SCK_DELETE, SCI_SHIFT, SCI_CUT},
{SCK_DELETE, SCI_CTRL, SCI_DELWORDRIGHT},
{SCK_DELETE, SCI_CSHIFT, SCI_DELLINERIGHT},
{SCK_INSERT, SCI_NORM, SCI_EDITTOGGLEOVERTYPE},
{SCK_INSERT, SCI_SHIFT, SCI_PASTE},
{SCK_INSERT, SCI_CTRL, SCI_COPY},
{SCK_ESCAPE, SCI_NORM, SCI_CANCEL},
{SCK_BACK, SCI_NORM, SCI_DELETEBACK},
{SCK_BACK, SCI_SHIFT, SCI_DELETEBACK},
{SCK_BACK, SCI_CTRL, SCI_DELWORDLEFT},
{SCK_BACK, SCI_ALT, SCI_UNDO},
{SCK_BACK, SCI_CSHIFT, SCI_DELLINELEFT},
{'Z', SCI_CTRL, SCI_UNDO},
{'Y', SCI_CTRL, SCI_REDO},
{'X', SCI_CTRL, SCI_CUT},
{'C', SCI_CTRL, SCI_COPY},
{'V', SCI_CTRL, SCI_PASTE},
{'A', SCI_CTRL, SCI_SELECTALL},
{SCK_TAB, SCI_NORM, SCI_TAB},
{SCK_TAB, SCI_SHIFT, SCI_BACKTAB},
{SCK_RETURN, SCI_NORM, SCI_NEWLINE},
{SCK_RETURN, SCI_SHIFT, SCI_NEWLINE},
{SCK_ADD, SCI_CTRL, SCI_ZOOMIN},
{SCK_SUBTRACT, SCI_CTRL, SCI_ZOOMOUT},
{SCK_DIVIDE, SCI_CTRL, SCI_SETZOOM},
//'L', SCI_CTRL, SCI_FORMFEED,
{'L', SCI_CTRL, SCI_LINECUT},
{'L', SCI_CSHIFT, SCI_LINEDELETE},
{'T', SCI_CSHIFT, SCI_LINECOPY},
{'T', SCI_CTRL, SCI_LINETRANSPOSE},
{'D', SCI_CTRL, SCI_SELECTIONDUPLICATE},
{'U', SCI_CTRL, SCI_LOWERCASE},
{'U', SCI_CSHIFT, SCI_UPPERCASE},
{0,0,0},
};
<commit_msg>Integrate OS X key mapping into main key map.<commit_after>// Scintilla source code edit control
/** @file KeyMap.cxx
** Defines a mapping between keystrokes and commands.
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include "Platform.h"
#include "Scintilla.h"
#include "KeyMap.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
KeyMap::KeyMap() : kmap(0), len(0), alloc(0) {
for (int i = 0; MapDefault[i].key; i++) {
AssignCmdKey(MapDefault[i].key,
MapDefault[i].modifiers,
MapDefault[i].msg);
}
}
KeyMap::~KeyMap() {
Clear();
}
void KeyMap::Clear() {
delete []kmap;
kmap = 0;
len = 0;
alloc = 0;
}
void KeyMap::AssignCmdKey(int key, int modifiers, unsigned int msg) {
if ((len+1) >= alloc) {
KeyToCommand *ktcNew = new KeyToCommand[alloc + 5];
if (!ktcNew)
return;
for (int k = 0; k < len; k++)
ktcNew[k] = kmap[k];
alloc += 5;
delete []kmap;
kmap = ktcNew;
}
for (int keyIndex = 0; keyIndex < len; keyIndex++) {
if ((key == kmap[keyIndex].key) && (modifiers == kmap[keyIndex].modifiers)) {
kmap[keyIndex].msg = msg;
return;
}
}
kmap[len].key = key;
kmap[len].modifiers = modifiers;
kmap[len].msg = msg;
len++;
}
unsigned int KeyMap::Find(int key, int modifiers) {
for (int i = 0; i < len; i++) {
if ((key == kmap[i].key) && (modifiers == kmap[i].modifiers)) {
return kmap[i].msg;
}
}
return 0;
}
#if PLAT_GTK_MACOSX
#define OS_X_KEYS 1
#else
#define OS_X_KEYS 0
#endif
// Define a modifier that is exactly Ctrl key on all platforms
// Most uses of Ctrl map to Cmd on OS X but some can't so use SCI_[S]CTRL_META
#if OS_X_KEYS
#define SCI_CTRL_META SCI_META
#define SCI_SCTRL_META (SCI_META | SCI_SHIFT)
#else
#define SCI_CTRL_META SCI_CTRL
#define SCI_SCTRL_META (SCI_CTRL | SCI_SHIFT)
#endif
const KeyToCommand KeyMap::MapDefault[] = {
#if OS_X_KEYS
{SCK_DOWN, SCI_CTRL, SCI_DOCUMENTEND},
{SCK_DOWN, SCI_CSHIFT, SCI_DOCUMENTENDEXTEND},
{SCK_UP, SCI_CTRL, SCI_DOCUMENTSTART},
{SCK_UP, SCI_CSHIFT, SCI_DOCUMENTSTARTEXTEND},
{SCK_LEFT, SCI_CTRL, SCI_VCHOME},
{SCK_LEFT, SCI_CSHIFT, SCI_VCHOMEEXTEND},
{SCK_RIGHT, SCI_CTRL, SCI_LINEEND},
{SCK_RIGHT, SCI_CSHIFT, SCI_LINEENDEXTEND},
#endif
{SCK_DOWN, SCI_NORM, SCI_LINEDOWN},
{SCK_DOWN, SCI_SHIFT, SCI_LINEDOWNEXTEND},
{SCK_DOWN, SCI_CTRL_META, SCI_LINESCROLLDOWN},
{SCK_DOWN, SCI_ASHIFT, SCI_LINEDOWNRECTEXTEND},
{SCK_UP, SCI_NORM, SCI_LINEUP},
{SCK_UP, SCI_SHIFT, SCI_LINEUPEXTEND},
{SCK_UP, SCI_CTRL_META, SCI_LINESCROLLUP},
{SCK_UP, SCI_ASHIFT, SCI_LINEUPRECTEXTEND},
{'[', SCI_CTRL, SCI_PARAUP},
{'[', SCI_CSHIFT, SCI_PARAUPEXTEND},
{']', SCI_CTRL, SCI_PARADOWN},
{']', SCI_CSHIFT, SCI_PARADOWNEXTEND},
{SCK_LEFT, SCI_NORM, SCI_CHARLEFT},
{SCK_LEFT, SCI_SHIFT, SCI_CHARLEFTEXTEND},
{SCK_LEFT, SCI_CTRL_META, SCI_WORDLEFT},
{SCK_LEFT, SCI_SCTRL_META, SCI_WORDLEFTEXTEND},
{SCK_LEFT, SCI_ASHIFT, SCI_CHARLEFTRECTEXTEND},
{SCK_RIGHT, SCI_NORM, SCI_CHARRIGHT},
{SCK_RIGHT, SCI_SHIFT, SCI_CHARRIGHTEXTEND},
{SCK_RIGHT, SCI_CTRL_META, SCI_WORDRIGHT},
{SCK_RIGHT, SCI_SCTRL_META, SCI_WORDRIGHTEXTEND},
{SCK_RIGHT, SCI_ASHIFT, SCI_CHARRIGHTRECTEXTEND},
{'/', SCI_CTRL, SCI_WORDPARTLEFT},
{'/', SCI_CSHIFT, SCI_WORDPARTLEFTEXTEND},
{'\\', SCI_CTRL, SCI_WORDPARTRIGHT},
{'\\', SCI_CSHIFT, SCI_WORDPARTRIGHTEXTEND},
{SCK_HOME, SCI_NORM, SCI_VCHOME},
{SCK_HOME, SCI_SHIFT, SCI_VCHOMEEXTEND},
{SCK_HOME, SCI_CTRL, SCI_DOCUMENTSTART},
{SCK_HOME, SCI_CSHIFT, SCI_DOCUMENTSTARTEXTEND},
{SCK_HOME, SCI_ALT, SCI_HOMEDISPLAY},
{SCK_HOME, SCI_ASHIFT, SCI_VCHOMERECTEXTEND},
{SCK_END, SCI_NORM, SCI_LINEEND},
{SCK_END, SCI_SHIFT, SCI_LINEENDEXTEND},
{SCK_END, SCI_CTRL, SCI_DOCUMENTEND},
{SCK_END, SCI_CSHIFT, SCI_DOCUMENTENDEXTEND},
{SCK_END, SCI_ALT, SCI_LINEENDDISPLAY},
{SCK_END, SCI_ASHIFT, SCI_LINEENDRECTEXTEND},
{SCK_PRIOR, SCI_NORM, SCI_PAGEUP},
{SCK_PRIOR, SCI_SHIFT, SCI_PAGEUPEXTEND},
{SCK_PRIOR, SCI_ASHIFT, SCI_PAGEUPRECTEXTEND},
{SCK_NEXT, SCI_NORM, SCI_PAGEDOWN},
{SCK_NEXT, SCI_SHIFT, SCI_PAGEDOWNEXTEND},
{SCK_NEXT, SCI_ASHIFT, SCI_PAGEDOWNRECTEXTEND},
{SCK_DELETE, SCI_NORM, SCI_CLEAR},
{SCK_DELETE, SCI_SHIFT, SCI_CUT},
{SCK_DELETE, SCI_CTRL, SCI_DELWORDRIGHT},
{SCK_DELETE, SCI_CSHIFT, SCI_DELLINERIGHT},
{SCK_INSERT, SCI_NORM, SCI_EDITTOGGLEOVERTYPE},
{SCK_INSERT, SCI_SHIFT, SCI_PASTE},
{SCK_INSERT, SCI_CTRL, SCI_COPY},
{SCK_ESCAPE, SCI_NORM, SCI_CANCEL},
{SCK_BACK, SCI_NORM, SCI_DELETEBACK},
{SCK_BACK, SCI_SHIFT, SCI_DELETEBACK},
{SCK_BACK, SCI_CTRL, SCI_DELWORDLEFT},
{SCK_BACK, SCI_ALT, SCI_UNDO},
{SCK_BACK, SCI_CSHIFT, SCI_DELLINELEFT},
{'Z', SCI_CTRL, SCI_UNDO},
#if OS_X_KEYS
{'Z', SCI_CSHIFT, SCI_REDO},
#else
{'Y', SCI_CTRL, SCI_REDO},
#endif
{'X', SCI_CTRL, SCI_CUT},
{'C', SCI_CTRL, SCI_COPY},
{'V', SCI_CTRL, SCI_PASTE},
{'A', SCI_CTRL, SCI_SELECTALL},
{SCK_TAB, SCI_NORM, SCI_TAB},
{SCK_TAB, SCI_SHIFT, SCI_BACKTAB},
{SCK_RETURN, SCI_NORM, SCI_NEWLINE},
{SCK_RETURN, SCI_SHIFT, SCI_NEWLINE},
{SCK_ADD, SCI_CTRL, SCI_ZOOMIN},
{SCK_SUBTRACT, SCI_CTRL, SCI_ZOOMOUT},
{SCK_DIVIDE, SCI_CTRL, SCI_SETZOOM},
{'L', SCI_CTRL, SCI_LINECUT},
{'L', SCI_CSHIFT, SCI_LINEDELETE},
{'T', SCI_CSHIFT, SCI_LINECOPY},
{'T', SCI_CTRL, SCI_LINETRANSPOSE},
{'D', SCI_CTRL, SCI_SELECTIONDUPLICATE},
{'U', SCI_CTRL, SCI_LOWERCASE},
{'U', SCI_CSHIFT, SCI_UPPERCASE},
{0,0,0},
};
<|endoftext|>
|
<commit_before>// Scintilla source code edit control
/** @file LexCPP.cxx
** Lexer for C++, C, Java, and Javascript.
**/
// Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static bool IsOKBeforeRE(const int ch) {
return (ch == '(') || (ch == '=') || (ch == ',');
}
static inline bool IsAWordChar(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_');
}
static inline bool IsADoxygenChar(const int ch) {
return (islower(ch) || ch == '$' || ch == '@' ||
ch == '\\' || ch == '&' || ch == '<' ||
ch == '>' || ch == '#' || ch == '{' ||
ch == '}' || ch == '[' || ch == ']');
}
static inline bool IsStateComment(const int state) {
return ((state == SCE_C_COMMENT) ||
(state == SCE_C_COMMENTLINE) ||
(state == SCE_C_COMMENTDOC) ||
(state == SCE_C_COMMENTDOCKEYWORD) ||
(state == SCE_C_COMMENTDOCKEYWORDERROR));
}
static inline bool IsStateString(const int state) {
return ((state == SCE_C_STRING) || (state == SCE_C_VERBATIM));
}
static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor") != 0;
// Do not leak onto next line
if (initStyle == SCE_C_STRINGEOL)
initStyle = SCE_C_DEFAULT;
int chPrevNonWhite = ' ';
int visibleChars = 0;
bool lastWordWasUUID = false;
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
if (sc.atLineStart && (sc.state == SCE_C_STRING)) {
// Prevent SCE_C_STRINGEOL from leaking back to previous line
sc.SetState(SCE_C_STRING);
}
// Handle line continuation generically.
if (sc.ch == '\\') {
if (sc.Match("\\\n")) {
sc.Forward();
continue;
}
if (sc.Match("\\\r\n")) {
sc.Forward();
sc.Forward();
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_C_OPERATOR) {
sc.SetState(SCE_C_DEFAULT);
} else if (sc.state == SCE_C_NUMBER) {
if (!IsAWordChar(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || (sc.ch == '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
lastWordWasUUID = strcmp(s, "uuid") == 0;
sc.ChangeState(SCE_C_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_C_WORD2);
}
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_PREPROCESSOR) {
if (stylingWithinPreprocessor) {
if (IsASpace(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_COMMENT) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_COMMENTDOC) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '@' || sc.ch == '\\') {
sc.SetState(SCE_C_COMMENTDOCKEYWORD);
}
} else if (sc.state == SCE_C_COMMENTLINE || sc.state == SCE_C_COMMENTLINEDOC) {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_COMMENTDOCKEYWORD) {
if (sc.Match('*', '/')) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (!IsADoxygenChar(sc.ch)) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (!isspace(sc.ch) || !keywords3.InList(s+1)) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
}
sc.SetState(SCE_C_COMMENTDOC);
}
} else if (sc.state == SCE_C_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_CHARACTER) {
if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
} else if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_REGEX) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == '/') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '\\') {
// Gobble up the quoted character
if (sc.chNext == '\\' || sc.chNext == '/') {
sc.Forward();
}
}
} else if (sc.state == SCE_C_VERBATIM) {
if (sc.ch == '\"') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
sc.ForwardSetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_UUID) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ')') {
sc.SetState(SCE_C_DEFAULT);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_C_DEFAULT) {
if (sc.Match('@', '\"')) {
sc.SetState(SCE_C_VERBATIM);
sc.Forward();
} else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_NUMBER);
}
} else if (IsAWordStart(sc.ch) || (sc.ch == '@')) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_IDENTIFIER);
}
} else if (sc.Match('/', '*')) {
if (sc.Match("/**") || sc.Match("/*!")) { // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTDOC);
} else {
sc.SetState(SCE_C_COMMENT);
}
sc.Forward(); // Eat the * so it isn't used for the end of the comment
} else if (sc.Match('/', '/')) {
if (sc.Match("///") || sc.Match("//!")) // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTLINEDOC);
else
sc.SetState(SCE_C_COMMENTLINE);
} else if (sc.ch == '/' && IsOKBeforeRE(chPrevNonWhite)) {
sc.SetState(SCE_C_REGEX);
} else if (sc.ch == '\"') {
sc.SetState(SCE_C_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_C_CHARACTER);
} else if (sc.ch == '#' && visibleChars == 0) {
// Preprocessor commands are alone on their line
sc.SetState(SCE_C_PREPROCESSOR);
// Skip whitespace between # and preprocessor word
do {
sc.Forward();
} while ((sc.ch == ' ') && (sc.ch == '\t') && sc.More());
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (isoperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_C_OPERATOR);
}
}
if (sc.atLineEnd) {
// Reset states to begining of colourise so no surprises
// if different sets of lines lexed.
chPrevNonWhite = ' ';
visibleChars = 0;
lastWordWasUUID = false;
}
if (!IsASpace(sc.ch)) {
chPrevNonWhite = sc.ch;
visibleChars++;
}
}
sc.Complete();
}
static void FoldCppDoc(unsigned int startPos, int length, int initStyle, WordList *[],
Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style = initStyle;
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int stylePrev = style;
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment &&
(style == SCE_C_COMMENT || style == SCE_C_COMMENTDOC)) {
if (style != stylePrev) {
levelCurrent++;
} else if ((style != styleNext) && !atEOL) {
// Comments don't end at end of line and the next character may be unstyled.
levelCurrent--;
}
}
if (style == SCE_C_OPERATOR) {
if (ch == '{') {
levelCurrent++;
} else if (ch == '}') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const cppWordLists[] = {
"Primary keywords and identifiers",
"Secondary keywords and identifiers",
"Documentation comment keywords",
0,
};
LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc, "cpp", FoldCppDoc, cppWordLists);
LexerModule lmTCL(SCLEX_TCL, ColouriseCppDoc, "tcl", FoldCppDoc, cppWordLists);
<commit_msg>Fixed folding problem when keywords appeared in document comments.<commit_after>// Scintilla source code edit control
/** @file LexCPP.cxx
** Lexer for C++, C, Java, and Javascript.
**/
// Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static bool IsOKBeforeRE(const int ch) {
return (ch == '(') || (ch == '=') || (ch == ',');
}
static inline bool IsAWordChar(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_');
}
static inline bool IsADoxygenChar(const int ch) {
return (islower(ch) || ch == '$' || ch == '@' ||
ch == '\\' || ch == '&' || ch == '<' ||
ch == '>' || ch == '#' || ch == '{' ||
ch == '}' || ch == '[' || ch == ']');
}
static inline bool IsStateComment(const int state) {
return ((state == SCE_C_COMMENT) ||
(state == SCE_C_COMMENTLINE) ||
(state == SCE_C_COMMENTDOC) ||
(state == SCE_C_COMMENTDOCKEYWORD) ||
(state == SCE_C_COMMENTDOCKEYWORDERROR));
}
static inline bool IsStateString(const int state) {
return ((state == SCE_C_STRING) || (state == SCE_C_VERBATIM));
}
static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor") != 0;
// Do not leak onto next line
if (initStyle == SCE_C_STRINGEOL)
initStyle = SCE_C_DEFAULT;
int chPrevNonWhite = ' ';
int visibleChars = 0;
bool lastWordWasUUID = false;
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
if (sc.atLineStart && (sc.state == SCE_C_STRING)) {
// Prevent SCE_C_STRINGEOL from leaking back to previous line
sc.SetState(SCE_C_STRING);
}
// Handle line continuation generically.
if (sc.ch == '\\') {
if (sc.Match("\\\n")) {
sc.Forward();
continue;
}
if (sc.Match("\\\r\n")) {
sc.Forward();
sc.Forward();
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_C_OPERATOR) {
sc.SetState(SCE_C_DEFAULT);
} else if (sc.state == SCE_C_NUMBER) {
if (!IsAWordChar(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || (sc.ch == '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
lastWordWasUUID = strcmp(s, "uuid") == 0;
sc.ChangeState(SCE_C_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_C_WORD2);
}
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_PREPROCESSOR) {
if (stylingWithinPreprocessor) {
if (IsASpace(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_COMMENT) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_COMMENTDOC) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '@' || sc.ch == '\\') {
sc.SetState(SCE_C_COMMENTDOCKEYWORD);
}
} else if (sc.state == SCE_C_COMMENTLINE || sc.state == SCE_C_COMMENTLINEDOC) {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_COMMENTDOCKEYWORD) {
if (sc.Match('*', '/')) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (!IsADoxygenChar(sc.ch)) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (!isspace(sc.ch) || !keywords3.InList(s+1)) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
}
sc.SetState(SCE_C_COMMENTDOC);
}
} else if (sc.state == SCE_C_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_CHARACTER) {
if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
} else if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_REGEX) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == '/') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '\\') {
// Gobble up the quoted character
if (sc.chNext == '\\' || sc.chNext == '/') {
sc.Forward();
}
}
} else if (sc.state == SCE_C_VERBATIM) {
if (sc.ch == '\"') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
sc.ForwardSetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_UUID) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ')') {
sc.SetState(SCE_C_DEFAULT);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_C_DEFAULT) {
if (sc.Match('@', '\"')) {
sc.SetState(SCE_C_VERBATIM);
sc.Forward();
} else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_NUMBER);
}
} else if (IsAWordStart(sc.ch) || (sc.ch == '@')) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_IDENTIFIER);
}
} else if (sc.Match('/', '*')) {
if (sc.Match("/**") || sc.Match("/*!")) { // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTDOC);
} else {
sc.SetState(SCE_C_COMMENT);
}
sc.Forward(); // Eat the * so it isn't used for the end of the comment
} else if (sc.Match('/', '/')) {
if (sc.Match("///") || sc.Match("//!")) // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTLINEDOC);
else
sc.SetState(SCE_C_COMMENTLINE);
} else if (sc.ch == '/' && IsOKBeforeRE(chPrevNonWhite)) {
sc.SetState(SCE_C_REGEX);
} else if (sc.ch == '\"') {
sc.SetState(SCE_C_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_C_CHARACTER);
} else if (sc.ch == '#' && visibleChars == 0) {
// Preprocessor commands are alone on their line
sc.SetState(SCE_C_PREPROCESSOR);
// Skip whitespace between # and preprocessor word
do {
sc.Forward();
} while ((sc.ch == ' ') && (sc.ch == '\t') && sc.More());
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (isoperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_C_OPERATOR);
}
}
if (sc.atLineEnd) {
// Reset states to begining of colourise so no surprises
// if different sets of lines lexed.
chPrevNonWhite = ' ';
visibleChars = 0;
lastWordWasUUID = false;
}
if (!IsASpace(sc.ch)) {
chPrevNonWhite = sc.ch;
visibleChars++;
}
}
sc.Complete();
}
static bool IsStreamCommentStyle(int style) {
return style == SCE_C_COMMENT ||
style == SCE_C_COMMENTDOC ||
style == SCE_C_COMMENTDOCKEYWORD ||
style == SCE_C_COMMENTDOCKEYWORDERROR;
}
static void FoldCppDoc(unsigned int startPos, int length, int initStyle, WordList *[],
Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style = initStyle;
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int stylePrev = style;
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment && IsStreamCommentStyle(style)) {
if (!IsStreamCommentStyle(stylePrev)) {
levelCurrent++;
} else if (!IsStreamCommentStyle(styleNext) && !atEOL) {
// Comments don't end at end of line and the next character may be unstyled.
levelCurrent--;
}
}
if (style == SCE_C_OPERATOR) {
if (ch == '{') {
levelCurrent++;
} else if (ch == '}') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const cppWordLists[] = {
"Primary keywords and identifiers",
"Secondary keywords and identifiers",
"Documentation comment keywords",
0,
};
LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc, "cpp", FoldCppDoc, cppWordLists);
LexerModule lmTCL(SCLEX_TCL, ColouriseCppDoc, "tcl", FoldCppDoc, cppWordLists);
<|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 "chrome/browser/chromeos/login/wizard_accessibility_helper.h"
#include "base/logging.h"
#include "base/stl_util-inl.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_accessibility_api.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
#include "views/accelerator.h"
#include "views/view.h"
namespace chromeos {
scoped_ptr<views::Accelerator> WizardAccessibilityHelper::accelerator_;
// static
views::Accelerator WizardAccessibilityHelper::GetAccelerator() {
if (!WizardAccessibilityHelper::accelerator_.get())
WizardAccessibilityHelper::accelerator_.reset(
new views::Accelerator(app::VKEY_Z, false, true, true));
return *(WizardAccessibilityHelper::accelerator_.get());
}
// static
WizardAccessibilityHelper* WizardAccessibilityHelper::GetInstance() {
return Singleton<WizardAccessibilityHelper>::get();
}
WizardAccessibilityHelper::WizardAccessibilityHelper() {
accessibility_handler_.reset(new WizardAccessibilityHandler());
profile_ = ProfileManager::GetDefaultProfile();
registered_notifications_ = false;
}
void WizardAccessibilityHelper::RegisterNotifications() {
registrar_.Add(accessibility_handler_.get(),
NotificationType::ACCESSIBILITY_CONTROL_FOCUSED,
NotificationService::AllSources());
registrar_.Add(accessibility_handler_.get(),
NotificationType::ACCESSIBILITY_CONTROL_ACTION,
NotificationService::AllSources());
registrar_.Add(accessibility_handler_.get(),
NotificationType::ACCESSIBILITY_TEXT_CHANGED,
NotificationService::AllSources());
registrar_.Add(accessibility_handler_.get(),
NotificationType::ACCESSIBILITY_MENU_OPENED,
NotificationService::AllSources());
registrar_.Add(accessibility_handler_.get(),
NotificationType::ACCESSIBILITY_MENU_CLOSED,
NotificationService::AllSources());
registered_notifications_ = true;
}
void WizardAccessibilityHelper::UnregisterNotifications() {
if (!registered_notifications_)
return;
registrar_.RemoveAll();
registered_notifications_ = false;
}
void WizardAccessibilityHelper::MaybeEnableAccessibility(
views::View* view_tree) {
if (g_browser_process &&
g_browser_process->local_state()->GetBoolean(
prefs::kAccessibilityEnabled)) {
EnableAccessibility(view_tree);
} else {
AddViewToBuffer(view_tree);
}
}
void WizardAccessibilityHelper::MaybeSpeak(const char* str, bool queue,
bool interruptible) {
if (g_browser_process &&
g_browser_process->local_state()->GetBoolean(
prefs::kAccessibilityEnabled)) {
accessibility_handler_->Speak(str, queue, interruptible);
}
}
void WizardAccessibilityHelper::EnableAccessibility(views::View* view_tree) {
VLOG(1) << "Enabling accessibility.";
if (!registered_notifications_)
RegisterNotifications();
if (g_browser_process) {
PrefService* prefService = g_browser_process->local_state();
if (!prefService->GetBoolean(prefs::kAccessibilityEnabled)) {
prefService->SetBoolean(prefs::kAccessibilityEnabled, true);
prefService->ScheduleSavePersistentPrefs();
}
}
ExtensionAccessibilityEventRouter::GetInstance()->
SetAccessibilityEnabled(true);
AddViewToBuffer(view_tree);
// If accessibility pref is set, enable accessibility for all views in
// the buffer for which access is not yet enabled.
for (std::map<views::View*, bool>::iterator iter =
views_buffer_.begin();
iter != views_buffer_.end(); ++iter) {
if (!(*iter).second) {
AccessibleViewHelper *helper = new AccessibleViewHelper((*iter).first,
profile_);
accessible_view_helpers_.push_back(helper);
(*iter).second = true;
}
}
}
void WizardAccessibilityHelper::AddViewToBuffer(views::View* view_tree) {
if (!view_tree->GetWidget())
return;
bool view_exists = false;
// Check if the view is already queued for enabling accessibility.
// Prevent adding the same view in the buffer twice.
for (std::map<views::View*, bool>::iterator iter = views_buffer_.begin();
iter != views_buffer_.end(); ++iter) {
if ((*iter).first == view_tree) {
view_exists = true;
break;
}
}
if (!view_exists)
views_buffer_[view_tree] = false;
}
} // namespace chromeos
<commit_msg>Disable enable accessibility hotkey for ChromeOS login screen.<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 "chrome/browser/chromeos/login/wizard_accessibility_helper.h"
#include "base/logging.h"
#include "base/stl_util-inl.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_accessibility_api.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
#include "views/accelerator.h"
#include "views/view.h"
namespace chromeos {
scoped_ptr<views::Accelerator> WizardAccessibilityHelper::accelerator_;
// static
views::Accelerator WizardAccessibilityHelper::GetAccelerator() {
// Use an accelerator that would never match any hotkey to temporarily
// disable the accessibility hotkey per http://crosbug.com/9195
// TODO(xiyuan): Change back to real hotkey as the following
// new views::Accelerator(app::VKEY_Z, false, true, true)
if (!WizardAccessibilityHelper::accelerator_.get())
WizardAccessibilityHelper::accelerator_.reset(
new views::Accelerator(app::VKEY_UNKNOWN, 0xdeadbeef));
return *(WizardAccessibilityHelper::accelerator_.get());
}
// static
WizardAccessibilityHelper* WizardAccessibilityHelper::GetInstance() {
return Singleton<WizardAccessibilityHelper>::get();
}
WizardAccessibilityHelper::WizardAccessibilityHelper() {
accessibility_handler_.reset(new WizardAccessibilityHandler());
profile_ = ProfileManager::GetDefaultProfile();
registered_notifications_ = false;
}
void WizardAccessibilityHelper::RegisterNotifications() {
registrar_.Add(accessibility_handler_.get(),
NotificationType::ACCESSIBILITY_CONTROL_FOCUSED,
NotificationService::AllSources());
registrar_.Add(accessibility_handler_.get(),
NotificationType::ACCESSIBILITY_CONTROL_ACTION,
NotificationService::AllSources());
registrar_.Add(accessibility_handler_.get(),
NotificationType::ACCESSIBILITY_TEXT_CHANGED,
NotificationService::AllSources());
registrar_.Add(accessibility_handler_.get(),
NotificationType::ACCESSIBILITY_MENU_OPENED,
NotificationService::AllSources());
registrar_.Add(accessibility_handler_.get(),
NotificationType::ACCESSIBILITY_MENU_CLOSED,
NotificationService::AllSources());
registered_notifications_ = true;
}
void WizardAccessibilityHelper::UnregisterNotifications() {
if (!registered_notifications_)
return;
registrar_.RemoveAll();
registered_notifications_ = false;
}
void WizardAccessibilityHelper::MaybeEnableAccessibility(
views::View* view_tree) {
if (g_browser_process &&
g_browser_process->local_state()->GetBoolean(
prefs::kAccessibilityEnabled)) {
EnableAccessibility(view_tree);
} else {
AddViewToBuffer(view_tree);
}
}
void WizardAccessibilityHelper::MaybeSpeak(const char* str, bool queue,
bool interruptible) {
if (g_browser_process &&
g_browser_process->local_state()->GetBoolean(
prefs::kAccessibilityEnabled)) {
accessibility_handler_->Speak(str, queue, interruptible);
}
}
void WizardAccessibilityHelper::EnableAccessibility(views::View* view_tree) {
VLOG(1) << "Enabling accessibility.";
if (!registered_notifications_)
RegisterNotifications();
if (g_browser_process) {
PrefService* prefService = g_browser_process->local_state();
if (!prefService->GetBoolean(prefs::kAccessibilityEnabled)) {
prefService->SetBoolean(prefs::kAccessibilityEnabled, true);
prefService->ScheduleSavePersistentPrefs();
}
}
ExtensionAccessibilityEventRouter::GetInstance()->
SetAccessibilityEnabled(true);
AddViewToBuffer(view_tree);
// If accessibility pref is set, enable accessibility for all views in
// the buffer for which access is not yet enabled.
for (std::map<views::View*, bool>::iterator iter =
views_buffer_.begin();
iter != views_buffer_.end(); ++iter) {
if (!(*iter).second) {
AccessibleViewHelper *helper = new AccessibleViewHelper((*iter).first,
profile_);
accessible_view_helpers_.push_back(helper);
(*iter).second = true;
}
}
}
void WizardAccessibilityHelper::AddViewToBuffer(views::View* view_tree) {
if (!view_tree->GetWidget())
return;
bool view_exists = false;
// Check if the view is already queued for enabling accessibility.
// Prevent adding the same view in the buffer twice.
for (std::map<views::View*, bool>::iterator iter = views_buffer_.begin();
iter != views_buffer_.end(); ++iter) {
if ((*iter).first == view_tree) {
view_exists = true;
break;
}
}
if (!view_exists)
views_buffer_[view_tree] = false;
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>// Scintilla source code edit control
/** @file LexCSS.cxx
** Lexer for Cascade Style Sheets
** Written by Jakub Vrna
**/
// Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static inline bool IsAWordChar(const unsigned int ch) {
return (isalnum(ch) || ch == '-' || ch >= 161);
}
inline bool IsCssOperator(const char ch) {
if (!isalnum(ch) && (ch == '{' || ch == '}' || ch == ':' || ch == ',' || ch == ';' || ch == '.' || ch == '#' || ch == '!' || ch == '@'))
return true;
return false;
}
static void ColouriseCssDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &pseudoClasses = *keywordlists[1];
StyleContext sc(startPos, length, initStyle, styler);
int lastState = -1; // before operator
int lastStateC = -1; // before comment
int op = ' '; // last operator
for (; sc.More(); sc.Forward()) {
if (sc.state == SCE_CSS_COMMENT && sc.Match('*', '/')) {
if (lastStateC == -1) {
// backtrack to get last state
unsigned int i = startPos;
for (; i > 0; i--) {
if ((lastStateC = styler.StyleAt(i-1)) != SCE_CSS_COMMENT) {
if (lastStateC == SCE_CSS_OPERATOR) {
op = styler.SafeGetCharAt(i-1);
while (--i) {
lastState = styler.StyleAt(i-1);
if (lastState != SCE_CSS_OPERATOR && lastState != SCE_CSS_COMMENT)
break;
}
if (i == 0)
lastState = SCE_CSS_DEFAULT;
}
break;
}
}
if (i == 0)
lastStateC = SCE_CSS_DEFAULT;
}
sc.Forward();
sc.ForwardSetState(lastStateC);
}
if (sc.state == SCE_CSS_COMMENT)
continue;
if (sc.state == SCE_CSS_OPERATOR) {
if (op == ' ') {
unsigned int i = startPos;
op = styler.SafeGetCharAt(i-1);
while (--i) {
lastState = styler.StyleAt(i-1);
if (lastState != SCE_CSS_OPERATOR && lastState != SCE_CSS_COMMENT)
break;
}
}
switch (op) {
case '@':
if (lastState == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_DIRECTIVE);
break;
case '{':
if (lastState == SCE_CSS_DIRECTIVE)
sc.SetState(SCE_CSS_DEFAULT);
else if (lastState == SCE_CSS_TAG)
sc.SetState(SCE_CSS_IDENTIFIER);
break;
case '}':
if (lastState == SCE_CSS_DEFAULT || lastState == SCE_CSS_VALUE || lastState == SCE_CSS_IMPORTANT || lastState == SCE_CSS_IDENTIFIER)
sc.SetState(SCE_CSS_DEFAULT);
break;
case ':':
if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_DEFAULT || lastState == SCE_CSS_CLASS || lastState == SCE_CSS_ID)
sc.SetState(SCE_CSS_PSEUDOCLASS);
else if (lastState == SCE_CSS_IDENTIFIER || lastState == SCE_CSS_UNKNOWN_IDENTIFIER)
sc.SetState(SCE_CSS_VALUE);
break;
case '.':
if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_CLASS);
break;
case '#':
if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_ID);
break;
case ',':
if (lastState == SCE_CSS_TAG)
sc.SetState(SCE_CSS_DEFAULT);
break;
case ';':
if (lastState == SCE_CSS_DIRECTIVE)
sc.SetState(SCE_CSS_DEFAULT);
else if (lastState == SCE_CSS_VALUE || lastState == SCE_CSS_IMPORTANT)
sc.SetState(SCE_CSS_IDENTIFIER);
break;
case '!':
if (lastState == SCE_CSS_VALUE)
sc.SetState(SCE_CSS_IMPORTANT);
break;
}
}
if (IsAWordChar(sc.ch)) {
if (sc.state == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_TAG);
continue;
}
if (IsAWordChar(sc.chPrev) && (
sc.state == SCE_CSS_IDENTIFIER || sc.state == SCE_CSS_UNKNOWN_IDENTIFIER
|| sc.state == SCE_CSS_PSEUDOCLASS || sc.state == SCE_CSS_UNKNOWN_PSEUDOCLASS
|| sc.state == SCE_CSS_IMPORTANT
)) {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
char *s2 = s;
while (*s2 && !IsAWordChar(*s2))
s2++;
switch (sc.state) {
case SCE_CSS_IDENTIFIER:
if (!keywords.InList(s2))
sc.ChangeState(SCE_CSS_UNKNOWN_IDENTIFIER);
break;
case SCE_CSS_UNKNOWN_IDENTIFIER:
if (keywords.InList(s2))
sc.ChangeState(SCE_CSS_IDENTIFIER);
break;
case SCE_CSS_PSEUDOCLASS:
if (!pseudoClasses.InList(s2))
sc.ChangeState(SCE_CSS_UNKNOWN_PSEUDOCLASS);
break;
case SCE_CSS_UNKNOWN_PSEUDOCLASS:
if (pseudoClasses.InList(s2))
sc.ChangeState(SCE_CSS_PSEUDOCLASS);
break;
case SCE_CSS_IMPORTANT:
if (strcmp(s2, "important") != 0)
sc.ChangeState(SCE_CSS_VALUE);
break;
}
}
if (sc.ch != '.' && sc.ch != ':' && sc.ch != '#' && (sc.state == SCE_CSS_CLASS || sc.state == SCE_CSS_PSEUDOCLASS || sc.state == SCE_CSS_UNKNOWN_PSEUDOCLASS || sc.state == SCE_CSS_UNKNOWN_PSEUDOCLASS || sc.state == SCE_CSS_ID))
sc.SetState(SCE_CSS_TAG);
if (sc.Match('/', '*')) {
lastStateC = sc.state;
sc.SetState(SCE_CSS_COMMENT);
sc.Forward();
continue;
}
if (IsCssOperator(static_cast<char>(sc.ch))
&& (sc.state != SCE_CSS_VALUE || sc.ch == ';' || sc.ch == '}' || sc.ch == '!')
&& (sc.state != SCE_CSS_DIRECTIVE || sc.ch == ';' || sc.ch == '{')
) {
if (sc.state != SCE_CSS_OPERATOR)
lastState = sc.state;
sc.SetState(SCE_CSS_OPERATOR);
op = sc.ch;
}
}
sc.Complete();
}
static void FoldCSSDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool inComment = (styler.StyleAt(startPos-1) == SCE_CSS_COMMENT);
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styler.StyleAt(i);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment) {
if (!inComment && (style == SCE_CSS_COMMENT))
levelCurrent++;
else if (inComment && (style != SCE_CSS_COMMENT))
levelCurrent--;
inComment = (style == SCE_CSS_COMMENT);
}
if (style == SCE_CSS_OPERATOR) {
if (ch == '{') {
levelCurrent++;
} else if (ch == '}') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
LexerModule lmCss(SCLEX_CSS, ColouriseCssDoc, "css", FoldCSSDoc);
<commit_msg>Upgraded keyword list descriptions from Brian Quinlan.<commit_after>// Scintilla source code edit control
/** @file LexCSS.cxx
** Lexer for Cascade Style Sheets
** Written by Jakub Vrna
**/
// Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static inline bool IsAWordChar(const unsigned int ch) {
return (isalnum(ch) || ch == '-' || ch >= 161);
}
inline bool IsCssOperator(const char ch) {
if (!isalnum(ch) && (ch == '{' || ch == '}' || ch == ':' || ch == ',' || ch == ';' || ch == '.' || ch == '#' || ch == '!' || ch == '@'))
return true;
return false;
}
static void ColouriseCssDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &pseudoClasses = *keywordlists[1];
StyleContext sc(startPos, length, initStyle, styler);
int lastState = -1; // before operator
int lastStateC = -1; // before comment
int op = ' '; // last operator
for (; sc.More(); sc.Forward()) {
if (sc.state == SCE_CSS_COMMENT && sc.Match('*', '/')) {
if (lastStateC == -1) {
// backtrack to get last state
unsigned int i = startPos;
for (; i > 0; i--) {
if ((lastStateC = styler.StyleAt(i-1)) != SCE_CSS_COMMENT) {
if (lastStateC == SCE_CSS_OPERATOR) {
op = styler.SafeGetCharAt(i-1);
while (--i) {
lastState = styler.StyleAt(i-1);
if (lastState != SCE_CSS_OPERATOR && lastState != SCE_CSS_COMMENT)
break;
}
if (i == 0)
lastState = SCE_CSS_DEFAULT;
}
break;
}
}
if (i == 0)
lastStateC = SCE_CSS_DEFAULT;
}
sc.Forward();
sc.ForwardSetState(lastStateC);
}
if (sc.state == SCE_CSS_COMMENT)
continue;
if (sc.state == SCE_CSS_OPERATOR) {
if (op == ' ') {
unsigned int i = startPos;
op = styler.SafeGetCharAt(i-1);
while (--i) {
lastState = styler.StyleAt(i-1);
if (lastState != SCE_CSS_OPERATOR && lastState != SCE_CSS_COMMENT)
break;
}
}
switch (op) {
case '@':
if (lastState == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_DIRECTIVE);
break;
case '{':
if (lastState == SCE_CSS_DIRECTIVE)
sc.SetState(SCE_CSS_DEFAULT);
else if (lastState == SCE_CSS_TAG)
sc.SetState(SCE_CSS_IDENTIFIER);
break;
case '}':
if (lastState == SCE_CSS_DEFAULT || lastState == SCE_CSS_VALUE || lastState == SCE_CSS_IMPORTANT || lastState == SCE_CSS_IDENTIFIER)
sc.SetState(SCE_CSS_DEFAULT);
break;
case ':':
if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_DEFAULT || lastState == SCE_CSS_CLASS || lastState == SCE_CSS_ID)
sc.SetState(SCE_CSS_PSEUDOCLASS);
else if (lastState == SCE_CSS_IDENTIFIER || lastState == SCE_CSS_UNKNOWN_IDENTIFIER)
sc.SetState(SCE_CSS_VALUE);
break;
case '.':
if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_CLASS);
break;
case '#':
if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_ID);
break;
case ',':
if (lastState == SCE_CSS_TAG)
sc.SetState(SCE_CSS_DEFAULT);
break;
case ';':
if (lastState == SCE_CSS_DIRECTIVE)
sc.SetState(SCE_CSS_DEFAULT);
else if (lastState == SCE_CSS_VALUE || lastState == SCE_CSS_IMPORTANT)
sc.SetState(SCE_CSS_IDENTIFIER);
break;
case '!':
if (lastState == SCE_CSS_VALUE)
sc.SetState(SCE_CSS_IMPORTANT);
break;
}
}
if (IsAWordChar(sc.ch)) {
if (sc.state == SCE_CSS_DEFAULT)
sc.SetState(SCE_CSS_TAG);
continue;
}
if (IsAWordChar(sc.chPrev) && (
sc.state == SCE_CSS_IDENTIFIER || sc.state == SCE_CSS_UNKNOWN_IDENTIFIER
|| sc.state == SCE_CSS_PSEUDOCLASS || sc.state == SCE_CSS_UNKNOWN_PSEUDOCLASS
|| sc.state == SCE_CSS_IMPORTANT
)) {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
char *s2 = s;
while (*s2 && !IsAWordChar(*s2))
s2++;
switch (sc.state) {
case SCE_CSS_IDENTIFIER:
if (!keywords.InList(s2))
sc.ChangeState(SCE_CSS_UNKNOWN_IDENTIFIER);
break;
case SCE_CSS_UNKNOWN_IDENTIFIER:
if (keywords.InList(s2))
sc.ChangeState(SCE_CSS_IDENTIFIER);
break;
case SCE_CSS_PSEUDOCLASS:
if (!pseudoClasses.InList(s2))
sc.ChangeState(SCE_CSS_UNKNOWN_PSEUDOCLASS);
break;
case SCE_CSS_UNKNOWN_PSEUDOCLASS:
if (pseudoClasses.InList(s2))
sc.ChangeState(SCE_CSS_PSEUDOCLASS);
break;
case SCE_CSS_IMPORTANT:
if (strcmp(s2, "important") != 0)
sc.ChangeState(SCE_CSS_VALUE);
break;
}
}
if (sc.ch != '.' && sc.ch != ':' && sc.ch != '#' && (sc.state == SCE_CSS_CLASS || sc.state == SCE_CSS_PSEUDOCLASS || sc.state == SCE_CSS_UNKNOWN_PSEUDOCLASS || sc.state == SCE_CSS_UNKNOWN_PSEUDOCLASS || sc.state == SCE_CSS_ID))
sc.SetState(SCE_CSS_TAG);
if (sc.Match('/', '*')) {
lastStateC = sc.state;
sc.SetState(SCE_CSS_COMMENT);
sc.Forward();
continue;
}
if (IsCssOperator(static_cast<char>(sc.ch))
&& (sc.state != SCE_CSS_VALUE || sc.ch == ';' || sc.ch == '}' || sc.ch == '!')
&& (sc.state != SCE_CSS_DIRECTIVE || sc.ch == ';' || sc.ch == '{')
) {
if (sc.state != SCE_CSS_OPERATOR)
lastState = sc.state;
sc.SetState(SCE_CSS_OPERATOR);
op = sc.ch;
}
}
sc.Complete();
}
static void FoldCSSDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool inComment = (styler.StyleAt(startPos-1) == SCE_CSS_COMMENT);
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styler.StyleAt(i);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment) {
if (!inComment && (style == SCE_CSS_COMMENT))
levelCurrent++;
else if (inComment && (style != SCE_CSS_COMMENT))
levelCurrent--;
inComment = (style == SCE_CSS_COMMENT);
}
if (style == SCE_CSS_OPERATOR) {
if (ch == '{') {
levelCurrent++;
} else if (ch == '}') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const cssWordListDesc[] = {
"Keywords",
"Pseudo classes",
0
};
LexerModule lmCss(SCLEX_CSS, ColouriseCssDoc, "css", FoldCSSDoc, cssWordListDesc);
<|endoftext|>
|
<commit_before>#include "libtiff.hh"
using namespace node;
using namespace v8;
Persistent<FunctionTemplate> TIFFFile::constructor_template;
namespace node {
void TIFFFile::Initialize(Handle<Object> target) {
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(TIFFFile::New);
constructor_template = Persistent<FunctionTemplate>::New(t);
constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
constructor_template->SetClassName(String::NewSymbol("TIFFFile"));
constructor_template->InstanceTemplate()->
SetAccessor(String::NewSymbol("IMAGEWIDTH"), TIFFFile::fieldsGetter);
constructor_template->InstanceTemplate()->
SetAccessor(String::NewSymbol("IMAGELENGTH"), TIFFFile::fieldsGetter);
constructor_template->InstanceTemplate()->
SetAccessor(String::NewSymbol("BITSPERSAMPLE"), TIFFFile::fieldsGetter);
constructor_template->InstanceTemplate()->
SetAccessor(String::NewSymbol("SAMPLESPERPIXEL"), TIFFFile::fieldsGetter);
constructor_template->InstanceTemplate()->
SetAccessor(String::NewSymbol("PLANARCONFIG"), TIFFFile::fieldsGetter);
constructor_template->InstanceTemplate()->
SetAccessor(String::NewSymbol("PHOTOMETRIC"), TIFFFile::fieldsGetter);
constructor_template->InstanceTemplate()->
SetAccessor(String::NewSymbol("ORIENTATION"), TIFFFile::fieldsGetter);
constructor_template->InstanceTemplate()->
SetAccessor(String::NewSymbol("scanlineSize"), TIFFFile::fieldsGetter);
constructor_template->InstanceTemplate()->
SetAccessor(String::NewSymbol("filename"), TIFFFile::fieldsGetter);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "pushAsPage", TIFFFile::pushAsPage);
target->Set(String::NewSymbol("TIFFFile"), constructor_template->GetFunction());
}
Handle<Value> TIFFFile::New(const Arguments &args) {
HandleScope scope;
TIFFFile *tifffile;
/* Validate input parameters */
if (args.Length() == 2 && args[0]->IsString() && args[1]->IsString()) {
String::Utf8Value filename(args[0]);
String::Utf8Value mode(args[1]);
/* Open tiff file */
TIFF* tif = TIFFOpen(*filename, *mode);
/* Check for success */
if (tif != NULL) {
/* Create TIFFFile object */
tifffile = new TIFFFile(tif, *filename, (strcmp(*mode, "r") != 0));
} else {
/* Throw an error */
return ThrowException(Exception::TypeError(String::New("Can't open tiff file.")));
}
} else {
/* Throw an error */
return ThrowException(Exception::TypeError(String::New("Invalid params (String filename, String mode)")));
}
/* Wrap object */
tifffile->Wrap(args.This());
/* Return new TIFFFile */
return args.This();
}
Handle<Value> TIFFFile::fieldsGetter(Local< String > property, const AccessorInfo &info) {
HandleScope scope;
TIFFFile *self = ObjectWrap::Unwrap<TIFFFile>(info.This());
String::Utf8Value propName(property);
if (strcmp(*propName, "IMAGEWIDTH") == 0) {
uint32 imageWidth;
TIFFGetField(self->tif, TIFFTAG_IMAGEWIDTH, &imageWidth);
return scope.Close(Uint32::New(imageWidth));
} else if (strcmp(*propName, "IMAGELENGTH") == 0) {
uint32 imageLength;
TIFFGetField(self->tif, TIFFTAG_IMAGELENGTH, &imageLength);
return scope.Close(Uint32::New(imageLength));
} else if (strcmp(*propName, "BITSPERSAMPLE") == 0) {
uint16 bps;
TIFFGetField(self->tif, TIFFTAG_BITSPERSAMPLE, &bps);
return scope.Close(Uint32::New(bps));
} else if (strcmp(*propName, "SAMPLESPERPIXEL") == 0) {
uint16 spp;
TIFFGetField(self->tif, TIFFTAG_SAMPLESPERPIXEL, &spp);
return scope.Close(Uint32::New(spp));
} else if (strcmp(*propName, "PLANARCONFIG") == 0) {
uint16 pc;
TIFFGetField(self->tif, TIFFTAG_PLANARCONFIG, &pc);
return scope.Close(Uint32::New(pc));
} else if (strcmp(*propName, "PHOTOMETRIC") == 0) {
uint16 pm;
TIFFGetField(self->tif, TIFFTAG_PHOTOMETRIC, &pm);
return scope.Close(Uint32::New(pm));
} else if (strcmp(*propName, "ORIENTATION") == 0) {
uint16 o9n;
TIFFGetFieldDefaulted(self->tif, TIFFTAG_ORIENTATION, &o9n);
return scope.Close(Uint32::New(o9n));
} else if (strcmp(*propName, "scanlineSize") == 0) {
int32 ss;
ss = TIFFScanlineSize(self->tif);
return scope.Close(Int32::New(ss));
} else if (strcmp(*propName, "filename") == 0) {
return scope.Close(String::New(self->filename));
} else {
return scope.Close(Undefined());
}
}
Handle<Value> TIFFFile::pushAsPage(const Arguments &args) {
HandleScope scope;
TIFFFile *self = ObjectWrap::Unwrap<TIFFFile>(args.This());
if (!self->forWrite) {
return ThrowException(Exception::TypeError(String::New("Destination tiff must be opened for writing.")));
}
if (args.Length() != 1 || !TIFFFile::HasInstance(args[0])) {
return ThrowException(Exception::TypeError(String::New("Invalid params (TIFFFile source)")));
}
TIFFFile *src = ObjectWrap::Unwrap<TIFFFile>(args[0]->ToObject());
if (src->forWrite) {
return ThrowException(Exception::TypeError(String::New("Source tiff must be opened for reading.")));
}
uint32 imageWidth, imageLength;
uint16 bitsPerSample, samplesPerPixel, planarConfig, photometric, orientation;
int32 scanlineSize;
tdata_t buf;
TIFFGetField(src->tif, TIFFTAG_IMAGEWIDTH, &imageWidth);
TIFFGetField(src->tif, TIFFTAG_IMAGELENGTH, &imageLength);
TIFFGetField(src->tif, TIFFTAG_BITSPERSAMPLE, &bitsPerSample);
TIFFGetField(src->tif, TIFFTAG_SAMPLESPERPIXEL, &samplesPerPixel);
TIFFGetField(src->tif, TIFFTAG_PLANARCONFIG, &planarConfig);
TIFFGetField(src->tif, TIFFTAG_PHOTOMETRIC, &photometric);
TIFFGetFieldDefaulted(src->tif, TIFFTAG_ORIENTATION, &orientation);
scanlineSize = TIFFScanlineSize(src->tif);
TIFFSetField(self->tif, TIFFTAG_COMPRESSION, COMPRESSION_LZW);
TIFFSetField(self->tif, TIFFTAG_IMAGEWIDTH, imageWidth);
TIFFSetField(self->tif, TIFFTAG_IMAGELENGTH, imageLength);
TIFFSetField(self->tif, TIFFTAG_BITSPERSAMPLE, bitsPerSample);
TIFFSetField(self->tif, TIFFTAG_SAMPLESPERPIXEL, samplesPerPixel);
TIFFSetField(self->tif, TIFFTAG_PLANARCONFIG, planarConfig);
TIFFSetField(self->tif, TIFFTAG_PHOTOMETRIC, photometric);
TIFFSetField(self->tif, TIFFTAG_ORIENTATION, orientation);
TIFFSetField(self->tif, TIFFTAG_SUBFILETYPE, FILETYPE_PAGE);
TIFFSetField(self->tif, TIFFTAG_PAGENUMBER, self->pageNumber, self->pageNumber + 1);
buf = _TIFFmalloc(scanlineSize);
if (planarConfig == PLANARCONFIG_CONTIG) {
for (uint32 i = 0; i < imageLength; i++) {
TIFFReadScanline(src->tif, buf, i);
TIFFWriteScanline(self->tif, buf, i);
}
} else if (planarConfig == PLANARCONFIG_SEPARATE) {
for (uint16 s = 0; s < samplesPerPixel; s++) {
for (uint32 i = 0; i < imageLength; i++) {
TIFFReadScanline(self->tif, buf, i, s);
TIFFWriteScanline(self->tif, buf, i, s);
}
}
for (uint32 i = 0; i < imageLength; i++) {
TIFFReadScanline(src->tif, buf, i, 0);
TIFFWriteScanline(self->tif, buf, i, 0);
}
}
_TIFFfree(buf);
TIFFWriteDirectory(self->tif);
self->pageNumber++;
return args.This();
}
}
// Exporting function
extern "C" void
init (v8::Handle<v8::Object> target)
{
HandleScope scope;
TIFFFile::Initialize(target);
}
NODE_MODULE(tiff_multipage, init);<commit_msg>Already have one captain..<commit_after>#include "libtiff.hh"
using namespace node;
using namespace v8;
Persistent<FunctionTemplate> TIFFFile::constructor_template;
namespace node {
void TIFFFile::Initialize(Handle<Object> target) {
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(TIFFFile::New);
constructor_template = Persistent<FunctionTemplate>::New(t);
constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
constructor_template->SetClassName(String::NewSymbol("TIFFFile"));
constructor_template->InstanceTemplate()->
SetAccessor(String::NewSymbol("IMAGEWIDTH"), TIFFFile::fieldsGetter);
constructor_template->InstanceTemplate()->
SetAccessor(String::NewSymbol("IMAGELENGTH"), TIFFFile::fieldsGetter);
constructor_template->InstanceTemplate()->
SetAccessor(String::NewSymbol("BITSPERSAMPLE"), TIFFFile::fieldsGetter);
constructor_template->InstanceTemplate()->
SetAccessor(String::NewSymbol("SAMPLESPERPIXEL"), TIFFFile::fieldsGetter);
constructor_template->InstanceTemplate()->
SetAccessor(String::NewSymbol("PLANARCONFIG"), TIFFFile::fieldsGetter);
constructor_template->InstanceTemplate()->
SetAccessor(String::NewSymbol("PHOTOMETRIC"), TIFFFile::fieldsGetter);
constructor_template->InstanceTemplate()->
SetAccessor(String::NewSymbol("ORIENTATION"), TIFFFile::fieldsGetter);
constructor_template->InstanceTemplate()->
SetAccessor(String::NewSymbol("scanlineSize"), TIFFFile::fieldsGetter);
constructor_template->InstanceTemplate()->
SetAccessor(String::NewSymbol("filename"), TIFFFile::fieldsGetter);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "pushAsPage", TIFFFile::pushAsPage);
target->Set(String::NewSymbol("TIFFFile"), constructor_template->GetFunction());
}
Handle<Value> TIFFFile::New(const Arguments &args) {
HandleScope scope;
TIFFFile *tifffile;
if (args.Length() == 2 && args[0]->IsString() && args[1]->IsString()) {
String::Utf8Value filename(args[0]);
String::Utf8Value mode(args[1]);
TIFF* tif = TIFFOpen(*filename, *mode);
if (tif != NULL) {
tifffile = new TIFFFile(tif, *filename, (strcmp(*mode, "r") != 0));
} else {
return ThrowException(Exception::TypeError(String::New("Can't open tiff file.")));
}
} else {
return ThrowException(Exception::TypeError(String::New("Invalid params (String filename, String mode)")));
}
tifffile->Wrap(args.This());
return args.This();
}
Handle<Value> TIFFFile::fieldsGetter(Local< String > property, const AccessorInfo &info) {
HandleScope scope;
TIFFFile *self = ObjectWrap::Unwrap<TIFFFile>(info.This());
String::Utf8Value propName(property);
if (strcmp(*propName, "IMAGEWIDTH") == 0) {
uint32 imageWidth;
TIFFGetField(self->tif, TIFFTAG_IMAGEWIDTH, &imageWidth);
return scope.Close(Uint32::New(imageWidth));
} else if (strcmp(*propName, "IMAGELENGTH") == 0) {
uint32 imageLength;
TIFFGetField(self->tif, TIFFTAG_IMAGELENGTH, &imageLength);
return scope.Close(Uint32::New(imageLength));
} else if (strcmp(*propName, "BITSPERSAMPLE") == 0) {
uint16 bps;
TIFFGetField(self->tif, TIFFTAG_BITSPERSAMPLE, &bps);
return scope.Close(Uint32::New(bps));
} else if (strcmp(*propName, "SAMPLESPERPIXEL") == 0) {
uint16 spp;
TIFFGetField(self->tif, TIFFTAG_SAMPLESPERPIXEL, &spp);
return scope.Close(Uint32::New(spp));
} else if (strcmp(*propName, "PLANARCONFIG") == 0) {
uint16 pc;
TIFFGetField(self->tif, TIFFTAG_PLANARCONFIG, &pc);
return scope.Close(Uint32::New(pc));
} else if (strcmp(*propName, "PHOTOMETRIC") == 0) {
uint16 pm;
TIFFGetField(self->tif, TIFFTAG_PHOTOMETRIC, &pm);
return scope.Close(Uint32::New(pm));
} else if (strcmp(*propName, "ORIENTATION") == 0) {
uint16 o9n;
TIFFGetFieldDefaulted(self->tif, TIFFTAG_ORIENTATION, &o9n);
return scope.Close(Uint32::New(o9n));
} else if (strcmp(*propName, "scanlineSize") == 0) {
int32 ss;
ss = TIFFScanlineSize(self->tif);
return scope.Close(Int32::New(ss));
} else if (strcmp(*propName, "filename") == 0) {
return scope.Close(String::New(self->filename));
} else {
return scope.Close(Undefined());
}
}
Handle<Value> TIFFFile::pushAsPage(const Arguments &args) {
HandleScope scope;
TIFFFile *self = ObjectWrap::Unwrap<TIFFFile>(args.This());
if (!self->forWrite) {
return ThrowException(Exception::TypeError(String::New("Destination tiff must be opened for writing.")));
}
if (args.Length() != 1 || !TIFFFile::HasInstance(args[0])) {
return ThrowException(Exception::TypeError(String::New("Invalid params (TIFFFile source)")));
}
TIFFFile *src = ObjectWrap::Unwrap<TIFFFile>(args[0]->ToObject());
if (src->forWrite) {
return ThrowException(Exception::TypeError(String::New("Source tiff must be opened for reading.")));
}
uint32 imageWidth, imageLength;
uint16 bitsPerSample, samplesPerPixel, planarConfig, photometric, orientation;
int32 scanlineSize;
tdata_t buf;
TIFFGetField(src->tif, TIFFTAG_IMAGEWIDTH, &imageWidth);
TIFFGetField(src->tif, TIFFTAG_IMAGELENGTH, &imageLength);
TIFFGetField(src->tif, TIFFTAG_BITSPERSAMPLE, &bitsPerSample);
TIFFGetField(src->tif, TIFFTAG_SAMPLESPERPIXEL, &samplesPerPixel);
TIFFGetField(src->tif, TIFFTAG_PLANARCONFIG, &planarConfig);
TIFFGetField(src->tif, TIFFTAG_PHOTOMETRIC, &photometric);
TIFFGetFieldDefaulted(src->tif, TIFFTAG_ORIENTATION, &orientation);
scanlineSize = TIFFScanlineSize(src->tif);
TIFFSetField(self->tif, TIFFTAG_COMPRESSION, COMPRESSION_LZW);
TIFFSetField(self->tif, TIFFTAG_IMAGEWIDTH, imageWidth);
TIFFSetField(self->tif, TIFFTAG_IMAGELENGTH, imageLength);
TIFFSetField(self->tif, TIFFTAG_BITSPERSAMPLE, bitsPerSample);
TIFFSetField(self->tif, TIFFTAG_SAMPLESPERPIXEL, samplesPerPixel);
TIFFSetField(self->tif, TIFFTAG_PLANARCONFIG, planarConfig);
TIFFSetField(self->tif, TIFFTAG_PHOTOMETRIC, photometric);
TIFFSetField(self->tif, TIFFTAG_ORIENTATION, orientation);
TIFFSetField(self->tif, TIFFTAG_SUBFILETYPE, FILETYPE_PAGE);
TIFFSetField(self->tif, TIFFTAG_PAGENUMBER, self->pageNumber, self->pageNumber + 1);
buf = _TIFFmalloc(scanlineSize);
if (planarConfig == PLANARCONFIG_CONTIG) {
for (uint32 i = 0; i < imageLength; i++) {
TIFFReadScanline(src->tif, buf, i);
TIFFWriteScanline(self->tif, buf, i);
}
} else if (planarConfig == PLANARCONFIG_SEPARATE) {
for (uint16 s = 0; s < samplesPerPixel; s++) {
for (uint32 i = 0; i < imageLength; i++) {
TIFFReadScanline(self->tif, buf, i, s);
TIFFWriteScanline(self->tif, buf, i, s);
}
}
for (uint32 i = 0; i < imageLength; i++) {
TIFFReadScanline(src->tif, buf, i, 0);
TIFFWriteScanline(self->tif, buf, i, 0);
}
}
_TIFFfree(buf);
TIFFWriteDirectory(self->tif);
self->pageNumber++;
return args.This();
}
}
// Exporting function
extern "C" void
init (v8::Handle<v8::Object> target)
{
HandleScope scope;
TIFFFile::Initialize(target);
}
NODE_MODULE(tiff_multipage, init);<|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 "chrome/browser/password_manager/password_form_data.h"
#include "chrome/browser/sync/sessions/session_state.h"
#include "chrome/test/live_sync/live_passwords_sync_test.h"
using webkit_glue::PasswordForm;
static const char* kValidPassphrase = "passphrase!";
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, FAILS_Add) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, Add) {
#endif
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
PasswordForm form;
form.origin = GURL("http://www.google.com/");
form.username_value = ASCIIToUTF16("username");
form.password_value = ASCIIToUTF16("password");
AddLogin(GetVerifierPasswordStore(), form);
AddLogin(GetPasswordStore(0), form);
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
std::vector<PasswordForm> expected;
GetLogins(GetVerifierPasswordStore(), form, expected);
ASSERT_EQ(1U, expected.size());
std::vector<PasswordForm> actual_zero;
GetLogins(GetPasswordStore(0), form, actual_zero);
ASSERT_TRUE(ContainsSamePasswordForms(expected, actual_zero));
std::vector<PasswordForm> actual_one;
GetLogins(GetPasswordStore(1), form, actual_one);
ASSERT_TRUE(ContainsSamePasswordForms(expected, actual_one));
}
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, FAILS_Race) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, Race) {
#endif
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
PasswordForm form;
form.origin = GURL("http://www.google.com/");
PasswordForm form_zero;
form_zero.origin = GURL("http://www.google.com/");
form_zero.username_value = ASCIIToUTF16("username");
form_zero.password_value = ASCIIToUTF16("zero");
AddLogin(GetPasswordStore(0), form_zero);
PasswordForm form_one;
form_one.origin = GURL("http://www.google.com/");
form_one.username_value = ASCIIToUTF16("username");
form_one.password_value = ASCIIToUTF16("one");
AddLogin(GetPasswordStore(1), form_one);
ASSERT_TRUE(AwaitQuiescence());
std::vector<PasswordForm> actual_zero;
GetLogins(GetPasswordStore(0), form, actual_zero);
ASSERT_EQ(1U, actual_zero.size());
std::vector<PasswordForm> actual_one;
GetLogins(GetPasswordStore(1), form, actual_one);
ASSERT_EQ(1U, actual_one.size());
ASSERT_TRUE(ContainsSamePasswordForms(actual_zero, actual_one));
}
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, FAILS_SetPassphrase) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, SetPassphrase) {
#endif
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
GetClient(0)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(0)->AwaitPassphraseAccepted();
GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1));
ASSERT_TRUE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
}
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
FAILS_SetPassphraseAndAddPassword) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
SetPassphraseAndAddPassword) {
#endif
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
GetClient(0)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(0)->AwaitPassphraseAccepted();
PasswordForm form;
form.origin = GURL("http://www.google.com/");
form.username_value = ASCIIToUTF16("username");
form.password_value = ASCIIToUTF16("password");
AddLogin(GetPasswordStore(0), form);
GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1));
ASSERT_TRUE(GetClient(1)->service()->observed_passphrase_required());
ASSERT_EQ(1, GetClient(1)->GetLastSessionSnapshot()->
num_conflicting_updates);
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->AwaitSyncCycleCompletion("Accept passphrase and decrypt.");
ASSERT_EQ(0, GetClient(1)->GetLastSessionSnapshot()->
num_conflicting_updates);
}
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
FAILS_SetPassphraseAndThenSetupSync) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
SetPassphraseAndThenSetupSync) {
#endif
ASSERT_TRUE(SetupClients()) << "SetupClients() failed.";
ASSERT_TRUE(GetClient(0)->SetupSync());
GetClient(0)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(0)->AwaitPassphraseAccepted();
GetClient(0)->AwaitSyncCycleCompletion("Initial sync.");
ASSERT_TRUE(GetClient(1)->SetupSync());
ASSERT_TRUE(AwaitQuiescence());
ASSERT_TRUE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
}
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
FAILS_SetPassphraseTwice) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
SetPassphraseTwice) {
#endif
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
GetClient(0)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(0)->AwaitPassphraseAccepted();
GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1));
ASSERT_TRUE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
}
<commit_msg>Disabling a couple of failing passphrase sync tests.<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 "chrome/browser/password_manager/password_form_data.h"
#include "chrome/browser/sync/sessions/session_state.h"
#include "chrome/test/live_sync/live_passwords_sync_test.h"
using webkit_glue::PasswordForm;
static const char* kValidPassphrase = "passphrase!";
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, FAILS_Add) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, Add) {
#endif
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
PasswordForm form;
form.origin = GURL("http://www.google.com/");
form.username_value = ASCIIToUTF16("username");
form.password_value = ASCIIToUTF16("password");
AddLogin(GetVerifierPasswordStore(), form);
AddLogin(GetPasswordStore(0), form);
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
std::vector<PasswordForm> expected;
GetLogins(GetVerifierPasswordStore(), form, expected);
ASSERT_EQ(1U, expected.size());
std::vector<PasswordForm> actual_zero;
GetLogins(GetPasswordStore(0), form, actual_zero);
ASSERT_TRUE(ContainsSamePasswordForms(expected, actual_zero));
std::vector<PasswordForm> actual_one;
GetLogins(GetPasswordStore(1), form, actual_one);
ASSERT_TRUE(ContainsSamePasswordForms(expected, actual_one));
}
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, FAILS_Race) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, Race) {
#endif
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
PasswordForm form;
form.origin = GURL("http://www.google.com/");
PasswordForm form_zero;
form_zero.origin = GURL("http://www.google.com/");
form_zero.username_value = ASCIIToUTF16("username");
form_zero.password_value = ASCIIToUTF16("zero");
AddLogin(GetPasswordStore(0), form_zero);
PasswordForm form_one;
form_one.origin = GURL("http://www.google.com/");
form_one.username_value = ASCIIToUTF16("username");
form_one.password_value = ASCIIToUTF16("one");
AddLogin(GetPasswordStore(1), form_one);
ASSERT_TRUE(AwaitQuiescence());
std::vector<PasswordForm> actual_zero;
GetLogins(GetPasswordStore(0), form, actual_zero);
ASSERT_EQ(1U, actual_zero.size());
std::vector<PasswordForm> actual_one;
GetLogins(GetPasswordStore(1), form, actual_one);
ASSERT_EQ(1U, actual_one.size());
ASSERT_TRUE(ContainsSamePasswordForms(actual_zero, actual_one));
}
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, FAILS_SetPassphrase) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, SetPassphrase) {
#endif
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
GetClient(0)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(0)->AwaitPassphraseAccepted();
GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1));
ASSERT_TRUE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
}
// TODO(sync): Remove FAILS_ annotation after http://crbug.com/59867 is fixed.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
FAILS_SetPassphraseAndAddPassword) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
SetPassphraseAndAddPassword) {
#endif
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
GetClient(0)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(0)->AwaitPassphraseAccepted();
PasswordForm form;
form.origin = GURL("http://www.google.com/");
form.username_value = ASCIIToUTF16("username");
form.password_value = ASCIIToUTF16("password");
AddLogin(GetPasswordStore(0), form);
GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1));
ASSERT_TRUE(GetClient(1)->service()->observed_passphrase_required());
ASSERT_EQ(1, GetClient(1)->GetLastSessionSnapshot()->
num_conflicting_updates);
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->AwaitSyncCycleCompletion("Accept passphrase and decrypt.");
ASSERT_EQ(0, GetClient(1)->GetLastSessionSnapshot()->
num_conflicting_updates);
}
// TODO(sync): Remove DISABLED_ annotation after http://crbug.com/59867 and
// http://crbug.com/67862 are fixed.
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
DISABLED_SetPassphraseAndThenSetupSync) {
ASSERT_TRUE(SetupClients()) << "SetupClients() failed.";
ASSERT_TRUE(GetClient(0)->SetupSync());
GetClient(0)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(0)->AwaitPassphraseAccepted();
GetClient(0)->AwaitSyncCycleCompletion("Initial sync.");
ASSERT_TRUE(GetClient(1)->SetupSync());
ASSERT_TRUE(AwaitQuiescence());
ASSERT_TRUE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
}
// TODO(sync): Remove DISABLED_ annotation after http://crbug.com/59867 and
// http://crbug.com/67862 are fixed.
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
DISABLED_SetPassphraseTwice) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
GetClient(0)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(0)->AwaitPassphraseAccepted();
GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1));
ASSERT_TRUE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
GetClient(1)->service()->SetPassphrase(kValidPassphrase, true);
GetClient(1)->AwaitPassphraseAccepted();
ASSERT_FALSE(GetClient(1)->service()->observed_passphrase_required());
}
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Lewis Baker
// Licenced under MIT license. See LICENSE.txt for details.
///////////////////////////////////////////////////////////////////////////////
#ifndef CPPCORO_DETAIL_WIN32_OVERLAPPED_OPERATION_HPP_INCLUDED
#define CPPCORO_DETAIL_WIN32_OVERLAPPED_OPERATION_HPP_INCLUDED
#include <cppcoro/cancellation_registration.hpp>
#include <cppcoro/cancellation_token.hpp>
#include <cppcoro/operation_cancelled.hpp>
#include <cppcoro/detail/win32.hpp>
#include <optional>
#include <system_error>
#include <experimental/coroutine>
#include <cassert>
namespace cppcoro
{
namespace detail
{
class win32_overlapped_operation_base
: protected detail::win32::io_state
{
public:
win32_overlapped_operation_base(
detail::win32::io_state::callback_type* callback) noexcept
: detail::win32::io_state(callback)
, m_errorCode(0)
, m_numberOfBytesTransferred(0)
{}
win32_overlapped_operation_base(
void* pointer,
detail::win32::io_state::callback_type* callback) noexcept
: detail::win32::io_state(pointer, callback)
, m_errorCode(0)
, m_numberOfBytesTransferred(0)
{}
win32_overlapped_operation_base(
std::uint64_t offset,
detail::win32::io_state::callback_type* callback) noexcept
: detail::win32::io_state(offset, callback)
, m_errorCode(0)
, m_numberOfBytesTransferred(0)
{}
_OVERLAPPED* get_overlapped() noexcept
{
return reinterpret_cast<_OVERLAPPED*>(
static_cast<detail::win32::overlapped*>(this));
}
std::size_t get_result()
{
if (m_errorCode != 0)
{
throw std::system_error{
static_cast<int>(m_errorCode),
std::system_category()
};
}
return m_numberOfBytesTransferred;
}
detail::win32::dword_t m_errorCode;
detail::win32::dword_t m_numberOfBytesTransferred;
};
template<typename OPERATION>
class win32_overlapped_operation
: protected win32_overlapped_operation_base
{
protected:
win32_overlapped_operation() noexcept
: win32_overlapped_operation_base(
&win32_overlapped_operation::on_operation_completed)
{}
win32_overlapped_operation(void* pointer) noexcept
: win32_overlapped_operation_base(
pointer,
&win32_overlapped_operation::on_operation_completed)
{}
win32_overlapped_operation(std::uint64_t offset) noexcept
: win32_overlapped_operation_base(
offset,
&win32_overlapped_operation::on_operation_completed)
{}
public:
bool await_ready() const noexcept { return false; }
bool await_suspend(std::experimental::coroutine_handle<> awaitingCoroutine)
{
static_assert(std::is_base_of_v<win32_overlapped_operation, OPERATION>);
m_awaitingCoroutine = awaitingCoroutine;
return static_cast<OPERATION*>(this)->try_start();
}
decltype(auto) await_resume()
{
return static_cast<OPERATION*>(this)->get_result();
}
private:
static void on_operation_completed(
detail::win32::io_state* ioState,
detail::win32::dword_t errorCode,
detail::win32::dword_t numberOfBytesTransferred,
[[maybe_unused]] detail::win32::ulongptr_t completionKey) noexcept
{
auto* operation = static_cast<win32_overlapped_operation*>(ioState);
operation->m_errorCode = errorCode;
operation->m_numberOfBytesTransferred = numberOfBytesTransferred;
operation->m_awaitingCoroutine.resume();
}
std::experimental::coroutine_handle<> m_awaitingCoroutine;
};
template<typename OPERATION>
class win32_overlapped_operation_cancellable
: protected win32_overlapped_operation_base
{
// ERROR_OPERATION_ABORTED value from <Windows.h>
static constexpr detail::win32::dword_t error_operation_aborted = 995L;
protected:
win32_overlapped_operation_cancellable(cancellation_token&& ct) noexcept
: win32_overlapped_operation_base(&win32_overlapped_operation_cancellable::on_operation_completed)
, m_state(ct.is_cancellation_requested() ? state::completed : state::not_started)
, m_cancellationToken(std::move(ct))
{
m_errorCode = error_operation_aborted;
}
win32_overlapped_operation_cancellable(
void* pointer,
cancellation_token&& ct) noexcept
: win32_overlapped_operation_base(pointer, &win32_overlapped_operation_cancellable::on_operation_completed)
, m_state(ct.is_cancellation_requested() ? state::completed : state::not_started)
, m_cancellationToken(std::move(ct))
{
m_errorCode = error_operation_aborted;
}
win32_overlapped_operation_cancellable(
std::uint64_t offset,
cancellation_token&& ct) noexcept
: win32_overlapped_operation_base(offset, &win32_overlapped_operation_cancellable::on_operation_completed)
, m_state(ct.is_cancellation_requested() ? state::completed : state::not_started)
, m_cancellationToken(std::move(ct))
{
m_errorCode = error_operation_aborted;
}
win32_overlapped_operation_cancellable(
win32_overlapped_operation_cancellable&& other) noexcept
: win32_overlapped_operation_base(std::move(other))
, m_state(other.m_state.load(std::memory_order_relaxed))
, m_cancellationToken(std::move(other.m_cancellationToken))
{
assert(m_errorCode == other.m_errorCode);
assert(m_numberOfBytesTransferred == other.m_numberOfBytesTransferred);
}
public:
bool await_ready() const noexcept
{
return m_state.load(std::memory_order_relaxed) == state::completed;
}
bool await_suspend(std::experimental::coroutine_handle<> awaitingCoroutine)
{
static_assert(std::is_base_of_v<win32_overlapped_operation_cancellable, OPERATION>);
m_awaitingCoroutine = awaitingCoroutine;
// TRICKY: Register cancellation callback before starting the operation
// in case the callback registration throws due to insufficient
// memory. We need to make sure that the logic that occurs after
// starting the operation is noexcept, otherwise we run into the
// problem of not being able to cancel the started operation and
// the dilemma of what to do with the exception.
//
// However, doing this means that the cancellation callback may run
// prior to returning below so in the case that cancellation may
// occur we defer setting the state to 'started' until after
// the operation has finished starting. The cancellation callback
// will only attempt to request cancellation of the operation with
// CancelIoEx() once the state has been set to 'started'.
const bool canBeCancelled = m_cancellationToken.can_be_cancelled();
if (canBeCancelled)
{
m_cancellationCallback.emplace(
std::move(m_cancellationToken),
[this] { this->on_cancellation_requested(); });
}
else
{
m_state.store(state::started, std::memory_order_relaxed);
}
// Now start the operation.
const bool willCompleteAsynchronously = static_cast<OPERATION*>(this)->try_start();
if (!willCompleteAsynchronously)
{
// Operation completed synchronously, resume awaiting coroutine immediately.
return false;
}
if (canBeCancelled)
{
// Need to flag that the operation has finished starting now.
// However, the operation may have completed concurrently on
// another thread, transitioning directly from not_started -> complete.
// Or it may have had the cancellation callback execute and transition
// from not_started -> cancellation_requested. We use a compare-exchange
// to determine a winner between these potential racing cases.
state oldState = state::not_started;
if (!m_state.compare_exchange_strong(
oldState,
state::started,
std::memory_order_release,
std::memory_order_acquire))
{
if (oldState == state::cancellation_requested)
{
// Request the operation be cancelled.
// Note that it may have already completed on a background
// thread by now so this request for cancellation may end up
// being ignored.
static_cast<OPERATION*>(this)->cancel();
if (!m_state.compare_exchange_strong(
oldState,
state::started,
std::memory_order_release,
std::memory_order_acquire))
{
assert(oldState == state::completed);
return false;
}
}
else
{
assert(oldState == state::completed);
return false;
}
}
}
return true;
}
decltype(auto) await_resume()
{
// Free memory used by the cancellation callback now that the operation
// has completed rather than waiting until the operation object destructs.
// eg. If the operation is passed to when_all() then the operation object
// may not be destructed until all of the operations complete.
m_cancellationCallback.reset();
if (m_errorCode == error_operation_aborted)
{
throw operation_cancelled{};
}
return static_cast<OPERATION*>(this)->get_result();
}
private:
enum class state
{
not_started,
started,
cancellation_requested,
completed
};
void on_cancellation_requested() noexcept
{
auto oldState = m_state.load(std::memory_order_acquire);
if (oldState == state::not_started)
{
// This callback is running concurrently with await_suspend().
// The call to start the operation may not have returned yet so
// we can't safely request cancellation of it. Instead we try to
// notify the await_suspend() thread by transitioning the state
// to state::cancellation_requested so that the await_suspend()
// thread can request cancellation after it has finished starting
// the operation.
const bool transferredCancelResponsibility =
m_state.compare_exchange_strong(
oldState,
state::cancellation_requested,
std::memory_order_release,
std::memory_order_acquire);
if (transferredCancelResponsibility)
{
return;
}
}
// No point requesting cancellation if the operation has already completed.
if (oldState != state::completed)
{
static_cast<OPERATION*>(this)->cancel();
}
}
static void on_operation_completed(
detail::win32::io_state* ioState,
detail::win32::dword_t errorCode,
detail::win32::dword_t numberOfBytesTransferred,
[[maybe_unused]] detail::win32::ulongptr_t completionKey) noexcept
{
auto* operation = static_cast<win32_overlapped_operation_cancellable*>(ioState);
operation->m_errorCode = errorCode;
operation->m_numberOfBytesTransferred = numberOfBytesTransferred;
auto state = operation->m_state.load(std::memory_order_acquire);
if (state == state::started)
{
operation->m_state.store(state::completed, std::memory_order_relaxed);
operation->m_awaitingCoroutine.resume();
}
else
{
// We are racing with await_suspend() call suspending.
// Try to mark it as completed using an atomic exchange and look
// at the previous value to determine whether the coroutine suspended
// first (in which case we resume it now) or we marked it as completed
// first (in which case await_suspend() will return false and immediately
// resume the coroutine).
state = operation->m_state.exchange(
state::completed,
std::memory_order_acq_rel);
if (state == state::started)
{
// The await_suspend() method returned (or will return) 'true' and so
// we need to resume the coroutine.
operation->m_awaitingCoroutine.resume();
}
}
}
std::atomic<state> m_state;
cppcoro::cancellation_token m_cancellationToken;
std::optional<cppcoro::cancellation_registration> m_cancellationCallback;
std::experimental::coroutine_handle<> m_awaitingCoroutine;
};
}
}
#endif
<commit_msg>Work around MSVC codegen bug that caused socket tests to hang<commit_after>///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Lewis Baker
// Licenced under MIT license. See LICENSE.txt for details.
///////////////////////////////////////////////////////////////////////////////
#ifndef CPPCORO_DETAIL_WIN32_OVERLAPPED_OPERATION_HPP_INCLUDED
#define CPPCORO_DETAIL_WIN32_OVERLAPPED_OPERATION_HPP_INCLUDED
#include <cppcoro/cancellation_registration.hpp>
#include <cppcoro/cancellation_token.hpp>
#include <cppcoro/operation_cancelled.hpp>
#include <cppcoro/detail/win32.hpp>
#include <optional>
#include <system_error>
#include <experimental/coroutine>
#include <cassert>
namespace cppcoro
{
namespace detail
{
class win32_overlapped_operation_base
: protected detail::win32::io_state
{
public:
win32_overlapped_operation_base(
detail::win32::io_state::callback_type* callback) noexcept
: detail::win32::io_state(callback)
, m_errorCode(0)
, m_numberOfBytesTransferred(0)
{}
win32_overlapped_operation_base(
void* pointer,
detail::win32::io_state::callback_type* callback) noexcept
: detail::win32::io_state(pointer, callback)
, m_errorCode(0)
, m_numberOfBytesTransferred(0)
{}
win32_overlapped_operation_base(
std::uint64_t offset,
detail::win32::io_state::callback_type* callback) noexcept
: detail::win32::io_state(offset, callback)
, m_errorCode(0)
, m_numberOfBytesTransferred(0)
{}
_OVERLAPPED* get_overlapped() noexcept
{
return reinterpret_cast<_OVERLAPPED*>(
static_cast<detail::win32::overlapped*>(this));
}
std::size_t get_result()
{
if (m_errorCode != 0)
{
throw std::system_error{
static_cast<int>(m_errorCode),
std::system_category()
};
}
return m_numberOfBytesTransferred;
}
detail::win32::dword_t m_errorCode;
detail::win32::dword_t m_numberOfBytesTransferred;
};
template<typename OPERATION>
class win32_overlapped_operation
: protected win32_overlapped_operation_base
{
protected:
win32_overlapped_operation() noexcept
: win32_overlapped_operation_base(
&win32_overlapped_operation::on_operation_completed)
{}
win32_overlapped_operation(void* pointer) noexcept
: win32_overlapped_operation_base(
pointer,
&win32_overlapped_operation::on_operation_completed)
{}
win32_overlapped_operation(std::uint64_t offset) noexcept
: win32_overlapped_operation_base(
offset,
&win32_overlapped_operation::on_operation_completed)
{}
public:
bool await_ready() const noexcept { return false; }
CPPCORO_NOINLINE
bool await_suspend(std::experimental::coroutine_handle<> awaitingCoroutine)
{
static_assert(std::is_base_of_v<win32_overlapped_operation, OPERATION>);
m_awaitingCoroutine = awaitingCoroutine;
return static_cast<OPERATION*>(this)->try_start();
}
decltype(auto) await_resume()
{
return static_cast<OPERATION*>(this)->get_result();
}
private:
static void on_operation_completed(
detail::win32::io_state* ioState,
detail::win32::dword_t errorCode,
detail::win32::dword_t numberOfBytesTransferred,
[[maybe_unused]] detail::win32::ulongptr_t completionKey) noexcept
{
auto* operation = static_cast<win32_overlapped_operation*>(ioState);
operation->m_errorCode = errorCode;
operation->m_numberOfBytesTransferred = numberOfBytesTransferred;
operation->m_awaitingCoroutine.resume();
}
std::experimental::coroutine_handle<> m_awaitingCoroutine;
};
template<typename OPERATION>
class win32_overlapped_operation_cancellable
: protected win32_overlapped_operation_base
{
// ERROR_OPERATION_ABORTED value from <Windows.h>
static constexpr detail::win32::dword_t error_operation_aborted = 995L;
protected:
win32_overlapped_operation_cancellable(cancellation_token&& ct) noexcept
: win32_overlapped_operation_base(&win32_overlapped_operation_cancellable::on_operation_completed)
, m_state(ct.is_cancellation_requested() ? state::completed : state::not_started)
, m_cancellationToken(std::move(ct))
{
m_errorCode = error_operation_aborted;
}
win32_overlapped_operation_cancellable(
void* pointer,
cancellation_token&& ct) noexcept
: win32_overlapped_operation_base(pointer, &win32_overlapped_operation_cancellable::on_operation_completed)
, m_state(ct.is_cancellation_requested() ? state::completed : state::not_started)
, m_cancellationToken(std::move(ct))
{
m_errorCode = error_operation_aborted;
}
win32_overlapped_operation_cancellable(
std::uint64_t offset,
cancellation_token&& ct) noexcept
: win32_overlapped_operation_base(offset, &win32_overlapped_operation_cancellable::on_operation_completed)
, m_state(ct.is_cancellation_requested() ? state::completed : state::not_started)
, m_cancellationToken(std::move(ct))
{
m_errorCode = error_operation_aborted;
}
win32_overlapped_operation_cancellable(
win32_overlapped_operation_cancellable&& other) noexcept
: win32_overlapped_operation_base(std::move(other))
, m_state(other.m_state.load(std::memory_order_relaxed))
, m_cancellationToken(std::move(other.m_cancellationToken))
{
assert(m_errorCode == other.m_errorCode);
assert(m_numberOfBytesTransferred == other.m_numberOfBytesTransferred);
}
public:
bool await_ready() const noexcept
{
return m_state.load(std::memory_order_relaxed) == state::completed;
}
CPPCORO_NOINLINE
bool await_suspend(std::experimental::coroutine_handle<> awaitingCoroutine)
{
static_assert(std::is_base_of_v<win32_overlapped_operation_cancellable, OPERATION>);
m_awaitingCoroutine = awaitingCoroutine;
// TRICKY: Register cancellation callback before starting the operation
// in case the callback registration throws due to insufficient
// memory. We need to make sure that the logic that occurs after
// starting the operation is noexcept, otherwise we run into the
// problem of not being able to cancel the started operation and
// the dilemma of what to do with the exception.
//
// However, doing this means that the cancellation callback may run
// prior to returning below so in the case that cancellation may
// occur we defer setting the state to 'started' until after
// the operation has finished starting. The cancellation callback
// will only attempt to request cancellation of the operation with
// CancelIoEx() once the state has been set to 'started'.
const bool canBeCancelled = m_cancellationToken.can_be_cancelled();
if (canBeCancelled)
{
m_cancellationCallback.emplace(
std::move(m_cancellationToken),
[this] { this->on_cancellation_requested(); });
}
else
{
m_state.store(state::started, std::memory_order_relaxed);
}
// Now start the operation.
const bool willCompleteAsynchronously = static_cast<OPERATION*>(this)->try_start();
if (!willCompleteAsynchronously)
{
// Operation completed synchronously, resume awaiting coroutine immediately.
return false;
}
if (canBeCancelled)
{
// Need to flag that the operation has finished starting now.
// However, the operation may have completed concurrently on
// another thread, transitioning directly from not_started -> complete.
// Or it may have had the cancellation callback execute and transition
// from not_started -> cancellation_requested. We use a compare-exchange
// to determine a winner between these potential racing cases.
state oldState = state::not_started;
if (!m_state.compare_exchange_strong(
oldState,
state::started,
std::memory_order_release,
std::memory_order_acquire))
{
if (oldState == state::cancellation_requested)
{
// Request the operation be cancelled.
// Note that it may have already completed on a background
// thread by now so this request for cancellation may end up
// being ignored.
static_cast<OPERATION*>(this)->cancel();
if (!m_state.compare_exchange_strong(
oldState,
state::started,
std::memory_order_release,
std::memory_order_acquire))
{
assert(oldState == state::completed);
return false;
}
}
else
{
assert(oldState == state::completed);
return false;
}
}
}
return true;
}
decltype(auto) await_resume()
{
// Free memory used by the cancellation callback now that the operation
// has completed rather than waiting until the operation object destructs.
// eg. If the operation is passed to when_all() then the operation object
// may not be destructed until all of the operations complete.
m_cancellationCallback.reset();
if (m_errorCode == error_operation_aborted)
{
throw operation_cancelled{};
}
return static_cast<OPERATION*>(this)->get_result();
}
private:
enum class state
{
not_started,
started,
cancellation_requested,
completed
};
void on_cancellation_requested() noexcept
{
auto oldState = m_state.load(std::memory_order_acquire);
if (oldState == state::not_started)
{
// This callback is running concurrently with await_suspend().
// The call to start the operation may not have returned yet so
// we can't safely request cancellation of it. Instead we try to
// notify the await_suspend() thread by transitioning the state
// to state::cancellation_requested so that the await_suspend()
// thread can request cancellation after it has finished starting
// the operation.
const bool transferredCancelResponsibility =
m_state.compare_exchange_strong(
oldState,
state::cancellation_requested,
std::memory_order_release,
std::memory_order_acquire);
if (transferredCancelResponsibility)
{
return;
}
}
// No point requesting cancellation if the operation has already completed.
if (oldState != state::completed)
{
static_cast<OPERATION*>(this)->cancel();
}
}
static void on_operation_completed(
detail::win32::io_state* ioState,
detail::win32::dword_t errorCode,
detail::win32::dword_t numberOfBytesTransferred,
[[maybe_unused]] detail::win32::ulongptr_t completionKey) noexcept
{
auto* operation = static_cast<win32_overlapped_operation_cancellable*>(ioState);
operation->m_errorCode = errorCode;
operation->m_numberOfBytesTransferred = numberOfBytesTransferred;
auto state = operation->m_state.load(std::memory_order_acquire);
if (state == state::started)
{
operation->m_state.store(state::completed, std::memory_order_relaxed);
operation->m_awaitingCoroutine.resume();
}
else
{
// We are racing with await_suspend() call suspending.
// Try to mark it as completed using an atomic exchange and look
// at the previous value to determine whether the coroutine suspended
// first (in which case we resume it now) or we marked it as completed
// first (in which case await_suspend() will return false and immediately
// resume the coroutine).
state = operation->m_state.exchange(
state::completed,
std::memory_order_acq_rel);
if (state == state::started)
{
// The await_suspend() method returned (or will return) 'true' and so
// we need to resume the coroutine.
operation->m_awaitingCoroutine.resume();
}
}
}
std::atomic<state> m_state;
cppcoro::cancellation_token m_cancellationToken;
std::optional<cppcoro::cancellation_registration> m_cancellationCallback;
std::experimental::coroutine_handle<> m_awaitingCoroutine;
};
}
}
#endif
<|endoftext|>
|
<commit_before>/**
* @file src/Module.cpp
* @date dec. 2015
* @author PhRG - opticalp.fr
*/
/*
Copyright (c) 2015 Ph. Renaud-Goud / Opticalp
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 "Module.h"
#include "ModuleFactory.h"
#include "ModuleManager.h"
#include "ThreadManager.h"
#include "ModuleTask.h"
#include "OutPort.h"
#include "Poco/NumberFormatter.h"
#include "Poco/NumberParser.h"
std::vector<std::string> Module::names;
Poco::RWLock Module::namesLock;
void Module::notifyCreation()
{
// if not EmptyModule, add this to module manager
if (mParent)
Poco::Util::Application::instance().getSubsystem<ModuleManager>().addModule(this);
}
Module::~Module()
{
// TODO: tasks?
// notify parent factory
if (mParent)
{
mParent->removeChildModule(this);
// notify module manager
Poco::Util::Application::instance().getSubsystem<ModuleManager>().removeModule(this);
}
}
#include "Poco/Exception.h"
void Module::setInternalName(std::string internalName)
{
namesLock.writeLock();
switch (checkName(internalName))
{
case nameOk:
mInternalName = internalName;
names.push_back(mInternalName);
namesLock.unlock();
return;
case nameExists:
namesLock.unlock();
throw Poco::ExistsException("setInternalName",
internalName + " already in use");
case nameBadSyntax:
namesLock.unlock();
throw Poco::SyntaxException("setInternalName",
"The name should only contain alphanumeric characters "
"or \"-\", \"_\", \".\"");
}
}
void Module::setCustomName(std::string customName)
{
if (customName.empty() || customName.compare(internalName())==0)
{
mName = internalName();
// update conf file prefix key
setPrefixKey("module." + mName);
return;
}
namesLock.writeLock();
switch (checkName(customName))
{
case nameOk:
mName = customName;
names.push_back(mName);
namesLock.unlock();
return;
case nameExists:
freeInternalName();
namesLock.unlock();
throw Poco::ExistsException("setCustomName",
customName + " already in use");
case nameBadSyntax:
freeInternalName();
namesLock.unlock();
throw Poco::SyntaxException("setCustomName",
"The name should only contain alphanumeric characters "
"or \"-\", \"_\", \".\"");
}
}
ModuleFactory* Module::parent()
{
if (mParent)
return mParent;
else
throw Poco::InvalidAccessException("parent",
"This module has no valid parent factory");
}
#include "Poco/RegularExpression.h"
Module::NameStatus Module::checkName(std::string newName)
{
// check syntax
Poco::RegularExpression regex("^[0-9a-zA-Z\\._-]+$");
if (!regex.match(newName))
return nameBadSyntax;
// check existance
for (std::vector<std::string>::iterator it = names.begin(),
ite = names.end(); it != ite; it++)
if (it->compare(newName)==0)
return nameExists;
return nameOk;
}
void Module::freeInternalName()
{
// verify that this is a module creation process
if (!name().empty())
return;
for (std::vector<std::string>::reverse_iterator it = names.rbegin(),
ite = names.rend(); it != ite; it++ )
{
if (it->compare(internalName())==0)
{
names.erase((it+1).base());
return;
}
}
}
void Module::run()
{
expireOutData();
setRunningState(ModuleTask::retrievingInDataLocks);
int startCond = startCondition();
mergeTasks(portsWithNewData());
setRunningState(ModuleTask::processing);
process(startCond);
}
bool Module::sleep(long milliseconds)
{
if (*runningTask)
return (*runningTask)->sleep(milliseconds);
Poco::Thread::sleep(milliseconds);
return false;
}
bool Module::yield()
{
if (*runningTask)
return (*runningTask)->yield();
Poco::Thread::yield();
return false;
}
void Module::setProgress(float progress)
{
if (*runningTask == NULL)
return;
(*runningTask)->setProgress(progress);
}
bool Module::isCancelled()
{
if (*runningTask == NULL)
return false;
return (*runningTask)->isCancelled();
}
void Module::cancel()
{
if (*runningTask)
(*runningTask)->cancel();
throw Poco::RuntimeException(name(), "cancel. not in a task");
}
InPort* Module::triggingPort()
{
if (*runningTask)
return (*runningTask)->triggingPort();
throw Poco::RuntimeException(name(), "querying trigging port. not in a task");
}
void Module::setRunningState(ModuleTask::RunningStates state)
{
if (*runningTask == NULL)
return;
(*runningTask)->setRunningState(state);
}
ModuleTask::RunningStates Module::getRunningState()
{
if (*runningTask == NULL)
return ModuleTask::processing;
return (*runningTask)->getRunningState();
}
bool Module::enqueueTask(ModuleTask* task)
{
Poco::FastMutex::ScopedLock lock(taskMngtMutex);
Poco::Util::Application::instance()
.getSubsystem<ThreadManager>()
.registerNewModuleTask(task);
allTasks.insert(task);
taskQueue.push_back(task);
if (taskQueue.size()>1)
return false;
// check in allTasks if there is a task that is running
for (std::set<ModuleTask*>::iterator it = allTasks.begin(),
ite = allTasks.end(); it != ite; it++)
{
switch ((*it)->getState())
{
case MergeableTask::TASK_STARTING:
case MergeableTask::TASK_RUNNING:
poco_information(logger(), task->name()
+ ": a task is already running for " + name());
return false;
case MergeableTask::TASK_FALSE_START:
case MergeableTask::TASK_IDLE: // probably self
case MergeableTask::TASK_CANCELLING:
case MergeableTask::TASK_FINISHED:
break;
default:
poco_bugcheck_msg("unknown task state");
}
}
return true;
}
void Module::popTask()
{
Poco::ScopedLockWithUnlock<Poco::FastMutex> lock(taskMngtMutex);
if (taskQueue.empty())
return;
ModuleTask* nextTask = taskQueue.front();
poco_information(logger(), "poping out the next task: " + nextTask->name());
taskQueue.pop_front();
lock.unlock();
Poco::Util::Application::instance()
.getSubsystem<ThreadManager>()
.startModuleTask(nextTask);
}
void Module::popTaskSync()
{
Poco::ScopedLockWithUnlock<Poco::FastMutex> lock(taskMngtMutex);
if (taskQueue.empty())
{
poco_information(logger(), (*runningTask)->name() + ": empty task queue, nothing to sync pop");
return;
}
ModuleTask* nextTask = taskQueue.front();
poco_information(logger(), "SYNC poping out the next task: " + nextTask->name());
taskQueue.pop_front();
lock.unlock();
Poco::Util::Application::instance()
.getSubsystem<ThreadManager>()
.startSyncModuleTask(nextTask);
}
void Module::unregisterTask(ModuleTask* task)
{
Poco::FastMutex::ScopedLock lock(taskMngtMutex);
allTasks.erase(task);
}
void Module::mergeTasks(std::set<size_t> inPortIndexes)
{
Poco::FastMutex::ScopedLock lock(taskMngtMutex);
for (std::set<size_t>::iterator it = inPortIndexes.begin(),
ite = inPortIndexes.end(); it != ite; )
{
InPort* trigPort = getInPort(*it);
if (triggingPort() == trigPort)
{
it++;
continue; // current task
}
bool found = false;
// seek
for (std::list<ModuleTask*>::iterator qIt = taskQueue.begin(),
qIte = taskQueue.end(); qIt != qIte; qIt++)
{
poco_information(logger(), "taskQueue includes: " + (*qIt)->name());
if ((*qIt)->triggingPort() == trigPort)
{
found = true;
(*runningTask)->merge(*qIt);
taskQueue.erase(qIt);
poco_information(logger(), "slave task found, merging OK");
break;
}
}
if (!found)
{
poco_warning(logger(),
"Unable to merge the task for " + trigPort->name()
+ ". Retry.");
if (yield())
throw Poco::RuntimeException(name(), "Cancelation upon user request");
}
else
it++;
}
}
<commit_msg>Fix deadlock issue with task merging.<commit_after>/**
* @file src/Module.cpp
* @date dec. 2015
* @author PhRG - opticalp.fr
*/
/*
Copyright (c) 2015 Ph. Renaud-Goud / Opticalp
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 "Module.h"
#include "ModuleFactory.h"
#include "ModuleManager.h"
#include "ThreadManager.h"
#include "ModuleTask.h"
#include "OutPort.h"
#include "Poco/NumberFormatter.h"
#include "Poco/NumberParser.h"
std::vector<std::string> Module::names;
Poco::RWLock Module::namesLock;
void Module::notifyCreation()
{
// if not EmptyModule, add this to module manager
if (mParent)
Poco::Util::Application::instance().getSubsystem<ModuleManager>().addModule(this);
}
Module::~Module()
{
// TODO: tasks?
// notify parent factory
if (mParent)
{
mParent->removeChildModule(this);
// notify module manager
Poco::Util::Application::instance().getSubsystem<ModuleManager>().removeModule(this);
}
}
#include "Poco/Exception.h"
void Module::setInternalName(std::string internalName)
{
namesLock.writeLock();
switch (checkName(internalName))
{
case nameOk:
mInternalName = internalName;
names.push_back(mInternalName);
namesLock.unlock();
return;
case nameExists:
namesLock.unlock();
throw Poco::ExistsException("setInternalName",
internalName + " already in use");
case nameBadSyntax:
namesLock.unlock();
throw Poco::SyntaxException("setInternalName",
"The name should only contain alphanumeric characters "
"or \"-\", \"_\", \".\"");
}
}
void Module::setCustomName(std::string customName)
{
if (customName.empty() || customName.compare(internalName())==0)
{
mName = internalName();
// update conf file prefix key
setPrefixKey("module." + mName);
return;
}
namesLock.writeLock();
switch (checkName(customName))
{
case nameOk:
mName = customName;
names.push_back(mName);
namesLock.unlock();
return;
case nameExists:
freeInternalName();
namesLock.unlock();
throw Poco::ExistsException("setCustomName",
customName + " already in use");
case nameBadSyntax:
freeInternalName();
namesLock.unlock();
throw Poco::SyntaxException("setCustomName",
"The name should only contain alphanumeric characters "
"or \"-\", \"_\", \".\"");
}
}
ModuleFactory* Module::parent()
{
if (mParent)
return mParent;
else
throw Poco::InvalidAccessException("parent",
"This module has no valid parent factory");
}
#include "Poco/RegularExpression.h"
Module::NameStatus Module::checkName(std::string newName)
{
// check syntax
Poco::RegularExpression regex("^[0-9a-zA-Z\\._-]+$");
if (!regex.match(newName))
return nameBadSyntax;
// check existance
for (std::vector<std::string>::iterator it = names.begin(),
ite = names.end(); it != ite; it++)
if (it->compare(newName)==0)
return nameExists;
return nameOk;
}
void Module::freeInternalName()
{
// verify that this is a module creation process
if (!name().empty())
return;
for (std::vector<std::string>::reverse_iterator it = names.rbegin(),
ite = names.rend(); it != ite; it++ )
{
if (it->compare(internalName())==0)
{
names.erase((it+1).base());
return;
}
}
}
void Module::run()
{
expireOutData();
setRunningState(ModuleTask::retrievingInDataLocks);
int startCond = startCondition();
mergeTasks(portsWithNewData());
setRunningState(ModuleTask::processing);
process(startCond);
}
bool Module::sleep(long milliseconds)
{
if (*runningTask)
return (*runningTask)->sleep(milliseconds);
Poco::Thread::sleep(milliseconds);
return false;
}
bool Module::yield()
{
if (*runningTask)
return (*runningTask)->yield();
Poco::Thread::yield();
return false;
}
void Module::setProgress(float progress)
{
if (*runningTask == NULL)
return;
(*runningTask)->setProgress(progress);
}
bool Module::isCancelled()
{
if (*runningTask == NULL)
return false;
return (*runningTask)->isCancelled();
}
void Module::cancel()
{
if (*runningTask)
(*runningTask)->cancel();
throw Poco::RuntimeException(name(), "cancel. not in a task");
}
InPort* Module::triggingPort()
{
if (*runningTask)
return (*runningTask)->triggingPort();
throw Poco::RuntimeException(name(), "querying trigging port. not in a task");
}
void Module::setRunningState(ModuleTask::RunningStates state)
{
if (*runningTask == NULL)
return;
(*runningTask)->setRunningState(state);
}
ModuleTask::RunningStates Module::getRunningState()
{
if (*runningTask == NULL)
return ModuleTask::processing;
return (*runningTask)->getRunningState();
}
bool Module::enqueueTask(ModuleTask* task)
{
Poco::FastMutex::ScopedLock lock(taskMngtMutex);
Poco::Util::Application::instance()
.getSubsystem<ThreadManager>()
.registerNewModuleTask(task);
allTasks.insert(task);
taskQueue.push_back(task);
if (taskQueue.size()>1)
return false;
// check in allTasks if there is a task that is running
for (std::set<ModuleTask*>::iterator it = allTasks.begin(),
ite = allTasks.end(); it != ite; it++)
{
switch ((*it)->getState())
{
case MergeableTask::TASK_STARTING:
case MergeableTask::TASK_RUNNING:
poco_information(logger(), task->name()
+ ": a task is already running for " + name());
return false;
case MergeableTask::TASK_FALSE_START:
case MergeableTask::TASK_IDLE: // probably self
case MergeableTask::TASK_CANCELLING:
case MergeableTask::TASK_FINISHED:
break;
default:
poco_bugcheck_msg("unknown task state");
}
}
return true;
}
void Module::popTask()
{
Poco::ScopedLockWithUnlock<Poco::FastMutex> lock(taskMngtMutex);
if (taskQueue.empty())
return;
ModuleTask* nextTask = taskQueue.front();
poco_information(logger(), "poping out the next task: " + nextTask->name());
taskQueue.pop_front();
Poco::Util::Application::instance()
.getSubsystem<ThreadManager>()
.startModuleTask(nextTask);
lock.unlock();
}
void Module::popTaskSync()
{
Poco::ScopedLockWithUnlock<Poco::FastMutex> lock(taskMngtMutex);
if (taskQueue.empty())
{
poco_information(logger(), (*runningTask)->name() + ": empty task queue, nothing to sync pop");
return;
}
ModuleTask* nextTask = taskQueue.front();
poco_information(logger(), "SYNC poping out the next task: " + nextTask->name());
taskQueue.pop_front();
lock.unlock();
Poco::Util::Application::instance()
.getSubsystem<ThreadManager>()
.startSyncModuleTask(nextTask);
}
void Module::unregisterTask(ModuleTask* task)
{
Poco::FastMutex::ScopedLock lock(taskMngtMutex);
allTasks.erase(task);
}
void Module::mergeTasks(std::set<size_t> inPortIndexes)
{
// Poco::FastMutex::ScopedLock lock(taskMngtMutex);
taskMngtMutex.lock();
for (std::set<size_t>::iterator it = inPortIndexes.begin(),
ite = inPortIndexes.end(); it != ite; )
{
bool found = false;
InPort* trigPort;
try
{
trigPort = getInPort(*it);
if (triggingPort() == trigPort)
{
it++;
continue; // current task
}
// seek
for (std::list<ModuleTask*>::iterator qIt = taskQueue.begin(),
qIte = taskQueue.end(); qIt != qIte; qIt++)
{
poco_information(logger(), "taskQueue includes: " + (*qIt)->name());
if ((*qIt)->triggingPort() == trigPort)
{
found = true;
(*runningTask)->merge(*qIt);
taskQueue.erase(qIt);
poco_information(logger(), "slave task found, merging OK");
break;
}
}
}
catch (...)
{
taskMngtMutex.unlock();
throw;
}
if (!found)
{
taskMngtMutex.unlock();
poco_warning(logger(),
"Unable to merge the task for " + trigPort->name()
+ ". Retry.");
if (sleep(500))
throw Poco::RuntimeException(name(), "Cancelation upon user request");
taskMngtMutex.lock();
}
else
it++;
}
taskMngtMutex.unlock();
}
<|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 "media/filters/audio_renderer_algorithm_base.h"
#include "base/logging.h"
#include "media/base/buffers.h"
namespace media {
// The size in bytes we try to maintain for the |queue_|. Previous usage
// maintained a deque of 16 Buffers, each of size 4Kb. This worked well, so we
// maintain this number of bytes (16 * 4096).
const uint32 kDefaultMinQueueSizeInBytes = 65536;
AudioRendererAlgorithmBase::AudioRendererAlgorithmBase()
: channels_(0),
sample_rate_(0),
sample_bytes_(0),
playback_rate_(0.0f),
queue_(0, kDefaultMinQueueSizeInBytes) {
}
AudioRendererAlgorithmBase::~AudioRendererAlgorithmBase() {}
void AudioRendererAlgorithmBase::Initialize(int channels,
int sample_rate,
int sample_bits,
float initial_playback_rate,
RequestReadCallback* callback) {
DCHECK_GT(channels, 0);
DCHECK_LE(channels, 6) << "We only support <=6 channel audio.";
DCHECK_GT(sample_rate, 0);
DCHECK_LE(sample_rate, 256000)
<< "We only support sample rates at or below 256000Hz.";
DCHECK_GT(sample_bits, 0);
DCHECK_LE(sample_bits, 32) << "We only support 8, 16, 32 bit audio.";
DCHECK_EQ(sample_bits % 8, 0) << "We only support 8, 16, 32 bit audio.";
DCHECK(callback);
channels_ = channels;
sample_rate_ = sample_rate;
sample_bytes_ = sample_bits / 8;
request_read_callback_.reset(callback);
set_playback_rate(initial_playback_rate);
}
void AudioRendererAlgorithmBase::FlushBuffers() {
// Clear the queue of decoded packets (releasing the buffers).
queue_.Clear();
request_read_callback_->Run();
}
base::TimeDelta AudioRendererAlgorithmBase::GetTime() {
return queue_.current_time();
}
void AudioRendererAlgorithmBase::EnqueueBuffer(Buffer* buffer_in) {
// If we're at end of stream, |buffer_in| contains no data.
if (!buffer_in->IsEndOfStream())
queue_.Append(buffer_in);
// If we still don't have enough data, request more.
if (!IsQueueFull())
request_read_callback_->Run();
}
float AudioRendererAlgorithmBase::playback_rate() {
return playback_rate_;
}
void AudioRendererAlgorithmBase::set_playback_rate(float new_rate) {
DCHECK_GE(new_rate, 0.0);
playback_rate_ = new_rate;
}
bool AudioRendererAlgorithmBase::IsQueueEmpty() {
return queue_.forward_bytes() == 0;
}
bool AudioRendererAlgorithmBase::IsQueueFull() {
return (queue_.forward_bytes() >= kDefaultMinQueueSizeInBytes);
}
uint32 AudioRendererAlgorithmBase::QueueSize() {
return queue_.forward_bytes();
}
void AudioRendererAlgorithmBase::AdvanceInputPosition(uint32 bytes) {
queue_.Seek(bytes);
if (!IsQueueFull())
request_read_callback_->Run();
}
uint32 AudioRendererAlgorithmBase::CopyFromInput(uint8* dest, uint32 bytes) {
return queue_.Peek(dest, bytes);
}
int AudioRendererAlgorithmBase::channels() {
return channels_;
}
int AudioRendererAlgorithmBase::sample_rate() {
return sample_rate_;
}
int AudioRendererAlgorithmBase::sample_bytes() {
return sample_bytes_;
}
} // namespace media
<commit_msg>audio ola resampler accept 8 channel source BUG=59832 TEST=player_wtl _xvid_pcm_7.1_640x480_183sec_m1599.wav<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 "media/filters/audio_renderer_algorithm_base.h"
#include "base/logging.h"
#include "media/base/buffers.h"
namespace media {
// The size in bytes we try to maintain for the |queue_|. Previous usage
// maintained a deque of 16 Buffers, each of size 4Kb. This worked well, so we
// maintain this number of bytes (16 * 4096).
const uint32 kDefaultMinQueueSizeInBytes = 65536;
AudioRendererAlgorithmBase::AudioRendererAlgorithmBase()
: channels_(0),
sample_rate_(0),
sample_bytes_(0),
playback_rate_(0.0f),
queue_(0, kDefaultMinQueueSizeInBytes) {
}
AudioRendererAlgorithmBase::~AudioRendererAlgorithmBase() {}
void AudioRendererAlgorithmBase::Initialize(int channels,
int sample_rate,
int sample_bits,
float initial_playback_rate,
RequestReadCallback* callback) {
DCHECK_GT(channels, 0);
DCHECK_LE(channels, 8) << "We only support <= 8 channel audio.";
DCHECK_GT(sample_rate, 0);
DCHECK_LE(sample_rate, 256000)
<< "We only support sample rates at or below 256000Hz.";
DCHECK_GT(sample_bits, 0);
DCHECK_LE(sample_bits, 32) << "We only support 8, 16, 32 bit audio.";
DCHECK_EQ(sample_bits % 8, 0) << "We only support 8, 16, 32 bit audio.";
DCHECK(callback);
channels_ = channels;
sample_rate_ = sample_rate;
sample_bytes_ = sample_bits / 8;
request_read_callback_.reset(callback);
set_playback_rate(initial_playback_rate);
}
void AudioRendererAlgorithmBase::FlushBuffers() {
// Clear the queue of decoded packets (releasing the buffers).
queue_.Clear();
request_read_callback_->Run();
}
base::TimeDelta AudioRendererAlgorithmBase::GetTime() {
return queue_.current_time();
}
void AudioRendererAlgorithmBase::EnqueueBuffer(Buffer* buffer_in) {
// If we're at end of stream, |buffer_in| contains no data.
if (!buffer_in->IsEndOfStream())
queue_.Append(buffer_in);
// If we still don't have enough data, request more.
if (!IsQueueFull())
request_read_callback_->Run();
}
float AudioRendererAlgorithmBase::playback_rate() {
return playback_rate_;
}
void AudioRendererAlgorithmBase::set_playback_rate(float new_rate) {
DCHECK_GE(new_rate, 0.0);
playback_rate_ = new_rate;
}
bool AudioRendererAlgorithmBase::IsQueueEmpty() {
return queue_.forward_bytes() == 0;
}
bool AudioRendererAlgorithmBase::IsQueueFull() {
return (queue_.forward_bytes() >= kDefaultMinQueueSizeInBytes);
}
uint32 AudioRendererAlgorithmBase::QueueSize() {
return queue_.forward_bytes();
}
void AudioRendererAlgorithmBase::AdvanceInputPosition(uint32 bytes) {
queue_.Seek(bytes);
if (!IsQueueFull())
request_read_callback_->Run();
}
uint32 AudioRendererAlgorithmBase::CopyFromInput(uint8* dest, uint32 bytes) {
return queue_.Peek(dest, bytes);
}
int AudioRendererAlgorithmBase::channels() {
return channels_;
}
int AudioRendererAlgorithmBase::sample_rate() {
return sample_rate_;
}
int AudioRendererAlgorithmBase::sample_bytes() {
return sample_bytes_;
}
} // namespace media
<|endoftext|>
|
<commit_before>/**
* @file windows_volume_catcher.cpp
* @brief A Windows implementation of volume level control of all audio channels opened by a process.
*
* @cond
* $LicenseInfo:firstyear=2010&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
* @endcond
*/
#include "volume_catcher.h"
#include <windows.h>
#include "llsingleton.h"
class VolumeCatcherImpl : public LLSingleton<VolumeCatcherImpl>
{
friend LLSingleton<VolumeCatcherImpl>;
public:
void setVolume(F32 volume);
void setPan(F32 pan);
private:
// This is a singleton class -- both callers and the component implementation should use getInstance() to find the instance.
VolumeCatcherImpl();
~VolumeCatcherImpl();
typedef void (WINAPI *set_volume_func_t)(F32);
typedef void (WINAPI *set_mute_func_t)(bool);
set_volume_func_t mSetVolumeFunc;
set_mute_func_t mSetMuteFunc;
// tests if running on Vista, 7, 8 + once in CTOR
bool isWindowsVistaOrHigher();
F32 mVolume;
F32 mPan;
bool mSystemIsVistaOrHigher;
};
bool VolumeCatcherImpl::isWindowsVistaOrHigher()
{
OSVERSIONINFO osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
return osvi.dwMajorVersion >= 6;
}
VolumeCatcherImpl::VolumeCatcherImpl()
: mVolume(1.0f), // default volume is max
mPan(0.f) // default pan is centered
{
mSystemIsVistaOrHigher = isWindowsVistaOrHigher();
if ( mSystemIsVistaOrHigher )
{
HMODULE handle = ::LoadLibrary(L"winmm.dll");
if(handle)
{
mSetVolumeFunc = (set_volume_func_t)::GetProcAddress(handle, "setPluginVolume");
mSetMuteFunc = (set_mute_func_t)::GetProcAddress(handle, "setPluginMute");
}
}
}
VolumeCatcherImpl::~VolumeCatcherImpl()
{
}
void VolumeCatcherImpl::setVolume(F32 volume)
{
mVolume = volume;
if ( ! mSystemIsVistaOrHigher )
{
// set both left/right to same volume
// TODO: use pan value to set independently
DWORD left_channel = (DWORD)(mVolume * 65535.0f);
DWORD right_channel = (DWORD)(mVolume * 65535.0f);
DWORD hw_volume = left_channel << 16 | right_channel;
::waveOutSetVolume(NULL, hw_volume);
}
else
{
if (mSetMuteFunc)
{
mSetMuteFunc(volume == 0.f);
}
if (mSetVolumeFunc)
{
mSetVolumeFunc(mVolume);
}
}
}
void VolumeCatcherImpl::setPan(F32 pan)
{ // remember pan for calculating individual channel levels later
mPan = pan;
}
/////////////////////////////////////////////////////
VolumeCatcher::VolumeCatcher()
{
pimpl = VolumeCatcherImpl::getInstance();
}
VolumeCatcher::~VolumeCatcher()
{
// Let the instance persist until exit.
}
void VolumeCatcher::setVolume(F32 volume)
{
pimpl->setVolume(volume);
}
void VolumeCatcher::setPan(F32 pan)
{
pimpl->setPan(pan);
}
void VolumeCatcher::pump()
{
// No periodic tasks are necessary for this implementation.
}
<commit_msg>MAINT-2281: correct test for XP (corrected fix I applied incorrectly)<commit_after>/**
* @file windows_volume_catcher.cpp
* @brief A Windows implementation of volume level control of all audio channels opened by a process.
*
* @cond
* $LicenseInfo:firstyear=2010&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
* @endcond
*/
#include "volume_catcher.h"
#include <windows.h>
#include "llsingleton.h"
class VolumeCatcherImpl : public LLSingleton<VolumeCatcherImpl>
{
friend LLSingleton<VolumeCatcherImpl>;
public:
void setVolume(F32 volume);
void setPan(F32 pan);
private:
// This is a singleton class -- both callers and the component implementation should use getInstance() to find the instance.
VolumeCatcherImpl();
~VolumeCatcherImpl();
typedef void (WINAPI *set_volume_func_t)(F32);
typedef void (WINAPI *set_mute_func_t)(bool);
set_volume_func_t mSetVolumeFunc;
set_mute_func_t mSetMuteFunc;
// tests if running on Vista, 7, 8 + once in CTOR
bool isWindowsVistaOrHigher();
F32 mVolume;
F32 mPan;
bool mSystemIsVistaOrHigher;
};
bool VolumeCatcherImpl::isWindowsVistaOrHigher()
{
OSVERSIONINFO osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
return osvi.dwMajorVersion >= 6;
}
VolumeCatcherImpl::VolumeCatcherImpl()
: mVolume(1.0f), // default volume is max
mPan(0.f) // default pan is centered
{
mSystemIsVistaOrHigher = isWindowsVistaOrHigher();
if ( ! mSystemIsVistaOrHigher )
{
HMODULE handle = ::LoadLibrary(L"winmm.dll");
if(handle)
{
mSetVolumeFunc = (set_volume_func_t)::GetProcAddress(handle, "setPluginVolume");
mSetMuteFunc = (set_mute_func_t)::GetProcAddress(handle, "setPluginMute");
}
}
}
VolumeCatcherImpl::~VolumeCatcherImpl()
{
}
void VolumeCatcherImpl::setVolume(F32 volume)
{
mVolume = volume;
if ( mSystemIsVistaOrHigher )
{
// set both left/right to same volume
// TODO: use pan value to set independently
DWORD left_channel = (DWORD)(mVolume * 65535.0f);
DWORD right_channel = (DWORD)(mVolume * 65535.0f);
DWORD hw_volume = left_channel << 16 | right_channel;
::waveOutSetVolume(NULL, hw_volume);
}
else
{
if (mSetMuteFunc)
{
mSetMuteFunc(volume == 0.f);
}
if (mSetVolumeFunc)
{
mSetVolumeFunc(mVolume);
}
}
}
void VolumeCatcherImpl::setPan(F32 pan)
{ // remember pan for calculating individual channel levels later
mPan = pan;
}
/////////////////////////////////////////////////////
VolumeCatcher::VolumeCatcher()
{
pimpl = VolumeCatcherImpl::getInstance();
}
VolumeCatcher::~VolumeCatcher()
{
// Let the instance persist until exit.
}
void VolumeCatcher::setVolume(F32 volume)
{
pimpl->setVolume(volume);
}
void VolumeCatcher::setPan(F32 pan)
{
pimpl->setPan(pan);
}
void VolumeCatcher::pump()
{
// No periodic tasks are necessary for this implementation.
}
<|endoftext|>
|
<commit_before>#ifndef NETWORKING_H
#define NETWORKING_H
#include <iostream>
#include <set>
#ifdef _WIN32
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#else
#include <signal.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/select.h>
#include <unistd.h>
#endif
#include "../core/hlt.hpp"
extern bool quiet_output;
class Networking {
public:
void startAndConnectBot(std::string command);
void handleInitNetworking(unsigned char playerTag, const hlt::Map & m, int * playerMillis, std::string * playerName);
void handleFrameNetworking(unsigned char playerTag, const hlt::Map & m, int * playermillis, std::set<hlt::Move> * moves);
void killPlayer(unsigned char playerTag);
bool isProcessDead(unsigned char playerTag);
int numberOfPlayers();
std::vector< std::vector<std::string> > player_logs;
private:
#ifdef _WIN32
struct WinConnection {
HANDLE write, read;
};
std::vector<WinConnection> connections;
std::vector<HANDLE> processes;
#else
struct UniConnection {
int read, write;
};
std::vector< UniConnection > connections;
std::vector<int> processes;
#endif
std::string serializeMap(const hlt::Map & map);
std::set<hlt::Move> deserializeMoveSet(std::string & inputString, const hlt::Map & m);
void sendString(unsigned char playerTag, std::string &sendString);
std::string getString(unsigned char playerTag, unsigned int timoutMillis);
};
#endif
<commit_msg>Fixed preproc indentation<commit_after>#ifndef NETWORKING_H
#define NETWORKING_H
#include <iostream>
#include <set>
#ifdef _WIN32
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#else
#include <signal.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/select.h>
#include <unistd.h>
#endif
#include "../core/hlt.hpp"
extern bool quiet_output;
class Networking {
public:
void startAndConnectBot(std::string command);
void handleInitNetworking(unsigned char playerTag, const hlt::Map & m, int * playerMillis, std::string * playerName);
void handleFrameNetworking(unsigned char playerTag, const hlt::Map & m, int * playermillis, std::set<hlt::Move> * moves);
void killPlayer(unsigned char playerTag);
bool isProcessDead(unsigned char playerTag);
int numberOfPlayers();
std::vector<std::string> player_logs;
private:
#ifdef _WIN32
struct WinConnection {
HANDLE write, read;
};
std::vector<WinConnection> connections;
std::vector<HANDLE> processes;
#else
struct UniConnection {
int read, write;
};
std::vector< UniConnection > connections;
std::vector<int> processes;
#endif
std::string serializeMap(const hlt::Map & map);
std::set<hlt::Move> deserializeMoveSet(std::string & inputString, const hlt::Map & m);
void sendString(unsigned char playerTag, std::string &sendString);
std::string getString(unsigned char playerTag, unsigned int timoutMillis);
};
#endif
<|endoftext|>
|
<commit_before>/*
* Option.cpp
*
* Created on: 04/05/2011
* User: diego
* Author: Diego Lago <diego.lago.gonzalez@gmail.com>
*/
#include "../include/cli++/Option.hpp"
#include "../include/cli++/OptionDefinition.hpp"
#include "../include/cli++/Exceptions.hpp"
#include "../include/cli++/Utils.hpp"
namespace clipp {
static const size_t MaxParameterCount = 65536;
Option::Option(const string name, const string value)
: fId(0),
fName(name),
fOccurrences(1),
fValues(MaxParameterCount),
fOptdef(NULL)
{
if(fName.empty()) {
throw length_error("Option: Option name cannot be empty.");
}
if(!value.empty()) {
fValues.push_back(value);
}
}
Option::~Option() {
}
int
Option::id() const {
return fId;
}
const string
Option::name() const {
return fName;
}
const OptionDefinition*
Option::optionDefinition() const {
return fOptdef;
}
void
Option::incOccurrenceCount() {
fOccurrences++;
}
int
Option::occurrences() const {
return fOccurrences;
}
void
Option::add(const string value) {
if(!value.empty()) {
fValues.push_back(value);
}
}
void
Option::set(const string value, int index) {
if(!value.empty()) {
if(index >= 0 && index < (int)fValues.size()) {
fValues[index] = value;
} else {
throw clipp::error::OutOfBounds("Cannot set value " + value + " at index " + StringFrom<int>(index) + " from option '" + fName + "'.", fName);
}
}
}
const string
Option::getAt(unsigned short index) const {
if(index < (int)fValues.size()) {
return fValues[index];
} else {
throw clipp::error::OutOfBounds("Cannot get value at index " + StringFrom<unsigned short>(index) + " from option '" + fName + "'.", fName);
}
}
const string
Option::get() const {
return getAt(0);
}
int
Option::countValues() const {
return fValues.size();
}
void
Option::checkArguments() {
if(fOptdef == NULL) {
throw clipp::error::OptionDefinition("FATAL: OptionDefinition pointer from Option (_optdef) is NULL. Contact developer.");
}
for(Strings::const_iterator it = fValues.begin(); it != fValues.end(); ++it) {
fOptdef->checkArgumentType(*it);
fOptdef->checkArgumentValue(*it);
}
}
} // namespace clipp
<commit_msg>Implemented isNegated in the Option.<commit_after>/*
* Option.cpp
*
* Created on: 04/05/2011
* User: diego
* Author: Diego Lago <diego.lago.gonzalez@gmail.com>
*/
#include "../include/cli++/Option.hpp"
#include "../include/cli++/OptionDefinition.hpp"
#include "../include/cli++/Exceptions.hpp"
#include "../include/cli++/Utils.hpp"
namespace clipp {
static const size_t MaxParameterCount = 65536;
Option::Option(const string name, const string value)
: fId(0),
fName(name),
fOccurrences(1),
fValues(MaxParameterCount),
fOptdef(NULL)
{
if(fName.empty()) {
throw length_error("Option: Option name cannot be empty.");
}
if(!value.empty()) {
fValues.push_back(value);
}
}
Option::~Option() {
}
int
Option::id() const {
return fId;
}
const string
Option::name() const {
return fName;
}
bool
Option::isNegated() const {
return fIsNegated;
}
const OptionDefinition*
Option::optionDefinition() const {
return fOptdef;
}
void
Option::incOccurrenceCount() {
fOccurrences++;
}
int
Option::occurrences() const {
return fOccurrences;
}
void
Option::add(const string value) {
if(!value.empty()) {
fValues.push_back(value);
}
}
void
Option::set(const string value, int index) {
if(!value.empty()) {
if(index >= 0 && index < (int)fValues.size()) {
fValues[index] = value;
} else {
throw clipp::error::OutOfBounds("Cannot set value " + value + " at index " + StringFrom<int>(index) + " from option '" + fName + "'.", fName);
}
}
}
const string
Option::getAt(unsigned short index) const {
if(index < (int)fValues.size()) {
return fValues[index];
} else {
throw clipp::error::OutOfBounds("Cannot get value at index " + StringFrom<unsigned short>(index) + " from option '" + fName + "'.", fName);
}
}
const string
Option::get() const {
return getAt(0);
}
int
Option::countValues() const {
return fValues.size();
}
void
Option::checkArguments() {
if(fOptdef == NULL) {
throw clipp::error::OptionDefinition("FATAL: OptionDefinition pointer from Option (_optdef) is NULL. Contact developer.");
}
for(Strings::const_iterator it = fValues.begin(); it != fValues.end(); ++it) {
fOptdef->checkArgumentType(*it);
fOptdef->checkArgumentValue(*it);
}
}
} // namespace clipp
<|endoftext|>
|
<commit_before>/*
Copyright Kitware, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "Output.h"
#include "Utils.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclFriend.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclOpenMP.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Support/raw_ostream.h"
#include <fstream>
#include <iostream>
#include <queue>
//----------------------------------------------------------------------------
class ASTVisitorBase
{
protected:
clang::CompilerInstance& CI;
clang::ASTContext const& CTX;
llvm::raw_ostream& OS;
ASTVisitorBase(clang::CompilerInstance& ci,
clang::ASTContext const& ctx,
llvm::raw_ostream& os): CI(ci), CTX(ctx), OS(os) {}
// Record status of one AST node to be dumped.
struct DumpNode {
DumpNode(): Index(0), Complete(false) {}
// Index in nodes ordered by first encounter.
unsigned int Index;
// Whether the node is to be traversed completely.
bool Complete;
};
// Report all decl nodes as unimplemented until overridden.
#define ABSTRACT_DECL(DECL)
#define DECL(CLASS, BASE) \
void Output##CLASS##Decl(clang::CLASS##Decl const* d, DumpNode const* dn) { \
this->OutputUnimplementedDecl(d, dn); \
}
#include "clang/AST/DeclNodes.inc"
void OutputUnimplementedDecl(clang::Decl const* d, DumpNode const* dn) {
this->OS << " <Unimplemented id=\"_" << dn->Index
<< "\" kind=\"" << encodeXML(d->getDeclKindName()) << "\"/>\n";
}
// Report all type nodes as unimplemented until overridden.
#define ABSTRACT_TYPE(CLASS, BASE)
#define TYPE(CLASS, BASE) \
void Output##CLASS##Type(clang::CLASS##Type const* t, DumpNode const* dn) { \
this->OutputUnimplementedType(t, dn); \
}
#include "clang/AST/TypeNodes.def"
void OutputUnimplementedType(clang::Type const* t, DumpNode const* dn) {
this->OS << " <Unimplemented id=\"_" << dn->Index
<< "\" type_class=\"" << encodeXML(t->getTypeClassName())
<< "\"/>\n";
}
};
//----------------------------------------------------------------------------
class ASTVisitor: public ASTVisitorBase
{
// Store an entry in the node traversal queue.
struct QueueEntry {
// Available node kinds.
enum Kinds {
KindDecl,
KindType
};
QueueEntry(): Kind(KindDecl), Decl(0), DN(0) {}
QueueEntry(clang::Decl const* d, DumpNode const* dn):
Kind(KindDecl), Decl(d), DN(dn) {}
QueueEntry(clang::QualType t, DumpNode const* dn):
Kind(KindType), Decl(0), Type(t), DN(dn) {}
// Kind of node at this entry.
Kinds Kind;
// The declaration when Kind == KindDecl.
clang::Decl const* Decl;
// The type when Kind == KindType.
clang::QualType Type;
// The dump status for this node.
DumpNode const* DN;
};
// Order clang::QualType values.
struct QualTypeCompare {
bool operator()(clang::QualType l, clang::QualType r) const {
// Order by pointer value without discarding low-order
// bits used to encode qualifiers.
void* lpp = &l;
void* rpp = &r;
return *static_cast<void**>(lpp) < *static_cast<void**>(rpp);
}
};
/** Get the dump status node for a Clang declaration. */
DumpNode* GetDumpNode(clang::Decl const* d) {
return &this->DeclNodes[d];
}
/** Get the dump status node for a Clang type. */
DumpNode* GetDumpNode(clang::QualType t) {
return &this->TypeNodes[t];
}
/** Allocate a dump node for a Clang declaration. */
unsigned int AddDumpNode(clang::Decl const* d, bool complete);
/** Allocate a dump node for a Clang type. */
unsigned int AddDumpNode(clang::QualType t, bool complete);
/** Helper common to AddDumpNode implementation for every kind. */
template <typename K> unsigned int AddDumpNodeImpl(K k, bool complete);
/** Queue leftover nodes that do not need complete output. */
void QueueIncompleteDumpNodes();
/** Traverse AST nodes until the queue is empty. */
void ProcessQueue();
/** Dispatch output of a declaration. */
void OutputDecl(clang::Decl const* d, DumpNode const* dn);
/** Dispatch output of a qualified or unqualified type. */
void OutputType(clang::QualType t, DumpNode const* dn);
/** Output a qualified type and queue its unqualified type. */
void OutputCvQualifiedType(clang::QualType t, DumpNode const* dn);
/** Queue declarations matching given qualified name in given context. */
void LookupStart(clang::DeclContext const* dc, std::string const& name);
private:
// List of starting declaration names.
std::vector<std::string> const& StartNames;
// Total number of nodes to be dumped.
unsigned int NodeCount;
// Whether we are in the complete or incomplete output step.
bool RequireComplete;
// Map from clang AST declaration node to our dump status node.
typedef std::map<clang::Decl const*, DumpNode> DeclNodesMap;
DeclNodesMap DeclNodes;
// Map from clang AST type node to our dump status node.
typedef std::map<clang::QualType, DumpNode, QualTypeCompare> TypeNodesMap;
TypeNodesMap TypeNodes;
// Node traversal queue.
std::queue<QueueEntry> Queue;
public:
ASTVisitor(clang::CompilerInstance& ci,
clang::ASTContext const& ctx,
llvm::raw_ostream& os,
std::vector<std::string> const& startNames):
ASTVisitorBase(ci, ctx, os),
StartNames(startNames),
NodeCount(0),
RequireComplete(true) {}
/** Visit declarations in the given translation unit.
This is the main entry point. */
void HandleTranslationUnit(clang::TranslationUnitDecl const* tu);
};
//----------------------------------------------------------------------------
unsigned int ASTVisitor::AddDumpNode(clang::Decl const* d, bool complete) {
// Add the node for the canonical declaration instance.
return this->AddDumpNodeImpl(d->getCanonicalDecl(), complete);
}
//----------------------------------------------------------------------------
unsigned int ASTVisitor::AddDumpNode(clang::QualType t, bool complete) {
return this->AddDumpNodeImpl(t, complete);
}
//----------------------------------------------------------------------------
template <typename K>
unsigned int ASTVisitor::AddDumpNodeImpl(K k, bool complete)
{
// Update an existing node or add one.
DumpNode* dn = this->GetDumpNode(k);
if (dn->Index) {
// Node was already encountered. See if it is now complete.
if(complete && !dn->Complete) {
// Node is now complete, but wasn't before. Queue it.
dn->Complete = true;
this->Queue.push(QueueEntry(k, dn));
}
} else {
// This is a new node. Assign it an index.
dn->Index = ++this->NodeCount;
dn->Complete = complete;
if(complete || !this->RequireComplete) {
// Node is complete. Queue it.
this->Queue.push(QueueEntry(k, dn));
}
}
// Return node's index.
return dn->Index;
}
//----------------------------------------------------------------------------
void ASTVisitor::QueueIncompleteDumpNodes()
{
// Queue declaration nodes that do not need complete output.
for(DeclNodesMap::const_iterator i = this->DeclNodes.begin(),
e = this->DeclNodes.end(); i != e; ++i) {
if(!i->second.Complete) {
this->Queue.push(QueueEntry(i->first, &i->second));
}
}
// Queue type nodes that do not need complete output.
for(TypeNodesMap::const_iterator i = this->TypeNodes.begin(),
e = this->TypeNodes.end(); i != e; ++i) {
if(!i->second.Complete) {
this->Queue.push(QueueEntry(i->first, &i->second));
}
}
}
//----------------------------------------------------------------------------
void ASTVisitor::ProcessQueue()
{
// Dispatch each entry in the queue based on its node kind.
while(!this->Queue.empty()) {
QueueEntry qe = this->Queue.front();
this->Queue.pop();
switch(qe.Kind) {
case QueueEntry::KindDecl:
this->OutputDecl(qe.Decl, qe.DN);
break;
case QueueEntry::KindType:
this->OutputType(qe.Type, qe.DN);
break;
}
}
}
//----------------------------------------------------------------------------
void ASTVisitor::OutputDecl(clang::Decl const* d, DumpNode const* dn)
{
// Dispatch output of the declaration.
switch (d->getKind()) {
#define ABSTRACT_DECL(DECL)
#define DECL(CLASS, BASE) \
case clang::Decl::CLASS: \
this->Output##CLASS##Decl( \
static_cast<clang::CLASS##Decl const*>(d), dn); \
break;
#include "clang/AST/DeclNodes.inc"
}
}
//----------------------------------------------------------------------------
void ASTVisitor::OutputType(clang::QualType t, DumpNode const* dn)
{
if(t.hasLocalQualifiers()) {
// Output the qualified type. This will queue
// the unqualified type if necessary.
this->OutputCvQualifiedType(t, dn);
} else {
// Dispatch output of the unqualified type.
switch (t->getTypeClass()) {
#define ABSTRACT_TYPE(CLASS, BASE)
#define TYPE(CLASS, BASE) \
case clang::Type::CLASS: \
this->Output##CLASS##Type( \
static_cast<clang::CLASS##Type const*>(t.getTypePtr()), dn); \
break;
#include "clang/AST/TypeNodes.def"
}
}
}
//----------------------------------------------------------------------------
void ASTVisitor::OutputCvQualifiedType(clang::QualType t, DumpNode const* dn)
{
// TODO: Output a CvQualifiedType element that references the
// unqualified type element and lists qualifier attributes.
static_cast<void>(t);
static_cast<void>(dn);
}
//----------------------------------------------------------------------------
void ASTVisitor::LookupStart(clang::DeclContext const* dc,
std::string const& name)
{
std::string::size_type pos = name.find("::");
std::string cur = name.substr(0, pos);
clang::IdentifierTable& ids = CI.getPreprocessor().getIdentifierTable();
clang::DeclContext::lookup_const_result r =
dc->lookup(clang::DeclarationName(&ids.get(cur)));
if(pos == name.npos) {
for(clang::DeclContext::lookup_const_iterator i = r.begin(), e = r.end();
i != e; ++i) {
this->AddDumpNode(*i, true);
}
} else {
std::string rest = name.substr(pos+2);
for(clang::DeclContext::lookup_const_iterator i = r.begin(), e = r.end();
i != e; ++i) {
if (clang::DeclContext* idc = clang::dyn_cast<clang::DeclContext>(*i)) {
this->LookupStart(idc, rest);
}
}
}
}
//----------------------------------------------------------------------------
void ASTVisitor::HandleTranslationUnit(clang::TranslationUnitDecl const* tu)
{
// Add the starting nodes for the dump.
if(!this->StartNames.empty()) {
// Use the specified starting locations.
for(std::vector<std::string>::const_iterator i = this->StartNames.begin(),
e = this->StartNames.end(); i != e; ++i) {
this->LookupStart(tu, *i);
}
} else {
// No start specified. Use whole translation unit.
this->AddDumpNode(tu, true);
}
// Start dump with gccxml-compatible format.
this->OS <<
"<?xml version=\"1.0\"?>\n"
"<GCC_XML version=\"0.9.0\" cvs_revision=\"1.136\">\n"
;
// Dump the complete nodes.
this->ProcessQueue();
// Queue all the incomplete nodes.
this->RequireComplete = false;
this->QueueIncompleteDumpNodes();
// Dump the incomplete nodes.
this->ProcessQueue();
// Finish dump.
this->OS <<
"</GCC_XML>\n"
;
}
//----------------------------------------------------------------------------
void outputXML(clang::CompilerInstance& ci,
clang::ASTContext const& ctx,
llvm::raw_ostream& os,
std::vector<std::string> const& startNames)
{
ASTVisitor v(ci, ctx, os, startNames);
v.HandleTranslationUnit(ctx.getTranslationUnitDecl());
}
<commit_msg>Add output for 'File' XML elements<commit_after>/*
Copyright Kitware, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "Output.h"
#include "Utils.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclFriend.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclOpenMP.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Support/raw_ostream.h"
#include <fstream>
#include <iostream>
#include <queue>
//----------------------------------------------------------------------------
class ASTVisitorBase
{
protected:
clang::CompilerInstance& CI;
clang::ASTContext const& CTX;
llvm::raw_ostream& OS;
ASTVisitorBase(clang::CompilerInstance& ci,
clang::ASTContext const& ctx,
llvm::raw_ostream& os): CI(ci), CTX(ctx), OS(os) {}
// Record status of one AST node to be dumped.
struct DumpNode {
DumpNode(): Index(0), Complete(false) {}
// Index in nodes ordered by first encounter.
unsigned int Index;
// Whether the node is to be traversed completely.
bool Complete;
};
// Report all decl nodes as unimplemented until overridden.
#define ABSTRACT_DECL(DECL)
#define DECL(CLASS, BASE) \
void Output##CLASS##Decl(clang::CLASS##Decl const* d, DumpNode const* dn) { \
this->OutputUnimplementedDecl(d, dn); \
}
#include "clang/AST/DeclNodes.inc"
void OutputUnimplementedDecl(clang::Decl const* d, DumpNode const* dn) {
this->OS << " <Unimplemented id=\"_" << dn->Index
<< "\" kind=\"" << encodeXML(d->getDeclKindName()) << "\"/>\n";
}
// Report all type nodes as unimplemented until overridden.
#define ABSTRACT_TYPE(CLASS, BASE)
#define TYPE(CLASS, BASE) \
void Output##CLASS##Type(clang::CLASS##Type const* t, DumpNode const* dn) { \
this->OutputUnimplementedType(t, dn); \
}
#include "clang/AST/TypeNodes.def"
void OutputUnimplementedType(clang::Type const* t, DumpNode const* dn) {
this->OS << " <Unimplemented id=\"_" << dn->Index
<< "\" type_class=\"" << encodeXML(t->getTypeClassName())
<< "\"/>\n";
}
};
//----------------------------------------------------------------------------
class ASTVisitor: public ASTVisitorBase
{
// Store an entry in the node traversal queue.
struct QueueEntry {
// Available node kinds.
enum Kinds {
KindDecl,
KindType
};
QueueEntry(): Kind(KindDecl), Decl(0), DN(0) {}
QueueEntry(clang::Decl const* d, DumpNode const* dn):
Kind(KindDecl), Decl(d), DN(dn) {}
QueueEntry(clang::QualType t, DumpNode const* dn):
Kind(KindType), Decl(0), Type(t), DN(dn) {}
// Kind of node at this entry.
Kinds Kind;
// The declaration when Kind == KindDecl.
clang::Decl const* Decl;
// The type when Kind == KindType.
clang::QualType Type;
// The dump status for this node.
DumpNode const* DN;
};
// Order clang::QualType values.
struct QualTypeCompare {
bool operator()(clang::QualType l, clang::QualType r) const {
// Order by pointer value without discarding low-order
// bits used to encode qualifiers.
void* lpp = &l;
void* rpp = &r;
return *static_cast<void**>(lpp) < *static_cast<void**>(rpp);
}
};
/** Get the dump status node for a Clang declaration. */
DumpNode* GetDumpNode(clang::Decl const* d) {
return &this->DeclNodes[d];
}
/** Get the dump status node for a Clang type. */
DumpNode* GetDumpNode(clang::QualType t) {
return &this->TypeNodes[t];
}
/** Allocate a dump node for a Clang declaration. */
unsigned int AddDumpNode(clang::Decl const* d, bool complete);
/** Allocate a dump node for a Clang type. */
unsigned int AddDumpNode(clang::QualType t, bool complete);
/** Helper common to AddDumpNode implementation for every kind. */
template <typename K> unsigned int AddDumpNodeImpl(K k, bool complete);
/** Allocate a dump node for a source file entry. */
unsigned int AddDumpFile(clang::FileEntry const* f);
/** Queue leftover nodes that do not need complete output. */
void QueueIncompleteDumpNodes();
/** Traverse AST nodes until the queue is empty. */
void ProcessQueue();
void ProcessFileQueue();
/** Dispatch output of a declaration. */
void OutputDecl(clang::Decl const* d, DumpNode const* dn);
/** Dispatch output of a qualified or unqualified type. */
void OutputType(clang::QualType t, DumpNode const* dn);
/** Output a qualified type and queue its unqualified type. */
void OutputCvQualifiedType(clang::QualType t, DumpNode const* dn);
/** Queue declarations matching given qualified name in given context. */
void LookupStart(clang::DeclContext const* dc, std::string const& name);
private:
// List of starting declaration names.
std::vector<std::string> const& StartNames;
// Total number of nodes to be dumped.
unsigned int NodeCount;
// Total number of source files to be referenced.
unsigned int FileCount;
// Whether we are in the complete or incomplete output step.
bool RequireComplete;
// Map from clang AST declaration node to our dump status node.
typedef std::map<clang::Decl const*, DumpNode> DeclNodesMap;
DeclNodesMap DeclNodes;
// Map from clang AST type node to our dump status node.
typedef std::map<clang::QualType, DumpNode, QualTypeCompare> TypeNodesMap;
TypeNodesMap TypeNodes;
// Map from clang file entry to our source file index.
typedef std::map<clang::FileEntry const*, unsigned int> FileNodesMap;
FileNodesMap FileNodes;
// Node traversal queue.
std::queue<QueueEntry> Queue;
// File traversal queue.
std::queue<clang::FileEntry const*> FileQueue;
public:
ASTVisitor(clang::CompilerInstance& ci,
clang::ASTContext const& ctx,
llvm::raw_ostream& os,
std::vector<std::string> const& startNames):
ASTVisitorBase(ci, ctx, os),
StartNames(startNames),
NodeCount(0), FileCount(0),
RequireComplete(true) {}
/** Visit declarations in the given translation unit.
This is the main entry point. */
void HandleTranslationUnit(clang::TranslationUnitDecl const* tu);
};
//----------------------------------------------------------------------------
unsigned int ASTVisitor::AddDumpNode(clang::Decl const* d, bool complete) {
// Add the node for the canonical declaration instance.
return this->AddDumpNodeImpl(d->getCanonicalDecl(), complete);
}
//----------------------------------------------------------------------------
unsigned int ASTVisitor::AddDumpNode(clang::QualType t, bool complete) {
return this->AddDumpNodeImpl(t, complete);
}
//----------------------------------------------------------------------------
template <typename K>
unsigned int ASTVisitor::AddDumpNodeImpl(K k, bool complete)
{
// Update an existing node or add one.
DumpNode* dn = this->GetDumpNode(k);
if (dn->Index) {
// Node was already encountered. See if it is now complete.
if(complete && !dn->Complete) {
// Node is now complete, but wasn't before. Queue it.
dn->Complete = true;
this->Queue.push(QueueEntry(k, dn));
}
} else {
// This is a new node. Assign it an index.
dn->Index = ++this->NodeCount;
dn->Complete = complete;
if(complete || !this->RequireComplete) {
// Node is complete. Queue it.
this->Queue.push(QueueEntry(k, dn));
}
}
// Return node's index.
return dn->Index;
}
//----------------------------------------------------------------------------
unsigned int ASTVisitor::AddDumpFile(clang::FileEntry const* f)
{
unsigned int& index = this->FileNodes[f];
if(index == 0) {
index = ++this->FileCount;
this->FileQueue.push(f);
}
return index;
}
//----------------------------------------------------------------------------
void ASTVisitor::QueueIncompleteDumpNodes()
{
// Queue declaration nodes that do not need complete output.
for(DeclNodesMap::const_iterator i = this->DeclNodes.begin(),
e = this->DeclNodes.end(); i != e; ++i) {
if(!i->second.Complete) {
this->Queue.push(QueueEntry(i->first, &i->second));
}
}
// Queue type nodes that do not need complete output.
for(TypeNodesMap::const_iterator i = this->TypeNodes.begin(),
e = this->TypeNodes.end(); i != e; ++i) {
if(!i->second.Complete) {
this->Queue.push(QueueEntry(i->first, &i->second));
}
}
}
//----------------------------------------------------------------------------
void ASTVisitor::ProcessQueue()
{
// Dispatch each entry in the queue based on its node kind.
while(!this->Queue.empty()) {
QueueEntry qe = this->Queue.front();
this->Queue.pop();
switch(qe.Kind) {
case QueueEntry::KindDecl:
this->OutputDecl(qe.Decl, qe.DN);
break;
case QueueEntry::KindType:
this->OutputType(qe.Type, qe.DN);
break;
}
}
}
//----------------------------------------------------------------------------
void ASTVisitor::ProcessFileQueue()
{
while(!this->FileQueue.empty()) {
clang::FileEntry const* f = this->FileQueue.front();
this->FileQueue.pop();
this->OS <<
" <File"
" id=\"f" << this->FileNodes[f] << "\""
" name=\"" << encodeXML(f->getName()) << "\""
"/>\n"
;
}
}
//----------------------------------------------------------------------------
void ASTVisitor::OutputDecl(clang::Decl const* d, DumpNode const* dn)
{
// Dispatch output of the declaration.
switch (d->getKind()) {
#define ABSTRACT_DECL(DECL)
#define DECL(CLASS, BASE) \
case clang::Decl::CLASS: \
this->Output##CLASS##Decl( \
static_cast<clang::CLASS##Decl const*>(d), dn); \
break;
#include "clang/AST/DeclNodes.inc"
}
}
//----------------------------------------------------------------------------
void ASTVisitor::OutputType(clang::QualType t, DumpNode const* dn)
{
if(t.hasLocalQualifiers()) {
// Output the qualified type. This will queue
// the unqualified type if necessary.
this->OutputCvQualifiedType(t, dn);
} else {
// Dispatch output of the unqualified type.
switch (t->getTypeClass()) {
#define ABSTRACT_TYPE(CLASS, BASE)
#define TYPE(CLASS, BASE) \
case clang::Type::CLASS: \
this->Output##CLASS##Type( \
static_cast<clang::CLASS##Type const*>(t.getTypePtr()), dn); \
break;
#include "clang/AST/TypeNodes.def"
}
}
}
//----------------------------------------------------------------------------
void ASTVisitor::OutputCvQualifiedType(clang::QualType t, DumpNode const* dn)
{
// TODO: Output a CvQualifiedType element that references the
// unqualified type element and lists qualifier attributes.
static_cast<void>(t);
static_cast<void>(dn);
}
//----------------------------------------------------------------------------
void ASTVisitor::LookupStart(clang::DeclContext const* dc,
std::string const& name)
{
std::string::size_type pos = name.find("::");
std::string cur = name.substr(0, pos);
clang::IdentifierTable& ids = CI.getPreprocessor().getIdentifierTable();
clang::DeclContext::lookup_const_result r =
dc->lookup(clang::DeclarationName(&ids.get(cur)));
if(pos == name.npos) {
for(clang::DeclContext::lookup_const_iterator i = r.begin(), e = r.end();
i != e; ++i) {
this->AddDumpNode(*i, true);
}
} else {
std::string rest = name.substr(pos+2);
for(clang::DeclContext::lookup_const_iterator i = r.begin(), e = r.end();
i != e; ++i) {
if (clang::DeclContext* idc = clang::dyn_cast<clang::DeclContext>(*i)) {
this->LookupStart(idc, rest);
}
}
}
}
//----------------------------------------------------------------------------
void ASTVisitor::HandleTranslationUnit(clang::TranslationUnitDecl const* tu)
{
// Add the starting nodes for the dump.
if(!this->StartNames.empty()) {
// Use the specified starting locations.
for(std::vector<std::string>::const_iterator i = this->StartNames.begin(),
e = this->StartNames.end(); i != e; ++i) {
this->LookupStart(tu, *i);
}
} else {
// No start specified. Use whole translation unit.
this->AddDumpNode(tu, true);
}
// Start dump with gccxml-compatible format.
this->OS <<
"<?xml version=\"1.0\"?>\n"
"<GCC_XML version=\"0.9.0\" cvs_revision=\"1.136\">\n"
;
// Dump the complete nodes.
this->ProcessQueue();
// Queue all the incomplete nodes.
this->RequireComplete = false;
this->QueueIncompleteDumpNodes();
// Dump the incomplete nodes.
this->ProcessQueue();
// Dump the filename queue.
this->ProcessFileQueue();
// Finish dump.
this->OS <<
"</GCC_XML>\n"
;
}
//----------------------------------------------------------------------------
void outputXML(clang::CompilerInstance& ci,
clang::ASTContext const& ctx,
llvm::raw_ostream& os,
std::vector<std::string> const& startNames)
{
ASTVisitor v(ci, ctx, os, startNames);
v.HandleTranslationUnit(ctx.getTranslationUnitDecl());
}
<|endoftext|>
|
<commit_before>#pragma once
#include <boost/shared_ptr.hpp>
#include <darc/inbound_data.hpp>
#include <darc/serializer/boost.hpp>
#include <darc/message_packet.hpp>
#include <darc/subscribe_packet.hpp>
#include <darc/peer.hpp>
namespace darc
{
class RemoteDispatcher
{
protected:
// Datastructure stuff, refactor out
typedef std::pair</*peer*/ID, /*tag*/ID> remote_tag_type;
typedef std::set<remote_tag_type> remote_tag_list_type;
typedef boost::shared_ptr<remote_tag_list_type> remote_tag_list_type_ptr;
typedef std::map</*tag*/ID, remote_tag_list_type_ptr> remote_list_type;
remote_list_type list_;
peer& peer_;
protected:
void handle_subscribe_packet(const darc::ID& src_peer_id,
darc::buffer::shared_buffer data)
{
}
void handle_message_packet(const darc::ID& src_peer_id,
darc::buffer::shared_buffer data)
{
}
public:
RemoteDispatcher(peer& p) :
peer_(p)
{
}
void recv(const darc::ID& src_peer_id,
darc::service_type service_id,
darc::buffer::shared_buffer data)
{
darc::inbound_data<darc::serializer::boost_serializer, uint32_t> payload_type_i(data);
switch(payload_type_i.get())
{
case subscribe_packet::payload_id:
{
handle_subscribe_packet(src_peer_id, data);
}
break;
case message_packet::payload_id:
{
handle_message_packet(src_peer_id, data);
}
break;
default:
assert(0);
}
}
void new_tag_event(ID tag_id,
ID alias_id,
ID peer_id)
{
remote_list_type::iterator item = list_.find(tag_id);
if(item != list_.end())
{
remote_tag_list_type& l = *(item->second);
l.insert(remote_tag_type(peer_id, alias_id));
}
else
{
remote_tag_list_type_ptr lp = boost::make_shared<remote_tag_list_type>();
lp->insert(remote_tag_type(peer_id, alias_id));
list_.insert(remote_list_type::value_type(tag_id, lp));
}
}
template<typename T>
void dispatch_remotely(const ID& tag_id, const boost::shared_ptr<const T> &msg)
{
remote_list_type::iterator item = list_.find(tag_id);
if(item != list_.end())
{
for(remote_tag_list_type::iterator it = item->second->begin();
it != item->second->end();
it++)
{
// todo: here we send a copy to all
send_msg(tag_id, it->first, msg);
}
}
}
template<typename T>
void send_msg(const ID& tag_id, const ID& peer_id, const boost::shared_ptr<const T> &msg)
{
}
};
}
<commit_msg>serialize and send message<commit_after>#pragma once
#include <boost/shared_ptr.hpp>
#include <darc/inbound_data.hpp>
#include <darc/serializer/boost.hpp>
#include <darc/payload_header_packet.hpp>
#include <darc/message_packet.hpp>
#include <darc/subscribe_packet.hpp>
#include <darc/peer.hpp>
namespace darc
{
class RemoteDispatcher
{
protected:
// Datastructure stuff, refactor out
typedef std::pair</*peer*/ID, /*tag*/ID> remote_tag_type;
typedef std::set<remote_tag_type> remote_tag_list_type;
typedef boost::shared_ptr<remote_tag_list_type> remote_tag_list_type_ptr;
typedef std::map</*tag*/ID, remote_tag_list_type_ptr> remote_list_type;
remote_list_type list_;
peer& peer_;
protected:
void handle_subscribe_packet(const darc::ID& src_peer_id,
darc::buffer::shared_buffer data)
{
}
void handle_message_packet(const darc::ID& src_peer_id,
darc::buffer::shared_buffer data)
{
}
public:
RemoteDispatcher(peer& p) :
peer_(p)
{
}
void recv(const darc::ID& src_peer_id,
darc::service_type service_id,
darc::buffer::shared_buffer data)
{
darc::inbound_data<darc::serializer::boost_serializer, uint32_t> payload_type_i(data);
switch(payload_type_i.get())
{
case subscribe_packet::payload_id:
{
handle_subscribe_packet(src_peer_id, data);
}
break;
case message_packet::payload_id:
{
handle_message_packet(src_peer_id, data);
}
break;
default:
assert(0);
}
}
void new_tag_event(ID tag_id,
ID alias_id,
ID peer_id)
{
remote_list_type::iterator item = list_.find(tag_id);
if(item != list_.end())
{
remote_tag_list_type& l = *(item->second);
l.insert(remote_tag_type(peer_id, alias_id));
}
else
{
remote_tag_list_type_ptr lp = boost::make_shared<remote_tag_list_type>();
lp->insert(remote_tag_type(peer_id, alias_id));
list_.insert(remote_list_type::value_type(tag_id, lp));
}
}
template<typename T>
void dispatch_remotely(const ID& tag_id, const boost::shared_ptr<const T> &msg)
{
remote_list_type::iterator item = list_.find(tag_id);
if(item != list_.end())
{
for(remote_tag_list_type::iterator it = item->second->begin();
it != item->second->end();
it++)
{
// todo: here we send a copy to all
send_msg(tag_id, it->first, msg);
}
}
}
template<typename T>
void send_msg(const ID& tag_id, const ID& peer_id, const boost::shared_ptr<const T> &msg)
{
// todo move to peer_service
buffer::shared_buffer buffer = boost::make_shared<buffer::const_size_buffer>(1024*10); // todo
payload_header_packet hdr;
hdr.payload_type = message_packet::payload_id;
outbound_data<serializer::boost_serializer, payload_header_packet> o_hdr(hdr);
message_packet msg_hdr(tag_id);
outbound_data<serializer::boost_serializer, message_packet> o_msg_hdr(msg_hdr);
outbound_ptr<serializer::boost_serializer, T> o_msg(msg);
outbound_pair o_pair1(o_hdr, o_msg_hdr);
outbound_pair o_pair2(o_pair1, o_msg);
o_pair2.pack(buffer);
peer_.send_to(peer_id, 52, buffer);
}
};
}
<|endoftext|>
|
<commit_before>/**
* \file
* \brief StaticThread class header
*
* \author Copyright (C) 2014-2015 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/.
*
* \date 2015-03-26
*/
#ifndef INCLUDE_DISTORTOS_STATICTHREAD_HPP_
#define INCLUDE_DISTORTOS_STATICTHREAD_HPP_
#include "distortos/Thread.hpp"
#include "distortos/SignalsReceiver.hpp"
namespace distortos
{
/**
* \brief StaticThread class is a templated interface for thread that has automatic storage for stack.
*
* \param StackSize is the size of stack, bytes
* \param CanReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this thread
* \param Function is the function that will be executed in separate thread
* \param Args are the arguments for Function
*/
template<size_t StackSize, bool CanReceiveSignals, typename Function, typename... Args>
class StaticThread : public Thread<Function, Args...>
{
public:
/// base of StaticThread
using Base = Thread<Function, Args...>;
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) :
Base{&stack_, sizeof(stack_), priority, schedulingPolicy, std::forward<Function>(function),
std::forward<Args>(args)...}
{
}
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, Function&& function, Args&&... args) :
StaticThread{priority, SchedulingPolicy::RoundRobin, std::forward<Function>(function),
std::forward<Args>(args)...}
{
}
StaticThread(const StaticThread&) = delete;
StaticThread(StaticThread&&) = default;
const StaticThread& operator=(const StaticThread&) = delete;
StaticThread& operator=(StaticThread&&) = delete;
private:
/// stack buffer
typename std::aligned_storage<StackSize>::type stack_;
};
/**
* \brief StaticThread class is a templated interface for thread that has automatic storage for stack and internal
* SignalsReceiver object.
*
* Specialization for threads with enabled reception of signals (CanReceiveSignals == true)
*
* \param StackSize is the size of stack, bytes
* \param Function is the function that will be executed in separate thread
* \param Args are the arguments for Function
*/
template<size_t StackSize, typename Function, typename... Args>
class StaticThread<StackSize, true, Function, Args...> : public Thread<Function, Args...>
{
public:
/// base of StaticThread
using Base = Thread<Function, Args...>;
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) :
Base{&stack_, sizeof(stack_), priority, schedulingPolicy, &signalsReceiver_,
std::forward<Function>(function), std::forward<Args>(args)...},
signalsReceiver_{}
{
}
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, Function&& function, Args&&... args) :
StaticThread{priority, SchedulingPolicy::RoundRobin, std::forward<Function>(function),
std::forward<Args>(args)...}
{
}
StaticThread(const StaticThread&) = delete;
StaticThread(StaticThread&&) = default;
const StaticThread& operator=(const StaticThread&) = delete;
StaticThread& operator=(StaticThread&&) = delete;
private:
/// stack buffer
typename std::aligned_storage<StackSize>::type stack_;
/// internal SignalsReceiver object
SignalsReceiver signalsReceiver_;
};
/**
* \brief Helper factory function to make StaticThread object with partially deduced template arguments
*
* \param StackSize is the size of stack, bytes
* \param CanReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this thread
* \param Function is the function that will be executed
* \param Args are the arguments for Function
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*
* \return StaticThread object with partially deduced template arguments
*/
template<size_t StackSize, bool CanReceiveSignals = {}, typename Function, typename... Args>
StaticThread<StackSize, CanReceiveSignals, Function, Args...> makeStaticThread(const uint8_t priority,
const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args)
{
return {priority, schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...};
}
/**
* \brief Helper factory function to make StaticThread object with partially deduced template arguments
*
* \param StackSize is the size of stack, bytes
* \param CanReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this thread
* \param Function is the function that will be executed
* \param Args are the arguments for Function
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*
* \return StaticThread object with partially deduced template arguments
*/
template<size_t StackSize, bool CanReceiveSignals = {}, typename Function, typename... Args>
StaticThread<StackSize, CanReceiveSignals, Function, Args...> makeStaticThread(const uint8_t priority,
Function&& function, Args&&... args)
{
return {priority, std::forward<Function>(function), std::forward<Args>(args)...};
}
} // namespace distortos
#endif // INCLUDE_DISTORTOS_STATICTHREAD_HPP_
<commit_msg>StaticThread: replace internal SignalsReceiver with StaticSignalsReceiver<commit_after>/**
* \file
* \brief StaticThread class header
*
* \author Copyright (C) 2014-2015 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/.
*
* \date 2015-03-26
*/
#ifndef INCLUDE_DISTORTOS_STATICTHREAD_HPP_
#define INCLUDE_DISTORTOS_STATICTHREAD_HPP_
#include "distortos/Thread.hpp"
#include "distortos/StaticSignalsReceiver.hpp"
namespace distortos
{
/**
* \brief StaticThread class is a templated interface for thread that has automatic storage for stack.
*
* \param StackSize is the size of stack, bytes
* \param CanReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this thread
* \param Function is the function that will be executed in separate thread
* \param Args are the arguments for Function
*/
template<size_t StackSize, bool CanReceiveSignals, typename Function, typename... Args>
class StaticThread : public Thread<Function, Args...>
{
public:
/// base of StaticThread
using Base = Thread<Function, Args...>;
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) :
Base{&stack_, sizeof(stack_), priority, schedulingPolicy, std::forward<Function>(function),
std::forward<Args>(args)...}
{
}
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, Function&& function, Args&&... args) :
StaticThread{priority, SchedulingPolicy::RoundRobin, std::forward<Function>(function),
std::forward<Args>(args)...}
{
}
StaticThread(const StaticThread&) = delete;
StaticThread(StaticThread&&) = default;
const StaticThread& operator=(const StaticThread&) = delete;
StaticThread& operator=(StaticThread&&) = delete;
private:
/// stack buffer
typename std::aligned_storage<StackSize>::type stack_;
};
/**
* \brief StaticThread class is a templated interface for thread that has automatic storage for stack and internal
* StaticSignalsReceiver object.
*
* Specialization for threads with enabled reception of signals (CanReceiveSignals == true)
*
* \param StackSize is the size of stack, bytes
* \param Function is the function that will be executed in separate thread
* \param Args are the arguments for Function
*/
template<size_t StackSize, typename Function, typename... Args>
class StaticThread<StackSize, true, Function, Args...> : public Thread<Function, Args...>
{
public:
/// base of StaticThread
using Base = Thread<Function, Args...>;
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args) :
Base{&stack_, sizeof(stack_), priority, schedulingPolicy, &staticSignalsReceiver_,
std::forward<Function>(function), std::forward<Args>(args)...},
staticSignalsReceiver_{}
{
}
/**
* \brief StaticThread's constructor
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*/
StaticThread(const uint8_t priority, Function&& function, Args&&... args) :
StaticThread{priority, SchedulingPolicy::RoundRobin, std::forward<Function>(function),
std::forward<Args>(args)...}
{
}
StaticThread(const StaticThread&) = delete;
StaticThread(StaticThread&&) = default;
const StaticThread& operator=(const StaticThread&) = delete;
StaticThread& operator=(StaticThread&&) = delete;
private:
/// stack buffer
typename std::aligned_storage<StackSize>::type stack_;
/// internal StaticSignalsReceiver object
StaticSignalsReceiver staticSignalsReceiver_;
};
/**
* \brief Helper factory function to make StaticThread object with partially deduced template arguments
*
* \param StackSize is the size of stack, bytes
* \param CanReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this thread
* \param Function is the function that will be executed
* \param Args are the arguments for Function
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] schedulingPolicy is the scheduling policy of the thread
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*
* \return StaticThread object with partially deduced template arguments
*/
template<size_t StackSize, bool CanReceiveSignals = {}, typename Function, typename... Args>
StaticThread<StackSize, CanReceiveSignals, Function, Args...> makeStaticThread(const uint8_t priority,
const SchedulingPolicy schedulingPolicy, Function&& function, Args&&... args)
{
return {priority, schedulingPolicy, std::forward<Function>(function), std::forward<Args>(args)...};
}
/**
* \brief Helper factory function to make StaticThread object with partially deduced template arguments
*
* \param StackSize is the size of stack, bytes
* \param CanReceiveSignals selects whether reception of signals is enabled (true) or disabled (false) for this thread
* \param Function is the function that will be executed
* \param Args are the arguments for Function
*
* \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
* \param [in] function is a function that will be executed in separate thread
* \param [in] args are arguments for function
*
* \return StaticThread object with partially deduced template arguments
*/
template<size_t StackSize, bool CanReceiveSignals = {}, typename Function, typename... Args>
StaticThread<StackSize, CanReceiveSignals, Function, Args...> makeStaticThread(const uint8_t priority,
Function&& function, Args&&... args)
{
return {priority, std::forward<Function>(function), std::forward<Args>(args)...};
}
} // namespace distortos
#endif // INCLUDE_DISTORTOS_STATICTHREAD_HPP_
<|endoftext|>
|
<commit_before>/**
* \file
* \brief Architecture specific symbols
*
* \author Copyright (C) 2014 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/.
*
* \date 2014-08-06
*/
#ifndef INCLUDE_DISTORTOS_ARCHITECTURE_HPP_
#define INCLUDE_DISTORTOS_ARCHITECTURE_HPP_
#include "distortos/architecture/parameters.hpp"
#include <cstddef>
namespace distortos
{
/// architecture namespace has symbols that need to be provided by selected architecture
namespace architecture
{
/**
* \brief Enables interrupt masking.
*
* Disables normal-priority interrupts.
*
* \note High-priority interrupts are not controlled by distortos, so they may be left enabled. Support for that feature
* is architecture-dependent.
*
* \return previous value of interrupts' mask, must be used for matched restoreInterruptMasking() call
*/
InterruptMask enableInterruptMasking();
/**
* \brief Architecture-specific stack initialization.
*
* This function fills provided buffer with hardware and software stack frame and calculates value of stack pointer
* register. After this function completes, stack is ready for context switching.
*
* \attention buffer and size must be properly adjusted for architecture requirements
*
* \param [in] buffer is a pointer to stack's buffer
* \param [in] size is the size of stack's buffer, bytes
* \param [in] function is a reference to thread's function
* \param [in] arguments is an argument for function
* \param [in] trap is a reference to trap function called when thread function returns
*
* \return value that can be used as thread's stack pointer, ready for context switching
*/
void * initializeStack(void *buffer, size_t size, void * (&function)(void *), void *arguments, void (&trap)(void *));
/**
* \brief Restores interrupt masking.
*
* Restores previous interrupt masking state (before matching enableInterruptMasking() was called), enabling some (maybe
* all) interrupts.
*
* \param [in] interrupt_mask is the value of interrupts' mask, must come from previous call to enableInterruptMasking()
*/
void restoreInterruptMasking(InterruptMask interrupt_mask);
/**
* \brief Architecture-specific request for context switch.
*
* Causes the architecture to do context save, call scheduler::schedulerInstance.switchContext() and do context restore.
* The call to scheduler::schedulerInstance.switchContext() must be done from the context in which such call is valid
* (usually system interrupt).
*/
void requestContextSwitch();
/**
* \brief Architecture-specific start of scheduling.
*
* Initializes all required hardware/software to perform context switching and starts the scheduling.
*/
__attribute__ ((noreturn))
void startScheduling();
} // namespace architecture
} // namespace distortos
#endif // INCLUDE_DISTORTOS_ARCHITECTURE_HPP_
<commit_msg>include/distortos/architecture.hpp: add declaration of disableInterruptMasking()<commit_after>/**
* \file
* \brief Architecture specific symbols
*
* \author Copyright (C) 2014 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/.
*
* \date 2014-08-06
*/
#ifndef INCLUDE_DISTORTOS_ARCHITECTURE_HPP_
#define INCLUDE_DISTORTOS_ARCHITECTURE_HPP_
#include "distortos/architecture/parameters.hpp"
#include <cstddef>
namespace distortos
{
/// architecture namespace has symbols that need to be provided by selected architecture
namespace architecture
{
/**
* \brief Disables interrupt masking.
*
* Enables normal-priority interrupts.
*
* \return previous value of interrupts' mask, must be used for matched restoreInterruptMasking() call
*/
InterruptMask disableInterruptMasking();
/**
* \brief Enables interrupt masking.
*
* Disables normal-priority interrupts.
*
* \note High-priority interrupts are not controlled by distortos, so they may be left enabled. Support for that feature
* is architecture-dependent.
*
* \return previous value of interrupts' mask, must be used for matched restoreInterruptMasking() call
*/
InterruptMask enableInterruptMasking();
/**
* \brief Architecture-specific stack initialization.
*
* This function fills provided buffer with hardware and software stack frame and calculates value of stack pointer
* register. After this function completes, stack is ready for context switching.
*
* \attention buffer and size must be properly adjusted for architecture requirements
*
* \param [in] buffer is a pointer to stack's buffer
* \param [in] size is the size of stack's buffer, bytes
* \param [in] function is a reference to thread's function
* \param [in] arguments is an argument for function
* \param [in] trap is a reference to trap function called when thread function returns
*
* \return value that can be used as thread's stack pointer, ready for context switching
*/
void * initializeStack(void *buffer, size_t size, void * (&function)(void *), void *arguments, void (&trap)(void *));
/**
* \brief Restores interrupt masking.
*
* Restores previous interrupt masking state (before matching enableInterruptMasking() or disableInterruptMasking() was
* called), enabling some (maybe all, maybe none) interrupts.
*
* \param [in] interrupt_mask is the value of interrupts' mask, must come from previous call to enableInterruptMasking()
* or disableInterruptMasking()
*/
void restoreInterruptMasking(InterruptMask interrupt_mask);
/**
* \brief Architecture-specific request for context switch.
*
* Causes the architecture to do context save, call scheduler::schedulerInstance.switchContext() and do context restore.
* The call to scheduler::schedulerInstance.switchContext() must be done from the context in which such call is valid
* (usually system interrupt).
*/
void requestContextSwitch();
/**
* \brief Architecture-specific start of scheduling.
*
* Initializes all required hardware/software to perform context switching and starts the scheduling.
*/
__attribute__ ((noreturn))
void startScheduling();
} // namespace architecture
} // namespace distortos
#endif // INCLUDE_DISTORTOS_ARCHITECTURE_HPP_
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2013 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef MAPNIK_POLYGON_CLIPPER_HPP
#define MAPNIK_POLYGON_CLIPPER_HPP
// stl
#include <iostream>
#include <deque>
// mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/geometry.hpp>
// boost
#include <boost/tuple/tuple.hpp>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/register/point.hpp>
BOOST_GEOMETRY_REGISTER_POINT_2D(mapnik::coord2d, double, cs::cartesian, x, y)
// register mapnik::box2d<double>
namespace boost { namespace geometry { namespace traits
{
template<> struct tag<mapnik::box2d<double> > { typedef box_tag type; };
template<> struct point_type<mapnik::box2d<double> > { typedef mapnik::coord2d type; };
template <>
struct indexed_access<mapnik::box2d<double>, min_corner, 0>
{
typedef coordinate_type<mapnik::coord2d>::type ct;
static inline ct get(mapnik::box2d<double> const& b) { return b.minx();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_minx(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, min_corner, 1>
{
typedef coordinate_type<mapnik::coord2d>::type ct;
static inline ct get(mapnik::box2d<double> const& b) { return b.miny();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_miny(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, max_corner, 0>
{
typedef coordinate_type<mapnik::coord2d>::type ct;
static inline ct get(mapnik::box2d<double> const& b) { return b.maxx();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_maxx(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, max_corner, 1>
{
typedef coordinate_type<mapnik::coord2d>::type ct;
static inline ct get(mapnik::box2d<double> const& b) { return b.maxy();}
static inline void set(mapnik::box2d<double> &b , ct const& value) { b.set_maxy(value); }
};
}}}
namespace mapnik {
using namespace boost::geometry;
template <typename Geometry>
struct polygon_clipper
{
typedef mapnik::coord2d point_2d;
typedef model::polygon<mapnik::coord2d> polygon_2d;
typedef std::deque<polygon_2d> polygon_list;
enum
{
clip = 1,
no_clip = 2,
ignore = 3
} state_;
polygon_clipper(Geometry & geom)
: state_(clip),
clip_box_(),
geom_(geom)
{
}
polygon_clipper(box2d<double> const& clip_box, Geometry & geom)
:state_(clip),
clip_box_(clip_box),
geom_(geom)
{
init();
}
void set_clip_box(box2d<double> const& clip_box)
{
state_ = clip;
clip_box_ = clip_box;
init();
}
unsigned type() const
{
return geom_.type();
}
void rewind(unsigned path_id)
{
if (state_ == clip) output_.rewind(path_id);
else geom_.rewind(path_id);
}
unsigned vertex (double * x, double * y)
{
switch (state_)
{
case clip:
return output_.vertex(x,y);
case no_clip:
return geom_.vertex(x,y);
case ignore:
return SEG_END;
}
}
private:
void init()
{
geom_.rewind(0);
box2d<double> bbox = geom_.envelope();
if (clip_box_.contains(bbox))
{
// shortcut to original geometry (no-clipping)
state_ = no_clip;
return;
}
else if (!clip_box_.intersects(bbox))
{
// polygon is outside of clipping box
state_ = ignore;
return;
}
polygon_2d subject_poly;
double x,y;
double prev_x, prev_y;
geom_.rewind(0);
unsigned ring_count = 0;
while (true)
{
unsigned cmd = geom_.vertex(&x,&y);
if (cmd == SEG_END) break;
if (cmd == SEG_MOVETO)
{
prev_x = x;
prev_y = y;
if (ring_count == 0)
{
append(subject_poly, make<point_2d>(x,y));
}
else
{
subject_poly.inners().push_back(polygon_2d::inner_container_type::value_type());
append(subject_poly.inners().back(),make<point_2d>(x,y));
}
++ring_count;
}
else if (cmd == SEG_LINETO)
{
if (std::abs(x - prev_x) < 1e-12 && std::abs(y - prev_y) < 1e-12)
{
#ifdef MAPNIK_LOG
MAPNIK_LOG_WARN(polygon_clipper)
<< std::setprecision(12) << "coincident vertices:(" << prev_x << ","
<< prev_y << ") , (" << x << "," << y << ")";
#endif
continue;
}
prev_x = x;
prev_y = y;
if (ring_count == 1)
{
append(subject_poly, make<point_2d>(x,y));
}
else
{
append(subject_poly.inners().back(),make<point_2d>(x,y));
}
}
}
polygon_list clipped_polygons;
#ifdef MAPNIK_LOG
double area = boost::geometry::area(subject_poly);
if (area < 0)
{
MAPNIK_LOG_ERROR(polygon_clipper) << "negative area detected for polygon indicating incorrect winding order";
}
#endif
try
{
boost::geometry::intersection(clip_box_, subject_poly, clipped_polygons);
}
catch (boost::geometry::exception const& ex)
{
std::cerr << ex.what() << std::endl;
}
for (polygon_2d const& poly : clipped_polygons)
{
bool move_to = true;
for (point_2d const& c : boost::geometry::exterior_ring(poly))
{
if (move_to)
{
move_to = false;
output_.move_to(c.x,c.y);
}
else
{
output_.line_to(c.x,c.y);
}
}
output_.close_path();
// interior rings
for (polygon_2d::inner_container_type::value_type const& ring : boost::geometry::interior_rings(poly))
{
move_to = true;
for (point_2d const& c : ring)
{
if (move_to)
{
move_to = false;
output_.move_to(c.x,c.y);
}
else
{
output_.line_to(c.x,c.y);
}
}
output_.close_path();
}
}
}
box2d<double> clip_box_;
Geometry & geom_;
mapnik::geometry_type output_;
};
}
#endif //MAPNIK_POLYGON_CLIPPER_HPP
<commit_msg>polygon clipper: ensure we return from function<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2013 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef MAPNIK_POLYGON_CLIPPER_HPP
#define MAPNIK_POLYGON_CLIPPER_HPP
// stl
#include <iostream>
#include <deque>
// mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/geometry.hpp>
// boost
#include <boost/tuple/tuple.hpp>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/register/point.hpp>
BOOST_GEOMETRY_REGISTER_POINT_2D(mapnik::coord2d, double, cs::cartesian, x, y)
// register mapnik::box2d<double>
namespace boost { namespace geometry { namespace traits
{
template<> struct tag<mapnik::box2d<double> > { typedef box_tag type; };
template<> struct point_type<mapnik::box2d<double> > { typedef mapnik::coord2d type; };
template <>
struct indexed_access<mapnik::box2d<double>, min_corner, 0>
{
typedef coordinate_type<mapnik::coord2d>::type ct;
static inline ct get(mapnik::box2d<double> const& b) { return b.minx();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_minx(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, min_corner, 1>
{
typedef coordinate_type<mapnik::coord2d>::type ct;
static inline ct get(mapnik::box2d<double> const& b) { return b.miny();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_miny(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, max_corner, 0>
{
typedef coordinate_type<mapnik::coord2d>::type ct;
static inline ct get(mapnik::box2d<double> const& b) { return b.maxx();}
static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_maxx(value); }
};
template <>
struct indexed_access<mapnik::box2d<double>, max_corner, 1>
{
typedef coordinate_type<mapnik::coord2d>::type ct;
static inline ct get(mapnik::box2d<double> const& b) { return b.maxy();}
static inline void set(mapnik::box2d<double> &b , ct const& value) { b.set_maxy(value); }
};
}}}
namespace mapnik {
using namespace boost::geometry;
template <typename Geometry>
struct polygon_clipper
{
typedef mapnik::coord2d point_2d;
typedef model::polygon<mapnik::coord2d> polygon_2d;
typedef std::deque<polygon_2d> polygon_list;
enum
{
clip = 1,
no_clip = 2,
ignore = 3
} state_;
polygon_clipper(Geometry & geom)
: state_(clip),
clip_box_(),
geom_(geom)
{
}
polygon_clipper(box2d<double> const& clip_box, Geometry & geom)
:state_(clip),
clip_box_(clip_box),
geom_(geom)
{
init();
}
void set_clip_box(box2d<double> const& clip_box)
{
state_ = clip;
clip_box_ = clip_box;
init();
}
unsigned type() const
{
return geom_.type();
}
void rewind(unsigned path_id)
{
if (state_ == clip) output_.rewind(path_id);
else geom_.rewind(path_id);
}
unsigned vertex (double * x, double * y)
{
switch (state_)
{
case clip:
return output_.vertex(x,y);
case no_clip:
return geom_.vertex(x,y);
case ignore:
return SEG_END;
}
return SEG_END;
}
private:
void init()
{
geom_.rewind(0);
box2d<double> bbox = geom_.envelope();
if (clip_box_.contains(bbox))
{
// shortcut to original geometry (no-clipping)
state_ = no_clip;
return;
}
else if (!clip_box_.intersects(bbox))
{
// polygon is outside of clipping box
state_ = ignore;
return;
}
polygon_2d subject_poly;
double x,y;
double prev_x, prev_y;
geom_.rewind(0);
unsigned ring_count = 0;
while (true)
{
unsigned cmd = geom_.vertex(&x,&y);
if (cmd == SEG_END) break;
if (cmd == SEG_MOVETO)
{
prev_x = x;
prev_y = y;
if (ring_count == 0)
{
append(subject_poly, make<point_2d>(x,y));
}
else
{
subject_poly.inners().push_back(polygon_2d::inner_container_type::value_type());
append(subject_poly.inners().back(),make<point_2d>(x,y));
}
++ring_count;
}
else if (cmd == SEG_LINETO)
{
if (std::abs(x - prev_x) < 1e-12 && std::abs(y - prev_y) < 1e-12)
{
#ifdef MAPNIK_LOG
MAPNIK_LOG_WARN(polygon_clipper)
<< std::setprecision(12) << "coincident vertices:(" << prev_x << ","
<< prev_y << ") , (" << x << "," << y << ")";
#endif
continue;
}
prev_x = x;
prev_y = y;
if (ring_count == 1)
{
append(subject_poly, make<point_2d>(x,y));
}
else
{
append(subject_poly.inners().back(),make<point_2d>(x,y));
}
}
}
polygon_list clipped_polygons;
#ifdef MAPNIK_LOG
double area = boost::geometry::area(subject_poly);
if (area < 0)
{
MAPNIK_LOG_ERROR(polygon_clipper) << "negative area detected for polygon indicating incorrect winding order";
}
#endif
try
{
boost::geometry::intersection(clip_box_, subject_poly, clipped_polygons);
}
catch (boost::geometry::exception const& ex)
{
std::cerr << ex.what() << std::endl;
}
for (polygon_2d const& poly : clipped_polygons)
{
bool move_to = true;
for (point_2d const& c : boost::geometry::exterior_ring(poly))
{
if (move_to)
{
move_to = false;
output_.move_to(c.x,c.y);
}
else
{
output_.line_to(c.x,c.y);
}
}
output_.close_path();
// interior rings
for (polygon_2d::inner_container_type::value_type const& ring : boost::geometry::interior_rings(poly))
{
move_to = true;
for (point_2d const& c : ring)
{
if (move_to)
{
move_to = false;
output_.move_to(c.x,c.y);
}
else
{
output_.line_to(c.x,c.y);
}
}
output_.close_path();
}
}
}
box2d<double> clip_box_;
Geometry & geom_;
mapnik::geometry_type output_;
};
}
#endif //MAPNIK_POLYGON_CLIPPER_HPP
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_TEXT_SYMBOLIZER_HPP
#define MAPNIK_TEXT_SYMBOLIZER_HPP
// mapnik
#include <mapnik/color.hpp>
#include <mapnik/font_set.hpp>
#include <mapnik/graphics.hpp>
#include <mapnik/filter_factory.hpp>
#include <mapnik/symbolizer.hpp>
#include <mapnik/text_placements.hpp>
// boost
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
// stl
#include <string>
namespace mapnik
{
struct MAPNIK_DECL text_symbolizer : public symbolizer_base
{
// Note - we do not use boost::make_shared below as VC2008 and VC2010 are
// not able to compile make_shared used within a constructor
text_symbolizer(text_placements_ptr placements = text_placements_ptr(
boost::make_shared<text_placements_dummy>())
);
text_symbolizer(expression_ptr name, std::string const& face_name,
float size, color const& fill,
text_placements_ptr placements = text_placements_ptr(new text_placements_dummy)
);
text_symbolizer(expression_ptr name, float size, color const& fill,
text_placements_ptr placements = text_placements_ptr(new text_placements_dummy)
);
text_symbolizer(text_symbolizer const& rhs);
text_symbolizer& operator=(text_symbolizer const& rhs);
expression_ptr get_name() const;
void set_name(expression_ptr expr);
expression_ptr get_orientation() const; // orienation (rotation angle atm)
void set_orientation(expression_ptr expr);
unsigned get_text_ratio() const; // target ratio for text bounding box in pixels
void set_text_ratio(unsigned ratio);
unsigned get_wrap_width() const; // width to wrap text at, or trigger ratio
void set_wrap_width(unsigned ratio);
unsigned char get_wrap_char() const; // character used to wrap lines
std::string get_wrap_char_string() const; // character used to wrap lines as std::string
void set_wrap_char(unsigned char character);
void set_wrap_char_from_string(std::string const& character);
text_transform_e get_text_transform() const; // text conversion on strings before display
void set_text_transform(text_transform_e convert);
unsigned get_line_spacing() const; // spacing between lines of text
void set_line_spacing(unsigned spacing);
unsigned get_character_spacing() const; // spacing between characters in text
void set_character_spacing(unsigned spacing);
unsigned get_label_spacing() const; // spacing between repeated labels on lines
void set_label_spacing(unsigned spacing);
unsigned get_label_position_tolerance() const; //distance the label can be moved on the line to fit, if 0 the default is used
void set_label_position_tolerance(unsigned tolerance);
bool get_force_odd_labels() const; // try render an odd amount of labels
void set_force_odd_labels(bool force);
double get_max_char_angle_delta() const; // maximum change in angle between adjacent characters
void set_max_char_angle_delta(double angle);
float get_text_size() const;
void set_text_size(float size);
std::string const& get_face_name() const;
void set_face_name(std::string face_name);
font_set const& get_fontset() const;
void set_fontset(font_set const& fset);
color const& get_fill() const;
void set_fill(color const& fill);
void set_halo_fill(color const& fill);
color const& get_halo_fill() const;
void set_halo_radius(double radius);
double get_halo_radius() const;
void set_label_placement(label_placement_e label_p);
label_placement_e get_label_placement() const;
void set_vertical_alignment(vertical_alignment_e valign);
vertical_alignment_e get_vertical_alignment() const;
void set_displacement(double x, double y);
void set_displacement(position const& p);
position const& get_displacement() const;
void set_avoid_edges(bool avoid);
bool get_avoid_edges() const;
void set_minimum_distance(double distance);
double get_minimum_distance() const;
void set_minimum_padding(double distance);
double get_minimum_padding() const;
void set_minimum_path_length(double size);
double get_minimum_path_length() const;
void set_allow_overlap(bool overlap);
bool get_allow_overlap() const;
void set_text_opacity(double opacity);
double get_text_opacity() const;
bool get_wrap_before() const; // wrap text at wrap_char immediately before current work
void set_wrap_before(bool wrap_before);
void set_horizontal_alignment(horizontal_alignment_e valign);
horizontal_alignment_e get_horizontal_alignment() const;
void set_justify_alignment(justify_alignment_e valign);
justify_alignment_e get_justify_alignment() const;
text_placements_ptr get_placement_options() const;
void set_placement_options(text_placements_ptr placement_options);
private:
expression_ptr name_;
expression_ptr orientation_;
std::string face_name_;
font_set fontset_;
unsigned text_ratio_;
unsigned wrap_width_;
unsigned char wrap_char_;
text_transform_e text_transform_;
unsigned line_spacing_;
unsigned character_spacing_;
unsigned label_spacing_;
unsigned label_position_tolerance_;
bool force_odd_labels_;
double max_char_angle_delta_;
color fill_;
color halo_fill_;
double halo_radius_;
label_placement_e label_p_;
bool avoid_edges_;
double minimum_distance_;
double minimum_padding_;
double minimum_path_length_;
bool overlap_;
double text_opacity_;
bool wrap_before_;
text_placements_ptr placement_options_;
};
}
#endif // MAPNIK_TEXT_SYMBOLIZER_HPP
<commit_msg>Add deprecation warnings.<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_TEXT_SYMBOLIZER_HPP
#define MAPNIK_TEXT_SYMBOLIZER_HPP
// mapnik
#include <mapnik/color.hpp>
#include <mapnik/font_set.hpp>
#include <mapnik/graphics.hpp>
#include <mapnik/filter_factory.hpp>
#include <mapnik/symbolizer.hpp>
#include <mapnik/text_placements.hpp>
// boost
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
// stl
#include <string>
// Warning disabled for the moment
#if (0 && __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
#define func_deprecated __attribute__ ((deprecated))
#else
#define func_deprecated
#endif
namespace mapnik
{
struct MAPNIK_DECL text_symbolizer : public symbolizer_base
{
// Note - we do not use boost::make_shared below as VC2008 and VC2010 are
// not able to compile make_shared used within a constructor
text_symbolizer(text_placements_ptr placements = text_placements_ptr(
boost::make_shared<text_placements_dummy>())
);
text_symbolizer(expression_ptr name, std::string const& face_name,
float size, color const& fill,
text_placements_ptr placements = text_placements_ptr(new text_placements_dummy)
);
text_symbolizer(expression_ptr name, float size, color const& fill,
text_placements_ptr placements = text_placements_ptr(new text_placements_dummy)
);
text_symbolizer(text_symbolizer const& rhs);
text_symbolizer& operator=(text_symbolizer const& rhs);
expression_ptr get_name() const func_deprecated;
void set_name(expression_ptr expr);
expression_ptr get_orientation() const func_deprecated; // orienation (rotation angle atm)
void set_orientation(expression_ptr expr);
unsigned get_text_ratio() const func_deprecated; // target ratio for text bounding box in pixels
void set_text_ratio(unsigned ratio);
unsigned get_wrap_width() const func_deprecated; // width to wrap text at, or trigger ratio
void set_wrap_width(unsigned ratio);
unsigned char get_wrap_char() const func_deprecated; // character used to wrap lines
std::string get_wrap_char_string() const func_deprecated; // character used to wrap lines as std::string
void set_wrap_char(unsigned char character);
void set_wrap_char_from_string(std::string const& character);
text_transform_e get_text_transform() const func_deprecated; // text conversion on strings before display
void set_text_transform(text_transform_e convert);
unsigned get_line_spacing() const func_deprecated; // spacing between lines of text
void set_line_spacing(unsigned spacing);
unsigned get_character_spacing() const func_deprecated; // spacing between characters in text
void set_character_spacing(unsigned spacing);
unsigned get_label_spacing() const func_deprecated; // spacing between repeated labels on lines
void set_label_spacing(unsigned spacing);
unsigned get_label_position_tolerance() const func_deprecated; //distance the label can be moved on the line to fit, if 0 the default is used
void set_label_position_tolerance(unsigned tolerance);
bool get_force_odd_labels() const func_deprecated; // try render an odd amount of labels
void set_force_odd_labels(bool force);
double get_max_char_angle_delta() const func_deprecated; // maximum change in angle between adjacent characters
void set_max_char_angle_delta(double angle);
float get_text_size() const func_deprecated;
void set_text_size(float size);
std::string const& get_face_name() const func_deprecated;
void set_face_name(std::string face_name);
font_set const& get_fontset() const func_deprecated;
void set_fontset(font_set const& fset);
color const& get_fill() const func_deprecated;
void set_fill(color const& fill);
void set_halo_fill(color const& fill);
color const& get_halo_fill() const func_deprecated;
void set_halo_radius(double radius);
double get_halo_radius() const func_deprecated;
void set_label_placement(label_placement_e label_p);
label_placement_e get_label_placement() const func_deprecated;
void set_vertical_alignment(vertical_alignment_e valign);
vertical_alignment_e get_vertical_alignment() const func_deprecated;
void set_displacement(double x, double y);
void set_displacement(position const& p);
position const& get_displacement() const func_deprecated;
void set_avoid_edges(bool avoid);
bool get_avoid_edges() const func_deprecated;
void set_minimum_distance(double distance);
double get_minimum_distance() const func_deprecated;
void set_minimum_padding(double distance);
double get_minimum_padding() const func_deprecated;
void set_minimum_path_length(double size);
double get_minimum_path_length() const func_deprecated;
void set_allow_overlap(bool overlap);
bool get_allow_overlap() const func_deprecated;
void set_text_opacity(double opacity);
double get_text_opacity() const func_deprecated;
void set_wrap_before(bool wrap_before);
bool get_wrap_before() const func_deprecated; // wrap text at wrap_char immediately before current work
void set_horizontal_alignment(horizontal_alignment_e valign);
horizontal_alignment_e get_horizontal_alignment() const func_deprecated;
void set_justify_alignment(justify_alignment_e valign);
justify_alignment_e get_justify_alignment() const func_deprecated;
text_placements_ptr get_placement_options() const;
void set_placement_options(text_placements_ptr placement_options);
private:
expression_ptr name_;
expression_ptr orientation_;
std::string face_name_;
font_set fontset_;
unsigned text_ratio_;
unsigned wrap_width_;
unsigned char wrap_char_;
text_transform_e text_transform_;
unsigned line_spacing_;
unsigned character_spacing_;
unsigned label_spacing_;
unsigned label_position_tolerance_;
bool force_odd_labels_;
double max_char_angle_delta_;
color fill_;
color halo_fill_;
double halo_radius_;
label_placement_e label_p_;
bool avoid_edges_;
double minimum_distance_;
double minimum_padding_;
double minimum_path_length_;
bool overlap_;
double text_opacity_;
bool wrap_before_;
text_placements_ptr placement_options_;
};
}
#endif // MAPNIK_TEXT_SYMBOLIZER_HPP
<|endoftext|>
|
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#ifndef IMPL_CONTAINER_H
#define IMPL_CONTAINER_H
#include <memory>
namespace nix {
namespace base {
template<typename T>
class ImplContainer {
protected:
std::shared_ptr<T> impl_ptr;
public:
ImplContainer() {}
ImplContainer(T *p_impl)
: impl_ptr(p_impl)
{
}
ImplContainer(const std::shared_ptr<T> &p_impl)
: impl_ptr(p_impl)
{
}
ImplContainer(const ImplContainer<T> &other)
: impl_ptr(other.impl_ptr)
{
}
virtual ImplContainer<T> &operator=(const ImplContainer<T> &other) {
if (*this != other) {
ImplContainer tmp(other);
swap(tmp);
}
return *this;
}
virtual bool operator==(const ImplContainer<T> &other) {
return this->impl_ptr == other.impl_ptr;
}
virtual bool operator!=(const ImplContainer<T> &other) {
return !(*this == other);
}
virtual void swap(ImplContainer<T> &second) {
using std::swap;
swap(impl_ptr, second.impl_ptr);
}
virtual ~ImplContainer() {}
std::shared_ptr<T> impl() const {
return impl_ptr;
}
};
} // namespace base
} // namespace nix
#endif
<commit_msg>ImplContainer: support for assignment and comparison with NULL and nullptr<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#ifndef IMPL_CONTAINER_H
#define IMPL_CONTAINER_H
#include <memory>
namespace nix {
namespace base {
template<typename T>
class ImplContainer {
protected:
std::shared_ptr<T> impl_ptr;
public:
ImplContainer() {}
ImplContainer(T *p_impl)
: impl_ptr(p_impl)
{
}
ImplContainer(const std::shared_ptr<T> &p_impl)
: impl_ptr(p_impl)
{
}
ImplContainer(const ImplContainer<T> &other)
: impl_ptr(other.impl_ptr)
{
}
virtual ImplContainer<T> &operator=(const ImplContainer<T> &other) {
if (*this != other) {
ImplContainer tmp(other);
swap(tmp);
}
return *this;
}
virtual ImplContainer<T> &operator=(std::nullptr_t nullp) {
impl_ptr = nullp;
return *this;
}
virtual bool operator==(const ImplContainer<T> &other) {
return this->impl_ptr == other.impl_ptr;
}
virtual bool operator!=(const ImplContainer<T> &other) {
return !(*this == other);
}
virtual bool operator==(std::nullptr_t nullp) {
return impl_ptr == nullp;
}
virtual bool operator!=(std::nullptr_t nullp) {
return impl_ptr != nullp;
}
virtual void swap(ImplContainer<T> &second) {
using std::swap;
swap(impl_ptr, second.impl_ptr);
}
virtual ~ImplContainer() {}
std::shared_ptr<T> impl() const {
return impl_ptr;
}
};
} // namespace base
} // namespace nix
#endif
<|endoftext|>
|
<commit_before>#ifndef PLANET_BASIC_OPERATION_HPP
#define PLANET_BASIC_OPERATION_HPP
#include <planet/common.hpp>
namespace planet {
class file_entry;
//
// planet core handler
//
class planet_operation {
protected:
static std::vector<char>& data_vector(file_entry& file);
public:
virtual ~planet_operation() noexcept
{
}
// Create new instance of this file operation
virtual shared_ptr<planet_operation> new_instance() const = 0;
// Open, read, write and close hook functions
virtual int open(shared_ptr<file_entry>, path_type const&) = 0;
virtual int read(shared_ptr<file_entry>, char *buf, size_t size, off_t offset) = 0;
virtual int write(shared_ptr<file_entry>, char const *buf, size_t size, off_t offset) = 0;
virtual int release(shared_ptr<file_entry>) = 0;
// Initialize the first arguemnt of file_entry
// shared_ptr<file_entry> is the new file entry which a new file operation will use
virtual int mknod(shared_ptr<file_entry>, path_type const&, mode_t, dev_t) = 0;
// Destoroy the first arguments of file_entry
// shared_ptr<file_entry> was used by an other file operation, and now no one never uses it
virtual int rmnod(shared_ptr<file_entry>, path_type const&) = 0;
};
//
// Note: All of planetfs operations must inherit planet_operation
// and implement static function named `is_matching_path()`
// which returns true if the given path is for the operation
//
// default file operation which is used if no other operations match the target path
class default_file_op final : public planet_operation {
public:
~default_file_op() = default;
shared_ptr<planet_operation> new_instance() const;
int open(shared_ptr<file_entry> file_ent, path_type const& path) override;
int read(shared_ptr<file_entry> file_ent, char *buf, size_t size, off_t offset) override;
int write(shared_ptr<file_entry> file_ent, char const *buf, size_t size, off_t offset) override;
int release(shared_ptr<file_entry> file_ent) override;
int mknod(shared_ptr<file_entry>, path_type const&, mode_t, dev_t) override;
int rmnod(shared_ptr<file_entry>, path_type const&) override;
static bool is_matching_path(path_type const&)
{
return true;
}
};
} //namespace planet
#endif // PLANET_BASIC_OPERATION_HPP
<commit_msg>Fix typo in basic_operation.hpp<commit_after>#ifndef PLANET_BASIC_OPERATION_HPP
#define PLANET_BASIC_OPERATION_HPP
#include <planet/common.hpp>
namespace planet {
class file_entry;
//
// planet core handler
//
class planet_operation {
protected:
static std::vector<char>& data_vector(file_entry& file);
public:
virtual ~planet_operation() noexcept
{
}
// Create new instance of this file operation
virtual shared_ptr<planet_operation> new_instance() const = 0;
// Open, read, write and close hook functions
virtual int open(shared_ptr<file_entry>, path_type const&) = 0;
virtual int read(shared_ptr<file_entry>, char *buf, size_t size, off_t offset) = 0;
virtual int write(shared_ptr<file_entry>, char const *buf, size_t size, off_t offset) = 0;
virtual int release(shared_ptr<file_entry>) = 0;
// Initialize the first arguemnt of file_entry
// shared_ptr<file_entry> is the new file entry which a new file operation will use
virtual int mknod(shared_ptr<file_entry>, path_type const&, mode_t, dev_t) = 0;
// Destoroy the first argument of file_entry
// shared_ptr<file_entry> was used by an other file operation, and now no one never uses it
virtual int rmnod(shared_ptr<file_entry>, path_type const&) = 0;
};
//
// Note: All of planetfs operations must inherit planet_operation
// and implement static function named `is_matching_path()`
// which returns true if the given path is for the operation
//
// default file operation which is used if no other operations match the target path
class default_file_op final : public planet_operation {
public:
~default_file_op() = default;
shared_ptr<planet_operation> new_instance() const;
int open(shared_ptr<file_entry> file_ent, path_type const& path) override;
int read(shared_ptr<file_entry> file_ent, char *buf, size_t size, off_t offset) override;
int write(shared_ptr<file_entry> file_ent, char const *buf, size_t size, off_t offset) override;
int release(shared_ptr<file_entry> file_ent) override;
int mknod(shared_ptr<file_entry>, path_type const&, mode_t, dev_t) override;
int rmnod(shared_ptr<file_entry>, path_type const&) override;
static bool is_matching_path(path_type const&)
{
return true;
}
};
} //namespace planet
#endif // PLANET_BASIC_OPERATION_HPP
<|endoftext|>
|
<commit_before>//===- include/seec/Trace/TraceFormat.hpp --------------------------- C++ -===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#ifndef SEEC_TRACE_TRACEFORMAT_HPP
#define SEEC_TRACE_TRACEFORMAT_HPP
#include "seec/Preprocessor/Apply.h"
#include "seec/Util/Maybe.hpp"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdint>
#include <utility>
#include <memory>
#include <type_traits>
namespace seec {
namespace runtime_errors {
class Arg;
}
namespace trace {
/// Type used for offsets into trace files.
typedef uint64_t offset_uint;
/// Value used to represent an invalid or nonexistant offset.
inline offset_uint noOffset() {
return std::numeric_limits<offset_uint>::max();
}
/// Version of the trace storage format.
constexpr inline uint64_t formatVersion() { return 3; }
/// ThreadID used to indicate that an event location refers to the initial
/// state of the process.
constexpr inline uint32_t initialDataThreadID() { return 0; }
/// ProcessTime used to refer to the initial state of the process.
constexpr inline uint64_t initialDataProcessTime() { return 0; }
/// Enumeration of possible event types.
enum class EventType : uint8_t {
None = 0,
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) NAME,
#include "seec/Trace/Events.def"
Highest
};
/// \brief Get a string indicating describing the value of Type.
char const *describe(EventType Type);
//------------------------------------------------------------------------------
// Event traits
//------------------------------------------------------------------------------
/// For events that represent the start of an event block. That is, events with
/// this trait can be applied separately to any prior events.
template<EventType ET>
struct is_block_start { static bool const value = false; };
/// For events that contain additional information for a preceding event.
template<EventType ET>
struct is_subservient { static bool const value = false; };
/// For events that affect the currently active function.
template<EventType ET>
struct is_function_level { static bool const value = false; };
/// For events that set the currently active instruction.
template<EventType ET>
struct is_instruction { static bool const value = false; };
/// For events that affect the shared process state.
template<EventType ET>
struct modifies_shared_state { static bool const value = false; };
/// For events that set memory state (not clearing).
template<EventType ET>
struct is_memory_state { static bool const value = false; };
/// Dummy trait for events that define no other traits.
template<EventType ET>
struct no_traits { static bool const value = false; };
#define SEEC_PP_TRAIT(EVENT_NAME, TRAIT_NAME) \
template<> \
struct TRAIT_NAME<EventType::EVENT_NAME> { static bool const value = true; }; \
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \
SEEC_PP_APPLY(SEEC_PP_TRAIT, TRAITS)
#include "seec/Trace/Events.def"
#undef SEEC_PP_TRAIT
//------------------------------------------------------------------------------
// FunctionRecord
//------------------------------------------------------------------------------
///
struct FunctionRecord {
uint32_t Index;
offset_uint EventOffsetStart;
offset_uint EventOffsetEnd;
uint64_t ThreadTimeEntered;
uint64_t ThreadTimeExited;
offset_uint ChildListOffset;
offset_uint NonLocalChangeListOffset;
};
//------------------------------------------------------------------------------
// RuntimeValueRecord
//------------------------------------------------------------------------------
union RuntimeValueRecord {
uint64_t UInt64;
uintptr_t UIntPtr;
float Float;
double Double;
long double LongDouble;
/// \brief Default construct.
RuntimeValueRecord()
{}
/// \brief Copy construct.
RuntimeValueRecord(RuntimeValueRecord const &Other) = default;
/// \brief Construct a new record holding a uint32_t.
explicit RuntimeValueRecord(uint32_t Value)
: UInt64(Value)
{}
/// \brief Construct a new record holding a uint64_t.
explicit RuntimeValueRecord(uint64_t Value)
: UInt64(Value)
{}
/// \brief Create a new record holding a uintptr_t.
explicit RuntimeValueRecord(void const *Value)
: UIntPtr(reinterpret_cast<uintptr_t>(Value))
{}
/// \brief Construct a new record holding a float.
explicit RuntimeValueRecord(float Value)
: Float(Value)
{}
/// \brief Construct a new record holding a double.
explicit RuntimeValueRecord(double Value)
: Double(Value)
{}
/// \brief Construct a new record holding a long double.
explicit RuntimeValueRecord(long double Value)
: LongDouble(Value)
{}
/// \brief Copy assign.
RuntimeValueRecord &operator=(RuntimeValueRecord const &RHS) = default;
};
llvm::raw_ostream & operator<<(llvm::raw_ostream &Out,
RuntimeValueRecord const &Record);
//------------------------------------------------------------------------------
// EventRecordBase
//------------------------------------------------------------------------------
// forward-declaration
template<EventType ET>
class EventRecord;
/// \brief Base class for all event records.
class EventRecordBase {
EventType Type;
uint8_t PreviousEventSize;
public:
EventRecordBase(EventType Type, uint8_t PreviousEventSize)
: Type(Type),
PreviousEventSize(PreviousEventSize)
{}
/// \name Conversion
/// @{
template<EventType ET>
EventRecord<ET> const &as() const {
assert(Type == ET);
return *(static_cast<EventRecord<ET> const *>(this));
}
/// @}
/// \name Query event properties
/// @{
/// Get the type of this event.
EventType getType() const { return Type; }
/// Get the size of the event immediately preceding this event.
uint8_t getPreviousEventSize() const { return PreviousEventSize; }
/// Get the size of this event.
std::size_t getEventSize() const;
/// Get the value of this event's ProcessTime, if it has one.
seec::Maybe<uint64_t> getProcessTime() const;
/// Get the value of this event's ThreadTime, if it has one.
seec::Maybe<uint64_t> getThreadTime() const;
/// Get the value of this event's Index member, if it has one.
seec::Maybe<uint32_t> getIndex() const;
/// Check if this event has the is_block_start trait.
bool isBlockStart() const {
switch (Type) {
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \
case EventType::NAME: return is_block_start<EventType::NAME>::value;
#include "seec/Trace/Events.def"
default: llvm_unreachable("Reference to unknown event type!");
}
return false;
}
/// Check if this event has the is_subservient trait.
bool isSubservient() const {
switch (Type) {
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \
case EventType::NAME: return is_subservient<EventType::NAME>::value;
#include "seec/Trace/Events.def"
default: llvm_unreachable("Reference to unknown event type!");
}
return false;
}
/// Check if this event has the is_function_level trait.
bool isFunctionLevel() const {
switch (Type) {
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \
case EventType::NAME: return is_function_level<EventType::NAME>::value;
#include "seec/Trace/Events.def"
default: llvm_unreachable("Reference to unknown event type!");
}
return false;
}
/// Check if this event has the is_instruction trait.
bool isInstruction() const {
switch (Type) {
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \
case EventType::NAME: return is_instruction<EventType::NAME>::value;
#include "seec/Trace/Events.def"
default: llvm_unreachable("Reference to unknown event type!");
}
return false;
}
/// Check if this event has the modifies_shared_state trait.
bool modifiesSharedState() const {
switch (Type) {
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \
case EventType::NAME: \
return modifies_shared_state<EventType::NAME>::value;
#include "seec/Trace/Events.def"
default: llvm_unreachable("Reference to unknown event type!");
}
return false;
}
/// Check if this event has the is_memory_state trait.
bool isMemoryState() const {
switch (Type) {
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \
case EventType::NAME: \
return is_memory_state<EventType::NAME>::value;
#include "seec/Trace/Events.def"
default: llvm_unreachable("Reference to unknown event type!");
}
return false;
}
/// @} (Query event properties)
};
llvm::raw_ostream & operator<<(llvm::raw_ostream &Out,
EventRecordBase const &Event);
//------------------------------------------------------------------------------
// Event records
//------------------------------------------------------------------------------
template<EventType ET>
class EventRecord : public EventRecordBase {};
#define SEEC_PP_MEMBER(TYPE, NAME) TYPE NAME;
#define SEEC_PP_ACCESSOR(TYPE, NAME) \
TYPE const &get##NAME() const { return NAME; } \
static std::size_t sizeof##NAME() { return sizeof(NAME); } \
typedef TYPE typeof##NAME;
#define SEEC_PP_PARAMETER(TYPE, NAME) , TYPE NAME
#define SEEC_PP_INITIALIZE(TYPE, NAME) , NAME(NAME)
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \
template<> \
class EventRecord<EventType::NAME> : public EventRecordBase { \
private: \
SEEC_PP_APPLY(SEEC_PP_MEMBER, MEMBERS) \
public: \
SEEC_PP_APPLY(SEEC_PP_ACCESSOR, MEMBERS) \
\
EventRecord(uint8_t PreviousEventSize \
SEEC_PP_APPLY(SEEC_PP_PARAMETER, MEMBERS) \
) \
: EventRecordBase(EventType::NAME, PreviousEventSize) \
SEEC_PP_APPLY(SEEC_PP_INITIALIZE, MEMBERS) \
{} \
};
#include "seec/Trace/Events.def"
#undef SEEC_PP_MEMBER
#undef SEEC_PP_ACCESSOR
#undef SEEC_PP_PARAMETER
#undef SEEC_PP_INITIALIZE
// Declare raw_ostream output for all event records.
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \
llvm::raw_ostream &operator<<(llvm::raw_ostream &Out, \
EventRecord<EventType::NAME> const &Event);
#include "seec/Trace/Events.def"
/// \brief Holds the thread and offset of an event record.
///
class EventLocation {
/// The thread that contains the event.
uint32_t ThreadID;
/// The offset of the event in the thread's event trace.
offset_uint Offset;
public:
/// Construct a new empty EventLocation.
EventLocation()
: ThreadID(0),
Offset(noOffset())
{}
/// Construct a new EventLocation.
EventLocation(uint32_t EventThreadID, offset_uint EventOffset)
: ThreadID(EventThreadID),
Offset(EventOffset)
{}
EventLocation(EventLocation const &) = default;
EventLocation &operator=(EventLocation const &) = default;
/// Get the thread ID of the thread that contains the event.
uint32_t getThreadID() const { return ThreadID; }
/// Check whether this event location has a legitimate offset.
bool hasOffset() const { return Offset != noOffset(); }
/// Get the offset of the event in the thread's event trace.
offset_uint getOffset() const { return Offset; }
/// \name Comparison
/// @{
/// \brief Check if this EventLocation is equal to another EventLocation.
bool operator==(EventLocation const &RHS) const {
return ThreadID == RHS.ThreadID && Offset == RHS.Offset;
}
/// \brief Check if this EventLocation differs from another EventLocation.
bool operator!=(EventLocation const &RHS) const {
return !operator==(RHS);
}
/// @} (Comparison)
};
} // namespace trace (in seec)
} // namespace seec
#endif // SEEC_TRACE_TRACEFORMAT_HPP
<commit_msg>Remove unused dummy trait "no_traits".<commit_after>//===- include/seec/Trace/TraceFormat.hpp --------------------------- C++ -===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#ifndef SEEC_TRACE_TRACEFORMAT_HPP
#define SEEC_TRACE_TRACEFORMAT_HPP
#include "seec/Preprocessor/Apply.h"
#include "seec/Util/Maybe.hpp"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdint>
#include <utility>
#include <memory>
#include <type_traits>
namespace seec {
namespace runtime_errors {
class Arg;
}
namespace trace {
/// Type used for offsets into trace files.
typedef uint64_t offset_uint;
/// Value used to represent an invalid or nonexistant offset.
inline offset_uint noOffset() {
return std::numeric_limits<offset_uint>::max();
}
/// Version of the trace storage format.
constexpr inline uint64_t formatVersion() { return 3; }
/// ThreadID used to indicate that an event location refers to the initial
/// state of the process.
constexpr inline uint32_t initialDataThreadID() { return 0; }
/// ProcessTime used to refer to the initial state of the process.
constexpr inline uint64_t initialDataProcessTime() { return 0; }
/// Enumeration of possible event types.
enum class EventType : uint8_t {
None = 0,
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) NAME,
#include "seec/Trace/Events.def"
Highest
};
/// \brief Get a string indicating describing the value of Type.
char const *describe(EventType Type);
//------------------------------------------------------------------------------
// Event traits
//------------------------------------------------------------------------------
/// For events that represent the start of an event block. That is, events with
/// this trait can be applied separately to any prior events.
template<EventType ET>
struct is_block_start { static bool const value = false; };
/// For events that contain additional information for a preceding event.
template<EventType ET>
struct is_subservient { static bool const value = false; };
/// For events that affect the currently active function.
template<EventType ET>
struct is_function_level { static bool const value = false; };
/// For events that set the currently active instruction.
template<EventType ET>
struct is_instruction { static bool const value = false; };
/// For events that affect the shared process state.
template<EventType ET>
struct modifies_shared_state { static bool const value = false; };
/// For events that set memory state (not clearing).
template<EventType ET>
struct is_memory_state { static bool const value = false; };
#define SEEC_PP_TRAIT(EVENT_NAME, TRAIT_NAME) \
template<> \
struct TRAIT_NAME<EventType::EVENT_NAME> { static bool const value = true; }; \
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \
SEEC_PP_APPLY(SEEC_PP_TRAIT, TRAITS)
#include "seec/Trace/Events.def"
#undef SEEC_PP_TRAIT
//------------------------------------------------------------------------------
// FunctionRecord
//------------------------------------------------------------------------------
///
struct FunctionRecord {
uint32_t Index;
offset_uint EventOffsetStart;
offset_uint EventOffsetEnd;
uint64_t ThreadTimeEntered;
uint64_t ThreadTimeExited;
offset_uint ChildListOffset;
offset_uint NonLocalChangeListOffset;
};
//------------------------------------------------------------------------------
// RuntimeValueRecord
//------------------------------------------------------------------------------
union RuntimeValueRecord {
uint64_t UInt64;
uintptr_t UIntPtr;
float Float;
double Double;
long double LongDouble;
/// \brief Default construct.
RuntimeValueRecord()
{}
/// \brief Copy construct.
RuntimeValueRecord(RuntimeValueRecord const &Other) = default;
/// \brief Construct a new record holding a uint32_t.
explicit RuntimeValueRecord(uint32_t Value)
: UInt64(Value)
{}
/// \brief Construct a new record holding a uint64_t.
explicit RuntimeValueRecord(uint64_t Value)
: UInt64(Value)
{}
/// \brief Create a new record holding a uintptr_t.
explicit RuntimeValueRecord(void const *Value)
: UIntPtr(reinterpret_cast<uintptr_t>(Value))
{}
/// \brief Construct a new record holding a float.
explicit RuntimeValueRecord(float Value)
: Float(Value)
{}
/// \brief Construct a new record holding a double.
explicit RuntimeValueRecord(double Value)
: Double(Value)
{}
/// \brief Construct a new record holding a long double.
explicit RuntimeValueRecord(long double Value)
: LongDouble(Value)
{}
/// \brief Copy assign.
RuntimeValueRecord &operator=(RuntimeValueRecord const &RHS) = default;
};
llvm::raw_ostream & operator<<(llvm::raw_ostream &Out,
RuntimeValueRecord const &Record);
//------------------------------------------------------------------------------
// EventRecordBase
//------------------------------------------------------------------------------
// forward-declaration
template<EventType ET>
class EventRecord;
/// \brief Base class for all event records.
class EventRecordBase {
EventType Type;
uint8_t PreviousEventSize;
public:
EventRecordBase(EventType Type, uint8_t PreviousEventSize)
: Type(Type),
PreviousEventSize(PreviousEventSize)
{}
/// \name Conversion
/// @{
template<EventType ET>
EventRecord<ET> const &as() const {
assert(Type == ET);
return *(static_cast<EventRecord<ET> const *>(this));
}
/// @}
/// \name Query event properties
/// @{
/// Get the type of this event.
EventType getType() const { return Type; }
/// Get the size of the event immediately preceding this event.
uint8_t getPreviousEventSize() const { return PreviousEventSize; }
/// Get the size of this event.
std::size_t getEventSize() const;
/// Get the value of this event's ProcessTime, if it has one.
seec::Maybe<uint64_t> getProcessTime() const;
/// Get the value of this event's ThreadTime, if it has one.
seec::Maybe<uint64_t> getThreadTime() const;
/// Get the value of this event's Index member, if it has one.
seec::Maybe<uint32_t> getIndex() const;
/// Check if this event has the is_block_start trait.
bool isBlockStart() const {
switch (Type) {
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \
case EventType::NAME: return is_block_start<EventType::NAME>::value;
#include "seec/Trace/Events.def"
default: llvm_unreachable("Reference to unknown event type!");
}
return false;
}
/// Check if this event has the is_subservient trait.
bool isSubservient() const {
switch (Type) {
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \
case EventType::NAME: return is_subservient<EventType::NAME>::value;
#include "seec/Trace/Events.def"
default: llvm_unreachable("Reference to unknown event type!");
}
return false;
}
/// Check if this event has the is_function_level trait.
bool isFunctionLevel() const {
switch (Type) {
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \
case EventType::NAME: return is_function_level<EventType::NAME>::value;
#include "seec/Trace/Events.def"
default: llvm_unreachable("Reference to unknown event type!");
}
return false;
}
/// Check if this event has the is_instruction trait.
bool isInstruction() const {
switch (Type) {
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \
case EventType::NAME: return is_instruction<EventType::NAME>::value;
#include "seec/Trace/Events.def"
default: llvm_unreachable("Reference to unknown event type!");
}
return false;
}
/// Check if this event has the modifies_shared_state trait.
bool modifiesSharedState() const {
switch (Type) {
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \
case EventType::NAME: \
return modifies_shared_state<EventType::NAME>::value;
#include "seec/Trace/Events.def"
default: llvm_unreachable("Reference to unknown event type!");
}
return false;
}
/// Check if this event has the is_memory_state trait.
bool isMemoryState() const {
switch (Type) {
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \
case EventType::NAME: \
return is_memory_state<EventType::NAME>::value;
#include "seec/Trace/Events.def"
default: llvm_unreachable("Reference to unknown event type!");
}
return false;
}
/// @} (Query event properties)
};
llvm::raw_ostream & operator<<(llvm::raw_ostream &Out,
EventRecordBase const &Event);
//------------------------------------------------------------------------------
// Event records
//------------------------------------------------------------------------------
template<EventType ET>
class EventRecord : public EventRecordBase {};
#define SEEC_PP_MEMBER(TYPE, NAME) TYPE NAME;
#define SEEC_PP_ACCESSOR(TYPE, NAME) \
TYPE const &get##NAME() const { return NAME; } \
static std::size_t sizeof##NAME() { return sizeof(NAME); } \
typedef TYPE typeof##NAME;
#define SEEC_PP_PARAMETER(TYPE, NAME) , TYPE NAME
#define SEEC_PP_INITIALIZE(TYPE, NAME) , NAME(NAME)
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \
template<> \
class EventRecord<EventType::NAME> : public EventRecordBase { \
private: \
SEEC_PP_APPLY(SEEC_PP_MEMBER, MEMBERS) \
public: \
SEEC_PP_APPLY(SEEC_PP_ACCESSOR, MEMBERS) \
\
EventRecord(uint8_t PreviousEventSize \
SEEC_PP_APPLY(SEEC_PP_PARAMETER, MEMBERS) \
) \
: EventRecordBase(EventType::NAME, PreviousEventSize) \
SEEC_PP_APPLY(SEEC_PP_INITIALIZE, MEMBERS) \
{} \
};
#include "seec/Trace/Events.def"
#undef SEEC_PP_MEMBER
#undef SEEC_PP_ACCESSOR
#undef SEEC_PP_PARAMETER
#undef SEEC_PP_INITIALIZE
// Declare raw_ostream output for all event records.
#define SEEC_TRACE_EVENT(NAME, MEMBERS, TRAITS) \
llvm::raw_ostream &operator<<(llvm::raw_ostream &Out, \
EventRecord<EventType::NAME> const &Event);
#include "seec/Trace/Events.def"
/// \brief Holds the thread and offset of an event record.
///
class EventLocation {
/// The thread that contains the event.
uint32_t ThreadID;
/// The offset of the event in the thread's event trace.
offset_uint Offset;
public:
/// Construct a new empty EventLocation.
EventLocation()
: ThreadID(0),
Offset(noOffset())
{}
/// Construct a new EventLocation.
EventLocation(uint32_t EventThreadID, offset_uint EventOffset)
: ThreadID(EventThreadID),
Offset(EventOffset)
{}
EventLocation(EventLocation const &) = default;
EventLocation &operator=(EventLocation const &) = default;
/// Get the thread ID of the thread that contains the event.
uint32_t getThreadID() const { return ThreadID; }
/// Check whether this event location has a legitimate offset.
bool hasOffset() const { return Offset != noOffset(); }
/// Get the offset of the event in the thread's event trace.
offset_uint getOffset() const { return Offset; }
/// \name Comparison
/// @{
/// \brief Check if this EventLocation is equal to another EventLocation.
bool operator==(EventLocation const &RHS) const {
return ThreadID == RHS.ThreadID && Offset == RHS.Offset;
}
/// \brief Check if this EventLocation differs from another EventLocation.
bool operator!=(EventLocation const &RHS) const {
return !operator==(RHS);
}
/// @} (Comparison)
};
} // namespace trace (in seec)
} // namespace seec
#endif // SEEC_TRACE_TRACEFORMAT_HPP
<|endoftext|>
|
<commit_before>#include "Player.h"
#include "Logger.h"
#include "Configuration.h"
Player::Player(double x_, double y_, Sprite* sprite_) :
Entity(x_, y_, sprite_),
vx(0),
vy(0),
speed(15),
maxSpeed(500),
cameraX(0),
cameraY(0),
levelW(0),
levelH(0)
{
this->state = STATE_JUMPING;
if(this->sprite != nullptr){
this->width = this->sprite->getWidth();
this->height = this->sprite->getHeight();
}
else{
Logger::warning("No sprite set for the player! Null sprite.");
}
}
Player::~Player(){
if(this->sprite != nullptr){
this->sprite->free();
delete this->sprite;
this->sprite = nullptr;
}
}
void Player::update(double dt_){
/// @todo Fix all these magic/weird numbers.
this->x += this->vx * dt_;
// Left wall.
if(this->x < 0){
this->x = 0;
this->vx = 0;
}
// Right wall.
else if(this->x + this->width > this->levelW){
this->x = this->levelW - this->width;
this->vx = 0;
}
this->y += this->vy * dt_;
// Top wall.
if(this->y < 0){
this->y = 0;
this->vy = 0;
}
// Bottom wall.
else if(this->y + this->height + 40 > this->levelH){
this->y = this->levelH - this->height - 40;
this->vy = 0;
this->state = STATE_STANDING;
}
}
void Player::render(){
const int dx = this->x - this->cameraX;
const int dy = this->y - this->cameraY;
this->sprite->render(dx, dy);
}
void Player::updateInput(array<bool, GameKeys::MAX> keyStates_){
/// @todo Fix all these magic/weird numbers.
switch(this->state){
case STATE_STANDING:
if(keyStates_[GameKeys::UP]){
this->state = STATE_JUMPING;
this->vy = -40*this->speed;
}
if(keyStates_[GameKeys::ROLL]){
this->state = STATE_ROLLING;
this->vx = 100*this->speed;
}
if(keyStates_[GameKeys::DOWN]){
this->speed = 7.5;
this->maxSpeed = 350;
this->state = STATE_CROUCHING;
}
break;
case STATE_JUMPING:
this->vy += 2*this->speed;
break;
case STATE_CROUCHING:
if(!keyStates_[GameKeys::DOWN]){
this->speed = 15;
this->maxSpeed = 500;
this->state = STATE_STANDING;
}
break;
case STATE_ROLLING:
this->vx *= 0.95;
if(this->vx < 3 && this->vx > (-3)){
this->state = STATE_STANDING;
this->vx = 0;
}
break;
default:
break;
}
// Movement.
if(keyStates_[GameKeys::LEFT]){
if(this->vx > -this->maxSpeed){
this->vx -= this->speed;
}
}
else if(keyStates_[GameKeys::RIGHT]){
if(this->vx < this->maxSpeed){
this->vx += this->speed;
}
}
else{
this->vx *= 0.95;
}
}
void Player::setCameraXY(double x_, double y_){
this->cameraX = x_;
this->cameraY = y_;
}
void Player::setLevelWH(unsigned int width_, unsigned int height_){
this->levelW = width_;
this->levelH = height_;
}
<commit_msg>improving rolling<commit_after>#include "Player.h"
#include "Logger.h"
#include "Configuration.h"
Player::Player(double x_, double y_, Sprite* sprite_) :
Entity(x_, y_, sprite_),
vx(0),
vy(0),
speed(15),
maxSpeed(500),
cameraX(0),
cameraY(0),
levelW(0),
levelH(0)
{
this->state = STATE_JUMPING;
if(this->sprite != nullptr){
this->width = this->sprite->getWidth();
this->height = this->sprite->getHeight();
}
else{
Logger::warning("No sprite set for the player! Null sprite.");
}
}
Player::~Player(){
if(this->sprite != nullptr){
this->sprite->free();
delete this->sprite;
this->sprite = nullptr;
}
}
void Player::update(double dt_){
/// @todo Fix all these magic/weird numbers.
this->x += this->vx * dt_;
// Left wall.
if(this->x < 0){
this->x = 0;
this->vx = 0;
}
// Right wall.
else if(this->x + this->width > this->levelW){
this->x = this->levelW - this->width;
this->vx = 0;
}
this->y += this->vy * dt_;
// Top wall.
if(this->y < 0){
this->y = 0;
this->vy = 0;
}
// Bottom wall.
else if(this->y + this->height + 40 > this->levelH){
this->y = this->levelH - this->height - 40;
this->vy = 0;
this->state = STATE_STANDING;
}
}
void Player::render(){
const int dx = this->x - this->cameraX;
const int dy = this->y - this->cameraY;
this->sprite->render(dx, dy);
}
void Player::updateInput(array<bool, GameKeys::MAX> keyStates_){
/// @todo Fix all these magic/weird numbers.
switch(this->state){
case STATE_STANDING:
if(keyStates_[GameKeys::UP]){
this->state = STATE_JUMPING;
this->vy = -40*this->speed;
}
if(keyStates_[GameKeys::ROLL]){
this->state = STATE_ROLLING;
}
if(keyStates_[GameKeys::DOWN]){
this->speed = 7.5;
this->maxSpeed = 350;
this->state = STATE_CROUCHING;
}
break;
case STATE_JUMPING:
this->vy += 2*this->speed;
break;
case STATE_CROUCHING:
if(!keyStates_[GameKeys::DOWN]){
this->speed = 15;
this->maxSpeed = 500;
this->state = STATE_STANDING;
}
break;
case STATE_ROLLING:
this->vx = 70*this->speed;
this->state = STATE_STANDING;
break;
default:
break;
}
// X movement.
if(keyStates_[GameKeys::LEFT]){
if(this->vx > -this->maxSpeed){
this->vx -= this->speed;
}
}
else if(keyStates_[GameKeys::RIGHT]){
if(this->vx < this->maxSpeed){
this->vx += this->speed;
}
}
else{
this->vx *= 0.95;
}
}
void Player::setCameraXY(double x_, double y_){
this->cameraX = x_;
this->cameraY = y_;
}
void Player::setLevelWH(unsigned int width_, unsigned int height_){
this->levelW = width_;
this->levelH = height_;
}
<|endoftext|>
|
<commit_before>/// @file
/// @author Boris Mikic
/// @version 2.5
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php
#include <hltypes/hltypesUtil.h>
#include "Buffer.h"
#include "Category.h"
#include "Player.h"
#include "Sound.h"
namespace xal
{
Player::Player(Sound* sound, Buffer* buffer) : gain(1.0f), pitch(1.0f), paused(false),
looping(false), fadeSpeed(0.0f), fadeTime(0.0f), offset(0.0f), bufferIndex(0),
processedByteCount(0)
{
this->sound = sound;
this->buffer = buffer;
}
Player::~Player()
{
}
float Player::getGain()
{
xal::mgr->_lock();
float gain = this->_getGain();
xal::mgr->_unlock();
return gain;
}
float Player::_getGain()
{
return this->gain;
}
void Player::setGain(float value)
{
xal::mgr->_lock();
this->_setGain(value);
xal::mgr->_unlock();
}
void Player::_setGain(float value)
{
this->gain = hclamp(value, 0.0f, 1.0f);
this->_systemUpdateGain(this->gain);
}
float Player::getPitch()
{
xal::mgr->_lock();
float pitch = this->_getPitch();
xal::mgr->_unlock();
return pitch;
}
float Player::_getPitch()
{
return this->pitch;
}
void Player::setPitch(float value)
{
xal::mgr->_lock();
this->_setPitch(value);
xal::mgr->_unlock();
}
void Player::_setPitch(float value)
{
this->pitch = hclamp(value, 0.01f, 100.0f);
this->_systemUpdatePitch();
}
float Player::getTimePosition()
{
return ((float)this->getSamplePosition() / this->buffer->getSamplingRate());
}
unsigned int Player::getSamplePosition()
{
xal::mgr->_lock();
unsigned int position = this->_systemGetBufferPosition();
if (this->sound->isStreamed())
{
// corrects position by using number of processed bytes (circular)
position = (position + (STREAM_BUFFER_COUNT - this->bufferIndex) * STREAM_BUFFER_SIZE) % STREAM_BUFFER;
// adds streamed processed byte count
position += this->processedByteCount;
}
position = hmin(position, (unsigned int)this->sound->getSize());
unsigned int samplePosition = (unsigned int)(position /
(this->buffer->getChannels() * this->buffer->getBitsPerSample() * 0.125f));
xal::mgr->_unlock();
return samplePosition;
}
hstr Player::getName()
{
return this->sound->getName();
}
hstr Player::getFilename()
{
return this->sound->getFilename();
}
hstr Player::getRealFilename()
{
return this->sound->getRealFilename();
}
float Player::getDuration()
{
return this->buffer->getDuration();
}
int Player::getSize()
{
return this->buffer->getSize();
}
bool Player::isPlaying()
{
return (!this->isFadingOut() && this->_systemIsPlaying());
}
bool Player::isPaused()
{
return (this->paused && !this->isFading());
}
bool Player::isFading()
{
return (this->fadeSpeed != 0.0f);
}
bool Player::isFadingIn()
{
return (this->fadeSpeed > 0.0f);
}
bool Player::isFadingOut()
{
return (this->fadeSpeed < 0.0f);
}
Category* Player::getCategory()
{
return this->sound->getCategory();
}
void Player::_update(float k)
{
if (this->sound->isStreamed() && this->_systemIsPlaying())
{
this->processedByteCount += this->_systemUpdateStream();
}
if (this->isFading())
{
this->fadeTime += this->fadeSpeed * k;
if (this->fadeTime >= 1.0f && this->fadeSpeed > 0.0f)
{
this->_setGain(this->gain);
this->fadeTime = 1.0f;
this->fadeSpeed = 0.0f;
}
else if (this->fadeTime <= 0.0f && this->fadeSpeed < 0.0f)
{
this->fadeTime = 0.0f;
this->fadeSpeed = 0.0f;
if (!this->paused)
{
this->_stop();
return;
}
this->_pause();
}
else
{
this->_systemUpdateGain(this->_calcFadeGain());
}
}
}
void Player::play(float fadeTime, bool looping)
{
xal::mgr->_lock();
this->_play(fadeTime, looping);
xal::mgr->_unlock();
}
void Player::stop(float fadeTime)
{
xal::mgr->_lock();
this->_stop(fadeTime);
xal::mgr->_unlock();
}
void Player::pause(float fadeTime)
{
xal::mgr->_lock();
this->_pause(fadeTime);
xal::mgr->_unlock();
}
void Player::_play(float fadeTime, bool looping)
{
if (!xal::mgr->isEnabled())
{
return;
}
if (xal::mgr->isSuspended())
{
if (!xal::mgr->suspendedPlayers.contains(this))
{
xal::mgr->suspendedPlayers += this;
if (!this->paused)
{
this->looping = looping;
this->paused = true;
}
}
return;
}
if (!this->_systemPreparePlay())
{
return;
}
if (!this->paused)
{
this->looping = looping;
}
bool alreadyFading = this->isFading();
if (!alreadyFading && !this->_systemIsPlaying())
{
this->buffer->prepare();
this->_systemPrepareBuffer();
if (this->paused)
{
this->_systemSetOffset(this->offset);
}
}
if (fadeTime > 0.0f)
{
this->fadeSpeed = 1.0f / fadeTime;
}
else
{
this->fadeTime = 1.0f;
this->fadeSpeed = 0.0f;
}
this->_systemUpdateGain(this->_calcFadeGain());
if (!alreadyFading)
{
this->_systemPlay();
}
this->paused = false;
}
void Player::_stop(float fadeTime)
{
if (xal::mgr->isSuspended() && xal::mgr->suspendedPlayers.contains(this))
{
xal::mgr->suspendedPlayers -= this;
}
this->paused = false;
this->_stopSound(fadeTime);
this->offset = 0.0f;
this->processedByteCount = 0;
}
void Player::_pause(float fadeTime)
{
this->paused = true;
this->_stopSound(fadeTime);
}
float Player::_calcGain()
{
return (this->gain * this->sound->getCategory()->getGain() * xal::mgr->getGlobalGain());
}
float Player::_calcFadeGain()
{
return (this->gain * this->sound->getCategory()->getGain() * xal::mgr->getGlobalGain() * this->fadeTime);
}
void Player::_stopSound(float fadeTime)
{
if (fadeTime > 0.0f)
{
this->fadeSpeed = -1.0f / fadeTime;
return;
}
this->offset = this->_systemGetOffset();
this->processedByteCount += this->_systemStop();
this->buffer->release();
this->fadeTime = 0.0f;
this->fadeSpeed = 0.0f;
}
}
<commit_msg>fixed gain calculation bug<commit_after>/// @file
/// @author Boris Mikic
/// @version 2.5
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php
#include <hltypes/hltypesUtil.h>
#include "Buffer.h"
#include "Category.h"
#include "Player.h"
#include "Sound.h"
namespace xal
{
Player::Player(Sound* sound, Buffer* buffer) : gain(1.0f), pitch(1.0f), paused(false),
looping(false), fadeSpeed(0.0f), fadeTime(0.0f), offset(0.0f), bufferIndex(0),
processedByteCount(0)
{
this->sound = sound;
this->buffer = buffer;
}
Player::~Player()
{
}
float Player::getGain()
{
xal::mgr->_lock();
float gain = this->_getGain();
xal::mgr->_unlock();
return gain;
}
float Player::_getGain()
{
return this->gain;
}
void Player::setGain(float value)
{
xal::mgr->_lock();
this->_setGain(value);
xal::mgr->_unlock();
}
void Player::_setGain(float value)
{
this->gain = hclamp(value, 0.0f, 1.0f);
this->_systemUpdateGain(this->_calcGain());
}
float Player::getPitch()
{
xal::mgr->_lock();
float pitch = this->_getPitch();
xal::mgr->_unlock();
return pitch;
}
float Player::_getPitch()
{
return this->pitch;
}
void Player::setPitch(float value)
{
xal::mgr->_lock();
this->_setPitch(value);
xal::mgr->_unlock();
}
void Player::_setPitch(float value)
{
this->pitch = hclamp(value, 0.01f, 100.0f);
this->_systemUpdatePitch();
}
float Player::getTimePosition()
{
return ((float)this->getSamplePosition() / this->buffer->getSamplingRate());
}
unsigned int Player::getSamplePosition()
{
xal::mgr->_lock();
unsigned int position = this->_systemGetBufferPosition();
if (this->sound->isStreamed())
{
// corrects position by using number of processed bytes (circular)
position = (position + (STREAM_BUFFER_COUNT - this->bufferIndex) * STREAM_BUFFER_SIZE) % STREAM_BUFFER;
// adds streamed processed byte count
position += this->processedByteCount;
}
position = hmin(position, (unsigned int)this->sound->getSize());
unsigned int samplePosition = (unsigned int)(position /
(this->buffer->getChannels() * this->buffer->getBitsPerSample() * 0.125f));
xal::mgr->_unlock();
return samplePosition;
}
hstr Player::getName()
{
return this->sound->getName();
}
hstr Player::getFilename()
{
return this->sound->getFilename();
}
hstr Player::getRealFilename()
{
return this->sound->getRealFilename();
}
float Player::getDuration()
{
return this->buffer->getDuration();
}
int Player::getSize()
{
return this->buffer->getSize();
}
bool Player::isPlaying()
{
return (!this->isFadingOut() && this->_systemIsPlaying());
}
bool Player::isPaused()
{
return (this->paused && !this->isFading());
}
bool Player::isFading()
{
return (this->fadeSpeed != 0.0f);
}
bool Player::isFadingIn()
{
return (this->fadeSpeed > 0.0f);
}
bool Player::isFadingOut()
{
return (this->fadeSpeed < 0.0f);
}
Category* Player::getCategory()
{
return this->sound->getCategory();
}
void Player::_update(float k)
{
if (this->sound->isStreamed() && this->_systemIsPlaying())
{
this->processedByteCount += this->_systemUpdateStream();
}
if (this->isFading())
{
this->fadeTime += this->fadeSpeed * k;
if (this->fadeTime >= 1.0f && this->fadeSpeed > 0.0f)
{
this->_setGain(this->gain);
this->fadeTime = 1.0f;
this->fadeSpeed = 0.0f;
}
else if (this->fadeTime <= 0.0f && this->fadeSpeed < 0.0f)
{
this->fadeTime = 0.0f;
this->fadeSpeed = 0.0f;
if (!this->paused)
{
this->_stop();
return;
}
this->_pause();
}
else
{
this->_systemUpdateGain(this->_calcFadeGain());
}
}
}
void Player::play(float fadeTime, bool looping)
{
xal::mgr->_lock();
this->_play(fadeTime, looping);
xal::mgr->_unlock();
}
void Player::stop(float fadeTime)
{
xal::mgr->_lock();
this->_stop(fadeTime);
xal::mgr->_unlock();
}
void Player::pause(float fadeTime)
{
xal::mgr->_lock();
this->_pause(fadeTime);
xal::mgr->_unlock();
}
void Player::_play(float fadeTime, bool looping)
{
if (!xal::mgr->isEnabled())
{
return;
}
if (xal::mgr->isSuspended())
{
if (!xal::mgr->suspendedPlayers.contains(this))
{
xal::mgr->suspendedPlayers += this;
if (!this->paused)
{
this->looping = looping;
this->paused = true;
}
}
return;
}
if (!this->_systemPreparePlay())
{
return;
}
if (!this->paused)
{
this->looping = looping;
}
bool alreadyFading = this->isFading();
if (!alreadyFading && !this->_systemIsPlaying())
{
this->buffer->prepare();
this->_systemPrepareBuffer();
if (this->paused)
{
this->_systemSetOffset(this->offset);
}
}
if (fadeTime > 0.0f)
{
this->fadeSpeed = 1.0f / fadeTime;
}
else
{
this->fadeTime = 1.0f;
this->fadeSpeed = 0.0f;
}
this->_systemUpdateGain(this->_calcFadeGain());
if (!alreadyFading)
{
this->_systemPlay();
}
this->paused = false;
}
void Player::_stop(float fadeTime)
{
if (xal::mgr->isSuspended() && xal::mgr->suspendedPlayers.contains(this))
{
xal::mgr->suspendedPlayers -= this;
}
this->paused = false;
this->_stopSound(fadeTime);
this->offset = 0.0f;
this->processedByteCount = 0;
}
void Player::_pause(float fadeTime)
{
this->paused = true;
this->_stopSound(fadeTime);
}
float Player::_calcGain()
{
return (this->gain * this->sound->getCategory()->getGain() * xal::mgr->getGlobalGain());
}
float Player::_calcFadeGain()
{
return (this->gain * this->sound->getCategory()->getGain() * xal::mgr->getGlobalGain() * this->fadeTime);
}
void Player::_stopSound(float fadeTime)
{
if (fadeTime > 0.0f)
{
this->fadeSpeed = -1.0f / fadeTime;
return;
}
this->offset = this->_systemGetOffset();
this->processedByteCount += this->_systemStop();
this->buffer->release();
this->fadeTime = 0.0f;
this->fadeSpeed = 0.0f;
}
}
<|endoftext|>
|
<commit_before>// cpsm - fuzzy path matcher
// Copyright (C) 2015 Jamie Liu
//
// 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 "matcher.h"
#include <algorithm>
#include <cstdint>
#include <limits>
#include <utility>
#include <boost/range/adaptor/reversed.hpp>
#include "path_util.h"
#include "str_util.h"
namespace cpsm {
Matcher::Matcher(boost::string_ref const query, MatcherOpts opts,
StringHandler strings)
: opts_(std::move(opts)), strings_(std::move(strings)) {
strings_.decode(query, query_);
if (opts_.is_path) {
// Store the index of the first character after the rightmost path
// separator in the query. (Store an index rather than an iterator to keep
// Matcher copyable/moveable.)
query_key_begin_index_ =
std::find(query_.crbegin(), query_.crend(), path_separator()).base() -
query_.cbegin();
switch (opts_.query_path_mode) {
case MatcherOpts::QueryPathMode::NORMAL:
require_full_part_ = false;
break;
case MatcherOpts::QueryPathMode::STRICT:
require_full_part_ = true;
break;
case MatcherOpts::QueryPathMode::AUTO:
require_full_part_ =
(query.find_first_of(path_separator()) != std::string::npos);
break;
}
} else {
query_key_begin_index_ = 0;
require_full_part_ = false;
}
// Queries are smartcased (case-sensitive only if any uppercase appears in the
// query).
is_case_sensitive_ =
std::any_of(query_.begin(), query_.end(),
[&](char32_t const c) { return strings_.is_uppercase(c); });
cur_file_parts_ = path_components_of(opts_.cur_file);
if (!cur_file_parts_.empty()) {
cur_file_key_ = cur_file_parts_.back();
// Strip the extension from cur_file_key_, if any (but not the trailing .)
auto const ext_sep_pos = cur_file_key_.find_last_of('.');
if (ext_sep_pos != boost::string_ref::npos) {
cur_file_key_ = cur_file_key_.substr(0, ext_sep_pos + 1);
}
}
}
bool Matcher::match_base(boost::string_ref const item, MatchBase& m,
std::set<CharCount>* match_positions,
std::vector<char32_t>* const buf,
std::vector<char32_t>* const buf2) const {
m = MatchBase();
std::vector<char32_t> key_chars_local;
std::vector<char32_t>& key_chars = buf ? *buf : key_chars_local;
std::vector<char32_t> temp_chars_local;
std::vector<char32_t>& temp_chars = buf2 ? *buf2 : temp_chars_local;
std::vector<CharCount> key_char_positions;
std::vector<CharCount> temp_char_positions;
std::vector<boost::string_ref> item_parts;
if (opts_.is_path) {
item_parts = path_components_of(item);
} else {
item_parts.push_back(item);
}
if (!item_parts.empty()) {
m.unmatched_len = item_parts.back().size();
}
if (query_.empty()) {
match_path(item_parts, m);
return true;
}
// Since for paths (the common case) we prefer rightmost path components, we
// scan path components right-to-left.
auto query_it = query_.crbegin();
auto const query_end = query_.crend();
auto query_key_begin = query_.cend();
// Index into item_parts, counting from the right.
CharCount item_part_index = 0;
// Offset of the beginning of the current item part from the beginning of the
// item, in bytes.
CharCount item_part_first_byte = item.size();
std::set<CharCount> match_part_positions;
for (boost::string_ref const item_part :
boost::adaptors::reverse(item_parts)) {
if (query_it == query_end) {
break;
}
std::vector<char32_t>& item_part_chars =
(item_part_index == 0) ? key_chars : temp_chars;
item_part_chars.clear();
std::vector<CharCount>* item_part_char_positions = nullptr;
if (match_positions) {
item_part_first_byte -= item_part.size();
match_part_positions.clear();
item_part_char_positions =
(item_part_index == 0) ? &key_char_positions : &temp_char_positions;
item_part_char_positions->clear();
}
strings_.decode(item_part, item_part_chars, item_part_char_positions);
// Since path components are matched right-to-left, query characters must be
// consumed greedily right-to-left.
auto query_prev = query_it;
for (auto it = item_part_chars.crbegin(), end = item_part_chars.crend();
it != end; ++it) {
if (match_char(*it, *query_it)) {
// Don't store match positions for the key yet, since match_key will
// refine them.
if (match_positions && item_part_index != 0) {
std::size_t const i =
item_part_chars.size() - (it - item_part_chars.crbegin());
CharCount begin = (*item_part_char_positions)[i - 1];
CharCount end;
if (i == item_part_chars.size()) {
end = item_part.size();
} else {
end = (*item_part_char_positions)[i];
}
for (; begin < end; begin++) {
match_part_positions.insert(item_part_first_byte + begin);
}
}
++query_it;
if (query_it == query_end) {
break;
}
}
}
// If strict query path mode is on, the match must have run to a path
// separator. If not, discard the match.
if (require_full_part_ &&
!((query_it == query_end) || (*query_it == path_separator()))) {
query_it = query_prev;
}
// Ok, done matching this part.
if (query_it != query_prev) {
m.parts++;
}
if (item_part_index == 0) {
query_key_begin = query_it.base();
}
item_part_index++;
if (match_positions) {
for (auto const pos : match_part_positions) {
match_positions->insert(pos);
}
}
}
// Did all characters match?
if (query_it != query_end) {
return false;
}
// Fill path match data.
match_path(item_parts, m);
// Now do more refined matching on the key (the rightmost path component of
// the item for a path match, and just the full item otherwise).
if (match_positions) {
// Adjust key_char_positions to be relative to the beginning of the string
// rather than the beginning of the key. item_parts can't be empty because
// query is non-empty and matching was successful.
CharCount const item_key_first_byte =
item.size() - item_parts.back().size();
for (auto& pos : key_char_positions) {
pos += item_key_first_byte;
}
// Push item.size() to simplify key_char_positions indexing in match_key
// and save an extra parameter.
key_char_positions.push_back(item.size());
}
match_key(key_chars, query_key_begin, m, match_positions, key_char_positions);
return true;
}
void Matcher::match_path(std::vector<boost::string_ref> const& item_parts,
MatchBase& m) const {
if (!opts_.is_path) {
return;
}
m.path_distance = path_distance_between(cur_file_parts_, item_parts);
// We don't want to exclude cur_file as a match, but we also don't want it
// to be the top match, so force cur_file_prefix_len to 0 for cur_file (i.e.
// if path_distance is 0).
if (m.path_distance != 0 && !item_parts.empty()) {
m.cur_file_prefix_len = common_prefix(cur_file_key_, item_parts.back());
}
}
void Matcher::match_key(
std::vector<char32_t> const& key,
std::vector<char32_t>::const_iterator const query_key, MatchBase& m,
std::set<CharCount>* const match_positions,
std::vector<CharCount> const& key_char_positions) const {
auto const query_key_end = query_.cend();
if (query_key == query_key_end) {
return;
}
// key can't be empty since [query_key, query_.end()) is non-empty.
const auto is_word_prefix = [&](std::size_t const i) -> bool {
if (i == 0) {
return true;
}
if (strings_.is_alphanumeric(key[i]) &&
!strings_.is_alphanumeric(key[i - 1])) {
return true;
}
if (strings_.is_uppercase(key[i]) && !strings_.is_uppercase(key[i - 1])) {
return true;
}
return false;
};
// Attempt two matches. In the first pass, only match word prefixes and
// non-alphanumeric characters to try and get a word prefix-only match. In
// the second pass, match greedily.
for (int pass = 0; pass < 2; pass++) {
auto query_it = query_key;
CharCount word_index = 0;
CharCount2 word_index_sum = 0;
CharCount word_prefix_len = 0;
bool start_matched = false;
bool at_word_start = true;
bool word_matched = false;
std::set<CharCount> match_positions_pass;
for (std::size_t i = 0; i < key.size(); i++) {
if (is_word_prefix(i)) {
word_index++;
at_word_start = true;
word_matched = false;
}
if (pass == 0 && strings_.is_alphanumeric(*query_it) && !at_word_start) {
continue;
}
if (match_char(key[i], *query_it)) {
if (at_word_start) {
word_prefix_len++;
}
if (!word_matched) {
word_index_sum += word_index;
word_matched = true;
}
if (i == 0) {
start_matched = true;
}
if (match_positions) {
CharCount begin = key_char_positions[i];
CharCount const end = key_char_positions[i+1];
for (; begin < end; begin++) {
match_positions_pass.insert(begin);
}
}
++query_it;
if (query_it == query_key_end) {
auto const query_key_begin = query_.cbegin() + query_key_begin_index_;
if (query_key != query_key_begin) {
m.prefix_score = std::numeric_limits<CharCount2>::max();
if (start_matched) {
m.prefix_score = std::numeric_limits<CharCount2>::max() - 1;
}
} else if ((i + 1) == std::size_t(query_key_end - query_key_begin)) {
m.prefix_score = 0;
} else if (pass == 0) {
m.prefix_score = word_index_sum;
} else if (start_matched) {
m.prefix_score = std::numeric_limits<CharCount2>::max() - 3;
} else {
m.prefix_score = std::numeric_limits<CharCount2>::max() - 2;
}
m.word_prefix_len = word_prefix_len;
m.unmatched_len = key.size() - (i + 1);
if (match_positions) {
for (auto const pos : match_positions_pass) {
match_positions->insert(pos);
}
}
return;
}
} else {
at_word_start = false;
}
}
}
}
bool Matcher::match_char(char32_t item, char32_t const query) const {
if (!is_case_sensitive_) {
// The query must not contain any uppercase letters since otherwise the
// query would be case-sensitive, so just force all uppercase characters to
// lowercase.
if (strings_.is_uppercase(item)) {
item = strings_.to_lowercase(item);
}
}
return item == query;
}
} // namespace cpsm
<commit_msg>Fix repeated highlighting of path separators<commit_after>// cpsm - fuzzy path matcher
// Copyright (C) 2015 Jamie Liu
//
// 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 "matcher.h"
#include <algorithm>
#include <cstdint>
#include <limits>
#include <utility>
#include <boost/range/adaptor/reversed.hpp>
#include "path_util.h"
#include "str_util.h"
namespace cpsm {
Matcher::Matcher(boost::string_ref const query, MatcherOpts opts,
StringHandler strings)
: opts_(std::move(opts)), strings_(std::move(strings)) {
strings_.decode(query, query_);
if (opts_.is_path) {
// Store the index of the first character after the rightmost path
// separator in the query. (Store an index rather than an iterator to keep
// Matcher copyable/moveable.)
query_key_begin_index_ =
std::find(query_.crbegin(), query_.crend(), path_separator()).base() -
query_.cbegin();
switch (opts_.query_path_mode) {
case MatcherOpts::QueryPathMode::NORMAL:
require_full_part_ = false;
break;
case MatcherOpts::QueryPathMode::STRICT:
require_full_part_ = true;
break;
case MatcherOpts::QueryPathMode::AUTO:
require_full_part_ =
(query.find_first_of(path_separator()) != std::string::npos);
break;
}
} else {
query_key_begin_index_ = 0;
require_full_part_ = false;
}
// Queries are smartcased (case-sensitive only if any uppercase appears in the
// query).
is_case_sensitive_ =
std::any_of(query_.begin(), query_.end(),
[&](char32_t const c) { return strings_.is_uppercase(c); });
cur_file_parts_ = path_components_of(opts_.cur_file);
if (!cur_file_parts_.empty()) {
cur_file_key_ = cur_file_parts_.back();
// Strip the extension from cur_file_key_, if any (but not the trailing .)
auto const ext_sep_pos = cur_file_key_.find_last_of('.');
if (ext_sep_pos != boost::string_ref::npos) {
cur_file_key_ = cur_file_key_.substr(0, ext_sep_pos + 1);
}
}
}
bool Matcher::match_base(boost::string_ref const item, MatchBase& m,
std::set<CharCount>* match_positions,
std::vector<char32_t>* const buf,
std::vector<char32_t>* const buf2) const {
m = MatchBase();
std::vector<char32_t> key_chars_local;
std::vector<char32_t>& key_chars = buf ? *buf : key_chars_local;
std::vector<char32_t> temp_chars_local;
std::vector<char32_t>& temp_chars = buf2 ? *buf2 : temp_chars_local;
std::vector<CharCount> key_char_positions;
std::vector<CharCount> temp_char_positions;
std::vector<boost::string_ref> item_parts;
if (opts_.is_path) {
item_parts = path_components_of(item);
} else {
item_parts.push_back(item);
}
if (!item_parts.empty()) {
m.unmatched_len = item_parts.back().size();
}
if (query_.empty()) {
match_path(item_parts, m);
return true;
}
// Since for paths (the common case) we prefer rightmost path components, we
// scan path components right-to-left.
auto query_it = query_.crbegin();
auto const query_end = query_.crend();
auto query_key_begin = query_.cend();
// Index into item_parts, counting from the right.
CharCount item_part_index = 0;
// Offset of the beginning of the current item part from the beginning of the
// item, in bytes.
CharCount item_part_first_byte = item.size();
std::set<CharCount> match_part_positions;
for (boost::string_ref const item_part :
boost::adaptors::reverse(item_parts)) {
if (query_it == query_end) {
break;
}
std::vector<char32_t>& item_part_chars =
(item_part_index == 0) ? key_chars : temp_chars;
item_part_chars.clear();
std::vector<CharCount>* item_part_char_positions = nullptr;
if (match_positions) {
item_part_first_byte -= item_part.size();
match_part_positions.clear();
item_part_char_positions =
(item_part_index == 0) ? &key_char_positions : &temp_char_positions;
item_part_char_positions->clear();
}
strings_.decode(item_part, item_part_chars, item_part_char_positions);
// Since path components are matched right-to-left, query characters must be
// consumed greedily right-to-left.
auto query_prev = query_it;
for (auto it = item_part_chars.crbegin(), end = item_part_chars.crend();
it != end; ++it) {
if (match_char(*it, *query_it)) {
// Don't store match positions for the key yet, since match_key will
// refine them.
if (match_positions && item_part_index != 0) {
std::size_t const i =
item_part_chars.size() - (it - item_part_chars.crbegin());
CharCount begin = (*item_part_char_positions)[i - 1];
CharCount end;
if (i == item_part_chars.size()) {
end = item_part.size();
} else {
end = (*item_part_char_positions)[i];
}
for (; begin < end; begin++) {
match_part_positions.insert(item_part_first_byte + begin);
}
}
++query_it;
if (query_it == query_end) {
break;
}
}
}
// If strict query path mode is on, the match must have run to a path
// separator. If not, discard the match.
if (require_full_part_ &&
!((query_it == query_end) || (*query_it == path_separator()))) {
query_it = query_prev;
if (match_positions) {
match_part_positions.clear();
}
}
// Ok, done matching this part.
if (query_it != query_prev) {
m.parts++;
}
if (item_part_index == 0) {
query_key_begin = query_it.base();
}
item_part_index++;
if (match_positions) {
for (auto const pos : match_part_positions) {
match_positions->insert(pos);
}
}
}
// Did all characters match?
if (query_it != query_end) {
return false;
}
// Fill path match data.
match_path(item_parts, m);
// Now do more refined matching on the key (the rightmost path component of
// the item for a path match, and just the full item otherwise).
if (match_positions) {
// Adjust key_char_positions to be relative to the beginning of the string
// rather than the beginning of the key. item_parts can't be empty because
// query is non-empty and matching was successful.
CharCount const item_key_first_byte =
item.size() - item_parts.back().size();
for (auto& pos : key_char_positions) {
pos += item_key_first_byte;
}
// Push item.size() to simplify key_char_positions indexing in match_key
// and save an extra parameter.
key_char_positions.push_back(item.size());
}
match_key(key_chars, query_key_begin, m, match_positions, key_char_positions);
return true;
}
void Matcher::match_path(std::vector<boost::string_ref> const& item_parts,
MatchBase& m) const {
if (!opts_.is_path) {
return;
}
m.path_distance = path_distance_between(cur_file_parts_, item_parts);
// We don't want to exclude cur_file as a match, but we also don't want it
// to be the top match, so force cur_file_prefix_len to 0 for cur_file (i.e.
// if path_distance is 0).
if (m.path_distance != 0 && !item_parts.empty()) {
m.cur_file_prefix_len = common_prefix(cur_file_key_, item_parts.back());
}
}
void Matcher::match_key(
std::vector<char32_t> const& key,
std::vector<char32_t>::const_iterator const query_key, MatchBase& m,
std::set<CharCount>* const match_positions,
std::vector<CharCount> const& key_char_positions) const {
auto const query_key_end = query_.cend();
if (query_key == query_key_end) {
return;
}
// key can't be empty since [query_key, query_.end()) is non-empty.
const auto is_word_prefix = [&](std::size_t const i) -> bool {
if (i == 0) {
return true;
}
if (strings_.is_alphanumeric(key[i]) &&
!strings_.is_alphanumeric(key[i - 1])) {
return true;
}
if (strings_.is_uppercase(key[i]) && !strings_.is_uppercase(key[i - 1])) {
return true;
}
return false;
};
// Attempt two matches. In the first pass, only match word prefixes and
// non-alphanumeric characters to try and get a word prefix-only match. In
// the second pass, match greedily.
for (int pass = 0; pass < 2; pass++) {
auto query_it = query_key;
CharCount word_index = 0;
CharCount2 word_index_sum = 0;
CharCount word_prefix_len = 0;
bool start_matched = false;
bool at_word_start = true;
bool word_matched = false;
std::set<CharCount> match_positions_pass;
for (std::size_t i = 0; i < key.size(); i++) {
if (is_word_prefix(i)) {
word_index++;
at_word_start = true;
word_matched = false;
}
if (pass == 0 && strings_.is_alphanumeric(*query_it) && !at_word_start) {
continue;
}
if (match_char(key[i], *query_it)) {
if (at_word_start) {
word_prefix_len++;
}
if (!word_matched) {
word_index_sum += word_index;
word_matched = true;
}
if (i == 0) {
start_matched = true;
}
if (match_positions) {
CharCount begin = key_char_positions[i];
CharCount const end = key_char_positions[i+1];
for (; begin < end; begin++) {
match_positions_pass.insert(begin);
}
}
++query_it;
if (query_it == query_key_end) {
auto const query_key_begin = query_.cbegin() + query_key_begin_index_;
if (query_key != query_key_begin) {
m.prefix_score = std::numeric_limits<CharCount2>::max();
if (start_matched) {
m.prefix_score = std::numeric_limits<CharCount2>::max() - 1;
}
} else if ((i + 1) == std::size_t(query_key_end - query_key_begin)) {
m.prefix_score = 0;
} else if (pass == 0) {
m.prefix_score = word_index_sum;
} else if (start_matched) {
m.prefix_score = std::numeric_limits<CharCount2>::max() - 3;
} else {
m.prefix_score = std::numeric_limits<CharCount2>::max() - 2;
}
m.word_prefix_len = word_prefix_len;
m.unmatched_len = key.size() - (i + 1);
if (match_positions) {
for (auto const pos : match_positions_pass) {
match_positions->insert(pos);
}
}
return;
}
} else {
at_word_start = false;
}
}
}
}
bool Matcher::match_char(char32_t item, char32_t const query) const {
if (!is_case_sensitive_) {
// The query must not contain any uppercase letters since otherwise the
// query would be case-sensitive, so just force all uppercase characters to
// lowercase.
if (strings_.is_uppercase(item)) {
item = strings_.to_lowercase(item);
}
}
return item == query;
}
} // namespace cpsm
<|endoftext|>
|
<commit_before>// Copyright (c) 2016 ZZBGames
//
// 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 ZZB_CORE_TILESET_HPP
#define ZZB_CORE_TILESET_HPP
#include <string>
#include <SFML/Graphics/Image.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <zzbgames/util/Dimension.hpp>
#include <zzbgames/util/Insets.hpp>
namespace zzbgames {
namespace tiles {
/**
* @brief The Tileset class represents an image split in a tile grid.
*/
class Tileset {
public:
/**
* @brief Creates a new Tileset object from a file.
*
* @param filename The name of the tileset image file.
* @param tileSize The size of each tile in pixels.
* @param margin The inner margin of this tileset.
* @param spacing The spacing between each tile in pixels.
*
* @throw std::ios_base::failure if the loading of the image fails.
*/
Tileset(const std::string &filename, const util::Dimension &tileSize, const util::Insets &margin,
const util::Insets &spacing);
~Tileset();
/**
* ]brief Returns the number of tiles of this tileset.
*
* @return The number of tiles of this tileset.
*/
unsigned long tileCount() const;
private:
/**
* @brief Computes and initializes the grid size.
*/
void computeGridSize();
private:
/// \brief The size of this tileset in squares.
util::Dimension m_gridSize;
/// @brief The image used by this tileset.
sf::Image m_image;
/// @brief The inner margin of this tileset.
util::Insets m_margin;
/// @brief The spacing between each tile in pixels.
util::Insets m_spacing;
/// @brief The texture used by this tileset.
sf::Texture m_texture;
/// @brief The size of each tile in pixels.
util::Dimension m_tileSize;
};
}
}
#endif //ZZB_CORE_TILESET_HPP
<commit_msg>Fix docs<commit_after>// Copyright (c) 2016 ZZBGames
//
// 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 ZZB_CORE_TILESET_HPP
#define ZZB_CORE_TILESET_HPP
#include <string>
#include <SFML/Graphics/Image.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <zzbgames/util/Dimension.hpp>
#include <zzbgames/util/Insets.hpp>
namespace zzbgames {
namespace tiles {
/**
* @brief The Tileset class represents an image split in a tile grid.
*/
class Tileset {
public:
/**
* @brief Creates a new Tileset object from a file.
*
* @param filename The name of the tileset image file.
* @param tileSize The size of each tile in pixels.
* @param margin The inner margin of this tileset.
* @param spacing The spacing between each tile in pixels.
*
* @throw std::ios_base::failure if the loading of the image fails.
*/
Tileset(const std::string &filename, const util::Dimension &tileSize, const util::Insets &margin,
const util::Insets &spacing);
~Tileset();
/**
* @brief Returns the number of tiles of this tileset.
*
* @return The number of tiles of this tileset.
*/
unsigned long tileCount() const;
private:
/**
* @brief Computes and initializes the grid size.
*/
void computeGridSize();
private:
/// @brief The size of this tileset in squares.
util::Dimension m_gridSize;
/// @brief The image used by this tileset.
sf::Image m_image;
/// @brief The inner margin of this tileset.
util::Insets m_margin;
/// @brief The spacing between each tile in pixels.
util::Insets m_spacing;
/// @brief The texture used by this tileset.
sf::Texture m_texture;
/// @brief The size of each tile in pixels.
util::Dimension m_tileSize;
};
}
}
#endif //ZZB_CORE_TILESET_HPP
<|endoftext|>
|
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/Source.hpp>
#include <queue>
#include <nix/File.hpp>
#include <nix/util/util.hpp>
using namespace nix;
Source::Source()
: EntityWithMetadata()
{
}
Source::Source(const Source &other)
: EntityWithMetadata(other.impl())
{
}
Source::Source(const std::shared_ptr<base::ISource> &p_impl)
: EntityWithMetadata(p_impl)
{
}
Source::Source(std::shared_ptr<base::ISource> &&ptr)
: EntityWithMetadata(std::move(ptr))
{
}
//--------------------------------------------------
// Methods concerning child sources
//--------------------------------------------------
Source Source::createSource(const std::string &name, const std::string &type) {
util::checkEntityNameAndType(name, type);
if(backend()->hasSource(name)) {
throw DuplicateName("Source with the given name already exists!");
}
return backend()->createSource(name, type);
}
bool Source::hasSource(const Source &source) const {
if (!util::checkEntityInput(source, false)) {
return false;
}
return backend()->hasSource(source.id());
}
std::vector<Source> Source::sources(const util::Filter<Source>::type &filter) const {
auto f = [this] (ndsize_t i) { return getSource(i); };
return getEntities<Source>(f, sourceCount(), filter);
}
bool Source::deleteSource(const Source &source) {
if (!util::checkEntityInput(source, false)) {
return false;
}
return backend()->deleteSource(source.id());
}
struct SourceCont {
Source entity;
size_t depth;
};
std::vector<Source> Source::findSources(const util::Filter<Source>::type &filter,
size_t max_depth) const
{
std::vector<Source> results;
std::queue<SourceCont> todo;
todo.push({*this, 0});
while (todo.size() > 0)
{
SourceCont current = todo.front();
todo.pop();
bool filter_ok = filter(current.entity);
if (filter_ok) {
results.push_back(current.entity);
}
if (current.depth < max_depth) {
std::vector<Source> children = current.entity.sources();
size_t next_depth = current.depth + 1;
for (auto it = children.begin(); it != children.end(); ++it) {
todo.push({*it, next_depth});
}
}
}
return results;
}
//------------------------------------------------------
// Operators and other functions
//------------------------------------------------------
std::vector<nix::DataArray> Source::referringDataArrays() const {
std::vector<nix::DataArray> arrays;
nix::File f = backend()->parentFile();
for (auto b : f.blocks()) {
std::vector<nix::DataArray> temp = b.dataArrays(nix::util::SourceFilter<nix::DataArray>(id()));
arrays.insert(arrays.end(), temp.begin(), temp.end());
}
return arrays;
}
std::vector<nix::Tag> Source::referringTags() const {
std::vector<nix::Tag> tags;
nix::File f = backend()->parentFile();
for (auto b : f.blocks()) {
std::vector<nix::Tag> temp = b.tags(nix::util::SourceFilter<nix::Tag>(id()));
tags.insert(tags.end(), temp.begin(), temp.end());
}
return tags;
}
std::vector<nix::MultiTag> Source::referringMultiTags() const {
std::vector<nix::MultiTag> tags;
nix::File f = backend()->parentFile();
for (auto b : f.blocks()) {
std::vector<nix::MultiTag> temp = b.multiTags(nix::util::SourceFilter<nix::MultiTag>(id()));
tags.insert(tags.end(), temp.begin(), temp.end());
}
return tags;
}
std::ostream& nix::operator<<(std::ostream &out, const Source &ent) {
out << "Source: {name = " << ent.name();
out << ", type = " << ent.type();
out << ", id = " << ent.id() << "}";
return out;
}
<commit_msg>[Source] simplify referringXYZ methods<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/Source.hpp>
#include <queue>
#include <nix/File.hpp>
#include <nix/util/util.hpp>
using namespace nix;
Source::Source()
: EntityWithMetadata()
{
}
Source::Source(const Source &other)
: EntityWithMetadata(other.impl())
{
}
Source::Source(const std::shared_ptr<base::ISource> &p_impl)
: EntityWithMetadata(p_impl)
{
}
Source::Source(std::shared_ptr<base::ISource> &&ptr)
: EntityWithMetadata(std::move(ptr))
{
}
//--------------------------------------------------
// Methods concerning child sources
//--------------------------------------------------
Source Source::createSource(const std::string &name, const std::string &type) {
util::checkEntityNameAndType(name, type);
if(backend()->hasSource(name)) {
throw DuplicateName("Source with the given name already exists!");
}
return backend()->createSource(name, type);
}
bool Source::hasSource(const Source &source) const {
if (!util::checkEntityInput(source, false)) {
return false;
}
return backend()->hasSource(source.id());
}
std::vector<Source> Source::sources(const util::Filter<Source>::type &filter) const {
auto f = [this] (ndsize_t i) { return getSource(i); };
return getEntities<Source>(f, sourceCount(), filter);
}
bool Source::deleteSource(const Source &source) {
if (!util::checkEntityInput(source, false)) {
return false;
}
return backend()->deleteSource(source.id());
}
struct SourceCont {
Source entity;
size_t depth;
};
std::vector<Source> Source::findSources(const util::Filter<Source>::type &filter,
size_t max_depth) const
{
std::vector<Source> results;
std::queue<SourceCont> todo;
todo.push({*this, 0});
while (todo.size() > 0)
{
SourceCont current = todo.front();
todo.pop();
bool filter_ok = filter(current.entity);
if (filter_ok) {
results.push_back(current.entity);
}
if (current.depth < max_depth) {
std::vector<Source> children = current.entity.sources();
size_t next_depth = current.depth + 1;
for (auto it = children.begin(); it != children.end(); ++it) {
todo.push({*it, next_depth});
}
}
}
return results;
}
//------------------------------------------------------
// Operators and other functions
//------------------------------------------------------
std::vector<nix::DataArray> Source::referringDataArrays() const {
nix::File f = backend()->parentFile();
nix::Block b = backend()->parentBlock();
return b.dataArrays(nix::util::SourceFilter<nix::DataArray>(id()));
}
std::vector<nix::Tag> Source::referringTags() const {
nix::File f = backend()->parentFile();
nix::Block b = backend()->parentBlock();
return b.tags(nix::util::SourceFilter<nix::Tag>(id()));
}
std::vector<nix::MultiTag> Source::referringMultiTags() const {
nix::File f = backend()->parentFile();
nix::Block b = backend()->parentBlock();
return b.multiTags(nix::util::SourceFilter<nix::MultiTag>(id()));
}
std::ostream& nix::operator<<(std::ostream &out, const Source &ent) {
out << "Source: {name = " << ent.name();
out << ", type = " << ent.type();
out << ", id = " << ent.id() << "}";
return out;
}
<|endoftext|>
|
<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "metrics.h"
#include <errno.h>
#include <stdio.h>
#include <string.h>
#ifndef WIN32
#include <sys/time.h>
#else
#include <windows.h>
#endif
#include "util.h"
Metrics* g_metrics = NULL;
namespace {
#ifndef WIN32
/// Compute a platform-specific high-res timer value that fits into an int64.
int64_t HighResTimer() {
timeval tv;
if (gettimeofday(&tv, NULL) < 0)
Fatal("gettimeofday: %s", strerror(errno));
return (int64_t)tv.tv_sec * 1000*1000 + tv.tv_usec;
}
/// Convert a delta of HighResTimer() values to microseconds.
int64_t TimerToMicros(int64_t dt) {
// No conversion necessary.
return dt;
}
#else
int64_t LargeIntegerToInt64(const LARGE_INTEGER& i) {
return ((int64_t)i.HighPart) << 32 | i.LowPart;
}
int64_t HighResTimer() {
LARGE_INTEGER counter;
if (!QueryPerformanceCounter(&counter))
Fatal("QueryPerformanceCounter: %s", GetLastErrorString().c_str());
return LargeIntegerToInt64(counter);
}
int64_t TimerToMicros(int64_t dt) {
static int64_t ticks_per_sec = 0;
if (!ticks_per_sec) {
LARGE_INTEGER freq;
if (!QueryPerformanceFrequency(&freq))
Fatal("QueryPerformanceFrequency: %s", GetLastErrorString().c_str());
ticks_per_sec = LargeIntegerToInt64(freq);
}
// dt is in ticks. We want microseconds.
return (dt * 1000000) / ticks_per_sec;
}
#endif
} // anonymous namespace
ScopedMetric::ScopedMetric(Metric* metric) {
metric_ = metric;
if (!metric_)
return;
start_ = HighResTimer();
}
ScopedMetric::~ScopedMetric() {
if (!metric_)
return;
metric_->count++;
int64_t dt = TimerToMicros(HighResTimer() - start_);
metric_->sum += dt;
}
Metric* Metrics::NewMetric(const string& name) {
Metric* metric = new Metric;
metric->name = name;
metric->count = 0;
metric->sum = 0;
metrics_.push_back(metric);
return metric;
}
void Metrics::Report() {
printf("%-10s\t%-6s\t%9s\t%s\n",
"metric", "count", "total (ms)" , "avg (us)");
for (vector<Metric*>::iterator i = metrics_.begin(); i != metrics_.end(); ++i) {
Metric* metric = *i;
double total = metric->sum / (double)1000;
double avg = metric->sum / (double)metric->count;
printf("%-10s\t%-6d\t%-8.1f\t%.1f\n", metric->name.c_str(),
metric->count, total, avg);
}
}
<commit_msg>dynamic metrics report width<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "metrics.h"
#include <errno.h>
#include <stdio.h>
#include <string.h>
#ifndef WIN32
#include <sys/time.h>
#else
#include <windows.h>
#endif
#include "util.h"
Metrics* g_metrics = NULL;
namespace {
#ifndef WIN32
/// Compute a platform-specific high-res timer value that fits into an int64.
int64_t HighResTimer() {
timeval tv;
if (gettimeofday(&tv, NULL) < 0)
Fatal("gettimeofday: %s", strerror(errno));
return (int64_t)tv.tv_sec * 1000*1000 + tv.tv_usec;
}
/// Convert a delta of HighResTimer() values to microseconds.
int64_t TimerToMicros(int64_t dt) {
// No conversion necessary.
return dt;
}
#else
int64_t LargeIntegerToInt64(const LARGE_INTEGER& i) {
return ((int64_t)i.HighPart) << 32 | i.LowPart;
}
int64_t HighResTimer() {
LARGE_INTEGER counter;
if (!QueryPerformanceCounter(&counter))
Fatal("QueryPerformanceCounter: %s", GetLastErrorString().c_str());
return LargeIntegerToInt64(counter);
}
int64_t TimerToMicros(int64_t dt) {
static int64_t ticks_per_sec = 0;
if (!ticks_per_sec) {
LARGE_INTEGER freq;
if (!QueryPerformanceFrequency(&freq))
Fatal("QueryPerformanceFrequency: %s", GetLastErrorString().c_str());
ticks_per_sec = LargeIntegerToInt64(freq);
}
// dt is in ticks. We want microseconds.
return (dt * 1000000) / ticks_per_sec;
}
#endif
} // anonymous namespace
ScopedMetric::ScopedMetric(Metric* metric) {
metric_ = metric;
if (!metric_)
return;
start_ = HighResTimer();
}
ScopedMetric::~ScopedMetric() {
if (!metric_)
return;
metric_->count++;
int64_t dt = TimerToMicros(HighResTimer() - start_);
metric_->sum += dt;
}
Metric* Metrics::NewMetric(const string& name) {
Metric* metric = new Metric;
metric->name = name;
metric->count = 0;
metric->sum = 0;
metrics_.push_back(metric);
return metric;
}
void Metrics::Report() {
int width = 0;
for (vector<Metric*>::iterator i = metrics_.begin();
i != metrics_.end(); ++i) {
width = max((int)(*i)->name.size(), width);
}
printf("%-*s\t%-6s\t%9s\t%s\n", width,
"metric", "count", "total (ms)" , "avg (us)");
for (vector<Metric*>::iterator i = metrics_.begin();
i != metrics_.end(); ++i) {
Metric* metric = *i;
double total = metric->sum / (double)1000;
double avg = metric->sum / (double)metric->count;
printf("%-*s\t%-6d\t%-8.1f\t%.1f\n", width, metric->name.c_str(),
metric->count, total, avg);
}
}
<|endoftext|>
|
<commit_before>#include "MDPattern.hh"
#include "Elektron.hh"
#include "MDMessages.hh"
#include "helpers.h"
#include "MDParams.hh"
#include "GUI.h"
bool MDPattern::fromSysex(uint8_t *data, uint16_t len) {
if (len != 0xACA - 6) {
// wrong length
return false;
}
uint16_t cksum = 0;
for (int i = 9 - 6; i < 0xAC6 - 6; i++) {
cksum += data[i];
}
cksum &= 0x3FFF;
if (cksum != to16Bit(data[0xAC6 - 6], data[0xAC7 - 6])) {
// wrong checksum
return false;
}
origPosition = data[9 - 6];
uint8_t data2[204];
sysex_to_data_elektron(data + 0xA - 6, data2, 74);
uint8_t *ptr = data2;
for (int i = 0; i < 16; i++) {
trigPatterns[i] = to32Bit(ptr);
ptr += 4;
}
sysex_to_data_elektron(data + 0x54 - 6, data2, 74);
ptr = data2;
for (int i = 0; i < 16; i++) {
lockPatterns[i] = to32Bit(ptr);
ptr += 4;
}
sysex_to_data_elektron(data + 0x9e - 6, data2, 19);
accentPattern = to32Bit(data2);
slidePattern = to32Bit(data2 + 4);
swingPattern = to32Bit(data2 + 8);
swingAmount = to32Bit(data2 + 12);
accentAmount = data[0xB1 - 6];
patternLength = data[0xB2 - 6];
doubleTempo = (data[0xb3 - 6] == 1);
scale = data[0xb4 - 6];
kit = data[0xb5 - 6];
numLockedRows = data[0xb6 - 6];
sysex_to_data_elektron(data + 0xB7 - 6, (uint8_t *)locks, 2341);
sysex_to_data_elektron(data + 0x9DC - 6, data2, 234);
accentEditAll = (to32Bit(data2) == 1);
slideEditAll = (to32Bit(data2 + 4) == 1);
swingEditAll = (to32Bit(data2 + 8) == 1);
ptr = data2 + 12;
for (int i = 0; i < 16; i++) {
accentPatterns[i] = to32Bit(ptr);
ptr += 4;
}
for (int i = 0; i < 16; i++) {
slidePatterns[i] = to32Bit(ptr);
ptr += 4;
}
for (int i = 0; i < 16; i++) {
swingPatterns[i] = to32Bit(ptr);
ptr += 4;
}
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 24; j++) {
paramLocks[i][j] = -1;
}
}
numRows = 0;
for (int i = 0; i < 64; i++) {
lockTracks[i] = -1;
lockParams[i] = -1;
}
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 24; j++) {
paramLocks[i][j] = -1;
if (IS_BIT_SET(lockPatterns[i], j)) {
paramLocks[i][j] = numRows;
lockTracks[numRows] = i;
lockParams[numRows] = j;
numRows++;
}
}
}
return true;
}
uint16_t MDPattern::toSysex(uint8_t *data, uint16_t len) {
if (len < 0xacb)
return 0;
m_memclr(data, 0xACB);
data[0] = 0xF0;
m_memcpy(data + 1, machinedrum_sysex_hdr, sizeof(machinedrum_sysex_hdr));
data[6] = MD_PATTERN_MESSAGE_ID;
data[7] = 0x03; // version
data[8] = 0x01;
data[9] = origPosition;
uint8_t data2[204];
uint8_t *ptr = data2;
for (int i = 0; i < 16; i++) {
from32Bit(trigPatterns[i], ptr);
ptr += 4;
}
data_to_sysex_elektron(data2, data + 0xA, 64);
recalculateLockPatterns();
ptr = data2;
for (int i = 0; i < 16; i++) {
from32Bit(lockPatterns[i], ptr);
ptr += 4;
}
data_to_sysex_elektron(data2, data + 0x54, 64);
from32Bit(accentPattern, data2);
from32Bit(slidePattern, data2 + 4);
from32Bit(swingPattern, data2 + 8);
from32Bit(swingAmount, data2 + 12);
data_to_sysex_elektron(data2, data + 0x9e, 16);
data[0xB1] = accentAmount;
data[0xB2] = patternLength;
data[0xb3] = doubleTempo ? 1 : 0;
data[0xb4] = scale;
data[0xb5] = kit;
data[0xb6] = numLockedRows;
uint16_t retlen = 0;
uint16_t cnt = 0;
ptr = data + 0xB7;
{
uint16_t cnt7 = 0;
ptr[0] = 0;
for (int track = 0; track < 16; track++) {
for (int param = 0; param < 24; param++) {
if (paramLocks[track][param] != -1) {
uint8_t *data3 = locks[paramLocks[track][param]];
for (int i = 0; i < 32; i++) {
uint8_t c = data3[i] & 0x7F;
uint8_t msb = data3[i] >> 7;
ptr[0] |= msb << (6 - cnt7);
ptr[1 + cnt7] = c;
if (cnt7++ == 6) {
ptr += 8;
retlen += 8;
ptr[0] = 0;
cnt7 = 0;
}
cnt++;
}
}
}
}
for (uint16_t i = cnt; i < 64 * 32; i++) {
uint8_t c = 0 & 0x7F;
uint8_t msb = 0 >> 7;
ptr[0] |= msb << (6 - cnt7);
ptr[1 + cnt7] = c;
if (cnt7++ == 6) {
ptr += 8;
retlen += 8;
ptr[0] = 0;
cnt7 = 0;
}
cnt++;
}
retlen += cnt7 + (cnt7 != 0 ? 1 : 0);
}
from32Bit(accentEditAll ? 1 : 0, data2);
from32Bit(slideEditAll ? 1 : 0, data2 + 4);
from32Bit(swingEditAll ? 1 : 0, data2 + 8);
ptr = data2 + 12;
for (int i = 0; i < 16; i++) {
from32Bit(accentPatterns[i], ptr);
ptr += 4;
}
for (int i = 0; i < 16; i++) {
from32Bit(slidePatterns[i], ptr);
ptr += 4;
}
for (int i = 0; i < 16; i++) {
from32Bit(swingPatterns[i], ptr);
ptr += 4;
}
data_to_sysex_elektron(data2, data + 0x9DC, 204);
uint16_t checksum = 0;
for (int i = 9; i < 0xac6; i++)
checksum += data[i];
data[0xac6] = (uint8_t)((checksum >> 7) & 0x7F);
data[0xac7] = (uint8_t)(checksum & 0x7F);
uint16_t length = 0xacb - 7 - 3;
data[0xac8] = (uint8_t)((length >> 7) &0x7F);
data[0xac9] = (uint8_t)(length & 0x7F);
data[0xaca] = 0xF7;
return 0xacb;
}
bool MDPattern::isLockPatternEmpty(uint8_t idx) {
for (int i = 0; i < 32; i++) {
if (locks[idx][i] != 255)
return false;
}
return true;
}
bool MDPattern::isLockPatternEmpty(uint8_t idx, uint32_t trigs) {
for (int i = 0; i < 32; i++) {
if (locks[idx][i] != 255 || !IS_BIT_SET(trigs, i))
return false;
}
return true;
}
void MDPattern::cleanupLocks() {
for (int i = 0; i < 64; i++) {
if (lockTracks[i] != -1) {
if (isLockPatternEmpty(i, trigPatterns[lockTracks[i]])) {
if (lockParams[i] != -1) {
paramLocks[lockTracks[i]][lockParams[i]] = -1;
}
lockTracks[i] = -1;
lockParams[i] = -1;
}
} else {
lockParams[i] = -1;
}
}
}
void MDPattern::clearPattern() {
for (int i = 0; i < 16; i++) {
clearTrack(i);
}
}
void MDPattern::clearTrack(uint8_t track) {
if (track >= 16)
return;
for (int i = 0; i < 32; i++) {
clearTrig(track, i);
}
}
void MDPattern::clearLockPattern(uint8_t lock) {
if (lock >= 64)
return;
for (int i = 0; i < 32; i++) {
locks[lock][i] = 255;
if (lockTracks[lock] != -1 && lockParams[lock] != -1) {
paramLocks[lockTracks[lock]][lockParams[lock]] = -1;
}
lockTracks[lock] = -1;
lockParams[lock] = -1;
}
}
void MDPattern::clearParamLocks(uint8_t track, uint8_t param) {
int8_t idx = paramLocks[track][param];
if (idx != -1) {
clearLockPattern(idx);
}
}
void MDPattern::clearTrackLocks(uint8_t track) {
for (int i = 0; i < 24; i++) {
clearParamLocks(track, i);
}
}
void MDPattern::clearTrig(uint8_t track, uint8_t trig) {
CLEAR_BIT(trigPatterns[track], trig);
for (int i = 0; i < 24; i++) {
clearLock(track, trig, i);
}
}
void MDPattern::setTrig(uint8_t track, uint8_t trig) {
SET_BIT(trigPatterns[track], trig);
}
int8_t MDPattern::getNextEmptyLock() {
for (int i = 0; i < 64; i++) {
if (lockTracks[i] == -1 && lockParams[i] == -1) {
return i;
}
}
return -1;
}
bool MDPattern::addLock(uint8_t track, uint8_t trig, uint8_t param, uint8_t value) {
int8_t idx = paramLocks[track][param];
if (idx == -1) {
idx = getNextEmptyLock();
if (idx == -1)
return false;
paramLocks[track][param] = idx;
lockTracks[idx] = track;
lockParams[idx] = param;
}
locks[idx][trig] = value;
return true;
}
void MDPattern::clearLock(uint8_t track, uint8_t trig, uint8_t param) {
int8_t idx = paramLocks[track][param];
if (idx == -1)
return;
locks[idx][trig] = 255;
if (isLockPatternEmpty(idx, trigPatterns[track])) {
paramLocks[track][param] = -1;
lockTracks[idx] = -1;
lockParams[idx] = -1;
}
}
void MDPattern::recalculateLockPatterns() {
for (int track = 0; track < 16; track++) {
lockPatterns[track] = 0;
for (int param = 0; param < 24; param++) {
if (paramLocks[track][param] != -1) {
SET_BIT(lockPatterns[track], param);
}
}
}
}
uint8_t MDPattern::getLock(uint8_t track, uint8_t trig, uint8_t param) {
int8_t idx = paramLocks[track][param];
if (idx == -1)
return 255;
return locks[idx][trig];
}
<commit_msg>init locks when adding a new row<commit_after>#include "MDPattern.hh"
#include "Elektron.hh"
#include "MDMessages.hh"
#include "helpers.h"
#include "MDParams.hh"
#include "GUI.h"
bool MDPattern::fromSysex(uint8_t *data, uint16_t len) {
if (len != 0xACA - 6) {
// wrong length
return false;
}
uint16_t cksum = 0;
for (int i = 9 - 6; i < 0xAC6 - 6; i++) {
cksum += data[i];
}
cksum &= 0x3FFF;
if (cksum != to16Bit(data[0xAC6 - 6], data[0xAC7 - 6])) {
// wrong checksum
return false;
}
origPosition = data[9 - 6];
uint8_t data2[204];
sysex_to_data_elektron(data + 0xA - 6, data2, 74);
uint8_t *ptr = data2;
for (int i = 0; i < 16; i++) {
trigPatterns[i] = to32Bit(ptr);
ptr += 4;
}
sysex_to_data_elektron(data + 0x54 - 6, data2, 74);
ptr = data2;
for (int i = 0; i < 16; i++) {
lockPatterns[i] = to32Bit(ptr);
ptr += 4;
}
sysex_to_data_elektron(data + 0x9e - 6, data2, 19);
accentPattern = to32Bit(data2);
slidePattern = to32Bit(data2 + 4);
swingPattern = to32Bit(data2 + 8);
swingAmount = to32Bit(data2 + 12);
accentAmount = data[0xB1 - 6];
patternLength = data[0xB2 - 6];
doubleTempo = (data[0xb3 - 6] == 1);
scale = data[0xb4 - 6];
kit = data[0xb5 - 6];
numLockedRows = data[0xb6 - 6];
sysex_to_data_elektron(data + 0xB7 - 6, (uint8_t *)locks, 2341);
sysex_to_data_elektron(data + 0x9DC - 6, data2, 234);
accentEditAll = (to32Bit(data2) == 1);
slideEditAll = (to32Bit(data2 + 4) == 1);
swingEditAll = (to32Bit(data2 + 8) == 1);
ptr = data2 + 12;
for (int i = 0; i < 16; i++) {
accentPatterns[i] = to32Bit(ptr);
ptr += 4;
}
for (int i = 0; i < 16; i++) {
slidePatterns[i] = to32Bit(ptr);
ptr += 4;
}
for (int i = 0; i < 16; i++) {
swingPatterns[i] = to32Bit(ptr);
ptr += 4;
}
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 24; j++) {
paramLocks[i][j] = -1;
}
}
numRows = 0;
for (int i = 0; i < 64; i++) {
lockTracks[i] = -1;
lockParams[i] = -1;
}
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 24; j++) {
paramLocks[i][j] = -1;
if (IS_BIT_SET(lockPatterns[i], j)) {
paramLocks[i][j] = numRows;
lockTracks[numRows] = i;
lockParams[numRows] = j;
numRows++;
}
}
}
return true;
}
uint16_t MDPattern::toSysex(uint8_t *data, uint16_t len) {
if (len < 0xacb)
return 0;
m_memclr(data, 0xACB);
data[0] = 0xF0;
m_memcpy(data + 1, machinedrum_sysex_hdr, sizeof(machinedrum_sysex_hdr));
data[6] = MD_PATTERN_MESSAGE_ID;
data[7] = 0x03; // version
data[8] = 0x01;
data[9] = origPosition;
uint8_t data2[204];
uint8_t *ptr = data2;
for (int i = 0; i < 16; i++) {
from32Bit(trigPatterns[i], ptr);
ptr += 4;
}
data_to_sysex_elektron(data2, data + 0xA, 64);
recalculateLockPatterns();
ptr = data2;
for (int i = 0; i < 16; i++) {
from32Bit(lockPatterns[i], ptr);
ptr += 4;
}
data_to_sysex_elektron(data2, data + 0x54, 64);
from32Bit(accentPattern, data2);
from32Bit(slidePattern, data2 + 4);
from32Bit(swingPattern, data2 + 8);
from32Bit(swingAmount, data2 + 12);
data_to_sysex_elektron(data2, data + 0x9e, 16);
data[0xB1] = accentAmount;
data[0xB2] = patternLength;
data[0xb3] = doubleTempo ? 1 : 0;
data[0xb4] = scale;
data[0xb5] = kit;
data[0xb6] = numLockedRows;
uint16_t retlen = 0;
uint16_t cnt = 0;
ptr = data + 0xB7;
{
uint16_t cnt7 = 0;
ptr[0] = 0;
for (int track = 0; track < 16; track++) {
for (int param = 0; param < 24; param++) {
if (paramLocks[track][param] != -1) {
uint8_t *data3 = locks[paramLocks[track][param]];
for (int i = 0; i < 32; i++) {
uint8_t c = data3[i] & 0x7F;
uint8_t msb = data3[i] >> 7;
ptr[0] |= msb << (6 - cnt7);
ptr[1 + cnt7] = c;
if (cnt7++ == 6) {
ptr += 8;
retlen += 8;
ptr[0] = 0;
cnt7 = 0;
}
cnt++;
}
}
}
}
for (uint16_t i = cnt; i < 64 * 32; i++) {
uint8_t c = 0 & 0x7F;
uint8_t msb = 0 >> 7;
ptr[0] |= msb << (6 - cnt7);
ptr[1 + cnt7] = c;
if (cnt7++ == 6) {
ptr += 8;
retlen += 8;
ptr[0] = 0;
cnt7 = 0;
}
cnt++;
}
retlen += cnt7 + (cnt7 != 0 ? 1 : 0);
}
from32Bit(accentEditAll ? 1 : 0, data2);
from32Bit(slideEditAll ? 1 : 0, data2 + 4);
from32Bit(swingEditAll ? 1 : 0, data2 + 8);
ptr = data2 + 12;
for (int i = 0; i < 16; i++) {
from32Bit(accentPatterns[i], ptr);
ptr += 4;
}
for (int i = 0; i < 16; i++) {
from32Bit(slidePatterns[i], ptr);
ptr += 4;
}
for (int i = 0; i < 16; i++) {
from32Bit(swingPatterns[i], ptr);
ptr += 4;
}
data_to_sysex_elektron(data2, data + 0x9DC, 204);
uint16_t checksum = 0;
for (int i = 9; i < 0xac6; i++)
checksum += data[i];
data[0xac6] = (uint8_t)((checksum >> 7) & 0x7F);
data[0xac7] = (uint8_t)(checksum & 0x7F);
uint16_t length = 0xacb - 7 - 3;
data[0xac8] = (uint8_t)((length >> 7) &0x7F);
data[0xac9] = (uint8_t)(length & 0x7F);
data[0xaca] = 0xF7;
return 0xacb;
}
bool MDPattern::isLockPatternEmpty(uint8_t idx) {
for (int i = 0; i < 32; i++) {
if (locks[idx][i] != 255)
return false;
}
return true;
}
bool MDPattern::isLockPatternEmpty(uint8_t idx, uint32_t trigs) {
for (int i = 0; i < 32; i++) {
if (locks[idx][i] != 255 || !IS_BIT_SET(trigs, i))
return false;
}
return true;
}
void MDPattern::cleanupLocks() {
for (int i = 0; i < 64; i++) {
if (lockTracks[i] != -1) {
if (isLockPatternEmpty(i, trigPatterns[lockTracks[i]])) {
if (lockParams[i] != -1) {
paramLocks[lockTracks[i]][lockParams[i]] = -1;
}
lockTracks[i] = -1;
lockParams[i] = -1;
}
} else {
lockParams[i] = -1;
}
}
}
void MDPattern::clearPattern() {
for (int i = 0; i < 16; i++) {
clearTrack(i);
}
}
void MDPattern::clearTrack(uint8_t track) {
if (track >= 16)
return;
for (int i = 0; i < 32; i++) {
clearTrig(track, i);
}
}
void MDPattern::clearLockPattern(uint8_t lock) {
if (lock >= 64)
return;
for (int i = 0; i < 32; i++) {
locks[lock][i] = 255;
if (lockTracks[lock] != -1 && lockParams[lock] != -1) {
paramLocks[lockTracks[lock]][lockParams[lock]] = -1;
}
lockTracks[lock] = -1;
lockParams[lock] = -1;
}
}
void MDPattern::clearParamLocks(uint8_t track, uint8_t param) {
int8_t idx = paramLocks[track][param];
if (idx != -1) {
clearLockPattern(idx);
}
}
void MDPattern::clearTrackLocks(uint8_t track) {
for (int i = 0; i < 24; i++) {
clearParamLocks(track, i);
}
}
void MDPattern::clearTrig(uint8_t track, uint8_t trig) {
CLEAR_BIT(trigPatterns[track], trig);
for (int i = 0; i < 24; i++) {
clearLock(track, trig, i);
}
}
void MDPattern::setTrig(uint8_t track, uint8_t trig) {
SET_BIT(trigPatterns[track], trig);
}
int8_t MDPattern::getNextEmptyLock() {
for (int i = 0; i < 64; i++) {
if (lockTracks[i] == -1 && lockParams[i] == -1) {
return i;
}
}
return -1;
}
bool MDPattern::addLock(uint8_t track, uint8_t trig, uint8_t param, uint8_t value) {
int8_t idx = paramLocks[track][param];
if (idx == -1) {
idx = getNextEmptyLock();
if (idx == -1)
return false;
paramLocks[track][param] = idx;
lockTracks[idx] = track;
lockParams[idx] = param;
for (int i = 0; i < 32; i++) {
locks[idx][i] = 255;
}
}
locks[idx][trig] = value;
return true;
}
void MDPattern::clearLock(uint8_t track, uint8_t trig, uint8_t param) {
int8_t idx = paramLocks[track][param];
if (idx == -1)
return;
locks[idx][trig] = 255;
if (isLockPatternEmpty(idx, trigPatterns[track])) {
paramLocks[track][param] = -1;
lockTracks[idx] = -1;
lockParams[idx] = -1;
}
}
void MDPattern::recalculateLockPatterns() {
for (int track = 0; track < 16; track++) {
lockPatterns[track] = 0;
for (int param = 0; param < 24; param++) {
if (paramLocks[track][param] != -1) {
SET_BIT(lockPatterns[track], param);
}
}
}
}
uint8_t MDPattern::getLock(uint8_t track, uint8_t trig, uint8_t param) {
int8_t idx = paramLocks[track][param];
if (idx == -1)
return 255;
return locks[idx][trig];
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2011-2017 Branimir Karadzic. All rights reserved.
* License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
*/
#include "common.h"
#include "bgfx_utils.h"
#include <bx/uint32_t.h>
#include "imgui/imgui.h"
#include <bgfx/embedded_shader.h>
// embedded shaders
#include "vs_drawstress.bin.h"
#include "fs_drawstress.bin.h"
namespace
{
static const bgfx::EmbeddedShader s_embeddedShaders[] =
{
BGFX_EMBEDDED_SHADER(vs_drawstress),
BGFX_EMBEDDED_SHADER(fs_drawstress),
BGFX_EMBEDDED_SHADER_END()
};
struct PosColorVertex
{
float m_x;
float m_y;
float m_z;
uint32_t m_abgr;
static void init()
{
ms_decl
.begin()
.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
.end();
}
static bgfx::VertexDecl ms_decl;
};
bgfx::VertexDecl PosColorVertex::ms_decl;
static PosColorVertex s_cubeVertices[8] =
{
{-1.0f, 1.0f, 1.0f, 0xff000000 },
{ 1.0f, 1.0f, 1.0f, 0xff0000ff },
{-1.0f, -1.0f, 1.0f, 0xff00ff00 },
{ 1.0f, -1.0f, 1.0f, 0xff00ffff },
{-1.0f, 1.0f, -1.0f, 0xffff0000 },
{ 1.0f, 1.0f, -1.0f, 0xffff00ff },
{-1.0f, -1.0f, -1.0f, 0xffffff00 },
{ 1.0f, -1.0f, -1.0f, 0xffffffff },
};
static const uint16_t s_cubeIndices[36] =
{
0, 1, 2, // 0
1, 3, 2,
4, 6, 5, // 2
5, 6, 7,
0, 2, 4, // 4
4, 2, 6,
1, 5, 3, // 6
5, 7, 3,
0, 4, 1, // 8
4, 5, 1,
2, 3, 6, // 10
6, 3, 7,
};
#if BX_PLATFORM_EMSCRIPTEN
static const int64_t highwm = 1000000/35;
static const int64_t lowwm = 1000000/27;
#else
static const int64_t highwm = 1000000/65;
static const int64_t lowwm = 1000000/57;
#endif // BX_PLATFORM_EMSCRIPTEN
class ExampleDrawStress : public entry::AppI
{
public:
ExampleDrawStress(const char* _name, const char* _description)
: entry::AppI(_name, _description)
{
}
void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
{
Args args(_argc, _argv);
m_width = _width;
m_height = _height;
m_debug = BGFX_DEBUG_NONE;
m_reset = BGFX_RESET_NONE;
m_autoAdjust = true;
m_scrollArea = 0;
m_dim = 16;
m_maxDim = 40;
m_transform = 0;
m_timeOffset = bx::getHPCounter();
m_deltaTimeNs = 0;
m_deltaTimeAvgNs = 0;
m_numFrames = 0;
bgfx::init(args.m_type, args.m_pciId);
bgfx::reset(m_width, m_height, m_reset);
const bgfx::Caps* caps = bgfx::getCaps();
m_maxDim = (int32_t)bx::fpow(float(caps->limits.maxDrawCalls), 1.0f/3.0f);
// Enable debug text.
bgfx::setDebug(m_debug);
// Set view 0 clear state.
bgfx::setViewClear(0
, BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
, 0x303030ff
, 1.0f
, 0
);
// Create vertex stream declaration.
PosColorVertex::init();
bgfx::RendererType::Enum type = bgfx::getRendererType();
// Create program from shaders.
m_program = bgfx::createProgram(
bgfx::createEmbeddedShader(s_embeddedShaders, type, "vs_drawstress")
, bgfx::createEmbeddedShader(s_embeddedShaders, type, "fs_drawstress")
, true /* destroy shaders when program is destroyed */
);
// Create static vertex buffer.
m_vbh = bgfx::createVertexBuffer(
bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) )
, PosColorVertex::ms_decl
);
// Create static index buffer.
m_ibh = bgfx::createIndexBuffer(bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ) );
// Imgui.
imguiCreate();
}
int shutdown() override
{
// Cleanup.
imguiDestroy();
bgfx::destroy(m_ibh);
bgfx::destroy(m_vbh);
bgfx::destroy(m_program);
// Shutdown bgfx.
bgfx::shutdown();
return 0;
}
bool update() override
{
if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
{
int64_t now = bx::getHPCounter();
static int64_t last = now;
const int64_t hpFreq = bx::getHPFrequency();
const int64_t frameTime = now - last;
last = now;
const double freq = double(hpFreq);
const double toMs = 1000.0/freq;
m_deltaTimeNs += frameTime*1000000/hpFreq;
if (m_deltaTimeNs > 1000000)
{
m_deltaTimeAvgNs = m_deltaTimeNs / bx::int64_max(1, m_numFrames);
if (m_autoAdjust)
{
if (m_deltaTimeAvgNs < highwm)
{
m_dim = bx::uint32_min(m_dim + 2, m_maxDim);
}
else if (m_deltaTimeAvgNs > lowwm)
{
m_dim = bx::uint32_max(m_dim - 1, 2);
}
}
m_deltaTimeNs = 0;
m_numFrames = 0;
}
else
{
++m_numFrames;
}
float time = (float)( (now-m_timeOffset)/freq);
imguiBeginFrame(m_mouseState.m_mx
, m_mouseState.m_my
, (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
| (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
| (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
, m_mouseState.m_mz
, uint16_t(m_width)
, uint16_t(m_height)
);
showExampleDialog(this);
ImGui::SetNextWindowPos(ImVec2((float)m_width - (float)m_width / 4.0f - 10.0f, 10.0f) );
ImGui::SetNextWindowSize(ImVec2((float)m_width / 4.0f, (float)m_height / 2.0f) );
ImGui::Begin("Settings"
, NULL
, ImVec2((float)m_width / 4.0f, (float)m_height / 2.0f)
, ImGuiWindowFlags_AlwaysAutoResize
);
ImGui::RadioButton("Rotate",&m_transform,0);
ImGui::RadioButton("No fragments",&m_transform,1);
ImGui::Separator();
ImGui::Checkbox("Auto adjust", &m_autoAdjust);
ImGui::SliderInt("Dim", &m_dim, 5, m_maxDim);
ImGui::Text("Draw calls: %d", m_dim*m_dim*m_dim);
ImGui::Text("Avg Delta Time (1 second) [ms]: %0.4f", m_deltaTimeAvgNs/1000.0f);
ImGui::Separator();
const bgfx::Stats* stats = bgfx::getStats();
ImGui::Text("GPU %0.6f [ms]", double(stats->gpuTimeEnd - stats->gpuTimeBegin)*1000.0/stats->gpuTimerFreq);
ImGui::Text("CPU %0.6f [ms]", double(stats->cpuTimeEnd - stats->cpuTimeBegin)*1000.0/stats->cpuTimerFreq);
ImGui::Text("Waiting for render thread %0.6f [ms]", double(stats->waitRender) * toMs);
ImGui::Text("Waiting for submit thread %0.6f [ms]", double(stats->waitSubmit) * toMs);
ImGui::End();
imguiEndFrame();
float at[3] = { 0.0f, 0.0f, 0.0f };
float eye[3] = { 0.0f, 0.0f, -35.0f };
float view[16];
bx::mtxLookAt(view, eye, at);
const bgfx::Caps* caps = bgfx::getCaps();
float proj[16];
bx::mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 100.0f, caps->homogeneousDepth);
// Set view and projection matrix for view 0.
bgfx::setViewTransform(0, view, proj);
// Set view 0 default viewport.
bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
// This dummy draw call is here to make sure that view 0 is cleared
// if no other draw calls are submitted to view 0.
bgfx::touch(0);
float mtxS[16];
const float scale = 0 == m_transform ? 0.25f : 0.0f;
bx::mtxScale(mtxS, scale, scale, scale);
const float step = 0.6f;
float pos[3];
pos[0] = -step*m_dim / 2.0f;
pos[1] = -step*m_dim / 2.0f;
pos[2] = -15.0;
for (uint32_t zz = 0; zz < uint32_t(m_dim); ++zz)
{
for (uint32_t yy = 0; yy < uint32_t(m_dim); ++yy)
{
for (uint32_t xx = 0; xx < uint32_t(m_dim); ++xx)
{
float mtxR[16];
bx::mtxRotateXYZ(mtxR, time + xx*0.21f, time + yy*0.37f, time + yy*0.13f);
float mtx[16];
bx::mtxMul(mtx, mtxS, mtxR);
mtx[12] = pos[0] + float(xx)*step;
mtx[13] = pos[1] + float(yy)*step;
mtx[14] = pos[2] + float(zz)*step;
// Set model matrix for rendering.
bgfx::setTransform(mtx);
// Set vertex and index buffer.
bgfx::setVertexBuffer(0, m_vbh);
bgfx::setIndexBuffer(m_ibh);
// Set render states.
bgfx::setState(BGFX_STATE_DEFAULT);
// Submit primitive for rendering to view 0.
bgfx::submit(0, m_program);
}
}
}
// Advance to next frame. Rendering thread will be kicked to
// process submitted rendering primitives.
bgfx::frame();
return true;
}
return false;
}
entry::MouseState m_mouseState;
uint32_t m_width;
uint32_t m_height;
uint32_t m_debug;
uint32_t m_reset;
bool m_autoAdjust;
int32_t m_scrollArea;
int32_t m_dim;
int32_t m_maxDim;
int32_t m_transform;
int64_t m_timeOffset;
int64_t m_deltaTimeNs;
int64_t m_deltaTimeAvgNs;
int64_t m_numFrames;
bgfx::ProgramHandle m_program;
bgfx::VertexBufferHandle m_vbh;
bgfx::IndexBufferHandle m_ibh;
};
} // namespace
ENTRY_IMPLEMENT_MAIN(ExampleDrawStress, "17-drawstress", "Draw stress, maximizing number of draw calls.");
<commit_msg>Switching 17-drawstress to use encoder API.<commit_after>/*
* Copyright 2011-2017 Branimir Karadzic. All rights reserved.
* License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
*/
#include "common.h"
#include "bgfx_utils.h"
#include <bx/uint32_t.h>
#include "imgui/imgui.h"
#include <bgfx/embedded_shader.h>
// embedded shaders
#include "vs_drawstress.bin.h"
#include "fs_drawstress.bin.h"
namespace
{
static const bgfx::EmbeddedShader s_embeddedShaders[] =
{
BGFX_EMBEDDED_SHADER(vs_drawstress),
BGFX_EMBEDDED_SHADER(fs_drawstress),
BGFX_EMBEDDED_SHADER_END()
};
struct PosColorVertex
{
float m_x;
float m_y;
float m_z;
uint32_t m_abgr;
static void init()
{
ms_decl
.begin()
.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
.end();
}
static bgfx::VertexDecl ms_decl;
};
bgfx::VertexDecl PosColorVertex::ms_decl;
static PosColorVertex s_cubeVertices[8] =
{
{-1.0f, 1.0f, 1.0f, 0xff000000 },
{ 1.0f, 1.0f, 1.0f, 0xff0000ff },
{-1.0f, -1.0f, 1.0f, 0xff00ff00 },
{ 1.0f, -1.0f, 1.0f, 0xff00ffff },
{-1.0f, 1.0f, -1.0f, 0xffff0000 },
{ 1.0f, 1.0f, -1.0f, 0xffff00ff },
{-1.0f, -1.0f, -1.0f, 0xffffff00 },
{ 1.0f, -1.0f, -1.0f, 0xffffffff },
};
static const uint16_t s_cubeIndices[36] =
{
0, 1, 2, // 0
1, 3, 2,
4, 6, 5, // 2
5, 6, 7,
0, 2, 4, // 4
4, 2, 6,
1, 5, 3, // 6
5, 7, 3,
0, 4, 1, // 8
4, 5, 1,
2, 3, 6, // 10
6, 3, 7,
};
#if BX_PLATFORM_EMSCRIPTEN
static const int64_t highwm = 1000000/35;
static const int64_t lowwm = 1000000/27;
#else
static const int64_t highwm = 1000000/65;
static const int64_t lowwm = 1000000/57;
#endif // BX_PLATFORM_EMSCRIPTEN
class ExampleDrawStress : public entry::AppI
{
public:
ExampleDrawStress(const char* _name, const char* _description)
: entry::AppI(_name, _description)
{
}
void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
{
Args args(_argc, _argv);
m_width = _width;
m_height = _height;
m_debug = BGFX_DEBUG_NONE;
m_reset = BGFX_RESET_NONE;
m_autoAdjust = true;
m_scrollArea = 0;
m_dim = 16;
m_maxDim = 40;
m_transform = 0;
m_timeOffset = bx::getHPCounter();
m_deltaTimeNs = 0;
m_deltaTimeAvgNs = 0;
m_numFrames = 0;
bgfx::init(args.m_type, args.m_pciId);
bgfx::reset(m_width, m_height, m_reset);
const bgfx::Caps* caps = bgfx::getCaps();
m_maxDim = (int32_t)bx::fpow(float(caps->limits.maxDrawCalls), 1.0f/3.0f);
// Enable debug text.
bgfx::setDebug(m_debug);
// Set view 0 clear state.
bgfx::setViewClear(0
, BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
, 0x303030ff
, 1.0f
, 0
);
// Create vertex stream declaration.
PosColorVertex::init();
bgfx::RendererType::Enum type = bgfx::getRendererType();
// Create program from shaders.
m_program = bgfx::createProgram(
bgfx::createEmbeddedShader(s_embeddedShaders, type, "vs_drawstress")
, bgfx::createEmbeddedShader(s_embeddedShaders, type, "fs_drawstress")
, true /* destroy shaders when program is destroyed */
);
// Create static vertex buffer.
m_vbh = bgfx::createVertexBuffer(
bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) )
, PosColorVertex::ms_decl
);
// Create static index buffer.
m_ibh = bgfx::createIndexBuffer(bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ) );
// Imgui.
imguiCreate();
}
int shutdown() override
{
// Cleanup.
imguiDestroy();
bgfx::destroy(m_ibh);
bgfx::destroy(m_vbh);
bgfx::destroy(m_program);
// Shutdown bgfx.
bgfx::shutdown();
return 0;
}
bool update() override
{
if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
{
int64_t now = bx::getHPCounter();
static int64_t last = now;
const int64_t hpFreq = bx::getHPFrequency();
const int64_t frameTime = now - last;
last = now;
const double freq = double(hpFreq);
const double toMs = 1000.0/freq;
m_deltaTimeNs += frameTime*1000000/hpFreq;
if (m_deltaTimeNs > 1000000)
{
m_deltaTimeAvgNs = m_deltaTimeNs / bx::int64_max(1, m_numFrames);
if (m_autoAdjust)
{
if (m_deltaTimeAvgNs < highwm)
{
m_dim = bx::uint32_min(m_dim + 2, m_maxDim);
}
else if (m_deltaTimeAvgNs > lowwm)
{
m_dim = bx::uint32_max(m_dim - 1, 2);
}
}
m_deltaTimeNs = 0;
m_numFrames = 0;
}
else
{
++m_numFrames;
}
float time = (float)( (now-m_timeOffset)/freq);
imguiBeginFrame(m_mouseState.m_mx
, m_mouseState.m_my
, (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
| (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
| (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
, m_mouseState.m_mz
, uint16_t(m_width)
, uint16_t(m_height)
);
showExampleDialog(this);
ImGui::SetNextWindowPos(ImVec2((float)m_width - (float)m_width / 4.0f - 10.0f, 10.0f) );
ImGui::SetNextWindowSize(ImVec2((float)m_width / 4.0f, (float)m_height / 2.0f) );
ImGui::Begin("Settings"
, NULL
, ImVec2((float)m_width / 4.0f, (float)m_height / 2.0f)
, ImGuiWindowFlags_AlwaysAutoResize
);
ImGui::RadioButton("Rotate",&m_transform,0);
ImGui::RadioButton("No fragments",&m_transform,1);
ImGui::Separator();
ImGui::Checkbox("Auto adjust", &m_autoAdjust);
ImGui::SliderInt("Dim", &m_dim, 5, m_maxDim);
ImGui::Text("Draw calls: %d", m_dim*m_dim*m_dim);
ImGui::Text("Avg Delta Time (1 second) [ms]: %0.4f", m_deltaTimeAvgNs/1000.0f);
ImGui::Separator();
const bgfx::Stats* stats = bgfx::getStats();
ImGui::Text("GPU %0.6f [ms]", double(stats->gpuTimeEnd - stats->gpuTimeBegin)*1000.0/stats->gpuTimerFreq);
ImGui::Text("CPU %0.6f [ms]", double(stats->cpuTimeEnd - stats->cpuTimeBegin)*1000.0/stats->cpuTimerFreq);
ImGui::Text("Waiting for render thread %0.6f [ms]", double(stats->waitRender) * toMs);
ImGui::Text("Waiting for submit thread %0.6f [ms]", double(stats->waitSubmit) * toMs);
ImGui::End();
imguiEndFrame();
float at[3] = { 0.0f, 0.0f, 0.0f };
float eye[3] = { 0.0f, 0.0f, -35.0f };
float view[16];
bx::mtxLookAt(view, eye, at);
const bgfx::Caps* caps = bgfx::getCaps();
float proj[16];
bx::mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 100.0f, caps->homogeneousDepth);
// Set view and projection matrix for view 0.
bgfx::setViewTransform(0, view, proj);
// Set view 0 default viewport.
bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
// This dummy draw call is here to make sure that view 0 is cleared
// if no other draw calls are submitted to view 0.
bgfx::touch(0);
float mtxS[16];
const float scale = 0 == m_transform ? 0.25f : 0.0f;
bx::mtxScale(mtxS, scale, scale, scale);
const float step = 0.6f;
float pos[3];
pos[0] = -step*m_dim / 2.0f;
pos[1] = -step*m_dim / 2.0f;
pos[2] = -15.0;
bgfx::Encoder* encoder = bgfx::begin();
for (uint32_t zz = 0; zz < uint32_t(m_dim); ++zz)
{
for (uint32_t yy = 0; yy < uint32_t(m_dim); ++yy)
{
for (uint32_t xx = 0; xx < uint32_t(m_dim); ++xx)
{
float mtxR[16];
bx::mtxRotateXYZ(mtxR, time + xx*0.21f, time + yy*0.37f, time + yy*0.13f);
float mtx[16];
bx::mtxMul(mtx, mtxS, mtxR);
mtx[12] = pos[0] + float(xx)*step;
mtx[13] = pos[1] + float(yy)*step;
mtx[14] = pos[2] + float(zz)*step;
// Set model matrix for rendering.
encoder->setTransform(mtx);
// Set vertex and index buffer.
encoder->setVertexBuffer(0, m_vbh);
encoder->setIndexBuffer(m_ibh);
// Set render states.
encoder->setState(BGFX_STATE_DEFAULT);
// Submit primitive for rendering to view 0.
encoder->submit(0, m_program);
}
}
}
bgfx::end(encoder);
// Advance to next frame. Rendering thread will be kicked to
// process submitted rendering primitives.
bgfx::frame();
return true;
}
return false;
}
entry::MouseState m_mouseState;
uint32_t m_width;
uint32_t m_height;
uint32_t m_debug;
uint32_t m_reset;
bool m_autoAdjust;
int32_t m_scrollArea;
int32_t m_dim;
int32_t m_maxDim;
int32_t m_transform;
int64_t m_timeOffset;
int64_t m_deltaTimeNs;
int64_t m_deltaTimeAvgNs;
int64_t m_numFrames;
bgfx::ProgramHandle m_program;
bgfx::VertexBufferHandle m_vbh;
bgfx::IndexBufferHandle m_ibh;
};
} // namespace
ENTRY_IMPLEMENT_MAIN(ExampleDrawStress, "17-drawstress", "Draw stress, maximizing number of draw calls.");
<|endoftext|>
|
<commit_before>// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <Rmath.h>
#include <vector>
#include <cassert>
#include "vmat.h"
#include "gmat.h"
#include "DataPairs.h"
#include "quadrule.h"
#include "pn.h"
#include "functions.h"
using namespace Rcpp;
using namespace arma;
using namespace std;
const double twopi = 2*datum::pi;
/////////////////////////////////////////////////////////////////////////////////////////////////
/* Full loglikelihood */
double loglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaCond, vmat sigmaU, vec u, bool full=1){
data.pi_gen(row, u); // Estimation of pi based on u
irowvec causes = data.causes_get(row); // Failure causes for pair in question
double res = 0; // Initialising output (loglik contribution)
if ((causes(0) > 0) & (causes(1) > 0)){
/* Both individuals experience failure */
res = logdF2(row, causes, data, sigmaJoint, u);
}
else if((causes(0) <= 0) & (causes(1) <= 0)){
/* Neither individual experience failure */
if ((causes(0) < 0) & (causes(1) < 0)){
// Full follow-up for both individuals
for (unsigned i=1; i<=2; i++){ // Over individuals
double lik = 1;
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double prob = F1(row, j, i, data);
lik -= prob;
}
res += log(lik);
}
}
else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){
// Full follow-up for only one individual
for (unsigned i=1; i<=2; i++){ // Over individuals
double lik = 1;
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
if (causes(i-1) < 0){
double prob = F1(row, j, i, data);
lik -= prob;
}
else {
double prob = F1(row, j, i, data, sigmaMarg, u);
lik -= prob;
}
}
res += log(lik);
}
}
else {
// Full follow-up for neither individual
double lik = 1;
// Marginal probabilities
for (unsigned i=1; i<=2; i++){ // Over individuals
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double prob = F1(row, j, i, data, sigmaMarg, u);
lik -= prob; // Subtracting
}
}
// Bivariate probabilities
for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes
for (unsigned l=1; l<=data.ncauses; l++){
irowvec vcauses(2);
vcauses(0) = k; vcauses(1) = l;
double prob = F2(row, vcauses, data, sigmaJoint, u);
lik += prob; // Adding
}
}
res = log(lik);
}
}
else {
/* One individual experiences failure the other does not */
for (unsigned i=1; i<=2; i++){ // Over individuals
unsigned cause = causes(i-1);
if (cause > 0){
// Marginal probability of failure
res += logdF1(row, cause, i, data, sigmaMarg, u);
}
else {
// Marginal probability of no failure
unsigned cond_cause;
if (i==1){
cond_cause = causes(1);
}
else {
cond_cause = causes(0);
}
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double lik = 1;
if (cause < 0){
// Unconditional
double prob = F1(row, j, i, data);
lik -= prob;
}
else {
// Conditional
double prob = F1(row, j, i, cond_cause, data, sigmaCond, u);
lik -= prob;
}
res += log(lik);
}
}
}
}
/* Contribution from u */
if (full){
vmat sig = sigmaU; // Variance-covariance matrix of u
double inner = as_scalar(u*sig.inv*u.t());
// PDF of u
double logpdfu = log(pow(twopi,-(data.ncauses/2))) + sig.loginvsqdet - 0.5*inner;
// Adding to the loglik
res += logpdfu;
}
/* Return */
return(res);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/* Score function of full loglikelihood */
rowvec Dloglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaCond, vmat sigmaU, vec u, bool full=1){
/* Estimation of pi, dpidu and dlogpidu */
data.pi_gen(row, u);
data.dpidu_gen(row, u);
data.dlogpidu_gen(row, u);
irowvec causes = data.causes_get(row); // Failure causes for pair in question
rowvec res = zeros<rowvec>(data.ncauses); // Initialising output (score contribution)
if ((causes(0) > 0) & (causes(1) > 0)){
/* Both individuals experience failure */
res = dlogdF2du(row, causes, data, sigmaJoint, u);
}
else if((causes(0) <= 0) & (causes(1) <= 0)){
/* Neither individual experience failure */
if ((causes(0) < 0) & (causes(1) < 0)){
// Full follow-up for both individuals
for (unsigned i=1; i<=2; i++){ // Over individuals
double lik = 1;
rowvec likdu = zeros<rowvec>(data.ncauses);
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double prob = F1(row, j, i, data);
rowvec probdu = dF1du(row, j, i, data);
lik -= prob;
likdu -= probdu;
}
res += (1/lik)*likdu;
}
}
else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){
// Full follow-up for only one individual
for (unsigned i=1; i<=2; i++){ // Over individuals
double lik = 1;
rowvec likdu = zeros<rowvec>(data.ncauses);
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
if (causes(i-1) < 0){
double prob = F1(row, j, i, data);
rowvec probdu = dF1du(row, j, i, data);
lik -= prob;
likdu -= probdu;
}
else {
double prob = F1(row, j, i, data, sigmaMarg, u);
rowvec probdu = dF1du(row, j, i, data, sigmaMarg, u);
lik -= prob;
likdu -= probdu;
}
}
res += (1/lik)*likdu;
}
}
else {
// Full follow-up for neither individual
double lik = 1;
rowvec likdu = zeros<rowvec>(data.ncauses);
// Marginal probabilities
for (unsigned i=1; i<=2; i++){ // Over individuals
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double prob = F1(row, j, i, data, sigmaMarg, u);
rowvec probdu = dF1du(row, j, i, data, sigmaMarg, u);
lik -= prob; // Subtracting
likdu -= probdu;
}
}
// Bivariate probabilities
for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes
for (unsigned l=1; l<=data.ncauses; l++){
irowvec vcauses(2);
vcauses(0) = k; vcauses(1) = l;
double prob = F2(row, vcauses, data, sigmaJoint, u);
rowvec probdu = dF2du(row, vcauses, data, sigmaJoint, u);
lik += prob; // Adding
likdu += probdu;
}
}
res = (1/lik)*likdu;
}
}
else {
/* One individual experiences failure the other does not */
for (unsigned i=1; i<=2; i++){ // Over individuals
unsigned cause = causes(i-1);
if (cause > 0){
// Marginal probability of failure
res += dlogdF1du(row, cause, i, data, sigmaMarg, u);
}
else {
// Marginal probability of no failure
unsigned cond_cause;
if (i==1){
cond_cause = causes(1);
}
else {
cond_cause = causes(0);
}
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double lik = 1;
rowvec likdu = zeros<rowvec>(data.ncauses);
if (cause < 0){ // Uncondtional
double prob = F1(row, j, i, data);
rowvec probdu = dF1du(row, j, i, data);
lik -= prob;
likdu -= probdu;
}
else { // Conditional
double prob = F1(row, j, i, cond_cause, data, sigmaCond, u);
rowvec probdu = dF1du(row, j, i, cond_cause, data, sigmaCond, u);
lik -= prob;
likdu -= probdu;
}
res += (1/lik)*likdu;
}
}
}
}
/* Contribution from u */
if (full){
vmat sig = sigmaU; // Variance-covariance matrix etc. of u
// Adding to the score
res += -u.t()*sig.inv;
};
return(res);
}
/////////////////////////////////////////////////////////////////////////////
// FOR TESTING
double loglikout(mat sigma, vec u, int ncauses, imat causes, mat alpha, mat dalpha, mat beta, mat gamma){
// Initialising gmats of sigma (Joint, Cond)
gmat sigmaJoint = gmat(ncauses, ncauses);
gmat sigmaCond = gmat(ncauses, ncauses);
gmat sigmaMarg = gmat(ncauses, 1);
// Vectors for extracting rows and columns from sigma
uvec rcJ(2); /* for joint */
uvec rc1(1); /* for conditional */
uvec rc2(ncauses+1); /* for conditional */
uvec rcu(ncauses);
for (int h=0; h<ncauses; h++){
rcu(h) = ncauses + h;
};
// Calculating and setting sigmaJoint
for (int h=0; h<ncauses; h++){
for (int i=0; i<ncauses; i++){
rcJ(0)=h;
rcJ(1)=ncauses+i;
vmat x = vmat(sigma, rcJ, rcu);
sigmaJoint.set(h,i,x);
};
};
// Calculating and setting sigmaMarg
for (int h=0; h<ncauses; h++){
rc1(0) = h;
vmat x = vmat(sigma, rc1, rcu);
sigmaMarg.set(h,1,x);
};
// Calculating and setting sigmaCond
for (int h=0; h<ncauses; h++){
for (int i=0; i<ncauses; i++){
rc1(0) = h;
rc2(0) = i;
for (int j=0; j<ncauses; j++){
rc2(j+1) = rcu(j);
};
vmat x = vmat(sigma, rc1, rc2);
sigmaCond.set(h,i,x);
};
};
// vmat of the us
mat matU = sigma.submat(rcu,rcu);
vmat sigmaU = vmat(matU);
// Generating DataPairs
DataPairs data = DataPairs(ncauses, causes, alpha, dalpha, beta, gamma);
unsigned row = 1;
// Estimating likelihood contribution
double loglik = loglikfull(row, data, sigmaMarg, sigmaJoint, sigmaCond, sigmaU, u);
// Return
return loglik;
};
//rowvec Dloglikout(unsigned row, mat sigma, mat data, vec u){
// Generating gmats of sigma (Marg, Joint, MargCond, sigU)
// Generating DataPairs
// Estimating score contribution
// rowvec score = Dloglikfull(unsigned row, DataPairs data, gmat sigmaJoint, gmat sigmaMargCond, vmat sigmaU, vec u, bool full=1);
// Return
// return score;
//};
<commit_msg>export<commit_after>// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <Rmath.h>
#include <vector>
#include <cassert>
#include "vmat.h"
#include "gmat.h"
#include "DataPairs.h"
#include "quadrule.h"
#include "pn.h"
#include "functions.h"
using namespace Rcpp;
using namespace arma;
using namespace std;
const double twopi = 2*datum::pi;
/////////////////////////////////////////////////////////////////////////////////////////////////
/* Full loglikelihood */
double loglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaCond, vmat sigmaU, vec u, bool full=1){
data.pi_gen(row, u); // Estimation of pi based on u
irowvec causes = data.causes_get(row); // Failure causes for pair in question
double res = 0; // Initialising output (loglik contribution)
if ((causes(0) > 0) & (causes(1) > 0)){
/* Both individuals experience failure */
res = logdF2(row, causes, data, sigmaJoint, u);
}
else if((causes(0) <= 0) & (causes(1) <= 0)){
/* Neither individual experience failure */
if ((causes(0) < 0) & (causes(1) < 0)){
// Full follow-up for both individuals
for (unsigned i=1; i<=2; i++){ // Over individuals
double lik = 1;
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double prob = F1(row, j, i, data);
lik -= prob;
}
res += log(lik);
}
}
else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){
// Full follow-up for only one individual
for (unsigned i=1; i<=2; i++){ // Over individuals
double lik = 1;
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
if (causes(i-1) < 0){
double prob = F1(row, j, i, data);
lik -= prob;
}
else {
double prob = F1(row, j, i, data, sigmaMarg, u);
lik -= prob;
}
}
res += log(lik);
}
}
else {
// Full follow-up for neither individual
double lik = 1;
// Marginal probabilities
for (unsigned i=1; i<=2; i++){ // Over individuals
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double prob = F1(row, j, i, data, sigmaMarg, u);
lik -= prob; // Subtracting
}
}
// Bivariate probabilities
for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes
for (unsigned l=1; l<=data.ncauses; l++){
irowvec vcauses(2);
vcauses(0) = k; vcauses(1) = l;
double prob = F2(row, vcauses, data, sigmaJoint, u);
lik += prob; // Adding
}
}
res = log(lik);
}
}
else {
/* One individual experiences failure the other does not */
for (unsigned i=1; i<=2; i++){ // Over individuals
unsigned cause = causes(i-1);
if (cause > 0){
// Marginal probability of failure
res += logdF1(row, cause, i, data, sigmaMarg, u);
}
else {
// Marginal probability of no failure
unsigned cond_cause;
if (i==1){
cond_cause = causes(1);
}
else {
cond_cause = causes(0);
}
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double lik = 1;
if (cause < 0){
// Unconditional
double prob = F1(row, j, i, data);
lik -= prob;
}
else {
// Conditional
double prob = F1(row, j, i, cond_cause, data, sigmaCond, u);
lik -= prob;
}
res += log(lik);
}
}
}
}
/* Contribution from u */
if (full){
vmat sig = sigmaU; // Variance-covariance matrix of u
double inner = as_scalar(u*sig.inv*u.t());
// PDF of u
double logpdfu = log(pow(twopi,-(data.ncauses/2))) + sig.loginvsqdet - 0.5*inner;
// Adding to the loglik
res += logpdfu;
}
/* Return */
return(res);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/* Score function of full loglikelihood */
rowvec Dloglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaCond, vmat sigmaU, vec u, bool full=1){
/* Estimation of pi, dpidu and dlogpidu */
data.pi_gen(row, u);
data.dpidu_gen(row, u);
data.dlogpidu_gen(row, u);
irowvec causes = data.causes_get(row); // Failure causes for pair in question
rowvec res = zeros<rowvec>(data.ncauses); // Initialising output (score contribution)
if ((causes(0) > 0) & (causes(1) > 0)){
/* Both individuals experience failure */
res = dlogdF2du(row, causes, data, sigmaJoint, u);
}
else if((causes(0) <= 0) & (causes(1) <= 0)){
/* Neither individual experience failure */
if ((causes(0) < 0) & (causes(1) < 0)){
// Full follow-up for both individuals
for (unsigned i=1; i<=2; i++){ // Over individuals
double lik = 1;
rowvec likdu = zeros<rowvec>(data.ncauses);
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double prob = F1(row, j, i, data);
rowvec probdu = dF1du(row, j, i, data);
lik -= prob;
likdu -= probdu;
}
res += (1/lik)*likdu;
}
}
else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){
// Full follow-up for only one individual
for (unsigned i=1; i<=2; i++){ // Over individuals
double lik = 1;
rowvec likdu = zeros<rowvec>(data.ncauses);
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
if (causes(i-1) < 0){
double prob = F1(row, j, i, data);
rowvec probdu = dF1du(row, j, i, data);
lik -= prob;
likdu -= probdu;
}
else {
double prob = F1(row, j, i, data, sigmaMarg, u);
rowvec probdu = dF1du(row, j, i, data, sigmaMarg, u);
lik -= prob;
likdu -= probdu;
}
}
res += (1/lik)*likdu;
}
}
else {
// Full follow-up for neither individual
double lik = 1;
rowvec likdu = zeros<rowvec>(data.ncauses);
// Marginal probabilities
for (unsigned i=1; i<=2; i++){ // Over individuals
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double prob = F1(row, j, i, data, sigmaMarg, u);
rowvec probdu = dF1du(row, j, i, data, sigmaMarg, u);
lik -= prob; // Subtracting
likdu -= probdu;
}
}
// Bivariate probabilities
for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes
for (unsigned l=1; l<=data.ncauses; l++){
irowvec vcauses(2);
vcauses(0) = k; vcauses(1) = l;
double prob = F2(row, vcauses, data, sigmaJoint, u);
rowvec probdu = dF2du(row, vcauses, data, sigmaJoint, u);
lik += prob; // Adding
likdu += probdu;
}
}
res = (1/lik)*likdu;
}
}
else {
/* One individual experiences failure the other does not */
for (unsigned i=1; i<=2; i++){ // Over individuals
unsigned cause = causes(i-1);
if (cause > 0){
// Marginal probability of failure
res += dlogdF1du(row, cause, i, data, sigmaMarg, u);
}
else {
// Marginal probability of no failure
unsigned cond_cause;
if (i==1){
cond_cause = causes(1);
}
else {
cond_cause = causes(0);
}
for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes
double lik = 1;
rowvec likdu = zeros<rowvec>(data.ncauses);
if (cause < 0){ // Uncondtional
double prob = F1(row, j, i, data);
rowvec probdu = dF1du(row, j, i, data);
lik -= prob;
likdu -= probdu;
}
else { // Conditional
double prob = F1(row, j, i, cond_cause, data, sigmaCond, u);
rowvec probdu = dF1du(row, j, i, cond_cause, data, sigmaCond, u);
lik -= prob;
likdu -= probdu;
}
res += (1/lik)*likdu;
}
}
}
}
/* Contribution from u */
if (full){
vmat sig = sigmaU; // Variance-covariance matrix etc. of u
// Adding to the score
res += -u.t()*sig.inv;
};
return(res);
}
/////////////////////////////////////////////////////////////////////////////
// FOR TESTING
// [[Rcpp::export]]
double loglikout(mat sigma, vec u, int ncauses, imat causes, mat alpha, mat dalpha, mat beta, mat gamma){
// Initialising gmats of sigma (Joint, Cond)
gmat sigmaJoint = gmat(ncauses, ncauses);
gmat sigmaCond = gmat(ncauses, ncauses);
gmat sigmaMarg = gmat(ncauses, 1);
// Vectors for extracting rows and columns from sigma
uvec rcJ(2); /* for joint */
uvec rc1(1); /* for conditional */
uvec rc2(ncauses+1); /* for conditional */
uvec rcu(ncauses);
for (int h=0; h<ncauses; h++){
rcu(h) = ncauses + h;
};
// Calculating and setting sigmaJoint
for (int h=0; h<ncauses; h++){
for (int i=0; i<ncauses; i++){
rcJ(0)=h;
rcJ(1)=ncauses+i;
vmat x = vmat(sigma, rcJ, rcu);
sigmaJoint.set(h,i,x);
};
};
// Calculating and setting sigmaMarg
for (int h=0; h<ncauses; h++){
rc1(0) = h;
vmat x = vmat(sigma, rc1, rcu);
sigmaMarg.set(h,1,x);
};
// Calculating and setting sigmaCond
for (int h=0; h<ncauses; h++){
for (int i=0; i<ncauses; i++){
rc1(0) = h;
rc2(0) = i;
for (int j=0; j<ncauses; j++){
rc2(j+1) = rcu(j);
};
vmat x = vmat(sigma, rc1, rc2);
sigmaCond.set(h,i,x);
};
};
// vmat of the us
mat matU = sigma.submat(rcu,rcu);
vmat sigmaU = vmat(matU);
// Generating DataPairs
DataPairs data = DataPairs(ncauses, causes, alpha, dalpha, beta, gamma);
unsigned row = 1;
// Estimating likelihood contribution
double loglik = loglikfull(row, data, sigmaMarg, sigmaJoint, sigmaCond, sigmaU, u);
// Return
return loglik;
};
//rowvec Dloglikout(unsigned row, mat sigma, mat data, vec u){
// Generating gmats of sigma (Marg, Joint, MargCond, sigU)
// Generating DataPairs
// Estimating score contribution
// rowvec score = Dloglikfull(unsigned row, DataPairs data, gmat sigmaJoint, gmat sigmaMargCond, vmat sigmaU, vec u, bool full=1);
// Return
// return score;
//};
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
*/
extern "C" {
#include <ovsdb_wrapper.h>
};
#include <cmn/agent.h>
#include <oper/vn.h>
#include <oper/vxlan.h>
#include <oper/physical_device_vn.h>
#include <ovs_tor_agent/tor_agent_init.h>
#include <ovsdb_client.h>
#include <ovsdb_client_idl.h>
#include <ovsdb_client_session.h>
#include <base/util.h>
#include <net/mac_address.h>
#include <oper/agent_sandesh.h>
#include <ovsdb_types.h>
#include <ovsdb_route_peer.h>
#include <logical_switch_ovsdb.h>
#include <unicast_mac_local_ovsdb.h>
using OVSDB::UnicastMacLocalOvsdb;
using OVSDB::UnicastMacLocalEntry;
using OVSDB::OvsdbClientSession;
using std::string;
UnicastMacLocalEntry::UnicastMacLocalEntry(UnicastMacLocalOvsdb *table,
const UnicastMacLocalEntry *key) : OvsdbEntry(table), mac_(key->mac_),
logical_switch_name_(key->logical_switch_name_), dest_ip_(key->dest_ip_) {
}
UnicastMacLocalEntry::UnicastMacLocalEntry(UnicastMacLocalOvsdb *table,
struct ovsdb_idl_row *row) : OvsdbEntry(table),
mac_(ovsdb_wrapper_ucast_mac_local_mac(row)),
logical_switch_name_(ovsdb_wrapper_ucast_mac_local_logical_switch(row)),
dest_ip_() {
if (ovsdb_wrapper_ucast_mac_local_dst_ip(row))
dest_ip_ = ovsdb_wrapper_ucast_mac_local_dst_ip(row);
}
UnicastMacLocalEntry::~UnicastMacLocalEntry() {
}
bool UnicastMacLocalEntry::Add() {
UnicastMacLocalOvsdb *table = static_cast<UnicastMacLocalOvsdb *>(table_);
OVSDB_TRACE(Trace, "Adding Route " + mac_ + " VN uuid " +
logical_switch_name_ + " destination IP " + dest_ip_);
LogicalSwitchTable *l_table = table_->client_idl()->logical_switch_table();
LogicalSwitchEntry l_key(l_table, logical_switch_name_.c_str());
LogicalSwitchEntry *ls_entry =
static_cast<LogicalSwitchEntry *>(l_table->Find(&l_key));
const PhysicalDeviceVn *dev_vn =
static_cast<const PhysicalDeviceVn *>(ls_entry->GetDBEntry());
vrf_ = dev_vn->vn()->GetVrf();
vxlan_id_ = dev_vn->vn()->vxlan_id()->vxlan_id();
boost::system::error_code err;
Ip4Address dest = Ip4Address::from_string(dest_ip_, err);
table->peer()->AddOvsRoute(dev_vn->vn(), MacAddress(mac_), dest);
return true;
}
bool UnicastMacLocalEntry::Delete() {
UnicastMacLocalOvsdb *table = static_cast<UnicastMacLocalOvsdb *>(table_);
OVSDB_TRACE(Trace, "Deleting Route " + mac_ + " VN uuid " +
logical_switch_name_ + " destination IP " + dest_ip_);
table->peer()->DeleteOvsRoute(vrf_, vxlan_id_, MacAddress(mac_));
return true;
}
bool UnicastMacLocalEntry::IsLess(const KSyncEntry& entry) const {
const UnicastMacLocalEntry &ucast =
static_cast<const UnicastMacLocalEntry&>(entry);
if (mac_ != ucast.mac_)
return mac_ < ucast.mac_;
return logical_switch_name_ < ucast.logical_switch_name_;
}
KSyncEntry *UnicastMacLocalEntry::UnresolvedReference() {
LogicalSwitchTable *l_table = table_->client_idl()->logical_switch_table();
LogicalSwitchEntry key(l_table, logical_switch_name_.c_str());
LogicalSwitchEntry *l_switch =
static_cast<LogicalSwitchEntry *>(l_table->GetReference(&key));
if (!l_switch->IsResolved()) {
return l_switch;
}
return NULL;
}
const std::string &UnicastMacLocalEntry::mac() const {
return mac_;
}
const std::string &UnicastMacLocalEntry::logical_switch_name() const {
return logical_switch_name_;
}
const std::string &UnicastMacLocalEntry::dest_ip() const {
return dest_ip_;
}
UnicastMacLocalOvsdb::UnicastMacLocalOvsdb(OvsdbClientIdl *idl, OvsPeer *peer) :
OvsdbObject(idl), peer_(peer) {
idl->Register(OvsdbClientIdl::OVSDB_UCAST_MAC_LOCAL,
boost::bind(&UnicastMacLocalOvsdb::Notify, this, _1, _2));
}
UnicastMacLocalOvsdb::~UnicastMacLocalOvsdb() {
client_idl_->UnRegister(OvsdbClientIdl::OVSDB_UCAST_MAC_LOCAL);
}
OvsPeer *UnicastMacLocalOvsdb::peer() {
return peer_;
}
void UnicastMacLocalOvsdb::Notify(OvsdbClientIdl::Op op,
struct ovsdb_idl_row *row) {
const char *ls_name = ovsdb_wrapper_ucast_mac_local_logical_switch(row);
const char *dest_ip = ovsdb_wrapper_ucast_mac_local_dst_ip(row);
/* ignore if ls_name is not present */
if (ls_name == NULL) {
return;
}
UnicastMacLocalEntry key(this, row);
UnicastMacLocalEntry *entry =
static_cast<UnicastMacLocalEntry *>(FindActiveEntry(&key));
/* trigger delete if dest ip is not available */
if (op == OvsdbClientIdl::OVSDB_DEL || dest_ip == NULL) {
if (entry != NULL) {
Delete(entry);
}
} else if (op == OvsdbClientIdl::OVSDB_ADD) {
if (entry == NULL) {
entry = static_cast<UnicastMacLocalEntry *>(Create(&key));
}
} else {
assert(0);
}
}
KSyncEntry *UnicastMacLocalOvsdb::Alloc(const KSyncEntry *key, uint32_t index) {
const UnicastMacLocalEntry *k_entry =
static_cast<const UnicastMacLocalEntry *>(key);
UnicastMacLocalEntry *entry = new UnicastMacLocalEntry(this, k_entry);
return entry;
}
/////////////////////////////////////////////////////////////////////////////
// Sandesh routines
/////////////////////////////////////////////////////////////////////////////
class UnicastMacLocalSandeshTask : public Task {
public:
UnicastMacLocalSandeshTask(std::string resp_ctx) :
Task((TaskScheduler::GetInstance()->GetTaskId("Agent::KSync")), -1),
resp_(new OvsdbUnicastMacLocalResp()), resp_data_(resp_ctx) {
}
virtual ~UnicastMacLocalSandeshTask() {}
virtual bool Run() {
std::vector<OvsdbUnicastMacLocalEntry> macs;
TorAgentInit *init =
static_cast<TorAgentInit *>(Agent::GetInstance()->agent_init());
OvsdbClientSession *session = init->ovsdb_client()->next_session(NULL);
UnicastMacLocalOvsdb *table =
session->client_idl()->unicast_mac_local_ovsdb();
UnicastMacLocalEntry *entry =
static_cast<UnicastMacLocalEntry *>(table->Next(NULL));
while (entry != NULL) {
OvsdbUnicastMacLocalEntry oentry;
oentry.set_state(entry->StateString());
oentry.set_mac(entry->mac());
oentry.set_logical_switch(entry->logical_switch_name());
oentry.set_dest_ip(entry->dest_ip());
macs.push_back(oentry);
entry = static_cast<UnicastMacLocalEntry *>(table->Next(entry));
}
resp_->set_macs(macs);
SendResponse();
return true;
}
private:
void SendResponse() {
resp_->set_context(resp_data_);
resp_->set_more(false);
resp_->Response();
}
OvsdbUnicastMacLocalResp *resp_;
std::string resp_data_;
DISALLOW_COPY_AND_ASSIGN(UnicastMacLocalSandeshTask);
};
void OvsdbUnicastMacLocalReq::HandleRequest() const {
UnicastMacLocalSandeshTask *task = new UnicastMacLocalSandeshTask(context());
TaskScheduler *scheduler = TaskScheduler::GetInstance();
scheduler->Enqueue(task);
}
<commit_msg>change to use right API to get VXlan id<commit_after>/*
* Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
*/
extern "C" {
#include <ovsdb_wrapper.h>
};
#include <cmn/agent.h>
#include <oper/vn.h>
#include <oper/vxlan.h>
#include <oper/physical_device_vn.h>
#include <ovs_tor_agent/tor_agent_init.h>
#include <ovsdb_client.h>
#include <ovsdb_client_idl.h>
#include <ovsdb_client_session.h>
#include <base/util.h>
#include <net/mac_address.h>
#include <oper/agent_sandesh.h>
#include <ovsdb_types.h>
#include <ovsdb_route_peer.h>
#include <logical_switch_ovsdb.h>
#include <unicast_mac_local_ovsdb.h>
using OVSDB::UnicastMacLocalOvsdb;
using OVSDB::UnicastMacLocalEntry;
using OVSDB::OvsdbClientSession;
using std::string;
UnicastMacLocalEntry::UnicastMacLocalEntry(UnicastMacLocalOvsdb *table,
const UnicastMacLocalEntry *key) : OvsdbEntry(table), mac_(key->mac_),
logical_switch_name_(key->logical_switch_name_), dest_ip_(key->dest_ip_) {
}
UnicastMacLocalEntry::UnicastMacLocalEntry(UnicastMacLocalOvsdb *table,
struct ovsdb_idl_row *row) : OvsdbEntry(table),
mac_(ovsdb_wrapper_ucast_mac_local_mac(row)),
logical_switch_name_(ovsdb_wrapper_ucast_mac_local_logical_switch(row)),
dest_ip_() {
if (ovsdb_wrapper_ucast_mac_local_dst_ip(row))
dest_ip_ = ovsdb_wrapper_ucast_mac_local_dst_ip(row);
}
UnicastMacLocalEntry::~UnicastMacLocalEntry() {
}
bool UnicastMacLocalEntry::Add() {
UnicastMacLocalOvsdb *table = static_cast<UnicastMacLocalOvsdb *>(table_);
OVSDB_TRACE(Trace, "Adding Route " + mac_ + " VN uuid " +
logical_switch_name_ + " destination IP " + dest_ip_);
LogicalSwitchTable *l_table = table_->client_idl()->logical_switch_table();
LogicalSwitchEntry l_key(l_table, logical_switch_name_.c_str());
LogicalSwitchEntry *ls_entry =
static_cast<LogicalSwitchEntry *>(l_table->Find(&l_key));
const PhysicalDeviceVn *dev_vn =
static_cast<const PhysicalDeviceVn *>(ls_entry->GetDBEntry());
vrf_ = dev_vn->vn()->GetVrf();
vxlan_id_ = dev_vn->vn()->GetVxLanId();
boost::system::error_code err;
Ip4Address dest = Ip4Address::from_string(dest_ip_, err);
table->peer()->AddOvsRoute(dev_vn->vn(), MacAddress(mac_), dest);
return true;
}
bool UnicastMacLocalEntry::Delete() {
UnicastMacLocalOvsdb *table = static_cast<UnicastMacLocalOvsdb *>(table_);
OVSDB_TRACE(Trace, "Deleting Route " + mac_ + " VN uuid " +
logical_switch_name_ + " destination IP " + dest_ip_);
table->peer()->DeleteOvsRoute(vrf_, vxlan_id_, MacAddress(mac_));
return true;
}
bool UnicastMacLocalEntry::IsLess(const KSyncEntry& entry) const {
const UnicastMacLocalEntry &ucast =
static_cast<const UnicastMacLocalEntry&>(entry);
if (mac_ != ucast.mac_)
return mac_ < ucast.mac_;
return logical_switch_name_ < ucast.logical_switch_name_;
}
KSyncEntry *UnicastMacLocalEntry::UnresolvedReference() {
LogicalSwitchTable *l_table = table_->client_idl()->logical_switch_table();
LogicalSwitchEntry key(l_table, logical_switch_name_.c_str());
LogicalSwitchEntry *l_switch =
static_cast<LogicalSwitchEntry *>(l_table->GetReference(&key));
if (!l_switch->IsResolved()) {
return l_switch;
}
return NULL;
}
const std::string &UnicastMacLocalEntry::mac() const {
return mac_;
}
const std::string &UnicastMacLocalEntry::logical_switch_name() const {
return logical_switch_name_;
}
const std::string &UnicastMacLocalEntry::dest_ip() const {
return dest_ip_;
}
UnicastMacLocalOvsdb::UnicastMacLocalOvsdb(OvsdbClientIdl *idl, OvsPeer *peer) :
OvsdbObject(idl), peer_(peer) {
idl->Register(OvsdbClientIdl::OVSDB_UCAST_MAC_LOCAL,
boost::bind(&UnicastMacLocalOvsdb::Notify, this, _1, _2));
}
UnicastMacLocalOvsdb::~UnicastMacLocalOvsdb() {
client_idl_->UnRegister(OvsdbClientIdl::OVSDB_UCAST_MAC_LOCAL);
}
OvsPeer *UnicastMacLocalOvsdb::peer() {
return peer_;
}
void UnicastMacLocalOvsdb::Notify(OvsdbClientIdl::Op op,
struct ovsdb_idl_row *row) {
const char *ls_name = ovsdb_wrapper_ucast_mac_local_logical_switch(row);
const char *dest_ip = ovsdb_wrapper_ucast_mac_local_dst_ip(row);
/* ignore if ls_name is not present */
if (ls_name == NULL) {
return;
}
UnicastMacLocalEntry key(this, row);
UnicastMacLocalEntry *entry =
static_cast<UnicastMacLocalEntry *>(FindActiveEntry(&key));
/* trigger delete if dest ip is not available */
if (op == OvsdbClientIdl::OVSDB_DEL || dest_ip == NULL) {
if (entry != NULL) {
Delete(entry);
}
} else if (op == OvsdbClientIdl::OVSDB_ADD) {
if (entry == NULL) {
entry = static_cast<UnicastMacLocalEntry *>(Create(&key));
}
} else {
assert(0);
}
}
KSyncEntry *UnicastMacLocalOvsdb::Alloc(const KSyncEntry *key, uint32_t index) {
const UnicastMacLocalEntry *k_entry =
static_cast<const UnicastMacLocalEntry *>(key);
UnicastMacLocalEntry *entry = new UnicastMacLocalEntry(this, k_entry);
return entry;
}
/////////////////////////////////////////////////////////////////////////////
// Sandesh routines
/////////////////////////////////////////////////////////////////////////////
class UnicastMacLocalSandeshTask : public Task {
public:
UnicastMacLocalSandeshTask(std::string resp_ctx) :
Task((TaskScheduler::GetInstance()->GetTaskId("Agent::KSync")), -1),
resp_(new OvsdbUnicastMacLocalResp()), resp_data_(resp_ctx) {
}
virtual ~UnicastMacLocalSandeshTask() {}
virtual bool Run() {
std::vector<OvsdbUnicastMacLocalEntry> macs;
TorAgentInit *init =
static_cast<TorAgentInit *>(Agent::GetInstance()->agent_init());
OvsdbClientSession *session = init->ovsdb_client()->next_session(NULL);
UnicastMacLocalOvsdb *table =
session->client_idl()->unicast_mac_local_ovsdb();
UnicastMacLocalEntry *entry =
static_cast<UnicastMacLocalEntry *>(table->Next(NULL));
while (entry != NULL) {
OvsdbUnicastMacLocalEntry oentry;
oentry.set_state(entry->StateString());
oentry.set_mac(entry->mac());
oentry.set_logical_switch(entry->logical_switch_name());
oentry.set_dest_ip(entry->dest_ip());
macs.push_back(oentry);
entry = static_cast<UnicastMacLocalEntry *>(table->Next(entry));
}
resp_->set_macs(macs);
SendResponse();
return true;
}
private:
void SendResponse() {
resp_->set_context(resp_data_);
resp_->set_more(false);
resp_->Response();
}
OvsdbUnicastMacLocalResp *resp_;
std::string resp_data_;
DISALLOW_COPY_AND_ASSIGN(UnicastMacLocalSandeshTask);
};
void OvsdbUnicastMacLocalReq::HandleRequest() const {
UnicastMacLocalSandeshTask *task = new UnicastMacLocalSandeshTask(context());
TaskScheduler *scheduler = TaskScheduler::GetInstance();
scheduler->Enqueue(task);
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2013-2018 Ubidots.
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.
Developed and maintained by Jose Garcia and Cristian Arrieta for IoT Services
Inc
@jotathebest at github: https://github.com/jotathebest
@crisap94 at github: https://github.com/crisap94
*/
#include "UbiTcp.h"
/**************************************************************************
* Overloaded constructors
***************************************************************************/
/**
* @brief Construct a new UbiTCP object and power up the module
*
* @param token Users token
* @param server Server addres
* @param port Server port
* @param user_agent Reference from the device being connected
* @param apn GPRS network name
* @param apnUser GPRS network username
* @param apnPass GPRS network passwrod
*/
UbiTCP::UbiTCP(UbiToken token, UbiServer server, const int port, const char *user_agent, UbiApn apn, UbiApn apnUser,
UbiApn apnPass) {
_server = server;
_user_agent = user_agent;
_token = token;
_port = port;
_apn = apn;
_apnUser = apnUser;
_apnPass = apnPass;
_client_tcp = GPRS::getInstance() == NULL ? new GPRS(RX, TX, BAUDRATE) : GPRS::getInstance();
}
/**************************************************************************
* Destructor
***************************************************************************/
UbiTCP::~UbiTCP() {
delete[] _server;
delete[] _user_agent;
delete[] _token;
delete[] _apn;
delete[] _apnUser;
delete[] _apnPass;
free(_client_tcp);
}
/**************************************************************************
* Cloud Functions
***************************************************************************/
/**
* @brief Post new data to ubidots server
*
* @param device_label Label of the device to be set or update in the ubidots
* platform
* @param device_name Device name to be published
* @param payload Body to be processed by the Ubidot server
* @return true The data was succesfully published
* @return false Something went wrong with the sending.
*/
bool UbiTCP::sendData(const char *device_label, const char *device_name, char *payload) {
if (!_preConnectionChecks()) {
return false;
}
_client_tcp->send(payload);
/* Parses the host answer, returns true if it is 'Ok' */
char *response = (char *)malloc(sizeof(char) * MAX_BUFFER_SIZE);
float value = _parseTCPAnswer("POST", response);
free(response);
if (value != ERROR_VALUE) {
_client_tcp->close();
_client_tcp->disconnect();
return true;
}
return false;
}
/**
* @brief Get request over TCP to Ubidots server
*
* @param device_label device label of the device
* @param variable_label variable label to be fetched
* @return float Response value from the server
*/
float UbiTCP::get(const char *device_label, const char *variable_label) {
if (!_preConnectionChecks()) {
return ERROR_VALUE;
}
if (_debug) {
Serial.println(F("waiting to fetch..."));
}
uint16_t endpointLength = _endpointLength(device_label, variable_label);
char *endpoint = (char *)malloc(sizeof(char) * endpointLength + 1);
sprintf(endpoint, "%s|LV|%s|%s:%s|end HTTP/1.0\r\n\r\n", USER_AGENT, _token, device_label, variable_label);
_client_tcp->send(endpoint, endpointLength);
char *response = (char *)malloc(sizeof(char) * MAX_BUFFER_SIZE);
float value = _parseTCPAnswer("POST", response);
_client_tcp->close();
_client_tcp->disconnect();
delay(200);
free(endpoint);
free(response);
return value;
}
/**************************************************************************
* Auxiliar
***************************************************************************/
/**
* @brief Do the initialization of the device
*
* @return true The device is responding to the commands
* @return false The device is not reponding, probably bad Serial communication
*/
bool UbiTCP::_initGPRS() {
_guaranteePowerOn();
uint8_t attempts = 0;
bool flag = true;
if (_debug) {
Serial.print("Start TCP Connection...\r\n");
Serial.print("Initializing module...\r\n");
}
// use DHCP
while (!_client_tcp->init() && attempts < 5) {
delay(1000);
attempts += 1;
if (attempts == 5) {
flag = false;
break;
}
if (_debug) {
Serial.print("Checking Serial connection...\r\n");
}
}
return flag;
}
/**
* @brief Extablish the phisical connection with the GPRS network
*
* @return true The network is accepted by the device
* @return false The device could connect to it, probably the frequency
*/
bool UbiTCP::_isNetworkRegistered() {
uint8_t attempts = 0;
bool flag = true;
// use DHCP
while (!_client_tcp->isNetworkRegistered() && attempts < 5) {
delay(1000);
attempts += 1;
if (attempts == 5) {
flag = false;
break;
}
if (_debug) {
Serial.println(F("Network has not been registered yet!"));
}
}
if (_debug) {
Serial.println(F("Network has been registered into the module"));
}
return flag;
}
/**
* @brief The GPRS establish a new connection with the service
* TODO cast the _apn, _apnUser, _apnPass to the join method.
*
*/
bool UbiTCP::_isJoinedToNetwork() {
uint8_t attempts = 0;
bool flag = true;
bool isJoined = false;
// use DHCP
while (!isJoined && attempts < 5) {
isJoined = _client_tcp->join(_F(_apn), _F(_apnUser), _F(_apnPass));
delay(2000);
attempts += 1;
if (attempts == 1) {
if (_debug) {
Serial.print(F("Network status: "));
Serial.println(isJoined ? F("Joined") : F("Not Joined"));
Serial.println(F("Simcard Credentials"));
Serial.print(F("Apn: "));
Serial.println(_apn);
Serial.print(F("User: "));
Serial.println(_apnUser);
Serial.print(F("Pass: "));
Serial.println(_apnPass);
Serial.println();
}
}
if (_debug) {
Serial.print(F("Trying to join to the network ["));
Serial.print(attempts);
Serial.println(F("]"));
}
if (attempts == 5) {
if (_debug) {
Serial.println(F("[ERROR] Couldn't join the network\n\n"));
}
flag = false;
break;
}
}
if (_debug && flag) {
Serial.print(F("Network status: "));
Serial.println(isJoined ? F("Joined") : F("Not Joined"));
// successful DHCP
Serial.print(F("IP Address is "));
Serial.println(_client_tcp->getIPAddress());
if (!_checkIpAddress()) {
Serial.println(F("IpAddress NOT VALID!"));
_isJoinedToNetwork();
}
}
return flag;
}
/**
* @brief Check the Octecs from the IP Address to make a valid request for the
* IMEI, it splits the IP into tokes by the "." sparator, if there are 4 so it
* is ok
*
* @return true There a valid connection to internet
* @return false There is NOT a valid connection to internet
*/
bool UbiTCP::_checkIpAddress() {
char *ipAddress = _client_tcp->getIPAddress();
char *separator = ".";
char *octet;
uint8_t octecNumber = 0;
octet = strtok(ipAddress, separator);
while (octet != NULL) {
octecNumber += 1;
octet = strtok(NULL, separator);
}
if (octecNumber == 4) {
return true;
} else {
return false;
}
}
/**
* @brief Establish connection with Ubidots Server
*
* @return true Succesfull connection
* @return false Failed connection
*/
bool UbiTCP::_connectToServer() {
if (!_client_tcp->connect(TCP, UBI_INDUSTRIAL, UBIDOTS_TCP_PORT)) {
if (_debug) {
Serial.println(F("Error Connecting to Ubidots server"));
return false;
}
} else {
_server_connected = true;
if (_debug) {
Serial.println(F("Connection to Ubidots server success!"));
}
return true;
}
}
/**
* @brief Calculate the lenght of the enpoint to be send over TCP to the server
*
* @param device_label device label of the device
* @param variable_label variable label to be updated or fetched
* @return uint16_t Lenght of the enpoint
*/
uint16_t UbiTCP::_endpointLength(const char *device_label, const char *variable_label) {
uint16_t endpointLength = strlen("|LV||:|end HTTP/1.0\r\n\r\n") + strlen(USER_AGENT) + strlen(_token) +
strlen(device_label) + strlen(variable_label);
return endpointLength;
}
/**
* @brief Parse the TCP host answer and saves it to the input char pointer.
* @param request_type Type of request GET or POST
* @param response [Mandatory] Buffer to contain the payload from the server
* @return float Value from the response
*/
float UbiTCP::_parseTCPAnswer(const char *request_type, char *response) {
int j = 0;
if (_debug) {
Serial.println(F("----------"));
Serial.println(F("Server's response:"));
}
while (true) {
int ret = _client_tcp->recv(response, MAX_BUFFER_SIZE);
if (ret <= 0) {
if (_debug) {
Serial.println(F("fetch over..."));
}
break;
}
response[ret] = '\0';
if (_debug) {
Serial.print(F("Recv: "));
Serial.print(ret);
Serial.print(F(" bytes: "));
Serial.println(response);
}
}
if (_debug) {
Serial.println(F("\n----------"));
}
response[j] = '\0';
float result = ERROR_VALUE;
// POST
if (strcmp(request_type, "POST") == 0) {
char *pch = strstr(response, "OK");
if (pch != NULL) {
result = 1;
}
return result;
}
// LV
char *pch = strchr(response, '|');
if (pch != NULL) {
result = atof(pch + 1);
}
return result;
}
/**
* @brief Enable the debug
*
* @param debug Makes available debug traces
*/
void UbiTCP::setDebug(bool debug) { _debug = debug; }
/**
* @brief Checks if the socket is still opened with the Ubidots Server through
* the attribute
*
* @return true Server Connected
* @return false Server Obviusly not connected
*/
bool UbiTCP::serverConnected() { return _server_connected; }
/**
* @brief Handle the proper behavior of the SIM900 before fetching or sending
* data to Ubidots
*
* @return true Everything was fine
* @return false something went wrong.
*/
bool UbiTCP::_preConnectionChecks() {
if (!_initGPRS()) {
return false;
}
if (!_isNetworkRegistered()) {
return false;
}
if (!_isJoinedToNetwork()) {
return false;
}
if (!_connectToServer()) {
return false;
}
return true;
}
/**
* @brief Check if the module is already powered on, if not then it tries to
* power it forever.
*
*/
void UbiTCP::_guaranteePowerOn() {
if (_debug) {
Serial.println(F("Cheking Power status SIM900 module"));
}
if (!_client_tcp->checkPowerUp()) {
pinMode(SIM900_POWER_UP_PIN, OUTPUT);
if (_debug) {
Serial.println(F("Turning on the SIM900 Module"));
}
_client_tcp->powerUpDown();
delay(2000);
_guaranteePowerOn();
} else {
if (_debug) {
Serial.println(F("SIM900 status: Powered On"));
}
}
}
<commit_msg>Adding more fixes<commit_after>/*
Copyright (c) 2013-2018 Ubidots.
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.
Developed and maintained by Jose Garcia and Cristian Arrieta for IoT Services
Inc
@jotathebest at github: https://github.com/jotathebest
@crisap94 at github: https://github.com/crisap94
*/
#include "UbiTcp.h"
/**************************************************************************
* Overloaded constructors
***************************************************************************/
/**
* @brief Construct a new UbiTCP object and power up the module
*
* @param token Users token
* @param server Server addres
* @param port Server port
* @param user_agent Reference from the device being connected
* @param apn GPRS network name
* @param apnUser GPRS network username
* @param apnPass GPRS network passwrod
*/
UbiTCP::UbiTCP(UbiToken token, UbiServer server, const int port, const char *user_agent, UbiApn apn, UbiApn apnUser,
UbiApn apnPass) {
_server = server;
_user_agent = user_agent;
_token = token;
_port = port;
_apn = apn;
_apnUser = apnUser;
_apnPass = apnPass;
_client_tcp = GPRS::getInstance() == NULL ? new GPRS(RX, TX, BAUDRATE) : GPRS::getInstance();
}
/**************************************************************************
* Destructor
***************************************************************************/
UbiTCP::~UbiTCP() {
delete[] _server;
delete[] _user_agent;
delete[] _token;
delete[] _apn;
delete[] _apnUser;
delete[] _apnPass;
free(_client_tcp);
}
/**************************************************************************
* Cloud Functions
***************************************************************************/
/**
* @brief Post new data to ubidots server
*
* @param device_label Label of the device to be set or update in the ubidots
* platform
* @param device_name Device name to be published
* @param payload Body to be processed by the Ubidot server
* @return true The data was succesfully published
* @return false Something went wrong with the sending.
*/
bool UbiTCP::sendData(const char *device_label, const char *device_name, char *payload) {
if (_debug) {
Serial.print("Start TCP Connection...\r\n");
}
if (!_preConnectionChecks()) {
return false;
}
_client_tcp->send(payload);
/* Parses the host answer, returns true if it is 'Ok' */
char *response = (char *)malloc(sizeof(char) * MAX_BUFFER_SIZE);
float value = _parseTCPAnswer("POST", response);
free(response);
if (value != ERROR_VALUE) {
_client_tcp->close();
_client_tcp->disconnect();
return true;
}
return false;
}
/**
* @brief Get request over TCP to Ubidots server
*
* @param device_label device label of the device
* @param variable_label variable label to be fetched
* @return float Response value from the server
*/
float UbiTCP::get(const char *device_label, const char *variable_label) {
if (_debug) {
Serial.print("Start TCP Connection...\r\n");
}
if (!_preConnectionChecks()) {
return ERROR_VALUE;
}
if (_debug) {
Serial.println(F("waiting to fetch..."));
}
uint16_t endpointLength = _endpointLength(device_label, variable_label);
char *endpoint = (char *)malloc(sizeof(char) * endpointLength + 1);
sprintf(endpoint, "%s|LV|%s|%s:%s|end HTTP/1.0\r\n\r\n", USER_AGENT, _token, device_label, variable_label);
_client_tcp->send(endpoint, endpointLength);
free(endpoint);
char *response = (char *)malloc(sizeof(char) * MAX_BUFFER_SIZE);
float value = _parseTCPAnswer("POST", response);
free(response);
_client_tcp->close();
_client_tcp->disconnect();
delay(200);
return value;
}
/**************************************************************************
* Auxiliar
***************************************************************************/
/**
* @brief Do the initialization of the device
*
* @return true The device is responding to the commands
* @return false The device is not reponding, probably bad Serial communication
*/
bool UbiTCP::_initGPRS() {
if (!isInitiatedModule) {
uint8_t attempts = 0;
isInitiatedModule = true;
if (_debug) {
Serial.print(F("Initializing module...\r\n"));
}
// use DHCP
while (!_client_tcp->init() && attempts < 5) {
delay(500);
attempts += 1;
if (attempts == 5) {
isInitiatedModule = false;
}
if (_debug) {
Serial.print(F("Checking Serial connection ["));
Serial.print(attempts);
Serial.println(F("]"));
}
}
}
return isInitiatedModule;
}
/**
* @brief Extablish the phisical connection with the GPRS network
*
* @return true The network is accepted by the device
* @return false The device could connect to it, probably the frequency
*/
bool UbiTCP::_isNetworkRegistered() {
if (!isNetwowrkRegistered) {
if (_debug) {
Serial.println(F("Registering Network into the module"));
}
uint8_t attempts = 0;
isNetwowrkRegistered = true;
// use DHCP
while (!_client_tcp->isNetworkRegistered() && attempts < 5) {
delay(500);
yield();
attempts += 1;
if (attempts == 5) {
isNetwowrkRegistered = false;
}
if (_debug) {
Serial.print(F("Trying to register the network ["));
Serial.print(attempts);
Serial.println(F("]"));
}
}
if (_debug && !isNetwowrkRegistered) {
Serial.println(F("[ERROR] Couldn't register into the network\n\n"));
}
if (_debug && isNetwowrkRegistered) {
Serial.println(F("Network has been registered into the module"));
}
}
return isNetwowrkRegistered;
}
/**
* @brief The GPRS establish a new connection with the service
* TODO cast the _apn, _apnUser, _apnPass to the join method.
*
*/
bool UbiTCP::_isJoinedToNetwork() {
uint8_t attempts = 0;
bool flag = true;
bool isJoined = false;
// use DHCP
while (!isJoined && attempts < 5) {
isJoined = _client_tcp->join(_F(_apn), _F(_apnUser), _F(_apnPass));
delay(2000);
attempts += 1;
if (attempts == 1) {
if (_debug) {
Serial.print(F("Network status: "));
Serial.println(isJoined ? F("Joined") : F("Not Joined"));
Serial.println(F("Simcard Credentials"));
Serial.print(F("Apn: "));
Serial.println(_apn);
Serial.print(F("User: "));
Serial.println(_apnUser);
Serial.print(F("Pass: "));
Serial.println(_apnPass);
Serial.println();
}
}
if (_debug) {
Serial.print(F("Trying to join to the network ["));
Serial.print(attempts);
Serial.println(F("]"));
}
if (attempts == 5) {
if (_debug) {
Serial.println(F("[ERROR] Couldn't join the network\n\n"));
}
flag = false;
break;
}
}
if (_debug && flag) {
Serial.print(F("Network status: "));
Serial.println(isJoined ? F("Joined") : F("Not Joined"));
// successful DHCP
Serial.print(F("IP Address is "));
Serial.println(_client_tcp->getIPAddress());
if (!_checkIpAddress()) {
Serial.println(F("IpAddress NOT VALID!"));
_isJoinedToNetwork();
}
}
return flag;
}
/**
* @brief Check the Octecs from the IP Address to make a valid request for the
* IMEI, it splits the IP into tokes by the "." sparator, if there are 4 so it
* is ok
*
* @return true There a valid connection to internet
* @return false There is NOT a valid connection to internet
*/
bool UbiTCP::_checkIpAddress() {
char *ipAddress = _client_tcp->getIPAddress();
char *separator = ".";
char *octet;
uint8_t octecNumber = 0;
octet = strtok(ipAddress, separator);
while (octet != NULL) {
octecNumber += 1;
octet = strtok(NULL, separator);
}
if (octecNumber == 4) {
return true;
} else {
return false;
}
}
/**
* @brief Establish connection with Ubidots Server
*
* @return true Succesfull connection
* @return false Failed connection
*/
bool UbiTCP::_connectToServer() {
if (!_client_tcp->connect(TCP, UBI_INDUSTRIAL, UBIDOTS_TCP_PORT)) {
if (_debug) {
Serial.println(F("Error Connecting to Ubidots server"));
_server_connected = false;
return false;
}
} else {
_server_connected = true;
if (_debug) {
Serial.println(F("Connection to Ubidots server success!"));
}
return true;
}
}
/**
* @brief Calculate the lenght of the enpoint to be send over TCP to the server
*
* @param device_label device label of the device
* @param variable_label variable label to be updated or fetched
* @return uint16_t Lenght of the enpoint
*/
uint16_t UbiTCP::_endpointLength(const char *device_label, const char *variable_label) {
uint16_t endpointLength = strlen("|LV||:|end HTTP/1.0\r\n\r\n") + strlen(USER_AGENT) + strlen(_token) +
strlen(device_label) + strlen(variable_label);
return endpointLength;
}
/**
* @brief Parse the TCP host answer and saves it to the input char pointer.
* @param request_type Type of request GET or POST
* @param response [Mandatory] Buffer to contain the payload from the server
* @return float Value from the response
*/
float UbiTCP::_parseTCPAnswer(const char *request_type, char *response) {
int j = 0;
if (_debug) {
Serial.println(F("----------"));
Serial.println(F("Server's response:"));
}
while (true) {
int ret = _client_tcp->recv(response, MAX_BUFFER_SIZE);
if (ret <= 0) {
if (_debug) {
Serial.println(F("fetch over..."));
}
break;
}
response[ret] = '\0';
if (_debug) {
Serial.print(F("Recv: "));
Serial.print(ret);
Serial.print(F(" bytes: "));
Serial.println(response);
}
}
if (_debug) {
Serial.println(F("\n----------"));
}
response[j] = '\0';
float result = ERROR_VALUE;
// POST
if (strcmp(request_type, "POST") == 0) {
char *pch = strstr(response, "OK");
if (pch != NULL) {
result = 1;
}
return result;
}
// LV
char *pch = strchr(response, '|');
if (pch != NULL) {
result = atof(pch + 1);
}
return result;
}
/**
* @brief Enable the debug
*
* @param debug Makes available debug traces
*/
void UbiTCP::setDebug(bool debug) { _debug = debug; }
/**
* @brief Checks if the socket is still opened with the Ubidots Server through
* the attribute
*
* @return true Server Connected
* @return false Server Obviusly not connected
*/
bool UbiTCP::serverConnected() { return _server_connected; }
/**
* @brief Handle the proper behavior of the SIM900 before fetching or sending
* data to Ubidots
*
* @return true Everything was fine
* @return false something went wrong.
*/
bool UbiTCP::_preConnectionChecks() {
if (_guaranteePowerOn()) {
return false;
}
if (!_initGPRS()) {
return false;
}
if (!_isNetworkRegistered()) {
return false;
}
if (!_isJoinedToNetwork()) {
return false;
}
if (!_connectToServer()) {
return false;
}
return true;
}
/**
* @brief Check if the module is already powered on, if not then it tries to
* power it forever.
*
*/
bool UbiTCP::_guaranteePowerOn() {
if (!isPoweredOn) {
if (_debug) {
Serial.println(F("Cheking Power status SIM900 module"));
}
if (!_client_tcp->checkPowerUp()) {
pinMode(SIM900_POWER_UP_PIN, OUTPUT);
if (_debug) {
Serial.println(F("Turning on the SIM900 Module"));
}
_client_tcp->powerUpDown();
delay(2000);
_guaranteePowerOn();
} else {
isPoweredOn = true;
if (_debug) {
Serial.println(F("SIM900 status: Powered On"));
}
}
}
}
<|endoftext|>
|
<commit_before>/**
* @file visibility
*/
#include "visibility.h"
#include "forecast_time.h"
#include "level.h"
#include "logger.h"
#include "plugin_factory.h"
#include "util.h"
#include <boost/lexical_cast.hpp>
#include <cmath>
#include "fetcher.h"
#include "hitool.h"
#include "neons.h"
using namespace std;
using namespace himan;
using namespace himan::plugin;
const double defaultVis = 40000;
// Lumi- tai räntäsateen intensiteetin "tehostus" [mm/h]
// Tällä siis tarkoitus saada mallin heikotkin lumisadeintensiteetit huonontamaan näkyvyyttä
const double pseudoRR = 0.13;
// Raja-arvo merkittävälle sumupilven määrälle [0..1]
const double stLimit = 0.55;
// Sumupilven max korkeus [m], 305m = 1000ft
const double stMaxH = 305.;
const himan::params PFParams({himan::param("PRECFORM2-N"), himan::param("PRECFORM-N")});
const himan::params RHParam({himan::param("RH-PRCNT"), himan::param("RH-0TO1")});
const himan::param RRParam(himan::param("RRR-KGM2"));
const himan::params NParam({himan::param("N-PRCNT"), himan::param("N-0TO1")});
// ..and their levels
const himan::level NLevel(himan::kHeight, 0, "HEIGHT");
const himan::level RHLevel(himan::kHeight, 2, "HEIGHT");
double VisibilityInRain(double stN, double stH, double RR, double RH, int PF);
double VisibilityInMist(double stN, double stH, double RR, double RH);
visibility::visibility()
{
itsClearTextFormula = "<algorithm>";
itsLogger = logger("visibility");
}
void visibility::Process(std::shared_ptr<const plugin_configuration> conf)
{
Init(conf);
SetParams({param("VV2-M", 407)});
Start();
}
/*
* Calculate()
*
* This function does the actual calculation.
*/
void visibility::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex)
{
auto myThreadedLogger = logger("visibilityThread #" + boost::lexical_cast<string>(threadIndex));
forecast_time forecastTime = myTargetInfo->Time();
level forecastLevel = myTargetInfo->Level();
forecast_type forecastType = myTargetInfo->ForecastType();
myThreadedLogger.Info("Calculating time " + static_cast<string>(forecastTime.ValidDateTime()) + " level " +
static_cast<string>(forecastLevel));
info_t RHInfo = Fetch(forecastTime, RHLevel, RHParam, forecastType, false);
info_t PFInfo = Fetch(forecastTime, NLevel, PFParams, forecastType, false);
info_t RRInfo = Fetch(forecastTime, NLevel, RRParam, forecastType, false);
if (!RRInfo || !RHInfo || !PFInfo)
{
myThreadedLogger.Warning("Skipping step " + boost::lexical_cast<string>(forecastTime.Step()) + ", level " +
static_cast<string>(forecastLevel));
return;
}
double RHScale = 1;
if (itsConfiguration->SourceProducer().Id() == 1 || itsConfiguration->SourceProducer().Id() == 199 ||
itsConfiguration->SourceProducer().Id() == 4)
{
RHScale = 100;
}
auto h = GET_PLUGIN(hitool);
h->Configuration(itsConfiguration);
h->Time(myTargetInfo->Time());
h->ForecastType(myTargetInfo->ForecastType());
// Alle 304m (1000ft) sumupilven (max) määrä [0..1]
auto stN = h->VerticalMaximum(NParam, 0, stMaxH);
// Stratus <15m (~0-50ft)
auto st15 = h->VerticalAverage(NParam, 0, 15);
// Stratus 15-45m (~50-150ft)
auto st45 = h->VerticalAverage(NParam, 15, 45);
// Sumupilven korkeus [m]
auto stH = h->VerticalHeightGreaterThan(NParam, 0, stMaxH, stLimit);
// Jos sumupilveä ohut kerros (vain) ~alimmalla mallipinnalla, jätetään alin kerros huomioimatta
// (ehkä mieluummin ylempää keskiarvo, jottei tällöin mahdollinen ylempi st-kerros huononna näkyvyyttä liikaa?)
auto stHup = h->VerticalHeightGreaterThan(NParam, 25, stMaxH, stLimit);
auto stNup = h->VerticalAverage(NParam, 15, stMaxH);
assert(stH.size() == stHup.size());
assert(st15.size() == stH.size());
for (size_t i = 0; i < stH.size(); i++)
{
if (st15[i] > stLimit && st45[i] < stLimit)
{
stN[i] = stNup[i];
stH[i] = stHup[i];
}
}
string deviceType = "CPU";
auto& target = VEC(myTargetInfo);
for (auto&& tup : zip_range(target, VEC(PFInfo), VEC(RRInfo), VEC(RHInfo), stN, stH))
{
double& result = tup.get<0>();
double PF = tup.get<1>();
double RR = tup.get<2>();
double RH = tup.get<3>();
double stratN = tup.get<4>();
double stratH = tup.get<5>();
if (RR == kFloatMissing || RH == kFloatMissing)
{
continue;
}
assert(stratN <= 1.0);
assert(RR < 50);
stratN *= 100; // Note! Cloudiness is scaled to percents
RH *= RHScale;
assert(RH < 102.);
double visPre = defaultVis;
if (RR > 0)
{
visPre = VisibilityInRain(stratN, stratH, RR, RH, PF);
}
double visMist = VisibilityInMist(stratN, stratH, RR, RH);
// Choose lower visibility to be the end result
result = fmin(visMist, visPre);
}
myThreadedLogger.Info("[" + deviceType +
"] Missing values: " + boost::lexical_cast<string>(myTargetInfo->Data().MissingCount()) +
"/" + boost::lexical_cast<string>(myTargetInfo->Data().Size()));
}
double VisibilityInRain(double stN, double stH, double RR, double RH, int PF)
{
double visPre = defaultVis;
// Näkyvyyden utuisuuskerroin sateessa 2m suhteellisen kosteuden perusteella [0,85...8,5, kun 100%<rh<10%]
// (jos rh<85%, näkyvyyttä parannetaan)
const double RHpre = 85. / RH;
// Näkyvyyden utuisuuskerroin sateessa matalan sumupilven (alle 1000ft) määrän perusteella [1...0,85, kun
// 50<N<100%]
// Alle 50% sumupilven määrä ei siis huononna näkyvyyttä sateessa
const double stNpre = (stN >= 50) ? log(50) / log(stN) : 1;
// Näkyvyyden utuisuuskerroin sateessa matalan sumupilvikorkeuden perusteella [0,68...1, kun stH=12...152m]
// Yli 152m (500ft) korkeudella oleva sumupilvi ei siis huononna näkyvyyttä sateessa
const double stHpre = (stH != kFloatMissing && stH < 152) ? pow((stH / 152), 0.15) : 1;
assert(PF != kFloatMissing);
switch (PF)
{
case 0:
case 4:
// Tihku (tai jäätävä tihku)
// Nakyvyys intensiteetin perusteella
visPre = 1. / RR * 500;
break;
case 1:
case 5:
// Vesisade (tai jäätävä vesisade)
// Nakyvyys intensiteetin perusteella
// (kaava antaa ehkä turhan huonoja <4000m näkyvyyksiä reippaassa RR>4 vesisateessa)
visPre = 1 / RR * 6000 + 2000;
break;
case 3:
// Snow
// Näkyvyys intensiteetin perusteella
visPre = 1 / (RR + pseudoRR) * 1400;
break;
case 2:
// Sleet
// Näkyvyys intensiteetin perusteella
visPre = 1 / (RR + pseudoRR) * 2000;
break;
default:
throw runtime_error("New unhandled precipitation form value: " + to_string(PF));
}
// Mahdollinen lisähuononnus utuisuuden perusteella
visPre = visPre * RHpre * stNpre * stHpre;
return fmin(visPre, defaultVis);
}
double VisibilityInMist(double stN, double stH, double RR, double RH)
{
double visMist = defaultVis;
// Näkyvyyden utuisuuskerroin udussa/sumussa sumupilven määrän perusteella [7,5...0,68, kun stN = 0...100%]
const double stNmist = 75. / (stN + 10);
// Nakyvyyden utuisuuskerroin udussa/sumussa sumupilvikorkeuden perusteella [ 0,47...1, kun par500 = 50...999ft]
const double stHmist = (stH != kFloatMissing && stH < 305) ? pow((stH / 0.3048 / 1000), 0.25) : 1;
// Nakyvyys udussa/sumussa, lasketaan myos heikossa sateessa (tarkoituksena tasoittaa suuria
// nakyvyysgradientteja sateen reunalla)
// (ehka syyta rajata vain tilanteisiin, jossa sateen perusteella saatu nakyvyys oli viela >8000?)
if ((RR < 0.5 || RR == kFloatMissing) && RH > 80)
{
// Näkyvyys udussa/sumussa
// Yksinkertaistetty kaava, eli lasketaan samalla tavalla riippumatta siitä, onko pakkasta vai ei
// (pakkaset eri tavalla voisi olla parempi tapa)
// Alkuarvo suht. kosteuden perusteella [700-31400m, kun 100<=RH<80]
visMist = pow((101 - RH), 1.25) * 700;
// Lisamuokkaus sumupilven maaran ja korkeuden perusteella
visMist = visMist * stNmist * stHmist;
}
return fmin(visMist, defaultVis);
}
<commit_msg>Fix problem where visibility crashed because precipitation was found but form was missing.<commit_after>/**
* @file visibility
*/
#include "visibility.h"
#include "forecast_time.h"
#include "level.h"
#include "logger.h"
#include "plugin_factory.h"
#include "util.h"
#include "fetcher.h"
#include "hitool.h"
using namespace std;
using namespace himan;
using namespace himan::plugin;
const double defaultVis = 40000;
// Lumi- tai räntäsateen intensiteetin "tehostus" [mm/h]
// Tällä siis tarkoitus saada mallin heikotkin lumisadeintensiteetit huonontamaan näkyvyyttä
const double pseudoRR = 0.13;
// Raja-arvo merkittävälle sumupilven määrälle [0..1]
const double stLimit = 0.55;
// Sumupilven max korkeus [m], 305m = 1000ft
const double stMaxH = 305.;
const himan::params PFParams({himan::param("PRECFORM2-N"), himan::param("PRECFORM-N")});
const himan::params RHParam({himan::param("RH-PRCNT"), himan::param("RH-0TO1")});
const himan::params RRParam({himan::param("RR-1-MM"), himan::param("RRR-KGM2")});
const himan::params NParam({himan::param("N-PRCNT"), himan::param("N-0TO1")});
// ..and their levels
const himan::level NLevel(himan::kHeight, 0, "HEIGHT");
const himan::level RHLevel(himan::kHeight, 2, "HEIGHT");
double VisibilityInRain(double stN, double stH, double RR, double RH, int PF);
double VisibilityInMist(double stN, double stH, double RR, double RH);
visibility::visibility()
{
itsClearTextFormula = "<algorithm>";
itsLogger = logger("visibility");
}
void visibility::Process(std::shared_ptr<const plugin_configuration> conf)
{
Init(conf);
SetParams({param("VV2-M", 407)});
Start();
}
/*
* Calculate()
*
* This function does the actual calculation.
*/
void visibility::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex)
{
auto myThreadedLogger = logger("visibilityThread #" + to_string(threadIndex));
forecast_time forecastTime = myTargetInfo->Time();
level forecastLevel = myTargetInfo->Level();
forecast_type forecastType = myTargetInfo->ForecastType();
myThreadedLogger.Info("Calculating time " + static_cast<string>(forecastTime.ValidDateTime()) + " level " +
static_cast<string>(forecastLevel));
info_t RHInfo = Fetch(forecastTime, RHLevel, RHParam, forecastType, false);
info_t PFInfo = Fetch(forecastTime, NLevel, PFParams, forecastType, false);
info_t RRInfo = Fetch(forecastTime, NLevel, RRParam, forecastType, false);
if (!RRInfo || !RHInfo || !PFInfo)
{
myThreadedLogger.Warning("Skipping step " + to_string(forecastTime.Step()) + ", level " +
static_cast<string>(forecastLevel));
return;
}
double RHScale = 1;
if (itsConfiguration->SourceProducer().Id() == 1 || itsConfiguration->SourceProducer().Id() == 199 ||
itsConfiguration->SourceProducer().Id() == 4)
{
RHScale = 100;
}
auto h = GET_PLUGIN(hitool);
h->Configuration(itsConfiguration);
h->Time(myTargetInfo->Time());
h->ForecastType(myTargetInfo->ForecastType());
// Alle 304m (1000ft) sumupilven (max) määrä [0..1]
auto stN = h->VerticalMaximum(NParam, 0, stMaxH);
// Stratus <15m (~0-50ft)
auto st15 = h->VerticalAverage(NParam, 0, 15);
// Stratus 15-45m (~50-150ft)
auto st45 = h->VerticalAverage(NParam, 15, 45);
// Sumupilven korkeus [m]
auto stH = h->VerticalHeightGreaterThan(NParam, 0, stMaxH, stLimit);
// Jos sumupilveä ohut kerros (vain) ~alimmalla mallipinnalla, jätetään alin kerros huomioimatta
// (ehkä mieluummin ylempää keskiarvo, jottei tällöin mahdollinen ylempi st-kerros huononna näkyvyyttä liikaa?)
auto stHup = h->VerticalHeightGreaterThan(NParam, 25, stMaxH, stLimit);
auto stNup = h->VerticalAverage(NParam, 15, stMaxH);
assert(stH.size() == stHup.size());
assert(st15.size() == stH.size());
for (size_t i = 0; i < stH.size(); i++)
{
if (st15[i] > stLimit && st45[i] < stLimit)
{
stN[i] = stNup[i];
stH[i] = stHup[i];
}
}
string deviceType = "CPU";
auto& target = VEC(myTargetInfo);
for (auto&& tup : zip_range(target, VEC(PFInfo), VEC(RRInfo), VEC(RHInfo), stN, stH))
{
double& result = tup.get<0>();
double PF = tup.get<1>();
double RR = tup.get<2>();
double RH = tup.get<3>();
double stratN = tup.get<4>();
double stratH = tup.get<5>();
if (RR == kFloatMissing || RH == kFloatMissing)
{
continue;
}
assert(stratN <= 1.0);
assert(RR < 50);
stratN *= 100; // Note! Cloudiness is scaled to percents
RH *= RHScale;
assert(RH < 102.);
double visPre = defaultVis;
if (RR > 0)
{
visPre = VisibilityInRain(stratN, stratH, RR, RH, static_cast<int>(PF));
}
double visMist = VisibilityInMist(stratN, stratH, RR, RH);
// Choose lower visibility to be the end result
result = fmin(visMist, visPre);
}
myThreadedLogger.Info("[" + deviceType + "] Missing values: " + to_string(myTargetInfo->Data().MissingCount()) +
"/" + to_string(myTargetInfo->Data().Size()));
}
double VisibilityInRain(double stN, double stH, double RR, double RH, int PF)
{
double visPre = defaultVis;
// Näkyvyyden utuisuuskerroin sateessa 2m suhteellisen kosteuden perusteella [0,85...8,5, kun 100%<rh<10%]
// (jos rh<85%, näkyvyyttä parannetaan)
const double RHpre = 85. / RH;
// Näkyvyyden utuisuuskerroin sateessa matalan sumupilven (alle 1000ft) määrän perusteella [1...0,85, kun
// 50<N<100%]
// Alle 50% sumupilven määrä ei siis huononna näkyvyyttä sateessa
const double stNpre = (stN >= 50) ? log(50) / log(stN) : 1;
// Näkyvyyden utuisuuskerroin sateessa matalan sumupilvikorkeuden perusteella [0,68...1, kun stH=12...152m]
// Yli 152m (500ft) korkeudella oleva sumupilvi ei siis huononna näkyvyyttä sateessa
const double stHpre = (stH != kFloatMissing && stH < 152) ? pow((stH / 152), 0.15) : 1;
assert(PF != kFloatMissing);
switch (PF)
{
case 0:
case 4:
// Tihku (tai jäätävä tihku)
// Nakyvyys intensiteetin perusteella
visPre = 1. / RR * 500;
break;
case 1:
case 5:
// Vesisade (tai jäätävä vesisade)
// Nakyvyys intensiteetin perusteella
// (kaava antaa ehkä turhan huonoja <4000m näkyvyyksiä reippaassa RR>4 vesisateessa)
visPre = 1 / RR * 6000 + 2000;
break;
case 3:
// Snow
// Näkyvyys intensiteetin perusteella
visPre = 1 / (RR + pseudoRR) * 1400;
break;
case 2:
// Sleet
// Näkyvyys intensiteetin perusteella
visPre = 1 / (RR + pseudoRR) * 2000;
break;
default:
throw runtime_error("New unhandled precipitation form value: " + to_string(PF));
}
// Mahdollinen lisähuononnus utuisuuden perusteella
visPre = visPre * RHpre * stNpre * stHpre;
return fmin(visPre, defaultVis);
}
double VisibilityInMist(double stN, double stH, double RR, double RH)
{
double visMist = defaultVis;
// Näkyvyyden utuisuuskerroin udussa/sumussa sumupilven määrän perusteella [7,5...0,68, kun stN = 0...100%]
const double stNmist = 75. / (stN + 10);
// Nakyvyyden utuisuuskerroin udussa/sumussa sumupilvikorkeuden perusteella [ 0,47...1, kun par500 = 50...999ft]
const double stHmist = (stH != kFloatMissing && stH < 305) ? pow((stH / 0.3048 / 1000), 0.25) : 1;
// Nakyvyys udussa/sumussa, lasketaan myos heikossa sateessa (tarkoituksena tasoittaa suuria
// nakyvyysgradientteja sateen reunalla)
// (ehka syyta rajata vain tilanteisiin, jossa sateen perusteella saatu nakyvyys oli viela >8000?)
if ((RR < 0.5 || RR == kFloatMissing) && RH > 80)
{
// Näkyvyys udussa/sumussa
// Yksinkertaistetty kaava, eli lasketaan samalla tavalla riippumatta siitä, onko pakkasta vai ei
// (pakkaset eri tavalla voisi olla parempi tapa)
// Alkuarvo suht. kosteuden perusteella [700-31400m, kun 100<=RH<80]
visMist = pow((101 - RH), 1.25) * 700;
// Lisamuokkaus sumupilven maaran ja korkeuden perusteella
visMist = visMist * stNmist * stHmist;
}
return fmin(visMist, defaultVis);
}
<|endoftext|>
|
<commit_before><commit_msg>Hrm, it's hard explaining, and indeed thinking about what's going on in here :-) Think this is a better representation.<commit_after><|endoftext|>
|
<commit_before>// $Id$
#include <base/logstream.h>
#include <lac/solver_control.h>
/*----------------------- SolverControl ---------------------------------*/
SolverControl::SolverControl (const unsigned int maxiter,
const double tolerance,
const bool log_history,
const bool log_result)
:
maxsteps(maxiter),
tol(tolerance),
lvalue(1.e300),
lstep(0),
log_history(log_history),
log_result(log_result)
{};
SolverControl::~SolverControl()
{};
SolverControl::State
SolverControl::check (const unsigned int step,
const double check_value)
{
if (log_history)
deallog << "Check " << step << "\t" << check_value << endl;
lstep = step;
lvalue = check_value;
if (step>=maxsteps)
{
if (log_result)
deallog << "Failure step " << step
<< " value " << check_value << endl;
return failure;
}
if (check_value <= tol)
{
if (log_result)
deallog << "Convergence step " << step
<< " value " << check_value << endl;
return success;
}
return iterate;
};
double
SolverControl::last_value() const
{
return lvalue;
};
unsigned int
SolverControl::last_step() const
{
return lstep;
};
/*----------------------- ReductionControl ---------------------------------*/
ReductionControl::ReductionControl(const unsigned int n,
const double tol,
const double red,
const bool log_history,
const bool log_result)
:
SolverControl (n, tol, log_history, log_result),
reduce(red)
{};
ReductionControl::~ReductionControl()
{};
double
ReductionControl::initial_value() const {
return initial_val;
};
SolverControl::State
ReductionControl::check (const unsigned int step,
const double check_value)
{
if (step==0)
{
initial_val = check_value;
reduced_tol = check_value * reduce;
};
if (check_value < reduced_tol)
{
if (log_result)
deallog << "Convergence step " << step
<< " value " << check_value << endl;
return success;
}
else
return SolverControl::check(step, check_value);
};
<commit_msg>Output of starting residual<commit_after>// $Id$
#include <base/logstream.h>
#include <lac/solver_control.h>
/*----------------------- SolverControl ---------------------------------*/
SolverControl::SolverControl (const unsigned int maxiter,
const double tolerance,
const bool log_history,
const bool log_result)
:
maxsteps(maxiter),
tol(tolerance),
lvalue(1.e300),
lstep(0),
log_history(log_history),
log_result(log_result)
{};
SolverControl::~SolverControl()
{};
SolverControl::State
SolverControl::check (const unsigned int step,
const double check_value)
{
if (log_history)
deallog << "Check " << step << "\t" << check_value << endl;
lstep = step;
lvalue = check_value;
if ((step==0) && log_result)
{
deallog << "Starting value " << check_value << endl;
}
if (step>=maxsteps)
{
if (log_result)
deallog << "Failure step " << step
<< " value " << check_value << endl;
return failure;
}
if (check_value <= tol)
{
if (log_result)
deallog << "Convergence step " << step
<< " value " << check_value << endl;
return success;
}
return iterate;
};
double
SolverControl::last_value() const
{
return lvalue;
};
unsigned int
SolverControl::last_step() const
{
return lstep;
};
/*----------------------- ReductionControl ---------------------------------*/
ReductionControl::ReductionControl(const unsigned int n,
const double tol,
const double red,
const bool log_history,
const bool log_result)
:
SolverControl (n, tol, log_history, log_result),
reduce(red)
{};
ReductionControl::~ReductionControl()
{};
double
ReductionControl::initial_value() const {
return initial_val;
};
SolverControl::State
ReductionControl::check (const unsigned int step,
const double check_value)
{
if (step==0)
{
initial_val = check_value;
reduced_tol = check_value * reduce;
};
if (check_value < reduced_tol)
{
if (log_result)
deallog << "Convergence step " << step
<< " value " << check_value << endl;
return success;
}
else
return SolverControl::check(step, check_value);
};
<|endoftext|>
|
<commit_before>/*
* This file is part of PlantLight application.
*
* 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.
*
*/
/*
* Built for ATMega328P 1Mhz, using AVR Pololu programmer.
* VERSION 2.0b004
*/
#include <avr/sleep.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <Arduino.h>
#include <Timezone.h>
#include <BH1750FVI.h>
#include <DS3232RTC.h>
#include "PowerUtils.h"
#include "TimeUtils.h"
#define SERIAL_BAUD 9600 // Serial baud per second
// Pins
#define RTC_INT_SQW 4 // INT/SQW pin from RTC
#define RELAY_SW_OUT 5 // Relay out pin
#define ENABLE_H 16 // Enable hour (default)
#define DISABLE_H 23 // Disable hour (default)
#define ENA_DIS_MIN 0 // Enable and disable minute (default)
#define POLLING_INT 3 // Polling interval (default) [s]
#define SAMPLE_COUNT 10 // Light sample count (average measurement)
#define MAX_SAMPLE_COUNT 50 // Max light sample count
#define LUX_TH 10 // Lux threshold
#define LUX_TH_HIST 5 // Lux threshold (hysteresis compensation)
//#define RTC_CONTROL 0x0E // TODO remove
//#define RTC_STATUS 0x0F
// ################################# Constants ################################
// ################################# Variables ################################
TwoWire bus; // TinyWireM instance (I2C bus)
//BH1750FVI BH1750(bus); // Light sensor instance
DS3232RTC RTC(bus); // RTC clock instance
static float luxSamples[MAX_SAMPLE_COUNT] = {};
static uint8_t readCounter = 0;
static boolean relayState = false;
static struct tm utcTime, localTime;
//CET Time Zone (Rome, Berlin) -> UTC/GMT + 1
const TimeChangeRule CEST = {"CEST", Last, Sun, Mar, 2, 120}; // Central European Summer Time
const TimeChangeRule CET = {"CET ", Last, Sun, Oct, 3, 60}; // Central European Standard Time
Timezone TZ(CEST, CET); // Constructor to build object from DST Rules
TimeChangeRule *tcr; // Pointer to the time change rule, use to get TZ abbreviations
// Options data
typedef struct {
int8_t hhE, mmE, hhD, mmD; // Time of day to enable or disable light
uint8_t poll; // Polling interval when enabled [s]
uint8_t sampleCount; // Light sample count (average measurement)
uint8_t luxTh; // Lux threshold
uint8_t luxThHys; // Lux threshold (hysteresis compensation)
} options; // Options structure
options opt; // Global application options
// ############################################################################
// Sensor reading functions
// ############################################################################
/*
* Sample from light sensor.
*
* Return: the current mobile average value.
*/
float sample() {
float tmpLux = 0.0;
// Shift left values in sample array
for (int i = 0; i < opt.sampleCount - 1; ++i) {
luxSamples[i] = luxSamples[i + 1];
tmpLux += luxSamples[i];
}
//luxSamples[opt.sampleCount - 1] = BH1750.getLightIntensity(); // TODO Get lux value
luxSamples[opt.sampleCount - 1] = 9.0;
tmpLux += luxSamples[opt.sampleCount - 1];
if (readCounter < opt.sampleCount) {
readCounter++;
}
return tmpLux / readCounter;
}
/*
* Cleans the mobile average array.
*/
void cleanLuxArray() {
readCounter = 0;
for (int i = 0; i < opt.sampleCount; ++i) {
luxSamples[i] = 0.0;
}
}
/*
* Checks the light condition to switch the relay on or off.
*
* Return: true to turn on the relay.
*/
boolean checkLightCond(float lux) {
int low = 0, high = 0;
for (int i = opt.sampleCount / 2 + 1 ; i < opt.sampleCount - 1; ++i) {
if (luxSamples[i] <= LUX_TH) {
low++;
} else {
high++;
}
}
if (readCounter >= opt.sampleCount / 2 + 1) {
// Turn light on
if (high <= 2 && lux <= LUX_TH) {
return true;
}
// Turn light off
if (relayState && lux <= LUX_TH + LUX_TH_HIST) {
return true;
} else {
return false;
}
}
return false;
}
boolean checkEnable(const struct tm &now) {
int minE = opt.hhE * 60 + opt.mmE;
int minD = opt.hhD * 60 + opt.mmD;
int nowM = now.tm_hour * 60 + now.tm_min;
if (minE == minD) {
return true;
} else if (minE < minD) {
return (minE <= nowM && nowM < minD);
} else {
return (minE <= nowM || nowM < minD);
}
}
#ifdef DEBUG
void printLuxArray() {
for (int i = 0; i < opt.sampleCount; ++i) {
Serial.print(luxSamples[i]);
Serial.print(" ");
}
}
#endif
// ############################################################################
// AVR specific functions
// ############################################################################
/*
* PCINT Interrupt Service Routine
*/
ISR(PCINT2_vect) {
// Don't do anything here but we must include this
// block of code otherwise the interrupt calls an
// uninitialized interrupt handler.
}
/*
* Set various power reduction options
*/
static void powerReduction() {
// Disable digital input buffer on ADC pins
DIDR0 = (1 << ADC5D) | (1 << ADC4D) | (1 << ADC3D) | (1 << ADC2D) | (1 << ADC1D) | (1 << ADC0D);
// Disable digital input buffer on Analog comparator pins
DIDR1 |= (1 << AIN1D) | (1 << AIN0D);
// Disable Analog Comparator interrupt
ACSR &= ~(1 << ACIE);
// Disable Analog Comparator
ACSR |= (1 << ACD);
// Disable unused peripherals to save power
// Disable ADC (ADC must be disabled before shutdown)
ADCSRA &= ~(1 << ADEN);
// Enable power reduction register except:
// - USART0: for serial communications
// - TWI module: for I2C communications
// - TIMER0: for millis()
PRR = 0xFF & (~(1 << PRUSART0)) & (~(1 << PRTWI)) & (~(1 << PRTIM0));
}
void setup() {
uint8_t retcode;
Serial.begin(SERIAL_BAUD);
// I2C begin() is called BEFORE sensors library "begin" methods:
// it is called just once for all the sensors.
bus.begin();
// Setup pins modes
pinMode(RELAY_SW_OUT, OUTPUT);
pinMode(RTC_INT_SQW, INPUT_PULLUP);
// RTC connection check
if ((retcode = RTC.checkCon()) != 0) {
Serial.print("RTC err: ");
Serial.println(retcode);
// Exit application code to infinite loop
exit(retcode);
}
// Default options load
opt.hhE = 21;//ENABLE_H;
opt.mmE = 0;//ENA_DIS_MIN;
opt.hhD = 21;//DISABLE_H;
opt.mmD = 1;//ENA_DIS_MIN;
opt.poll = POLLING_INT;
opt.sampleCount = SAMPLE_COUNT;
opt.luxTh = LUX_TH;
opt.luxThHys = LUX_TH_HIST;
if (opt.sampleCount > MAX_SAMPLE_COUNT) {
opt.sampleCount = MAX_SAMPLE_COUNT;
}
// Real time clock set: UTC time!
makeTime(&utcTime, 2018, 11, 28, 20, 59, 55);
RTC.write(&utcTime);
//RTC.read(&utcTime);
TZ.toLocal(&utcTime, &localTime, &tcr);
//#ifdef DEBUG
// printTime(&utcTime, "UTC");
// printTime(&localTime, tcr->abbrev);
//#endif
// Set alarm to the RTC clock in UTC format!!
RTC.setAlarm(ALM2_MATCH_HOURS, opt.mmE, opt.hhE, 0);
// Clear the alarm flag
RTC.alarm(ALARM_2);
// Set the alarm interrupt
RTC.alarmInterrupt(ALARM_2, true);
// Light Sensor initialization
// BH1750.powerOn();
// BH1750.setMode(BH1750_CONTINUOUS_HIGH_RES_MODE_2);
// BH1750.setMtreg(200); // Set measurement time register to high value
// delay(100);
// BH1750.sleep(); // Send light sensor to sleep
// Power settings
powerReduction();
// Interrupt configuration
PCMSK2 |= _BV(PCINT20); // Pin change mask: listen to portD bit 4 (D4) (RTC_INT_SQW)
PCMSK2 |= _BV(PCINT16); // Pin change mask: listen to portD bit 0 (D0) (Serial RX)
PCICR |= _BV(PCIE2); // Enable PCINT interrupt on portD
}
void loop() {
RTC.read(&utcTime);
TZ.toLocal(&utcTime, &localTime, &tcr);
#ifdef DEBUG
printTime(&utcTime, "UTC");
printTime(&localTime, tcr->abbrev);
#endif
// TODO if (checkEnable(localTime)) {
if (checkEnable(utcTime)) {
RTC.setAlarm(ALM1_MATCH_SECONDS, (utcTime.tm_sec + opt.poll) % 60, 0, 0, 0);
// Set the alarm interrupt
RTC.alarmInterrupt(ALARM_1, true);
// // One time mode: the sensor reads and goes into sleep mode autonomously
// BH1750.wakeUp(BH1750_ONE_TIME_HIGH_RES_MODE_2);
//
// // Wait for the sensor to be fully awake.
// delay(500);
float lux = sample();
relayState = checkLightCond(lux);
digitalWrite(RELAY_SW_OUT, relayState);
#ifdef DEBUG
printLuxArray();
Serial.print("= ");
Serial.print(lux);
Serial.print(" ");
if (relayState)
Serial.println("ON");
else Serial.println("OFF");
#endif
} else {
// TODO set next alarm
makeTime(&utcTime, 2018, 11, 28, 20, 59, 54);
RTC.write(&utcTime);
// Reset the alarm interrupt
RTC.alarmInterrupt(ALARM_1, false);
cleanLuxArray();
digitalWrite(RELAY_SW_OUT, false);
relayState = false;
}
#ifdef DEBUG
Serial.println("Sleeping...");
Serial.println();
delay(500);
#endif
systemSleep(SLEEP_MODE_PWR_DOWN); // Send the unit to sleep
RTC.alarm(ALARM_1); // Necessary to reset the alarm flag on RTC!
RTC.alarm(ALARM_2); // Necessary to reset the alarm flag on RTC!
}
<commit_msg>Added "set time mode", function to read date from serial, moved RTC interrupt to external INT0.<commit_after>/*
* This file is part of PlantLight application.
*
* 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.
*
*/
/*
* Built for ATMega328P 1Mhz, using AVR Pololu programmer.
* VERSION 2.0b004
*/
#include <avr/sleep.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <Arduino.h>
#include <Timezone.h>
#include <BH1750FVI.h>
#include <DS3232RTC.h>
#include "PowerUtils.h"
#include "TimeUtils.h"
#define SERIAL_BAUD 9600 // Serial baud per second
// Pins
#define RTC_INT_SQW 2 // INT/SQW pin from RTC: external interrupt
#define RELAY_SW_OUT 5 // Relay output pin
#define SET_TIME_IN 4 // Set time mode input pin: pin change interrupt
// TODO time mode LED
#define ENABLE_H 16 // Enable hour (default)
#define DISABLE_H 23 // Disable hour (default)
#define ENA_DIS_MIN 0 // Enable and disable minute (default)
#define POLLING_INT 3 // Polling interval (default) [s]
#define SAMPLE_COUNT 10 // Light sample count (average measurement)
#define MAX_SAMPLE_COUNT 50 // Max light sample count
#define LUX_TH 10 // Lux threshold
#define LUX_TH_HIST 5 // Lux threshold (hysteresis compensation)
//#define RTC_CONTROL 0x0E // TODO remove
//#define RTC_STATUS 0x0F
// ################################# Constants ################################
// ################################# Variables ################################
TwoWire bus; // TinyWireM instance (I2C bus)
//BH1750FVI BH1750(bus); // Light sensor instance
DS3232RTC RTC(bus); // RTC clock instance
static float luxSamples[MAX_SAMPLE_COUNT] = {};
static uint8_t readCounter = 0;
static boolean relayState = false;
volatile boolean setTimeMode = false;
static struct tm utcTime, localTime;
//CET Time Zone (Rome, Berlin) -> UTC/GMT + 1
const TimeChangeRule CEST = {"CEST", Last, Sun, Mar, 2, 120}; // Central European Summer Time
const TimeChangeRule CET = {"CET ", Last, Sun, Oct, 3, 60}; // Central European Standard Time
Timezone TZ(CEST, CET); // Constructor to build object from DST Rules
TimeChangeRule *tcr; // Pointer to the time change rule, use to get TZ abbreviations
// Options data
typedef struct {
int8_t hhE, mmE, hhD, mmD; // Time of day to enable or disable light
uint8_t poll; // Polling interval when enabled [s]
uint8_t sampleCount; // Light sample count (average measurement)
uint8_t luxTh; // Lux threshold
uint8_t luxThHys; // Lux threshold (hysteresis compensation)
} options; // Options structure
options opt; // Global application options
// ############################################################################
// Sensor reading functions
// ############################################################################
/*
* Sample from light sensor.
*
* Return: the current mobile average value.
*/
float sample() {
float tmpLux = 0.0;
// Shift left values in sample array
for (int i = 0; i < opt.sampleCount - 1; ++i) {
luxSamples[i] = luxSamples[i + 1];
tmpLux += luxSamples[i];
}
//luxSamples[opt.sampleCount - 1] = BH1750.getLightIntensity(); // TODO Get lux value
luxSamples[opt.sampleCount - 1] = 9.0;
tmpLux += luxSamples[opt.sampleCount - 1];
if (readCounter < opt.sampleCount) {
readCounter++;
}
return tmpLux / readCounter;
}
/*
* Cleans the mobile average array.
*/
void cleanLuxArray() {
readCounter = 0;
for (int i = 0; i < opt.sampleCount; ++i) {
luxSamples[i] = 0.0;
}
}
/*
* Checks the light condition to switch the relay on or off.
*
* Return: true to turn on the relay.
*/
boolean checkLightCond(float lux) {
int low = 0, high = 0;
for (int i = opt.sampleCount / 2 + 1 ; i < opt.sampleCount - 1; ++i) {
if (luxSamples[i] <= LUX_TH) {
low++;
} else {
high++;
}
}
if (readCounter >= opt.sampleCount / 2 + 1) {
// Turn light on
if (high <= 2 && lux <= LUX_TH) {
return true;
}
// Turn light off
if (relayState && lux <= LUX_TH + LUX_TH_HIST) {
return true;
} else {
return false;
}
}
return false;
}
boolean checkEnable(const struct tm &now) {
int minE = opt.hhE * 60 + opt.mmE;
int minD = opt.hhD * 60 + opt.mmD;
int nowM = now.tm_hour * 60 + now.tm_min;
if (minE == minD) {
return true;
} else if (minE < minD) {
return (minE <= nowM && nowM < minD);
} else {
return (minE <= nowM || nowM < minD);
}
}
#ifdef DEBUG
void printLuxArray() {
for (int i = 0; i < opt.sampleCount; ++i) {
Serial.print(luxSamples[i]);
Serial.print(" ");
}
}
#endif
/**
* Set the date and time by entering the following on the serial input:
* year,month,day,hour,minute,second,
*
* Where
* year can be two or four digits,
* month is 1-12,
* day is 1-31,
* hour is 0-23, and
* minute and second are 0-59.
*
* Entering the final comma delimiter (after "second") will avoid a TODO
* one-second timeout and will allow the RTC to be set more accurately.
*
* No validity checking is done, invalid values or incomplete syntax
* in the input will result in an incorrect RTC setting.
*/
// TODO exit from serial (quit?)
boolean setTimeSerial() {
int16_t YYYY; // Year in 4 digit format
int8_t MM, DD, hh, mm, ss;
time_t t;
// Check for input to set the RTC, minimum length is 12, i.e. yy,m,d,h,m,s
if (Serial.available() >= 12) {
int y = Serial.parseInt();
if (y >= 100 && y < 1000) {
Serial.println(F("Error: Year must be two digits or four digits!"));
} else {
if (y >= 1000) {
YYYY = y;
} else {
// (y < 100)
YYYY = y + 2000;
}
MM = Serial.parseInt();
DD = Serial.parseInt();
hh = Serial.parseInt();
mm = Serial.parseInt();
ss = Serial.parseInt();
t = makeTime(YYYY, MM, DD, hh, mm, ss);
// Use the time_t value to ensure correct weekday is set
RTC.set(t);
// Set UTC application time
memset((void*) &utcTime, 0, sizeof(utcTime));
gmtime_r(&t, &utcTime);
// Convert UTC time in local time
TZ.toLocal(&utcTime, &localTime, &tcr);
Serial.println(F("RTC set to: "));
printTime(&utcTime, "UTC");
printTime(&localTime, tcr->abbrev);
Serial.println();
// Dump any extraneous input
while (Serial.available() > 0)
Serial.read();
}
return true;
}
return false;
}
// ############################################################################
// AVR specific functions
// ############################################################################
/*
* PCINT Interrupt Service Routines
*/
ISR(PCINT2_vect) {
setTimeMode = true;
}
/*
* INT0 Interrupt Service Routines
*
* External interrupt on PD2
*/
ISR(INT0_vect) {
// Don't do anything here but we must include this
// block of code otherwise the interrupt calls an
// uninitialized interrupt handler.
}
/*
* Set various power reduction options
*/
static void powerReduction() {
// Disable digital input buffer on ADC pins
DIDR0 = (1 << ADC5D) | (1 << ADC4D) | (1 << ADC3D) | (1 << ADC2D) | (1 << ADC1D) | (1 << ADC0D);
// Disable digital input buffer on Analog comparator pins
DIDR1 |= (1 << AIN1D) | (1 << AIN0D);
// Disable Analog Comparator interrupt
ACSR &= ~(1 << ACIE);
// Disable Analog Comparator
ACSR |= (1 << ACD);
// Disable unused peripherals to save power
// Disable ADC (ADC must be disabled before shutdown)
ADCSRA &= ~(1 << ADEN);
// Enable power reduction register except:
// - USART0: for serial communications
// - TWI module: for I2C communications
// - TIMER0: for millis()
PRR = 0xFF & (~(1 << PRUSART0)) & (~(1 << PRTWI)) & (~(1 << PRTIM0));
}
void setup() {
uint8_t retcode;
Serial.begin(SERIAL_BAUD);
// I2C begin() is called BEFORE sensors library "begin" methods:
// it is called just once for all the sensors.
bus.begin();
// Setup pins modes
pinMode(RELAY_SW_OUT, OUTPUT);
pinMode(RTC_INT_SQW, INPUT_PULLUP);
pinMode(SET_TIME_IN, INPUT_PULLUP);
// RTC connection check
if ((retcode = RTC.checkCon()) != 0) {
Serial.print("RTC err: ");
Serial.println(retcode);
// Exit application code to infinite loop
exit(retcode);
}
// Default options load
opt.hhE = 21;//ENABLE_H;
opt.mmE = 0;//ENA_DIS_MIN;
opt.hhD = 21;//DISABLE_H;
opt.mmD = 1;//ENA_DIS_MIN;
opt.poll = 20; // TODO POLLING_INT;
opt.sampleCount = SAMPLE_COUNT;
opt.luxTh = LUX_TH;
opt.luxThHys = LUX_TH_HIST;
if (opt.sampleCount > MAX_SAMPLE_COUNT) {
opt.sampleCount = MAX_SAMPLE_COUNT;
}
// Real time clock set: UTC time!
//makeTime(&utcTime, 2018, 11, 28, 12, 59, 55);
//RTC.write(&utcTime);
RTC.read(&utcTime);
TZ.toLocal(&utcTime, &localTime, &tcr);
#ifdef DEBUG
printTime(&utcTime, "UTC");
printTime(&localTime, tcr->abbrev);
#endif
// Set alarm to the RTC clock in UTC format!!
RTC.setAlarm(ALM2_MATCH_HOURS, opt.mmE, opt.hhE, 0);
// Clear the alarm flag
RTC.alarm(ALARM_2);
// Set the alarm interrupt
RTC.alarmInterrupt(ALARM_2, true);
// Light Sensor initialization
// BH1750.powerOn();
// BH1750.setMode(BH1750_CONTINUOUS_HIGH_RES_MODE_2);
// BH1750.setMtreg(200); // Set measurement time register to high value
// delay(100);
// BH1750.sleep(); // Send light sensor to sleep
// Power settings
powerReduction();
// Interrupt configuration
PCMSK2 |= _BV(PCINT20); // Pin change mask: listen to portD bit 4 (D4) (SET_TIME_IN)
PCICR |= _BV(PCIE2); // Enable PCINT interrupt on portD
EICRA |= _BV(ISC01); // Set INT0 to trigger on falling edge (RTC_INT_SQW)
EIMSK |= _BV(INT0); // Turns on INT0
}
void loop() {
RTC.read(&utcTime);
TZ.toLocal(&utcTime, &localTime, &tcr);
#ifdef DEBUG
printTime(&utcTime, "UTC");
printTime(&localTime, tcr->abbrev);
#endif
if (setTimeMode) {
// ############################# SET TIME MODE ############################
Serial.println("Wake");
delay(500);
if (setTimeSerial()) {
// TODO set alarm
setTimeMode = false;
}
} else {
// TODO if (checkEnable(localTime)) {
if (checkEnable(utcTime)) {
RTC.setAlarm(ALM1_MATCH_SECONDS, (utcTime.tm_sec + opt.poll) % 60, 0, 0, 0);
// Clear the alarm flag
RTC.alarm(ALARM_1);
// Set the alarm interrupt
RTC.alarmInterrupt(ALARM_1, true);
// // One time mode: the sensor reads and goes into sleep mode autonomously
// BH1750.wakeUp(BH1750_ONE_TIME_HIGH_RES_MODE_2);
//
// // Wait for the sensor to be fully awake.
// delay(500);
float lux = sample();
relayState = checkLightCond(lux);
digitalWrite(RELAY_SW_OUT, relayState);
#ifdef DEBUG
printLuxArray();
Serial.print("= ");
Serial.print(lux);
Serial.print(" ");
if (relayState)
Serial.println("ON");
else Serial.println("OFF");
#endif
} else {
// Reset the alarm interrupt
RTC.alarmInterrupt(ALARM_1, false);
cleanLuxArray();
digitalWrite(RELAY_SW_OUT, false);
relayState = false;
}
#ifdef DEBUG
Serial.println("Sleeping...");
Serial.println();
delay(100);
#endif
systemSleep(SLEEP_MODE_PWR_DOWN); // Send the unit to sleep
RTC.alarm(ALARM_1); // Necessary to reset the alarm flag on RTC!
RTC.alarm(ALARM_2); // Necessary to reset the alarm flag on RTC!
}
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <math.h>
#include "mylib/mymath.hpp"
int main(int argc, char** argv)
{
unsigned long int n;
if (argc!=2 || sscanf(argv[1],"%lu",&n)!=1) {
fprintf(stderr,"Usage:\n%s integration_steps\n\n\n",argv[0]);
}
// Integration limits.
const double global_a=1E-5;
const double global_b=1;
const double y=integral(integrand, n, global_a, global_b);
const double y_exact=4*(pow(global_b,0.25)-pow(global_a,0.25));
printf("Result=%lf Exact=%lf Difference=%lf\n", y, y_exact, y-y_exact);
return 0;
}
<commit_msg>Fix running integral_seq w/o args<commit_after>#include <stdio.h>
#include <math.h>
#include "mylib/mymath.hpp"
int main(int argc, char** argv)
{
unsigned long int n;
if (argc!=2 || sscanf(argv[1],"%lu",&n)!=1) {
fprintf(stderr,"Usage:\n%s integration_steps\n\n\n",argv[0]);
return 1;
}
// Integration limits.
const double global_a=1E-5;
const double global_b=1;
const double y=integral(integrand, n, global_a, global_b);
const double y_exact=4*(pow(global_b,0.25)-pow(global_a,0.25));
printf("Result=%lf Exact=%lf Difference=%lf\n", y, y_exact, y-y_exact);
return 0;
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <math.h>
#include "mylib/mymath.hpp"
int main(int argc, char** argv)
{
unsigned long int n;
if (argc!=2 || sscanf(argv[1],"%lu",&n)!=1) return 1;
// Integration limits.
const double global_a=1E-5;
const double global_b=1;
const double y=integral(integrand, n, global_a, global_b);
const double y_exact=4*(pow(global_b,0.25)-pow(global_a,0.25));
printf("Result=%lf Exact=%lf Difference=%lf\n", y, y_exact, y-y_exact);
return 0;
}
<commit_msg>Improved help message for integral_seq<commit_after>#include <stdio.h>
#include <math.h>
#include "mylib/mymath.hpp"
int main(int argc, char** argv)
{
unsigned long int n;
if (argc!=2 || sscanf(argv[1],"%lu",&n)!=1) {
fprintf(stderr,"Usage:\n%s integration_steps\n\n\n",argv[0]);
// Integration limits.
const double global_a=1E-5;
const double global_b=1;
const double y=integral(integrand, n, global_a, global_b);
const double y_exact=4*(pow(global_b,0.25)-pow(global_a,0.25));
printf("Result=%lf Exact=%lf Difference=%lf\n", y, y_exact, y-y_exact);
return 0;
}
<|endoftext|>
|
<commit_before>/*
*
* MIT License
*
* Copyright (c) 2016-2018 The Cats Project
*
* 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 CATS_CORECAT_DATA_ARRAY_HPP
#define CATS_CORECAT_DATA_ARRAY_HPP
#include <cstddef>
#include <memory>
#include <utility>
#include "Allocator/DefaultAllocator.hpp"
#include "../Util/Iterator.hpp"
namespace Cats {
namespace Corecat {
inline namespace Data {
template <typename T>
class ArrayView;
template <typename T, typename A = DefaultAllocator>
class Array {
public:
using Type = T;
using AllocatorType = A;
using Iterator = Type*;
using ConstIterator = const Type*;
using ReverseIterator = Corecat::ReverseIterator<Iterator>;
using ConstReverseIterator = Corecat::ReverseIterator<ConstIterator>;
using ArrayViewType = ArrayView<T>;
using ConstArrayViewType = ArrayView<const T>;
private:
A allocator;
Type* data = nullptr;
std::size_t size = 0;
std::size_t capacity = 0;
public:
Array() = default;
Array(std::size_t size_) { resize(size_); }
Array(const Array& src) {
data = static_cast<T*>(allocator.allocate(src.size * sizeof(T)));
size = src.size;
capacity = size;
std::size_t i = 0;
try {
for(; i < size; ++i) new(data + i) T(src.data[i]);
} catch(...) {
for(std::size_t j = 0; j < i; ++j) data[j].~T();
allocator.deallocate(data, capacity * sizeof(T));
throw;
}
}
Array(Array&& src) noexcept { swap(src); }
~Array() {
clear();
if(data) allocator.deallocate(data, capacity * sizeof(T));
}
Array& operator =(const Array& src) {
if(src.size > capacity) {
T* newData = static_cast<T*>(allocator.allocate(src.size * sizeof(T)));
std::size_t i = 0;
try {
for(; i < src.size; ++i) new(newData + i) T(src.data[i]);
} catch(...) {
for(std::size_t j = 0; j < i; ++j) newData[j].~T();
allocator.deallocate(newData, src.size * sizeof(T));
throw;
}
if(data) {
for(std::size_t i = 0; i < size; ++i) data[i].~T();
allocator.deallocate(data, capacity * sizeof(T));
}
data = newData;
size = src.size;
capacity = size;
} else if(src.size > size) {
std::size_t i = 0;
for(; i < size; ++i) data[i] = src.data[i];
try {
for(; i < src.size; ++i) new(data + i) T(src.data[i]);
} catch(...) {
for(std::size_t j = size; j < i; ++j) data[j].~T();
throw;
}
size = src.size;
} else {
std::size_t i = 0;
for(; i < src.size; ++i) data[i] = src.data[i];
for(; i < size; ++i) data[i].~T();
size = src.size;
}
return *this;
}
Array& operator =(Array&& src) noexcept { swap(src); return *this; }
operator ConstArrayViewType() const noexcept { return getView(); }
operator ArrayViewType() noexcept { return getView(); }
const Type& operator [](std::size_t index) const noexcept { return data[index]; }
Type& operator [](std::size_t index) noexcept { return data[index]; }
const Type* getData() const noexcept { return data; }
Type* getData() noexcept { return data; }
std::size_t getSize() const noexcept { return size; }
std::size_t getCapacity() const noexcept { return capacity; }
ConstArrayViewType getView() const noexcept { return {data, size}; }
ArrayViewType getView() noexcept { return {data, size}; }
bool isEmpty() const noexcept { return !size; }
void clear() noexcept { resize(0); }
void reserve(std::size_t capacity_) {
if(capacity >= capacity_) return;
T* data_ = static_cast<T*>(allocator.allocate(capacity_ * sizeof(T)));
std::size_t i = 0;
try {
for(; i < size; ++i) new(data_ + i) T(data[i]);
} catch(...) {
for(std::size_t j = 0; j < i; ++j) data[j].~T();
allocator.deallocate(data_, capacity_ * sizeof(T));
throw;
}
if(data) {
for(std::size_t i = 0; i < size; ++i) data[i].~T();
allocator.deallocate(data, capacity * sizeof(T));
}
data = data_;
capacity = capacity_;
}
void resize(std::size_t size_) {
if(size_ < size) {
for(std::size_t i = size_ - 1; i != size_ - 1; --i)
data[i].~T();
} else if(size_ > size) {
if(size_ <= capacity) {
std::size_t i = size;
try {
for(; i < size_; ++i) new(data + i) T();
} catch(...) {
for(std::size_t j = 0; j < i; ++j) data[j].~T();
throw;
}
} else {
T* data_ = static_cast<T*>(allocator.allocate(size_ * sizeof(T)));
std::size_t i = 0;
try {
for(; i < size; ++i) new(data_ + i) T(data[i]);
for(; i < size_; ++i) new(data_ + i) T();
} catch(...) {
for(std::size_t j = 0; j < i; ++j) data_[j].~T();
allocator.deallocate(data_, size_ * sizeof(T));
throw;
}
if(data) {
for(std::size_t i = 0; i < size; ++i) data[i].~T();
allocator.deallocate(data, capacity * sizeof(T));
}
data = data_;
capacity = size_;
}
}
size = size_;
}
template <typename... Arg>
void push(Arg&&... arg) {
if(size < capacity) {
new(data + size) T(std::forward<Arg>(arg)...);
} else {
std::size_t newSize = size + 1;
T* newData = static_cast<T*>(allocator.allocate(newSize * sizeof(T)));
std::size_t i = 0;
try {
for(; i < size; ++i) new(newData + i) T(data[i]);
new(newData + size) T(std::forward<Arg>(arg)...);
} catch(...) {
for(std::size_t j = 0; j < i; ++j) newData[j].~T();
allocator.deallocate(newData, newSize * sizeof(T));
throw;
}
if(data) {
for(std::size_t i = 0; i < size; ++i) data[i].~T();
allocator.deallocate(data, capacity * sizeof(T));
}
data = newData;
capacity = newSize;
}
++size;
}
void pop() noexcept {
if(!size) return;
data[--size].~T();
}
void swap(Array& src) noexcept {
std::swap(allocator, src.allocator);
std::swap(data, src.data);
std::swap(size, src.size);
std::swap(capacity, src.capacity);
}
Iterator begin() const noexcept { return data; }
Iterator end() const noexcept { return data + size; }
ConstIterator cbegin() const noexcept { return begin(); }
ConstIterator cend() const noexcept { return end(); }
ReverseIterator rbegin() const noexcept { return ReverseIterator(end()); }
ReverseIterator rend() const noexcept { return ReverseIterator(begin()); }
ConstReverseIterator crbegin() const noexcept { return ConstReverseIterator(cend()); }
ConstReverseIterator crend() const noexcept { return ConstReverseIterator(cbegin()); }
};
template <typename T>
class ArrayView {
public:
using Type = T;
using Iterator = Type*;
using ConstIterator = const Type*;
using ReverseIterator = Corecat::ReverseIterator<Iterator>;
using ConstReverseIterator = Corecat::ReverseIterator<ConstIterator>;
private:
Type* data = nullptr;
std::size_t size = 0;
public:
ArrayView() = default;
ArrayView(std::nullptr_t) noexcept {}
ArrayView(Type* data_, std::size_t size_) noexcept : data(data_), size(size_) {}
template <std::size_t S>
ArrayView(Type (&array)[S]) noexcept : data(array), size(S) {}
ArrayView(std::initializer_list<T> list) noexcept : data(list.begin()), size(list.size()) {}
ArrayView(const ArrayView& src) = default;
ArrayView& operator =(const ArrayView& src) = default;
operator ArrayView<const Type>() noexcept { return {data, size}; }
Type& operator [](std::size_t index) const noexcept { return data[index]; }
Type* getData() const noexcept { return data; }
void setData(T* data_, std::size_t size_) noexcept { data = data_, size = size_; }
std::size_t getSize() const noexcept { return size; }
void setSize(std::size_t size_) noexcept { size = size_; }
bool isEmpty() const noexcept { return !size; }
ArrayView slice(std::ptrdiff_t beginPos) const noexcept { return slice(beginPos, size); }
ArrayView slice(std::ptrdiff_t beginPos, std::ptrdiff_t endPos) const noexcept {
if(beginPos < 0) beginPos = std::max<std::ptrdiff_t>(beginPos + size, 0);
else beginPos = std::min<std::ptrdiff_t>(beginPos, size);
if(endPos < 0) endPos = std::max<std::ptrdiff_t>(endPos + size, 0);
else endPos = std::min<std::ptrdiff_t>(endPos, size);
if(beginPos < endPos) return {data + beginPos, std::size_t(endPos - beginPos)};
else return {};
}
Iterator begin() const noexcept { return data; }
Iterator end() const noexcept { return data + size; }
ConstIterator cbegin() const noexcept { return begin(); }
ConstIterator cend() const noexcept { return end(); }
ReverseIterator rbegin() const noexcept { return ReverseIterator(end()); }
ReverseIterator rend() const noexcept { return ReverseIterator(begin()); }
ConstReverseIterator crbegin() const noexcept { return ConstReverseIterator(cend()); }
ConstReverseIterator crend() const noexcept { return ConstReverseIterator(cbegin()); }
};
}
}
}
#endif
<commit_msg>Update Array<commit_after>/*
*
* MIT License
*
* Copyright (c) 2016-2018 The Cats Project
*
* 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 CATS_CORECAT_DATA_ARRAY_HPP
#define CATS_CORECAT_DATA_ARRAY_HPP
#include <cstddef>
#include <memory>
#include <utility>
#include "Allocator/DefaultAllocator.hpp"
#include "../Util/Iterator.hpp"
namespace Cats {
namespace Corecat {
inline namespace Data {
template <typename T>
class ArrayView;
template <typename T, typename A = DefaultAllocator>
class Array {
public:
using Type = T;
using AllocatorType = A;
using Iterator = Type*;
using ConstIterator = const Type*;
using ReverseIterator = Corecat::ReverseIterator<Iterator>;
using ConstReverseIterator = Corecat::ReverseIterator<ConstIterator>;
using ArrayViewType = ArrayView<T>;
using ConstArrayViewType = ArrayView<const T>;
private:
A allocator;
Type* data = nullptr;
std::size_t size = 0;
std::size_t capacity = 0;
public:
Array() = default;
Array(std::size_t size_) { resize(size_); }
Array(const Array& src) {
data = static_cast<T*>(allocator.allocate(src.size * sizeof(T)));
size = src.size;
capacity = size;
std::size_t i = 0;
try {
for(; i < size; ++i) new(data + i) T(src.data[i]);
} catch(...) {
for(std::size_t j = 0; j < i; ++j) data[j].~T();
allocator.deallocate(data, capacity * sizeof(T));
throw;
}
}
Array(Array&& src) noexcept { swap(src); }
~Array() {
clear();
if(data) allocator.deallocate(data, capacity * sizeof(T));
}
Array& operator =(const Array& src) {
if(src.size > capacity) {
T* newData = static_cast<T*>(allocator.allocate(src.size * sizeof(T)));
std::size_t i = 0;
try {
for(; i < src.size; ++i) new(newData + i) T(src.data[i]);
} catch(...) {
for(std::size_t j = 0; j < i; ++j) newData[j].~T();
allocator.deallocate(newData, src.size * sizeof(T));
throw;
}
if(data) {
for(std::size_t i = 0; i < size; ++i) data[i].~T();
allocator.deallocate(data, capacity * sizeof(T));
}
data = newData;
size = src.size;
capacity = size;
} else if(src.size > size) {
std::size_t i = 0;
for(; i < size; ++i) data[i] = src.data[i];
try {
for(; i < src.size; ++i) new(data + i) T(src.data[i]);
} catch(...) {
for(std::size_t j = size; j < i; ++j) data[j].~T();
throw;
}
size = src.size;
} else {
std::size_t i = 0;
for(; i < src.size; ++i) data[i] = src.data[i];
for(; i < size; ++i) data[i].~T();
size = src.size;
}
return *this;
}
Array& operator =(Array&& src) noexcept { swap(src); return *this; }
operator ConstArrayViewType() const noexcept { return getView(); }
operator ArrayViewType() noexcept { return getView(); }
const Type& operator [](std::size_t index) const noexcept { return data[index]; }
Type& operator [](std::size_t index) noexcept { return data[index]; }
const Type* getData() const noexcept { return data; }
Type* getData() noexcept { return data; }
std::size_t getSize() const noexcept { return size; }
std::size_t getCapacity() const noexcept { return capacity; }
ConstArrayViewType getView() const noexcept { return {data, size}; }
ArrayViewType getView() noexcept { return {data, size}; }
bool isEmpty() const noexcept { return !size; }
void clear() noexcept { resize(0); }
void reserve(std::size_t capacity_) {
if(capacity >= capacity_) return;
T* data_ = static_cast<T*>(allocator.allocate(capacity_ * sizeof(T)));
std::size_t i = 0;
try {
for(; i < size; ++i) new(data_ + i) T(data[i]);
} catch(...) {
for(std::size_t j = 0; j < i; ++j) data[j].~T();
allocator.deallocate(data_, capacity_ * sizeof(T));
throw;
}
if(data) {
for(std::size_t i = 0; i < size; ++i) data[i].~T();
allocator.deallocate(data, capacity * sizeof(T));
}
data = data_;
capacity = capacity_;
}
void resize(std::size_t size_) {
if(size_ < size) {
for(std::size_t i = size_ - 1; i != size_ - 1; --i)
data[i].~T();
} else if(size_ > size) {
if(size_ <= capacity) {
std::size_t i = size;
try {
for(; i < size_; ++i) new(data + i) T();
} catch(...) {
for(std::size_t j = 0; j < i; ++j) data[j].~T();
throw;
}
} else {
T* data_ = static_cast<T*>(allocator.allocate(size_ * sizeof(T)));
std::size_t i = 0;
try {
for(; i < size; ++i) new(data_ + i) T(data[i]);
for(; i < size_; ++i) new(data_ + i) T();
} catch(...) {
for(std::size_t j = 0; j < i; ++j) data_[j].~T();
allocator.deallocate(data_, size_ * sizeof(T));
throw;
}
if(data) {
for(std::size_t i = 0; i < size; ++i) data[i].~T();
allocator.deallocate(data, capacity * sizeof(T));
}
data = data_;
capacity = size_;
}
}
size = size_;
}
template <typename... Arg>
void push(Arg&&... arg) {
if(size < capacity) {
new(data + size) T(std::forward<Arg>(arg)...);
} else {
std::size_t newSize = size + 1;
T* newData = static_cast<T*>(allocator.allocate(newSize * sizeof(T)));
std::size_t i = 0;
try {
for(; i < size; ++i) new(newData + i) T(data[i]);
new(newData + size) T(std::forward<Arg>(arg)...);
} catch(...) {
for(std::size_t j = 0; j < i; ++j) newData[j].~T();
allocator.deallocate(newData, newSize * sizeof(T));
throw;
}
if(data) {
for(std::size_t i = 0; i < size; ++i) data[i].~T();
allocator.deallocate(data, capacity * sizeof(T));
}
data = newData;
capacity = newSize;
}
++size;
}
void pop() noexcept {
if(!size) return;
data[--size].~T();
}
void swap(Array& src) noexcept {
std::swap(allocator, src.allocator);
std::swap(data, src.data);
std::swap(size, src.size);
std::swap(capacity, src.capacity);
}
Iterator begin() const noexcept { return data; }
Iterator end() const noexcept { return data + size; }
ConstIterator cbegin() const noexcept { return begin(); }
ConstIterator cend() const noexcept { return end(); }
ReverseIterator rbegin() const noexcept { return ReverseIterator(end()); }
ReverseIterator rend() const noexcept { return ReverseIterator(begin()); }
ConstReverseIterator crbegin() const noexcept { return ConstReverseIterator(cend()); }
ConstReverseIterator crend() const noexcept { return ConstReverseIterator(cbegin()); }
};
template <typename T>
class ArrayView {
public:
using Type = T;
using Iterator = Type*;
using ConstIterator = const Type*;
using ReverseIterator = Corecat::ReverseIterator<Iterator>;
using ConstReverseIterator = Corecat::ReverseIterator<ConstIterator>;
private:
Type* data = nullptr;
std::size_t size = 0;
public:
ArrayView() = default;
ArrayView(std::nullptr_t) noexcept {}
ArrayView(Type* data_, std::size_t size_) noexcept : data(data_), size(size_) {}
template <std::size_t S>
ArrayView(Type (&array)[S]) noexcept : data(array), size(S) {}
ArrayView(std::initializer_list<T> list) noexcept : data(list.begin()), size(list.size()) {}
ArrayView(const ArrayView& src) = default;
ArrayView& operator =(const ArrayView& src) = default;
operator ArrayView<const Type>() noexcept { return {data, size}; }
Type& operator [](std::size_t index) const noexcept { return data[index]; }
Type* getData() const noexcept { return data; }
void setData(T* data_, std::size_t size_) noexcept { data = data_, size = size_; }
std::size_t getSize() const noexcept { return size; }
void setSize(std::size_t size_) noexcept { size = size_; }
bool isEmpty() const noexcept { return !size; }
ArrayView slice(std::ptrdiff_t beginPos) const noexcept { return slice(beginPos, size); }
ArrayView slice(std::ptrdiff_t beginPos, std::ptrdiff_t endPos) const noexcept {
if(beginPos < 0) beginPos = std::max<std::ptrdiff_t>(beginPos + size, 0);
else beginPos = std::min<std::ptrdiff_t>(beginPos, size);
if(endPos < 0) endPos = std::max<std::ptrdiff_t>(endPos + size, 0);
else endPos = std::min<std::ptrdiff_t>(endPos, size);
if(beginPos < endPos) return {data + beginPos, std::size_t(endPos - beginPos)};
else return {};
}
void swap(ArrayView& src) noexcept {
std::swap(data, src.data);
std::swap(size, src.size);
}
Iterator begin() const noexcept { return data; }
Iterator end() const noexcept { return data + size; }
ConstIterator cbegin() const noexcept { return begin(); }
ConstIterator cend() const noexcept { return end(); }
ReverseIterator rbegin() const noexcept { return ReverseIterator(end()); }
ReverseIterator rend() const noexcept { return ReverseIterator(begin()); }
ConstReverseIterator crbegin() const noexcept { return ConstReverseIterator(cend()); }
ConstReverseIterator crend() const noexcept { return ConstReverseIterator(cbegin()); }
};
}
}
}
#endif
<|endoftext|>
|
<commit_before>/*******************************************************************************
* Copyright (c) 2015, Jean-David Gadina - www.xs-labs.com
* Distributed under the Boost Software License, Version 1.0.
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
******************************************************************************/
/*!
* @copyright (c) 2015 - Jean-David Gadina - www.xs-labs.com
* @brief Replacement of std::atomic supporting non trivially-copyable types
*/
#ifndef XS_ATOMIC_H
#define XS_ATOMIC_H
#include <type_traits>
#include <utility>
#include <atomic>
#include <mutex>
namespace XS
{
template< typename _T_, class _E_ = void >
class Atomic
{
public:
Atomic( void ) = delete;
Atomic( _T_ v ) = delete;
Atomic( const Atomic< _T_ > & o ) = delete;
Atomic( const Atomic< _T_ > && o ) = delete;
Atomic< _T_ > & operator =( _T_ v ) = delete;
Atomic< _T_ > & operator =( const Atomic< _T_ > & o ) = delete;
Atomic< _T_ > & operator =( const Atomic< _T_ > && o ) = delete;
};
template< typename _T_ >
class Atomic< _T_, typename std::enable_if< std::is_trivially_copyable< _T_ >::value >::type >
{
private:
typedef std::atomic< _T_ > _A_;
public:
Atomic( void ): _v{}
{}
Atomic( _T_ v ): _v{ v }
{}
Atomic( const Atomic< _T_ > & o ): _v{ o._v.load() }
{}
Atomic( const Atomic< _T_ > && o ): _v{ std::move( o._v ) }
{}
~Atomic( void )
{}
Atomic< _T_ > & operator =( Atomic< _T_ > o )
{
this->_v = o._v;
return *( this );
}
Atomic< _T_ > & operator =( _T_ v )
{
this->_v = v;
return *( this );
}
operator _T_ ( void ) const
{
return this->_v;
}
_T_ * operator ->( void ) const
{
return this->_v;
}
Atomic< _T_ > & operator ++ ( void )
{
this->_v++;
return *( this );
}
Atomic< _T_ > operator ++ ( int )
{
Atomic< _T_ > a( *( this ) );
operator++();
return a;
}
Atomic< _T_ > & operator -- ( void )
{
this->_v--;
return *( this );
}
Atomic< _T_ > operator -- ( int )
{
Atomic< _T_ > a( *( this ) );
operator--();
return a;
}
Atomic< _T_ > & operator += ( _T_ v )
{
this->_v += v;
return *( this );
}
Atomic< _T_ > & operator -= ( _T_ v )
{
this->_v -= v;
return *( this );
}
Atomic< _T_ > & operator &= ( _T_ v )
{
this->_v &= v;
return *( this );
}
Atomic< _T_ > & operator |= ( _T_ v )
{
this->_v |= v;
return *( this );
}
Atomic< _T_ > & operator ^= ( _T_ v )
{
this->_v ^= v;
return *( this );
}
bool IsLockFree( void )
{
return this->_v.is_lock_free();
}
friend void swap( Atomic< _T_ > & o1, Atomic< _T_ > & o2 )
{
using std::swap;
swap( o1._v, o2._v );
}
private:
_A_ _v;
};
template< typename _T_ >
class Atomic< _T_, typename std::enable_if< !std::is_trivially_copyable< _T_ >::value >::type >
{
private:
typedef std::recursive_mutex _M_;
typedef std::lock_guard< _M_ > _L_;
public:
Atomic( void ): _v{}
{}
Atomic( _T_ v ): _v{ v }
{}
Atomic( const Atomic< _T_ > & o ): Atomic< _T_ >( o, _L_( o._rmtx ) )
{}
Atomic( const Atomic< _T_ > && o ): Atomic< _T_ >( o, _L_( o._rmtx ) )
{}
~Atomic( void )
{}
Atomic< _T_ > & operator =( Atomic< _T_ > o )
{
std::lock( this->_rmtx, o._rmtx );
_L_ l1( this->_rmtx, std::adopt_lock );
_L_ l2( o._rmtx, std::adopt_lock );
this->_v = o._v;
return *( this );
}
Atomic< _T_ > & operator =( _T_ v )
{
_L_ l( this->_rmtx );
this->_v = v;
return *( this );
}
operator _T_ ( void ) const
{
_L_ l( this->_rmtx );
return this->_v;
}
_T_ * operator ->( void ) const
{
_L_ l( this->_rmtx );
return this->_v;
}
bool IsLockFree( void )
{
return false;
}
friend void swap( Atomic< _T_ > & o1, Atomic< _T_ > & o2 )
{
std::lock( o1._rmtx, o2._rmtx );
_L_ l1( o1._rmtx, std::adopt_lock );
_L_ l2( o2._rmtx, std::adopt_lock );
using std::swap;
swap( o1._v, o2._v );
}
private:
Atomic( const Atomic< _T_ > & o, _L_ & l ): _v{ o._v }
{
( void )l;
}
Atomic( const Atomic< _T_ > && o, _L_ & l ): _v{ std::move( o._v ) }
{
( void )l;
}
_T_ _v;
mutable _M_ _rmtx;
};
}
#endif /* XS_ATOMIC_H */
<commit_msg>const<commit_after>/*******************************************************************************
* Copyright (c) 2015, Jean-David Gadina - www.xs-labs.com
* Distributed under the Boost Software License, Version 1.0.
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
******************************************************************************/
/*!
* @copyright (c) 2015 - Jean-David Gadina - www.xs-labs.com
* @brief Replacement of std::atomic supporting non trivially-copyable types
*/
#ifndef XS_ATOMIC_H
#define XS_ATOMIC_H
#include <type_traits>
#include <utility>
#include <atomic>
#include <mutex>
namespace XS
{
template< typename _T_, class _E_ = void >
class Atomic
{
public:
Atomic( void ) = delete;
Atomic( _T_ v ) = delete;
Atomic( const Atomic< _T_ > & o ) = delete;
Atomic( const Atomic< _T_ > && o ) = delete;
Atomic< _T_ > & operator =( _T_ v ) = delete;
Atomic< _T_ > & operator =( const Atomic< _T_ > & o ) = delete;
Atomic< _T_ > & operator =( const Atomic< _T_ > && o ) = delete;
};
template< typename _T_ >
class Atomic< _T_, typename std::enable_if< std::is_trivially_copyable< _T_ >::value >::type >
{
private:
typedef std::atomic< _T_ > _A_;
public:
Atomic( void ): _v{}
{}
Atomic( _T_ v ): _v{ v }
{}
Atomic( const Atomic< _T_ > & o ): _v{ o._v.load() }
{}
Atomic( const Atomic< _T_ > && o ): _v{ std::move( o._v ) }
{}
~Atomic( void )
{}
Atomic< _T_ > & operator =( Atomic< _T_ > o )
{
this->_v = o._v;
return *( this );
}
Atomic< _T_ > & operator =( _T_ v )
{
this->_v = v;
return *( this );
}
operator _T_ ( void ) const
{
return this->_v;
}
_T_ * operator ->( void ) const
{
return this->_v;
}
Atomic< _T_ > & operator ++ ( void )
{
this->_v++;
return *( this );
}
Atomic< _T_ > operator ++ ( int )
{
Atomic< _T_ > a( *( this ) );
operator++();
return a;
}
Atomic< _T_ > & operator -- ( void )
{
this->_v--;
return *( this );
}
Atomic< _T_ > operator -- ( int )
{
Atomic< _T_ > a( *( this ) );
operator--();
return a;
}
Atomic< _T_ > & operator += ( _T_ v )
{
this->_v += v;
return *( this );
}
Atomic< _T_ > & operator -= ( _T_ v )
{
this->_v -= v;
return *( this );
}
Atomic< _T_ > & operator &= ( _T_ v )
{
this->_v &= v;
return *( this );
}
Atomic< _T_ > & operator |= ( _T_ v )
{
this->_v |= v;
return *( this );
}
Atomic< _T_ > & operator ^= ( _T_ v )
{
this->_v ^= v;
return *( this );
}
bool IsLockFree( void ) const
{
return this->_v.is_lock_free();
}
friend void swap( Atomic< _T_ > & o1, Atomic< _T_ > & o2 )
{
using std::swap;
swap( o1._v, o2._v );
}
private:
_A_ _v;
};
template< typename _T_ >
class Atomic< _T_, typename std::enable_if< !std::is_trivially_copyable< _T_ >::value >::type >
{
private:
typedef std::recursive_mutex _M_;
typedef std::lock_guard< _M_ > _L_;
public:
Atomic( void ): _v{}
{}
Atomic( _T_ v ): _v{ v }
{}
Atomic( const Atomic< _T_ > & o ): Atomic< _T_ >( o, _L_( o._rmtx ) )
{}
Atomic( const Atomic< _T_ > && o ): Atomic< _T_ >( o, _L_( o._rmtx ) )
{}
~Atomic( void )
{}
Atomic< _T_ > & operator =( Atomic< _T_ > o )
{
std::lock( this->_rmtx, o._rmtx );
_L_ l1( this->_rmtx, std::adopt_lock );
_L_ l2( o._rmtx, std::adopt_lock );
this->_v = o._v;
return *( this );
}
Atomic< _T_ > & operator =( _T_ v )
{
_L_ l( this->_rmtx );
this->_v = v;
return *( this );
}
operator _T_ ( void ) const
{
_L_ l( this->_rmtx );
return this->_v;
}
_T_ * operator ->( void ) const
{
_L_ l( this->_rmtx );
return this->_v;
}
bool IsLockFree( void ) const
{
return false;
}
friend void swap( Atomic< _T_ > & o1, Atomic< _T_ > & o2 )
{
std::lock( o1._rmtx, o2._rmtx );
_L_ l1( o1._rmtx, std::adopt_lock );
_L_ l2( o2._rmtx, std::adopt_lock );
using std::swap;
swap( o1._v, o2._v );
}
private:
Atomic( const Atomic< _T_ > & o, _L_ & l ): _v{ o._v }
{
( void )l;
}
Atomic( const Atomic< _T_ > && o, _L_ & l ): _v{ std::move( o._v ) }
{
( void )l;
}
_T_ _v;
mutable _M_ _rmtx;
};
}
#endif /* XS_ATOMIC_H */
<|endoftext|>
|
<commit_before>#include <set>
#include "Module/Subsequence/Subsequence.hpp"
#include "Tools/Sequence/Sequence.hpp"
namespace aff3ct
{
namespace tools
{
size_t Sequence
::get_n_threads() const
{
return this->n_threads;
}
const std::vector<std::vector<module::Task*>>& Sequence
::get_firsts_tasks() const
{
return this->firsts_tasks;
}
const std::vector<std::vector<module::Task*>>& Sequence
::get_lasts_tasks() const
{
return this->lasts_tasks;
}
template <class C>
std::vector<C*> Sequence
::get_modules(const bool subsequence_modules) const
{
std::vector<C*> ret;
for (auto &mm : this->all_modules)
for (auto &m : mm)
{
if (subsequence_modules)
{
auto c = dynamic_cast<module::Subsequence*>(m);
if (c != nullptr)
{
auto subret = c->get_sequence().get_modules<C>(subsequence_modules);
ret.insert(ret.end(), subret.begin(), subret.end());
}
}
auto c = dynamic_cast<C*>(m);
if (c != nullptr)
ret.push_back(c);
}
return ret;
}
template <class C>
std::vector<C*> Sequence
::get_cloned_modules(const C &module_ref) const
{
std::vector<C*> cloned_modules(this->all_modules[0].size());
for (auto &e : this->all_modules)
{
auto c = dynamic_cast<C*>(e[0]);
if (c == &module_ref)
{
cloned_modules[0] = c;
for (size_t m = 1; m < cloned_modules.size(); m++)
{
c = dynamic_cast<C*>(e[m]);
if (c == nullptr)
{
std::stringstream message;
message << "'c' can't be 'nullptr', this should never happen.";
throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
}
cloned_modules[m] = c;
}
break;
}
}
return cloned_modules;
}
template <class SS>
inline void Sequence
::_init(Generic_node<SS> *root)
{
std::stringstream message;
message << "This should never happen.";
throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
}
template <>
inline void Sequence
::_init(Generic_node<tools::Sub_sequence_const> *root)
{
this->duplicate<tools::Sub_sequence_const, const module::Module>(root);
this->delete_tree(root);
}
template <>
inline void Sequence
::_init(Generic_node<tools::Sub_sequence> *root)
{
this->sequences[0] = root;
std::set<module::Module*> modules_set;
std::function<void(const Generic_node<tools::Sub_sequence>*)> collect_modules_list;
collect_modules_list = [&](const Generic_node<tools::Sub_sequence> *node)
{
if (node != nullptr)
{
if (node->get_c())
for (auto ta : node->get_c()->tasks)
modules_set.insert(&ta->get_module());
for (auto c : node->get_children())
collect_modules_list(c);
}
};
collect_modules_list(root);
for (auto m : modules_set)
this->all_modules[0].push_back(m);
this->duplicate<tools::Sub_sequence, module::Module>(root);
}
size_t Sequence
::get_n_frames() const
{
const auto n_frames = this->all_modules[0][0]->get_n_frames();
for (auto &mm : this->all_modules)
for (auto &m : mm)
if (m->get_n_frames() != n_frames)
{
std::stringstream message;
message << "All the modules do not have the same 'n_frames' value ('m->get_n_frames()' = "
<< m->get_n_frames() << ", 'n_frames' = " << n_frames << ").";
throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
}
return n_frames;
}
}
}
<commit_msg>Fix the `tools::Sequence::get_cloned_modules()` implementation.<commit_after>#include <set>
#include "Module/Subsequence/Subsequence.hpp"
#include "Tools/Sequence/Sequence.hpp"
namespace aff3ct
{
namespace tools
{
size_t Sequence
::get_n_threads() const
{
return this->n_threads;
}
const std::vector<std::vector<module::Task*>>& Sequence
::get_firsts_tasks() const
{
return this->firsts_tasks;
}
const std::vector<std::vector<module::Task*>>& Sequence
::get_lasts_tasks() const
{
return this->lasts_tasks;
}
template <class C>
std::vector<C*> Sequence
::get_modules(const bool subsequence_modules) const
{
std::vector<C*> ret;
for (auto &mm : this->all_modules)
for (auto &m : mm)
{
if (subsequence_modules)
{
auto c = dynamic_cast<module::Subsequence*>(m);
if (c != nullptr)
{
auto subret = c->get_sequence().get_modules<C>(subsequence_modules);
ret.insert(ret.end(), subret.begin(), subret.end());
}
}
auto c = dynamic_cast<C*>(m);
if (c != nullptr)
ret.push_back(c);
}
return ret;
}
template <class C>
std::vector<C*> Sequence
::get_cloned_modules(const C &module_ref) const
{
bool found = false;
size_t mid = 0;
while (mid < this->all_modules[0].size() && !found)
if (dynamic_cast<C*>(this->all_modules[0][mid]) == &module_ref)
found = true;
else
mid++;
if (!found)
{
std::stringstream message;
message << "'module_ref' can't be found in the sequence.";
throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
}
std::vector<C*> cloned_modules(this->all_modules.size());
for (size_t tid = 0; tid < this->all_modules.size(); tid++)
{
auto c = dynamic_cast<C*>(this->all_modules[tid][mid]);
if (c == nullptr)
{
std::stringstream message;
message << "'c' can't be 'nullptr', this should never happen.";
throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
}
cloned_modules[tid] = c;
}
return cloned_modules;
}
template <class SS>
inline void Sequence
::_init(Generic_node<SS> *root)
{
std::stringstream message;
message << "This should never happen.";
throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
}
template <>
inline void Sequence
::_init(Generic_node<tools::Sub_sequence_const> *root)
{
this->duplicate<tools::Sub_sequence_const, const module::Module>(root);
this->delete_tree(root);
}
template <>
inline void Sequence
::_init(Generic_node<tools::Sub_sequence> *root)
{
this->sequences[0] = root;
std::set<module::Module*> modules_set;
std::function<void(const Generic_node<tools::Sub_sequence>*)> collect_modules_list;
collect_modules_list = [&](const Generic_node<tools::Sub_sequence> *node)
{
if (node != nullptr)
{
if (node->get_c())
for (auto ta : node->get_c()->tasks)
modules_set.insert(&ta->get_module());
for (auto c : node->get_children())
collect_modules_list(c);
}
};
collect_modules_list(root);
for (auto m : modules_set)
this->all_modules[0].push_back(m);
this->duplicate<tools::Sub_sequence, module::Module>(root);
}
size_t Sequence
::get_n_frames() const
{
const auto n_frames = this->all_modules[0][0]->get_n_frames();
for (auto &mm : this->all_modules)
for (auto &m : mm)
if (m->get_n_frames() != n_frames)
{
std::stringstream message;
message << "All the modules do not have the same 'n_frames' value ('m->get_n_frames()' = "
<< m->get_n_frames() << ", 'n_frames' = " << n_frames << ").";
throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
}
return n_frames;
}
}
}
<|endoftext|>
|
<commit_before>#include "erlang_v8_drv.h"
Persistent<ObjectTemplate> GlobalFactory::Generate(Vm *vm,
ErlNifEnv *env) {
TRACE("GlobalFactory::Generate\n");
Locker locker(vm->isolate);
TRACE("GlobalFactory::Generate - 1\n");
Isolate::Scope iscope(vm->isolate);
TRACE("GlobalFactory::Generate - 2\n");
HandleScope handle_scope;
TRACE("GlobalFactory::Generate - 3\n");
Context::Scope scope(Context::New());
Local<ObjectTemplate> global = ObjectTemplate::New();
Local<Object> erlang = Object::New();
global->Set(String::New("erlang"), erlang);
erlang->Set(String::New("vm"), ErlWrapper::MakeHandle(vm, env, vm->term));
return Persistent<ObjectTemplate>::New(global);
}
<commit_msg>Call it erlang_v8 instead of erlang.<commit_after>#include "erlang_v8_drv.h"
Persistent<ObjectTemplate> GlobalFactory::Generate(Vm *vm,
ErlNifEnv *env) {
TRACE("GlobalFactory::Generate\n");
Locker locker(vm->isolate);
TRACE("GlobalFactory::Generate - 1\n");
Isolate::Scope iscope(vm->isolate);
TRACE("GlobalFactory::Generate - 2\n");
HandleScope handle_scope;
TRACE("GlobalFactory::Generate - 3\n");
Context::Scope scope(Context::New());
Local<ObjectTemplate> global = ObjectTemplate::New();
Local<Object> erlangV8 = Object::New();
global->Set(String::New("erlang_v8"), erlangV8);
erlangV8->Set(String::New("vm"), ErlWrapper::MakeHandle(vm, env, vm->term));
return Persistent<ObjectTemplate>::New(global);
}
<|endoftext|>
|
<commit_before>#pragma once
#include <array>
#include <cassert>
#include <map>
#include <string>
namespace brynet { namespace net { namespace http {
class HttpQueryParameter final
{
public:
void add(const std::string& k, const std::string& v)
{
if (!mParameter.empty())
{
mParameter += "&";
}
mParameter += k;
mParameter += "=";
mParameter += v;
}
const std::string& getResult() const
{
return mParameter;
}
private:
std::string mParameter;
};
class HttpRequest final
{
public:
enum class HTTP_METHOD
{
HTTP_METHOD_HEAD,
HTTP_METHOD_GET,
HTTP_METHOD_POST,
HTTP_METHOD_PUT,
HTTP_METHOD_DELETE,
HTTP_METHOD_MAX
};
HttpRequest()
{
setMethod(HTTP_METHOD::HTTP_METHOD_GET);
}
void setMethod(HTTP_METHOD protocol)
{
mMethod = protocol;
assert(mMethod > HTTP_METHOD::HTTP_METHOD_HEAD &&
mMethod < HTTP_METHOD::HTTP_METHOD_MAX);
}
void setHost(const std::string& host)
{
addHeadValue("Host", host);
}
void setUrl(const std::string& url)
{
mUrl = url;
}
void setCookie(const std::string& v)
{
addHeadValue("Cookie", v);
}
void setContentType(const std::string& v)
{
addHeadValue("Content-Type", v);
}
void setQuery(const std::string& query)
{
mQuery = query;
}
void setBody(const std::string& body)
{
mBody = body;
addHeadValue("Content-Length", std::to_string(body.size()));
}
void setBody(std::string&& body)
{
mBody = std::move(body);
addHeadValue("Content-Length", std::to_string(body.size()));
}
void addHeadValue(const std::string& field,
const std::string& value)
{
mHeadField[field] = value;
}
std::string getResult() const
{
const auto MethodMax = static_cast<size_t>(HTTP_METHOD::HTTP_METHOD_MAX);
const static std::array<std::string, MethodMax> HttpMethodString =
{"HEAD", "GET", "POST", "PUT", "DELETE"};
std::string ret;
if (mMethod >= HTTP_METHOD::HTTP_METHOD_HEAD &&
mMethod < HTTP_METHOD::HTTP_METHOD_MAX)
{
ret += HttpMethodString[static_cast<size_t>(mMethod)];
}
ret += " ";
ret += mUrl;
if (!mQuery.empty())
{
ret += "?";
ret += mQuery;
}
ret += " HTTP/1.1\r\n";
for (auto& v : mHeadField)
{
ret += v.first;
ret += ": ";
ret += v.second;
ret += "\r\n";
}
ret += "\r\n";
if (!mBody.empty())
{
ret += mBody;
}
return ret;
}
private:
std::string mUrl;
std::string mQuery;
std::string mBody;
HTTP_METHOD mMethod;
std::map<std::string, std::string> mHeadField;
};
class HttpResponse final
{
public:
enum class HTTP_RESPONSE_STATUS
{
NONE,
OK = 200,
};
HttpResponse()
: mStatus(HTTP_RESPONSE_STATUS::OK)
{
}
void setStatus(HTTP_RESPONSE_STATUS status)
{
mStatus = status;
}
void setContentType(const std::string& v)
{
addHeadValue("Content-Type", v);
}
void addHeadValue(const std::string& field,
const std::string& value)
{
mHeadField[field] = value;
}
void setBody(const std::string& body)
{
mBody = body;
addHeadValue("Content-Length", std::to_string(body.size()));
}
void setBody(std::string&& body)
{
mBody = std::move(body);
addHeadValue("Content-Length", std::to_string(body.size()));
}
std::string getResult() const
{
std::string ret = "HTTP/1.1 ";
ret += std::to_string(static_cast<int>(mStatus));
switch (mStatus)
{
case HTTP_RESPONSE_STATUS::OK:
ret += " OK";
break;
default:
ret += "UNKNOWN";
break;
}
ret += "\r\n";
for (auto& v : mHeadField)
{
ret += v.first;
ret += ": ";
ret += v.second;
ret += "\r\n";
}
ret += "\r\n";
if (!mBody.empty())
{
ret += mBody;
}
return ret;
}
private:
HTTP_RESPONSE_STATUS mStatus;
std::map<std::string, std::string> mHeadField;
std::string mBody;
};
}}}// namespace brynet::net::http
<commit_msg>fix bug of used after move<commit_after>#pragma once
#include <array>
#include <cassert>
#include <map>
#include <string>
namespace brynet { namespace net { namespace http {
class HttpQueryParameter final
{
public:
void add(const std::string& k, const std::string& v)
{
if (!mParameter.empty())
{
mParameter += "&";
}
mParameter += k;
mParameter += "=";
mParameter += v;
}
const std::string& getResult() const
{
return mParameter;
}
private:
std::string mParameter;
};
class HttpRequest final
{
public:
enum class HTTP_METHOD
{
HTTP_METHOD_HEAD,
HTTP_METHOD_GET,
HTTP_METHOD_POST,
HTTP_METHOD_PUT,
HTTP_METHOD_DELETE,
HTTP_METHOD_MAX
};
HttpRequest()
{
setMethod(HTTP_METHOD::HTTP_METHOD_GET);
}
void setMethod(HTTP_METHOD protocol)
{
mMethod = protocol;
assert(mMethod > HTTP_METHOD::HTTP_METHOD_HEAD &&
mMethod < HTTP_METHOD::HTTP_METHOD_MAX);
}
void setHost(const std::string& host)
{
addHeadValue("Host", host);
}
void setUrl(const std::string& url)
{
mUrl = url;
}
void setCookie(const std::string& v)
{
addHeadValue("Cookie", v);
}
void setContentType(const std::string& v)
{
addHeadValue("Content-Type", v);
}
void setQuery(const std::string& query)
{
mQuery = query;
}
void setBody(const std::string& body)
{
addHeadValue("Content-Length", std::to_string(body.size()));
mBody = body;
}
void setBody(std::string&& body)
{
addHeadValue("Content-Length", std::to_string(body.size()));
mBody = std::move(body);
}
void addHeadValue(const std::string& field,
const std::string& value)
{
mHeadField[field] = value;
}
std::string getResult() const
{
const auto MethodMax = static_cast<size_t>(HTTP_METHOD::HTTP_METHOD_MAX);
const static std::array<std::string, MethodMax> HttpMethodString =
{"HEAD", "GET", "POST", "PUT", "DELETE"};
std::string ret;
if (mMethod >= HTTP_METHOD::HTTP_METHOD_HEAD &&
mMethod < HTTP_METHOD::HTTP_METHOD_MAX)
{
ret += HttpMethodString[static_cast<size_t>(mMethod)];
}
ret += " ";
ret += mUrl;
if (!mQuery.empty())
{
ret += "?";
ret += mQuery;
}
ret += " HTTP/1.1\r\n";
for (auto& v : mHeadField)
{
ret += v.first;
ret += ": ";
ret += v.second;
ret += "\r\n";
}
ret += "\r\n";
if (!mBody.empty())
{
ret += mBody;
}
return ret;
}
private:
std::string mUrl;
std::string mQuery;
std::string mBody;
HTTP_METHOD mMethod;
std::map<std::string, std::string> mHeadField;
};
class HttpResponse final
{
public:
enum class HTTP_RESPONSE_STATUS
{
NONE,
OK = 200,
};
HttpResponse()
: mStatus(HTTP_RESPONSE_STATUS::OK)
{
}
void setStatus(HTTP_RESPONSE_STATUS status)
{
mStatus = status;
}
void setContentType(const std::string& v)
{
addHeadValue("Content-Type", v);
}
void addHeadValue(const std::string& field,
const std::string& value)
{
mHeadField[field] = value;
}
void setBody(const std::string& body)
{
addHeadValue("Content-Length", std::to_string(body.size()));
mBody = body;
}
void setBody(std::string&& body)
{
addHeadValue("Content-Length", std::to_string(body.size()));
mBody = std::move(body);
}
std::string getResult() const
{
std::string ret = "HTTP/1.1 ";
ret += std::to_string(static_cast<int>(mStatus));
switch (mStatus)
{
case HTTP_RESPONSE_STATUS::OK:
ret += " OK";
break;
default:
ret += "UNKNOWN";
break;
}
ret += "\r\n";
for (auto& v : mHeadField)
{
ret += v.first;
ret += ": ";
ret += v.second;
ret += "\r\n";
}
ret += "\r\n";
if (!mBody.empty())
{
ret += mBody;
}
return ret;
}
private:
HTTP_RESPONSE_STATUS mStatus;
std::map<std::string, std::string> mHeadField;
std::string mBody;
};
}}}// namespace brynet::net::http
<|endoftext|>
|
<commit_before>#ifndef ITERATOR_BASED_CRC32_H
#define ITERATOR_BASED_CRC32_H
#if defined(__x86_64__) && !defined(__MINGW64__)
#include <cpuid.h>
#endif
#include <boost/crc.hpp> // for boost::crc_32_type
#include <iterator>
namespace osrm
{
namespace contractor
{
class IteratorbasedCRC32
{
public:
bool using_hardware() const { return use_hardware_implementation; }
IteratorbasedCRC32() : crc(0) { use_hardware_implementation = detect_hardware_support(); }
template <class Iterator> unsigned operator()(Iterator iter, const Iterator end)
{
unsigned crc = 0;
while (iter != end)
{
using value_type = typename std::iterator_traits<Iterator>::value_type;
const char *data = reinterpret_cast<const char *>(&(*iter));
if (use_hardware_implementation)
{
crc = compute_in_hardware(data, sizeof(value_type));
}
else
{
crc = compute_in_software(data, sizeof(value_type));
}
++iter;
}
return crc;
}
private:
bool detect_hardware_support() const
{
static const int sse42_bit = 0x00100000;
const unsigned ecx = cpuid();
const bool sse42_found = (ecx & sse42_bit) != 0;
return sse42_found;
}
unsigned compute_in_software(const char *str, unsigned len)
{
crc_processor.process_bytes(str, len);
return crc_processor.checksum();
}
// adapted from http://byteworm.com/2010/10/13/crc32/
unsigned compute_in_hardware(const char *str, unsigned len)
{
#if defined(__x86_64__)
unsigned q = len / sizeof(unsigned);
unsigned r = len % sizeof(unsigned);
unsigned *p = (unsigned *)str;
// crc=0;
while (q--)
{
__asm__ __volatile__(".byte 0xf2, 0xf, 0x38, 0xf1, 0xf1;"
: "=S"(crc)
: "0"(crc), "c"(*p));
++p;
}
str = reinterpret_cast<char *>(p);
while (r--)
{
__asm__ __volatile__(".byte 0xf2, 0xf, 0x38, 0xf1, 0xf1;"
: "=S"(crc)
: "0"(crc), "c"(*str));
++str;
}
#endif
return crc;
}
inline unsigned cpuid() const
{
unsigned eax = 0, ebx = 0, ecx = 0, edx = 0;
// on X64 this calls hardware cpuid(.) instr. otherwise a dummy impl.
__get_cpuid(1, &eax, &ebx, &ecx, &edx);
return ecx;
}
#if defined(__MINGW64__) || defined(_MSC_VER) || !defined(__x86_64__)
inline void
__get_cpuid(int param, unsigned *eax, unsigned *ebx, unsigned *ecx, unsigned *edx) const
{
*ecx = 0;
}
#endif
boost::crc_optimal<32, 0x1EDC6F41, 0x0, 0x0, true, true> crc_processor;
unsigned crc;
bool use_hardware_implementation;
};
struct RangebasedCRC32
{
template <typename Iteratable> unsigned operator()(const Iteratable &iterable)
{
return crc32(std::begin(iterable), std::end(iterable));
}
bool using_hardware() const { return crc32.using_hardware(); }
private:
IteratorbasedCRC32 crc32;
};
}
}
#endif /* ITERATOR_BASED_CRC32_H */
<commit_msg>Clean up naming conventions in CRC32 code<commit_after>#ifndef ITERATOR_BASED_CRC32_H
#define ITERATOR_BASED_CRC32_H
#if defined(__x86_64__) && !defined(__MINGW64__)
#include <cpuid.h>
#endif
#include <boost/crc.hpp> // for boost::crc_32_type
#include <iterator>
namespace osrm
{
namespace contractor
{
class IteratorbasedCRC32
{
public:
bool UsingHardware() const { return use_hardware_implementation; }
IteratorbasedCRC32() : crc(0) { use_hardware_implementation = DetectHardwareSupport(); }
template <class Iterator> unsigned operator()(Iterator iter, const Iterator end)
{
unsigned crc = 0;
while (iter != end)
{
using value_type = typename std::iterator_traits<Iterator>::value_type;
const char *data = reinterpret_cast<const char *>(&(*iter));
if (use_hardware_implementation)
{
crc = ComputeInHardware(data, sizeof(value_type));
}
else
{
crc = ComputeInSoftware(data, sizeof(value_type));
}
++iter;
}
return crc;
}
private:
bool DetectHardwareSupport() const
{
static const int sse42_bit = 0x00100000;
const unsigned ecx = cpuid();
const bool sse42_found = (ecx & sse42_bit) != 0;
return sse42_found;
}
unsigned ComputeInSoftware(const char *str, unsigned len)
{
crc_processor.process_bytes(str, len);
return crc_processor.checksum();
}
// adapted from http://byteworm.com/2010/10/13/crc32/
unsigned ComputeInHardware(const char *str, unsigned len)
{
#if defined(__x86_64__)
unsigned q = len / sizeof(unsigned);
unsigned r = len % sizeof(unsigned);
unsigned *p = (unsigned *)str;
// crc=0;
while (q--)
{
__asm__ __volatile__(".byte 0xf2, 0xf, 0x38, 0xf1, 0xf1;"
: "=S"(crc)
: "0"(crc), "c"(*p));
++p;
}
str = reinterpret_cast<char *>(p);
while (r--)
{
__asm__ __volatile__(".byte 0xf2, 0xf, 0x38, 0xf1, 0xf1;"
: "=S"(crc)
: "0"(crc), "c"(*str));
++str;
}
#endif
return crc;
}
inline unsigned cpuid() const
{
unsigned eax = 0, ebx = 0, ecx = 0, edx = 0;
// on X64 this calls hardware cpuid(.) instr. otherwise a dummy impl.
__get_cpuid(1, &eax, &ebx, &ecx, &edx);
return ecx;
}
#if defined(__MINGW64__) || defined(_MSC_VER) || !defined(__x86_64__)
inline void
__get_cpuid(int param, unsigned *eax, unsigned *ebx, unsigned *ecx, unsigned *edx) const
{
*ecx = 0;
}
#endif
boost::crc_optimal<32, 0x1EDC6F41, 0x0, 0x0, true, true> crc_processor;
unsigned crc;
bool use_hardware_implementation;
};
struct RangebasedCRC32
{
template <typename Iteratable> unsigned operator()(const Iteratable &iterable)
{
return crc32(std::begin(iterable), std::end(iterable));
}
bool UsingHardware() const { return crc32.UsingHardware(); }
private:
IteratorbasedCRC32 crc32;
};
}
}
#endif /* ITERATOR_BASED_CRC32_H */
<|endoftext|>
|
<commit_before>#include "Logger.hpp"
#include <iostream>
#include "stream.hpp"
namespace wrd {
WRD_DEF_THIS(Logger)
typedef std::string string;
typedef wrd::BuildFeature::Config Config;
const wchar* This::getName() const { return "Logger"; }
const Stream& This::operator[](widx n) const { return getStream(n); }
Stream& This::operator[](widx n) { return getStream(n); }
const Stream& This::operator[](const wchar* message) const { return getStream(message); }
Stream& This::operator[](const wchar* message) { return getStream(message); }
Stream& This::getStream(widx n) {
if(n < 0 || n >= getStreamCount())
return nulOf<Stream>();
return *_streams[n];
}
const Stream& This::getStream(widx n) const {
WRD_UNCONST()
return unconst.getStream(n);
}
const Stream& This::getStream(const wchar* c_message) const {
string message = c_message;
for(auto e : _streams)
if(string(e->getName()) == message)
return *e;
return nulOf<Stream>();
}
Stream& This::getStream(const wchar* message) {
const This* consted = this;
return const_cast<Stream&>(consted->getStream(message));
}
wcnt This::getStreamCount() const { return _streams.size(); }
wbool This::dump(const wchar* message) {
wbool result = false;
for(auto e : _streams)
result |= e->dump(message);
return result;
}
wbool This::dumpFormat(const wchar* fmt, ...) {
va_list va;
va_start(va, fmt);
wchar buf[1024];
vsnprintf(buf, 1024, fmt, va);
va_end(va);
return dump(buf);
}
wbool This::pushStream(Stream* new_stream) {
if( ! new_stream) return true;
_streams.push_back(new_stream);
if(isInit())
return new_stream->init();
return false;
}
wbool This::init() {
rel();
static Stream* streams[] = {new ConsoleStream(), new FileLogStream("./logs"), 0};
Stream* e = 0;
for(int n=0; (e = streams[n]) ;n++)
pushStream(e);
return false;
}
wbool This::isInit() const {
for(auto e : _streams)
if( ! e->isInit())
return false;
return true;
}
wbool This::rel() {
for(auto e : _streams)
{
e->rel();
delete e;
}
_streams.clear();
return Super::rel();
}
This& This::get() {
static This* inner = 0;
if(inner->isNull())
{
inner = new This();
inner->init();
}
return *inner;
}
This::Logger() : Super() {}
This::Logger(const This& rhs) : Super(rhs) {}
}
<commit_msg>- [clog] setDisable of Logger doesn't work.<commit_after>#include "Logger.hpp"
#include <iostream>
#include "stream.hpp"
namespace wrd {
WRD_DEF_THIS(Logger)
typedef std::string string;
typedef wrd::BuildFeature::Config Config;
const wchar* This::getName() const { return "Logger"; }
const Stream& This::operator[](widx n) const { return getStream(n); }
Stream& This::operator[](widx n) { return getStream(n); }
const Stream& This::operator[](const wchar* message) const { return getStream(message); }
Stream& This::operator[](const wchar* message) { return getStream(message); }
Stream& This::getStream(widx n) {
if(n < 0 || n >= getStreamCount())
return nulOf<Stream>();
return *_streams[n];
}
const Stream& This::getStream(widx n) const {
WRD_UNCONST()
return unconst.getStream(n);
}
const Stream& This::getStream(const wchar* c_message) const {
string message = c_message;
for(auto e : _streams)
if(string(e->getName()) == message)
return *e;
return nulOf<Stream>();
}
Stream& This::getStream(const wchar* message) {
const This* consted = this;
return const_cast<Stream&>(consted->getStream(message));
}
wcnt This::getStreamCount() const { return _streams.size(); }
wbool This::dump(const wchar* message) {
if(!isEnable()) return false;
wbool result = false;
for(auto e : _streams)
result |= e->dump(message);
return result;
}
wbool This::dumpFormat(const wchar* fmt, ...) {
va_list va;
va_start(va, fmt);
wchar buf[1024];
vsnprintf(buf, 1024, fmt, va);
va_end(va);
return dump(buf);
}
wbool This::pushStream(Stream* new_stream) {
if( ! new_stream) return true;
_streams.push_back(new_stream);
if(isInit())
return new_stream->init();
return false;
}
wbool This::init() {
rel();
Super::init();
static Stream* streams[] = {new ConsoleStream(), new FileLogStream("./logs"), 0};
Stream* e = 0;
for(int n=0; (e = streams[n]) ;n++)
pushStream(e);
return false;
}
wbool This::isInit() const {
for(auto e : _streams)
if( ! e->isInit())
return false;
return true;
}
wbool This::rel() {
for(auto e : _streams)
{
e->rel();
delete e;
}
_streams.clear();
return Super::rel();
}
This& This::get() {
static This* inner = 0;
if(inner->isNull())
{
inner = new This();
inner->init();
}
return *inner;
}
This::Logger() : Super() {}
This::Logger(const This& rhs) : Super(rhs) {}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: MNameMapper.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: oj $ $Date: 2001-11-26 13:52:26 $
*
* 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): Darren Kenny
*
*
************************************************************************/
#include <MNameMapper.hxx>
#ifdef _DEBUG
# define OUtoCStr( x ) ( ::rtl::OUStringToOString ( (x), RTL_TEXTENCODING_ASCII_US).getStr())
#else /* _DEBUG */
# define OUtoCStr( x ) ("dummy")
#endif /* _DEBUG */
using namespace connectivity::mozab;
using namespace rtl;
bool
MNameMapper::ltstr::operator()( const ::rtl::OUString &s1, const ::rtl::OUString &s2) const
{
return s1.compareTo(s2) < 0;
}
MNameMapper::MNameMapper()
{
mDirMap = new MNameMapper::dirMap;
}
MNameMapper::~MNameMapper()
{
if ( mDirMap != NULL ) {
MNameMapper::dirMap::iterator iter;
for (iter = mDirMap -> begin(); iter != mDirMap -> end(); ++iter) {
NS_IF_RELEASE(((*iter).second));
}
delete mDirMap;
}
}
// May modify the name passed in so that it's unique
void
MNameMapper::add( ::rtl::OUString& str, nsIAbDirectory* abook )
{
MNameMapper::dirMap::iterator iter;
OSL_TRACE( "IN MNameMapper::add()\n" );
if ( abook == NULL ) {
OSL_TRACE( "\tOUT MNameMapper::add() called with null abook\n" );
return;
}
if ( mDirMap->find( str ) != mDirMap->end() ) {
// TODO - There's already and entry, so make the name unique
}
NS_IF_ADDREF(abook);
mDirMap->insert( MNameMapper::dirMap::value_type( str, abook ) );
OSL_TRACE( "\tOUT MNameMapper::add()\n" );
}
// Will replace the given dir
void
MNameMapper::replace( const ::rtl::OUString& str, nsIAbDirectory* abook )
{
// TODO - needs to be implemented...
OSL_TRACE( "IN/OUT MNameMapper::add()\n" );
}
bool
MNameMapper::getDir( const ::rtl::OUString& str, nsIAbDirectory* *abook )
{
MNameMapper::dirMap::iterator iter;
OSL_TRACE( "IN MNameMapper::getDir( %s )\n", OUtoCStr(str)?OUtoCStr(str):"NULL" );
if ( (iter = mDirMap->find( str )) != mDirMap->end() ) {
*abook = (*iter).second;
NS_IF_ADDREF(*abook);
} else {
*abook = NULL;
}
OSL_TRACE( "\tOUT MNameMapper::getDir() : %s\n", (*abook)?"True":"False" );
return( (*abook) != NULL );
}
<commit_msg>INTEGRATION: CWS dbgmacros1 (1.3.68); FILE MERGED 2003/04/09 10:23:32 kso 1.3.68.1: #108413# - debug macro unification.<commit_after>/*************************************************************************
*
* $RCSfile: MNameMapper.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2003-04-15 17:38:55 $
*
* 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): Darren Kenny
*
*
************************************************************************/
#include <MNameMapper.hxx>
#if OSL_DEBUG_LEVEL > 0
# define OUtoCStr( x ) ( ::rtl::OUStringToOString ( (x), RTL_TEXTENCODING_ASCII_US).getStr())
#else /* OSL_DEBUG_LEVEL */
# define OUtoCStr( x ) ("dummy")
#endif /* OSL_DEBUG_LEVEL */
using namespace connectivity::mozab;
using namespace rtl;
bool
MNameMapper::ltstr::operator()( const ::rtl::OUString &s1, const ::rtl::OUString &s2) const
{
return s1.compareTo(s2) < 0;
}
MNameMapper::MNameMapper()
{
mDirMap = new MNameMapper::dirMap;
}
MNameMapper::~MNameMapper()
{
if ( mDirMap != NULL ) {
MNameMapper::dirMap::iterator iter;
for (iter = mDirMap -> begin(); iter != mDirMap -> end(); ++iter) {
NS_IF_RELEASE(((*iter).second));
}
delete mDirMap;
}
}
// May modify the name passed in so that it's unique
void
MNameMapper::add( ::rtl::OUString& str, nsIAbDirectory* abook )
{
MNameMapper::dirMap::iterator iter;
OSL_TRACE( "IN MNameMapper::add()\n" );
if ( abook == NULL ) {
OSL_TRACE( "\tOUT MNameMapper::add() called with null abook\n" );
return;
}
if ( mDirMap->find( str ) != mDirMap->end() ) {
// TODO - There's already and entry, so make the name unique
}
NS_IF_ADDREF(abook);
mDirMap->insert( MNameMapper::dirMap::value_type( str, abook ) );
OSL_TRACE( "\tOUT MNameMapper::add()\n" );
}
// Will replace the given dir
void
MNameMapper::replace( const ::rtl::OUString& str, nsIAbDirectory* abook )
{
// TODO - needs to be implemented...
OSL_TRACE( "IN/OUT MNameMapper::add()\n" );
}
bool
MNameMapper::getDir( const ::rtl::OUString& str, nsIAbDirectory* *abook )
{
MNameMapper::dirMap::iterator iter;
OSL_TRACE( "IN MNameMapper::getDir( %s )\n", OUtoCStr(str)?OUtoCStr(str):"NULL" );
if ( (iter = mDirMap->find( str )) != mDirMap->end() ) {
*abook = (*iter).second;
NS_IF_ADDREF(*abook);
} else {
*abook = NULL;
}
OSL_TRACE( "\tOUT MNameMapper::getDir() : %s\n", (*abook)?"True":"False" );
return( (*abook) != NULL );
}
<|endoftext|>
|
<commit_before>//(c) 2016 by Authors
//This file is a part of ABruijn program.
//Released under the BSD license (see LICENSE file)
#include "general_polisher.h"
#include "alignment.h"
void GeneralPolisher::polishBubble(Bubble& bubble) const
{
auto optimize = [this] (const std::string& candidate,
const std::vector<std::string>& branches,
std::vector<StepInfo>& polishSteps)
{
std::string prevCandidate = candidate;
Alignment align(branches.size(), _subsMatrix);
while(true)
{
StepInfo rec = this->makeStep(prevCandidate, branches, align);
polishSteps.push_back(rec);
if (prevCandidate == rec.sequence) return prevCandidate;
prevCandidate = rec.sequence;
}
};
const int PRE_POLISH = 5;
//first, select closest X branches (by length) and polish with them
std::string prePolished = bubble.candidate;
if (bubble.branches.size() > PRE_POLISH * 2)
{
std::sort(bubble.branches.begin(), bubble.branches.end(),
[](const std::string& s1, const std::string& s2)
{return s1.length() < s2.length();});
size_t left = bubble.branches.size() / 2 - PRE_POLISH / 2;
size_t right = left + PRE_POLISH;
std::vector<std::string> reducedSet(bubble.branches.begin() + left,
bubble.branches.begin() + right);
prePolished = optimize(prePolished, reducedSet,
bubble.polishSteps);
}
//then, polish with all branches
bubble.candidate = optimize(prePolished, bubble.branches,
bubble.polishSteps);
}
StepInfo GeneralPolisher::makeStep(const std::string& candidate,
const std::vector<std::string>& branches,
Alignment& align) const
{
StepInfo stepResult;
//Global
double score = 0;
for (size_t i = 0; i < branches.size(); ++i)
{
score += align.globalAlignment(candidate, branches[i], i);
}
stepResult.score = score;
stepResult.sequence = candidate;
//Deletion
for (size_t del_index = 0; del_index < candidate.size(); del_index++)
{
score = 0;
for (size_t i = 0; i < branches.size(); i++)
{
score += align.addDeletion(i, del_index + 1);
}
if (score > stepResult.score)
{
stepResult.score = score;
stepResult.sequence = candidate;
stepResult.sequence.erase(del_index, 1);
}
}
//Substitution
char alphabet[4] = {'A', 'C', 'G', 'T'};
for (size_t sub_index = 0; sub_index < candidate.size(); sub_index++)
{
for (char letter : alphabet)
{
if (letter == candidate[sub_index]) continue;
score = 0;
for (size_t i = 0; i < branches.size(); i++)
{
score += align.addSubstitution(i, sub_index + 1, letter,
branches[i]);
}
if (score > stepResult.score)
{
stepResult.score = score;
stepResult.sequence = candidate;
stepResult.sequence[sub_index] = letter;
}
}
}
//Insertion
for (size_t ins_index = 0; ins_index < candidate.size()+1; ins_index++)
{
for (char letter : alphabet)
{
score = 0;
for (size_t i = 0; i < branches.size(); i++)
{
score += align.addInsertion(i, ins_index + 1, letter,
branches[i]);
}
if (score > stepResult.score)
{
stepResult.score = score;
stepResult.sequence = candidate;
stepResult.sequence.insert(ins_index, 1, letter);
}
}
}
return stepResult;
}
<commit_msg>changed order of polishing operations<commit_after>//(c) 2016 by Authors
//This file is a part of ABruijn program.
//Released under the BSD license (see LICENSE file)
#include "general_polisher.h"
#include "alignment.h"
void GeneralPolisher::polishBubble(Bubble& bubble) const
{
auto optimize = [this] (const std::string& candidate,
const std::vector<std::string>& branches,
std::vector<StepInfo>& polishSteps)
{
std::string prevCandidate = candidate;
Alignment align(branches.size(), _subsMatrix);
while(true)
{
StepInfo rec = this->makeStep(prevCandidate, branches, align);
polishSteps.push_back(rec);
if (prevCandidate == rec.sequence) return prevCandidate;
prevCandidate = rec.sequence;
}
};
//first, select closest X branches (by length) and polish with them
const int PRE_POLISH = 5;
std::string prePolished = bubble.candidate;
if (bubble.branches.size() > PRE_POLISH * 2)
{
std::sort(bubble.branches.begin(), bubble.branches.end(),
[](const std::string& s1, const std::string& s2)
{return s1.length() < s2.length();});
size_t left = bubble.branches.size() / 2 - PRE_POLISH / 2;
size_t right = left + PRE_POLISH;
std::vector<std::string> reducedSet(bubble.branches.begin() + left,
bubble.branches.begin() + right);
prePolished = optimize(prePolished, reducedSet,
bubble.polishSteps);
}
//then, polish with all branches
bubble.candidate = optimize(prePolished, bubble.branches,
bubble.polishSteps);
}
StepInfo GeneralPolisher::makeStep(const std::string& candidate,
const std::vector<std::string>& branches,
Alignment& align) const
{
static char alphabet[] = {'A', 'C', 'G', 'T'};
StepInfo stepResult;
//Alignment
double score = 0;
for (size_t i = 0; i < branches.size(); ++i)
{
score += align.globalAlignment(candidate, branches[i], i);
}
stepResult.score = score;
stepResult.sequence = candidate;
//Deletion
bool improvement = false;
for (size_t pos = 0; pos < candidate.size(); ++pos)
{
double score = 0;
for (size_t i = 0; i < branches.size(); i++)
{
score += align.addDeletion(i, pos + 1);
}
if (score > stepResult.score)
{
stepResult.score = score;
stepResult.sequence = candidate;
stepResult.sequence.erase(pos, 1);
improvement = true;
}
}
if (improvement) return stepResult;
//Insertion
improvement = false;
for (size_t pos = 0; pos < candidate.size() + 1; ++pos)
{
for (char letter : alphabet)
{
double score = 0;
for (size_t i = 0; i < branches.size(); i++)
{
score += align.addInsertion(i, pos + 1, letter,
branches[i]);
}
if (score > stepResult.score)
{
stepResult.score = score;
stepResult.sequence = candidate;
stepResult.sequence.insert(pos, 1, letter);
improvement = true;
}
}
}
if (improvement) return stepResult;
//Substitution
for (size_t pos = 0; pos < candidate.size(); ++pos)
{
for (char letter : alphabet)
{
if (letter == candidate[pos]) continue;
double score = 0;
for (size_t i = 0; i < branches.size(); i++)
{
score += align.addSubstitution(i, pos + 1, letter,
branches[i]);
}
if (score > stepResult.score)
{
stepResult.score = score;
stepResult.sequence = candidate;
stepResult.sequence[pos] = letter;
}
}
}
return stepResult;
}
<|endoftext|>
|
<commit_before>#include "SpotsScene.h"
// ----------------------------------------------------
void SpotsScene::setup() {
name = "spots scene";
string safeName = name;
ofStringReplace(safeName, " ", "_");
gui.setup(name, safeName+".xml", 20, 20);
gui.add(maxShapesOnScreen.setup("max shapes", 250, 1, 1000));
gui.add(releaseRate.setup("release rate", 0.2, 0.0, 1.0));
// setup box2d
box2d.init();
box2d.setGravity(0, 0);
box2d.setFPS(60);
circleFrcFlip = false;
bgColorTarget = ofRandomColor();
}
// ----------------------------------------------------
void SpotsScene::exitScene() {
BaseScene::exitScene();
//shapes.clear();
}
// ----------------------------------------------------
void SpotsScene::update() {
int nShapesToAdd = MAX(1, 10 * releaseRate);
for(int i=0; i<nShapesToAdd; i++) {
addShape();
}
for (vector<SpotShape>::iterator it=shapes.begin(); it!=shapes.end(); ++it) {
it->update();
it->addAttractionPoint(circleFrc + ofGetCenterScreen(), 0.03);//(ofGetCenterScreen(), 0.0002);
if(it->getPosition().distance(ofGetCenterScreen()) < 300) {
it->addRepulsionForce(ofGetCenterScreen(), 0.002);
}
}
box2d.update();
}
// ----------------------------------------------------
void SpotsScene::addPoints() {
pts.clear();
for(int i=0; i<6; i++) {
float x = ofRandom(10, CUBE_SCREEN_WIDTH-10);
float y = ofRandom(10, CUBE_SCREEN_HEIGHT-10);
pts.push_back(ofVec2f(x, y));
}
tris = triangulatePolygon(pts);
}
// ----------------------------------------------------
void SpotsScene::addShape() {
if(shapes.size() < maxShapesOnScreen) {
ofVec2f pt = ofGetCenterScreen();
float r = ofRandom(10, 30);
pt.x += cos(ofRandomuf()*TWO_PI) * r;
pt.y += sin(ofRandomuf()*TWO_PI) * r;
SpotShape shape;
shape.setPhysics(1, 0.1, 1);
shape.setup(box2d.getWorld(), pt, 1);
shape.radiusTarget = ofRandom(10, 30);
shapes.push_back(shape);
}
}
// ----------------------------------------------------
void SpotsScene::makeObstacles() {
obsticals.clear();
for (vector<TriangleShape>::iterator it=tris.begin(); it!=tris.end(); ++it) {
float radius = GeometryUtils::getTriangleRadius(it->c, it->b, it->a);
ofVec2f center = GeometryUtils::getTriangleCenter(it->a, it->b, it->c);
ofxBox2dCircle ob;
ob.setPhysics(0, 0.1, 1);
ob.setup(box2d.getWorld(), center, radius);
obsticals.push_back(ob);
}
}
// ----------------------------------------------------
void SpotsScene::keyPressed(int key) {
if(key == ' ') {
//addPoints();
//makeObstacles();
}
if(key == 'r') {
for(int i=0; i<MIN(30, shapes.size()-1); i++) {
int ranId = (int)ofRandom(0, shapes.size()-1);
shapes[ranId].radiusTarget = ofRandom(30, 100);
}
}
if(key == 's') {
for(int i=0; i<MIN(230, shapes.size()-1); i++) {
int ranId = (int)ofRandom(0, shapes.size()-1);
shapes[ranId].radiusTarget = ofRandom(2, 10);
}
}
if(key == 'b') {
bgColorTarget = ofRandomColor();
}
}
// ----------------------------------------------------
void SpotsScene::draw() {
drawBackground();
ofEnableAlphaBlending();
if((int)ofRandom(0, 300) == 30) {
circleFrcFlip = !circleFrcFlip;
}
float n = ofGetElapsedTimef() * 0.2;
if(circleFrcFlip) n *= -1;
float r = 5 + ofNoise(n, circleFrc.x/3000.0) * 300;
circleFrc.x = cos(n*TWO_PI) * r;
circleFrc.y = sin(n*TWO_PI) * r;
ofSetColor(255, 0, 0);
ofCircle(circleFrc+ofGetCenterScreen(), 13);
ofSetColor(255);
for (vector<SpotShape>::iterator it=shapes.begin(); it!=shapes.end(); ++it) {
ofVec2f p = it->getPosition();
float r = it->getRadius();
// it->tex->bind();
// glBegin(GL_QUADS);
//
// glVertex2f(p.x-r, p.y-r); glTexCoord2f(0, 0);
// glVertex2f(p.x+r, p.y-r); glTexCoord2f(1, 0);
// glVertex2f(p.x+r, p.y+r); glTexCoord2f(1, 1);
// glVertex2f(p.x-r, p.y+r); glTexCoord2f(0, 1);
//
ofSphere(p, 10);
// glEnd();
// it->tex->unbind();
if(!isPointInScreen(p, r)) {
it->destroy();
it->dead = true;
}
}
ofRemove(shapes, ofxBox2dBaseShape::shouldRemove);
ofFill();
ofSetColor(255, 100);
for (vector<ofVec2f>::iterator it=pts.begin(); it!=pts.end(); ++it) {
ofCircle(*it, 2);
}
for (vector<TriangleShape>::iterator it=tris.begin(); it!=tris.end(); ++it) {
ofSetColor(255, 10);
ofNoFill();
ofTriangle(it->a, it->b, it->c);
// the triangle area
float radius = GeometryUtils::getTriangleRadius(it->c, it->b, it->a);
// center of the triangle
ofVec2f center = GeometryUtils::getTriangleCenter(it->a, it->b, it->c);
ofCircle(center, radius);
/*ofSetColor(255);
ofDrawBitmapString("a", it->a+10);
ofDrawBitmapString("b", it->b+10);
ofDrawBitmapString("c", it->c+10);*/
ofCircle(center, 3);
}
ofSetColor(255);
ofDrawBitmapString(ofToString(box2d.getBodyCount()), 20, 50);
ofDrawBitmapString(ofToString(shapes.size()), 20, 90);
ofDrawBitmapString("r make bigger\ns make smaller", 20, 120);
gui.draw();
}
// ----------------------------------------------------
void SpotsScene::handleCommands(TwitterCommand& cmd, Effects& fx) {
// handle commands.
set<string>::const_iterator it = cmd.tokens.begin();
while(it != cmd.tokens.end()) {
const string& c = (*it);
if(c == "bigger") {
for(int i=0; i<MIN(30, shapes.size()-1); i++) {
int ranId = (int)ofRandom(0, shapes.size()-1);
shapes[ranId].radiusTarget = ofRandom(30, 100);
}
}
else if(c == "smaller") {
for(int i=0; i<MIN(30, shapes.size()-1); i++) {
int ranId = (int)ofRandom(0, shapes.size()-1);
shapes[ranId].radiusTarget = ofRandom(2, 10);
}
}
fx.applyEffect(c);
++it;
}
// handle colour
map<string, ofColor>::const_iterator cit = cmd.colours.begin();
while(cit != cmd.colours.end()) {
bgColorTarget = cit->second;
break;
}
}<commit_msg>Switched spot scene to have a black background and foreground colour as per setting<commit_after>#include "SpotsScene.h"
// ----------------------------------------------------
void SpotsScene::setup() {
name = "spots scene";
string safeName = name;
ofStringReplace(safeName, " ", "_");
gui.setup(name, safeName+".xml", 20, 20);
gui.add(maxShapesOnScreen.setup("max shapes", 250, 1, 1000));
gui.add(releaseRate.setup("release rate", 0.2, 0.0, 1.0));
// setup box2d
box2d.init();
box2d.setGravity(0, 0);
box2d.setFPS(60);
circleFrcFlip = false;
bgColorTarget = ofRandomColor();
}
// ----------------------------------------------------
void SpotsScene::exitScene() {
BaseScene::exitScene();
//shapes.clear();
}
// ----------------------------------------------------
void SpotsScene::update() {
int nShapesToAdd = MAX(1, 10 * releaseRate);
for(int i=0; i<nShapesToAdd; i++) {
addShape();
}
for (vector<SpotShape>::iterator it=shapes.begin(); it!=shapes.end(); ++it) {
it->update();
it->addAttractionPoint(circleFrc + ofGetCenterScreen(), 0.03);//(ofGetCenterScreen(), 0.0002);
if(it->getPosition().distance(ofGetCenterScreen()) < 300) {
it->addRepulsionForce(ofGetCenterScreen(), 0.002);
}
}
box2d.update();
}
// ----------------------------------------------------
void SpotsScene::addPoints() {
pts.clear();
for(int i=0; i<6; i++) {
float x = ofRandom(10, CUBE_SCREEN_WIDTH-10);
float y = ofRandom(10, CUBE_SCREEN_HEIGHT-10);
pts.push_back(ofVec2f(x, y));
}
tris = triangulatePolygon(pts);
}
// ----------------------------------------------------
void SpotsScene::addShape() {
if(shapes.size() < maxShapesOnScreen) {
ofVec2f pt = ofGetCenterScreen();
float r = ofRandom(10, 30);
pt.x += cos(ofRandomuf()*TWO_PI) * r;
pt.y += sin(ofRandomuf()*TWO_PI) * r;
SpotShape shape;
shape.setPhysics(1, 0.1, 1);
shape.setup(box2d.getWorld(), pt, 1);
shape.radiusTarget = ofRandom(70, 100);
shapes.push_back(shape);
}
}
// ----------------------------------------------------
void SpotsScene::makeObstacles() {
obsticals.clear();
for (vector<TriangleShape>::iterator it=tris.begin(); it!=tris.end(); ++it) {
float radius = GeometryUtils::getTriangleRadius(it->c, it->b, it->a);
ofVec2f center = GeometryUtils::getTriangleCenter(it->a, it->b, it->c);
ofxBox2dCircle ob;
ob.setPhysics(0, 0.1, 1);
ob.setup(box2d.getWorld(), center, radius);
obsticals.push_back(ob);
}
}
// ----------------------------------------------------
void SpotsScene::keyPressed(int key) {
if(key == ' ') {
//addPoints();
//makeObstacles();
}
if(key == 'r') {
for(int i=0; i<MIN(30, shapes.size()-1); i++) {
int ranId = (int)ofRandom(0, shapes.size()-1);
shapes[ranId].radiusTarget = ofRandom(30, 100);
}
}
if(key == 's') {
for(int i=0; i<MIN(230, shapes.size()-1); i++) {
int ranId = (int)ofRandom(0, shapes.size()-1);
shapes[ranId].radiusTarget = ofRandom(2, 10);
}
}
if(key == 'b') {
bgColorTarget = ofRandomColor();
}
}
// ----------------------------------------------------
void SpotsScene::draw() {
drawBackground(); //just to update the background colour, sloppy
ofSetColor(ofColor::black);
ofFill();
ofRect(0, 0, CUBE_SCREEN_WIDTH, CUBE_SCREEN_HEIGHT);
ofEnableAlphaBlending();
if((int)ofRandom(0, 300) == 30) {
circleFrcFlip = !circleFrcFlip;
}
float n = ofGetElapsedTimef() * 0.2;
if(circleFrcFlip) n *= -1;
float r = 5 + ofNoise(n, circleFrc.x/3000.0) * 300;
circleFrc.x = cos(n*TWO_PI) * r;
circleFrc.y = sin(n*TWO_PI) * r;
ofSetColor(255, 0, 0);
ofCircle(circleFrc+ofGetCenterScreen(), 13);
ofSetColor(bgColor);
for (vector<SpotShape>::iterator it=shapes.begin(); it!=shapes.end(); ++it) {
ofVec2f p = it->getPosition();
float r = it->getRadius();
// it->tex->bind();
// glBegin(GL_QUADS);
//
// glVertex2f(p.x-r, p.y-r); glTexCoord2f(0, 0);
// glVertex2f(p.x+r, p.y-r); glTexCoord2f(1, 0);
// glVertex2f(p.x+r, p.y+r); glTexCoord2f(1, 1);
// glVertex2f(p.x-r, p.y+r); glTexCoord2f(0, 1);
//
ofSphere(p, 10);
// glEnd();
// it->tex->unbind();
if(!isPointInScreen(p, r)) {
it->destroy();
it->dead = true;
}
}
ofRemove(shapes, ofxBox2dBaseShape::shouldRemove);
ofFill();
ofSetColor(bgColor, 100);
for (vector<ofVec2f>::iterator it=pts.begin(); it!=pts.end(); ++it) {
ofCircle(*it, 2);
}
for (vector<TriangleShape>::iterator it=tris.begin(); it!=tris.end(); ++it) {
ofSetColor(bgColor, 10);
ofNoFill();
ofTriangle(it->a, it->b, it->c);
// the triangle area
float radius = GeometryUtils::getTriangleRadius(it->c, it->b, it->a);
// center of the triangle
ofVec2f center = GeometryUtils::getTriangleCenter(it->a, it->b, it->c);
ofCircle(center, radius);
/*ofSetColor(255);
ofDrawBitmapString("a", it->a+10);
ofDrawBitmapString("b", it->b+10);
ofDrawBitmapString("c", it->c+10);*/
ofCircle(center, 3);
}
ofSetColor(255);
ofDrawBitmapString(ofToString(box2d.getBodyCount()), 20, 50);
ofDrawBitmapString(ofToString(shapes.size()), 20, 90);
ofDrawBitmapString("r make bigger\ns make smaller", 20, 120);
gui.draw();
}
// ----------------------------------------------------
void SpotsScene::handleCommands(TwitterCommand& cmd, Effects& fx) {
// handle commands.
set<string>::const_iterator it = cmd.tokens.begin();
while(it != cmd.tokens.end()) {
const string& c = (*it);
if(c == "bigger") {
for(int i=0; i<MIN(30, shapes.size()-1); i++) {
int ranId = (int)ofRandom(0, shapes.size()-1);
shapes[ranId].radiusTarget = ofRandom(30, 100);
}
}
else if(c == "smaller") {
for(int i=0; i<MIN(30, shapes.size()-1); i++) {
int ranId = (int)ofRandom(0, shapes.size()-1);
shapes[ranId].radiusTarget = ofRandom(2, 10);
}
}
fx.applyEffect(c);
++it;
}
// handle colour
map<string, ofColor>::const_iterator cit = cmd.colours.begin();
while(cit != cmd.colours.end()) {
bgColorTarget = cit->second;
break;
}
}<|endoftext|>
|
<commit_before>// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
//
#include "contrib/endpoints/src/api_manager/context/request_context.h"
#include <uuid/uuid.h>
#include <sstream>
using ::google::api_manager::utils::Status;
namespace google {
namespace api_manager {
namespace context {
namespace {
// Cloud Trace Context Header
const char kCloudTraceContextHeader[] = "X-Cloud-Trace-Context";
// Log message prefix for a success method.
const char kMessage[] = "Method: ";
// Log message prefix for an ignored method.
const char kIgnoredMessage[] =
"Endpoints management skipped for an unrecognized HTTP call: ";
// Unknown HTTP verb.
const char kUnknownHttpVerb[] = "<Unknown HTTP Verb>";
// Service control does not currently support logging with an empty
// operation name so we use this value until fix is available.
const char kUnrecognizedOperation[] = "<Unknown Operation Name>";
// Maximum 36 byte string for UUID
const int kMaxUUIDBufSize = 40;
// Default api key names
const char kDefaultApiKeyQueryName1[] = "key";
const char kDefaultApiKeyQueryName2[] = "api_key";
const char kDefaultApiKeyHeaderName[] = "x-api-key";
// Default location
const char kDefaultLocation[] = "us-central1";
// Genereates a UUID string
std::string GenerateUUID() {
char uuid_buf[kMaxUUIDBufSize];
uuid_t uuid;
uuid_generate(uuid);
uuid_unparse(uuid, uuid_buf);
return uuid_buf;
}
} // namespace
using context::ServiceContext;
RequestContext::RequestContext(std::shared_ptr<ServiceContext> service_context,
std::unique_ptr<Request> request)
: service_context_(service_context),
request_(std::move(request)),
is_first_report_(true) {
start_time_ = std::chrono::system_clock::now();
last_report_time_ = std::chrono::steady_clock::now();
operation_id_ = GenerateUUID();
const std::string &method = request_->GetRequestHTTPMethod();
const std::string &path = request_->GetRequestPath();
std::string query_params = request_->GetQueryParameters();
// In addition to matching the method, service_context_->GetMethodCallInfo()
// will extract the variable bindings from the url. We need variable bindings
// only when we need to do transcoding. If this turns out to be a performance
// problem for non-transcoded calls, we have a couple of options:
// 1) Do not extract variable bindings here, and do the method matching again
// with extracting variable bindings when transcoding is needed.
// 2) Store all the pieces needed for extracting variable bindings (such as
// http template variables, url path parts) in MethodCallInfo and extract
// variables lazily when needed.
method_call_ =
service_context_->GetMethodCallInfo(method, path, query_params);
if (method_call_.method_info) {
ExtractApiKey();
}
request_->FindHeader("referer", &http_referer_);
// Enable trace if tracing is not force disabled and the triggering header is
// set.
if (service_context_->cloud_trace_aggregator()) {
std::string trace_context_header;
request_->FindHeader(kCloudTraceContextHeader, &trace_context_header);
std::string method_name = kUnrecognizedOperation;
if (method_call_.method_info) {
method_name = method_call_.method_info->selector();
}
// qualify with the service name
method_name = service_context_->service_name() + "/" + method_name;
cloud_trace_.reset(cloud_trace::CreateCloudTrace(
trace_context_header, method_name,
&service_context_->cloud_trace_aggregator()->sampler()));
}
}
void RequestContext::ExtractApiKey() {
bool api_key_defined = false;
auto url_queries = method()->api_key_url_query_parameters();
if (url_queries) {
api_key_defined = true;
for (const auto &url_query : *url_queries) {
if (request_->FindQuery(url_query, &api_key_)) {
return;
}
}
}
auto headers = method()->api_key_http_headers();
if (headers) {
api_key_defined = true;
for (const auto &header : *headers) {
if (request_->FindHeader(header, &api_key_)) {
return;
}
}
}
if (!api_key_defined) {
// If api_key is not specified for a method,
// check "key" first, if not, check "api_key" in query parameter.
if (!request_->FindQuery(kDefaultApiKeyQueryName1, &api_key_)) {
if (!request_->FindQuery(kDefaultApiKeyQueryName2, &api_key_)) {
request_->FindHeader(kDefaultApiKeyHeaderName, &api_key_);
}
}
}
}
void RequestContext::CompleteCheck(Status status) {
// Makes sure set_check_continuation() is called.
// Only making sure CompleteCheck() is NOT called twice.
GOOGLE_CHECK(check_continuation_);
auto temp_continuation = check_continuation_;
check_continuation_ = nullptr;
temp_continuation(status);
}
void RequestContext::FillOperationInfo(service_control::OperationInfo *info) {
if (method()) {
info->operation_name = method()->selector();
} else {
info->operation_name = kUnrecognizedOperation;
}
info->operation_id = operation_id_;
if (check_response_info_.is_api_key_valid) {
info->api_key = api_key_;
}
info->producer_project_id = service_context()->project_id();
info->referer = http_referer_;
info->request_start_time = start_time_;
}
void RequestContext::FillLocation(service_control::ReportRequestInfo *info) {
if (service_context()->gce_metadata()->has_valid_data() &&
!service_context()->gce_metadata()->zone().empty()) {
info->location = service_context()->gce_metadata()->zone();
} else {
info->location = kDefaultLocation;
}
}
void RequestContext::FillComputePlatform(
service_control::ReportRequestInfo *info) {
compute_platform::ComputePlatform cp;
GceMetadata *metadata = service_context()->gce_metadata();
if (metadata == nullptr || !metadata->has_valid_data()) {
cp = compute_platform::UNKNOWN;
} else {
if (!metadata->gae_server_software().empty()) {
cp = compute_platform::GAE_FLEX;
} else if (!metadata->kube_env().empty()) {
cp = compute_platform::GKE;
} else {
cp = compute_platform::GCE;
}
}
info->compute_platform = cp;
}
void RequestContext::FillLogMessage(service_control::ReportRequestInfo *info) {
if (method()) {
info->api_method = method()->selector();
info->api_name = method()->api_name();
info->api_version = method()->api_version();
info->log_message = std::string(kMessage) + method()->selector();
} else {
std::string http_verb = info->method;
if (http_verb.empty()) {
http_verb = kUnknownHttpVerb;
}
info->log_message = std::string(kIgnoredMessage) + http_verb + " " +
request_->GetUnparsedRequestPath();
}
}
void RequestContext::FillCheckRequestInfo(
service_control::CheckRequestInfo *info) {
FillOperationInfo(info);
info->client_ip = request_->GetClientIP();
info->allow_unregistered_calls = method()->allow_unregistered_calls();
}
void RequestContext::FillReportRequestInfo(
Response *response, service_control::ReportRequestInfo *info) {
FillOperationInfo(info);
FillLocation(info);
FillComputePlatform(info);
info->url = request_->GetUnparsedRequestPath();
info->method = request_->GetRequestHTTPMethod();
info->protocol = request_->GetRequestProtocol();
info->check_response_info = check_response_info_;
info->auth_issuer = auth_issuer_;
info->auth_audience = auth_audience_;
if (!info->is_final_report) {
info->request_bytes = request_->GetGrpcRequestBytes();
info->response_bytes = request_->GetGrpcResponseBytes();
} else {
info->request_size = response->GetRequestSize();
info->response_size = response->GetResponseSize();
info->request_bytes = info->request_size;
info->response_bytes = info->response_size;
info->streaming_request_message_counts =
request_->GetGrpcRequestMessageCounts();
info->streaming_response_message_counts =
request_->GetGrpcResponseMessageCounts();
info->streaming_durations =
std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::system_clock::now() - start_time_)
.count();
info->status = response->GetResponseStatus();
info->response_code = info->status.HttpCode();
// Must be after response_code and method are assigned.
FillLogMessage(info);
response->GetLatencyInfo(&info->latency);
}
}
void RequestContext::StartBackendSpanAndSetTraceContext() {
backend_span_.reset(CreateSpan(cloud_trace_.get(), "Backend"));
// Set trace context header to backend. The span id in the header will
// be the backend span's id.
std::ostringstream trace_context_stream;
trace_context_stream << cloud_trace()->trace()->trace_id() << "/"
<< backend_span_->trace_span()->span_id() << ";"
<< cloud_trace()->options();
Status status = request()->AddHeaderToBackend(kCloudTraceContextHeader,
trace_context_stream.str());
if (!status.ok()) {
service_context()->env()->LogError(
"Failed to set trace context header to backend.");
}
}
} // namespace context
} // namespace api_manager
} // namespace google
<commit_msg>Do not report latency for streaming requests. (#20)<commit_after>// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
//
#include "contrib/endpoints/src/api_manager/context/request_context.h"
#include <uuid/uuid.h>
#include <sstream>
using ::google::api_manager::utils::Status;
namespace google {
namespace api_manager {
namespace context {
namespace {
// Cloud Trace Context Header
const char kCloudTraceContextHeader[] = "X-Cloud-Trace-Context";
// Log message prefix for a success method.
const char kMessage[] = "Method: ";
// Log message prefix for an ignored method.
const char kIgnoredMessage[] =
"Endpoints management skipped for an unrecognized HTTP call: ";
// Unknown HTTP verb.
const char kUnknownHttpVerb[] = "<Unknown HTTP Verb>";
// Service control does not currently support logging with an empty
// operation name so we use this value until fix is available.
const char kUnrecognizedOperation[] = "<Unknown Operation Name>";
// Maximum 36 byte string for UUID
const int kMaxUUIDBufSize = 40;
// Default api key names
const char kDefaultApiKeyQueryName1[] = "key";
const char kDefaultApiKeyQueryName2[] = "api_key";
const char kDefaultApiKeyHeaderName[] = "x-api-key";
// Default location
const char kDefaultLocation[] = "us-central1";
// Genereates a UUID string
std::string GenerateUUID() {
char uuid_buf[kMaxUUIDBufSize];
uuid_t uuid;
uuid_generate(uuid);
uuid_unparse(uuid, uuid_buf);
return uuid_buf;
}
} // namespace
using context::ServiceContext;
RequestContext::RequestContext(std::shared_ptr<ServiceContext> service_context,
std::unique_ptr<Request> request)
: service_context_(service_context),
request_(std::move(request)),
is_first_report_(true) {
start_time_ = std::chrono::system_clock::now();
last_report_time_ = std::chrono::steady_clock::now();
operation_id_ = GenerateUUID();
const std::string &method = request_->GetRequestHTTPMethod();
const std::string &path = request_->GetRequestPath();
std::string query_params = request_->GetQueryParameters();
// In addition to matching the method, service_context_->GetMethodCallInfo()
// will extract the variable bindings from the url. We need variable bindings
// only when we need to do transcoding. If this turns out to be a performance
// problem for non-transcoded calls, we have a couple of options:
// 1) Do not extract variable bindings here, and do the method matching again
// with extracting variable bindings when transcoding is needed.
// 2) Store all the pieces needed for extracting variable bindings (such as
// http template variables, url path parts) in MethodCallInfo and extract
// variables lazily when needed.
method_call_ =
service_context_->GetMethodCallInfo(method, path, query_params);
if (method_call_.method_info) {
ExtractApiKey();
}
request_->FindHeader("referer", &http_referer_);
// Enable trace if tracing is not force disabled and the triggering header is
// set.
if (service_context_->cloud_trace_aggregator()) {
std::string trace_context_header;
request_->FindHeader(kCloudTraceContextHeader, &trace_context_header);
std::string method_name = kUnrecognizedOperation;
if (method_call_.method_info) {
method_name = method_call_.method_info->selector();
}
// qualify with the service name
method_name = service_context_->service_name() + "/" + method_name;
cloud_trace_.reset(cloud_trace::CreateCloudTrace(
trace_context_header, method_name,
&service_context_->cloud_trace_aggregator()->sampler()));
}
}
void RequestContext::ExtractApiKey() {
bool api_key_defined = false;
auto url_queries = method()->api_key_url_query_parameters();
if (url_queries) {
api_key_defined = true;
for (const auto &url_query : *url_queries) {
if (request_->FindQuery(url_query, &api_key_)) {
return;
}
}
}
auto headers = method()->api_key_http_headers();
if (headers) {
api_key_defined = true;
for (const auto &header : *headers) {
if (request_->FindHeader(header, &api_key_)) {
return;
}
}
}
if (!api_key_defined) {
// If api_key is not specified for a method,
// check "key" first, if not, check "api_key" in query parameter.
if (!request_->FindQuery(kDefaultApiKeyQueryName1, &api_key_)) {
if (!request_->FindQuery(kDefaultApiKeyQueryName2, &api_key_)) {
request_->FindHeader(kDefaultApiKeyHeaderName, &api_key_);
}
}
}
}
void RequestContext::CompleteCheck(Status status) {
// Makes sure set_check_continuation() is called.
// Only making sure CompleteCheck() is NOT called twice.
GOOGLE_CHECK(check_continuation_);
auto temp_continuation = check_continuation_;
check_continuation_ = nullptr;
temp_continuation(status);
}
void RequestContext::FillOperationInfo(service_control::OperationInfo *info) {
if (method()) {
info->operation_name = method()->selector();
} else {
info->operation_name = kUnrecognizedOperation;
}
info->operation_id = operation_id_;
if (check_response_info_.is_api_key_valid) {
info->api_key = api_key_;
}
info->producer_project_id = service_context()->project_id();
info->referer = http_referer_;
info->request_start_time = start_time_;
}
void RequestContext::FillLocation(service_control::ReportRequestInfo *info) {
if (service_context()->gce_metadata()->has_valid_data() &&
!service_context()->gce_metadata()->zone().empty()) {
info->location = service_context()->gce_metadata()->zone();
} else {
info->location = kDefaultLocation;
}
}
void RequestContext::FillComputePlatform(
service_control::ReportRequestInfo *info) {
compute_platform::ComputePlatform cp;
GceMetadata *metadata = service_context()->gce_metadata();
if (metadata == nullptr || !metadata->has_valid_data()) {
cp = compute_platform::UNKNOWN;
} else {
if (!metadata->gae_server_software().empty()) {
cp = compute_platform::GAE_FLEX;
} else if (!metadata->kube_env().empty()) {
cp = compute_platform::GKE;
} else {
cp = compute_platform::GCE;
}
}
info->compute_platform = cp;
}
void RequestContext::FillLogMessage(service_control::ReportRequestInfo *info) {
if (method()) {
info->api_method = method()->selector();
info->api_name = method()->api_name();
info->api_version = method()->api_version();
info->log_message = std::string(kMessage) + method()->selector();
} else {
std::string http_verb = info->method;
if (http_verb.empty()) {
http_verb = kUnknownHttpVerb;
}
info->log_message = std::string(kIgnoredMessage) + http_verb + " " +
request_->GetUnparsedRequestPath();
}
}
void RequestContext::FillCheckRequestInfo(
service_control::CheckRequestInfo *info) {
FillOperationInfo(info);
info->client_ip = request_->GetClientIP();
info->allow_unregistered_calls = method()->allow_unregistered_calls();
}
void RequestContext::FillReportRequestInfo(
Response *response, service_control::ReportRequestInfo *info) {
FillOperationInfo(info);
FillLocation(info);
FillComputePlatform(info);
info->url = request_->GetUnparsedRequestPath();
info->method = request_->GetRequestHTTPMethod();
info->protocol = request_->GetRequestProtocol();
info->check_response_info = check_response_info_;
info->auth_issuer = auth_issuer_;
info->auth_audience = auth_audience_;
if (!info->is_final_report) {
info->request_bytes = request_->GetGrpcRequestBytes();
info->response_bytes = request_->GetGrpcResponseBytes();
} else {
info->request_size = response->GetRequestSize();
info->response_size = response->GetResponseSize();
info->request_bytes = info->request_size;
info->response_bytes = info->response_size;
info->streaming_request_message_counts =
request_->GetGrpcRequestMessageCounts();
info->streaming_response_message_counts =
request_->GetGrpcResponseMessageCounts();
info->streaming_durations =
std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::system_clock::now() - start_time_)
.count();
info->status = response->GetResponseStatus();
info->response_code = info->status.HttpCode();
// Must be after response_code and method are assigned.
FillLogMessage(info);
if(!method()->request_streaming() && !method()->response_streaming()) {
response->GetLatencyInfo(&info->latency);
}
}
}
void RequestContext::StartBackendSpanAndSetTraceContext() {
backend_span_.reset(CreateSpan(cloud_trace_.get(), "Backend"));
// Set trace context header to backend. The span id in the header will
// be the backend span's id.
std::ostringstream trace_context_stream;
trace_context_stream << cloud_trace()->trace()->trace_id() << "/"
<< backend_span_->trace_span()->span_id() << ";"
<< cloud_trace()->options();
Status status = request()->AddHeaderToBackend(kCloudTraceContextHeader,
trace_context_stream.str());
if (!status.ok()) {
service_context()->env()->LogError(
"Failed to set trace context header to backend.");
}
}
} // namespace context
} // namespace api_manager
} // namespace google
<|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 "build/build_config.h"
#include "chrome/browser/browser_list.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/result_codes.h"
#if defined(OS_WIN)
// TODO(port): these can probably all go away, even on win
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#endif
BrowserList::list_type BrowserList::browsers_;
std::vector<BrowserList::Observer*> BrowserList::observers_;
// static
void BrowserList::AddBrowser(Browser* browser) {
DCHECK(browser);
browsers_.push_back(browser);
g_browser_process->AddRefModule();
NotificationService::current()->Notify(
NotificationType::BROWSER_OPENED,
Source<Browser>(browser),
NotificationService::NoDetails());
// Send out notifications after add has occurred. Do some basic checking to
// try to catch evil observers that change the list from under us.
std::vector<Observer*>::size_type original_count = observers_.size();
for (int i = 0; i < static_cast<int>(observers_.size()); i++)
observers_[i]->OnBrowserAdded(browser);
DCHECK_EQ(original_count, observers_.size())
<< "observer list modified during notification";
}
// static
void BrowserList::RemoveBrowser(Browser* browser) {
RemoveBrowserFrom(browser, &last_active_browsers_);
bool close_app = (browsers_.size() == 1);
NotificationService::current()->Notify(
NotificationType::BROWSER_CLOSED,
Source<Browser>(browser), Details<bool>(&close_app));
// Send out notifications before anything changes. Do some basic checking to
// try to catch evil observers that change the list from under us.
std::vector<Observer*>::size_type original_count = observers_.size();
for (int i = 0; i < static_cast<int>(observers_.size()); i++)
observers_[i]->OnBrowserRemoving(browser);
DCHECK_EQ(original_count, observers_.size())
<< "observer list modified during notification";
RemoveBrowserFrom(browser, &browsers_);
// If the last Browser object was destroyed, make sure we try to close any
// remaining dependent windows too.
if (browsers_.empty())
AllBrowsersClosed();
g_browser_process->ReleaseModule();
}
// static
void BrowserList::AddObserver(BrowserList::Observer* observer) {
DCHECK(std::find(observers_.begin(), observers_.end(), observer)
== observers_.end()) << "Adding an observer twice";
observers_.push_back(observer);
}
// static
void BrowserList::RemoveObserver(BrowserList::Observer* observer) {
std::vector<Observer*>::iterator place =
std::find(observers_.begin(), observers_.end(), observer);
if (place == observers_.end()) {
NOTREACHED() << "Removing an observer that isn't registered.";
return;
}
observers_.erase(place);
}
// static
void BrowserList::CloseAllBrowsers(bool use_post) {
// Before we close the browsers shutdown all session services. That way an
// exit can restore all browsers open before exiting.
ProfileManager::ShutdownSessionServices();
BrowserList::const_iterator iter;
for (iter = BrowserList::begin(); iter != BrowserList::end();) {
if (use_post) {
(*iter)->window()->Close();
++iter;
} else {
// This path is hit during logoff/power-down. In this case we won't get
// a final message and so we force the browser to be deleted.
Browser* browser = *iter;
browser->window()->Close();
// Close doesn't immediately destroy the browser
// (Browser::TabStripEmpty() uses invoke later) but when we're ending the
// session we need to make sure the browser is destroyed now. So, invoke
// DestroyBrowser to make sure the browser is deleted and cleanup can
// happen.
browser->window()->DestroyBrowser();
iter = BrowserList::begin();
if (iter != BrowserList::end() && browser == *iter) {
// Destroying the browser should have removed it from the browser list.
// We should never get here.
NOTREACHED();
return;
}
}
}
}
// static
void BrowserList::WindowsSessionEnding() {
// EndSession is invoked once per frame. Only do something the first time.
static bool already_ended = false;
if (already_ended)
return;
already_ended = true;
browser_shutdown::OnShutdownStarting(browser_shutdown::END_SESSION);
// Write important data first.
g_browser_process->EndSession();
// Close all the browsers.
BrowserList::CloseAllBrowsers(false);
// Send out notification. This is used during testing so that the test harness
// can properly shutdown before we exit.
NotificationService::current()->Notify(
NotificationType::SESSION_END,
NotificationService::AllSources(),
NotificationService::NoDetails());
// And shutdown.
browser_shutdown::Shutdown();
#if defined(OS_WIN)
// At this point the message loop is still running yet we've shut everything
// down. If any messages are processed we'll likely crash. Exit now.
ExitProcess(ResultCodes::NORMAL_EXIT);
#else
NOTIMPLEMENTED();
#endif
}
// static
bool BrowserList::HasBrowserWithProfile(Profile* profile) {
BrowserList::const_iterator iter;
for (size_t i = 0; i < browsers_.size(); ++i) {
if (browsers_[i]->profile() == profile)
return true;
}
return false;
}
// static
BrowserList::list_type BrowserList::last_active_browsers_;
// static
void BrowserList::SetLastActive(Browser* browser) {
RemoveBrowserFrom(browser, &last_active_browsers_);
last_active_browsers_.push_back(browser);
for (int i = 0; i < static_cast<int>(observers_.size()); i++)
observers_[i]->OnBrowserSetLastActive(browser);
}
// static
Browser* BrowserList::GetLastActive() {
if (!last_active_browsers_.empty())
return *(last_active_browsers_.rbegin());
return NULL;
}
// static
Browser* BrowserList::GetLastActiveWithProfile(Profile* p) {
list_type::reverse_iterator browser = last_active_browsers_.rbegin();
for (; browser != last_active_browsers_.rend(); ++browser) {
if ((*browser)->profile() == p) {
return *browser;
}
}
return NULL;
}
// static
Browser* BrowserList::FindBrowserWithType(Profile* p, Browser::Type t) {
Browser* last_active = GetLastActive();
if (last_active && last_active->profile() == p && last_active->type() == t)
return last_active;
BrowserList::const_iterator i;
for (i = BrowserList::begin(); i != BrowserList::end(); ++i) {
if (*i == last_active)
continue;
if ((*i)->profile() == p && (*i)->type() == t)
return *i;
}
return NULL;
}
// static
Browser* BrowserList::FindBrowserWithProfile(Profile* p) {
Browser* last_active = GetLastActive();
if (last_active && last_active->profile() == p)
return last_active;
BrowserList::const_iterator i;
for (i = BrowserList::begin(); i != BrowserList::end(); ++i) {
if (*i == last_active)
continue;
if ((*i)->profile() == p)
return *i;
}
return NULL;
}
// static
Browser* BrowserList::FindBrowserWithID(SessionID::id_type desired_id) {
BrowserList::const_iterator i;
for (i = BrowserList::begin(); i != BrowserList::end(); ++i) {
if ((*i)->session_id().id() == desired_id)
return *i;
}
return NULL;
}
// static
size_t BrowserList::GetBrowserCountForType(Profile* p, Browser::Type type) {
BrowserList::const_iterator i;
size_t result = 0;
for (i = BrowserList::begin(); i != BrowserList::end(); ++i) {
if ((*i)->profile() == p && (*i)->type() == type)
result++;
}
return result;
}
// static
size_t BrowserList::GetBrowserCount(Profile* p) {
BrowserList::const_iterator i;
size_t result = 0;
for (i = BrowserList::begin(); i != BrowserList::end(); ++i) {
if ((*i)->profile() == p)
result++;
}
return result;
}
// static
bool BrowserList::IsOffTheRecordSessionActive() {
BrowserList::const_iterator i;
for (i = BrowserList::begin(); i != BrowserList::end(); ++i) {
if ((*i)->profile()->IsOffTheRecord())
return true;
}
return false;
}
// static
void BrowserList::RemoveBrowserFrom(Browser* browser, list_type* browser_list) {
const iterator remove_browser =
find(browser_list->begin(), browser_list->end(), browser);
if (remove_browser != browser_list->end())
browser_list->erase(remove_browser);
}
TabContentsIterator::TabContentsIterator()
: browser_iterator_(BrowserList::begin()),
web_view_index_(-1),
cur_(NULL) {
Advance();
}
void TabContentsIterator::Advance() {
// Unless we're at the beginning (index = -1) or end (iterator = end()),
// then the current TabContents should be valid.
DCHECK(web_view_index_ || browser_iterator_ == BrowserList::end() ||
cur_) << "Trying to advance past the end";
// Update cur_ to the next TabContents in the list.
for (;;) {
web_view_index_++;
while (web_view_index_ >= (*browser_iterator_)->tab_count()) {
// advance browsers
++browser_iterator_;
web_view_index_ = 0;
if (browser_iterator_ == BrowserList::end()) {
cur_ = NULL;
return;
}
}
TabContents* next_tab =
(*browser_iterator_)->GetTabContentsAt(web_view_index_);
if (next_tab) {
cur_ = next_tab;
return;
}
}
}
<commit_msg>Handling a case where the browser_iterator_ would be NULL. The DCHECK was fine but the code itself was missing the check.<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 "build/build_config.h"
#include "chrome/browser/browser_list.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/result_codes.h"
#if defined(OS_WIN)
// TODO(port): these can probably all go away, even on win
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#endif
BrowserList::list_type BrowserList::browsers_;
std::vector<BrowserList::Observer*> BrowserList::observers_;
// static
void BrowserList::AddBrowser(Browser* browser) {
DCHECK(browser);
browsers_.push_back(browser);
g_browser_process->AddRefModule();
NotificationService::current()->Notify(
NotificationType::BROWSER_OPENED,
Source<Browser>(browser),
NotificationService::NoDetails());
// Send out notifications after add has occurred. Do some basic checking to
// try to catch evil observers that change the list from under us.
std::vector<Observer*>::size_type original_count = observers_.size();
for (int i = 0; i < static_cast<int>(observers_.size()); i++)
observers_[i]->OnBrowserAdded(browser);
DCHECK_EQ(original_count, observers_.size())
<< "observer list modified during notification";
}
// static
void BrowserList::RemoveBrowser(Browser* browser) {
RemoveBrowserFrom(browser, &last_active_browsers_);
bool close_app = (browsers_.size() == 1);
NotificationService::current()->Notify(
NotificationType::BROWSER_CLOSED,
Source<Browser>(browser), Details<bool>(&close_app));
// Send out notifications before anything changes. Do some basic checking to
// try to catch evil observers that change the list from under us.
std::vector<Observer*>::size_type original_count = observers_.size();
for (int i = 0; i < static_cast<int>(observers_.size()); i++)
observers_[i]->OnBrowserRemoving(browser);
DCHECK_EQ(original_count, observers_.size())
<< "observer list modified during notification";
RemoveBrowserFrom(browser, &browsers_);
// If the last Browser object was destroyed, make sure we try to close any
// remaining dependent windows too.
if (browsers_.empty())
AllBrowsersClosed();
g_browser_process->ReleaseModule();
}
// static
void BrowserList::AddObserver(BrowserList::Observer* observer) {
DCHECK(std::find(observers_.begin(), observers_.end(), observer)
== observers_.end()) << "Adding an observer twice";
observers_.push_back(observer);
}
// static
void BrowserList::RemoveObserver(BrowserList::Observer* observer) {
std::vector<Observer*>::iterator place =
std::find(observers_.begin(), observers_.end(), observer);
if (place == observers_.end()) {
NOTREACHED() << "Removing an observer that isn't registered.";
return;
}
observers_.erase(place);
}
// static
void BrowserList::CloseAllBrowsers(bool use_post) {
// Before we close the browsers shutdown all session services. That way an
// exit can restore all browsers open before exiting.
ProfileManager::ShutdownSessionServices();
BrowserList::const_iterator iter;
for (iter = BrowserList::begin(); iter != BrowserList::end();) {
if (use_post) {
(*iter)->window()->Close();
++iter;
} else {
// This path is hit during logoff/power-down. In this case we won't get
// a final message and so we force the browser to be deleted.
Browser* browser = *iter;
browser->window()->Close();
// Close doesn't immediately destroy the browser
// (Browser::TabStripEmpty() uses invoke later) but when we're ending the
// session we need to make sure the browser is destroyed now. So, invoke
// DestroyBrowser to make sure the browser is deleted and cleanup can
// happen.
browser->window()->DestroyBrowser();
iter = BrowserList::begin();
if (iter != BrowserList::end() && browser == *iter) {
// Destroying the browser should have removed it from the browser list.
// We should never get here.
NOTREACHED();
return;
}
}
}
}
// static
void BrowserList::WindowsSessionEnding() {
// EndSession is invoked once per frame. Only do something the first time.
static bool already_ended = false;
if (already_ended)
return;
already_ended = true;
browser_shutdown::OnShutdownStarting(browser_shutdown::END_SESSION);
// Write important data first.
g_browser_process->EndSession();
// Close all the browsers.
BrowserList::CloseAllBrowsers(false);
// Send out notification. This is used during testing so that the test harness
// can properly shutdown before we exit.
NotificationService::current()->Notify(
NotificationType::SESSION_END,
NotificationService::AllSources(),
NotificationService::NoDetails());
// And shutdown.
browser_shutdown::Shutdown();
#if defined(OS_WIN)
// At this point the message loop is still running yet we've shut everything
// down. If any messages are processed we'll likely crash. Exit now.
ExitProcess(ResultCodes::NORMAL_EXIT);
#else
NOTIMPLEMENTED();
#endif
}
// static
bool BrowserList::HasBrowserWithProfile(Profile* profile) {
BrowserList::const_iterator iter;
for (size_t i = 0; i < browsers_.size(); ++i) {
if (browsers_[i]->profile() == profile)
return true;
}
return false;
}
// static
BrowserList::list_type BrowserList::last_active_browsers_;
// static
void BrowserList::SetLastActive(Browser* browser) {
RemoveBrowserFrom(browser, &last_active_browsers_);
last_active_browsers_.push_back(browser);
for (int i = 0; i < static_cast<int>(observers_.size()); i++)
observers_[i]->OnBrowserSetLastActive(browser);
}
// static
Browser* BrowserList::GetLastActive() {
if (!last_active_browsers_.empty())
return *(last_active_browsers_.rbegin());
return NULL;
}
// static
Browser* BrowserList::GetLastActiveWithProfile(Profile* p) {
list_type::reverse_iterator browser = last_active_browsers_.rbegin();
for (; browser != last_active_browsers_.rend(); ++browser) {
if ((*browser)->profile() == p) {
return *browser;
}
}
return NULL;
}
// static
Browser* BrowserList::FindBrowserWithType(Profile* p, Browser::Type t) {
Browser* last_active = GetLastActive();
if (last_active && last_active->profile() == p && last_active->type() == t)
return last_active;
BrowserList::const_iterator i;
for (i = BrowserList::begin(); i != BrowserList::end(); ++i) {
if (*i == last_active)
continue;
if ((*i)->profile() == p && (*i)->type() == t)
return *i;
}
return NULL;
}
// static
Browser* BrowserList::FindBrowserWithProfile(Profile* p) {
Browser* last_active = GetLastActive();
if (last_active && last_active->profile() == p)
return last_active;
BrowserList::const_iterator i;
for (i = BrowserList::begin(); i != BrowserList::end(); ++i) {
if (*i == last_active)
continue;
if ((*i)->profile() == p)
return *i;
}
return NULL;
}
// static
Browser* BrowserList::FindBrowserWithID(SessionID::id_type desired_id) {
BrowserList::const_iterator i;
for (i = BrowserList::begin(); i != BrowserList::end(); ++i) {
if ((*i)->session_id().id() == desired_id)
return *i;
}
return NULL;
}
// static
size_t BrowserList::GetBrowserCountForType(Profile* p, Browser::Type type) {
BrowserList::const_iterator i;
size_t result = 0;
for (i = BrowserList::begin(); i != BrowserList::end(); ++i) {
if ((*i)->profile() == p && (*i)->type() == type)
result++;
}
return result;
}
// static
size_t BrowserList::GetBrowserCount(Profile* p) {
BrowserList::const_iterator i;
size_t result = 0;
for (i = BrowserList::begin(); i != BrowserList::end(); ++i) {
if ((*i)->profile() == p)
result++;
}
return result;
}
// static
bool BrowserList::IsOffTheRecordSessionActive() {
BrowserList::const_iterator i;
for (i = BrowserList::begin(); i != BrowserList::end(); ++i) {
if ((*i)->profile()->IsOffTheRecord())
return true;
}
return false;
}
// static
void BrowserList::RemoveBrowserFrom(Browser* browser, list_type* browser_list) {
const iterator remove_browser =
find(browser_list->begin(), browser_list->end(), browser);
if (remove_browser != browser_list->end())
browser_list->erase(remove_browser);
}
TabContentsIterator::TabContentsIterator()
: browser_iterator_(BrowserList::begin()),
web_view_index_(-1),
cur_(NULL) {
Advance();
}
void TabContentsIterator::Advance() {
// Unless we're at the beginning (index = -1) or end (iterator = end()),
// then the current TabContents should be valid.
DCHECK(web_view_index_ || browser_iterator_ == BrowserList::end() || cur_)
<< "Trying to advance past the end";
// Update cur_ to the next TabContents in the list.
while (browser_iterator_ != BrowserList::end()) {
web_view_index_++;
while (web_view_index_ >= (*browser_iterator_)->tab_count()) {
// advance browsers
++browser_iterator_;
web_view_index_ = 0;
if (browser_iterator_ == BrowserList::end()) {
cur_ = NULL;
return;
}
}
TabContents* next_tab =
(*browser_iterator_)->GetTabContentsAt(web_view_index_);
if (next_tab) {
cur_ = next_tab;
return;
}
}
}
<|endoftext|>
|
<commit_before>/* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/mlir/quantization/tensorflow/utils/quant_spec.h"
#include <memory>
#include "tensorflow/compiler/mlir/lite/quantization/quantization_utils.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
namespace mlir {
namespace quant {
std::unique_ptr<OpQuantScaleSpec> GetTfQuantScaleSpec(Operation* op) {
auto scale_spec = std::make_unique<OpQuantScaleSpec>();
if (llvm::isa<
// clang-format off
// go/keep-sorted start
TF::ConcatV2Op,
TF::IdentityOp,
TF::MaxPoolOp,
TF::ReshapeOp
// go/keep-sorted end
// clang-format on
>(op)) {
scale_spec->has_same_scale_requirement = true;
}
return scale_spec;
}
} // namespace quant
} // namespace mlir
<commit_msg>Add more same scale ops<commit_after>/* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/mlir/quantization/tensorflow/utils/quant_spec.h"
#include <memory>
#include "tensorflow/compiler/mlir/lite/quantization/quantization_utils.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
namespace mlir {
namespace quant {
std::unique_ptr<OpQuantScaleSpec> GetTfQuantScaleSpec(Operation* op) {
auto scale_spec = std::make_unique<OpQuantScaleSpec>();
if (llvm::isa<
// clang-format off
// go/keep-sorted start
TF::ConcatV2Op,
TF::IdentityOp,
TF::MaxPoolOp,
TF::PadV2Op,
TF::ReshapeOp,
TF::SqueezeOp
// go/keep-sorted end
// clang-format on
>(op)) {
scale_spec->has_same_scale_requirement = true;
}
return scale_spec;
}
} // namespace quant
} // namespace mlir
<|endoftext|>
|
<commit_before>#include "pattern.h"
#include "visitor.h"
#include "choice.h"
#include "seq.h"
#include "repeat.h"
#include "character_set.h"
#include <set>
namespace tree_sitter {
namespace rules {
using std::string;
using std::hash;
using std::make_shared;
using std::set;
class PatternParser {
public:
PatternParser(const string &input) :
input(input),
length(input.length()),
position(0) {}
rule_ptr rule() {
auto result = term();
while (has_more_input() && peek() == '|') {
next();
result = make_shared<Choice>(result, term());
}
return result;
}
private:
rule_ptr term() {
rule_ptr result = factor();
while (has_more_input() && (peek() != '|') && (peek() != ')'))
result = Seq::Build({ result, factor() });
return result;
}
rule_ptr factor() {
rule_ptr result = atom();
if (has_more_input() && (peek() == '+')) {
next();
result = make_shared<Repeat>(result);
}
return result;
}
rule_ptr atom() {
rule_ptr result;
switch (peek()) {
case '(':
next();
result = rule();
if (peek() != ')')
error("mismatched parens");
else
next();
break;
case '[':
next();
result = char_set().copy();
if (peek() != ']')
error("mismatched square brackets");
else
next();
break;
case ')':
error("mismatched parens");
break;
default:
result = single_char().copy();
}
return result;
}
CharacterSet char_set() {
bool is_affirmative = true;
if (peek() == '^') {
next();
is_affirmative = false;
}
CharacterSet result;
while (has_more_input() && (peek() != ']'))
result.add_set(single_char());
return is_affirmative ? result : result.complement();
}
CharacterSet single_char() {
CharacterSet value({ '\0' });
switch (peek()) {
case '\\':
next();
value = escaped_char(peek());
next();
break;
default:
char first_char = peek();
next();
if (peek() == '-') {
next();
value = CharacterSet({ CharacterRange(first_char, peek()) });
next();
} else {
value = CharacterSet({ first_char });
}
}
return value;
}
CharacterSet escaped_char(char value) {
switch (value) {
case '\\':
case '(':
case ')':
return CharacterSet({ value });
case 'w':
return CharacterSet({{'a', 'z'}, {'A', 'Z'}});
case 'd':
return CharacterSet({CharacterRange('0', '9')});
default:
error("unrecognized escape sequence");
return CharacterSet();
}
}
void next() {
position++;
}
char peek() {
return input[position];
}
bool has_more_input() {
return position < length;
}
void error(const char *message) {
throw string("Invalid regex pattern '") + input + "': " + message;
}
const string input;
const size_t length;
int position;
};
Pattern::Pattern(const string &string) : value(string) {};
bool Pattern::operator==(tree_sitter::rules::Rule const &other) const {
auto pattern = dynamic_cast<const Pattern *>(&other);
return pattern && (pattern->value == value);
}
size_t Pattern::hash_code() const {
return hash<string>()(value);
}
rule_ptr Pattern::copy() const {
return std::make_shared<Pattern>(*this);
}
string Pattern::to_string() const {
return string("#<pattern '") + value + "'>";
}
void Pattern::accept(Visitor &visitor) const {
visitor.visit(this);
}
rule_ptr Pattern::to_rule_tree() const {
return PatternParser(value).rule();
}
}
}
<commit_msg>Don't use exceptions in pattern parser<commit_after>#include "pattern.h"
#include "visitor.h"
#include "choice.h"
#include "seq.h"
#include "repeat.h"
#include "character_set.h"
#include <set>
namespace tree_sitter {
namespace rules {
using std::string;
using std::hash;
using std::make_shared;
using std::set;
class PatternParser {
public:
PatternParser(const string &input) :
input(input),
length(input.length()),
position(0) {}
rule_ptr rule() {
auto result = term();
while (has_more_input() && peek() == '|') {
next();
result = make_shared<Choice>(result, term());
}
return result;
}
private:
rule_ptr term() {
rule_ptr result = factor();
while (has_more_input() && (peek() != '|') && (peek() != ')'))
result = Seq::Build({ result, factor() });
return result;
}
rule_ptr factor() {
rule_ptr result = atom();
if (has_more_input() && (peek() == '+')) {
next();
result = make_shared<Repeat>(result);
}
return result;
}
rule_ptr atom() {
rule_ptr result;
switch (peek()) {
case '(':
next();
result = rule();
if (has_error()) return result;
if (peek() != ')') {
error = "mismatched parens";
return result;
}
next();
break;
case '[':
next();
result = char_set().copy();
if (has_error()) return result;
if (peek() != ']') {
error = "mismatched square brackets";
return result;
}
next();
break;
case ')':
error = "mismatched parens";
break;
default:
result = single_char().copy();
}
return result;
}
CharacterSet char_set() {
bool is_affirmative = true;
if (peek() == '^') {
next();
is_affirmative = false;
}
CharacterSet result;
while (has_more_input() && (peek() != ']'))
result.add_set(single_char());
return is_affirmative ? result : result.complement();
}
CharacterSet single_char() {
CharacterSet value;
switch (peek()) {
case '\\':
next();
value = escaped_char(peek());
if (has_error()) return value;
next();
break;
default:
char first_char = peek();
next();
if (peek() == '-') {
next();
value = CharacterSet({ CharacterRange(first_char, peek()) });
next();
} else {
value = CharacterSet({ first_char });
}
}
return value;
}
CharacterSet escaped_char(char value) {
switch (value) {
case '\\':
case '(':
case ')':
return CharacterSet({ value });
case 'w':
return CharacterSet({{'a', 'z'}, {'A', 'Z'}});
case 'd':
return CharacterSet({CharacterRange('0', '9')});
default:
error = "unrecognized escape sequence";
return CharacterSet();
}
}
void next() {
position++;
}
char peek() {
return input[position];
}
bool has_more_input() {
return position < length;
}
bool has_error() {
return error != "";
}
string error;
const string input;
const size_t length;
int position;
};
Pattern::Pattern(const string &string) : value(string) {};
bool Pattern::operator==(tree_sitter::rules::Rule const &other) const {
auto pattern = dynamic_cast<const Pattern *>(&other);
return pattern && (pattern->value == value);
}
size_t Pattern::hash_code() const {
return hash<string>()(value);
}
rule_ptr Pattern::copy() const {
return std::make_shared<Pattern>(*this);
}
string Pattern::to_string() const {
return string("#<pattern '") + value + "'>";
}
void Pattern::accept(Visitor &visitor) const {
visitor.visit(this);
}
rule_ptr Pattern::to_rule_tree() const {
return PatternParser(value).rule();
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: bootstrap.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: kz $ $Date: 2006-01-03 12:42:13 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "osl/diagnose.h"
#include "rtl/alloc.h"
#include "rtl/bootstrap.hxx"
#include "rtl/string.hxx"
#include "uno/mapping.hxx"
#include "uno/environment.hxx"
#include "cppuhelper/bootstrap.hxx"
#include "com/sun/star/lang/XComponent.hpp"
#include "com/sun/star/lang/XSingleComponentFactory.hpp"
#include "jni.h"
#include "jvmaccess/virtualmachine.hxx"
#include "jvmaccess/unovirtualmachine.hxx"
#include "vm.hxx"
#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using ::rtl::OString;
using ::rtl::OUString;
namespace javaunohelper
{
inline ::rtl::OUString jstring_to_oustring( jstring jstr, JNIEnv * jni_env )
{
OSL_ASSERT( sizeof (sal_Unicode) == sizeof (jchar) );
jsize len = jni_env->GetStringLength( jstr );
rtl_uString * ustr =
(rtl_uString *)rtl_allocateMemory( sizeof (rtl_uString) + (len * sizeof (sal_Unicode)) );
jni_env->GetStringRegion( jstr, 0, len, ustr->buffer );
OSL_ASSERT( JNI_FALSE == jni_env->ExceptionCheck() );
ustr->refCount = 1;
ustr->length = len;
ustr->buffer[ len ] = '\0';
return ::rtl::OUString( ustr, SAL_NO_ACQUIRE );
}
}
//==================================================================================================
extern "C" JNIEXPORT jobject JNICALL Java_com_sun_star_comp_helper_Bootstrap_cppuhelper_1bootstrap(
JNIEnv * jni_env, jclass jClass, jstring juno_rc, jobjectArray jpairs,
jobject loader )
{
try
{
if (0 != jpairs)
{
jsize nPos = 0, len = jni_env->GetArrayLength( jpairs );
while (nPos < len)
{
// name
jstring jstr = (jstring)jni_env->GetObjectArrayElement( jpairs, nPos );
if (JNI_FALSE != jni_env->ExceptionCheck())
{
jni_env->ExceptionClear();
throw RuntimeException(
OUSTR("index out of bounds?!"), Reference< XInterface >() );
}
if (0 != jstr)
{
OUString name( ::javaunohelper::jstring_to_oustring( jstr, jni_env ) );
// value
jstr = (jstring)jni_env->GetObjectArrayElement( jpairs, nPos +1 );
if (JNI_FALSE != jni_env->ExceptionCheck())
{
jni_env->ExceptionClear();
throw RuntimeException(
OUSTR("index out of bounds?!"), Reference< XInterface >() );
}
if (0 != jstr)
{
OUString value( ::javaunohelper::jstring_to_oustring( jstr, jni_env ) );
// set bootstrap parameter
::rtl::Bootstrap::set( name, value );
}
}
nPos += 2;
}
}
// bootstrap uno
Reference< XComponentContext > xContext;
if (0 == juno_rc)
{
xContext = ::cppu::defaultBootstrap_InitialComponentContext();
}
else
{
OUString uno_rc( ::javaunohelper::jstring_to_oustring( juno_rc, jni_env ) );
xContext = ::cppu::defaultBootstrap_InitialComponentContext( uno_rc );
}
// create vm access
::rtl::Reference< ::jvmaccess::UnoVirtualMachine > vm_access(
::javaunohelper::create_vm_access( jni_env, loader ) );
// wrap vm singleton entry
xContext = ::javaunohelper::install_vm_singleton( xContext, vm_access );
// get uno envs
OUString cpp_env_name = OUSTR(CPPU_CURRENT_LANGUAGE_BINDING_NAME);
OUString java_env_name = OUSTR(UNO_LB_JAVA);
Environment java_env, cpp_env;
uno_getEnvironment((uno_Environment **)&cpp_env, cpp_env_name.pData, NULL);
uno_getEnvironment( (uno_Environment **)&java_env, java_env_name.pData, vm_access.get() );
// map to java
Mapping mapping( cpp_env.get(), java_env.get() );
if (! mapping.is())
{
Reference< lang::XComponent > xComp( xContext, UNO_QUERY );
if (xComp.is())
xComp->dispose();
throw RuntimeException(
OUSTR("cannot get mapping C++ <-> Java!"),
Reference< XInterface >() );
}
jobject jret = (jobject)mapping.mapInterface( xContext.get(), ::getCppuType( &xContext ) );
jobject jlocal = jni_env->NewLocalRef( jret );
jni_env->DeleteGlobalRef( jret );
return jlocal;
}
catch (RuntimeException & exc)
{
jclass c = jni_env->FindClass( "com/sun/star/uno/RuntimeException" );
if (0 != c)
{
OString cstr( ::rtl::OUStringToOString(
exc.Message, RTL_TEXTENCODING_JAVA_UTF8 ) );
OSL_TRACE( __FILE__": forwarding RuntimeException: %s", cstr.getStr() );
jni_env->ThrowNew( c, cstr.getStr() );
}
}
catch (Exception & exc)
{
jclass c = jni_env->FindClass( "com/sun/star/uno/Exception" );
if (0 != c)
{
OString cstr( ::rtl::OUStringToOString(
exc.Message, RTL_TEXTENCODING_JAVA_UTF8 ) );
OSL_TRACE( __FILE__": forwarding Exception: %s", cstr.getStr() );
jni_env->ThrowNew( c, cstr.getStr() );
}
}
return 0;
}
<commit_msg>INTEGRATION: CWS warnings01 (1.8.8); FILE MERGED 2006/01/25 19:57:46 sb 1.8.8.3: RESYNC: (1.9-1.10); FILE MERGED 2005/09/23 02:50:24 sb 1.8.8.2: RESYNC: (1.8-1.9); FILE MERGED 2005/09/09 12:44:16 sb 1.8.8.1: #i53898# Made code warning-free.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: bootstrap.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hr $ $Date: 2006-06-19 21:54:45 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "osl/diagnose.h"
#include "rtl/alloc.h"
#include "rtl/bootstrap.hxx"
#include "rtl/string.hxx"
#include "uno/mapping.hxx"
#include "uno/environment.hxx"
#include "cppuhelper/bootstrap.hxx"
#include "com/sun/star/lang/XComponent.hpp"
#include "com/sun/star/lang/XSingleComponentFactory.hpp"
#include "jni.h"
#include "jvmaccess/virtualmachine.hxx"
#include "jvmaccess/unovirtualmachine.hxx"
#include "vm.hxx"
#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using ::rtl::OString;
using ::rtl::OUString;
namespace javaunohelper
{
inline ::rtl::OUString jstring_to_oustring( jstring jstr, JNIEnv * jni_env )
{
OSL_ASSERT( sizeof (sal_Unicode) == sizeof (jchar) );
jsize len = jni_env->GetStringLength( jstr );
rtl_uString * ustr =
(rtl_uString *)rtl_allocateMemory( sizeof (rtl_uString) + (len * sizeof (sal_Unicode)) );
jni_env->GetStringRegion( jstr, 0, len, ustr->buffer );
OSL_ASSERT( JNI_FALSE == jni_env->ExceptionCheck() );
ustr->refCount = 1;
ustr->length = len;
ustr->buffer[ len ] = '\0';
return ::rtl::OUString( ustr, SAL_NO_ACQUIRE );
}
}
//==================================================================================================
extern "C" JNIEXPORT jobject JNICALL Java_com_sun_star_comp_helper_Bootstrap_cppuhelper_1bootstrap(
JNIEnv * jni_env, jclass, jstring juno_rc, jobjectArray jpairs,
jobject loader )
{
try
{
if (0 != jpairs)
{
jsize nPos = 0, len = jni_env->GetArrayLength( jpairs );
while (nPos < len)
{
// name
jstring jstr = (jstring)jni_env->GetObjectArrayElement( jpairs, nPos );
if (JNI_FALSE != jni_env->ExceptionCheck())
{
jni_env->ExceptionClear();
throw RuntimeException(
OUSTR("index out of bounds?!"), Reference< XInterface >() );
}
if (0 != jstr)
{
OUString name( ::javaunohelper::jstring_to_oustring( jstr, jni_env ) );
// value
jstr = (jstring)jni_env->GetObjectArrayElement( jpairs, nPos +1 );
if (JNI_FALSE != jni_env->ExceptionCheck())
{
jni_env->ExceptionClear();
throw RuntimeException(
OUSTR("index out of bounds?!"), Reference< XInterface >() );
}
if (0 != jstr)
{
OUString value( ::javaunohelper::jstring_to_oustring( jstr, jni_env ) );
// set bootstrap parameter
::rtl::Bootstrap::set( name, value );
}
}
nPos += 2;
}
}
// bootstrap uno
Reference< XComponentContext > xContext;
if (0 == juno_rc)
{
xContext = ::cppu::defaultBootstrap_InitialComponentContext();
}
else
{
OUString uno_rc( ::javaunohelper::jstring_to_oustring( juno_rc, jni_env ) );
xContext = ::cppu::defaultBootstrap_InitialComponentContext( uno_rc );
}
// create vm access
::rtl::Reference< ::jvmaccess::UnoVirtualMachine > vm_access(
::javaunohelper::create_vm_access( jni_env, loader ) );
// wrap vm singleton entry
xContext = ::javaunohelper::install_vm_singleton( xContext, vm_access );
// get uno envs
OUString cpp_env_name = OUSTR(CPPU_CURRENT_LANGUAGE_BINDING_NAME);
OUString java_env_name = OUSTR(UNO_LB_JAVA);
Environment java_env, cpp_env;
uno_getEnvironment((uno_Environment **)&cpp_env, cpp_env_name.pData, NULL);
uno_getEnvironment( (uno_Environment **)&java_env, java_env_name.pData, vm_access.get() );
// map to java
Mapping mapping( cpp_env.get(), java_env.get() );
if (! mapping.is())
{
Reference< lang::XComponent > xComp( xContext, UNO_QUERY );
if (xComp.is())
xComp->dispose();
throw RuntimeException(
OUSTR("cannot get mapping C++ <-> Java!"),
Reference< XInterface >() );
}
jobject jret = (jobject)mapping.mapInterface( xContext.get(), ::getCppuType( &xContext ) );
jobject jlocal = jni_env->NewLocalRef( jret );
jni_env->DeleteGlobalRef( jret );
return jlocal;
}
catch (RuntimeException & exc)
{
jclass c = jni_env->FindClass( "com/sun/star/uno/RuntimeException" );
if (0 != c)
{
OString cstr( ::rtl::OUStringToOString(
exc.Message, RTL_TEXTENCODING_JAVA_UTF8 ) );
OSL_TRACE( __FILE__": forwarding RuntimeException: %s", cstr.getStr() );
jni_env->ThrowNew( c, cstr.getStr() );
}
}
catch (Exception & exc)
{
jclass c = jni_env->FindClass( "com/sun/star/uno/Exception" );
if (0 != c)
{
OString cstr( ::rtl::OUStringToOString(
exc.Message, RTL_TEXTENCODING_JAVA_UTF8 ) );
OSL_TRACE( __FILE__": forwarding Exception: %s", cstr.getStr() );
jni_env->ThrowNew( c, cstr.getStr() );
}
}
return 0;
}
<|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 "chrome/worker/worker_thread.h"
#include "base/command_line.h"
#include "base/lazy_instance.h"
#include "base/thread_local.h"
#include "chrome/common/appcache/appcache_dispatcher.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/db_message_filter.h"
#include "chrome/common/web_database_observer_impl.h"
#include "chrome/common/worker_messages.h"
#include "chrome/worker/webworker_stub.h"
#include "chrome/worker/websharedworker_stub.h"
#include "chrome/worker/worker_webkitclient_impl.h"
#include "ipc/ipc_sync_channel.h"
#include "third_party/WebKit/WebKit/chromium/public/WebBlobRegistry.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDatabase.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/WebKit/chromium/public/WebRuntimeFeatures.h"
using WebKit::WebRuntimeFeatures;
static base::LazyInstance<base::ThreadLocalPointer<WorkerThread> > lazy_tls(
base::LINKER_INITIALIZED);
WorkerThread::WorkerThread() {
lazy_tls.Pointer()->Set(this);
webkit_client_.reset(new WorkerWebKitClientImpl);
WebKit::initialize(webkit_client_.get());
appcache_dispatcher_.reset(new AppCacheDispatcher(this));
web_database_observer_impl_.reset(new WebDatabaseObserverImpl(this));
WebKit::WebDatabase::setObserver(web_database_observer_impl_.get());
db_message_filter_ = new DBMessageFilter();
channel()->AddFilter(db_message_filter_.get());
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
WebKit::WebRuntimeFeatures::enableDatabase(
!command_line.HasSwitch(switches::kDisableDatabases));
WebKit::WebRuntimeFeatures::enableApplicationCache(
!command_line.HasSwitch(switches::kDisableApplicationCache));
#if defined(OS_WIN)
// We don't yet support notifications on non-Windows, so hide it from pages.
WebRuntimeFeatures::enableNotifications(
!command_line.HasSwitch(switches::kDisableDesktopNotifications));
#endif
WebRuntimeFeatures::enableSockets(
!command_line.HasSwitch(switches::kDisableWebSockets));
WebRuntimeFeatures::enableFileSystem(
!command_line.HasSwitch(switches::kDisableFileSystem));
}
WorkerThread::~WorkerThread() {
// Shutdown in reverse of the initialization order.
channel()->RemoveFilter(db_message_filter_.get());
db_message_filter_ = NULL;
WebKit::shutdown();
lazy_tls.Pointer()->Set(NULL);
}
WorkerThread* WorkerThread::current() {
return lazy_tls.Pointer()->Get();
}
void WorkerThread::OnControlMessageReceived(const IPC::Message& msg) {
// Appcache messages are handled by a delegate.
if (appcache_dispatcher_->OnMessageReceived(msg))
return;
IPC_BEGIN_MESSAGE_MAP(WorkerThread, msg)
IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker, OnCreateWorker)
IPC_END_MESSAGE_MAP()
}
void WorkerThread::OnCreateWorker(
const WorkerProcessMsg_CreateWorker_Params& params) {
WorkerAppCacheInitInfo appcache_init_info(
params.is_shared, params.creator_process_id,
params.creator_appcache_host_id,
params.shared_worker_appcache_id);
// WebWorkerStub and WebSharedWorkerStub own themselves.
if (params.is_shared)
new WebSharedWorkerStub(params.name, params.route_id, appcache_init_info);
else
new WebWorkerStub(params.url, params.route_id, appcache_init_info);
}
// The browser process is likely dead. Terminate all workers.
void WorkerThread::OnChannelError() {
set_on_channel_error_called(true);
for (WorkerStubsList::iterator it = worker_stubs_.begin();
it != worker_stubs_.end(); ++it) {
(*it)->OnChannelError();
}
}
void WorkerThread::RemoveWorkerStub(WebWorkerStubBase* stub) {
worker_stubs_.erase(stub);
}
void WorkerThread::AddWorkerStub(WebWorkerStubBase* stub) {
worker_stubs_.insert(stub);
}
<commit_msg>Fix bug 64688: Expose typed arrays in Workers<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 "chrome/worker/worker_thread.h"
#include "base/command_line.h"
#include "base/lazy_instance.h"
#include "base/thread_local.h"
#include "chrome/common/appcache/appcache_dispatcher.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/db_message_filter.h"
#include "chrome/common/web_database_observer_impl.h"
#include "chrome/common/worker_messages.h"
#include "chrome/worker/webworker_stub.h"
#include "chrome/worker/websharedworker_stub.h"
#include "chrome/worker/worker_webkitclient_impl.h"
#include "ipc/ipc_sync_channel.h"
#include "third_party/WebKit/WebKit/chromium/public/WebBlobRegistry.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDatabase.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/WebKit/chromium/public/WebRuntimeFeatures.h"
using WebKit::WebRuntimeFeatures;
static base::LazyInstance<base::ThreadLocalPointer<WorkerThread> > lazy_tls(
base::LINKER_INITIALIZED);
WorkerThread::WorkerThread() {
lazy_tls.Pointer()->Set(this);
webkit_client_.reset(new WorkerWebKitClientImpl);
WebKit::initialize(webkit_client_.get());
appcache_dispatcher_.reset(new AppCacheDispatcher(this));
web_database_observer_impl_.reset(new WebDatabaseObserverImpl(this));
WebKit::WebDatabase::setObserver(web_database_observer_impl_.get());
db_message_filter_ = new DBMessageFilter();
channel()->AddFilter(db_message_filter_.get());
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
WebKit::WebRuntimeFeatures::enableDatabase(
!command_line.HasSwitch(switches::kDisableDatabases));
WebKit::WebRuntimeFeatures::enableApplicationCache(
!command_line.HasSwitch(switches::kDisableApplicationCache));
#if defined(OS_WIN)
// We don't yet support notifications on non-Windows, so hide it from pages.
WebRuntimeFeatures::enableNotifications(
!command_line.HasSwitch(switches::kDisableDesktopNotifications));
#endif
WebRuntimeFeatures::enableSockets(
!command_line.HasSwitch(switches::kDisableWebSockets));
WebRuntimeFeatures::enableFileSystem(
!command_line.HasSwitch(switches::kDisableFileSystem));
WebRuntimeFeatures::enableWebGL(
!command_line.HasSwitch(switches::kDisableExperimentalWebGL));
}
WorkerThread::~WorkerThread() {
// Shutdown in reverse of the initialization order.
channel()->RemoveFilter(db_message_filter_.get());
db_message_filter_ = NULL;
WebKit::shutdown();
lazy_tls.Pointer()->Set(NULL);
}
WorkerThread* WorkerThread::current() {
return lazy_tls.Pointer()->Get();
}
void WorkerThread::OnControlMessageReceived(const IPC::Message& msg) {
// Appcache messages are handled by a delegate.
if (appcache_dispatcher_->OnMessageReceived(msg))
return;
IPC_BEGIN_MESSAGE_MAP(WorkerThread, msg)
IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker, OnCreateWorker)
IPC_END_MESSAGE_MAP()
}
void WorkerThread::OnCreateWorker(
const WorkerProcessMsg_CreateWorker_Params& params) {
WorkerAppCacheInitInfo appcache_init_info(
params.is_shared, params.creator_process_id,
params.creator_appcache_host_id,
params.shared_worker_appcache_id);
// WebWorkerStub and WebSharedWorkerStub own themselves.
if (params.is_shared)
new WebSharedWorkerStub(params.name, params.route_id, appcache_init_info);
else
new WebWorkerStub(params.url, params.route_id, appcache_init_info);
}
// The browser process is likely dead. Terminate all workers.
void WorkerThread::OnChannelError() {
set_on_channel_error_called(true);
for (WorkerStubsList::iterator it = worker_stubs_.begin();
it != worker_stubs_.end(); ++it) {
(*it)->OnChannelError();
}
}
void WorkerThread::RemoveWorkerStub(WebWorkerStubBase* stub) {
worker_stubs_.erase(stub);
}
void WorkerThread::AddWorkerStub(WebWorkerStubBase* stub) {
worker_stubs_.insert(stub);
}
<|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 "base/string_util.h"
#include "chrome/browser/worker_host/worker_service.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"
static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";
class WorkerTest : public UILayoutTest {
protected:
virtual ~WorkerTest() { }
void RunTest(const std::wstring& test_case) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url = GetTestUrl(L"workers", test_case);
ASSERT_TRUE(tab->NavigateToURL(url));
std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);
ASSERT_STREQ(kTestCompleteSuccess, value.c_str());
}
bool WaitForProcessCountToBe(int tabs, int workers) {
// The 1 is for the browser process.
int number_of_processes = 1 + workers +
(UITest::in_process_renderer() ? 0 : tabs);
#if defined(OS_LINUX)
// On Linux, we also have a zygote process and a sandbox host process.
number_of_processes += 2;
#endif
int cur_process_count;
for (int i = 0; i < 10; ++i) {
cur_process_count = GetBrowserProcessCount();
if (cur_process_count == number_of_processes)
return true;
PlatformThread::Sleep(sleep_timeout_ms() / 10);
}
EXPECT_EQ(number_of_processes, cur_process_count);
return false;
}
};
TEST_F(WorkerTest, SingleWorker) {
RunTest(L"single_worker.html");
}
TEST_F(WorkerTest, MultipleWorkers) {
RunTest(L"multi_worker.html");
}
#if defined(OS_LINUX)
#define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests
#endif
TEST_F(WorkerTest, WorkerFastLayoutTests) {
static const char* kLayoutTestFiles[] = {
"stress-js-execution.html",
"use-machine-stack.html",
"worker-call.html",
"worker-cloneport.html",
"worker-close.html",
"worker-constructor.html",
"worker-context-gc.html",
"worker-context-multi-port.html",
"worker-event-listener.html",
"worker-gc.html",
// worker-lifecycle.html relies on layoutTestController.workerThreadCount
// which is not currently implemented.
// "worker-lifecycle.html",
"worker-location.html",
"worker-messageport.html",
// Disabled after r27089 (WebKit merge), http://crbug.com/22947
// "worker-messageport-gc.html",
"worker-multi-port.html",
"worker-navigator.html",
"worker-replace-global-constructor.html",
"worker-replace-self.html",
"worker-script-error.html",
"worker-terminate.html",
// clearInterval() sometimes lets the timer continue to fire
// http://code.google.com/p/chromium/issues/detail?id=25548
// "worker-timeout.html"
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// Worker tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
TEST_F(WorkerTest, WorkerHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
// flakey? BUG 16934 "text-encoding.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"worker-importScripts.html",
#endif
"worker-redirect.html",
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
"abort-exception-assert.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"close.html",
#endif
//"methods-async.html",
//"methods.html",
"xmlhttprequest-file-not-found.html"
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest");
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, MessagePorts) {
static const char* kLayoutTestFiles[] = {
"message-channel-gc.html",
"message-channel-gc-2.html",
"message-channel-gc-3.html",
"message-channel-gc-4.html",
"message-port.html",
"message-port-clone.html",
// http://code.google.com/p/chromium/issues/detail?id=23709
// "message-port-constructor-for-deleted-document.html",
"message-port-deleted-document.html",
"message-port-deleted-frame.html",
// http://crbug.com/23597 (caused by http://trac.webkit.org/changeset/48978)
// "message-port-inactive-document.html",
"message-port-multi.html",
"message-port-no-wrapper.html",
// Only works with run-webkit-tests --leaks.
//"message-channel-listener-circular-ownership.html",
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("events");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// MessagePort tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
// Disable LimitPerPage on Linux. Seems to work on Mac though:
// http://code.google.com/p/chromium/issues/detail?id=22608
#if !defined(OS_LINUX)
// This test fails after WebKit merge 49414:49432. (BUG=24652)
TEST_F(WorkerTest, LimitPerPage) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1),
UITest::GetBrowserProcessCount());
}
#endif
TEST_F(WorkerTest, LimitTotal) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
int total_workers = WorkerService::kMaxWorkersWhenSeparate;
int tab_count = (total_workers / max_workers_per_tab) + 1;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
for (int i = 1; i < tab_count; ++i)
window->AppendTab(url);
// Check that we didn't create more than the max number of workers.
ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
// Now close a page and check that the queued workers were started.
tab->NavigateToURL(GetTestUrl(L"google", L"google.html"));
ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
}
<commit_msg>Enable back some worker UI tests.<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 "base/string_util.h"
#include "chrome/browser/worker_host/worker_service.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"
static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";
class WorkerTest : public UILayoutTest {
protected:
virtual ~WorkerTest() { }
void RunTest(const std::wstring& test_case) {
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
GURL url = GetTestUrl(L"workers", test_case);
ASSERT_TRUE(tab->NavigateToURL(url));
std::string value = WaitUntilCookieNonEmpty(tab.get(), url,
kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);
ASSERT_STREQ(kTestCompleteSuccess, value.c_str());
}
bool WaitForProcessCountToBe(int tabs, int workers) {
// The 1 is for the browser process.
int number_of_processes = 1 + workers +
(UITest::in_process_renderer() ? 0 : tabs);
#if defined(OS_LINUX)
// On Linux, we also have a zygote process and a sandbox host process.
number_of_processes += 2;
#endif
int cur_process_count;
for (int i = 0; i < 10; ++i) {
cur_process_count = GetBrowserProcessCount();
if (cur_process_count == number_of_processes)
return true;
PlatformThread::Sleep(sleep_timeout_ms() / 10);
}
EXPECT_EQ(number_of_processes, cur_process_count);
return false;
}
};
TEST_F(WorkerTest, SingleWorker) {
RunTest(L"single_worker.html");
}
TEST_F(WorkerTest, MultipleWorkers) {
RunTest(L"multi_worker.html");
}
#if defined(OS_LINUX)
#define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests
#endif
TEST_F(WorkerTest, WorkerFastLayoutTests) {
static const char* kLayoutTestFiles[] = {
"stress-js-execution.html",
"use-machine-stack.html",
"worker-call.html",
"worker-cloneport.html",
"worker-close.html",
"worker-constructor.html",
"worker-context-gc.html",
"worker-context-multi-port.html",
"worker-event-listener.html",
"worker-gc.html",
// worker-lifecycle.html relies on layoutTestController.workerThreadCount
// which is not currently implemented.
// "worker-lifecycle.html",
"worker-location.html",
"worker-messageport.html",
// Disabled after r27089 (WebKit merge), http://crbug.com/22947
// "worker-messageport-gc.html",
"worker-multi-port.html",
"worker-navigator.html",
"worker-replace-global-constructor.html",
"worker-replace-self.html",
"worker-script-error.html",
"worker-terminate.html",
// clearInterval() sometimes lets the timer continue to fire
// http://code.google.com/p/chromium/issues/detail?id=25548
// "worker-timeout.html"
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// Worker tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
TEST_F(WorkerTest, WorkerHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
// flakey? BUG 16934 "text-encoding.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"worker-importScripts.html",
#endif
"worker-redirect.html",
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {
static const char* kLayoutTestFiles[] = {
"abort-exception-assert.html",
#if defined(OS_WIN)
// Fails on the mac (and linux?):
// http://code.google.com/p/chromium/issues/detail?id=22599
"close.html",
#endif
//"methods-async.html",
//"methods.html",
"xmlhttprequest-file-not-found.html"
};
FilePath http_test_dir;
http_test_dir = http_test_dir.AppendASCII("LayoutTests");
http_test_dir = http_test_dir.AppendASCII("http");
http_test_dir = http_test_dir.AppendASCII("tests");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest");
worker_test_dir = worker_test_dir.AppendASCII("workers");
InitializeForLayoutTest(http_test_dir, worker_test_dir, true);
StartHttpServer(new_http_root_dir_);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], true);
StopHttpServer();
}
TEST_F(WorkerTest, MessagePorts) {
static const char* kLayoutTestFiles[] = {
"message-channel-gc.html",
"message-channel-gc-2.html",
"message-channel-gc-3.html",
"message-channel-gc-4.html",
"message-port.html",
"message-port-clone.html",
"message-port-constructor-for-deleted-document.html",
"message-port-deleted-document.html",
"message-port-deleted-frame.html",
"message-port-inactive-document.html",
"message-port-multi.html",
"message-port-no-wrapper.html",
// Only works with run-webkit-tests --leaks.
//"message-channel-listener-circular-ownership.html",
};
FilePath fast_test_dir;
fast_test_dir = fast_test_dir.AppendASCII("LayoutTests");
fast_test_dir = fast_test_dir.AppendASCII("fast");
FilePath worker_test_dir;
worker_test_dir = worker_test_dir.AppendASCII("events");
InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);
// MessagePort tests also rely on common files in js/resources.
FilePath js_dir = fast_test_dir.AppendASCII("js");
FilePath resource_dir;
resource_dir = resource_dir.AppendASCII("resources");
AddResourceForLayoutTest(js_dir, resource_dir);
for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)
RunLayoutTest(kLayoutTestFiles[i], false);
}
// Disable LimitPerPage on Linux. Seems to work on Mac though:
// http://code.google.com/p/chromium/issues/detail?id=22608
#if !defined(OS_LINUX)
// This test fails after WebKit merge 49414:49432. (BUG=24652)
TEST_F(WorkerTest, LimitPerPage) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1),
UITest::GetBrowserProcessCount());
}
#endif
TEST_F(WorkerTest, LimitTotal) {
int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;
int total_workers = WorkerService::kMaxWorkersWhenSeparate;
int tab_count = (total_workers / max_workers_per_tab) + 1;
GURL url = GetTestUrl(L"workers", L"many_workers.html");
url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab));
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(url));
scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
for (int i = 1; i < tab_count; ++i)
window->AppendTab(url);
// Check that we didn't create more than the max number of workers.
ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
// Now close a page and check that the queued workers were started.
tab->NavigateToURL(GetTestUrl(L"google", L"google.html"));
ASSERT_TRUE(WaitForProcessCountToBe(tab_count, total_workers));
}
<|endoftext|>
|
<commit_before>// This pass performs some transformations to enable parallel code
// generation.
#include "astutil.h"
#include "expr.h"
#include "passes.h"
#include "stmt.h"
#include "symbol.h"
#include "stringutil.h"
#include "driver.h"
#include "files.h"
// Move begin blocks into their own functions so that it can be later
// interfaced with the expected thread interface.
static void
begin_encapsulation() {
int ufid = 1;
forv_Vec( ModuleSymbol, mod, allModules) {
Vec<BaseAST*> asts;
collect_asts( &asts, mod);
forv_Vec( BaseAST, ast, asts) {
if (BlockStmt *b = dynamic_cast<BlockStmt*>(ast)) {
if (BLOCK_BEGIN == b->blockTag) {
// replace with a new block w/ each stmt -> function call
BlockStmt *newb = new BlockStmt();
newb->blockTag = b->blockTag;
char *fname = stringcat( "_begin_block", intstring( ufid++));
FnSymbol *fn = new FnSymbol( fname);
fn->retType = dtVoid;
for_alist(Expr, stmt, b->body) {
stmt->remove();
fn->insertAtTail( stmt); // move stmts to new begin function
}
b->insertAtTail( new DefExpr( fn));
b->insertAtTail( new CallExpr( fname));
}
}
}
}
}
// This pass moves each cobegin statement into nested functions. Currently,
// each statement is moved to within it's own function and the
// appropriate function def and call expressions are added.
static void
cobegin_encapsulation() {
int ufid = 1;
forv_Vec( ModuleSymbol, mod, allModules) {
Vec<BaseAST*> asts;
collect_asts( &asts, mod);
forv_Vec( BaseAST, ast, asts) {
if (BlockStmt *b = dynamic_cast<BlockStmt*>(ast)) {
if (BLOCK_COBEGIN == b->blockTag) {
// replace with a new block w/ each stmt -> function call
BlockStmt *newb = new BlockStmt();
newb->blockTag = b->blockTag;
for_alist(Expr, stmt, b->body) {
char *fname = stringcat( "_cobegin_stmt", intstring( ufid++));
FnSymbol *fn = new FnSymbol( fname);
fn->retType = dtVoid;
stmt->remove();
fn->insertAtTail( stmt); // move stmt to new function
newb->insertAtHead( new DefExpr (fn));
newb->insertAtTail( new CallExpr (fname));
}
b->insertBefore (newb);
b->remove ();
}
}
}
}
}
void
parallel1 (void) {
addLibInfo ("-lpthread");
if (parallelPass) {
begin_encapsulation(); // move begin block to within a function
cobegin_encapsulation(); // move cobegin stmts to within a function
}
}
// Mark locals that should be heap allocated and insert a call to allocate
// them on the heap. This is for begin blocks where the forked child thread
// and parent thread may have different lifetimes. The locals cannot live
// on a thread's stack.
static void
begin_mark_locals() {
Vec<SymExpr*> arglist;
// Find all the args that should be heap allocated -> arglist
forv_Vec( ModuleSymbol, mod, allModules) {
Vec<BaseAST*> asts;
collect_asts( &asts, mod);
forv_Vec( BaseAST, ast, asts) {
BlockStmt *b = dynamic_cast<BlockStmt*>(ast);
if (b && (BLOCK_BEGIN == b->blockTag)) {
// note, should only be one call expr in the body of the begin
for_alist( Expr, stmt, b->body) {
if (CallExpr *fcall = dynamic_cast<CallExpr*>(stmt)) {
// add the args that need to be heap allocated
for_actuals(arg, fcall) {
if (SymExpr *s = dynamic_cast<SymExpr*>(arg)) {
arglist.add( s);
}
}
}
}
}
}
}
// do a buch of stuff:
// - mark locals as heap allocated
// - create associated mutex + reference counter
// - add mutex + ref-counter to nested function's arg list
// - add calls to init ref-counter, touch, and free
forv_Vec( SymExpr, se, arglist) {
VarSymbol *local; // var that is referenced
if (!(local = dynamic_cast<VarSymbol*>( se->var))) {
INT_FATAL( se->var, "currently can only handle locals (not args)");
}
Expr *localdef = local->defPoint;
if (!local->on_heap) { // no reference counter associated yet
local->on_heap = true;
// create reference counter
char *refcname = stringcat( "_", stringcat(local->name, "_refc"));
VarSymbol *refc = new VarSymbol( refcname,
dtInt[INT_SIZE_32],
VAR_NORMAL,
VAR_VAR);
refc->on_heap = true;
localdef->insertBefore( new DefExpr( refc));
local->refc = refc;
// create reference counter mutex
char *mname = stringcat( "_", stringcat(local->name, "_refcmutex"));
VarSymbol *m = new VarSymbol( mname, dtMutex, VAR_NORMAL, VAR_VAR);
m->on_heap = true; // needs to be heap allocated
localdef->insertBefore( new DefExpr( m));
local->refcMutex = m;
}
// add refc and mutex args as both actuals and formals
CallExpr *ce;
if (!(ce = dynamic_cast<CallExpr*>( se->parentExpr))) {
INT_FATAL( se->parentExpr, "should be walking args of a call within begin");
}
ce->argList->insertAtTail( new SymExpr( local->refc));
ce->argList->insertAtTail( new SymExpr( local->refcMutex));
ArgSymbol *rc_arg = new ArgSymbol( INTENT_REF,
local->refc->name,
dtInt[INT_SIZE_32]);
ArgSymbol *rcm_arg = new ArgSymbol( INTENT_REF,
local->refcMutex->name,
dtMutex);
FnSymbol *fn = dynamic_cast<FnSymbol*>( (dynamic_cast<SymExpr*>( ce->baseExpr))->var);
fn->insertFormalAtTail(new DefExpr( rc_arg));
fn->insertFormalAtTail(new DefExpr( rcm_arg));
localdef->insertAfter( new CallExpr( PRIMITIVE_REFC_TOUCH,
local,
local->refc,
local->refcMutex));
localdef->insertAfter( new CallExpr( PRIMITIVE_REFC_INIT,
local,
local->refc,
local->refcMutex));
BlockStmt *mainfb = dynamic_cast<BlockStmt*>(localdef->parentExpr);
Expr *laststmt = mainfb->body->last();
if (dynamic_cast<ReturnStmt*>(laststmt)) {
laststmt->insertBefore( new CallExpr( PRIMITIVE_REFC_RELEASE,
local,
local->refc,
local->refcMutex));
} else {
laststmt->insertAfter( new CallExpr( PRIMITIVE_REFC_RELEASE,
local,
local->refc,
local->refcMutex));
}
// add touch + release for the begin block
se->getStmtExpr()->parentExpr->insertBefore( new CallExpr( PRIMITIVE_REFC_TOUCH,
local,
local->refc,
local->refcMutex));
ArgSymbol *fa = dynamic_cast<ArgSymbol*>( actual_to_formal( se));
fn->body->body->last()->insertBefore( new CallExpr( PRIMITIVE_REFC_RELEASE,
fa,
rc_arg,
rcm_arg));
}
// for each on_heap variable, add call to allocate it
forv_Vec(ModuleSymbol, mod, allModules) {
Vec<BaseAST*> asts;
asts.clear();
collect_asts_postorder(&asts, mod);
forv_Vec(BaseAST, ast, asts) {
if (VarSymbol *vs = dynamic_cast<VarSymbol*>(ast)) {
if (vs->on_heap) {
CallExpr *alloc = new CallExpr( PRIMITIVE_CHPL_ALLOC,
vs->type->symbol,
new_StringSymbol("heap alloc'd via begin"));
vs->defPoint->insertAfter(new CallExpr(PRIMITIVE_SET_HEAPVAR,
vs->defPoint->sym,
alloc));
}
}
}
}
}
// Package args into a class and call a wrapper function with that
// object. The wrapper function will then call the function
// created by the previous parallel pass. This is a way to pass along
// multiple args through the limitation of one arg in the runtime's
// thread creation interface.
static void
thread_args() {
forv_Vec( ModuleSymbol, mod, allModules) {
Vec<BaseAST*> asts;
collect_asts( &asts, mod);
forv_Vec( BaseAST, ast, asts) {
if (BlockStmt *b = dynamic_cast<BlockStmt*>(ast)) {
if ((BLOCK_BEGIN == b->blockTag) ||
(BLOCK_COBEGIN == b->blockTag)) {
BlockStmt *newb = new BlockStmt();
newb->blockTag = b->blockTag;
for_alist(Expr, expr, b->body) {
if (CallExpr *fcall = dynamic_cast<CallExpr*>(expr)) {
// create a new class to capture refs to locals
char* fname = (dynamic_cast<SymExpr*>(fcall->baseExpr))->var->name;
ClassType* ctype = new ClassType( CLASS_CLASS);
TypeSymbol* new_c = new TypeSymbol( stringcat("_class_locals",
fname),
ctype);
// disable reference counting, handle manually
new_c->addPragma("no gc");
// add the function args as fields in the class
for_actuals(arg, fcall) {
SymExpr *s = dynamic_cast<SymExpr*>(arg);
Symbol *var = s->var; // arg or var
VarSymbol* field = new VarSymbol(var->name, var->type);
field->is_ref = true;
ctype->fields->insertAtTail(new DefExpr(field));
}
mod->stmts->insertAtHead(new DefExpr(new_c));
// create the class variable instance and allocate it
VarSymbol *tempc = new VarSymbol( stringcat( "_args_for",
fname),
ctype);
b->insertBefore( new DefExpr( tempc));
CallExpr *tempc_alloc = new CallExpr( PRIMITIVE_CHPL_ALLOC,
ctype->symbol,
new_StringSymbol( stringcat( "instance of class ", ctype->symbol->name)));
b->insertBefore( new CallExpr( PRIMITIVE_MOVE,
tempc,
tempc_alloc));
// set the references in the class instance
for_actuals(arg, fcall) {
SymExpr *s = dynamic_cast<SymExpr*>(arg);
Symbol *var = s->var; // var or arg
CallExpr *setc=new CallExpr(PRIMITIVE_SET_MEMBER_REF_TO,
tempc,
ctype->getField(var->name),
var);
b->insertBefore( setc);
}
// create wrapper-function that uses the class instance
FnSymbol *wrap_fn = new FnSymbol( stringcat("wrap", fname));
DefExpr *fcall_def= (dynamic_cast<SymExpr*>( fcall->baseExpr))->var->defPoint;
ArgSymbol *wrap_c = new ArgSymbol( INTENT_BLANK, "c", ctype);
wrap_fn->insertFormalAtTail( wrap_c);
mod->stmts->insertAtTail(new DefExpr(wrap_fn));
newb->insertAtTail( new CallExpr( wrap_fn, tempc));
wrap_fn->insertAtTail(new CallExpr(PRIMITIVE_CHPL_FREE, wrap_c));
// translate the original cobegin function
CallExpr *new_cofn = new CallExpr( (dynamic_cast<SymExpr*>(fcall->baseExpr))->var);
for_fields(field, ctype) { // insert args
new_cofn->insertAtTail( new CallExpr(PRIMITIVE_GET_MEMBER_REF_TO,
wrap_c,
field));
}
// WAW: touch + free for the class arg wrapper
/* WAW: this strategy doesn't work because the _touch/_free
functions are not defined.
if (!no_gc && (BLOCK_BEGIN == b->blockTag)) {
b->insertBefore( new CallExpr( new FnSymbol("_touch"), tempc));
wrap_fn->insertAtTail( new CallExpr( new FnSymbol("_free"), wrap_c));
}
*/
wrap_fn->retType = dtVoid;
fcall->remove(); // rm orig. call
wrap_fn->insertAtHead(new_cofn); // add new call
wrap_fn->insertAtHead(new CallExpr(PRIMITIVE_THREAD_INIT));
fcall_def->remove(); // move orig. def
mod->stmts->insertAtTail(fcall_def); // to top-level
normalize(wrap_fn);
}
}
b->replace(newb);
}
}
}
}
}
void
parallel2 (void) {
if (parallelPass) {
begin_mark_locals();
thread_args();
}
}
<commit_msg>Minor comment changes and cleanup.<commit_after>// This pass performs some transformations to enable parallel code
// generation for begin and cobegin blocks.
#include "astutil.h"
#include "expr.h"
#include "passes.h"
#include "stmt.h"
#include "symbol.h"
#include "stringutil.h"
#include "driver.h"
#include "files.h"
// Move begin blocks into their own functions so that it can be later
// interfaced with the expected thread interface.
static void
begin_encapsulation() {
int ufid = 1;
forv_Vec( ModuleSymbol, mod, allModules) {
Vec<BaseAST*> asts;
collect_asts( &asts, mod);
forv_Vec( BaseAST, ast, asts) {
if (BlockStmt *b = dynamic_cast<BlockStmt*>(ast)) {
if (BLOCK_BEGIN == b->blockTag) {
// replace with a new block w/ each stmt -> function call
BlockStmt *newb = new BlockStmt();
newb->blockTag = b->blockTag;
char *fname = stringcat( "_begin_block", intstring( ufid++));
FnSymbol *fn = new FnSymbol( fname);
fn->retType = dtVoid;
for_alist(Expr, stmt, b->body) {
stmt->remove();
fn->insertAtTail( stmt); // move stmts to new begin function
}
b->insertAtTail( new DefExpr( fn));
b->insertAtTail( new CallExpr( fname));
}
}
}
}
}
// This pass moves each cobegin statement into nested functions. Currently,
// each statement is moved to within it's own function and the
// appropriate function def and call expressions are added.
static void
cobegin_encapsulation() {
int ufid = 1;
forv_Vec( ModuleSymbol, mod, allModules) {
Vec<BaseAST*> asts;
collect_asts( &asts, mod);
forv_Vec( BaseAST, ast, asts) {
if (BlockStmt *b = dynamic_cast<BlockStmt*>(ast)) {
if (BLOCK_COBEGIN == b->blockTag) {
// replace with a new block w/ each stmt -> function call
BlockStmt *newb = new BlockStmt();
newb->blockTag = b->blockTag;
for_alist(Expr, stmt, b->body) {
char *fname = stringcat( "_cobegin_stmt", intstring( ufid++));
FnSymbol *fn = new FnSymbol( fname);
fn->retType = dtVoid;
stmt->remove();
fn->insertAtTail( stmt); // move stmt to new function
newb->insertAtHead( new DefExpr (fn));
newb->insertAtTail( new CallExpr (fname));
}
b->insertBefore (newb);
b->remove ();
}
}
}
}
}
// First pass of the parallel transformations for begin and cobegin blocks.
void
parallel1 (void) {
addLibInfo ("-lpthread");
if (parallelPass) {
begin_encapsulation(); // move begin block to within a function
cobegin_encapsulation(); // move cobegin stmts to within a function
}
}
// Mark locals that should be heap allocated and insert a call to allocate
// them on the heap. This is for begin blocks where the forked child thread
// and parent thread may have different lifetimes. The locals cannot live
// on a thread's stack.
// In addition to moving these vars to the heap, we will also use
// reference counting to garbage collect. Will need a counter and mutex
// for each var. Of course, those will be heap allocated also.
static void
begin_mark_locals() {
Vec<SymExpr*> arglist;
// Find all the args that should be heap allocated -> arglist
forv_Vec( ModuleSymbol, mod, allModules) {
Vec<BaseAST*> asts;
collect_asts( &asts, mod);
forv_Vec( BaseAST, ast, asts) {
BlockStmt *b = dynamic_cast<BlockStmt*>(ast);
if (b && (BLOCK_BEGIN == b->blockTag)) {
// note, should only be one call expr in the body of the begin
for_alist( Expr, stmt, b->body) {
if (CallExpr *fcall = dynamic_cast<CallExpr*>(stmt)) {
// add the args that need to be heap allocated
for_actuals(arg, fcall) {
if (SymExpr *s = dynamic_cast<SymExpr*>(arg)) {
arglist.add( s);
}
}
}
}
}
}
}
// do a buch of stuff:
// - mark locals as heap allocated
// - create associated mutex + reference counter
// - add mutex + ref-counter to nested function's arg list
// - add calls to init ref-counter, touch, and free
forv_Vec( SymExpr, se, arglist) {
VarSymbol *local; // var that is referenced
if (!(local = dynamic_cast<VarSymbol*>( se->var))) {
INT_FATAL( se->var, "currently can only handle locals (not args)");
}
Expr *localdef = local->defPoint;
if (!local->on_heap) { // no reference counter associated yet
local->on_heap = true;
// create reference counter
char *refcname = stringcat( "_", stringcat(local->name, "_refc"));
VarSymbol *refc = new VarSymbol( refcname,
dtInt[INT_SIZE_32],
VAR_NORMAL,
VAR_VAR);
refc->on_heap = true;
localdef->insertBefore( new DefExpr( refc));
local->refc = refc;
// create reference counter mutex
char *mname = stringcat( "_", stringcat(local->name, "_refcmutex"));
VarSymbol *m = new VarSymbol( mname, dtMutex, VAR_NORMAL, VAR_VAR);
m->on_heap = true; // needs to be heap allocated
localdef->insertBefore( new DefExpr( m));
local->refcMutex = m;
}
// add refc and mutex args as both actuals and formals
CallExpr *ce;
if (!(ce = dynamic_cast<CallExpr*>( se->parentExpr))) {
INT_FATAL( se->parentExpr, "should be walking args of a call within begin");
}
ce->argList->insertAtTail( new SymExpr( local->refc));
ce->argList->insertAtTail( new SymExpr( local->refcMutex));
ArgSymbol *rc_arg = new ArgSymbol( INTENT_REF,
local->refc->name,
dtInt[INT_SIZE_32]);
ArgSymbol *rcm_arg = new ArgSymbol( INTENT_REF,
local->refcMutex->name,
dtMutex);
FnSymbol *fn = dynamic_cast<FnSymbol*>( (dynamic_cast<SymExpr*>( ce->baseExpr))->var);
fn->insertFormalAtTail(new DefExpr( rc_arg));
fn->insertFormalAtTail(new DefExpr( rcm_arg));
localdef->insertAfter( new CallExpr( PRIMITIVE_REFC_TOUCH,
local,
local->refc,
local->refcMutex));
localdef->insertAfter( new CallExpr( PRIMITIVE_REFC_INIT,
local,
local->refc,
local->refcMutex));
BlockStmt *mainfb = dynamic_cast<BlockStmt*>(localdef->parentExpr);
Expr *laststmt = mainfb->body->last();
if (dynamic_cast<ReturnStmt*>(laststmt)) {
laststmt->insertBefore( new CallExpr( PRIMITIVE_REFC_RELEASE,
local,
local->refc,
local->refcMutex));
} else {
laststmt->insertAfter( new CallExpr( PRIMITIVE_REFC_RELEASE,
local,
local->refc,
local->refcMutex));
}
// add touch + release for the begin block
se->getStmtExpr()->parentExpr->insertBefore( new CallExpr( PRIMITIVE_REFC_TOUCH,
local,
local->refc,
local->refcMutex));
ArgSymbol *fa = dynamic_cast<ArgSymbol*>( actual_to_formal( se));
fn->body->body->last()->insertBefore( new CallExpr( PRIMITIVE_REFC_RELEASE,
fa,
rc_arg,
rcm_arg));
}
// for each on_heap variable, add call to allocate it
forv_Vec(ModuleSymbol, mod, allModules) {
Vec<BaseAST*> asts;
asts.clear();
collect_asts_postorder(&asts, mod);
forv_Vec(BaseAST, ast, asts) {
if (VarSymbol *vs = dynamic_cast<VarSymbol*>(ast)) {
if (vs->on_heap) {
CallExpr *alloc = new CallExpr( PRIMITIVE_CHPL_ALLOC,
vs->type->symbol,
new_StringSymbol("heap alloc'd via begin"));
vs->defPoint->insertAfter(new CallExpr(PRIMITIVE_SET_HEAPVAR,
vs->defPoint->sym,
alloc));
}
}
}
}
}
// Package args into a class and call a wrapper function with that
// object. The wrapper function will then call the function
// created by the previous parallel pass. This is a way to pass along
// multiple args through the limitation of one arg in the runtime's
// thread creation interface.
static void
thread_args() {
forv_Vec( ModuleSymbol, mod, allModules) {
Vec<BaseAST*> asts;
collect_asts( &asts, mod);
forv_Vec( BaseAST, ast, asts) {
if (BlockStmt *b = dynamic_cast<BlockStmt*>(ast)) {
if ((BLOCK_BEGIN == b->blockTag) ||
(BLOCK_COBEGIN == b->blockTag)) {
BlockStmt *newb = new BlockStmt();
newb->blockTag = b->blockTag;
for_alist(Expr, expr, b->body) {
if (CallExpr *fcall = dynamic_cast<CallExpr*>(expr)) {
// create a new class to capture refs to locals
char* fname = (dynamic_cast<SymExpr*>(fcall->baseExpr))->var->name;
ClassType* ctype = new ClassType( CLASS_CLASS);
TypeSymbol* new_c = new TypeSymbol( stringcat("_class_locals",
fname),
ctype);
// disable reference counting, handle manually
new_c->addPragma("no gc");
// add the function args as fields in the class
for_actuals(arg, fcall) {
SymExpr *s = dynamic_cast<SymExpr*>(arg);
Symbol *var = s->var; // arg or var
VarSymbol* field = new VarSymbol(var->name, var->type);
field->is_ref = true;
ctype->fields->insertAtTail(new DefExpr(field));
}
mod->stmts->insertAtHead(new DefExpr(new_c));
// create the class variable instance and allocate it
VarSymbol *tempc = new VarSymbol( stringcat( "_args_for",
fname),
ctype);
b->insertBefore( new DefExpr( tempc));
CallExpr *tempc_alloc = new CallExpr( PRIMITIVE_CHPL_ALLOC,
ctype->symbol,
new_StringSymbol( stringcat( "instance of class ", ctype->symbol->name)));
b->insertBefore( new CallExpr( PRIMITIVE_MOVE,
tempc,
tempc_alloc));
// set the references in the class instance
for_actuals(arg, fcall) {
SymExpr *s = dynamic_cast<SymExpr*>(arg);
Symbol *var = s->var; // var or arg
CallExpr *setc=new CallExpr(PRIMITIVE_SET_MEMBER_REF_TO,
tempc,
ctype->getField(var->name),
var);
b->insertBefore( setc);
}
// create wrapper-function that uses the class instance
FnSymbol *wrap_fn = new FnSymbol( stringcat("wrap", fname));
DefExpr *fcall_def= (dynamic_cast<SymExpr*>( fcall->baseExpr))->var->defPoint;
ArgSymbol *wrap_c = new ArgSymbol( INTENT_BLANK, "c", ctype);
wrap_fn->insertFormalAtTail( wrap_c);
mod->stmts->insertAtTail(new DefExpr(wrap_fn));
newb->insertAtTail( new CallExpr( wrap_fn, tempc));
wrap_fn->insertAtTail(new CallExpr(PRIMITIVE_CHPL_FREE, wrap_c));
// translate the original cobegin function
CallExpr *new_cofn = new CallExpr( (dynamic_cast<SymExpr*>(fcall->baseExpr))->var);
for_fields(field, ctype) { // insert args
new_cofn->insertAtTail( new CallExpr(PRIMITIVE_GET_MEMBER_REF_TO,
wrap_c,
field));
}
wrap_fn->retType = dtVoid;
fcall->remove(); // rm orig. call
wrap_fn->insertAtHead(new_cofn); // add new call
wrap_fn->insertAtHead(new CallExpr(PRIMITIVE_THREAD_INIT));
fcall_def->remove(); // move orig. def
mod->stmts->insertAtTail(fcall_def); // to top-level
normalize(wrap_fn);
}
}
b->replace(newb);
}
}
}
}
}
// Second pass of the parallel transformations for begin and cobegin blocks.
void
parallel2 (void) {
if (parallelPass) {
begin_mark_locals();
thread_args();
}
}
<|endoftext|>
|
<commit_before>#include "peel_outer_hull_layers.h"
#include "outer_hull.h"
#include "writePLY.h"
#include <vector>
#include <iostream>
#define IGL_PEEL_OUTER_HULL_LAYERS_DEBUG
#ifdef IGL_PEEL_OUTER_HULL_LAYERS_DEBUG
#include "STR.h"
#endif
template <
typename DerivedV,
typename DerivedF,
typename Derivedodd,
typename Derivedflip>
IGL_INLINE size_t igl::peel_outer_hull_layers(
const Eigen::PlainObjectBase<DerivedV > & V,
const Eigen::PlainObjectBase<DerivedF > & F,
Eigen::PlainObjectBase<Derivedodd > & odd,
Eigen::PlainObjectBase<Derivedflip > & flip)
{
using namespace Eigen;
using namespace std;
typedef typename DerivedF::Index Index;
typedef Matrix<typename DerivedF::Scalar,Dynamic,DerivedF::ColsAtCompileTime> MatrixXF;
typedef Matrix<Index,Dynamic,1> MatrixXI;
typedef Matrix<typename Derivedflip::Scalar,Dynamic,Derivedflip::ColsAtCompileTime> MatrixXflip;
const Index m = F.rows();
#ifdef IGL_PEEL_OUTER_HULL_LAYERS_DEBUG
cout<<"peel outer hull layers..."<<endl;
#endif
#ifdef IGL_PEEL_OUTER_HULL_LAYERS_DEBUG
cout<<"resize output ..."<<endl;
#endif
// keep track of iteration parity and whether flipped in hull
MatrixXF Fr = F;
odd.resize(m,1);
flip.resize(m,1);
// Keep track of index map
MatrixXI IM = MatrixXI::LinSpaced(m,0,m-1);
// This is O(n * layers)
bool odd_iter = true;
MatrixXI P(m,1);
Index iter = 0;
while(Fr.size() > 0)
{
assert(Fr.rows() == IM.rows());
// Compute outer hull of current Fr
MatrixXF Fo;
MatrixXI Jo;
MatrixXflip flipr;
#ifdef IGL_PEEL_OUTER_HULL_LAYERS_DEBUG
cout<<"calling outer hull..."<<endl;
writePLY(STR("outer-hull-input-"<<iter<<".ply"),V,Fr);
#endif
outer_hull(V,Fr,Fo,Jo,flipr);
#ifdef IGL_PEEL_OUTER_HULL_LAYERS_DEBUG
writePLY(STR("outer-hull-output-"<<iter<<".ply"),V,Fo);
cout<<"reindex, flip..."<<endl;
#endif
assert(Fo.rows() == Jo.rows());
// all faces in Fo of Fr
vector<bool> in_outer(Fr.rows(),false);
for(Index g = 0;g<Jo.rows();g++)
{
odd(IM(Jo(g))) = odd_iter;
P(IM(Jo(g))) = iter;
in_outer[Jo(g)] = true;
flip(IM(Jo(g))) = flipr(Jo(g));
}
// Fr = Fr - Fo
// update IM
MatrixXF prev_Fr = Fr;
MatrixXI prev_IM = IM;
Fr.resize(prev_Fr.rows() - Fo.rows(),F.cols());
IM.resize(Fr.rows());
{
Index g = 0;
for(Index f = 0;f<prev_Fr.rows();f++)
{
if(!in_outer[f])
{
Fr.row(g) = prev_Fr.row(f);
IM(g) = prev_IM(f);
g++;
}
}
}
odd_iter = !odd_iter;
iter++;
}
return iter;
}
#ifdef IGL_STATIC_LIBRARY
// Explicit template specialization
template size_t igl::peel_outer_hull_layers<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<bool, -1, 1, 0, -1, 1>, Eigen::Matrix<bool, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<bool, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<bool, -1, 1, 0, -1, 1> >&);
#endif
<commit_msg>turn off debug<commit_after>#include "peel_outer_hull_layers.h"
#include "outer_hull.h"
#include "writePLY.h"
#include <vector>
#include <iostream>
//#define IGL_PEEL_OUTER_HULL_LAYERS_DEBUG
#ifdef IGL_PEEL_OUTER_HULL_LAYERS_DEBUG
#include "STR.h"
#endif
template <
typename DerivedV,
typename DerivedF,
typename Derivedodd,
typename Derivedflip>
IGL_INLINE size_t igl::peel_outer_hull_layers(
const Eigen::PlainObjectBase<DerivedV > & V,
const Eigen::PlainObjectBase<DerivedF > & F,
Eigen::PlainObjectBase<Derivedodd > & odd,
Eigen::PlainObjectBase<Derivedflip > & flip)
{
using namespace Eigen;
using namespace std;
typedef typename DerivedF::Index Index;
typedef Matrix<typename DerivedF::Scalar,Dynamic,DerivedF::ColsAtCompileTime> MatrixXF;
typedef Matrix<Index,Dynamic,1> MatrixXI;
typedef Matrix<typename Derivedflip::Scalar,Dynamic,Derivedflip::ColsAtCompileTime> MatrixXflip;
const Index m = F.rows();
#ifdef IGL_PEEL_OUTER_HULL_LAYERS_DEBUG
cout<<"peel outer hull layers..."<<endl;
#endif
#ifdef IGL_PEEL_OUTER_HULL_LAYERS_DEBUG
cout<<"resize output ..."<<endl;
#endif
// keep track of iteration parity and whether flipped in hull
MatrixXF Fr = F;
odd.resize(m,1);
flip.resize(m,1);
// Keep track of index map
MatrixXI IM = MatrixXI::LinSpaced(m,0,m-1);
// This is O(n * layers)
bool odd_iter = true;
MatrixXI P(m,1);
Index iter = 0;
while(Fr.size() > 0)
{
assert(Fr.rows() == IM.rows());
// Compute outer hull of current Fr
MatrixXF Fo;
MatrixXI Jo;
MatrixXflip flipr;
#ifdef IGL_PEEL_OUTER_HULL_LAYERS_DEBUG
cout<<"calling outer hull..."<<endl;
writePLY(STR("outer-hull-input-"<<iter<<".ply"),V,Fr);
#endif
outer_hull(V,Fr,Fo,Jo,flipr);
#ifdef IGL_PEEL_OUTER_HULL_LAYERS_DEBUG
writePLY(STR("outer-hull-output-"<<iter<<".ply"),V,Fo);
cout<<"reindex, flip..."<<endl;
#endif
assert(Fo.rows() == Jo.rows());
// all faces in Fo of Fr
vector<bool> in_outer(Fr.rows(),false);
for(Index g = 0;g<Jo.rows();g++)
{
odd(IM(Jo(g))) = odd_iter;
P(IM(Jo(g))) = iter;
in_outer[Jo(g)] = true;
flip(IM(Jo(g))) = flipr(Jo(g));
}
// Fr = Fr - Fo
// update IM
MatrixXF prev_Fr = Fr;
MatrixXI prev_IM = IM;
Fr.resize(prev_Fr.rows() - Fo.rows(),F.cols());
IM.resize(Fr.rows());
{
Index g = 0;
for(Index f = 0;f<prev_Fr.rows();f++)
{
if(!in_outer[f])
{
Fr.row(g) = prev_Fr.row(f);
IM(g) = prev_IM(f);
g++;
}
}
}
odd_iter = !odd_iter;
iter++;
}
return iter;
}
#ifdef IGL_STATIC_LIBRARY
// Explicit template specialization
template size_t igl::peel_outer_hull_layers<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<bool, -1, 1, 0, -1, 1>, Eigen::Matrix<bool, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<bool, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<bool, -1, 1, 0, -1, 1> >&);
#endif
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2016 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_JSON_STRINGIFIER_HPP
#define MAPNIK_JSON_STRINGIFIER_HPP
// mapnik
#include <mapnik/json/generic_json.hpp>
#include <mapnik/util/conversions.hpp>
#include <mapnik/util/variant.hpp>
// stl
#include <string>
namespace mapnik { namespace json {
struct stringifier
{
std::string operator()(std::string const& val) const
{
return "\"" + val + "\"";
}
std::string operator()(value_null) const
{
return "null";
}
std::string operator()(value_bool val) const
{
return val ? "true" : "false";
}
std::string operator()(value_integer val) const
{
std::string str;
util::to_string(str, val);
return str;
}
std::string operator()(value_double val) const
{
std::string str;
util::to_string(str, val);
return str;
}
std::string operator()(std::vector<mapnik::json::json_value> const& array) const
{
std::string str = "[";
bool first = true;
for (auto const& val : array)
{
if (first) first = false;
else str += ",";
str += mapnik::util::apply_visitor(*this, val);
}
str += "]";
return str;
}
std::string operator()(std::vector<std::pair<std::string, mapnik::json::json_value>> const& object) const
{
std::string str = "{";
bool first = true;
for (auto const& kv : object)
{
if (first) first = false;
else str += ",";
str += kv.first;
str += ":";
str += mapnik::util::apply_visitor(*this, kv.second);
}
str += "}";
return str;
}
};
}}
#endif // MAPNIK_JSON_STRINGIFIER_HPP
<commit_msg>json stringifier - add missing quoting in nested json objects (ref #3491)<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2016 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_JSON_STRINGIFIER_HPP
#define MAPNIK_JSON_STRINGIFIER_HPP
// mapnik
#include <mapnik/json/generic_json.hpp>
#include <mapnik/util/conversions.hpp>
#include <mapnik/util/variant.hpp>
// stl
#include <string>
namespace mapnik { namespace json {
struct stringifier
{
std::string operator()(std::string const& val) const
{
return "\"" + val + "\"";
}
std::string operator()(value_null) const
{
return "null";
}
std::string operator()(value_bool val) const
{
return val ? "true" : "false";
}
std::string operator()(value_integer val) const
{
std::string str;
util::to_string(str, val);
return str;
}
std::string operator()(value_double val) const
{
std::string str;
util::to_string(str, val);
return str;
}
std::string operator()(std::vector<mapnik::json::json_value> const& array) const
{
std::string str = "[";
bool first = true;
for (auto const& val : array)
{
if (first) first = false;
else str += ",";
str += mapnik::util::apply_visitor(*this, val);
}
str += "]";
return str;
}
std::string operator()(std::vector<std::pair<std::string, mapnik::json::json_value>> const& object) const
{
std::string str = "{";
bool first = true;
for (auto const& kv : object)
{
if (first) first = false;
else str += ",";
str += "\"" + kv.first + "\"";
str += ":";
str += mapnik::util::apply_visitor(*this, kv.second);
}
str += "}";
return str;
}
};
}}
#endif // MAPNIK_JSON_STRINGIFIER_HPP
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2016 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_SVG_PATH_PARSER_HPP
#define MAPNIK_SVG_PATH_PARSER_HPP
// mapnik
#include <mapnik/config.hpp>
#include <mapnik/svg/svg_converter.hpp>
#include <mapnik/svg/svg_path_attributes.hpp>
// stl
#include <string>
namespace mapnik {
namespace svg {
template <typename PathType>
bool parse_path(const char* wkt, PathType& p);
template <typename PathType>
bool parse_points(const char* wkt, PathType& p);
template <typename TransformType>
bool MAPNIK_DECL parse_svg_transform(const char* wkt, TransformType& tr);
//
extern template bool MAPNIK_DECL parse_path<svg_converter_type>(const char*, svg_converter_type&);
extern template bool MAPNIK_DECL parse_points<svg_converter_type>(const char*, svg_converter_type&);
extern template bool MAPNIK_DECL parse_svg_transform<svg_converter_type>(const char*, svg_converter_type&);
}
}
#endif // MAPNIK_SVG_PATH_PARSER_HPP
<commit_msg>remove unused include directive<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2016 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_SVG_PATH_PARSER_HPP
#define MAPNIK_SVG_PATH_PARSER_HPP
// mapnik
#include <mapnik/config.hpp>
#include <mapnik/svg/svg_converter.hpp>
// stl
#include <string>
namespace mapnik {
namespace svg {
template <typename PathType>
bool parse_path(const char* wkt, PathType& p);
template <typename PathType>
bool parse_points(const char* wkt, PathType& p);
template <typename TransformType>
bool MAPNIK_DECL parse_svg_transform(const char* wkt, TransformType& tr);
//
extern template bool MAPNIK_DECL parse_path<svg_converter_type>(const char*, svg_converter_type&);
extern template bool MAPNIK_DECL parse_points<svg_converter_type>(const char*, svg_converter_type&);
extern template bool MAPNIK_DECL parse_svg_transform<svg_converter_type>(const char*, svg_converter_type&);
}
}
#endif // MAPNIK_SVG_PATH_PARSER_HPP
<|endoftext|>
|
<commit_before>/*
* Copyright 2010,
* François Bleibel,
* Olivier Stasse,
*
* CNRS/AIST
*
*/
#ifndef __SOTVECTORTOMATRIX_HH
#define __SOTVECTORTOMATRIX_HH
#include <dynamic-graph/all-signals.h>
#include <dynamic-graph/entity.h>
#include <sot/core/matrix-geometry.hh>
/* Matrix */
#include <dynamic-graph/linear-algebra.h>
/* STD */
#include <vector>
/* --------------------------------------------------------------------- */
/* --- API ------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
#if defined(WIN32)
#if defined(vector_to_rotation_EXPORTS)
#define SOTVECTORTOROTATION_EXPORT __declspec(dllexport)
#else
#define SOTVECTORTOROTATION_EXPORT __declspec(dllimport)
#endif
#else
#define SOTVECTORTOROTATION_EXPORT
#endif
/* --------------------------------------------------------------------- */
/* --- VECTOR ---------------------------------------------------------- */
/* --------------------------------------------------------------------- */
namespace dynamicgraph {
namespace sot {
class SOTVECTORTOROTATION_EXPORT VectorToRotation
: public dynamicgraph::Entity {
enum sotAxis { AXIS_X, AXIS_Y, AXIS_Z };
unsigned int size;
std::vector<sotAxis> axes;
public:
static const std::string CLASS_NAME;
virtual const std::string &getClassName(void) const { return CLASS_NAME; }
VectorToRotation(const std::string &name);
virtual ~VectorToRotation(void) {}
dynamicgraph::SignalPtr<dynamicgraph::Vector, int> SIN;
dynamicgraph::SignalTimeDependent<MatrixRotation, int> SOUT;
MatrixRotation &computeRotation(const dynamicgraph::Vector &angles,
MatrixRotation &res);
};
} /* namespace sot */
} /* namespace dynamicgraph */
#endif // #ifndef __SOTVECTORTOMATRIX_HH
<commit_msg>deprecate vector-to-rotation, fix #128<commit_after>/*
* Copyright 2010,
* François Bleibel,
* Olivier Stasse,
*
* CNRS/AIST
*
*/
#ifndef __SOTVECTORTOMATRIX_HH
#define __SOTVECTORTOMATRIX_HH
#include <dynamic-graph/all-signals.h>
#include <dynamic-graph/entity.h>
#include <sot/core/matrix-geometry.hh>
/* Matrix */
#include <dynamic-graph/linear-algebra.h>
/* STD */
#include <vector>
/* --------------------------------------------------------------------- */
/* --- API ------------------------------------------------------------- */
/* --------------------------------------------------------------------- */
#if defined(WIN32)
#if defined(vector_to_rotation_EXPORTS)
#define SOTVECTORTOROTATION_EXPORT __declspec(dllexport)
#else
#define SOTVECTORTOROTATION_EXPORT __declspec(dllimport)
#endif
#else
#define SOTVECTORTOROTATION_EXPORT
#endif
/* --------------------------------------------------------------------- */
/* --- VECTOR ---------------------------------------------------------- */
/* --------------------------------------------------------------------- */
namespace dynamicgraph {
namespace sot {
class[[deprecated("use RPYToMatrix")]] SOTVECTORTOROTATION_EXPORT
VectorToRotation : public dynamicgraph::Entity {
enum sotAxis { AXIS_X, AXIS_Y, AXIS_Z };
unsigned int size;
std::vector<sotAxis> axes;
public:
static const std::string CLASS_NAME;
virtual const std::string &getClassName(void) const { return CLASS_NAME; }
VectorToRotation(const std::string &name);
virtual ~VectorToRotation(void) {}
dynamicgraph::SignalPtr<dynamicgraph::Vector, int> SIN;
dynamicgraph::SignalTimeDependent<MatrixRotation, int> SOUT;
MatrixRotation &computeRotation(const dynamicgraph::Vector &angles,
MatrixRotation &res);
};
} /* namespace sot */
} /* namespace dynamicgraph */
#endif // #ifndef __SOTVECTORTOMATRIX_HH
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.