text
stringlengths 54
60.6k
|
---|
<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2012, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* 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 "Quota.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Quota::get_quota(
const string& id,
VectorAttribute ** va,
map<string, Attribute *>::iterator& it)
{
VectorAttribute * q;
istringstream iss(id);
int id_i;
*va = 0;
if ( id.empty() )
{
return -1;
}
iss >> id_i;
if (iss.fail() || !iss.eof())
{
return -1;
}
for ( it = attributes.begin(); it != attributes.end(); it++)
{
q = static_cast<VectorAttribute *>(it->second);
if (q->vector_value("ID") == id)
{
*va = q;
return 0;
}
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Quota::add_to_quota(VectorAttribute * attr, const string& va_name, float num)
{
istringstream iss;
ostringstream oss;
float total;
iss.str(attr->vector_value(va_name.c_str()));
iss >> total;
total += num;
oss << total;
attr->replace(va_name, oss.str());
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Quota::set(vector<Attribute*> * new_quotas, bool default_allowed, string& error)
{
vector<Attribute *>::iterator it;
VectorAttribute * iq;
VectorAttribute * tq;
string id;
for ( it = new_quotas->begin(); it != new_quotas->end(); it++)
{
iq = dynamic_cast<VectorAttribute *>(*it);
if ( iq == 0 )
{
goto error_limits;
}
id = iq->vector_value("ID");
if ( get_quota(id, &tq) == -1 )
{
goto error_limits;
}
if ( tq == 0 )
{
VectorAttribute * nq;
if ((nq = new_quota(iq, default_allowed)) == 0)
{
goto error_limits;
}
add(nq);
}
else
{
if (update_limits(tq, iq, default_allowed) != 0)
{
goto error_limits;
}
}
cleanup_quota(id);
}
return 0;
error_limits:
ostringstream oss;
oss << "Negative limits or bad format in quota " << template_name;
if ( iq != 0 )
{
string * quota_str = iq->marshall(",");
oss << " = [ " << *quota_str << " ]";
delete quota_str;
}
error = oss.str();
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
bool Quota::check_quota(const string& qid,
map<string, float>& usage_req,
Quotas& default_quotas,
string& error)
{
VectorAttribute * q;
VectorAttribute * default_q;
map<string, float>::iterator it;
bool check;
float limit;
float usage;
if ( get_quota(qid, &q) == -1 )
{
ostringstream oss;
oss << "String '" << qid << "' is not a valid ID";
error = oss.str();
return false;
}
if ( get_default_quota(qid, default_quotas, &default_q) == -1 )
{
default_q = 0;
}
// -------------------------------------------------------------------------
// Quota does not exist, create a new one
// -------------------------------------------------------------------------
if ( q == 0 )
{
map<string, string> values;
for (int i=0; i < num_metrics; i++)
{
string metrics_used = metrics[i];
metrics_used += "_USED";
values.insert(make_pair(metrics[i], "-1"));
values.insert(make_pair(metrics_used, "0"));
}
if (!qid.empty())
{
values.insert(make_pair("ID", qid));
}
q = new VectorAttribute(template_name, values);
add(q);
}
// -------------------------------------------------------------------------
// Check the quotas for each usage request
// -------------------------------------------------------------------------
for (int i=0; i < num_metrics; i++)
{
string metrics_used = metrics[i];
metrics_used += "_USED";
it = usage_req.find(metrics[i]);
if (it == usage_req.end())
{
continue;
}
q->vector_value(metrics[i], limit);
q->vector_value(metrics_used.c_str(), usage);
if ( limit == -1 )
{
if ( default_q != 0 )
{
default_q->vector_value(metrics[i], limit);
}
else
{
limit = 0;
}
}
check = ( limit == 0 ) || ( ( usage + it->second ) <= limit );
if ( !check )
{
ostringstream oss;
oss << "limit of " << limit << " reached for " << metrics[i]
<< " quota in " << template_name;
if ( !qid.empty() )
{
oss << " with ID: " << qid;
}
error = oss.str();
return false;
}
}
// -------------------------------------------------------------------------
// Add resource usage to quotas
// -------------------------------------------------------------------------
for (int i=0; i < num_metrics; i++)
{
string metrics_used = metrics[i];
metrics_used += "_USED";
it = usage_req.find(metrics[i]);
if (it == usage_req.end())
{
continue;
}
add_to_quota(q, metrics_used, it->second);
}
return true;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Quota::del_quota(const string& qid, map<string, float>& usage_req)
{
VectorAttribute * q;
map<string, float>::iterator it;
if ( get_quota(qid, &q) == -1)
{
return;
}
if ( q == 0 )
{
return;
}
for (int i=0; i < num_metrics; i++)
{
string metrics_used = metrics[i];
metrics_used += "_USED";
it = usage_req.find(metrics[i]);
if (it == usage_req.end())
{
continue;
}
add_to_quota(q, metrics_used, -it->second);
}
cleanup_quota(qid);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Quota::cleanup_quota(const string& qid)
{
VectorAttribute * q;
map<string, Attribute *>::iterator q_it;
float limit, limit_tmp;
float usage, usage_tmp;
if ( get_quota(qid, &q, q_it) == -1)
{
return;
}
if ( q == 0 )
{
return;
}
limit = 0;
usage = 0;
for (int i=0; i < num_metrics; i++)
{
string metrics_used = metrics[i];
metrics_used += "_USED";
q->vector_value(metrics[i], limit_tmp);
q->vector_value(metrics_used.c_str(), usage_tmp);
limit += limit_tmp;
usage += usage_tmp;
}
if ( limit == 0 && usage == 0 )
{
delete static_cast<Attribute *>(q_it->second);
attributes.erase(q_it);
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Quota::update_limits(
VectorAttribute * quota,
const VectorAttribute * va,
bool default_allowed)
{
string limit;
float limit_i;
for (int i=0; i < num_metrics; i++)
{
limit = va->vector_value_str(metrics[i], limit_i);
//No quota, NaN or negative
if ((default_allowed &&
( limit_i < -1 || ( limit_i == -1 && limit == "" ))) ||
(!default_allowed && limit_i < 0) )
{
return -1;
}
else
{
quota->replace(metrics[i], limit);
}
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
VectorAttribute * Quota::new_quota(VectorAttribute * va, bool default_allowed)
{
map<string,string> limits;
string limit;
int limit_i;
for (int i=0; i < num_metrics; i++)
{
string metrics_used = metrics[i];
metrics_used += "_USED";
limit = va->vector_value_str(metrics[i], limit_i);
//No quota, NaN or negative
if ( (default_allowed && limit_i < -1) ||
(!default_allowed && limit_i < 0) )
{
limit = "0";
}
limits.insert(make_pair(metrics[i], limit));
limits.insert(make_pair(metrics_used, "0"));
}
string id = va->vector_value("ID");
if ( !id.empty() )
{
limits.insert(make_pair("ID", id));
}
return new VectorAttribute(template_name,limits);
}
<commit_msg>Feature #1611: Fix quota cleanup<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2012, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* 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 "Quota.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Quota::get_quota(
const string& id,
VectorAttribute ** va,
map<string, Attribute *>::iterator& it)
{
VectorAttribute * q;
istringstream iss(id);
int id_i;
*va = 0;
if ( id.empty() )
{
return -1;
}
iss >> id_i;
if (iss.fail() || !iss.eof())
{
return -1;
}
for ( it = attributes.begin(); it != attributes.end(); it++)
{
q = static_cast<VectorAttribute *>(it->second);
if (q->vector_value("ID") == id)
{
*va = q;
return 0;
}
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Quota::add_to_quota(VectorAttribute * attr, const string& va_name, float num)
{
istringstream iss;
ostringstream oss;
float total;
iss.str(attr->vector_value(va_name.c_str()));
iss >> total;
total += num;
oss << total;
attr->replace(va_name, oss.str());
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Quota::set(vector<Attribute*> * new_quotas, bool default_allowed, string& error)
{
vector<Attribute *>::iterator it;
VectorAttribute * iq;
VectorAttribute * tq;
string id;
for ( it = new_quotas->begin(); it != new_quotas->end(); it++)
{
iq = dynamic_cast<VectorAttribute *>(*it);
if ( iq == 0 )
{
goto error_limits;
}
id = iq->vector_value("ID");
if ( get_quota(id, &tq) == -1 )
{
goto error_limits;
}
if ( tq == 0 )
{
VectorAttribute * nq;
if ((nq = new_quota(iq, default_allowed)) == 0)
{
goto error_limits;
}
add(nq);
}
else
{
if (update_limits(tq, iq, default_allowed) != 0)
{
goto error_limits;
}
}
cleanup_quota(id);
}
return 0;
error_limits:
ostringstream oss;
oss << "Negative limits or bad format in quota " << template_name;
if ( iq != 0 )
{
string * quota_str = iq->marshall(",");
oss << " = [ " << *quota_str << " ]";
delete quota_str;
}
error = oss.str();
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
bool Quota::check_quota(const string& qid,
map<string, float>& usage_req,
Quotas& default_quotas,
string& error)
{
VectorAttribute * q;
VectorAttribute * default_q;
map<string, float>::iterator it;
bool check;
float limit;
float usage;
if ( get_quota(qid, &q) == -1 )
{
ostringstream oss;
oss << "String '" << qid << "' is not a valid ID";
error = oss.str();
return false;
}
if ( get_default_quota(qid, default_quotas, &default_q) == -1 )
{
default_q = 0;
}
// -------------------------------------------------------------------------
// Quota does not exist, create a new one
// -------------------------------------------------------------------------
if ( q == 0 )
{
map<string, string> values;
for (int i=0; i < num_metrics; i++)
{
string metrics_used = metrics[i];
metrics_used += "_USED";
values.insert(make_pair(metrics[i], "-1"));
values.insert(make_pair(metrics_used, "0"));
}
if (!qid.empty())
{
values.insert(make_pair("ID", qid));
}
q = new VectorAttribute(template_name, values);
add(q);
}
// -------------------------------------------------------------------------
// Check the quotas for each usage request
// -------------------------------------------------------------------------
for (int i=0; i < num_metrics; i++)
{
string metrics_used = metrics[i];
metrics_used += "_USED";
it = usage_req.find(metrics[i]);
if (it == usage_req.end())
{
continue;
}
q->vector_value(metrics[i], limit);
q->vector_value(metrics_used.c_str(), usage);
if ( limit == -1 )
{
if ( default_q != 0 )
{
default_q->vector_value(metrics[i], limit);
}
else
{
limit = 0;
}
}
check = ( limit == 0 ) || ( ( usage + it->second ) <= limit );
if ( !check )
{
ostringstream oss;
oss << "limit of " << limit << " reached for " << metrics[i]
<< " quota in " << template_name;
if ( !qid.empty() )
{
oss << " with ID: " << qid;
}
error = oss.str();
return false;
}
}
// -------------------------------------------------------------------------
// Add resource usage to quotas
// -------------------------------------------------------------------------
for (int i=0; i < num_metrics; i++)
{
string metrics_used = metrics[i];
metrics_used += "_USED";
it = usage_req.find(metrics[i]);
if (it == usage_req.end())
{
continue;
}
add_to_quota(q, metrics_used, it->second);
}
return true;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Quota::del_quota(const string& qid, map<string, float>& usage_req)
{
VectorAttribute * q;
map<string, float>::iterator it;
if ( get_quota(qid, &q) == -1)
{
return;
}
if ( q == 0 )
{
return;
}
for (int i=0; i < num_metrics; i++)
{
string metrics_used = metrics[i];
metrics_used += "_USED";
it = usage_req.find(metrics[i]);
if (it == usage_req.end())
{
continue;
}
add_to_quota(q, metrics_used, -it->second);
}
cleanup_quota(qid);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Quota::cleanup_quota(const string& qid)
{
VectorAttribute * q;
map<string, Attribute *>::iterator q_it;
float usage, usage_tmp, limit_tmp;
bool no_limit;
if ( get_quota(qid, &q, q_it) == -1)
{
return;
}
if ( q == 0 )
{
return;
}
no_limit = true;
usage = 0;
for (int i=0; i < num_metrics; i++)
{
string metrics_used = metrics[i];
metrics_used += "_USED";
q->vector_value(metrics[i], limit_tmp);
q->vector_value(metrics_used.c_str(), usage_tmp);
no_limit = (no_limit && (limit_tmp <= 0) ); // Unlimited or default limit
usage += usage_tmp;
}
if ( usage == 0 && no_limit )
{
delete static_cast<Attribute *>(q_it->second);
attributes.erase(q_it);
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Quota::update_limits(
VectorAttribute * quota,
const VectorAttribute * va,
bool default_allowed)
{
string limit;
float limit_i;
for (int i=0; i < num_metrics; i++)
{
limit = va->vector_value_str(metrics[i], limit_i);
//No quota, NaN or negative
if ((default_allowed &&
( limit_i < -1 || ( limit_i == -1 && limit == "" ))) ||
(!default_allowed && limit_i < 0) )
{
return -1;
}
else
{
quota->replace(metrics[i], limit);
}
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
VectorAttribute * Quota::new_quota(VectorAttribute * va, bool default_allowed)
{
map<string,string> limits;
string limit;
int limit_i;
for (int i=0; i < num_metrics; i++)
{
string metrics_used = metrics[i];
metrics_used += "_USED";
limit = va->vector_value_str(metrics[i], limit_i);
//No quota, NaN or negative
if ( (default_allowed && limit_i < -1) ||
(!default_allowed && limit_i < 0) )
{
limit = "0";
}
limits.insert(make_pair(metrics[i], limit));
limits.insert(make_pair(metrics_used, "0"));
}
string id = va->vector_value("ID");
if ( !id.empty() )
{
limits.insert(make_pair("ID", id));
}
return new VectorAttribute(template_name,limits);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>
using namespace std;
#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1
typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;
const double eps = 1e-6;
const ll LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;
#define x first
#define y second
#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);
const int maxw=50000;
double dp[maxw+10];
struct node
{
int a,b;
bool operator <(const node t) const
{
return 1.0*b/a>1.0*t.b/t.a;
}
}wa[110],st[110];
double Greed(int n,int w)
{
double sum=0;
int i=0;
while(w&&i<n)
{
if(w>=wa[i].a)
{
sum+=wa[i].b;
w-=wa[i++].a;
}
else
{
sum+=w*1.0*wa[i].b/wa[i].a;
w=0;
}
}
return sum;
}
int n,w;
int c,i,l=0,r=0;
void Init(){
memset(dp,0,sizeof(dp));
for(i=0;i<n;i++)
{
scanf("%d%d%d",&st[l].a,&st[l].b,&c);
if(c)
wa[r++]=st[l];
else
l++;
}
sort(wa,wa+r);
return ;
}
void Solve(){
REP(i,1,w)
dp[i]=Greed(r,i);
REP(i,0,l-1)
REPD(j,w,st[i].a)
dp[j]=max(dp[j],dp[j-st[i].a]+st[i].b);
printf("%.2lf\n",dp[w]);
return ;
}
int main(){
freopen("uoj9513.in","r",stdin);
while(~scanf("%d%d",&n,&w))
Init(),Solve();
return 0;
}<commit_msg>update uoj9513<commit_after>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>
using namespace std;
#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1
typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;
const double eps = 1e-6;
const ll LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;
#define x first
#define y second
#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);
const int maxw=50000;
double dp[maxw+10];
struct node
{
int a,b;
bool operator <(const node t) const
{
return 1.0*b/a>1.0*t.b/t.a;//单价最高的
}
}wa[110],st[110];
double Greed(int n,int w)
{
double sum=0;
int i=0;
while(w&&i<n)
{
if(w>=wa[i].a)//从单价最高的开始取,取到不能全部放入
{
sum+=wa[i].b;
w-=wa[i++].a;
}
else//不能全部放入就放满
{
sum+=w*1.0*wa[i].b/wa[i].a;
w=0;
}
}
return sum;
}
int n,w;
int c,i,l=0,r=0;
void Init(){
memset(dp,0,sizeof(dp));
for(i=0;i<n;i++)
{
scanf("%d%d%d",&st[l].a,&st[l].b,&c);
if(c)
wa[r++]=st[l];
else
l++;
}
sort(wa,wa+r);
return ;
}
void Solve(){
//先全部放水
REP(i,1,w)
dp[i]=Greed(r,i);
//01背包咯
REP(i,0,l-1)
REPD(j,w,st[i].a)
dp[j]>?=dp[j-st[i].a]+st[i].b;
printf("%.2lf\n",dp[w]);
return ;
}
int main(){
freopen("uoj9513.in","r",stdin);
while(~scanf("%d%d",&n,&w))
Init(),Solve();
return 0;
}<|endoftext|> |
<commit_before>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "QmitkInteractionSchemeToolBar.h"
#include <QActionGroup>
QmitkInteractionSchemeToolBar::QmitkInteractionSchemeToolBar(QWidget* parent/* = nullptr*/)
: QToolBar(parent)
, m_ActionGroup(new QActionGroup(this))
, m_InteractionSchemeSwitcher(nullptr)
, m_InteractionEventHandler(nullptr)
{
QToolBar::setOrientation(Qt::Vertical);
QToolBar::setIconSize(QSize(17, 17));
m_ActionGroup->setExclusive(false); // allow having no action selected
AddButton(InteractionScheme::PACSStandard, tr("Pointer"), QIcon(":/Qmitk/mm_pointer.png"), true);
AddButton(InteractionScheme::PACSLevelWindow, tr("Level/Window"), QIcon(":/Qmitk/mm_contrast.png"));
AddButton(InteractionScheme::PACSPan, tr("Pan"), QIcon(":/Qmitk/mm_pan.png"));
AddButton(InteractionScheme::PACSScroll, tr("Scroll"), QIcon(":/Qmitk/mm_scroll.png"));
AddButton(InteractionScheme::PACSZoom, tr("Zoom"), QIcon(":/Qmitk/mm_zoom.png"));
m_InteractionSchemeSwitcher = mitk::InteractionSchemeSwitcher::New();
}
void QmitkInteractionSchemeToolBar::SetInteractionEventHandler(mitk::InteractionEventHandler::Pointer interactionEventHandler)
{
if (interactionEventHandler == m_InteractionEventHandler)
{
return;
}
m_InteractionEventHandler = interactionEventHandler;
try
{
m_InteractionSchemeSwitcher->SetInteractionScheme(m_InteractionEventHandler, InteractionScheme::PACSStandard);
}
catch (const mitk::Exception&)
{
return;
}
}
void QmitkInteractionSchemeToolBar::AddButton(InteractionScheme interactionScheme, const QString& toolName, const QIcon& icon, bool on)
{
QAction* action = new QAction(icon, toolName, this);
action->setCheckable(true);
action->setActionGroup(m_ActionGroup);
action->setChecked(on);
action->setData(interactionScheme);
connect(action, SIGNAL(triggered()), this, SLOT(OnInteractionSchemeChanged()));
QToolBar::addAction(action);
}
QmitkInteractionSchemeToolBar::~QmitkInteractionSchemeToolBar()
{
// nothing here
}
void QmitkInteractionSchemeToolBar::OnInteractionSchemeChanged()
{
QAction* action = dynamic_cast<QAction*>(sender());
if (action)
{
for (auto actionIter : m_ActionGroup->actions())
{
if (actionIter != action)
{
actionIter->setChecked(false);
}
}
InteractionScheme interactionScheme = static_cast<InteractionScheme>(action->data().toInt());
// If the selected option is unchecked, use the base interaction with no primary tool
if (!action->isChecked())
{
interactionScheme = InteractionScheme::PACSBase;
}
try
{
m_InteractionSchemeSwitcher->SetInteractionScheme(m_InteractionEventHandler, interactionScheme);
}
catch (const mitk::Exception&)
{
return;
}
}
}
<commit_msg>Set width of PACS toolbar to fixed size to avoid changing render window size<commit_after>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "QmitkInteractionSchemeToolBar.h"
#include <QActionGroup>
QmitkInteractionSchemeToolBar::QmitkInteractionSchemeToolBar(QWidget* parent/* = nullptr*/)
: QToolBar(parent)
, m_ActionGroup(new QActionGroup(this))
, m_InteractionSchemeSwitcher(nullptr)
, m_InteractionEventHandler(nullptr)
{
QToolBar::setOrientation(Qt::Vertical);
QToolBar::setIconSize(QSize(17, 17));
QToolBar::setFixedWidth(33);
m_ActionGroup->setExclusive(false); // allow having no action selected
AddButton(InteractionScheme::PACSStandard, tr("Pointer"), QIcon(":/Qmitk/mm_pointer.png"), true);
AddButton(InteractionScheme::PACSLevelWindow, tr("Level/Window"), QIcon(":/Qmitk/mm_contrast.png"));
AddButton(InteractionScheme::PACSPan, tr("Pan"), QIcon(":/Qmitk/mm_pan.png"));
AddButton(InteractionScheme::PACSScroll, tr("Scroll"), QIcon(":/Qmitk/mm_scroll.png"));
AddButton(InteractionScheme::PACSZoom, tr("Zoom"), QIcon(":/Qmitk/mm_zoom.png"));
m_InteractionSchemeSwitcher = mitk::InteractionSchemeSwitcher::New();
}
void QmitkInteractionSchemeToolBar::SetInteractionEventHandler(mitk::InteractionEventHandler::Pointer interactionEventHandler)
{
if (interactionEventHandler == m_InteractionEventHandler)
{
return;
}
m_InteractionEventHandler = interactionEventHandler;
try
{
m_InteractionSchemeSwitcher->SetInteractionScheme(m_InteractionEventHandler, InteractionScheme::PACSStandard);
}
catch (const mitk::Exception&)
{
return;
}
}
void QmitkInteractionSchemeToolBar::AddButton(InteractionScheme interactionScheme, const QString& toolName, const QIcon& icon, bool on)
{
QAction* action = new QAction(icon, toolName, this);
action->setCheckable(true);
action->setActionGroup(m_ActionGroup);
action->setChecked(on);
action->setData(interactionScheme);
connect(action, SIGNAL(triggered()), this, SLOT(OnInteractionSchemeChanged()));
QToolBar::addAction(action);
}
QmitkInteractionSchemeToolBar::~QmitkInteractionSchemeToolBar()
{
// nothing here
}
void QmitkInteractionSchemeToolBar::OnInteractionSchemeChanged()
{
QAction* action = dynamic_cast<QAction*>(sender());
if (action)
{
for (auto actionIter : m_ActionGroup->actions())
{
if (actionIter != action)
{
actionIter->setChecked(false);
}
}
InteractionScheme interactionScheme = static_cast<InteractionScheme>(action->data().toInt());
// If the selected option is unchecked, use the base interaction with no primary tool
if (!action->isChecked())
{
interactionScheme = InteractionScheme::PACSBase;
}
try
{
m_InteractionSchemeSwitcher->SetInteractionScheme(m_InteractionEventHandler, interactionScheme);
}
catch (const mitk::Exception&)
{
return;
}
}
}
<|endoftext|> |
<commit_before>#include "keyboard-layout-manager.h"
#include <X11/XKBlib.h>
#include <X11/Xutil.h>
#include <X11/extensions/XKBrules.h>
#include <cwctype>
void KeyboardLayoutManager::Init(v8::Handle<v8::Object> exports, v8::Handle<v8::Object> module) {
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> newTemplate = Nan::New<v8::FunctionTemplate>(KeyboardLayoutManager::New);
newTemplate->SetClassName(Nan::New<v8::String>("KeyboardLayoutManager").ToLocalChecked());
newTemplate->InstanceTemplate()->SetInternalFieldCount(1);
v8::Local<v8::ObjectTemplate> proto = newTemplate->PrototypeTemplate();
Nan::SetMethod(proto, "getCurrentKeyboardLayout", KeyboardLayoutManager::GetCurrentKeyboardLayout);
Nan::SetMethod(proto, "getCurrentKeyboardLanguage", KeyboardLayoutManager::GetCurrentKeyboardLayout); // NB: Intentionally mapped to same stub
Nan::SetMethod(proto, "getInstalledKeyboardLanguages", KeyboardLayoutManager::GetInstalledKeyboardLanguages);
Nan::SetMethod(proto, "getCurrentKeymap", KeyboardLayoutManager::GetCurrentKeymap);
module->Set(Nan::New("exports").ToLocalChecked(), newTemplate->GetFunction());
}
NODE_MODULE(keyboard_layout_manager, KeyboardLayoutManager::Init)
NAN_METHOD(KeyboardLayoutManager::New) {
Nan::HandleScope scope;
v8::Local<v8::Function> callbackHandle = info[0].As<v8::Function>();
Nan::Callback *callback = new Nan::Callback(callbackHandle);
KeyboardLayoutManager *manager = new KeyboardLayoutManager(callback);
manager->Wrap(info.This());
return;
}
KeyboardLayoutManager::KeyboardLayoutManager(Nan::Callback *callback) : callback(callback) {
xDisplay = XOpenDisplay("");
if (!xDisplay) {
Nan::ThrowError("Could not connect to X display.");
}
XIM xInputMethod = XOpenIM(xDisplay, 0, 0, 0);
if (!xInputMethod) {
Nan::ThrowError("Could not create an input method.");
}
XIMStyles* styles = 0;
if (XGetIMValues(xInputMethod, XNQueryInputStyle, &styles, NULL) || !styles) {
Nan::ThrowError("Could not retrieve input styles.");
}
XIMStyle bestMatchStyle = 0;
for (int i = 0; i < styles->count_styles; i++) {
XIMStyle thisStyle = styles->supported_styles[i];
if (thisStyle == (XIMPreeditNothing | XIMStatusNothing))
{
bestMatchStyle = thisStyle;
break;
}
}
XFree(styles);
if (!bestMatchStyle) {
Nan::ThrowError("Could not retrieve input styles.");
}
Window window;
int revert_to;
XGetInputFocus(xDisplay, &window, &revert_to);
if (!window) {
Nan::ThrowError("Could not find foreground window.");
}
xInputContext = XCreateIC(
xInputMethod, XNInputStyle, bestMatchStyle, XNClientWindow, window,
XNFocusWindow, window, NULL
);
if (!xInputContext) {
Nan::ThrowError("Could not create an input context.");
}
}
KeyboardLayoutManager::~KeyboardLayoutManager() {
XDestroyIC(xInputContext);
XCloseDisplay(xDisplay);
delete callback;
};
void KeyboardLayoutManager::HandleKeyboardLayoutChanged() {
}
NAN_METHOD(KeyboardLayoutManager::GetCurrentKeyboardLayout) {
Nan::HandleScope scope;
KeyboardLayoutManager* manager = Nan::ObjectWrap::Unwrap<KeyboardLayoutManager>(info.Holder());
v8::Handle<v8::Value> result;
XkbRF_VarDefsRec vdr;
char *tmp = NULL;
if (XkbRF_GetNamesProp(manager->xDisplay, &tmp, &vdr) && vdr.layout && vdr.variant) {
result = Nan::New<v8::String>(std::string(vdr.layout) + "," + std::string(vdr.variant)).ToLocalChecked();
} else {
result = Nan::Null();
}
info.GetReturnValue().Set(result);
return;
}
NAN_METHOD(KeyboardLayoutManager::GetInstalledKeyboardLanguages) {
Nan::HandleScope scope;
return;
}
struct KeycodeMapEntry {
uint xkbKeycode;
const char *dom3Code;
};
#define USB_KEYMAP_DECLARATION static const KeycodeMapEntry keyCodeMap[] =
#define USB_KEYMAP(usb, evdev, xkb, win, mac, code, id) {xkb, code}
#include "keycode_converter_data.inc"
v8::Local<v8::Value> CharacterForNativeCode(XIC xInputContext, XKeyEvent *keyEvent, uint xkbKeycode, uint state) {
keyEvent->keycode = xkbKeycode;
keyEvent->state = state;
wchar_t characters[2];
int count = XwcLookupString(xInputContext, keyEvent, characters, 2, NULL, NULL);
if (count > 0 && !std::iswcntrl(characters[0])) {
return Nan::New<v8::String>(reinterpret_cast<const uint16_t *>(characters), count).ToLocalChecked();
} else {
return Nan::Null();
}
}
NAN_METHOD(KeyboardLayoutManager::GetCurrentKeymap) {
v8::Handle<v8::Object> result = Nan::New<v8::Object>();
KeyboardLayoutManager* manager = Nan::ObjectWrap::Unwrap<KeyboardLayoutManager>(info.Holder());
v8::Local<v8::String> unmodifiedKey = Nan::New("unmodified").ToLocalChecked();
v8::Local<v8::String> withShiftKey = Nan::New("withShift").ToLocalChecked();
// Clear cached keymap
XMappingEvent eventMap = {MappingNotify, 0, false, manager->xDisplay, 0, MappingKeyboard, 0, 0};
XRefreshKeyboardMapping(&eventMap);
// Set up an event to reuse across CharacterForNativeCode calls
XEvent event;
memset(&event, 0, sizeof(XEvent));
XKeyEvent* keyEvent = &event.xkey;
keyEvent->display = manager->xDisplay;
keyEvent->type = KeyPress;
size_t keyCodeMapSize = sizeof(keyCodeMap) / sizeof(keyCodeMap[0]);
for (size_t i = 0; i < keyCodeMapSize; i++) {
const char *dom3Code = keyCodeMap[i].dom3Code;
uint xkbKeycode = keyCodeMap[i].xkbKeycode;
if (dom3Code && xkbKeycode > 0x0000) {
v8::Local<v8::String> dom3CodeKey = Nan::New(dom3Code).ToLocalChecked();
v8::Local<v8::Value> unmodified = CharacterForNativeCode(manager->xInputContext, keyEvent, xkbKeycode, 0);
v8::Local<v8::Value> withShift = CharacterForNativeCode(manager->xInputContext, keyEvent, xkbKeycode, ShiftMask);
if (unmodified->IsString() || withShift->IsString()) {
v8::Local<v8::Object> entry = Nan::New<v8::Object>();
entry->Set(unmodifiedKey, unmodified);
entry->Set(withShiftKey, withShift);
result->Set(dom3CodeKey, entry);
}
}
}
info.GetReturnValue().Set(result);
}
<commit_msg>Add return statements when catching errors<commit_after>#include "keyboard-layout-manager.h"
#include <X11/XKBlib.h>
#include <X11/Xutil.h>
#include <X11/extensions/XKBrules.h>
#include <cwctype>
void KeyboardLayoutManager::Init(v8::Handle<v8::Object> exports, v8::Handle<v8::Object> module) {
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> newTemplate = Nan::New<v8::FunctionTemplate>(KeyboardLayoutManager::New);
newTemplate->SetClassName(Nan::New<v8::String>("KeyboardLayoutManager").ToLocalChecked());
newTemplate->InstanceTemplate()->SetInternalFieldCount(1);
v8::Local<v8::ObjectTemplate> proto = newTemplate->PrototypeTemplate();
Nan::SetMethod(proto, "getCurrentKeyboardLayout", KeyboardLayoutManager::GetCurrentKeyboardLayout);
Nan::SetMethod(proto, "getCurrentKeyboardLanguage", KeyboardLayoutManager::GetCurrentKeyboardLayout); // NB: Intentionally mapped to same stub
Nan::SetMethod(proto, "getInstalledKeyboardLanguages", KeyboardLayoutManager::GetInstalledKeyboardLanguages);
Nan::SetMethod(proto, "getCurrentKeymap", KeyboardLayoutManager::GetCurrentKeymap);
module->Set(Nan::New("exports").ToLocalChecked(), newTemplate->GetFunction());
}
NODE_MODULE(keyboard_layout_manager, KeyboardLayoutManager::Init)
NAN_METHOD(KeyboardLayoutManager::New) {
Nan::HandleScope scope;
v8::Local<v8::Function> callbackHandle = info[0].As<v8::Function>();
Nan::Callback *callback = new Nan::Callback(callbackHandle);
KeyboardLayoutManager *manager = new KeyboardLayoutManager(callback);
manager->Wrap(info.This());
return;
}
KeyboardLayoutManager::KeyboardLayoutManager(Nan::Callback *callback) : callback(callback) {
xDisplay = XOpenDisplay("");
if (!xDisplay) {
Nan::ThrowError("Could not connect to X display.");
return;
}
XIM xInputMethod = XOpenIM(xDisplay, 0, 0, 0);
if (!xInputMethod) {
Nan::ThrowError("Could not create an input method.");
return;
}
XIMStyles* styles = 0;
if (XGetIMValues(xInputMethod, XNQueryInputStyle, &styles, NULL) || !styles) {
Nan::ThrowError("Could not retrieve input styles.");
return;
}
XIMStyle bestMatchStyle = 0;
for (int i = 0; i < styles->count_styles; i++) {
XIMStyle thisStyle = styles->supported_styles[i];
if (thisStyle == (XIMPreeditNothing | XIMStatusNothing))
{
bestMatchStyle = thisStyle;
break;
}
}
XFree(styles);
if (!bestMatchStyle) {
Nan::ThrowError("Could not retrieve input styles.");
return;
}
Window window;
int revert_to;
XGetInputFocus(xDisplay, &window, &revert_to);
if (!window) {
Nan::ThrowError("Could not find foreground window.");
return;
}
xInputContext = XCreateIC(
xInputMethod, XNInputStyle, bestMatchStyle, XNClientWindow, window,
XNFocusWindow, window, NULL
);
if (!xInputContext) {
Nan::ThrowError("Could not create an input context.");
return;
}
}
KeyboardLayoutManager::~KeyboardLayoutManager() {
XDestroyIC(xInputContext);
XCloseDisplay(xDisplay);
delete callback;
};
void KeyboardLayoutManager::HandleKeyboardLayoutChanged() {
}
NAN_METHOD(KeyboardLayoutManager::GetCurrentKeyboardLayout) {
Nan::HandleScope scope;
KeyboardLayoutManager* manager = Nan::ObjectWrap::Unwrap<KeyboardLayoutManager>(info.Holder());
v8::Handle<v8::Value> result;
XkbRF_VarDefsRec vdr;
char *tmp = NULL;
if (XkbRF_GetNamesProp(manager->xDisplay, &tmp, &vdr) && vdr.layout && vdr.variant) {
result = Nan::New<v8::String>(std::string(vdr.layout) + "," + std::string(vdr.variant)).ToLocalChecked();
} else {
result = Nan::Null();
}
info.GetReturnValue().Set(result);
return;
}
NAN_METHOD(KeyboardLayoutManager::GetInstalledKeyboardLanguages) {
Nan::HandleScope scope;
return;
}
struct KeycodeMapEntry {
uint xkbKeycode;
const char *dom3Code;
};
#define USB_KEYMAP_DECLARATION static const KeycodeMapEntry keyCodeMap[] =
#define USB_KEYMAP(usb, evdev, xkb, win, mac, code, id) {xkb, code}
#include "keycode_converter_data.inc"
v8::Local<v8::Value> CharacterForNativeCode(XIC xInputContext, XKeyEvent *keyEvent, uint xkbKeycode, uint state) {
keyEvent->keycode = xkbKeycode;
keyEvent->state = state;
wchar_t characters[2];
int count = XwcLookupString(xInputContext, keyEvent, characters, 2, NULL, NULL);
if (count > 0 && !std::iswcntrl(characters[0])) {
return Nan::New<v8::String>(reinterpret_cast<const uint16_t *>(characters), count).ToLocalChecked();
} else {
return Nan::Null();
}
}
NAN_METHOD(KeyboardLayoutManager::GetCurrentKeymap) {
v8::Handle<v8::Object> result = Nan::New<v8::Object>();
KeyboardLayoutManager* manager = Nan::ObjectWrap::Unwrap<KeyboardLayoutManager>(info.Holder());
v8::Local<v8::String> unmodifiedKey = Nan::New("unmodified").ToLocalChecked();
v8::Local<v8::String> withShiftKey = Nan::New("withShift").ToLocalChecked();
// Clear cached keymap
XMappingEvent eventMap = {MappingNotify, 0, false, manager->xDisplay, 0, MappingKeyboard, 0, 0};
XRefreshKeyboardMapping(&eventMap);
// Set up an event to reuse across CharacterForNativeCode calls
XEvent event;
memset(&event, 0, sizeof(XEvent));
XKeyEvent* keyEvent = &event.xkey;
keyEvent->display = manager->xDisplay;
keyEvent->type = KeyPress;
size_t keyCodeMapSize = sizeof(keyCodeMap) / sizeof(keyCodeMap[0]);
for (size_t i = 0; i < keyCodeMapSize; i++) {
const char *dom3Code = keyCodeMap[i].dom3Code;
uint xkbKeycode = keyCodeMap[i].xkbKeycode;
if (dom3Code && xkbKeycode > 0x0000) {
v8::Local<v8::String> dom3CodeKey = Nan::New(dom3Code).ToLocalChecked();
v8::Local<v8::Value> unmodified = CharacterForNativeCode(manager->xInputContext, keyEvent, xkbKeycode, 0);
v8::Local<v8::Value> withShift = CharacterForNativeCode(manager->xInputContext, keyEvent, xkbKeycode, ShiftMask);
if (unmodified->IsString() || withShift->IsString()) {
v8::Local<v8::Object> entry = Nan::New<v8::Object>();
entry->Set(unmodifiedKey, unmodified);
entry->Set(withShiftKey, withShift);
result->Set(dom3CodeKey, entry);
}
}
}
info.GetReturnValue().Set(result);
}
<|endoftext|> |
<commit_before>#include "graphicitemblock.h"
#include <QBrush>
#include <QColor>
#include <QFontMetrics>
#include <QDebug>
#include <QAction>
#include <parameterint.h>
#include <input.h>
#include <output.h>
libblockdia::GraphicItemBlock::GraphicItemBlock(Block *block, QGraphicsItem *parent) : QGraphicsItem(parent)
{
this->block = block;
this->isMouseHovered = false;
this->giBlockHead = Q_NULLPTR;
this->updateData();
this->setAcceptHoverEvents(true);
}
QRectF libblockdia::GraphicItemBlock::boundingRect() const
{
if (this->isMouseHovered) {
return this->currentBoundingRectHighlighted;
} else {
return this->currentBoundingRect;
}
}
void libblockdia::GraphicItemBlock::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
Q_UNUSED(painter);
// paint highlight border if hovered
if (this->isMouseHovered) {
painter->fillRect(this->currentBoundingRectHighlighted, QColor("#f00"));
}
// // background 0-cross
// QRectF r = this->childrenBoundingRect();
// r.setX(r.x() - 50);
// r.setY(r.y() - 50);
// r.setWidth(r.width() + 100);
// r.setHeight(r.height() + 100);
// painter->setPen(Qt::red);
// painter->drawRect(r);
// painter->drawLine(-200, 0, 200, 0);
// painter->drawLine(0, -200, 0, 200);
}
void libblockdia::GraphicItemBlock::updateData()
{
this->prepareGeometryChange();
qreal widthMaximum = 0;
qreal widthInputs = 0;
qreal widthOutputs = 0;
qreal heightMaximum = 0;
// get block information
QList<Input *> blockInputList = this->block->getInputs();
QList<Output *> blockOutputsList = this->block->getOutputs();
QList<Parameter *> blockParameters = this->block->getParameters();
int countPublicParams = 0;
int countPrivateParams = 0;
for (int i=0; i < blockParameters.size(); ++i) {
if (blockParameters.at(i)->isPublic()) {
++countPublicParams;
} else {
++countPrivateParams;
}
}
// ------------------------------------------------------------------------
// Create Sub GraphicItems
// ------------------------------------------------------------------------
// create new header
if (this->giBlockHead == Q_NULLPTR) {
this->giBlockHead = new GraphicItemBlockHeader(this->block, this);
}
// update header
this->giBlockHead->updateData();
if (this->giBlockHead->actualNeededWidth() > widthMaximum) widthMaximum = this->giBlockHead->actualNeededWidth();
this->giBlockHead->setY(heightMaximum + this->giBlockHead->boundingRect().height() / 2.0);
heightMaximum += this->giBlockHead->boundingRect().height();
// resize public parameters list
while (this->giParamsPublic.size() > countPublicParams) delete this->giParamsPublic.takeLast();
while (this->giParamsPublic.size() < countPublicParams) this->giParamsPublic.append(new GraphicItemParameter(this->block, 0, this));
// update public parameters
int idxParamPub = 0;
for (int i=0; i < blockParameters.size(); ++i) {
if (blockParameters.at(i)->isPublic()) {
GraphicItemParameter *giParam = this->giParamsPublic.at(idxParamPub);
giParam->updateData(i);
if (giParam->actualNeededWidth() > widthMaximum) widthMaximum = giParam->actualNeededWidth();
giParam->setY(heightMaximum + giParam->boundingRect().height()/2.0);
heightMaximum += giParam->boundingRect().height();
// update maximum width
if (giParam->actualNeededWidth() > widthMaximum) widthMaximum = giParam->actualNeededWidth();
++idxParamPub;
}
}
// resize IO list
while (this->giInOuts.size() > blockInputList.size() || this->giInOuts.size() > blockOutputsList.size()) {
QPair<GraphicItemInput *, GraphicItemOutput *> p = this->giInOuts.takeLast();
delete p.first;
delete p.second;
}
while (this->giInOuts.size() < blockInputList.size() || this->giInOuts.size() < blockOutputsList.size()) {
QPair<GraphicItemInput *, GraphicItemOutput *> p;
p.first = new GraphicItemInput(this->block, -1, this);
p.second = new GraphicItemOutput(this->block, -1, this);
this->giInOuts.append(p);
}
// update inputs/output list
for (int i = 0; i < this->giInOuts.size(); ++i) {
QPair<GraphicItemInput *, GraphicItemOutput *> p = this->giInOuts.at(i);
// create new input
if (i <= blockInputList.size()) {
p.first->updateData(i);
} else {
p.first->updateData();
}
// create new output
if (i < blockOutputsList.size()) {
p.second->updateData(i);
} else {
p.second->updateData();
}
// calculate width
if (p.first->actualNeededWidth() > widthInputs) widthInputs = p.first->actualNeededWidth();
if (p.second->actualNeededWidth() > widthOutputs) widthOutputs = p.second->actualNeededWidth();
qreal w = widthInputs + widthOutputs;
if (w > widthMaximum) widthMaximum = w;
// calculate height
p.first->setY(heightMaximum + p.first->boundingRect().height() / 2.0);
p.second->setY(heightMaximum + p.second->boundingRect().height() / 2.0);
heightMaximum += (p.first->boundingRect().height() > p.second->boundingRect().height()) ? p.first->boundingRect().height() : p.second->boundingRect().height();
}
// resize private parameters list
while (this->giParamsPrivate.size() > countPrivateParams) delete this->giParamsPrivate.takeLast();
while (this->giParamsPrivate.size() < countPrivateParams) this->giParamsPrivate.append(new GraphicItemParameter(this->block, -1, this));
// update private parameters
int idxParamPriv = 0;
for (int i=0; i < blockParameters.size(); ++i) {
if (!blockParameters.at(i)->isPublic()) {
GraphicItemParameter *giParam = this->giParamsPrivate.at(idxParamPriv);
giParam->updateData(i);
if (giParam->actualNeededWidth() > widthMaximum) widthMaximum = giParam->actualNeededWidth();
giParam->setY(heightMaximum + giParam->boundingRect().height()/2.0);
heightMaximum += giParam->boundingRect().height();
// update maximum width
if (giParam->actualNeededWidth() > widthMaximum) widthMaximum = giParam->actualNeededWidth();
++idxParamPriv;
}
}
// ------------------------------------------------------------------------
// Update Positons
// ------------------------------------------------------------------------
// header
this->giBlockHead->setMinWidth(widthMaximum);
this->giBlockHead->setX(0);
this->giBlockHead->moveBy(0, - heightMaximum/2.0);
// private parameters
for (int i=0; i < this->giParamsPrivate.size(); ++i) {
GraphicItemParameter *giParam = this->giParamsPrivate.at(i);
giParam->setMinWidth(widthMaximum);
giParam->moveBy(0, - heightMaximum/2.0);
}
// stretch i/o widths
if ((widthInputs + widthOutputs) < widthMaximum) {
int w = widthMaximum - widthInputs - widthOutputs;
widthInputs += w/2.0;
widthOutputs += w/2.0;
}
// In-/Outputs
for (int i=0; i < this->giInOuts.size(); ++i) {
QPair<GraphicItemInput *, GraphicItemOutput *> p = this->giInOuts.at(i);
// update input
p.first->setMinWidth(widthInputs);
p.first->moveBy(0, - heightMaximum/2.0);
p.first->setX(- widthMaximum / 2.0 + p.first->boundingRect().width() / 2.0);
// update output
p.second->setMinWidth(widthOutputs);
p.second->moveBy(0, - heightMaximum/2.0);
p.second->setX(widthMaximum / 2.0 - p.second->boundingRect().width() / 2.0);
}
// public parameters
for (int i=0; i < this->giParamsPublic.size(); ++i) {
GraphicItemParameter *giParam = this->giParamsPublic.at(i);
giParam->setMinWidth(widthMaximum);
giParam->moveBy(0, - heightMaximum/2.0);
}
// calculate new bounding rect
this->currentBoundingRect = QRectF(- widthMaximum / 2.0, - heightMaximum / 2.0, widthMaximum, heightMaximum);
this->currentBoundingRectHighlighted = this->currentBoundingRect;
this->currentBoundingRectHighlighted.adjust(-2, -2, 2, 2);
}
void libblockdia::GraphicItemBlock::hoverEnterEvent(QGraphicsSceneHoverEvent *e)
{
Q_UNUSED(e);
this->prepareGeometryChange();
this->isMouseHovered = true;
}
void libblockdia::GraphicItemBlock::hoverLeaveEvent(QGraphicsSceneHoverEvent *e)
{
Q_UNUSED(e);
this->prepareGeometryChange();
this->isMouseHovered = false;
}
void libblockdia::GraphicItemBlock::contextMenuEvent(QGraphicsSceneContextMenuEvent *e)
{
Parameter *param = Q_NULLPTR;
Input *input = Q_NULLPTR;
Output *output = Q_NULLPTR;
// ------------------------------------------------------------------------
// Find Child Item Objects
// ------------------------------------------------------------------------
// check if parameter is clicked
if (param == Q_NULLPTR && input == Q_NULLPTR && output == Q_NULLPTR) {
for (int i=0; i < this->giParamsPrivate.size(); ++i) {
GraphicItemParameter *item = this->giParamsPrivate.at(i);
if (item->isMouseHovered()) {
int idx = item->parameterIndex();
if (idx >= 0) {
QList<Parameter *> listParams = this->block->getParameters();
if (idx < listParams.size()) {
param = listParams.at(idx);
break;
}
}
}
}
}
if (param == Q_NULLPTR && input == Q_NULLPTR && output == Q_NULLPTR) {
for (int i=0; i < this->giParamsPublic.size(); ++i) {
GraphicItemParameter *item = this->giParamsPublic.at(i);
if (item->isMouseHovered()) {
int idx = item->parameterIndex();
if (idx >= 0) {
QList<Parameter *> listParams = this->block->getParameters();
if (idx < listParams.size()) {
param = listParams.at(idx);
break;
}
}
}
}
}
// check if input is clicked
if (param == Q_NULLPTR && input == Q_NULLPTR && output == Q_NULLPTR) {
for (int i=0; i < this->giInOuts.size(); ++i) {
QPair<GraphicItemInput *, GraphicItemOutput *> p = this->giInOuts.at(i);
if (p.first->isMouseHovered()) {
int idx = p.first->inputIndex();
if (idx >= 0) {
QList<Input *> l = this->block->getInputs();
if (idx < l.size()) {
input = l.at(idx);
break;
}
}
} else if (p.second->isMouseHovered()) {
int idx = p.second->outputIndex();
if (idx >= 0) {
QList<Output *> l = this->block->getOutputs();
if (idx < l.size()) {
output = l.at(idx);
break;
}
}
}
}
}
// ------------------------------------------------------------------------
// Create Menu
// ------------------------------------------------------------------------
// create menu - parameter add
QMenu menuAddParam("Add Parameter");
QAction *actionParameterAddInt = menuAddParam.addAction("Integer Parameter");
// create menu - main
QMenu menu;
QAction *actionEditTypeName = menu.addAction("Edit Type Name");
QAction *actionEditTypeId = menu.addAction("Edit Type ID");
// add inputs/outputs/params
menu.addSeparator();
QAction *actionAddInput = menu.addAction("Add Input");
QAction *actionAddOutput = menu.addAction("Add Output");
menu.addMenu(&menuAddParam);
// parameter menu
QAction *actionParameterDelete = Q_NULLPTR;
QAction *actionParameterEdit = Q_NULLPTR;
if (param != Q_NULLPTR) {
QMenu *menuSub = new QMenu(param->name());
menu.addSeparator();
menu.addMenu(menuSub);
actionParameterDelete = menuSub->addAction("Delete Parameter");
actionParameterEdit = menuSub->addAction("Edit Parameter");
}
// input menu
QAction *actionInputDelete = Q_NULLPTR;
QAction *actionInputEdit = Q_NULLPTR;
if (input != Q_NULLPTR) {
QMenu *menuSub = new QMenu(input->name());
menu.addSeparator();
menu.addMenu(menuSub);
actionInputDelete = menuSub->addAction("Delete Input");
actionInputEdit = menuSub->addAction("Edit Input");
}
// output menu
QAction *actionOutputDelete = Q_NULLPTR;
QAction *actionOutputEdit = Q_NULLPTR;
if (output != Q_NULLPTR) {
QMenu *menuSub = new QMenu(output->name());
menu.addSeparator();
menu.addMenu(menuSub);
actionOutputDelete = menuSub->addAction("Delete Output");
actionOutputEdit = menuSub->addAction("Edit Output");
}
// ------------------------------------------------------------------------
// Execute Menu
// ------------------------------------------------------------------------
// execute menu
QAction *action = menu.exec(e->screenPos());
// no action
if (action == Q_NULLPTR) {
// do nothing
}
// add pramter
else if (action == actionParameterAddInt) {
new ParameterInt("new parameter", this->block);
}
// delete parameter
else if (action == actionParameterDelete) {
param->deleteLater();
}
// add input
else if (action == actionAddInput) {
new Input("new input", this->block);
}
// delete input
else if (action == actionInputDelete) {
input->deleteLater();
}
// add output
else if (action == actionAddOutput) {
new Output("new output", this->block);
}
// delete output
else if (action == actionOutputDelete) {
output->deleteLater();
}
}
<commit_msg>parameter public/private edit<commit_after>#include "graphicitemblock.h"
#include <QBrush>
#include <QColor>
#include <QFontMetrics>
#include <QDebug>
#include <QAction>
#include <parameterint.h>
#include <input.h>
#include <output.h>
libblockdia::GraphicItemBlock::GraphicItemBlock(Block *block, QGraphicsItem *parent) : QGraphicsItem(parent)
{
this->block = block;
this->isMouseHovered = false;
this->giBlockHead = Q_NULLPTR;
this->updateData();
this->setAcceptHoverEvents(true);
}
QRectF libblockdia::GraphicItemBlock::boundingRect() const
{
if (this->isMouseHovered) {
return this->currentBoundingRectHighlighted;
} else {
return this->currentBoundingRect;
}
}
void libblockdia::GraphicItemBlock::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
Q_UNUSED(painter);
// paint highlight border if hovered
if (this->isMouseHovered) {
painter->fillRect(this->currentBoundingRectHighlighted, QColor("#f00"));
}
// // background 0-cross
// QRectF r = this->childrenBoundingRect();
// r.setX(r.x() - 50);
// r.setY(r.y() - 50);
// r.setWidth(r.width() + 100);
// r.setHeight(r.height() + 100);
// painter->setPen(Qt::red);
// painter->drawRect(r);
// painter->drawLine(-200, 0, 200, 0);
// painter->drawLine(0, -200, 0, 200);
}
void libblockdia::GraphicItemBlock::updateData()
{
this->prepareGeometryChange();
qreal widthMaximum = 0;
qreal widthInputs = 0;
qreal widthOutputs = 0;
qreal heightMaximum = 0;
// get block information
QList<Input *> blockInputList = this->block->getInputs();
QList<Output *> blockOutputsList = this->block->getOutputs();
QList<Parameter *> blockParameters = this->block->getParameters();
int countPublicParams = 0;
int countPrivateParams = 0;
for (int i=0; i < blockParameters.size(); ++i) {
if (blockParameters.at(i)->isPublic()) {
++countPublicParams;
} else {
++countPrivateParams;
}
}
// ------------------------------------------------------------------------
// Create Sub GraphicItems
// ------------------------------------------------------------------------
// create new header
if (this->giBlockHead == Q_NULLPTR) {
this->giBlockHead = new GraphicItemBlockHeader(this->block, this);
}
// update header
this->giBlockHead->updateData();
if (this->giBlockHead->actualNeededWidth() > widthMaximum) widthMaximum = this->giBlockHead->actualNeededWidth();
this->giBlockHead->setY(heightMaximum + this->giBlockHead->boundingRect().height() / 2.0);
heightMaximum += this->giBlockHead->boundingRect().height();
// resize public parameters list
while (this->giParamsPublic.size() > countPublicParams) delete this->giParamsPublic.takeLast();
while (this->giParamsPublic.size() < countPublicParams) this->giParamsPublic.append(new GraphicItemParameter(this->block, 0, this));
// update public parameters
int idxParamPub = 0;
for (int i=0; i < blockParameters.size(); ++i) {
if (blockParameters.at(i)->isPublic()) {
GraphicItemParameter *giParam = this->giParamsPublic.at(idxParamPub);
giParam->updateData(i);
if (giParam->actualNeededWidth() > widthMaximum) widthMaximum = giParam->actualNeededWidth();
giParam->setY(heightMaximum + giParam->boundingRect().height()/2.0);
heightMaximum += giParam->boundingRect().height();
// update maximum width
if (giParam->actualNeededWidth() > widthMaximum) widthMaximum = giParam->actualNeededWidth();
++idxParamPub;
}
}
// resize IO list
while (this->giInOuts.size() > blockInputList.size() || this->giInOuts.size() > blockOutputsList.size()) {
QPair<GraphicItemInput *, GraphicItemOutput *> p = this->giInOuts.takeLast();
delete p.first;
delete p.second;
}
while (this->giInOuts.size() < blockInputList.size() || this->giInOuts.size() < blockOutputsList.size()) {
QPair<GraphicItemInput *, GraphicItemOutput *> p;
p.first = new GraphicItemInput(this->block, -1, this);
p.second = new GraphicItemOutput(this->block, -1, this);
this->giInOuts.append(p);
}
// update inputs/output list
for (int i = 0; i < this->giInOuts.size(); ++i) {
QPair<GraphicItemInput *, GraphicItemOutput *> p = this->giInOuts.at(i);
// create new input
if (i <= blockInputList.size()) {
p.first->updateData(i);
} else {
p.first->updateData();
}
// create new output
if (i < blockOutputsList.size()) {
p.second->updateData(i);
} else {
p.second->updateData();
}
// calculate width
if (p.first->actualNeededWidth() > widthInputs) widthInputs = p.first->actualNeededWidth();
if (p.second->actualNeededWidth() > widthOutputs) widthOutputs = p.second->actualNeededWidth();
qreal w = widthInputs + widthOutputs;
if (w > widthMaximum) widthMaximum = w;
// calculate height
p.first->setY(heightMaximum + p.first->boundingRect().height() / 2.0);
p.second->setY(heightMaximum + p.second->boundingRect().height() / 2.0);
heightMaximum += (p.first->boundingRect().height() > p.second->boundingRect().height()) ? p.first->boundingRect().height() : p.second->boundingRect().height();
}
// resize private parameters list
while (this->giParamsPrivate.size() > countPrivateParams) delete this->giParamsPrivate.takeLast();
while (this->giParamsPrivate.size() < countPrivateParams) this->giParamsPrivate.append(new GraphicItemParameter(this->block, -1, this));
// update private parameters
int idxParamPriv = 0;
for (int i=0; i < blockParameters.size(); ++i) {
if (!blockParameters.at(i)->isPublic()) {
GraphicItemParameter *giParam = this->giParamsPrivate.at(idxParamPriv);
giParam->updateData(i);
if (giParam->actualNeededWidth() > widthMaximum) widthMaximum = giParam->actualNeededWidth();
giParam->setY(heightMaximum + giParam->boundingRect().height()/2.0);
heightMaximum += giParam->boundingRect().height();
// update maximum width
if (giParam->actualNeededWidth() > widthMaximum) widthMaximum = giParam->actualNeededWidth();
++idxParamPriv;
}
}
// ------------------------------------------------------------------------
// Update Positons
// ------------------------------------------------------------------------
// header
this->giBlockHead->setMinWidth(widthMaximum);
this->giBlockHead->setX(0);
this->giBlockHead->moveBy(0, - heightMaximum/2.0);
// private parameters
for (int i=0; i < this->giParamsPrivate.size(); ++i) {
GraphicItemParameter *giParam = this->giParamsPrivate.at(i);
giParam->setMinWidth(widthMaximum);
giParam->moveBy(0, - heightMaximum/2.0);
}
// stretch i/o widths
if ((widthInputs + widthOutputs) < widthMaximum) {
int w = widthMaximum - widthInputs - widthOutputs;
widthInputs += w/2.0;
widthOutputs += w/2.0;
}
// In-/Outputs
for (int i=0; i < this->giInOuts.size(); ++i) {
QPair<GraphicItemInput *, GraphicItemOutput *> p = this->giInOuts.at(i);
// update input
p.first->setMinWidth(widthInputs);
p.first->moveBy(0, - heightMaximum/2.0);
p.first->setX(- widthMaximum / 2.0 + p.first->boundingRect().width() / 2.0);
// update output
p.second->setMinWidth(widthOutputs);
p.second->moveBy(0, - heightMaximum/2.0);
p.second->setX(widthMaximum / 2.0 - p.second->boundingRect().width() / 2.0);
}
// public parameters
for (int i=0; i < this->giParamsPublic.size(); ++i) {
GraphicItemParameter *giParam = this->giParamsPublic.at(i);
giParam->setMinWidth(widthMaximum);
giParam->moveBy(0, - heightMaximum/2.0);
}
// calculate new bounding rect
this->currentBoundingRect = QRectF(- widthMaximum / 2.0, - heightMaximum / 2.0, widthMaximum, heightMaximum);
this->currentBoundingRectHighlighted = this->currentBoundingRect;
this->currentBoundingRectHighlighted.adjust(-2, -2, 2, 2);
}
void libblockdia::GraphicItemBlock::hoverEnterEvent(QGraphicsSceneHoverEvent *e)
{
Q_UNUSED(e);
this->prepareGeometryChange();
this->isMouseHovered = true;
}
void libblockdia::GraphicItemBlock::hoverLeaveEvent(QGraphicsSceneHoverEvent *e)
{
Q_UNUSED(e);
this->prepareGeometryChange();
this->isMouseHovered = false;
}
void libblockdia::GraphicItemBlock::contextMenuEvent(QGraphicsSceneContextMenuEvent *e)
{
Parameter *param = Q_NULLPTR;
Input *input = Q_NULLPTR;
Output *output = Q_NULLPTR;
// ------------------------------------------------------------------------
// Find Child Item Objects
// ------------------------------------------------------------------------
// check if parameter is clicked
if (param == Q_NULLPTR && input == Q_NULLPTR && output == Q_NULLPTR) {
for (int i=0; i < this->giParamsPrivate.size(); ++i) {
GraphicItemParameter *item = this->giParamsPrivate.at(i);
if (item->isMouseHovered()) {
int idx = item->parameterIndex();
if (idx >= 0) {
QList<Parameter *> listParams = this->block->getParameters();
if (idx < listParams.size()) {
param = listParams.at(idx);
break;
}
}
}
}
}
if (param == Q_NULLPTR && input == Q_NULLPTR && output == Q_NULLPTR) {
for (int i=0; i < this->giParamsPublic.size(); ++i) {
GraphicItemParameter *item = this->giParamsPublic.at(i);
if (item->isMouseHovered()) {
int idx = item->parameterIndex();
if (idx >= 0) {
QList<Parameter *> listParams = this->block->getParameters();
if (idx < listParams.size()) {
param = listParams.at(idx);
break;
}
}
}
}
}
// check if input is clicked
if (param == Q_NULLPTR && input == Q_NULLPTR && output == Q_NULLPTR) {
for (int i=0; i < this->giInOuts.size(); ++i) {
QPair<GraphicItemInput *, GraphicItemOutput *> p = this->giInOuts.at(i);
if (p.first->isMouseHovered()) {
int idx = p.first->inputIndex();
if (idx >= 0) {
QList<Input *> l = this->block->getInputs();
if (idx < l.size()) {
input = l.at(idx);
break;
}
}
} else if (p.second->isMouseHovered()) {
int idx = p.second->outputIndex();
if (idx >= 0) {
QList<Output *> l = this->block->getOutputs();
if (idx < l.size()) {
output = l.at(idx);
break;
}
}
}
}
}
// ------------------------------------------------------------------------
// Create Menu
// ------------------------------------------------------------------------
// create menu - parameter add
QMenu menuAddParam("Add Parameter");
QAction *actionParameterAddInt = menuAddParam.addAction("Integer Parameter");
// create menu - main
QMenu menu;
QAction *actionEditTypeName = menu.addAction("Edit Type Name");
QAction *actionEditTypeId = menu.addAction("Edit Type ID");
// add inputs/outputs/params
menu.addSeparator();
QAction *actionAddInput = menu.addAction("Add Input");
QAction *actionAddOutput = menu.addAction("Add Output");
menu.addMenu(&menuAddParam);
// parameter menu
QAction *actionParameterDelete = Q_NULLPTR;
QAction *actionParameterEdit = Q_NULLPTR;
QAction *actionParameterPublic = Q_NULLPTR;
QAction *actionParameterPrivate = Q_NULLPTR;
if (param != Q_NULLPTR) {
QMenu *menuSub = new QMenu(param->name());
menu.addSeparator();
menu.addMenu(menuSub);
if (param->isPublic()) actionParameterPrivate = menuSub->addAction("Set Private Parameter");
else actionParameterPublic = menuSub->addAction("Set Public Paramerer");
actionParameterEdit = menuSub->addAction("Edit Parameter");
actionParameterDelete = menuSub->addAction("Delete Parameter");
}
// input menu
QAction *actionInputDelete = Q_NULLPTR;
QAction *actionInputEdit = Q_NULLPTR;
if (input != Q_NULLPTR) {
QMenu *menuSub = new QMenu(input->name());
menu.addSeparator();
menu.addMenu(menuSub);
actionInputEdit = menuSub->addAction("Edit Input");
actionInputDelete = menuSub->addAction("Delete Input");
}
// output menu
QAction *actionOutputDelete = Q_NULLPTR;
QAction *actionOutputEdit = Q_NULLPTR;
if (output != Q_NULLPTR) {
QMenu *menuSub = new QMenu(output->name());
menu.addSeparator();
menu.addMenu(menuSub);
actionOutputEdit = menuSub->addAction("Edit Output");
actionOutputDelete = menuSub->addAction("Delete Output");
}
// ------------------------------------------------------------------------
// Execute Menu
// ------------------------------------------------------------------------
// execute menu
QAction *action = menu.exec(e->screenPos());
// no action
if (action == Q_NULLPTR) {
// do nothing
}
// add pramter
else if (action == actionParameterAddInt) {
new ParameterInt("new parameter", this->block);
}
// delete parameter
else if (action == actionParameterDelete) {
param->deleteLater();
}
// set parameter private
else if (action == actionParameterPrivate) {
param->setPublic(false);
}
// set parameter public
else if (action == actionParameterPublic) {
param->setPublic(true);
}
// add input
else if (action == actionAddInput) {
new Input("new input", this->block);
}
// delete input
else if (action == actionInputDelete) {
input->deleteLater();
}
// add output
else if (action == actionAddOutput) {
new Output("new output", this->block);
}
// delete output
else if (action == actionOutputDelete) {
output->deleteLater();
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "qmljsscopebuilder.h"
#include "qmljsbind.h"
#include "qmljsinterpreter.h"
#include "qmljsevaluate.h"
#include "parser/qmljsast_p.h"
using namespace QmlJS;
using namespace QmlJS::Interpreter;
using namespace QmlJS::AST;
ScopeBuilder::ScopeBuilder(Context *context, Document::Ptr doc, const Snapshot &snapshot)
: _doc(doc)
, _snapshot(snapshot)
, _context(context)
{
initializeScopeChain();
}
ScopeBuilder::~ScopeBuilder()
{
}
void ScopeBuilder::push(AST::Node *node)
{
_nodes += node;
// QML scope object
Node *qmlObject = cast<UiObjectDefinition *>(node);
if (! qmlObject)
qmlObject = cast<UiObjectBinding *>(node);
if (qmlObject)
setQmlScopeObject(qmlObject);
// JS scopes
if (FunctionDeclaration *fun = cast<FunctionDeclaration *>(node)) {
ObjectValue *functionScope = _doc->bind()->findFunctionScope(fun);
if (functionScope)
_context->scopeChain().jsScopes += functionScope;
}
_context->scopeChain().update();
}
void ScopeBuilder::push(const QList<AST::Node *> &nodes)
{
foreach (Node *node, nodes)
push(node);
}
void ScopeBuilder::pop()
{
Node *toRemove = _nodes.last();
_nodes.removeLast();
// JS scopes
if (cast<FunctionDeclaration *>(toRemove))
_context->scopeChain().jsScopes.removeLast();
// QML scope object
if (! _nodes.isEmpty()
&& (cast<UiObjectDefinition *>(toRemove) || cast<UiObjectBinding *>(toRemove)))
setQmlScopeObject(_nodes.last());
_context->scopeChain().update();
}
void ScopeBuilder::initializeScopeChain()
{
ScopeChain &scopeChain = _context->scopeChain();
scopeChain = ScopeChain(); // reset
Interpreter::Engine *engine = _context->engine();
// ### TODO: This object ought to contain the global namespace additions by QML.
scopeChain.globalScope = engine->globalObject();
if (! _doc) {
scopeChain.update();
return;
}
Bind *bind = _doc->bind();
QHash<Document *, ScopeChain::QmlComponentChain *> componentScopes;
ScopeChain::QmlComponentChain *chain = new ScopeChain::QmlComponentChain;
scopeChain.qmlComponentScope = QSharedPointer<const ScopeChain::QmlComponentChain>(chain);
if (_doc->qmlProgram()) {
componentScopes.insert(_doc.data(), chain);
makeComponentChain(_doc, chain, &componentScopes);
if (const TypeEnvironment *typeEnvironment = _context->typeEnvironment(_doc.data()))
scopeChain.qmlTypes = typeEnvironment;
} else {
// add scope chains for all components that import this file
foreach (Document::Ptr otherDoc, _snapshot) {
foreach (const ImportInfo &import, otherDoc->bind()->imports()) {
if (import.type() == ImportInfo::FileImport && _doc->fileName() == import.name()) {
ScopeChain::QmlComponentChain *component = new ScopeChain::QmlComponentChain;
componentScopes.insert(otherDoc.data(), component);
chain->instantiatingComponents += component;
makeComponentChain(otherDoc, component, &componentScopes);
}
}
}
// ### TODO: Which type environment do scripts see?
if (bind->rootObjectValue())
scopeChain.jsScopes += bind->rootObjectValue();
}
scopeChain.update();
}
void ScopeBuilder::makeComponentChain(
Document::Ptr doc,
ScopeChain::QmlComponentChain *target,
QHash<Document *, ScopeChain::QmlComponentChain *> *components)
{
if (!doc->qmlProgram())
return;
Bind *bind = doc->bind();
// add scopes for all components instantiating this one
foreach (Document::Ptr otherDoc, _snapshot) {
if (otherDoc == doc)
continue;
if (otherDoc->bind()->usesQmlPrototype(bind->rootObjectValue(), _context)) {
if (components->contains(otherDoc.data())) {
// target->instantiatingComponents += components->value(otherDoc.data());
} else {
ScopeChain::QmlComponentChain *component = new ScopeChain::QmlComponentChain;
components->insert(otherDoc.data(), component);
target->instantiatingComponents += component;
makeComponentChain(otherDoc, component, components);
}
}
}
// build this component scope
target->document = doc;
}
void ScopeBuilder::setQmlScopeObject(Node *node)
{
ScopeChain &scopeChain = _context->scopeChain();
if (_doc->bind()->isGroupedPropertyBinding(node)) {
UiObjectDefinition *definition = cast<UiObjectDefinition *>(node);
if (!definition)
return;
const Value *v = scopeObjectLookup(definition->qualifiedTypeNameId);
if (!v)
return;
const ObjectValue *object = v->asObjectValue();
if (!object)
return;
scopeChain.qmlScopeObjects.clear();
scopeChain.qmlScopeObjects += object;
}
const ObjectValue *scopeObject = _doc->bind()->findQmlObject(node);
if (scopeObject) {
scopeChain.qmlScopeObjects.clear();
scopeChain.qmlScopeObjects += scopeObject;
} else {
return; // Probably syntax errors, where we're working with a "recovered" AST.
}
// check if the object has a Qt.ListElement or Qt.Connections ancestor
// ### allow only signal bindings for Connections
const ObjectValue *prototype = scopeObject->prototype(_context);
while (prototype) {
if (const QmlObjectValue *qmlMetaObject = dynamic_cast<const QmlObjectValue *>(prototype)) {
if ((qmlMetaObject->className() == QLatin1String("ListElement")
|| qmlMetaObject->className() == QLatin1String("Connections")
) && qmlMetaObject->packageName() == QLatin1String("Qt")) {
scopeChain.qmlScopeObjects.clear();
break;
}
}
prototype = prototype->prototype(_context);
}
// check if the object has a Qt.PropertyChanges ancestor
prototype = scopeObject->prototype(_context);
prototype = isPropertyChangesObject(_context, prototype);
// find the target script binding
if (prototype) {
UiObjectInitializer *initializer = 0;
if (UiObjectDefinition *definition = cast<UiObjectDefinition *>(node))
initializer = definition->initializer;
if (UiObjectBinding *binding = cast<UiObjectBinding *>(node))
initializer = binding->initializer;
if (initializer) {
for (UiObjectMemberList *m = initializer->members; m; m = m->next) {
if (UiScriptBinding *scriptBinding = cast<UiScriptBinding *>(m->member)) {
if (scriptBinding->qualifiedId && scriptBinding->qualifiedId->name
&& scriptBinding->qualifiedId->name->asString() == QLatin1String("target")
&& ! scriptBinding->qualifiedId->next) {
// ### make Evaluate understand statements.
if (ExpressionStatement *expStmt = cast<ExpressionStatement *>(scriptBinding->statement)) {
Evaluate evaluator(_context);
const Value *targetValue = evaluator(expStmt->expression);
if (const ObjectValue *target = value_cast<const ObjectValue *>(targetValue)) {
scopeChain.qmlScopeObjects.prepend(target);
} else {
scopeChain.qmlScopeObjects.clear();
}
}
}
}
}
}
}
}
const Value *ScopeBuilder::scopeObjectLookup(AST::UiQualifiedId *id)
{
// do a name lookup on the scope objects
const Value *result = 0;
foreach (const ObjectValue *scopeObject, _context->scopeChain().qmlScopeObjects) {
const ObjectValue *object = scopeObject;
for (UiQualifiedId *it = id; it; it = it->next) {
if (!it->name)
return 0;
result = object->property(it->name->asString(), _context);
if (!result)
break;
if (it->next) {
object = result->asObjectValue();
if (!object) {
result = 0;
break;
}
}
}
if (result)
break;
}
return result;
}
const ObjectValue *ScopeBuilder::isPropertyChangesObject(const Context *context,
const ObjectValue *object)
{
const ObjectValue *prototype = object;
while (prototype) {
if (const QmlObjectValue *qmlMetaObject = dynamic_cast<const QmlObjectValue *>(prototype)) {
if (qmlMetaObject->className() == QLatin1String("PropertyChanges")
&& (qmlMetaObject->packageName() == QLatin1String("Qt")
|| qmlMetaObject->packageName() == QLatin1String("QtQuick")))
return prototype;
}
prototype = prototype->prototype(context);
}
return 0;
}
<commit_msg>QmlJS: Fix false-positive errors reported for ListElement, Connections.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "qmljsscopebuilder.h"
#include "qmljsbind.h"
#include "qmljsinterpreter.h"
#include "qmljsevaluate.h"
#include "parser/qmljsast_p.h"
using namespace QmlJS;
using namespace QmlJS::Interpreter;
using namespace QmlJS::AST;
ScopeBuilder::ScopeBuilder(Context *context, Document::Ptr doc, const Snapshot &snapshot)
: _doc(doc)
, _snapshot(snapshot)
, _context(context)
{
initializeScopeChain();
}
ScopeBuilder::~ScopeBuilder()
{
}
void ScopeBuilder::push(AST::Node *node)
{
_nodes += node;
// QML scope object
Node *qmlObject = cast<UiObjectDefinition *>(node);
if (! qmlObject)
qmlObject = cast<UiObjectBinding *>(node);
if (qmlObject)
setQmlScopeObject(qmlObject);
// JS scopes
if (FunctionDeclaration *fun = cast<FunctionDeclaration *>(node)) {
ObjectValue *functionScope = _doc->bind()->findFunctionScope(fun);
if (functionScope)
_context->scopeChain().jsScopes += functionScope;
}
_context->scopeChain().update();
}
void ScopeBuilder::push(const QList<AST::Node *> &nodes)
{
foreach (Node *node, nodes)
push(node);
}
void ScopeBuilder::pop()
{
Node *toRemove = _nodes.last();
_nodes.removeLast();
// JS scopes
if (cast<FunctionDeclaration *>(toRemove))
_context->scopeChain().jsScopes.removeLast();
// QML scope object
if (! _nodes.isEmpty()
&& (cast<UiObjectDefinition *>(toRemove) || cast<UiObjectBinding *>(toRemove)))
setQmlScopeObject(_nodes.last());
_context->scopeChain().update();
}
void ScopeBuilder::initializeScopeChain()
{
ScopeChain &scopeChain = _context->scopeChain();
scopeChain = ScopeChain(); // reset
Interpreter::Engine *engine = _context->engine();
// ### TODO: This object ought to contain the global namespace additions by QML.
scopeChain.globalScope = engine->globalObject();
if (! _doc) {
scopeChain.update();
return;
}
Bind *bind = _doc->bind();
QHash<Document *, ScopeChain::QmlComponentChain *> componentScopes;
ScopeChain::QmlComponentChain *chain = new ScopeChain::QmlComponentChain;
scopeChain.qmlComponentScope = QSharedPointer<const ScopeChain::QmlComponentChain>(chain);
if (_doc->qmlProgram()) {
componentScopes.insert(_doc.data(), chain);
makeComponentChain(_doc, chain, &componentScopes);
if (const TypeEnvironment *typeEnvironment = _context->typeEnvironment(_doc.data()))
scopeChain.qmlTypes = typeEnvironment;
} else {
// add scope chains for all components that import this file
foreach (Document::Ptr otherDoc, _snapshot) {
foreach (const ImportInfo &import, otherDoc->bind()->imports()) {
if (import.type() == ImportInfo::FileImport && _doc->fileName() == import.name()) {
ScopeChain::QmlComponentChain *component = new ScopeChain::QmlComponentChain;
componentScopes.insert(otherDoc.data(), component);
chain->instantiatingComponents += component;
makeComponentChain(otherDoc, component, &componentScopes);
}
}
}
// ### TODO: Which type environment do scripts see?
if (bind->rootObjectValue())
scopeChain.jsScopes += bind->rootObjectValue();
}
scopeChain.update();
}
void ScopeBuilder::makeComponentChain(
Document::Ptr doc,
ScopeChain::QmlComponentChain *target,
QHash<Document *, ScopeChain::QmlComponentChain *> *components)
{
if (!doc->qmlProgram())
return;
Bind *bind = doc->bind();
// add scopes for all components instantiating this one
foreach (Document::Ptr otherDoc, _snapshot) {
if (otherDoc == doc)
continue;
if (otherDoc->bind()->usesQmlPrototype(bind->rootObjectValue(), _context)) {
if (components->contains(otherDoc.data())) {
// target->instantiatingComponents += components->value(otherDoc.data());
} else {
ScopeChain::QmlComponentChain *component = new ScopeChain::QmlComponentChain;
components->insert(otherDoc.data(), component);
target->instantiatingComponents += component;
makeComponentChain(otherDoc, component, components);
}
}
}
// build this component scope
target->document = doc;
}
void ScopeBuilder::setQmlScopeObject(Node *node)
{
ScopeChain &scopeChain = _context->scopeChain();
if (_doc->bind()->isGroupedPropertyBinding(node)) {
UiObjectDefinition *definition = cast<UiObjectDefinition *>(node);
if (!definition)
return;
const Value *v = scopeObjectLookup(definition->qualifiedTypeNameId);
if (!v)
return;
const ObjectValue *object = v->asObjectValue();
if (!object)
return;
scopeChain.qmlScopeObjects.clear();
scopeChain.qmlScopeObjects += object;
}
const ObjectValue *scopeObject = _doc->bind()->findQmlObject(node);
if (scopeObject) {
scopeChain.qmlScopeObjects.clear();
scopeChain.qmlScopeObjects += scopeObject;
} else {
return; // Probably syntax errors, where we're working with a "recovered" AST.
}
// check if the object has a Qt.ListElement or Qt.Connections ancestor
// ### allow only signal bindings for Connections
const ObjectValue *prototype = scopeObject->prototype(_context);
while (prototype) {
if (const QmlObjectValue *qmlMetaObject = dynamic_cast<const QmlObjectValue *>(prototype)) {
if ((qmlMetaObject->className() == QLatin1String("ListElement")
|| qmlMetaObject->className() == QLatin1String("Connections")
) && (qmlMetaObject->packageName() == QLatin1String("Qt")
|| qmlMetaObject->packageName() == QLatin1String("QtQuick"))) {
scopeChain.qmlScopeObjects.clear();
break;
}
}
prototype = prototype->prototype(_context);
}
// check if the object has a Qt.PropertyChanges ancestor
prototype = scopeObject->prototype(_context);
prototype = isPropertyChangesObject(_context, prototype);
// find the target script binding
if (prototype) {
UiObjectInitializer *initializer = 0;
if (UiObjectDefinition *definition = cast<UiObjectDefinition *>(node))
initializer = definition->initializer;
if (UiObjectBinding *binding = cast<UiObjectBinding *>(node))
initializer = binding->initializer;
if (initializer) {
for (UiObjectMemberList *m = initializer->members; m; m = m->next) {
if (UiScriptBinding *scriptBinding = cast<UiScriptBinding *>(m->member)) {
if (scriptBinding->qualifiedId && scriptBinding->qualifiedId->name
&& scriptBinding->qualifiedId->name->asString() == QLatin1String("target")
&& ! scriptBinding->qualifiedId->next) {
// ### make Evaluate understand statements.
if (ExpressionStatement *expStmt = cast<ExpressionStatement *>(scriptBinding->statement)) {
Evaluate evaluator(_context);
const Value *targetValue = evaluator(expStmt->expression);
if (const ObjectValue *target = value_cast<const ObjectValue *>(targetValue)) {
scopeChain.qmlScopeObjects.prepend(target);
} else {
scopeChain.qmlScopeObjects.clear();
}
}
}
}
}
}
}
}
const Value *ScopeBuilder::scopeObjectLookup(AST::UiQualifiedId *id)
{
// do a name lookup on the scope objects
const Value *result = 0;
foreach (const ObjectValue *scopeObject, _context->scopeChain().qmlScopeObjects) {
const ObjectValue *object = scopeObject;
for (UiQualifiedId *it = id; it; it = it->next) {
if (!it->name)
return 0;
result = object->property(it->name->asString(), _context);
if (!result)
break;
if (it->next) {
object = result->asObjectValue();
if (!object) {
result = 0;
break;
}
}
}
if (result)
break;
}
return result;
}
const ObjectValue *ScopeBuilder::isPropertyChangesObject(const Context *context,
const ObjectValue *object)
{
const ObjectValue *prototype = object;
while (prototype) {
if (const QmlObjectValue *qmlMetaObject = dynamic_cast<const QmlObjectValue *>(prototype)) {
if (qmlMetaObject->className() == QLatin1String("PropertyChanges")
&& (qmlMetaObject->packageName() == QLatin1String("Qt")
|| qmlMetaObject->packageName() == QLatin1String("QtQuick")))
return prototype;
}
prototype = prototype->prototype(context);
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 Pavel Kirienko <[email protected]>
*/
#include <uavcan/transport/frame.hpp>
#include <uavcan/transport/can_io.hpp>
#include <cassert>
namespace uavcan
{
/**
* Frame
*/
const uint8_t Frame::MaxIndexForService;
const uint8_t Frame::MaxIndexForMessage;
uint_fast8_t Frame::getMaxIndexForTransferType(const TransferType type)
{
if (type == TransferTypeMessageBroadcast ||
type == TransferTypeMessageUnicast)
{
return MaxIndexForMessage;
}
else if (type == TransferTypeServiceRequest ||
type == TransferTypeServiceResponse)
{
return MaxIndexForService;
}
else
{
UAVCAN_ASSERT(0);
return 0;
}
}
void Frame::setPriority(const TransferPriority priority)
{
UAVCAN_ASSERT(priority < NumTransferPriorities);
if (transfer_type_ == TransferTypeMessageBroadcast ||
transfer_type_ == TransferTypeMessageUnicast)
{
if (priority != TransferPriorityService)
{
transfer_priority_ = priority;
}
else
{
UAVCAN_ASSERT(0);
}
}
else
{
UAVCAN_ASSERT(0);
}
}
int Frame::getMaxPayloadLen() const
{
switch (getTransferType())
{
case TransferTypeMessageBroadcast:
{
return int(sizeof(payload_));
}
case TransferTypeServiceResponse:
case TransferTypeServiceRequest:
case TransferTypeMessageUnicast:
{
return int(sizeof(payload_)) - 1;
}
default:
{
UAVCAN_ASSERT(0);
return -ErrLogic;
}
}
}
int Frame::setPayload(const uint8_t* data, unsigned len)
{
const int maxlen = getMaxPayloadLen();
if (maxlen < 0)
{
return maxlen;
}
len = min(unsigned(maxlen), len);
(void)copy(data, data + len, payload_);
payload_len_ = uint_fast8_t(len);
return int(len);
}
template <int OFFSET, int WIDTH>
inline static uint32_t bitunpack(uint32_t val)
{
StaticAssert<(OFFSET >= 0)>::check();
StaticAssert<(WIDTH > 0)>::check();
StaticAssert<((OFFSET + WIDTH) <= 29)>::check();
return (val >> OFFSET) & ((1UL << WIDTH) - 1);
}
bool Frame::parse(const CanFrame& can_frame)
{
if (can_frame.isErrorFrame() || can_frame.isRemoteTransmissionRequest() || !can_frame.isExtended())
{
return false;
}
if (can_frame.dlc > sizeof(can_frame.data))
{
UAVCAN_ASSERT(0); // This is not a protocol error, so UAVCAN_ASSERT() is ok
return false;
}
/*
* CAN ID parsing
*/
const uint32_t id = can_frame.id & CanFrame::MaskExtID;
transfer_id_ = uint8_t(bitunpack<0, 3>(id));
last_frame_ = bitunpack<3, 1>(id) != 0;
// TT-specific fields skipped
transfer_priority_ = TransferPriority(bitunpack<27, 2>(id));
if (transfer_priority_ == TransferPriorityService)
{
frame_index_ = uint_fast8_t(bitunpack<4, 6>(id));
src_node_id_ = uint8_t(bitunpack<10, 7>(id));
data_type_id_ = uint16_t(bitunpack<17, 9>(id));
// RequestNotResponse
transfer_type_ = (bitunpack<26, 1>(id) == 1U) ? TransferTypeServiceRequest : TransferTypeServiceResponse;
}
else
{
frame_index_ = uint_fast8_t(bitunpack<4, 4>(id));
// BroadcastNotUnicast
transfer_type_ = (bitunpack<8, 1>(id) == 1U) ? TransferTypeMessageBroadcast : TransferTypeMessageUnicast;
src_node_id_ = uint8_t(bitunpack<9, 7>(id));
data_type_id_ = uint16_t(bitunpack<16, 11>(id));
}
/*
* CAN payload parsing
*/
switch (transfer_type_)
{
case TransferTypeMessageBroadcast:
{
dst_node_id_ = NodeID::Broadcast;
payload_len_ = can_frame.dlc;
(void)copy(can_frame.data, can_frame.data + can_frame.dlc, payload_);
break;
}
case TransferTypeServiceResponse:
case TransferTypeServiceRequest:
case TransferTypeMessageUnicast:
{
if (can_frame.dlc < 1)
{
return false;
}
if (can_frame.data[0] & 0x80) // RESERVED, must be zero
{
return false;
}
dst_node_id_ = can_frame.data[0] & 0x7F;
payload_len_ = uint8_t(can_frame.dlc - 1);
(void)copy(can_frame.data + 1, can_frame.data + can_frame.dlc, payload_);
break;
}
default:
{
return false;
}
}
/*
* Special case for anonymous transfers - trailing 8 bits of CAN ID must be ignored
* - Transfer ID (assumed zero)
* - Last Frame (assumed true)
* - Frame Index (assumed zero)
*/
if (src_node_id_.isBroadcast())
{
transfer_id_ = TransferID(0);
last_frame_ = true;
frame_index_ = 0;
}
return isValid();
}
template <int OFFSET, int WIDTH>
inline static uint32_t bitpack(uint32_t field)
{
StaticAssert<(OFFSET >= 0)>::check();
StaticAssert<(WIDTH > 0)>::check();
StaticAssert<((OFFSET + WIDTH) <= 29)>::check();
UAVCAN_ASSERT((field & ((1UL << WIDTH) - 1)) == field);
return uint32_t((field & ((1UL << WIDTH) - 1)) << OFFSET);
}
bool Frame::compile(CanFrame& out_can_frame) const
{
if (!isValid())
{
UAVCAN_ASSERT(0); // This is an application error, so we need to maximize it.
return false;
}
/*
* Setting CAN ID field
*/
// Common fields for messages and services
out_can_frame.id =
CanFrame::FlagEFF |
bitpack<0, 3>(transfer_id_.get()) |
bitpack<3, 1>(last_frame_) |
/* TT-specific fields skipped */
bitpack<27, 2>(transfer_priority_);
if (transfer_type_ == TransferTypeServiceRequest ||
transfer_type_ == TransferTypeServiceResponse)
{
out_can_frame.id |=
bitpack<4, 6>(frame_index_) |
bitpack<10, 7>(src_node_id_.get()) |
bitpack<17, 9>(data_type_id_.get()) |
bitpack<26, 1>((transfer_type_ == TransferTypeServiceRequest) ? 1U : 0U);
}
else if (transfer_type_ == TransferTypeMessageBroadcast ||
transfer_type_ == TransferTypeMessageUnicast)
{
out_can_frame.id |=
bitpack<4, 4>(frame_index_) |
bitpack<8, 1>((transfer_type_ == TransferTypeMessageBroadcast) ? 1U : 0U) |
bitpack<9, 7>(src_node_id_.get()) |
bitpack<16, 11>(data_type_id_.get());
}
else
{
UAVCAN_ASSERT(0);
return false;
}
/*
* Setting payload
*/
switch (transfer_type_)
{
case TransferTypeMessageBroadcast:
{
out_can_frame.dlc = uint8_t(payload_len_);
(void)copy(payload_, payload_ + payload_len_, out_can_frame.data);
break;
}
case TransferTypeServiceResponse:
case TransferTypeServiceRequest:
case TransferTypeMessageUnicast:
{
UAVCAN_ASSERT((payload_len_ + 1U) <= sizeof(out_can_frame.data));
out_can_frame.data[0] = dst_node_id_.get();
out_can_frame.dlc = uint8_t(payload_len_ + 1);
(void)copy(payload_, payload_ + payload_len_, out_can_frame.data + 1);
break;
}
default:
{
UAVCAN_ASSERT(0);
return false;
}
}
/*
* Setting trailing bits of CAN ID for anonymous message
* This overrides the following fields:
* - Transfer ID (assumed zero)
* - Last Frame (assumed true)
* - Frame Index (assumed zero)
*/
if (src_node_id_.isBroadcast())
{
uint8_t sum = 0;
out_can_frame.id &= ~bitpack<0, 8>(sum); // Clearing bits
for (uint_fast8_t i = 0; i < payload_len_; i++)
{
sum = static_cast<uint8_t>(sum + payload_[i]);
}
out_can_frame.id |= bitpack<0, 8>(sum); // Setting the checksum
}
return true;
}
bool Frame::isValid() const
{
/*
* Frame index
*/
if (frame_index_ > getMaxIndex())
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
if ((frame_index_ == getMaxIndex()) && !last_frame_)
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
/*
* Node ID
*/
if (!src_node_id_.isValid() ||
!dst_node_id_.isValid())
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
if (src_node_id_.isUnicast() &&
(src_node_id_ == dst_node_id_))
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
/*
* Transfer type
*/
if (transfer_type_ >= NumTransferTypes)
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
if ((transfer_type_ == TransferTypeMessageBroadcast) != dst_node_id_.isBroadcast())
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
// Anonymous transfers
if (src_node_id_.isBroadcast() &&
(!last_frame_ || (frame_index_ > 0) || (transfer_type_ != TransferTypeMessageBroadcast)))
{
return false;
}
/*
* Payload
*/
if (static_cast<int>(payload_len_) > getMaxPayloadLen())
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
/*
* Data type ID
*/
if (!data_type_id_.isValidForDataTypeKind(getDataTypeKindForTransferType(transfer_type_)))
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
/*
* Priority
*/
if (transfer_priority_ >= NumTransferPriorities)
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
if (transfer_type_ == TransferTypeServiceRequest ||
transfer_type_ == TransferTypeServiceResponse)
{
if (transfer_priority_ != TransferPriorityService)
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
}
return true;
}
bool Frame::operator==(const Frame& rhs) const
{
return
(transfer_priority_ == rhs.transfer_priority_) &&
(transfer_type_ == rhs.transfer_type_) &&
(data_type_id_ == rhs.data_type_id_) &&
(src_node_id_ == rhs.src_node_id_) &&
(dst_node_id_ == rhs.dst_node_id_) &&
(frame_index_ == rhs.frame_index_) &&
(transfer_id_ == rhs.transfer_id_) &&
(last_frame_ == rhs.last_frame_) &&
(payload_len_ == rhs.payload_len_) &&
equal(payload_, payload_ + payload_len_, rhs.payload_);
}
#if UAVCAN_TOSTRING
std::string Frame::toString() const
{
/*
* - Priority
* - Data Type ID
* - Transfer Type
* - Source Node ID
* - Frame Index
* - Last Frame
* - Transfer ID
*/
static const int BUFLEN = 100;
char buf[BUFLEN];
int ofs = snprintf(buf, BUFLEN, "prio=%d dtid=%d tt=%d snid=%d dnid=%d idx=%d last=%d tid=%d payload=[",
int(transfer_priority_), int(data_type_id_.get()), int(transfer_type_), int(src_node_id_.get()),
int(dst_node_id_.get()), int(frame_index_), int(last_frame_), int(transfer_id_.get()));
for (unsigned i = 0; i < payload_len_; i++)
{
ofs += snprintf(buf + ofs, unsigned(BUFLEN - ofs), "%02x", payload_[i]);
if ((i + 1) < payload_len_)
{
ofs += snprintf(buf + ofs, unsigned(BUFLEN - ofs), " ");
}
}
(void)snprintf(buf + ofs, unsigned(BUFLEN - ofs), "]");
return std::string(buf);
}
#endif
/**
* RxFrame
*/
bool RxFrame::parse(const CanRxFrame& can_frame)
{
if (!Frame::parse(can_frame))
{
return false;
}
if (can_frame.ts_mono.isZero()) // Monotonic timestamps are mandatory.
{
UAVCAN_ASSERT(0); // If it is not set, it's a driver failure.
return false;
}
ts_mono_ = can_frame.ts_mono;
ts_utc_ = can_frame.ts_utc;
iface_index_ = can_frame.iface_index;
return true;
}
#if UAVCAN_TOSTRING
std::string RxFrame::toString() const
{
std::string out = Frame::toString();
out.reserve(128);
out += " ts_m=" + ts_mono_.toString();
out += " ts_utc=" + ts_utc_.toString();
out += " iface=";
out += char('0' + iface_index_);
return out;
}
#endif
}
<commit_msg>Add missing include<commit_after>/*
* Copyright (C) 2014 Pavel Kirienko <[email protected]>
*/
#include <uavcan/transport/frame.hpp>
#include <uavcan/transport/can_io.hpp>
#include <uavcan/debug.hpp>
#include <cassert>
namespace uavcan
{
/**
* Frame
*/
const uint8_t Frame::MaxIndexForService;
const uint8_t Frame::MaxIndexForMessage;
uint_fast8_t Frame::getMaxIndexForTransferType(const TransferType type)
{
if (type == TransferTypeMessageBroadcast ||
type == TransferTypeMessageUnicast)
{
return MaxIndexForMessage;
}
else if (type == TransferTypeServiceRequest ||
type == TransferTypeServiceResponse)
{
return MaxIndexForService;
}
else
{
UAVCAN_ASSERT(0);
return 0;
}
}
void Frame::setPriority(const TransferPriority priority)
{
UAVCAN_ASSERT(priority < NumTransferPriorities);
if (transfer_type_ == TransferTypeMessageBroadcast ||
transfer_type_ == TransferTypeMessageUnicast)
{
if (priority != TransferPriorityService)
{
transfer_priority_ = priority;
}
else
{
UAVCAN_ASSERT(0);
}
}
else
{
UAVCAN_ASSERT(0);
}
}
int Frame::getMaxPayloadLen() const
{
switch (getTransferType())
{
case TransferTypeMessageBroadcast:
{
return int(sizeof(payload_));
}
case TransferTypeServiceResponse:
case TransferTypeServiceRequest:
case TransferTypeMessageUnicast:
{
return int(sizeof(payload_)) - 1;
}
default:
{
UAVCAN_ASSERT(0);
return -ErrLogic;
}
}
}
int Frame::setPayload(const uint8_t* data, unsigned len)
{
const int maxlen = getMaxPayloadLen();
if (maxlen < 0)
{
return maxlen;
}
len = min(unsigned(maxlen), len);
(void)copy(data, data + len, payload_);
payload_len_ = uint_fast8_t(len);
return int(len);
}
template <int OFFSET, int WIDTH>
inline static uint32_t bitunpack(uint32_t val)
{
StaticAssert<(OFFSET >= 0)>::check();
StaticAssert<(WIDTH > 0)>::check();
StaticAssert<((OFFSET + WIDTH) <= 29)>::check();
return (val >> OFFSET) & ((1UL << WIDTH) - 1);
}
bool Frame::parse(const CanFrame& can_frame)
{
if (can_frame.isErrorFrame() || can_frame.isRemoteTransmissionRequest() || !can_frame.isExtended())
{
return false;
}
if (can_frame.dlc > sizeof(can_frame.data))
{
UAVCAN_ASSERT(0); // This is not a protocol error, so UAVCAN_ASSERT() is ok
return false;
}
/*
* CAN ID parsing
*/
const uint32_t id = can_frame.id & CanFrame::MaskExtID;
transfer_id_ = uint8_t(bitunpack<0, 3>(id));
last_frame_ = bitunpack<3, 1>(id) != 0;
// TT-specific fields skipped
transfer_priority_ = TransferPriority(bitunpack<27, 2>(id));
if (transfer_priority_ == TransferPriorityService)
{
frame_index_ = uint_fast8_t(bitunpack<4, 6>(id));
src_node_id_ = uint8_t(bitunpack<10, 7>(id));
data_type_id_ = uint16_t(bitunpack<17, 9>(id));
// RequestNotResponse
transfer_type_ = (bitunpack<26, 1>(id) == 1U) ? TransferTypeServiceRequest : TransferTypeServiceResponse;
}
else
{
frame_index_ = uint_fast8_t(bitunpack<4, 4>(id));
// BroadcastNotUnicast
transfer_type_ = (bitunpack<8, 1>(id) == 1U) ? TransferTypeMessageBroadcast : TransferTypeMessageUnicast;
src_node_id_ = uint8_t(bitunpack<9, 7>(id));
data_type_id_ = uint16_t(bitunpack<16, 11>(id));
}
/*
* CAN payload parsing
*/
switch (transfer_type_)
{
case TransferTypeMessageBroadcast:
{
dst_node_id_ = NodeID::Broadcast;
payload_len_ = can_frame.dlc;
(void)copy(can_frame.data, can_frame.data + can_frame.dlc, payload_);
break;
}
case TransferTypeServiceResponse:
case TransferTypeServiceRequest:
case TransferTypeMessageUnicast:
{
if (can_frame.dlc < 1)
{
return false;
}
if (can_frame.data[0] & 0x80) // RESERVED, must be zero
{
return false;
}
dst_node_id_ = can_frame.data[0] & 0x7F;
payload_len_ = uint8_t(can_frame.dlc - 1);
(void)copy(can_frame.data + 1, can_frame.data + can_frame.dlc, payload_);
break;
}
default:
{
return false;
}
}
/*
* Special case for anonymous transfers - trailing 8 bits of CAN ID must be ignored
* - Transfer ID (assumed zero)
* - Last Frame (assumed true)
* - Frame Index (assumed zero)
*/
if (src_node_id_.isBroadcast())
{
transfer_id_ = TransferID(0);
last_frame_ = true;
frame_index_ = 0;
}
return isValid();
}
template <int OFFSET, int WIDTH>
inline static uint32_t bitpack(uint32_t field)
{
StaticAssert<(OFFSET >= 0)>::check();
StaticAssert<(WIDTH > 0)>::check();
StaticAssert<((OFFSET + WIDTH) <= 29)>::check();
UAVCAN_ASSERT((field & ((1UL << WIDTH) - 1)) == field);
return uint32_t((field & ((1UL << WIDTH) - 1)) << OFFSET);
}
bool Frame::compile(CanFrame& out_can_frame) const
{
if (!isValid())
{
UAVCAN_ASSERT(0); // This is an application error, so we need to maximize it.
return false;
}
/*
* Setting CAN ID field
*/
// Common fields for messages and services
out_can_frame.id =
CanFrame::FlagEFF |
bitpack<0, 3>(transfer_id_.get()) |
bitpack<3, 1>(last_frame_) |
/* TT-specific fields skipped */
bitpack<27, 2>(transfer_priority_);
if (transfer_type_ == TransferTypeServiceRequest ||
transfer_type_ == TransferTypeServiceResponse)
{
out_can_frame.id |=
bitpack<4, 6>(frame_index_) |
bitpack<10, 7>(src_node_id_.get()) |
bitpack<17, 9>(data_type_id_.get()) |
bitpack<26, 1>((transfer_type_ == TransferTypeServiceRequest) ? 1U : 0U);
}
else if (transfer_type_ == TransferTypeMessageBroadcast ||
transfer_type_ == TransferTypeMessageUnicast)
{
out_can_frame.id |=
bitpack<4, 4>(frame_index_) |
bitpack<8, 1>((transfer_type_ == TransferTypeMessageBroadcast) ? 1U : 0U) |
bitpack<9, 7>(src_node_id_.get()) |
bitpack<16, 11>(data_type_id_.get());
}
else
{
UAVCAN_ASSERT(0);
return false;
}
/*
* Setting payload
*/
switch (transfer_type_)
{
case TransferTypeMessageBroadcast:
{
out_can_frame.dlc = uint8_t(payload_len_);
(void)copy(payload_, payload_ + payload_len_, out_can_frame.data);
break;
}
case TransferTypeServiceResponse:
case TransferTypeServiceRequest:
case TransferTypeMessageUnicast:
{
UAVCAN_ASSERT((payload_len_ + 1U) <= sizeof(out_can_frame.data));
out_can_frame.data[0] = dst_node_id_.get();
out_can_frame.dlc = uint8_t(payload_len_ + 1);
(void)copy(payload_, payload_ + payload_len_, out_can_frame.data + 1);
break;
}
default:
{
UAVCAN_ASSERT(0);
return false;
}
}
/*
* Setting trailing bits of CAN ID for anonymous message
* This overrides the following fields:
* - Transfer ID (assumed zero)
* - Last Frame (assumed true)
* - Frame Index (assumed zero)
*/
if (src_node_id_.isBroadcast())
{
uint8_t sum = 0;
out_can_frame.id &= ~bitpack<0, 8>(sum); // Clearing bits
for (uint_fast8_t i = 0; i < payload_len_; i++)
{
sum = static_cast<uint8_t>(sum + payload_[i]);
}
out_can_frame.id |= bitpack<0, 8>(sum); // Setting the checksum
}
return true;
}
bool Frame::isValid() const
{
/*
* Frame index
*/
if (frame_index_ > getMaxIndex())
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
if ((frame_index_ == getMaxIndex()) && !last_frame_)
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
/*
* Node ID
*/
if (!src_node_id_.isValid() ||
!dst_node_id_.isValid())
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
if (src_node_id_.isUnicast() &&
(src_node_id_ == dst_node_id_))
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
/*
* Transfer type
*/
if (transfer_type_ >= NumTransferTypes)
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
if ((transfer_type_ == TransferTypeMessageBroadcast) != dst_node_id_.isBroadcast())
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
// Anonymous transfers
if (src_node_id_.isBroadcast() &&
(!last_frame_ || (frame_index_ > 0) || (transfer_type_ != TransferTypeMessageBroadcast)))
{
return false;
}
/*
* Payload
*/
if (static_cast<int>(payload_len_) > getMaxPayloadLen())
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
/*
* Data type ID
*/
if (!data_type_id_.isValidForDataTypeKind(getDataTypeKindForTransferType(transfer_type_)))
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
/*
* Priority
*/
if (transfer_priority_ >= NumTransferPriorities)
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
if (transfer_type_ == TransferTypeServiceRequest ||
transfer_type_ == TransferTypeServiceResponse)
{
if (transfer_priority_ != TransferPriorityService)
{
UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__);
return false;
}
}
return true;
}
bool Frame::operator==(const Frame& rhs) const
{
return
(transfer_priority_ == rhs.transfer_priority_) &&
(transfer_type_ == rhs.transfer_type_) &&
(data_type_id_ == rhs.data_type_id_) &&
(src_node_id_ == rhs.src_node_id_) &&
(dst_node_id_ == rhs.dst_node_id_) &&
(frame_index_ == rhs.frame_index_) &&
(transfer_id_ == rhs.transfer_id_) &&
(last_frame_ == rhs.last_frame_) &&
(payload_len_ == rhs.payload_len_) &&
equal(payload_, payload_ + payload_len_, rhs.payload_);
}
#if UAVCAN_TOSTRING
std::string Frame::toString() const
{
/*
* - Priority
* - Data Type ID
* - Transfer Type
* - Source Node ID
* - Frame Index
* - Last Frame
* - Transfer ID
*/
static const int BUFLEN = 100;
char buf[BUFLEN];
int ofs = snprintf(buf, BUFLEN, "prio=%d dtid=%d tt=%d snid=%d dnid=%d idx=%d last=%d tid=%d payload=[",
int(transfer_priority_), int(data_type_id_.get()), int(transfer_type_), int(src_node_id_.get()),
int(dst_node_id_.get()), int(frame_index_), int(last_frame_), int(transfer_id_.get()));
for (unsigned i = 0; i < payload_len_; i++)
{
ofs += snprintf(buf + ofs, unsigned(BUFLEN - ofs), "%02x", payload_[i]);
if ((i + 1) < payload_len_)
{
ofs += snprintf(buf + ofs, unsigned(BUFLEN - ofs), " ");
}
}
(void)snprintf(buf + ofs, unsigned(BUFLEN - ofs), "]");
return std::string(buf);
}
#endif
/**
* RxFrame
*/
bool RxFrame::parse(const CanRxFrame& can_frame)
{
if (!Frame::parse(can_frame))
{
return false;
}
if (can_frame.ts_mono.isZero()) // Monotonic timestamps are mandatory.
{
UAVCAN_ASSERT(0); // If it is not set, it's a driver failure.
return false;
}
ts_mono_ = can_frame.ts_mono;
ts_utc_ = can_frame.ts_utc;
iface_index_ = can_frame.iface_index;
return true;
}
#if UAVCAN_TOSTRING
std::string RxFrame::toString() const
{
std::string out = Frame::toString();
out.reserve(128);
out += " ts_m=" + ts_mono_.toString();
out += " ts_utc=" + ts_utc_.toString();
out += " iface=";
out += char('0' + iface_index_);
return out;
}
#endif
}
<|endoftext|> |
<commit_before>#pragma once
namespace perlin{
typedef float real;
constexpr uint_fast8_t perm[512] = {
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233,
7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23,
190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219,
203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174,
20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27,
166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230,
220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25,
63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,
200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173,
186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118,
126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182,
189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163,
70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19,
98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246,
97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162,
241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181,
199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150,
254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128,
195, 78, 66, 215, 61, 156, 180, 151, 160, 137, 91, 90, 15, 131,
13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69,
142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75,
0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33,
88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74,
165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229,
122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244,
102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132,
187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86,
164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124,
123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59,
227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119,
248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172,
9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178,
185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210,
144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239,
107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176,
115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114,
67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180
};
inline constexpr real fade(const real t){
return pow(t, 3) * (t * (t * 6 - 15) + 10);
}
inline constexpr real lerp(
const real t,
const real a,
const real b
){
return a + t * (b - a);
}
inline constexpr real grad(
const int hash,
const real x,
const real y,
const real z
){
const auto h = hash & 15;
const auto u = h < 8 ? x : y,
v = h < 4 ? y : h == 12 || h == 14 ? x : z;
return ((h & 1) == 0 ? u : -u)
+ ((h & 2) == 0 ? v : -v);
}
inline constexpr real noise(
const real x = 0.0,
const real y = 0.0,
const real z = 0.0
){
const auto unit_x = (int)floor(x) & 255,
unit_y = (int)floor(y) & 255,
unit_z = (int)floor(z) & 255;
const auto sub_x = x - floor(x),
sub_y = y - floor(y),
sub_z = z - floor(z);
const auto u = fade(sub_x),
v = fade(sub_y),
w = fade(sub_z);
const auto a = perm[unit_x] + unit_y,
aa = perm[a] + unit_z,
ab = perm[a + 1] + unit_z,
b = perm[unit_x + 1] + unit_y,
ba = perm[b] + unit_z,
bb = perm[b + 1] + unit_z;
return lerp(w,
lerp(
v,
lerp(
u,
grad(
perm[aa],
sub_x,
sub_y,
sub_z
),
grad(
perm[ba],
sub_x - 1,
sub_y,
sub_z
)
),
lerp(
u,
grad(
perm[ab],
sub_x,
sub_y - 1,
sub_z
),
grad(
perm[bb],
sub_x - 1,
sub_y - 1,
sub_z
)
)
),
lerp(
v,
lerp(
u,
grad(
perm[aa + 1],
sub_x,
sub_y,
sub_z - 1
),
grad(
perm[ba + 1],
sub_x - 1,
sub_y,
sub_z - 1
)
),
lerp(
u,
grad(
perm[ab + 1],
sub_x,
sub_y - 1,
sub_z - 1
),
grad(
perm[bb + 1],
sub_x - 1,
sub_y - 1,
sub_z - 1
)
)
)
);
}
};
<commit_msg>Replace all tabs with 4 spaces<commit_after>#pragma once
namespace perlin{
typedef float real;
constexpr uint_fast8_t perm[512] = {
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233,
7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23,
190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219,
203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174,
20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27,
166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230,
220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25,
63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,
200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173,
186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118,
126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182,
189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163,
70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19,
98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246,
97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162,
241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181,
199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150,
254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128,
195, 78, 66, 215, 61, 156, 180, 151, 160, 137, 91, 90, 15, 131,
13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69,
142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75,
0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33,
88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74,
165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229,
122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244,
102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132,
187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86,
164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124,
123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59,
227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119,
248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172,
9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178,
185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210,
144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239,
107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176,
115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114,
67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180
};
inline constexpr real fade(const real t){
return pow(t, 3) * (t * (t * 6 - 15) + 10);
}
inline constexpr real lerp(
const real t,
const real a,
const real b
){
return a + t * (b - a);
}
inline constexpr real grad(
const int hash,
const real x,
const real y,
const real z
){
const auto h = hash & 15;
const auto u = h < 8 ? x : y,
v = h < 4 ? y : h == 12 || h == 14 ? x : z;
return ((h & 1) == 0 ? u : -u)
+ ((h & 2) == 0 ? v : -v);
}
inline constexpr real noise(
const real x = 0.0,
const real y = 0.0,
const real z = 0.0
){
const auto unit_x = (int)floor(x) & 255,
unit_y = (int)floor(y) & 255,
unit_z = (int)floor(z) & 255;
const auto sub_x = x - floor(x),
sub_y = y - floor(y),
sub_z = z - floor(z);
const auto u = fade(sub_x),
v = fade(sub_y),
w = fade(sub_z);
const auto a = perm[unit_x] + unit_y,
aa = perm[a] + unit_z,
ab = perm[a + 1] + unit_z,
b = perm[unit_x + 1] + unit_y,
ba = perm[b] + unit_z,
bb = perm[b + 1] + unit_z;
return lerp(w,
lerp(
v,
lerp(
u,
grad(
perm[aa],
sub_x,
sub_y,
sub_z
),
grad(
perm[ba],
sub_x - 1,
sub_y,
sub_z
)
),
lerp(
u,
grad(
perm[ab],
sub_x,
sub_y - 1,
sub_z
),
grad(
perm[bb],
sub_x - 1,
sub_y - 1,
sub_z
)
)
),
lerp(
v,
lerp(
u,
grad(
perm[aa + 1],
sub_x,
sub_y,
sub_z - 1
),
grad(
perm[ba + 1],
sub_x - 1,
sub_y,
sub_z - 1
)
),
lerp(
u,
grad(
perm[ab + 1],
sub_x,
sub_y - 1,
sub_z - 1
),
grad(
perm[bb + 1],
sub_x - 1,
sub_y - 1,
sub_z - 1
)
)
)
);
}
};
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkPolygonGroupSpatialObjectXMLFileTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkPolygonGroupSpatialObject.h"
#include "itkPolygonSpatialObject.h"
#include <iostream>
#include "itkPolygonGroupSpatialObjectXMLFile.h"
#include <itksys/SystemTools.hxx>
static float points[11][2] =
{
{1,1},{1,2},{1.25,2},{1.25,1.25},{1.75,1.25},
{1.75,1.5},{1.5,1.5},{1.5,2},{2,2},{2,1},{1,1}
};
typedef itk::PolygonSpatialObject<3> Polygon3DType;
typedef itk::PolygonGroupSpatialObject<3> PolygonGroup3DType;
typedef PolygonGroup3DType::Pointer PolygonGroup3DPointer;
int
buildPolygonGroup(PolygonGroup3DPointer &PolygonGroup)
{
try
{
for(float z = 0.0; z <= 10.0; z += 1.0)
{
itk::PolygonSpatialObject<3>::Pointer strand
= itk::PolygonSpatialObject<3>::New();
if(!PolygonGroup->AddStrand(strand))
{
std::cerr << "Error adding point" << std::endl;
return -1;
}
strand->SetThickness(1.0);
//
// add all points to this strand.
for(int i = 0; i < 11; i++)
{
double pos[3];
pos[0] = points[i][0];
pos[1] = points[i][1];
pos[2] = z;
itk::PolygonSpatialObject<3>::PointType curpoint(pos);
if(!strand->AddPoint(curpoint))
{
std::cerr << "Error adding point" << std::endl;
return -1;
}
}
}
}
catch(itk::ExceptionObject &)
{
std::cerr << "Error creating PolygonGroup" << std::endl;
return -1;
}
return 0;
}
int testPolygonGroupEquivalence(PolygonGroup3DPointer &p1,
PolygonGroup3DPointer &p2)
{
//
// Write out polygondata
PolygonGroup3DType::ChildrenListType *children1 =
p1->GetChildren(0,NULL);
PolygonGroup3DType::ChildrenListType::iterator it1 =
children1->begin();
PolygonGroup3DType::ChildrenListType::iterator end1 =
children1->end();
PolygonGroup3DType::ChildrenListType *children2 =
p2->GetChildren(0,NULL);
PolygonGroup3DType::ChildrenListType::iterator it2 =
children2->begin();
PolygonGroup3DType::ChildrenListType::iterator end2 =
children2->end();
while(it1 != end1)
{
if(it2 == end2) // premature end of list
return -1;
Polygon3DType *curstrand1 =
dynamic_cast<Polygon3DType *>((*it1).GetPointer());
Polygon3DType *curstrand2 =
dynamic_cast<Polygon3DType *>((*it2).GetPointer());
Polygon3DType::PointListType &points1 =
curstrand1->GetPoints();
Polygon3DType::PointListType &points2 =
curstrand2->GetPoints();
Polygon3DType::PointListType::iterator pointIt1
= points1.begin();
Polygon3DType::PointListType::iterator pointItEnd1
= points1.end();
Polygon3DType::PointListType::iterator pointIt2
= points2.begin();
Polygon3DType::PointListType::iterator pointItEnd2
= points2.end();
while(pointIt1 != pointItEnd1)
{
if(pointIt2 == pointItEnd2)
return -1;
Polygon3DType::PointType curpoint1 =
(*pointIt1).GetPosition();
Polygon3DType::PointType curpoint2 =
(*pointIt2).GetPosition();
pointIt1++;
pointIt2++;
}
if(pointIt2 != pointItEnd2)
return -1;
it1++;
it2++;
}
if(it2 != end2)
return -1;
return 0;
}
int itkPolygonGroupSpatialObjectXMLFileTest(int ac, char *av[])
{
if(ac < 2)
{
std::cerr << "Usage: " << av[0] << " XMLfile\n";
return EXIT_FAILURE;
}
PolygonGroup3DPointer PolygonGroup = PolygonGroup3DType::New();
PolygonGroup3DPointer PGroupFromFile;
if(buildPolygonGroup(PolygonGroup) != 0 || PolygonGroup.IsNull())
{
std::cerr << "Error building polygon group" << std::endl;
return EXIT_FAILURE;
}
std::string xmlfilename(av[1]);
xmlfilename = xmlfilename + "/PolygonGroupSpatialObjectXMLFileTest.xml";
try
{
itk::PolygonGroupSpatialObjectXMLFileWriter::Pointer pw =
itk::PolygonGroupSpatialObjectXMLFileWriter::New();
pw->SetFilename(xmlfilename.c_str());
pw->SetObject(&(*PolygonGroup));
pw->WriteFile();
}
catch(itk::ExceptionObject &)
{
std::cerr << "Error Creating file" << std::endl;
return EXIT_FAILURE;
}
try
{
itk::PolygonGroupSpatialObjectXMLFileReader::Pointer p =
itk::PolygonGroupSpatialObjectXMLFileReader::New();
p->SetFilename(xmlfilename.c_str());
p->GenerateOutputInformation();
PGroupFromFile = p->GetOutputObject();
if(PGroupFromFile.IsNull())
{
std::cerr << "Error retrieving object pointer" << std::endl;
return EXIT_FAILURE;
}
}
catch(itk::ExceptionObject &)
{
std::cerr << "Error Reading file" << std::endl;
return EXIT_FAILURE;
}
itksys::SystemTools::RemoveFile(xmlfilename.c_str());
return testPolygonGroupEquivalence(PolygonGroup,PGroupFromFile);
}
<commit_msg>FIX: MLKs, list of children must be deleted<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkPolygonGroupSpatialObjectXMLFileTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkPolygonGroupSpatialObject.h"
#include "itkPolygonSpatialObject.h"
#include <iostream>
#include "itkPolygonGroupSpatialObjectXMLFile.h"
#include <itksys/SystemTools.hxx>
static float points[11][2] =
{
{1,1},{1,2},{1.25,2},{1.25,1.25},{1.75,1.25},
{1.75,1.5},{1.5,1.5},{1.5,2},{2,2},{2,1},{1,1}
};
typedef itk::PolygonSpatialObject<3> Polygon3DType;
typedef itk::PolygonGroupSpatialObject<3> PolygonGroup3DType;
typedef PolygonGroup3DType::Pointer PolygonGroup3DPointer;
int
buildPolygonGroup(PolygonGroup3DPointer &PolygonGroup)
{
try
{
for(float z = 0.0; z <= 10.0; z += 1.0)
{
itk::PolygonSpatialObject<3>::Pointer strand
= itk::PolygonSpatialObject<3>::New();
if(!PolygonGroup->AddStrand(strand))
{
std::cerr << "Error adding point" << std::endl;
return -1;
}
strand->SetThickness(1.0);
//
// add all points to this strand.
for(int i = 0; i < 11; i++)
{
double pos[3];
pos[0] = points[i][0];
pos[1] = points[i][1];
pos[2] = z;
itk::PolygonSpatialObject<3>::PointType curpoint(pos);
if(!strand->AddPoint(curpoint))
{
std::cerr << "Error adding point" << std::endl;
return -1;
}
}
}
}
catch(itk::ExceptionObject &)
{
std::cerr << "Error creating PolygonGroup" << std::endl;
return -1;
}
return 0;
}
int testPolygonGroupEquivalence(PolygonGroup3DPointer &p1,
PolygonGroup3DPointer &p2)
{
//
// Write out polygondata
PolygonGroup3DType::ChildrenListType *children1 =
p1->GetChildren(0,NULL);
PolygonGroup3DType::ChildrenListType::iterator it1 =
children1->begin();
PolygonGroup3DType::ChildrenListType::iterator end1 =
children1->end();
PolygonGroup3DType::ChildrenListType *children2 =
p2->GetChildren(0,NULL);
PolygonGroup3DType::ChildrenListType::iterator it2 =
children2->begin();
PolygonGroup3DType::ChildrenListType::iterator end2 =
children2->end();
while(it1 != end1)
{
if(it2 == end2) // premature end of list
{
delete children1;
delete children2;
return -1;
}
Polygon3DType *curstrand1 =
dynamic_cast<Polygon3DType *>((*it1).GetPointer());
Polygon3DType *curstrand2 =
dynamic_cast<Polygon3DType *>((*it2).GetPointer());
Polygon3DType::PointListType &points1 =
curstrand1->GetPoints();
Polygon3DType::PointListType &points2 =
curstrand2->GetPoints();
Polygon3DType::PointListType::iterator pointIt1
= points1.begin();
Polygon3DType::PointListType::iterator pointItEnd1
= points1.end();
Polygon3DType::PointListType::iterator pointIt2
= points2.begin();
Polygon3DType::PointListType::iterator pointItEnd2
= points2.end();
while(pointIt1 != pointItEnd1)
{
if(pointIt2 == pointItEnd2)
{
delete children1;
delete children2;
return -1;
}
Polygon3DType::PointType curpoint1 =
(*pointIt1).GetPosition();
Polygon3DType::PointType curpoint2 =
(*pointIt2).GetPosition();
pointIt1++;
pointIt2++;
}
if(pointIt2 != pointItEnd2)
{
delete children1;
delete children2;
return -1;
}
it1++;
it2++;
}
if(it2 != end2)
{
delete children1;
delete children2;
return -1;
}
delete children1;
delete children2;
return 0;
}
int itkPolygonGroupSpatialObjectXMLFileTest(int ac, char *av[])
{
if(ac < 2)
{
std::cerr << "Usage: " << av[0] << " XMLfile\n";
return EXIT_FAILURE;
}
PolygonGroup3DPointer PolygonGroup = PolygonGroup3DType::New();
PolygonGroup3DPointer PGroupFromFile;
if(buildPolygonGroup(PolygonGroup) != 0 || PolygonGroup.IsNull())
{
std::cerr << "Error building polygon group" << std::endl;
return EXIT_FAILURE;
}
std::string xmlfilename(av[1]);
xmlfilename = xmlfilename + "/PolygonGroupSpatialObjectXMLFileTest.xml";
try
{
itk::PolygonGroupSpatialObjectXMLFileWriter::Pointer pw =
itk::PolygonGroupSpatialObjectXMLFileWriter::New();
pw->SetFilename(xmlfilename.c_str());
pw->SetObject(&(*PolygonGroup));
pw->WriteFile();
}
catch(itk::ExceptionObject &)
{
std::cerr << "Error Creating file" << std::endl;
return EXIT_FAILURE;
}
try
{
itk::PolygonGroupSpatialObjectXMLFileReader::Pointer p =
itk::PolygonGroupSpatialObjectXMLFileReader::New();
p->SetFilename(xmlfilename.c_str());
p->GenerateOutputInformation();
PGroupFromFile = p->GetOutputObject();
if(PGroupFromFile.IsNull())
{
std::cerr << "Error retrieving object pointer" << std::endl;
return EXIT_FAILURE;
}
}
catch(itk::ExceptionObject &)
{
std::cerr << "Error Reading file" << std::endl;
return EXIT_FAILURE;
}
itksys::SystemTools::RemoveFile(xmlfilename.c_str());
return testPolygonGroupEquivalence(PolygonGroup,PGroupFromFile);
}
<|endoftext|> |
<commit_before>#include <boost/thread.hpp>
#include <ir/index_manager/index/IndexMergeManager.h>
#include <ir/index_manager/index/GPartitionMerger.h>
#include <ir/index_manager/index/DefaultMerger.h>
#include <ir/index_manager/index/DBTMerger.h>
#include <ir/index_manager/index/OfflineIndexMerger.h>
#include <ir/index_manager/index/IndexReader.h>
NS_IZENELIB_IR_BEGIN
namespace indexmanager{
IndexMergeManager::IndexMergeManager(Indexer* pIndexer)
:pIndexer_(pIndexer)
{
pBarrelsInfo_ = pIndexer_->getBarrelsInfo();
if(!strcasecmp(pIndexer_->pConfigurationManager_->mergeStrategy_.param_.c_str(),"realtime"))
indexMergers_[ONLINE] = new DBTMerger(pIndexer_);
else
indexMergers_[ONLINE] = new DefaultMerger(pIndexer_);
indexMergers_[OFFLINE] = new OfflineIndexMerger(pIndexer_, pBarrelsInfo_->getBarrelCount());
}
IndexMergeManager::~IndexMergeManager()
{
}
void IndexMergeManager::run()
{
mergethread_.reset(new boost::thread(boost::bind(&IndexMergeManager::mergeIndex, this)));
mergethread_->detach();
}
void IndexMergeManager::stop()
{
tasks_.clear();
MergeOP op;
op.opType = NOOP;
tasks_.push(op);
mergethread_->join();
for(std::map<MergeOPType, IndexMerger*>::iterator iter = indexMergers_.begin();
iter != indexMergers_.end(); ++iter)
delete iter->second;
}
void IndexMergeManager::triggerMerge(BarrelInfo* pBarrelInfo)
{
MergeOP op;
op.opType = ONLINE;
op.pBarrelInfo = pBarrelInfo;
tasks_.push(op);
}
void IndexMergeManager::mergeIndex()
{
while(true)
{
MergeOP op;
tasks_.pop(op);
switch(op.opType)
{
case ONLINE:
{
IndexMerger* pIndexMerger = indexMergers_[op.opType];
pIndexMerger->addToMerge(pBarrelsInfo_, op.pBarrelInfo);
}
break;
case FINISH:
{
IndexMerger* pIndexMerger = indexMergers_[ONLINE];
pIndexMerger->endMerge();
BarrelInfo* pBaInfo;
pBarrelsInfo_->startIterator();
while (pBarrelsInfo_->hasNext())
{
pBaInfo = pBarrelsInfo_->next();
pBaInfo->setSearchable(true);
}
pBarrelsInfo_->setLock(true);
pIndexMerger->updateBarrels(pBarrelsInfo_);
pBarrelsInfo_->write(pIndexer_->getDirectory());
pBarrelsInfo_->setLock(false);
}
break;
case OFFLINE:
{
OfflineIndexMerger* pIndexMerger = reinterpret_cast<OfflineIndexMerger*>(indexMergers_[op.opType]);
pIndexMerger->setBarrels(pBarrelsInfo_->getBarrelCount());
if(pIndexer_->getIndexReader()->getDocFilter())
pIndexMerger->setDocFilter(pIndexer_->getIndexReader()->getDocFilter());
pIndexMerger->merge(pBarrelsInfo_);
pIndexer_->getIndexReader()->delDocFilter();
pIndexMerger->setDocFilter(NULL);
}
break;
case NOOP:
return;
}
}
}
void IndexMergeManager::optimizeIndex()
{
MergeOP op;
if(tasks_.empty())
{
op.opType = OFFLINE;
}
else
{
op.opType = FINISH;
}
tasks_.push(op);
}
}
NS_IZENELIB_IR_END
<commit_msg>clear<commit_after>#include <boost/thread.hpp>
#include <ir/index_manager/index/IndexMergeManager.h>
#include <ir/index_manager/index/GPartitionMerger.h>
#include <ir/index_manager/index/DefaultMerger.h>
#include <ir/index_manager/index/DBTMerger.h>
#include <ir/index_manager/index/OfflineIndexMerger.h>
#include <ir/index_manager/index/IndexReader.h>
NS_IZENELIB_IR_BEGIN
namespace indexmanager{
IndexMergeManager::IndexMergeManager(Indexer* pIndexer)
:pIndexer_(pIndexer)
{
pBarrelsInfo_ = pIndexer_->getBarrelsInfo();
if(!strcasecmp(pIndexer_->pConfigurationManager_->mergeStrategy_.param_.c_str(),"realtime"))
indexMergers_[ONLINE] = new DBTMerger(pIndexer_);
else
indexMergers_[ONLINE] = new DefaultMerger(pIndexer_);
indexMergers_[OFFLINE] = new OfflineIndexMerger(pIndexer_, pBarrelsInfo_->getBarrelCount());
}
IndexMergeManager::~IndexMergeManager()
{
}
void IndexMergeManager::run()
{
mergethread_.reset(new boost::thread(boost::bind(&IndexMergeManager::mergeIndex, this)));
mergethread_->detach();
}
void IndexMergeManager::stop()
{
tasks_.clear();
MergeOP op;
op.opType = NOOP;
tasks_.push(op);
mergethread_->join();
for(std::map<MergeOPType, IndexMerger*>::iterator iter = indexMergers_.begin();
iter != indexMergers_.end(); ++iter)
delete iter->second;
}
void IndexMergeManager::triggerMerge(BarrelInfo* pBarrelInfo)
{
MergeOP op;
op.opType = ONLINE;
op.pBarrelInfo = pBarrelInfo;
tasks_.push(op);
}
void IndexMergeManager::mergeIndex()
{
while(true)
{
MergeOP op;
tasks_.pop(op);
switch(op.opType)
{
case ONLINE:
{
IndexMerger* pIndexMerger = indexMergers_[op.opType];
pIndexMerger->addToMerge(pBarrelsInfo_, op.pBarrelInfo);
}
break;
case FINISH:
{
IndexMerger* pIndexMerger = indexMergers_[ONLINE];
pIndexMerger->endMerge();
BarrelInfo* pBaInfo;
pBarrelsInfo_->startIterator();
while (pBarrelsInfo_->hasNext())
{
pBaInfo = pBarrelsInfo_->next();
pBaInfo->setSearchable(true);
}
pBarrelsInfo_->setLock(true);
pIndexMerger->updateBarrels(pBarrelsInfo_);
pBarrelsInfo_->write(pIndexer_->getDirectory());
pBarrelsInfo_->setLock(false);
}
break;
case OFFLINE:
{
OfflineIndexMerger* pIndexMerger = reinterpret_cast<OfflineIndexMerger*>(indexMergers_[op.opType]);
pIndexMerger->setBarrels(pBarrelsInfo_->getBarrelCount());
if(pIndexer_->getIndexReader()->getDocFilter())
pIndexMerger->setDocFilter(pIndexer_->getIndexReader()->getDocFilter());
pIndexMerger->merge(pBarrelsInfo_);
pIndexer_->getIndexReader()->delDocFilter();
pIndexMerger->setDocFilter(NULL);
BarrelInfo* pBaInfo;
pBarrelsInfo_->startIterator();
while (pBarrelsInfo_->hasNext())
{
pBaInfo = pBarrelsInfo_->next();
pBaInfo->setSearchable(true);
}
pBarrelsInfo_->setLock(true);
pIndexMerger->updateBarrels(pBarrelsInfo_);
pBarrelsInfo_->write(pIndexer_->getDirectory());
pBarrelsInfo_->setLock(false);
}
break;
case NOOP:
return;
}
}
}
void IndexMergeManager::optimizeIndex()
{
MergeOP op;
if(tasks_.empty())
{
op.opType = OFFLINE;
}
else
{
op.opType = FINISH;
}
tasks_.push(op);
}
}
NS_IZENELIB_IR_END
<|endoftext|> |
<commit_before>
#include "InverseKinematicsStudy.h"
#include "OpenSenseUtilities.h"
#include <OpenSim/Common/IO.h>
#include <OpenSim/Common/TimeSeriesTable.h>
#include <OpenSim/Common/TableSource.h>
#include <OpenSim/Common/STOFileAdapter.h>
#include <OpenSim/Common/TRCFileAdapter.h>
#include <OpenSim/Common/Reporter.h>
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Simulation/Model/PhysicalOffsetFrame.h>
#include <OpenSim/Simulation/InverseKinematicsSolver.h>
#include <OpenSim/Simulation/OrientationsReference.h>
#include "ExperimentalMarker.h"
#include "ExperimentalFrame.h"
using namespace OpenSim;
using namespace SimTK;
using namespace std;
InverseKinematicsStudy::InverseKinematicsStudy()
{
constructProperties();
}
InverseKinematicsStudy::InverseKinematicsStudy(const std::string& setupFile)
: Object(setupFile, true)
{
constructProperties();
updateFromXMLDocument();
}
InverseKinematicsStudy::~InverseKinematicsStudy()
{
}
void InverseKinematicsStudy::constructProperties()
{
constructProperty_accuracy(1e-6);
constructProperty_constraint_weight(Infinity);
Array<double> range{ Infinity, 2};
constructProperty_time_range(range);
constructProperty_sensor_to_opensim_rotations(
SimTK::Vec3(-SimTK_PI / 2, 0, 0));
constructProperty_model_file_name("");
constructProperty_marker_file_name("");
constructProperty_orientations_file_name("");
constructProperty_results_directory("");
}
void InverseKinematicsStudy::
previewExperimentalData(const TimeSeriesTableVec3& markers,
const TimeSeriesTable_<SimTK::Rotation>& orientations) const
{
Model previewWorld;
// Load the marker data into a TableSource that has markers
// as its output which each markers occupying its own channel
TableSourceVec3* markersSource = new TableSourceVec3(markers);
// Add the markersSource Component to the model
previewWorld.addComponent(markersSource);
// Get the underlying Table backing the the marker Source so we
// know how many markers we have and their names
const auto& markerData = markersSource->getTable();
auto& times = markerData.getIndependentColumn();
auto startEnd = getTimeRangeInUse(times);
// Create an ExperimentalMarker Component for every column in the markerData
for (int i = 0; i < int(markerData.getNumColumns()) ; ++i) {
auto marker = new ExperimentalMarker();
marker->setName(markerData.getColumnLabel(i));
// markers are owned by the model
previewWorld.addComponent(marker);
// the time varying location of the marker comes from the markersSource
// Component
marker->updInput("location_in_ground").connect(
markersSource->getOutput("column").getChannel(markerData.getColumnLabel(i)));
}
previewWorld.setUseVisualizer(true);
SimTK::State& state = previewWorld.initSystem();
state.updTime() = times[0];
previewWorld.realizePosition(state);
previewWorld.getVisualizer().show(state);
char c;
std::cout << "press any key to visualize experimental marker data ..." << std::endl;
std::cin >> c;
for (size_t j =startEnd[0]; j <= startEnd[1]; j=j+10) {
std::cout << "time: " << times[j] << "s" << std::endl;
state.setTime(times[j]);
previewWorld.realizePosition(state);
previewWorld.getVisualizer().show(state);
}
}
void InverseKinematicsStudy::
runInverseKinematicsWithOrientationsFromFile(Model& model,
const std::string& orientationsFileName,
bool visualizeResults)
{
// Add a reporter to get IK computed coordinate values out
TableReporter* ikReporter = new TableReporter();
ikReporter->setName("ik_reporter");
auto coordinates = model.updComponentList<Coordinate>();
// Hookup reporter inputs to the individual coordinate outputs
// and lock coordinates that are translational since they cannot be
for (auto& coord : coordinates) {
ikReporter->updInput("inputs").connect(
coord.getOutput("value"), coord.getName());
if(coord.getMotionType() == Coordinate::Translational) {
coord.setDefaultLocked(true);
}
}
model.addComponent(ikReporter);
TimeSeriesTable_<SimTK::Quaternion> quatTable(orientationsFileName);
std::cout << "Loading orientations as quaternions from "
<< orientationsFileName << std::endl;
// Convert to OpenSim Frame
const SimTK::Vec3& rotations = get_sensor_to_opensim_rotations();
SimTK::Rotation sensorToOpenSim = SimTK::Rotation(
SimTK::BodyOrSpaceType::SpaceRotationSequence,
rotations[0], SimTK::XAxis, rotations[1], SimTK::YAxis,
rotations[2], SimTK::ZAxis);
// Rotate data so Y-Axis is up
OpenSenseUtilities::rotateOrientationTable(quatTable, sensorToOpenSim);
auto startEnd = getTimeRangeInUse(quatTable.getIndependentColumn());
TimeSeriesTable_<SimTK::Rotation> orientationsData =
OpenSenseUtilities::convertQuaternionsToRotations(quatTable);
// Trim orientation data based on User input times
orientationsData.trim(get_time_range(0),get_time_range(1));
OrientationsReference oRefs(orientationsData);
MarkersReference mRefs{};
SimTK::Array_<CoordinateReference> coordinateReferences;
// visualize for debugging
if (visualizeResults)
model.setUseVisualizer(true);
SimTK::State& s0 = model.initSystem();
double t0 = s0.getTime();
// create the solver given the input data
const double accuracy = 1e-4;
InverseKinematicsSolver ikSolver(model, mRefs, oRefs,
coordinateReferences);
ikSolver.setAccuracy(accuracy);
auto& times = oRefs.getTimes();
s0.updTime() = times[0];
ikSolver.assemble(s0);
if (visualizeResults) {
model.getVisualizer().show(s0);
model.getVisualizer().getSimbodyVisualizer().setShowSimTime(true);
}
for (auto time : times) {
s0.updTime() = time;
ikSolver.track(s0);
if (visualizeResults)
model.getVisualizer().show(s0);
else
cout << "Solved frame at time: " << time << endl;
// realize to report to get reporter to pull values from model
model.realizeReport(s0);
}
auto report = ikReporter->getTable();
auto eix = orientationsFileName.rfind(".");
auto stix = orientationsFileName.rfind("/") + 1;
IO::makeDir(get_results_directory());
std::string outName = "ik_" + orientationsFileName.substr(stix, eix-stix);
std::string outputFile = get_results_directory() + "/" + outName;
// Convert to degrees to compare with marker-based IK
// but only for rotational coordinates
model.getSimbodyEngine().convertRadiansToDegrees(report);
report.updTableMetaData().setValueForKey<string>("name", outName);
STOFileAdapter_<double>::write(report, outputFile + ".mot");
std::cout << "Wrote IK with IMU tracking results to: '" <<
outputFile << "'." << std::endl;
}
// main driver
bool InverseKinematicsStudy::run(bool visualizeResults)
{
if (_model.empty()) {
_model.reset(new Model(get_model_file_name()));
}
runInverseKinematicsWithOrientationsFromFile(*_model,
get_orientations_file_name(),
visualizeResults);
return true;
}
SimTK::Array_<int> InverseKinematicsStudy::getTimeRangeInUse(
const std::vector<double>& times ) const
{
int nt = static_cast<int>(times.size());
int startIx = 0;
int endIx = nt-1;
for (int i = 0; i < nt; ++i) {
if (times[i] <= get_time_range(0)) {
startIx = i;
}
else {
break;
}
}
for (int i = nt - 1; i > 0; --i) {
if (times[i] >= get_time_range(1)) {
endIx= i;
}
else {
break;
}
}
SimTK::Array_<int> retArray;
retArray.push_back(startIx);
retArray.push_back(endIx);
return retArray;
}
TimeSeriesTable_<SimTK::Vec3>
InverseKinematicsStudy::loadMarkersFile(const std::string& markerFile)
{
TimeSeriesTable_<Vec3> markers(markerFile);
std::cout << markerFile << " loaded " << markers.getNumColumns() << " markers "
<< " and " << markers.getNumRows() << " rows of data." << std::endl;
if (markers.hasTableMetaDataKey("Units")) {
std::cout << markerFile << " has Units meta data." << std::endl;
auto& value = markers.getTableMetaData().getValueForKey("Units");
std::cout << markerFile << " Units are " << value.getValue<std::string>() << std::endl;
if (value.getValue<std::string>() == "mm") {
std::cout << "Marker data in mm, converting to m." << std::endl;
for (size_t i = 0; i < markers.getNumRows(); ++i) {
markers.updRowAtIndex(i) *= 0.001;
}
markers.updTableMetaData().removeValueForKey("Units");
markers.updTableMetaData().setValueForKey<std::string>("Units", "m");
}
}
auto& value = markers.getTableMetaData().getValueForKey("Units");
std::cout << markerFile << " Units are " << value.getValue<std::string>() << std::endl;
return markers;
}
<commit_msg>updated time range setting<commit_after>
#include "InverseKinematicsStudy.h"
#include "OpenSenseUtilities.h"
#include <OpenSim/Common/IO.h>
#include <OpenSim/Common/TimeSeriesTable.h>
#include <OpenSim/Common/TableSource.h>
#include <OpenSim/Common/STOFileAdapter.h>
#include <OpenSim/Common/TRCFileAdapter.h>
#include <OpenSim/Common/Reporter.h>
#include <OpenSim/Simulation/Model/Model.h>
#include <OpenSim/Simulation/Model/PhysicalOffsetFrame.h>
#include <OpenSim/Simulation/InverseKinematicsSolver.h>
#include <OpenSim/Simulation/OrientationsReference.h>
#include "ExperimentalMarker.h"
#include "ExperimentalFrame.h"
using namespace OpenSim;
using namespace SimTK;
using namespace std;
InverseKinematicsStudy::InverseKinematicsStudy()
{
constructProperties();
}
InverseKinematicsStudy::InverseKinematicsStudy(const std::string& setupFile)
: Object(setupFile, true)
{
constructProperties();
updateFromXMLDocument();
}
InverseKinematicsStudy::~InverseKinematicsStudy()
{
}
void InverseKinematicsStudy::constructProperties()
{
constructProperty_accuracy(1e-6);
constructProperty_constraint_weight(Infinity);
Array<double> range{ Infinity, 2};
constructProperty_time_range(range);
constructProperty_sensor_to_opensim_rotations(
SimTK::Vec3(-SimTK_PI / 2, 0, 0));
constructProperty_model_file_name("");
constructProperty_marker_file_name("");
constructProperty_orientations_file_name("");
constructProperty_results_directory("");
}
void InverseKinematicsStudy::
previewExperimentalData(const TimeSeriesTableVec3& markers,
const TimeSeriesTable_<SimTK::Rotation>& orientations) const
{
Model previewWorld;
// Load the marker data into a TableSource that has markers
// as its output which each markers occupying its own channel
TableSourceVec3* markersSource = new TableSourceVec3(markers);
// Add the markersSource Component to the model
previewWorld.addComponent(markersSource);
// Get the underlying Table backing the the marker Source so we
// know how many markers we have and their names
const auto& markerData = markersSource->getTable();
auto& times = markerData.getIndependentColumn();
auto startEnd = getTimeRangeInUse(times);
// Create an ExperimentalMarker Component for every column in the markerData
for (int i = 0; i < int(markerData.getNumColumns()) ; ++i) {
auto marker = new ExperimentalMarker();
marker->setName(markerData.getColumnLabel(i));
// markers are owned by the model
previewWorld.addComponent(marker);
// the time varying location of the marker comes from the markersSource
// Component
marker->updInput("location_in_ground").connect(
markersSource->getOutput("column").getChannel(markerData.getColumnLabel(i)));
}
previewWorld.setUseVisualizer(true);
SimTK::State& state = previewWorld.initSystem();
state.updTime() = times[0];
previewWorld.realizePosition(state);
previewWorld.getVisualizer().show(state);
char c;
std::cout << "press any key to visualize experimental marker data ..." << std::endl;
std::cin >> c;
for (size_t j =startEnd[0]; j <= startEnd[1]; j=j+10) {
std::cout << "time: " << times[j] << "s" << std::endl;
state.setTime(times[j]);
previewWorld.realizePosition(state);
previewWorld.getVisualizer().show(state);
}
}
void InverseKinematicsStudy::
runInverseKinematicsWithOrientationsFromFile(Model& model,
const std::string& orientationsFileName,
bool visualizeResults)
{
// Add a reporter to get IK computed coordinate values out
TableReporter* ikReporter = new TableReporter();
ikReporter->setName("ik_reporter");
auto coordinates = model.updComponentList<Coordinate>();
// Hookup reporter inputs to the individual coordinate outputs
// and lock coordinates that are translational since they cannot be
for (auto& coord : coordinates) {
ikReporter->updInput("inputs").connect(
coord.getOutput("value"), coord.getName());
if(coord.getMotionType() == Coordinate::Translational) {
coord.setDefaultLocked(true);
}
}
model.addComponent(ikReporter);
TimeSeriesTable_<SimTK::Quaternion> quatTable(orientationsFileName);
std::cout << "Loading orientations as quaternions from "
<< orientationsFileName << std::endl;
// Convert to OpenSim Frame
const SimTK::Vec3& rotations = get_sensor_to_opensim_rotations();
SimTK::Rotation sensorToOpenSim = SimTK::Rotation(
SimTK::BodyOrSpaceType::SpaceRotationSequence,
rotations[0], SimTK::XAxis, rotations[1], SimTK::YAxis,
rotations[2], SimTK::ZAxis);
// Rotate data so Y-Axis is up
OpenSenseUtilities::rotateOrientationTable(quatTable, sensorToOpenSim);
auto startEnd = getTimeRangeInUse(quatTable.getIndependentColumn());
TimeSeriesTable_<SimTK::Rotation> orientationsData =
OpenSenseUtilities::convertQuaternionsToRotations(quatTable);
// Trim orientation data based on User input times
cout << startEnd[0] << endl;
cout << startEnd[1] << endl;
orientationsData.trim(startEnd[0],startEnd[1]);
OrientationsReference oRefs(orientationsData);
MarkersReference mRefs{};
SimTK::Array_<CoordinateReference> coordinateReferences;
// visualize for debugging
if (visualizeResults)
model.setUseVisualizer(true);
SimTK::State& s0 = model.initSystem();
double t0 = s0.getTime();
// create the solver given the input data
const double accuracy = 1e-4;
InverseKinematicsSolver ikSolver(model, mRefs, oRefs,
coordinateReferences);
ikSolver.setAccuracy(accuracy);
auto& times = oRefs.getTimes();
s0.updTime() = times[0];
ikSolver.assemble(s0);
if (visualizeResults) {
model.getVisualizer().show(s0);
model.getVisualizer().getSimbodyVisualizer().setShowSimTime(true);
}
for (auto time : times) {
s0.updTime() = time;
ikSolver.track(s0);
if (visualizeResults)
model.getVisualizer().show(s0);
else
cout << "Solved frame at time: " << time << endl;
// realize to report to get reporter to pull values from model
model.realizeReport(s0);
}
auto report = ikReporter->getTable();
auto eix = orientationsFileName.rfind(".");
auto stix = orientationsFileName.rfind("/") + 1;
IO::makeDir(get_results_directory());
std::string outName = "ik_" + orientationsFileName.substr(stix, eix-stix);
std::string outputFile = get_results_directory() + "/" + outName;
// Convert to degrees to compare with marker-based IK
// but only for rotational coordinates
model.getSimbodyEngine().convertRadiansToDegrees(report);
report.updTableMetaData().setValueForKey<string>("name", outName);
STOFileAdapter_<double>::write(report, outputFile + ".mot");
std::cout << "Wrote IK with IMU tracking results to: '" <<
outputFile << "'." << std::endl;
}
// main driver
bool InverseKinematicsStudy::run(bool visualizeResults)
{
if (_model.empty()) {
_model.reset(new Model(get_model_file_name()));
}
runInverseKinematicsWithOrientationsFromFile(*_model,
get_orientations_file_name(),
visualizeResults);
return true;
}
SimTK::Array_<int> InverseKinematicsStudy::getTimeRangeInUse(
const std::vector<double>& times ) const
{
int nt = static_cast<int>(times.size());
int startIx = 0;
int endIx = nt-1;
int startTime = times[startIx];
int endTime = times[endIx];
if (get_time_range(0)>get_time_range(1)){
throw std::invalid_argument( "Start time greater than End time" );
}
// Check and set the start time
if (get_time_range(0) != Infinity) {
// Check if User Specified time ranges are legal
if (get_time_range(0)<times[startIx]) {
throw std::invalid_argument( "Start time out of range" );
} else {
startTime = get_time_range(0);
}
}
// Check and set end time
if (get_time_range(1) != Infinity) {
// Check if User Specified time ranges are legal
if (get_time_range(1)>times[endIx]) {
throw std::invalid_argument( "End time out of range" );
} else {
endTime = get_time_range(1);
}
}
SimTK::Array_<int> retArray;
retArray.push_back(startTime);
retArray.push_back(endTime);
std::cout << "startTime::" << startTime << std::endl;
std::cout << "endTime::" << endTime << std::endl;
return retArray;
}
TimeSeriesTable_<SimTK::Vec3>
InverseKinematicsStudy::loadMarkersFile(const std::string& markerFile)
{
TimeSeriesTable_<Vec3> markers(markerFile);
std::cout << markerFile << " loaded " << markers.getNumColumns() << " markers "
<< " and " << markers.getNumRows() << " rows of data." << std::endl;
if (markers.hasTableMetaDataKey("Units")) {
std::cout << markerFile << " has Units meta data." << std::endl;
auto& value = markers.getTableMetaData().getValueForKey("Units");
std::cout << markerFile << " Units are " << value.getValue<std::string>() << std::endl;
if (value.getValue<std::string>() == "mm") {
std::cout << "Marker data in mm, converting to m." << std::endl;
for (size_t i = 0; i < markers.getNumRows(); ++i) {
markers.updRowAtIndex(i) *= 0.001;
}
markers.updTableMetaData().removeValueForKey("Units");
markers.updTableMetaData().setValueForKey<std::string>("Units", "m");
}
}
auto& value = markers.getTableMetaData().getValueForKey("Units");
std::cout << markerFile << " Units are " << value.getValue<std::string>() << std::endl;
return markers;
}
<|endoftext|> |
<commit_before>#include <cstddef>
#include <cstdlib>
#include <tightdb.hpp>
using namespace std;
using namespace tightdb;
// @@Example: ex_cpp_group_constructor_memory @@
TIGHTDB_TABLE_2(PeopleTable,
name, String,
age, Int)
void func(const char* data, size_t size)
{
Group g(data, size);
PeopleTable::Ref table = g.get_table<PeopleTable>("people");
table.add("Mary", 14);
table.add("Joe", 17);
table.add("Jack", 22);
g.write("people.tightdb");
}
int main()
{
Group g;
size_t size;
char* data = g.write_to_mem(size);
if (!data) return 1;
try {
func(data, size);
}
catch (...) {
free(data);
throw;
}
free(data);
}
// @@EndExample@@
<commit_msg>Fixes for: Examples created for documentation of Group constructors<commit_after>#include <cstddef>
#include <cstdlib>
#include <tightdb.hpp>
using namespace std;
using namespace tightdb;
// @@Example: ex_cpp_group_constructor_memory @@
TIGHTDB_TABLE_2(PeopleTable,
name, String,
age, Int)
void func(const char* data, size_t size)
{
Group g(data, size);
PeopleTable::Ref table = g.get_table<PeopleTable>("people");
table.add("Mary", 14);
table.add("Joe", 17);
table.add("Jack", 22);
g.write("people.tightdb");
}
// @@EndExample@@
int main()
{
Group g;
size_t size;
char* data = g.write_to_mem(size);
if (!data) return 1;
try {
func(data, size);
}
catch (...) {
free(data);
throw;
}
free(data);
}
<|endoftext|> |
<commit_before>#include <map>
#include <vector>
#include <thread>
#include <chrono>
#include <mutex>
#include <set>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <fcntl.h>
#include "mruset.h"
#include "utils.h"
#include "connection.h"
#include "rpcclient.h"
class MempoolClient : public Connection {
public:
MempoolClient(int fd_in, std::string hostIn) : Connection(fd_in, hostIn, NULL) { construction_done(); }
void send_pool(std::set<std::vector<unsigned char> >::const_iterator mempool_begin, const std::set<std::vector<unsigned char> >::const_iterator mempool_end, int send_mutex=0) {
while (mempool_begin != mempool_end) {
assert(mempool_begin->size() == 32);
do_send_bytes((const char*) &(*mempool_begin)[0], 32, send_mutex);
mempool_begin++;
}
}
private:
void net_process(const std::function<void(std::string)>& disconnect) {
char buf[1];
ssize_t res = read_all(buf, 1);
if (res == 1)
disconnect("Read bytes from mempool client?");
else
disconnect("Socket error reading bytes from mempool client");
}
};
int main(int argc, char** argv) {
if (argc != 3 && argc != 4) {
printf("USAGE: %s listen_port local_port [::ffff:whitelisted prefix string]\n", argv[0]);
return -1;
}
int listen_fd;
struct sockaddr_in6 addr;
if ((listen_fd = socket(AF_INET6, SOCK_STREAM, 0)) < 0) {
printf("Failed to create socket\n");
return -1;
}
memset(&addr, 0, sizeof(addr));
addr.sin6_family = AF_INET6;
addr.sin6_addr = in6addr_any;
addr.sin6_port = htons(std::stoul(argv[1]));
int reuse = 1;
if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) ||
bind(listen_fd, (struct sockaddr *) &addr, sizeof(addr)) < 0 ||
listen(listen_fd, 3) < 0) {
printf("Failed to bind port: %s\n", strerror(errno));
return -1;
}
std::mutex map_mutex;
std::map<std::string, MempoolClient*> clientMap;
std::mutex mempool_mutex;
std::chrono::steady_clock::time_point last_mempool_request(std::chrono::steady_clock::time_point::min());
mruset<std::vector<unsigned char> > mempool(MAX_TXN_IN_FAS);
RPCClient rpcTrustedP2P("127.0.0.1", std::stoul(argv[2]),
[&](std::vector<std::vector<unsigned char> >& txn_list) {
std::set<std::vector<unsigned char> > new_txn;
{
std::lock_guard<std::mutex> lock(mempool_mutex);
// 50 txn @ 10k/tx per sec == 500Kbps
int txn_gathered = 0, txn_to_gather = 50*to_millis_lu(std::chrono::steady_clock::now() - last_mempool_request)/1000;
last_mempool_request = std::chrono::steady_clock::now();
for (const std::vector<unsigned char>& txn : txn_list) {
if (mempool.insert(txn).second) {
new_txn.insert(txn);
txn_gathered++;
}
if (txn_gathered >= txn_to_gather)
return;
}
}
std::lock_guard<std::mutex> lock(map_mutex);
for (auto it = clientMap.begin(); it != clientMap.end(); it++) {
if (!it->second->getDisconnectFlags())
it->second->send_pool(new_txn.begin(), new_txn.end());
}
});
std::thread([&](void) {
while (true) {
std::this_thread::sleep_for(std::chrono::milliseconds(500)); // Implicit new-connection rate-limit
{
std::lock_guard<std::mutex> lock(map_mutex);
for (auto it = clientMap.begin(); it != clientMap.end();) {
if (it->second->getDisconnectFlags() & DISCONNECT_COMPLETE) {
fprintf(stderr, "%lld: Culled %s, have %lu relay clients\n", (long long) time(NULL), it->first.c_str(), clientMap.size() - 1);
delete it->second;
clientMap.erase(it++);
} else
it++;
}
}
rpcTrustedP2P.maybe_get_txn_for_block();
}
}).detach();
std::string droppostfix(".uptimerobot.com");
std::string whitelistprefix("NOT AN ADDRESS");
if (argc == 4)
whitelistprefix = argv[3];
socklen_t addr_size = sizeof(addr);
while (true) {
int new_fd;
if ((new_fd = accept(listen_fd, (struct sockaddr *) &addr, &addr_size)) < 0) {
printf("Failed to select (%d: %s)\n", new_fd, strerror(errno));
return -1;
}
std::string host = gethostname(&addr);
std::lock_guard<std::mutex> lock(map_mutex);
if ((clientMap.count(host) && host.compare(0, whitelistprefix.length(), whitelistprefix) != 0) ||
(host.length() > droppostfix.length() && !host.compare(host.length() - droppostfix.length(), droppostfix.length(), droppostfix))) {
if (clientMap.count(host)) {
const auto& client = clientMap[host];
fprintf(stderr, "%lld: Got duplicate connection from %s (original's disconnect status: %d)\n", (long long) time(NULL), host.c_str(), client->getDisconnectFlags());
}
close(new_fd);
} else {
if (host.compare(0, whitelistprefix.length(), whitelistprefix) == 0)
host += ":" + std::to_string(addr.sin6_port);
assert(clientMap.count(host) == 0);
MempoolClient* client = new MempoolClient(new_fd, host);
clientMap[host] = client;
fprintf(stderr, "%lld: New connection from %s, have %lu relay clients\n", (long long) time(NULL), host.c_str(), clientMap.size());
int send_mutex = client->get_send_mutex();
{
std::lock_guard<std::mutex> lock(mempool_mutex);
client->send_pool(mempool.begin(), mempool.end(), send_mutex);
}
client->release_send_mutex(send_mutex);
}
}
}
<commit_msg>Fix mempool server loop break<commit_after>#include <map>
#include <vector>
#include <thread>
#include <chrono>
#include <mutex>
#include <set>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <fcntl.h>
#include "mruset.h"
#include "utils.h"
#include "connection.h"
#include "rpcclient.h"
class MempoolClient : public Connection {
public:
MempoolClient(int fd_in, std::string hostIn) : Connection(fd_in, hostIn, NULL) { construction_done(); }
void send_pool(std::set<std::vector<unsigned char> >::const_iterator mempool_begin, const std::set<std::vector<unsigned char> >::const_iterator mempool_end, int send_mutex=0) {
while (mempool_begin != mempool_end) {
assert(mempool_begin->size() == 32);
do_send_bytes((const char*) &(*mempool_begin)[0], 32, send_mutex);
mempool_begin++;
}
}
private:
void net_process(const std::function<void(std::string)>& disconnect) {
char buf[1];
ssize_t res = read_all(buf, 1);
if (res == 1)
disconnect("Read bytes from mempool client?");
else
disconnect("Socket error reading bytes from mempool client");
}
};
int main(int argc, char** argv) {
if (argc != 3 && argc != 4) {
printf("USAGE: %s listen_port local_port [::ffff:whitelisted prefix string]\n", argv[0]);
return -1;
}
int listen_fd;
struct sockaddr_in6 addr;
if ((listen_fd = socket(AF_INET6, SOCK_STREAM, 0)) < 0) {
printf("Failed to create socket\n");
return -1;
}
memset(&addr, 0, sizeof(addr));
addr.sin6_family = AF_INET6;
addr.sin6_addr = in6addr_any;
addr.sin6_port = htons(std::stoul(argv[1]));
int reuse = 1;
if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) ||
bind(listen_fd, (struct sockaddr *) &addr, sizeof(addr)) < 0 ||
listen(listen_fd, 3) < 0) {
printf("Failed to bind port: %s\n", strerror(errno));
return -1;
}
std::mutex map_mutex;
std::map<std::string, MempoolClient*> clientMap;
std::mutex mempool_mutex;
std::chrono::steady_clock::time_point last_mempool_request(std::chrono::steady_clock::time_point::min());
mruset<std::vector<unsigned char> > mempool(MAX_TXN_IN_FAS);
RPCClient rpcTrustedP2P("127.0.0.1", std::stoul(argv[2]),
[&](std::vector<std::vector<unsigned char> >& txn_list) {
std::set<std::vector<unsigned char> > new_txn;
{
std::lock_guard<std::mutex> lock(mempool_mutex);
// 50 txn @ 10k/tx per sec == 500Kbps
int txn_gathered = 0, txn_to_gather = 50*to_millis_lu(std::chrono::steady_clock::now() - last_mempool_request)/1000;
last_mempool_request = std::chrono::steady_clock::now();
for (const std::vector<unsigned char>& txn : txn_list) {
if (mempool.insert(txn).second) {
new_txn.insert(txn);
txn_gathered++;
}
if (txn_gathered >= txn_to_gather)
break;
}
}
std::lock_guard<std::mutex> lock(map_mutex);
for (auto it = clientMap.begin(); it != clientMap.end(); it++) {
if (!it->second->getDisconnectFlags())
it->second->send_pool(new_txn.begin(), new_txn.end());
}
});
std::thread([&](void) {
while (true) {
std::this_thread::sleep_for(std::chrono::milliseconds(500)); // Implicit new-connection rate-limit
{
std::lock_guard<std::mutex> lock(map_mutex);
for (auto it = clientMap.begin(); it != clientMap.end();) {
if (it->second->getDisconnectFlags() & DISCONNECT_COMPLETE) {
fprintf(stderr, "%lld: Culled %s, have %lu relay clients\n", (long long) time(NULL), it->first.c_str(), clientMap.size() - 1);
delete it->second;
clientMap.erase(it++);
} else
it++;
}
}
rpcTrustedP2P.maybe_get_txn_for_block();
}
}).detach();
std::string droppostfix(".uptimerobot.com");
std::string whitelistprefix("NOT AN ADDRESS");
if (argc == 4)
whitelistprefix = argv[3];
socklen_t addr_size = sizeof(addr);
while (true) {
int new_fd;
if ((new_fd = accept(listen_fd, (struct sockaddr *) &addr, &addr_size)) < 0) {
printf("Failed to select (%d: %s)\n", new_fd, strerror(errno));
return -1;
}
std::string host = gethostname(&addr);
std::lock_guard<std::mutex> lock(map_mutex);
if ((clientMap.count(host) && host.compare(0, whitelistprefix.length(), whitelistprefix) != 0) ||
(host.length() > droppostfix.length() && !host.compare(host.length() - droppostfix.length(), droppostfix.length(), droppostfix))) {
if (clientMap.count(host)) {
const auto& client = clientMap[host];
fprintf(stderr, "%lld: Got duplicate connection from %s (original's disconnect status: %d)\n", (long long) time(NULL), host.c_str(), client->getDisconnectFlags());
}
close(new_fd);
} else {
if (host.compare(0, whitelistprefix.length(), whitelistprefix) == 0)
host += ":" + std::to_string(addr.sin6_port);
assert(clientMap.count(host) == 0);
MempoolClient* client = new MempoolClient(new_fd, host);
clientMap[host] = client;
fprintf(stderr, "%lld: New connection from %s, have %lu relay clients\n", (long long) time(NULL), host.c_str(), clientMap.size());
int send_mutex = client->get_send_mutex();
{
std::lock_guard<std::mutex> lock(mempool_mutex);
client->send_pool(mempool.begin(), mempool.end(), send_mutex);
}
client->release_send_mutex(send_mutex);
}
}
}
<|endoftext|> |
<commit_before>#include "core/iallocator.h"
#include "core/binary_array.h"
#include "core/crc32.h"
#include "core/fs/file_system.h"
#include "core/fs/ifile.h"
#include "core/json_serializer.h"
#include "core/library.h"
#include "core/log.h"
#include "core/array.h"
#include "editor/world_editor.h"
#include "engine/engine.h"
#include "engine/iplugin.h"
#include "engine/plugin_manager.h"
#include "engine/lua_wrapper.h"
#include "universe/universe.h"
static const uint32_t SCRIPT_HASH = crc32("script");
namespace Lumix
{
class LuaScriptSystemImpl;
void registerEngineLuaAPI(Engine&, Universe&, lua_State* L);
void registerPhysicsLuaAPI(Engine&, Universe&, lua_State* L);
static const uint32_t LUA_SCRIPT_HASH = crc32("lua_script");
class LuaScriptSystem : public IPlugin
{
public:
Engine& m_engine;
BaseProxyAllocator m_allocator;
LuaScriptSystem(Engine& engine);
IAllocator& getAllocator();
virtual IScene* createScene(Universe& universe) override;
virtual void destroyScene(IScene* scene) override;
virtual bool create() override;
virtual void destroy() override;
virtual const char* getName() const override;
virtual void setWorldEditor(WorldEditor& editor) override;
};
class LuaScriptScene : public IScene
{
public:
LuaScriptScene(LuaScriptSystem& system, Engine& engine, Universe& universe)
: m_system(system)
, m_universe(universe)
, m_scripts(system.getAllocator())
, m_valid(system.getAllocator())
, m_global_state(nullptr)
{
if (system.m_engine.getWorldEditor())
{
system.m_engine.getWorldEditor()
->gameModeToggled()
.bind<LuaScriptScene, &LuaScriptScene::onGameModeToggled>(this);
}
}
~LuaScriptScene()
{
if (m_system.m_engine.getWorldEditor())
{
m_system.m_engine.getWorldEditor()
->gameModeToggled()
.unbind<LuaScriptScene, &LuaScriptScene::onGameModeToggled>(
this);
}
}
virtual Universe& getUniverse() override { return m_universe; }
void registerAPI(lua_State* L)
{
registerEngineLuaAPI(m_system.m_engine, m_universe, L);
if (m_system.m_engine.getPluginManager().getPlugin("physics"))
{
registerPhysicsLuaAPI(m_system.m_engine, m_universe, L);
}
}
void startGame()
{
m_global_state = luaL_newstate();
luaL_openlibs(m_global_state);
registerAPI(m_global_state);
for (int i = 0; i < m_scripts.size(); ++i)
{
if (m_valid[i])
{
Script& script = m_scripts[i];
FILE* fp = fopen(script.m_path.c_str(), "rb");
if (fp)
{
script.m_state = lua_newthread(m_global_state);
lua_pushinteger(script.m_state, script.m_entity);
lua_setglobal(script.m_state, "this");
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
fseek(fp, 0, SEEK_SET);
Array<char> content(m_system.getAllocator());
content.resize(size + 1);
fread(&content[0], 1, size, fp);
content[size] = '\0';
bool errors =
luaL_loadbuffer(script.m_state,
&content[0],
size,
script.m_path.c_str()) != LUA_OK;
errors =
errors ||
lua_pcall(script.m_state, 0, LUA_MULTRET, 0) != LUA_OK;
if (errors)
{
g_log_error.log("lua")
<< script.m_path.c_str() << ": "
<< lua_tostring(script.m_state, -1);
lua_pop(script.m_state, 1);
}
fclose(fp);
}
else
{
script.m_state = nullptr;
g_log_error.log("lua script") << "error loading "
<< script.m_path.c_str();
}
}
}
}
void stopGame() { lua_close(m_global_state); }
void onGameModeToggled(bool is_game_mode)
{
if (is_game_mode)
{
startGame();
}
else
{
stopGame();
}
}
virtual ComponentIndex createComponent(uint32_t type,
Entity entity) override
{
if (type == LUA_SCRIPT_HASH)
{
LuaScriptScene::Script& script = m_scripts.pushEmpty();
script.m_entity = entity;
script.m_path = "";
script.m_state = nullptr;
m_valid.push(true);
m_universe.addComponent(entity, type, this, m_scripts.size() - 1);
return m_scripts.size() - 1;
}
return INVALID_COMPONENT;
}
virtual void destroyComponent(ComponentIndex component,
uint32_t type) override
{
if (type == LUA_SCRIPT_HASH)
{
m_universe.destroyComponent(
Entity(m_scripts[component].m_entity), type, this, component);
m_valid[component] = false;
}
}
virtual void serialize(OutputBlob& serializer) override
{
serializer.write(m_scripts.size());
for (int i = 0; i < m_scripts.size(); ++i)
{
serializer.write(m_scripts[i].m_entity);
serializer.writeString(m_scripts[i].m_path.c_str());
serializer.write((bool)m_valid[i]);
}
}
virtual void deserialize(InputBlob& serializer) override
{
int len = serializer.read<int>();
m_scripts.resize(len);
m_valid.resize(len);
for (int i = 0; i < m_scripts.size(); ++i)
{
serializer.read(m_scripts[i].m_entity);
char tmp[LUMIX_MAX_PATH];
serializer.readString(tmp, LUMIX_MAX_PATH);
m_valid[i] = serializer.read<bool>();
m_scripts[i].m_path = tmp;
m_scripts[i].m_state = nullptr;
if (m_valid[i])
{
m_universe.addComponent(
Entity(m_scripts[i].m_entity), LUA_SCRIPT_HASH, this, i);
}
}
}
virtual IPlugin& getPlugin() const override { return m_system; }
virtual void update(float time_delta) override
{
if (lua_getglobal(m_global_state, "update") == LUA_TFUNCTION)
{
lua_pushnumber(m_global_state, time_delta);
if (lua_pcall(m_global_state, 1, 0, 0) != LUA_OK)
{
g_log_error.log("lua") << lua_tostring(m_global_state, -1);
}
}
}
virtual bool ownComponentType(uint32_t type) const override
{
return type == LUA_SCRIPT_HASH;
}
void getScriptPath(ComponentIndex cmp, string& path)
{
path = m_scripts[cmp].m_path.c_str();
}
void setScriptPath(ComponentIndex cmp, const string& path)
{
m_scripts[cmp].m_path = path;
}
private:
class Script
{
public:
Lumix::Path m_path;
int m_entity;
lua_State* m_state;
};
private:
LuaScriptSystem& m_system;
BinaryArray m_valid;
Array<Script> m_scripts;
lua_State* m_global_state;
Universe& m_universe;
};
LuaScriptSystem::LuaScriptSystem(Engine& engine)
: m_engine(engine)
, m_allocator(engine.getAllocator())
{
}
IAllocator& LuaScriptSystem::getAllocator()
{
return m_allocator;
}
IScene* LuaScriptSystem::createScene(Universe& universe)
{
return m_allocator.newObject<LuaScriptScene>(*this, m_engine, universe);
}
void LuaScriptSystem::destroyScene(IScene* scene)
{
m_allocator.deleteObject(scene);
}
bool LuaScriptSystem::create()
{
return true;
}
void LuaScriptSystem::setWorldEditor(WorldEditor& editor)
{
IAllocator& allocator = editor.getAllocator();
editor.registerComponentType("lua_script", "Lua script");
editor.registerProperty(
"lua_script",
allocator.newObject<FilePropertyDescriptor<LuaScriptScene>>(
"source",
(void (LuaScriptScene::*)(ComponentIndex, string&)) &
LuaScriptScene::getScriptPath,
&LuaScriptScene::setScriptPath,
"Lua (*.lua)",
allocator));
}
void LuaScriptSystem::destroy()
{
}
const char* LuaScriptSystem::getName() const
{
return "lua_script";
}
extern "C" LUMIX_LIBRARY_EXPORT IPlugin* createPlugin(Engine& engine)
{
return engine.getAllocator().newObject<LuaScriptSystem>(engine);
}
} // ~namespace Lumix
<commit_msg>fixed crash when there is not update function in lua<commit_after>#include "core/iallocator.h"
#include "core/binary_array.h"
#include "core/crc32.h"
#include "core/fs/file_system.h"
#include "core/fs/ifile.h"
#include "core/json_serializer.h"
#include "core/library.h"
#include "core/log.h"
#include "core/array.h"
#include "editor/world_editor.h"
#include "engine/engine.h"
#include "engine/iplugin.h"
#include "engine/plugin_manager.h"
#include "engine/lua_wrapper.h"
#include "universe/universe.h"
static const uint32_t SCRIPT_HASH = crc32("script");
namespace Lumix
{
class LuaScriptSystemImpl;
void registerEngineLuaAPI(Engine&, Universe&, lua_State* L);
void registerPhysicsLuaAPI(Engine&, Universe&, lua_State* L);
static const uint32_t LUA_SCRIPT_HASH = crc32("lua_script");
class LuaScriptSystem : public IPlugin
{
public:
Engine& m_engine;
BaseProxyAllocator m_allocator;
LuaScriptSystem(Engine& engine);
IAllocator& getAllocator();
virtual IScene* createScene(Universe& universe) override;
virtual void destroyScene(IScene* scene) override;
virtual bool create() override;
virtual void destroy() override;
virtual const char* getName() const override;
virtual void setWorldEditor(WorldEditor& editor) override;
};
class LuaScriptScene : public IScene
{
public:
LuaScriptScene(LuaScriptSystem& system, Engine& engine, Universe& universe)
: m_system(system)
, m_universe(universe)
, m_scripts(system.getAllocator())
, m_valid(system.getAllocator())
, m_global_state(nullptr)
{
if (system.m_engine.getWorldEditor())
{
system.m_engine.getWorldEditor()
->gameModeToggled()
.bind<LuaScriptScene, &LuaScriptScene::onGameModeToggled>(this);
}
}
~LuaScriptScene()
{
if (m_system.m_engine.getWorldEditor())
{
m_system.m_engine.getWorldEditor()
->gameModeToggled()
.unbind<LuaScriptScene, &LuaScriptScene::onGameModeToggled>(
this);
}
}
virtual Universe& getUniverse() override { return m_universe; }
void registerAPI(lua_State* L)
{
registerEngineLuaAPI(m_system.m_engine, m_universe, L);
if (m_system.m_engine.getPluginManager().getPlugin("physics"))
{
registerPhysicsLuaAPI(m_system.m_engine, m_universe, L);
}
}
void startGame()
{
m_global_state = luaL_newstate();
luaL_openlibs(m_global_state);
registerAPI(m_global_state);
for (int i = 0; i < m_scripts.size(); ++i)
{
if (m_valid[i])
{
Script& script = m_scripts[i];
FILE* fp = fopen(script.m_path.c_str(), "rb");
if (fp)
{
script.m_state = lua_newthread(m_global_state);
lua_pushinteger(script.m_state, script.m_entity);
lua_setglobal(script.m_state, "this");
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
fseek(fp, 0, SEEK_SET);
Array<char> content(m_system.getAllocator());
content.resize(size + 1);
fread(&content[0], 1, size, fp);
content[size] = '\0';
bool errors =
luaL_loadbuffer(script.m_state,
&content[0],
size,
script.m_path.c_str()) != LUA_OK;
errors =
errors ||
lua_pcall(script.m_state, 0, LUA_MULTRET, 0) != LUA_OK;
if (errors)
{
g_log_error.log("lua")
<< script.m_path.c_str() << ": "
<< lua_tostring(script.m_state, -1);
lua_pop(script.m_state, 1);
}
fclose(fp);
}
else
{
script.m_state = nullptr;
g_log_error.log("lua script") << "error loading "
<< script.m_path.c_str();
}
}
}
}
void stopGame() { lua_close(m_global_state); }
void onGameModeToggled(bool is_game_mode)
{
if (is_game_mode)
{
startGame();
}
else
{
stopGame();
}
}
virtual ComponentIndex createComponent(uint32_t type,
Entity entity) override
{
if (type == LUA_SCRIPT_HASH)
{
LuaScriptScene::Script& script = m_scripts.pushEmpty();
script.m_entity = entity;
script.m_path = "";
script.m_state = nullptr;
m_valid.push(true);
m_universe.addComponent(entity, type, this, m_scripts.size() - 1);
return m_scripts.size() - 1;
}
return INVALID_COMPONENT;
}
virtual void destroyComponent(ComponentIndex component,
uint32_t type) override
{
if (type == LUA_SCRIPT_HASH)
{
m_universe.destroyComponent(
Entity(m_scripts[component].m_entity), type, this, component);
m_valid[component] = false;
}
}
virtual void serialize(OutputBlob& serializer) override
{
serializer.write(m_scripts.size());
for (int i = 0; i < m_scripts.size(); ++i)
{
serializer.write(m_scripts[i].m_entity);
serializer.writeString(m_scripts[i].m_path.c_str());
serializer.write((bool)m_valid[i]);
}
}
virtual void deserialize(InputBlob& serializer) override
{
int len = serializer.read<int>();
m_scripts.resize(len);
m_valid.resize(len);
for (int i = 0; i < m_scripts.size(); ++i)
{
serializer.read(m_scripts[i].m_entity);
char tmp[LUMIX_MAX_PATH];
serializer.readString(tmp, LUMIX_MAX_PATH);
m_valid[i] = serializer.read<bool>();
m_scripts[i].m_path = tmp;
m_scripts[i].m_state = nullptr;
if (m_valid[i])
{
m_universe.addComponent(
Entity(m_scripts[i].m_entity), LUA_SCRIPT_HASH, this, i);
}
}
}
virtual IPlugin& getPlugin() const override { return m_system; }
virtual void update(float time_delta) override
{
if (lua_getglobal(m_global_state, "update") == LUA_TFUNCTION)
{
lua_pushnumber(m_global_state, time_delta);
if (lua_pcall(m_global_state, 1, 0, 0) != LUA_OK)
{
g_log_error.log("lua") << lua_tostring(m_global_state, -1);
}
}
else
{
lua_pop(m_global_state, 1);
}
}
virtual bool ownComponentType(uint32_t type) const override
{
return type == LUA_SCRIPT_HASH;
}
void getScriptPath(ComponentIndex cmp, string& path)
{
path = m_scripts[cmp].m_path.c_str();
}
void setScriptPath(ComponentIndex cmp, const string& path)
{
m_scripts[cmp].m_path = path;
}
private:
class Script
{
public:
Lumix::Path m_path;
int m_entity;
lua_State* m_state;
};
private:
LuaScriptSystem& m_system;
BinaryArray m_valid;
Array<Script> m_scripts;
lua_State* m_global_state;
Universe& m_universe;
};
LuaScriptSystem::LuaScriptSystem(Engine& engine)
: m_engine(engine)
, m_allocator(engine.getAllocator())
{
}
IAllocator& LuaScriptSystem::getAllocator()
{
return m_allocator;
}
IScene* LuaScriptSystem::createScene(Universe& universe)
{
return m_allocator.newObject<LuaScriptScene>(*this, m_engine, universe);
}
void LuaScriptSystem::destroyScene(IScene* scene)
{
m_allocator.deleteObject(scene);
}
bool LuaScriptSystem::create()
{
return true;
}
void LuaScriptSystem::setWorldEditor(WorldEditor& editor)
{
IAllocator& allocator = editor.getAllocator();
editor.registerComponentType("lua_script", "Lua script");
editor.registerProperty(
"lua_script",
allocator.newObject<FilePropertyDescriptor<LuaScriptScene>>(
"source",
(void (LuaScriptScene::*)(ComponentIndex, string&)) &
LuaScriptScene::getScriptPath,
&LuaScriptScene::setScriptPath,
"Lua (*.lua)",
allocator));
}
void LuaScriptSystem::destroy()
{
}
const char* LuaScriptSystem::getName() const
{
return "lua_script";
}
extern "C" LUMIX_LIBRARY_EXPORT IPlugin* createPlugin(Engine& engine)
{
return engine.getAllocator().newObject<LuaScriptSystem>(engine);
}
} // ~namespace Lumix
<|endoftext|> |
<commit_before>#ifndef VECMATH_HPP
#define VECMATH_HPP
#include <SFML/System.hpp>
#include <cmath>
namespace vecmath
{
const float pi = 3.1415926535897;
template<typename T>
T norm(const sf::Vector2<T>& a)
{
return std::sqrt(a.x*a.x + a.y*a.y);
}
template<typename T>
T dot(const sf::Vector2<T>& a, const sf::Vector2<T>& b)
{
return a.x*b.x + a.y*b.y;
}
template<typename T>
bool intersect(const sf::Vector2<T>& p0, const sf::Vector2<T>& p1,
const sf::Vector2<T>& q0, const sf::Vector2<T>& q1,
sf::Vector2<T>* intersection)
{
auto dp = p1 - p0;
auto dpt = sf::Vector2<T>(-dp.y, dp.x);
auto dq = q1 - q0;
auto dqt = sf::Vector2<T>(-dq.y, dq.x);
// dpt is orthogonal to p1-p0, so if dpt.dq = 0 then
// dp is parallel to dq and there's no intersection
if(std::abs(vecmath::dot(dpt, dq)) < 10e-5) return false;
T mu1 = vecmath::dot((p0 - q0), dpt) / vecmath::dot(dpt, dq);
T mu2 = vecmath::dot((q0 - p0), dqt) / vecmath::dot(dqt, dp);
// mu is parameter for Q
if(0 <= mu1 && mu1 <= 1 && 0 <= mu2 && mu2 <= 1)
{
intersection->x = q0.x + mu1 * (q1.x-q0.x);
intersection->y = q0.y + mu1 * (q1.y-q0.y);
return true;
}
else
{
return false;
}
}
}
#endif /* VECMATH_HPP */
<commit_msg>Allowed unbounded above line intersections<commit_after>#ifndef VECMATH_HPP
#define VECMATH_HPP
#include <SFML/System.hpp>
#include <cmath>
namespace vecmath
{
const float pi = 3.1415926535897;
template<typename T>
T norm(const sf::Vector2<T>& a)
{
return std::sqrt(a.x*a.x + a.y*a.y);
}
template<typename T>
T dot(const sf::Vector2<T>& a, const sf::Vector2<T>& b)
{
return a.x*b.x + a.y*b.y;
}
template<typename T>
bool intersect(const sf::Vector2<T>& p0, const sf::Vector2<T>& p1,
const sf::Vector2<T>& q0, const sf::Vector2<T>& q1,
sf::Vector2<T>* intersection, bool unboundAbove=false)
{
auto dp = p1 - p0;
auto dpt = sf::Vector2<T>(-dp.y, dp.x);
auto dq = q1 - q0;
auto dqt = sf::Vector2<T>(-dq.y, dq.x);
// dpt is orthogonal to p1-p0, so if dpt.dq = 0 then
// dp is parallel to dq and there's no intersection
if(std::abs(vecmath::dot(dpt, dq)) < 10e-5) return false;
T mu1 = vecmath::dot((p0 - q0), dpt) / vecmath::dot(dpt, dq);
T mu2 = vecmath::dot((q0 - p0), dqt) / vecmath::dot(dqt, dp);
// mu is parameter for Q
if(0 <= mu1 && 0 <= mu2 && (unboundAbove || (mu1 <= 1 && mu2 <= 1)))
{
intersection->x = q0.x + mu1 * (q1.x-q0.x);
intersection->y = q0.y + mu1 * (q1.y-q0.y);
return true;
}
else
{
return false;
}
}
}
#endif /* VECMATH_HPP */
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");
// Client version number
#define CLIENT_VERSION_SUFFIX "-hobo"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "60c7bb3"
# define GIT_COMMIT_DATE "Thu Oct 24 17:56:53 2013"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Update version.cpp<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");
// Client version number
#define CLIENT_VERSION_SUFFIX "-hobo"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "b3d0643"
# define GIT_COMMIT_DATE "Fri Nov 01 01:56:53 2013"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|> |
<commit_before>/* FOLLOWGATE - envelope follower controlling a gate
FOLLOWGATE uses the amplitude envelope of the modulator to control the
action of a gate applied to the carrier. The gate opens when the power
of the modulator rises above a threshold and closes when the power falls
below the threshold. The bottom of the gate can be adjusted (via the
<range> parameter) so that it sits flush against the "floor" or rides
above the floor, letting some signal through even when the gate is closed.
The carrier is supplied as the "left" channel, the modulator as the
"right" channel. (See below.)
p0 = output start time
p1 = input start time (must be 0 for aux bus -- see below)
p2 = duration
p3 = carrier amplitude multiplier *
p4 = modulator amplitude multiplier
p5 = power gauge window length (in samples; try 100)
p6 = smoothness -- how much to smooth the power gauge output (0-1; try .8)
p7 = attack time -- how long it takes the gate to fully open once the
modulator power rises above the threshold
p8 = release time -- how long it takes the gate to fully close once the
modulator power falls below the threshold
p9 = pan (in percent-to-left form: 0-1) [optional, default is .5]
p10 = power threshold [optional; if missing, must use gen 2] **
p11 = range [optional; if missing, must use gen 3] ***
p3 (carrier amp), p4 (modulator amp), p6 (smoothness), p7 (attack time),
p8 (release time), p9 (pan), p10 (threshold) and p11 (range) can
receive dynamic updates from a table or real-time control source.
NOTES:
- The "left" input channel comes from the bus with the lower number;
the "right" input channel from the bus with the higher number.
- Currently in RTcmix it's not possible for an instrument to take input
from both an "in" bus and an "aux in" bus at the same time. So, for
example, if you want the modulator to come from a microphone, which
must enter via an "in" bus, and the carrier to come from a WAVETABLE
instrument via an "aux" bus, then you must route the mic into the MIX
instrument as a way to convert it from "in" to "aux in". If you want
the carrier to come from a file, then it must first go through MIX
(or some other instrument) to send it into an aux bus. Since the
instrument is usually taking input from an aux bus, the input start
time for this instrument must be zero. The only exception would be if
you're taking the carrier and modulator signals from the left and right
channels of the same sound file.
- The envelope follower consists of a power gauge that measures the
average power of the modulator signal. The window length (p5) is the
number of samples to average. Large values (> 1000) track only gross
amplitude changes; small values (< 10) track very minute changes. If
the power level changes abruptly, as it does especially with long
windows, you'll hear zipper noise. Reduce this by increasing the
smoothness (p6). This applies a low-pass filter to the power gauge
signal, smoothing any abrupt changes.
- You'll probably always need to boost the modulator amplitude
multiplier (p4) beyond what you'd expect, because we're using the
RMS power of the modulator to affect the carrier, and this is always
lower than the peak amplitude of the modulator signal.
----
Notes about backward compatibility with pre-v4 scores:
* If an old-style gen table 1 is present, its values will be multiplied
by p3 (carrier amp), even if the latter is dynamic.
** If p10 is missing, you must use an old-style gen table 2 for the
power threshold curve.
*** If p11 is missing, you must use an old-style gen table 3 for the
range curve.
John Gibson <johgibso at indiana dot edu>, 1/5/03; rev for v4, JGG, 7/24/04
*/
//#define DEBUG
#include "FOLLOWGATE.h"
#include <float.h> // for FLT_MAX
/* ------------------------------------------------------------ FOLLOWGATE -- */
FOLLOWGATE :: FOLLOWGATE()
{
thresh_table = NULL;
range_table = NULL;
state = belowThreshold;
attack_time = release_time = -FLT_MAX;
}
/* ----------------------------------------------------------- ~FOLLOWGATE -- */
FOLLOWGATE :: ~FOLLOWGATE()
{
delete thresh_table;
delete range_table;
delete envelope;
}
/* -------------------------------------------------------------- pre_init -- */
int FOLLOWGATE :: pre_init(double p[], int n_args)
{
oneoverSR = 1.0 / SR;
return 0;
}
/* ------------------------------------------------------------- post_init -- */
int FOLLOWGATE :: post_init(double p[], int n_args)
{
if (n_args < 11) { // no p10 power threshold PField, must use gen table
double *function = floc(2);
if (function == NULL)
return die(instname(), "Either use the power threshold pfield (p10) "
"or make an old-style gen function in slot 2.");
int len = fsize(2);
thresh_table = new TableL(SR, getdur(), function, len);
}
if (n_args < 12) { // no p11 range PField, must use gen table
double *function = floc(3);
if (function == NULL)
return die(instname(), "Either use the range pfield (p11) "
"or make an old-style gen function in slot 3.");
int len = fsize(3);
range_table = new TableL(SR, getdur(), function, len);
}
envelope = new Envelope(SR);
return 0;
}
/* --------------------------------------------------------- update_params -- */
void FOLLOWGATE :: update_params(double p[])
{
if (p[7] != attack_time) {
attack_time = p[7];
if (attack_time < 0.0)
attack_time = 0.0;
attack_rate = attack_time ? oneoverSR / attack_time : 1.0;
}
if (p[8] != release_time) {
release_time = p[8];
if (release_time < 0.0)
release_time = 0.0;
release_rate = release_time ? oneoverSR / release_time : 1.0;
}
pctleft = nargs > 9 ? p[9] : 0.5; // default is center
if (nargs > 10)
threshold = p[10];
else
threshold = thresh_table->tick(currentFrame(), 1.0);
if (threshold < 0.0)
threshold = 0.0;
if (nargs > 11)
range = p[11];
else
range = range_table->tick(currentFrame(), 1.0);
if (range < 0.0)
range = 0.0;
if (state == belowThreshold) {
if (envelope->getState() == ENV_RAMPING)
envelope->setTarget(range);
else
envelope->setValue(range);
}
}
/* -------------------------------------------------------- process_sample -- */
float FOLLOWGATE :: process_sample(float sample, float power)
{
DPRINT1("%f\n", power);
if (power >= threshold) {
if (state == belowThreshold) {
state = aboveThreshold;
envelope->setRate(attack_rate);
envelope->keyOn();
}
}
else {
if (state == aboveThreshold) {
state = belowThreshold;
envelope->setRate(release_rate);
envelope->keyOff();
envelope->setTarget(range);
}
}
float env = envelope->tick();
DPRINT1("%f\n", env);
return sample * env;
}
/* -------------------------------------------------------- makeFOLLOWGATE -- */
Instrument *makeFOLLOWGATE()
{
FOLLOWGATE *inst;
inst = new FOLLOWGATE();
inst->set_bus_config("FOLLOWGATE");
return inst;
}
/* ------------------------------------------------------------- rtprofile -- */
void rtprofile()
{
RT_INTRO("FOLLOWGATE", makeFOLLOWGATE);
}
<commit_msg>Minor debug print change.<commit_after>/* FOLLOWGATE - envelope follower controlling a gate
FOLLOWGATE uses the amplitude envelope of the modulator to control the
action of a gate applied to the carrier. The gate opens when the power
of the modulator rises above a threshold and closes when the power falls
below the threshold. The bottom of the gate can be adjusted (via the
<range> parameter) so that it sits flush against the "floor" or rides
above the floor, letting some signal through even when the gate is closed.
The carrier is supplied as the "left" channel, the modulator as the
"right" channel. (See below.)
p0 = output start time
p1 = input start time (must be 0 for aux bus -- see below)
p2 = duration
p3 = carrier amplitude multiplier *
p4 = modulator amplitude multiplier
p5 = power gauge window length (in samples; try 100)
p6 = smoothness -- how much to smooth the power gauge output (0-1; try .8)
p7 = attack time -- how long it takes the gate to fully open once the
modulator power rises above the threshold
p8 = release time -- how long it takes the gate to fully close once the
modulator power falls below the threshold
p9 = pan (in percent-to-left form: 0-1) [optional, default is .5]
p10 = power threshold [optional; if missing, must use gen 2] **
p11 = range [optional; if missing, must use gen 3] ***
p3 (carrier amp), p4 (modulator amp), p6 (smoothness), p7 (attack time),
p8 (release time), p9 (pan), p10 (threshold) and p11 (range) can
receive dynamic updates from a table or real-time control source.
NOTES:
- The "left" input channel comes from the bus with the lower number;
the "right" input channel from the bus with the higher number.
- Currently in RTcmix it's not possible for an instrument to take input
from both an "in" bus and an "aux in" bus at the same time. So, for
example, if you want the modulator to come from a microphone, which
must enter via an "in" bus, and the carrier to come from a WAVETABLE
instrument via an "aux" bus, then you must route the mic into the MIX
instrument as a way to convert it from "in" to "aux in". If you want
the carrier to come from a file, then it must first go through MIX
(or some other instrument) to send it into an aux bus. Since the
instrument is usually taking input from an aux bus, the input start
time for this instrument must be zero. The only exception would be if
you're taking the carrier and modulator signals from the left and right
channels of the same sound file.
- The envelope follower consists of a power gauge that measures the
average power of the modulator signal. The window length (p5) is the
number of samples to average. Large values (> 1000) track only gross
amplitude changes; small values (< 10) track very minute changes. If
the power level changes abruptly, as it does especially with long
windows, you'll hear zipper noise. Reduce this by increasing the
smoothness (p6). This applies a low-pass filter to the power gauge
signal, smoothing any abrupt changes.
- You'll probably always need to boost the modulator amplitude
multiplier (p4) beyond what you'd expect, because we're using the
RMS power of the modulator to affect the carrier, and this is always
lower than the peak amplitude of the modulator signal.
----
Notes about backward compatibility with pre-v4 scores:
* If an old-style gen table 1 is present, its values will be multiplied
by p3 (carrier amp), even if the latter is dynamic.
** If p10 is missing, you must use an old-style gen table 2 for the
power threshold curve.
*** If p11 is missing, you must use an old-style gen table 3 for the
range curve.
John Gibson <johgibso at indiana dot edu>, 1/5/03; rev for v4, JGG, 7/24/04
*/
//#define DEBUG
#include "FOLLOWGATE.h"
#include <float.h> // for FLT_MAX
/* ------------------------------------------------------------ FOLLOWGATE -- */
FOLLOWGATE :: FOLLOWGATE()
{
thresh_table = NULL;
range_table = NULL;
state = belowThreshold;
attack_time = release_time = -FLT_MAX;
}
/* ----------------------------------------------------------- ~FOLLOWGATE -- */
FOLLOWGATE :: ~FOLLOWGATE()
{
delete thresh_table;
delete range_table;
delete envelope;
}
/* -------------------------------------------------------------- pre_init -- */
int FOLLOWGATE :: pre_init(double p[], int n_args)
{
oneoverSR = 1.0 / SR;
return 0;
}
/* ------------------------------------------------------------- post_init -- */
int FOLLOWGATE :: post_init(double p[], int n_args)
{
if (n_args < 11) { // no p10 power threshold PField, must use gen table
double *function = floc(2);
if (function == NULL)
return die(instname(), "Either use the power threshold pfield (p10) "
"or make an old-style gen function in slot 2.");
int len = fsize(2);
thresh_table = new TableL(SR, getdur(), function, len);
}
if (n_args < 12) { // no p11 range PField, must use gen table
double *function = floc(3);
if (function == NULL)
return die(instname(), "Either use the range pfield (p11) "
"or make an old-style gen function in slot 3.");
int len = fsize(3);
range_table = new TableL(SR, getdur(), function, len);
}
envelope = new Envelope(SR);
return 0;
}
/* --------------------------------------------------------- update_params -- */
void FOLLOWGATE :: update_params(double p[])
{
if (p[7] != attack_time) {
attack_time = p[7];
if (attack_time < 0.0)
attack_time = 0.0;
attack_rate = attack_time ? oneoverSR / attack_time : 1.0;
}
if (p[8] != release_time) {
release_time = p[8];
if (release_time < 0.0)
release_time = 0.0;
release_rate = release_time ? oneoverSR / release_time : 1.0;
}
pctleft = nargs > 9 ? p[9] : 0.5; // default is center
if (nargs > 10)
threshold = p[10];
else
threshold = thresh_table->tick(currentFrame(), 1.0);
if (threshold < 0.0)
threshold = 0.0;
if (nargs > 11)
range = p[11];
else
range = range_table->tick(currentFrame(), 1.0);
if (range < 0.0)
range = 0.0;
if (state == belowThreshold) {
if (envelope->getState() == ENV_RAMPING)
envelope->setTarget(range);
else
envelope->setValue(range);
}
}
/* -------------------------------------------------------- process_sample -- */
float FOLLOWGATE :: process_sample(float sample, float power)
{
if (power >= threshold) {
if (state == belowThreshold) {
state = aboveThreshold;
envelope->setRate(attack_rate);
envelope->keyOn();
}
}
else {
if (state == aboveThreshold) {
state = belowThreshold;
envelope->setRate(release_rate);
envelope->keyOff();
envelope->setTarget(range);
}
}
float env = envelope->tick();
DPRINT3("sample: %f, power: %f, env: %f\n", sample, power, env);
return sample * env;
}
/* -------------------------------------------------------- makeFOLLOWGATE -- */
Instrument *makeFOLLOWGATE()
{
FOLLOWGATE *inst;
inst = new FOLLOWGATE();
inst->set_bus_config("FOLLOWGATE");
return inst;
}
/* ------------------------------------------------------------- rtprofile -- */
void rtprofile()
{
RT_INTRO("FOLLOWGATE", makeFOLLOWGATE);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("HoboNickels");
// Client version number
#define CLIENT_VERSION_SUFFIX "-hobo"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "da0cbf9"
# define GIT_COMMIT_DATE "Sun Mar 30 12:17:00 2014"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Version 1.4<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("HoboNickels");
// Client version number
#define CLIENT_VERSION_SUFFIX "-hobo"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "4ddc7a0a"
# define GIT_COMMIT_DATE "Tue Apr 08 19:58:00 2014"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|> |
<commit_before>#include "table_builder.h"
#include <unordered_map>
#include "item_set.h"
#include "rules.h"
#include "item_set.h"
#include "grammar.h"
using namespace std;
namespace tree_sitter {
namespace lr {
static int NOT_FOUND = -1;
class ParseTableBuilder {
const Grammar grammar;
std::unordered_map<const ItemSet, size_t> parse_state_indices;
std::unordered_map<const ItemSet, size_t> lex_state_indices;
ParseTable parse_table;
LexTable lex_table;
long parse_state_index_for_item_set(const ItemSet &item_set) const {
auto entry = parse_state_indices.find(item_set);
return (entry == parse_state_indices.end()) ? NOT_FOUND : entry->second;
}
long lex_state_index_for_item_set(const ItemSet &item_set) const {
auto entry = lex_state_indices.find(item_set);
return (entry == lex_state_indices.end()) ? NOT_FOUND : entry->second;
}
void add_shift_actions(const ItemSet &item_set, size_t state_index) {
for (auto transition : item_set.sym_transitions(grammar)) {
rules::Symbol symbol = *transition.first;
ItemSet item_set = *transition.second;
size_t new_state_index = add_parse_state(item_set);
parse_table.add_action(state_index, symbol.name, ParseAction::Shift(new_state_index));
}
}
void add_advance_actions(const ItemSet &item_set, size_t state_index) {
for (auto transition : item_set.char_transitions(grammar)) {
rules::Character rule = *transition.first;
ItemSet item_set = *transition.second;
size_t new_state_index = add_lex_state(item_set);
lex_table.add_action(state_index, rule.value, LexAction::Advance(new_state_index));
}
}
void add_accept_token_actions(const ItemSet &item_set, size_t state_index) {
for (Item item : item_set) {
if (item.is_done()) {
lex_table.add_default_action(state_index, LexAction::Accept(item.rule_name));
}
}
}
void add_reduce_actions(const ItemSet &item_set, size_t state_index) {
for (Item item : item_set) {
if (item.is_done()) {
if (item.rule_name == ParseTable::START) {
parse_table.add_action(state_index, ParseTable::END_OF_INPUT, ParseAction::Accept());
} else {
parse_table.add_default_action(state_index, ParseAction::Reduce(item.rule_name, item.consumed_sym_count));
}
}
}
}
size_t add_lex_state(const ItemSet &item_set) {
auto state_index = lex_state_index_for_item_set(item_set);
if (state_index == NOT_FOUND) {
state_index = lex_table.add_state();
lex_state_indices[item_set] = state_index;
add_advance_actions(item_set, state_index);
add_accept_token_actions(item_set, state_index);
}
return state_index;
}
size_t add_parse_state(const ItemSet &item_set) {
auto state_index = parse_state_index_for_item_set(item_set);
if (state_index == NOT_FOUND) {
state_index = parse_table.add_state();
parse_state_indices[item_set] = state_index;
parse_table.states[state_index].lex_state_index = add_lex_state(item_set);
add_shift_actions(item_set, state_index);
add_reduce_actions(item_set, state_index);
}
return state_index;
}
public:
ParseTableBuilder(const Grammar &grammar) :
grammar(grammar),
parse_table(ParseTable(grammar.rule_names())),
lex_table(LexTable(grammar.rule_names())),
parse_state_indices(unordered_map<const ItemSet, size_t>()),
lex_state_indices(unordered_map<const ItemSet, size_t>())
{};
std::pair<ParseTable, LexTable> build() {
auto item = Item(ParseTable::START, rules::sym(grammar.start_rule_name), 0);
auto item_set = ItemSet(item, grammar);
add_parse_state(item_set);
return std::pair<ParseTable, LexTable>(parse_table, lex_table);
}
};
std::pair<ParseTable, LexTable> build_tables(const tree_sitter::Grammar &grammar) {
return ParseTableBuilder(grammar).build();
}
}
}<commit_msg>Rename ParseTableBuilder -> TableBuilder<commit_after>#include "table_builder.h"
#include <unordered_map>
#include "item_set.h"
#include "rules.h"
#include "item_set.h"
#include "grammar.h"
using namespace std;
namespace tree_sitter {
namespace lr {
static int NOT_FOUND = -1;
class TableBuilder {
const Grammar grammar;
std::unordered_map<const ItemSet, size_t> parse_state_indices;
std::unordered_map<const ItemSet, size_t> lex_state_indices;
ParseTable parse_table;
LexTable lex_table;
long parse_state_index_for_item_set(const ItemSet &item_set) const {
auto entry = parse_state_indices.find(item_set);
return (entry == parse_state_indices.end()) ? NOT_FOUND : entry->second;
}
long lex_state_index_for_item_set(const ItemSet &item_set) const {
auto entry = lex_state_indices.find(item_set);
return (entry == lex_state_indices.end()) ? NOT_FOUND : entry->second;
}
void add_shift_actions(const ItemSet &item_set, size_t state_index) {
for (auto transition : item_set.sym_transitions(grammar)) {
rules::Symbol symbol = *transition.first;
ItemSet item_set = *transition.second;
size_t new_state_index = add_parse_state(item_set);
parse_table.add_action(state_index, symbol.name, ParseAction::Shift(new_state_index));
}
}
void add_advance_actions(const ItemSet &item_set, size_t state_index) {
for (auto transition : item_set.char_transitions(grammar)) {
rules::Character rule = *transition.first;
ItemSet item_set = *transition.second;
size_t new_state_index = add_lex_state(item_set);
lex_table.add_action(state_index, rule.value, LexAction::Advance(new_state_index));
}
}
void add_accept_token_actions(const ItemSet &item_set, size_t state_index) {
for (Item item : item_set) {
if (item.is_done()) {
lex_table.add_default_action(state_index, LexAction::Accept(item.rule_name));
}
}
}
void add_reduce_actions(const ItemSet &item_set, size_t state_index) {
for (Item item : item_set) {
if (item.is_done()) {
if (item.rule_name == ParseTable::START) {
parse_table.add_action(state_index, ParseTable::END_OF_INPUT, ParseAction::Accept());
} else {
parse_table.add_default_action(state_index, ParseAction::Reduce(item.rule_name, item.consumed_sym_count));
}
}
}
}
size_t add_lex_state(const ItemSet &item_set) {
auto state_index = lex_state_index_for_item_set(item_set);
if (state_index == NOT_FOUND) {
state_index = lex_table.add_state();
lex_state_indices[item_set] = state_index;
add_advance_actions(item_set, state_index);
add_accept_token_actions(item_set, state_index);
}
return state_index;
}
size_t add_parse_state(const ItemSet &item_set) {
auto state_index = parse_state_index_for_item_set(item_set);
if (state_index == NOT_FOUND) {
state_index = parse_table.add_state();
parse_state_indices[item_set] = state_index;
parse_table.states[state_index].lex_state_index = add_lex_state(item_set);
add_shift_actions(item_set, state_index);
add_reduce_actions(item_set, state_index);
}
return state_index;
}
public:
TableBuilder(const Grammar &grammar) :
grammar(grammar),
parse_table(ParseTable(grammar.rule_names())),
lex_table(LexTable(grammar.rule_names())),
parse_state_indices(unordered_map<const ItemSet, size_t>()),
lex_state_indices(unordered_map<const ItemSet, size_t>())
{};
std::pair<ParseTable, LexTable> build() {
auto item = Item(ParseTable::START, rules::sym(grammar.start_rule_name), 0);
auto item_set = ItemSet(item, grammar);
add_parse_state(item_set);
return std::pair<ParseTable, LexTable>(parse_table, lex_table);
}
};
std::pair<ParseTable, LexTable> build_tables(const tree_sitter::Grammar &grammar) {
return TableBuilder(grammar).build();
}
}
}<|endoftext|> |
<commit_before>/*
nsjail
-----------------------------------------
Copyright 2014 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 "nsjail.h"
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <termios.h>
#include <unistd.h>
#include "cmdline.h"
#include "logs.h"
#include "macros.h"
#include "net.h"
#include "sandbox.h"
#include "subproc.h"
#include "util.h"
namespace nsjail {
static __thread int sigFatal = 0;
static __thread bool showProc = false;
static void sigHandler(int sig) {
if (sig == SIGALRM) {
return;
}
if (sig == SIGCHLD) {
return;
}
if (sig == SIGUSR1 || sig == SIGQUIT) {
showProc = true;
return;
}
sigFatal = sig;
}
static bool setSigHandler(int sig) {
LOG_D("Setting sighandler for signal %s (%d)", util::sigName(sig).c_str(), sig);
sigset_t smask;
sigemptyset(&smask);
struct sigaction sa;
sa.sa_handler = sigHandler;
sa.sa_mask = smask;
sa.sa_flags = 0;
sa.sa_restorer = NULL;
if (sig == SIGTTIN || sig == SIGTTOU) {
sa.sa_handler = SIG_IGN;
};
if (sigaction(sig, &sa, NULL) == -1) {
PLOG_E("sigaction(%d)", sig);
return false;
}
return true;
}
static bool setSigHandlers(void) {
for (const auto& i : nssigs) {
if (!setSigHandler(i)) {
return false;
}
}
return true;
}
static bool setTimer(nsjconf_t* nsjconf) {
if (nsjconf->mode == MODE_STANDALONE_EXECVE) {
return true;
}
struct itimerval it = {
.it_interval =
{
.tv_sec = 1,
.tv_usec = 0,
},
.it_value =
{
.tv_sec = 1,
.tv_usec = 0,
},
};
if (setitimer(ITIMER_REAL, &it, NULL) == -1) {
PLOG_E("setitimer(ITIMER_REAL)");
return false;
}
return true;
}
static void listenMode(nsjconf_t* nsjconf) {
int listenfd = net::getRecvSocket(nsjconf->bindhost.c_str(), nsjconf->port);
if (listenfd == -1) {
return;
}
for (;;) {
if (sigFatal > 0) {
subproc::killAll(nsjconf);
logs::logStop(sigFatal);
close(listenfd);
return;
}
if (showProc) {
showProc = false;
subproc::displayProc(nsjconf);
}
int connfd = net::acceptConn(listenfd);
if (connfd >= 0) {
subproc::runChild(nsjconf, connfd, connfd, connfd);
close(connfd);
}
subproc::reapProc(nsjconf);
}
}
static int standaloneMode(nsjconf_t* nsjconf) {
subproc::runChild(nsjconf, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO);
for (;;) {
int child_status = subproc::reapProc(nsjconf);
if (subproc::countProc(nsjconf) == 0) {
if (nsjconf->mode == MODE_STANDALONE_ONCE) {
return child_status;
}
subproc::runChild(nsjconf, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO);
continue;
}
if (showProc) {
showProc = false;
subproc::displayProc(nsjconf);
}
if (sigFatal > 0) {
subproc::killAll(nsjconf);
logs::logStop(sigFatal);
return -1;
}
pause();
}
// not reached
}
std::unique_ptr<struct termios> getTC(int fd) {
std::unique_ptr<struct termios> trm(new struct termios);
if (ioctl(fd, TCGETS, trm.get()) == -1) {
PLOG_D("ioctl(fd=%d, TCGETS) failed", fd);
return nullptr;
}
LOG_D("Saved the current state of the TTY");
return trm;
}
void setTC(int fd, const struct termios* trm) {
if (!trm) {
return;
}
if (ioctl(fd, TCSETS, trm) == -1) {
PLOG_W("ioctl(fd=%d, TCSETS) failed", fd);
return;
}
LOG_D("Restored the previous state of the TTY");
}
} // namespace nsjail
int main(int argc, char* argv[]) {
std::unique_ptr<nsjconf_t> nsjconf = cmdline::parseArgs(argc, argv);
std::unique_ptr<struct termios> trm = nsjail::getTC(STDIN_FILENO);
if (!nsjconf) {
LOG_F("Couldn't parse cmdline options");
}
if (!nsjconf->clone_newuser && geteuid() != 0) {
LOG_W("--disable_clone_newuser might require root() privs");
}
if (nsjconf->daemonize && (daemon(0, 0) == -1)) {
PLOG_F("daemon");
}
cmdline::logParams(nsjconf.get());
if (!nsjail::setSigHandlers()) {
LOG_F("nsjail::setSigHandlers() failed");
}
if (!nsjail::setTimer(nsjconf.get())) {
LOG_F("nsjail::setTimer() failed");
}
if (!sandbox::preparePolicy(nsjconf.get())) {
LOG_F("Couldn't prepare sandboxing policy");
}
int ret = 0;
if (nsjconf->mode == MODE_LISTEN_TCP) {
nsjail::listenMode(nsjconf.get());
} else {
ret = nsjail::standaloneMode(nsjconf.get());
}
sandbox::closePolicy(nsjconf.get());
/* Try to restore the underlying console's params in case some program has changed it */
nsjail::setTC(STDIN_FILENO, trm.get());
return ret;
}
<commit_msg>nsjail: make listenMode return int<commit_after>/*
nsjail
-----------------------------------------
Copyright 2014 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 "nsjail.h"
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <termios.h>
#include <unistd.h>
#include "cmdline.h"
#include "logs.h"
#include "macros.h"
#include "net.h"
#include "sandbox.h"
#include "subproc.h"
#include "util.h"
namespace nsjail {
static __thread int sigFatal = 0;
static __thread bool showProc = false;
static void sigHandler(int sig) {
if (sig == SIGALRM) {
return;
}
if (sig == SIGCHLD) {
return;
}
if (sig == SIGUSR1 || sig == SIGQUIT) {
showProc = true;
return;
}
sigFatal = sig;
}
static bool setSigHandler(int sig) {
LOG_D("Setting sighandler for signal %s (%d)", util::sigName(sig).c_str(), sig);
sigset_t smask;
sigemptyset(&smask);
struct sigaction sa;
sa.sa_handler = sigHandler;
sa.sa_mask = smask;
sa.sa_flags = 0;
sa.sa_restorer = NULL;
if (sig == SIGTTIN || sig == SIGTTOU) {
sa.sa_handler = SIG_IGN;
};
if (sigaction(sig, &sa, NULL) == -1) {
PLOG_E("sigaction(%d)", sig);
return false;
}
return true;
}
static bool setSigHandlers(void) {
for (const auto& i : nssigs) {
if (!setSigHandler(i)) {
return false;
}
}
return true;
}
static bool setTimer(nsjconf_t* nsjconf) {
if (nsjconf->mode == MODE_STANDALONE_EXECVE) {
return true;
}
struct itimerval it = {
.it_interval =
{
.tv_sec = 1,
.tv_usec = 0,
},
.it_value =
{
.tv_sec = 1,
.tv_usec = 0,
},
};
if (setitimer(ITIMER_REAL, &it, NULL) == -1) {
PLOG_E("setitimer(ITIMER_REAL)");
return false;
}
return true;
}
static int listenMode(nsjconf_t* nsjconf) {
int listenfd = net::getRecvSocket(nsjconf->bindhost.c_str(), nsjconf->port);
if (listenfd == -1) {
return 0;
}
for (;;) {
if (sigFatal > 0) {
subproc::killAll(nsjconf);
logs::logStop(sigFatal);
close(listenfd);
return 0;
}
if (showProc) {
showProc = false;
subproc::displayProc(nsjconf);
}
int connfd = net::acceptConn(listenfd);
if (connfd >= 0) {
subproc::runChild(nsjconf, connfd, connfd, connfd);
close(connfd);
}
subproc::reapProc(nsjconf);
}
}
static int standaloneMode(nsjconf_t* nsjconf) {
subproc::runChild(nsjconf, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO);
for (;;) {
int child_status = subproc::reapProc(nsjconf);
if (subproc::countProc(nsjconf) == 0) {
if (nsjconf->mode == MODE_STANDALONE_ONCE) {
return child_status;
}
subproc::runChild(nsjconf, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO);
continue;
}
if (showProc) {
showProc = false;
subproc::displayProc(nsjconf);
}
if (sigFatal > 0) {
subproc::killAll(nsjconf);
logs::logStop(sigFatal);
return -1;
}
pause();
}
// not reached
}
std::unique_ptr<struct termios> getTC(int fd) {
std::unique_ptr<struct termios> trm(new struct termios);
if (ioctl(fd, TCGETS, trm.get()) == -1) {
PLOG_D("ioctl(fd=%d, TCGETS) failed", fd);
return nullptr;
}
LOG_D("Saved the current state of the TTY");
return trm;
}
void setTC(int fd, const struct termios* trm) {
if (!trm) {
return;
}
if (ioctl(fd, TCSETS, trm) == -1) {
PLOG_W("ioctl(fd=%d, TCSETS) failed", fd);
return;
}
LOG_D("Restored the previous state of the TTY");
}
} // namespace nsjail
int main(int argc, char* argv[]) {
std::unique_ptr<nsjconf_t> nsjconf = cmdline::parseArgs(argc, argv);
std::unique_ptr<struct termios> trm = nsjail::getTC(STDIN_FILENO);
if (!nsjconf) {
LOG_F("Couldn't parse cmdline options");
}
if (!nsjconf->clone_newuser && geteuid() != 0) {
LOG_W("--disable_clone_newuser might require root() privs");
}
if (nsjconf->daemonize && (daemon(0, 0) == -1)) {
PLOG_F("daemon");
}
cmdline::logParams(nsjconf.get());
if (!nsjail::setSigHandlers()) {
LOG_F("nsjail::setSigHandlers() failed");
}
if (!nsjail::setTimer(nsjconf.get())) {
LOG_F("nsjail::setTimer() failed");
}
if (!sandbox::preparePolicy(nsjconf.get())) {
LOG_F("Couldn't prepare sandboxing policy");
}
int ret = 0;
if (nsjconf->mode == MODE_LISTEN_TCP) {
ret = nsjail::listenMode(nsjconf.get());
} else {
ret = nsjail::standaloneMode(nsjconf.get());
}
sandbox::closePolicy(nsjconf.get());
/* Try to restore the underlying console's params in case some program has changed it */
nsjail::setTC(STDIN_FILENO, trm.get());
return ret;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011, Michael Lehn
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2) Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3) Neither the name of the FLENS development group nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef FLENS_LAPACK_AUXILIARY_POW_TCC
#define FLENS_LAPACK_AUXILIARY_POW_TCC 1
#include <cmath>
#include <flens/lapack/auxiliary/pow.h>
namespace flens {
template <typename T>
typename RestrictTo<!IsSame<T,int>::value,
T>::Type
pow(const T &base, const T &exponent)
{
return std::pow(base, exponent);
}
template <typename T>
T
pow(const T &base, int exponent)
{
//
// TODO: Make this more general and call an external Fortran routine
// that computes 'pow(base, exponent)' for comparison
//
# ifdef CHECK_CXXLAPACK
if (exponent==2) {
return base*base;
}
# endif
return std::pow(base, exponent);
}
} // namespace flens
#endif // FLENS_LAPACK_AUXILIARY_POW_TCC
<commit_msg>Added custom implementation of pow(int, int)<commit_after>/*
* Copyright (c) 2011, Michael Lehn
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2) Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3) Neither the name of the FLENS development group nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef FLENS_LAPACK_AUXILIARY_POW_TCC
#define FLENS_LAPACK_AUXILIARY_POW_TCC 1
#include <cmath>
#include <flens/lapack/auxiliary/pow.h>
namespace flens {
template <typename T>
typename RestrictTo<!IsSame<T,int>::value,
T>::Type
pow(const T &base, const T &exponent)
{
ASSERT( exponent>=0 );
if ( exponent==0 ) {
return 1;
} else if ( exponent==1 ) {
return base;
}
int value = flens::pow(base, exponent/2 );
if ( exponent%2==0 ) {
return value*value;
}
return base*value*value;
//return std::pow(base, exponent);
}
template <typename T>
T
pow(const T &base, int exponent)
{
//
// TODO: Make this more general and call an external Fortran routine
// that computes 'pow(base, exponent)' for comparison
//
# ifdef CHECK_CXXLAPACK
if (exponent==2) {
return base*base;
}
# endif
return std::pow(base, exponent);
}
} // namespace flens
#endif // FLENS_LAPACK_AUXILIARY_POW_TCC
<|endoftext|> |
<commit_before>
#include <log4cplus/consoleappender.h>
#include <log4cplus/layout.h>
#include <log4cplus/logger.h>
#include <log4cplus/ndc.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/threads.h>
#include <exception>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
using namespace log4cplus;
using namespace log4cplus::helpers;
using namespace log4cplus::thread;
#define MILLIS_TO_NANOS 1000
#define NUM_THREADS 4
#define NUM_LOOPS 10
class SlowObject {
public:
SlowObject()
: mutex( LOG4CPLUS_MUTEX_CREATE ),
logger(Logger::getInstance("SlowObject"))
{ logger.setLogLevel(TRACE_LOG_LEVEL); }
void doSomething() {
LOG4CPLUS_TRACE_METHOD(logger, "SlowObject::doSomething()")
LOG4CPLUS_BEGIN_SYNCHRONIZE_ON_MUTEX( mutex )
LOG4CPLUS_INFO(logger, "Actually doing something...")
sleep(0, 75 * MILLIS_TO_NANOS);
LOG4CPLUS_INFO(logger, "Actually doing something...DONE")
LOG4CPLUS_END_SYNCHRONIZE_ON_MUTEX
yield();
}
private:
LOG4CPLUS_MUTEX_PTR_DECLARE mutex;
Logger logger;
};
SlowObject *global;
class TestThread : public AbstractThread {
public:
TestThread(std::string n)
: name(n), logger(Logger::getInstance("test.TestThread"))
{
}
virtual void run();
private:
Logger logger;
std::string name;
};
int
main()
{
auto_ptr<SlowObject> globalContainer(new SlowObject());
global = globalContainer.get();
try {
log4cplus::helpers::LogLog::getLogLog()->setInternalDebugging(true);
Logger logger = Logger::getInstance("main");
Logger::getRoot().setLogLevel(INFO_LOG_LEVEL);
LogLevel ll = logger.getLogLevel();
cout << "main Priority: " << getLogLevelManager().toString(ll) << endl;
helpers::SharedObjectPtr<Appender> append_1(new ConsoleAppender());
append_1->setLayout( std::auto_ptr<Layout>(new log4cplus::TTCCLayout()) );
Logger::getRoot().addAppender(append_1);
append_1->setName("cout");
append_1 = 0;
log4cplus::helpers::SharedObjectPtr<TestThread> threads[NUM_THREADS];
int i = 0;
for(i=0; i<NUM_THREADS; ++i) {
stringstream s;
s << "Thread-" << i;
threads[i] = new TestThread(s.str());
}
for(i=0; i<NUM_THREADS; ++i) {
threads[i]->start();
}
LOG4CPLUS_DEBUG(logger, "All Threads started...")
for(i=0; i<NUM_THREADS; ++i) {
while(threads[i]->isRunning()) {
sleep(0, 200 * MILLIS_TO_NANOS);
}
}
LOG4CPLUS_INFO(logger, "Exiting main()...")
}
catch(std::exception &e) {
LOG4CPLUS_FATAL(Logger::getRoot(), "main()- Exception occured: " << e.what())
}
catch(...) {
LOG4CPLUS_FATAL(Logger::getRoot(), "main()- Exception occured")
}
log4cplus::Logger::shutdown();
return 0;
}
void
TestThread::run()
{
try {
LOG4CPLUS_WARN(logger, name + " TestThread.run()- Starting...")
NDC& ndc = getNDC();
NDCContextCreator _first_ndc(name);
LOG4CPLUS_DEBUG(logger, "Entering Run()...")
for(int i=0; i<NUM_LOOPS; ++i) {
NDCContextCreator _ndc("loop");
global->doSomething();
}
LOG4CPLUS_DEBUG(logger, "Exiting run()...")
ndc.remove();
}
catch(exception& e) {
LOG4CPLUS_FATAL(logger, "TestThread.run()- Exception occurred: " << e.what())
}
catch(...) {
LOG4CPLUS_FATAL(logger, "TestThread.run()- Exception occurred!!")
}
LOG4CPLUS_WARN(logger, name << " TestThread.run()- Finished")
} // end "run"
<commit_msg>Stopped using the std::sstring* classes.<commit_after>
#include <log4cplus/consoleappender.h>
#include <log4cplus/layout.h>
#include <log4cplus/logger.h>
#include <log4cplus/ndc.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/threads.h>
#include <log4cplus/streams.h>
#include <exception>
#include <iostream>
#include <string>
using namespace std;
using namespace log4cplus;
using namespace log4cplus::helpers;
using namespace log4cplus::thread;
#define MILLIS_TO_NANOS 1000
#define NUM_THREADS 4
#define NUM_LOOPS 10
class SlowObject {
public:
SlowObject()
: mutex( LOG4CPLUS_MUTEX_CREATE ),
logger(Logger::getInstance("SlowObject"))
{ logger.setLogLevel(TRACE_LOG_LEVEL); }
void doSomething() {
LOG4CPLUS_TRACE_METHOD(logger, "SlowObject::doSomething()")
LOG4CPLUS_BEGIN_SYNCHRONIZE_ON_MUTEX( mutex )
LOG4CPLUS_INFO(logger, "Actually doing something...")
sleep(0, 75 * MILLIS_TO_NANOS);
LOG4CPLUS_INFO(logger, "Actually doing something...DONE")
LOG4CPLUS_END_SYNCHRONIZE_ON_MUTEX
yield();
}
private:
LOG4CPLUS_MUTEX_PTR_DECLARE mutex;
Logger logger;
};
SlowObject *global;
class TestThread : public AbstractThread {
public:
TestThread(tstring n)
: name(n), logger(Logger::getInstance("test.TestThread"))
{
}
virtual void run();
private:
Logger logger;
tstring name;
};
int
main()
{
auto_ptr<SlowObject> globalContainer(new SlowObject());
global = globalContainer.get();
try {
log4cplus::helpers::LogLog::getLogLog()->setInternalDebugging(true);
Logger logger = Logger::getInstance("main");
Logger::getRoot().setLogLevel(INFO_LOG_LEVEL);
LogLevel ll = logger.getLogLevel();
cout << "main Priority: " << getLogLevelManager().toString(ll) << endl;
helpers::SharedObjectPtr<Appender> append_1(new ConsoleAppender());
append_1->setLayout( std::auto_ptr<Layout>(new log4cplus::TTCCLayout()) );
Logger::getRoot().addAppender(append_1);
append_1->setName("cout");
append_1 = 0;
log4cplus::helpers::SharedObjectPtr<TestThread> threads[NUM_THREADS];
int i = 0;
for(i=0; i<NUM_THREADS; ++i) {
tostringstream s;
s << "Thread-" << i;
threads[i] = new TestThread(s.str());
}
for(i=0; i<NUM_THREADS; ++i) {
threads[i]->start();
}
LOG4CPLUS_DEBUG(logger, "All Threads started...")
for(i=0; i<NUM_THREADS; ++i) {
while(threads[i]->isRunning()) {
sleep(0, 200 * MILLIS_TO_NANOS);
}
}
LOG4CPLUS_INFO(logger, "Exiting main()...")
}
catch(std::exception &e) {
LOG4CPLUS_FATAL(Logger::getRoot(), "main()- Exception occured: " << e.what())
}
catch(...) {
LOG4CPLUS_FATAL(Logger::getRoot(), "main()- Exception occured")
}
log4cplus::Logger::shutdown();
return 0;
}
void
TestThread::run()
{
try {
LOG4CPLUS_WARN(logger, name + " TestThread.run()- Starting...")
NDC& ndc = getNDC();
NDCContextCreator _first_ndc(name);
LOG4CPLUS_DEBUG(logger, "Entering Run()...")
for(int i=0; i<NUM_LOOPS; ++i) {
NDCContextCreator _ndc("loop");
global->doSomething();
}
LOG4CPLUS_DEBUG(logger, "Exiting run()...")
ndc.remove();
}
catch(exception& e) {
LOG4CPLUS_FATAL(logger, "TestThread.run()- Exception occurred: " << e.what())
}
catch(...) {
LOG4CPLUS_FATAL(logger, "TestThread.run()- Exception occurred!!")
}
LOG4CPLUS_WARN(logger, name << " TestThread.run()- Finished")
} // end "run"
<|endoftext|> |
<commit_before>/*-------------------------------------------------------------------------
* drawElements Quality Program Tester Core
* ----------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Generic main().
*//*--------------------------------------------------------------------*/
#include "tcuDefs.hpp"
#include "tcuCommandLine.hpp"
#include "tcuPlatform.hpp"
#include "tcuApp.hpp"
#include "tcuResource.hpp"
#include "tcuTestLog.hpp"
#include "deUniquePtr.hpp"
#include <cstdio>
// Implement this in your platform port.
tcu::Platform* createPlatform (void);
int main (int argc, char** argv)
{
#if (DE_OS != DE_OS_WIN32)
// Set stdout to line-buffered mode (will be fully buffered by default if stdout is pipe).
setvbuf(stdout, DE_NULL, _IOLBF, 4*1024);
#endif
try
{
tcu::CommandLine cmdLine (argc, argv);
tcu::DirArchive archive (".");
tcu::TestLog log (cmdLine.getLogFileName(), argc-1, argv+1, cmdLine.getLogFlags());
de::UniquePtr<tcu::Platform> platform (createPlatform());
de::UniquePtr<tcu::App> app (new tcu::App(*platform, archive, log, cmdLine));
// Main loop.
for (;;)
{
if (!app->iterate())
break;
}
}
catch (const std::exception& e)
{
tcu::die("%s", e.what());
}
return 0;
}
<commit_msg>Generate a non-zero exit code on test failure<commit_after>/*-------------------------------------------------------------------------
* drawElements Quality Program Tester Core
* ----------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Generic main().
*//*--------------------------------------------------------------------*/
#include "tcuDefs.hpp"
#include "tcuCommandLine.hpp"
#include "tcuPlatform.hpp"
#include "tcuApp.hpp"
#include "tcuResource.hpp"
#include "tcuTestLog.hpp"
#include "tcuTestSessionExecutor.hpp"
#include "deUniquePtr.hpp"
#include <cstdio>
// Implement this in your platform port.
tcu::Platform* createPlatform (void);
int main (int argc, char** argv)
{
int exitStatus = EXIT_SUCCESS;
#if (DE_OS != DE_OS_WIN32)
// Set stdout to line-buffered mode (will be fully buffered by default if stdout is pipe).
setvbuf(stdout, DE_NULL, _IOLBF, 4*1024);
#endif
try
{
tcu::CommandLine cmdLine (argc, argv);
tcu::DirArchive archive (".");
tcu::TestLog log (cmdLine.getLogFileName(), argc-1, argv+1, cmdLine.getLogFlags());
de::UniquePtr<tcu::Platform> platform (createPlatform());
de::UniquePtr<tcu::App> app (new tcu::App(*platform, archive, log, cmdLine));
// Main loop.
for (;;)
{
if (!app->iterate())
{
if (cmdLine.getRunMode() == tcu::RUNMODE_EXECUTE &&
(!app->getResult().isComplete || app->getResult().numFailed))
{
exitStatus = EXIT_FAILURE;
}
break;
}
}
}
catch (const std::exception& e)
{
tcu::die("%s", e.what());
}
return exitStatus;
}
<|endoftext|> |
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "DataIO.h"
#include "MooseMesh.h"
template<>
void
dataStore(std::ostream & stream, Real & v, void * /*context*/)
{
stream.write((char *) &v, sizeof(v));
}
template<>
void
dataStore(std::ostream & stream, std::string & v, void * /*context*/)
{
// Write the size of the string
unsigned int size = v.size();
stream.write((char *) &size, sizeof(size));
// Write the string
stream.write(v.c_str(), sizeof(char)*(size+1));
}
template<>
void
dataStore(std::ostream & stream, DenseMatrix<Real> & v, void * /*context*/)
{
for (unsigned int i = 0; i < v.m(); i++)
for (unsigned int j = 0; j < v.n(); j++)
{
Real r = v(i, j);
stream.write((char *) &r, sizeof(r));
}
}
template<>
void
dataStore(std::ostream & stream, ColumnMajorMatrix & v, void * /*context*/)
{
for (unsigned int i = 0; i < v.m(); i++)
for (unsigned int j = 0; j < v.n(); j++)
{
Real r = v(i, j);
stream.write((char *) &r, sizeof(r));
}
}
template<>
void
dataStore(std::ostream & stream, RealTensorValue & v, void * /*context*/)
{
for (unsigned int i = 0; i < LIBMESH_DIM; i++)
for (unsigned int j = 0; i < LIBMESH_DIM; i++)
stream.write((char *) &v(i, j), sizeof(v(i, j)));
}
template<>
void
dataStore(std::ostream & stream, RealVectorValue & v, void * /*context*/)
{
// Obviously if someone loads data with different LIBMESH_DIM than was used for saving them, it won't work.
for (unsigned int i = 0; i < LIBMESH_DIM; i++)
stream.write((char *) &v(i), sizeof(v(i)));
}
template<>
void
dataStore(std::ostream & stream, const Elem * & e, void * context)
{
// Moose::out<<"const Elem pointer store"<<std::endl;
// TODO: Write out the unique ID of this elem
dof_id_type id = libMesh::DofObject::invalid_id;
if (e)
{
id = e->id();
// Moose::out<<"Storing Elem id: "<<id<<std::endl;
if (id == libMesh::DofObject::invalid_id)
mooseError("Can't output Elems with invalid ids!");
}
else
{
// Moose::out<<"Outputting NULL Elem pointer"<<std::endl;
}
storeHelper(stream, id, context);
}
template<>
void
dataStore(std::ostream & stream, const Node * & n, void * context)
{
// Moose::out<<"const Node pointer store"<<std::endl;
// TODO: Write out the unique ID of this node
dof_id_type id = libMesh::DofObject::invalid_id;
if (n)
{
id = n->id();
// Moose::out<<"Storing Node id: "<<id<<std::endl;
if (id == libMesh::DofObject::invalid_id)
mooseError("Can't output Nodes with invalid ids!");
}
else
{
// Moose::out<<"Outputting NULL Node pointer"<<std::endl;
}
storeHelper(stream, id, context);
}
template<>
void
dataStore(std::ostream & stream, Elem * & e, void * context)
{
// Moose::out<<"const Elem pointer store"<<std::endl;
// TODO: Write out the unique ID of this elem
dof_id_type id = libMesh::DofObject::invalid_id;
if (e)
{
id = e->id();
// Moose::out<<"Storing Elem id: "<<id<<std::endl;
if (id == libMesh::DofObject::invalid_id)
mooseError("Can't output Elems with invalid ids!");
}
else
{
// Moose::out<<"Outputting NULL Elem pointer"<<std::endl;
}
storeHelper(stream, id, context);
}
template<>
void
dataStore(std::ostream & stream, Node * & n, void * context)
{
// Moose::out<<"const Node pointer store"<<std::endl;
// TODO: Write out the unique ID of this node
dof_id_type id = libMesh::DofObject::invalid_id;
if (n)
{
id = n->id();
// Moose::out<<"Storing Node id: "<<id<<std::endl;
if (id == libMesh::DofObject::invalid_id)
mooseError("Can't output Nodes with invalid ids!");
}
else
{
// Moose::out<<"Outputting NULL Node pointer"<<std::endl;
}
storeHelper(stream, id, context);
}
// global load functions
template<>
void
dataLoad(std::istream & stream, Real & v, void * /*context*/)
{
// Moose::out<<"Real dataLoad"<<std::endl;
stream.read((char *) &v, sizeof(v));
}
template<>
void
dataLoad(std::istream & stream, std::string & v, void * /*context*/)
{
// Moose::out<<"std::string dataLoad"<<std::endl;
// Read the size of the string
unsigned int size = 0;
stream.read((char *) &size, sizeof(size));
// Moose::out<<"Size: "<<size<<std::endl;
// Read the string
char* s = new char[size+1];
stream.read(s, sizeof(char)*(size+1));
// Store the string and clean up
v = s;
delete[] s;
}
template<>
void
dataLoad(std::istream & stream, DenseMatrix<Real> & v, void * /*context*/)
{
for (unsigned int i = 0; i < v.m(); i++)
for (unsigned int j = 0; j < v.n(); j++)
{
Real r = 0;
stream.read((char *) &r, sizeof(r));
v(i, j) = r;
}
}
template<>
void
dataLoad(std::istream & stream, ColumnMajorMatrix & v, void * /*context*/)
{
for (unsigned int i = 0; i < v.m(); i++)
for (unsigned int j = 0; j < v.n(); j++)
{
Real r = 0;
stream.read((char *) &r, sizeof(r));
v(i, j) = r;
}
}
template<>
void
dataLoad(std::istream & stream, RealTensorValue & v, void * /*context*/)
{
// Obviously if someone loads data with different LIBMESH_DIM than was used for saving them, it won't work.
for (unsigned int i = 0; i < LIBMESH_DIM; i++)
for (unsigned int j = 0; i < LIBMESH_DIM; i++)
{
Real r = 0;
stream.read((char *) &r, sizeof(r));
v(i, j) = r;
}
}
template<>
void
dataLoad(std::istream & stream, RealVectorValue & v, void * /*context*/)
{
// Obviously if someone loads data with different LIBMESH_DIM than was used for saving them, it won't work.
for (unsigned int i = 0; i < LIBMESH_DIM; i++)
{
Real r = 0;
stream.read((char *) &r, sizeof(r));
v(i) = r;
}
}
template<>
void
dataLoad(std::istream & stream, const Elem * & e, void * context)
{
if (!context)
mooseError("Can only load Elem objects using a MooseMesh context!");
MooseMesh * mesh = static_cast<MooseMesh *>(context);
// Moose::out<<"Elem pointer load"<<std::endl;
// TODO: Write out the unique ID of this element
dof_id_type id = libMesh::DofObject::invalid_id;
loadHelper(stream, id, context);
if (id != libMesh::DofObject::invalid_id)
{
e = mesh->elem(id);
// Moose::out<<"Retrived Elem: "<<id<<std::endl;
// Moose::out<<"Elem ptr: "<<e<<std::endl;
// Moose::out<<"Elem id: "<<e->id()<<std::endl;
}
else
{
e = NULL;
// Moose::out<<"NULL Elem"<<std::endl;
}
}
template<>
void
dataLoad(std::istream & stream, const Node * & n, void * context)
{
if (!context)
mooseError("Can only load Node objects using a MooseMesh context!");
MooseMesh * mesh = static_cast<MooseMesh *>(context);
// Moose::out<<"Node pointer load"<<std::endl;
// TODO: Write out the unique ID of this nodeent
dof_id_type id = libMesh::DofObject::invalid_id;
loadHelper(stream, id, context);
if (id != libMesh::DofObject::invalid_id)
{
n = mesh->nodePtr(id);
// Moose::out<<"Retrived Node: "<<id<<std::endl;
}
else
{
n = NULL;
// Moose::out<<"NULL Node"<<std::endl;
}
}
template<>
void
dataLoad(std::istream & stream, Elem * & e, void * context)
{
if (!context)
mooseError("Can only load Elem objects using a MooseMesh context!");
MooseMesh * mesh = static_cast<MooseMesh *>(context);
// Moose::out<<"Elem pointer load"<<std::endl;
// TODO: Write out the unique ID of this element
dof_id_type id = libMesh::DofObject::invalid_id;
loadHelper(stream, id, context);
if (id != libMesh::DofObject::invalid_id)
{
e = mesh->elem(id);
// Moose::out<<"Retrived Elem: "<<id<<std::endl;
// Moose::out<<"Elem ptr: "<<e<<std::endl;
// Moose::out<<"Elem id: "<<e->id()<<std::endl;
}
else
{
e = NULL;
// Moose::out<<"NULL Elem"<<std::endl;
}
}
template<>
void
dataLoad(std::istream & stream, Node * & n, void * context)
{
if (!context)
mooseError("Can only load Node objects using a MooseMesh context!");
MooseMesh * mesh = static_cast<MooseMesh *>(context);
// Moose::out<<"Node pointer load"<<std::endl;
// TODO: Write out the unique ID of this nodeent
dof_id_type id = libMesh::DofObject::invalid_id;
loadHelper(stream, id, context);
if (id != libMesh::DofObject::invalid_id)
{
n = mesh->nodePtr(id);
// Moose::out<<"Retrived Node: "<<id<<std::endl;
}
else
{
n = NULL;
// Moose::out<<"NULL Node"<<std::endl;
}
}
<commit_msg>Writing/reading size of DenseMatrix to/from Checkpoint files (#5380)<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "DataIO.h"
#include "MooseMesh.h"
template<>
void
dataStore(std::ostream & stream, Real & v, void * /*context*/)
{
stream.write((char *) &v, sizeof(v));
}
template<>
void
dataStore(std::ostream & stream, std::string & v, void * /*context*/)
{
// Write the size of the string
unsigned int size = v.size();
stream.write((char *) &size, sizeof(size));
// Write the string
stream.write(v.c_str(), sizeof(char)*(size+1));
}
template<>
void
dataStore(std::ostream & stream, DenseMatrix<Real> & v, void * /*context*/)
{
unsigned int m = v.m();
unsigned int n = v.n();
stream.write((char *) &m, sizeof(m));
stream.write((char *) &n, sizeof(n));
for (unsigned int i = 0; i < v.m(); i++)
for (unsigned int j = 0; j < v.n(); j++)
{
Real r = v(i, j);
stream.write((char *) &r, sizeof(r));
}
}
template<>
void
dataStore(std::ostream & stream, ColumnMajorMatrix & v, void * /*context*/)
{
for (unsigned int i = 0; i < v.m(); i++)
for (unsigned int j = 0; j < v.n(); j++)
{
Real r = v(i, j);
stream.write((char *) &r, sizeof(r));
}
}
template<>
void
dataStore(std::ostream & stream, RealTensorValue & v, void * /*context*/)
{
for (unsigned int i = 0; i < LIBMESH_DIM; i++)
for (unsigned int j = 0; i < LIBMESH_DIM; i++)
stream.write((char *) &v(i, j), sizeof(v(i, j)));
}
template<>
void
dataStore(std::ostream & stream, RealVectorValue & v, void * /*context*/)
{
// Obviously if someone loads data with different LIBMESH_DIM than was used for saving them, it won't work.
for (unsigned int i = 0; i < LIBMESH_DIM; i++)
stream.write((char *) &v(i), sizeof(v(i)));
}
template<>
void
dataStore(std::ostream & stream, const Elem * & e, void * context)
{
// Moose::out<<"const Elem pointer store"<<std::endl;
// TODO: Write out the unique ID of this elem
dof_id_type id = libMesh::DofObject::invalid_id;
if (e)
{
id = e->id();
// Moose::out<<"Storing Elem id: "<<id<<std::endl;
if (id == libMesh::DofObject::invalid_id)
mooseError("Can't output Elems with invalid ids!");
}
else
{
// Moose::out<<"Outputting NULL Elem pointer"<<std::endl;
}
storeHelper(stream, id, context);
}
template<>
void
dataStore(std::ostream & stream, const Node * & n, void * context)
{
// Moose::out<<"const Node pointer store"<<std::endl;
// TODO: Write out the unique ID of this node
dof_id_type id = libMesh::DofObject::invalid_id;
if (n)
{
id = n->id();
// Moose::out<<"Storing Node id: "<<id<<std::endl;
if (id == libMesh::DofObject::invalid_id)
mooseError("Can't output Nodes with invalid ids!");
}
else
{
// Moose::out<<"Outputting NULL Node pointer"<<std::endl;
}
storeHelper(stream, id, context);
}
template<>
void
dataStore(std::ostream & stream, Elem * & e, void * context)
{
// Moose::out<<"const Elem pointer store"<<std::endl;
// TODO: Write out the unique ID of this elem
dof_id_type id = libMesh::DofObject::invalid_id;
if (e)
{
id = e->id();
// Moose::out<<"Storing Elem id: "<<id<<std::endl;
if (id == libMesh::DofObject::invalid_id)
mooseError("Can't output Elems with invalid ids!");
}
else
{
// Moose::out<<"Outputting NULL Elem pointer"<<std::endl;
}
storeHelper(stream, id, context);
}
template<>
void
dataStore(std::ostream & stream, Node * & n, void * context)
{
// Moose::out<<"const Node pointer store"<<std::endl;
// TODO: Write out the unique ID of this node
dof_id_type id = libMesh::DofObject::invalid_id;
if (n)
{
id = n->id();
// Moose::out<<"Storing Node id: "<<id<<std::endl;
if (id == libMesh::DofObject::invalid_id)
mooseError("Can't output Nodes with invalid ids!");
}
else
{
// Moose::out<<"Outputting NULL Node pointer"<<std::endl;
}
storeHelper(stream, id, context);
}
// global load functions
template<>
void
dataLoad(std::istream & stream, Real & v, void * /*context*/)
{
// Moose::out<<"Real dataLoad"<<std::endl;
stream.read((char *) &v, sizeof(v));
}
template<>
void
dataLoad(std::istream & stream, std::string & v, void * /*context*/)
{
// Moose::out<<"std::string dataLoad"<<std::endl;
// Read the size of the string
unsigned int size = 0;
stream.read((char *) &size, sizeof(size));
// Moose::out<<"Size: "<<size<<std::endl;
// Read the string
char* s = new char[size+1];
stream.read(s, sizeof(char)*(size+1));
// Store the string and clean up
v = s;
delete[] s;
}
template<>
void
dataLoad(std::istream & stream, DenseMatrix<Real> & v, void * /*context*/)
{
unsigned int nr = 0, nc = 0;
stream.read((char *) &nr, sizeof(nr));
stream.read((char *) &nc, sizeof(nc));
v.resize(nr,nc);
for (unsigned int i = 0; i < v.m(); i++)
for (unsigned int j = 0; j < v.n(); j++)
{
Real r = 0;
stream.read((char *) &r, sizeof(r));
v(i, j) = r;
}
}
template<>
void
dataLoad(std::istream & stream, ColumnMajorMatrix & v, void * /*context*/)
{
for (unsigned int i = 0; i < v.m(); i++)
for (unsigned int j = 0; j < v.n(); j++)
{
Real r = 0;
stream.read((char *) &r, sizeof(r));
v(i, j) = r;
}
}
template<>
void
dataLoad(std::istream & stream, RealTensorValue & v, void * /*context*/)
{
// Obviously if someone loads data with different LIBMESH_DIM than was used for saving them, it won't work.
for (unsigned int i = 0; i < LIBMESH_DIM; i++)
for (unsigned int j = 0; i < LIBMESH_DIM; i++)
{
Real r = 0;
stream.read((char *) &r, sizeof(r));
v(i, j) = r;
}
}
template<>
void
dataLoad(std::istream & stream, RealVectorValue & v, void * /*context*/)
{
// Obviously if someone loads data with different LIBMESH_DIM than was used for saving them, it won't work.
for (unsigned int i = 0; i < LIBMESH_DIM; i++)
{
Real r = 0;
stream.read((char *) &r, sizeof(r));
v(i) = r;
}
}
template<>
void
dataLoad(std::istream & stream, const Elem * & e, void * context)
{
if (!context)
mooseError("Can only load Elem objects using a MooseMesh context!");
MooseMesh * mesh = static_cast<MooseMesh *>(context);
// Moose::out<<"Elem pointer load"<<std::endl;
// TODO: Write out the unique ID of this element
dof_id_type id = libMesh::DofObject::invalid_id;
loadHelper(stream, id, context);
if (id != libMesh::DofObject::invalid_id)
{
e = mesh->elem(id);
// Moose::out<<"Retrived Elem: "<<id<<std::endl;
// Moose::out<<"Elem ptr: "<<e<<std::endl;
// Moose::out<<"Elem id: "<<e->id()<<std::endl;
}
else
{
e = NULL;
// Moose::out<<"NULL Elem"<<std::endl;
}
}
template<>
void
dataLoad(std::istream & stream, const Node * & n, void * context)
{
if (!context)
mooseError("Can only load Node objects using a MooseMesh context!");
MooseMesh * mesh = static_cast<MooseMesh *>(context);
// Moose::out<<"Node pointer load"<<std::endl;
// TODO: Write out the unique ID of this nodeent
dof_id_type id = libMesh::DofObject::invalid_id;
loadHelper(stream, id, context);
if (id != libMesh::DofObject::invalid_id)
{
n = mesh->nodePtr(id);
// Moose::out<<"Retrived Node: "<<id<<std::endl;
}
else
{
n = NULL;
// Moose::out<<"NULL Node"<<std::endl;
}
}
template<>
void
dataLoad(std::istream & stream, Elem * & e, void * context)
{
if (!context)
mooseError("Can only load Elem objects using a MooseMesh context!");
MooseMesh * mesh = static_cast<MooseMesh *>(context);
// Moose::out<<"Elem pointer load"<<std::endl;
// TODO: Write out the unique ID of this element
dof_id_type id = libMesh::DofObject::invalid_id;
loadHelper(stream, id, context);
if (id != libMesh::DofObject::invalid_id)
{
e = mesh->elem(id);
// Moose::out<<"Retrived Elem: "<<id<<std::endl;
// Moose::out<<"Elem ptr: "<<e<<std::endl;
// Moose::out<<"Elem id: "<<e->id()<<std::endl;
}
else
{
e = NULL;
// Moose::out<<"NULL Elem"<<std::endl;
}
}
template<>
void
dataLoad(std::istream & stream, Node * & n, void * context)
{
if (!context)
mooseError("Can only load Node objects using a MooseMesh context!");
MooseMesh * mesh = static_cast<MooseMesh *>(context);
// Moose::out<<"Node pointer load"<<std::endl;
// TODO: Write out the unique ID of this nodeent
dof_id_type id = libMesh::DofObject::invalid_id;
loadHelper(stream, id, context);
if (id != libMesh::DofObject::invalid_id)
{
n = mesh->nodePtr(id);
// Moose::out<<"Retrived Node: "<<id<<std::endl;
}
else
{
n = NULL;
// Moose::out<<"NULL Node"<<std::endl;
}
}
<|endoftext|> |
<commit_before>#include "gms/gossiper.hh"
#include "gms/failure_detector.hh"
namespace gms {
gossiper::gossiper()
: _scheduled_gossip_task([this] { run(); }) {
// half of QUARATINE_DELAY, to ensure _just_removed_endpoints has enough leeway to prevent re-gossip
fat_client_timeout = (int64_t) (QUARANTINE_DELAY / 2);
/* register with the Failure Detector for receiving Failure detector events */
get_local_failure_detector().register_failure_detection_event_listener(this->shared_from_this());
// Register this instance with JMX
init_messaging_service_handler();
}
void gossiper::init_messaging_service_handler() {
ms().register_handler(messaging_verb::ECHO, [] (empty_msg msg) {
return make_ready_future<empty_msg>();
});
ms().register_handler_oneway(messaging_verb::GOSSIP_SHUTDOWN, [] (inet_address from) {
// TODO: Implement processing of incoming SHUTDOWN message
get_local_failure_detector().force_conviction(from);
return messaging_service::no_wait();
});
ms().register_handler(messaging_verb::GOSSIP_DIGEST_SYN, [] (gossip_digest_syn msg) {
// TODO: Implement processing of incoming ACK2 message
print("gossiper: Server got syn msg = %s\n", msg);
auto ep = inet_address("2.2.2.2");
int32_t gen = 800;
int32_t ver = 900;
std::vector<gms::gossip_digest> digests{
{ep, gen++, ver++},
};
std::map<inet_address, endpoint_state> eps{
{ep, endpoint_state()},
};
gms::gossip_digest_ack ack(std::move(digests), std::move(eps));
return make_ready_future<gossip_digest_ack>(ack);
});
ms().register_handler_oneway(messaging_verb::GOSSIP_DIGEST_ACK2, [] (gossip_digest_ack2 msg) {
print("gossiper: Server got ack2 msg = %s\n", msg);
// TODO: Implement processing of incoming ACK2 message
return messaging_service::no_wait();
});
}
bool gossiper::send_gossip(gossip_digest_syn message, std::set<inet_address> epset) {
std::vector<inet_address> __live_endpoints(epset.begin(), epset.end());
size_t size = __live_endpoints.size();
if (size < 1) {
return false;
}
/* Generate a random number from 0 -> size */
std::uniform_int_distribution<int> dist(0, size - 1);
int index = dist(_random);
inet_address to = __live_endpoints[index];
// if (logger.isTraceEnabled())
// logger.trace("Sending a GossipDigestSyn to {} ...", to);
using RetMsg = gossip_digest_ack;
auto id = get_shard_id(to);
print("send_gossip: Sending to shard %s\n", id);
ms().send_message<RetMsg>(messaging_verb::GOSSIP_DIGEST_SYN, std::move(id), std::move(message)).then([this, id] (RetMsg ack) {
print("send_gossip: Client sent gossip_digest_syn got gossip_digest_ack reply = %s\n", ack);
// TODO: Implement processing of incoming ACK message
auto ep1 = inet_address("3.3.3.3");
std::map<inet_address, endpoint_state> eps{
{ep1, endpoint_state()},
};
gms::gossip_digest_ack2 ack2(std::move(eps));
return ms().send_message_oneway<void>(messaging_verb::GOSSIP_DIGEST_ACK2, std::move(id), std::move(ack2)).then([] () {
print("send_gossip: Client sent gossip_digest_ack2 got reply = void\n");
return make_ready_future<>();
});
});
return _seeds.count(to);
}
void gossiper::notify_failure_detector(inet_address endpoint, endpoint_state remote_endpoint_state) {
/*
* If the local endpoint state exists then report to the FD only
* if the versions workout.
*/
auto it = endpoint_state_map.find(endpoint);
if (it != endpoint_state_map.end()) {
auto& local_endpoint_state = it->second;
i_failure_detector& fd = get_local_failure_detector();
int local_generation = local_endpoint_state.get_heart_beat_state().get_generation();
int remote_generation = remote_endpoint_state.get_heart_beat_state().get_generation();
if (remote_generation > local_generation) {
local_endpoint_state.update_timestamp();
// this node was dead and the generation changed, this indicates a reboot, or possibly a takeover
// we will clean the fd intervals for it and relearn them
if (!local_endpoint_state.is_alive()) {
//logger.debug("Clearing interval times for {} due to generation change", endpoint);
fd.remove(endpoint);
}
fd.report(endpoint);
return;
}
if (remote_generation == local_generation) {
int local_version = get_max_endpoint_state_version(local_endpoint_state);
int remote_version = remote_endpoint_state.get_heart_beat_state().get_heart_beat_version();
if (remote_version > local_version) {
local_endpoint_state.update_timestamp();
// just a version change, report to the fd
fd.report(endpoint);
}
}
}
}
void gossiper::apply_state_locally(std::map<inet_address, endpoint_state>& map) {
for (auto& entry : map) {
auto& ep = entry.first;
if (ep == get_broadcast_address() && !is_in_shadow_round()) {
continue;
}
if (_just_removed_endpoints.count(ep)) {
// if (logger.isTraceEnabled())
// logger.trace("Ignoring gossip for {} because it is quarantined", ep);
continue;
}
/*
If state does not exist just add it. If it does then add it if the remote generation is greater.
If there is a generation tie, attempt to break it by heartbeat version.
*/
endpoint_state& remote_state = entry.second;
auto it = endpoint_state_map.find(ep);
if (it != endpoint_state_map.end()) {
endpoint_state& local_ep_state_ptr = it->second;
int local_generation = local_ep_state_ptr.get_heart_beat_state().get_generation();
int remote_generation = remote_state.get_heart_beat_state().get_generation();
// if (logger.isTraceEnabled()) {
// logger.trace("{} local generation {}, remote generation {}", ep, local_generation, remote_generation);
// }
if (local_generation != 0 && remote_generation > local_generation + MAX_GENERATION_DIFFERENCE) {
// assume some peer has corrupted memory and is broadcasting an unbelievable generation about another peer (or itself)
// logger.warn("received an invalid gossip generation for peer {}; local generation = {}, received generation = {}",
// ep, local_generation, remote_generation);
} else if (remote_generation > local_generation) {
// if (logger.isTraceEnabled())
// logger.trace("Updating heartbeat state generation to {} from {} for {}", remote_generation, local_generation, ep);
// major state change will handle the update by inserting the remote state directly
handle_major_state_change(ep, remote_state);
} else if (remote_generation == local_generation) { //generation has not changed, apply new states
/* find maximum state */
int local_max_version = get_max_endpoint_state_version(local_ep_state_ptr);
int remote_max_version = get_max_endpoint_state_version(remote_state);
if (remote_max_version > local_max_version) {
// apply states, but do not notify since there is no major change
apply_new_states(ep, local_ep_state_ptr, remote_state);
} else {
// if (logger.isTraceEnabled()) {
// logger.trace("Ignoring remote version {} <= {} for {}", remote_max_version, local_max_version, ep);
}
if (!local_ep_state_ptr.is_alive() && !is_dead_state(local_ep_state_ptr)) { // unless of course, it was dead
mark_alive(ep, local_ep_state_ptr);
}
} else {
// if (logger.isTraceEnabled())
// logger.trace("Ignoring remote generation {} < {}", remote_generation, local_generation);
}
} else {
// this is a new node, report it to the FD in case it is the first time we are seeing it AND it's not alive
get_local_failure_detector().report(ep);
handle_major_state_change(ep, remote_state);
fail(unimplemented::cause::GOSSIP);
}
}
}
void gossiper::remove_endpoint(inet_address endpoint) {
// do subscribers first so anything in the subscriber that depends on gossiper state won't get confused
for (shared_ptr<i_endpoint_state_change_subscriber>& subscriber : _subscribers) {
subscriber->on_remove(endpoint);
}
if(_seeds.count(endpoint)) {
build_seeds_list();
_seeds.erase(endpoint);
//logger.info("removed {} from _seeds, updated _seeds list = {}", endpoint, _seeds);
}
_live_endpoints.erase(endpoint);
_unreachable_endpoints.erase(endpoint);
// do not remove endpointState until the quarantine expires
get_local_failure_detector().remove(endpoint);
// FIXME: MessagingService
//MessagingService.instance().resetVersion(endpoint);
fail(unimplemented::cause::GOSSIP);
quarantine_endpoint(endpoint);
// FIXME: MessagingService
//MessagingService.instance().destroyConnectionPool(endpoint);
// if (logger.isDebugEnabled())
// logger.debug("removing endpoint {}", endpoint);
}
void gossiper::do_status_check() {
// if (logger.isTraceEnabled())
// logger.trace("Performing status check ...");
int64_t now = now_millis();
// FIXME:
// int64_t pending = ((JMXEnabledThreadPoolExecutor) StageManager.getStage(Stage.GOSSIP)).getPendingTasks();
int64_t pending = 1;
if (pending > 0 && _last_processed_message_at < now - 1000) {
// FIXME: SLEEP
// if some new messages just arrived, give the executor some time to work on them
//Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
// still behind? something's broke
if (_last_processed_message_at < now - 1000) {
// logger.warn("Gossip stage has {} pending tasks; skipping status check (no nodes will be marked down)", pending);
return;
}
}
for (auto& entry : endpoint_state_map) {
const inet_address& endpoint = entry.first;
if (endpoint == get_broadcast_address()) {
continue;
}
get_local_failure_detector().interpret(endpoint);
fail(unimplemented::cause::GOSSIP);
auto it = endpoint_state_map.find(endpoint);
if (it != endpoint_state_map.end()) {
endpoint_state& ep_state = it->second;
// check if this is a fat client. fat clients are removed automatically from
// gossip after FatClientTimeout. Do not remove dead states here.
if (is_gossip_only_member(endpoint)
&& !_just_removed_endpoints.count(endpoint)
&& ((now - ep_state.get_update_timestamp().time_since_epoch().count()) > fat_client_timeout)) {
// logger.info("FatClient {} has been silent for {}ms, removing from gossip", endpoint, FatClientTimeout);
remove_endpoint(endpoint); // will put it in _just_removed_endpoints to respect quarantine delay
evict_from_membershipg(endpoint); // can get rid of the state immediately
}
// check for dead state removal
int64_t expire_time = get_expire_time_for_endpoint(endpoint);
if (!ep_state.is_alive() && (now > expire_time)) {
/* && (!StorageService.instance.getTokenMetadata().isMember(endpoint))) */
// if (logger.isDebugEnabled()) {
// logger.debug("time is expiring for endpoint : {} ({})", endpoint, expire_time);
// }
evict_from_membershipg(endpoint);
}
}
}
for (auto it = _just_removed_endpoints.begin(); it != _just_removed_endpoints.end();) {
auto& t= it->second;
if ((now - t) > QUARANTINE_DELAY) {
// if (logger.isDebugEnabled())
// logger.debug("{} elapsed, {} gossip quarantine over", QUARANTINE_DELAY, entry.getKey());
it = _just_removed_endpoints.erase(it);
} else {
it++;
}
}
}
void gossiper::run() {
print("---> In Gossip::run() \n");
//wait on messaging service to start listening
// MessagingService.instance().waitUntilListening();
/* Update the local heartbeat counter. */
//endpoint_state_map.get(FBUtilities.getBroadcastAddress()).get_heart_beat_state().updateHeartBeat();
// if (logger.isTraceEnabled())
// logger.trace("My heartbeat is now {}", endpoint_state_map.get(FBUtilities.getBroadcastAddress()).get_heart_beat_state().get_heart_beat_version());
std::vector<gossip_digest> g_digests;
this->make_random_gossip_digest(g_digests);
// FIXME: hack
if (g_digests.size() > 0 || true) {
sstring cluster_name("my cluster_name");
sstring partioner_name("my partioner name");
gossip_digest_syn message(cluster_name, partioner_name, g_digests);
/* Gossip to some random live member */
_live_endpoints.emplace(inet_address("127.0.0.1")); // FIXME: hack
bool gossiped_to_seed = do_gossip_to_live_member(message);
/* Gossip to some unreachable member with some probability to check if he is back up */
do_gossip_to_unreachable_member(message);
/* Gossip to a seed if we did not do so above, or we have seen less nodes
than there are seeds. This prevents partitions where each group of nodes
is only gossiping to a subset of the seeds.
The most straightforward check would be to check that all the seeds have been
verified either as live or unreachable. To avoid that computation each round,
we reason that:
either all the live nodes are seeds, in which case non-seeds that come online
will introduce themselves to a member of the ring by definition,
or there is at least one non-seed node in the list, in which case eventually
someone will gossip to it, and then do a gossip to a random seed from the
gossipedToSeed check.
See CASSANDRA-150 for more exposition. */
if (!gossiped_to_seed || _live_endpoints.size() < _seeds.size()) {
do_gossip_to_seed(message);
}
do_status_check();
}
}
} // namespace gms
<commit_msg>gossip: Implement GossipDigestAck2VerbHandler<commit_after>#include "gms/gossiper.hh"
#include "gms/failure_detector.hh"
namespace gms {
gossiper::gossiper()
: _scheduled_gossip_task([this] { run(); }) {
// half of QUARATINE_DELAY, to ensure _just_removed_endpoints has enough leeway to prevent re-gossip
fat_client_timeout = (int64_t) (QUARANTINE_DELAY / 2);
/* register with the Failure Detector for receiving Failure detector events */
get_local_failure_detector().register_failure_detection_event_listener(this->shared_from_this());
// Register this instance with JMX
init_messaging_service_handler();
}
void gossiper::init_messaging_service_handler() {
ms().register_handler(messaging_verb::ECHO, [] (empty_msg msg) {
return make_ready_future<empty_msg>();
});
ms().register_handler_oneway(messaging_verb::GOSSIP_SHUTDOWN, [] (inet_address from) {
// TODO: Implement processing of incoming SHUTDOWN message
get_local_failure_detector().force_conviction(from);
return messaging_service::no_wait();
});
ms().register_handler(messaging_verb::GOSSIP_DIGEST_SYN, [] (gossip_digest_syn msg) {
// TODO: Implement processing of incoming ACK2 message
print("gossiper: Server got syn msg = %s\n", msg);
auto ep = inet_address("2.2.2.2");
int32_t gen = 800;
int32_t ver = 900;
std::vector<gms::gossip_digest> digests{
{ep, gen++, ver++},
};
std::map<inet_address, endpoint_state> eps{
{ep, endpoint_state()},
};
gms::gossip_digest_ack ack(std::move(digests), std::move(eps));
return make_ready_future<gossip_digest_ack>(ack);
});
ms().register_handler_oneway(messaging_verb::GOSSIP_DIGEST_ACK2, [this] (gossip_digest_ack2 msg) {
print("gossiper: Server got ack2 msg = %s\n", msg);
auto& remote_ep_state_map = msg.get_endpoint_state_map();
/* Notify the Failure Detector */
this->notify_failure_detector(remote_ep_state_map);
this->apply_state_locally(remote_ep_state_map);
return messaging_service::no_wait();
});
}
bool gossiper::send_gossip(gossip_digest_syn message, std::set<inet_address> epset) {
std::vector<inet_address> __live_endpoints(epset.begin(), epset.end());
size_t size = __live_endpoints.size();
if (size < 1) {
return false;
}
/* Generate a random number from 0 -> size */
std::uniform_int_distribution<int> dist(0, size - 1);
int index = dist(_random);
inet_address to = __live_endpoints[index];
// if (logger.isTraceEnabled())
// logger.trace("Sending a GossipDigestSyn to {} ...", to);
using RetMsg = gossip_digest_ack;
auto id = get_shard_id(to);
print("send_gossip: Sending to shard %s\n", id);
ms().send_message<RetMsg>(messaging_verb::GOSSIP_DIGEST_SYN, std::move(id), std::move(message)).then([this, id] (RetMsg ack) {
print("send_gossip: Client sent gossip_digest_syn got gossip_digest_ack reply = %s\n", ack);
// TODO: Implement processing of incoming ACK message
auto ep1 = inet_address("3.3.3.3");
std::map<inet_address, endpoint_state> eps{
{ep1, endpoint_state()},
};
gms::gossip_digest_ack2 ack2(std::move(eps));
return ms().send_message_oneway<void>(messaging_verb::GOSSIP_DIGEST_ACK2, std::move(id), std::move(ack2)).then([] () {
print("send_gossip: Client sent gossip_digest_ack2 got reply = void\n");
return make_ready_future<>();
});
});
return _seeds.count(to);
}
void gossiper::notify_failure_detector(inet_address endpoint, endpoint_state remote_endpoint_state) {
/*
* If the local endpoint state exists then report to the FD only
* if the versions workout.
*/
auto it = endpoint_state_map.find(endpoint);
if (it != endpoint_state_map.end()) {
auto& local_endpoint_state = it->second;
i_failure_detector& fd = get_local_failure_detector();
int local_generation = local_endpoint_state.get_heart_beat_state().get_generation();
int remote_generation = remote_endpoint_state.get_heart_beat_state().get_generation();
if (remote_generation > local_generation) {
local_endpoint_state.update_timestamp();
// this node was dead and the generation changed, this indicates a reboot, or possibly a takeover
// we will clean the fd intervals for it and relearn them
if (!local_endpoint_state.is_alive()) {
//logger.debug("Clearing interval times for {} due to generation change", endpoint);
fd.remove(endpoint);
}
fd.report(endpoint);
return;
}
if (remote_generation == local_generation) {
int local_version = get_max_endpoint_state_version(local_endpoint_state);
int remote_version = remote_endpoint_state.get_heart_beat_state().get_heart_beat_version();
if (remote_version > local_version) {
local_endpoint_state.update_timestamp();
// just a version change, report to the fd
fd.report(endpoint);
}
}
}
}
void gossiper::apply_state_locally(std::map<inet_address, endpoint_state>& map) {
for (auto& entry : map) {
auto& ep = entry.first;
if (ep == get_broadcast_address() && !is_in_shadow_round()) {
continue;
}
if (_just_removed_endpoints.count(ep)) {
// if (logger.isTraceEnabled())
// logger.trace("Ignoring gossip for {} because it is quarantined", ep);
continue;
}
/*
If state does not exist just add it. If it does then add it if the remote generation is greater.
If there is a generation tie, attempt to break it by heartbeat version.
*/
endpoint_state& remote_state = entry.second;
auto it = endpoint_state_map.find(ep);
if (it != endpoint_state_map.end()) {
endpoint_state& local_ep_state_ptr = it->second;
int local_generation = local_ep_state_ptr.get_heart_beat_state().get_generation();
int remote_generation = remote_state.get_heart_beat_state().get_generation();
// if (logger.isTraceEnabled()) {
// logger.trace("{} local generation {}, remote generation {}", ep, local_generation, remote_generation);
// }
if (local_generation != 0 && remote_generation > local_generation + MAX_GENERATION_DIFFERENCE) {
// assume some peer has corrupted memory and is broadcasting an unbelievable generation about another peer (or itself)
// logger.warn("received an invalid gossip generation for peer {}; local generation = {}, received generation = {}",
// ep, local_generation, remote_generation);
} else if (remote_generation > local_generation) {
// if (logger.isTraceEnabled())
// logger.trace("Updating heartbeat state generation to {} from {} for {}", remote_generation, local_generation, ep);
// major state change will handle the update by inserting the remote state directly
handle_major_state_change(ep, remote_state);
} else if (remote_generation == local_generation) { //generation has not changed, apply new states
/* find maximum state */
int local_max_version = get_max_endpoint_state_version(local_ep_state_ptr);
int remote_max_version = get_max_endpoint_state_version(remote_state);
if (remote_max_version > local_max_version) {
// apply states, but do not notify since there is no major change
apply_new_states(ep, local_ep_state_ptr, remote_state);
} else {
// if (logger.isTraceEnabled()) {
// logger.trace("Ignoring remote version {} <= {} for {}", remote_max_version, local_max_version, ep);
}
if (!local_ep_state_ptr.is_alive() && !is_dead_state(local_ep_state_ptr)) { // unless of course, it was dead
mark_alive(ep, local_ep_state_ptr);
}
} else {
// if (logger.isTraceEnabled())
// logger.trace("Ignoring remote generation {} < {}", remote_generation, local_generation);
}
} else {
// this is a new node, report it to the FD in case it is the first time we are seeing it AND it's not alive
get_local_failure_detector().report(ep);
handle_major_state_change(ep, remote_state);
fail(unimplemented::cause::GOSSIP);
}
}
}
void gossiper::remove_endpoint(inet_address endpoint) {
// do subscribers first so anything in the subscriber that depends on gossiper state won't get confused
for (shared_ptr<i_endpoint_state_change_subscriber>& subscriber : _subscribers) {
subscriber->on_remove(endpoint);
}
if(_seeds.count(endpoint)) {
build_seeds_list();
_seeds.erase(endpoint);
//logger.info("removed {} from _seeds, updated _seeds list = {}", endpoint, _seeds);
}
_live_endpoints.erase(endpoint);
_unreachable_endpoints.erase(endpoint);
// do not remove endpointState until the quarantine expires
get_local_failure_detector().remove(endpoint);
// FIXME: MessagingService
//MessagingService.instance().resetVersion(endpoint);
fail(unimplemented::cause::GOSSIP);
quarantine_endpoint(endpoint);
// FIXME: MessagingService
//MessagingService.instance().destroyConnectionPool(endpoint);
// if (logger.isDebugEnabled())
// logger.debug("removing endpoint {}", endpoint);
}
void gossiper::do_status_check() {
// if (logger.isTraceEnabled())
// logger.trace("Performing status check ...");
int64_t now = now_millis();
// FIXME:
// int64_t pending = ((JMXEnabledThreadPoolExecutor) StageManager.getStage(Stage.GOSSIP)).getPendingTasks();
int64_t pending = 1;
if (pending > 0 && _last_processed_message_at < now - 1000) {
// FIXME: SLEEP
// if some new messages just arrived, give the executor some time to work on them
//Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
// still behind? something's broke
if (_last_processed_message_at < now - 1000) {
// logger.warn("Gossip stage has {} pending tasks; skipping status check (no nodes will be marked down)", pending);
return;
}
}
for (auto& entry : endpoint_state_map) {
const inet_address& endpoint = entry.first;
if (endpoint == get_broadcast_address()) {
continue;
}
get_local_failure_detector().interpret(endpoint);
fail(unimplemented::cause::GOSSIP);
auto it = endpoint_state_map.find(endpoint);
if (it != endpoint_state_map.end()) {
endpoint_state& ep_state = it->second;
// check if this is a fat client. fat clients are removed automatically from
// gossip after FatClientTimeout. Do not remove dead states here.
if (is_gossip_only_member(endpoint)
&& !_just_removed_endpoints.count(endpoint)
&& ((now - ep_state.get_update_timestamp().time_since_epoch().count()) > fat_client_timeout)) {
// logger.info("FatClient {} has been silent for {}ms, removing from gossip", endpoint, FatClientTimeout);
remove_endpoint(endpoint); // will put it in _just_removed_endpoints to respect quarantine delay
evict_from_membershipg(endpoint); // can get rid of the state immediately
}
// check for dead state removal
int64_t expire_time = get_expire_time_for_endpoint(endpoint);
if (!ep_state.is_alive() && (now > expire_time)) {
/* && (!StorageService.instance.getTokenMetadata().isMember(endpoint))) */
// if (logger.isDebugEnabled()) {
// logger.debug("time is expiring for endpoint : {} ({})", endpoint, expire_time);
// }
evict_from_membershipg(endpoint);
}
}
}
for (auto it = _just_removed_endpoints.begin(); it != _just_removed_endpoints.end();) {
auto& t= it->second;
if ((now - t) > QUARANTINE_DELAY) {
// if (logger.isDebugEnabled())
// logger.debug("{} elapsed, {} gossip quarantine over", QUARANTINE_DELAY, entry.getKey());
it = _just_removed_endpoints.erase(it);
} else {
it++;
}
}
}
void gossiper::run() {
print("---> In Gossip::run() \n");
//wait on messaging service to start listening
// MessagingService.instance().waitUntilListening();
/* Update the local heartbeat counter. */
//endpoint_state_map.get(FBUtilities.getBroadcastAddress()).get_heart_beat_state().updateHeartBeat();
// if (logger.isTraceEnabled())
// logger.trace("My heartbeat is now {}", endpoint_state_map.get(FBUtilities.getBroadcastAddress()).get_heart_beat_state().get_heart_beat_version());
std::vector<gossip_digest> g_digests;
this->make_random_gossip_digest(g_digests);
// FIXME: hack
if (g_digests.size() > 0 || true) {
sstring cluster_name("my cluster_name");
sstring partioner_name("my partioner name");
gossip_digest_syn message(cluster_name, partioner_name, g_digests);
/* Gossip to some random live member */
_live_endpoints.emplace(inet_address("127.0.0.1")); // FIXME: hack
bool gossiped_to_seed = do_gossip_to_live_member(message);
/* Gossip to some unreachable member with some probability to check if he is back up */
do_gossip_to_unreachable_member(message);
/* Gossip to a seed if we did not do so above, or we have seen less nodes
than there are seeds. This prevents partitions where each group of nodes
is only gossiping to a subset of the seeds.
The most straightforward check would be to check that all the seeds have been
verified either as live or unreachable. To avoid that computation each round,
we reason that:
either all the live nodes are seeds, in which case non-seeds that come online
will introduce themselves to a member of the ring by definition,
or there is at least one non-seed node in the list, in which case eventually
someone will gossip to it, and then do a gossip to a random seed from the
gossipedToSeed check.
See CASSANDRA-150 for more exposition. */
if (!gossiped_to_seed || _live_endpoints.size() < _seeds.size()) {
do_gossip_to_seed(message);
}
do_status_check();
}
}
} // namespace gms
<|endoftext|> |
<commit_before>#include "xchainer/shape.h"
#include <gtest/gtest.h>
#include "xchainer/dtype.h"
#include "xchainer/strides.h"
namespace xchainer {
namespace {
void CheckSpanEqual(std::initializer_list<int64_t> expect, gsl::span<const int64_t> actual) {
EXPECT_EQ(gsl::make_span(expect.begin(), expect.end()), actual);
}
TEST(ShapeTest, Ctor) {
{
const Shape shape = {2, 3, 4};
EXPECT_EQ(3, shape.ndim());
EXPECT_EQ(size_t{3}, shape.size());
CheckSpanEqual({2, 3, 4}, shape.span());
EXPECT_EQ(2 * 3 * 4, shape.GetTotalSize());
}
{
const std::array<int64_t, 3> dims = {2, 3, 4};
const Shape shape(gsl::make_span(dims));
EXPECT_EQ(3, shape.ndim());
CheckSpanEqual({2, 3, 4}, shape.span());
}
{
const std::array<int64_t, kMaxNdim + 1> too_long = {1};
EXPECT_THROW(Shape(gsl::make_span(too_long)), DimensionError);
}
}
TEST(ShapeTest, Subscript) {
const Shape shape = {2, 3, 4};
EXPECT_EQ(2, shape[0]);
EXPECT_EQ(3, shape[1]);
EXPECT_EQ(4, shape[2]);
EXPECT_THROW(shape[-1], DimensionError);
EXPECT_THROW(shape[3], DimensionError);
}
TEST(ShapeTest, Compare) {
{
const Shape shape = {2, 3, 4};
const Shape shape2 = {2, 3, 4};
EXPECT_TRUE(shape == shape2);
}
{
const Shape shape = {2, 3, 4};
const Shape shape2 = {2, 3};
EXPECT_TRUE(shape != shape2);
}
{
const Shape shape = {2, 3, 4};
const Shape shape2 = {1, 2, 3};
EXPECT_TRUE(shape != shape2);
}
}
TEST(ShapeTest, CheckEqual) {
{
const Shape shape = {2, 3, 4};
const Shape shape2 = {2, 3, 4};
EXPECT_NO_THROW(CheckEqual(shape, shape2));
}
{
const Shape shape = {2, 3, 4};
const Shape shape2 = {};
EXPECT_THROW(CheckEqual(shape, shape2), DimensionError);
}
}
TEST(ShapeTest, Iterator) {
const Shape shape = {2, 3, 4};
CheckSpanEqual({2, 3, 4}, gsl::make_span(shape.begin(), shape.end()));
CheckSpanEqual({4, 3, 2}, gsl::make_span(std::vector<int64_t>{shape.rbegin(), shape.rend()}));
}
TEST(ShapeTest, ToString) {
{
const Shape shape = {};
EXPECT_EQ(shape.ToString(), "()");
}
{
const Shape shape = {1};
EXPECT_EQ(shape.ToString(), "(1,)");
}
{
const Shape shape = {2, 3, 4};
EXPECT_EQ(shape.ToString(), "(2, 3, 4)");
}
}
TEST(ShapeTest, IsContiguous) {
{
Shape shape{2, 3, 4};
Strides strides{shape, GetElementSize(Dtype::kFloat64)};
EXPECT_TRUE(internal::IsContiguous(shape, strides, GetElementSize(Dtype::kFloat64)));
}
{
Shape shape{2, 3, 4};
Strides strides{shape, GetElementSize(Dtype::kFloat64)};
EXPECT_FALSE(internal::IsContiguous(shape, strides, GetElementSize(Dtype::kFloat32)));
}
}
} // namespace
} // namespace xchainer
<commit_msg>Add more IsContiguous tests<commit_after>#include "xchainer/shape.h"
#include <gtest/gtest.h>
#include "xchainer/dtype.h"
#include "xchainer/strides.h"
namespace xchainer {
namespace {
void CheckSpanEqual(std::initializer_list<int64_t> expect, gsl::span<const int64_t> actual) {
EXPECT_EQ(gsl::make_span(expect.begin(), expect.end()), actual);
}
TEST(ShapeTest, Ctor) {
{
const Shape shape = {2, 3, 4};
EXPECT_EQ(3, shape.ndim());
EXPECT_EQ(size_t{3}, shape.size());
CheckSpanEqual({2, 3, 4}, shape.span());
EXPECT_EQ(2 * 3 * 4, shape.GetTotalSize());
}
{
const std::array<int64_t, 3> dims = {2, 3, 4};
const Shape shape(gsl::make_span(dims));
EXPECT_EQ(3, shape.ndim());
CheckSpanEqual({2, 3, 4}, shape.span());
}
{
const std::array<int64_t, kMaxNdim + 1> too_long = {1};
EXPECT_THROW(Shape(gsl::make_span(too_long)), DimensionError);
}
}
TEST(ShapeTest, Subscript) {
const Shape shape = {2, 3, 4};
EXPECT_EQ(2, shape[0]);
EXPECT_EQ(3, shape[1]);
EXPECT_EQ(4, shape[2]);
EXPECT_THROW(shape[-1], DimensionError);
EXPECT_THROW(shape[3], DimensionError);
}
TEST(ShapeTest, Compare) {
{
const Shape shape = {2, 3, 4};
const Shape shape2 = {2, 3, 4};
EXPECT_TRUE(shape == shape2);
}
{
const Shape shape = {2, 3, 4};
const Shape shape2 = {2, 3};
EXPECT_TRUE(shape != shape2);
}
{
const Shape shape = {2, 3, 4};
const Shape shape2 = {1, 2, 3};
EXPECT_TRUE(shape != shape2);
}
}
TEST(ShapeTest, CheckEqual) {
{
const Shape shape = {2, 3, 4};
const Shape shape2 = {2, 3, 4};
EXPECT_NO_THROW(CheckEqual(shape, shape2));
}
{
const Shape shape = {2, 3, 4};
const Shape shape2 = {};
EXPECT_THROW(CheckEqual(shape, shape2), DimensionError);
}
}
TEST(ShapeTest, Iterator) {
const Shape shape = {2, 3, 4};
CheckSpanEqual({2, 3, 4}, gsl::make_span(shape.begin(), shape.end()));
CheckSpanEqual({4, 3, 2}, gsl::make_span(std::vector<int64_t>{shape.rbegin(), shape.rend()}));
}
TEST(ShapeTest, ToString) {
{
const Shape shape = {};
EXPECT_EQ(shape.ToString(), "()");
}
{
const Shape shape = {1};
EXPECT_EQ(shape.ToString(), "(1,)");
}
{
const Shape shape = {2, 3, 4};
EXPECT_EQ(shape.ToString(), "(2, 3, 4)");
}
}
TEST(ShapeTest, IsContiguous) {
{
Shape shape{2, 3, 4};
Strides strides{shape, GetElementSize(Dtype::kFloat32)};
EXPECT_TRUE(internal::IsContiguous(shape, strides, GetElementSize(Dtype::kFloat32)));
}
{
Shape shape{2, 3, 4};
Strides strides{shape, GetElementSize(Dtype::kFloat32)};
EXPECT_FALSE(internal::IsContiguous(shape, strides, GetElementSize(Dtype::kFloat64)));
}
{
Shape shape{2, 3, 4};
Strides strides{48, 16, 4};
EXPECT_TRUE(internal::IsContiguous(shape, strides, GetElementSize(Dtype::kFloat32)));
}
{
Shape shape{2, 3, 4};
Strides strides{32, 16, 4};
EXPECT_FALSE(internal::IsContiguous(shape, strides, GetElementSize(Dtype::kFloat32)));
}
}
} // namespace
} // namespace xchainer
<|endoftext|> |
<commit_before>#include "../include/FileReaderWriter.h"
#include "../include/LogicEvent.h"
#include "../include/FileState.h"
#include <iostream>
//See copyright notice in file Copyright in the root directory of this archive.
using namespace std;
FileReaderWriter::FileReaderWriter(string &filename,int numofgates,
string io, vector<int> *desportid,
vector<string> *desgatesnames,int maxnumlines):
fileName(filename),numOfGates(numofgates),IO(io),desPortId(desportid),
desGatesNames(desgatesnames),maxNumLines(maxnumlines),fileIoStream(0){}
FileReaderWriter::~FileReaderWriter(){
if(numOfGates != 0){
delete desGatesNames;
delete [] outputHandles;
delete fileIoStream;
}
}
void
FileReaderWriter::initialize(){
string objname = getName();
cout<<endl;
cout<<"this is " << objname<<endl;
if(numOfGates != 0){
outputHandles = new SimulationObject *[numOfGates];
for (int i = 0; i < numOfGates; i++ ){
outputHandles[i] = getObjectHandle((*desGatesNames)[i]);
cout<<"my des gate is "<<((*desGatesNames)[i])<<endl;
}
}
if("I"==IO){
fileIoStream = openInputFile(fileName);
ostringstream bitstring;
string bitS = getLine(fileIoStream,bitstring);
if (bitS=="")
cout<<"Fail to read the first line from the input file"<<endl;
else{
FileState *state = dynamic_cast<FileState *>(getState());
int bit = getBitValue(bitS);
cout<<"the bit read from "<<fileName<<" is "<<bit<<endl;
clearOstringstream(bitstring);
IntVTime sendTime = dynamic_cast<const IntVTime&>(getSimulationTime());
double ldelay = 1.0;
IntVTime recvTime = sendTime +(int)ldelay;
LogicEvent *newEvent = new LogicEvent(sendTime,
recvTime,
this,
this);
newEvent->bitValue = bit;
newEvent->sourcePort = 1;
newEvent->destinationPort =0; // leave this field, will be filled out in the executeProcess()
state->numLinesProcessed++;
cout<<state->numLinesProcessed<<" lines have been read. "<<endl;
this->receiveEvent(newEvent);
}
}
if("O"==IO){
fileIoStream = openOutputFile(fileName,ios::out);
cout<<"I have no des gate."<<endl;
}
cout<<getName()<<" finishes the initilization."<<endl;
}
void
FileReaderWriter::finalize(){}
void
FileReaderWriter::executeProcess(){
FileState *state = static_cast<FileState *> (getState());
cout<<endl;
cout<<"in the executeProcess()"<< getName()<<endl;
LogicEvent *logicEvent = NULL;
while(true == haveMoreEvents()){
logicEvent = (LogicEvent *)getEvent();
if(logicEvent != NULL){
IntVTime sendTime = static_cast<const IntVTime&>(getSimulationTime());
if("I"==IO){
//send the event to the gate
for(int i = 0; i < numOfGates; i++){
//SimulationObject *receiver = getObjectHandle(desGateName);
LogicEvent *sendToGate = new LogicEvent(sendTime,
sendTime+1,
this,
outputHandles[i]);
sendToGate->bitValue = logicEvent->bitValue;
sendToGate->sourcePort = logicEvent->sourcePort;
sendToGate->destinationPort = (*desPortId)[i];
outputHandles[i]->receiveEvent(sendToGate);
cout<<(*desGatesNames)[i]<<" receives the event"<<endl;
cout<<"des port is "<<(*desPortId)[i]<<endl;
}
//read one line and send an event to itself
int lineprocessed = state->numLinesProcessed;
if(lineprocessed < maxNumLines){
ostringstream bitstring;
string bitS = getLine(fileIoStream,bitstring);
int bit = getBitValue(bitS);
clearOstringstream(bitstring);
LogicEvent *sendToSelf = new LogicEvent(sendTime,
sendTime+1,
this,
this);
sendToSelf->setbitValue(bit);
sendToSelf->setsourcePort(1);
sendToSelf->setdestinationPort(0);
state->numLinesProcessed++;
this->receiveEvent(sendToSelf);
}
}
if("O"==IO){
ostringstream outstream;
outstream<<logicEvent->bitValue;
fileIoStream->insert(outstream);
fileIoStream->flush();
}
}
}
}
State*
FileReaderWriter::allocateState() {
//return (State *) new NInputGateState(numberOfInputs);
return (State*) new FileState();
}
void
FileReaderWriter::deallocateState(const State *state){
//delete (NInputGateState *)state;
delete (FileState*) state;
}
void
FileReaderWriter::reclaimEvent(const Event *event){
delete (LogicEvent *)event;
}
void
FileReaderWriter::reportError(const string &msg, SEVERITY level){}
SimulationStream*
FileReaderWriter::openInputFile(string& filename){
return getIFStream(filename);
}
SimulationStream*
FileReaderWriter::openOutputFile(string& filename,ios::openmode mode){
return getOFStream(filename, mode);
}
bool
FileReaderWriter::haveMoreLines(SimulationStream* simPt){
return !(simPt->eof());
}
string
FileReaderWriter::getLine(SimulationStream* simPt, ostringstream& ost){
return (simPt->readLine(ost)).str();
}
void
FileReaderWriter::clearOstringstream(ostringstream& ost){
ost.str("");
}
int
FileReaderWriter::getBitValue(string logicBit){
stringstream sstream;
int bitValue;
sstream << logicBit;
sstream >> bitValue;
return bitValue;
}
<commit_msg>adjust the code format<commit_after>#include "../include/FileReaderWriter.h"
#include "../include/LogicEvent.h"
#include "../include/FileState.h"
#include <iostream>
//See copyright notice in file Copyright in the root directory of this archive.
using namespace std;
FileReaderWriter::FileReaderWriter(string &filename,int numofgates,
string io, vector<int> *desportid,
vector<string> *desgatesnames,int maxnumlines):
fileName(filename),numOfGates(numofgates),IO(io),desPortId(desportid),
desGatesNames(desgatesnames),maxNumLines(maxnumlines),fileIoStream(0){}
FileReaderWriter::~FileReaderWriter(){ }
void
FileReaderWriter::initialize(){
string objname = getName();
cout<<endl;
cout<<"this is " << objname<<endl;
if(numOfGates != 0){
outputHandles = new SimulationObject *[numOfGates];
for (int i = 0; i < numOfGates; i++ ){
outputHandles[i] = getObjectHandle((*desGatesNames)[i]);
cout<<"my des gate is "<<((*desGatesNames)[i])<<endl;
}
}
if("I"==IO){
fileIoStream = openInputFile(fileName);
ostringstream bitstring;
string bitS = getLine(fileIoStream,bitstring);
if (bitS=="")
cout<<"Fail to read the first line from the input file"<<endl;
else{
FileState *state = dynamic_cast<FileState *>(getState());
int bit = getBitValue(bitS);
cout<<"the bit read from "<<fileName<<" is "<<bit<<endl;
clearOstringstream(bitstring);
IntVTime sendTime = dynamic_cast<const IntVTime&>(getSimulationTime());
double ldelay = 1.0;
IntVTime recvTime = sendTime +(int)ldelay;
LogicEvent *newEvent = new LogicEvent(sendTime,
recvTime,
this,
this);
newEvent->bitValue = bit;
newEvent->sourcePort = 1;
newEvent->destinationPort =0; // leave this field, will be filled out in the executeProcess()
state->numLinesProcessed++;
cout<<state->numLinesProcessed<<" lines have been read. "<<endl;
this->receiveEvent(newEvent);
}
}
if("O"==IO){
fileIoStream = openOutputFile(fileName,ios::out);
cout<<"I have no des gate."<<endl;
}
cout<<getName()<<" finishes the initilization."<<endl;
}
void
FileReaderWriter::finalize(){ /*fileIoStream -> flush();*/}
void
FileReaderWriter::executeProcess(){
FileState *state = static_cast<FileState *> (getState());
cout<<endl;
cout<<"in the executeProcess()"<< getName()<<endl;
LogicEvent *logicEvent = NULL;
while(true == haveMoreEvents()){
logicEvent = (LogicEvent *)getEvent();
if(logicEvent != NULL){
IntVTime sendTime = static_cast<const IntVTime&>(getSimulationTime());
if("I"==IO){
//send the event to the gate
for(int i = 0; i < numOfGates; i++){
//SimulationObject *receiver = getObjectHandle(desGateName);
LogicEvent *sendToGate = new LogicEvent(sendTime,
sendTime+1,
this,
outputHandles[i]);
sendToGate->bitValue = logicEvent->bitValue;
sendToGate->sourcePort = logicEvent->sourcePort;
sendToGate->destinationPort = (*desPortId)[i];
outputHandles[i]->receiveEvent(sendToGate);
cout<<(*desGatesNames)[i]<<" receives the event"<<endl;
cout<<"des port is "<<(*desPortId)[i]<<endl;
}
//read one line and send an event to itself
int lineprocessed = state->numLinesProcessed;
if(lineprocessed < maxNumLines){
ostringstream bitstring;
string bitS = getLine(fileIoStream,bitstring);
int bit = getBitValue(bitS);
clearOstringstream(bitstring);
LogicEvent *sendToSelf = new LogicEvent(sendTime,
sendTime+1,
this,
this);
sendToSelf->setbitValue(bit);
sendToSelf->setsourcePort(1);
sendToSelf->setdestinationPort(0);
state->numLinesProcessed++;
this->receiveEvent(sendToSelf);
}
}
if("O"==IO){
int writetimes = state->numLinesProcessed;
if(writetimes<maxNumLines){
ostringstream outstream;
outstream<<logicEvent->bitValue;
cout<<"write to file!"<<endl;
fileIoStream->insert(outstream);
fileIoStream->flush();
cout<<"finish write"<<endl;
// fileIoStream->put('a');
state->numLinesProcessed++;
}
}
}
}
}
State*
FileReaderWriter::allocateState() {
//return (State *) new NInputGateState(numberOfInputs);
return (State*) new FileState();
}
void
FileReaderWriter::deallocateState(const State *state){
//delete (NInputGateState *)state;
delete (FileState*) state;
}
void
FileReaderWriter::reclaimEvent(const Event *event){
delete (LogicEvent *)event;
}
void
FileReaderWriter::reportError(const string &msg, SEVERITY level){}
SimulationStream*
FileReaderWriter::openInputFile(string& filename){
return getIFStream(filename);
}
SimulationStream*
FileReaderWriter::openOutputFile(string& filename,ios::openmode mode){
return getOFStream(filename, mode);
}
bool
FileReaderWriter::haveMoreLines(SimulationStream* simPt){
return !(simPt->eof());
}
string
FileReaderWriter::getLine(SimulationStream* simPt, ostringstream& ost){
return (simPt->readLine(ost)).str();
}
void
FileReaderWriter::clearOstringstream(ostringstream& ost){
ost.str("");
}
int
FileReaderWriter::getBitValue(string logicBit){
stringstream sstream;
int bitValue;
sstream << logicBit;
sstream >> bitValue;
return bitValue;
}
<|endoftext|> |
<commit_before>// gogo-tree.cc -- convert Go frontend Gogo IR to gcc trees.
// Copyright 2009 The Go 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 "go-system.h"
#include "toplev.h"
#include "tree.h"
#include "stringpool.h"
#include "stor-layout.h"
#include "varasm.h"
#include "gimple-expr.h"
#include "gimplify.h"
#include "tree-iterator.h"
#include "cgraph.h"
#include "langhooks.h"
#include "convert.h"
#include "output.h"
#include "diagnostic.h"
#include "go-c.h"
#include "types.h"
#include "expressions.h"
#include "statements.h"
#include "runtime.h"
#include "backend.h"
#include "gogo.h"
// Whether we have seen any errors.
bool
saw_errors()
{
return errorcount != 0 || sorrycount != 0;
}
// Return the integer type to use for a size.
GO_EXTERN_C
tree
go_type_for_size(unsigned int bits, int unsignedp)
{
const char* name;
switch (bits)
{
case 8:
name = unsignedp ? "uint8" : "int8";
break;
case 16:
name = unsignedp ? "uint16" : "int16";
break;
case 32:
name = unsignedp ? "uint32" : "int32";
break;
case 64:
name = unsignedp ? "uint64" : "int64";
break;
default:
if (bits == POINTER_SIZE && unsignedp)
name = "uintptr";
else
return NULL_TREE;
}
Type* type = Type::lookup_integer_type(name);
return type_to_tree(type->get_backend(go_get_gogo()));
}
// Return the type to use for a mode.
GO_EXTERN_C
tree
go_type_for_mode(enum machine_mode mode, int unsignedp)
{
// FIXME: This static_cast should be in machmode.h.
enum mode_class mc = static_cast<enum mode_class>(GET_MODE_CLASS(mode));
if (mc == MODE_INT)
return go_type_for_size(GET_MODE_BITSIZE(mode), unsignedp);
else if (mc == MODE_FLOAT)
{
Type* type;
switch (GET_MODE_BITSIZE (mode))
{
case 32:
type = Type::lookup_float_type("float32");
break;
case 64:
type = Type::lookup_float_type("float64");
break;
default:
// We have to check for long double in order to support
// i386 excess precision.
if (mode == TYPE_MODE(long_double_type_node))
return long_double_type_node;
return NULL_TREE;
}
return type_to_tree(type->get_backend(go_get_gogo()));
}
else if (mc == MODE_COMPLEX_FLOAT)
{
Type *type;
switch (GET_MODE_BITSIZE (mode))
{
case 64:
type = Type::lookup_complex_type("complex64");
break;
case 128:
type = Type::lookup_complex_type("complex128");
break;
default:
// We have to check for long double in order to support
// i386 excess precision.
if (mode == TYPE_MODE(complex_long_double_type_node))
return complex_long_double_type_node;
return NULL_TREE;
}
return type_to_tree(type->get_backend(go_get_gogo()));
}
else
return NULL_TREE;
}
<commit_msg>compiler: Remove GCC langhooks from frontend proper.<commit_after>// gogo-tree.cc -- convert Go frontend Gogo IR to gcc trees.
// Copyright 2009 The Go 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 "go-system.h"
#include "toplev.h"
#include "tree.h"
#include "stringpool.h"
#include "stor-layout.h"
#include "varasm.h"
#include "gimple-expr.h"
#include "gimplify.h"
#include "tree-iterator.h"
#include "cgraph.h"
#include "langhooks.h"
#include "convert.h"
#include "output.h"
#include "diagnostic.h"
#include "go-c.h"
#include "types.h"
#include "expressions.h"
#include "statements.h"
#include "runtime.h"
#include "backend.h"
#include "gogo.h"
// Whether we have seen any errors.
bool
saw_errors()
{
return errorcount != 0 || sorrycount != 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include <SFML/Graphics.hpp>
#include <GL/gl.h>
#include <DMUtils/maths.hpp>
#include <DMUtils/sfml.hpp>
#include <LightSystem/LightSystem.hpp>
#include <LightSystem/SpotLight.hpp>
#define WIDTH 640
#define HEIGHT 480
//font taken from http://www.fontspace.com/melifonts/sweet-cheeks
int main(int argc, char** argv) {
sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT), "LightSystem test");
bool debugLightMapOnly = false;
bool aabb = false;
bool debugUseShader = true;
bool debugDrawLights = true;
bool update = false;
//bg
sf::Texture bg;
if(!bg.loadFromFile("data/map.png")) exit(-1);
//if(!bg.loadFromFile("data/map2.jpg")) exit(-1);
//bg.setRepeated(true);
sf::Sprite bgSpr(bg,sf::IntRect(0,0,WIDTH,HEIGHT));
bgSpr.setOrigin(sf::Vector2f(WIDTH/2,HEIGHT/2));
int fps = 0;
int elapsedFrames = 0;
sf::Clock clock, pclock;
sf::Font font;
if(!font.loadFromFile("data/Sweet Cheeks.ttf")) exit(-1); //because yes
sf::Text text;
text.setFont(font);
text.setCharacterSize(18);
text.setPosition(580,10);
text.setString("0");
text.setColor(sf::Color::White);
sf::View view;
view.setSize(sf::Vector2f(WIDTH,HEIGHT));
sf::RectangleShape p(sf::Vector2f(10,10));
p.setFillColor(sf::Color::Blue);
p.setPosition(sf::Vector2f(1680,2090));
p.setOrigin(5,5);
int speed = 5;
DMGDVT::LS::LightSystem ls;
ls.setAmbiantLight(sf::Color(15,0,60));
ls.setView(view);
//1679,1583 radius DA SA I B LF
DMGDVT::LS::SpotLight* spot = new DMGDVT::LS::SpotLight(sf::Vector2f(1678,1582),200,sf::Color::Red, 0.0f ,M_PIf*2.0f,1.0f,0.5f,1.0f);
DMGDVT::LS::SpotLight* spot2 = new DMGDVT::LS::SpotLight(sf::Vector2f(1778,1417),200,sf::Color::Blue,0.0f ,M_PIf*2.0f,1.0f,0.5f,1.0f);
DMGDVT::LS::SpotLight* spot3 = new DMGDVT::LS::SpotLight(sf::Vector2f(1878,1582),200,sf::Color::Green,0.0f ,M_PIf*2.0f,1.0f,0.5f,1.0f);
DMGDVT::LS::SpotLight* spot4 = new DMGDVT::LS::SpotLight(sf::Vector2f(1520,1871),300,sf::Color::White,-M_PIf/4.0f ,M_PIf/5.0f,0.5f,1.0f,1.5f);
DMGDVT::LS::SpotLight* spot5 = new DMGDVT::LS::SpotLight(sf::Vector2f(1840,1871),300,sf::Color::White,M_PIf/4.0f ,M_PIf/5.0f,0.5f,1.0f,1.5f);
/*template add example*/ls.addLight<DMGDVT::LS::SpotLight>(sf::Vector2f(1679,2200),800,sf::Color(250,95,20),M_PIf ,M_PIf/3.0f,1.0f,0.0f,2.0f);
//1679,1583 radius DA SA I B LF
DMGDVT::LS::SpotLight* playerLight = new DMGDVT::LS::SpotLight(p.getPosition(),200,sf::Color::White);
playerLight->setLinearity(2.0f);
playerLight->setBleed(0.0f);
playerLight->setSpreadAngle(M_PIf/3.0f);
playerLight->setDirectionAngle(M_PIf);
ls.addLight(spot);
ls.addLight(spot2);
ls.addLight(spot3);
ls.addLight(spot4);
ls.addLight(spot5);
ls.addLight(playerLight);
sf::Vector2i mouseInt = sf::Mouse::getPosition(window);
sf::Vector2f mouse(window.mapPixelToCoords(mouseInt));
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
else if(event.type == sf::Event::KeyPressed){
switch(event.key.code) {
case sf::Keyboard::Escape:
{
window.close();
} break;
case sf::Keyboard::Up :
{
p.move(0,-speed);
} break;
case sf::Keyboard::Down :
{
p.move(0,speed);
} break;
case sf::Keyboard::Left :
{
p.move(-speed,0);
} break;
case sf::Keyboard::Right :
{
p.move(speed,0);
} break;
case sf::Keyboard::F1 :
{
aabb = !aabb;
} break;
case sf::Keyboard::F2 :
{
debugLightMapOnly = !debugLightMapOnly;
} break;
case sf::Keyboard::F3 :
{
debugUseShader = !debugUseShader;
} break;
case sf::Keyboard::F4 :
{
debugDrawLights = !debugDrawLights;
} break;
default: break;
}
}
}
mouseInt = sf::Mouse::getPosition(window);
mouse = window.mapPixelToCoords(mouseInt);
playerLight->setDirectionAngle(DMUtils::sfml::getAngleBetweenVectors(sf::Vector2f(0.0f,1.0f),mouse-sf::Vector2f(WIDTH/2.0f,HEIGHT/2.0f)));
playerLight->setPosition(p.getPosition());
if(update) ls.update(playerLight);
update = false;
int x = p.getPosition().x-WIDTH/2;
int y = p.getPosition().y-HEIGHT/2;
bgSpr.setTextureRect(sf::IntRect(x,y,WIDTH,HEIGHT));
bgSpr.setPosition(p.getPosition());
window.clear();
sf::View baseView = window.getView();
view.setCenter(p.getPosition());
window.setView(view);
window.draw(bgSpr);
window.draw(p);
int flags = 0;
if(debugLightMapOnly) flags |= DMGDVT::LS::LightSystem::DEBUG_FLAGS::LIGHTMAP_ONLY;
if(!debugUseShader) flags |= DMGDVT::LS::LightSystem::DEBUG_FLAGS::SHADER_OFF;
ls.debugRender(view,window,flags);
//use ls.render if not using debug
if(debugDrawLights) ls.draw(view,window);
if(aabb) ls.drawAABB(view,window);
window.setView(baseView);
window.draw(text);
window.display();
//sf::sleep(sf::milliseconds(16));
++elapsedFrames;
if(clock.getElapsedTime().asMilliseconds() > 500) {
fps = elapsedFrames;
elapsedFrames = 0;
clock.restart();
//for some reason my compiler doesn't find to_string so..
std::ostringstream str;
str << (fps*2);
text.setString(str.str());
}
}
return 0;
}
<commit_msg>Transformed the main in a good example of the library<commit_after>#include <iostream>
#include <sstream>
#include <SFML/Graphics.hpp>
#include <GL/gl.h>
#include <DMUtils/maths.hpp>
#include <DMUtils/sfml.hpp>
#include <LightSystem/LightSystem.hpp>
#include <LightSystem/SpotLight.hpp>
#define WIDTH 640
#define HEIGHT 480
//font taken from http://www.fontspace.com/melifonts/sweet-cheeks
int main(int argc, char** argv) {
/** SFML STUFF **/
sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT), "LightSystem test");
bool debugLightMapOnly = false;
bool aabb = false;
bool debugUseShader = true;
bool debugDrawLights = true;
//bg
sf::Texture bg;
if(!bg.loadFromFile("data/map.png")) exit(-1);
//if(!bg.loadFromFile("data/map2.jpg")) exit(-1);
//bg.setRepeated(true);
sf::Sprite bgSpr(bg,sf::IntRect(0,0,WIDTH,HEIGHT));
bgSpr.setOrigin(sf::Vector2f(WIDTH/2,HEIGHT/2));
int fps = 0;
int elapsedFrames = 0;
sf::Clock clock, flickerClock;
sf::Font font;
if(!font.loadFromFile("data/Sweet Cheeks.ttf")) exit(-1); //because yes
sf::Text text;
text.setFont(font);
text.setCharacterSize(18);
text.setPosition(580,10);
text.setString("0");
text.setColor(sf::Color::White);
sf::View view;
view.setSize(sf::Vector2f(WIDTH,HEIGHT));
sf::RectangleShape p(sf::Vector2f(10,10));
p.setFillColor(sf::Color::Blue);
p.setPosition(sf::Vector2f(1680,2090));
p.setOrigin(5,5);
int speed = 5;
sf::Vector2i mouseInt = sf::Mouse::getPosition(window);
sf::Vector2f mouse(window.mapPixelToCoords(mouseInt));
/** LIGHTSYSTEM EXAMPLE */
//create your LightSystem
//one per game is usually enough
DMGDVT::LS::LightSystem ls;
//change ambiant light
ls.setAmbiantLight(sf::Color(15,0,60));
//the lightSystem needs to be aware of the view you're using to properly draw the lights
ls.setView(view);
//Let's create a bunch of lights now
//the lights HAVE to be dynamically allocated. The LightSystem destroys them for you when it's destroyed
//do NOT destroy a light that hasn't been removed yet, it will cause a segfault
//you can change that using LightSystem::setAutoDelete
//if you do that you have to take care of the deletion yourself so be careful
//to ensure R + G + B = W
DMGDVT::LS::SpotLight* spotRed = new DMGDVT::LS::SpotLight(sf::Vector2f(1072,1678),200,sf::Color::Red, 0.0f ,M_PIf*2.0f,1.0f,0.5f,1.0f);
DMGDVT::LS::SpotLight* spotBlue = new DMGDVT::LS::SpotLight(sf::Vector2f(1272,1678),200,sf::Color::Blue,0.0f ,M_PIf*2.0f,1.0f,0.5f,1.0f);
DMGDVT::LS::SpotLight* spotGreen = new DMGDVT::LS::SpotLight(sf::Vector2f(1172,1578),200,sf::Color::Green,0.0f ,M_PIf*2.0f,1.0f,0.5f,1.0f);
//looks at the player, shows that you don't need to update a light if you're just rotating it around
DMGDVT::LS::SpotLight* eyeSpotLeft = new DMGDVT::LS::SpotLight(sf::Vector2f(1520,1871),300,sf::Color::White,-M_PIf/4.0f ,M_PIf/5.0f,0.5f,1.0f,1.5f);
DMGDVT::LS::SpotLight* eyeSpotRight = new DMGDVT::LS::SpotLight(sf::Vector2f(1840,1871),300,sf::Color::White,M_PIf/4.0f ,M_PIf/5.0f,0.5f,1.0f,1.5f);
DMGDVT::LS::SpotLight* sunRise = new DMGDVT::LS::SpotLight(sf::Vector2f(1679,2200),500,sf::Color(245,125,20),M_PIf ,M_PIf/3.0f,1.0f,0.0f,2.0f);
//flickering light. Something for dynamic lights is planned for later, but for now the code later shows how to do it
DMGDVT::LS::SpotLight* firePit1 = new DMGDVT::LS::SpotLight(sf::Vector2f(1584,1166),200,sf::Color(210,115,10),0.0f ,M_PIf*2.0f,1.0f,0.1f,1.0f);
DMGDVT::LS::SpotLight* firePit2 = new DMGDVT::LS::SpotLight(sf::Vector2f(1775,1166),200,sf::Color(210,115,10),0.0f ,M_PIf*2.0f,1.0f,0.1f,1.0f);
//just some more lights to test a few things
DMGDVT::LS::SpotLight* lamp = new DMGDVT::LS::SpotLight(sf::Vector2f(2160,1583),200,sf::Color::White,0.0f ,M_PIf*2.0f,1.0f,0.0f,0.50f);
DMGDVT::LS::SpotLight* hugeSpot = new DMGDVT::LS::SpotLight(sf::Vector2f(2845,1245),800,sf::Color::White,M_PIf/2.0f ,M_PIf/10.0f,1.0f,0.0f,2.0f);
//template add example
//also follows the player around, showing you don't need to update a light if you're just moving it around
DMGDVT::LS::SpotLight* playerLight = ls.addLight<DMGDVT::LS::SpotLight>(p.getPosition(),200,sf::Color::Yellow);
//add them all to the LightSystem
ls.addLight(spotRed);
ls.addLight(spotBlue);
ls.addLight(spotGreen);
ls.addLight(eyeSpotLeft);
ls.addLight(eyeSpotRight);
ls.addLight(sunRise);
ls.addLight(firePit1);
ls.addLight(firePit2);
ls.addLight(lamp);
ls.addLight(hugeSpot);
//Modify a light
playerLight->setDirectionAngle(M_PIf);
//if you modify ANY of the parameters below, you have to update the light's texture using ls.update(Light*);
//otherwise the update won't be taken into account
playerLight->setLinearity(2.0f);
playerLight->setBleed(0.0f);
playerLight->setSpreadAngle(M_PIf/3.0f);
playerLight->setColor(sf::Color::White);
playerLight->setIntensity(1.0f);
playerLight->setRadius(200);
ls.update(playerLight);
//the loop
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
else if(event.type == sf::Event::KeyPressed){
switch(event.key.code) {
case sf::Keyboard::Escape:
{
window.close();
} break;
case sf::Keyboard::Up :
{
p.move(0,-speed);
} break;
case sf::Keyboard::Down :
{
p.move(0,speed);
} break;
case sf::Keyboard::Left :
{
p.move(-speed,0);
} break;
case sf::Keyboard::Right :
{
p.move(speed,0);
} break;
case sf::Keyboard::F1 :
{
aabb = !aabb;
} break;
case sf::Keyboard::F2 :
{
debugLightMapOnly = !debugLightMapOnly;
} break;
case sf::Keyboard::F3 :
{
debugUseShader = !debugUseShader;
} break;
case sf::Keyboard::F4 :
{
debugDrawLights = !debugDrawLights;
} break;
case sf::Keyboard::F:
{
//see above, this parameter requires an update of the light's internal texture
//shows you how to turn a light ON and OFF easily
//in this particular case, you wouldn't need to update the texture
//since the lights aren't drawn if their intensity is 0
playerLight->setIntensity(1.0f - playerLight->getIntensity());
ls.update(playerLight);
} break;
case sf::Keyboard::S:
{
//this parameter requires an update
if(playerLight->getSpreadAngle()==2.0f*M_PIf) {
playerLight->setSpreadAngle(M_PIf/3.0f);
playerLight->setRadius(200);
} else {
playerLight->setSpreadAngle(2.0*M_PIf);
playerLight->setRadius(100);
}
ls.update(playerLight);
} break;
default: break;
}
}
}
mouseInt = sf::Mouse::getPosition(window);
mouse = window.mapPixelToCoords(mouseInt);
//example of code allowing you to make a light following your cursor centered on your character
//my character is fixed on the screen at {w/2,h/2}
//for something cleaner you might want to be using window.mapCoordsToPixel(p.getPosition()) instead
playerLight->setDirectionAngle(DMUtils::sfml::getAngleBetweenVectors(sf::Vector2f(0.0f,1.0f),mouse-sf::Vector2f(WIDTH/2.0f,HEIGHT/2.0f)));
playerLight->setPosition(p.getPosition());
//shows you how to follow an object of the map
eyeSpotLeft->setDirectionAngle(DMUtils::sfml::getAngleBetweenVectors(sf::Vector2f(0.0f,1.0f),p.getPosition() - eyeSpotLeft->getPosition()));
eyeSpotRight->setDirectionAngle(DMUtils::sfml::getAngleBetweenVectors(sf::Vector2f(0.0f,1.0f),p.getPosition() - eyeSpotRight->getPosition()));
//basic drawing stuff
int x = p.getPosition().x-WIDTH/2;
int y = p.getPosition().y-HEIGHT/2;
bgSpr.setTextureRect(sf::IntRect(x,y,WIDTH,HEIGHT));
bgSpr.setPosition(p.getPosition());
window.clear();
sf::View baseView = window.getView();
view.setCenter(p.getPosition());
//it is EXTREMELY IMPORTANT that you use the LightSystem::draw INSIDE your view
window.setView(view);
window.draw(bgSpr);
window.draw(p);
int flags = 0;
if(debugLightMapOnly) flags |= DMGDVT::LS::LightSystem::DEBUG_FLAGS::LIGHTMAP_ONLY;
if(!debugUseShader) flags |= DMGDVT::LS::LightSystem::DEBUG_FLAGS::SHADER_OFF;
//use LightSystem::render if not using debug
//if using debugRender, the flags allow you to modify the way the lights are drawn
ls.debugRender(view,window,flags);
if(debugDrawLights) ls.draw(view,window);
//draws the light's AABB
if(aabb) ls.drawAABB(view,window);
window.setView(baseView);
window.draw(text);
window.display();
//sf::sleep(sf::milliseconds(16));
++elapsedFrames;
if(clock.getElapsedTime().asMilliseconds() > 500) {
fps = elapsedFrames;
elapsedFrames = 0;
clock.restart();
//for some reason my compiler doesn't find to_string so..
std::ostringstream str;
str << (fps*2);
text.setString(str.str());
}
//this is an example of how to make a light flicker
if(flickerClock.getElapsedTime().asMilliseconds() > 100) {
flickerClock.restart();
if(firePit1->getRadius() == 200) {
firePit1->setRadius(180);
firePit2->setRadius(180);
} else {
firePit1->setRadius(200);
firePit2->setRadius(200);
}
ls.update(firePit1);
ls.update(firePit2);
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include <QVariant>
#include <QList>
#include <QStringList>
#include <QDir>
#include <QDebug>
#include "qtcsv/variantdata.h"
#include "qtcsv/reader.h"
#include "qtcsv/writer.h"
void WriteToFile(const QString& filePath);
void ReadAndPrint(const QString& filePath);
void ReadAndProcess(const QString& filePath);
int main()
{
QString filePath = QDir::currentPath() + "/info.csv";
WriteToFile(filePath);
ReadAndPrint(filePath);
ReadAndProcess(filePath);
return 0;
}
void WriteToFile(const QString& filePath)
{
qDebug() << "=== Write to csv-file ==";
QVariant first(2);
QList<QVariant> second;
second << QVariant("pi") << 3.14159265359;
QStringList fourth;
fourth << "one" << "two";
QtCSV::VariantData varData;
varData << first << second;
varData.addEmptyRow();
varData.addRow(fourth);
if ( false == QtCSV::Writer::write(filePath, varData) )
{
qDebug() << "Failed to write to a file";
}
qDebug() << "... Write is OK";
}
void ReadAndPrint(const QString& filePath)
{
qDebug() << "=== Read csv-file and print it content to terminal ==";
QList<QStringList> readData = QtCSV::Reader::readToList(filePath);
for ( int i = 0; i < readData.size(); ++i )
{
qDebug() << readData.at(i).join(",");
}
}
void ReadAndProcess(const QString& filePath)
{
qDebug() << "=== Read csv-file and process it content ==";
// Create processor that revert elements in a row and save
// them into internal container
class RevertProcessor : public QtCSV::Reader::AbstractProcessor
{
public:
QList< QStringList > data;
virtual bool process(const QStringList& elements)
{
QList<QString> revertedElements;
for (int i = 0; i < elements.size(); ++i)
{
revertedElements.push_front(elements.at(i));
}
data.push_back(QStringList(revertedElements));
return true;
}
};
RevertProcessor processor;
if (false == QtCSV::Reader::readToProcessor(filePath, processor))
{
qDebug() << "Failed to read file";
return;
}
// Print rows with reverted elements
for ( int i = 0; i < processor.data.size(); ++i )
{
qDebug() << processor.data.at(i).join(",");
}
}
<commit_msg>Fix and update RevertProcessor due to changes in AbstractProcessor<commit_after>#include <algorithm>
#include <QVariant>
#include <QList>
#include <QStringList>
#include <QDir>
#include <QDebug>
#include "qtcsv/variantdata.h"
#include "qtcsv/reader.h"
#include "qtcsv/writer.h"
void WriteToFile(const QString& filePath);
void ReadAndPrint(const QString& filePath);
void ReadAndProcess(const QString& filePath);
int main()
{
QString filePath = QDir::currentPath() + "/info.csv";
WriteToFile(filePath);
ReadAndPrint(filePath);
ReadAndProcess(filePath);
return 0;
}
void WriteToFile(const QString& filePath)
{
qDebug() << "=== Write to csv-file ==";
QVariant first(2);
QList<QVariant> second;
second << QVariant("pi") << 3.14159265359;
QStringList fourth;
fourth << "one" << "two";
QtCSV::VariantData varData;
varData << first << second;
varData.addEmptyRow();
varData.addRow(fourth);
if ( false == QtCSV::Writer::write(filePath, varData) )
{
qDebug() << "Failed to write to a file";
}
qDebug() << "... Write is OK";
}
void ReadAndPrint(const QString& filePath)
{
qDebug() << "=== Read csv-file and print it content to terminal ==";
QList<QStringList> readData = QtCSV::Reader::readToList(filePath);
for ( int i = 0; i < readData.size(); ++i )
{
qDebug() << readData.at(i).join(",");
}
}
void ReadAndProcess(const QString& filePath)
{
qDebug() << "=== Read csv-file and process it content ==";
// Create processor that:
// - replate empty lines by some data
// - revert elements in a row and save them into internal container
class RevertProcessor : public QtCSV::Reader::AbstractProcessor
{
public:
QList< QStringList > data;
virtual void preProcessRawLine(QString& line)
{
if (line.isEmpty())
{
line = "Say 'No' to empty lines!";
}
}
virtual bool processRowElements(const QStringList& elements)
{
QList<QString> revertedElements(elements);
std::reverse(revertedElements.begin(), revertedElements.end());
data.push_back(QStringList(revertedElements));
return true;
}
};
RevertProcessor processor;
if (false == QtCSV::Reader::readToProcessor(filePath, processor))
{
qDebug() << "Failed to read file";
return;
}
// Print rows with reverted elements
for ( int i = 0; i < processor.data.size(); ++i )
{
qDebug() << processor.data.at(i).join(",");
}
}
<|endoftext|> |
<commit_before>/** @file
SSLNextProtocolSet
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "ink_config.h"
#include "apidefs.h"
#include "libts.h"
#include "P_SSLNextProtocolSet.h"
// For currently defined protocol strings, see
// http://technotes.googlecode.com/git/nextprotoneg.html. The OpenSSL
// documentation tells us to return a string in "wire format". The
// draft NPN RFC helpfuly refuses to document the wire format. The
// above link says we need to send length-prefixed strings, but does
// not say how many bytes the length is. For the record, it's 1.
unsigned char *
append_protocol(const char * proto, unsigned char * buf)
{
size_t sz = strlen(proto);
*buf++ = (unsigned char)sz;
memcpy(buf, proto, sz);
return buf + sz;
}
static bool
create_npn_advertisement(
const SSLNextProtocolSet::NextProtocolEndpoint::list_type& endpoints,
unsigned char ** npn, size_t * len)
{
const SSLNextProtocolSet::NextProtocolEndpoint * ep;
unsigned char * advertised;
*npn = NULL;
*len = 0;
for (ep = endpoints.head; ep != NULL; ep = endpoints.next(ep)) {
*len += (strlen(ep->protocol) + 1);
}
*npn = advertised = (unsigned char *)ats_malloc(*len);
if (!(*npn)) {
goto fail;
}
for (ep = endpoints.head; ep != NULL; ep = endpoints.next(ep)) {
advertised = append_protocol(ep->protocol, advertised);
}
return true;
fail:
ats_free(*npn);
*npn = NULL;
*len = 0;
return false;
}
bool
SSLNextProtocolSet::advertiseProtocols(const unsigned char ** out, unsigned * len) const
{
if (!npn && !this->endpoints.empty()) {
create_npn_advertisement(this->endpoints, &npn, &npnsz);
}
if (npn && npnsz) {
*out = npn;
*len = npnsz;
Debug("ssl", "advertised NPN set %.*s", (int)npnsz, npn);
return true;
}
return false;
}
bool
SSLNextProtocolSet::registerEndpoint(const char * proto, Continuation * ep)
{
// Once we start advertising, the set is closed. We need to hand an immutable
// string down into OpenSSL, and there is no mechanism to tell us when it's
// done with it so we have to keep it forever.
if (this->npn) {
return false;
}
if (strlen(proto) > 255) {
return false;
}
if (findEndpoint(proto) == NULL) {
this->endpoints.push(NEW(new NextProtocolEndpoint(proto, ep)));
return true;
}
return false;
}
bool
SSLNextProtocolSet::unregisterEndpoint(const char * proto, Continuation * ep)
{
for (NextProtocolEndpoint * e = this->endpoints.head;
e; e = this->endpoints.next(e)) {
if (strcmp(proto, e->protocol) == 0 && e->endpoint == ep) {
// Protocol must be registered only once; no need to remove
// any more entries.
this->endpoints.remove(e);
return true;
}
}
return false;
}
Continuation *
SSLNextProtocolSet::findEndpoint(
const unsigned char * proto, unsigned len,
TSClientProtoStack *proto_stack, const char **selected_protocol) const
{
for (const NextProtocolEndpoint * ep = this->endpoints.head;
ep != NULL; ep = this->endpoints.next(ep)) {
size_t sz = strlen(ep->protocol);
if (sz == len && memcmp(ep->protocol, proto, len) == 0) {
if (proto_stack) {
*proto_stack = ep->proto_stack;
}
if (selected_protocol) {
*selected_protocol = ep->protocol;
}
return ep->endpoint;
}
}
return NULL;
}
Continuation *
SSLNextProtocolSet::findEndpoint(const char * proto) const
{
for (const NextProtocolEndpoint * ep = this->endpoints.head;
ep != NULL; ep = this->endpoints.next(ep)) {
if (strcmp(proto, ep->protocol) == 0) {
return ep->endpoint;
}
}
return NULL;
}
SSLNextProtocolSet::SSLNextProtocolSet()
: npn(0), npnsz(0)
{
}
SSLNextProtocolSet::~SSLNextProtocolSet()
{
ats_free(this->npn);
for (NextProtocolEndpoint * ep; (ep = this->endpoints.pop());) {
delete ep;
}
}
SSLNextProtocolSet::NextProtocolEndpoint::NextProtocolEndpoint(
const char * proto, Continuation * ep)
: protocol(proto), endpoint(ep)
{
if (proto == TS_NPN_PROTOCOL_HTTP_1_1 ||
proto == TS_NPN_PROTOCOL_HTTP_1_0) {
proto_stack = ((1u << TS_PROTO_TLS) | (1u << TS_PROTO_HTTP));
} else if (proto == TS_NPN_PROTOCOL_SPDY_3_1 ||
proto == TS_NPN_PROTOCOL_SPDY_3 ||
proto == TS_NPN_PROTOCOL_SPDY_2 ||
proto == TS_NPN_PROTOCOL_SPDY_1) {
proto_stack = ((1u << TS_PROTO_TLS) | (1u << TS_PROTO_SPDY));
} else {
proto_stack = (1u << TS_PROTO_TLS);
}
}
SSLNextProtocolSet::NextProtocolEndpoint::~NextProtocolEndpoint()
{
}
<commit_msg>Changing ssl debug message for npn advertisement<commit_after>/** @file
SSLNextProtocolSet
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "ink_config.h"
#include "apidefs.h"
#include "libts.h"
#include "P_SSLNextProtocolSet.h"
// For currently defined protocol strings, see
// http://technotes.googlecode.com/git/nextprotoneg.html. The OpenSSL
// documentation tells us to return a string in "wire format". The
// draft NPN RFC helpfuly refuses to document the wire format. The
// above link says we need to send length-prefixed strings, but does
// not say how many bytes the length is. For the record, it's 1.
unsigned char *
append_protocol(const char * proto, unsigned char * buf)
{
size_t sz = strlen(proto);
*buf++ = (unsigned char)sz;
memcpy(buf, proto, sz);
return buf + sz;
}
static bool
create_npn_advertisement(
const SSLNextProtocolSet::NextProtocolEndpoint::list_type& endpoints,
unsigned char ** npn, size_t * len)
{
const SSLNextProtocolSet::NextProtocolEndpoint * ep;
unsigned char * advertised;
*npn = NULL;
*len = 0;
for (ep = endpoints.head; ep != NULL; ep = endpoints.next(ep)) {
*len += (strlen(ep->protocol) + 1);
}
*npn = advertised = (unsigned char *)ats_malloc(*len);
if (!(*npn)) {
goto fail;
}
for (ep = endpoints.head; ep != NULL; ep = endpoints.next(ep)) {
Debug("ssl", "advertising protocol %s", ep->protocol);
advertised = append_protocol(ep->protocol, advertised);
}
return true;
fail:
ats_free(*npn);
*npn = NULL;
*len = 0;
return false;
}
bool
SSLNextProtocolSet::advertiseProtocols(const unsigned char ** out, unsigned * len) const
{
if (!npn && !this->endpoints.empty()) {
create_npn_advertisement(this->endpoints, &npn, &npnsz);
}
if (npn && npnsz) {
*out = npn;
*len = npnsz;
return true;
}
return false;
}
bool
SSLNextProtocolSet::registerEndpoint(const char * proto, Continuation * ep)
{
// Once we start advertising, the set is closed. We need to hand an immutable
// string down into OpenSSL, and there is no mechanism to tell us when it's
// done with it so we have to keep it forever.
if (this->npn) {
return false;
}
if (strlen(proto) > 255) {
return false;
}
if (findEndpoint(proto) == NULL) {
this->endpoints.push(NEW(new NextProtocolEndpoint(proto, ep)));
return true;
}
return false;
}
bool
SSLNextProtocolSet::unregisterEndpoint(const char * proto, Continuation * ep)
{
for (NextProtocolEndpoint * e = this->endpoints.head;
e; e = this->endpoints.next(e)) {
if (strcmp(proto, e->protocol) == 0 && e->endpoint == ep) {
// Protocol must be registered only once; no need to remove
// any more entries.
this->endpoints.remove(e);
return true;
}
}
return false;
}
Continuation *
SSLNextProtocolSet::findEndpoint(
const unsigned char * proto, unsigned len,
TSClientProtoStack *proto_stack, const char **selected_protocol) const
{
for (const NextProtocolEndpoint * ep = this->endpoints.head;
ep != NULL; ep = this->endpoints.next(ep)) {
size_t sz = strlen(ep->protocol);
if (sz == len && memcmp(ep->protocol, proto, len) == 0) {
if (proto_stack) {
*proto_stack = ep->proto_stack;
}
if (selected_protocol) {
*selected_protocol = ep->protocol;
}
return ep->endpoint;
}
}
return NULL;
}
Continuation *
SSLNextProtocolSet::findEndpoint(const char * proto) const
{
for (const NextProtocolEndpoint * ep = this->endpoints.head;
ep != NULL; ep = this->endpoints.next(ep)) {
if (strcmp(proto, ep->protocol) == 0) {
return ep->endpoint;
}
}
return NULL;
}
SSLNextProtocolSet::SSLNextProtocolSet()
: npn(0), npnsz(0)
{
}
SSLNextProtocolSet::~SSLNextProtocolSet()
{
ats_free(this->npn);
for (NextProtocolEndpoint * ep; (ep = this->endpoints.pop());) {
delete ep;
}
}
SSLNextProtocolSet::NextProtocolEndpoint::NextProtocolEndpoint(
const char * proto, Continuation * ep)
: protocol(proto), endpoint(ep)
{
if (proto == TS_NPN_PROTOCOL_HTTP_1_1 ||
proto == TS_NPN_PROTOCOL_HTTP_1_0) {
proto_stack = ((1u << TS_PROTO_TLS) | (1u << TS_PROTO_HTTP));
} else if (proto == TS_NPN_PROTOCOL_SPDY_3_1 ||
proto == TS_NPN_PROTOCOL_SPDY_3 ||
proto == TS_NPN_PROTOCOL_SPDY_2 ||
proto == TS_NPN_PROTOCOL_SPDY_1) {
proto_stack = ((1u << TS_PROTO_TLS) | (1u << TS_PROTO_SPDY));
} else {
proto_stack = (1u << TS_PROTO_TLS);
}
}
SSLNextProtocolSet::NextProtocolEndpoint::~NextProtocolEndpoint()
{
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/tasks/deciders/path_reuse_decider/path_reuse_decider.h"
#include <algorithm>
#include <string>
#include <vector>
namespace apollo {
namespace planning {
// #define ADEBUG AINFO
using apollo::common::Status;
int PathReuseDecider::reusable_path_counter_ = 0;
int PathReuseDecider::total_path_counter_ = 0;
PathReuseDecider::PathReuseDecider(const TaskConfig& config)
: Decider(config) {}
Status PathReuseDecider::Process(Frame* const frame,
ReferenceLineInfo* const reference_line_info) {
// Sanity checks.
CHECK_NOTNULL(frame);
CHECK_NOTNULL(reference_line_info);
// Check if path is reusable
if (Decider::config_.path_reuse_decider_config().reuse_path() &&
CheckPathReusable(frame, reference_line_info)) {
++reusable_path_counter_; // count reusable path
}
++total_path_counter_; // count total path
ADEBUG << "reusable_path_counter_" << reusable_path_counter_;
ADEBUG << "total_path_counter_" << total_path_counter_;
return Status::OK();
}
bool PathReuseDecider::CheckPathReusable(
Frame* const frame, ReferenceLineInfo* const reference_line_info) {
return IsSameStopObstacles(frame, reference_line_info);
// return IsSameObstacles(reference_line_info);
}
bool PathReuseDecider::IsSameStopObstacles(
Frame* const frame, ReferenceLineInfo* const reference_line_info) {
if (history_->GetLastFrame() == nullptr) return false;
const std::vector<const HistoryObjectDecision*> history_objects_decisions =
history_->GetLastFrame()->GetStopObjectDecisions();
const auto& reference_line = reference_line_info->reference_line();
std::vector<double> history_stop_positions;
std::vector<double> current_stop_positions;
GetCurrentStopObstacleS(reference_line_info, ¤t_stop_positions);
GetHistoryStopSPosition(reference_line_info, history_objects_decisions,
&history_stop_positions);
// get current vehicle s
common::math::Vec2d adc_position = {
common::VehicleStateProvider::Instance()->x(),
common::VehicleStateProvider::Instance()->y()};
common::SLPoint adc_position_sl;
reference_line.XYToSL(adc_position, &adc_position_sl);
ADEBUG << "ADC_s:" << adc_position_sl.s();
double nearest_history_stop_s = FLAGS_default_front_clear_distance;
double nearest_current_stop_s = FLAGS_default_front_clear_distance;
for (auto history_stop_position : history_stop_positions) {
ADEBUG << "current_stop_position " << history_stop_position
<< "adc_position_sl.s()" << adc_position_sl.s();
if (history_stop_position < adc_position_sl.s()) {
continue;
} else {
// find nearest history stop
nearest_history_stop_s = history_stop_position;
break;
}
}
for (auto current_stop_position : current_stop_positions) {
ADEBUG << "current_stop_position " << current_stop_position
<< "adc_position_sl.s()" << adc_position_sl.s();
if (current_stop_position < adc_position_sl.s()) {
continue;
} else {
// find nearest current stop
nearest_current_stop_s = current_stop_position;
break;
}
}
return SameStopS(nearest_history_stop_s, nearest_current_stop_s);
}
// compare history stop position vs current stop position
bool PathReuseDecider::SameStopS(const double history_stop_s,
const double current_stop_s) {
const double KNegative = 0.1; // (meter) closer
const double kPositive = 0.5; // (meter) further
ADEBUG << "current_stop_s" << current_stop_s;
ADEBUG << "history_stop_s" << history_stop_s;
if ((current_stop_s > history_stop_s &&
current_stop_s - history_stop_s < kPositive) ||
(current_stop_s < history_stop_s &&
history_stop_s - current_stop_s < KNegative))
return true;
return false;
}
// get current stop positions
void PathReuseDecider::GetCurrentStopPositions(
Frame* frame,
std::vector<const common::PointENU*>* current_stop_positions) {
auto obstacles = frame->obstacles();
for (auto obstacle : obstacles) {
const std::vector<ObjectDecisionType>& current_decisions =
obstacle->decisions();
for (auto current_decision : current_decisions) {
if (current_decision.has_stop())
current_stop_positions->emplace_back(
¤t_decision.stop().stop_point());
}
}
// sort
std::sort(current_stop_positions->begin(), current_stop_positions->end(),
[](const common::PointENU* lhs, const common::PointENU* rhs) {
return (lhs->x() < rhs->x() ||
(lhs->x() == rhs->x() && lhs->y() < rhs->y()));
});
}
// get current stop obstacle position in s-direction
void PathReuseDecider::GetCurrentStopObstacleS(
ReferenceLineInfo* const reference_line_info,
std::vector<double>* current_stop_obstacle) {
// get all obstacles
for (auto obstacle :
reference_line_info->path_decision()->obstacles().Items()) {
ADEBUG << "current obstacle: "
<< obstacle->PerceptionSLBoundary().start_s();
if (obstacle->IsLaneBlocking())
current_stop_obstacle->emplace_back(
obstacle->PerceptionSLBoundary().start_s());
}
// sort w.r.t s
std::sort(current_stop_obstacle->begin(), current_stop_obstacle->end());
}
// get history stop positions at current reference line
void PathReuseDecider::GetHistoryStopSPosition(
ReferenceLineInfo* const reference_line_info,
const std::vector<const HistoryObjectDecision*>& history_objects_decisions,
std::vector<double>* history_stop_positions) {
const auto& reference_line = reference_line_info->reference_line();
for (auto history_object_decision : history_objects_decisions) {
const std::vector<const ObjectDecisionType*> decisions =
history_object_decision->GetObjectDecision();
for (const ObjectDecisionType* decision : decisions) {
if (decision->has_stop()) {
common::math::Vec2d stop_position({decision->stop().stop_point().x(),
decision->stop().stop_point().y()});
common::SLPoint stop_position_sl;
reference_line.XYToSL(stop_position, &stop_position_sl);
history_stop_positions->emplace_back(stop_position_sl.s() -
decision->stop().distance_s());
ADEBUG << "stop_position_x: " << decision->stop().stop_point().x();
ADEBUG << "stop_position_y: " << decision->stop().stop_point().y();
ADEBUG << "stop_distance_s: " << decision->stop().distance_s();
ADEBUG << "stop_distance_s: " << stop_position_sl.s();
ADEBUG << "adjusted_stop_distance_s: "
<< stop_position_sl.s() - decision->stop().distance_s();
}
}
}
// sort w.r.t s
std::sort(history_stop_positions->begin(), history_stop_positions->end());
}
// compare obstacles
bool PathReuseDecider::IsSameObstacles(
ReferenceLineInfo* const reference_line_info) {
const auto& history_frame = FrameHistory::Instance()->Latest();
if (!history_frame) return false;
const auto& history_reference_line_info =
history_frame->reference_line_info().front();
const IndexedList<std::string, Obstacle>& history_obstacles =
history_reference_line_info.path_decision().obstacles();
const ReferenceLine& history_reference_line =
history_reference_line_info.reference_line();
const ReferenceLine& current_reference_line =
reference_line_info->reference_line();
if (reference_line_info->path_decision()->obstacles().Items().size() !=
history_obstacles.Items().size())
return false;
for (auto obstacle :
reference_line_info->path_decision()->obstacles().Items()) {
const std::string& obstacle_id = obstacle->Id();
// same obstacle id
auto history_obstacle = history_obstacles.Find(obstacle_id);
if (!history_obstacle ||
(obstacle->IsStatic() != history_obstacle->IsStatic()) ||
(IsBlockingDrivingPathObstacle(current_reference_line, obstacle) !=
IsBlockingDrivingPathObstacle(history_reference_line,
history_obstacle)))
return false;
}
return true;
} // namespace planning
} // namespace planning
} // namespace apollo
<commit_msg>planning: minior bug fix for path_reuse_decider<commit_after>/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/tasks/deciders/path_reuse_decider/path_reuse_decider.h"
#include <algorithm>
#include <string>
#include <vector>
namespace apollo {
namespace planning {
// #define ADEBUG AINFO
using apollo::common::Status;
int PathReuseDecider::reusable_path_counter_ = 0;
int PathReuseDecider::total_path_counter_ = 0;
PathReuseDecider::PathReuseDecider(const TaskConfig& config)
: Decider(config) {}
Status PathReuseDecider::Process(Frame* const frame,
ReferenceLineInfo* const reference_line_info) {
// Sanity checks.
CHECK_NOTNULL(frame);
CHECK_NOTNULL(reference_line_info);
// Check if path is reusable
if (Decider::config_.path_reuse_decider_config().reuse_path() &&
CheckPathReusable(frame, reference_line_info)) {
++reusable_path_counter_; // count reusable path
}
++total_path_counter_; // count total path
ADEBUG << "reusable_path_counter_" << reusable_path_counter_;
ADEBUG << "total_path_counter_" << total_path_counter_;
return Status::OK();
}
bool PathReuseDecider::CheckPathReusable(
Frame* const frame, ReferenceLineInfo* const reference_line_info) {
// return IsSameStopObstacles(frame, reference_line_info);
return IsSameObstacles(reference_line_info);
}
bool PathReuseDecider::IsSameStopObstacles(
Frame* const frame, ReferenceLineInfo* const reference_line_info) {
if (history_->GetLastFrame() == nullptr) return false;
const std::vector<const HistoryObjectDecision*> history_objects_decisions =
history_->GetLastFrame()->GetStopObjectDecisions();
const auto& reference_line = reference_line_info->reference_line();
std::vector<double> history_stop_positions;
std::vector<double> current_stop_positions;
GetCurrentStopObstacleS(reference_line_info, ¤t_stop_positions);
GetHistoryStopSPosition(reference_line_info, history_objects_decisions,
&history_stop_positions);
// get current vehicle s
common::math::Vec2d adc_position = {
common::VehicleStateProvider::Instance()->x(),
common::VehicleStateProvider::Instance()->y()};
common::SLPoint adc_position_sl;
reference_line.XYToSL(adc_position, &adc_position_sl);
ADEBUG << "ADC_s:" << adc_position_sl.s();
double nearest_history_stop_s = FLAGS_default_front_clear_distance;
double nearest_current_stop_s = FLAGS_default_front_clear_distance;
for (auto history_stop_position : history_stop_positions) {
ADEBUG << "current_stop_position " << history_stop_position
<< "adc_position_sl.s()" << adc_position_sl.s();
if (history_stop_position < adc_position_sl.s()) {
continue;
} else {
// find nearest history stop
nearest_history_stop_s = history_stop_position;
break;
}
}
for (auto current_stop_position : current_stop_positions) {
ADEBUG << "current_stop_position " << current_stop_position
<< "adc_position_sl.s()" << adc_position_sl.s();
if (current_stop_position < adc_position_sl.s()) {
continue;
} else {
// find nearest current stop
nearest_current_stop_s = current_stop_position;
break;
}
}
return SameStopS(nearest_history_stop_s, nearest_current_stop_s);
}
// compare history stop position vs current stop position
bool PathReuseDecider::SameStopS(const double history_stop_s,
const double current_stop_s) {
const double KNegative = 0.1; // (meter) closer
const double kPositive = 0.5; // (meter) further
ADEBUG << "current_stop_s" << current_stop_s;
ADEBUG << "history_stop_s" << history_stop_s;
if ((current_stop_s >= history_stop_s &&
current_stop_s - history_stop_s <= kPositive) ||
(current_stop_s <= history_stop_s &&
history_stop_s - current_stop_s <= KNegative))
return true;
return false;
}
// get current stop positions
void PathReuseDecider::GetCurrentStopPositions(
Frame* frame,
std::vector<const common::PointENU*>* current_stop_positions) {
auto obstacles = frame->obstacles();
for (auto obstacle : obstacles) {
const std::vector<ObjectDecisionType>& current_decisions =
obstacle->decisions();
for (auto current_decision : current_decisions) {
if (current_decision.has_stop())
current_stop_positions->emplace_back(
¤t_decision.stop().stop_point());
}
}
// sort
std::sort(current_stop_positions->begin(), current_stop_positions->end(),
[](const common::PointENU* lhs, const common::PointENU* rhs) {
return (lhs->x() < rhs->x() ||
(lhs->x() == rhs->x() && lhs->y() < rhs->y()));
});
}
// get current stop obstacle position in s-direction
void PathReuseDecider::GetCurrentStopObstacleS(
ReferenceLineInfo* const reference_line_info,
std::vector<double>* current_stop_obstacle) {
// get all obstacles
for (auto obstacle :
reference_line_info->path_decision()->obstacles().Items()) {
ADEBUG << "current obstacle: "
<< obstacle->PerceptionSLBoundary().start_s();
if (obstacle->IsLaneBlocking())
current_stop_obstacle->emplace_back(
obstacle->PerceptionSLBoundary().start_s());
}
// sort w.r.t s
std::sort(current_stop_obstacle->begin(), current_stop_obstacle->end());
}
// get history stop positions at current reference line
void PathReuseDecider::GetHistoryStopSPosition(
ReferenceLineInfo* const reference_line_info,
const std::vector<const HistoryObjectDecision*>& history_objects_decisions,
std::vector<double>* history_stop_positions) {
const auto& reference_line = reference_line_info->reference_line();
for (auto history_object_decision : history_objects_decisions) {
const std::vector<const ObjectDecisionType*> decisions =
history_object_decision->GetObjectDecision();
for (const ObjectDecisionType* decision : decisions) {
if (decision->has_stop()) {
common::math::Vec2d stop_position({decision->stop().stop_point().x(),
decision->stop().stop_point().y()});
common::SLPoint stop_position_sl;
reference_line.XYToSL(stop_position, &stop_position_sl);
history_stop_positions->emplace_back(stop_position_sl.s() -
decision->stop().distance_s());
ADEBUG << "stop_position_x: " << decision->stop().stop_point().x();
ADEBUG << "stop_position_y: " << decision->stop().stop_point().y();
ADEBUG << "stop_distance_s: " << decision->stop().distance_s();
ADEBUG << "stop_distance_s: " << stop_position_sl.s();
ADEBUG << "adjusted_stop_distance_s: "
<< stop_position_sl.s() - decision->stop().distance_s();
}
}
}
// sort w.r.t s
std::sort(history_stop_positions->begin(), history_stop_positions->end());
}
// compare obstacles
bool PathReuseDecider::IsSameObstacles(
ReferenceLineInfo* const reference_line_info) {
const auto& history_frame = FrameHistory::Instance()->Latest();
if (!history_frame) return false;
const auto& history_reference_line_info =
history_frame->reference_line_info().front();
const IndexedList<std::string, Obstacle>& history_obstacles =
history_reference_line_info.path_decision().obstacles();
const ReferenceLine& history_reference_line =
history_reference_line_info.reference_line();
const ReferenceLine& current_reference_line =
reference_line_info->reference_line();
if (reference_line_info->path_decision()->obstacles().Items().size() !=
history_obstacles.Items().size())
return false;
for (auto obstacle :
reference_line_info->path_decision()->obstacles().Items()) {
const std::string& obstacle_id = obstacle->Id();
// same obstacle id
auto history_obstacle = history_obstacles.Find(obstacle_id);
if (!history_obstacle ||
(obstacle->IsStatic() != history_obstacle->IsStatic()) ||
(IsBlockingDrivingPathObstacle(current_reference_line, obstacle) !=
IsBlockingDrivingPathObstacle(history_reference_line,
history_obstacle)))
return false;
}
// TODO(SHU) add colision check
return true;
}
} // namespace planning
} // namespace apollo
<|endoftext|> |
<commit_before>// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "qfunction.hpp"
#include "quadinterpolator.hpp"
#include "quadinterpolator_face.hpp"
namespace mfem
{
QuadratureFunction &QuadratureFunction::operator=(double value)
{
Vector::operator=(value);
return *this;
}
QuadratureFunction &QuadratureFunction::operator=(const Vector &v)
{
MFEM_ASSERT(qspace && v.Size() == this->Size(), "");
Vector::operator=(v);
return *this;
}
QuadratureFunction::QuadratureFunction(Mesh *mesh, std::istream &in)
{
const char *msg = "invalid input stream";
std::string ident;
qspace = new QuadratureSpace(mesh, in);
own_qspace = true;
in >> ident; MFEM_VERIFY(ident == "VDim:", msg);
in >> vdim;
Load(in, vdim*qspace->GetSize());
}
void QuadratureFunction::SetSpace(QuadratureSpaceBase *qspace_, int vdim_)
{
if (qspace_ != qspace)
{
if (own_qspace) { delete qspace; }
qspace = qspace_;
own_qspace = false;
}
vdim = (vdim_ < 0) ? vdim : vdim_;
SetSize(vdim*qspace->GetSize());
}
void QuadratureFunction::SetSpace(
QuadratureSpaceBase *qspace_, double *qf_data, int vdim_)
{
if (qspace_ != qspace)
{
if (own_qspace) { delete qspace; }
qspace = qspace_;
own_qspace = false;
}
vdim = (vdim_ < 0) ? vdim : vdim_;
NewDataAndSize(qf_data, vdim*qspace->GetSize());
}
void QuadratureFunction::Save(std::ostream &os) const
{
MFEM_ABORT("Not implemented.");
// GetSpace()->Save(os);
// os << "VDim: " << vdim << '\n'
// << '\n';
// Vector::Print(os, vdim);
// os.flush();
}
void QuadratureFunction::ProjectGridFunction(const GridFunction &gf)
{
SetVDim(gf.VectorDim());
if (auto *qs_elem = dynamic_cast<QuadratureSpace*>(qspace))
{
const FiniteElementSpace &gf_fes = *gf.FESpace();
const bool use_tensor_products = UsesTensorBasis(gf_fes);
const ElementDofOrdering ordering = use_tensor_products ?
ElementDofOrdering::LEXICOGRAPHIC :
ElementDofOrdering::NATIVE;
// Use element restriction to go from L-vector to E-vector
const Operator *R = gf_fes.GetElementRestriction(ordering);
Vector e_vec(R->Height());
R->Mult(gf, e_vec);
// Use quadrature interpolator to go from E-vector to Q-vector
const QuadratureInterpolator *qi = gf_fes.GetQuadratureInterpolator(*qs_elem);
qi->SetOutputLayout(QVectorLayout::byVDIM);
qi->DisableTensorProducts(!use_tensor_products);
qi->Values(e_vec, *this);
}
else if (auto *qs_face = dynamic_cast<FaceQuadratureSpace*>(qspace))
{
const FiniteElementSpace &gf_fes = *gf.FESpace();
const bool use_tensor_products = UsesTensorBasis(gf_fes);
const ElementDofOrdering ordering = use_tensor_products ?
ElementDofOrdering::LEXICOGRAPHIC :
ElementDofOrdering::NATIVE;
const FaceType face_type = qs_face->GetFaceType();
// Use element restriction to go from L-vector to E-vector
const Operator *R = gf_fes.GetFaceRestriction(
ordering, face_type, L2FaceValues::SingleValued);
Vector e_vec(R->Height());
R->Mult(gf, e_vec);
// Use quadrature interpolator to go from E-vector to Q-vector
const FaceQuadratureInterpolator *qi =
gf_fes.GetFaceQuadratureInterpolator(qspace->GetIntRule(0), face_type);
qi->SetOutputLayout(QVectorLayout::byVDIM);
qi->DisableTensorProducts(!use_tensor_products);
qi->Values(e_vec, *this);
}
else
{
// This branch should be unreachable
MFEM_ABORT("Unsupported case.");
}
}
std::ostream &operator<<(std::ostream &os, const QuadratureFunction &qf)
{
qf.Save(os);
return os;
}
void QuadratureFunction::SaveVTU(std::ostream &os, VTKFormat format,
int compression_level) const
{
os << R"(<VTKFile type="UnstructuredGrid" version="0.1")";
if (compression_level != 0)
{
os << R"( compressor="vtkZLibDataCompressor")";
}
os << " byte_order=\"" << VTKByteOrder() << "\">\n";
os << "<UnstructuredGrid>\n";
const char *fmt_str = (format == VTKFormat::ASCII) ? "ascii" : "binary";
const char *type_str = (format != VTKFormat::BINARY32) ? "Float64" : "Float32";
std::vector<char> buf;
Mesh &mesh = *qspace->GetMesh();
int np = qspace->GetSize();
int ne = mesh.GetNE();
int sdim = mesh.SpaceDimension();
// For quadrature functions, each point is a vertex cell, so number of cells
// is equal to number of points
os << "<Piece NumberOfPoints=\"" << np
<< "\" NumberOfCells=\"" << np << "\">\n";
// print out the points
os << "<Points>\n";
os << "<DataArray type=\"" << type_str
<< "\" NumberOfComponents=\"3\" format=\"" << fmt_str << "\">\n";
Vector pt(sdim);
for (int i = 0; i < ne; i++)
{
ElementTransformation &T = *mesh.GetElementTransformation(i);
const IntegrationRule &ir = GetIntRule(i);
for (int j = 0; j < ir.Size(); j++)
{
T.Transform(ir[j], pt);
WriteBinaryOrASCII(os, buf, pt[0], " ", format);
if (sdim > 1) { WriteBinaryOrASCII(os, buf, pt[1], " ", format); }
else { WriteBinaryOrASCII(os, buf, 0.0, " ", format); }
if (sdim > 2) { WriteBinaryOrASCII(os, buf, pt[2], "", format); }
else { WriteBinaryOrASCII(os, buf, 0.0, "", format); }
if (format == VTKFormat::ASCII) { os << '\n'; }
}
}
if (format != VTKFormat::ASCII)
{
WriteBase64WithSizeAndClear(os, buf, compression_level);
}
os << "</DataArray>\n";
os << "</Points>\n";
// Write cells (each cell is just a vertex)
os << "<Cells>\n";
// Connectivity
os << R"(<DataArray type="Int32" Name="connectivity" format=")"
<< fmt_str << "\">\n";
for (int i=0; i<np; ++i) { WriteBinaryOrASCII(os, buf, i, "\n", format); }
if (format != VTKFormat::ASCII)
{
WriteBase64WithSizeAndClear(os, buf, compression_level);
}
os << "</DataArray>\n";
// Offsets
os << R"(<DataArray type="Int32" Name="offsets" format=")"
<< fmt_str << "\">\n";
for (int i=0; i<np; ++i) { WriteBinaryOrASCII(os, buf, i, "\n", format); }
if (format != VTKFormat::ASCII)
{
WriteBase64WithSizeAndClear(os, buf, compression_level);
}
os << "</DataArray>\n";
// Types
os << R"(<DataArray type="UInt8" Name="types" format=")"
<< fmt_str << "\">\n";
for (int i = 0; i < np; i++)
{
uint8_t vtk_cell_type = VTKGeometry::POINT;
WriteBinaryOrASCII(os, buf, vtk_cell_type, "\n", format);
}
if (format != VTKFormat::ASCII)
{
WriteBase64WithSizeAndClear(os, buf, compression_level);
}
os << "</DataArray>\n";
os << "</Cells>\n";
os << "<PointData>\n";
os << "<DataArray type=\"" << type_str << "\" Name=\"u\" format=\""
<< fmt_str << "\" NumberOfComponents=\"" << vdim << "\">\n";
for (int i = 0; i < ne; i++)
{
DenseMatrix vals;
GetValues(i, vals);
for (int j = 0; j < vals.Size(); ++j)
{
for (int vd = 0; vd < vdim; ++vd)
{
WriteBinaryOrASCII(os, buf, vals(vd, j), " ", format);
}
if (format == VTKFormat::ASCII) { os << '\n'; }
}
}
if (format != VTKFormat::ASCII)
{
WriteBase64WithSizeAndClear(os, buf, compression_level);
}
os << "</DataArray>\n";
os << "</PointData>\n";
os << "</Piece>\n";
os << "</UnstructuredGrid>\n";
os << "</VTKFile>" << std::endl;
}
void QuadratureFunction::SaveVTU(const std::string &filename, VTKFormat format,
int compression_level) const
{
std::ofstream f(filename + ".vtu");
SaveVTU(f, format, compression_level);
}
}
<commit_msg>Uncomment QuadratureFunction::Save implementation<commit_after>// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "qfunction.hpp"
#include "quadinterpolator.hpp"
#include "quadinterpolator_face.hpp"
namespace mfem
{
QuadratureFunction &QuadratureFunction::operator=(double value)
{
Vector::operator=(value);
return *this;
}
QuadratureFunction &QuadratureFunction::operator=(const Vector &v)
{
MFEM_ASSERT(qspace && v.Size() == this->Size(), "");
Vector::operator=(v);
return *this;
}
QuadratureFunction::QuadratureFunction(Mesh *mesh, std::istream &in)
{
const char *msg = "invalid input stream";
std::string ident;
qspace = new QuadratureSpace(mesh, in);
own_qspace = true;
in >> ident; MFEM_VERIFY(ident == "VDim:", msg);
in >> vdim;
Load(in, vdim*qspace->GetSize());
}
void QuadratureFunction::SetSpace(QuadratureSpaceBase *qspace_, int vdim_)
{
if (qspace_ != qspace)
{
if (own_qspace) { delete qspace; }
qspace = qspace_;
own_qspace = false;
}
vdim = (vdim_ < 0) ? vdim : vdim_;
SetSize(vdim*qspace->GetSize());
}
void QuadratureFunction::SetSpace(
QuadratureSpaceBase *qspace_, double *qf_data, int vdim_)
{
if (qspace_ != qspace)
{
if (own_qspace) { delete qspace; }
qspace = qspace_;
own_qspace = false;
}
vdim = (vdim_ < 0) ? vdim : vdim_;
NewDataAndSize(qf_data, vdim*qspace->GetSize());
}
void QuadratureFunction::Save(std::ostream &os) const
{
GetSpace()->Save(os);
os << "VDim: " << vdim << '\n'
<< '\n';
Vector::Print(os, vdim);
os.flush();
}
void QuadratureFunction::ProjectGridFunction(const GridFunction &gf)
{
SetVDim(gf.VectorDim());
if (auto *qs_elem = dynamic_cast<QuadratureSpace*>(qspace))
{
const FiniteElementSpace &gf_fes = *gf.FESpace();
const bool use_tensor_products = UsesTensorBasis(gf_fes);
const ElementDofOrdering ordering = use_tensor_products ?
ElementDofOrdering::LEXICOGRAPHIC :
ElementDofOrdering::NATIVE;
// Use element restriction to go from L-vector to E-vector
const Operator *R = gf_fes.GetElementRestriction(ordering);
Vector e_vec(R->Height());
R->Mult(gf, e_vec);
// Use quadrature interpolator to go from E-vector to Q-vector
const QuadratureInterpolator *qi = gf_fes.GetQuadratureInterpolator(*qs_elem);
qi->SetOutputLayout(QVectorLayout::byVDIM);
qi->DisableTensorProducts(!use_tensor_products);
qi->Values(e_vec, *this);
}
else if (auto *qs_face = dynamic_cast<FaceQuadratureSpace*>(qspace))
{
const FiniteElementSpace &gf_fes = *gf.FESpace();
const bool use_tensor_products = UsesTensorBasis(gf_fes);
const ElementDofOrdering ordering = use_tensor_products ?
ElementDofOrdering::LEXICOGRAPHIC :
ElementDofOrdering::NATIVE;
const FaceType face_type = qs_face->GetFaceType();
// Use element restriction to go from L-vector to E-vector
const Operator *R = gf_fes.GetFaceRestriction(
ordering, face_type, L2FaceValues::SingleValued);
Vector e_vec(R->Height());
R->Mult(gf, e_vec);
// Use quadrature interpolator to go from E-vector to Q-vector
const FaceQuadratureInterpolator *qi =
gf_fes.GetFaceQuadratureInterpolator(qspace->GetIntRule(0), face_type);
qi->SetOutputLayout(QVectorLayout::byVDIM);
qi->DisableTensorProducts(!use_tensor_products);
qi->Values(e_vec, *this);
}
else
{
// This branch should be unreachable
MFEM_ABORT("Unsupported case.");
}
}
std::ostream &operator<<(std::ostream &os, const QuadratureFunction &qf)
{
qf.Save(os);
return os;
}
void QuadratureFunction::SaveVTU(std::ostream &os, VTKFormat format,
int compression_level) const
{
os << R"(<VTKFile type="UnstructuredGrid" version="0.1")";
if (compression_level != 0)
{
os << R"( compressor="vtkZLibDataCompressor")";
}
os << " byte_order=\"" << VTKByteOrder() << "\">\n";
os << "<UnstructuredGrid>\n";
const char *fmt_str = (format == VTKFormat::ASCII) ? "ascii" : "binary";
const char *type_str = (format != VTKFormat::BINARY32) ? "Float64" : "Float32";
std::vector<char> buf;
Mesh &mesh = *qspace->GetMesh();
int np = qspace->GetSize();
int ne = mesh.GetNE();
int sdim = mesh.SpaceDimension();
// For quadrature functions, each point is a vertex cell, so number of cells
// is equal to number of points
os << "<Piece NumberOfPoints=\"" << np
<< "\" NumberOfCells=\"" << np << "\">\n";
// print out the points
os << "<Points>\n";
os << "<DataArray type=\"" << type_str
<< "\" NumberOfComponents=\"3\" format=\"" << fmt_str << "\">\n";
Vector pt(sdim);
for (int i = 0; i < ne; i++)
{
ElementTransformation &T = *mesh.GetElementTransformation(i);
const IntegrationRule &ir = GetIntRule(i);
for (int j = 0; j < ir.Size(); j++)
{
T.Transform(ir[j], pt);
WriteBinaryOrASCII(os, buf, pt[0], " ", format);
if (sdim > 1) { WriteBinaryOrASCII(os, buf, pt[1], " ", format); }
else { WriteBinaryOrASCII(os, buf, 0.0, " ", format); }
if (sdim > 2) { WriteBinaryOrASCII(os, buf, pt[2], "", format); }
else { WriteBinaryOrASCII(os, buf, 0.0, "", format); }
if (format == VTKFormat::ASCII) { os << '\n'; }
}
}
if (format != VTKFormat::ASCII)
{
WriteBase64WithSizeAndClear(os, buf, compression_level);
}
os << "</DataArray>\n";
os << "</Points>\n";
// Write cells (each cell is just a vertex)
os << "<Cells>\n";
// Connectivity
os << R"(<DataArray type="Int32" Name="connectivity" format=")"
<< fmt_str << "\">\n";
for (int i=0; i<np; ++i) { WriteBinaryOrASCII(os, buf, i, "\n", format); }
if (format != VTKFormat::ASCII)
{
WriteBase64WithSizeAndClear(os, buf, compression_level);
}
os << "</DataArray>\n";
// Offsets
os << R"(<DataArray type="Int32" Name="offsets" format=")"
<< fmt_str << "\">\n";
for (int i=0; i<np; ++i) { WriteBinaryOrASCII(os, buf, i, "\n", format); }
if (format != VTKFormat::ASCII)
{
WriteBase64WithSizeAndClear(os, buf, compression_level);
}
os << "</DataArray>\n";
// Types
os << R"(<DataArray type="UInt8" Name="types" format=")"
<< fmt_str << "\">\n";
for (int i = 0; i < np; i++)
{
uint8_t vtk_cell_type = VTKGeometry::POINT;
WriteBinaryOrASCII(os, buf, vtk_cell_type, "\n", format);
}
if (format != VTKFormat::ASCII)
{
WriteBase64WithSizeAndClear(os, buf, compression_level);
}
os << "</DataArray>\n";
os << "</Cells>\n";
os << "<PointData>\n";
os << "<DataArray type=\"" << type_str << "\" Name=\"u\" format=\""
<< fmt_str << "\" NumberOfComponents=\"" << vdim << "\">\n";
for (int i = 0; i < ne; i++)
{
DenseMatrix vals;
GetValues(i, vals);
for (int j = 0; j < vals.Size(); ++j)
{
for (int vd = 0; vd < vdim; ++vd)
{
WriteBinaryOrASCII(os, buf, vals(vd, j), " ", format);
}
if (format == VTKFormat::ASCII) { os << '\n'; }
}
}
if (format != VTKFormat::ASCII)
{
WriteBase64WithSizeAndClear(os, buf, compression_level);
}
os << "</DataArray>\n";
os << "</PointData>\n";
os << "</Piece>\n";
os << "</UnstructuredGrid>\n";
os << "</VTKFile>" << std::endl;
}
void QuadratureFunction::SaveVTU(const std::string &filename, VTKFormat format,
int compression_level) const
{
std::ofstream f(filename + ".vtu");
SaveVTU(f, format, compression_level);
}
}
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
int main() {
int a[100][100];
int d[100][100];
a = d;
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
}
}
}
}<commit_msg>Update Floyd with input output<commit_after>#include <iostream>
using namespace std;
int main() {
int n = 4;
int a[n][n];
int d[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> a[i][j];
d[i][j] = a[i][j];
}
}
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << d[i][j] << ' ';
}
cout << endl;
}
}<|endoftext|> |
<commit_before>#include "parse.h"
bool is_number(const std::string& s)
{
std::string::const_iterator it = s.begin();
while (it != s.end() && std::isdigit(*it)) ++it;
return !s.empty() && it == s.end();
}
void host_graph::print_offset_array()
{
std::cout << "R = [";
for(auto i=R.begin(),e=R.end(); i!=e; ++i)
{
if(i == R.begin())
{
std::cout << *i;
}
else
{
std::cout << "," << *i;
}
}
std::cout << "]" << std::endl;
}
void host_graph::print_edge_array()
{
std::cout << "C = [";
for(auto i=C.begin(),e=C.end(); i!=e; ++i)
{
if(i == C.begin())
{
std::cout << *i;
}
else
{
std::cout << "," << *i;
}
}
std::cout << "]" << std::endl;
}
void host_graph::print_from_array()
{
std::cout << "F = [";
for(auto i=F.begin(),e=F.end(); i!=e; ++i)
{
if(i == F.begin())
{
std::cout << *i;
}
else
{
std::cout << "," << *i;
}
}
std::cout << "]" << std::endl;
}
void host_graph::print_adjacency_list()
{
std::cout << "Edge lists for each vertex: " << std::endl;
for(int i=0; i<n; i++)
{
int begin = R[i];
int end = R[i+1];
for(int j=begin; j<end; j++)
{
if(j==begin)
{
std::cout << i << " | " << C[j];
}
else
{
std::cout << ", " << C[j];
}
}
if(begin == end) //Single, unconnected node
{
std::cout << i << " | ";
}
std::cout << std::endl;
}
}
host_graph parse(char *file)
{
std::string s(file);
if(s.find(".graph") != std::string::npos)
{
return parse_metis(file);
}
else if(s.find(".txt") != std::string::npos)
{
return parse_snap(file);
}
else
{
std::cerr << "Error: Unsupported file type." << std::endl;
exit(-1);
}
}
host_graph parse_metis(char *file)
{
host_graph g;
//Get n,m
std::ifstream metis(file,std::ifstream::in);
std::string line;
bool firstline = true;
int current_node = 0;
int current_edge = 0;
if(!metis.good())
{
std::cerr << "Error opening graph file." << std::endl;
exit(-1);
}
while(std::getline(metis,line))
{
if(line[0] == '%')
{
continue;
}
std::vector<std::string> splitvec;
//Mimic boost::split to not have a huge dependency on boost for limited functionality
std::string temp;
for(std::string::iterator i=line.begin(),e=line.end();i!=e;++i)
{
if((*i == '\t') || (*i == ' '))
{
splitvec.push_back(temp);
temp.clear();
}
else
{
temp.append(i,i+1);
}
}
if(!temp.empty())
{
splitvec.push_back(temp);
}
if(firstline)
{
g.n = stoi(splitvec[0]);
g.m = 2*stoi(splitvec[1]);
if(splitvec.size() > 3)
{
std::cerr << "Error: Weighted graphs are not yet supported." << std::endl;
exit(-2);
}
else if((splitvec.size() == 3) && (stoi(splitvec[2]) != 0))
{
std::cerr << "Error: Weighted graphs are not yet supported." << std::endl;
exit(-2);
}
firstline = false;
g.R.resize(g.n+1);
g.C.resize(g.m);
g.F.resize(g.m);
g.R[0] = 0;
current_node++;
}
else
{
//Count the number of edges that this vertex has and add that to the most recent value in R
g.R[current_node] = splitvec.size()+g.R[current_node-1];
for(unsigned i=0; i<splitvec.size(); i++)
{
//coPapersDBLP uses a space to mark the beginning of each line, so we'll account for that here
if(!is_number(splitvec[i]))
{
//Need to adjust g.R
g.R[current_node]--;
continue;
}
//Store the neighbors in C
//METIS graphs are indexed by one, but for our convenience we represent them as if
//they were zero-indexed
g.C[current_edge] = stoi(splitvec[i])-1;
g.F[current_edge] = current_node-1;
current_edge++;
}
current_node++;
}
}
g.directed = false;
return g;
}
host_graph parse_snap(char *file)
{
host_graph g;
std::ifstream snap(file,std::ifstream::in);
if(!snap.good())
{
std::cerr << "Error opening graph file." << std::endl;
}
std::string line;
std::set<int> vertices; //Keep track of the number of unique vertices
bool extra_info_warned = false;
bool self_edge_warned = false;
while(std::getline(snap,line))
{
if(line[0] == '#')
{
continue;
}
std::vector<std::string> splitvec;
//Mimic boost::split to not have a huge dependency on boost for limited functionality
std::string temp;
for(std::string::iterator i=line.begin(),e=line.end();i!=e;++i)
{
if((*i == '\t') || (*i == ' '))
{
splitvec.push_back(temp);
temp.clear();
}
else
{
temp.append(i,i+1);
}
}
if(!temp.empty())
{
splitvec.push_back(temp);
}
if((splitvec.size() > 2) && (!extra_info_warned))
{
std::cerr << "Warning: Ignoring extra information associated with each edge." << std::endl;
std::cerr << "Example: " << std::endl;
for(auto i=splitvec.begin()+2,e=splitvec.end(); i!=e; ++i)
{
std::cerr << *i << std::endl;
}
extra_info_warned = true;
}
int u = stoi(splitvec[0]);
int v = stoi(splitvec[1]);
if((u == v) && (!self_edge_warned))
{
std::cerr << "Warning: Self-edge detected. (" << u << "," << v << ")" << std::endl;
self_edge_warned = true;
}
g.F.push_back(u);
g.C.push_back(v);
vertices.insert(u);
vertices.insert(v);
}
//Now induce R from F and C
g.m = g.F.size();
g.n = vertices.size();
vertices.clear();
g.R.resize(g.n+1);
g.R[0] = 0;
int last_node = 0;
for(int i=0; i<g.m; i++)
{
while((g.F[i] > last_node) && (last_node < (g.n+1)))
{
g.R[++last_node] = i;
}
}
while(last_node < g.n)
{
g.R[++last_node] = g.m;
}
g.directed = true; //FIXME: For now, only support directed SNAP graphs
return g;
}
bool host_graph::write_edgelist_to_file(const std::string &file, bool header)
{
std::ofstream ofs(file.c_str());
if(ofs.good())
{
if(header)
{
ofs << n << " " << m << std::endl;
}
for(int i=0; i<m; i++)
{
ofs << F[i] << " " << C[i] << std::endl;
}
ofs.close();
}
else
{
std::cerr << "Error opening file " << file << " for writing." << std::endl;
return false;
}
return true;
}
<commit_msg>Minor parsing adjustment for lines with leading spaces.<commit_after>#include "parse.h"
bool is_number(const std::string& s)
{
std::string::const_iterator it = s.begin();
while (it != s.end() && std::isdigit(*it)) ++it;
return !s.empty() && it == s.end();
}
void host_graph::print_offset_array()
{
std::cout << "R = [";
for(auto i=R.begin(),e=R.end(); i!=e; ++i)
{
if(i == R.begin())
{
std::cout << *i;
}
else
{
std::cout << "," << *i;
}
}
std::cout << "]" << std::endl;
}
void host_graph::print_edge_array()
{
std::cout << "C = [";
for(auto i=C.begin(),e=C.end(); i!=e; ++i)
{
if(i == C.begin())
{
std::cout << *i;
}
else
{
std::cout << "," << *i;
}
}
std::cout << "]" << std::endl;
}
void host_graph::print_from_array()
{
std::cout << "F = [";
for(auto i=F.begin(),e=F.end(); i!=e; ++i)
{
if(i == F.begin())
{
std::cout << *i;
}
else
{
std::cout << "," << *i;
}
}
std::cout << "]" << std::endl;
}
void host_graph::print_adjacency_list()
{
std::cout << "Edge lists for each vertex: " << std::endl;
for(int i=0; i<n; i++)
{
int begin = R[i];
int end = R[i+1];
for(int j=begin; j<end; j++)
{
if(j==begin)
{
std::cout << i << " | " << C[j];
}
else
{
std::cout << ", " << C[j];
}
}
if(begin == end) //Single, unconnected node
{
std::cout << i << " | ";
}
std::cout << std::endl;
}
}
host_graph parse(char *file)
{
std::string s(file);
if(s.find(".graph") != std::string::npos)
{
return parse_metis(file);
}
else if(s.find(".txt") != std::string::npos)
{
return parse_snap(file);
}
else
{
std::cerr << "Error: Unsupported file type." << std::endl;
exit(-1);
}
}
host_graph parse_metis(char *file)
{
host_graph g;
//Get n,m
std::ifstream metis(file,std::ifstream::in);
std::string line;
bool firstline = true;
int current_node = 0;
int current_edge = 0;
if(!metis.good())
{
std::cerr << "Error opening graph file." << std::endl;
exit(-1);
}
while(std::getline(metis,line))
{
if(line[0] == '%')
{
continue;
}
std::vector<std::string> splitvec;
//Mimic boost::split to not have a huge dependency on boost for limited functionality
std::string temp;
for(std::string::iterator i=line.begin(),e=line.end();i!=e;++i)
{
if(((*i == '\t') || (*i == ' ')) && (!temp.empty()))
{
splitvec.push_back(temp);
temp.clear();
}
else
{
temp.append(i,i+1);
}
}
if(!temp.empty())
{
splitvec.push_back(temp);
}
if(firstline)
{
g.n = stoi(splitvec[0]);
g.m = 2*stoi(splitvec[1]);
if(splitvec.size() > 3)
{
std::cerr << "Error: Weighted graphs are not yet supported." << std::endl;
exit(-2);
}
else if((splitvec.size() == 3) && (stoi(splitvec[2]) != 0))
{
std::cerr << "Error: Weighted graphs are not yet supported." << std::endl;
exit(-2);
}
firstline = false;
g.R.resize(g.n+1);
g.C.resize(g.m);
g.F.resize(g.m);
g.R[0] = 0;
current_node++;
}
else
{
//Count the number of edges that this vertex has and add that to the most recent value in R
g.R[current_node] = splitvec.size()+g.R[current_node-1];
for(unsigned i=0; i<splitvec.size(); i++)
{
//coPapersDBLP uses a space to mark the beginning of each line, so we'll account for that here
if(!is_number(splitvec[i]))
{
//Need to adjust g.R
g.R[current_node]--;
continue;
}
//Store the neighbors in C
//METIS graphs are indexed by one, but for our convenience we represent them as if
//they were zero-indexed
g.C[current_edge] = stoi(splitvec[i])-1;
g.F[current_edge] = current_node-1;
current_edge++;
}
current_node++;
}
}
g.directed = false;
return g;
}
host_graph parse_snap(char *file)
{
host_graph g;
std::ifstream snap(file,std::ifstream::in);
if(!snap.good())
{
std::cerr << "Error opening graph file." << std::endl;
}
std::string line;
std::set<int> vertices; //Keep track of the number of unique vertices
bool extra_info_warned = false;
bool self_edge_warned = false;
while(std::getline(snap,line))
{
if(line[0] == '#')
{
continue;
}
std::vector<std::string> splitvec;
//Mimic boost::split to not have a huge dependency on boost for limited functionality
std::string temp;
for(std::string::iterator i=line.begin(),e=line.end();i!=e;++i)
{
if((*i == '\t') || (*i == ' '))
{
splitvec.push_back(temp);
temp.clear();
}
else
{
temp.append(i,i+1);
}
}
if(!temp.empty())
{
splitvec.push_back(temp);
}
if((splitvec.size() > 2) && (!extra_info_warned))
{
std::cerr << "Warning: Ignoring extra information associated with each edge." << std::endl;
std::cerr << "Example: " << std::endl;
for(auto i=splitvec.begin()+2,e=splitvec.end(); i!=e; ++i)
{
std::cerr << *i << std::endl;
}
extra_info_warned = true;
}
int u = stoi(splitvec[0]);
int v = stoi(splitvec[1]);
if((u == v) && (!self_edge_warned))
{
std::cerr << "Warning: Self-edge detected. (" << u << "," << v << ")" << std::endl;
self_edge_warned = true;
}
g.F.push_back(u);
g.C.push_back(v);
vertices.insert(u);
vertices.insert(v);
}
//Now induce R from F and C
g.m = g.F.size();
g.n = vertices.size();
vertices.clear();
g.R.resize(g.n+1);
g.R[0] = 0;
int last_node = 0;
for(int i=0; i<g.m; i++)
{
while((g.F[i] > last_node) && (last_node < (g.n+1)))
{
g.R[++last_node] = i;
}
}
while(last_node < g.n)
{
g.R[++last_node] = g.m;
}
g.directed = true; //FIXME: For now, only support directed SNAP graphs
return g;
}
bool host_graph::write_edgelist_to_file(const std::string &file, bool header)
{
std::ofstream ofs(file.c_str());
if(ofs.good())
{
if(header)
{
ofs << n << " " << m << std::endl;
}
for(int i=0; i<m; i++)
{
ofs << F[i] << " " << C[i] << std::endl;
}
ofs.close();
}
else
{
std::cerr << "Error opening file " << file << " for writing." << std::endl;
return false;
}
return true;
}
<|endoftext|> |
<commit_before>#include "mainboard.h"
#include "ui_mainboard.h"
#include <QTextStream>
#include <QLabel>
#include <QString>
#include <QPushButton>
#include <QIcon>
#include <QSize>
#include <QObject>
#include <QSignalMapper>
#include "chesslogic.h";
#include "QDebug";
MainBoard::MainBoard(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainBoard)
{
ui->setupUi(this);
this->setFixedSize(1920, 1080);
this->setStyleSheet("background-color: #F0E8E8;");
//TODO this must not be hardcoded when we have more than 1 skirmishes
cl = new ChessLogic();
QString whiteFigureNames[NUMBER_OF_FIGURES] = {":/wPawn", ":/wBishop", ":/wHorse", ":/wRook", ":/wQueen", ":/wKing"};
QString blackFigureNames[NUMBER_OF_FIGURES] = {":/bPawn", ":/bBishop", ":/bHorse", ":/bRook", ":/bQueen", ":/bKing"};
for(int i = 0; i < 50; i++)
{
figures[i] = new QIcon(":/bKing");
}
figures[11] = new QIcon(whiteFigureNames[0]);
figures[12] = new QIcon(whiteFigureNames[2]);
figures[13] = new QIcon(whiteFigureNames[2]);
figures[14] = new QIcon(whiteFigureNames[3]);
figures[15] = new QIcon(whiteFigureNames[1]);
figures[15] = new QIcon(whiteFigureNames[1]);
figures[17] = new QIcon(whiteFigureNames[5]);
figures[18] = new QIcon(whiteFigureNames[4]);
figures[21] = new QIcon(blackFigureNames[0]);
figures[22] = new QIcon(blackFigureNames[2]);
figures[23] = new QIcon(blackFigureNames[2]);
figures[24] = new QIcon(blackFigureNames[3]);
figures[25] = new QIcon(blackFigureNames[1]);
figures[25] = new QIcon(blackFigureNames[1]);
figures[27] = new QIcon(blackFigureNames[5]);
figures[28] =new QIcon( blackFigureNames[4]);
//Initialize Figures
size.setHeight(60);
size.setWidth(60);
initializeBoard(); //initializing the QLabel & QPushButton objects
initializeFigures();//initializing QIcons (figures)
createBoard(); //creating the board and the QpushButtons on top of the board
RefreshBoard();
//positions[5][5]->setStyleSheet("background-color: red");
mapper = new QSignalMapper(this);
connect(mapper, SIGNAL(mapped(int)), this, SLOT(movePieceStart(int)));
int holder[8][8];
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 8; j++)
{
holder[0][j] = 100 + j;
if(i > 0)
{
holder[i][j] = (i * 10) + j;
}
mapper->setMapping(positions[i][j], holder[i][j]);
connect(positions[i][j], SIGNAL(clicked()), mapper, SLOT(map()));
}
}
pieceSignals();
}
void MainBoard::movingPieces()
{
if(onMove)
{
qDebug() << "onMove-true";
positions[0][5]->setIcon(currentPieceIcon);
qDebug() << "sled slagane na nova ikona";
}
// positions[globalButtonCoordinateX][globalButtonCoordinateY]->setIcon(QIcon());
}
void MainBoard::pieceSignals()
{
//connect(positions[globalButtonCoordinateX][globalButtonCoordinateY], SIGNAL(clicked()), this, SLOT(movePieceStart(int)));
connect(positions[0][5], SIGNAL(clicked()), this, SLOT(movingPieces()));
}
void MainBoard::movePieceStart(int i)
{
mappedButtons = i;//from value to index
qDebug() << "mappedButtons: " << mappedButtons;
int firstColumn = 100;//first column mapping
int currentX = 0;//all other columns mapping
for(int z = 10; z <=80; z+=10)
{
currentX++;
for(int j = 0; j <= 7; j++)
{
if(mappedButtons >= firstColumn)
{
globalButtonCoordinateX = 0;
globalButtonCoordinateY = j;
firstColumn++;
}
if(mappedButtons >=z && mappedButtons <= z + 10 - 3)
{
globalButtonCoordinateX = currentX;
globalButtonCoordinateY = j;
z++;
}
}
}
qDebug() << "X: " << globalButtonCoordinateX;
qDebug() << "Y: " << globalButtonCoordinateY;
QIcon currentIcon = positions[globalButtonCoordinateX][globalButtonCoordinateY]->icon();
if((currentIcon.isNull()) == false)
{
onMove = true;
currentPieceIcon = positions[globalButtonCoordinateX][globalButtonCoordinateY]->icon();
}
}
//will disable buttons that are not used at start game
void MainBoard::disableButtons()
{
for(int i = 0; i < BOARD_COLS; i++)
{
for(int j = 2; j < BOARD_ROWS - 2; j++)
{
positions[i][j]->setEnabled(false);
}
}
}
//initialize each QIcon (each figure) and setting the size of all figures
void MainBoard::initializeFigures()
{
for(int i = 0; i < NUMBER_OF_FIGURES; i++)
{
whiteFigures[i] = new QIcon(whiteFigureNames[i]);//{"wPawn", "wBishop", "wHorse", "wRook", "wQueen", "wKing"};
blackFigures[i] = new QIcon(blackFigureNames[i]);//{"bPawn", "bBishop", "bHorse", "bRook", "bQueen", "bKing"};
}
}
//initializing each QLabel and QPushButton
void MainBoard::initializeBoard()
{
for(int i = 0; i < BOARD_COLS; i++)
{
square_letter_label[i] = new QLabel(this);
square_numb_label[i] = new QLabel(this);
for(int j = 0; j < BOARD_ROWS; j++)
{
Sqares[i][j] = new QLabel(this);
positions[i][j] = new QPushButton(this);
}
}
}
//creating chess board and buttons for the figures
void MainBoard::createBoard()
{
for(int i = 0; i < BOARD_COLS; i++)
{
square_letter_label[i]->setText(letter_label[i]);
square_letter_label[i]->setGeometry(x_axis[i] + 45, y_axis[7] + 100, squares_label_width, squares_label_height);
square_numb_label[i]->setText(numb_label[i]);
square_numb_label[i]->setGeometry(x_axis[0] - 25,y_axis[i] + 35, squares_label_width, squares_label_height);
for(int j = 0; j < BOARD_ROWS; j++)
{
Sqares[i][j]->setGeometry(x_axis[i],y_axis[j], squares_size,squares_size);
positions[i][j]->setGeometry(x_axis[i],y_axis[j], squares_size,squares_size);
positions[i][j]->setIconSize(size);
positions[i][j]->setStyleSheet("background-color: transparent;");
if((i%2) == 0)
{
if((j % 2) == 0)
{
Sqares[i][j]->setStyleSheet("background-color: #EBF5FF;");
}
else
{
Sqares[i][j]->setStyleSheet("background-color: #6A1919;");
}
}
else
{
if((j % 2) != 0)
{
Sqares[i][j]->setStyleSheet("background-color: #EBF5FF ;");
}
else
{
Sqares[i][j]->setStyleSheet("background-color: #6A1919;");
}
}
}
}
}
void MainBoard::RefreshBoard()
{
int** currentBoard = cl->GetBoard();
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 8; j++)
{
//*figures[currentBoard[i][j]];
if(currentBoard[i][j] > 0)
{
positions[i][j]->setIcon(*figures[currentBoard[i][j]]);
}
qDebug() << i << " " << j << " " << currentBoard[i][j];
}
}
}
MainBoard::~MainBoard()
{
delete ui;
delete cl;
}
<commit_msg>moving figures<commit_after>#include "mainboard.h"
#include "ui_mainboard.h"
#include <QTextStream>
#include <QLabel>
#include <QString>
#include <QPushButton>
#include <QIcon>
#include <QSize>
#include <QObject>
#include <QSignalMapper>
#include "chesslogic.h";
#include "QDebug";
MainBoard::MainBoard(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainBoard)
{
ui->setupUi(this);
this->setFixedSize(1920, 1080);
this->setStyleSheet("background-color: #F0E8E8;");
//TODO this must not be hardcoded when we have more than 1 skirmishes
cl = new ChessLogic();
QString whiteFigureNames[NUMBER_OF_FIGURES] = {":/wPawn", ":/wBishop", ":/wHorse", ":/wRook", ":/wQueen", ":/wKing"};
QString blackFigureNames[NUMBER_OF_FIGURES] = {":/bPawn", ":/bBishop", ":/bHorse", ":/bRook", ":/bQueen", ":/bKing"};
for(int i = 0; i < 50; i++)
{
figures[i] = new QIcon(":/bKing");
}
figures[11] = new QIcon(whiteFigureNames[0]);
figures[12] = new QIcon(whiteFigureNames[2]);
figures[13] = new QIcon(whiteFigureNames[2]);
figures[14] = new QIcon(whiteFigureNames[3]);
figures[15] = new QIcon(whiteFigureNames[1]);
figures[15] = new QIcon(whiteFigureNames[1]);
figures[17] = new QIcon(whiteFigureNames[5]);
figures[18] = new QIcon(whiteFigureNames[4]);
figures[21] = new QIcon(blackFigureNames[0]);
figures[22] = new QIcon(blackFigureNames[2]);
figures[23] = new QIcon(blackFigureNames[2]);
figures[24] = new QIcon(blackFigureNames[3]);
figures[25] = new QIcon(blackFigureNames[1]);
figures[25] = new QIcon(blackFigureNames[1]);
figures[27] = new QIcon(blackFigureNames[5]);
figures[28] =new QIcon( blackFigureNames[4]);
//Initialize Figures
size.setHeight(60);
size.setWidth(60);
initializeBoard(); //initializing the QLabel & QPushButton objects
initializeFigures();//initializing QIcons (figures)
createBoard(); //creating the board and the QpushButtons on top of the board
RefreshBoard();
//positions[5][5]->setStyleSheet("background-color: red");
mapper = new QSignalMapper(this);
connect(mapper, SIGNAL(mapped(int)), this, SLOT(movePieceStart(int)));
int holder[8][8];
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 8; j++)
{
holder[0][j] = 100 + j;
if(i > 0)
{
holder[i][j] = (i * 10) + j;
}
mapper->setMapping(positions[i][j], holder[i][j]);
connect(positions[i][j], SIGNAL(clicked()), mapper, SLOT(map()));
}
}
pieceSignals();
}
void MainBoard::movingPieces()
{
if(onMove)
{
QIcon *emptyIcon = new QIcon();
positions[7][7]->setIcon(*emptyIcon);
qDebug() << "onMove-true";
positions[oldGlobalButtonCoordinateX][oldGlobalButtonCoordinateY]->setIcon(QIcon());
positions[globalButtonCoordinateX][globalButtonCoordinateY]->setIcon(currentPieceIcon);
}
}
void MainBoard::movePieceStart(int i)
{
mappedButtons = i;//from value to index
qDebug() << "mappedButtons: " << mappedButtons;
int firstColumn = 100;//first column mapping
int currentX = 0;//all other columns mapping
for(int z = 10; z <=80; z+=10)
{
currentX++;
for(int j = 0; j <= 7; j++)
{
if(mappedButtons >= firstColumn)
{
globalButtonCoordinateX = 0;
globalButtonCoordinateY = j;
firstColumn++;
}
if(mappedButtons >=z && mappedButtons <= z + 10 - 3)
{
globalButtonCoordinateX = currentX;
globalButtonCoordinateY = j;
z++;
}
}
}
qDebug() << "X: " << globalButtonCoordinateX;
qDebug() << "Y: " << globalButtonCoordinateY;
QIcon currentIcon = positions[globalButtonCoordinateX][globalButtonCoordinateY]->icon();
if((currentIcon.isNull()) == false)
{
onMove = true;
currentPieceIcon = positions[globalButtonCoordinateX][globalButtonCoordinateY]->icon();
oldGlobalButtonCoordinateX = globalButtonCoordinateX;
oldGlobalButtonCoordinateY = globalButtonCoordinateY;
}
}
//will disable buttons that are not used at start game
void MainBoard::disableButtons()
{
for(int i = 0; i < BOARD_COLS; i++)
{
for(int j = 2; j < BOARD_ROWS - 2; j++)
{
positions[i][j]->setEnabled(false);
}
}
}
//initialize each QIcon (each figure) and setting the size of all figures
void MainBoard::initializeFigures()
{
for(int i = 0; i < NUMBER_OF_FIGURES; i++)
{
whiteFigures[i] = new QIcon(whiteFigureNames[i]);//{"wPawn", "wBishop", "wHorse", "wRook", "wQueen", "wKing"};
blackFigures[i] = new QIcon(blackFigureNames[i]);//{"bPawn", "bBishop", "bHorse", "bRook", "bQueen", "bKing"};
}
}
//initializing each QLabel and QPushButton
void MainBoard::initializeBoard()
{
for(int i = 0; i < BOARD_COLS; i++)
{
square_letter_label[i] = new QLabel(this);
square_numb_label[i] = new QLabel(this);
for(int j = 0; j < BOARD_ROWS; j++)
{
Sqares[i][j] = new QLabel(this);
positions[i][j] = new QPushButton(this);
}
}
}
//creating chess board and buttons for the figures
void MainBoard::createBoard()
{
for(int i = 0; i < BOARD_COLS; i++)
{
square_letter_label[i]->setText(letter_label[i]);
square_letter_label[i]->setGeometry(x_axis[i] + 45, y_axis[7] + 100, squares_label_width, squares_label_height);
square_numb_label[i]->setText(numb_label[i]);
square_numb_label[i]->setGeometry(x_axis[0] - 25,y_axis[i] + 35, squares_label_width, squares_label_height);
for(int j = 0; j < BOARD_ROWS; j++)
{
Sqares[i][j]->setGeometry(x_axis[i],y_axis[j], squares_size,squares_size);
positions[i][j]->setGeometry(x_axis[i],y_axis[j], squares_size,squares_size);
positions[i][j]->setIconSize(size);
positions[i][j]->setStyleSheet("background-color: transparent;");
if((i%2) == 0)
{
if((j % 2) == 0)
{
Sqares[i][j]->setStyleSheet("background-color: #EBF5FF;");
}
else
{
Sqares[i][j]->setStyleSheet("background-color: #6A1919;");
}
}
else
{
if((j % 2) != 0)
{
Sqares[i][j]->setStyleSheet("background-color: #EBF5FF ;");
}
else
{
Sqares[i][j]->setStyleSheet("background-color: #6A1919;");
}
}
}
}
}
void MainBoard::RefreshBoard()
{
int** currentBoard = cl->GetBoard();
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 8; j++)
{
//*figures[currentBoard[i][j]];
if(currentBoard[i][j] > 0)
{
positions[i][j]->setIcon(*figures[currentBoard[i][j]]);
}
qDebug() << i << " " << j << " " << currentBoard[i][j];
}
}
}
MainBoard::~MainBoard()
{
delete ui;
delete cl;
}
<|endoftext|> |
<commit_before>/**
* @file Main.cpp
*/
#include "GLFWEW.h"
#include "Texture.h"
#include "Shader.h"
#include "OffscreenBuffer.h"
#include <glm/gtc/matrix_transform.hpp>
#include <iostream>
#include <vector>
/// _f[^^.
struct Vertex
{
glm::vec3 position; ///< W.
glm::vec4 color; ///< F.
glm::vec2 texCoord; ///< eNX`W.
};
/// _f[^.
const Vertex vertices[] = {
{ {-0.5f, -0.3f, 0.5f}, {0.0f, 1.0f, 0.0f, 1.0f}, {0.0f, 0.0f} },
{ { 0.3f, -0.3f, 0.5f}, {0.0f, 0.0f, 1.0f, 1.0f}, {1.0f, 0.0f} },
{ { 0.3f, 0.5f, 0.5f}, {1.0f, 0.0f, 0.0f, 1.0f}, {1.0f, 1.0f} },
{ {-0.5f, 0.5f, 0.5f}, {0.0f, 0.0f, 1.0f, 1.0f}, {0.0f, 1.0f} },
{ {-0.3f, 0.3f, 0.1f}, {0.0f, 0.0f, 1.0f, 1.0f}, {0.0f, 1.0f} },
{ {-0.3f, -0.5f, 0.1f}, {0.0f, 1.0f, 1.0f, 1.0f}, {0.0f, 0.0f} },
{ { 0.5f, -0.5f, 0.1f}, {0.0f, 0.0f, 1.0f, 1.0f}, {1.0f, 0.0f} },
{ { 0.5f, -0.5f, 0.1f}, {1.0f, 0.0f, 0.0f, 1.0f}, {1.0f, 0.0f} },
{ { 0.5f, 0.3f, 0.1f}, {1.0f, 1.0f, 0.0f, 1.0f}, {1.0f, 1.0f} },
{ {-0.3f, 0.3f, 0.1f}, {1.0f, 0.0f, 0.0f, 1.0f}, {0.0f, 1.0f} },
{ {-1.0f,-1.0f, 0.5f}, {1.0f, 1.0f, 1.0f, 1.0f}, {1.0f, 0.0f} },
{ { 1.0f,-1.0f, 0.5f}, {1.0f, 1.0f, 1.0f, 1.0f}, {0.0f, 0.0f} },
{ { 1.0f, 1.0f, 0.5f}, {1.0f, 1.0f, 1.0f, 1.0f}, {0.0f, 1.0f} },
{ {-1.0f, 1.0f, 0.5f}, {1.0f, 1.0f, 1.0f, 1.0f}, {1.0f, 1.0f} },
};
/// CfbNXf[^.
const GLuint indices[] = {
0, 1, 2, 2, 3, 0,
4, 5, 6, 7, 8, 9,
10, 11, 12, 12, 13, 10,
};
/**
* `f[^.
*/
struct RenderingPart
{
GLvoid* offset; ///< `JnCfbNX̃oCgItZbg.
GLsizei size; ///< `悷CfbNX.
};
/**
* RenderingPart쐬.
*
* @param offset `JnCfbNX̃ItZbg(CfbNXP).
* @param size `悷CfbNX.
*
* @return 쐬`IuWFNg.
*/
constexpr RenderingPart MakeRenderingPart(GLsizei offset, GLsizei size) {
return { reinterpret_cast<GLvoid*>(offset * sizeof(GLuint)), size };
}
/**
* `f[^Xg.
*/
static const RenderingPart renderingParts[] = {
MakeRenderingPart(0, 12),
MakeRenderingPart(12, 6),
};
/**
* Vertex Buffer Object쐬.
*
* @param size _f[^̃TCY.
* @param data _f[^ւ̃|C^.
*
* @return 쐬VBO.
*/
GLuint CreateVBO(GLsizeiptr size, const GLvoid* data)
{
GLuint vbo = 0;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return vbo;
}
/**
* Index Buffer Object쐬.
*
* @param size CfbNXf[^̃TCY.
* @param data CfbNXf[^ւ̃|C^.
*
* @return 쐬IBO.
*/
GLuint CreateIBO(GLsizeiptr size, const GLvoid* data)
{
GLuint ibo = 0;
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
return ibo;
}
/**
* _Agr[gݒ肷.
*
* @param index _Agr[g̃CfbNX.
* @param cls _f[^^.
* @param mbr _Agr[gɐݒ肷cls̃oϐ.
*/
#define SetVertexAttribPointer(index, cls, mbr) SetVertexAttribPointerI( \
index, \
sizeof(cls::mbr) / sizeof(float), \
sizeof(cls), \
reinterpret_cast<GLvoid*>(offsetof(cls, mbr)))
void SetVertexAttribPointerI(GLuint index, GLint size, GLsizei stride, const GLvoid* pointer)
{
glEnableVertexAttribArray(index);
glVertexAttribPointer(index, size, GL_FLOAT, GL_FALSE, stride, pointer);
}
/**
* Vertex Array Object쐬.
*
* @param vbo VAOɊ֘AtVBO.
* @param ibo VAOɊ֘AtIBO.
*
* @return 쐬VAO.
*/
GLuint CreateVAO(GLuint vbo, GLuint ibo)
{
GLuint vao = 0;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
SetVertexAttribPointer(0, Vertex, position);
SetVertexAttribPointer(1, Vertex, color);
SetVertexAttribPointer(2, Vertex, texCoord);
glBindVertexArray(0);
glDeleteBuffers(1, &vbo);
glDeleteBuffers(1, &ibo);
return vao;
}
/// Gg[|Cg.
int main()
{
GLFWEW::Window& window = GLFWEW::Window::Instance();
if (!window.Init(800, 600, "OpenGL Tutorial")) {
return 1;
}
const GLuint vbo = CreateVBO(sizeof(vertices), vertices);
const GLuint ibo = CreateIBO(sizeof(indices), indices);
const GLuint vao = CreateVAO(vbo, ibo);
const GLuint shaderProgram = Shader::CreateProgramFromFile("Res/Tutorial.vert", "Res/Tutorial.frag");
if (!vbo || !ibo || !vao || !shaderProgram) {
return 1;
}
// eNX`f[^.
TexturePtr tex = Texture::LoadFromFile("Res/sample.bmp");
if (!tex) {
return 1;
}
const OffscreenBufferPtr offscreen = OffscreenBuffer::Create(800, 600);
glEnable(GL_DEPTH_TEST);
// C[v.
while (!window.ShouldClose()) {
glBindFramebuffer(GL_FRAMEBUFFER, offscreen->GetFramebuffer());
glClearColor(0.1f, 0.3f, 0.5f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// _]ړ.
static float degree = 0.0f;
degree += 0.1f;
if (degree >= 360.0f) { degree -= 360.0f; }
const glm::vec3 viewPos = glm::rotate(glm::mat4(), glm::radians(degree), glm::vec3(0, 1, 0)) * glm::vec4(2, 3, 3, 1);
glUseProgram(shaderProgram);
const GLint matMVPLoc = glGetUniformLocation(shaderProgram, "matMVP");
if (matMVPLoc >= 0) {
const glm::mat4x4 matProj =
glm::perspective(glm::radians(45.0f), 800.0f / 600.0f, 0.1f, 100.0f);
const glm::mat4x4 matView =
glm::lookAt(viewPos, glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
const glm::mat4x4 matMVP = matProj * matView;
glUniformMatrix4fv(matMVPLoc, 1, GL_FALSE, &matMVP[0][0]);
}
const GLint colorSamplerLoc = glGetUniformLocation(shaderProgram, "colorSampler");
if (colorSamplerLoc >= 0) {
glUniform1i(colorSamplerLoc, 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex->Id());
}
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, renderingParts[0].size, GL_UNSIGNED_INT, renderingParts[0].offset);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClearColor(0.5f, 0.3f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (colorSamplerLoc >= 0) {
glBindTexture(GL_TEXTURE_2D, offscreen->GetTexutre());
}
if (matMVPLoc >= 0) {
glUniformMatrix4fv(matMVPLoc, 1, GL_FALSE, &glm::mat4()[0][0]);
}
glDrawElements(GL_TRIANGLES, renderingParts[1].size, GL_UNSIGNED_INT, renderingParts[1].offset);
window.SwapBuffers();
}
glDeleteProgram(shaderProgram);
glDeleteVertexArrays(1, &vao);
return 0;
}<commit_msg>第04回8.3節の追加分を実装.<commit_after>/**
* @file Main.cpp
*/
#include "GLFWEW.h"
#include "Texture.h"
#include "Shader.h"
#include "OffscreenBuffer.h"
#include <glm/gtc/matrix_transform.hpp>
#include <iostream>
#include <vector>
/// _f[^^.
struct Vertex
{
glm::vec3 position; ///< W.
glm::vec4 color; ///< F.
glm::vec2 texCoord; ///< eNX`W.
};
/// _f[^.
const Vertex vertices[] = {
{ {-0.5f, -0.3f, 0.5f}, {1.0f, 1.0f, 1.0f, 1.0f}, {0.0f, 0.0f} },
{ { 0.3f, -0.3f, 0.5f}, {1.0f, 1.0f, 1.0f, 1.0f}, {1.0f, 0.0f} },
{ { 0.3f, 0.5f, 0.5f}, {1.0f, 1.0f, 1.0f, 1.0f}, {1.0f, 1.0f} },
{ {-0.5f, 0.5f, 0.5f}, {1.0f, 1.0f, 1.0f, 1.0f}, {0.0f, 1.0f} },
{ {-0.3f, 0.3f, 0.1f}, {0.0f, 0.0f, 1.0f, 1.0f}, {0.0f, 1.0f} },
{ {-0.3f, -0.5f, 0.1f}, {0.0f, 1.0f, 1.0f, 1.0f}, {0.0f, 0.0f} },
{ { 0.5f, -0.5f, 0.1f}, {0.0f, 0.0f, 1.0f, 1.0f}, {1.0f, 0.0f} },
{ { 0.5f, -0.5f, 0.1f}, {1.0f, 0.0f, 0.0f, 1.0f}, {1.0f, 0.0f} },
{ { 0.5f, 0.3f, 0.1f}, {1.0f, 1.0f, 0.0f, 1.0f}, {1.0f, 1.0f} },
{ {-0.3f, 0.3f, 0.1f}, {1.0f, 0.0f, 0.0f, 1.0f}, {0.0f, 1.0f} },
{ {-1.0f,-1.0f, 0.5f}, {1.0f, 1.0f, 1.0f, 1.0f}, {1.0f, 0.0f} },
{ { 1.0f,-1.0f, 0.5f}, {1.0f, 1.0f, 1.0f, 1.0f}, {0.0f, 0.0f} },
{ { 1.0f, 1.0f, 0.5f}, {1.0f, 1.0f, 1.0f, 1.0f}, {0.0f, 1.0f} },
{ {-1.0f, 1.0f, 0.5f}, {1.0f, 1.0f, 1.0f, 1.0f}, {1.0f, 1.0f} },
};
/// CfbNXf[^.
const GLuint indices[] = {
0, 1, 2, 2, 3, 0,
4, 5, 6, 7, 8, 9,
10, 11, 12, 12, 13, 10,
};
/**
* `f[^.
*/
struct RenderingPart
{
GLvoid* offset; ///< `JnCfbNX̃oCgItZbg.
GLsizei size; ///< `悷CfbNX.
};
/**
* RenderingPart쐬.
*
* @param offset `JnCfbNX̃ItZbg(CfbNXP).
* @param size `悷CfbNX.
*
* @return 쐬`IuWFNg.
*/
constexpr RenderingPart MakeRenderingPart(GLsizei offset, GLsizei size) {
return { reinterpret_cast<GLvoid*>(offset * sizeof(GLuint)), size };
}
/**
* `f[^Xg.
*/
static const RenderingPart renderingParts[] = {
MakeRenderingPart(0, 12),
MakeRenderingPart(12, 6),
};
/**
* Vertex Buffer Object쐬.
*
* @param size _f[^̃TCY.
* @param data _f[^ւ̃|C^.
*
* @return 쐬VBO.
*/
GLuint CreateVBO(GLsizeiptr size, const GLvoid* data)
{
GLuint vbo = 0;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return vbo;
}
/**
* Index Buffer Object쐬.
*
* @param size CfbNXf[^̃TCY.
* @param data CfbNXf[^ւ̃|C^.
*
* @return 쐬IBO.
*/
GLuint CreateIBO(GLsizeiptr size, const GLvoid* data)
{
GLuint ibo = 0;
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
return ibo;
}
/**
* _Agr[gݒ肷.
*
* @param index _Agr[g̃CfbNX.
* @param cls _f[^^.
* @param mbr _Agr[gɐݒ肷cls̃oϐ.
*/
#define SetVertexAttribPointer(index, cls, mbr) SetVertexAttribPointerI( \
index, \
sizeof(cls::mbr) / sizeof(float), \
sizeof(cls), \
reinterpret_cast<GLvoid*>(offsetof(cls, mbr)))
void SetVertexAttribPointerI(GLuint index, GLint size, GLsizei stride, const GLvoid* pointer)
{
glEnableVertexAttribArray(index);
glVertexAttribPointer(index, size, GL_FLOAT, GL_FALSE, stride, pointer);
}
/**
* Vertex Array Object쐬.
*
* @param vbo VAOɊ֘AtVBO.
* @param ibo VAOɊ֘AtIBO.
*
* @return 쐬VAO.
*/
GLuint CreateVAO(GLuint vbo, GLuint ibo)
{
GLuint vao = 0;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
SetVertexAttribPointer(0, Vertex, position);
SetVertexAttribPointer(1, Vertex, color);
SetVertexAttribPointer(2, Vertex, texCoord);
glBindVertexArray(0);
glDeleteBuffers(1, &vbo);
glDeleteBuffers(1, &ibo);
return vao;
}
/// Gg[|Cg.
int main()
{
GLFWEW::Window& window = GLFWEW::Window::Instance();
if (!window.Init(800, 600, "OpenGL Tutorial")) {
return 1;
}
const GLuint vbo = CreateVBO(sizeof(vertices), vertices);
const GLuint ibo = CreateIBO(sizeof(indices), indices);
const GLuint vao = CreateVAO(vbo, ibo);
const GLuint shaderProgram = Shader::CreateProgramFromFile("Res/Tutorial.vert", "Res/Tutorial.frag");
if (!vbo || !ibo || !vao || !shaderProgram) {
return 1;
}
// eNX`f[^.
TexturePtr tex = Texture::LoadFromFile("Res/sample.bmp");
if (!tex) {
return 1;
}
const OffscreenBufferPtr offscreen = OffscreenBuffer::Create(800, 600);
glEnable(GL_DEPTH_TEST);
// C[v.
while (!window.ShouldClose()) {
glBindFramebuffer(GL_FRAMEBUFFER, offscreen->GetFramebuffer());
glClearColor(0.1f, 0.3f, 0.5f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// _]ړ.
static float degree = 0.0f;
degree += 0.1f;
if (degree >= 360.0f) { degree -= 360.0f; }
const glm::vec3 viewPos = glm::rotate(glm::mat4(), glm::radians(degree), glm::vec3(0, 1, 0)) * glm::vec4(2, 3, 3, 1);
glUseProgram(shaderProgram);
const GLint matMVPLoc = glGetUniformLocation(shaderProgram, "matMVP");
if (matMVPLoc >= 0) {
const glm::mat4x4 matProj =
glm::perspective(glm::radians(45.0f), 800.0f / 600.0f, 0.1f, 100.0f);
const glm::mat4x4 matView =
glm::lookAt(viewPos, glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
const glm::mat4x4 matMVP = matProj * matView;
glUniformMatrix4fv(matMVPLoc, 1, GL_FALSE, &matMVP[0][0]);
}
const GLint colorSamplerLoc = glGetUniformLocation(shaderProgram, "colorSampler");
if (colorSamplerLoc >= 0) {
glUniform1i(colorSamplerLoc, 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex->Id());
}
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, renderingParts[0].size, GL_UNSIGNED_INT, renderingParts[0].offset);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClearColor(0.5f, 0.3f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (colorSamplerLoc >= 0) {
glBindTexture(GL_TEXTURE_2D, offscreen->GetTexutre());
}
if (matMVPLoc >= 0) {
glUniformMatrix4fv(matMVPLoc, 1, GL_FALSE, &glm::mat4()[0][0]);
}
glDrawElements(GL_TRIANGLES, renderingParts[1].size, GL_UNSIGNED_INT, renderingParts[1].offset);
window.SwapBuffers();
}
glDeleteProgram(shaderProgram);
glDeleteVertexArrays(1, &vao);
return 0;
}<|endoftext|> |
<commit_before>/* Kate search plugin
*
* Copyright (C) 2013 by Kåre Särs <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program in a file called COPYING; if not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "FolderFilesList.h"
#include <QDir>
#include <QFileInfo>
#include <QFileInfoList>
#include <QDebug>
#include <QMimeDatabase>
#include <QMimeType>
FolderFilesList::FolderFilesList(QObject *parent) : QThread(parent) {}
FolderFilesList::~FolderFilesList()
{
m_cancelSearch = true;
wait();
}
void FolderFilesList::run()
{
m_files.clear();
QFileInfo folderInfo(m_folder);
checkNextItem(folderInfo);
if (m_cancelSearch) m_files.clear();
}
void FolderFilesList::generateList(const QString &folder,
bool recursive,
bool hidden,
bool symlinks,
bool binary,
const QString &types,
const QString &excludes)
{
m_cancelSearch = false;
m_folder = folder;
m_recursive = recursive;
m_hidden = hidden;
m_symlinks = symlinks;
m_binary = binary;
m_types = types.split(QLatin1Char(','), QString::SkipEmptyParts);
if (m_types.isEmpty()) {
m_types << QStringLiteral("*");
}
QStringList tmpExcludes = excludes.split(QLatin1Char(','));
m_excludeList.clear();
for (int i=0; i<tmpExcludes.size(); i++) {
QRegExp rx(tmpExcludes[i]);
rx.setPatternSyntax(QRegExp::Wildcard);
m_excludeList << rx;
}
start();
}
QStringList FolderFilesList::fileList() { return m_files; }
void FolderFilesList::cancelSearch()
{
m_cancelSearch = true;
}
void FolderFilesList::checkNextItem(const QFileInfo &item)
{
if (m_cancelSearch) {
return;
}
if (item.isFile()) {
if (!m_binary) {
QMimeType mimeType = QMimeDatabase().mimeTypeForFile(item);
if (!mimeType.inherits(QStringLiteral("text/plain"))) {
return;
}
}
m_files << item.absoluteFilePath();
}
else {
QDir currentDir(item.absoluteFilePath());
if (!currentDir.isReadable()) {
qDebug() << currentDir.absolutePath() << "Not readable";
return;
}
QDir::Filters filter = QDir::Files | QDir::NoDotAndDotDot | QDir::Readable;
if (m_hidden) filter |= QDir::Hidden;
if (m_recursive) filter |= QDir::AllDirs;
if (!m_symlinks) filter |= QDir::NoSymLinks;
// sort the items to have an deterministic order!
const QFileInfoList currentItems = currentDir.entryInfoList(m_types, filter, QDir::LocaleAware);
bool skip;
for (int i = 0; i<currentItems.size(); ++i) {
skip = false;
for (int j=0; j<m_excludeList.size(); j++) {
if (m_excludeList[j].exactMatch(currentItems[i].fileName())) {
skip = true;
break;
}
}
if (!skip) {
checkNextItem(currentItems[i]);
}
}
}
}
<commit_msg>missed QDir::Name<commit_after>/* Kate search plugin
*
* Copyright (C) 2013 by Kåre Särs <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program in a file called COPYING; if not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "FolderFilesList.h"
#include <QDir>
#include <QFileInfo>
#include <QFileInfoList>
#include <QDebug>
#include <QMimeDatabase>
#include <QMimeType>
FolderFilesList::FolderFilesList(QObject *parent) : QThread(parent) {}
FolderFilesList::~FolderFilesList()
{
m_cancelSearch = true;
wait();
}
void FolderFilesList::run()
{
m_files.clear();
QFileInfo folderInfo(m_folder);
checkNextItem(folderInfo);
if (m_cancelSearch) m_files.clear();
}
void FolderFilesList::generateList(const QString &folder,
bool recursive,
bool hidden,
bool symlinks,
bool binary,
const QString &types,
const QString &excludes)
{
m_cancelSearch = false;
m_folder = folder;
m_recursive = recursive;
m_hidden = hidden;
m_symlinks = symlinks;
m_binary = binary;
m_types = types.split(QLatin1Char(','), QString::SkipEmptyParts);
if (m_types.isEmpty()) {
m_types << QStringLiteral("*");
}
QStringList tmpExcludes = excludes.split(QLatin1Char(','));
m_excludeList.clear();
for (int i=0; i<tmpExcludes.size(); i++) {
QRegExp rx(tmpExcludes[i]);
rx.setPatternSyntax(QRegExp::Wildcard);
m_excludeList << rx;
}
start();
}
QStringList FolderFilesList::fileList() { return m_files; }
void FolderFilesList::cancelSearch()
{
m_cancelSearch = true;
}
void FolderFilesList::checkNextItem(const QFileInfo &item)
{
if (m_cancelSearch) {
return;
}
if (item.isFile()) {
if (!m_binary) {
QMimeType mimeType = QMimeDatabase().mimeTypeForFile(item);
if (!mimeType.inherits(QStringLiteral("text/plain"))) {
return;
}
}
m_files << item.absoluteFilePath();
}
else {
QDir currentDir(item.absoluteFilePath());
if (!currentDir.isReadable()) {
qDebug() << currentDir.absolutePath() << "Not readable";
return;
}
QDir::Filters filter = QDir::Files | QDir::NoDotAndDotDot | QDir::Readable;
if (m_hidden) filter |= QDir::Hidden;
if (m_recursive) filter |= QDir::AllDirs;
if (!m_symlinks) filter |= QDir::NoSymLinks;
// sort the items to have an deterministic order!
const QFileInfoList currentItems = currentDir.entryInfoList(m_types, filter, QDir::Name | QDir::LocaleAware);
bool skip;
for (int i = 0; i<currentItems.size(); ++i) {
skip = false;
for (int j=0; j<m_excludeList.size(); j++) {
if (m_excludeList[j].exactMatch(currentItems[i].fileName())) {
skip = true;
break;
}
}
if (!skip) {
checkNextItem(currentItems[i]);
}
}
}
}
<|endoftext|> |
<commit_before>/***********************************************************************
filename: CEGUIOpenGLTexture.cpp
created: Sun Jan 11 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
*
* 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 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 <GL/glew.h>
#include "CEGUIOpenGLTexture.h"
#include "CEGUIExceptions.h"
#include "CEGUISystem.h"
#include "CEGUIImageCodec.h"
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
OpenGLTexture::OpenGLTexture(OpenGLRenderer& owner) :
d_size(0, 0),
d_grabBuffer(0),
d_dataSize(0, 0),
d_texelScaling(0, 0),
d_owner(owner)
{
generateOpenGLTexture();
}
//----------------------------------------------------------------------------//
OpenGLTexture::OpenGLTexture(OpenGLRenderer& owner, const String& filename,
const String& resourceGroup) :
d_size(0, 0),
d_grabBuffer(0),
d_dataSize(0, 0),
d_owner(owner)
{
generateOpenGLTexture();
loadFromFile(filename, resourceGroup);
}
//----------------------------------------------------------------------------//
OpenGLTexture::OpenGLTexture(OpenGLRenderer& owner, const Size& size) :
d_size(0, 0),
d_grabBuffer(0),
d_dataSize(0, 0),
d_owner(owner)
{
generateOpenGLTexture();
setTextureSize(size);
}
//----------------------------------------------------------------------------//
OpenGLTexture::OpenGLTexture(OpenGLRenderer& owner, GLuint tex,
const Size& size) :
d_ogltexture(tex),
d_size(size),
d_grabBuffer(0),
d_dataSize(size),
d_owner(owner)
{
updateCachedScaleValues();
}
//----------------------------------------------------------------------------//
OpenGLTexture::~OpenGLTexture()
{
cleanupOpenGLTexture();
}
//----------------------------------------------------------------------------//
const Size& OpenGLTexture::getSize() const
{
return d_size;
}
//----------------------------------------------------------------------------//
const Size& OpenGLTexture::getOriginalDataSize() const
{
return d_dataSize;
}
//----------------------------------------------------------------------------//
const Vector2& OpenGLTexture::getTexelScaling() const
{
return d_texelScaling;
}
//----------------------------------------------------------------------------//
void OpenGLTexture::loadFromFile(const String& filename,
const String& resourceGroup)
{
// Note from PDT:
// There is somewhat tight coupling here between OpenGLTexture and the
// ImageCodec classes - we have intimate knowledge of how they are
// implemented and that knowledge is relied upon in an unhealthy way; this
// should be addressed at some stage.
// load file to memory via resource provider
RawDataContainer texFile;
System::getSingleton().getResourceProvider()->
loadRawDataContainer(filename, texFile, resourceGroup);
// get and check existence of CEGUI::System (needed to access ImageCodec)
System* sys = System::getSingletonPtr();
if (!sys)
CEGUI_THROW(RendererException("OpenGLTexture::loadFromFile - "
"CEGUI::System object has not been created: "
"unable to access ImageCodec."));
Texture* res = sys->getImageCodec().load(texFile, this);
// unload file data buffer
System::getSingleton().getResourceProvider()->
unloadRawDataContainer(texFile);
if (!res)
// It's an error
CEGUI_THROW(RendererException("OpenGLTexture::loadFromFile - " +
sys->getImageCodec().getIdentifierString() +
" failed to load image '" + filename + "'."));
}
//----------------------------------------------------------------------------//
void OpenGLTexture::loadFromMemory(const void* buffer, const Size& buffer_size,
PixelFormat pixel_format)
{
GLint comps;
GLenum format;
switch (pixel_format)
{
case PF_RGB:
comps = 3;
format = GL_RGB;
break;
case PF_RGBA:
comps = 4;
format = GL_RGBA;
break;
};
setTextureSize(buffer_size);
// store size of original data we are loading
d_dataSize = buffer_size;
// update scale values
updateCachedScaleValues();
// save old texture binding
GLuint old_tex;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));
// do the real work of getting the data into the texture
glBindTexture(GL_TEXTURE_2D, d_ogltexture);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0,
static_cast<GLsizei>(buffer_size.d_width),
static_cast<GLsizei>(buffer_size.d_height),
format, GL_UNSIGNED_BYTE, buffer);
// restore previous texture binding.
glBindTexture(GL_TEXTURE_2D, old_tex);
}
//----------------------------------------------------------------------------//
void OpenGLTexture::saveToMemory(void* buffer)
{
// save old texture binding
GLuint old_tex;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));
glBindTexture(GL_TEXTURE_2D, d_ogltexture);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
// restore previous texture binding.
glBindTexture(GL_TEXTURE_2D, old_tex);
}
//----------------------------------------------------------------------------//
void OpenGLTexture::setTextureSize(const Size& sz)
{
const Size size(d_owner.getAdjustedTextureSize(sz));
// make sure size is within boundaries
GLfloat maxSize;
glGetFloatv(GL_MAX_TEXTURE_SIZE, &maxSize);
if ((size.d_width > maxSize) || (size.d_height > maxSize))
CEGUI_THROW(RendererException(
"OpenGLTexture::setTextureSize: size too big"));
// save old texture binding
GLuint old_tex;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));
// set texture to required size
glBindTexture(GL_TEXTURE_2D, d_ogltexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8,
static_cast<GLsizei>(size.d_width),
static_cast<GLsizei>(size.d_height),
0, GL_RGBA , GL_UNSIGNED_BYTE, 0);
// restore previous texture binding.
glBindTexture(GL_TEXTURE_2D, old_tex);
d_dataSize = d_size = size;
updateCachedScaleValues();
}
//----------------------------------------------------------------------------//
void OpenGLTexture::grabTexture()
{
// if texture has already been grabbed, do nothing.
if (d_grabBuffer)
return;
// save old texture binding
GLuint old_tex;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));
// bind the texture we want to grab
glBindTexture(GL_TEXTURE_2D, d_ogltexture);
// allocate the buffer for storing the image data
d_grabBuffer = new uint8[static_cast<int>(4*d_size.d_width*d_size.d_height)];
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, d_grabBuffer);
// delete the texture
glDeleteTextures(1, &d_ogltexture);
// restore previous texture binding.
glBindTexture(GL_TEXTURE_2D, old_tex);
}
//----------------------------------------------------------------------------//
void OpenGLTexture::restoreTexture()
{
if (d_grabBuffer)
{
generateOpenGLTexture();
// save old texture binding
GLuint old_tex;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));
// bind the texture to restore to
glBindTexture(GL_TEXTURE_2D, d_ogltexture);
// reload the saved image data
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
static_cast<GLsizei>(d_size.d_width),
static_cast<GLsizei>(d_size.d_height),
0, GL_RGBA, GL_UNSIGNED_BYTE, d_grabBuffer);
// restore previous texture binding.
glBindTexture(GL_TEXTURE_2D, old_tex);
// free the grabbuffer
delete [] d_grabBuffer;
d_grabBuffer = 0;
}
}
//----------------------------------------------------------------------------//
void OpenGLTexture::updateCachedScaleValues()
{
//
// calculate what to use for x scale
//
const float orgW = d_dataSize.d_width;
const float texW = d_size.d_width;
// if texture and original data width are the same, scale is based
// on the original size.
// if texture is wider (and source data was not stretched), scale
// is based on the size of the resulting texture.
d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW);
//
// calculate what to use for y scale
//
const float orgH = d_dataSize.d_height;
const float texH = d_size.d_height;
// if texture and original data height are the same, scale is based
// on the original size.
// if texture is taller (and source data was not stretched), scale
// is based on the size of the resulting texture.
d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH);
}
//----------------------------------------------------------------------------//
void OpenGLTexture::generateOpenGLTexture()
{
// save old texture binding
GLuint old_tex;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));
glGenTextures(1, &d_ogltexture);
// set some parameters for this texture.
glBindTexture(GL_TEXTURE_2D, d_ogltexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, 0x812F); // GL_CLAMP_TO_EDGE
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, 0x812F); // GL_CLAMP_TO_EDGE
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
// restore previous texture binding.
glBindTexture(GL_TEXTURE_2D, old_tex);
}
//----------------------------------------------------------------------------//
void OpenGLTexture::cleanupOpenGLTexture()
{
// if the grabbuffer is not empty then free it
if (d_grabBuffer)
{
delete[] d_grabBuffer;
d_grabBuffer = 0;
}
// otherwise delete any OpenGL texture associated with this object.
else
{
glDeleteTextures(1, &d_ogltexture);
d_ogltexture = 0;
}
}
//----------------------------------------------------------------------------//
GLuint OpenGLTexture::getOpenGLTexture() const
{
return d_ogltexture;
}
//----------------------------------------------------------------------------//
void OpenGLTexture::setOpenGLTexture(GLuint tex, const Size& size)
{
if (d_ogltexture != tex)
{
// cleanup the current state first.
cleanupOpenGLTexture();
d_ogltexture = tex;
}
d_dataSize = d_size = size;
updateCachedScaleValues();
}
} // End of CEGUI namespace section
<commit_msg>FIX: In OpenGL renderer, default pixel unpack setting of 4 was causing headaches on textures with unusual widths. See: http://www.cegui.org.uk/mantis/view.php?id=778<commit_after>/***********************************************************************
filename: CEGUIOpenGLTexture.cpp
created: Sun Jan 11 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
*
* 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 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 <GL/glew.h>
#include "CEGUIOpenGLTexture.h"
#include "CEGUIExceptions.h"
#include "CEGUISystem.h"
#include "CEGUIImageCodec.h"
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
OpenGLTexture::OpenGLTexture(OpenGLRenderer& owner) :
d_size(0, 0),
d_grabBuffer(0),
d_dataSize(0, 0),
d_texelScaling(0, 0),
d_owner(owner)
{
generateOpenGLTexture();
}
//----------------------------------------------------------------------------//
OpenGLTexture::OpenGLTexture(OpenGLRenderer& owner, const String& filename,
const String& resourceGroup) :
d_size(0, 0),
d_grabBuffer(0),
d_dataSize(0, 0),
d_owner(owner)
{
generateOpenGLTexture();
loadFromFile(filename, resourceGroup);
}
//----------------------------------------------------------------------------//
OpenGLTexture::OpenGLTexture(OpenGLRenderer& owner, const Size& size) :
d_size(0, 0),
d_grabBuffer(0),
d_dataSize(0, 0),
d_owner(owner)
{
generateOpenGLTexture();
setTextureSize(size);
}
//----------------------------------------------------------------------------//
OpenGLTexture::OpenGLTexture(OpenGLRenderer& owner, GLuint tex,
const Size& size) :
d_ogltexture(tex),
d_size(size),
d_grabBuffer(0),
d_dataSize(size),
d_owner(owner)
{
updateCachedScaleValues();
}
//----------------------------------------------------------------------------//
OpenGLTexture::~OpenGLTexture()
{
cleanupOpenGLTexture();
}
//----------------------------------------------------------------------------//
const Size& OpenGLTexture::getSize() const
{
return d_size;
}
//----------------------------------------------------------------------------//
const Size& OpenGLTexture::getOriginalDataSize() const
{
return d_dataSize;
}
//----------------------------------------------------------------------------//
const Vector2& OpenGLTexture::getTexelScaling() const
{
return d_texelScaling;
}
//----------------------------------------------------------------------------//
void OpenGLTexture::loadFromFile(const String& filename,
const String& resourceGroup)
{
// Note from PDT:
// There is somewhat tight coupling here between OpenGLTexture and the
// ImageCodec classes - we have intimate knowledge of how they are
// implemented and that knowledge is relied upon in an unhealthy way; this
// should be addressed at some stage.
// load file to memory via resource provider
RawDataContainer texFile;
System::getSingleton().getResourceProvider()->
loadRawDataContainer(filename, texFile, resourceGroup);
// get and check existence of CEGUI::System (needed to access ImageCodec)
System* sys = System::getSingletonPtr();
if (!sys)
CEGUI_THROW(RendererException("OpenGLTexture::loadFromFile - "
"CEGUI::System object has not been created: "
"unable to access ImageCodec."));
Texture* res = sys->getImageCodec().load(texFile, this);
// unload file data buffer
System::getSingleton().getResourceProvider()->
unloadRawDataContainer(texFile);
if (!res)
// It's an error
CEGUI_THROW(RendererException("OpenGLTexture::loadFromFile - " +
sys->getImageCodec().getIdentifierString() +
" failed to load image '" + filename + "'."));
}
//----------------------------------------------------------------------------//
void OpenGLTexture::loadFromMemory(const void* buffer, const Size& buffer_size,
PixelFormat pixel_format)
{
GLint comps;
GLenum format;
switch (pixel_format)
{
case PF_RGB:
comps = 3;
format = GL_RGB;
break;
case PF_RGBA:
comps = 4;
format = GL_RGBA;
break;
};
setTextureSize(buffer_size);
// store size of original data we are loading
d_dataSize = buffer_size;
// update scale values
updateCachedScaleValues();
// save old states
GLuint old_tex, old_pack;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));
glGetIntegerv(GL_UNPACK_ALIGNMENT, reinterpret_cast<GLint*>(&old_tex));
// do the real work of getting the data into the texture
glBindTexture(GL_TEXTURE_2D, d_ogltexture);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0,
static_cast<GLsizei>(buffer_size.d_width),
static_cast<GLsizei>(buffer_size.d_height),
format, GL_UNSIGNED_BYTE, buffer);
// restore previous states.
glPixelStorei(GL_UNPACK_ALIGNMENT, old_pack);
glBindTexture(GL_TEXTURE_2D, old_tex);
}
//----------------------------------------------------------------------------//
void OpenGLTexture::saveToMemory(void* buffer)
{
// save old texture binding
GLuint old_tex;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));
glBindTexture(GL_TEXTURE_2D, d_ogltexture);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
// restore previous texture binding.
glBindTexture(GL_TEXTURE_2D, old_tex);
}
//----------------------------------------------------------------------------//
void OpenGLTexture::setTextureSize(const Size& sz)
{
const Size size(d_owner.getAdjustedTextureSize(sz));
// make sure size is within boundaries
GLfloat maxSize;
glGetFloatv(GL_MAX_TEXTURE_SIZE, &maxSize);
if ((size.d_width > maxSize) || (size.d_height > maxSize))
CEGUI_THROW(RendererException(
"OpenGLTexture::setTextureSize: size too big"));
// save old texture binding
GLuint old_tex;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));
// set texture to required size
glBindTexture(GL_TEXTURE_2D, d_ogltexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8,
static_cast<GLsizei>(size.d_width),
static_cast<GLsizei>(size.d_height),
0, GL_RGBA , GL_UNSIGNED_BYTE, 0);
// restore previous texture binding.
glBindTexture(GL_TEXTURE_2D, old_tex);
d_dataSize = d_size = size;
updateCachedScaleValues();
}
//----------------------------------------------------------------------------//
void OpenGLTexture::grabTexture()
{
// if texture has already been grabbed, do nothing.
if (d_grabBuffer)
return;
// save old texture binding
GLuint old_tex;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));
// bind the texture we want to grab
glBindTexture(GL_TEXTURE_2D, d_ogltexture);
// allocate the buffer for storing the image data
d_grabBuffer = new uint8[static_cast<int>(4*d_size.d_width*d_size.d_height)];
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, d_grabBuffer);
// delete the texture
glDeleteTextures(1, &d_ogltexture);
// restore previous texture binding.
glBindTexture(GL_TEXTURE_2D, old_tex);
}
//----------------------------------------------------------------------------//
void OpenGLTexture::restoreTexture()
{
if (d_grabBuffer)
{
generateOpenGLTexture();
// save old texture binding
GLuint old_tex;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));
// bind the texture to restore to
glBindTexture(GL_TEXTURE_2D, d_ogltexture);
// reload the saved image data
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
static_cast<GLsizei>(d_size.d_width),
static_cast<GLsizei>(d_size.d_height),
0, GL_RGBA, GL_UNSIGNED_BYTE, d_grabBuffer);
// restore previous texture binding.
glBindTexture(GL_TEXTURE_2D, old_tex);
// free the grabbuffer
delete [] d_grabBuffer;
d_grabBuffer = 0;
}
}
//----------------------------------------------------------------------------//
void OpenGLTexture::updateCachedScaleValues()
{
//
// calculate what to use for x scale
//
const float orgW = d_dataSize.d_width;
const float texW = d_size.d_width;
// if texture and original data width are the same, scale is based
// on the original size.
// if texture is wider (and source data was not stretched), scale
// is based on the size of the resulting texture.
d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW);
//
// calculate what to use for y scale
//
const float orgH = d_dataSize.d_height;
const float texH = d_size.d_height;
// if texture and original data height are the same, scale is based
// on the original size.
// if texture is taller (and source data was not stretched), scale
// is based on the size of the resulting texture.
d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH);
}
//----------------------------------------------------------------------------//
void OpenGLTexture::generateOpenGLTexture()
{
// save old texture binding
GLuint old_tex;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&old_tex));
glGenTextures(1, &d_ogltexture);
// set some parameters for this texture.
glBindTexture(GL_TEXTURE_2D, d_ogltexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, 0x812F); // GL_CLAMP_TO_EDGE
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, 0x812F); // GL_CLAMP_TO_EDGE
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
// restore previous texture binding.
glBindTexture(GL_TEXTURE_2D, old_tex);
}
//----------------------------------------------------------------------------//
void OpenGLTexture::cleanupOpenGLTexture()
{
// if the grabbuffer is not empty then free it
if (d_grabBuffer)
{
delete[] d_grabBuffer;
d_grabBuffer = 0;
}
// otherwise delete any OpenGL texture associated with this object.
else
{
glDeleteTextures(1, &d_ogltexture);
d_ogltexture = 0;
}
}
//----------------------------------------------------------------------------//
GLuint OpenGLTexture::getOpenGLTexture() const
{
return d_ogltexture;
}
//----------------------------------------------------------------------------//
void OpenGLTexture::setOpenGLTexture(GLuint tex, const Size& size)
{
if (d_ogltexture != tex)
{
// cleanup the current state first.
cleanupOpenGLTexture();
d_ogltexture = tex;
}
d_dataSize = d_size = size;
updateCachedScaleValues();
}
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>#include <sequence/Parser.hpp>
#include <cstdio>
#include <cstdlib>
namespace sequence {
inline static void printRegular(const Item& item) {
const auto pFilename = item.filename.c_str();
switch (item.getType()) {
case Item::SINGLE:
printf("%s\n", pFilename);
break;
case Item::INVALID:
printf("Invalid\n");
break;
case Item::INDICED:
printf("%s (%lu) %d\n", pFilename, (unsigned long) item.indices.size(), item.padding);
break;
case Item::PACKED:
if (item.step == 1)
printf("%s [%d:%d] #%d\n", pFilename, item.start, item.end, item.padding);
else
printf("%s [%d:%d]/%d #%d\n", pFilename, item.start, item.end, item.step, item.padding);
break;
}
}
inline static void printRegular(const FolderContent&result) {
printf("\n\n* %s\n", result.name.c_str());
for (const Item &item : result.directories)
printRegular(item);
printf("\n");
for (const Item &item : result.files)
printRegular(item);
}
inline static void printJson(const Item& item) {
const auto pFilename = item.filename.c_str();
switch (item.getType()) {
case Item::SINGLE:
printf("%s\n", pFilename);
break;
case Item::INVALID:
printf("Invalid\n");
break;
case Item::INDICED:
printf("%s (%lu) %d\n", pFilename, (unsigned long) item.indices.size(), item.padding);
break;
case Item::PACKED:
if (item.step == 1)
printf("%s [%d:%d] #%d\n", pFilename, item.start, item.end, item.padding);
else
printf("%s [%d:%d]/%d #%d\n", pFilename, item.start, item.end, item.step, item.padding);
break;
}
}
inline static void printJson(const FolderContent&result) {
printf("{");
printf(R"("path":"%s",[)", result.name.c_str());
for (const Item &item : result.directories)
printJson(item);
printf("],[");
for (const Item &item : result.files)
printJson(item);
printf("]");
printf("}");
}
} // namespace sequence
static void printHelp() {
printf("USAGE [OPTIONS] [FOLDER]\n");
printf("--help,-h Print help and exit\n");
printf("--merge-padding,-m Merge sequence with different padding\n");
printf("--recursive,-r Parse folder recursively\n");
printf("--pack,-p Drop indices and replace with one or several contiguous chunks\n");
printf("--bake-singleton,-b Replace Items with only one index by it's corresponding filename\n");
printf("--sort,-s Print folder and files lexicographically sorted\n");
// printf("--json,-j Output result as a json object\n");
printf("--keep= Strategy to handle ambiguous locations\n");
printf(" none flattens the set\n");
printf(" first keep first number\n");
printf(" last keep last number\n");
printf(" max-variance keep number with highest variance (default)\n");
printf(" backups to 'none' if same variance\n");
}
#include <list>
int main(int argc, char **argv) {
using namespace std;
using namespace sequence;
bool recursive = false;
bool json = false;
Configuration configuration;
configuration.getPivotIndex = RETAIN_HIGHEST_VARIANCE;
string folder = ".";
for (int i = 1; i < argc; ++i) {
string arg = argv[i];
if (arg == "--help" || arg == "-h") {
printHelp();
return 0;
} else if (arg == "--merge-padding" || arg == "-m")
configuration.mergePadding = true;
else if (arg == "--pack" || arg == "-p")
configuration.pack = true;
else if (arg == "--recursive" || arg == "-r")
recursive = true;
else if (arg == "--bake-singleton" || arg == "-b")
configuration.bakeSingleton = true;
else if (arg == "--sort" || arg == "-s")
configuration.sort = true;
// else if (arg == "--json" || arg == "-j")
// json = true;
else if (arg == "--keep=none")
configuration.getPivotIndex = RETAIN_NONE;
else if (arg == "--keep=first")
configuration.getPivotIndex = RETAIN_FIRST_LOCATION;
else if (arg == "--keep=last")
configuration.getPivotIndex = RETAIN_LAST_LOCATION;
else if (arg == "--keep=max-variance")
configuration.getPivotIndex = RETAIN_HIGHEST_VARIANCE;
else if (arg[0] == '-') {
printf("Unknown option : %s\n", arg.c_str());
return EXIT_FAILURE;
} else
folder = arg;
}
list<Item> folders;
folders.emplace_back(folder);
while (!folders.empty()) {
const auto ¤t = folders.front().filename;
auto result = parseDir(configuration, current.c_str());
for (const Item &item : result.directories) {
const string& filename = item.filename;
if (recursive && !filename.empty() && filename != "." && filename != "..") {
const bool lastCurrentCharIsSlash = current.back() == '/';
if (lastCurrentCharIsSlash)
folders.emplace_back(current + filename);
else
folders.emplace_back(current + '/' + filename);
}
}
if (json)
printJson(result);
else
printRegular(result);
folders.pop_front();
}
return EXIT_SUCCESS;
}
<commit_msg>working on json export<commit_after>#include <sequence/Parser.hpp>
#include <ostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
namespace sequence {
inline static void printRegular(const Item& item) {
const auto pFilename = item.filename.c_str();
switch (item.getType()) {
case Item::SINGLE:
printf("%s\n", pFilename);
break;
case Item::INVALID:
printf("Invalid\n");
break;
case Item::INDICED:
printf("%s (%lu) %d\n", pFilename, (unsigned long) item.indices.size(), item.padding);
break;
case Item::PACKED:
if (item.step == 1)
printf("%s [%d:%d] #%d\n", pFilename, item.start, item.end, item.padding);
else
printf("%s [%d:%d]/%d #%d\n", pFilename, item.start, item.end, item.step, item.padding);
break;
}
}
inline static void printRegular(const FolderContent&result) {
printf("\n\n* %s\n", result.name.c_str());
for (const Item &item : result.directories)
printRegular(item);
printf("\n");
for (const Item &item : result.files)
printRegular(item);
}
//
//struct JsonRaii {
// JsonRaii(char open, char end, char separator)
// const char open;
// const char end;
// const char separator;
//};
//
//template<typename T>
//inline static void printJson(const T& value) {
//}
//
//template<>
//void printJson(const Item &item) {
// switch (item.getType()) {
// case Item::SINGLE:
// printf(R"({"filename":"%s"})", item.filename.c_str());
// break;
// case Item::INVALID:
// printf("{}");
// break;
// case Item::INDICED:
// break;
// case Item::PACKED:
// break;
// }
//}
//
//template<>
//void printJson(const Items &items) {
// bool first = true;
// printf("[");
// for (const Item &item : items) {
// if (!first)
// printf(",");
// printJson(item);
// first = false;
// }
// printf("]");
//}
//
//template<>
//void printJson(const FolderContent &result) {
// printf("{");
// printf(R"("path":"%s","directories":)", result.name.c_str());
// printJson(result.directories);
// printf(R"(,"files":)");
// printJson(result.files);
// printf("}");
//}
struct JsonRaii {
JsonRaii(std::ostream& stream, char open, char end) :
stream(stream), end(end), first(true) {
stream << open;
}
static JsonRaii object(std::ostream& stream) {
return JsonRaii(stream, '{', '}');
}
static JsonRaii array(std::ostream& stream) {
return JsonRaii(stream, '[', ']');
}
~JsonRaii() {
stream << end;
}
template<typename T>
std::ostream& operator<<(const T &value) {
if (!first)
stream << ',';
first = false;
return stream << value;
}
std::ostream& stream;
const char end;
bool first;
};
} // namespace sequence
static void printHelp() {
printf("USAGE [OPTIONS] [FOLDER]\n");
printf("--help,-h Print help and exit\n");
printf("--merge-padding,-m Merge sequence with different padding\n");
printf("--recursive,-r Parse folder recursively\n");
printf("--pack,-p Drop indices and replace with one or several contiguous chunks\n");
printf("--bake-singleton,-b Replace Items with only one index by it's corresponding filename\n");
printf("--sort,-s Print folder and files lexicographically sorted\n");
// printf("--json,-j Output result as a json object\n");
printf("--keep= Strategy to handle ambiguous locations\n");
printf(" none flattens the set\n");
printf(" first keep first number\n");
printf(" last keep last number\n");
printf(" max-variance keep number with highest variance (default)\n");
printf(" backups to 'none' if same variance\n");
}
#include <list>
int main(int argc, char **argv) {
using namespace std;
using namespace sequence;
bool recursive = false;
bool json = false;
Configuration configuration;
configuration.getPivotIndex = RETAIN_HIGHEST_VARIANCE;
string folder = ".";
for (int i = 1; i < argc; ++i) {
string arg = argv[i];
if (arg == "--help" || arg == "-h") {
printHelp();
return 0;
} else if (arg == "--merge-padding" || arg == "-m")
configuration.mergePadding = true;
else if (arg == "--pack" || arg == "-p")
configuration.pack = true;
else if (arg == "--recursive" || arg == "-r")
recursive = true;
else if (arg == "--bake-singleton" || arg == "-b")
configuration.bakeSingleton = true;
else if (arg == "--sort" || arg == "-s")
configuration.sort = true;
// else if (arg == "--json" || arg == "-j")
// json = true;
else if (arg == "--keep=none")
configuration.getPivotIndex = RETAIN_NONE;
else if (arg == "--keep=first")
configuration.getPivotIndex = RETAIN_FIRST_LOCATION;
else if (arg == "--keep=last")
configuration.getPivotIndex = RETAIN_LAST_LOCATION;
else if (arg == "--keep=max-variance")
configuration.getPivotIndex = RETAIN_HIGHEST_VARIANCE;
else if (arg[0] == '-') {
printf("Unknown option : %s\n", arg.c_str());
return EXIT_FAILURE;
} else
folder = arg;
}
list<Item> folders;
folders.emplace_back(folder);
while (!folders.empty()) {
const auto ¤t = folders.front().filename;
auto result = parseDir(configuration, current.c_str());
for (const Item &item : result.directories) {
const string& filename = item.filename;
if (recursive && !filename.empty() && filename != "." && filename != "..") {
const bool lastCurrentCharIsSlash = current.back() == '/';
if (lastCurrentCharIsSlash)
folders.emplace_back(current + filename);
else
folders.emplace_back(current + '/' + filename);
}
}
if (json) {
ostringstream oss;
{
JsonRaii json = JsonRaii::array(oss);
json << "toto";
json << "tata";
}
printf("%s", oss.str().c_str());
} else
printRegular(result);
folders.pop_front();
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Use with:
// -Xclang -load -Xclang path/to/string-plugin.so -Xclang -add-plugin -Xclang format-plugin
// and zero or more of
// -Xclang -plugin-arg-format-plugin -Xclang -list=functions.txt
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>
#define __STDC_LIMIT_MACROS 1
#define __STDC_CONSTANT_MACROS 1
#include <clang/AST/AST.h>
#include <clang/AST/ASTConsumer.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/FrontendPluginRegistry.h>
#include <clang/Sema/Sema.h>
#include <llvm/ADT/SmallBitVector.h>
#include "split.h"
#include "utf8string.h"
namespace {
struct FunctionDesc {
std::string name;
clang::Sema::FormatStringType type;
unsigned format_arg;
unsigned var_arg;
};
FunctionDesc const default_function_list[] = {
// Wide string formatting
{ "wprintf", clang::Sema::FST_Printf, 1, 2 },
{ "fwprintf", clang::Sema::FST_Printf, 2, 3 },
{ "swprintf", clang::Sema::FST_Printf, 2, 3 },
{ "vwprintf", clang::Sema::FST_Printf, 1, 0 },
{ "vfwprintf", clang::Sema::FST_Printf, 2, 0 },
{ "vswprintf", clang::Sema::FST_Printf, 2, 0 },
{ "wscanf", clang::Sema::FST_Scanf, 1, 2 },
{ "fwscanf", clang::Sema::FST_Scanf, 2, 3 },
{ "swscanf", clang::Sema::FST_Scanf, 2, 3 },
{ "vwscanf", clang::Sema::FST_Scanf, 1, 0 },
{ "vfwscanf", clang::Sema::FST_Scanf, 2, 0 },
{ "vswscanf", clang::Sema::FST_Scanf, 2, 0 },
// Annex K
{ "wprintf_s", clang::Sema::FST_Printf, 1, 2 },
{ "fwprintf_s", clang::Sema::FST_Printf, 2, 3 },
{ "swprintf_s", clang::Sema::FST_Printf, 3, 4 },
{ "snwprintf_s", clang::Sema::FST_Printf, 3, 4 },
{ "vwprintf_s", clang::Sema::FST_Printf, 1, 0 },
{ "vfwprintf_s", clang::Sema::FST_Printf, 2, 0 },
{ "vswprintf_s", clang::Sema::FST_Printf, 3, 0 },
{ "vsnwprintf_s", clang::Sema::FST_Printf, 3, 0 },
{ "wscanf_s", clang::Sema::FST_Scanf, 1, 2 },
{ "fwscanf_s", clang::Sema::FST_Scanf, 2, 3 },
{ "swscanf_s", clang::Sema::FST_Scanf, 2, 3 },
{ "vwscanf_s", clang::Sema::FST_Scanf, 1, 0 },
{ "vfwscanf_s", clang::Sema::FST_Scanf, 2, 0 },
{ "vswscanf_s", clang::Sema::FST_Scanf, 2, 0 },
// Wide string time
{ "wcsftime", clang::Sema::FST_Strftime, 3, 0 },
};
struct GettextDesc {
std::string name;
unsigned format_arg;
};
struct FormatString
{
std::string string;
clang::StringLiteral const *expr;
};
class FormatVisitor : public clang::RecursiveASTVisitor<FormatVisitor> {
public:
explicit FormatVisitor(
clang::CompilerInstance& inst,
std::vector<FunctionDesc> const & functions,
std::vector<GettextDesc> const & gettexts) :
instance(inst),
diagnostics(inst.getDiagnostics())
{
not_literal = diagnostics.getCustomDiagID(clang::DiagnosticsEngine::Warning, "format is not a string literal");
for (auto fs = functions.begin(); fs != functions.end(); ++fs) {
function_list.push_back(*fs);
}
for (auto gs = gettexts.begin(); gs != gettexts.end(); ++gs) {
gettext_list.push_back(*gs);
}
}
bool VisitCallExpr(clang::CallExpr *exp)
{
clang::FunctionDecl *d = exp->getDirectCallee();
if (d == nullptr) { return true; }
// Assume that any function with a format attribute is checked in the
// core; don't duplicate the warning
if (!d->hasAttr<clang::FormatAttr>()) {
// Determine whether the function is one we're looking for
llvm::StringRef const name = d->getIdentifier()->getName();
for (auto fs = function_list.begin(); fs != function_list.end(); ++fs) {
if (name == fs->name) {
processFormat(exp, *fs);
break;
}
}
}
return true;
}
private:
void processFormat(clang::CallExpr *expr, FunctionDesc const & desc)
{
std::vector<FormatString> formats;
getFormatStrings(formats, expr->getArg(desc.format_arg-1));
llvm::ArrayRef<const clang::Expr *> args(
expr->getArgs(),
expr->getNumArgs());
for (auto i = formats.begin(); i != formats.end(); ++i) {
clang::StringLiteral *fexpr = nullptr;
if (!i->expr->isAscii() && !i->expr->isUTF8()) {
clang::QualType type = instance.getASTContext().getConstantArrayType(
instance.getASTContext().CharTy.withConst(),
llvm::APInt(32, i->string.size()+1),
clang::ArrayType::Normal, 0);
clang::SourceLocation loc =
// Offset 1 for the L, u or U prefix
i->expr->getLocStart().getLocWithOffset(1);
fexpr = clang::StringLiteral::Create(
instance.getASTContext(),
clang::StringRef(i->string.c_str(), i->string.size()),
clang::StringLiteral::UTF8,
false,
type,
loc);
}
llvm::SmallBitVector checked_args;
instance.getSema().CheckFormatString(
fexpr ? fexpr : i->expr,
i->expr,
args,
desc.var_arg == 0,
desc.format_arg - 1,
desc.var_arg - 1,
desc.type,
true,
clang::Sema::VariadicFunction,
checked_args);
}
}
void getFormatStrings(
std::vector<FormatString>& formats,
clang::Expr const *arg)
{
if (arg == nullptr) { return; }
// Pass any implicit type conversions
arg = arg->IgnoreImplicit();
// If function call, look for gettext-like functions
{
clang::CallExpr const *call = llvm::dyn_cast_or_null<clang::CallExpr>(arg);
if (call != nullptr) {
clang::FunctionDecl const *d = call->getDirectCallee();
if (d == nullptr) { goto warn; }
if (d->hasAttr<clang::FormatArgAttr>()) {
for (auto a = d->specific_attr_begin<clang::FormatArgAttr>();
a != d->specific_attr_end<clang::FormatArgAttr>(); ++a) {
// The function may have any number of format_arg attributes;
// this allows the function to accept multiple format strings
getFormatStrings(formats, call->getArg((*a)->getFormatIdx()-1));
}
} else {
llvm::StringRef const name = d->getIdentifier()->getName();
bool found = false;
for (auto a = gettext_list.begin();
a != gettext_list.end(); ++a) {
// The function appear any number of times in getext_list;
// this allows the function to accept multiple format strings
if (name == a->name) {
getFormatStrings(formats, call->getArg(a->format_arg-1));
found = true;
}
}
if (!found) { goto warn; }
}
return;
}
}
// If conditional operator, process the two possible format strings
{
clang::AbstractConditionalOperator const *cond = llvm::dyn_cast_or_null<clang::AbstractConditionalOperator>(arg);
if (cond != nullptr) {
getFormatStrings(formats, cond->getTrueExpr());
getFormatStrings(formats, cond->getFalseExpr());
return;
}
}
{
// If string literal, add it to the list
clang::StringLiteral const *str = llvm::dyn_cast_or_null<clang::StringLiteral>(arg);
if (str != nullptr) {
// Get the text of the string literal
FormatString fmt;
fmt.string = stringToUTF8(str);
fmt.expr = str;
formats.push_back(fmt);
return;
}
}
warn:
// Can't process this format; raise a warning
diagnostics.Report(arg->getLocStart(), not_literal);
}
clang::CompilerInstance& instance;
clang::DiagnosticsEngine& diagnostics;
unsigned not_literal;
std::vector<FunctionDesc> function_list;
std::vector<GettextDesc> gettext_list;
};
struct FormatASTConsumer : public clang::ASTConsumer {
public:
explicit FormatASTConsumer(
clang::CompilerInstance& inst,
std::vector<FunctionDesc> const & functions,
std::vector<GettextDesc> const & gettexts)
: Visitor(inst, functions, gettexts) {}
virtual void HandleTranslationUnit(clang::ASTContext &Context)
{
Visitor.TraverseDecl(Context.getTranslationUnitDecl());
}
private:
FormatVisitor Visitor;
};
class FormatAction : public clang::PluginASTAction {
public:
clang::ASTConsumer* CreateASTConsumer(clang::CompilerInstance& inst, llvm::StringRef str) override
{
if (function_list.empty()) {
for (std::size_t i = 0; i < sizeof(default_function_list)/sizeof(default_function_list[0]); ++i) {
function_list.push_back(default_function_list[i]);
}
}
return new FormatASTConsumer(inst, function_list, gettext_list);
}
bool ParseArgs(const clang::CompilerInstance& inst,
const std::vector<std::string>& args) override
{
bool ok = true;
clang::DiagnosticsEngine *diagnostics = &inst.getDiagnostics();
unsigned bad_file = diagnostics->getCustomDiagID(clang::DiagnosticsEngine::Error, "cannot open file %0: %1");
unsigned bad_option = diagnostics->getCustomDiagID(clang::DiagnosticsEngine::Error, "unknown option: %0");
for (auto i = args.begin(); i != args.end(); ++i) {
std::string arg = *i;
if (arg.substr(0, 6) == "-list=") {
std::string filename(arg.substr(6));
std::ifstream file(filename);
while (file.good()) {
std::string line;
std::getline(file, line);
std::vector<std::string> vec = Split(line);
if (vec.size() < 3) { continue; }
if (vec[1] == "gettext") {
GettextDesc desc;
desc.name = vec[0];
desc.format_arg = std::strtoull(vec[2].c_str(), nullptr, 10);
gettext_list.push_back(desc);
} else {
FunctionDesc desc;
desc.name = vec[0];
if (vec[1] == "printf") {
desc.type = clang::Sema::FST_Printf;
} else if (vec[1] == "scanf") {
desc.type = clang::Sema::FST_Scanf;
} else if (vec[1] == "NSString") {
desc.type = clang::Sema::FST_NSString;
} else if (vec[1] == "strftime") {
desc.type = clang::Sema::FST_Strftime;
} else if (vec[1] == "strfmon") {
desc.type = clang::Sema::FST_Strfmon;
} else if (vec[1] == "kprintf") {
desc.type = clang::Sema::FST_Kprintf;
} else {
continue;
}
desc.format_arg = std::strtoull(vec[2].c_str(), nullptr, 10);
desc.var_arg = vec.size() > 3 ? std::strtoull(vec[3].c_str(), nullptr, 10) : 0;
function_list.push_back(desc);
}
}
if (!file.eof()) {
// failed to open the file, or error while reading it
diagnostics->Report(bad_file) << filename << std::strerror(errno);
ok = false;
}
} else {
diagnostics->Report(bad_option) << arg;
ok = false;
}
}
return ok;
}
private:
std::vector<FunctionDesc> function_list;
std::vector<GettextDesc> gettext_list;
};
} // end anonymous namespace
static clang::FrontendPluginRegistry::Add<FormatAction>
X("format-plugin", "provide format checking for wide string functions");
<commit_msg>Make methods const where possible.<commit_after>// Use with:
// -Xclang -load -Xclang path/to/string-plugin.so -Xclang -add-plugin -Xclang format-plugin
// and zero or more of
// -Xclang -plugin-arg-format-plugin -Xclang -list=functions.txt
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>
#define __STDC_LIMIT_MACROS 1
#define __STDC_CONSTANT_MACROS 1
#include <clang/AST/AST.h>
#include <clang/AST/ASTConsumer.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/FrontendPluginRegistry.h>
#include <clang/Sema/Sema.h>
#include <llvm/ADT/SmallBitVector.h>
#include "split.h"
#include "utf8string.h"
namespace {
struct FunctionDesc {
std::string name;
clang::Sema::FormatStringType type;
unsigned format_arg;
unsigned var_arg;
};
FunctionDesc const default_function_list[] = {
// Wide string formatting
{ "wprintf", clang::Sema::FST_Printf, 1, 2 },
{ "fwprintf", clang::Sema::FST_Printf, 2, 3 },
{ "swprintf", clang::Sema::FST_Printf, 2, 3 },
{ "vwprintf", clang::Sema::FST_Printf, 1, 0 },
{ "vfwprintf", clang::Sema::FST_Printf, 2, 0 },
{ "vswprintf", clang::Sema::FST_Printf, 2, 0 },
{ "wscanf", clang::Sema::FST_Scanf, 1, 2 },
{ "fwscanf", clang::Sema::FST_Scanf, 2, 3 },
{ "swscanf", clang::Sema::FST_Scanf, 2, 3 },
{ "vwscanf", clang::Sema::FST_Scanf, 1, 0 },
{ "vfwscanf", clang::Sema::FST_Scanf, 2, 0 },
{ "vswscanf", clang::Sema::FST_Scanf, 2, 0 },
// Annex K
{ "wprintf_s", clang::Sema::FST_Printf, 1, 2 },
{ "fwprintf_s", clang::Sema::FST_Printf, 2, 3 },
{ "swprintf_s", clang::Sema::FST_Printf, 3, 4 },
{ "snwprintf_s", clang::Sema::FST_Printf, 3, 4 },
{ "vwprintf_s", clang::Sema::FST_Printf, 1, 0 },
{ "vfwprintf_s", clang::Sema::FST_Printf, 2, 0 },
{ "vswprintf_s", clang::Sema::FST_Printf, 3, 0 },
{ "vsnwprintf_s", clang::Sema::FST_Printf, 3, 0 },
{ "wscanf_s", clang::Sema::FST_Scanf, 1, 2 },
{ "fwscanf_s", clang::Sema::FST_Scanf, 2, 3 },
{ "swscanf_s", clang::Sema::FST_Scanf, 2, 3 },
{ "vwscanf_s", clang::Sema::FST_Scanf, 1, 0 },
{ "vfwscanf_s", clang::Sema::FST_Scanf, 2, 0 },
{ "vswscanf_s", clang::Sema::FST_Scanf, 2, 0 },
// Wide string time
{ "wcsftime", clang::Sema::FST_Strftime, 3, 0 },
};
struct GettextDesc {
std::string name;
unsigned format_arg;
};
struct FormatString
{
std::string string;
clang::StringLiteral const *expr;
};
class FormatVisitor : public clang::RecursiveASTVisitor<FormatVisitor> {
public:
explicit FormatVisitor(
clang::CompilerInstance& inst,
std::vector<FunctionDesc> const & functions,
std::vector<GettextDesc> const & gettexts) :
instance(inst),
diagnostics(inst.getDiagnostics())
{
not_literal = diagnostics.getCustomDiagID(clang::DiagnosticsEngine::Warning, "format is not a string literal");
for (auto fs = functions.begin(); fs != functions.end(); ++fs) {
function_list.push_back(*fs);
}
for (auto gs = gettexts.begin(); gs != gettexts.end(); ++gs) {
gettext_list.push_back(*gs);
}
}
bool VisitCallExpr(clang::CallExpr *exp)
{
clang::FunctionDecl *d = exp->getDirectCallee();
if (d == nullptr) { return true; }
// Assume that any function with a format attribute is checked in the
// core; don't duplicate the warning
if (!d->hasAttr<clang::FormatAttr>()) {
// Determine whether the function is one we're looking for
llvm::StringRef const name = d->getIdentifier()->getName();
for (auto fs = function_list.begin(); fs != function_list.end(); ++fs) {
if (name == fs->name) {
processFormat(exp, *fs);
break;
}
}
}
return true;
}
private:
void processFormat(clang::CallExpr *expr, FunctionDesc const & desc) const
{
std::vector<FormatString> formats;
getFormatStrings(formats, expr->getArg(desc.format_arg-1));
llvm::ArrayRef<const clang::Expr *> args(
expr->getArgs(),
expr->getNumArgs());
for (auto i = formats.begin(); i != formats.end(); ++i) {
clang::StringLiteral *fexpr = nullptr;
if (!i->expr->isAscii() && !i->expr->isUTF8()) {
clang::QualType type = instance.getASTContext().getConstantArrayType(
instance.getASTContext().CharTy.withConst(),
llvm::APInt(32, i->string.size()+1),
clang::ArrayType::Normal, 0);
clang::SourceLocation loc =
// Offset 1 for the L, u or U prefix
i->expr->getLocStart().getLocWithOffset(1);
fexpr = clang::StringLiteral::Create(
instance.getASTContext(),
clang::StringRef(i->string.c_str(), i->string.size()),
clang::StringLiteral::UTF8,
false,
type,
loc);
}
llvm::SmallBitVector checked_args;
instance.getSema().CheckFormatString(
fexpr ? fexpr : i->expr,
i->expr,
args,
desc.var_arg == 0,
desc.format_arg - 1,
desc.var_arg - 1,
desc.type,
true,
clang::Sema::VariadicFunction,
checked_args);
}
}
void getFormatStrings(
std::vector<FormatString>& formats,
clang::Expr const *arg) const
{
if (arg == nullptr) { return; }
// Pass any implicit type conversions
arg = arg->IgnoreImplicit();
// If function call, look for gettext-like functions
{
clang::CallExpr const *call = llvm::dyn_cast_or_null<clang::CallExpr>(arg);
if (call != nullptr) {
clang::FunctionDecl const *d = call->getDirectCallee();
if (d == nullptr) { goto warn; }
if (d->hasAttr<clang::FormatArgAttr>()) {
for (auto a = d->specific_attr_begin<clang::FormatArgAttr>();
a != d->specific_attr_end<clang::FormatArgAttr>(); ++a) {
// The function may have any number of format_arg attributes;
// this allows the function to accept multiple format strings
getFormatStrings(formats, call->getArg((*a)->getFormatIdx()-1));
}
} else {
llvm::StringRef const name = d->getIdentifier()->getName();
bool found = false;
for (auto a = gettext_list.begin();
a != gettext_list.end(); ++a) {
// The function appear any number of times in getext_list;
// this allows the function to accept multiple format strings
if (name == a->name) {
getFormatStrings(formats, call->getArg(a->format_arg-1));
found = true;
}
}
if (!found) { goto warn; }
}
return;
}
}
// If conditional operator, process the two possible format strings
{
clang::AbstractConditionalOperator const *cond = llvm::dyn_cast_or_null<clang::AbstractConditionalOperator>(arg);
if (cond != nullptr) {
getFormatStrings(formats, cond->getTrueExpr());
getFormatStrings(formats, cond->getFalseExpr());
return;
}
}
{
// If string literal, add it to the list
clang::StringLiteral const *str = llvm::dyn_cast_or_null<clang::StringLiteral>(arg);
if (str != nullptr) {
// Get the text of the string literal
FormatString fmt;
fmt.string = stringToUTF8(str);
fmt.expr = str;
formats.push_back(fmt);
return;
}
}
warn:
// Can't process this format; raise a warning
diagnostics.Report(arg->getLocStart(), not_literal);
}
clang::CompilerInstance& instance;
clang::DiagnosticsEngine& diagnostics;
unsigned not_literal;
std::vector<FunctionDesc> function_list;
std::vector<GettextDesc> gettext_list;
};
struct FormatASTConsumer : public clang::ASTConsumer {
public:
explicit FormatASTConsumer(
clang::CompilerInstance& inst,
std::vector<FunctionDesc> const & functions,
std::vector<GettextDesc> const & gettexts)
: Visitor(inst, functions, gettexts) {}
virtual void HandleTranslationUnit(clang::ASTContext &Context)
{
Visitor.TraverseDecl(Context.getTranslationUnitDecl());
}
private:
FormatVisitor Visitor;
};
class FormatAction : public clang::PluginASTAction {
public:
clang::ASTConsumer* CreateASTConsumer(clang::CompilerInstance& inst, llvm::StringRef str) override
{
if (function_list.empty()) {
for (std::size_t i = 0; i < sizeof(default_function_list)/sizeof(default_function_list[0]); ++i) {
function_list.push_back(default_function_list[i]);
}
}
return new FormatASTConsumer(inst, function_list, gettext_list);
}
bool ParseArgs(const clang::CompilerInstance& inst,
const std::vector<std::string>& args) override
{
bool ok = true;
clang::DiagnosticsEngine *diagnostics = &inst.getDiagnostics();
unsigned bad_file = diagnostics->getCustomDiagID(clang::DiagnosticsEngine::Error, "cannot open file %0: %1");
unsigned bad_option = diagnostics->getCustomDiagID(clang::DiagnosticsEngine::Error, "unknown option: %0");
for (auto i = args.begin(); i != args.end(); ++i) {
std::string arg = *i;
if (arg.substr(0, 6) == "-list=") {
std::string filename(arg.substr(6));
std::ifstream file(filename);
while (file.good()) {
std::string line;
std::getline(file, line);
std::vector<std::string> vec = Split(line);
if (vec.size() < 3) { continue; }
if (vec[1] == "gettext") {
GettextDesc desc;
desc.name = vec[0];
desc.format_arg = std::strtoull(vec[2].c_str(), nullptr, 10);
gettext_list.push_back(desc);
} else {
FunctionDesc desc;
desc.name = vec[0];
if (vec[1] == "printf") {
desc.type = clang::Sema::FST_Printf;
} else if (vec[1] == "scanf") {
desc.type = clang::Sema::FST_Scanf;
} else if (vec[1] == "NSString") {
desc.type = clang::Sema::FST_NSString;
} else if (vec[1] == "strftime") {
desc.type = clang::Sema::FST_Strftime;
} else if (vec[1] == "strfmon") {
desc.type = clang::Sema::FST_Strfmon;
} else if (vec[1] == "kprintf") {
desc.type = clang::Sema::FST_Kprintf;
} else {
continue;
}
desc.format_arg = std::strtoull(vec[2].c_str(), nullptr, 10);
desc.var_arg = vec.size() > 3 ? std::strtoull(vec[3].c_str(), nullptr, 10) : 0;
function_list.push_back(desc);
}
}
if (!file.eof()) {
// failed to open the file, or error while reading it
diagnostics->Report(bad_file) << filename << std::strerror(errno);
ok = false;
}
} else {
diagnostics->Report(bad_option) << arg;
ok = false;
}
}
return ok;
}
private:
std::vector<FunctionDesc> function_list;
std::vector<GettextDesc> gettext_list;
};
} // end anonymous namespace
static clang::FrontendPluginRegistry::Add<FormatAction>
X("format-plugin", "provide format checking for wide string functions");
<|endoftext|> |
<commit_before>#ifndef AL_FREENECT_HPP
#define AL_FREENECT_HPP
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2012. The Regents of the University of California.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
Neither the name of the University of California nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
File description:
Binding to freenect library.
File author(s):
Graham Wakefield, 2012, [email protected]
*/
#include "allocore/al_Allocore.hpp"
#include "alloutil/al_FPS.hpp"
#include "libfreenect/libfreenect.h"
#include <map>
namespace al {
// run libfreenect on a backtround thread to reduce CPU load:
class Freenect : public Thread, public ThreadFunction {
public:
static void depth_cb(freenect_device *dev, void *depth, uint32_t timestamp);
static void video_cb(freenect_device *dev, void *video, uint32_t timestamp);
static bool check(const char * what, int code);
class Callback {
public:
Callback(int idx=0);
virtual ~Callback();
// Warning: these will be called from a background thread:
virtual void onVideo(Texture& raw, uint32_t timestamp) {}
virtual void onDepth(Texture& raw, uint32_t timestamp) {}
static Vec3f depthToEye(int x, int y, uint16_t d);
static double rawDepthToMeters(uint16_t raw);
void reconfigure();
bool startVideo();
bool stopVideo();
bool startDepth();
bool stopDepth();
// returns tilt in radians
double tilt();
void tilt(double radians);
Texture depth, video;
protected:
freenect_device * dev;
};
// ThreadFunction:
virtual void operator()();
static Freenect& get();
static void stop();
virtual ~Freenect();
private:
Freenect();
Freenect * singleton;
freenect_context * ctx;
bool active;
};
inline bool Freenect::check(const char * what, int code) {
if (code < 0) {
AL_WARN("Error (%s): %d", what, code);
return false;
}
return true;
}
inline Freenect::Callback::Callback(int idx) {
dev = 0;
Freenect& self = get();
if (check("open", freenect_open_device(self.ctx, &dev, idx))) {
freenect_set_user(dev, this);
reconfigure();
}
}
inline Freenect::Callback::~Callback() {
if (dev) freenect_set_user(dev, 0);
}
inline double Freenect::Callback::rawDepthToMeters(uint16_t raw) {
static const double k1 = 1.1863;
static const double k2 = 1./2842.5;
static const double k3 = 0.1236;
return k3 * tan(raw*k2 + k1);
}
// @see http://nicolas.burrus.name/index.php/Research/KinectCalibration
inline Vec3f Freenect::Callback::depthToEye(int x, int y, uint16_t d) {
// size of a pixel in meters, at zero/near plane:
static const double metersPerPixelX = 1./594.21434211923247;
static const double metersPerPixelY = 1./591.04053696870778;
// location of X,Y corner at zero plane, in pixels:
static const double edgeX = 339.30780975300314; // x edge pixel
static const double edgeY = 242.73913761751615; // y edge pixel
const double meters = rawDepthToMeters(d);
const double disparityX = (x - edgeX); // in pixels
const double disparityY = (y - edgeY); // in pixels
return Vec3f(meters * disparityX * metersPerPixelX,
meters * disparityY * metersPerPixelY,
meters
);
}
inline void Freenect::Callback::reconfigure() {
AlloArrayHeader header;
const freenect_frame_mode dmode = freenect_get_current_depth_mode(dev);
header.type = AlloUInt16Ty;
header.components = 1;
header.dimcount = 2;
header.dim[0] = dmode.width;
header.dim[1] = dmode.height;
header.stride[0] = (dmode.data_bits_per_pixel+dmode.padding_bits_per_pixel)/8;
header.stride[1] = header.stride[0] * dmode.width;
depth.configure(header);
depth.array().dataCalloc();
const freenect_frame_mode vmode = freenect_get_current_video_mode(dev);
header.type = AlloUInt8Ty;
header.components = 3;
header.dimcount = 2;
header.dim[0] = vmode.width;
header.dim[1] = vmode.height;
header.stride[0] = (vmode.data_bits_per_pixel+vmode.padding_bits_per_pixel)/8;
header.stride[1] = header.stride[0] * vmode.width;
video.configure(header);
video.array().dataCalloc();
}
inline bool Freenect::Callback::startVideo() {
if (dev) {
freenect_set_video_callback(dev, video_cb);
return check("start_video", freenect_start_video(dev));
}
return false;
}
inline bool Freenect::Callback::stopVideo() {
if (dev) {
return check("stop_video", freenect_stop_video(dev));
}
return false;
}
inline bool Freenect::Callback::startDepth() {
if (dev) {
freenect_set_depth_callback(dev, depth_cb);
return check("start_depth", freenect_start_depth(dev));
}
return false;
}
inline bool Freenect::Callback::stopDepth() {
if (dev) {
return check("stop_depth", freenect_stop_depth(dev));
}
return false;
}
// returns tilt in radians
inline double Freenect::Callback::tilt() {
double t = 0;
if (dev) {
freenect_update_tilt_state(dev);
freenect_raw_tilt_state * state = freenect_get_tilt_state(dev);
if (state) {
t = freenect_get_tilt_degs(state);
} else {
AL_WARN("Error: no state");
}
}
return t * M_DEG2RAD;
}
inline void Freenect::Callback::tilt(double radians) {
freenect_set_tilt_degs(dev, radians * M_RAD2DEG);
}
// ThreadFunction:
inline void Freenect::operator()() {
// listen for messages on main thread:
while (active) {
//printf(".");
// blocking call:
freenect_process_events(ctx);
}
}
static Freenect& get();
inline void Freenect::stop() {
Freenect& self = get();
self.active = 0;
self.Thread::join();
}
inline Freenect::~Freenect() {
active = false;
Thread::join();
freenect_shutdown(ctx);
}
inline Freenect::Freenect() : Thread() {
// TODO: handle multiple contexts?
freenect_usb_context * usb_ctx = NULL;
int res = freenect_init(&ctx, usb_ctx);
if (res < 0) {
AL_WARN("Error: failed to initialize libfreenect");
exit(0);
}
int numdevs = freenect_num_devices(ctx);
printf("%d devices\n", numdevs);
active = true;
Thread::start(*this);
}
}
#endif
<commit_msg>Corrected libfreenect.h location.<commit_after>#ifndef AL_FREENECT_HPP
#define AL_FREENECT_HPP
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2012. The Regents of the University of California.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
Neither the name of the University of California nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
File description:
Binding to freenect library.
File author(s):
Graham Wakefield, 2012, [email protected]
*/
#include "allocore/al_Allocore.hpp"
#include "alloutil/al_FPS.hpp"
#include "libfreenect.h"
#include <map>
namespace al {
// run libfreenect on a backtround thread to reduce CPU load:
class Freenect : public Thread, public ThreadFunction {
public:
static void depth_cb(freenect_device *dev, void *depth, uint32_t timestamp);
static void video_cb(freenect_device *dev, void *video, uint32_t timestamp);
static bool check(const char * what, int code);
class Callback {
public:
Callback(int idx=0);
virtual ~Callback();
// Warning: these will be called from a background thread:
virtual void onVideo(Texture& raw, uint32_t timestamp) {}
virtual void onDepth(Texture& raw, uint32_t timestamp) {}
static Vec3f depthToEye(int x, int y, uint16_t d);
static double rawDepthToMeters(uint16_t raw);
void reconfigure();
bool startVideo();
bool stopVideo();
bool startDepth();
bool stopDepth();
// returns tilt in radians
double tilt();
void tilt(double radians);
Texture depth, video;
protected:
freenect_device * dev;
};
// ThreadFunction:
virtual void operator()();
static Freenect& get();
static void stop();
virtual ~Freenect();
private:
Freenect();
Freenect * singleton;
freenect_context * ctx;
bool active;
};
inline bool Freenect::check(const char * what, int code) {
if (code < 0) {
AL_WARN("Error (%s): %d", what, code);
return false;
}
return true;
}
inline Freenect::Callback::Callback(int idx) {
dev = 0;
Freenect& self = get();
if (check("open", freenect_open_device(self.ctx, &dev, idx))) {
freenect_set_user(dev, this);
reconfigure();
}
}
inline Freenect::Callback::~Callback() {
if (dev) freenect_set_user(dev, 0);
}
inline double Freenect::Callback::rawDepthToMeters(uint16_t raw) {
static const double k1 = 1.1863;
static const double k2 = 1./2842.5;
static const double k3 = 0.1236;
return k3 * tan(raw*k2 + k1);
}
// @see http://nicolas.burrus.name/index.php/Research/KinectCalibration
inline Vec3f Freenect::Callback::depthToEye(int x, int y, uint16_t d) {
// size of a pixel in meters, at zero/near plane:
static const double metersPerPixelX = 1./594.21434211923247;
static const double metersPerPixelY = 1./591.04053696870778;
// location of X,Y corner at zero plane, in pixels:
static const double edgeX = 339.30780975300314; // x edge pixel
static const double edgeY = 242.73913761751615; // y edge pixel
const double meters = rawDepthToMeters(d);
const double disparityX = (x - edgeX); // in pixels
const double disparityY = (y - edgeY); // in pixels
return Vec3f(meters * disparityX * metersPerPixelX,
meters * disparityY * metersPerPixelY,
meters
);
}
inline void Freenect::Callback::reconfigure() {
AlloArrayHeader header;
const freenect_frame_mode dmode = freenect_get_current_depth_mode(dev);
header.type = AlloUInt16Ty;
header.components = 1;
header.dimcount = 2;
header.dim[0] = dmode.width;
header.dim[1] = dmode.height;
header.stride[0] = (dmode.data_bits_per_pixel+dmode.padding_bits_per_pixel)/8;
header.stride[1] = header.stride[0] * dmode.width;
depth.configure(header);
depth.array().dataCalloc();
const freenect_frame_mode vmode = freenect_get_current_video_mode(dev);
header.type = AlloUInt8Ty;
header.components = 3;
header.dimcount = 2;
header.dim[0] = vmode.width;
header.dim[1] = vmode.height;
header.stride[0] = (vmode.data_bits_per_pixel+vmode.padding_bits_per_pixel)/8;
header.stride[1] = header.stride[0] * vmode.width;
video.configure(header);
video.array().dataCalloc();
}
inline bool Freenect::Callback::startVideo() {
if (dev) {
freenect_set_video_callback(dev, video_cb);
return check("start_video", freenect_start_video(dev));
}
return false;
}
inline bool Freenect::Callback::stopVideo() {
if (dev) {
return check("stop_video", freenect_stop_video(dev));
}
return false;
}
inline bool Freenect::Callback::startDepth() {
if (dev) {
freenect_set_depth_callback(dev, depth_cb);
return check("start_depth", freenect_start_depth(dev));
}
return false;
}
inline bool Freenect::Callback::stopDepth() {
if (dev) {
return check("stop_depth", freenect_stop_depth(dev));
}
return false;
}
// returns tilt in radians
inline double Freenect::Callback::tilt() {
double t = 0;
if (dev) {
freenect_update_tilt_state(dev);
freenect_raw_tilt_state * state = freenect_get_tilt_state(dev);
if (state) {
t = freenect_get_tilt_degs(state);
} else {
AL_WARN("Error: no state");
}
}
return t * M_DEG2RAD;
}
inline void Freenect::Callback::tilt(double radians) {
freenect_set_tilt_degs(dev, radians * M_RAD2DEG);
}
// ThreadFunction:
inline void Freenect::operator()() {
// listen for messages on main thread:
while (active) {
//printf(".");
// blocking call:
freenect_process_events(ctx);
}
}
static Freenect& get();
inline void Freenect::stop() {
Freenect& self = get();
self.active = 0;
self.Thread::join();
}
inline Freenect::~Freenect() {
active = false;
Thread::join();
freenect_shutdown(ctx);
}
inline Freenect::Freenect() : Thread() {
// TODO: handle multiple contexts?
freenect_usb_context * usb_ctx = NULL;
int res = freenect_init(&ctx, usb_ctx);
if (res < 0) {
AL_WARN("Error: failed to initialize libfreenect");
exit(0);
}
int numdevs = freenect_num_devices(ctx);
printf("%d devices\n", numdevs);
active = true;
Thread::start(*this);
}
}
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2017, Vlad Meșco
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "control.h"
#include "logger.h"
#include "string_utils.h"
#include <algorithm>
#include <cassert>
#include <cstdio>
#ifndef USE_REGEX_RENAME
# ifdef __GNUC__
# define USE_REGEX_RENAME
# endif
#endif
#ifdef USE_REGEX_RENAME
# include <regex>
#endif
#define FIND_WHAT(id, then) \
auto found = FindWhat(id); \
if(found == model_->whats.end()) then;
#define DIRTY() do{\
model_->dirty = true; \
}while(0)
auto Control::FindWhat(evData id) -> decltype(model_->whats)::iterator
{
LOGGER(l);
auto found = std::find_if(model_->whats.begin(), model_->whats.end(), [id](WhatEntry& e) -> bool {
return e.name == id;
});
if(found == model_->whats.end())
{
l(L"Failed to find %ls...", id.c_str());
}
return found;
}
void Control::SetWhosName(evData oldName, std::wstring name)
{
LOGGER(l);
auto found = std::find_if(model_->whos.begin(), model_->whos.end(), [oldName](WhoEntry& e) -> bool {
return e.name == oldName;
});
if(found == model_->whos.end())
{
l(L"Failed to find %ls...", oldName.c_str());
return;
}
found->name = name;
DIRTY();
Event e = {
Event::WHO,
Event::NAME_CHANGED,
oldName,
name.c_str(),
source_
};
Fire(&e);
}
void Control::SetWhosParam(Control::evData id, std::wstring key, std::wstring value)
{
LOGGER(l);
auto foundEntry = std::find_if(model_->whos.begin(), model_->whos.end(), [id](WhoEntry& e) -> bool {
return e.name == id;
});
if(foundEntry == model_->whos.end()) {
l(L"Failed to find %ls...", id.c_str());
return;
}
auto&& params = foundEntry->params;
auto found = std::find_if(params.begin(), params.end(), [key](WhoEntry::Params::reference p) -> bool {
return p.first == key;
});
if(found == params.end()) {
params.emplace_back(key, value);
} else {
found->second = value;
}
DIRTY();
Event e = {
Event::WHO,
Event::CHANGED,
id,
key,
source_
};
Fire(&e);
}
void Control::SetWhosSchema(Control::evData id, Schema const* schema)
{
LOGGER(l);
auto foundEntry = std::find_if(model_->whos.begin(), model_->whos.end(), [id](WhoEntry& e) -> bool {
return e.name == id;
});
if(foundEntry == model_->whos.end()) {
l(L"Failed to find %ls...", id.c_str());
return;
}
foundEntry->schema = schema;
DIRTY();
Event e = {
Event::WHO,
Event::CHANGED,
id,
L" schema",
source_
};
Fire(&e);
}
void Control::SetWhatsName(Control::evData id, std::wstring name)
{
LOGGER(l);
auto found = std::find_if(model_->whats.begin(), model_->whats.end(), [id](WhatEntry& e) -> bool {
return e.name == id;
});
if(found == model_->whats.end())
{
l(L"Failed to find %ls...", id.c_str());
return;
}
found->name = name;
DIRTY();
Event e = {
Event::WHAT,
Event::NAME_CHANGED,
id,
name.c_str(),
source_
};
Fire(&e);
#ifdef USE_REGEX_RENAME
std::wstringstream pattern;
pattern << L"\\b" << id << L"\\b";
std::wregex r(pattern.str(), std::wregex::ECMAScript);
std::wstringstream buf;
std::regex_replace(std::ostreambuf_iterator<wchar_t>(buf),
model_->output.begin(), model_->output.end(), r, name);
auto newOutput = buf.str();
if(newOutput != model_->output) {
model_->output = newOutput;
Event e = {
Event::OUTPUT,
Event::CHANGED,
L"OUTPUT",
L"",
source_
};
Fire(&e);
}
#endif
}
void Control::SetWhatsBpm(Control::evData id, std::wstring bpm)
{
LOGGER(l);
FIND_WHAT(id, return);
found->bpm = bpm;
DIRTY();
Event e = {
Event::WHAT,
Event::CHANGED,
id,
L"bpm",
source_
};
Fire(&e);
}
Event::Source Control::InsertColumnPrivate(evData id, column_p_t before, wchar_t c)
{
LOGGER(l);
if(id.empty()
|| id == L"OUTPUT")
{
#if 1
l(L"using text editor, should not be called\n");
#else
Column col;
auto size = model_->whats.size();
model_->output.insert(before, column_t(size, c));
DIRTY();
return Event::OUTPUT;
#endif
}
FIND_WHAT(id, return Event::WHAT);
auto size = model_->whos.size();
found->columns.insert(before, column_t(size, c));
DIRTY();
return Event::WHAT;
}
void Control::InsertColumn(evData id, column_p_t before, wchar_t c)
{
LOGGER(l);
auto source = InsertColumnPrivate(id, before, c);
if(source == Event::GLOBAL) return;
Event e = {
source,
Event::CHANGED,
id,
L"",
source_
};
Fire(&e);
}
void Control::Fire(Event* ev)
{
LOGGER(l);
std::for_each(model_->views.begin(), model_->views.end(), [&ev](View* v) {
v->OnEvent(ev);
});
}
void Control::SetCell(evData what, column_p_t before, int row, wchar_t c)
{
LOGGER(l);
if(what.empty()
|| what == L"OUTPUT")
{
#if 1
l(L"using text editor, should not be called\n");
#else
if(before == model_->output.end())
{
(void) InsertColumnPrivate(what, before, ' ');
auto pos = model_->output.end();
std::advance(pos, -1);
return SetCell(what, pos, row, c);
}
auto pos = before->begin();
std::advance(pos, row);
*pos = c;
DIRTY();
Event e = {
Event::OUTPUT,
Event::CHANGED,
what,
L"",
source_
};
Fire(&e);
#endif
return;
}
FIND_WHAT(what, return);
if(before == found->columns.end())
{
(void) InsertColumnPrivate(what, before, (c != ' ') ? '.' : ' ');
auto pos = found->columns.end();
std::advance(pos, -1);
return SetCell(what, pos, row, c);
}
auto pos = before->begin();
std::advance(pos, row);
*pos = c;
DIRTY();
Event e = {
Event::WHAT,
Event::CHANGED,
what,
L"",
source_
};
Fire(&e);
}
void Control::BlankCell(evData id, int col, int row)
{
LOGGER(l);
if(id.empty()
|| id == L"OUTPUT")
{
#if 1
l(L"using text editor, should not be called\n");
#else
auto it = model_->output.begin();
std::advance(it, col);
auto& col = *it;
if(row < 0 || row >= col.size())
{
l(L"my=%d is out of bounds\n", row);
return;
}
auto cit = col.begin();
std::advance(cit, row);
auto& cell = *cit;
cell = (cell == L' ')
? L' '
: L'.'
;
DIRTY();
Event e = {
Event::OUTPUT,
Event::CHANGED,
id,
L"",
source_
};
Fire(&e);
#endif
return;
} else {
FIND_WHAT(id, return);
WhatEntry& we = *found;
auto it = we.columns.begin();
std::advance(it, col);
auto& col = *it;
if(row < 0 || row >= col.size())
{
l(L"my=%d is out of bounds\n", row);
return;
}
auto cit = col.begin();
std::advance(cit, row);
auto& cell = *cit;
cell = (cell == L' ')
? L' '
: L'.'
;
DIRTY();
Event e = {
Event::WHAT,
Event::CHANGED,
id,
L"",
source_
};
Fire(&e);
return;
}
}
void Control::InsertText(int mpos, int pos, std::wstring const& text)
{
LOGGER(l);
l(L"model: %d view: %d %ls\n", mpos, pos, text.c_str());
model_->output.insert(mpos, text);
DIRTY();
Event e = {
Event::OUTPUT,
Event::TEXT_INSERTED,
std::to_wstring(pos),
text,
source_
};
Fire(&e);
}
void Control::DeleteText(int mpos, int mlength, int pos, int length)
{
LOGGER(l);
l(L"model: %d+%d view: %d+%d\n", mpos, mlength, pos, length);
model_->output.erase(mpos, mlength);
DIRTY();
Event e = {
Event::OUTPUT,
Event::TEXT_DELETED,
std::to_wstring(pos),
std::to_wstring(length),
source_
};
Fire(&e);
}
void Control::DeleteWhat(evData id)
{
LOGGER(l);
auto found = std::find_if(model_->whats.begin(), model_->whats.end(), [&id](WhatEntry& what) -> bool {
return what.name == id;
});
if(found == model_->whats.end()) {
l(L"%ls not found in model\n", id.c_str());
return;
}
model_->whats.erase(found);
Event e = {
Event::WHAT,
Event::DELETED,
id,
L"",
source_
};
Fire(&e);
}
void Control::DeleteWho(evData id)
{
LOGGER(l);
size_t nth = 0;
auto found = model_->whos.end();
for(auto it = model_->whos.begin(); it != model_->whos.end(); ++it, ++nth) {
if(it->name == id) {
found = it;
break;
}
}
if(found == model_->whos.end()) {
l(L"%ls not found in model\n", id.c_str());
return;
}
l(L"cleaning up row %ld\n", nth);
std::for_each(model_->whats.begin(), model_->whats.end(), [nth, &l](WhatEntry& e) {
l(L"cleaning up in %ls\n", e.name.c_str());
std::for_each(e.columns.begin(), e.columns.end(), [nth](column_t& col) {
auto pos = col.begin();
std::advance(pos, nth);
col.erase(pos);
});
});
l(L"erasing entry\n");
model_->whos.erase(found);
Event e = {
Event::WHO,
Event::DELETED,
id,
L"",
source_
};
Fire(&e);
}
<commit_msg>explicitly include sstream<commit_after>/*
Copyright (c) 2017, Vlad Meșco
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "control.h"
#include "logger.h"
#include "string_utils.h"
#include <algorithm>
#include <cassert>
#include <cstdio>
#ifndef USE_REGEX_RENAME
# ifdef __GNUC__
# define USE_REGEX_RENAME
# endif
#endif
#ifdef USE_REGEX_RENAME
# include <regex>
# include <sstream>
#endif
#define FIND_WHAT(id, then) \
auto found = FindWhat(id); \
if(found == model_->whats.end()) then;
#define DIRTY() do{\
model_->dirty = true; \
}while(0)
auto Control::FindWhat(evData id) -> decltype(model_->whats)::iterator
{
LOGGER(l);
auto found = std::find_if(model_->whats.begin(), model_->whats.end(), [id](WhatEntry& e) -> bool {
return e.name == id;
});
if(found == model_->whats.end())
{
l(L"Failed to find %ls...", id.c_str());
}
return found;
}
void Control::SetWhosName(evData oldName, std::wstring name)
{
LOGGER(l);
auto found = std::find_if(model_->whos.begin(), model_->whos.end(), [oldName](WhoEntry& e) -> bool {
return e.name == oldName;
});
if(found == model_->whos.end())
{
l(L"Failed to find %ls...", oldName.c_str());
return;
}
found->name = name;
DIRTY();
Event e = {
Event::WHO,
Event::NAME_CHANGED,
oldName,
name.c_str(),
source_
};
Fire(&e);
}
void Control::SetWhosParam(Control::evData id, std::wstring key, std::wstring value)
{
LOGGER(l);
auto foundEntry = std::find_if(model_->whos.begin(), model_->whos.end(), [id](WhoEntry& e) -> bool {
return e.name == id;
});
if(foundEntry == model_->whos.end()) {
l(L"Failed to find %ls...", id.c_str());
return;
}
auto&& params = foundEntry->params;
auto found = std::find_if(params.begin(), params.end(), [key](WhoEntry::Params::reference p) -> bool {
return p.first == key;
});
if(found == params.end()) {
params.emplace_back(key, value);
} else {
found->second = value;
}
DIRTY();
Event e = {
Event::WHO,
Event::CHANGED,
id,
key,
source_
};
Fire(&e);
}
void Control::SetWhosSchema(Control::evData id, Schema const* schema)
{
LOGGER(l);
auto foundEntry = std::find_if(model_->whos.begin(), model_->whos.end(), [id](WhoEntry& e) -> bool {
return e.name == id;
});
if(foundEntry == model_->whos.end()) {
l(L"Failed to find %ls...", id.c_str());
return;
}
foundEntry->schema = schema;
DIRTY();
Event e = {
Event::WHO,
Event::CHANGED,
id,
L" schema",
source_
};
Fire(&e);
}
void Control::SetWhatsName(Control::evData id, std::wstring name)
{
LOGGER(l);
auto found = std::find_if(model_->whats.begin(), model_->whats.end(), [id](WhatEntry& e) -> bool {
return e.name == id;
});
if(found == model_->whats.end())
{
l(L"Failed to find %ls...", id.c_str());
return;
}
found->name = name;
DIRTY();
Event e = {
Event::WHAT,
Event::NAME_CHANGED,
id,
name.c_str(),
source_
};
Fire(&e);
#ifdef USE_REGEX_RENAME
std::wstringstream pattern;
pattern << L"\\b" << id << L"\\b";
std::wregex r(pattern.str(), std::wregex::ECMAScript);
std::wstringstream buf;
std::regex_replace(std::ostreambuf_iterator<wchar_t>(buf),
model_->output.begin(), model_->output.end(), r, name);
auto newOutput = buf.str();
if(newOutput != model_->output) {
model_->output = newOutput;
Event e = {
Event::OUTPUT,
Event::CHANGED,
L"OUTPUT",
L"",
source_
};
Fire(&e);
}
#endif
}
void Control::SetWhatsBpm(Control::evData id, std::wstring bpm)
{
LOGGER(l);
FIND_WHAT(id, return);
found->bpm = bpm;
DIRTY();
Event e = {
Event::WHAT,
Event::CHANGED,
id,
L"bpm",
source_
};
Fire(&e);
}
Event::Source Control::InsertColumnPrivate(evData id, column_p_t before, wchar_t c)
{
LOGGER(l);
if(id.empty()
|| id == L"OUTPUT")
{
#if 1
l(L"using text editor, should not be called\n");
#else
Column col;
auto size = model_->whats.size();
model_->output.insert(before, column_t(size, c));
DIRTY();
return Event::OUTPUT;
#endif
}
FIND_WHAT(id, return Event::WHAT);
auto size = model_->whos.size();
found->columns.insert(before, column_t(size, c));
DIRTY();
return Event::WHAT;
}
void Control::InsertColumn(evData id, column_p_t before, wchar_t c)
{
LOGGER(l);
auto source = InsertColumnPrivate(id, before, c);
if(source == Event::GLOBAL) return;
Event e = {
source,
Event::CHANGED,
id,
L"",
source_
};
Fire(&e);
}
void Control::Fire(Event* ev)
{
LOGGER(l);
std::for_each(model_->views.begin(), model_->views.end(), [&ev](View* v) {
v->OnEvent(ev);
});
}
void Control::SetCell(evData what, column_p_t before, int row, wchar_t c)
{
LOGGER(l);
if(what.empty()
|| what == L"OUTPUT")
{
#if 1
l(L"using text editor, should not be called\n");
#else
if(before == model_->output.end())
{
(void) InsertColumnPrivate(what, before, ' ');
auto pos = model_->output.end();
std::advance(pos, -1);
return SetCell(what, pos, row, c);
}
auto pos = before->begin();
std::advance(pos, row);
*pos = c;
DIRTY();
Event e = {
Event::OUTPUT,
Event::CHANGED,
what,
L"",
source_
};
Fire(&e);
#endif
return;
}
FIND_WHAT(what, return);
if(before == found->columns.end())
{
(void) InsertColumnPrivate(what, before, (c != ' ') ? '.' : ' ');
auto pos = found->columns.end();
std::advance(pos, -1);
return SetCell(what, pos, row, c);
}
auto pos = before->begin();
std::advance(pos, row);
*pos = c;
DIRTY();
Event e = {
Event::WHAT,
Event::CHANGED,
what,
L"",
source_
};
Fire(&e);
}
void Control::BlankCell(evData id, int col, int row)
{
LOGGER(l);
if(id.empty()
|| id == L"OUTPUT")
{
#if 1
l(L"using text editor, should not be called\n");
#else
auto it = model_->output.begin();
std::advance(it, col);
auto& col = *it;
if(row < 0 || row >= col.size())
{
l(L"my=%d is out of bounds\n", row);
return;
}
auto cit = col.begin();
std::advance(cit, row);
auto& cell = *cit;
cell = (cell == L' ')
? L' '
: L'.'
;
DIRTY();
Event e = {
Event::OUTPUT,
Event::CHANGED,
id,
L"",
source_
};
Fire(&e);
#endif
return;
} else {
FIND_WHAT(id, return);
WhatEntry& we = *found;
auto it = we.columns.begin();
std::advance(it, col);
auto& col = *it;
if(row < 0 || row >= col.size())
{
l(L"my=%d is out of bounds\n", row);
return;
}
auto cit = col.begin();
std::advance(cit, row);
auto& cell = *cit;
cell = (cell == L' ')
? L' '
: L'.'
;
DIRTY();
Event e = {
Event::WHAT,
Event::CHANGED,
id,
L"",
source_
};
Fire(&e);
return;
}
}
void Control::InsertText(int mpos, int pos, std::wstring const& text)
{
LOGGER(l);
l(L"model: %d view: %d %ls\n", mpos, pos, text.c_str());
model_->output.insert(mpos, text);
DIRTY();
Event e = {
Event::OUTPUT,
Event::TEXT_INSERTED,
std::to_wstring(pos),
text,
source_
};
Fire(&e);
}
void Control::DeleteText(int mpos, int mlength, int pos, int length)
{
LOGGER(l);
l(L"model: %d+%d view: %d+%d\n", mpos, mlength, pos, length);
model_->output.erase(mpos, mlength);
DIRTY();
Event e = {
Event::OUTPUT,
Event::TEXT_DELETED,
std::to_wstring(pos),
std::to_wstring(length),
source_
};
Fire(&e);
}
void Control::DeleteWhat(evData id)
{
LOGGER(l);
auto found = std::find_if(model_->whats.begin(), model_->whats.end(), [&id](WhatEntry& what) -> bool {
return what.name == id;
});
if(found == model_->whats.end()) {
l(L"%ls not found in model\n", id.c_str());
return;
}
model_->whats.erase(found);
Event e = {
Event::WHAT,
Event::DELETED,
id,
L"",
source_
};
Fire(&e);
}
void Control::DeleteWho(evData id)
{
LOGGER(l);
size_t nth = 0;
auto found = model_->whos.end();
for(auto it = model_->whos.begin(); it != model_->whos.end(); ++it, ++nth) {
if(it->name == id) {
found = it;
break;
}
}
if(found == model_->whos.end()) {
l(L"%ls not found in model\n", id.c_str());
return;
}
l(L"cleaning up row %ld\n", nth);
std::for_each(model_->whats.begin(), model_->whats.end(), [nth, &l](WhatEntry& e) {
l(L"cleaning up in %ls\n", e.name.c_str());
std::for_each(e.columns.begin(), e.columns.end(), [nth](column_t& col) {
auto pos = col.begin();
std::advance(pos, nth);
col.erase(pos);
});
});
l(L"erasing entry\n");
model_->whos.erase(found);
Event e = {
Event::WHO,
Event::DELETED,
id,
L"",
source_
};
Fire(&e);
}
<|endoftext|> |
<commit_before>#include "box.hpp"
Box::Box() :
Shape{},
min_{glm::vec3{0.0, 0.0, 0.0}},
max_{glm::vec3{0.0, 0.0, 0.0}} { std::cout << "ctor box ()" << "\n"; }
Box::Box(glm::vec3 const& min, glm::vec3 const& max) :
Shape{}, min_{min}, max_{max} { std::cout << "ctor box (min, max)" << "\n"; }
Box::Box(Material const& material, std::string const& n,
glm::vec3 const& min, glm::vec3 const& max) :
Shape{material, n}, min_{min}, max_{max} {
std::cout << "ctor box (material, name, min, max)" << "\n";
}
Box::~Box() { std::cout << "Box::~Box" << "\n"; }
/* virtual */ double Box::area() const {
// 6*(area of one side)
return 6.0 * (std::abs(max_.x - min_.x) * std::abs(max_.x - min_.x));
}
/* virtual */ double Box::volume() const {
//length * width * height
return std::abs(max_.x - min_.x)
* std::abs(max_.y - min_.y)
* std::abs(max_.z - min_.z);
}
/* virtual */ std::ostream& Box::print(std::ostream& os) const {
/* os << "\n";
os << "Box \"" << name() << "\" : \n";
os << " name : " << name() << "\n";
os << " material : " << material();
os << " minimum : "
<< "(" << min().x << "," << min().y << "," << min().z << ")" << "\n";
os << " maximum : "
<< "(" << max().x << "," << max().y << "," << max().z << ")" << "\n";
os << " area : " << area() << "\n";
os << " volume : " << volume() << "\n";
*/
return os;
}
bool Box::intersect(Ray const& r) const {
float foo{0.0};
return Box::intersect(r, foo);
}
bool Box::intersect(
Ray const& ray,
float& dist,
std::shared_ptr<Shape> & ptr) const{
return Box::intersect(ray, dist);
}
bool Box::intersect(Ray const& r, float& dist) const {
glm::vec3 dir = glm::normalize(r.direction);
/*
t-values: scalar of ray vector,
calculated by solving ray = min(min_.x, max_x) or ray = max(min_.x, max_.x)
respectively.
*/
/*
mini: possible t-values of intersect point on the box side nearer to
ray.origin.
maxi: possible t-values of intersect point on the far side of the box.
tmin: t-value of intersection point on near box side
tmax: t-value of intersection point on far box side
*/
float mini, maxi;
float tmin, tmax;
tmin = std::min((min_.x - r.origin.x) * (1/dir.x), //multiply with inverted vector
(max_.x - r.origin.x) * (1/dir.x));
tmax = std::max((min_.x - r.origin.x) * (1/dir.x),
(max_.x - r.origin.x) * (1/dir.x));
mini = (min_.y - r.origin.y) * (1/dir.y);
maxi = (max_.y - r.origin.y) * (1/dir.y);
tmin = std::max(tmin, std::min(mini, maxi));
tmax = std::min(tmax, std::max(mini, maxi));
mini = (min_.z - r.origin.z) * (1/dir.z);
maxi = (max_.z - r.origin.z) * (1/dir.z);
tmin = std::max(tmin, std::min(mini, maxi));
tmax = std::min(tmax, std::max(mini, maxi));
//is there a distance between the two intersection points?
if (tmax < std::max<float>(0.0, tmin)) return false;
//calculate distance between origin and intersection point (pythagoras):
dist = std::sqrt( (dir.x*tmin * dir.x*tmin)
+ (dir.y*tmin * dir.y*tmin)
+ (dir.z*tmin * dir.z*tmin) );
//std::cout<<"Do you even intersect? BOX"<< std::endl;
return true;
}
glm::vec3 Box::intersect_normal(Ray const& ray) const{
// std::cout << " Origin (" << raystructure.origin_.x << raystructure.origin_.y <<
// raystructure.origin_.z<< ") Direction (" << raystructure.direction_.x <<
// raystructure.direction_.y<< raystructure.direction_.z << " "<< std::endl;
float distance_inters = 0;
bool intersect_test = intersect(ray, distance_inters);
glm::vec3 intersection = {(distance_inters * ray.direction.x),(distance_inters * ray.direction.y),(distance_inters * ray.direction.z)};
glm::vec3 center = {((min_.x + max_.x)/2),((min_.y + max_.y)/2),((min_.z + max_.z)/2)};
glm::vec3 normal = {0.0, 0.0, 0.0};
float min_distance = std::numeric_limits<float>::max();
float epsilon = 400*min_distance;
//DONT DO DRUGS AND GIT
glm::vec3 hit = intersection;
float diff = 0.0;
diff = hit.x - min_.x;
if (diff < epsilon) normal = {-1.0, 0.0, 0.0};
diff = hit.x - max_.x;
if (diff < epsilon) normal = {1.0, 0.0, 0.0};
diff = hit.x - max_.x;
if (diff < epsilon) normal = {0.0, -1.0, 0.0};
diff = hit.x - max_.x;
if (diff < epsilon) normal = {0.0, 1.0, 0.0};
diff = hit.x - max_.x;
if (diff < epsilon) normal = {0.0, 0.0, 1.0};
diff = hit.x - max_.x;
if (diff < epsilon) normal = {0.0, 0.0, -1.0};
normal = glm::normalize(normal);
return normal;
}
Raystructure Box::raystruct_intersect(Ray const& r) const {
bool intersect_test =false;
float distance = 0;
intersect_test = intersect(r, distance);
if (true == intersect_test){
return Raystructure{r.origin, r.direction, Color{0,0,0},
material(), distance, intersect_normal(r),intersect_test};
}
return Raystructure{r.origin, r.direction, Color{0,0,0},
material(), std::numeric_limits<float>::max(),
glm::vec3{0, 0, 0},intersect_test};
}
<commit_msg>fix stupid bug in box.cpp<commit_after>#include "box.hpp"
Box::Box() :
Shape{},
min_{glm::vec3{0.0, 0.0, 0.0}},
max_{glm::vec3{0.0, 0.0, 0.0}} { std::cout << "ctor box ()" << "\n"; }
Box::Box(glm::vec3 const& min, glm::vec3 const& max) :
Shape{}, min_{min}, max_{max} { std::cout << "ctor box (min, max)" << "\n"; }
Box::Box(Material const& material, std::string const& n,
glm::vec3 const& min, glm::vec3 const& max) :
Shape{material, n}, min_{min}, max_{max} {
std::cout << "ctor box (material, name, min, max)" << "\n";
}
Box::~Box() { std::cout << "Box::~Box" << "\n"; }
/* virtual */ double Box::area() const {
// 6*(area of one side)
return 6.0 * (std::abs(max_.x - min_.x) * std::abs(max_.x - min_.x));
}
/* virtual */ double Box::volume() const {
//length * width * height
return std::abs(max_.x - min_.x)
* std::abs(max_.y - min_.y)
* std::abs(max_.z - min_.z);
}
/* virtual */ std::ostream& Box::print(std::ostream& os) const {
/* os << "\n";
os << "Box \"" << name() << "\" : \n";
os << " name : " << name() << "\n";
os << " material : " << material();
os << " minimum : "
<< "(" << min().x << "," << min().y << "," << min().z << ")" << "\n";
os << " maximum : "
<< "(" << max().x << "," << max().y << "," << max().z << ")" << "\n";
os << " area : " << area() << "\n";
os << " volume : " << volume() << "\n";
*/
return os;
}
bool Box::intersect(Ray const& r) const {
float foo{0.0};
return Box::intersect(r, foo);
}
bool Box::intersect(
Ray const& ray,
float& dist,
std::shared_ptr<Shape> & ptr) const{
return Box::intersect(ray, dist);
}
bool Box::intersect(Ray const& r, float& dist) const {
glm::vec3 dir = glm::normalize(r.direction);
/*
t-values: scalar of ray vector,
calculated by solving ray = min(min_.x, max_x) or ray = max(min_.x, max_.x)
respectively.
*/
/*
mini: possible t-values of intersect point on the box side nearer to
ray.origin.
maxi: possible t-values of intersect point on the far side of the box.
tmin: t-value of intersection point on near box side
tmax: t-value of intersection point on far box side
*/
float mini, maxi;
float tmin, tmax;
tmin = std::min((min_.x - r.origin.x) * (1/dir.x), //multiply with inverted vector
(max_.x - r.origin.x) * (1/dir.x));
tmax = std::max((min_.x - r.origin.x) * (1/dir.x),
(max_.x - r.origin.x) * (1/dir.x));
mini = (min_.y - r.origin.y) * (1/dir.y);
maxi = (max_.y - r.origin.y) * (1/dir.y);
tmin = std::max(tmin, std::min(mini, maxi));
tmax = std::min(tmax, std::max(mini, maxi));
mini = (min_.z - r.origin.z) * (1/dir.z);
maxi = (max_.z - r.origin.z) * (1/dir.z);
tmin = std::max(tmin, std::min(mini, maxi));
tmax = std::min(tmax, std::max(mini, maxi));
//is there a distance between the two intersection points?
if (tmax < std::max<float>(0.0, tmin)) return false;
//calculate distance between origin and intersection point (pythagoras):
dist = std::sqrt( (dir.x*tmin * dir.x*tmin)
+ (dir.y*tmin * dir.y*tmin)
+ (dir.z*tmin * dir.z*tmin) );
//std::cout<<"Do you even intersect? BOX"<< std::endl;
return true;
}
glm::vec3 Box::intersect_normal(Ray const& ray) const{
// std::cout << " Origin (" << raystructure.origin_.x << raystructure.origin_.y <<
// raystructure.origin_.z<< ") Direction (" << raystructure.direction_.x <<
// raystructure.direction_.y<< raystructure.direction_.z << " "<< std::endl;
float distance_inters = 0;
bool intersect_test = intersect(ray, distance_inters);
glm::vec3 intersection = {(distance_inters * ray.direction.x),(distance_inters * ray.direction.y),(distance_inters * ray.direction.z)};
glm::vec3 center = {((min_.x + max_.x)/2),((min_.y + max_.y)/2),((min_.z + max_.z)/2)};
glm::vec3 normal = {0.0, 0.0, 0.0};
float min_distance = std::numeric_limits<float>::max();
float epsilon = 400*min_distance; //arbitrary small number
glm::vec3 hit = intersection;
float diff = 0.0;
diff = hit.x - min_.x;
if (diff < epsilon) normal = {-1.0, 0.0, 0.0};
diff = hit.x - max_.x;
if (diff < epsilon) normal = {1.0, 0.0, 0.0};
diff = hit.x - min_.y;
if (diff < epsilon) normal = {0.0, -1.0, 0.0};
diff = hit.x - max_.y;
if (diff < epsilon) normal = {0.0, 1.0, 0.0};
diff = hit.x - min_.z;
if (diff < epsilon) normal = {0.0, 0.0, 1.0};
diff = hit.x - max_.z;
if (diff < epsilon) normal = {0.0, 0.0, -1.0};
normal = glm::normalize(normal);
return normal;
}
Raystructure Box::raystruct_intersect(Ray const& r) const {
bool intersect_test =false;
float distance = 0;
intersect_test = intersect(r, distance);
if (true == intersect_test){
return Raystructure{r.origin, r.direction, Color{0,0,0},
material(), distance, intersect_normal(r),intersect_test};
}
return Raystructure{r.origin, r.direction, Color{0,0,0},
material(), std::numeric_limits<float>::max(),
glm::vec3{0, 0, 0},intersect_test};
}
<|endoftext|> |
<commit_before>//This is a dual-purpose class for gene pools - it serves as a "base"
//GA, and also as a gene pool for individuals in hierarchical GAs
//Since these functions are, by and large, very similar, they can be
//combined together into one class
#include "HierarchicalGenePool.h"
#include <sstream>
#include <iostream>
using namespace std;
//If we don't know the optimum
HierarchicalGenePool::HierarchicalGenePool(int newPopulationSize, Individual * templateIndividual, int myMaxGenerations, int numIterations, GenerationModel * newModel) : GenePool() {
init(newPopulationSize, templateIndividual, myMaxGenerations, numIterations, newModel);
}
//Unknown optimum, overridden seed
HierarchicalGenePool::HierarchicalGenePool(int newPopulationSize, Individual * templateIndividual, int myMaxGenerations, int numIterations, int newSeed, GenerationModel * newModel) : GenePool(newSeed) {
init(newPopulationSize, templateIndividual, myMaxGenerations, numIterations, newModel);
}
//If we do know the optimum
HierarchicalGenePool::HierarchicalGenePool(int newPopulationSize, Individual * templateIndividual, int myMaxGenerations, int numIterations, GenerationModel * newModel, int optimalGenome[]) : GenePool() {
init(newPopulationSize, templateIndividual, myMaxGenerations, numIterations, newModel);
knownOptimum = true;
optimumGenome = optimalGenome;
Individual * optimumIndividual = templateIndividual->makeSpecifiedCopy(optimalGenome);
optimumFitness = optimumIndividual->checkFitness();
delete(optimumIndividual);
}
//Known optimum, known seed
HierarchicalGenePool::HierarchicalGenePool(int newPopulationSize, Individual * templateIndividual, int myMaxGenerations, int numIterations, int newSeed, GenerationModel * newModel, int optimalGenome[]) : GenePool(newSeed) {
init(newPopulationSize, templateIndividual, myMaxGenerations, numIterations, newModel);
knownOptimum = true;
optimumGenome = optimalGenome;
Individual * optimumIndividual = templateIndividual->makeSpecifiedCopy(optimalGenome);
optimumFitness = optimumIndividual->checkFitness();
delete(optimumIndividual);
}
HierarchicalGenePool::~HierarchicalGenePool() {
for (int i = 0; i < populationSize; i++) {
delete(myPopulation[i]);
}
free(myPopulation);
free(populationFitnesses);
if (optimumGenome != NULL) {
free(optimumGenome);
}
}
void HierarchicalGenePool::init(int newPopulationSize, Individual * templateIndividual, int myMaxGenerations, int numIterations, GenerationModel * newModel) {
myPopulation = (Individual**)malloc(sizeof(Individual*)*newPopulationSize);
populationFitnesses = (int*)malloc(sizeof(int)*newPopulationSize);
populationSize = newPopulationSize;
currentGeneration = 0;
readOnce = false;
optimumGenome = NULL;
maxGenerations = myMaxGenerations;
numIterationsPerGeneration = numIterations;
myModel = newModel;
for (int i = 0; i < populationSize; i++) {
myPopulation[i] = templateIndividual->makeRandomCopy();
}
optimumFound = false;
knownOptimum = false;
evaluateFitnesses();
}
//Evaluates the fitnesses of the population of this particular GenePool
//Basically a convenience thing
void HierarchicalGenePool::evaluateFitnesses() {
for (int i = 0; i < populationSize; i++) {
populationFitnesses[i] = myPopulation[i]->checkFitness();
}
}
//Evaluates the fitnesses of a given population of individuals
//Doesn't care what their genetic makeup is - uses their fitness functions
int * HierarchicalGenePool::evaluateFitnesses(Individual ** populationToEval, int populationToEvalSize) {
int * populationToEvalFitnesses = (int*)malloc(sizeof(int)*populationToEvalSize);
for (int i = 0; i < populationToEvalSize; i++) {
populationToEvalFitnesses[i] = populationToEval[i]->checkFitness();
}
return populationToEvalFitnesses;
}
//When we need a specific individual
void * HierarchicalGenePool::getIndex(int index) {
void * returnValue;
returnValue = (void*)myPopulation[index];
return returnValue;
}
void * HierarchicalGenePool::getFittest() {
return getIndex(0);
}
//Run one generation
void HierarchicalGenePool::nextGeneration() {
Individual ** newPopulation;
if (currentGeneration < maxGenerations && optimumFound == false) {
//Run the hierarchical component first - we're evolving
//from the bottom up
myPopulation[0]->runHierarchicalGenerations();
//Re-evaluate the fitnesses to take the lower GenePools
//running their generations into account
evaluateFitnesses();
newPopulation = myModel->breedMutateSelect(myPopulation, populationFitnesses, populationSize);
currentGeneration += 1;
if (knownOptimum == true) {
for (int i = 0; i < populationSize && optimumFound == false; i++) {
//TODO: make this more approximate
if (populationFitnesses[i] == optimumFitness) {
optimumFound = true;
}
}
}
//The new generation replaces the old
for (int i = 0; i < populationSize; i++) {
myPopulation[i] = newPopulation[i]->deepCopy();
delete(newPopulation[i]);
}
free(newPopulation);
}
}
//For HGAs - if we want to run multiple generations of a lower-level gene pool
//for every one of a higher-level one, this is how
//Basically a loop wrapped around nextGeneration()
void HierarchicalGenePool::runGenerations() {
int target = currentGeneration + numIterationsPerGeneration;
for (int i = currentGeneration; i < target && i < maxGenerations && optimumFound == false; i++) {
nextGeneration();
}
}
void HierarchicalGenePool::sortPopulation() {
//TODO: Make more efficient
Individual * tempIndividual;
int temp;
for (int i = 0; i < populationSize; i++) {
for (int k = 0; k < populationSize; k++) {
if (populationFitnesses[i] > populationFitnesses[k]) {
tempIndividual = myPopulation[i];
temp = populationFitnesses[i];
myPopulation[i] = myPopulation[k];
populationFitnesses[i] = populationFitnesses[k];
myPopulation[k] = tempIndividual;
populationFitnesses[k] = temp;
}
}
}
}
int HierarchicalGenePool::getHighestFitness() {
return populationFitnesses[0];
}
string HierarchicalGenePool::toString() {
string returnString = "";
stringstream ss;
string populationString;
ss << "Population size: " << populationSize << "\n";
for (int i = 0; i < populationSize; i++) {
if (readOnce == false) {
populationString = myPopulation[i]->toString();
} else {
populationString = myPopulation[i]->toGenomeString();
}
ss << "Member " << i << ": " << populationString << " Fitness: " << populationFitnesses[i] << "\n";
}
if (readOnce == false) {
ss << "Seed: " << seed << "\n";
ss << "Selection Info:\n" << myModel->toString();
}
readOnce = true;
returnString = ss.str();
return returnString;
}
<commit_msg>[HierarchicalGenePool]: Fixed getFittest() method<commit_after>//This is a dual-purpose class for gene pools - it serves as a "base"
//GA, and also as a gene pool for individuals in hierarchical GAs
//Since these functions are, by and large, very similar, they can be
//combined together into one class
#include "HierarchicalGenePool.h"
#include <sstream>
#include <iostream>
using namespace std;
//If we don't know the optimum
HierarchicalGenePool::HierarchicalGenePool(int newPopulationSize, Individual * templateIndividual, int myMaxGenerations, int numIterations, GenerationModel * newModel) : GenePool() {
init(newPopulationSize, templateIndividual, myMaxGenerations, numIterations, newModel);
}
//Unknown optimum, overridden seed
HierarchicalGenePool::HierarchicalGenePool(int newPopulationSize, Individual * templateIndividual, int myMaxGenerations, int numIterations, int newSeed, GenerationModel * newModel) : GenePool(newSeed) {
init(newPopulationSize, templateIndividual, myMaxGenerations, numIterations, newModel);
}
//If we do know the optimum
HierarchicalGenePool::HierarchicalGenePool(int newPopulationSize, Individual * templateIndividual, int myMaxGenerations, int numIterations, GenerationModel * newModel, int optimalGenome[]) : GenePool() {
init(newPopulationSize, templateIndividual, myMaxGenerations, numIterations, newModel);
knownOptimum = true;
optimumGenome = optimalGenome;
Individual * optimumIndividual = templateIndividual->makeSpecifiedCopy(optimalGenome);
optimumFitness = optimumIndividual->checkFitness();
delete(optimumIndividual);
}
//Known optimum, known seed
HierarchicalGenePool::HierarchicalGenePool(int newPopulationSize, Individual * templateIndividual, int myMaxGenerations, int numIterations, int newSeed, GenerationModel * newModel, int optimalGenome[]) : GenePool(newSeed) {
init(newPopulationSize, templateIndividual, myMaxGenerations, numIterations, newModel);
knownOptimum = true;
optimumGenome = optimalGenome;
Individual * optimumIndividual = templateIndividual->makeSpecifiedCopy(optimalGenome);
optimumFitness = optimumIndividual->checkFitness();
delete(optimumIndividual);
}
HierarchicalGenePool::~HierarchicalGenePool() {
for (int i = 0; i < populationSize; i++) {
delete(myPopulation[i]);
}
free(myPopulation);
free(populationFitnesses);
if (optimumGenome != NULL) {
free(optimumGenome);
}
}
void HierarchicalGenePool::init(int newPopulationSize, Individual * templateIndividual, int myMaxGenerations, int numIterations, GenerationModel * newModel) {
myPopulation = (Individual**)malloc(sizeof(Individual*)*newPopulationSize);
populationFitnesses = (int*)malloc(sizeof(int)*newPopulationSize);
populationSize = newPopulationSize;
currentGeneration = 0;
readOnce = false;
optimumGenome = NULL;
maxGenerations = myMaxGenerations;
numIterationsPerGeneration = numIterations;
myModel = newModel;
for (int i = 0; i < populationSize; i++) {
myPopulation[i] = templateIndividual->makeRandomCopy();
}
optimumFound = false;
knownOptimum = false;
evaluateFitnesses();
}
//Evaluates the fitnesses of the population of this particular GenePool
//Basically a convenience thing
void HierarchicalGenePool::evaluateFitnesses() {
for (int i = 0; i < populationSize; i++) {
populationFitnesses[i] = myPopulation[i]->checkFitness();
}
}
//Evaluates the fitnesses of a given population of individuals
//Doesn't care what their genetic makeup is - uses their fitness functions
int * HierarchicalGenePool::evaluateFitnesses(Individual ** populationToEval, int populationToEvalSize) {
int * populationToEvalFitnesses = (int*)malloc(sizeof(int)*populationToEvalSize);
for (int i = 0; i < populationToEvalSize; i++) {
populationToEvalFitnesses[i] = populationToEval[i]->checkFitness();
}
return populationToEvalFitnesses;
}
//When we need a specific individual
void * HierarchicalGenePool::getIndex(int index) {
void * returnValue;
returnValue = (void*)myPopulation[index];
return returnValue;
}
void * HierarchicalGenePool::getFittest() {
int fittestIndex;
int fittestIndexFitness = 0;
for (int i = 0; i < populationSize; i++) {
if (populationFitnesses[i] > fittestIndexFitness) {
fittestIndex = i;
fittestIndexFitness = populationFitnesses[i];
}
}
return (void*)myPopulation[fittestIndex];
}
//Run one generation
void HierarchicalGenePool::nextGeneration() {
Individual ** newPopulation;
if (currentGeneration < maxGenerations && optimumFound == false) {
//Run the hierarchical component first - we're evolving
//from the bottom up
myPopulation[0]->runHierarchicalGenerations();
//Re-evaluate the fitnesses to take the lower GenePools
//running their generations into account
evaluateFitnesses();
newPopulation = myModel->breedMutateSelect(myPopulation, populationFitnesses, populationSize);
currentGeneration += 1;
if (knownOptimum == true) {
for (int i = 0; i < populationSize && optimumFound == false; i++) {
//TODO: make this more approximate
if (populationFitnesses[i] == optimumFitness) {
optimumFound = true;
}
}
}
//The new generation replaces the old
for (int i = 0; i < populationSize; i++) {
myPopulation[i] = newPopulation[i]->deepCopy();
delete(newPopulation[i]);
}
free(newPopulation);
}
}
//For HGAs - if we want to run multiple generations of a lower-level gene pool
//for every one of a higher-level one, this is how
//Basically a loop wrapped around nextGeneration()
void HierarchicalGenePool::runGenerations() {
int target = currentGeneration + numIterationsPerGeneration;
for (int i = currentGeneration; i < target && i < maxGenerations && optimumFound == false; i++) {
nextGeneration();
}
}
void HierarchicalGenePool::sortPopulation() {
//TODO: Make more efficient
Individual * tempIndividual;
int temp;
for (int i = 0; i < populationSize; i++) {
for (int k = 0; k < populationSize; k++) {
if (populationFitnesses[i] > populationFitnesses[k]) {
tempIndividual = myPopulation[i];
temp = populationFitnesses[i];
myPopulation[i] = myPopulation[k];
populationFitnesses[i] = populationFitnesses[k];
myPopulation[k] = tempIndividual;
populationFitnesses[k] = temp;
}
}
}
}
int HierarchicalGenePool::getHighestFitness() {
return populationFitnesses[0];
}
string HierarchicalGenePool::toString() {
string returnString = "";
stringstream ss;
string populationString;
ss << "Population size: " << populationSize << "\n";
for (int i = 0; i < populationSize; i++) {
if (readOnce == false) {
populationString = myPopulation[i]->toString();
} else {
populationString = myPopulation[i]->toGenomeString();
}
ss << "Member " << i << ": " << populationString << " Fitness: " << populationFitnesses[i] << "\n";
}
if (readOnce == false) {
ss << "Seed: " << seed << "\n";
ss << "Selection Info:\n" << myModel->toString();
}
readOnce = true;
returnString = ss.str();
return returnString;
}
<|endoftext|> |
<commit_before>/*
* TexLogParser.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/tex/TexLogParser.hpp>
#include <boost/foreach.hpp>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <core/Error.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/SafeConvert.hpp>
#include <core/system/System.hpp>
namespace core {
namespace tex {
namespace {
// Helper function, returns true if str begins with any of these values
bool beginsWith(const std::string& str,
const std::string& test1,
const std::string& test2=std::string(),
const std::string& test3=std::string(),
const std::string& test4=std::string())
{
using namespace boost::algorithm;
if (starts_with(str, test1))
return true;
if (test2.empty())
return false;
else if (starts_with(str, test2))
return true;
if (test3.empty())
return false;
else if (starts_with(str, test3))
return true;
if (test4.empty())
return false;
else if (starts_with(str, test4))
return true;
return false;
}
// Finds unmatched parens in `line` and puts them in pParens. Can be either
// ( or ). Logically the result can only be [zero or more ')'] followed by
// [zero or more '('].
void findUnmatchedParens(const std::string& line,
std::vector<std::string::const_iterator>* pParens)
{
// We need to ignore close parens unless they are at the start of a line,
// preceded by nothing but whitespace and/or other close parens. Without
// this, sample.Rnw has some false positives due to some math errors, e.g.:
//
// l.204 (x + (y^
// 2))
//
// The first line is ignored because it's part of an error message. The rest
// gets parsed and underflows the file stack.
bool ignoreCloseParens = false;
// NOTE: I don't know if it's possible for (<filename> to appear anywhere
// but the beginning of the line (preceded only by whitespace(?) and close
// parens). But the Sublime Text 2 plugin code seemed to imply that it is
// possible.
for (std::string::const_iterator it = line.begin(); it != line.end(); it++)
{
switch (*it)
{
case '(':
pParens->push_back(it);
ignoreCloseParens = true;
break;
case ')':
if (pParens->empty() || *(pParens->back()) == ')')
{
if (!ignoreCloseParens)
pParens->push_back(it);
}
else
pParens->pop_back();
break;
case ' ':
case '\t':
break;
default:
ignoreCloseParens = true;
break;
}
}
}
FilePath resolveFilename(const FilePath& rootDir,
const std::string& filename)
{
std::string result = filename;
// Remove quotes if necessary
if (result.size() > 2 &&
boost::algorithm::starts_with(result, "\"") &&
boost::algorithm::ends_with(result, "\""))
{
result.erase(result.size()-1, 1);
}
// Strip leading ./
if (boost::algorithm::starts_with(result, "./"))
result.erase(0, 2);
if (result.empty())
return FilePath();
// Check for existence of file
FilePath file = rootDir.complete(result);
if (file.exists())
return file;
else
return FilePath();
}
// TeX wraps lines hard at 79 characters. We use heuristics as described in
// Sublime Text's TeX plugin to determine where these breaks are.
void unwrapLines(std::vector<std::string>* pLines,
std::vector<size_t>* pLinesUnwrapped=NULL)
{
static boost::regex regexLine("^l\\.(\\d+)\\s");
static boost::regex regexAssignment("^\\\\.*?=");
std::vector<std::string>::iterator pos = pLines->begin();
for ( ; pos != pLines->end(); pos++)
{
// The first line is always long, and not artificially wrapped
if (pos == pLines->begin())
continue;
if (pos->length() != 79)
continue;
// The **<filename> line may be long, but we don't care about it
if (beginsWith(*pos, "**"))
continue;
while (true)
{
std::vector<std::string>::iterator nextPos = pos + 1;
// No more lines to add
if (nextPos == pLines->end())
break;
if (nextPos->empty())
break;
// Underfull/Overfull terminator
if (*nextPos == " []")
break;
// Common prefixes
if (beginsWith(*nextPos, "File:", "Package:", "Document Class:"))
break;
// More prefixes
if (beginsWith(*nextPos, "LaTeX Warning:", "LaTeX Info:", "LaTeX2e <"))
break;
if (boost::regex_search(*nextPos, regexAssignment))
break;
if (boost::regex_search(*nextPos, regexLine))
break;
bool breakAfterAppend = nextPos->length() != 79;
pos->append(*nextPos);
// NOTE: Erase is a simple but inefficient way of handling this. Would
// be way faster to maintain an output iterator that points to the
// correct point in pLines, and when finished, truncate whatever
// elements come after the final position of the output iterator.
pLines->erase(nextPos, nextPos+1);
if (pLinesUnwrapped)
pLinesUnwrapped->push_back(1 + (pos - pLines->begin()));
if (breakAfterAppend)
break;
}
}
}
class FileStack : public boost::noncopyable
{
public:
explicit FileStack(FilePath rootDir) : rootDir_(rootDir)
{
}
FilePath currentFile()
{
return currentFile_;
}
void processLine(const std::string& line)
{
std::vector<std::string::const_iterator> parens;
findUnmatchedParens(line, &parens);
BOOST_FOREACH(std::string::const_iterator it, parens)
{
if (*it == ')')
{
if (!fileStack_.empty())
{
fileStack_.pop_back();
updateCurrentFile();
}
else
{
LOG_WARNING_MESSAGE("File context stack underflow while parsing "
"TeX log");
}
}
else if (*it == '(')
{
fileStack_.push_back(
resolveFilename(rootDir_, std::string(it+1, line.end())));
updateCurrentFile();
}
else
BOOST_ASSERT(false);
}
}
private:
void updateCurrentFile()
{
for (std::vector<FilePath>::reverse_iterator it = fileStack_.rbegin();
it != fileStack_.rend();
it++)
{
if (!it->empty())
{
currentFile_ = *it;
return;
}
}
currentFile_ = FilePath();
}
FilePath rootDir_;
FilePath currentFile_;
std::vector<FilePath> fileStack_;
};
FilePath texFilePath(const std::string& logPath, const FilePath& compileDir)
{
// some tex compilers report file names with absolute paths and some
// report them relative to the compilation directory -- on Posix use
// realPath to get a clean full path back -- note the fact that we
// don't do this on Windows is a tacit assumption that Windows TeX logs
// are either absolute or don't require interpretation of .., etc.
FilePath path = compileDir.complete(logPath);
#ifdef _WIN32
return path;
#else
FilePath realPath;
Error error = core::system::realPath(path.absolutePath(), &realPath);
if (error)
{
LOG_ERROR(error);
return path;
}
else
{
return realPath;
}
#endif
}
size_t calculateWrappedLine(const std::vector<size_t>& unwrappedLines,
size_t unwrappedLineNum)
{
for (std::vector<size_t>::const_iterator it = unwrappedLines.begin();
it != unwrappedLines.end();
it++)
{
if (*it >= unwrappedLineNum)
{
return unwrappedLineNum + (it - unwrappedLines.begin());
}
}
return unwrappedLineNum + unwrappedLines.size();
}
} // anonymous namespace
Error parseLatexLog(const FilePath& logFilePath, LogEntries* pLogEntries)
{
static boost::regex regexOverUnderfullLines(" at lines (\\d+)--(\\d+)\\s*(?:\\[])?$");
static boost::regex regexWarning("^(?:.*?) Warning: (.+)");
static boost::regex regexWarningEnd(" input line (\\d+)\\.$");
static boost::regex regexLnn("^l\\.(\\d+)\\s");
static boost::regex regexCStyleError("^(.+):(\\d+):\\s(.+)$");
std::vector<std::string> lines;
Error error = readStringVectorFromFile(logFilePath, &lines, false);
if (error)
return error;
std::vector<size_t> linesUnwrapped;
unwrapLines(&lines, &linesUnwrapped);
FilePath rootDir = logFilePath.parent();
FileStack fileStack(rootDir);
for (std::vector<std::string>::const_iterator it = lines.begin();
it != lines.end();
it++)
{
const std::string& line = *it;
int logLineNum = (it - lines.begin()) + 1;
// We slurp overfull/underfull messages with no further processing
// (i.e. not manipulating the file stack)
if (beginsWith(line, "Overfull ", "Underfull "))
{
std::string msg = line;
int lineNum = -1;
// Parse lines, if present
boost::smatch overUnderfullLinesMatch;
if (boost::regex_search(line,
overUnderfullLinesMatch,
regexOverUnderfullLines))
{
lineNum = safe_convert::stringTo<int>(overUnderfullLinesMatch[1],
-1);
}
// Single line case
bool singleLine = boost::algorithm::ends_with(line, "[]");
if (singleLine)
{
msg.erase(line.size()-2, 2);
boost::algorithm::trim_right(msg);
}
pLogEntries->push_back(LogEntry(logFilePath,
calculateWrappedLine(linesUnwrapped,
logLineNum),
LogEntry::Box,
fileStack.currentFile(),
lineNum,
msg));
if (singleLine)
continue;
for (; it != lines.end(); it++)
{
// For multi-line case, we're looking for " []" on a line by itself
if (*it == " []")
break;
}
// The iterator would be incremented by the outer for loop, must not
// let it go past the end! (If we did get to the end, it would
// mean the log file was malformed, but we still can't crash in this
// situation.)
if (it == lines.end())
break;
else
continue;
}
fileStack.processLine(line);
// Now see if it's an error or warning
if (beginsWith(line, "! "))
{
std::string errorMsg = line.substr(2);
int lineNum = -1;
boost::smatch match;
for (it++; it != lines.end(); it++)
{
if (boost::regex_search(*it, match, regexLnn))
{
lineNum = safe_convert::stringTo<int>(match[1], -1);
break;
}
}
pLogEntries->push_back(LogEntry(logFilePath,
calculateWrappedLine(linesUnwrapped,
logLineNum),
LogEntry::Error,
fileStack.currentFile(),
lineNum,
errorMsg));
// The iterator would be incremented by the outer for loop, must not
// let it go past the end! (If we did get to the end, it would
// mean the log file was malformed, but we still can't crash in this
// situation.)
if (it == lines.end())
break;
else
continue;
}
boost::smatch warningMatch;
if (boost::regex_search(line, warningMatch, regexWarning))
{
std::string warningMsg = warningMatch[1];
int lineNum = -1;
while (true)
{
if (boost::algorithm::ends_with(warningMsg, "."))
{
boost::smatch warningEndMatch;
if (boost::regex_search(*it, warningEndMatch, regexWarningEnd))
{
lineNum = safe_convert::stringTo<int>(warningEndMatch[1], -1);
}
break;
}
if (++it == lines.end())
break;
warningMsg.append(*it);
}
pLogEntries->push_back(LogEntry(logFilePath,
calculateWrappedLine(linesUnwrapped,
logLineNum),
LogEntry::Warning,
fileStack.currentFile(),
lineNum,
warningMsg));
// The iterator would be incremented by the outer for loop, must not
// let it go past the end! (If we did get to the end, it would
// mean the log file was malformed, but we still can't crash in this
// situation.)
if (it == lines.end())
break;
else
continue;
}
boost::smatch cStyleErrorMatch;
if (boost::regex_search(line, cStyleErrorMatch, regexCStyleError))
{
FilePath cstyleFile = resolveFilename(rootDir, cStyleErrorMatch[1]);
if (cstyleFile.exists())
{
int lineNum = safe_convert::stringTo<int>(cStyleErrorMatch[2], -1);
pLogEntries->push_back(LogEntry(logFilePath,
calculateWrappedLine(linesUnwrapped,
logLineNum),
LogEntry::Error,
cstyleFile,
lineNum,
cStyleErrorMatch[3]));
}
}
}
return Success();
}
Error parseBibtexLog(const FilePath& logFilePath, LogEntries* pLogEntries)
{
boost::regex re("^(.*)---line ([0-9]+) of file (.*)$");
// get the lines
std::vector<std::string> lines;
Error error = core::readStringVectorFromFile(logFilePath, &lines, false);
if (error)
return error;
// look for error messages
for (std::vector<std::string>::const_iterator it = lines.begin();
it != lines.end();
it++)
{
boost::smatch match;
if (regex_match(*it, match, re))
{
pLogEntries->push_back(
LogEntry(
logFilePath,
(it - lines.begin()) + 1,
LogEntry::Error,
texFilePath(match[3], logFilePath.parent()),
boost::lexical_cast<int>(match[2]),
match[1]));
}
}
return Success();
}
} // namespace tex
} // namespace core
<commit_msg>TexLogParser needs to deal with >1 file scopes on same line<commit_after>/*
* TexLogParser.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/tex/TexLogParser.hpp>
#include <boost/foreach.hpp>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <core/Error.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/SafeConvert.hpp>
#include <core/system/System.hpp>
namespace core {
namespace tex {
namespace {
// Helper function, returns true if str begins with any of these values
bool beginsWith(const std::string& str,
const std::string& test1,
const std::string& test2=std::string(),
const std::string& test3=std::string(),
const std::string& test4=std::string())
{
using namespace boost::algorithm;
if (starts_with(str, test1))
return true;
if (test2.empty())
return false;
else if (starts_with(str, test2))
return true;
if (test3.empty())
return false;
else if (starts_with(str, test3))
return true;
if (test4.empty())
return false;
else if (starts_with(str, test4))
return true;
return false;
}
// Finds unmatched parens in `line` and puts them in pParens. Can be either
// ( or ). Logically the result can only be [zero or more ')'] followed by
// [zero or more '('].
void findUnmatchedParens(const std::string& line,
std::vector<std::string::const_iterator>* pParens)
{
// We need to ignore close parens unless they are at the start of a line,
// preceded by nothing but whitespace and/or other close parens. Without
// this, sample.Rnw has some false positives due to some math errors, e.g.:
//
// l.204 (x + (y^
// 2))
//
// The first line is ignored because it's part of an error message. The rest
// gets parsed and underflows the file stack.
bool ignoreCloseParens = false;
// NOTE: I don't know if it's possible for (<filename> to appear anywhere
// but the beginning of the line (preceded only by whitespace(?) and close
// parens). But the Sublime Text 2 plugin code seemed to imply that it is
// possible.
for (std::string::const_iterator it = line.begin(); it != line.end(); it++)
{
switch (*it)
{
case '(':
pParens->push_back(it);
ignoreCloseParens = true;
break;
case ')':
if (pParens->empty() || *(pParens->back()) == ')')
{
if (!ignoreCloseParens)
pParens->push_back(it);
}
else
pParens->pop_back();
break;
case ' ':
case '\t':
break;
default:
ignoreCloseParens = true;
break;
}
}
}
FilePath resolveFilename(const FilePath& rootDir,
const std::string& filename)
{
std::string result = filename;
// Remove quotes if necessary
if (result.size() > 2 &&
boost::algorithm::starts_with(result, "\"") &&
boost::algorithm::ends_with(result, "\""))
{
result.erase(result.size()-1, 1);
}
// Strip leading ./
if (boost::algorithm::starts_with(result, "./"))
result.erase(0, 2);
if (result.empty())
return FilePath();
// Check for existence of file
FilePath file = rootDir.complete(result);
if (file.exists() && !file.isDirectory())
return file;
else
return FilePath();
}
// TeX wraps lines hard at 79 characters. We use heuristics as described in
// Sublime Text's TeX plugin to determine where these breaks are.
void unwrapLines(std::vector<std::string>* pLines,
std::vector<size_t>* pLinesUnwrapped=NULL)
{
static boost::regex regexLine("^l\\.(\\d+)\\s");
static boost::regex regexAssignment("^\\\\.*?=");
std::vector<std::string>::iterator pos = pLines->begin();
for ( ; pos != pLines->end(); pos++)
{
// The first line is always long, and not artificially wrapped
if (pos == pLines->begin())
continue;
if (pos->length() != 79)
continue;
// The **<filename> line may be long, but we don't care about it
if (beginsWith(*pos, "**"))
continue;
while (true)
{
std::vector<std::string>::iterator nextPos = pos + 1;
// No more lines to add
if (nextPos == pLines->end())
break;
if (nextPos->empty())
break;
// Underfull/Overfull terminator
if (*nextPos == " []")
break;
// Common prefixes
if (beginsWith(*nextPos, "File:", "Package:", "Document Class:"))
break;
// More prefixes
if (beginsWith(*nextPos, "LaTeX Warning:", "LaTeX Info:", "LaTeX2e <"))
break;
if (boost::regex_search(*nextPos, regexAssignment))
break;
if (boost::regex_search(*nextPos, regexLine))
break;
bool breakAfterAppend = nextPos->length() != 79;
pos->append(*nextPos);
// NOTE: Erase is a simple but inefficient way of handling this. Would
// be way faster to maintain an output iterator that points to the
// correct point in pLines, and when finished, truncate whatever
// elements come after the final position of the output iterator.
pLines->erase(nextPos, nextPos+1);
if (pLinesUnwrapped)
pLinesUnwrapped->push_back(1 + (pos - pLines->begin()));
if (breakAfterAppend)
break;
}
}
}
class FileStack : public boost::noncopyable
{
public:
explicit FileStack(FilePath rootDir) : rootDir_(rootDir)
{
}
FilePath currentFile()
{
return currentFile_;
}
void processLine(const std::string& line)
{
typedef std::vector<std::string::const_iterator> Iterators;
Iterators parens;
findUnmatchedParens(line, &parens);
for (Iterators::const_iterator itParen = parens.begin();
itParen != parens.end();
itParen++)
{
std::string::const_iterator it = *itParen;
if (*it == ')')
{
if (!fileStack_.empty())
{
fileStack_.pop_back();
updateCurrentFile();
}
else
{
LOG_WARNING_MESSAGE("File context stack underflow while parsing "
"TeX log");
}
}
else if (*it == '(')
{
std::string::const_iterator itFilenameEnd =
// case: no other ( on this line
(itParen + 1 == parens.end()) ? line.end() :
// case: space before next paren, eat it
*(*(itParen+1)-1) == ' ' ? *(itParen+1)-1 :
// case: other
*(itParen+1);
std::string filename = std::string(it+1, itFilenameEnd);
fileStack_.push_back(resolveFilename(rootDir_, filename));
updateCurrentFile();
}
else
BOOST_ASSERT(false);
}
}
private:
void updateCurrentFile()
{
for (std::vector<FilePath>::reverse_iterator it = fileStack_.rbegin();
it != fileStack_.rend();
it++)
{
if (!it->empty())
{
currentFile_ = *it;
return;
}
}
currentFile_ = FilePath();
}
FilePath rootDir_;
FilePath currentFile_;
std::vector<FilePath> fileStack_;
};
FilePath texFilePath(const std::string& logPath, const FilePath& compileDir)
{
// some tex compilers report file names with absolute paths and some
// report them relative to the compilation directory -- on Posix use
// realPath to get a clean full path back -- note the fact that we
// don't do this on Windows is a tacit assumption that Windows TeX logs
// are either absolute or don't require interpretation of .., etc.
FilePath path = compileDir.complete(logPath);
#ifdef _WIN32
return path;
#else
FilePath realPath;
Error error = core::system::realPath(path.absolutePath(), &realPath);
if (error)
{
LOG_ERROR(error);
return path;
}
else
{
return realPath;
}
#endif
}
size_t calculateWrappedLine(const std::vector<size_t>& unwrappedLines,
size_t unwrappedLineNum)
{
for (std::vector<size_t>::const_iterator it = unwrappedLines.begin();
it != unwrappedLines.end();
it++)
{
if (*it >= unwrappedLineNum)
{
return unwrappedLineNum + (it - unwrappedLines.begin());
}
}
return unwrappedLineNum + unwrappedLines.size();
}
} // anonymous namespace
Error parseLatexLog(const FilePath& logFilePath, LogEntries* pLogEntries)
{
static boost::regex regexOverUnderfullLines(" at lines (\\d+)--(\\d+)\\s*(?:\\[])?$");
static boost::regex regexWarning("^(?:.*?) Warning: (.+)");
static boost::regex regexWarningEnd(" input line (\\d+)\\.$");
static boost::regex regexLnn("^l\\.(\\d+)\\s");
static boost::regex regexCStyleError("^(.+):(\\d+):\\s(.+)$");
std::vector<std::string> lines;
Error error = readStringVectorFromFile(logFilePath, &lines, false);
if (error)
return error;
std::vector<size_t> linesUnwrapped;
unwrapLines(&lines, &linesUnwrapped);
FilePath rootDir = logFilePath.parent();
FileStack fileStack(rootDir);
for (std::vector<std::string>::const_iterator it = lines.begin();
it != lines.end();
it++)
{
const std::string& line = *it;
int logLineNum = (it - lines.begin()) + 1;
// We slurp overfull/underfull messages with no further processing
// (i.e. not manipulating the file stack)
if (beginsWith(line, "Overfull ", "Underfull "))
{
std::string msg = line;
int lineNum = -1;
// Parse lines, if present
boost::smatch overUnderfullLinesMatch;
if (boost::regex_search(line,
overUnderfullLinesMatch,
regexOverUnderfullLines))
{
lineNum = safe_convert::stringTo<int>(overUnderfullLinesMatch[1],
-1);
}
// Single line case
bool singleLine = boost::algorithm::ends_with(line, "[]");
if (singleLine)
{
msg.erase(line.size()-2, 2);
boost::algorithm::trim_right(msg);
}
pLogEntries->push_back(LogEntry(logFilePath,
calculateWrappedLine(linesUnwrapped,
logLineNum),
LogEntry::Box,
fileStack.currentFile(),
lineNum,
msg));
if (singleLine)
continue;
for (; it != lines.end(); it++)
{
// For multi-line case, we're looking for " []" on a line by itself
if (*it == " []")
break;
}
// The iterator would be incremented by the outer for loop, must not
// let it go past the end! (If we did get to the end, it would
// mean the log file was malformed, but we still can't crash in this
// situation.)
if (it == lines.end())
break;
else
continue;
}
fileStack.processLine(line);
// Now see if it's an error or warning
if (beginsWith(line, "! "))
{
std::string errorMsg = line.substr(2);
int lineNum = -1;
boost::smatch match;
for (it++; it != lines.end(); it++)
{
if (boost::regex_search(*it, match, regexLnn))
{
lineNum = safe_convert::stringTo<int>(match[1], -1);
break;
}
}
pLogEntries->push_back(LogEntry(logFilePath,
calculateWrappedLine(linesUnwrapped,
logLineNum),
LogEntry::Error,
fileStack.currentFile(),
lineNum,
errorMsg));
// The iterator would be incremented by the outer for loop, must not
// let it go past the end! (If we did get to the end, it would
// mean the log file was malformed, but we still can't crash in this
// situation.)
if (it == lines.end())
break;
else
continue;
}
boost::smatch warningMatch;
if (boost::regex_search(line, warningMatch, regexWarning))
{
std::string warningMsg = warningMatch[1];
int lineNum = -1;
while (true)
{
if (boost::algorithm::ends_with(warningMsg, "."))
{
boost::smatch warningEndMatch;
if (boost::regex_search(*it, warningEndMatch, regexWarningEnd))
{
lineNum = safe_convert::stringTo<int>(warningEndMatch[1], -1);
}
break;
}
if (++it == lines.end())
break;
warningMsg.append(*it);
}
pLogEntries->push_back(LogEntry(logFilePath,
calculateWrappedLine(linesUnwrapped,
logLineNum),
LogEntry::Warning,
fileStack.currentFile(),
lineNum,
warningMsg));
// The iterator would be incremented by the outer for loop, must not
// let it go past the end! (If we did get to the end, it would
// mean the log file was malformed, but we still can't crash in this
// situation.)
if (it == lines.end())
break;
else
continue;
}
boost::smatch cStyleErrorMatch;
if (boost::regex_search(line, cStyleErrorMatch, regexCStyleError))
{
FilePath cstyleFile = resolveFilename(rootDir, cStyleErrorMatch[1]);
if (cstyleFile.exists())
{
int lineNum = safe_convert::stringTo<int>(cStyleErrorMatch[2], -1);
pLogEntries->push_back(LogEntry(logFilePath,
calculateWrappedLine(linesUnwrapped,
logLineNum),
LogEntry::Error,
cstyleFile,
lineNum,
cStyleErrorMatch[3]));
}
}
}
return Success();
}
Error parseBibtexLog(const FilePath& logFilePath, LogEntries* pLogEntries)
{
boost::regex re("^(.*)---line ([0-9]+) of file (.*)$");
// get the lines
std::vector<std::string> lines;
Error error = core::readStringVectorFromFile(logFilePath, &lines, false);
if (error)
return error;
// look for error messages
for (std::vector<std::string>::const_iterator it = lines.begin();
it != lines.end();
it++)
{
boost::smatch match;
if (regex_match(*it, match, re))
{
pLogEntries->push_back(
LogEntry(
logFilePath,
(it - lines.begin()) + 1,
LogEntry::Error,
texFilePath(match[3], logFilePath.parent()),
boost::lexical_cast<int>(match[2]),
match[1]));
}
}
return Success();
}
} // namespace tex
} // namespace core
<|endoftext|> |
<commit_before>
// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This
// project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-
// width of 100 characters per line.
//
// Author(s):
// Cedric Nugteren <www.cedricnugteren.nl>
//
// This determines when to switch between the direct (for small sizes) and in-direct GEMM kernel
// with pre/post-processing kernels (for larger sizes). These can be set in a similar way as for the
// regular kernel tuning parameters: they can be specific for a certain vendor or device or can use
// some common default values.
//
// =================================================================================================
namespace clblast {
namespace database {
// =================================================================================================
const Database::DatabaseEntry KernelSelectionHalf = {
"KernelSelection", Precision::kHalf, {
{ // Intel GPUs
kDeviceTypeGPU, "Intel", {
{ "Intel(R) HD Graphics Skylake ULT GT2", { {"XGEMM_MIN_INDIRECT_SIZE",1*1*1} } },
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",384*384*384} } },
}
},
{ // NVIDIA GPUs
kDeviceTypeGPU, "NVIDIA", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",768*768*768} } },
}
},
{ // Default
kDeviceTypeAll, "default", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",512*512*512} } },
}
},
}
};
// =================================================================================================
const Database::DatabaseEntry KernelSelectionSingle = {
"KernelSelection", Precision::kSingle, {
{ // Intel GPUs
kDeviceTypeGPU, "Intel", {
{ "Intel(R) HD Graphics Skylake ULT GT2", { {"XGEMM_MIN_INDIRECT_SIZE",1*1*1} } },
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",384*384*384} } },
}
},
{ // NVIDIA GPUs
kDeviceTypeGPU, "NVIDIA", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",768*768*768} } },
}
},
{ // Default
kDeviceTypeAll, "default", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",512*512*512} } },
}
},
}
};
// =================================================================================================
const Database::DatabaseEntry KernelSelectionComplexSingle = {
"KernelSelection", Precision::kComplexSingle, {
{ // Intel GPUs
kDeviceTypeGPU, "Intel", {
{ "Intel(R) HD Graphics Skylake ULT GT2", { {"XGEMM_MIN_INDIRECT_SIZE",1*1*1} } },
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",384*384*384} } },
}
},
{ // NVIDIA GPUs
kDeviceTypeGPU, "NVIDIA", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",768*768*768} } },
}
},
{ // Default
kDeviceTypeAll, "default", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",512*512*512} } },
}
},
}
};
// =================================================================================================
const Database::DatabaseEntry KernelSelectionDouble = {
"KernelSelection", Precision::kDouble, {
{ // Intel GPUs
kDeviceTypeGPU, "Intel", {
{ "Intel(R) HD Graphics Skylake ULT GT2", { {"XGEMM_MIN_INDIRECT_SIZE",1*1*1} } },
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",384*384*384} } },
}
},
{ // NVIDIA GPUs
kDeviceTypeGPU, "NVIDIA", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",768*768*768} } },
}
},
{ // Default
kDeviceTypeAll, "default", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",512*512*512} } },
}
},
}
};
// =================================================================================================
const Database::DatabaseEntry KernelSelectionComplexDouble = {
"KernelSelection", Precision::kComplexDouble, {
{ // Intel GPUs
kDeviceTypeGPU, "Intel", {
{ "Intel(R) HD Graphics Skylake ULT GT2", { {"XGEMM_MIN_INDIRECT_SIZE",1*1*1} } },
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",384*384*384} } },
}
},
{ // NVIDIA GPUs
kDeviceTypeGPU, "NVIDIA", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",768*768*768} } },
}
},
{ // Default
kDeviceTypeAll, "default", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",512*512*512} } },
}
},
}
};
// =================================================================================================
} // namespace database
} // namespace clblast
<commit_msg>Made Intel GPUs always use the indirect version of the GEMM kernel<commit_after>
// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This
// project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-
// width of 100 characters per line.
//
// Author(s):
// Cedric Nugteren <www.cedricnugteren.nl>
//
// This determines when to switch between the direct (for small sizes) and in-direct GEMM kernel
// with pre/post-processing kernels (for larger sizes). These can be set in a similar way as for the
// regular kernel tuning parameters: they can be specific for a certain vendor or device or can use
// some common default values.
//
// =================================================================================================
namespace clblast {
namespace database {
// =================================================================================================
const Database::DatabaseEntry KernelSelectionHalf = {
"KernelSelection", Precision::kHalf, {
{ // Intel GPUs
kDeviceTypeGPU, "Intel", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",1*1*1} } },
}
},
{ // NVIDIA GPUs
kDeviceTypeGPU, "NVIDIA", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",768*768*768} } },
}
},
{ // Default
kDeviceTypeAll, "default", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",512*512*512} } },
}
},
}
};
// =================================================================================================
const Database::DatabaseEntry KernelSelectionSingle = {
"KernelSelection", Precision::kSingle, {
{ // Intel GPUs
kDeviceTypeGPU, "Intel", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",1*1*1} } },
}
},
{ // NVIDIA GPUs
kDeviceTypeGPU, "NVIDIA", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",768*768*768} } },
}
},
{ // Default
kDeviceTypeAll, "default", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",512*512*512} } },
}
},
}
};
// =================================================================================================
const Database::DatabaseEntry KernelSelectionComplexSingle = {
"KernelSelection", Precision::kComplexSingle, {
{ // Intel GPUs
kDeviceTypeGPU, "Intel", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",1*1*1} } },
}
},
{ // NVIDIA GPUs
kDeviceTypeGPU, "NVIDIA", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",768*768*768} } },
}
},
{ // Default
kDeviceTypeAll, "default", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",512*512*512} } },
}
},
}
};
// =================================================================================================
const Database::DatabaseEntry KernelSelectionDouble = {
"KernelSelection", Precision::kDouble, {
{ // Intel GPUs
kDeviceTypeGPU, "Intel", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",1*1*1} } },
}
},
{ // NVIDIA GPUs
kDeviceTypeGPU, "NVIDIA", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",768*768*768} } },
}
},
{ // Default
kDeviceTypeAll, "default", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",512*512*512} } },
}
},
}
};
// =================================================================================================
const Database::DatabaseEntry KernelSelectionComplexDouble = {
"KernelSelection", Precision::kComplexDouble, {
{ // Intel GPUs
kDeviceTypeGPU, "Intel", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",1*1*1} } },
}
},
{ // NVIDIA GPUs
kDeviceTypeGPU, "NVIDIA", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",768*768*768} } },
}
},
{ // Default
kDeviceTypeAll, "default", {
{ "default", { {"XGEMM_MIN_INDIRECT_SIZE",512*512*512} } },
}
},
}
};
// =================================================================================================
} // namespace database
} // namespace clblast
<|endoftext|> |
<commit_before>#include <mos/render/environment_light.hpp>
namespace mos {
EnvironmentLight::EnvironmentLight(const glm::vec3 &position,
const glm::vec3 &extent,
const float strength,
const glm::uvec2 resolution)
: texture(resolution.x, resolution.y), box(RenderBox(position, extent)), strength(strength), cube_camera(position) {
}
EnvironmentLight::EnvironmentLight(const EnvironmentLight &light) : texture(light.texture), box(light.box), strength(light.strength), cube_camera(light.cube_camera) {}
EnvironmentLight &EnvironmentLight::operator=(const EnvironmentLight &other) {
texture = other.texture;
box = other.box;
strength = other.strength;
cube_camera = other.cube_camera;
return *this;
}
}<commit_msg>Optimization bug<commit_after>#include <mos/render/environment_light.hpp>
namespace mos {
EnvironmentLight::EnvironmentLight(const glm::vec3 &position,
const glm::vec3 &extent,
const float strength,
const glm::uvec2 resolution)
: texture(resolution.x, resolution.y),
box(RenderBox(position, extent)),
strength(strength),
cube_camera(position) {
}
EnvironmentLight::EnvironmentLight(const EnvironmentLight &light) :
texture(light.texture),
box(light.box),
strength(light.strength),
cube_camera(light.cube_camera),
target(light.target)
{}
EnvironmentLight &EnvironmentLight::operator=(const EnvironmentLight &other) {
texture = other.texture;
box = other.box;
strength = other.strength;
cube_camera = other.cube_camera;
target = other.target;
return *this;
}
}<|endoftext|> |
<commit_before>#pragma once
#include "grid_base.hpp"
#include <numeric>
namespace gftools {
template <bool Fermion> inline complex_type Matsubara(int n, real_type beta){return PI*I/beta*complex_type(2*n+Fermion);};
template <bool Fermion> inline int MatsubaraIndex(complex_type in, real_type beta){return std::round((beta*imag(in)/PI-Fermion)/2.0);};
inline complex_type FMatsubara(int n, real_type beta){return Matsubara<1>(n,beta);};
inline complex_type BMatsubara(int n, real_type beta){return Matsubara<0>(n,beta);};
inline int FMatsubaraIndex(complex_type in, real_type beta){return MatsubaraIndex<1>(in,beta);};
inline int BMatsubaraIndex(complex_type in, real_type beta){return MatsubaraIndex<0>(in,beta);};
/** A Grid of fermionic Matsubara frequencies. */
template <bool Fermion>
class matsubara_grid : public grid_base<complex_type, matsubara_grid<Fermion>>
{
public:
typedef grid_base<complex_type, matsubara_grid<Fermion>> base;
typedef typename base::point point;
using base::vals_;
using typename base::ex_wrong_index;
//typedef typename grid_base<complex_type, matsubara_grid<Fermion>>::point point;
//using typename grid_base<complex_type, matsubara_grid<Fermion>>::point;
/** Inverse temperature. */
const real_type _beta;
/** Spacing between values. */
const real_type _spacing;
/** Min and max numbers of freq. - useful for searching. */
const int w_min_, w_max_;
matsubara_grid(int min, int max, real_type beta);
matsubara_grid(const matsubara_grid &rhs);
matsubara_grid(matsubara_grid&& rhs);
int getNumber(complex_type in) const;
point find_nearest(complex_type in) const;
template <class Obj> auto integrate(const Obj &in) const -> decltype(in(vals_[0]));
template <class Obj> auto prod(const Obj &in) const -> decltype(in(vals_[0]));
//template <class Obj> auto gridIntegrate(const std::vector<Obj> &in) const -> Obj;
template <class Obj> auto eval(Obj &in, complex_type x) const ->decltype(in[0]);
//template <class Obj> auto eval(Obj &in, point x) const ->decltype(in[0]);
//using base::eval;
};
typedef matsubara_grid<1> fmatsubara_grid;
typedef matsubara_grid<0> bmatsubara_grid;
//
// matsubara_grid implementations
//
template <bool F>
matsubara_grid<F>::matsubara_grid(int min, int max, real_type beta):
//grid_base<complex_type, matsubara_grid<F>>(min,max,std::bind(Matsubara<F>, std::placeholders::_1, beta)),
grid_base<complex_type, matsubara_grid<F>>(min,max,[beta](int n){return Matsubara<F>(n,beta);}),
_beta(beta),
_spacing(PI/beta),
w_min_(min),
w_max_(max)
{
}
template <bool F>
matsubara_grid<F>::matsubara_grid(const matsubara_grid<F> &rhs) :
grid_base<complex_type, matsubara_grid<F>>(rhs.vals_),
_beta(rhs._beta),
_spacing(rhs._spacing),
w_min_(rhs.w_min_),
w_max_(rhs.w_max_)
{
}
template <bool F>
matsubara_grid<F>::matsubara_grid(matsubara_grid<F>&& rhs):
grid_base<complex_type, matsubara_grid>(rhs.vals_),
_beta(rhs._beta),
_spacing(rhs._spacing),
w_min_(rhs.w_min_),
w_max_(rhs.w_max_)
{
}
template <bool F>
template <class Obj>
auto matsubara_grid<F>::integrate(const Obj &in) const -> decltype(in(vals_[0]))
{
decltype(in(this->vals_[0])) R = in(this->vals_[0]);
R=std::accumulate(vals_.begin()+1, vals_.end(), R,[&](decltype(in(vals_[0]))& y,decltype(vals_[0]) &x) {return y+in(x);});
return R/_beta;
}
template <bool F>
template <class Obj>
auto matsubara_grid<F>::prod(const Obj &in) const -> decltype(in(vals_[0]))
{
// fix prod for more numerical stability
decltype(in(vals_[0])) R = in(vals_[0]);
R=std::accumulate(vals_.begin()+1, vals_.end(), R,[&](decltype(in(vals_[0]))& y,decltype(vals_[0]) &x) {return y*in(x);});
//decltype(in(vals_[0])) R = in(vals_[vals_.size()/2]);
//R=std::accumulate(vals_.begin()+1+vals_.size()/2, vals_.end(), R,[&](decltype(in(vals_[0]))& y,decltype(vals_[0]) &x) {DEBUG(x << "|" << in(x) << "|" << y << "->" << y*in(x)); return y*in(x);});
//R=std::accumulate(vals_.begin(), vals_.begin()+vals_.size()/2, R,[&](decltype(in(vals_[0]))& y,decltype(vals_[0]) &x) {DEBUG(x << "|" << in(x) << "|" << y << "->" << y*in(x)); return y*in(x);});
return R;
}
template <bool F>
inline typename matsubara_grid<F>::point matsubara_grid<F>::find_nearest (complex_type in) const
{
int n=getNumber(in);
#ifndef NDEBUG
//DEBUG("Invoking matsubara find");
#endif
if (n>=w_min_ && n<w_max_) { return vals_[n-w_min_]; }
else {
#ifndef NDEBUG
//ERROR("Couldn't find the point");
#endif
if (n<w_min_) return vals_[0];
else return vals_[vals_.size()-1];
};
}
template <bool F>
inline int matsubara_grid<F>::getNumber(complex_type in) const
{
assert (std::abs(real(in))<std::numeric_limits<real_type>::epsilon());
return std::lround(imag(in)/_spacing-F)/2;
};
template <bool F>
template <class Obj>
inline auto matsubara_grid<F>::eval(Obj &in, complex_type x) const ->decltype(in[0])
{
const auto find_result=this->find_nearest(x);
if (!tools::is_float_equal<complex_type>(x,find_result.val_)) { throw (ex_wrong_index()); }
return in[find_result.index_];
}
} // end of namespace gftools
<commit_msg>matsubara_grid : beta() public method and rename _beta to beta_ and _spacing to spacing_<commit_after>#pragma once
#include "grid_base.hpp"
#include <numeric>
namespace gftools {
template <bool Fermion> inline complex_type Matsubara(int n, real_type beta){return PI*I/beta*complex_type(2*n+Fermion);};
template <bool Fermion> inline int MatsubaraIndex(complex_type in, real_type beta){return std::round((beta*imag(in)/PI-Fermion)/2.0);};
inline complex_type FMatsubara(int n, real_type beta){return Matsubara<1>(n,beta);};
inline complex_type BMatsubara(int n, real_type beta){return Matsubara<0>(n,beta);};
inline int FMatsubaraIndex(complex_type in, real_type beta){return MatsubaraIndex<1>(in,beta);};
inline int BMatsubaraIndex(complex_type in, real_type beta){return MatsubaraIndex<0>(in,beta);};
/** A Grid of fermionic Matsubara frequencies. */
template <bool Fermion>
class matsubara_grid : public grid_base<complex_type, matsubara_grid<Fermion>>
{
public:
typedef grid_base<complex_type, matsubara_grid<Fermion>> base;
typedef typename base::point point;
using base::vals_;
using typename base::ex_wrong_index;
//typedef typename grid_base<complex_type, matsubara_grid<Fermion>>::point point;
//using typename grid_base<complex_type, matsubara_grid<Fermion>>::point;
/** Inverse temperature. */
const real_type beta_;
/** Spacing between values. */
const real_type spacing_;
/** Min and max numbers of freq. - useful for searching. */
const int w_min_, w_max_;
matsubara_grid(int min, int max, real_type beta);
matsubara_grid(const matsubara_grid &rhs);
matsubara_grid(matsubara_grid&& rhs);
int getNumber(complex_type in) const;
double beta() const { return beta_; }
point find_nearest(complex_type in) const;
template <class Obj> auto integrate(const Obj &in) const -> decltype(in(vals_[0]));
template <class Obj> auto prod(const Obj &in) const -> decltype(in(vals_[0]));
//template <class Obj> auto gridIntegrate(const std::vector<Obj> &in) const -> Obj;
template <class Obj> auto eval(Obj &in, complex_type x) const ->decltype(in[0]);
//template <class Obj> auto eval(Obj &in, point x) const ->decltype(in[0]);
//using base::eval;
};
typedef matsubara_grid<1> fmatsubara_grid;
typedef matsubara_grid<0> bmatsubara_grid;
//
// matsubara_grid implementations
//
template <bool F>
matsubara_grid<F>::matsubara_grid(int min, int max, real_type beta):
//grid_base<complex_type, matsubara_grid<F>>(min,max,std::bind(Matsubara<F>, std::placeholders::_1, beta)),
grid_base<complex_type, matsubara_grid<F>>(min,max,[beta](int n){return Matsubara<F>(n,beta);}),
beta_(beta),
spacing_(PI/beta),
w_min_(min),
w_max_(max)
{
}
template <bool F>
matsubara_grid<F>::matsubara_grid(const matsubara_grid<F> &rhs) :
grid_base<complex_type, matsubara_grid<F>>(rhs.vals_),
beta_(rhs.beta_),
spacing_(rhs.spacing_),
w_min_(rhs.w_min_),
w_max_(rhs.w_max_)
{
}
template <bool F>
matsubara_grid<F>::matsubara_grid(matsubara_grid<F>&& rhs):
grid_base<complex_type, matsubara_grid>(rhs.vals_),
beta_(rhs.beta_),
spacing_(rhs.spacing_),
w_min_(rhs.w_min_),
w_max_(rhs.w_max_)
{
}
template <bool F>
template <class Obj>
auto matsubara_grid<F>::integrate(const Obj &in) const -> decltype(in(vals_[0]))
{
decltype(in(this->vals_[0])) R = in(this->vals_[0]);
R=std::accumulate(vals_.begin()+1, vals_.end(), R,[&](decltype(in(vals_[0]))& y,decltype(vals_[0]) &x) {return y+in(x);});
return R/beta_;
}
template <bool F>
template <class Obj>
auto matsubara_grid<F>::prod(const Obj &in) const -> decltype(in(vals_[0]))
{
// fix prod for more numerical stability
decltype(in(vals_[0])) R = in(vals_[0]);
R=std::accumulate(vals_.begin()+1, vals_.end(), R,[&](decltype(in(vals_[0]))& y,decltype(vals_[0]) &x) {return y*in(x);});
//decltype(in(vals_[0])) R = in(vals_[vals_.size()/2]);
//R=std::accumulate(vals_.begin()+1+vals_.size()/2, vals_.end(), R,[&](decltype(in(vals_[0]))& y,decltype(vals_[0]) &x) {DEBUG(x << "|" << in(x) << "|" << y << "->" << y*in(x)); return y*in(x);});
//R=std::accumulate(vals_.begin(), vals_.begin()+vals_.size()/2, R,[&](decltype(in(vals_[0]))& y,decltype(vals_[0]) &x) {DEBUG(x << "|" << in(x) << "|" << y << "->" << y*in(x)); return y*in(x);});
return R;
}
template <bool F>
inline typename matsubara_grid<F>::point matsubara_grid<F>::find_nearest (complex_type in) const
{
int n=getNumber(in);
#ifndef NDEBUG
//DEBUG("Invoking matsubara find");
#endif
if (n>=w_min_ && n<w_max_) { return vals_[n-w_min_]; }
else {
#ifndef NDEBUG
//ERROR("Couldn't find the point");
#endif
if (n<w_min_) return vals_[0];
else return vals_[vals_.size()-1];
};
}
template <bool F>
inline int matsubara_grid<F>::getNumber(complex_type in) const
{
assert (std::abs(real(in))<std::numeric_limits<real_type>::epsilon());
return std::lround(imag(in)/spacing_-F)/2;
};
template <bool F>
template <class Obj>
inline auto matsubara_grid<F>::eval(Obj &in, complex_type x) const ->decltype(in[0])
{
const auto find_result=this->find_nearest(x);
if (!tools::is_float_equal<complex_type>(x,find_result.val_)) { throw (ex_wrong_index()); }
return in[find_result.index_];
}
} // end of namespace gftools
<|endoftext|> |
<commit_before>/*
* PyDIP 3.0, Python bindings for DIPlib 3.0
*
* (c)2017, Flagship Biosciences, Inc., written by Cris Luengo.
*
* 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 "pydip.h"
#include "diplib/measurement.h"
dip::MeasurementTool measurementTool;
template< typename MeasurementValues >
py::handle MeasurementValuesToList( MeasurementValues values ) {
py::list list( values.size());
py::ssize_t index = 0;
for( auto& value: values ) {
PyList_SET_ITEM( list.ptr(), index++, py::cast( value ).release().ptr() );
}
return list.release();
}
void init_measurement( py::module& m ) {
auto mm = m.def_submodule("MeasurementTool", "A tool to quantify objects in an image.");
// dip::Measurement::FeatureInformation
auto fInfo = py::class_< dip::Measurement::FeatureInformation >( mm, "FeatureInformation", "Information about one measurement feature." );
fInfo.def( "__repr__", []( dip::Measurement::FeatureInformation const& self ) {
std::ostringstream os;
os << "<FeatureInformation: name = " << self.name << ", numberValues = " << self.numberValues << ">";
return os.str();
} );
fInfo.def_readonly( "name", &dip::Measurement::FeatureInformation::name );
fInfo.def_readonly( "startColumn", &dip::Measurement::FeatureInformation::startColumn );
fInfo.def_readonly( "numberValues", &dip::Measurement::FeatureInformation::numberValues );
// dip::Feature::ValueInformation
auto vInfo = py::class_< dip::Feature::ValueInformation >( mm, "ValueInformation", "Information about one measurement feature value." );
vInfo.def( "__repr__", []( dip::Feature::ValueInformation const& self ) {
std::ostringstream os;
os << "<ValueInformation: name = " << self.name << ", units = " << self.units << ">";
return os.str();
} );
vInfo.def_readonly( "name", &dip::Feature::ValueInformation::name );
vInfo.def_readonly( "units", &dip::Feature::ValueInformation::units );
// dip::Measurement::IteratorFeature
auto feat = py::class_< dip::Measurement::IteratorFeature >( mm, "Feature", "A Measurement table column group representing the results for one\nfeature." );
feat.def( "__repr__", []( dip::Measurement::IteratorFeature const& self ) {
std::ostringstream os;
os << "<MeasurementFeature for feature " << self.FeatureName() << " and " << self.NumberOfObjects() << " objects>";
return os.str();
} );
feat.def( "__getitem__", []( dip::Measurement::IteratorFeature const& self, dip::uint objectID ) { return MeasurementValuesToList( self[ objectID ] ); }, "objectID"_a );
feat.def( "FeatureName", &dip::Measurement::IteratorFeature::FeatureName );
feat.def( "NumberOfValues", &dip::Measurement::IteratorFeature::NumberOfValues );
feat.def( "NumberOfObjects", &dip::Measurement::IteratorFeature::NumberOfObjects );
feat.def( "Objects", &dip::Measurement::IteratorFeature::Objects );
// dip::Measurement::IteratorObject
auto obj = py::class_< dip::Measurement::IteratorObject >( mm, "Object", "A Measurement table row representing the results for one object." );
obj.def( "__repr__", []( dip::Measurement::IteratorObject const& self ) {
std::ostringstream os;
os << "<MeasurementObject with " << self.NumberOfFeatures() << " features for object " << self.ObjectID() << ">";
return os.str();
} );
obj.def( "__getitem__", []( dip::Measurement::IteratorObject const& self, dip::String const& name ) { return MeasurementValuesToList( self[ name ] ); }, "name"_a );
obj.def( "ObjectID", &dip::Measurement::IteratorObject::ObjectID );
obj.def( "NumberOfFeatures", &dip::Measurement::IteratorObject::NumberOfFeatures );
obj.def( "Features", &dip::Measurement::IteratorObject::Features );
// dip::Measurement
auto meas = py::class_< dip::Measurement >( mm, "Measurement", "The result of a call to PyDIP.Measure, a table with a column group for\neach feature and a row for each object." );
meas.def( "__repr__", []( dip::Measurement const& self ) {
std::ostringstream os;
os << "<Measurement with " << self.NumberOfFeatures() << " features for " << self.NumberOfObjects() << " objects>";
return os.str();
} );
meas.def( "__str__", []( dip::Measurement const& self ) { std::ostringstream os; os << self; return os.str(); } );
meas.def( "__getitem__", py::overload_cast< dip::uint >( &dip::Measurement::operator[], py::const_ ), "objectID"_a, py::return_value_policy::reference_internal );
meas.def( "__getitem__", py::overload_cast< dip::String const& >( &dip::Measurement::operator[], py::const_ ), "name"_a, py::return_value_policy::reference_internal );
meas.def( "FeatureExists", &dip::Measurement::FeatureExists );
meas.def( "Features", &dip::Measurement::Features );
meas.def( "NumberOfFeatures", &dip::Measurement::NumberOfFeatures );
meas.def( "Values", py::overload_cast< dip::String const& >( &dip::Measurement::Values, py::const_ ), "name"_a );
meas.def( "Values", py::overload_cast<>( &dip::Measurement::Values, py::const_ ));
meas.def( "NumberOfValues", py::overload_cast< dip::String const& >( &dip::Measurement::NumberOfValues, py::const_ ), "name"_a );
meas.def( "NumberOfValues", py::overload_cast<>( &dip::Measurement::NumberOfValues, py::const_ ));
meas.def( "ObjectExists", &dip::Measurement::ObjectExists );
meas.def( "Objects", &dip::Measurement::Objects );
meas.def( "NumberOfObjects", &dip::Measurement::NumberOfObjects );
meas.def( py::self + py::self );
// dip::MeasurementTool
mm.def( "Measure", []( dip::Image const& label, dip::Image const& grey, dip::StringArray const& features, dip::UnsignedArray const& objectIDs, dip::uint connectivity ) {
return measurementTool.Measure( label, grey, features, objectIDs, connectivity );
}, "label"_a, "grey"_a, "features"_a, "objectIDs"_a = dip::StringArray{}, "connectivity"_a = 0 );
mm.def( "Features", []() {
auto features = measurementTool.Features();
std::vector< std::tuple< dip::String, dip::String >> out;
for( auto const& f : features ) {
dip::String description = f.description;
if( f.needsGreyValue ) {
description += "*";
}
out.emplace_back( f.name, description );
}
return out;
} );
// Other functions
m.def( "ObjectToMeasurement", py::overload_cast< dip::Image const&, dip::Measurement::IteratorFeature const& >( &dip::ObjectToMeasurement ), "label"_a, "featureValues"_a );
m.def( "WriteCSV", &dip::WriteCSV, "measurement"_a, "filename"_a, "options"_a = dip::StringSet{} );
m.def( "Minimum", py::overload_cast< dip::Measurement::IteratorFeature const& >( &dip::Minimum ), "featureValues"_a );
m.def( "Maximum", py::overload_cast< dip::Measurement::IteratorFeature const& >( &dip::Maximum ), "featureValues"_a );
m.def( "Percentile", py::overload_cast< dip::Measurement::IteratorFeature const&, dip::dfloat >( &dip::Percentile ), "featureValues"_a, "percentile"_a );
m.def( "Median", py::overload_cast< dip::Measurement::IteratorFeature const& >( &dip::Median ), "featureValues"_a );
m.def( "Mean", py::overload_cast< dip::Measurement::IteratorFeature const& >( &dip::Mean ), "featureValues"_a );
m.def( "MaximumAndMinimum", []( dip::Measurement::IteratorFeature const& featureValues ) {
dip::MinMaxAccumulator acc = dip::MaximumAndMinimum( featureValues );
return py::make_tuple( acc.Minimum(), acc.Maximum() ).release();
}, "featureValues"_a );
m.def( "SampleStatistics", []( dip::Measurement::IteratorFeature const& featureValues ) {
dip::StatisticsAccumulator acc = dip::SampleStatistics( featureValues );
return py::make_tuple( acc.Mean(), acc.Variance(), acc.Skewness(), acc.ExcessKurtosis() ).release();
}, "featureValues"_a );
}
<commit_msg>Added default grey image in PyDIP `MeasurementTool.Measure` function. Fixes root cause of #6.<commit_after>/*
* PyDIP 3.0, Python bindings for DIPlib 3.0
*
* (c)2017, Flagship Biosciences, Inc., written by Cris Luengo.
*
* 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 "pydip.h"
#include "diplib/measurement.h"
dip::MeasurementTool measurementTool;
template< typename MeasurementValues >
py::handle MeasurementValuesToList( MeasurementValues values ) {
py::list list( values.size());
py::ssize_t index = 0;
for( auto& value: values ) {
PyList_SET_ITEM( list.ptr(), index++, py::cast( value ).release().ptr() );
}
return list.release();
}
void init_measurement( py::module& m ) {
auto mm = m.def_submodule("MeasurementTool", "A tool to quantify objects in an image.");
// dip::Measurement::FeatureInformation
auto fInfo = py::class_< dip::Measurement::FeatureInformation >( mm, "FeatureInformation", "Information about one measurement feature." );
fInfo.def( "__repr__", []( dip::Measurement::FeatureInformation const& self ) {
std::ostringstream os;
os << "<FeatureInformation: name = " << self.name << ", numberValues = " << self.numberValues << ">";
return os.str();
} );
fInfo.def_readonly( "name", &dip::Measurement::FeatureInformation::name );
fInfo.def_readonly( "startColumn", &dip::Measurement::FeatureInformation::startColumn );
fInfo.def_readonly( "numberValues", &dip::Measurement::FeatureInformation::numberValues );
// dip::Feature::ValueInformation
auto vInfo = py::class_< dip::Feature::ValueInformation >( mm, "ValueInformation", "Information about one measurement feature value." );
vInfo.def( "__repr__", []( dip::Feature::ValueInformation const& self ) {
std::ostringstream os;
os << "<ValueInformation: name = " << self.name << ", units = " << self.units << ">";
return os.str();
} );
vInfo.def_readonly( "name", &dip::Feature::ValueInformation::name );
vInfo.def_readonly( "units", &dip::Feature::ValueInformation::units );
// dip::Measurement::IteratorFeature
auto feat = py::class_< dip::Measurement::IteratorFeature >( mm, "Feature", "A Measurement table column group representing the results for one\nfeature." );
feat.def( "__repr__", []( dip::Measurement::IteratorFeature const& self ) {
std::ostringstream os;
os << "<MeasurementFeature for feature " << self.FeatureName() << " and " << self.NumberOfObjects() << " objects>";
return os.str();
} );
feat.def( "__getitem__", []( dip::Measurement::IteratorFeature const& self, dip::uint objectID ) { return MeasurementValuesToList( self[ objectID ] ); }, "objectID"_a );
feat.def( "FeatureName", &dip::Measurement::IteratorFeature::FeatureName );
feat.def( "NumberOfValues", &dip::Measurement::IteratorFeature::NumberOfValues );
feat.def( "NumberOfObjects", &dip::Measurement::IteratorFeature::NumberOfObjects );
feat.def( "Objects", &dip::Measurement::IteratorFeature::Objects );
// dip::Measurement::IteratorObject
auto obj = py::class_< dip::Measurement::IteratorObject >( mm, "Object", "A Measurement table row representing the results for one object." );
obj.def( "__repr__", []( dip::Measurement::IteratorObject const& self ) {
std::ostringstream os;
os << "<MeasurementObject with " << self.NumberOfFeatures() << " features for object " << self.ObjectID() << ">";
return os.str();
} );
obj.def( "__getitem__", []( dip::Measurement::IteratorObject const& self, dip::String const& name ) { return MeasurementValuesToList( self[ name ] ); }, "name"_a );
obj.def( "ObjectID", &dip::Measurement::IteratorObject::ObjectID );
obj.def( "NumberOfFeatures", &dip::Measurement::IteratorObject::NumberOfFeatures );
obj.def( "Features", &dip::Measurement::IteratorObject::Features );
// dip::Measurement
auto meas = py::class_< dip::Measurement >( mm, "Measurement", "The result of a call to PyDIP.Measure, a table with a column group for\neach feature and a row for each object." );
meas.def( "__repr__", []( dip::Measurement const& self ) {
std::ostringstream os;
os << "<Measurement with " << self.NumberOfFeatures() << " features for " << self.NumberOfObjects() << " objects>";
return os.str();
} );
meas.def( "__str__", []( dip::Measurement const& self ) { std::ostringstream os; os << self; return os.str(); } );
meas.def( "__getitem__", py::overload_cast< dip::uint >( &dip::Measurement::operator[], py::const_ ), "objectID"_a, py::return_value_policy::reference_internal );
meas.def( "__getitem__", py::overload_cast< dip::String const& >( &dip::Measurement::operator[], py::const_ ), "name"_a, py::return_value_policy::reference_internal );
meas.def( "FeatureExists", &dip::Measurement::FeatureExists );
meas.def( "Features", &dip::Measurement::Features );
meas.def( "NumberOfFeatures", &dip::Measurement::NumberOfFeatures );
meas.def( "Values", py::overload_cast< dip::String const& >( &dip::Measurement::Values, py::const_ ), "name"_a );
meas.def( "Values", py::overload_cast<>( &dip::Measurement::Values, py::const_ ));
meas.def( "NumberOfValues", py::overload_cast< dip::String const& >( &dip::Measurement::NumberOfValues, py::const_ ), "name"_a );
meas.def( "NumberOfValues", py::overload_cast<>( &dip::Measurement::NumberOfValues, py::const_ ));
meas.def( "ObjectExists", &dip::Measurement::ObjectExists );
meas.def( "Objects", &dip::Measurement::Objects );
meas.def( "NumberOfObjects", &dip::Measurement::NumberOfObjects );
meas.def( py::self + py::self );
// dip::MeasurementTool
mm.def( "Measure", []( dip::Image const& label, dip::Image const& grey, dip::StringArray const& features, dip::UnsignedArray const& objectIDs, dip::uint connectivity ) {
return measurementTool.Measure( label, grey, features, objectIDs, connectivity );
}, "label"_a, "grey"_a = dip::Image{}, "features"_a = dip::StringArray{ "Size" }, "objectIDs"_a = dip::StringArray{}, "connectivity"_a = 0 );
mm.def( "Features", []() {
auto features = measurementTool.Features();
std::vector< std::tuple< dip::String, dip::String >> out;
for( auto const& f : features ) {
dip::String description = f.description;
if( f.needsGreyValue ) {
description += "*";
}
out.emplace_back( f.name, description );
}
return out;
} );
// Other functions
m.def( "ObjectToMeasurement", py::overload_cast< dip::Image const&, dip::Measurement::IteratorFeature const& >( &dip::ObjectToMeasurement ), "label"_a, "featureValues"_a );
m.def( "WriteCSV", &dip::WriteCSV, "measurement"_a, "filename"_a, "options"_a = dip::StringSet{} );
m.def( "Minimum", py::overload_cast< dip::Measurement::IteratorFeature const& >( &dip::Minimum ), "featureValues"_a );
m.def( "Maximum", py::overload_cast< dip::Measurement::IteratorFeature const& >( &dip::Maximum ), "featureValues"_a );
m.def( "Percentile", py::overload_cast< dip::Measurement::IteratorFeature const&, dip::dfloat >( &dip::Percentile ), "featureValues"_a, "percentile"_a );
m.def( "Median", py::overload_cast< dip::Measurement::IteratorFeature const& >( &dip::Median ), "featureValues"_a );
m.def( "Mean", py::overload_cast< dip::Measurement::IteratorFeature const& >( &dip::Mean ), "featureValues"_a );
m.def( "MaximumAndMinimum", []( dip::Measurement::IteratorFeature const& featureValues ) {
dip::MinMaxAccumulator acc = dip::MaximumAndMinimum( featureValues );
return py::make_tuple( acc.Minimum(), acc.Maximum() ).release();
}, "featureValues"_a );
m.def( "SampleStatistics", []( dip::Measurement::IteratorFeature const& featureValues ) {
dip::StatisticsAccumulator acc = dip::SampleStatistics( featureValues );
return py::make_tuple( acc.Mean(), acc.Variance(), acc.Skewness(), acc.ExcessKurtosis() ).release();
}, "featureValues"_a );
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2010-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include <pluginlib/class_list_macros.h>
#include <nodelet/nodelet.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl_conversions/pcl_conversions.h>
#include <tf/transform_listener.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/CameraInfo.h>
#include <stereo_msgs/DisparityImage.h>
#include <image_transport/image_transport.h>
#include <image_transport/subscriber_filter.h>
#include <image_geometry/pinhole_camera_model.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <message_filters/subscriber.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/highgui/highgui.hpp>
#include <rtabmap_ros/MsgConversion.h>
#include "rtabmap/core/util3d.h"
#include "rtabmap/core/util3d_filtering.h"
#include "rtabmap/core/util3d_mapping.h"
#include "rtabmap/core/util3d_transforms.h"
namespace rtabmap_ros
{
class ObstaclesDetection : public nodelet::Nodelet
{
public:
ObstaclesDetection() :
frameId_("base_link"),
normalEstimationRadius_(0.05),
groundNormalAngle_(M_PI_4),
minClusterSize_(20),
maxFloorHeight_(-1),
maxObstaclesHeight_(1.5),
waitForTransform_(false),
simpleSegmentation_(false)
{}
virtual ~ObstaclesDetection()
{}
private:
virtual void onInit()
{
ros::NodeHandle & nh = getNodeHandle();
ros::NodeHandle & pnh = getPrivateNodeHandle();
int queueSize = 10;
pnh.param("queue_size", queueSize, queueSize);
pnh.param("frame_id", frameId_, frameId_);
pnh.param("normal_estimation_radius", normalEstimationRadius_, normalEstimationRadius_);
pnh.param("ground_normal_angle", groundNormalAngle_, groundNormalAngle_);
pnh.param("min_cluster_size", minClusterSize_, minClusterSize_);
pnh.param("max_obstacles_height", maxObstaclesHeight_, maxObstaclesHeight_);
pnh.param("max_floor_height", maxFloorHeight_, maxFloorHeight_);
pnh.param("wait_for_transform", waitForTransform_, waitForTransform_);
pnh.param("simple_segmentation", simpleSegmentation_, simpleSegmentation_);
cloudSub_ = nh.subscribe("cloud", 1, &ObstaclesDetection::callback, this);
groundPub_ = nh.advertise<sensor_msgs::PointCloud2>("ground", 1);
obstaclesPub_ = nh.advertise<sensor_msgs::PointCloud2>("obstacles", 1);
this->_lastFrameTime = ros::Time::now();
}
void callback(const sensor_msgs::PointCloud2ConstPtr & cloudMsg)
{
if (groundPub_.getNumSubscribers() == 0 && obstaclesPub_.getNumSubscribers() == 0)
{
// no one wants the results
return;
}
rtabmap::Transform localTransform;
try
{
if(waitForTransform_)
{
if(!tfListener_.waitForTransform(frameId_, cloudMsg->header.frame_id, cloudMsg->header.stamp, ros::Duration(1)))
{
ROS_ERROR("Could not get transform from %s to %s after 1 second!", frameId_.c_str(), cloudMsg->header.frame_id.c_str());
return;
}
}
tf::StampedTransform tmp;
tfListener_.lookupTransform(frameId_, cloudMsg->header.frame_id, cloudMsg->header.stamp, tmp);
localTransform = rtabmap_ros::transformFromTF(tmp);
}
catch(tf::TransformException & ex)
{
ROS_ERROR("%s",ex.what());
return;
}
pcl::PointCloud<pcl::PointXYZ>::Ptr originalCloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::fromROSMsg(*cloudMsg, *originalCloud);
if(originalCloud->size() == 0)
{
ROS_ERROR("Recieved empty point cloud!");
return;
}
originalCloud = rtabmap::util3d::transformPointCloud(originalCloud, localTransform);
/////////////////////////////////////////////////////////////////////////////
pcl::PointCloud<pcl::PointXYZ>::Ptr hypotheticalGroundCloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr obstaclesCloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::IndicesPtr ground, obstacles;
pcl::PointCloud<pcl::PointXYZ>::Ptr groundCloud(new pcl::PointCloud<pcl::PointXYZ>);
ros::Time lasttime = ros::Time::now();
if (!simpleSegmentation_){
ROS_ERROR("1-1");
hypotheticalGroundCloud = rtabmap::util3d::passThrough(originalCloud, "z", std::numeric_limits<int>::min(), maxFloorHeight_);
ROS_ERROR("1-2");
rtabmap::util3d::segmentObstaclesFromGround<pcl::PointXYZ>(hypotheticalGroundCloud,
ground, obstacles, normalEstimationRadius_, groundNormalAngle_, minClusterSize_);
ROS_ERROR("1-3");
if(ground.get() && ground->size())
{
pcl::copyPointCloud(*hypotheticalGroundCloud, *ground, *groundCloud);
}
ROS_ERROR("1-4");
obstaclesCloud = rtabmap::util3d::passThrough(originalCloud, "z", maxFloorHeight_, maxObstaclesHeight_);
ROS_ERROR("1-5");
if(obstacles.get() && obstacles->size())
{
pcl::PointCloud<pcl::PointXYZ>::Ptr obstaclesNearFloorCloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::copyPointCloud(*hypotheticalGroundCloud, *obstacles, *obstaclesNearFloorCloud);
*obstaclesCloud += *obstaclesNearFloorCloud;
}
ROS_ERROR("R 44444444444444444444444444444");
}
else{
obstaclesCloud = rtabmap::util3d::passThrough(originalCloud, "z", maxFloorHeight_, maxObstaclesHeight_);
}
if(groundPub_.getNumSubscribers())
{
sensor_msgs::PointCloud2 rosCloud;
pcl::toROSMsg(*groundCloud, rosCloud);
rosCloud.header.stamp = cloudMsg->header.stamp;
rosCloud.header.frame_id = frameId_;
//publish the message
groundPub_.publish(rosCloud);
}
if(obstaclesPub_.getNumSubscribers())
{
sensor_msgs::PointCloud2 rosCloud;
pcl::toROSMsg(*obstaclesCloud, rosCloud);
rosCloud.header.stamp = cloudMsg->header.stamp;
rosCloud.header.frame_id = frameId_;
//publish the message
obstaclesPub_.publish(rosCloud);
}
ros::Time curtime = ros::Time::now();
ros::Duration process_duration = curtime - lasttime;
ros::Duration between_frames = curtime - this->_lastFrameTime;
this->_lastFrameTime = curtime;
std::stringstream buffer;
buffer << "cloud=" << originalCloud->size() << " ground=" << hypotheticalGroundCloud->size() << " floor=" << ground->size() << " obst=" << obstacles->size();
buffer << " t=" << process_duration.toSec() << "s; " << (1./between_frames.toSec()) << "Hz";
//ROS_ERROR("3%s: %s", this->getName().c_str(), buffer.str().c_str());
}
private:
std::string frameId_;
double normalEstimationRadius_;
double groundNormalAngle_;
int minClusterSize_;
double maxObstaclesHeight_;
double maxFloorHeight_;
bool waitForTransform_;
bool simpleSegmentation_;
tf::TransformListener tfListener_;
ros::Publisher groundPub_;
ros::Publisher obstaclesPub_;
ros::Subscriber cloudSub_;
ros::Time _lastFrameTime;
};
PLUGINLIB_EXPORT_CLASS(rtabmap_ros::ObstaclesDetection, nodelet::Nodelet);
}
<commit_msg>Comment for debugging<commit_after>/*
Copyright (c) 2010-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <ros/ros.h>
#include <pluginlib/class_list_macros.h>
#include <nodelet/nodelet.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl_conversions/pcl_conversions.h>
#include <tf/transform_listener.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/CameraInfo.h>
#include <stereo_msgs/DisparityImage.h>
#include <image_transport/image_transport.h>
#include <image_transport/subscriber_filter.h>
#include <image_geometry/pinhole_camera_model.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <message_filters/subscriber.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/highgui/highgui.hpp>
#include <rtabmap_ros/MsgConversion.h>
#include "rtabmap/core/util3d.h"
#include "rtabmap/core/util3d_filtering.h"
#include "rtabmap/core/util3d_mapping.h"
#include "rtabmap/core/util3d_transforms.h"
namespace rtabmap_ros
{
class ObstaclesDetection : public nodelet::Nodelet
{
public:
ObstaclesDetection() :
frameId_("base_link"),
normalEstimationRadius_(0.05),
groundNormalAngle_(M_PI_4),
minClusterSize_(20),
maxFloorHeight_(-1),
maxObstaclesHeight_(1.5),
waitForTransform_(false),
simpleSegmentation_(false)
{}
virtual ~ObstaclesDetection()
{}
private:
virtual void onInit()
{
ros::NodeHandle & nh = getNodeHandle();
ros::NodeHandle & pnh = getPrivateNodeHandle();
int queueSize = 10;
pnh.param("queue_size", queueSize, queueSize);
pnh.param("frame_id", frameId_, frameId_);
pnh.param("normal_estimation_radius", normalEstimationRadius_, normalEstimationRadius_);
pnh.param("ground_normal_angle", groundNormalAngle_, groundNormalAngle_);
pnh.param("min_cluster_size", minClusterSize_, minClusterSize_);
pnh.param("max_obstacles_height", maxObstaclesHeight_, maxObstaclesHeight_);
pnh.param("max_floor_height", maxFloorHeight_, maxFloorHeight_);
pnh.param("wait_for_transform", waitForTransform_, waitForTransform_);
pnh.param("simple_segmentation", simpleSegmentation_, simpleSegmentation_);
cloudSub_ = nh.subscribe("cloud", 1, &ObstaclesDetection::callback, this);
groundPub_ = nh.advertise<sensor_msgs::PointCloud2>("ground", 1);
obstaclesPub_ = nh.advertise<sensor_msgs::PointCloud2>("obstacles", 1);
this->_lastFrameTime = ros::Time::now();
}
void callback(const sensor_msgs::PointCloud2ConstPtr & cloudMsg)
{
if (groundPub_.getNumSubscribers() == 0 && obstaclesPub_.getNumSubscribers() == 0)
{
// no one wants the results
return;
}
rtabmap::Transform localTransform;
try
{
if(waitForTransform_)
{
if(!tfListener_.waitForTransform(frameId_, cloudMsg->header.frame_id, cloudMsg->header.stamp, ros::Duration(1)))
{
ROS_ERROR("Could not get transform from %s to %s after 1 second!", frameId_.c_str(), cloudMsg->header.frame_id.c_str());
return;
}
}
tf::StampedTransform tmp;
tfListener_.lookupTransform(frameId_, cloudMsg->header.frame_id, cloudMsg->header.stamp, tmp);
localTransform = rtabmap_ros::transformFromTF(tmp);
}
catch(tf::TransformException & ex)
{
ROS_ERROR("%s",ex.what());
return;
}
pcl::PointCloud<pcl::PointXYZ>::Ptr originalCloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::fromROSMsg(*cloudMsg, *originalCloud);
if(originalCloud->size() == 0)
{
ROS_ERROR("Recieved empty point cloud!");
return;
}
originalCloud = rtabmap::util3d::transformPointCloud(originalCloud, localTransform);
/////////////////////////////////////////////////////////////////////////////
pcl::PointCloud<pcl::PointXYZ>::Ptr hypotheticalGroundCloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr obstaclesCloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::IndicesPtr ground, obstacles;
pcl::PointCloud<pcl::PointXYZ>::Ptr groundCloud(new pcl::PointCloud<pcl::PointXYZ>);
ros::Time lasttime = ros::Time::now();
if (!simpleSegmentation_){
ROS_ERROR("1-1");
hypotheticalGroundCloud = rtabmap::util3d::passThrough(originalCloud, "z", std::numeric_limits<int>::min(), maxFloorHeight_);
ROS_ERROR("1-2");
rtabmap::util3d::segmentObstaclesFromGround<pcl::PointXYZ>(hypotheticalGroundCloud,
ground, obstacles, normalEstimationRadius_, groundNormalAngle_, minClusterSize_);
ROS_ERROR("1-3");
if(ground.get() && ground->size())
{
pcl::copyPointCloud(*hypotheticalGroundCloud, *ground, *groundCloud);
}
ROS_ERROR("1-4");
obstaclesCloud = rtabmap::util3d::passThrough(originalCloud, "z", maxFloorHeight_, maxObstaclesHeight_);
ROS_ERROR("1-5");
if(obstacles.get() && obstacles->size())
{
pcl::PointCloud<pcl::PointXYZ>::Ptr obstaclesNearFloorCloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::copyPointCloud(*hypotheticalGroundCloud, *obstacles, *obstaclesNearFloorCloud);
*obstaclesCloud += *obstaclesNearFloorCloud;
}
ROS_ERROR("R 44444444444444444444444444444");
}
else{
ROS_ERROR("2-1");
obstaclesCloud = rtabmap::util3d::passThrough(originalCloud, "z", maxFloorHeight_, maxObstaclesHeight_);
ROS_ERROR("2-2");
}
if(groundPub_.getNumSubscribers())
{
sensor_msgs::PointCloud2 rosCloud;
pcl::toROSMsg(*groundCloud, rosCloud);
rosCloud.header.stamp = cloudMsg->header.stamp;
rosCloud.header.frame_id = frameId_;
//publish the message
groundPub_.publish(rosCloud);
}
if(obstaclesPub_.getNumSubscribers())
{
sensor_msgs::PointCloud2 rosCloud;
pcl::toROSMsg(*obstaclesCloud, rosCloud);
rosCloud.header.stamp = cloudMsg->header.stamp;
rosCloud.header.frame_id = frameId_;
//publish the message
obstaclesPub_.publish(rosCloud);
}
ros::Time curtime = ros::Time::now();
ros::Duration process_duration = curtime - lasttime;
ros::Duration between_frames = curtime - this->_lastFrameTime;
this->_lastFrameTime = curtime;
std::stringstream buffer;
buffer << "cloud=" << originalCloud->size() << " ground=" << hypotheticalGroundCloud->size() << " floor=" << ground->size() << " obst=" << obstacles->size();
buffer << " t=" << process_duration.toSec() << "s; " << (1./between_frames.toSec()) << "Hz";
//ROS_ERROR("3%s: %s", this->getName().c_str(), buffer.str().c_str());
}
private:
std::string frameId_;
double normalEstimationRadius_;
double groundNormalAngle_;
int minClusterSize_;
double maxObstaclesHeight_;
double maxFloorHeight_;
bool waitForTransform_;
bool simpleSegmentation_;
tf::TransformListener tfListener_;
ros::Publisher groundPub_;
ros::Publisher obstaclesPub_;
ros::Subscriber cloudSub_;
ros::Time _lastFrameTime;
};
PLUGINLIB_EXPORT_CLASS(rtabmap_ros::ObstaclesDetection, nodelet::Nodelet);
}
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Rice 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 the Rice 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: Mark Moll */
#include "ompl/control/PlannerData.h"
void ompl::control::PlannerData::clear(void)
{
base::PlannerData::clear();
controls.clear();
controlDurations.clear();
}
int ompl::control::PlannerData::recordEdge(const base::State *s1, const base::State *s2,
const Control* c, double duration)
{
int i = base::PlannerData::recordEdge(s1,s2);
if (i!=-1)
{
if (i >= (int) controls.size())
{
controls.resize(i+1);
controlDurations.resize(i+1);
}
controls[i].push_back(c);
controlDurations[i].push_back(duration);
}
return i;
}
<commit_msg>Removed control::PlannerData.cpp<commit_after><|endoftext|> |
<commit_before>// @(#)root/gpad:$Name: $:$Id: TDialogCanvas.cxx,v 1.3 2000/11/21 20:21:18 brun Exp $
// Author: Rene Brun 03/07/96
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TROOT.h"
#include "TDialogCanvas.h"
#include "TGroupButton.h"
#include "TText.h"
#include "TStyle.h"
ClassImp(TDialogCanvas)
//______________________________________________________________________________
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*
//*-* A DialogCanvas is a canvas specialized to set attributes.
//*-* It contains, in general, TGroupButton objects.
//*-* When the APPLY button is executed, the actions corresponding
//*-* to the active buttons are executed via the Interpreter.
//*-*
//*-* See examples in TAttLineCanvas, TAttFillCanvas, TAttTextCanvas, TAttMarkerCanvas
//______________________________________________________________________________
TDialogCanvas::TDialogCanvas() : TCanvas()
{
//*-*-*-*-*-*-*-*-*-*-*-*DialogCanvas default constructor*-*-*-*-*-*-*-*-*-*-*
//*-* ================================
}
//_____________________________________________________________________________
TDialogCanvas::TDialogCanvas(const char *name, const char *title, UInt_t ww, UInt_t wh)
: TCanvas(name,title,-ww,wh)
{
//*-*-*-*-*-*-*-*-*-*-*-*DialogCanvas constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* ========================
SetFillColor(36);
fEditable = kFALSE;
fRefObject = 0;
fRefPad = 0;
}
//______________________________________________________________________________
TDialogCanvas::~TDialogCanvas()
{
//*-*-*-*-*-*-*-*-*-*-*DialogCanvas default destructor*-*-*-*-*-*-*-*-*-*-*-*
//*-* ===============================
}
//______________________________________________________________________________
void TDialogCanvas::Apply(const char *action)
{
//*-*-*-*-*-*-*-*-*Called when the APPLY button is executed*-*-*-*-*-*-*-*-*-*-*
//*-* ========================================
SetCursor(kWatch);
TIter next(fPrimitives);
TObject *refobj = fRefObject;
TObject *obj;
TGroupButton *button;
if (!strcmp(action,"gStyle")) fRefObject = gStyle;
while ((obj = next())) {
if (obj->InheritsFrom(TGroupButton::Class())) {
button = (TGroupButton*)obj;
if (button->GetBorderMode() < 0) button->ExecuteAction();
}
}
fRefObject = refobj;
}
//______________________________________________________________________________
void TDialogCanvas::BuildStandardButtons()
{
//*-*-*-*-*-*-*-*-*Create APPLY, gStyle and CLOSE buttons*-*-*-*-*-*-*-*-*-*-*
//*-* ======================================
TGroupButton *apply = new TGroupButton("APPLY","Apply","",.05,.01,.3,.09);
apply->SetTextSize(0.55);
apply->SetBorderSize(3);
apply->SetFillColor(44);
apply->Draw();
apply = new TGroupButton("APPLY","gStyle","",.375,.01,.625,.09);
apply->SetTextSize(0.55);
apply->SetBorderSize(3);
apply->SetFillColor(44);
apply->Draw();
apply = new TGroupButton("APPLY","Close","",.70,.01,.95,.09);
apply->SetTextSize(0.55);
apply->SetBorderSize(3);
apply->SetFillColor(44);
apply->Draw();
}
//______________________________________________________________________________
void TDialogCanvas::Range(Double_t x1, Double_t y1, Double_t x2, Double_t y2)
{
//*-*-*-*-*-*-*-*-*-*-*Set world coordinate system for the pad*-*-*-*-*-*-*
//*-* =======================================
TPad::Range(x1,y1,x2,y2);
}
//______________________________________________________________________________
void TDialogCanvas::RecursiveRemove(TObject *obj)
{
//*-*-*-*-*-*-*-*Recursively remove object from a pad and its subpads*-*-*-*-*
//*-* ====================================================
TPad::RecursiveRemove(obj);
if (fRefObject == obj) fRefObject = 0;
if (fRefPad == obj) fRefPad = 0;
}
<commit_msg>Do not set the SetEditable flag in the default constructor. In the Apply function, force a call to Modified/Update for the selected pad.<commit_after>// @(#)root/gpad:$Name: $:$Id: TDialogCanvas.cxx,v 1.4 2001/01/12 08:27:47 brun Exp $
// Author: Rene Brun 03/07/96
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TROOT.h"
#include "TDialogCanvas.h"
#include "TGroupButton.h"
#include "TText.h"
#include "TStyle.h"
ClassImp(TDialogCanvas)
//______________________________________________________________________________
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*
//*-* A DialogCanvas is a canvas specialized to set attributes.
//*-* It contains, in general, TGroupButton objects.
//*-* When the APPLY button is executed, the actions corresponding
//*-* to the active buttons are executed via the Interpreter.
//*-*
//*-* See examples in TAttLineCanvas, TAttFillCanvas, TAttTextCanvas, TAttMarkerCanvas
//______________________________________________________________________________
TDialogCanvas::TDialogCanvas() : TCanvas()
{
//*-*-*-*-*-*-*-*-*-*-*-*DialogCanvas default constructor*-*-*-*-*-*-*-*-*-*-*
//*-* ================================
}
//_____________________________________________________________________________
TDialogCanvas::TDialogCanvas(const char *name, const char *title, UInt_t ww, UInt_t wh)
: TCanvas(name,title,-ww,wh)
{
//*-*-*-*-*-*-*-*-*-*-*-*DialogCanvas constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* ========================
SetFillColor(36);
fRefObject = 0;
fRefPad = 0;
}
//______________________________________________________________________________
TDialogCanvas::~TDialogCanvas()
{
//*-*-*-*-*-*-*-*-*-*-*DialogCanvas default destructor*-*-*-*-*-*-*-*-*-*-*-*
//*-* ===============================
}
//______________________________________________________________________________
void TDialogCanvas::Apply(const char *action)
{
//*-*-*-*-*-*-*-*-*Called when the APPLY button is executed*-*-*-*-*-*-*-*-*-*-*
//*-* ========================================
SetCursor(kWatch);
TIter next(fPrimitives);
TObject *refobj = fRefObject;
TObject *obj;
TGroupButton *button;
if (!strcmp(action,"gStyle")) fRefObject = gStyle;
while ((obj = next())) {
if (obj->InheritsFrom(TGroupButton::Class())) {
button = (TGroupButton*)obj;
if (button->GetBorderMode() < 0) button->ExecuteAction();
}
}
fRefObject = refobj;
gROOT->GetSelectedPad()->Modified();
gROOT->GetSelectedPad()->Update();
}
//______________________________________________________________________________
void TDialogCanvas::BuildStandardButtons()
{
//*-*-*-*-*-*-*-*-*Create APPLY, gStyle and CLOSE buttons*-*-*-*-*-*-*-*-*-*-*
//*-* ======================================
TGroupButton *apply = new TGroupButton("APPLY","Apply","",.05,.01,.3,.09);
apply->SetTextSize(0.55);
apply->SetBorderSize(3);
apply->SetFillColor(44);
apply->Draw();
apply = new TGroupButton("APPLY","gStyle","",.375,.01,.625,.09);
apply->SetTextSize(0.55);
apply->SetBorderSize(3);
apply->SetFillColor(44);
apply->Draw();
apply = new TGroupButton("APPLY","Close","",.70,.01,.95,.09);
apply->SetTextSize(0.55);
apply->SetBorderSize(3);
apply->SetFillColor(44);
apply->Draw();
}
//______________________________________________________________________________
void TDialogCanvas::Range(Double_t x1, Double_t y1, Double_t x2, Double_t y2)
{
//*-*-*-*-*-*-*-*-*-*-*Set world coordinate system for the pad*-*-*-*-*-*-*
//*-* =======================================
TPad::Range(x1,y1,x2,y2);
}
//______________________________________________________________________________
void TDialogCanvas::RecursiveRemove(TObject *obj)
{
//*-*-*-*-*-*-*-*Recursively remove object from a pad and its subpads*-*-*-*-*
//*-* ====================================================
TPad::RecursiveRemove(obj);
if (fRefObject == obj) fRefObject = 0;
if (fRefPad == obj) fRefPad = 0;
}
<|endoftext|> |
<commit_before>/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, 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.
// Internal Includes
#include <osvr/Common/ImagingComponent.h>
#include <osvr/Common/BaseDevice.h>
#include <osvr/Common/Serialization.h>
#include <osvr/Common/Buffer.h>
#include <osvr/Util/AlignedMemoryUniquePtr.h>
#include <osvr/Util/Flag.h>
#include <osvr/Util/Verbosity.h>
// Library/third-party includes
// - none
// Standard includes
#include <sstream>
#include <utility>
namespace osvr {
namespace common {
static inline uint32_t getBufferSize(OSVR_ImagingMetadata const &meta) {
return meta.height * meta.width * meta.depth * meta.channels;
}
namespace messages {
namespace {
template <typename T>
void process(OSVR_ImagingMetadata &meta, T &p) {
p(meta.height);
p(meta.width);
p(meta.channels);
p(meta.depth);
p(meta.type,
serialization::EnumAsIntegerTag<OSVR_ImagingValueType,
uint8_t>());
}
} // namespace
class ImageRegion::MessageSerialization {
public:
MessageSerialization(OSVR_ImagingMetadata const &meta,
OSVR_ImageBufferElement *imageData,
OSVR_ChannelCount sensor)
: m_meta(meta),
m_imgBuf(imageData,
[](OSVR_ImageBufferElement *) {
}), // That's a null-deleter right there for you.
m_sensor(sensor) {}
MessageSerialization() : m_imgBuf(nullptr) {}
template <typename T>
void allocateBuffer(T &, size_t bytes, std::true_type const &) {
m_imgBuf = util::makeAlignedImageBuffer(bytes);
}
template <typename T>
void allocateBuffer(T &, size_t, std::false_type const &) {
// Does nothing if we're serializing.
}
template <typename T> void processMessage(T &p) {
process(m_meta, p);
auto bytes = getBufferSize(m_meta);
/// Allocate the matrix backing data, if we're deserializing
/// only.
allocateBuffer(p, bytes, p.isDeserialize());
p(m_imgBuf.get(),
serialization::AlignedDataBufferTag(bytes, m_meta.depth));
}
ImageData getData() const {
ImageData ret;
ret.sensor = m_sensor;
ret.metadata = m_meta;
ret.buffer = m_imgBuf;
return ret;
}
private:
OSVR_ImagingMetadata m_meta;
ImageBufferPtr m_imgBuf;
OSVR_ChannelCount m_sensor;
};
const char *ImageRegion::identifier() {
return "com.osvr.imaging.imageregion";
}
#ifdef OSVR_COMMON_IN_PROCESS_IMAGING
namespace {
struct InProcessMemoryMessage {
OSVR_ImagingMetadata metadata;
OSVR_ChannelCount sensor;
int buffer;
};
template <typename T>
void process(InProcessMemoryMessage &ipmmMsg, T &p) {
process(ipmmMsg.metadata, p);
p(ipmmMsg.sensor);
p(ipmmMsg.buffer);
}
} // namespace
const char *ImagePlacedInProcessMemory::identifier() {
return "com.osvr.imaging.imageplacedinprocessmemory";
}
class ImagePlacedInProcessMemory::MessageSerialization {
public:
MessageSerialization() {}
explicit MessageSerialization(InProcessMemoryMessage &&msg)
: m_msgData(std::move(msg)) {}
#if defined(_MSC_VER) && defined(_PREFAST_)
// @todo workaround for apparent bug in VS2013 /analyze
explicit MessageSerialization(InProcessMemoryMessage const &msg)
: m_msgData(msg) {}
#endif
template <typename T> void processMessage(T &p) {
process(m_msgData, p);
}
InProcessMemoryMessage const &getMessage() { return m_msgData; }
private:
InProcessMemoryMessage m_msgData;
};
#endif
namespace {
struct SharedMemoryMessage {
OSVR_ImagingMetadata metadata;
IPCRingBuffer::sequence_type seqNum;
OSVR_ChannelCount sensor;
IPCRingBuffer::abi_level_type abiLevel;
IPCRingBuffer::BackendType backend;
std::string shmName;
};
template <typename T>
void process(SharedMemoryMessage &shmMsg, T &p) {
process(shmMsg.metadata, p);
p(shmMsg.seqNum);
p(shmMsg.sensor);
p(shmMsg.abiLevel);
p(shmMsg.backend);
p(shmMsg.shmName);
}
} // namespace
class ImagePlacedInSharedMemory::MessageSerialization {
public:
MessageSerialization() {}
explicit MessageSerialization(SharedMemoryMessage &&msg)
: m_msgData(std::move(msg)) {}
#if defined(_MSC_VER) && defined(_PREFAST_)
/// @todo workaround for apparent bug in VS2013 /analyze
explicit MessageSerialization(SharedMemoryMessage const &msg)
: m_msgData(msg) {}
#endif
template <typename T> void processMessage(T &p) {
process(m_msgData, p);
}
SharedMemoryMessage const &getMessage() { return m_msgData; }
private:
SharedMemoryMessage m_msgData;
};
const char *ImagePlacedInSharedMemory::identifier() {
return "com.osvr.imaging.imageplacedinsharedmemory";
}
} // namespace messages
shared_ptr<ImagingComponent>
ImagingComponent::create(OSVR_ChannelCount numChan) {
shared_ptr<ImagingComponent> ret(new ImagingComponent(numChan));
return ret;
}
ImagingComponent::ImagingComponent(OSVR_ChannelCount numChan)
: m_numSensor(numChan) {}
void ImagingComponent::sendImageData(OSVR_ImagingMetadata metadata,
OSVR_ImageBufferElement *imageData,
OSVR_ChannelCount sensor,
OSVR_TimeValue const ×tamp) {
util::Flag dataSent;
#ifdef OSVR_COMMON_IN_PROCESS_IMAGING
dataSent += m_sendImageDataViaInProcessMemory(metadata, imageData,
sensor, timestamp);
#else
dataSent += m_sendImageDataViaSharedMemory(metadata, imageData, sensor,
timestamp);
#endif
dataSent +=
m_sendImageDataOnTheWire(metadata, imageData, sensor, timestamp);
if (dataSent) {
m_checkFirst(metadata);
}
}
#ifdef OSVR_COMMON_IN_PROCESS_IMAGING
bool ImagingComponent::m_sendImageDataViaInProcessMemory(
OSVR_ImagingMetadata metadata, OSVR_ImageBufferElement *imageData,
OSVR_ChannelCount sensor, OSVR_TimeValue const ×tamp) {
auto imageBufferSize = getBufferSize(metadata);
/// @todo Assuming we should be releasing this pointer from the control
/// of the unique_ptr that holds it now, rather than freeing?
auto imageBufferCopy = util::makeAlignedImageBuffer(imageBufferSize);
memcpy(imageBufferCopy.get(), imageData, imageBufferSize);
Buffer<> buf;
messages::ImagePlacedInProcessMemory::MessageSerialization
serialization(messages::InProcessMemoryMessage{
metadata, sensor, reinterpret_cast<int>(imageBufferCopy)});
serialize(buf, serialization);
m_getParent().packMessage(
buf, imagePlacedInProcessMemory.getMessageType(), timestamp);
return true;
}
#endif
bool ImagingComponent::m_sendImageDataViaSharedMemory(
OSVR_ImagingMetadata metadata, OSVR_ImageBufferElement *imageData,
OSVR_ChannelCount sensor, OSVR_TimeValue const ×tamp) {
m_growShmVecIfRequired(sensor);
uint32_t imageBufferSize = getBufferSize(metadata);
if (!m_shmBuf[sensor] ||
m_shmBuf[sensor]->getEntrySize() != imageBufferSize) {
// create or replace the shared memory ring buffer.
auto makeName = [](OSVR_ChannelCount sensor,
std::string const &devName) {
std::ostringstream os;
os << "com.osvr.imaging/" << devName << "/" << int(sensor);
return os.str();
};
m_shmBuf[sensor] = IPCRingBuffer::create(
IPCRingBuffer::Options(
makeName(sensor, m_getParent().getDeviceName()))
.setEntrySize(imageBufferSize));
}
if (!m_shmBuf[sensor]) {
OSVR_DEV_VERBOSE(
"Some issue creating shared memory for imaging, skipping out.");
return false;
}
auto &shm = *(m_shmBuf[sensor]);
auto seq = shm.put(imageData, imageBufferSize);
Buffer<> buf;
messages::ImagePlacedInSharedMemory::MessageSerialization serialization(
messages::SharedMemoryMessage{metadata, seq, sensor,
IPCRingBuffer::getABILevel(),
shm.getBackend(), shm.getName()});
serialize(buf, serialization);
m_getParent().packMessage(
buf, imagePlacedInSharedMemory.getMessageType(), timestamp);
return true;
}
bool ImagingComponent::m_sendImageDataOnTheWire(
OSVR_ImagingMetadata metadata, OSVR_ImageBufferElement *imageData,
OSVR_ChannelCount sensor, OSVR_TimeValue const ×tamp) {
/// @todo currently only handle 8bit data over network
if (metadata.depth != 1) {
return false;
}
Buffer<> buf;
messages::ImageRegion::MessageSerialization msg(metadata, imageData,
sensor);
serialize(buf, msg);
if (buf.size() > vrpn_CONNECTION_TCP_BUFLEN) {
#if 0
OSVR_DEV_VERBOSE("Skipping imaging message: size is "
<< buf.size() << " vs the maximum of "
<< vrpn_CONNECTION_TCP_BUFLEN);
#endif
return false;
}
m_getParent().packMessage(buf, imageRegion.getMessageType(), timestamp);
m_getParent().sendPending();
return true;
}
int VRPN_CALLBACK
ImagingComponent::m_handleImageRegion(void *userdata, vrpn_HANDLERPARAM p) {
auto self = static_cast<ImagingComponent *>(userdata);
auto bufReader = readExternalBuffer(p.buffer, p.payload_len);
messages::ImageRegion::MessageSerialization msg;
deserialize(bufReader, msg);
auto data = msg.getData();
auto timestamp = util::time::fromStructTimeval(p.msg_time);
self->m_checkFirst(data.metadata);
for (auto const &cb : self->m_cb) {
cb(data, timestamp);
}
return 0;
}
#ifdef OSVR_COMMON_IN_PROCESS_IMAGING
int VRPN_CALLBACK ImagingComponent::m_handleImagePlacedInProcessMemory(
void *userdata, vrpn_HANDLERPARAM p) {
auto self = static_cast<ImagingComponent *>(userdata);
auto bufReader = readExternalBuffer(p.buffer, p.payload_len);
messages::ImagePlacedInProcessMemory::MessageSerialization msgSerialize;
deserialize(bufReader, msgSerialize);
auto msg = msgSerialize.getMessage();
ImageData data;
data.sensor = msg.sensor;
data.metadata = msg.metadata;
data.buffer.reset(
reinterpret_cast<OSVR_ImageBufferElement *>(msg.buffer),
&osvrAllignedFree);
auto timestamp = util::time::fromStructTimeval(p.msg_time);
self->m_checkFirst(msg.metadata);
for (auto const &cb : self->m_cb) {
cb(data, timestamp);
}
return 0;
}
#endif
int VRPN_CALLBACK ImagingComponent::m_handleImagePlacedInSharedMemory(
void *userdata, vrpn_HANDLERPARAM p) {
auto self = static_cast<ImagingComponent *>(userdata);
auto bufReader = readExternalBuffer(p.buffer, p.payload_len);
messages::ImagePlacedInSharedMemory::MessageSerialization msgSerialize;
deserialize(bufReader, msgSerialize);
auto &msg = msgSerialize.getMessage();
auto timestamp = util::time::fromStructTimeval(p.msg_time);
if (IPCRingBuffer::getABILevel() != msg.abiLevel) {
/// Can't interoperate with this server over shared memory
OSVR_DEV_VERBOSE("Can't handle SHM ABI level " << msg.abiLevel);
return 0;
}
self->m_growShmVecIfRequired(msg.sensor);
auto checkSameRingBuf = [](messages::SharedMemoryMessage const &msg,
IPCRingBufferPtr &ringbuf) {
return (msg.backend == ringbuf->getBackend()) &&
(ringbuf->getEntrySize() == getBufferSize(msg.metadata)) &&
(ringbuf->getName() == msg.shmName);
};
if (!self->m_shmBuf[msg.sensor] ||
!checkSameRingBuf(msg, self->m_shmBuf[msg.sensor])) {
self->m_shmBuf[msg.sensor] = IPCRingBuffer::find(
IPCRingBuffer::Options(msg.shmName, msg.backend));
}
if (!self->m_shmBuf[msg.sensor]) {
/// Can't find the shared memory referred to - possibly not a local
/// client
OSVR_DEV_VERBOSE("Can't find desired IPC ring buffer "
<< msg.shmName);
return 0;
}
auto &shm = self->m_shmBuf[msg.sensor];
auto getResult = shm->get(msg.seqNum);
if (getResult) {
auto bufptr = getResult.getBufferSmartPointer();
self->m_checkFirst(msg.metadata);
auto data = ImageData{msg.sensor, msg.metadata, bufptr};
for (auto const &cb : self->m_cb) {
cb(data, timestamp);
}
}
return 0;
}
void ImagingComponent::registerImageHandler(ImageHandler handler) {
if (m_cb.empty()) {
m_registerHandler(&ImagingComponent::m_handleImageRegion, this,
imageRegion.getMessageType());
m_registerHandler(
&ImagingComponent::m_handleImagePlacedInSharedMemory, this,
imagePlacedInSharedMemory.getMessageType());
#ifdef OSVR_COMMON_IN_PROCESS_IMAGING
m_registerHandler(
&ImagingComponent::m_handleImagePlacedInProcessMemory, this,
imagePlacedInProcessMemory.getMessageType());
#endif
}
m_cb.push_back(handler);
}
void ImagingComponent::m_parentSet() {
m_getParent().registerMessageType(imageRegion);
m_getParent().registerMessageType(imagePlacedInSharedMemory);
#ifdef OSVR_COMMON_IN_PROCESS_IMAGING
m_getParent().registerMessageType(imagePlacedInProcessMemory);
#endif
}
void ImagingComponent::m_checkFirst(OSVR_ImagingMetadata const &metadata) {
if (m_gotOne) {
return;
}
m_gotOne = true;
OSVR_DEV_VERBOSE("Sending/receiving first frame: width="
<< metadata.width << " height=" << metadata.height);
}
void ImagingComponent::m_growShmVecIfRequired(OSVR_ChannelCount sensor) {
if (m_shmBuf.size() <= sensor) {
m_shmBuf.resize(sensor + 1);
}
}
} // namespace common
} // namespace osvr
<commit_msg>Fix typo in in-process-memory imaging code.<commit_after>/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, 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.
// Internal Includes
#include <osvr/Common/ImagingComponent.h>
#include <osvr/Common/BaseDevice.h>
#include <osvr/Common/Serialization.h>
#include <osvr/Common/Buffer.h>
#include <osvr/Util/AlignedMemoryUniquePtr.h>
#include <osvr/Util/Flag.h>
#include <osvr/Util/Verbosity.h>
// Library/third-party includes
// - none
// Standard includes
#include <sstream>
#include <utility>
namespace osvr {
namespace common {
static inline uint32_t getBufferSize(OSVR_ImagingMetadata const &meta) {
return meta.height * meta.width * meta.depth * meta.channels;
}
namespace messages {
namespace {
template <typename T>
void process(OSVR_ImagingMetadata &meta, T &p) {
p(meta.height);
p(meta.width);
p(meta.channels);
p(meta.depth);
p(meta.type,
serialization::EnumAsIntegerTag<OSVR_ImagingValueType,
uint8_t>());
}
} // namespace
class ImageRegion::MessageSerialization {
public:
MessageSerialization(OSVR_ImagingMetadata const &meta,
OSVR_ImageBufferElement *imageData,
OSVR_ChannelCount sensor)
: m_meta(meta),
m_imgBuf(imageData,
[](OSVR_ImageBufferElement *) {
}), // That's a null-deleter right there for you.
m_sensor(sensor) {}
MessageSerialization() : m_imgBuf(nullptr) {}
template <typename T>
void allocateBuffer(T &, size_t bytes, std::true_type const &) {
m_imgBuf = util::makeAlignedImageBuffer(bytes);
}
template <typename T>
void allocateBuffer(T &, size_t, std::false_type const &) {
// Does nothing if we're serializing.
}
template <typename T> void processMessage(T &p) {
process(m_meta, p);
auto bytes = getBufferSize(m_meta);
/// Allocate the matrix backing data, if we're deserializing
/// only.
allocateBuffer(p, bytes, p.isDeserialize());
p(m_imgBuf.get(),
serialization::AlignedDataBufferTag(bytes, m_meta.depth));
}
ImageData getData() const {
ImageData ret;
ret.sensor = m_sensor;
ret.metadata = m_meta;
ret.buffer = m_imgBuf;
return ret;
}
private:
OSVR_ImagingMetadata m_meta;
ImageBufferPtr m_imgBuf;
OSVR_ChannelCount m_sensor;
};
const char *ImageRegion::identifier() {
return "com.osvr.imaging.imageregion";
}
#ifdef OSVR_COMMON_IN_PROCESS_IMAGING
namespace {
struct InProcessMemoryMessage {
OSVR_ImagingMetadata metadata;
OSVR_ChannelCount sensor;
int buffer;
};
template <typename T>
void process(InProcessMemoryMessage &ipmmMsg, T &p) {
process(ipmmMsg.metadata, p);
p(ipmmMsg.sensor);
p(ipmmMsg.buffer);
}
} // namespace
const char *ImagePlacedInProcessMemory::identifier() {
return "com.osvr.imaging.imageplacedinprocessmemory";
}
class ImagePlacedInProcessMemory::MessageSerialization {
public:
MessageSerialization() {}
explicit MessageSerialization(InProcessMemoryMessage &&msg)
: m_msgData(std::move(msg)) {}
#if defined(_MSC_VER) && defined(_PREFAST_)
// @todo workaround for apparent bug in VS2013 /analyze
explicit MessageSerialization(InProcessMemoryMessage const &msg)
: m_msgData(msg) {}
#endif
template <typename T> void processMessage(T &p) {
process(m_msgData, p);
}
InProcessMemoryMessage const &getMessage() { return m_msgData; }
private:
InProcessMemoryMessage m_msgData;
};
#endif
namespace {
struct SharedMemoryMessage {
OSVR_ImagingMetadata metadata;
IPCRingBuffer::sequence_type seqNum;
OSVR_ChannelCount sensor;
IPCRingBuffer::abi_level_type abiLevel;
IPCRingBuffer::BackendType backend;
std::string shmName;
};
template <typename T>
void process(SharedMemoryMessage &shmMsg, T &p) {
process(shmMsg.metadata, p);
p(shmMsg.seqNum);
p(shmMsg.sensor);
p(shmMsg.abiLevel);
p(shmMsg.backend);
p(shmMsg.shmName);
}
} // namespace
class ImagePlacedInSharedMemory::MessageSerialization {
public:
MessageSerialization() {}
explicit MessageSerialization(SharedMemoryMessage &&msg)
: m_msgData(std::move(msg)) {}
#if defined(_MSC_VER) && defined(_PREFAST_)
/// @todo workaround for apparent bug in VS2013 /analyze
explicit MessageSerialization(SharedMemoryMessage const &msg)
: m_msgData(msg) {}
#endif
template <typename T> void processMessage(T &p) {
process(m_msgData, p);
}
SharedMemoryMessage const &getMessage() { return m_msgData; }
private:
SharedMemoryMessage m_msgData;
};
const char *ImagePlacedInSharedMemory::identifier() {
return "com.osvr.imaging.imageplacedinsharedmemory";
}
} // namespace messages
shared_ptr<ImagingComponent>
ImagingComponent::create(OSVR_ChannelCount numChan) {
shared_ptr<ImagingComponent> ret(new ImagingComponent(numChan));
return ret;
}
ImagingComponent::ImagingComponent(OSVR_ChannelCount numChan)
: m_numSensor(numChan) {}
void ImagingComponent::sendImageData(OSVR_ImagingMetadata metadata,
OSVR_ImageBufferElement *imageData,
OSVR_ChannelCount sensor,
OSVR_TimeValue const ×tamp) {
util::Flag dataSent;
#ifdef OSVR_COMMON_IN_PROCESS_IMAGING
dataSent += m_sendImageDataViaInProcessMemory(metadata, imageData,
sensor, timestamp);
#else
dataSent += m_sendImageDataViaSharedMemory(metadata, imageData, sensor,
timestamp);
#endif
dataSent +=
m_sendImageDataOnTheWire(metadata, imageData, sensor, timestamp);
if (dataSent) {
m_checkFirst(metadata);
}
}
#ifdef OSVR_COMMON_IN_PROCESS_IMAGING
bool ImagingComponent::m_sendImageDataViaInProcessMemory(
OSVR_ImagingMetadata metadata, OSVR_ImageBufferElement *imageData,
OSVR_ChannelCount sensor, OSVR_TimeValue const ×tamp) {
auto imageBufferSize = getBufferSize(metadata);
/// @todo Assuming we should be releasing this pointer from the control
/// of the unique_ptr that holds it now, rather than freeing?
auto imageBufferCopy = util::makeAlignedImageBuffer(imageBufferSize);
memcpy(imageBufferCopy.get(), imageData, imageBufferSize);
Buffer<> buf;
messages::ImagePlacedInProcessMemory::MessageSerialization
serialization(messages::InProcessMemoryMessage{
metadata, sensor, reinterpret_cast<int>(imageBufferCopy)});
serialize(buf, serialization);
m_getParent().packMessage(
buf, imagePlacedInProcessMemory.getMessageType(), timestamp);
return true;
}
#endif
bool ImagingComponent::m_sendImageDataViaSharedMemory(
OSVR_ImagingMetadata metadata, OSVR_ImageBufferElement *imageData,
OSVR_ChannelCount sensor, OSVR_TimeValue const ×tamp) {
m_growShmVecIfRequired(sensor);
uint32_t imageBufferSize = getBufferSize(metadata);
if (!m_shmBuf[sensor] ||
m_shmBuf[sensor]->getEntrySize() != imageBufferSize) {
// create or replace the shared memory ring buffer.
auto makeName = [](OSVR_ChannelCount sensor,
std::string const &devName) {
std::ostringstream os;
os << "com.osvr.imaging/" << devName << "/" << int(sensor);
return os.str();
};
m_shmBuf[sensor] = IPCRingBuffer::create(
IPCRingBuffer::Options(
makeName(sensor, m_getParent().getDeviceName()))
.setEntrySize(imageBufferSize));
}
if (!m_shmBuf[sensor]) {
OSVR_DEV_VERBOSE(
"Some issue creating shared memory for imaging, skipping out.");
return false;
}
auto &shm = *(m_shmBuf[sensor]);
auto seq = shm.put(imageData, imageBufferSize);
Buffer<> buf;
messages::ImagePlacedInSharedMemory::MessageSerialization serialization(
messages::SharedMemoryMessage{metadata, seq, sensor,
IPCRingBuffer::getABILevel(),
shm.getBackend(), shm.getName()});
serialize(buf, serialization);
m_getParent().packMessage(
buf, imagePlacedInSharedMemory.getMessageType(), timestamp);
return true;
}
bool ImagingComponent::m_sendImageDataOnTheWire(
OSVR_ImagingMetadata metadata, OSVR_ImageBufferElement *imageData,
OSVR_ChannelCount sensor, OSVR_TimeValue const ×tamp) {
/// @todo currently only handle 8bit data over network
if (metadata.depth != 1) {
return false;
}
Buffer<> buf;
messages::ImageRegion::MessageSerialization msg(metadata, imageData,
sensor);
serialize(buf, msg);
if (buf.size() > vrpn_CONNECTION_TCP_BUFLEN) {
#if 0
OSVR_DEV_VERBOSE("Skipping imaging message: size is "
<< buf.size() << " vs the maximum of "
<< vrpn_CONNECTION_TCP_BUFLEN);
#endif
return false;
}
m_getParent().packMessage(buf, imageRegion.getMessageType(), timestamp);
m_getParent().sendPending();
return true;
}
int VRPN_CALLBACK
ImagingComponent::m_handleImageRegion(void *userdata, vrpn_HANDLERPARAM p) {
auto self = static_cast<ImagingComponent *>(userdata);
auto bufReader = readExternalBuffer(p.buffer, p.payload_len);
messages::ImageRegion::MessageSerialization msg;
deserialize(bufReader, msg);
auto data = msg.getData();
auto timestamp = util::time::fromStructTimeval(p.msg_time);
self->m_checkFirst(data.metadata);
for (auto const &cb : self->m_cb) {
cb(data, timestamp);
}
return 0;
}
#ifdef OSVR_COMMON_IN_PROCESS_IMAGING
int VRPN_CALLBACK ImagingComponent::m_handleImagePlacedInProcessMemory(
void *userdata, vrpn_HANDLERPARAM p) {
auto self = static_cast<ImagingComponent *>(userdata);
auto bufReader = readExternalBuffer(p.buffer, p.payload_len);
messages::ImagePlacedInProcessMemory::MessageSerialization msgSerialize;
deserialize(bufReader, msgSerialize);
auto msg = msgSerialize.getMessage();
ImageData data;
data.sensor = msg.sensor;
data.metadata = msg.metadata;
data.buffer.reset(
reinterpret_cast<OSVR_ImageBufferElement *>(msg.buffer),
&util::alignedFree);
auto timestamp = util::time::fromStructTimeval(p.msg_time);
self->m_checkFirst(msg.metadata);
for (auto const &cb : self->m_cb) {
cb(data, timestamp);
}
return 0;
}
#endif
int VRPN_CALLBACK ImagingComponent::m_handleImagePlacedInSharedMemory(
void *userdata, vrpn_HANDLERPARAM p) {
auto self = static_cast<ImagingComponent *>(userdata);
auto bufReader = readExternalBuffer(p.buffer, p.payload_len);
messages::ImagePlacedInSharedMemory::MessageSerialization msgSerialize;
deserialize(bufReader, msgSerialize);
auto &msg = msgSerialize.getMessage();
auto timestamp = util::time::fromStructTimeval(p.msg_time);
if (IPCRingBuffer::getABILevel() != msg.abiLevel) {
/// Can't interoperate with this server over shared memory
OSVR_DEV_VERBOSE("Can't handle SHM ABI level " << msg.abiLevel);
return 0;
}
self->m_growShmVecIfRequired(msg.sensor);
auto checkSameRingBuf = [](messages::SharedMemoryMessage const &msg,
IPCRingBufferPtr &ringbuf) {
return (msg.backend == ringbuf->getBackend()) &&
(ringbuf->getEntrySize() == getBufferSize(msg.metadata)) &&
(ringbuf->getName() == msg.shmName);
};
if (!self->m_shmBuf[msg.sensor] ||
!checkSameRingBuf(msg, self->m_shmBuf[msg.sensor])) {
self->m_shmBuf[msg.sensor] = IPCRingBuffer::find(
IPCRingBuffer::Options(msg.shmName, msg.backend));
}
if (!self->m_shmBuf[msg.sensor]) {
/// Can't find the shared memory referred to - possibly not a local
/// client
OSVR_DEV_VERBOSE("Can't find desired IPC ring buffer "
<< msg.shmName);
return 0;
}
auto &shm = self->m_shmBuf[msg.sensor];
auto getResult = shm->get(msg.seqNum);
if (getResult) {
auto bufptr = getResult.getBufferSmartPointer();
self->m_checkFirst(msg.metadata);
auto data = ImageData{msg.sensor, msg.metadata, bufptr};
for (auto const &cb : self->m_cb) {
cb(data, timestamp);
}
}
return 0;
}
void ImagingComponent::registerImageHandler(ImageHandler handler) {
if (m_cb.empty()) {
m_registerHandler(&ImagingComponent::m_handleImageRegion, this,
imageRegion.getMessageType());
m_registerHandler(
&ImagingComponent::m_handleImagePlacedInSharedMemory, this,
imagePlacedInSharedMemory.getMessageType());
#ifdef OSVR_COMMON_IN_PROCESS_IMAGING
m_registerHandler(
&ImagingComponent::m_handleImagePlacedInProcessMemory, this,
imagePlacedInProcessMemory.getMessageType());
#endif
}
m_cb.push_back(handler);
}
void ImagingComponent::m_parentSet() {
m_getParent().registerMessageType(imageRegion);
m_getParent().registerMessageType(imagePlacedInSharedMemory);
#ifdef OSVR_COMMON_IN_PROCESS_IMAGING
m_getParent().registerMessageType(imagePlacedInProcessMemory);
#endif
}
void ImagingComponent::m_checkFirst(OSVR_ImagingMetadata const &metadata) {
if (m_gotOne) {
return;
}
m_gotOne = true;
OSVR_DEV_VERBOSE("Sending/receiving first frame: width="
<< metadata.width << " height=" << metadata.height);
}
void ImagingComponent::m_growShmVecIfRequired(OSVR_ChannelCount sensor) {
if (m_shmBuf.size() <= sensor) {
m_shmBuf.resize(sensor + 1);
}
}
} // namespace common
} // namespace osvr
<|endoftext|> |
<commit_before><commit_msg>qt: Don't use QDateTime::toSecsSinceEpoch<commit_after><|endoftext|> |
<commit_before>// Copyright 2015 Patrick Putnam
//
// 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.
#ifndef CLOTHO_ROW_GROUPED_FREE_SPACE_EVALUATOR_HPP_
#define CLOTHO_ROW_GROUPED_FREE_SPACE_EVALUATOR_HPP_
#include "clotho/data_spaces/association_matrix/row_grouped_association_matrix.hpp"
#include "clotho/utility/bit_helper.hpp"
#include "clotho/utility/debruijn_bit_walker.hpp"
#include <set>
namespace clotho {
namespace genetics {
template < class BlockType, unsigned char P >
class free_space_evaluator< association_matrix< BlockType, row_grouped< P > > > {
public:
typedef association_matrix< BlockType, row_grouped< P > > space_type;
typedef typename space_type::block_type block_type;
typedef size_t * result_type;
typedef typename space_type::raw_block_pointer block_pointer;
typedef clotho::utility::debruijn_bit_walker< block_type > bit_walker_type;
typedef clotho::utility::BitHelper< block_type > bit_helper_type;
void operator()( space_type & ss, result_type res, size_t & fixed_offset, size_t & lost_offset, size_t & free_count, size_t M ) {
size_t W = bit_helper_type::padded_block_count( M );
block_type * tmp = new block_type[ 2 * W ];
memset( tmp, 255, sizeof(block_type) * W );
memset( tmp + W, 0, sizeof(block_type) * W );
const size_t row_count = ss.block_row_count();
size_t fo = fixed_offset;
size_t lo = lost_offset;
size_t fr = free_count;
block_type * fx_ptr = tmp;
block_type * var_ptr = tmp + W;
size_t k = 0;
while( k < row_count ) {
block_pointer start = ss.begin_block_row( k );
block_pointer end = ss.end_block_row( k );
fx_ptr = tmp;
var_ptr = tmp + W;
size_t i = 0;
while( start != end ) {
block_type b = *start++;
*fx_ptr &= b;
*var_ptr |= b;
if( ++i == row_grouped< P >::GROUP_SIZE ) {
++fx_ptr;
++var_ptr;
i = 0;
}
}
assert(fx_ptr == tmp + W);
k += row_grouped< P >::GROUP_SIZE;
}
size_t j = 0;
fx_ptr = tmp;
var_ptr = tmp + W;
while( fx_ptr != tmp + W ) {
block_type fx = *fx_ptr++;
block_type var = *var_ptr++;
block_type ls = ~(fx | var);
while( fx ) {
size_t b_idx = bit_walker_type::unset_next_index( fx ) + j;
if( b_idx < M ) {
res[ fr++ ] = b_idx;
res[ fo++ ] = b_idx;
}
}
while( ls ) {
size_t idx = bit_walker_type::unset_next_index( ls ) + j;
if( idx < M ) {
res[ fr++ ] = idx;
res[ lo++ ] = idx;
}
}
j += bit_helper_type::BITS_PER_BLOCK;
}
fixed_offset = fo;
lost_offset = lo;
free_count = fr;
delete [] tmp;
}
};
template < class BlockType >
class free_space_evaluator< association_matrix< BlockType, row_grouped< 1 > > > {
public:
typedef association_matrix< BlockType, row_grouped< 1 > > space_type;
typedef typename space_type::row_vector row_vector;
typedef typename row_vector::block_type block_type;
typedef size_t * result_type;
typedef typename row_vector::raw_pointer raw_pointer;
typedef clotho::utility::debruijn_bit_walker< block_type > bit_walker_type;
typedef clotho::utility::BitHelper< block_type > bit_helper_type;
free_space_evaluator() :
tmp(NULL)
, m_alloc_size(0)
{}
void operator()( space_type & ss, result_type res, size_t & fixed_offset, size_t & lost_offset, size_t & free_count, size_t M ) {
// size_t W = bit_helper_type::padded_block_count( M );
size_t W = ss.hard_block_count();
resize( W );
for( size_t i = 0; i < W; ++i ) {
tmp[ 2 * i ] = bit_helper_type::ALL_SET;
tmp[ 2 * i + 1 ] = bit_helper_type::ALL_UNSET;
}
std::set< raw_pointer > analyzed;
const size_t row_count = ss.row_count();
size_t fo = fixed_offset;
size_t lo = lost_offset;
size_t fr = free_count;
size_t k = 0;
while( k < row_count ) {
raw_pointer start = ss.getRow( k ).get();
if( analyzed.find( start ) == analyzed.end() ) {
analyzed.insert( start );
size_t N = ss.getRow( k ).m_size;
#ifdef DEBUGGING
assert( N <= W );
#endif // DEBUGGING
// size_t i = 0;
// while( i < N ) {
// block_type b = start[i];
// tmp[ 2 * i ] &= b;
// tmp[ 2 * i + 1 ] |= b;
// ++i;
// }
raw_pointer end = start + N;
block_type * t = tmp;
while( start != end ) {
*t++ &= *start;
*t++ |= *start++;
}
size_t i = N;
while( i < W ) {
tmp[ 2 * i ] = bit_helper_type::ALL_UNSET;
++i;
}
}
++k;
}
#ifdef DEBUGGING
std::cerr << "Free Space analyzed: " << analyzed.size() << std::endl;
#endif // DEBUGGING
size_t j = 0;
for( unsigned int i = 0; i < W; ++i ) {
block_type fx = tmp[ 2 *i ];
block_type var = tmp[2 * i + 1];
block_type ls = ~(fx | var);
while( fx ) {
size_t b_idx = bit_walker_type::unset_next_index( fx ) + j;
if( b_idx < M ) {
res[ fr++ ] = b_idx;
res[ fo++ ] = b_idx;
}
}
while( ls ) {
size_t idx = bit_walker_type::unset_next_index( ls ) + j;
if( idx < M ) {
res[ fr++ ] = idx;
res[ lo++ ] = idx;
}
}
j += bit_helper_type::BITS_PER_BLOCK;
}
fixed_offset = fo;
lost_offset = lo;
free_count = fr;
}
virtual ~free_space_evaluator() {
if( tmp != NULL ) {
delete [] tmp;
}
}
protected:
void resize( size_t W ) {
if( 2 * W > m_alloc_size ) {
if( tmp != NULL ) {
delete [] tmp;
}
tmp = new block_type[ 2 * W ];
m_alloc_size = 2 * W;
}
}
block_type * tmp;
size_t m_alloc_size;
};
} // namespace genetics
} // namespace clotho
#endif // CLOTHO_ROW_GROUPED_FREE_SPACE_EVALUATOR_HPP_
<commit_msg>Updated to try a different algorithm<commit_after>// Copyright 2015 Patrick Putnam
//
// 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.
#ifndef CLOTHO_ROW_GROUPED_FREE_SPACE_EVALUATOR_HPP_
#define CLOTHO_ROW_GROUPED_FREE_SPACE_EVALUATOR_HPP_
#include "clotho/data_spaces/association_matrix/row_grouped_association_matrix.hpp"
#include "clotho/utility/bit_helper.hpp"
#include "clotho/utility/debruijn_bit_walker.hpp"
#include <map>
#include <set>
namespace clotho {
namespace genetics {
template < class BlockType, unsigned char P >
class free_space_evaluator< association_matrix< BlockType, row_grouped< P > > > {
public:
typedef association_matrix< BlockType, row_grouped< P > > space_type;
typedef typename space_type::block_type block_type;
typedef size_t * result_type;
typedef typename space_type::raw_block_pointer block_pointer;
typedef clotho::utility::debruijn_bit_walker< block_type > bit_walker_type;
typedef clotho::utility::BitHelper< block_type > bit_helper_type;
void operator()( space_type & ss, result_type res, size_t & fixed_offset, size_t & lost_offset, size_t & free_count, size_t M ) {
size_t W = bit_helper_type::padded_block_count( M );
block_type * tmp = new block_type[ 2 * W ];
memset( tmp, 255, sizeof(block_type) * W );
memset( tmp + W, 0, sizeof(block_type) * W );
const size_t row_count = ss.block_row_count();
size_t fo = fixed_offset;
size_t lo = lost_offset;
size_t fr = free_count;
block_type * fx_ptr = tmp;
block_type * var_ptr = tmp + W;
size_t k = 0;
while( k < row_count ) {
block_pointer start = ss.begin_block_row( k );
block_pointer end = ss.end_block_row( k );
fx_ptr = tmp;
var_ptr = tmp + W;
size_t i = 0;
while( start != end ) {
block_type b = *start++;
*fx_ptr &= b;
*var_ptr |= b;
if( ++i == row_grouped< P >::GROUP_SIZE ) {
++fx_ptr;
++var_ptr;
i = 0;
}
}
assert(fx_ptr == tmp + W);
k += row_grouped< P >::GROUP_SIZE;
}
size_t j = 0;
fx_ptr = tmp;
var_ptr = tmp + W;
while( fx_ptr != tmp + W ) {
block_type fx = *fx_ptr++;
block_type var = *var_ptr++;
block_type ls = ~(fx | var);
while( fx ) {
size_t b_idx = bit_walker_type::unset_next_index( fx ) + j;
if( b_idx < M ) {
res[ fr++ ] = b_idx;
res[ fo++ ] = b_idx;
}
}
while( ls ) {
size_t idx = bit_walker_type::unset_next_index( ls ) + j;
if( idx < M ) {
res[ fr++ ] = idx;
res[ lo++ ] = idx;
}
}
j += bit_helper_type::BITS_PER_BLOCK;
}
fixed_offset = fo;
lost_offset = lo;
free_count = fr;
delete [] tmp;
}
};
/*
template < class BlockType >
class free_space_evaluator< association_matrix< BlockType, row_grouped< 1 > > > {
public:
typedef association_matrix< BlockType, row_grouped< 1 > > space_type;
typedef typename space_type::row_vector row_vector;
typedef typename row_vector::block_type block_type;
typedef size_t * result_type;
typedef typename row_vector::raw_pointer raw_pointer;
typedef clotho::utility::debruijn_bit_walker< block_type > bit_walker_type;
typedef clotho::utility::BitHelper< block_type > bit_helper_type;
free_space_evaluator() :
tmp(NULL)
, m_alloc_size(0)
{}
void operator()( space_type & ss, result_type res, size_t & fixed_offset, size_t & lost_offset, size_t & free_count, size_t M ) {
// size_t W = bit_helper_type::padded_block_count( M );
size_t W = ss.hard_block_count();
resize( W );
for( size_t i = 0; i < W; ++i ) {
tmp[ 2 * i ] = bit_helper_type::ALL_SET;
tmp[ 2 * i + 1 ] = bit_helper_type::ALL_UNSET;
}
std::set< raw_pointer > analyzed;
const size_t row_count = ss.row_count();
size_t fo = fixed_offset;
size_t lo = lost_offset;
size_t fr = free_count;
size_t k = 0;
while( k < row_count ) {
raw_pointer start = ss.getRow( k ).get();
if( analyzed.find( start ) == analyzed.end() ) {
analyzed.insert( start );
size_t N = ss.getRow( k ).m_size;
#ifdef DEBUGGING
assert( N <= W );
#endif // DEBUGGING
// size_t i = 0;
// while( i < N ) {
// block_type b = start[i];
// tmp[ 2 * i ] &= b;
// tmp[ 2 * i + 1 ] |= b;
// ++i;
// }
raw_pointer end = start + N;
block_type * t = tmp;
while( start != end ) {
*t++ &= *start;
*t++ |= *start++;
}
size_t i = N;
while( i < W ) {
tmp[ 2 * i ] = bit_helper_type::ALL_UNSET;
++i;
}
}
++k;
}
#ifdef DEBUGGING
std::cerr << "Free Space analyzed: " << analyzed.size() << std::endl;
#endif // DEBUGGING
size_t j = 0;
for( unsigned int i = 0; i < W; ++i ) {
block_type fx = tmp[ 2 *i ];
block_type var = tmp[2 * i + 1];
block_type ls = ~(fx | var);
while( fx ) {
size_t b_idx = bit_walker_type::unset_next_index( fx ) + j;
if( b_idx < M ) {
res[ fr++ ] = b_idx;
res[ fo++ ] = b_idx;
}
}
while( ls ) {
size_t idx = bit_walker_type::unset_next_index( ls ) + j;
if( idx < M ) {
res[ fr++ ] = idx;
res[ lo++ ] = idx;
}
}
j += bit_helper_type::BITS_PER_BLOCK;
}
fixed_offset = fo;
lost_offset = lo;
free_count = fr;
}
virtual ~free_space_evaluator() {
if( tmp != NULL ) {
delete [] tmp;
}
}
protected:
void resize( size_t W ) {
if( 2 * W > m_alloc_size ) {
if( tmp != NULL ) {
delete [] tmp;
}
tmp = new block_type[ 2 * W ];
m_alloc_size = 2 * W;
}
}
block_type * tmp;
size_t m_alloc_size;
};*/
/// this approach eliminates writing to the heap
/// utilizes stack buffers to write temporary data
template < class BlockType >
class free_space_evaluator< association_matrix< BlockType, row_grouped< 1 > > > {
public:
typedef association_matrix< BlockType, row_grouped< 1 > > space_type;
typedef typename space_type::row_vector row_vector;
typedef typename row_vector::block_type block_type;
typedef size_t * result_type;
typedef typename row_vector::raw_pointer raw_pointer;
typedef clotho::utility::debruijn_bit_walker< block_type > bit_walker_type;
typedef clotho::utility::BitHelper< block_type > bit_helper_type;
free_space_evaluator() {}
void operator()( space_type & ss, result_type res, size_t & fixed_offset, size_t & lost_offset, size_t & free_count, size_t M ) {
size_t W = ss.hard_block_count();
std::map< raw_pointer, size_t > analyzed;
typedef typename std::map< raw_pointer, size_t >::iterator iterator;
const size_t row_count = ss.row_count();
size_t fo = fixed_offset;
size_t lo = lost_offset;
size_t fr = free_count;
// pre-scan population for all unique sequences
size_t k = 0;
while( k < row_count ) {
raw_pointer start = ss.getRow( k ).get();
size_t s = ss.getRow( k ).m_size;
if( analyzed.find( start ) == analyzed.end() ) {
analyzed[ start ] = s;
}
++k;
}
#ifdef DEBUGGING
std::cerr << "Free Space analyzing: " << analyzed.size() << std::endl;
#endif // DEBUGGING
const size_t BUFFER_SIZE = 8;
k = 0;
while( k < W ) {
// // 16 * sizeof(block_type) * 2 == 16 * 8 * 2 == 256 byte buffer
block_type fx_buffer[ BUFFER_SIZE ];
block_type var_buffer[ BUFFER_SIZE ];
// initialize buffers
for( int x = 0; x < BUFFER_SIZE; ++x ) {
fx_buffer[ x ] = bit_helper_type::ALL_SET;
var_buffer[ x ] = bit_helper_type::ALL_UNSET;
}
// analyze block columns
for( iterator it = analyzed.begin(); it != analyzed.end(); it++ ) {
size_t S = it->second;
size_t N = ((k >= S)? 0 : (( k + BUFFER_SIZE <= S ) ? BUFFER_SIZE : (S - k)));
size_t x = 0;
raw_pointer r = it->first;
while( x < N ) {
block_type b = r[ k + x ];
fx_buffer[ x ] &= b;
var_buffer[ x ] |= b;
++x;
}
while( x < BUFFER_SIZE ) {
fx_buffer[ x ] = bit_helper_type::ALL_UNSET;
++x;
}
}
// write results
size_t j = k * bit_helper_type::BITS_PER_BLOCK;
for( unsigned int i = 0; i < BUFFER_SIZE; ++i ) {
block_type fx = fx_buffer[ i ];
block_type var = var_buffer[ i ];
block_type ls = ~(fx | var);
while( fx ) {
size_t b_idx = bit_walker_type::unset_next_index( fx ) + j;
if( b_idx < M ) {
res[ fr++ ] = b_idx;
res[ fo++ ] = b_idx;
}
}
while( ls ) {
size_t idx = bit_walker_type::unset_next_index( ls ) + j;
if( idx < M ) {
res[ fr++ ] = idx;
res[ lo++ ] = idx;
}
}
j += bit_helper_type::BITS_PER_BLOCK;
}
k += BUFFER_SIZE;
}
fixed_offset = fo;
lost_offset = lo;
free_count = fr;
}
virtual ~free_space_evaluator() { }
};
} // namespace genetics
} // namespace clotho
#endif // CLOTHO_ROW_GROUPED_FREE_SPACE_EVALUATOR_HPP_
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2019 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/congestion_controller/goog_cc/robust_throughput_estimator.h"
#include <stddef.h>
#include <algorithm>
#include <utility>
#include "rtc_base/checks.h"
namespace webrtc {
RobustThroughputEstimator::RobustThroughputEstimator(
const RobustThroughputEstimatorSettings& settings)
: settings_(settings) {
RTC_DCHECK(settings.enabled);
}
RobustThroughputEstimator::~RobustThroughputEstimator() {}
void RobustThroughputEstimator::IncomingPacketFeedbackVector(
const std::vector<PacketResult>& packet_feedback_vector) {
RTC_DCHECK(std::is_sorted(packet_feedback_vector.begin(),
packet_feedback_vector.end(),
PacketResult::ReceiveTimeOrder()));
for (const auto& packet : packet_feedback_vector) {
// Insert the new packet.
window_.push_back(packet);
// In most cases, receive timestamps should already be in order, but in the
// rare case where feedback packets have been reordered, we do some swaps to
// ensure that the window is sorted.
for (size_t i = window_.size() - 1;
i > 0 && window_[i].receive_time < window_[i - 1].receive_time; i--) {
std::swap(window_[i], window_[i - 1]);
}
// Remove old packets.
while (window_.size() > settings_.kMaxPackets ||
(window_.size() > settings_.min_packets &&
packet.receive_time - window_.front().receive_time >
settings_.window_duration)) {
window_.pop_front();
}
}
}
absl::optional<DataRate> RobustThroughputEstimator::bitrate() const {
if (window_.size() < settings_.initial_packets)
return absl::nullopt;
TimeDelta largest_recv_gap(TimeDelta::Millis(0));
TimeDelta second_largest_recv_gap(TimeDelta::Millis(0));
for (size_t i = 1; i < window_.size(); i++) {
// Find receive time gaps
TimeDelta gap = window_[i].receive_time - window_[i - 1].receive_time;
if (gap > largest_recv_gap) {
second_largest_recv_gap = largest_recv_gap;
largest_recv_gap = gap;
} else if (gap > second_largest_recv_gap) {
second_largest_recv_gap = gap;
}
}
Timestamp min_send_time = window_[0].sent_packet.send_time;
Timestamp max_send_time = window_[0].sent_packet.send_time;
Timestamp min_recv_time = window_[0].receive_time;
Timestamp max_recv_time = window_[0].receive_time;
DataSize data_size = DataSize::Bytes(0);
for (const auto& packet : window_) {
min_send_time = std::min(min_send_time, packet.sent_packet.send_time);
max_send_time = std::max(max_send_time, packet.sent_packet.send_time);
min_recv_time = std::min(min_recv_time, packet.receive_time);
max_recv_time = std::max(max_recv_time, packet.receive_time);
data_size += packet.sent_packet.size;
data_size +=
packet.sent_packet.prior_unacked_data * settings_.unacked_weight;
}
// Suppose a packet of size S is sent every T milliseconds.
// A window of N packets would contain N*S bytes, but the time difference
// between the first and the last packet would only be (N-1)*T. Thus, we
// need to remove one packet.
DataSize recv_size = data_size;
DataSize send_size = data_size;
if (settings_.assume_shared_link) {
// Depending on how the bottleneck queue is implemented, a large packet
// may delay sending of sebsequent packets, so the delay between packets
// i and i+1 depends on the size of both packets. In this case we minimize
// the maximum error by removing half of both the first and last packet
// size.
DataSize first_last_average_size =
(window_.front().sent_packet.size +
window_.front().sent_packet.prior_unacked_data +
window_.back().sent_packet.size +
window_.back().sent_packet.prior_unacked_data) /
2;
recv_size -= first_last_average_size;
send_size -= first_last_average_size;
} else {
// In the simpler case where the delay between packets i and i+1 only
// depends on the size of packet i+1, the first packet doesn't give us
// any information. Analogously, we assume that the start send time
// for the last packet doesn't depend on the size of the packet.
recv_size -= (window_.front().sent_packet.size +
window_.front().sent_packet.prior_unacked_data);
send_size -= (window_.back().sent_packet.size +
window_.back().sent_packet.prior_unacked_data);
}
// Remove the largest gap by replacing it by the second largest gap
// or the average gap.
TimeDelta send_duration = max_send_time - min_send_time;
TimeDelta recv_duration = (max_recv_time - min_recv_time) - largest_recv_gap;
if (settings_.reduce_bias) {
recv_duration += second_largest_recv_gap;
} else {
recv_duration += recv_duration / (window_.size() - 2);
}
send_duration = std::max(send_duration, TimeDelta::Millis(1));
recv_duration = std::max(recv_duration, TimeDelta::Millis(1));
return std::min(send_size / send_duration, recv_size / recv_duration);
}
} // namespace webrtc
<commit_msg>Scale unacked_data consistently in RobustThroughputEstimator<commit_after>/*
* Copyright (c) 2019 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/congestion_controller/goog_cc/robust_throughput_estimator.h"
#include <stddef.h>
#include <algorithm>
#include <utility>
#include "rtc_base/checks.h"
namespace webrtc {
RobustThroughputEstimator::RobustThroughputEstimator(
const RobustThroughputEstimatorSettings& settings)
: settings_(settings) {
RTC_DCHECK(settings.enabled);
}
RobustThroughputEstimator::~RobustThroughputEstimator() {}
void RobustThroughputEstimator::IncomingPacketFeedbackVector(
const std::vector<PacketResult>& packet_feedback_vector) {
RTC_DCHECK(std::is_sorted(packet_feedback_vector.begin(),
packet_feedback_vector.end(),
PacketResult::ReceiveTimeOrder()));
for (const auto& packet : packet_feedback_vector) {
// Insert the new packet.
window_.push_back(packet);
window_.back().sent_packet.prior_unacked_data =
window_.back().sent_packet.prior_unacked_data *
settings_.unacked_weight;
// In most cases, receive timestamps should already be in order, but in the
// rare case where feedback packets have been reordered, we do some swaps to
// ensure that the window is sorted.
for (size_t i = window_.size() - 1;
i > 0 && window_[i].receive_time < window_[i - 1].receive_time; i--) {
std::swap(window_[i], window_[i - 1]);
}
// Remove old packets.
while (window_.size() > settings_.kMaxPackets ||
(window_.size() > settings_.min_packets &&
packet.receive_time - window_.front().receive_time >
settings_.window_duration)) {
window_.pop_front();
}
}
}
absl::optional<DataRate> RobustThroughputEstimator::bitrate() const {
if (window_.size() < settings_.initial_packets)
return absl::nullopt;
TimeDelta largest_recv_gap(TimeDelta::Millis(0));
TimeDelta second_largest_recv_gap(TimeDelta::Millis(0));
for (size_t i = 1; i < window_.size(); i++) {
// Find receive time gaps
TimeDelta gap = window_[i].receive_time - window_[i - 1].receive_time;
if (gap > largest_recv_gap) {
second_largest_recv_gap = largest_recv_gap;
largest_recv_gap = gap;
} else if (gap > second_largest_recv_gap) {
second_largest_recv_gap = gap;
}
}
Timestamp min_send_time = window_[0].sent_packet.send_time;
Timestamp max_send_time = window_[0].sent_packet.send_time;
Timestamp min_recv_time = window_[0].receive_time;
Timestamp max_recv_time = window_[0].receive_time;
DataSize data_size = DataSize::Bytes(0);
for (const auto& packet : window_) {
min_send_time = std::min(min_send_time, packet.sent_packet.send_time);
max_send_time = std::max(max_send_time, packet.sent_packet.send_time);
min_recv_time = std::min(min_recv_time, packet.receive_time);
max_recv_time = std::max(max_recv_time, packet.receive_time);
data_size += packet.sent_packet.size;
data_size += packet.sent_packet.prior_unacked_data;
}
// Suppose a packet of size S is sent every T milliseconds.
// A window of N packets would contain N*S bytes, but the time difference
// between the first and the last packet would only be (N-1)*T. Thus, we
// need to remove one packet.
DataSize recv_size = data_size;
DataSize send_size = data_size;
if (settings_.assume_shared_link) {
// Depending on how the bottleneck queue is implemented, a large packet
// may delay sending of sebsequent packets, so the delay between packets
// i and i+1 depends on the size of both packets. In this case we minimize
// the maximum error by removing half of both the first and last packet
// size.
DataSize first_last_average_size =
(window_.front().sent_packet.size +
window_.front().sent_packet.prior_unacked_data +
window_.back().sent_packet.size +
window_.back().sent_packet.prior_unacked_data) /
2;
recv_size -= first_last_average_size;
send_size -= first_last_average_size;
} else {
// In the simpler case where the delay between packets i and i+1 only
// depends on the size of packet i+1, the first packet doesn't give us
// any information. Analogously, we assume that the start send time
// for the last packet doesn't depend on the size of the packet.
recv_size -= (window_.front().sent_packet.size +
window_.front().sent_packet.prior_unacked_data);
send_size -= (window_.back().sent_packet.size +
window_.back().sent_packet.prior_unacked_data);
}
// Remove the largest gap by replacing it by the second largest gap
// or the average gap.
TimeDelta send_duration = max_send_time - min_send_time;
TimeDelta recv_duration = (max_recv_time - min_recv_time) - largest_recv_gap;
if (settings_.reduce_bias) {
recv_duration += second_largest_recv_gap;
} else {
recv_duration += recv_duration / (window_.size() - 2);
}
send_duration = std::max(send_duration, TimeDelta::Millis(1));
recv_duration = std::max(recv_duration, TimeDelta::Millis(1));
return std::min(send_size / send_duration, recv_size / recv_duration);
}
} // namespace webrtc
<|endoftext|> |
<commit_before>#include "gpgpu/demos/ray_lut.hh"
#include "gpgpu/import/load_kernel.hh"
#include "gpgpu/interplatform/cl_liegroups.hh"
#include "gpgpu/wrappers/create_context.hh"
#include "gpgpu/wrappers/errors.hh"
#include "gpgpu/wrappers/image_read_write.hh"
#include "util/timing.hh"
#include "viewer/interaction/ui2d.hh"
#include "viewer/primitives/simple_geometry.hh"
#include "viewer/window_3d.hh"
#include "util/environment.hh"
#include "eigen.hh"
#include "out.hh"
#include "util/waves.hh"
#include <CL/cl.hpp>
#include <iostream>
#include <vector>
#include "gpgpu/demos/signed_distance_shapes.hh"
struct ImageSize {
std::size_t cols = -1;
std::size_t rows = -1;
};
estimation::NonlinearCameraModel nice_model(int cols, int rows) {
estimation::ProjectionCoefficients proj_coeffs;
proj_coeffs.fx = rows;
proj_coeffs.fy = rows;
proj_coeffs.cx = cols / 2;
proj_coeffs.cy = rows / 2;
proj_coeffs.k1 = 0.0;
proj_coeffs.k2 = -0.0;
proj_coeffs.p1 = 0.0;
proj_coeffs.p2 = 0.0;
proj_coeffs.k3 = 0.0;
proj_coeffs.rows = rows;
proj_coeffs.cols = cols;
const estimation::NonlinearCameraModel model(proj_coeffs);
return model;
}
void draw(viewer::Window3D& view,
viewer::Ui2d& ui2d,
cl::CommandQueue& cmd_queue,
cl::Kernel& sdf_kernel,
cl::Image2D& dv_rendered_image,
const RenderConfig& cc_cfg,
const ImageSize& out_im_size,
float t) {
// const jcc::PrintingScopedTimer tt("Frame Time");
const SE3 world_from_camera = view.camera_from_world().inverse();
const jcc::clSE3 cl_world_from_camera(world_from_camera);
JCHECK_STATUS(sdf_kernel.setArg(2, cl_world_from_camera));
const clRenderConfig cfg = cc_cfg.convert();
JCHECK_STATUS(sdf_kernel.setArg(3, cfg));
cl_float cl_zoom = 0.0001f;
JCHECK_STATUS(sdf_kernel.setArg(4, cl_zoom));
cl_float cl_t = t;
JCHECK_STATUS(sdf_kernel.setArg(5, cl_t));
const cl::NDRange work_group_size{static_cast<std::size_t>(out_im_size.cols),
static_cast<std::size_t>(out_im_size.rows)};
JCHECK_STATUS(
cmd_queue.enqueueNDRangeKernel(sdf_kernel, {0}, work_group_size, {480, 1u}));
cmd_queue.flush();
cv::Mat out_img(cv::Size(out_im_size.cols, out_im_size.rows), CV_32FC4,
cv::Scalar(0.0, 0.0, 0.0, 0.0));
jcc::read_image_from_device(cmd_queue, dv_rendered_image, out(out_img));
out_img.convertTo(out_img, CV_8UC4);
cv::cvtColor(out_img, out_img, CV_BGRA2BGR);
// ui2d.add_image(out_img, 1.0);
ui2d.flip();
}
int main() {
const auto view = viewer::get_window3d("Render Visualization");
view->set_view_preset(viewer::Window3D::ViewSetting::CAMERA);
view->set_azimuth(0.0);
view->set_elevation(0.0);
const auto background = view->add_primitive<viewer::SimpleGeometry>();
const geometry::shapes::Plane ground{jcc::Vec3::UnitZ(), 0.0};
background->add_plane({ground});
background->flip();
const auto ui2d = view->add_primitive<viewer::Ui2d>();
const auto geo = view->add_primitive<viewer::SimpleGeometry>();
cl_int status = 0;
const auto cl_info = jcc::create_context();
const auto kernels = read_kernels(
cl_info, jcc::Environment::repo_path() + "gpgpu/demos/signed_distance.cl");
auto sdf_kernel = kernels.at("compute_sdf");
cl::CommandQueue cmd_queue(cl_info.context);
ImageSize out_im_size;
out_im_size.cols = 2 * 480;
out_im_size.rows = 2 * 480;
const auto model = nice_model(out_im_size.cols, out_im_size.rows);
//
// Send the ray LUT
//
const cl::ImageFormat ray_lut_fmt(CL_RGBA, CL_FLOAT);
cl::Image2D dv_ray_lut(cl_info.context, CL_MEM_READ_ONLY, ray_lut_fmt, out_im_size.cols,
out_im_size.rows, 0, nullptr, &status);
{
JCHECK_STATUS(status);
const cv::Mat ray_lut =
jcc::create_ray_lut(model, out_im_size.cols, out_im_size.rows).clone();
jcc::send_image_to_device(cmd_queue, dv_ray_lut, ray_lut);
}
//
// Prepare a rendered image
//
const cl::ImageFormat output_image_fmt(CL_RGBA, CL_FLOAT);
cl::Image2D dv_rendered_image(cl_info.context, CL_MEM_WRITE_ONLY, output_image_fmt,
out_im_size.cols, out_im_size.rows, 0, nullptr, &status);
JCHECK_STATUS(sdf_kernel.setArg(0, dv_ray_lut));
JCHECK_STATUS(sdf_kernel.setArg(1, dv_rendered_image));
view->add_menu_hotkey("debug_mode", 0, 'P', 5);
view->add_menu_hotkey("terminal_iteration", 6, 'I', 24);
view->add_menu_hotkey("test_feature", 0, 'F', 2);
float t = 0.0;
RenderConfig cc_cfg;
view->add_toggle_callback("terminal_iteration", [&](int iter_ct) {
std::cout << "\tIteration Count --> " << iter_ct * 10 << std::endl;
cc_cfg.terminal_iteration = iter_ct * 10;
draw(*view, *ui2d, cmd_queue, sdf_kernel, dv_rendered_image, cc_cfg, out_im_size, t);
});
view->add_toggle_callback("test_feature", [&](int feature) {
std::cout << "\tTest Feature --> " << feature << std::endl;
cc_cfg.test_feature = feature;
draw(*view, *ui2d, cmd_queue, sdf_kernel, dv_rendered_image, cc_cfg, out_im_size, t);
});
view->add_toggle_callback("debug_mode", [&](int dbg_mode) {
if (dbg_mode == 1) {
std::cout << "\tSetting Debug Mode: Iterations" << std::endl;
} else if (dbg_mode == 2) {
std::cout << "\tSetting Debug Mode: Cone Distance" << std::endl;
} else if (dbg_mode == 3) {
std::cout << "\tSetting Debug Mode: Ray Length" << std::endl;
} else if (dbg_mode == 4) {
std::cout << "\tSetting Debug Mode: Normals" << std::endl;
} else {
std::cout << "\tDisabling Debug Mode" << std::endl;
}
cc_cfg.debug_mode = dbg_mode;
draw(*view, *ui2d, cmd_queue, sdf_kernel, dv_rendered_image, cc_cfg, out_im_size, t);
});
view->run_menu_callbacks();
view->trigger_continue();
while (true) {
t += 0.1;
// cc_cfg.terminal_iteration = view->get_menu("terminal_iteration") * 10;
draw(*view, *ui2d, cmd_queue, sdf_kernel, dv_rendered_image, cc_cfg, out_im_size, t);
view->spin_until_step();
}
}
<commit_msg>More debug power in signed distance<commit_after>#include "gpgpu/demos/ray_lut.hh"
#include "gpgpu/import/load_kernel.hh"
#include "gpgpu/interplatform/cl_liegroups.hh"
#include "gpgpu/wrappers/create_context.hh"
#include "gpgpu/wrappers/errors.hh"
#include "gpgpu/wrappers/image_read_write.hh"
#include "util/timing.hh"
#include "viewer/interaction/ui2d.hh"
#include "viewer/primitives/simple_geometry.hh"
#include "viewer/window_3d.hh"
#include "util/environment.hh"
#include "eigen.hh"
#include "out.hh"
#include "util/waves.hh"
#include <CL/cl.hpp>
#include <iostream>
#include <vector>
#include "gpgpu/demos/signed_distance_shapes.hh"
struct ImageSize {
std::size_t cols = -1;
std::size_t rows = -1;
};
estimation::NonlinearCameraModel nice_model(int cols, int rows) {
estimation::ProjectionCoefficients proj_coeffs;
proj_coeffs.fx = rows;
proj_coeffs.fy = rows;
proj_coeffs.cx = cols / 2;
proj_coeffs.cy = rows / 2;
proj_coeffs.k1 = 0.0;
proj_coeffs.k2 = -0.0;
proj_coeffs.p1 = 0.0;
proj_coeffs.p2 = 0.0;
proj_coeffs.k3 = 0.0;
proj_coeffs.rows = rows;
proj_coeffs.cols = cols;
const estimation::NonlinearCameraModel model(proj_coeffs);
return model;
}
void draw(viewer::Window3D& view,
viewer::Ui2d& ui2d,
cl::CommandQueue& cmd_queue,
cl::Kernel& sdf_kernel,
cl::Image2D& dv_rendered_image,
const RenderConfig& cc_cfg,
const ImageSize& out_im_size,
float t) {
const jcc::PrintingScopedTimer tt("Frame Time");
const SE3 world_from_camera = view.standard_camera_from_world().inverse();
const jcc::clSE3 cl_world_from_camera(world_from_camera);
JCHECK_STATUS(sdf_kernel.setArg(2, cl_world_from_camera));
const clRenderConfig cfg = cc_cfg.convert();
JCHECK_STATUS(sdf_kernel.setArg(3, cfg));
cl_float cl_t = t;
JCHECK_STATUS(sdf_kernel.setArg(4, cl_t));
const cl::NDRange work_group_size{static_cast<std::size_t>(out_im_size.cols),
static_cast<std::size_t>(out_im_size.rows)};
JCHECK_STATUS(
cmd_queue.enqueueNDRangeKernel(sdf_kernel, {0}, work_group_size, {480, 1u}));
cmd_queue.flush();
cv::Mat out_img(cv::Size(out_im_size.cols, out_im_size.rows), CV_32FC4,
cv::Scalar(0.0, 0.0, 0.0, 0.0));
jcc::read_image_from_device(cmd_queue, dv_rendered_image, out(out_img));
out_img.convertTo(out_img, CV_8UC4);
cv::cvtColor(out_img, out_img, CV_BGRA2BGR);
ui2d.add_image(out_img, 1.0);
ui2d.flip();
}
int main() {
const auto view = viewer::get_window3d("Render Visualization");
view->set_view_preset(viewer::Window3D::ViewSetting::CAMERA);
view->set_azimuth(0.0);
view->set_elevation(0.0);
const auto background = view->add_primitive<viewer::SimpleGeometry>();
const geometry::shapes::Plane ground{jcc::Vec3(0.0, -0.7, -0.7).normalized(), -5.0};
// const geometry::shapes::Plane ground{jcc::Vec3(0.0, 1.0, 0.0).normalized(), 1.0};
background->add_plane({ground});
background->flip();
const auto ui2d = view->add_primitive<viewer::Ui2d>();
const auto geo = view->add_primitive<viewer::SimpleGeometry>();
geo->add_point({jcc::Vec3::UnitX(), jcc::Vec4(1.0, 0.0, 0.0, 1.0), 3.0});
geo->add_point({jcc::Vec3::UnitY(), jcc::Vec4(0.0, 1.0, 0.0, 1.0), 3.0});
geo->add_point({jcc::Vec3::UnitZ(), jcc::Vec4(0.0, 0.0, 1.0, 1.0), 3.0});
geo->flip();
cl_int status = 0;
const auto cl_info = jcc::create_context();
const auto kernels = read_kernels(
cl_info, jcc::Environment::repo_path() + "gpgpu/demos/signed_distance.cl");
auto sdf_kernel = kernels.at("compute_sdf");
cl::CommandQueue cmd_queue(cl_info.context);
ImageSize out_im_size;
out_im_size.cols = 2 * 480;
out_im_size.rows = 2 * 480;
const auto model = nice_model(out_im_size.cols, out_im_size.rows);
//
// Send the ray LUT
//
const cl::ImageFormat ray_lut_fmt(CL_RGBA, CL_FLOAT);
cl::Image2D dv_ray_lut(cl_info.context, CL_MEM_READ_ONLY, ray_lut_fmt, out_im_size.cols,
out_im_size.rows, 0, nullptr, &status);
{
JCHECK_STATUS(status);
const cv::Mat ray_lut =
jcc::create_ray_lut(model, out_im_size.cols, out_im_size.rows).clone();
jcc::send_image_to_device(cmd_queue, dv_ray_lut, ray_lut);
}
//
// Prepare a rendered image
//
const cl::ImageFormat output_image_fmt(CL_RGBA, CL_FLOAT);
cl::Image2D dv_rendered_image(cl_info.context, CL_MEM_WRITE_ONLY, output_image_fmt,
out_im_size.cols, out_im_size.rows, 0, nullptr, &status);
JCHECK_STATUS(sdf_kernel.setArg(0, dv_ray_lut));
JCHECK_STATUS(sdf_kernel.setArg(1, dv_rendered_image));
view->add_menu_hotkey("debug_mode", 0, 'P', 5);
view->add_menu_hotkey("terminal_iteration", 6, 'I', 24);
view->add_menu_hotkey("test_feature", 0, 'F', 2);
float t = 0.0;
RenderConfig cc_cfg;
view->add_toggle_callback("terminal_iteration", [&](int iter_ct) {
std::cout << "\tIteration Count --> " << iter_ct * 10 << std::endl;
cc_cfg.terminal_iteration = iter_ct * 10;
draw(*view, *ui2d, cmd_queue, sdf_kernel, dv_rendered_image, cc_cfg, out_im_size, t);
});
view->add_toggle_callback("test_feature", [&](int feature) {
std::cout << "\tTest Feature --> " << feature << std::endl;
cc_cfg.test_feature = feature;
draw(*view, *ui2d, cmd_queue, sdf_kernel, dv_rendered_image, cc_cfg, out_im_size, t);
});
view->add_toggle_callback("debug_mode", [&](int dbg_mode) {
if (dbg_mode == 1) {
std::cout << "\tSetting Debug Mode: Iterations" << std::endl;
} else if (dbg_mode == 2) {
std::cout << "\tSetting Debug Mode: Cone Distance" << std::endl;
} else if (dbg_mode == 3) {
std::cout << "\tSetting Debug Mode: Ray Length" << std::endl;
} else if (dbg_mode == 4) {
std::cout << "\tSetting Debug Mode: Normals" << std::endl;
} else {
std::cout << "\tDisabling Debug Mode" << std::endl;
}
cc_cfg.debug_mode = dbg_mode;
draw(*view, *ui2d, cmd_queue, sdf_kernel, dv_rendered_image, cc_cfg, out_im_size, t);
});
view->run_menu_callbacks();
view->trigger_continue();
while (true) {
t += 0.1;
// cc_cfg.terminal_iteration = view->get_menu("terminal_iteration") * 10;
geo->add_sphere({jcc::Vec3(0.0, 0.0, 3.0), 0.5});
geo->add_sphere({jcc::Vec3(0.2, 0.0, 3.5), 1.0 + std::cos(0.05 * t)});
geo->add_sphere({jcc::Vec3(0.0, 0.0, 0.0), 0.1});
geo->flip();
draw(*view, *ui2d, cmd_queue, sdf_kernel, dv_rendered_image, cc_cfg, out_im_size, t);
view->spin_until_step();
}
}
<|endoftext|> |
<commit_before>#include "Mesh.hpp"
#include "ShaderProgram.hpp"
#include "ShaderBinding.hpp"
Mesh::Mesh(Vertex::Format format, BufferType bufferType, bool indexed) :
vertexFormat(format),
vertexCount(0),
indexCount(0),
vertexBuffer(0),
primitiveType(TRIANGLES),
bufferType(bufferType),
indexed(indexed) {
glGenBuffers(1, &vertexBuffer);
VBE_ASSERT(glGetError() == GL_NO_ERROR, "Failed to create VBO for mesh");
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
VBE_ASSERT(glGetError() == GL_NO_ERROR, "Failed to bind VBO for mesh");
glBufferData(GL_ARRAY_BUFFER, 0, nullptr, bufferType);
VBE_ASSERT(glGetError() == GL_NO_ERROR, "Failed to load VBO with empty vertex data");
if(indexed) {
glGenBuffers(1, &indexBuffer);
VBE_ASSERT(glGetError() == GL_NO_ERROR, "Failed to create IBO for mesh");
}
}
Mesh::~Mesh() {
if(vertexBuffer != 0)
glDeleteBuffers(1,&vertexBuffer);
for(std::map<GLuint,const ShaderBinding*>::iterator it = bindingsCache.begin(); it != bindingsCache.end(); ++it)
delete it->second;
}
void Mesh::draw(const ShaderProgram *program) {
VBE_ASSERT(program->getHandle() != 0, "nullptr program when about to draw mesh");
GLuint handle = program->getHandle();
if(bindingsCache.find(handle) == bindingsCache.end())
bindingsCache.insert(std::pair<GLuint,const ShaderBinding*>(handle,new ShaderBinding(program, this)));
const ShaderBinding* binding = bindingsCache.at(handle);
program->use();
binding->bindVAO();
if(!indexed) glDrawArrays(primitiveType, 0, vertexCount);
else glDrawElements(primitiveType, indexCount, GL_UNSIGNED_SHORT, 0);
}
const Vertex::Format& Mesh::getVertexFormat() const {
return vertexFormat;
}
unsigned int Mesh::getVertexCount() const {
return vertexCount;
}
unsigned int Mesh::getVertexSize() const {
return vertexFormat.vertexSize();
}
Mesh::BufferType Mesh::getType() const {
return bufferType;
}
GLuint Mesh::getVertexBuffer() const {
return vertexBuffer;
}
GLuint Mesh::getIndexBuffer() const {
return indexBuffer;
}
Mesh::PrimitiveType Mesh::getPrimitiveType() const {
return primitiveType;
}
bool Mesh::isIndexed() const {
return indexed;
}
void Mesh::setPrimitiveType(Mesh::PrimitiveType type) {
primitiveType = type;
}
void Mesh::setVertexData(void* vertexData, unsigned int newVertexCount) {
vertexCount = newVertexCount;
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vertexFormat.vertexSize() * vertexCount, vertexData, bufferType);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void Mesh::setVertexIndices(unsigned short* indexData, unsigned int newIndexCount) {
VBE_ASSERT(indexed, "Cannot set indexes for a non-indexed mesh");
indexCount = newIndexCount;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * sizeof(unsigned int), indexData, bufferType);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
Mesh* Mesh::loadFromFile(const std::string filepath, Mesh::BufferType bufferType) {
std::vector<Vertex::Element> elements;
elements.push_back(Vertex::Element(Vertex::Attribute::Position , Vertex::Element::Float, 3));
elements.push_back(Vertex::Element(Vertex::Attribute::Normal , Vertex::Element::Float, 3));
elements.push_back(Vertex::Element(Vertex::Attribute::TexCoord , Vertex::Element::Float, 2));
struct vert {
vert(vec3f pos, vec3f nor, vec2f tex) : pos(pos) , nor(nor), tex(tex) {}
vec3f pos,nor;
vec2f tex;
};
std::ifstream in(filepath.c_str(), std::ifstream::in);
VBE_ASSERT(in, "While importing OBJ: Cannot open " << filepath );
std::vector<vec3f> vertices;
std::vector<vec3f> normals;
std::vector<vec2f> textures;
std::vector<unsigned short> indices; //indices into data1
std::vector<vert> dataIndexed; //indexed data
std::vector<vert> dataNotIndexed; //unindexed data
std::string line;
while (getline(in, line)) {
if (line.substr(0,2) == "v ") {
std::istringstream s(line.substr(2));
vec3f v;
s >> v.x >> v.y >> v.z;
vertices.push_back(v);
}
else if (line.substr(0,3) == "vn ") {
std::istringstream s(line.substr(3));
vec3f v;
s >> v.x >> v.y >> v.z;
normals.push_back(v);
}
else if (line.substr(0,3) == "vt ") {
std::istringstream s(line.substr(3));
vec2f v;
s >> v.x >> v.y;
v.y = 1-v.y;
textures.push_back(v);
}
else if (line.substr(0,2) == "f ") {
std::istringstream s(line.substr(2));
std::vector<vec3s> vInf(3,vec3s(0));
char b;
s >> vInf[0].x >> b >> vInf[0].y >> b >> vInf[0].z
>> vInf[1].x >> b >> vInf[1].y >> b >> vInf[1].z
>> vInf[2].x >> b >> vInf[2].y >> b >> vInf[2].z;
vec3s indexes(-1,-1,-1);
for(unsigned int i = 0; i < 3; ++i)
for(unsigned int j = 0; j < dataIndexed.size(); ++j)
if(dataIndexed[j].pos == vertices[vInf[i].x-1] &&
dataIndexed[j].tex == textures[vInf[i].y-1] &&
dataIndexed[j].nor == normals[vInf[i].z-1])
indexes[i] = j;
for(unsigned int i = 0; i < 3; ++i) {
if(indexes[i] < 0) {
indexes[i] = dataIndexed.size();
dataIndexed.push_back(vert(vertices[vInf[i].x-1],normals[vInf[i].z-1],textures[vInf[i].y-1]));
}
indices.push_back(indexes[i]);
}
dataNotIndexed.push_back(vert(vertices[vInf[0].x-1],normals[vInf[0].z-1],textures[vInf[0].y-1]));
dataNotIndexed.push_back(vert(vertices[vInf[1].x-1],normals[vInf[1].z-1],textures[vInf[1].y-1]));
dataNotIndexed.push_back(vert(vertices[vInf[2].x-1],normals[vInf[2].z-1],textures[vInf[2].y-1]));
}
}
float sizeWithIndex = dataIndexed.size()*sizeof(dataIndexed[0])+indices.size()*sizeof(indices[0]);
float sizeWithoutIndex = dataNotIndexed.size()*sizeof(dataNotIndexed[0]);
Mesh* mesh = nullptr;
if(sizeWithoutIndex > sizeWithIndex) { //indexed
mesh = new Mesh(Vertex::Format(elements),bufferType,true);
mesh->setVertexData(&dataIndexed[0],dataIndexed.size());
mesh->setVertexIndices(&indices[0],indices.size());
}
else { //not indexed
mesh = new Mesh(Vertex::Format(elements),bufferType,false);
mesh->setVertexData(&dataNotIndexed[0],dataNotIndexed.size());
}
return mesh;
}
Mesh* Mesh::loadEmpty(Vertex::Format format, Mesh::BufferType bufferType, bool indexed) {
return new Mesh(format,bufferType,indexed);
}
<commit_msg>No longer n^2 mesh loading<commit_after>#include "Mesh.hpp"
#include "ShaderProgram.hpp"
#include "ShaderBinding.hpp"
Mesh::Mesh(Vertex::Format format, BufferType bufferType, bool indexed) :
vertexFormat(format),
vertexCount(0),
indexCount(0),
vertexBuffer(0),
primitiveType(TRIANGLES),
bufferType(bufferType),
indexed(indexed) {
glGenBuffers(1, &vertexBuffer);
VBE_ASSERT(glGetError() == GL_NO_ERROR, "Failed to create VBO for mesh");
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
VBE_ASSERT(glGetError() == GL_NO_ERROR, "Failed to bind VBO for mesh");
glBufferData(GL_ARRAY_BUFFER, 0, nullptr, bufferType);
VBE_ASSERT(glGetError() == GL_NO_ERROR, "Failed to load VBO with empty vertex data");
if(indexed) {
glGenBuffers(1, &indexBuffer);
VBE_ASSERT(glGetError() == GL_NO_ERROR, "Failed to create IBO for mesh");
}
}
Mesh::~Mesh() {
if(vertexBuffer != 0)
glDeleteBuffers(1,&vertexBuffer);
for(std::map<GLuint,const ShaderBinding*>::iterator it = bindingsCache.begin(); it != bindingsCache.end(); ++it)
delete it->second;
}
void Mesh::draw(const ShaderProgram *program) {
VBE_ASSERT(program->getHandle() != 0, "nullptr program when about to draw mesh");
GLuint handle = program->getHandle();
if(bindingsCache.find(handle) == bindingsCache.end())
bindingsCache.insert(std::pair<GLuint,const ShaderBinding*>(handle,new ShaderBinding(program, this)));
const ShaderBinding* binding = bindingsCache.at(handle);
program->use();
binding->bindVAO();
if(!indexed) glDrawArrays(primitiveType, 0, vertexCount);
else glDrawElements(primitiveType, indexCount, GL_UNSIGNED_SHORT, 0);
}
const Vertex::Format& Mesh::getVertexFormat() const {
return vertexFormat;
}
unsigned int Mesh::getVertexCount() const {
return vertexCount;
}
unsigned int Mesh::getVertexSize() const {
return vertexFormat.vertexSize();
}
Mesh::BufferType Mesh::getType() const {
return bufferType;
}
GLuint Mesh::getVertexBuffer() const {
return vertexBuffer;
}
GLuint Mesh::getIndexBuffer() const {
return indexBuffer;
}
Mesh::PrimitiveType Mesh::getPrimitiveType() const {
return primitiveType;
}
bool Mesh::isIndexed() const {
return indexed;
}
void Mesh::setPrimitiveType(Mesh::PrimitiveType type) {
primitiveType = type;
}
void Mesh::setVertexData(void* vertexData, unsigned int newVertexCount) {
vertexCount = newVertexCount;
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vertexFormat.vertexSize() * vertexCount, vertexData, bufferType);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void Mesh::setVertexIndices(unsigned short* indexData, unsigned int newIndexCount) {
VBE_ASSERT(indexed, "Cannot set indexes for a non-indexed mesh");
indexCount = newIndexCount;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * sizeof(unsigned int), indexData, bufferType);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
struct FunctorCompareVec3s{
bool operator()(const vec3s& a, const vec3s& b)
{
if(a.x != b.x) return a.x < b.x;
if(a.y != b.y) return a.y < b.y;
if(a.z != b.z) return a.z < b.z;
return false;
}
};
Mesh* Mesh::loadFromFile(const std::string filepath, Mesh::BufferType bufferType) {
std::vector<Vertex::Element> elements;
elements.push_back(Vertex::Element(Vertex::Attribute::Position , Vertex::Element::Float, 3));
elements.push_back(Vertex::Element(Vertex::Attribute::Normal , Vertex::Element::Float, 3));
elements.push_back(Vertex::Element(Vertex::Attribute::TexCoord , Vertex::Element::Float, 2));
struct vert {
vert(vec3f pos, vec3f nor, vec2f tex) : pos(pos) , nor(nor), tex(tex) {}
vec3f pos,nor;
vec2f tex;
};
std::ifstream in(filepath.c_str(), std::ifstream::in);
VBE_ASSERT(in, "While importing OBJ: Cannot open " << filepath );
std::vector<vec3f> vertices;
std::vector<vec3f> normals;
std::vector<vec2f> textures;
std::vector<unsigned short> indices; //indices into data1
std::vector<vert> dataIndexed; //indexed data
std::vector<vert> dataNotIndexed; //unindexed data
std::map<vec3s, int, FunctorCompareVec3s> indexMap;
std::string line;
while (getline(in, line)) {
if (line.substr(0,2) == "v ") {
std::istringstream s(line.substr(2));
vec3f v;
s >> v.x >> v.y >> v.z;
vertices.push_back(v);
}
else if (line.substr(0,3) == "vn ") {
std::istringstream s(line.substr(3));
vec3f v;
s >> v.x >> v.y >> v.z;
normals.push_back(v);
}
else if (line.substr(0,3) == "vt ") {
std::istringstream s(line.substr(3));
vec2f v;
s >> v.x >> v.y;
v.y = 1-v.y;
textures.push_back(v);
}
else if (line.substr(0,2) == "f ") {
std::istringstream s(line.substr(2));
std::vector<vec3s> vInf(3,vec3s(0));
char b;
s >> vInf[0].x >> b >> vInf[0].y >> b >> vInf[0].z
>> vInf[1].x >> b >> vInf[1].y >> b >> vInf[1].z
>> vInf[2].x >> b >> vInf[2].y >> b >> vInf[2].z;
vec3s indexes(-1,-1,-1);
for(unsigned int i = 0; i < 3; ++i)
{
std::map<vec3s, int, FunctorCompareVec3s>::iterator it = indexMap.find(vInf[i]);
int ind = 0;
if(it == indexMap.end())
{
ind = indexMap.size();
indexMap.insert(std::pair<vec3s, int>(vInf[i], dataIndexed.size()));
dataIndexed.push_back(vert(vertices[vInf[i].x-1],normals[vInf[i].z-1],textures[vInf[i].y-1]));
}
else
ind = it->second;
indices.push_back(ind);
dataNotIndexed.push_back(vert(vertices[vInf[i].x-1],normals[vInf[i].z-1],textures[vInf[i].y-1]));
}
}
}
float sizeWithIndex = dataIndexed.size()*sizeof(dataIndexed[0])+indices.size()*sizeof(indices[0]);
float sizeWithoutIndex = dataNotIndexed.size()*sizeof(dataNotIndexed[0]);
Mesh* mesh = nullptr;
if(sizeWithoutIndex > sizeWithIndex) { //indexed
mesh = new Mesh(Vertex::Format(elements),bufferType,true);
mesh->setVertexData(&dataIndexed[0],dataIndexed.size());
mesh->setVertexIndices(&indices[0],indices.size());
}
else { //not indexed
mesh = new Mesh(Vertex::Format(elements),bufferType,false);
mesh->setVertexData(&dataNotIndexed[0],dataNotIndexed.size());
}
return mesh;
}
Mesh* Mesh::loadEmpty(Vertex::Format format, Mesh::BufferType bufferType, bool indexed) {
return new Mesh(format,bufferType,indexed);
}
<|endoftext|> |
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2008 Sacha Schutz <[email protected]>
* Copyright (C) 2008 Olivier Gueudelot <[email protected]>
* Copyright (C) 2008 Charles Huet <[email protected]>
* Copyright (c) 2010 Arjen Hiemstra <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "mesh.h"
#include "materialinstance.h"
#include <QtGui/QMatrix4x4>
#include <QtGui/QColor>
#include "math.h"
#include "glheaders.h"
using namespace GluonGraphics;
class Mesh::MeshPrivate
{
public:
MeshPrivate()
{
buffer = 0;
vertexLoc = -1;
colorLoc = -1;
uvLoc = -1;
}
MaterialInstance* material;
GLuint buffer;
int colorOffset;
int uvOffset;
int vertexLoc;
int colorLoc;
int uvLoc;
};
Mesh::Mesh( QObject* parent )
: QObject( parent ),
d( new MeshPrivate )
{
}
Mesh::~Mesh()
{
delete d;
}
void
Mesh::load( const QString& filename )
{
if( isLoaded() )
return;
#ifdef __GNUC__
#warning Todo: Move vertex buffer related stuff to a VertexBuffer class.
#endif
QVector<float> vertices;
vertices << -1.f << -1.f << 0.f;
vertices << -1.f << 1.f << 0.f;
vertices << 1.f << 1.f << 0.f;
vertices << -1.f << -1.f << 0.f;
vertices << 1.f << 1.f << 0.f;
vertices << 1.f << -1.f << 0.f;
QVector<float> colors;
colors << 1.f << 1.f << 1.f << 1.f;
colors << 1.f << 1.f << 1.f << 1.f;
colors << 1.f << 1.f << 1.f << 1.f;
colors << 1.f << 1.f << 1.f << 1.f;
colors << 1.f << 1.f << 1.f << 1.f;
colors << 1.f << 1.f << 1.f << 1.f;
QVector<float> uvs;
uvs << 0.f << 0.f;
uvs << 0.f << 1.f;
uvs << 1.f << 1.f;
uvs << 0.f << 0.f;
uvs << 1.f << 1.f;
uvs << 1.f << 0.f;
createBuffer( vertices, colors, uvs );
}
void
Mesh::render( MaterialInstance* material )
{
renderBuffer( GL_TRIANGLES, 6, material );
}
bool
Mesh::isLoaded()
{
return d->buffer != 0;
}
void
Mesh::createBuffer( const QVector<float>& vertices, const QVector<float>& colors, const QVector<float>& uvs )
{
glGenBuffers( 1, &d->buffer );
glBindBuffer( GL_ARRAY_BUFFER, d->buffer );
glBufferData( GL_ARRAY_BUFFER, ( vertices.size() * 4 ) + ( colors.size() * 4 ) + ( uvs.size() * 4 ), 0, GL_STATIC_DRAW );
glBufferSubData( GL_ARRAY_BUFFER, 0, vertices.size() * 4, vertices.data() );
d->colorOffset = vertices.size() * 4;
glBufferSubData( GL_ARRAY_BUFFER, d->colorOffset, colors.size() * 4, colors.data() );
d->uvOffset = d->colorOffset + colors.size() * 4;
glBufferSubData( GL_ARRAY_BUFFER, d->uvOffset, uvs.size() * 4, uvs.data() );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
}
void
Mesh::renderBuffer( uint mode, int count, MaterialInstance* material )
{
if( d->buffer == 0 )
return;
if( d->vertexLoc == -1 )
d->vertexLoc = material->attributeLocation( "vertex" );
if( d->colorLoc == -1 )
d->colorLoc = material->attributeLocation( "color" );
if( d->uvLoc == -1 )
d->uvLoc = material->attributeLocation( "uv0" );
glBindBuffer( GL_ARRAY_BUFFER, d->buffer );
glVertexAttribPointer( d->vertexLoc, 3, GL_FLOAT, 0, 0, 0 );
glVertexAttribPointer( d->colorLoc, 4, GL_FLOAT, 0, 0, ( void* )( d->colorOffset ) );
glVertexAttribPointer( d->uvLoc, 2, GL_FLOAT, 0, 0, ( void* )( d->uvOffset ) );
glEnableVertexAttribArray( d->vertexLoc );
glEnableVertexAttribArray( d->colorLoc );
glEnableVertexAttribArray( d->uvLoc );
glDrawArrays( mode, 0, count );
glDisableVertexAttribArray( d->vertexLoc );
glDisableVertexAttribArray( d->colorLoc );
glDisableVertexAttribArray( d->uvLoc );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
}
#include "mesh.moc"
<commit_msg>Store the number of the vertices in createBuffer and render them all in renderBuffer. There was an hardcoded "6".<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2008 Sacha Schutz <[email protected]>
* Copyright (C) 2008 Olivier Gueudelot <[email protected]>
* Copyright (C) 2008 Charles Huet <[email protected]>
* Copyright (c) 2010 Arjen Hiemstra <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "mesh.h"
#include "materialinstance.h"
#include <QtGui/QMatrix4x4>
#include <QtGui/QColor>
#include "math.h"
#include "glheaders.h"
using namespace GluonGraphics;
class Mesh::MeshPrivate
{
public:
MeshPrivate()
{
buffer = 0;
vertexLoc = -1;
colorLoc = -1;
uvLoc = -1;
vertexCount = 0;
}
MaterialInstance* material;
GLuint buffer;
int colorOffset;
int uvOffset;
int vertexLoc;
int colorLoc;
int uvLoc;
int vertexCount;
};
Mesh::Mesh( QObject* parent )
: QObject( parent ),
d( new MeshPrivate )
{
}
Mesh::~Mesh()
{
delete d;
}
void
Mesh::load( const QString& filename )
{
if( isLoaded() )
return;
#ifdef __GNUC__
#warning Todo: Move vertex buffer related stuff to a VertexBuffer class.
#endif
QVector<float> vertices;
vertices << -1.f << -1.f << 0.f;
vertices << -1.f << 1.f << 0.f;
vertices << 1.f << 1.f << 0.f;
vertices << -1.f << -1.f << 0.f;
vertices << 1.f << 1.f << 0.f;
vertices << 1.f << -1.f << 0.f;
QVector<float> colors;
colors << 1.f << 1.f << 1.f << 1.f;
colors << 1.f << 1.f << 1.f << 1.f;
colors << 1.f << 1.f << 1.f << 1.f;
colors << 1.f << 1.f << 1.f << 1.f;
colors << 1.f << 1.f << 1.f << 1.f;
colors << 1.f << 1.f << 1.f << 1.f;
QVector<float> uvs;
uvs << 0.f << 0.f;
uvs << 0.f << 1.f;
uvs << 1.f << 1.f;
uvs << 0.f << 0.f;
uvs << 1.f << 1.f;
uvs << 1.f << 0.f;
createBuffer( vertices, colors, uvs );
}
void
Mesh::render( MaterialInstance* material )
{
renderBuffer( GL_TRIANGLES, d->vertexCount, material );
}
bool
Mesh::isLoaded()
{
return d->buffer != 0;
}
void
Mesh::createBuffer( const QVector<float>& vertices, const QVector<float>& colors, const QVector<float>& uvs )
{
glGenBuffers( 1, &d->buffer );
glBindBuffer( GL_ARRAY_BUFFER, d->buffer );
glBufferData( GL_ARRAY_BUFFER, ( vertices.size() * 4 ) + ( colors.size() * 4 ) + ( uvs.size() * 4 ), 0, GL_STATIC_DRAW );
glBufferSubData( GL_ARRAY_BUFFER, 0, vertices.size() * 4, vertices.data() );
d->colorOffset = vertices.size() * 4;
glBufferSubData( GL_ARRAY_BUFFER, d->colorOffset, colors.size() * 4, colors.data() );
d->uvOffset = d->colorOffset + colors.size() * 4;
glBufferSubData( GL_ARRAY_BUFFER, d->uvOffset, uvs.size() * 4, uvs.data() );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
d->vertexCount = vertices.size();
}
void
Mesh::renderBuffer( uint mode, int count, MaterialInstance* material )
{
if( d->buffer == 0 )
return;
if( d->vertexLoc == -1 )
d->vertexLoc = material->attributeLocation( "vertex" );
if( d->colorLoc == -1 )
d->colorLoc = material->attributeLocation( "color" );
if( d->uvLoc == -1 )
d->uvLoc = material->attributeLocation( "uv0" );
glBindBuffer( GL_ARRAY_BUFFER, d->buffer );
glVertexAttribPointer( d->vertexLoc, 3, GL_FLOAT, 0, 0, 0 );
glVertexAttribPointer( d->colorLoc, 4, GL_FLOAT, 0, 0, ( void* )( d->colorOffset ) );
glVertexAttribPointer( d->uvLoc, 2, GL_FLOAT, 0, 0, ( void* )( d->uvOffset ) );
glEnableVertexAttribArray( d->vertexLoc );
glEnableVertexAttribArray( d->colorLoc );
glEnableVertexAttribArray( d->uvLoc );
glDrawArrays( mode, 0, count );
glDisableVertexAttribArray( d->vertexLoc );
glDisableVertexAttribArray( d->colorLoc );
glDisableVertexAttribArray( d->uvLoc );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
}
#include "mesh.moc"
<|endoftext|> |
<commit_before>#include "graphicwindow.h"
GraphicWindow::GraphicWindow(const bhs::SimCondition& simCondition)
: m_lineShaders(new LineShaders)
, m_particleShaders(new ParticleShaders(&m_threadAdmin))
, m_computeShaders(new ComputeShaders)
, m_threadAdmin(this, m_computeShaders)
, m_walkSpeed(0.1f)
, m_lookAroundSpeed(1.0f)
, m_mousePressing(false)
, m_camera(CAMERA_INI_POS)
, m_fpsPreFrame(0)
, m_isCircleStrafing(false)
, m_circleStrafingSpeed(1.0f)
, m_simCondition(&simCondition)
{
m_camera.lookAtZero(1.0f);
m_camera.standXZ(false, 1.0f);
m_camera.lookAtZero(1.0f);
connect(&UpdateUi::it(), &UpdateUi::frameAdvance, &m_threadAdmin, &ThreadAdmin::frameAdvance);
connect(&UpdateUi::it(), &UpdateUi::resultReady, &m_threadAdmin, &ThreadAdmin::handleResults);
connect(&UpdateUi::it(), &UpdateUi::resetParticles, this, &GraphicWindow::resetParticles);
m_threadAdmin.start();
}
GraphicWindow::~GraphicWindow()
{
m_uiTimer.stop();
m_fpsTimer.stop();
m_threadAdmin.quit();
m_threadAdmin.wait();
makeCurrent();
delete m_computeShaders;
delete m_lineShaders;
delete m_particleShaders;
doneCurrent();
}
void GraphicWindow::initializeGL()
{
initializeOpenGLFunctions();
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
//glDepthFunc(GL_LESS);
m_lineShaders->initialize();
if (!m_particleShaders->initialize(this->height()))
return; // TODO error message
bhs::SimCondition sim;
m_particleShaders->setNBodyEngine(sim);
m_computeShaders->initialize();
m_threadAdmin.setComputeDevice(sim.compute);
m_uiTimer.start(30, this);
m_fpsTimer.start(1000, this);
}
void GraphicWindow::resizeGL(int w, int h)
{
qreal aspect = qreal(w) / qreal(h ? h : 1);
const qreal zNear = 1.0, zFar = 100.0, fov = 30.0;
m_projection.setToIdentity();
m_projection.perspective(fov, aspect, zNear, zFar);
m_particleShaders->resize(h);
}
void GraphicWindow::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
auto viewMatrix = m_camera.viewMatrix();
m_lineShaders->paint(m_projection * viewMatrix);
m_particleShaders->paint(m_projection * viewMatrix);
}
void GraphicWindow::keyPressEvent(QKeyEvent *ev)
{
if (ev->isAutoRepeat())
return;
if (ev->key() == Qt::Key_Escape)
{
m_camera.reset(CAMERA_INI_POS * 10.0f);
m_camera.lookAt(CAMERA_INI_POS, 1.0f);
m_camera.standXZ(false, 1.0f);
m_camera.lookAt(CAMERA_INI_POS, 1.0f);
}
m_keyPressing.append(static_cast<Qt::Key>(ev->key()));
}
void GraphicWindow::keyReleaseEvent(QKeyEvent* ev)
{
if (ev->isAutoRepeat())
return;
m_keyPressing.removeAll(static_cast<Qt::Key>(ev->key()));
}
void GraphicWindow::mousePressEvent(QMouseEvent* ev)
{
m_mouseLastPosition = ev->localPos();
m_mousePressing = true;
setCursor(Qt::BlankCursor);
m_mousePressPosition = QPoint(m_mouseLastPosition.x(), m_mouseLastPosition.y());
if (ev->buttons() == (Qt::MiddleButton))
{
m_camera.standXZ(false, 1.0f);
m_camera.lookAtZero(1.0f);
}
}
void GraphicWindow::mouseMoveEvent(QMouseEvent* ev)
{
if (m_mousePressing)
{
QPointF pos = ev->localPos();
QPointF diff = pos - m_mouseLastPosition;
if (ev->buttons() == Qt::LeftButton)
{
diff *= 0.01f;
m_camera.circleStrafing(diff.x());
m_camera.roundUp(-diff.y());
}
else if (ev->buttons() == Qt::RightButton)
{
diff *= 0.005f;
m_camera.strafe(diff.x());
m_camera.jump(-diff.y());
}
else if (ev->buttons() == (Qt::LeftButton | Qt::RightButton))
{
diff *= 0.1f;
m_camera.roll(diff.x());
}
m_mouseLastPosition = pos;
}
}
void GraphicWindow::mouseReleaseEvent(QMouseEvent*)
{
if (m_mousePressing)
{
setCursor(Qt::ArrowCursor);
QCursor::setPos(mapToGlobal(m_mousePressPosition));
m_mousePressing = false;
}
}
void GraphicWindow::wheelEvent(QWheelEvent* ev)
{
QPoint numDegrees = ev->angleDelta();
if (!numDegrees.isNull())
m_camera.walk(-numDegrees.y() * 0.01f);
}
void GraphicWindow::timerEvent(QTimerEvent* ev)
{
if (ev->timerId() == m_uiTimer.timerId()) {
if (m_keyPressing.indexOf(Qt::Key_W) >= 0)
m_camera.walk(-m_walkSpeed);
if (m_keyPressing.indexOf(Qt::Key_S) >= 0)
m_camera.walk(m_walkSpeed);
if (m_keyPressing.indexOf(Qt::Key_D) >= 0)
m_camera.strafe(-m_walkSpeed);
if (m_keyPressing.indexOf(Qt::Key_A) >= 0)
m_camera.strafe(m_walkSpeed);
if (m_keyPressing.indexOf(Qt::Key_Space) >= 0)
m_camera.jump(-m_walkSpeed);
if (m_keyPressing.indexOf(Qt::Key_Control) >= 0)
m_camera.jump(m_walkSpeed);
if (m_keyPressing.indexOf(Qt::Key_Up) >= 0)
m_camera.pitch(-m_lookAroundSpeed);
if (m_keyPressing.indexOf(Qt::Key_Down) >= 0)
m_camera.pitch(m_lookAroundSpeed);
if (m_keyPressing.indexOf(Qt::Key_Left) >= 0)
m_camera.yaw(-m_lookAroundSpeed);
if (m_keyPressing.indexOf(Qt::Key_Right) >= 0)
m_camera.yaw(m_lookAroundSpeed);
if (m_keyPressing.indexOf(Qt::Key_E) >= 0)
m_camera.roll(-m_lookAroundSpeed);
if (m_keyPressing.indexOf(Qt::Key_Q) >= 0)
m_camera.roll(m_lookAroundSpeed);
if (m_keyPressing.indexOf(Qt::Key_Shift) >= 0)
m_camera.standXZ();
if (m_keyPressing.indexOf(Qt::Key_Tab) >= 0)
m_camera.lookAtZero(0.2f);
if (m_keyPressing.indexOf(Qt::Key_Escape) >= 0)
m_camera.setPosition(CAMERA_INI_POS, 0.1f);
if (m_keyPressing.indexOf(Qt::Key_Home) >= 0)
m_camera.setPosition(QVector3D(), 0.1f);
if (m_keyPressing.indexOf(Qt::Key_End) >= 0)
m_camera.setPosition(QVector3D(), -0.1f);
if (m_isCircleStrafing)
m_camera.circleStrafing(m_circleStrafingSpeed * m_walkSpeed);
if (m_simCondition->compute == bhs::Compute::CPU)
m_particleShaders->updateGL();
emit UpdateUi::it().displayFrameNumber(m_threadAdmin.frameNum());
update();
}
else if (ev->timerId() == m_fpsTimer.timerId())
{
emit UpdateUi::it().displayFps(m_threadAdmin.frameNum() - m_fpsPreFrame);
m_fpsPreFrame = m_threadAdmin.frameNum();
}
}
void GraphicWindow::focusOutEvent(QFocusEvent*)
{
m_keyPressing.clear();
m_mousePressing = false;
}
void GraphicWindow::enableGridLines(const bool enabled)
{
m_lineShaders->enableGridLines(enabled);
}
void GraphicWindow::startSim()
{
int msec = 0;
if (m_simCondition->compute == bhs::Compute::GPU)
{
if (m_particleShaders->numberOfParticle() > 300)
msec = 1;
else if (m_particleShaders->numberOfParticle() > 2000)
msec = 10;
}
m_threadAdmin.startSim(msec);
}
void GraphicWindow::setLineType(const int index)
{
m_lineShaders->setLineType(index);
}
void GraphicWindow::frameAdvance1()
{
emit UpdateUi::it().frameAdvance(1);
}
void GraphicWindow::frameAdvance10()
{
emit UpdateUi::it().frameAdvance(10);
}
void GraphicWindow::frameAdvance100()
{
emit UpdateUi::it().frameAdvance(100);
}
void GraphicWindow::circleStrafing(const bool on)
{
if (on)
m_circleStrafingSpeed = -m_circleStrafingSpeed;
m_isCircleStrafing = on;
m_camera.lookAtZero(1.0f);
}
void GraphicWindow::resetWaitForDone(const bhs::SimCondition& sim)
{
m_fpsPreFrame = 0;
m_simCondition = ∼
m_threadAdmin.reset();
}
void GraphicWindow::resetParticles()
{
m_particleShaders->reset(*m_simCondition);
m_threadAdmin.setComputeDevice(m_simCondition->compute);
}
void GraphicWindow::setModelScale(const QString& text)
{
bool ok;
auto val = text.toDouble(&ok);
if (ok && val > 0.0)
m_particleShaders->setModelScale(1.0 / val);
}
void GraphicWindow::setModelScaleInt(int val)
{
double r1 = (double)val / (double)UpdateUi::SCALE_SLIDER_CENTER;
m_particleShaders->setModelScaleRatio(pow(r1, 10.0));
}
QString GraphicWindow::particleData()
{
return m_particleShaders->particleData();
}
int GraphicWindow::frameNumber()
{
return m_threadAdmin.frameNum();
}
<commit_msg>adjust mouse speed<commit_after>#include "graphicwindow.h"
GraphicWindow::GraphicWindow(const bhs::SimCondition& simCondition)
: m_lineShaders(new LineShaders)
, m_particleShaders(new ParticleShaders(&m_threadAdmin))
, m_computeShaders(new ComputeShaders)
, m_threadAdmin(this, m_computeShaders)
, m_walkSpeed(0.1f)
, m_lookAroundSpeed(1.0f)
, m_mousePressing(false)
, m_camera(CAMERA_INI_POS)
, m_fpsPreFrame(0)
, m_isCircleStrafing(false)
, m_circleStrafingSpeed(1.0f)
, m_simCondition(&simCondition)
{
m_camera.lookAtZero(1.0f);
m_camera.standXZ(false, 1.0f);
m_camera.lookAtZero(1.0f);
connect(&UpdateUi::it(), &UpdateUi::frameAdvance, &m_threadAdmin, &ThreadAdmin::frameAdvance);
connect(&UpdateUi::it(), &UpdateUi::resultReady, &m_threadAdmin, &ThreadAdmin::handleResults);
connect(&UpdateUi::it(), &UpdateUi::resetParticles, this, &GraphicWindow::resetParticles);
m_threadAdmin.start();
}
GraphicWindow::~GraphicWindow()
{
m_uiTimer.stop();
m_fpsTimer.stop();
m_threadAdmin.quit();
m_threadAdmin.wait();
makeCurrent();
delete m_computeShaders;
delete m_lineShaders;
delete m_particleShaders;
doneCurrent();
}
void GraphicWindow::initializeGL()
{
initializeOpenGLFunctions();
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
//glDepthFunc(GL_LESS);
m_lineShaders->initialize();
if (!m_particleShaders->initialize(this->height()))
return; // TODO error message
bhs::SimCondition sim;
m_particleShaders->setNBodyEngine(sim);
m_computeShaders->initialize();
m_threadAdmin.setComputeDevice(sim.compute);
m_uiTimer.start(30, this);
m_fpsTimer.start(1000, this);
}
void GraphicWindow::resizeGL(int w, int h)
{
qreal aspect = qreal(w) / qreal(h ? h : 1);
const qreal zNear = 1.0, zFar = 100.0, fov = 30.0;
m_projection.setToIdentity();
m_projection.perspective(fov, aspect, zNear, zFar);
m_particleShaders->resize(h);
}
void GraphicWindow::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
auto viewMatrix = m_camera.viewMatrix();
m_lineShaders->paint(m_projection * viewMatrix);
m_particleShaders->paint(m_projection * viewMatrix);
}
void GraphicWindow::keyPressEvent(QKeyEvent *ev)
{
if (ev->isAutoRepeat())
return;
if (ev->key() == Qt::Key_Escape)
{
m_camera.reset(CAMERA_INI_POS * 10.0f);
m_camera.lookAt(CAMERA_INI_POS, 1.0f);
m_camera.standXZ(false, 1.0f);
m_camera.lookAt(CAMERA_INI_POS, 1.0f);
}
m_keyPressing.append(static_cast<Qt::Key>(ev->key()));
}
void GraphicWindow::keyReleaseEvent(QKeyEvent* ev)
{
if (ev->isAutoRepeat())
return;
m_keyPressing.removeAll(static_cast<Qt::Key>(ev->key()));
}
void GraphicWindow::mousePressEvent(QMouseEvent* ev)
{
m_mouseLastPosition = ev->localPos();
m_mousePressing = true;
setCursor(Qt::BlankCursor);
m_mousePressPosition = QPoint(m_mouseLastPosition.x(), m_mouseLastPosition.y());
if (ev->buttons() == (Qt::MiddleButton))
{
m_camera.standXZ(false, 1.0f);
m_camera.lookAtZero(1.0f);
}
}
void GraphicWindow::mouseMoveEvent(QMouseEvent* ev)
{
if (m_mousePressing)
{
QPointF pos = ev->localPos();
QPointF diff = pos - m_mouseLastPosition;
if (ev->buttons() == Qt::LeftButton)
{
diff *= 0.02f;
m_camera.circleStrafing(diff.x());
m_camera.roundUp(-diff.y());
}
else if (ev->buttons() == Qt::RightButton)
{
diff *= 0.002f;
m_camera.strafe(diff.x());
m_camera.jump(-diff.y());
}
else if (ev->buttons() == (Qt::LeftButton | Qt::RightButton))
{
diff *= 0.1f;
m_camera.roll(diff.x());
}
m_mouseLastPosition = pos;
}
}
void GraphicWindow::mouseReleaseEvent(QMouseEvent*)
{
if (m_mousePressing)
{
setCursor(Qt::ArrowCursor);
QCursor::setPos(mapToGlobal(m_mousePressPosition));
m_mousePressing = false;
}
}
void GraphicWindow::wheelEvent(QWheelEvent* ev)
{
QPoint numDegrees = ev->angleDelta();
if (!numDegrees.isNull())
m_camera.walk(-numDegrees.y() * 0.01f);
}
void GraphicWindow::timerEvent(QTimerEvent* ev)
{
if (ev->timerId() == m_uiTimer.timerId()) {
if (m_keyPressing.indexOf(Qt::Key_W) >= 0)
m_camera.walk(-m_walkSpeed);
if (m_keyPressing.indexOf(Qt::Key_S) >= 0)
m_camera.walk(m_walkSpeed);
if (m_keyPressing.indexOf(Qt::Key_D) >= 0)
m_camera.strafe(-m_walkSpeed);
if (m_keyPressing.indexOf(Qt::Key_A) >= 0)
m_camera.strafe(m_walkSpeed);
if (m_keyPressing.indexOf(Qt::Key_Space) >= 0)
m_camera.jump(-m_walkSpeed);
if (m_keyPressing.indexOf(Qt::Key_Control) >= 0)
m_camera.jump(m_walkSpeed);
if (m_keyPressing.indexOf(Qt::Key_Up) >= 0)
m_camera.pitch(-m_lookAroundSpeed);
if (m_keyPressing.indexOf(Qt::Key_Down) >= 0)
m_camera.pitch(m_lookAroundSpeed);
if (m_keyPressing.indexOf(Qt::Key_Left) >= 0)
m_camera.yaw(-m_lookAroundSpeed);
if (m_keyPressing.indexOf(Qt::Key_Right) >= 0)
m_camera.yaw(m_lookAroundSpeed);
if (m_keyPressing.indexOf(Qt::Key_E) >= 0)
m_camera.roll(-m_lookAroundSpeed);
if (m_keyPressing.indexOf(Qt::Key_Q) >= 0)
m_camera.roll(m_lookAroundSpeed);
if (m_keyPressing.indexOf(Qt::Key_Shift) >= 0)
m_camera.standXZ();
if (m_keyPressing.indexOf(Qt::Key_Tab) >= 0)
m_camera.lookAtZero(0.2f);
if (m_keyPressing.indexOf(Qt::Key_Escape) >= 0)
m_camera.setPosition(CAMERA_INI_POS, 0.1f);
if (m_keyPressing.indexOf(Qt::Key_Home) >= 0)
m_camera.setPosition(QVector3D(), 0.1f);
if (m_keyPressing.indexOf(Qt::Key_End) >= 0)
m_camera.setPosition(QVector3D(), -0.1f);
if (m_isCircleStrafing)
m_camera.circleStrafing(m_circleStrafingSpeed * m_walkSpeed);
if (m_simCondition->compute == bhs::Compute::CPU)
m_particleShaders->updateGL();
emit UpdateUi::it().displayFrameNumber(m_threadAdmin.frameNum());
update();
}
else if (ev->timerId() == m_fpsTimer.timerId())
{
emit UpdateUi::it().displayFps(m_threadAdmin.frameNum() - m_fpsPreFrame);
m_fpsPreFrame = m_threadAdmin.frameNum();
}
}
void GraphicWindow::focusOutEvent(QFocusEvent*)
{
m_keyPressing.clear();
m_mousePressing = false;
}
void GraphicWindow::enableGridLines(const bool enabled)
{
m_lineShaders->enableGridLines(enabled);
}
void GraphicWindow::startSim()
{
int msec = 0;
if (m_simCondition->compute == bhs::Compute::GPU)
{
if (m_particleShaders->numberOfParticle() > 300)
msec = 1;
else if (m_particleShaders->numberOfParticle() > 2000)
msec = 10;
}
m_threadAdmin.startSim(msec);
}
void GraphicWindow::setLineType(const int index)
{
m_lineShaders->setLineType(index);
}
void GraphicWindow::frameAdvance1()
{
emit UpdateUi::it().frameAdvance(1);
}
void GraphicWindow::frameAdvance10()
{
emit UpdateUi::it().frameAdvance(10);
}
void GraphicWindow::frameAdvance100()
{
emit UpdateUi::it().frameAdvance(100);
}
void GraphicWindow::circleStrafing(const bool on)
{
if (on)
m_circleStrafingSpeed = -m_circleStrafingSpeed;
m_isCircleStrafing = on;
m_camera.lookAtZero(1.0f);
}
void GraphicWindow::resetWaitForDone(const bhs::SimCondition& sim)
{
m_fpsPreFrame = 0;
m_simCondition = ∼
m_threadAdmin.reset();
}
void GraphicWindow::resetParticles()
{
m_particleShaders->reset(*m_simCondition);
m_threadAdmin.setComputeDevice(m_simCondition->compute);
}
void GraphicWindow::setModelScale(const QString& text)
{
bool ok;
auto val = text.toDouble(&ok);
if (ok && val > 0.0)
m_particleShaders->setModelScale(1.0 / val);
}
void GraphicWindow::setModelScaleInt(int val)
{
double r1 = (double)val / (double)UpdateUi::SCALE_SLIDER_CENTER;
m_particleShaders->setModelScaleRatio(pow(r1, 10.0));
}
QString GraphicWindow::particleData()
{
return m_particleShaders->particleData();
}
int GraphicWindow::frameNumber()
{
return m_threadAdmin.frameNum();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 midnightBITS
*
* 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 __JIRA_JIRA_HPP__
#define __JIRA_JIRA_HPP__
#include <json/json.hpp>
#include <memory>
#include <string>
#include <vector>
#include <map>
namespace jira
{
enum class styles {
unset,
none,
error,
link
};
struct node {
virtual ~node() {}
virtual void setTooltip(const std::string& text) = 0;
virtual void addChild(std::unique_ptr<node>&& child) = 0;
virtual void setClass(styles) = 0;
virtual const std::vector<std::unique_ptr<node>>& values() const = 0;
};
class server;
struct document {
virtual ~document() {}
virtual void setCurrent(const std::shared_ptr<server>&) = 0;
virtual std::unique_ptr<node> createTableRow() = 0;
virtual std::unique_ptr<node> createSpan() = 0;
virtual std::unique_ptr<node> createIcon(const std::string& uri, const std::string& text, const std::string& description) = 0;
virtual std::unique_ptr<node> createUser(bool active, const std::string& display, const std::string& email, const std::string& login, std::map<uint32_t, std::string>&& avatar) = 0;
virtual std::unique_ptr<node> createLink(const std::string& href) = 0;
virtual std::unique_ptr<node> createText(const std::string& text) = 0;
};
class record {
std::unique_ptr<node> m_row;
std::string m_uri;
std::string m_key;
std::string m_id;
public:
record(const record&) = delete;
record& operator=(const record&) = delete;
record(record&&) = default;
record& operator=(record&&) = default;
record() = default;
std::string issue_uri() const;
void uri(const std::string& val) { m_uri = val; }
void issue_key(const std::string& key) { m_key = key; }
void issue_id(const std::string& id) { m_id = id; }
const std::string& issue_key() const { return m_key; }
const std::string& issue_id() const { return m_id; }
void setRow(std::unique_ptr<node>&&);
node* getRow() const { return m_row.get(); }
void addVal(std::unique_ptr<node>&&);
const std::vector<std::unique_ptr<node>>& values() const { return m_row->values(); }
};
struct type {
type(const std::string& id, const std::string& title) : m_id(id), m_title(title) {}
virtual ~type() {}
virtual const std::string& id() const { return m_id; }
virtual const std::string& title() const { return titleFull(); }
virtual const std::string& titleFull() const { return m_title; }
virtual std::unique_ptr<node> visit(document* doc, const record& issue, const json::map& object) const = 0;
virtual std::unique_ptr<node> visit(document* doc, const record& issue, const json::value& value) const;
private:
std::string m_id;
std::string m_title;
};
class db;
class model {
friend class db;
std::string m_uri;
std::vector<std::unique_ptr<type>> m_cols;
model(std::vector<std::unique_ptr<type>>&& cols, const std::string& uri) : m_cols(std::move(cols)), m_uri(uri) {}
public:
model() = default;
record visit(document* doc, const json::value& object, const std::string& key, const std::string& id) const;
const std::vector<std::unique_ptr<type>>& cols() const { return m_cols; }
};
class db {
struct creator {
virtual ~creator() {}
virtual std::unique_ptr<type> create(const std::string& id, const std::string& title) = 0;
};
template <typename T>
struct creator_impl : creator {
std::unique_ptr<type> create(const std::string& id, const std::string& title) override
{
return std::make_unique<T>(id, title);
}
};
struct creator_descr {
std::unique_ptr<creator> m_fn;
std::string m_sep;
};
struct type_descr {
std::string m_type;
std::string m_display;
bool m_array;
};
std::string m_uri;
std::map<std::string, creator_descr> m_types;
std::map<std::string, type_descr> m_fields;
template <typename T>
inline void field(const std::string& type, const std::string& sep = {})
{
auto it = m_types.find(type);
creator_descr creator{ std::make_unique<creator_impl<T>>(), sep };
if (it == m_types.end()) {
m_types.emplace(type, std::move(creator));
return;
}
it->second = std::move(creator);
}
std::unique_ptr<type> create(const std::string& id) const;
public:
db() = default;
db(const std::string& uri);
void reset_defs();
void debug_dump(std::ostream&);
model create_model(const std::vector<std::string>& names);
bool field_def(const std::string& id, bool is_array, const std::string& type, const std::string& display);
};
}
#endif // __JIRA_JIRA_HPP__
<commit_msg>[libjira] Adding a class for table header<commit_after>/*
* Copyright (C) 2015 midnightBITS
*
* 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 __JIRA_JIRA_HPP__
#define __JIRA_JIRA_HPP__
#include <json/json.hpp>
#include <memory>
#include <string>
#include <vector>
#include <map>
namespace jira
{
enum class styles {
unset,
none,
error,
link,
tableHeader
};
struct node {
virtual ~node() {}
virtual void setTooltip(const std::string& text) = 0;
virtual void addChild(std::unique_ptr<node>&& child) = 0;
virtual void setClass(styles) = 0;
virtual const std::vector<std::unique_ptr<node>>& values() const = 0;
};
class server;
struct document {
virtual ~document() {}
virtual void setCurrent(const std::shared_ptr<server>&) = 0;
virtual std::unique_ptr<node> createTableRow() = 0;
virtual std::unique_ptr<node> createSpan() = 0;
virtual std::unique_ptr<node> createIcon(const std::string& uri, const std::string& text, const std::string& description) = 0;
virtual std::unique_ptr<node> createUser(bool active, const std::string& display, const std::string& email, const std::string& login, std::map<uint32_t, std::string>&& avatar) = 0;
virtual std::unique_ptr<node> createLink(const std::string& href) = 0;
virtual std::unique_ptr<node> createText(const std::string& text) = 0;
};
class record {
std::unique_ptr<node> m_row;
std::string m_uri;
std::string m_key;
std::string m_id;
public:
record(const record&) = delete;
record& operator=(const record&) = delete;
record(record&&) = default;
record& operator=(record&&) = default;
record() = default;
std::string issue_uri() const;
void uri(const std::string& val) { m_uri = val; }
void issue_key(const std::string& key) { m_key = key; }
void issue_id(const std::string& id) { m_id = id; }
const std::string& issue_key() const { return m_key; }
const std::string& issue_id() const { return m_id; }
void setRow(std::unique_ptr<node>&&);
node* getRow() const { return m_row.get(); }
void addVal(std::unique_ptr<node>&&);
const std::vector<std::unique_ptr<node>>& values() const { return m_row->values(); }
};
struct type {
type(const std::string& id, const std::string& title) : m_id(id), m_title(title) {}
virtual ~type() {}
virtual const std::string& id() const { return m_id; }
virtual const std::string& title() const { return titleFull(); }
virtual const std::string& titleFull() const { return m_title; }
virtual std::unique_ptr<node> visit(document* doc, const record& issue, const json::map& object) const = 0;
virtual std::unique_ptr<node> visit(document* doc, const record& issue, const json::value& value) const;
private:
std::string m_id;
std::string m_title;
};
class db;
class model {
friend class db;
std::string m_uri;
std::vector<std::unique_ptr<type>> m_cols;
model(std::vector<std::unique_ptr<type>>&& cols, const std::string& uri) : m_cols(std::move(cols)), m_uri(uri) {}
public:
model() = default;
record visit(document* doc, const json::value& object, const std::string& key, const std::string& id) const;
const std::vector<std::unique_ptr<type>>& cols() const { return m_cols; }
};
class db {
struct creator {
virtual ~creator() {}
virtual std::unique_ptr<type> create(const std::string& id, const std::string& title) = 0;
};
template <typename T>
struct creator_impl : creator {
std::unique_ptr<type> create(const std::string& id, const std::string& title) override
{
return std::make_unique<T>(id, title);
}
};
struct creator_descr {
std::unique_ptr<creator> m_fn;
std::string m_sep;
};
struct type_descr {
std::string m_type;
std::string m_display;
bool m_array;
};
std::string m_uri;
std::map<std::string, creator_descr> m_types;
std::map<std::string, type_descr> m_fields;
template <typename T>
inline void field(const std::string& type, const std::string& sep = {})
{
auto it = m_types.find(type);
creator_descr creator{ std::make_unique<creator_impl<T>>(), sep };
if (it == m_types.end()) {
m_types.emplace(type, std::move(creator));
return;
}
it->second = std::move(creator);
}
std::unique_ptr<type> create(const std::string& id) const;
public:
db() = default;
db(const std::string& uri);
void reset_defs();
void debug_dump(std::ostream&);
model create_model(const std::vector<std::string>& names);
bool field_def(const std::string& id, bool is_array, const std::string& type, const std::string& display);
};
}
#endif // __JIRA_JIRA_HPP__
<|endoftext|> |
<commit_before>#include "Preference.h"
#include <string.h>
using namespace sqaod;
const char *sqaod::algorithmToString(Algorithm algo) {
switch (algo) {
case algoNaive:
return "naive";
case algoColoring:
return "coloring";
case algoBruteForceSearch:
return "brute_force_search";
case algoDefault:
return "default";
case algoUnknown:
default:
return "unknown";
}
}
Algorithm sqaod::algorithmFromString(const char *algoStr) {
if (strcasecmp("naive", algoStr) == 0)
return algoNaive;
if (strcasecmp("coloring", algoStr) == 0)
return algoColoring;
if (strcasecmp("brute_force_search", algoStr) == 0)
return algoBruteForceSearch;
if (strcasecmp("default", algoStr) == 0)
return algoDefault;
return algoUnknown;
}
enum PreferenceName sqaod::preferenceNameFromString(const char *name) {
if (strcasecmp("algorithm", name) == 0)
return pnAlgorithm;
if (strcasecmp("n_trotters", name) == 0)
return pnNumTrotters;
if (strcasecmp("tile_size", name) == 0)
return pnTileSize;
if (strcasecmp("tile_size_0", name) == 0)
return pnTileSize0;
if (strcasecmp("tile_size_1", name) == 0)
return pnTileSize1;
return pnUnknown;
}
const char *sqaod::preferenceNameToString(enum PreferenceName sp) {
switch (sp) {
case pnAlgorithm:
return "algorithm";
case pnNumTrotters:
return "n_trotters";
case pnTileSize:
return "tile_size";
case pnTileSize0:
return "tile_size_0";
case pnTileSize1:
return "tile_size_1";
default:
return "unknown";
}
}
<commit_msg>Using stricomp for strecasecmp() on Windows.<commit_after>#include "Preference.h"
#include <string.h>
#ifdef _WIN32
#define strcasecmp _stricmp
#endif
using namespace sqaod;
const char *sqaod::algorithmToString(Algorithm algo) {
switch (algo) {
case algoNaive:
return "naive";
case algoColoring:
return "coloring";
case algoBruteForceSearch:
return "brute_force_search";
case algoDefault:
return "default";
case algoUnknown:
default:
return "unknown";
}
}
Algorithm sqaod::algorithmFromString(const char *algoStr) {
if (strcasecmp("naive", algoStr) == 0)
return algoNaive;
if (strcasecmp("coloring", algoStr) == 0)
return algoColoring;
if (strcasecmp("brute_force_search", algoStr) == 0)
return algoBruteForceSearch;
if (strcasecmp("default", algoStr) == 0)
return algoDefault;
return algoUnknown;
}
enum PreferenceName sqaod::preferenceNameFromString(const char *name) {
if (strcasecmp("algorithm", name) == 0)
return pnAlgorithm;
if (strcasecmp("n_trotters", name) == 0)
return pnNumTrotters;
if (strcasecmp("tile_size", name) == 0)
return pnTileSize;
if (strcasecmp("tile_size_0", name) == 0)
return pnTileSize0;
if (strcasecmp("tile_size_1", name) == 0)
return pnTileSize1;
return pnUnknown;
}
const char *sqaod::preferenceNameToString(enum PreferenceName sp) {
switch (sp) {
case pnAlgorithm:
return "algorithm";
case pnNumTrotters:
return "n_trotters";
case pnTileSize:
return "tile_size";
case pnTileSize0:
return "tile_size_0";
case pnTileSize1:
return "tile_size_1";
default:
return "unknown";
}
}
<|endoftext|> |
<commit_before>
#include "tree_node.h"
namespace gui
{
////////////////////////////////////////
void tree_node::compute_minimum( void )
{
if ( _collapsed )
{
_root->compute_minimum();
set_minimum( _root->minimum_height(), _root->minimum_width() );
}
else
container<tree_layout>::compute_minimum();
}
////////////////////////////////////////
void tree_node::compute_layout( void )
{
if ( _collapsed )
{
_root->set_position( position() );
_root->set_size( width(), height() );
}
else
container<tree_layout>::compute_layout();
}
////////////////////////////////////////
bool tree_node::mouse_press( const draw::point &p, int button )
{
if ( _collapsed )
{
if ( _root->mouse_press( p, button ) )
{
_mouse_grab = _root;
return true;
}
return widget::mouse_press( p, button );
}
else
return container<tree_layout>::mouse_press( p, button );
}
////////////////////////////////////////
bool tree_node::mouse_release( const draw::point &p, int button )
{
if ( _mouse_grab )
{
auto tmp = _mouse_grab;
_mouse_grab.reset();
return tmp->mouse_release( p, button );
}
if ( _collapsed )
return _root->mouse_release( p, button );
else
return container<tree_layout>::mouse_release( p, button );
}
////////////////////////////////////////
bool tree_node::mouse_move( const draw::point &p )
{
if ( _mouse_grab )
return _mouse_grab->mouse_move( p );
if ( _collapsed )
return _root->mouse_move( p );
else
return container<tree_layout>::mouse_move( p );
}
////////////////////////////////////////
void tree_node::paint( const std::shared_ptr<draw::canvas> &c )
{
if ( _collapsed )
_root->paint( c );
else
container<tree_layout>::paint( c );
}
////////////////////////////////////////
}
<commit_msg>Fixed bug with computing minimum size.<commit_after>
#include "tree_node.h"
namespace gui
{
////////////////////////////////////////
void tree_node::compute_minimum( void )
{
if ( _collapsed )
{
_root->compute_minimum();
set_minimum( _root->minimum_width(), _root->minimum_height() );
}
else
container<tree_layout>::compute_minimum();
}
////////////////////////////////////////
void tree_node::compute_layout( void )
{
if ( _collapsed )
{
_root->set_position( position() );
_root->set_size( width(), height() );
}
else
container<tree_layout>::compute_layout();
}
////////////////////////////////////////
bool tree_node::mouse_press( const draw::point &p, int button )
{
if ( _collapsed )
{
if ( _root->mouse_press( p, button ) )
{
_mouse_grab = _root;
return true;
}
return widget::mouse_press( p, button );
}
else
return container<tree_layout>::mouse_press( p, button );
}
////////////////////////////////////////
bool tree_node::mouse_release( const draw::point &p, int button )
{
if ( _mouse_grab )
{
auto tmp = _mouse_grab;
_mouse_grab.reset();
return tmp->mouse_release( p, button );
}
if ( _collapsed )
return _root->mouse_release( p, button );
else
return container<tree_layout>::mouse_release( p, button );
}
////////////////////////////////////////
bool tree_node::mouse_move( const draw::point &p )
{
if ( _mouse_grab )
return _mouse_grab->mouse_move( p );
if ( _collapsed )
return _root->mouse_move( p );
else
return container<tree_layout>::mouse_move( p );
}
////////////////////////////////////////
void tree_node::paint( const std::shared_ptr<draw::canvas> &c )
{
if ( _collapsed )
_root->paint( c );
else
container<tree_layout>::paint( c );
}
////////////////////////////////////////
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: edtspell.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2007-06-27 16:31:54 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _EDTSPELL_HXX
#define _EDTSPELL_HXX
#include <svx/svxbox.hxx>
#include <svx/svxenum.hxx>
#include <svx/splwrap.hxx>
#include <svx/svxacorr.hxx>
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
namespace com { namespace sun { namespace star { namespace linguistic2 {
class XSpellChecker1;
}}}}
class EditView;
class ImpEditEngine;
class ContentNode;
class EditSpellWrapper : public SvxSpellWrapper
{
private:
EditView* pEditView;
void CheckSpellTo();
protected:
virtual void SpellStart( SvxSpellArea eArea );
virtual BOOL SpellContinue(); // Bereich pruefen
virtual void ReplaceAll( const String &rNewText, INT16 nLanguage );
virtual void SpellEnd();
virtual BOOL SpellMore();
virtual BOOL HasOtherCnt();
virtual void ScrollArea();
virtual void ChangeWord( const String& rNewWord, const USHORT nLang );
virtual void ChangeThesWord( const String& rNewWord );
virtual void AutoCorrect( const String& rOldWord, const String& rNewWord );
public:
EditSpellWrapper( Window* pWin,
::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XSpellChecker1 > &xChecker,
BOOL bIsStart,
BOOL bIsAllRight, EditView* pView );
};
struct WrongRange
{
USHORT nStart;
USHORT nEnd;
WrongRange( USHORT nS, USHORT nE ) { nStart = nS; nEnd = nE; }
};
SV_DECL_VARARR( WrongRanges, WrongRange, 4, 4 )
#define NOT_INVALID 0xFFFF
class WrongList : private WrongRanges
{
private:
USHORT nInvalidStart;
USHORT nInvalidEnd;
BOOL DbgIsBuggy() const;
public:
WrongList();
~WrongList();
BOOL IsInvalid() const { return nInvalidStart != NOT_INVALID; }
void SetValid() { nInvalidStart = NOT_INVALID; nInvalidEnd = 0; }
void MarkInvalid( USHORT nS, USHORT nE )
{
if ( ( nInvalidStart == NOT_INVALID ) || ( nInvalidStart > nS ) )
nInvalidStart = nS;
if ( nInvalidEnd < nE )
nInvalidEnd = nE;
}
USHORT Count() const { return WrongRanges::Count(); }
// Wenn man weiss was man tut:
WrongRange& GetObject( USHORT n ) const { return WrongRanges::GetObject( n ); }
void InsertWrong( const WrongRange& rWrong, USHORT nPos );
USHORT GetInvalidStart() const { return nInvalidStart; }
USHORT& GetInvalidStart() { return nInvalidStart; }
USHORT GetInvalidEnd() const { return nInvalidEnd; }
USHORT& GetInvalidEnd() { return nInvalidEnd; }
void TextInserted( USHORT nPos, USHORT nChars, BOOL bPosIsSep );
void TextDeleted( USHORT nPos, USHORT nChars );
void ResetRanges() { Remove( 0, Count() ); }
BOOL HasWrongs() const { return Count() != 0; }
void InsertWrong( USHORT nStart, USHORT nEnd, BOOL bClearRange );
BOOL NextWrong( USHORT& rnStart, USHORT& rnEnd ) const;
BOOL HasWrong( USHORT nStart, USHORT nEnd ) const;
BOOL HasAnyWrong( USHORT nStart, USHORT nEnd ) const;
void ClearWrongs( USHORT nStart, USHORT nEnd, const ContentNode* pNode );
void MarkWrongsInvalid();
WrongList* Clone() const;
};
inline void WrongList::InsertWrong( const WrongRange& rWrong, USHORT nPos )
{
WrongRanges::Insert( rWrong, nPos );
#ifdef DBG_UTIL
DBG_ASSERT( !DbgIsBuggy(), "Insert: WrongList kaputt!" );
#endif
}
class SVX_DLLPUBLIC EdtAutoCorrDoc : public SvxAutoCorrDoc
{
ImpEditEngine* pImpEE;
ContentNode* pCurNode;
USHORT nCursor;
BOOL bAllowUndoAction;
BOOL bUndoAction;
protected:
void ImplStartUndoAction();
public:
EdtAutoCorrDoc( ImpEditEngine* pImpEE, ContentNode* pCurNode, USHORT nCrsr, xub_Unicode cIns );
~EdtAutoCorrDoc();
virtual BOOL Delete( USHORT nStt, USHORT nEnd );
virtual BOOL Insert( USHORT nPos, const String& rTxt );
virtual BOOL Replace( USHORT nPos, const String& rTxt );
virtual BOOL SetAttr( USHORT nStt, USHORT nEnd, USHORT nSlotId, SfxPoolItem& );
virtual BOOL SetINetAttr( USHORT nStt, USHORT nEnd, const String& rURL );
virtual BOOL HasSymbolChars( USHORT nStt, USHORT nEnd );
virtual const String* GetPrevPara( BOOL bAtNormalPos );
virtual BOOL ChgAutoCorrWord( USHORT& rSttPos, USHORT nEndPos,
SvxAutoCorrect& rACorrect, const String** ppPara );
virtual LanguageType GetLanguage( USHORT nPos, BOOL bPrevPara = FALSE ) const;
USHORT GetCursor() const { return nCursor; }
};
#endif // EDTSPELL
<commit_msg>INTEGRATION: CWS changefileheader (1.9.368); FILE MERGED 2008/04/01 15:49:13 thb 1.9.368.3: #i85898# Stripping all external header guards 2008/04/01 12:46:19 thb 1.9.368.2: #i85898# Stripping all external header guards 2008/03/31 14:17:54 rt 1.9.368.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: edtspell.hxx,v $
* $Revision: 1.10 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _EDTSPELL_HXX
#define _EDTSPELL_HXX
#include <svx/svxbox.hxx>
#include <svx/svxenum.hxx>
#include <svx/splwrap.hxx>
#include <svx/svxacorr.hxx>
#include <com/sun/star/uno/Reference.h>
#include "svx/svxdllapi.h"
namespace com { namespace sun { namespace star { namespace linguistic2 {
class XSpellChecker1;
}}}}
class EditView;
class ImpEditEngine;
class ContentNode;
class EditSpellWrapper : public SvxSpellWrapper
{
private:
EditView* pEditView;
void CheckSpellTo();
protected:
virtual void SpellStart( SvxSpellArea eArea );
virtual BOOL SpellContinue(); // Bereich pruefen
virtual void ReplaceAll( const String &rNewText, INT16 nLanguage );
virtual void SpellEnd();
virtual BOOL SpellMore();
virtual BOOL HasOtherCnt();
virtual void ScrollArea();
virtual void ChangeWord( const String& rNewWord, const USHORT nLang );
virtual void ChangeThesWord( const String& rNewWord );
virtual void AutoCorrect( const String& rOldWord, const String& rNewWord );
public:
EditSpellWrapper( Window* pWin,
::com::sun::star::uno::Reference<
::com::sun::star::linguistic2::XSpellChecker1 > &xChecker,
BOOL bIsStart,
BOOL bIsAllRight, EditView* pView );
};
struct WrongRange
{
USHORT nStart;
USHORT nEnd;
WrongRange( USHORT nS, USHORT nE ) { nStart = nS; nEnd = nE; }
};
SV_DECL_VARARR( WrongRanges, WrongRange, 4, 4 )
#define NOT_INVALID 0xFFFF
class WrongList : private WrongRanges
{
private:
USHORT nInvalidStart;
USHORT nInvalidEnd;
BOOL DbgIsBuggy() const;
public:
WrongList();
~WrongList();
BOOL IsInvalid() const { return nInvalidStart != NOT_INVALID; }
void SetValid() { nInvalidStart = NOT_INVALID; nInvalidEnd = 0; }
void MarkInvalid( USHORT nS, USHORT nE )
{
if ( ( nInvalidStart == NOT_INVALID ) || ( nInvalidStart > nS ) )
nInvalidStart = nS;
if ( nInvalidEnd < nE )
nInvalidEnd = nE;
}
USHORT Count() const { return WrongRanges::Count(); }
// Wenn man weiss was man tut:
WrongRange& GetObject( USHORT n ) const { return WrongRanges::GetObject( n ); }
void InsertWrong( const WrongRange& rWrong, USHORT nPos );
USHORT GetInvalidStart() const { return nInvalidStart; }
USHORT& GetInvalidStart() { return nInvalidStart; }
USHORT GetInvalidEnd() const { return nInvalidEnd; }
USHORT& GetInvalidEnd() { return nInvalidEnd; }
void TextInserted( USHORT nPos, USHORT nChars, BOOL bPosIsSep );
void TextDeleted( USHORT nPos, USHORT nChars );
void ResetRanges() { Remove( 0, Count() ); }
BOOL HasWrongs() const { return Count() != 0; }
void InsertWrong( USHORT nStart, USHORT nEnd, BOOL bClearRange );
BOOL NextWrong( USHORT& rnStart, USHORT& rnEnd ) const;
BOOL HasWrong( USHORT nStart, USHORT nEnd ) const;
BOOL HasAnyWrong( USHORT nStart, USHORT nEnd ) const;
void ClearWrongs( USHORT nStart, USHORT nEnd, const ContentNode* pNode );
void MarkWrongsInvalid();
WrongList* Clone() const;
};
inline void WrongList::InsertWrong( const WrongRange& rWrong, USHORT nPos )
{
WrongRanges::Insert( rWrong, nPos );
#ifdef DBG_UTIL
DBG_ASSERT( !DbgIsBuggy(), "Insert: WrongList kaputt!" );
#endif
}
class SVX_DLLPUBLIC EdtAutoCorrDoc : public SvxAutoCorrDoc
{
ImpEditEngine* pImpEE;
ContentNode* pCurNode;
USHORT nCursor;
BOOL bAllowUndoAction;
BOOL bUndoAction;
protected:
void ImplStartUndoAction();
public:
EdtAutoCorrDoc( ImpEditEngine* pImpEE, ContentNode* pCurNode, USHORT nCrsr, xub_Unicode cIns );
~EdtAutoCorrDoc();
virtual BOOL Delete( USHORT nStt, USHORT nEnd );
virtual BOOL Insert( USHORT nPos, const String& rTxt );
virtual BOOL Replace( USHORT nPos, const String& rTxt );
virtual BOOL SetAttr( USHORT nStt, USHORT nEnd, USHORT nSlotId, SfxPoolItem& );
virtual BOOL SetINetAttr( USHORT nStt, USHORT nEnd, const String& rURL );
virtual BOOL HasSymbolChars( USHORT nStt, USHORT nEnd );
virtual const String* GetPrevPara( BOOL bAtNormalPos );
virtual BOOL ChgAutoCorrWord( USHORT& rSttPos, USHORT nEndPos,
SvxAutoCorrect& rACorrect, const String** ppPara );
virtual LanguageType GetLanguage( USHORT nPos, BOOL bPrevPara = FALSE ) const;
USHORT GetCursor() const { return nCursor; }
};
#endif // EDTSPELL
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: svdtouch.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: pjunck $ $Date: 2004-11-03 10:24:59 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SVDTOUCH_HXX
#define _SVDTOUCH_HXX
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
class Point;
class Polygon;
class PolyPolygon;
class XPolygon;
class XPolyPolygon;
class Rectangle;
//BFS09class OutputDevice;
sal_Bool IsPointInsidePoly(const Polygon& rPoly, const Point& rHit);
sal_Bool IsPointInsidePoly(const PolyPolygon& rPoly, const Point& rHit);
//BFS09sal_Bool IsPointInsidePoly(const XPolygon& rPoly, const Point& rHit, OutputDevice* pOut=NULL);
//BFS09sal_Bool IsPointInsidePoly(const XPolyPolygon& rPoly, const Point& rHit, OutputDevice* pOut=NULL);
sal_Bool IsPointInsidePoly(const XPolygon& rPoly, const Point& rHit);
sal_Bool IsPointInsidePoly(const XPolyPolygon& rPoly, const Point& rHit);
sal_Bool IsRectTouchesPoly(const Polygon& rPoly, const Rectangle& rHit);
sal_Bool IsRectTouchesPoly(const PolyPolygon& rPoly, const Rectangle& rHit);
//BFS09sal_Bool IsRectTouchesPoly(const XPolygon& rPoly, const Rectangle& rHit, OutputDevice* pOut=NULL);
//BFS09sal_Bool IsRectTouchesPoly(const XPolyPolygon& rPoly, const Rectangle& rHit, OutputDevice* pOut=NULL);
sal_Bool IsRectTouchesPoly(const XPolygon& rPoly, const Rectangle& rHit);
sal_Bool IsRectTouchesPoly(const XPolyPolygon& rPoly, const Rectangle& rHit);
sal_Bool IsRectTouchesLine(const Point& rPt1, const Point& rPt2, const Rectangle& rHit);
sal_Bool IsRectTouchesLine(const Polygon& rLine, const Rectangle& rHit);
sal_Bool IsRectTouchesLine(const PolyPolygon& rLine, const Rectangle& rHit);
//BFS09sal_Bool IsRectTouchesLine(const XPolygon& rLine, const Rectangle& rHit, OutputDevice* pOut=NULL);
//BFS09sal_Bool IsRectTouchesLine(const XPolyPolygon& rLine, const Rectangle& rHit, OutputDevice* pOut=NULL);
sal_Bool IsRectTouchesLine(const XPolygon& rLine, const Rectangle& rHit);
sal_Bool IsRectTouchesLine(const XPolyPolygon& rLine, const Rectangle& rHit);
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //_SVDTOUCH_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.598); FILE MERGED 2005/09/05 14:16:33 rt 1.2.598.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svdtouch.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 18:56:07 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SVDTOUCH_HXX
#define _SVDTOUCH_HXX
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
class Point;
class Polygon;
class PolyPolygon;
class XPolygon;
class XPolyPolygon;
class Rectangle;
//BFS09class OutputDevice;
sal_Bool IsPointInsidePoly(const Polygon& rPoly, const Point& rHit);
sal_Bool IsPointInsidePoly(const PolyPolygon& rPoly, const Point& rHit);
//BFS09sal_Bool IsPointInsidePoly(const XPolygon& rPoly, const Point& rHit, OutputDevice* pOut=NULL);
//BFS09sal_Bool IsPointInsidePoly(const XPolyPolygon& rPoly, const Point& rHit, OutputDevice* pOut=NULL);
sal_Bool IsPointInsidePoly(const XPolygon& rPoly, const Point& rHit);
sal_Bool IsPointInsidePoly(const XPolyPolygon& rPoly, const Point& rHit);
sal_Bool IsRectTouchesPoly(const Polygon& rPoly, const Rectangle& rHit);
sal_Bool IsRectTouchesPoly(const PolyPolygon& rPoly, const Rectangle& rHit);
//BFS09sal_Bool IsRectTouchesPoly(const XPolygon& rPoly, const Rectangle& rHit, OutputDevice* pOut=NULL);
//BFS09sal_Bool IsRectTouchesPoly(const XPolyPolygon& rPoly, const Rectangle& rHit, OutputDevice* pOut=NULL);
sal_Bool IsRectTouchesPoly(const XPolygon& rPoly, const Rectangle& rHit);
sal_Bool IsRectTouchesPoly(const XPolyPolygon& rPoly, const Rectangle& rHit);
sal_Bool IsRectTouchesLine(const Point& rPt1, const Point& rPt2, const Rectangle& rHit);
sal_Bool IsRectTouchesLine(const Polygon& rLine, const Rectangle& rHit);
sal_Bool IsRectTouchesLine(const PolyPolygon& rLine, const Rectangle& rHit);
//BFS09sal_Bool IsRectTouchesLine(const XPolygon& rLine, const Rectangle& rHit, OutputDevice* pOut=NULL);
//BFS09sal_Bool IsRectTouchesLine(const XPolyPolygon& rLine, const Rectangle& rHit, OutputDevice* pOut=NULL);
sal_Bool IsRectTouchesLine(const XPolygon& rLine, const Rectangle& rHit);
sal_Bool IsRectTouchesLine(const XPolyPolygon& rLine, const Rectangle& rHit);
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //_SVDTOUCH_HXX
<|endoftext|> |
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/translate/language_detection/language_detection_util.h"
#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "components/translate/core/common/translate_constants.h"
#include "components/translate/core/common/translate_metrics.h"
#include "components/translate/core/common/translate_util.h"
#if !defined(CLD_VERSION) || CLD_VERSION==1
#include "third_party/cld/encodings/compact_lang_det/compact_lang_det.h"
#include "third_party/cld/encodings/compact_lang_det/win/cld_unicodetext.h"
#endif
#if !defined(CLD_VERSION) || CLD_VERSION==2
#include "third_party/cld_2/src/public/compact_lang_det.h"
#endif
namespace {
// Similar language code list. Some languages are very similar and difficult
// for CLD to distinguish.
struct SimilarLanguageCode {
const char* const code;
int group;
};
const SimilarLanguageCode kSimilarLanguageCodes[] = {
{"bs", 1},
{"hr", 1},
{"hi", 2},
{"ne", 2},
};
// Checks |kSimilarLanguageCodes| and returns group code.
int GetSimilarLanguageGroupCode(const std::string& language) {
for (size_t i = 0; i < arraysize(kSimilarLanguageCodes); ++i) {
if (language.find(kSimilarLanguageCodes[i].code) != 0)
continue;
return kSimilarLanguageCodes[i].group;
}
return 0;
}
// Well-known languages which often have wrong server configuration of
// Content-Language: en.
// TODO(toyoshim): Remove these static tables and caller functions to
// translate/common, and implement them as std::set<>.
const char* kWellKnownCodesOnWrongConfiguration[] = {
"es", "pt", "ja", "ru", "de", "zh-CN", "zh-TW", "ar", "id", "fr", "it", "th"
};
// Applies a series of language code modification in proper order.
void ApplyLanguageCodeCorrection(std::string* code) {
// Correct well-known format errors.
translate::CorrectLanguageCodeTypo(code);
if (!translate::IsValidLanguageCode(*code)) {
*code = std::string();
return;
}
translate::ToTranslateLanguageSynonym(code);
}
int GetCLDMajorVersion() {
#if !defined(CLD_VERSION)
std::string group_name = base::FieldTrialList::FindFullName("CLD1VsCLD2");
if (group_name == "CLD2")
return 2;
else
return 1;
#else
return CLD_VERSION;
#endif
}
// Returns the ISO 639 language code of the specified |text|, or 'unknown' if it
// failed.
// |is_cld_reliable| will be set as true if CLD says the detection is reliable.
std::string DetermineTextLanguage(const base::string16& text,
bool* is_cld_reliable) {
std::string language = translate::kUnknownLanguageCode;
int text_bytes = 0;
bool is_reliable = false;
// Language or CLD2::Language
int cld_language = 0;
bool is_valid_language = false;
switch (GetCLDMajorVersion()) {
#if !defined(CLD_VERSION) || CLD_VERSION==1
case 1: {
int num_languages = 0;
cld_language =
DetectLanguageOfUnicodeText(NULL, text.c_str(), true, &is_reliable,
&num_languages, NULL, &text_bytes);
is_valid_language = cld_language != NUM_LANGUAGES &&
cld_language != UNKNOWN_LANGUAGE &&
cld_language != TG_UNKNOWN_LANGUAGE;
break;
}
#endif
#if !defined(CLD_VERSION) || CLD_VERSION==2
case 2: {
std::string utf8_text(base::UTF16ToUTF8(text));
CLD2::Language language3[3];
int percent3[3];
CLD2::DetectLanguageSummary(
utf8_text.c_str(), (int)utf8_text.size(), true, language3, percent3,
&text_bytes, &is_reliable);
cld_language = language3[0];
is_valid_language = cld_language != CLD2::NUM_LANGUAGES &&
cld_language != CLD2::UNKNOWN_LANGUAGE &&
cld_language != CLD2::TG_UNKNOWN_LANGUAGE;
break;
}
#endif
default:
NOTREACHED();
}
if (is_cld_reliable != NULL)
*is_cld_reliable = is_reliable;
// We don't trust the result if the CLD reports that the detection is not
// reliable, or if the actual text used to detect the language was less than
// 100 bytes (short texts can often lead to wrong results).
// TODO(toyoshim): CLD provides |is_reliable| flag. But, it just says that
// the determined language code is correct with 50% confidence. Chrome should
// handle the real confidence value to judge.
if (is_reliable && text_bytes >= 100 && is_valid_language) {
// We should not use LanguageCode_ISO_639_1 because it does not cover all
// the languages CLD can detect. As a result, it'll return the invalid
// language code for tradtional Chinese among others.
// |LanguageCodeWithDialect| will go through ISO 639-1, ISO-639-2 and
// 'other' tables to do the 'right' thing. In addition, it'll return zh-CN
// for Simplified Chinese.
switch (GetCLDMajorVersion()) {
#if !defined(CLD_VERSION) || CLD_VERSION==1
case 1:
language =
LanguageCodeWithDialects(static_cast<Language>(cld_language));
break;
#endif
#if !defined(CLD_VERSION) || CLD_VERSION==2
case 2:
// (1) CLD2's LanguageCode returns general Chinese 'zh' for
// CLD2::CHINESE, but Translate server doesn't accept it. This is
// converted to 'zh-CN' in the same way as CLD1's
// LanguageCodeWithDialects.
//
// (2) CLD2's LanguageCode returns zh-Hant instead of zh-TW for
// CLD2::CHINESE_T. This is technically more precise for the language
// code of traditional Chinese, while Translate server hasn't accepted
// zh-Hant yet.
if (cld_language == CLD2::CHINESE) {
language = "zh-CN";
} else if (cld_language == CLD2::CHINESE_T) {
language = "zh-TW";
} else {
language =
CLD2::LanguageCode(static_cast<CLD2::Language>(cld_language));
}
break;
#endif
default:
NOTREACHED();
}
}
VLOG(9) << "Detected lang_id: " << language << ", from Text:\n" << text
<< "\n*************************************\n";
return language;
}
// Checks if CLD can complement a sub code when the page language doesn't know
// the sub code.
bool CanCLDComplementSubCode(
const std::string& page_language, const std::string& cld_language) {
// Translate server cannot treat general Chinese. If Content-Language and
// CLD agree that the language is Chinese and Content-Language doesn't know
// which dialect is used, CLD language has priority.
// TODO(hajimehoshi): How about the other dialects like zh-MO?
return page_language == "zh" && StartsWithASCII(cld_language, "zh-", false);
}
} // namespace
namespace translate {
std::string DeterminePageLanguage(const std::string& code,
const std::string& html_lang,
const base::string16& contents,
std::string* cld_language_p,
bool* is_cld_reliable_p) {
base::TimeTicks begin_time = base::TimeTicks::Now();
bool is_cld_reliable;
std::string cld_language = DetermineTextLanguage(contents, &is_cld_reliable);
translate::ReportLanguageDetectionTime(begin_time, base::TimeTicks::Now());
if (cld_language_p != NULL)
*cld_language_p = cld_language;
if (is_cld_reliable_p != NULL)
*is_cld_reliable_p = is_cld_reliable;
translate::ToTranslateLanguageSynonym(&cld_language);
// Check if html lang attribute is valid.
std::string modified_html_lang;
if (!html_lang.empty()) {
modified_html_lang = html_lang;
ApplyLanguageCodeCorrection(&modified_html_lang);
translate::ReportHtmlLang(html_lang, modified_html_lang);
VLOG(9) << "html lang based language code: " << modified_html_lang;
}
// Check if Content-Language is valid.
std::string modified_code;
if (!code.empty()) {
modified_code = code;
ApplyLanguageCodeCorrection(&modified_code);
translate::ReportContentLanguage(code, modified_code);
}
// Adopt |modified_html_lang| if it is valid. Otherwise, adopt
// |modified_code|.
std::string language = modified_html_lang.empty() ? modified_code :
modified_html_lang;
// If |language| is empty, just use CLD result even though it might be
// translate::kUnknownLanguageCode.
if (language.empty()) {
translate::ReportLanguageVerification(
translate::LANGUAGE_VERIFICATION_CLD_ONLY);
return cld_language;
}
if (cld_language == kUnknownLanguageCode) {
translate::ReportLanguageVerification(
translate::LANGUAGE_VERIFICATION_UNKNOWN);
return language;
} else if (CanCLDComplementSubCode(language, cld_language)) {
translate::ReportLanguageVerification(
translate::LANGUAGE_VERIFICATION_CLD_COMPLEMENT_SUB_CODE);
return cld_language;
} else if (IsSameOrSimilarLanguages(language, cld_language)) {
translate::ReportLanguageVerification(
translate::LANGUAGE_VERIFICATION_CLD_AGREE);
return language;
} else if (MaybeServerWrongConfiguration(language, cld_language)) {
translate::ReportLanguageVerification(
translate::LANGUAGE_VERIFICATION_TRUST_CLD);
return cld_language;
} else {
translate::ReportLanguageVerification(
translate::LANGUAGE_VERIFICATION_CLD_DISAGREE);
// Content-Language value might be wrong because CLD says that this page
// is written in another language with confidence.
// In this case, Chrome doesn't rely on any of the language codes, and
// gives up suggesting a translation.
return std::string(kUnknownLanguageCode);
}
return language;
}
void CorrectLanguageCodeTypo(std::string* code) {
DCHECK(code);
size_t coma_index = code->find(',');
if (coma_index != std::string::npos) {
// There are more than 1 language specified, just keep the first one.
*code = code->substr(0, coma_index);
}
base::TrimWhitespaceASCII(*code, base::TRIM_ALL, code);
// An underscore instead of a dash is a frequent mistake.
size_t underscore_index = code->find('_');
if (underscore_index != std::string::npos)
(*code)[underscore_index] = '-';
// Change everything up to a dash to lower-case and everything after to upper.
size_t dash_index = code->find('-');
if (dash_index != std::string::npos) {
*code = StringToLowerASCII(code->substr(0, dash_index)) +
StringToUpperASCII(code->substr(dash_index));
} else {
*code = StringToLowerASCII(*code);
}
}
bool IsValidLanguageCode(const std::string& code) {
// Roughly check if the language code follows /[a-zA-Z]{2,3}(-[a-zA-Z]{2})?/.
// TODO(hajimehoshi): How about es-419, which is used as an Accept language?
std::vector<std::string> chunks;
base::SplitString(code, '-', &chunks);
if (chunks.size() < 1 || 2 < chunks.size())
return false;
const std::string& main_code = chunks[0];
if (main_code.size() < 1 || 3 < main_code.size())
return false;
for (std::string::const_iterator it = main_code.begin();
it != main_code.end(); ++it) {
if (!IsAsciiAlpha(*it))
return false;
}
if (chunks.size() == 1)
return true;
const std::string& sub_code = chunks[1];
if (sub_code.size() != 2)
return false;
for (std::string::const_iterator it = sub_code.begin();
it != sub_code.end(); ++it) {
if (!IsAsciiAlpha(*it))
return false;
}
return true;
}
bool IsSameOrSimilarLanguages(const std::string& page_language,
const std::string& cld_language) {
std::vector<std::string> chunks;
base::SplitString(page_language, '-', &chunks);
if (chunks.size() == 0)
return false;
std::string page_language_main_part = chunks[0];
base::SplitString(cld_language, '-', &chunks);
if (chunks.size() == 0)
return false;
std::string cld_language_main_part = chunks[0];
// Language code part of |page_language| is matched to one of |cld_language|.
// Country code is ignored here.
if (page_language_main_part == cld_language_main_part) {
// Languages are matched strictly. Reports false to metrics, but returns
// true.
translate::ReportSimilarLanguageMatch(false);
return true;
}
// Check if |page_language| and |cld_language| are in the similar language
// list and belong to the same language group.
int page_code = GetSimilarLanguageGroupCode(page_language);
bool match = page_code != 0 &&
page_code == GetSimilarLanguageGroupCode(cld_language);
translate::ReportSimilarLanguageMatch(match);
return match;
}
bool MaybeServerWrongConfiguration(const std::string& page_language,
const std::string& cld_language) {
// If |page_language| is not "en-*", respect it and just return false here.
if (!StartsWithASCII(page_language, "en", false))
return false;
// A server provides a language meta information representing "en-*". But it
// might be just a default value due to missing user configuration.
// Let's trust |cld_language| if the determined language is not difficult to
// distinguish from English, and the language is one of well-known languages
// which often provide "en-*" meta information mistakenly.
for (size_t i = 0; i < arraysize(kWellKnownCodesOnWrongConfiguration); ++i) {
if (cld_language == kWellKnownCodesOnWrongConfiguration[i])
return true;
}
return false;
}
} // namespace translate
<commit_msg>Revert of Use TOP #1 language from CLD2 instead of the summary language (https://codereview.chromium.org/75483009/)<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/translate/language_detection/language_detection_util.h"
#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "components/translate/core/common/translate_constants.h"
#include "components/translate/core/common/translate_metrics.h"
#include "components/translate/core/common/translate_util.h"
#if !defined(CLD_VERSION) || CLD_VERSION==1
#include "third_party/cld/encodings/compact_lang_det/compact_lang_det.h"
#include "third_party/cld/encodings/compact_lang_det/win/cld_unicodetext.h"
#endif
#if !defined(CLD_VERSION) || CLD_VERSION==2
#include "third_party/cld_2/src/public/compact_lang_det.h"
#endif
namespace {
// Similar language code list. Some languages are very similar and difficult
// for CLD to distinguish.
struct SimilarLanguageCode {
const char* const code;
int group;
};
const SimilarLanguageCode kSimilarLanguageCodes[] = {
{"bs", 1},
{"hr", 1},
{"hi", 2},
{"ne", 2},
};
// Checks |kSimilarLanguageCodes| and returns group code.
int GetSimilarLanguageGroupCode(const std::string& language) {
for (size_t i = 0; i < arraysize(kSimilarLanguageCodes); ++i) {
if (language.find(kSimilarLanguageCodes[i].code) != 0)
continue;
return kSimilarLanguageCodes[i].group;
}
return 0;
}
// Well-known languages which often have wrong server configuration of
// Content-Language: en.
// TODO(toyoshim): Remove these static tables and caller functions to
// translate/common, and implement them as std::set<>.
const char* kWellKnownCodesOnWrongConfiguration[] = {
"es", "pt", "ja", "ru", "de", "zh-CN", "zh-TW", "ar", "id", "fr", "it", "th"
};
// Applies a series of language code modification in proper order.
void ApplyLanguageCodeCorrection(std::string* code) {
// Correct well-known format errors.
translate::CorrectLanguageCodeTypo(code);
if (!translate::IsValidLanguageCode(*code)) {
*code = std::string();
return;
}
translate::ToTranslateLanguageSynonym(code);
}
int GetCLDMajorVersion() {
#if !defined(CLD_VERSION)
std::string group_name = base::FieldTrialList::FindFullName("CLD1VsCLD2");
if (group_name == "CLD2")
return 2;
else
return 1;
#else
return CLD_VERSION;
#endif
}
// Returns the ISO 639 language code of the specified |text|, or 'unknown' if it
// failed.
// |is_cld_reliable| will be set as true if CLD says the detection is reliable.
std::string DetermineTextLanguage(const base::string16& text,
bool* is_cld_reliable) {
std::string language = translate::kUnknownLanguageCode;
int text_bytes = 0;
bool is_reliable = false;
// Language or CLD2::Language
int cld_language = 0;
bool is_valid_language = false;
switch (GetCLDMajorVersion()) {
#if !defined(CLD_VERSION) || CLD_VERSION==1
case 1: {
int num_languages = 0;
cld_language =
DetectLanguageOfUnicodeText(NULL, text.c_str(), true, &is_reliable,
&num_languages, NULL, &text_bytes);
is_valid_language = cld_language != NUM_LANGUAGES &&
cld_language != UNKNOWN_LANGUAGE &&
cld_language != TG_UNKNOWN_LANGUAGE;
break;
}
#endif
#if !defined(CLD_VERSION) || CLD_VERSION==2
case 2: {
std::string utf8_text(base::UTF16ToUTF8(text));
CLD2::Language language3[3];
int percent3[3];
cld_language = CLD2::DetectLanguageSummary(
utf8_text.c_str(), (int)utf8_text.size(), true, language3, percent3,
&text_bytes, &is_reliable);
is_valid_language = cld_language != CLD2::NUM_LANGUAGES &&
cld_language != CLD2::UNKNOWN_LANGUAGE &&
cld_language != CLD2::TG_UNKNOWN_LANGUAGE;
break;
}
#endif
default:
NOTREACHED();
}
if (is_cld_reliable != NULL)
*is_cld_reliable = is_reliable;
// We don't trust the result if the CLD reports that the detection is not
// reliable, or if the actual text used to detect the language was less than
// 100 bytes (short texts can often lead to wrong results).
// TODO(toyoshim): CLD provides |is_reliable| flag. But, it just says that
// the determined language code is correct with 50% confidence. Chrome should
// handle the real confidence value to judge.
if (is_reliable && text_bytes >= 100 && is_valid_language) {
// We should not use LanguageCode_ISO_639_1 because it does not cover all
// the languages CLD can detect. As a result, it'll return the invalid
// language code for tradtional Chinese among others.
// |LanguageCodeWithDialect| will go through ISO 639-1, ISO-639-2 and
// 'other' tables to do the 'right' thing. In addition, it'll return zh-CN
// for Simplified Chinese.
switch (GetCLDMajorVersion()) {
#if !defined(CLD_VERSION) || CLD_VERSION==1
case 1:
language =
LanguageCodeWithDialects(static_cast<Language>(cld_language));
break;
#endif
#if !defined(CLD_VERSION) || CLD_VERSION==2
case 2:
// (1) CLD2's LanguageCode returns general Chinese 'zh' for
// CLD2::CHINESE, but Translate server doesn't accept it. This is
// converted to 'zh-CN' in the same way as CLD1's
// LanguageCodeWithDialects.
//
// (2) CLD2's LanguageCode returns zh-Hant instead of zh-TW for
// CLD2::CHINESE_T. This is technically more precise for the language
// code of traditional Chinese, while Translate server hasn't accepted
// zh-Hant yet.
if (cld_language == CLD2::CHINESE) {
language = "zh-CN";
} else if (cld_language == CLD2::CHINESE_T) {
language = "zh-TW";
} else {
language =
CLD2::LanguageCode(static_cast<CLD2::Language>(cld_language));
}
break;
#endif
default:
NOTREACHED();
}
}
VLOG(9) << "Detected lang_id: " << language << ", from Text:\n" << text
<< "\n*************************************\n";
return language;
}
// Checks if CLD can complement a sub code when the page language doesn't know
// the sub code.
bool CanCLDComplementSubCode(
const std::string& page_language, const std::string& cld_language) {
// Translate server cannot treat general Chinese. If Content-Language and
// CLD agree that the language is Chinese and Content-Language doesn't know
// which dialect is used, CLD language has priority.
// TODO(hajimehoshi): How about the other dialects like zh-MO?
return page_language == "zh" && StartsWithASCII(cld_language, "zh-", false);
}
} // namespace
namespace translate {
std::string DeterminePageLanguage(const std::string& code,
const std::string& html_lang,
const base::string16& contents,
std::string* cld_language_p,
bool* is_cld_reliable_p) {
base::TimeTicks begin_time = base::TimeTicks::Now();
bool is_cld_reliable;
std::string cld_language = DetermineTextLanguage(contents, &is_cld_reliable);
translate::ReportLanguageDetectionTime(begin_time, base::TimeTicks::Now());
if (cld_language_p != NULL)
*cld_language_p = cld_language;
if (is_cld_reliable_p != NULL)
*is_cld_reliable_p = is_cld_reliable;
translate::ToTranslateLanguageSynonym(&cld_language);
// Check if html lang attribute is valid.
std::string modified_html_lang;
if (!html_lang.empty()) {
modified_html_lang = html_lang;
ApplyLanguageCodeCorrection(&modified_html_lang);
translate::ReportHtmlLang(html_lang, modified_html_lang);
VLOG(9) << "html lang based language code: " << modified_html_lang;
}
// Check if Content-Language is valid.
std::string modified_code;
if (!code.empty()) {
modified_code = code;
ApplyLanguageCodeCorrection(&modified_code);
translate::ReportContentLanguage(code, modified_code);
}
// Adopt |modified_html_lang| if it is valid. Otherwise, adopt
// |modified_code|.
std::string language = modified_html_lang.empty() ? modified_code :
modified_html_lang;
// If |language| is empty, just use CLD result even though it might be
// translate::kUnknownLanguageCode.
if (language.empty()) {
translate::ReportLanguageVerification(
translate::LANGUAGE_VERIFICATION_CLD_ONLY);
return cld_language;
}
if (cld_language == kUnknownLanguageCode) {
translate::ReportLanguageVerification(
translate::LANGUAGE_VERIFICATION_UNKNOWN);
return language;
} else if (CanCLDComplementSubCode(language, cld_language)) {
translate::ReportLanguageVerification(
translate::LANGUAGE_VERIFICATION_CLD_COMPLEMENT_SUB_CODE);
return cld_language;
} else if (IsSameOrSimilarLanguages(language, cld_language)) {
translate::ReportLanguageVerification(
translate::LANGUAGE_VERIFICATION_CLD_AGREE);
return language;
} else if (MaybeServerWrongConfiguration(language, cld_language)) {
translate::ReportLanguageVerification(
translate::LANGUAGE_VERIFICATION_TRUST_CLD);
return cld_language;
} else {
translate::ReportLanguageVerification(
translate::LANGUAGE_VERIFICATION_CLD_DISAGREE);
// Content-Language value might be wrong because CLD says that this page
// is written in another language with confidence.
// In this case, Chrome doesn't rely on any of the language codes, and
// gives up suggesting a translation.
return std::string(kUnknownLanguageCode);
}
return language;
}
void CorrectLanguageCodeTypo(std::string* code) {
DCHECK(code);
size_t coma_index = code->find(',');
if (coma_index != std::string::npos) {
// There are more than 1 language specified, just keep the first one.
*code = code->substr(0, coma_index);
}
base::TrimWhitespaceASCII(*code, base::TRIM_ALL, code);
// An underscore instead of a dash is a frequent mistake.
size_t underscore_index = code->find('_');
if (underscore_index != std::string::npos)
(*code)[underscore_index] = '-';
// Change everything up to a dash to lower-case and everything after to upper.
size_t dash_index = code->find('-');
if (dash_index != std::string::npos) {
*code = StringToLowerASCII(code->substr(0, dash_index)) +
StringToUpperASCII(code->substr(dash_index));
} else {
*code = StringToLowerASCII(*code);
}
}
bool IsValidLanguageCode(const std::string& code) {
// Roughly check if the language code follows /[a-zA-Z]{2,3}(-[a-zA-Z]{2})?/.
// TODO(hajimehoshi): How about es-419, which is used as an Accept language?
std::vector<std::string> chunks;
base::SplitString(code, '-', &chunks);
if (chunks.size() < 1 || 2 < chunks.size())
return false;
const std::string& main_code = chunks[0];
if (main_code.size() < 1 || 3 < main_code.size())
return false;
for (std::string::const_iterator it = main_code.begin();
it != main_code.end(); ++it) {
if (!IsAsciiAlpha(*it))
return false;
}
if (chunks.size() == 1)
return true;
const std::string& sub_code = chunks[1];
if (sub_code.size() != 2)
return false;
for (std::string::const_iterator it = sub_code.begin();
it != sub_code.end(); ++it) {
if (!IsAsciiAlpha(*it))
return false;
}
return true;
}
bool IsSameOrSimilarLanguages(const std::string& page_language,
const std::string& cld_language) {
std::vector<std::string> chunks;
base::SplitString(page_language, '-', &chunks);
if (chunks.size() == 0)
return false;
std::string page_language_main_part = chunks[0];
base::SplitString(cld_language, '-', &chunks);
if (chunks.size() == 0)
return false;
std::string cld_language_main_part = chunks[0];
// Language code part of |page_language| is matched to one of |cld_language|.
// Country code is ignored here.
if (page_language_main_part == cld_language_main_part) {
// Languages are matched strictly. Reports false to metrics, but returns
// true.
translate::ReportSimilarLanguageMatch(false);
return true;
}
// Check if |page_language| and |cld_language| are in the similar language
// list and belong to the same language group.
int page_code = GetSimilarLanguageGroupCode(page_language);
bool match = page_code != 0 &&
page_code == GetSimilarLanguageGroupCode(cld_language);
translate::ReportSimilarLanguageMatch(match);
return match;
}
bool MaybeServerWrongConfiguration(const std::string& page_language,
const std::string& cld_language) {
// If |page_language| is not "en-*", respect it and just return false here.
if (!StartsWithASCII(page_language, "en", false))
return false;
// A server provides a language meta information representing "en-*". But it
// might be just a default value due to missing user configuration.
// Let's trust |cld_language| if the determined language is not difficult to
// distinguish from English, and the language is one of well-known languages
// which often provide "en-*" meta information mistakenly.
for (size_t i = 0; i < arraysize(kWellKnownCodesOnWrongConfiguration); ++i) {
if (cld_language == kWellKnownCodesOnWrongConfiguration[i])
return true;
}
return false;
}
} // namespace translate
<|endoftext|> |
<commit_before>/*
Copyright (c) 2014, Muzzley
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all
copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
//
// You can compile this application with the following command:
// g++ -std=c++0x -I/usr/include/muzzley Examples/galileo_app.cpp -o myapp -lmuzzley -lpthread
//
// And run it like this:
// ./myapp
//
// Once running, you can pair your smartphone to this app using
// the mobile muzzley application and the "Activity Id" that is
// written to the screen.
//
#define DEBUG 1
#define APP_TOKEN "3ddde2aa9832a038" // Get yours at muzzley.com
#define STATIC_ACTIVITY_ID "" // Optional.
#include <signal.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <string>
#include <muzzley.h>
using namespace std;
#if !defined __APPLE__
using namespace __gnu_cxx;
#endif
int main(int argc, char* argv[]) {
// Create the Muzzley client
muzzley::Client _client;
// Register listener to be invoked when activity is sucessfully created.
//
// Don't bother to store the returned activityId, the Client class already does that,
// access it through the 'getActivityId' method.
//
// Return 'false' if you want to stop other listeners from being invoked.
_client.on(muzzley::ActivityCreated, [] (muzzley::JSONObj& _data, muzzley::Client& _client) -> bool {
cout << "Activity created with id " << _data["d"]["activityId"] << endl << flush;
cout << "You can now pair your smartphone, using the muzzley app, to the activity id " << _data["d"]["activityId"] << endl << flush;
return true;
});
_client.on(muzzley::ParticipantJoined, [] (muzzley::JSONObj& _data, muzzley::Client& _client) -> bool {
// string widget = "gamepad";
string widget = "webview";
long participant_id = _data["d"]["participant"]["id"];
string name = _data["d"]["participant"]["name"];
cout << "Participant " << name << "(" << participant_id << ")" << " joined." << endl << flush;
cout << "Chaning widget to a... " << widget << endl << flush;
string participant_string;
muzzley::tostr(participant_string, _data);
cout << "Participant string: " << participant_string << endl << flush;
// Change widget to the native gamepad
// _client.changeWidget(participant_id, widget, [] (muzzley::JSONObj& _data, muzzley::Client& _client) -> bool {
// cout << "Widget successfully changed" << endl << flush;
// });
// Change widget to a custom WebView widget
muzzley::JSONObj _widget_opts;
_widget_opts <<
"widget" << widget <<
"params" << JSON (
"uuid" << "58b54ae9-c94d-4c71-a4f1-6412b2376b1d" <<
"orientation" << "portrait"
);
_client.changeWidget(participant_id, _widget_opts, [] (muzzley::JSONObj& _data, muzzley::Client& _client) -> bool {
cout << "Widget successfully changed" << endl << flush;
});
return true;
});
_client.on(muzzley::WidgetAction, [] (muzzley::JSONObj& _data, muzzley::Client& _client) -> bool {
string widget_data;
muzzley::tostr(widget_data, _data["d"]);
cout << "Native Widget action event fired: " << widget_data << endl << flush;
return true;
});
// Register listener to be invoked when app receives a signal message.
//
// Return 'false' if you want to stop other listeners from being invoked.
_client.on(muzzley::SignalingMessage, [] (muzzley::JSONObj& _data, muzzley::Client& _client) -> bool {
string action;
action.assign((string) _data["d"]["a"]);
cout << "Received signaling message for action " << action << endl << flush;
cout << "with data " << _data["d"]["d"] << endl << flush;
cout << "and isReplyNeeded " << _client.isReplyNeeded(_data) << endl << flush;
if (_client.isReplyNeeded(_data)) {
_client.reply(_data, JSON(
"s" << true <<
"m" << "this is a testing signal so is always successful!" <<
"d" << JSON(
"w" << "400" <<
"h" << "300"
)
));
cout << "great, replied to a Signal Message" << endl << flush;
}
return true;
});
// Connects the application to the Muzzley server.
//
// It will start the application loop synchronously,
// i.e. the program will not execute anything below this line.
_client.connectApp(APP_TOKEN, STATIC_ACTIVITY_ID);
return 0;
}<commit_msg>added return statement to lamba-function in 'examples/app.cpp'<commit_after>/*
Copyright (c) 2014, Muzzley
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all
copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
//
// You can compile this application with the following command:
// g++ -std=c++0x -I/usr/include/muzzley Examples/galileo_app.cpp -o myapp -lmuzzley -lpthread
//
// And run it like this:
// ./myapp
//
// Once running, you can pair your smartphone to this app using
// the mobile muzzley application and the "Activity Id" that is
// written to the screen.
//
#define DEBUG 1
#define APP_TOKEN "3ddde2aa9832a038" // Get yours at muzzley.com
#define STATIC_ACTIVITY_ID "" // Optional.
#include <signal.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <string>
#include <muzzley.h>
using namespace std;
#if !defined __APPLE__
using namespace __gnu_cxx;
#endif
int main(int argc, char* argv[]) {
// Create the Muzzley client
muzzley::Client _client;
// Register listener to be invoked when activity is sucessfully created.
//
// Don't bother to store the returned activityId, the Client class already does that,
// access it through the 'getActivityId' method.
//
// Return 'false' if you want to stop other listeners from being invoked.
_client.on(muzzley::ActivityCreated, [] (muzzley::JSONObj& _data, muzzley::Client& _client) -> bool {
cout << "Activity created with id " << _data["d"]["activityId"] << endl << flush;
cout << "You can now pair your smartphone, using the muzzley app, to the activity id " << _data["d"]["activityId"] << endl << flush;
return true;
});
_client.on(muzzley::ParticipantJoined, [] (muzzley::JSONObj& _data, muzzley::Client& _client) -> bool {
// string widget = "gamepad";
string widget = "webview";
long participant_id = _data["d"]["participant"]["id"];
string name = _data["d"]["participant"]["name"];
cout << "Participant " << name << "(" << participant_id << ")" << " joined." << endl << flush;
cout << "Chaning widget to a... " << widget << endl << flush;
string participant_string;
muzzley::tostr(participant_string, _data);
cout << "Participant string: " << participant_string << endl << flush;
// Change widget to the native gamepad
// _client.changeWidget(participant_id, widget, [] (muzzley::JSONObj& _data, muzzley::Client& _client) -> bool {
// cout << "Widget successfully changed" << endl << flush;
// });
// Change widget to a custom WebView widget
muzzley::JSONObj _widget_opts;
_widget_opts <<
"widget" << widget <<
"params" << JSON (
"uuid" << "58b54ae9-c94d-4c71-a4f1-6412b2376b1d" <<
"orientation" << "portrait"
);
_client.changeWidget(participant_id, _widget_opts, [] (muzzley::JSONObj& _data, muzzley::Client& _client) -> bool {
cout << "Widget successfully changed" << endl << flush;
return true;
});
return true;
});
_client.on(muzzley::WidgetAction, [] (muzzley::JSONObj& _data, muzzley::Client& _client) -> bool {
string widget_data;
muzzley::tostr(widget_data, _data["d"]);
cout << "Native Widget action event fired: " << widget_data << endl << flush;
return true;
});
// Register listener to be invoked when app receives a signal message.
//
// Return 'false' if you want to stop other listeners from being invoked.
_client.on(muzzley::SignalingMessage, [] (muzzley::JSONObj& _data, muzzley::Client& _client) -> bool {
string action;
action.assign((string) _data["d"]["a"]);
cout << "Received signaling message for action " << action << endl << flush;
cout << "with data " << _data["d"]["d"] << endl << flush;
cout << "and isReplyNeeded " << _client.isReplyNeeded(_data) << endl << flush;
if (_client.isReplyNeeded(_data)) {
_client.reply(_data, JSON(
"s" << true <<
"m" << "this is a testing signal so is always successful!" <<
"d" << JSON(
"w" << "400" <<
"h" << "300"
)
));
cout << "great, replied to a Signal Message" << endl << flush;
}
return true;
});
// Connects the application to the Muzzley server.
//
// It will start the application loop synchronously,
// i.e. the program will not execute anything below this line.
_client.connectApp(APP_TOKEN, STATIC_ACTIVITY_ID);
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>[-] comment<commit_after><|endoftext|> |
<commit_before>#include <BrewingStandTile.h>
BeaconTile::BeaconTile(int id) : EntityTile(id, &Material::metal) {
tex = getTextureUVCoordinateSet("glass", 0);
secondary_tex = getTextureUVCoordinateSet("obsidian", 0);
terciary_tex = getTextureUVCoordinateSet("beacon", 0);
//fourth_tex = getTextureUVCoordinateSet("beacon_beam", 0);
//fifth_tex = getTextureUVCoordinateSet("beacon_beam", 1);
beacon->renderPass = Tile::glass->renderPass;
Tile::solid[id] = false;
Tile::lightBlock[id] = 0;
new TileItem(id - 256);
}
const TextureUVCoordinateSet& BrewingStandTile::getTexture(signed char side, int data) {
return side == 0 ? tex : (side == 1 ? secondary_tex : terciary_tex);
}
TileEntity* BeaconTile::newTileEntity(const TilePos& tp) {
return new BeaconTileEntity();
}
<commit_msg>now beacon can be rendered on Inv p1<commit_after>#include <BrewingStandTile.h>
BeaconTile::BeaconTile(int id) : EntityTile(id, &Material::metal) {
tex = getTextureUVCoordinateSet("glass", 0);
secondary_tex = getTextureUVCoordinateSet("obsidian", 0);
terciary_tex = getTextureUVCoordinateSet("beacon", 0);
//fourth_tex = getTextureUVCoordinateSet("beacon_beam", 0);
//fifth_tex = getTextureUVCoordinateSet("beacon_beam", 1);
beacon->renderPass = Tile::glass->renderPass;
Tile::solid[id] = false;
Tile::lightBlock[id] = 0;
new TileItem(id - 256);
}
BeaconTile::isCubeShaped() {
return false;
}
BeaconTile::isSolidRender() {
return false;
}
const TextureUVCoordinateSet& BeaconTile::getTexture(signed char side, int data) {
return side == 0 ? tex : (side == 1 ? secondary_tex : terciary_tex);
}
TileEntity* BeaconTile::newTileEntity(const TilePos& tp) {
return new BeaconTileEntity();
}
<|endoftext|> |
<commit_before>//g++ gensecondarypair.cpp -lcrypto++ -o gensecondarypair
#include <string>
using namespace std;
#include <crypto++/rsa.h>
#include <crypto++/osrng.h>
#include <crypto++/base64.h>
#include <crypto++/files.h>
#include <crypto++/aes.h>
#include <crypto++/modes.h>
#include <crypto++/ripemd.h>
using namespace CryptoPP;
string GenKeyPair(AutoSeededRandomPool &rng)
{
// InvertibleRSAFunction is used directly only because the private key
// won't actually be used to perform any cryptographic operation;
// otherwise, an appropriate typedef'ed type from rsa.h would have been used.
InvertibleRSAFunction privkey;
privkey.Initialize(rng, 1024*4);
// With the current version of Crypto++, MessageEnd() needs to be called
// explicitly because Base64Encoder doesn't flush its buffer on destruction.
Base64Encoder privkeysink(new FileSink("secondary-privkey.txt"));
privkey.DEREncode(privkeysink);
privkeysink.MessageEnd();
// Suppose we want to store the public key separately,
// possibly because we will be sending the public key to a third party.
RSAFunction pubkey(privkey);
Base64Encoder pubkeysink(new FileSink("secondary-pubkey.txt"));
pubkey.DEREncode(pubkeysink);
pubkeysink.MessageEnd();
string pubkeyStr;
Base64Encoder pubkeysink2(new StringSink(pubkeyStr));
pubkey.DEREncode(pubkeysink2);
pubkeysink2.MessageEnd();
return pubkeyStr;
}
void SignSecondaryKey(AutoSeededRandomPool &rng, string strContents, string pass)
{
//Read private key
string encMasterPrivKey;
StringSink encMasterPrivKeySink(encMasterPrivKey);
FileSource file("master-privkey-enc.txt", true, new Base64Decoder);
file.CopyTo(encMasterPrivKeySink);
//Read initialization vector
byte iv[AES::BLOCKSIZE];
CryptoPP::ByteQueue bytesIv;
FileSource file2("master-privkey-iv.txt", true, new Base64Decoder);
file2.TransferTo(bytesIv);
bytesIv.MessageEnd();
bytesIv.Get(iv, AES::BLOCKSIZE);
cout << "IV:";
for(unsigned i=0;i<AES::BLOCKSIZE;i++)
{
cout << (int)(iv[i]) << ",";
}
cout << endl;
//Hash the pass phrase to create 128 bit key
string hashedPass;
RIPEMD128 hash;
StringSource(pass, true, new HashFilter(hash, new StringSink(hashedPass)));
//Decrypt master key
byte test[encMasterPrivKey.length()];
CFB_Mode<AES>::Decryption cfbDecryption((const unsigned char*)hashedPass.c_str(), hashedPass.length(), iv);
cfbDecryption.ProcessData(test, (byte *)encMasterPrivKey.c_str(), encMasterPrivKey.length());
StringSource masterKey(test, encMasterPrivKey.length(), new Base64Decoder);
cout << encMasterPrivKey.length() << endl;
cout << "Key:";
for(unsigned i=0;i<50;i++)
{
cout << test[i];
}
cout << "...";
for(unsigned i=encMasterPrivKey.length()-50;i<encMasterPrivKey.length();i++)
{
cout << test[i];
}
cout << endl;
RSA::PrivateKey privateKey;
privateKey.Load(masterKey);
//Sign message
RSASSA_PKCS1v15_SHA_Signer privkey(privateKey);
SecByteBlock sbbSignature(privkey.SignatureLength());
privkey.SignMessage(
rng,
(byte const*) strContents.data(),
strContents.size(),
sbbSignature);
//Save result
Base64Encoder enc(new FileSink("secondary-pubkey-sig.txt"));
enc.Put(sbbSignature, sbbSignature.size());
enc.MessageEnd();
}
int main()
{
cout << "Enter master key password" << endl;
string pass;
cin >> pass;
AutoSeededRandomPool rng;
string pubkey = GenKeyPair(rng);
SignSecondaryKey(rng, pubkey, pass);
}
<commit_msg>Master key encrypts and decrypts<commit_after>//g++ gensecondarypair.cpp -lcrypto++ -o gensecondarypair
#include <string>
using namespace std;
#include <crypto++/rsa.h>
#include <crypto++/osrng.h>
#include <crypto++/base64.h>
#include <crypto++/files.h>
#include <crypto++/aes.h>
#include <crypto++/modes.h>
#include <crypto++/ripemd.h>
using namespace CryptoPP;
string GenKeyPair(AutoSeededRandomPool &rng)
{
// InvertibleRSAFunction is used directly only because the private key
// won't actually be used to perform any cryptographic operation;
// otherwise, an appropriate typedef'ed type from rsa.h would have been used.
InvertibleRSAFunction privkey;
privkey.Initialize(rng, 1024*4);
// With the current version of Crypto++, MessageEnd() needs to be called
// explicitly because Base64Encoder doesn't flush its buffer on destruction.
Base64Encoder privkeysink(new FileSink("secondary-privkey.txt"));
privkey.DEREncode(privkeysink);
privkeysink.MessageEnd();
// Suppose we want to store the public key separately,
// possibly because we will be sending the public key to a third party.
RSAFunction pubkey(privkey);
Base64Encoder pubkeysink(new FileSink("secondary-pubkey.txt"));
pubkey.DEREncode(pubkeysink);
pubkeysink.MessageEnd();
string pubkeyStr;
Base64Encoder pubkeysink2(new StringSink(pubkeyStr));
pubkey.DEREncode(pubkeysink2);
pubkeysink2.MessageEnd();
return pubkeyStr;
}
void SignSecondaryKey(AutoSeededRandomPool &rng, string strContents, string pass)
{
//Read private key
string encMasterPrivKey;
StringSink encMasterPrivKeySink(encMasterPrivKey);
FileSource file("master-privkey-enc.txt", true, new Base64Decoder);
file.CopyTo(encMasterPrivKeySink);
//Read initialization vector
byte iv[AES::BLOCKSIZE];
CryptoPP::ByteQueue bytesIv;
FileSource file2("master-privkey-iv.txt", true, new Base64Decoder);
file2.TransferTo(bytesIv);
bytesIv.MessageEnd();
bytesIv.Get(iv, AES::BLOCKSIZE);
cout << "IV:";
for(unsigned i=0;i<AES::BLOCKSIZE;i++)
{
cout << (int)(iv[i]) << ",";
}
cout << endl;
//Hash the pass phrase to create 128 bit key
string hashedPass;
RIPEMD128 hash;
StringSource(pass, true, new HashFilter(hash, new StringSink(hashedPass)));
//Decrypt master key
byte test[encMasterPrivKey.length()];
CFB_Mode<AES>::Decryption cfbDecryption((const unsigned char*)hashedPass.c_str(), hashedPass.length(), iv);
cfbDecryption.ProcessData(test, (byte *)encMasterPrivKey.c_str(), encMasterPrivKey.length());
StringSource masterKey(test, encMasterPrivKey.length(), true, new Base64Decoder);
cout << encMasterPrivKey.length() << endl;
cout << "Key:";
for(unsigned i=0;i<50;i++)
{
cout << test[i];
}
cout << "...";
for(unsigned i=encMasterPrivKey.length()-50;i<encMasterPrivKey.length();i++)
{
cout << test[i];
}
cout << endl;
RSA::PrivateKey privateKey;
cout << "1" << endl;
privateKey.Load(masterKey);
cout << "x" << endl;
//Sign message
RSASSA_PKCS1v15_SHA_Signer privkey(privateKey);
SecByteBlock sbbSignature(privkey.SignatureLength());
privkey.SignMessage(
rng,
(byte const*) strContents.data(),
strContents.size(),
sbbSignature);
//Save result
Base64Encoder enc(new FileSink("secondary-pubkey-sig.txt"));
enc.Put(sbbSignature, sbbSignature.size());
enc.MessageEnd();
}
int main()
{
cout << "Enter master key password" << endl;
string pass;
cin >> pass;
AutoSeededRandomPool rng;
string pubkey = GenKeyPair(rng);
SignSecondaryKey(rng, pubkey, pass);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "bytes.hh"
#include "schema.hh"
#include "database_fwd.hh"
#include "db/serializer.hh"
#include "mutation_partition_visitor.hh"
#include "mutation_partition_serializer.hh"
// Immutable mutation form which can be read using any schema version of the same table.
// Safe to access from other shards via const&.
// Safe to pass serialized across nodes.
class canonical_mutation {
bytes _data;
canonical_mutation(bytes);
public:
explicit canonical_mutation(const mutation&);
canonical_mutation(canonical_mutation&&) = default;
canonical_mutation(const canonical_mutation&) = default;
canonical_mutation& operator=(const canonical_mutation&) = default;
canonical_mutation& operator=(canonical_mutation&&) = default;
// Create a mutation object interpreting this canonical mutation using
// given schema.
//
// Data which is not representable in the target schema is dropped. If this
// is not intended, user should sync the schema first.
mutation to_mutation(schema_ptr) const;
utils::UUID column_family_id() const;
friend class db::serializer<canonical_mutation>;
};
//
//template<>
//struct hash<canonical_mutation> {
// template<typename Hasher>
// void operator()(Hasher& h, const canonical_mutation& m) const {
// m.feed_hash(h);
// }
//};
namespace db {
template<> serializer<canonical_mutation>::serializer(const canonical_mutation&);
template<> void serializer<canonical_mutation>::write(output&, const canonical_mutation&);
template<> canonical_mutation serializer<canonical_mutation>::read(input&);
extern template class serializer<canonical_mutation>;
}
<commit_msg>canonical_mutation: Remove commented out junk<commit_after>/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "bytes.hh"
#include "schema.hh"
#include "database_fwd.hh"
#include "db/serializer.hh"
#include "mutation_partition_visitor.hh"
#include "mutation_partition_serializer.hh"
// Immutable mutation form which can be read using any schema version of the same table.
// Safe to access from other shards via const&.
// Safe to pass serialized across nodes.
class canonical_mutation {
bytes _data;
canonical_mutation(bytes);
public:
explicit canonical_mutation(const mutation&);
canonical_mutation(canonical_mutation&&) = default;
canonical_mutation(const canonical_mutation&) = default;
canonical_mutation& operator=(const canonical_mutation&) = default;
canonical_mutation& operator=(canonical_mutation&&) = default;
// Create a mutation object interpreting this canonical mutation using
// given schema.
//
// Data which is not representable in the target schema is dropped. If this
// is not intended, user should sync the schema first.
mutation to_mutation(schema_ptr) const;
utils::UUID column_family_id() const;
friend class db::serializer<canonical_mutation>;
};
namespace db {
template<> serializer<canonical_mutation>::serializer(const canonical_mutation&);
template<> void serializer<canonical_mutation>::write(output&, const canonical_mutation&);
template<> canonical_mutation serializer<canonical_mutation>::read(input&);
extern template class serializer<canonical_mutation>;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/chrome_browser_main_chromeos.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/lazy_instance.h"
#include "base/message_loop.h"
#include "chrome/browser/chromeos/bluetooth/bluetooth_manager.h"
#include "chrome/browser/chromeos/boot_times_loader.h"
#include "chrome/browser/chromeos/brightness_observer.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/dbus/dbus_thread_manager.h"
#include "chrome/browser/chromeos/dbus/session_manager_client.h"
#include "chrome/browser/chromeos/login/session_manager_observer.h"
#include "chrome/browser/chromeos/net/cros_network_change_notifier_factory.h"
#include "chrome/browser/chromeos/net/network_change_notifier_chromeos.h"
#include "chrome/browser/chromeos/system/statistics_provider.h"
#include "chrome/browser/defaults.h"
#include "chrome/common/chrome_switches.h"
#include "content/public/common/main_function_params.h"
#include "net/base/network_change_notifier.h"
#if defined(TOOLKIT_USES_GTK)
#include <gtk/gtk.h>
#endif
class MessageLoopObserver : public MessageLoopForUI::Observer {
#if defined(TOUCH_UI) || defined(USE_AURA)
virtual base::EventStatus WillProcessEvent(
const base::NativeEvent& event) OVERRIDE {
return base::EVENT_CONTINUE;
}
virtual void DidProcessEvent(
const base::NativeEvent& event) OVERRIDE {
}
#else
virtual void WillProcessEvent(GdkEvent* event) {
// On chromeos we want to map Alt-left click to right click.
// This code only changes presses and releases. We could decide to also
// modify drags and crossings. It doesn't seem to be a problem right now
// with our support for context menus (the only real need we have).
// There are some inconsistent states both with what we have and what
// we would get if we added drags. You could get a right drag without a
// right down for example, unless we started synthesizing events, which
// seems like more trouble than it's worth.
if ((event->type == GDK_BUTTON_PRESS ||
event->type == GDK_2BUTTON_PRESS ||
event->type == GDK_3BUTTON_PRESS ||
event->type == GDK_BUTTON_RELEASE) &&
event->button.button == 1 &&
event->button.state & GDK_MOD1_MASK) {
// Change the button to the third (right) one.
event->button.button = 3;
// Remove the Alt key and first button state.
event->button.state &= ~(GDK_MOD1_MASK | GDK_BUTTON1_MASK);
// Add the third (right) button state.
event->button.state |= GDK_BUTTON3_MASK;
}
}
virtual void DidProcessEvent(GdkEvent* event) {
}
#endif
};
static base::LazyInstance<MessageLoopObserver> g_message_loop_observer(
base::LINKER_INITIALIZED);
ChromeBrowserMainPartsChromeos::ChromeBrowserMainPartsChromeos(
const content::MainFunctionParams& parameters)
: ChromeBrowserMainPartsLinux(parameters) {
}
ChromeBrowserMainPartsChromeos::~ChromeBrowserMainPartsChromeos() {
chromeos::BluetoothManager::Shutdown();
// We should remove observers attached to D-Bus clients before
// DBusThreadManager is shut down.
if (session_manager_observer_.get()) {
chromeos::DBusThreadManager::Get()->GetSessionManagerClient()->
RemoveObserver(session_manager_observer_.get());
}
if (brightness_observer_.get()) {
chromeos::DBusThreadManager::Get()->GetPowerManagerClient()
->RemoveObserver(brightness_observer_.get());
}
chromeos::DBusThreadManager::Shutdown();
if (!parameters().ui_task && chromeos::CrosLibrary::Get())
chromeos::CrosLibrary::Shutdown();
// To be precise, logout (browser shutdown) is not yet done, but the
// remaining work is negligible, hence we say LogoutDone here.
chromeos::BootTimesLoader::Get()->AddLogoutTimeMarker("LogoutDone",
false);
chromeos::BootTimesLoader::Get()->WriteLogoutTimes();
}
void ChromeBrowserMainPartsChromeos::PreEarlyInitialization() {
ChromeBrowserMainPartsLinux::PreEarlyInitialization();
if (parsed_command_line().HasSwitch(switches::kGuestSession)) {
// Disable sync and extensions if we're in "browse without sign-in" mode.
CommandLine* singleton_command_line = CommandLine::ForCurrentProcess();
singleton_command_line->AppendSwitch(switches::kDisableSync);
singleton_command_line->AppendSwitch(switches::kDisableExtensions);
browser_defaults::bookmarks_enabled = false;
}
}
void ChromeBrowserMainPartsChromeos::PreMainMessageLoopStart() {
ChromeBrowserMainPartsLinux::PreMainMessageLoopStart();
// Initialize CrosLibrary only for the browser, unless running tests
// (which do their own CrosLibrary setup).
if (!parameters().ui_task) {
bool use_stub = parameters().command_line.HasSwitch(switches::kStubCros);
chromeos::CrosLibrary::Initialize(use_stub);
}
// Replace the default NetworkChangeNotifierFactory with ChromeOS specific
// implementation.
net::NetworkChangeNotifier::SetFactory(
new chromeos::CrosNetworkChangeNotifierFactory());
}
void ChromeBrowserMainPartsChromeos::PreMainMessageLoopRun() {
// FILE thread is created in ChromeBrowserMainParts::PreMainMessageLoopRun().
ChromeBrowserMainPartsLinux::PreMainMessageLoopRun();
// Get the statistics provider instance here to start loading statistcs
// on the background FILE thread.
chromeos::system::StatisticsProvider::GetInstance();
}
void ChromeBrowserMainPartsChromeos::PostMainMessageLoopStart() {
ChromeBrowserMainPartsPosix::PostMainMessageLoopStart();
MessageLoopForUI* message_loop = MessageLoopForUI::current();
message_loop->AddObserver(g_message_loop_observer.Pointer());
// Initialize DBusThreadManager for the browser. This must be done after
// the main message loop is started, as it uses the message loop.
chromeos::DBusThreadManager::Initialize();
// Initialize the brightness observer so that we'll display an onscreen
// indication of brightness changes during login.
brightness_observer_.reset(new chromeos::BrightnessObserver());
chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->AddObserver(
brightness_observer_.get());
// Initialize the session manager observer so that we'll take actions
// per signals sent from the session manager.
session_manager_observer_.reset(new chromeos::SessionManagerObserver);
chromeos::DBusThreadManager::Get()->GetSessionManagerClient()->
AddObserver(session_manager_observer_.get());
// Initialize the Chrome OS bluetooth subsystem
if (parsed_command_line().HasSwitch(switches::kEnableBluetooth)) {
chromeos::BluetoothManager::Initialize();
}
// Initialize the network change notifier for Chrome OS. The network
// change notifier starts to monitor changes from the power manager and
// the network manager.
chromeos::CrosNetworkChangeNotifierFactory::GetInstance()->Init();
}
<commit_msg>Set NumLock on by default when chrome starts.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/chrome_browser_main_chromeos.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/lazy_instance.h"
#include "base/message_loop.h"
#include "chrome/browser/chromeos/bluetooth/bluetooth_manager.h"
#include "chrome/browser/chromeos/boot_times_loader.h"
#include "chrome/browser/chromeos/brightness_observer.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/dbus/dbus_thread_manager.h"
#include "chrome/browser/chromeos/dbus/session_manager_client.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/input_method/xkeyboard.h"
#include "chrome/browser/chromeos/login/session_manager_observer.h"
#include "chrome/browser/chromeos/net/cros_network_change_notifier_factory.h"
#include "chrome/browser/chromeos/net/network_change_notifier_chromeos.h"
#include "chrome/browser/chromeos/system/runtime_environment.h"
#include "chrome/browser/chromeos/system/statistics_provider.h"
#include "chrome/browser/defaults.h"
#include "chrome/common/chrome_switches.h"
#include "content/public/common/main_function_params.h"
#include "net/base/network_change_notifier.h"
#if defined(TOOLKIT_USES_GTK)
#include <gtk/gtk.h>
#endif
class MessageLoopObserver : public MessageLoopForUI::Observer {
#if defined(TOUCH_UI) || defined(USE_AURA)
virtual base::EventStatus WillProcessEvent(
const base::NativeEvent& event) OVERRIDE {
return base::EVENT_CONTINUE;
}
virtual void DidProcessEvent(
const base::NativeEvent& event) OVERRIDE {
}
#else
virtual void WillProcessEvent(GdkEvent* event) {
// On chromeos we want to map Alt-left click to right click.
// This code only changes presses and releases. We could decide to also
// modify drags and crossings. It doesn't seem to be a problem right now
// with our support for context menus (the only real need we have).
// There are some inconsistent states both with what we have and what
// we would get if we added drags. You could get a right drag without a
// right down for example, unless we started synthesizing events, which
// seems like more trouble than it's worth.
if ((event->type == GDK_BUTTON_PRESS ||
event->type == GDK_2BUTTON_PRESS ||
event->type == GDK_3BUTTON_PRESS ||
event->type == GDK_BUTTON_RELEASE) &&
event->button.button == 1 &&
event->button.state & GDK_MOD1_MASK) {
// Change the button to the third (right) one.
event->button.button = 3;
// Remove the Alt key and first button state.
event->button.state &= ~(GDK_MOD1_MASK | GDK_BUTTON1_MASK);
// Add the third (right) button state.
event->button.state |= GDK_BUTTON3_MASK;
}
}
virtual void DidProcessEvent(GdkEvent* event) {
}
#endif
};
static base::LazyInstance<MessageLoopObserver> g_message_loop_observer(
base::LINKER_INITIALIZED);
ChromeBrowserMainPartsChromeos::ChromeBrowserMainPartsChromeos(
const content::MainFunctionParams& parameters)
: ChromeBrowserMainPartsLinux(parameters) {
}
ChromeBrowserMainPartsChromeos::~ChromeBrowserMainPartsChromeos() {
chromeos::BluetoothManager::Shutdown();
// We should remove observers attached to D-Bus clients before
// DBusThreadManager is shut down.
if (session_manager_observer_.get()) {
chromeos::DBusThreadManager::Get()->GetSessionManagerClient()->
RemoveObserver(session_manager_observer_.get());
}
if (brightness_observer_.get()) {
chromeos::DBusThreadManager::Get()->GetPowerManagerClient()
->RemoveObserver(brightness_observer_.get());
}
chromeos::DBusThreadManager::Shutdown();
if (!parameters().ui_task && chromeos::CrosLibrary::Get())
chromeos::CrosLibrary::Shutdown();
// To be precise, logout (browser shutdown) is not yet done, but the
// remaining work is negligible, hence we say LogoutDone here.
chromeos::BootTimesLoader::Get()->AddLogoutTimeMarker("LogoutDone",
false);
chromeos::BootTimesLoader::Get()->WriteLogoutTimes();
}
void ChromeBrowserMainPartsChromeos::PreEarlyInitialization() {
ChromeBrowserMainPartsLinux::PreEarlyInitialization();
if (parsed_command_line().HasSwitch(switches::kGuestSession)) {
// Disable sync and extensions if we're in "browse without sign-in" mode.
CommandLine* singleton_command_line = CommandLine::ForCurrentProcess();
singleton_command_line->AppendSwitch(switches::kDisableSync);
singleton_command_line->AppendSwitch(switches::kDisableExtensions);
browser_defaults::bookmarks_enabled = false;
}
}
void ChromeBrowserMainPartsChromeos::PreMainMessageLoopStart() {
ChromeBrowserMainPartsLinux::PreMainMessageLoopStart();
// Initialize CrosLibrary only for the browser, unless running tests
// (which do their own CrosLibrary setup).
if (!parameters().ui_task) {
bool use_stub = parameters().command_line.HasSwitch(switches::kStubCros);
chromeos::CrosLibrary::Initialize(use_stub);
}
// Replace the default NetworkChangeNotifierFactory with ChromeOS specific
// implementation.
net::NetworkChangeNotifier::SetFactory(
new chromeos::CrosNetworkChangeNotifierFactory());
}
void ChromeBrowserMainPartsChromeos::PreMainMessageLoopRun() {
// FILE thread is created in ChromeBrowserMainParts::PreMainMessageLoopRun().
ChromeBrowserMainPartsLinux::PreMainMessageLoopRun();
// Get the statistics provider instance here to start loading statistcs
// on the background FILE thread.
chromeos::system::StatisticsProvider::GetInstance();
}
void ChromeBrowserMainPartsChromeos::PostMainMessageLoopStart() {
ChromeBrowserMainPartsPosix::PostMainMessageLoopStart();
MessageLoopForUI* message_loop = MessageLoopForUI::current();
message_loop->AddObserver(g_message_loop_observer.Pointer());
// Initialize DBusThreadManager for the browser. This must be done after
// the main message loop is started, as it uses the message loop.
chromeos::DBusThreadManager::Initialize();
// Initialize the brightness observer so that we'll display an onscreen
// indication of brightness changes during login.
brightness_observer_.reset(new chromeos::BrightnessObserver());
chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->AddObserver(
brightness_observer_.get());
// Initialize the session manager observer so that we'll take actions
// per signals sent from the session manager.
session_manager_observer_.reset(new chromeos::SessionManagerObserver);
chromeos::DBusThreadManager::Get()->GetSessionManagerClient()->
AddObserver(session_manager_observer_.get());
// Initialize the Chrome OS bluetooth subsystem
if (parsed_command_line().HasSwitch(switches::kEnableBluetooth)) {
chromeos::BluetoothManager::Initialize();
}
// Initialize the network change notifier for Chrome OS. The network
// change notifier starts to monitor changes from the power manager and
// the network manager.
chromeos::CrosNetworkChangeNotifierFactory::GetInstance()->Init();
// For http://crosbug.com/p/5795 and http://crosbug.com/p/6245.
// Enable Num Lock on X start up.
if (chromeos::system::runtime_environment::IsRunningOnChromeOS()) {
chromeos::input_method::InputMethodManager::GetInstance()->GetXKeyboard()->
SetNumLockEnabled(true);
}
}
<|endoftext|> |
<commit_before>#include <cstdarg>
#include <cstdio>
#include <exception>
#include <iostream>
#include <sstream>
#include <string>
#include "lisp_ptr.hh"
#include "printer.hh"
#include "procedure.hh"
#include "rational.hh"
#include "s_closure.hh"
#include "zs_error.hh"
#include "zs_memory.hh"
static const size_t ERROR_MESSAGE_LENGTH = 256;
using namespace std;
void zs_terminate_handler() noexcept{
std::set_terminate(nullptr);
try{
rethrow_exception(current_exception());
}catch(const Lisp_ptr& errobj){
cerr << "uncaught exception!\n"
<< "raised object: " << errobj << '\n'
<< endl;
}catch(const std::exception& e){
cerr << "uncaught system exception!\n"
<< "what: " << e.what()
<< endl;
}catch(...){
cerr << "unexpected internal exception!\n"
<< endl;
}
cerr << "Aborting..." << endl;
abort();
}
static
string vprintf_string(const char* fmt, va_list ap){
string str(ERROR_MESSAGE_LENGTH, '\0');
vsnprintf(&(str[0]), str.size(), fmt, ap);
return str;
}
// error functions
void throw_zs_error(Lisp_ptr p, const char* fmt, ...){
va_list ap;
va_start(ap, fmt);
auto str = vprintf_string(fmt, ap);
va_end(ap);
if(!p){
throw Lisp_ptr{zs_new<String>(move(str))};
}else{
ostringstream oss;
oss << str << " @ (" << p << ")" << endl;
throw Lisp_ptr{zs_new<String>(oss.str())};
}
}
void throw_zs_error_append(Lisp_ptr context, Lisp_ptr p){
ostringstream oss;
oss << context << " : " << p;
throw Lisp_ptr{zs_new<String>(oss.str())};
}
void print_zs_warning(const char* fmt, ...){
va_list ap;
va_start(ap, fmt);
auto str = vprintf_string(fmt, ap);
va_end(ap);
cerr << str << endl;
}
void check_type(Ptr_tag tag, Lisp_ptr p){
if(p.tag() != tag){
throw_zs_error(p, "arg is not %s!", stringify(tag));
}
}
void check_numeric_type(Lisp_ptr p){
if(!is_numeric_type(p)){
throw_zs_error(p, "arg is not number!");
}
}
void check_identifier_type(Lisp_ptr p){
if(!identifierp(p)){
throw_zs_error(p, "arg is not identifier!");
}
}
void check_procedure_type(Lisp_ptr p){
if(!is_procedure(p)){
throw_zs_error(p, "arg is not procedure!");
}
}
void check_range(Lisp_ptr p, size_t min, size_t max){
check_type(Ptr_tag::integer, p);
auto idx = p.get<int>();
if(idx < min || idx >= max){
// The 'z' specifier is a C99 feature, included in C++11.
throw_zs_error({}, "inacceptable index ([%zd, %zd), supplied %d\n",
min, max, idx);
}
}
<commit_msg>fixed error message<commit_after>#include <cstdarg>
#include <cstdio>
#include <exception>
#include <iostream>
#include <sstream>
#include <string>
#include "lisp_ptr.hh"
#include "printer.hh"
#include "procedure.hh"
#include "rational.hh"
#include "s_closure.hh"
#include "zs_error.hh"
#include "zs_memory.hh"
static const size_t ERROR_MESSAGE_LENGTH = 256;
using namespace std;
void zs_terminate_handler() noexcept{
std::set_terminate(nullptr);
try{
rethrow_exception(current_exception());
}catch(const Lisp_ptr& errobj){
cerr << "uncaught exception!\n"
<< "raised object: " << errobj << '\n'
<< endl;
}catch(const std::exception& e){
cerr << "uncaught system exception!\n"
<< "what: " << e.what()
<< endl;
}catch(...){
cerr << "unexpected internal exception!\n"
<< endl;
}
cerr << "Aborting..." << endl;
abort();
}
// error functions
void throw_zs_error(Lisp_ptr p, const char* fmt, ...){
char strbuf[ERROR_MESSAGE_LENGTH];
va_list ap;
va_start(ap, fmt);
vsnprintf(strbuf, sizeof(strbuf), fmt, ap);
va_end(ap);
if(!p){
throw Lisp_ptr{zs_new<String>(strbuf)};
}else{
ostringstream oss;
oss << strbuf << " @ (" << p << ")" << endl;
throw Lisp_ptr{zs_new<String>(oss.str())};
}
}
void throw_zs_error_append(Lisp_ptr context, Lisp_ptr p){
ostringstream oss;
oss << context << " : " << p;
throw Lisp_ptr{zs_new<String>(oss.str())};
}
void print_zs_warning(const char* fmt, ...){
char strbuf[ERROR_MESSAGE_LENGTH];
va_list ap;
va_start(ap, fmt);
vsnprintf(strbuf, sizeof(strbuf), fmt, ap);
va_end(ap);
cerr << strbuf << endl;
}
void check_type(Ptr_tag tag, Lisp_ptr p){
if(p.tag() != tag){
throw_zs_error(p, "arg is not %s!", stringify(tag));
}
}
void check_numeric_type(Lisp_ptr p){
if(!is_numeric_type(p)){
throw_zs_error(p, "arg is not number!");
}
}
void check_identifier_type(Lisp_ptr p){
if(!identifierp(p)){
throw_zs_error(p, "arg is not identifier!");
}
}
void check_procedure_type(Lisp_ptr p){
if(!is_procedure(p)){
throw_zs_error(p, "arg is not procedure!");
}
}
void check_range(Lisp_ptr p, size_t min, size_t max){
check_type(Ptr_tag::integer, p);
auto idx = p.get<int>();
if(idx < min || idx >= max){
// The 'z' specifier is a C99 feature, included in C++11.
throw_zs_error({}, "inacceptable index ([%zd, %zd), supplied %d\n",
min, max, idx);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2016 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/
#include <iostream>
#include <pegtl.hh>
namespace csv1
{
// Simple CSV-file format for an unknown-at-compile-time number of values per
// line, the values are space/tab-padded integers, comment lines start with
// a hash and are ignored; the grammar does not enforce the same number of
// values per line, this would have to be done by the actions; last line can
// end with an LF or CR+LF but doesn't have to.
// Example file contents parsed by this grammar (excluding C++ comment intro):
// # This is a comment
// 123 , 124,41,1
// 1,2,3,4
// 1
// 1,2
struct value : pegtl::plus< pegtl::digit > {};
struct value_item : pegtl::pad< value, pegtl::blank > {};
struct value_list : pegtl::list_must< value_item, pegtl::one< ',' > > {};
struct value_line : pegtl::if_must< value_list, pegtl::eolf > {};
struct comment_line : pegtl::seq< pegtl::one< '#' >, pegtl::until< pegtl::eolf > > {};
struct line : pegtl::sor< comment_line, value_line > {};
struct file : pegtl::until< pegtl::eof, line > {};
} // csv1
int main( int argc, char ** argv )
{
for ( int i = 1; i < argc; ++i ) {
pegtl::file_parser fp( argv[ i ] );
std::cout << argv[ i ] << " " << fp.parse< csv1::file >() << std::endl;
}
return 0;
}
<commit_msg>Add actions.<commit_after>// Copyright (c) 2016 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/
#include <vector>
#include <string>
#include <cassert>
#include <cstdint>
#include <iostream>
#include <pegtl.hh>
namespace csv1
{
// Simple CSV-file format for an unknown-at-compile-time number of values per
// line, the values are space/tab-padded integers, comment lines start with
// a hash and are ignored; neither the grammar nor the included actions make
// sure that the number of values per line is always the same; last line can
// end with an LF or CR+LF but doesn't have to.
// Example file contents parsed by this grammar (excluding C++ comment intro):
// # This is a comment
// 123 , 124,41,1
// 1,2,3,4
// 1
// 1,2
struct value : pegtl::plus< pegtl::digit > {};
struct value_item : pegtl::pad< value, pegtl::blank > {};
struct value_list : pegtl::list_must< value_item, pegtl::one< ',' > > {};
struct value_line : pegtl::if_must< value_list, pegtl::eolf > {};
struct comment_line : pegtl::seq< pegtl::one< '#' >, pegtl::until< pegtl::eolf > > {};
struct line : pegtl::sor< comment_line, value_line > {};
struct file : pegtl::until< pegtl::eof, line > {};
// Data structure to store the result of a parsing run:
using result_data = std::vector< std::vector< unsigned long > >;
// Action and control classes to fill in the above data structure:
template< typename Rule > struct action : pegtl::nothing< Rule > {};
template<> struct action< value >
{
static void apply( const pegtl::action_input & in, result_data & data )
{
assert( ! data.empty() );
data.back().push_back( std::stoul( in.string() ) );
}
};
template< typename Rule > struct control : pegtl::normal< Rule > {};
template<> struct control< value_line >
: pegtl::normal< value_line >
{
template< typename Input >
static void start( Input &, result_data & data )
{
data.push_back( std::vector< unsigned long >() );
}
template< typename Input >
static void failure( Input &, result_data & data )
{
assert( ! data.empty() );
data.pop_back();
}
};
} // csv1
int main( int argc, char ** argv )
{
for ( int i = 1; i < argc; ++i ) {
pegtl::file_parser fp( argv[ i ] );
csv1::result_data data;
fp.parse< pegtl::must< csv1::file >, csv1::action, csv1::control >( data );
for ( const auto & line : data ) {
assert( ! line.empty() ); // The grammar doesn't allow empty lines.
std::cout << line.front();
for ( std::size_t j = 1; j < line.size(); ++j ) {
std::cout << ", " << line[ j ];
}
std::cout << std::endl;
}
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 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 <vector>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_observer.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/net_util.h"
// This file contains high-level startup tests for the extensions system. We've
// had many silly bugs where command line flags did not get propagated correctly
// into the services, so we didn't start correctly.
class ExtensionStartupTestBase : public InProcessBrowserTest {
public:
ExtensionStartupTestBase() : enable_extensions_(false) {
}
protected:
// InProcessBrowserTest
virtual void SetUpCommandLine(CommandLine* command_line) {
EnableDOMAutomation();
FilePath profile_dir;
PathService::Get(chrome::DIR_USER_DATA, &profile_dir);
profile_dir = profile_dir.AppendASCII("Default");
file_util::CreateDirectory(profile_dir);
preferences_file_ = profile_dir.AppendASCII("Preferences");
user_scripts_dir_ = profile_dir.AppendASCII("User Scripts");
extensions_dir_ = profile_dir.AppendASCII("Extensions");
if (enable_extensions_) {
FilePath src_dir;
PathService::Get(chrome::DIR_TEST_DATA, &src_dir);
src_dir = src_dir.AppendASCII("extensions").AppendASCII("good");
file_util::CopyFile(src_dir.AppendASCII("Preferences"),
preferences_file_);
file_util::CopyDirectory(src_dir.AppendASCII("Extensions"),
profile_dir, true); // recursive
} else {
command_line->AppendSwitch(switches::kDisableExtensions);
}
if (!load_extension_.value().empty()) {
command_line->AppendSwitchWithValue(switches::kLoadExtension,
load_extension_.ToWStringHack());
}
}
virtual void TearDown() {
EXPECT_TRUE(file_util::Delete(preferences_file_, false));
// TODO(phajdan.jr): Check return values of the functions below, carefully.
file_util::Delete(user_scripts_dir_, true);
file_util::Delete(extensions_dir_, true));
}
void WaitForServicesToStart(int num_expected_extensions,
bool expect_extensions_enabled) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
if (!service->is_ready())
ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY);
ASSERT_TRUE(service->is_ready());
ASSERT_EQ(static_cast<uint32>(num_expected_extensions),
service->extensions()->size());
ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled());
UserScriptMaster* master = browser()->profile()->GetUserScriptMaster();
if (!master->ScriptsReady()) {
ui_test_utils::WaitForNotification(
NotificationType::USER_SCRIPTS_UPDATED);
}
ASSERT_TRUE(master->ScriptsReady());
}
void TestInjection(bool expect_css, bool expect_script) {
// Load a page affected by the content script and test to see the effect.
FilePath test_file;
PathService::Get(chrome::DIR_TEST_DATA, &test_file);
test_file = test_file.AppendASCII("extensions")
.AppendASCII("test_file.html");
ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file));
bool result = false;
ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send("
L"document.defaultView.getComputedStyle(document.body, null)."
L"getPropertyValue('background-color') == 'rgb(245, 245, 220)')",
&result);
EXPECT_EQ(expect_css, result);
result = false;
ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'Modified')",
&result);
EXPECT_EQ(expect_script, result);
}
FilePath preferences_file_;
FilePath extensions_dir_;
FilePath user_scripts_dir_;
bool enable_extensions_;
FilePath load_extension_;
};
// ExtensionsStartupTest
// Ensures that we can startup the browser with --enable-extensions and some
// extensions installed and see them run and do basic things.
class ExtensionsStartupTest : public ExtensionStartupTestBase {
public:
ExtensionsStartupTest() {
enable_extensions_ = true;
}
};
IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, Test) {
WaitForServicesToStart(4, true); // 1 component extension and 3 others.
TestInjection(true, true);
}
// ExtensionsLoadTest
// Ensures that we can startup the browser with --load-extension and see them
// run.
class ExtensionsLoadTest : public ExtensionStartupTestBase {
public:
ExtensionsLoadTest() {
PathService::Get(chrome::DIR_TEST_DATA, &load_extension_);
load_extension_ = load_extension_
.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("Extensions")
.AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
.AppendASCII("1.0.0.0");
}
};
IN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, Test) {
WaitForServicesToStart(1, false);
TestInjection(true, true);
}
<commit_msg>Fix build (trivial syntax error).<commit_after>// Copyright (c) 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 <vector>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_observer.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/net_util.h"
// This file contains high-level startup tests for the extensions system. We've
// had many silly bugs where command line flags did not get propagated correctly
// into the services, so we didn't start correctly.
class ExtensionStartupTestBase : public InProcessBrowserTest {
public:
ExtensionStartupTestBase() : enable_extensions_(false) {
}
protected:
// InProcessBrowserTest
virtual void SetUpCommandLine(CommandLine* command_line) {
EnableDOMAutomation();
FilePath profile_dir;
PathService::Get(chrome::DIR_USER_DATA, &profile_dir);
profile_dir = profile_dir.AppendASCII("Default");
file_util::CreateDirectory(profile_dir);
preferences_file_ = profile_dir.AppendASCII("Preferences");
user_scripts_dir_ = profile_dir.AppendASCII("User Scripts");
extensions_dir_ = profile_dir.AppendASCII("Extensions");
if (enable_extensions_) {
FilePath src_dir;
PathService::Get(chrome::DIR_TEST_DATA, &src_dir);
src_dir = src_dir.AppendASCII("extensions").AppendASCII("good");
file_util::CopyFile(src_dir.AppendASCII("Preferences"),
preferences_file_);
file_util::CopyDirectory(src_dir.AppendASCII("Extensions"),
profile_dir, true); // recursive
} else {
command_line->AppendSwitch(switches::kDisableExtensions);
}
if (!load_extension_.value().empty()) {
command_line->AppendSwitchWithValue(switches::kLoadExtension,
load_extension_.ToWStringHack());
}
}
virtual void TearDown() {
EXPECT_TRUE(file_util::Delete(preferences_file_, false));
// TODO(phajdan.jr): Check return values of the functions below, carefully.
file_util::Delete(user_scripts_dir_, true);
file_util::Delete(extensions_dir_, true);
}
void WaitForServicesToStart(int num_expected_extensions,
bool expect_extensions_enabled) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
if (!service->is_ready())
ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY);
ASSERT_TRUE(service->is_ready());
ASSERT_EQ(static_cast<uint32>(num_expected_extensions),
service->extensions()->size());
ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled());
UserScriptMaster* master = browser()->profile()->GetUserScriptMaster();
if (!master->ScriptsReady()) {
ui_test_utils::WaitForNotification(
NotificationType::USER_SCRIPTS_UPDATED);
}
ASSERT_TRUE(master->ScriptsReady());
}
void TestInjection(bool expect_css, bool expect_script) {
// Load a page affected by the content script and test to see the effect.
FilePath test_file;
PathService::Get(chrome::DIR_TEST_DATA, &test_file);
test_file = test_file.AppendASCII("extensions")
.AppendASCII("test_file.html");
ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file));
bool result = false;
ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send("
L"document.defaultView.getComputedStyle(document.body, null)."
L"getPropertyValue('background-color') == 'rgb(245, 245, 220)')",
&result);
EXPECT_EQ(expect_css, result);
result = false;
ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'Modified')",
&result);
EXPECT_EQ(expect_script, result);
}
FilePath preferences_file_;
FilePath extensions_dir_;
FilePath user_scripts_dir_;
bool enable_extensions_;
FilePath load_extension_;
};
// ExtensionsStartupTest
// Ensures that we can startup the browser with --enable-extensions and some
// extensions installed and see them run and do basic things.
class ExtensionsStartupTest : public ExtensionStartupTestBase {
public:
ExtensionsStartupTest() {
enable_extensions_ = true;
}
};
IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, Test) {
WaitForServicesToStart(4, true); // 1 component extension and 3 others.
TestInjection(true, true);
}
// ExtensionsLoadTest
// Ensures that we can startup the browser with --load-extension and see them
// run.
class ExtensionsLoadTest : public ExtensionStartupTestBase {
public:
ExtensionsLoadTest() {
PathService::Get(chrome::DIR_TEST_DATA, &load_extension_);
load_extension_ = load_extension_
.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("Extensions")
.AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
.AppendASCII("1.0.0.0");
}
};
IN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, Test) {
WaitForServicesToStart(1, false);
TestInjection(true, true);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "swirlcons_user.h"
#include <fclaw2d_include_all.h>
#include <fclaw2d_clawpatch_options.h>
#include <fclaw2d_clawpatch.h>
#include <fc2d_clawpack46_options.h>
#include <fc2d_clawpack46.h>
/* ------------------------- ... and here ---------------------------- */
static
fclaw2d_domain_t* create_domain(sc_MPI_Comm mpicomm, fclaw_options_t* fclaw_opt,
user_options_t *user)
{
/* Mapped, multi-block domain */
p4est_connectivity_t *conn = NULL;
fclaw2d_domain_t *domain;
fclaw2d_map_context_t *cont = NULL, *brick = NULL;
int mi = fclaw_opt->mi;
int mj = fclaw_opt->mj;
int a = fclaw_opt->periodic_x;
int b = fclaw_opt->periodic_y;
double rotate[2];
rotate[0] = 0;
rotate[1] = 0;
switch (user->mapping) {
case 0:
/* Square brick domain */
conn = p4est_connectivity_new_brick(mi,mj,a,b);
brick = fclaw2d_map_new_brick(conn,mi,mj);
cont = fclaw2d_map_new_nomap_brick(brick);
break;
case 1:
conn = p4est_connectivity_new_brick(mi,mj,a,b);
brick = fclaw2d_map_new_brick(conn,mi,mj);
cont = fclaw2d_map_new_cart(brick,fclaw_opt->scale,
fclaw_opt->shift,
rotate);
break;
case 2:
/* Five patch square domain */
conn = p4est_connectivity_new_disk ();
cont = fclaw2d_map_new_fivepatch (fclaw_opt->scale,fclaw_opt->shift,
rotate,user->alpha);
break;
case 3:
/* bilinear square domain */
conn = p4est_connectivity_new_brick (mi,mj,a,b);
brick = fclaw2d_map_new_brick(conn,mi,mj);
cont = fclaw2d_map_new_bilinear (brick, fclaw_opt->scale,fclaw_opt->shift,
rotate,user->center);
break;
default:
SC_ABORT_NOT_REACHED ();
}
domain = fclaw2d_domain_new_conn_map (mpicomm, fclaw_opt->minlevel, conn, cont);
fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_ESSENTIAL);
fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);
return domain;
}
static
void run_program(fclaw2d_global_t* glob)
{
/* ---------------------------------------------------------------
Set domain data.
--------------------------------------------------------------- */
fclaw2d_domain_data_new(glob->domain);
/* Initialize virtual table for ForestClaw */
fclaw2d_vtable_initialize();
fclaw2d_diagnostics_vtable_initialize();
/* Initialize virtual tables for solvers */
fc2d_clawpack46_solver_initialize();
swirlcons_link_solvers(glob);
/* ---------------------------------------------------------------
Run
--------------------------------------------------------------- */
fclaw2d_initialize(glob);
fclaw2d_run(glob);
fclaw2d_finalize(glob);
}
int
main (int argc, char **argv)
{
fclaw_app_t *app;
int first_arg;
fclaw_exit_type_t vexit;
/* Options */
sc_options_t *options;
user_options_t *user_opt;
fclaw_options_t *fclaw_opt;
fclaw2d_clawpatch_options_t *clawpatch_opt;
fc2d_clawpack46_options_t *claw46_opt;
fclaw2d_global_t *glob;
fclaw2d_domain_t *domain;
sc_MPI_Comm mpicomm;
int retval;
/* Initialize application */
app = fclaw_app_new (&argc, &argv, NULL);
/* Create new options packages */
fclaw_opt = fclaw_options_register(app,"fclaw_options.ini");
clawpatch_opt = fclaw2d_clawpatch_options_register(app,"fclaw_options.ini");
claw46_opt = fc2d_clawpack46_options_register(app,"fclaw_options.ini");
user_opt = swirlcons_options_register(app,"fclaw_options.ini");
/* Read configuration file(s) and command line, and process options */
options = fclaw_app_get_options (app);
retval = fclaw_options_read_from_file(options);
vexit = fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used");
/* Run the program */
if (!retval & !vexit)
{
/* Options have been checked and are valid */
mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);
domain = create_domain(mpicomm, fclaw_opt,user_opt);
/* Create global structure which stores the domain, timers, etc */
glob = fclaw2d_global_new();
fclaw2d_global_store_domain(glob, domain);
/* Store option packages in glob */
fclaw2d_options_store (glob, fclaw_opt);
fclaw2d_clawpatch_options_store (glob, clawpatch_opt);
fc2d_clawpack46_options_store (glob, claw46_opt);
swirlcons_options_store (glob, user_opt);
run_program(glob);
fclaw2d_global_destroy(glob);
}
fclaw_app_destroy (app);
return 0;
}
<commit_msg>(swirlcons) Allow for periodic five patch domain<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "swirlcons_user.h"
#include <fclaw2d_include_all.h>
#include <fclaw2d_clawpatch_options.h>
#include <fclaw2d_clawpatch.h>
#include <fc2d_clawpack46_options.h>
#include <fc2d_clawpack46.h>
/* ------------------------- ... and here ---------------------------- */
static
fclaw2d_domain_t* create_domain(sc_MPI_Comm mpicomm, fclaw_options_t* fclaw_opt,
user_options_t *user)
{
/* Mapped, multi-block domain */
p4est_connectivity_t *conn = NULL;
fclaw2d_domain_t *domain;
fclaw2d_map_context_t *cont = NULL, *brick = NULL;
int mi = fclaw_opt->mi;
int mj = fclaw_opt->mj;
int a = fclaw_opt->periodic_x;
int b = fclaw_opt->periodic_y;
double rotate[2];
rotate[0] = 0;
rotate[1] = 0;
switch (user->mapping) {
case 0:
/* Square brick domain */
conn = p4est_connectivity_new_brick(mi,mj,a,b);
brick = fclaw2d_map_new_brick(conn,mi,mj);
cont = fclaw2d_map_new_nomap_brick(brick);
break;
case 1:
conn = p4est_connectivity_new_brick(mi,mj,a,b);
brick = fclaw2d_map_new_brick(conn,mi,mj);
cont = fclaw2d_map_new_cart(brick,fclaw_opt->scale,
fclaw_opt->shift,
rotate);
break;
case 2:
/* Five patch square domain */
conn = p4est_connectivity_new_disk (1,1);
cont = fclaw2d_map_new_fivepatch (fclaw_opt->scale,fclaw_opt->shift,
rotate,user->alpha);
break;
case 3:
/* bilinear square domain */
conn = p4est_connectivity_new_brick (mi,mj,a,b);
brick = fclaw2d_map_new_brick(conn,mi,mj);
cont = fclaw2d_map_new_bilinear (brick, fclaw_opt->scale,fclaw_opt->shift,
rotate,user->center);
break;
default:
SC_ABORT_NOT_REACHED ();
}
domain = fclaw2d_domain_new_conn_map (mpicomm, fclaw_opt->minlevel, conn, cont);
fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_ESSENTIAL);
fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);
return domain;
}
static
void run_program(fclaw2d_global_t* glob)
{
/* ---------------------------------------------------------------
Set domain data.
--------------------------------------------------------------- */
fclaw2d_domain_data_new(glob->domain);
/* Initialize virtual table for ForestClaw */
fclaw2d_vtable_initialize();
fclaw2d_diagnostics_vtable_initialize();
/* Initialize virtual tables for solvers */
fc2d_clawpack46_solver_initialize();
swirlcons_link_solvers(glob);
/* ---------------------------------------------------------------
Run
--------------------------------------------------------------- */
fclaw2d_initialize(glob);
fclaw2d_run(glob);
fclaw2d_finalize(glob);
}
int
main (int argc, char **argv)
{
fclaw_app_t *app;
int first_arg;
fclaw_exit_type_t vexit;
/* Options */
sc_options_t *options;
user_options_t *user_opt;
fclaw_options_t *fclaw_opt;
fclaw2d_clawpatch_options_t *clawpatch_opt;
fc2d_clawpack46_options_t *claw46_opt;
fclaw2d_global_t *glob;
fclaw2d_domain_t *domain;
sc_MPI_Comm mpicomm;
int retval;
/* Initialize application */
app = fclaw_app_new (&argc, &argv, NULL);
/* Create new options packages */
fclaw_opt = fclaw_options_register(app,"fclaw_options.ini");
clawpatch_opt = fclaw2d_clawpatch_options_register(app,"fclaw_options.ini");
claw46_opt = fc2d_clawpack46_options_register(app,"fclaw_options.ini");
user_opt = swirlcons_options_register(app,"fclaw_options.ini");
/* Read configuration file(s) and command line, and process options */
options = fclaw_app_get_options (app);
retval = fclaw_options_read_from_file(options);
vexit = fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used");
/* Run the program */
if (!retval & !vexit)
{
/* Options have been checked and are valid */
mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);
domain = create_domain(mpicomm, fclaw_opt,user_opt);
/* Create global structure which stores the domain, timers, etc */
glob = fclaw2d_global_new();
fclaw2d_global_store_domain(glob, domain);
/* Store option packages in glob */
fclaw2d_options_store (glob, fclaw_opt);
fclaw2d_clawpatch_options_store (glob, clawpatch_opt);
fc2d_clawpack46_options_store (glob, claw46_opt);
swirlcons_options_store (glob, user_opt);
run_program(glob);
fclaw2d_global_destroy(glob);
}
fclaw_app_destroy (app);
return 0;
}
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <[email protected]>
* @date 2014
* Unit tests for the solidity scanner.
*/
#include <libsolidity/Scanner.h>
#include <boost/test/unit_test.hpp>
namespace dev
{
namespace solidity
{
namespace test
{
BOOST_AUTO_TEST_SUITE(SolidityScanner)
BOOST_AUTO_TEST_CASE(test_empty)
{
Scanner scanner(CharStream(""));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(smoke_test)
{
Scanner scanner(CharStream("function break;765 \t \"string1\",'string2'\nidentifier1"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::FUNCTION);
BOOST_CHECK_EQUAL(scanner.next(), Token::BREAK);
BOOST_CHECK_EQUAL(scanner.next(), Token::SEMICOLON);
BOOST_CHECK_EQUAL(scanner.next(), Token::NUMBER);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "765");
BOOST_CHECK_EQUAL(scanner.next(), Token::STRING_LITERAL);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "string1");
BOOST_CHECK_EQUAL(scanner.next(), Token::COMMA);
BOOST_CHECK_EQUAL(scanner.next(), Token::STRING_LITERAL);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "string2");
BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "identifier1");
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(string_escapes)
{
Scanner scanner(CharStream(" { \"a\\x61\""));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::LBRACE);
BOOST_CHECK_EQUAL(scanner.next(), Token::STRING_LITERAL);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "aa");
}
BOOST_AUTO_TEST_CASE(string_escapes_with_zero)
{
Scanner scanner(CharStream(" { \"a\\x61\\x00abc\""));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::LBRACE);
BOOST_CHECK_EQUAL(scanner.next(), Token::STRING_LITERAL);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), std::string("aa\0abc", 6));
}
BOOST_AUTO_TEST_CASE(string_escape_illegal)
{
Scanner scanner(CharStream(" bla \"\\x6rf\" (illegalescape)"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.next(), Token::ILLEGAL);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "");
// TODO recovery from illegal tokens should be improved
BOOST_CHECK_EQUAL(scanner.next(), Token::ILLEGAL);
BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.next(), Token::ILLEGAL);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(hex_numbers)
{
Scanner scanner(CharStream("var x = 0x765432536763762734623472346;"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::VAR);
BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.next(), Token::ASSIGN);
BOOST_CHECK_EQUAL(scanner.next(), Token::NUMBER);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "0x765432536763762734623472346");
BOOST_CHECK_EQUAL(scanner.next(), Token::SEMICOLON);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(negative_numbers)
{
Scanner scanner(CharStream("var x = -.2 + -0x78 + -7.3 + 8.9;"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::VAR);
BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.next(), Token::ASSIGN);
BOOST_CHECK_EQUAL(scanner.next(), Token::NUMBER);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "-.2");
BOOST_CHECK_EQUAL(scanner.next(), Token::ADD);
BOOST_CHECK_EQUAL(scanner.next(), Token::NUMBER);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "-0x78");
BOOST_CHECK_EQUAL(scanner.next(), Token::ADD);
BOOST_CHECK_EQUAL(scanner.next(), Token::NUMBER);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "-7.3");
BOOST_CHECK_EQUAL(scanner.next(), Token::ADD);
BOOST_CHECK_EQUAL(scanner.next(), Token::NUMBER);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "8.9");
BOOST_CHECK_EQUAL(scanner.next(), Token::SEMICOLON);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(locations)
{
Scanner scanner(CharStream("function_identifier has ; -0x743/*comment*/\n ident //comment"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 0);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 19);
BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 20);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 23);
BOOST_CHECK_EQUAL(scanner.next(), Token::SEMICOLON);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 24);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 25);
BOOST_CHECK_EQUAL(scanner.next(), Token::NUMBER);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 26);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 32);
BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 45);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 50);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(ambiguities)
{
// test scanning of some operators which need look-ahead
Scanner scanner(CharStream("<=""<""+ +=a++ =>""<<"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::LTE);
BOOST_CHECK_EQUAL(scanner.next(), Token::LT);
BOOST_CHECK_EQUAL(scanner.next(), Token::ADD);
BOOST_CHECK_EQUAL(scanner.next(), Token::ASSIGN_ADD);
BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.next(), Token::INC);
BOOST_CHECK_EQUAL(scanner.next(), Token::ARROW);
BOOST_CHECK_EQUAL(scanner.next(), Token::SHL);
}
BOOST_AUTO_TEST_CASE(documentation_comments_parsed_begin)
{
Scanner scanner(CharStream("/// Send $(value / 1000) chocolates to the user"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), " Send $(value / 1000) chocolates to the user");
}
BOOST_AUTO_TEST_CASE(documentation_comments_parsed)
{
Scanner scanner(CharStream("some other tokens /// Send $(value / 1000) chocolates to the user"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), " Send $(value / 1000) chocolates to the user");
}
BOOST_AUTO_TEST_CASE(comment_before_eos)
{
Scanner scanner(CharStream("//"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(documentation_comment_before_eos)
{
Scanner scanner(CharStream("///"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), "");
}
BOOST_AUTO_TEST_SUITE_END()
}
}
} // end namespaces
<commit_msg>extra comments scanning test<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <[email protected]>
* @date 2014
* Unit tests for the solidity scanner.
*/
#include <libsolidity/Scanner.h>
#include <boost/test/unit_test.hpp>
namespace dev
{
namespace solidity
{
namespace test
{
BOOST_AUTO_TEST_SUITE(SolidityScanner)
BOOST_AUTO_TEST_CASE(test_empty)
{
Scanner scanner(CharStream(""));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(smoke_test)
{
Scanner scanner(CharStream("function break;765 \t \"string1\",'string2'\nidentifier1"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::FUNCTION);
BOOST_CHECK_EQUAL(scanner.next(), Token::BREAK);
BOOST_CHECK_EQUAL(scanner.next(), Token::SEMICOLON);
BOOST_CHECK_EQUAL(scanner.next(), Token::NUMBER);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "765");
BOOST_CHECK_EQUAL(scanner.next(), Token::STRING_LITERAL);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "string1");
BOOST_CHECK_EQUAL(scanner.next(), Token::COMMA);
BOOST_CHECK_EQUAL(scanner.next(), Token::STRING_LITERAL);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "string2");
BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "identifier1");
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(string_escapes)
{
Scanner scanner(CharStream(" { \"a\\x61\""));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::LBRACE);
BOOST_CHECK_EQUAL(scanner.next(), Token::STRING_LITERAL);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "aa");
}
BOOST_AUTO_TEST_CASE(string_escapes_with_zero)
{
Scanner scanner(CharStream(" { \"a\\x61\\x00abc\""));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::LBRACE);
BOOST_CHECK_EQUAL(scanner.next(), Token::STRING_LITERAL);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), std::string("aa\0abc", 6));
}
BOOST_AUTO_TEST_CASE(string_escape_illegal)
{
Scanner scanner(CharStream(" bla \"\\x6rf\" (illegalescape)"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.next(), Token::ILLEGAL);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "");
// TODO recovery from illegal tokens should be improved
BOOST_CHECK_EQUAL(scanner.next(), Token::ILLEGAL);
BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.next(), Token::ILLEGAL);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(hex_numbers)
{
Scanner scanner(CharStream("var x = 0x765432536763762734623472346;"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::VAR);
BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.next(), Token::ASSIGN);
BOOST_CHECK_EQUAL(scanner.next(), Token::NUMBER);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "0x765432536763762734623472346");
BOOST_CHECK_EQUAL(scanner.next(), Token::SEMICOLON);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(negative_numbers)
{
Scanner scanner(CharStream("var x = -.2 + -0x78 + -7.3 + 8.9;"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::VAR);
BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.next(), Token::ASSIGN);
BOOST_CHECK_EQUAL(scanner.next(), Token::NUMBER);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "-.2");
BOOST_CHECK_EQUAL(scanner.next(), Token::ADD);
BOOST_CHECK_EQUAL(scanner.next(), Token::NUMBER);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "-0x78");
BOOST_CHECK_EQUAL(scanner.next(), Token::ADD);
BOOST_CHECK_EQUAL(scanner.next(), Token::NUMBER);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "-7.3");
BOOST_CHECK_EQUAL(scanner.next(), Token::ADD);
BOOST_CHECK_EQUAL(scanner.next(), Token::NUMBER);
BOOST_CHECK_EQUAL(scanner.getCurrentLiteral(), "8.9");
BOOST_CHECK_EQUAL(scanner.next(), Token::SEMICOLON);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(locations)
{
Scanner scanner(CharStream("function_identifier has ; -0x743/*comment*/\n ident //comment"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 0);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 19);
BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 20);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 23);
BOOST_CHECK_EQUAL(scanner.next(), Token::SEMICOLON);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 24);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 25);
BOOST_CHECK_EQUAL(scanner.next(), Token::NUMBER);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 26);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 32);
BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().start, 45);
BOOST_CHECK_EQUAL(scanner.getCurrentLocation().end, 50);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
}
BOOST_AUTO_TEST_CASE(ambiguities)
{
// test scanning of some operators which need look-ahead
Scanner scanner(CharStream("<=""<""+ +=a++ =>""<<"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::LTE);
BOOST_CHECK_EQUAL(scanner.next(), Token::LT);
BOOST_CHECK_EQUAL(scanner.next(), Token::ADD);
BOOST_CHECK_EQUAL(scanner.next(), Token::ASSIGN_ADD);
BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.next(), Token::INC);
BOOST_CHECK_EQUAL(scanner.next(), Token::ARROW);
BOOST_CHECK_EQUAL(scanner.next(), Token::SHL);
}
BOOST_AUTO_TEST_CASE(documentation_comments_parsed_begin)
{
Scanner scanner(CharStream("/// Send $(value / 1000) chocolates to the user"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), " Send $(value / 1000) chocolates to the user");
}
BOOST_AUTO_TEST_CASE(documentation_comments_parsed)
{
Scanner scanner(CharStream("some other tokens /// Send $(value / 1000) chocolates to the user"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.next(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.next(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), " Send $(value / 1000) chocolates to the user");
}
BOOST_AUTO_TEST_CASE(comment_before_eos)
{
Scanner scanner(CharStream("//"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), "");
}
BOOST_AUTO_TEST_CASE(documentation_comment_before_eos)
{
Scanner scanner(CharStream("///"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::EOS);
BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), "");
}
BOOST_AUTO_TEST_CASE(comments_mixed_in_sequence)
{
Scanner scanner(CharStream("hello_world ///documentation comment \n"
"//simple comment \n"
"<<"));
BOOST_CHECK_EQUAL(scanner.getCurrentToken(), Token::IDENTIFIER);
BOOST_CHECK_EQUAL(scanner.next(), Token::SHL);
BOOST_CHECK_EQUAL(scanner.getCurrentCommentLiteral(), "documentation comment ");
}
BOOST_AUTO_TEST_SUITE_END()
}
}
} // end namespaces
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "precompiled_rptxml.hxx"
#include "xmlControlProperty.hxx"
#include <xmloff/xmluconv.hxx>
#include "xmlfilter.hxx"
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmlnmspe.hxx>
#include <xmloff/nmspmap.hxx>
#include "xmlEnums.hxx"
#include <tools/debug.hxx>
#include <tools/datetime.hxx>
#include <unotools/datetime.hxx>
#include <com/sun/star/util/DateTime.hpp>
#define TYPE_DATE 1
#define TYPE_TIME 2
#define TYPE_DATETIME 3
namespace rptxml
{
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::xml::sax;
DBG_NAME( rpt_OXMLControlProperty )
OXMLControlProperty::OXMLControlProperty( ORptFilter& rImport
,sal_uInt16 nPrfx
,const ::rtl::OUString& _sLocalName
,const Reference< XAttributeList > & _xAttrList
,const Reference< XPropertySet >& _xControl
,OXMLControlProperty* _pContainer) :
SvXMLImportContext( rImport, nPrfx, _sLocalName )
,m_xControl(_xControl)
,m_pContainer(_pContainer)
,m_bIsList(sal_False)
{
DBG_CTOR( rpt_OXMLControlProperty,NULL);
m_aPropType = ::getVoidCppuType();
OSL_ENSURE(_xAttrList.is(),"Attribute list is NULL!");
OSL_ENSURE(m_xControl.is(),"Control is NULL!");
const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
const SvXMLTokenMap& rTokenMap = rImport.GetControlPropertyElemTokenMap();
const sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0;
for(sal_Int16 i = 0; i < nLength; ++i)
{
::rtl::OUString sLocalName;
const rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
const rtl::OUString sValue = _xAttrList->getValueByIndex( i );
switch( rTokenMap.Get( nPrefix, sLocalName ) )
{
case XML_TOK_LIST_PROPERTY:
m_bIsList = sValue.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("true"));
break;
case XML_TOK_VALUE_TYPE:
{
// needs to be translated into a ::com::sun::star::uno::Type
DECLARE_STL_USTRINGACCESS_MAP( ::com::sun::star::uno::Type, MapString2Type );
static MapString2Type s_aTypeNameMap;
if (!s_aTypeNameMap.size())
{
s_aTypeNameMap[GetXMLToken( XML_BOOLEAN)] = ::getBooleanCppuType();
s_aTypeNameMap[GetXMLToken( XML_FLOAT)] = ::getCppuType( static_cast< double* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_DOUBLE)] = ::getCppuType( static_cast< double* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_STRING)] = ::getCppuType( static_cast< ::rtl::OUString* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_INT)] = ::getCppuType( static_cast< sal_Int32* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_SHORT)] = ::getCppuType( static_cast< sal_Int16* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_DATE)] = ::getCppuType( static_cast< com::sun::star::util::Date* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_TIME)] = ::getCppuType( static_cast< com::sun::star::util::Time* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_VOID)] = ::getVoidCppuType();
}
const ConstMapString2TypeIterator aTypePos = s_aTypeNameMap.find(sValue);
OSL_ENSURE(s_aTypeNameMap.end() != aTypePos, "OXMLControlProperty::OXMLControlProperty: invalid type!");
if (s_aTypeNameMap.end() != aTypePos)
m_aPropType = aTypePos->second;
}
break;
case XML_TOK_PROPERTY_NAME:
m_aSetting.Name = sValue;
break;
default:
break;
}
}
}
// -----------------------------------------------------------------------------
OXMLControlProperty::~OXMLControlProperty()
{
DBG_DTOR( rpt_OXMLControlProperty,NULL);
}
// -----------------------------------------------------------------------------
SvXMLImportContext* OXMLControlProperty::CreateChildContext(
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const Reference< XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
ORptFilter& rImport = GetOwnImport();
const SvXMLTokenMap& rTokenMap = rImport.GetControlPropertyElemTokenMap();
switch( rTokenMap.Get( nPrefix, rLocalName ) )
{
case XML_TOK_LIST_PROPERTY:
rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
pContext = new OXMLControlProperty( rImport, nPrefix, rLocalName,xAttrList,m_xControl);
break;
case XML_TOK_VALUE:
rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
pContext = new OXMLControlProperty( rImport, nPrefix, rLocalName,xAttrList,m_xControl,this );
break;
default:
break;
}
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
return pContext;
}
// -----------------------------------------------------------------------------
void OXMLControlProperty::EndElement()
{
if ( m_aSetting.Name.getLength() && m_xControl.is() )
{
if ( m_bIsList && !m_aSequence.getLength() )
m_aSetting.Value <<= m_aSequence;
try
{
m_xControl->setPropertyValue(m_aSetting.Name,m_aSetting.Value);
}
catch(const Exception&)
{
OSL_FAIL("Unknown property found!");
}
}
}
// -----------------------------------------------------------------------------
void OXMLControlProperty::Characters( const ::rtl::OUString& rChars )
{
if ( m_pContainer )
m_pContainer->addValue(rChars);
}
// -----------------------------------------------------------------------------
void OXMLControlProperty::addValue(const ::rtl::OUString& _sValue)
{
Any aValue;
if( TypeClass_VOID != m_aPropType.getTypeClass() )
aValue = convertString(m_aPropType, _sValue);
if ( !m_bIsList )
m_aSetting.Value = aValue;
else
{
sal_Int32 nPos = m_aSequence.getLength();
m_aSequence.realloc(nPos+1);
m_aSequence[nPos] = aValue;
}
}
// -----------------------------------------------------------------------------
ORptFilter& OXMLControlProperty::GetOwnImport()
{
return static_cast<ORptFilter&>(GetImport());
}
// -----------------------------------------------------------------------------
Any OXMLControlProperty::convertString(const ::com::sun::star::uno::Type& _rExpectedType, const ::rtl::OUString& _rReadCharacters)
{
ORptFilter& rImporter = GetOwnImport();
Any aReturn;
switch (_rExpectedType.getTypeClass())
{
case TypeClass_BOOLEAN: // sal_Bool
{
bool bValue;
#if OSL_DEBUG_LEVEL > 0
sal_Bool bSuccess =
#endif
rImporter.GetMM100UnitConverter().convertBool(bValue, _rReadCharacters);
OSL_ENSURE(bSuccess,
::rtl::OString("OXMLControlProperty::convertString: could not convert \"")
+= ::rtl::OString(_rReadCharacters.getStr(), _rReadCharacters.getLength(), RTL_TEXTENCODING_ASCII_US)
+= ::rtl::OString("\" into a boolean!"));
aReturn <<= bValue;
}
break;
case TypeClass_SHORT: // sal_Int16
case TypeClass_LONG: // sal_Int32
{ // it's a real int32/16 property
sal_Int32 nValue(0);
#if OSL_DEBUG_LEVEL > 0
sal_Bool bSuccess =
#endif
rImporter.GetMM100UnitConverter().convertNumber(nValue, _rReadCharacters);
OSL_ENSURE(bSuccess,
::rtl::OString("OXMLControlProperty::convertString: could not convert \"")
+= ::rtl::OString(_rReadCharacters.getStr(), _rReadCharacters.getLength(), RTL_TEXTENCODING_ASCII_US)
+= ::rtl::OString("\" into an integer!"));
if (TypeClass_SHORT == _rExpectedType.getTypeClass())
aReturn <<= (sal_Int16)nValue;
else
aReturn <<= (sal_Int32)nValue;
break;
}
case TypeClass_HYPER:
{
OSL_FAIL("OXMLControlProperty::convertString: 64-bit integers not implemented yet!");
}
break;
case TypeClass_DOUBLE:
{
double nValue = 0.0;
#if OSL_DEBUG_LEVEL > 0
sal_Bool bSuccess =
#endif
rImporter.GetMM100UnitConverter().convertDouble(nValue, _rReadCharacters);
OSL_ENSURE(bSuccess,
::rtl::OString("OXMLControlProperty::convertString: could not convert \"")
+= ::rtl::OString(_rReadCharacters.getStr(), _rReadCharacters.getLength(), RTL_TEXTENCODING_ASCII_US)
+= ::rtl::OString("\" into a double!"));
aReturn <<= (double)nValue;
}
break;
case TypeClass_STRING:
aReturn <<= _rReadCharacters;
break;
case TypeClass_STRUCT:
{
// recognized structs:
static ::com::sun::star::uno::Type s_aDateType = ::getCppuType(static_cast< ::com::sun::star::util::Date* >(NULL));
static ::com::sun::star::uno::Type s_aTimeType = ::getCppuType(static_cast< ::com::sun::star::util::Time* >(NULL));
static ::com::sun::star::uno::Type s_aDateTimeType = ::getCppuType(static_cast< ::com::sun::star::util::DateTime* >(NULL));
sal_Int32 nType = 0;
if ( _rExpectedType.equals(s_aDateType) )
nType = TYPE_DATE;
else if ( _rExpectedType.equals(s_aTimeType) )
nType = TYPE_TIME;
else if ( _rExpectedType.equals(s_aDateTimeType) )
nType = TYPE_DATETIME;
if ( !nType )
{
// first extract the double
double nValue = 0;
#if OSL_DEBUG_LEVEL > 0
sal_Bool bSuccess =
#endif
rImporter.GetMM100UnitConverter().convertDouble(nValue, _rReadCharacters);
OSL_ENSURE(bSuccess,
::rtl::OString("OPropertyImport::convertString: could not convert \"")
+= ::rtl::OString(_rReadCharacters.getStr(), _rReadCharacters.getLength(), RTL_TEXTENCODING_ASCII_US)
+= ::rtl::OString("\" into a double!"));
// then convert it into the target type
switch (nType)
{
case TYPE_DATE:
{
OSL_ENSURE(((sal_uInt32)nValue) - nValue == 0,
"OPropertyImport::convertString: a Date value with a fractional part?");
aReturn <<= implGetDate(nValue);
}
break;
case TYPE_TIME:
{
OSL_ENSURE(((sal_uInt32)nValue) == 0,
"OPropertyImport::convertString: a Time value with more than a fractional part?");
aReturn <<= implGetTime(nValue);
}
break;
case TYPE_DATETIME:
{
::com::sun::star::util::Time aTime = implGetTime(nValue);
::com::sun::star::util::Date aDate = implGetDate(nValue);
::com::sun::star::util::DateTime aDateTime;
aDateTime.HundredthSeconds = aTime.HundredthSeconds;
aDateTime.Seconds = aTime.Seconds;
aDateTime.Minutes = aTime.Minutes;
aDateTime.Hours = aTime.Hours;
aDateTime.Day = aDate.Day;
aDateTime.Month = aDate.Month;
aDateTime.Year = aDate.Year;
aReturn <<= aDateTime;
}
break;
default:
break;
}
}
else
OSL_FAIL("OPropertyImport::convertString: unsupported property type!");
}
break;
default:
OSL_FAIL("OXMLControlProperty::convertString: invalid type class!");
}
return aReturn;
}
//---------------------------------------------------------------------
::com::sun::star::util::Time OXMLControlProperty::implGetTime(double _nValue)
{
::com::sun::star::util::Time aTime;
sal_uInt32 nIntValue = sal_Int32(_nValue * 8640000);
nIntValue *= 8640000;
aTime.HundredthSeconds = (sal_uInt16)( nIntValue % 100 );
nIntValue /= 100;
aTime.Seconds = (sal_uInt16)( nIntValue % 60 );
nIntValue /= 60;
aTime.Minutes = (sal_uInt16)( nIntValue % 60 );
nIntValue /= 60;
OSL_ENSURE(nIntValue < 24, "OPropertyImport::implGetTime: more than a day?");
aTime.Hours = static_cast< sal_uInt16 >( nIntValue );
return aTime;
}
//---------------------------------------------------------------------
::com::sun::star::util::Date OXMLControlProperty::implGetDate(double _nValue)
{
Date aToolsDate((sal_uInt32)_nValue);
::com::sun::star::util::Date aDate;
::utl::typeConvert(aToolsDate, aDate);
return aDate;
}
//----------------------------------------------------------------------------
} // namespace rptxml
// -----------------------------------------------------------------------------
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fix build<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "precompiled_rptxml.hxx"
#include "xmlControlProperty.hxx"
#include <xmloff/xmluconv.hxx>
#include "xmlfilter.hxx"
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmlnmspe.hxx>
#include <xmloff/nmspmap.hxx>
#include "xmlEnums.hxx"
#include <tools/debug.hxx>
#include <tools/datetime.hxx>
#include <unotools/datetime.hxx>
#include <com/sun/star/util/DateTime.hpp>
#define TYPE_DATE 1
#define TYPE_TIME 2
#define TYPE_DATETIME 3
namespace rptxml
{
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::xml::sax;
DBG_NAME( rpt_OXMLControlProperty )
OXMLControlProperty::OXMLControlProperty( ORptFilter& rImport
,sal_uInt16 nPrfx
,const ::rtl::OUString& _sLocalName
,const Reference< XAttributeList > & _xAttrList
,const Reference< XPropertySet >& _xControl
,OXMLControlProperty* _pContainer) :
SvXMLImportContext( rImport, nPrfx, _sLocalName )
,m_xControl(_xControl)
,m_pContainer(_pContainer)
,m_bIsList(sal_False)
{
DBG_CTOR( rpt_OXMLControlProperty,NULL);
m_aPropType = ::getVoidCppuType();
OSL_ENSURE(_xAttrList.is(),"Attribute list is NULL!");
OSL_ENSURE(m_xControl.is(),"Control is NULL!");
const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
const SvXMLTokenMap& rTokenMap = rImport.GetControlPropertyElemTokenMap();
const sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0;
for(sal_Int16 i = 0; i < nLength; ++i)
{
::rtl::OUString sLocalName;
const rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
const rtl::OUString sValue = _xAttrList->getValueByIndex( i );
switch( rTokenMap.Get( nPrefix, sLocalName ) )
{
case XML_TOK_LIST_PROPERTY:
m_bIsList = sValue.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("true"));
break;
case XML_TOK_VALUE_TYPE:
{
// needs to be translated into a ::com::sun::star::uno::Type
DECLARE_STL_USTRINGACCESS_MAP( ::com::sun::star::uno::Type, MapString2Type );
static MapString2Type s_aTypeNameMap;
if (!s_aTypeNameMap.size())
{
s_aTypeNameMap[GetXMLToken( XML_BOOLEAN)] = ::getBooleanCppuType();
s_aTypeNameMap[GetXMLToken( XML_FLOAT)] = ::getCppuType( static_cast< double* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_DOUBLE)] = ::getCppuType( static_cast< double* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_STRING)] = ::getCppuType( static_cast< ::rtl::OUString* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_INT)] = ::getCppuType( static_cast< sal_Int32* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_SHORT)] = ::getCppuType( static_cast< sal_Int16* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_DATE)] = ::getCppuType( static_cast< com::sun::star::util::Date* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_TIME)] = ::getCppuType( static_cast< com::sun::star::util::Time* >(NULL) );
s_aTypeNameMap[GetXMLToken( XML_VOID)] = ::getVoidCppuType();
}
const ConstMapString2TypeIterator aTypePos = s_aTypeNameMap.find(sValue);
OSL_ENSURE(s_aTypeNameMap.end() != aTypePos, "OXMLControlProperty::OXMLControlProperty: invalid type!");
if (s_aTypeNameMap.end() != aTypePos)
m_aPropType = aTypePos->second;
}
break;
case XML_TOK_PROPERTY_NAME:
m_aSetting.Name = sValue;
break;
default:
break;
}
}
}
// -----------------------------------------------------------------------------
OXMLControlProperty::~OXMLControlProperty()
{
DBG_DTOR( rpt_OXMLControlProperty,NULL);
}
// -----------------------------------------------------------------------------
SvXMLImportContext* OXMLControlProperty::CreateChildContext(
sal_uInt16 nPrefix,
const ::rtl::OUString& rLocalName,
const Reference< XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
ORptFilter& rImport = GetOwnImport();
const SvXMLTokenMap& rTokenMap = rImport.GetControlPropertyElemTokenMap();
switch( rTokenMap.Get( nPrefix, rLocalName ) )
{
case XML_TOK_LIST_PROPERTY:
rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
pContext = new OXMLControlProperty( rImport, nPrefix, rLocalName,xAttrList,m_xControl);
break;
case XML_TOK_VALUE:
rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
pContext = new OXMLControlProperty( rImport, nPrefix, rLocalName,xAttrList,m_xControl,this );
break;
default:
break;
}
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
return pContext;
}
// -----------------------------------------------------------------------------
void OXMLControlProperty::EndElement()
{
if ( m_aSetting.Name.getLength() && m_xControl.is() )
{
if ( m_bIsList && !m_aSequence.getLength() )
m_aSetting.Value <<= m_aSequence;
try
{
m_xControl->setPropertyValue(m_aSetting.Name,m_aSetting.Value);
}
catch(const Exception&)
{
OSL_FAIL("Unknown property found!");
}
}
}
// -----------------------------------------------------------------------------
void OXMLControlProperty::Characters( const ::rtl::OUString& rChars )
{
if ( m_pContainer )
m_pContainer->addValue(rChars);
}
// -----------------------------------------------------------------------------
void OXMLControlProperty::addValue(const ::rtl::OUString& _sValue)
{
Any aValue;
if( TypeClass_VOID != m_aPropType.getTypeClass() )
aValue = convertString(m_aPropType, _sValue);
if ( !m_bIsList )
m_aSetting.Value = aValue;
else
{
sal_Int32 nPos = m_aSequence.getLength();
m_aSequence.realloc(nPos+1);
m_aSequence[nPos] = aValue;
}
}
// -----------------------------------------------------------------------------
ORptFilter& OXMLControlProperty::GetOwnImport()
{
return static_cast<ORptFilter&>(GetImport());
}
// -----------------------------------------------------------------------------
Any OXMLControlProperty::convertString(const ::com::sun::star::uno::Type& _rExpectedType, const ::rtl::OUString& _rReadCharacters)
{
ORptFilter& rImporter = GetOwnImport();
Any aReturn;
switch (_rExpectedType.getTypeClass())
{
case TypeClass_BOOLEAN: // sal_Bool
{
bool bValue;
#if OSL_DEBUG_LEVEL > 0
sal_Bool bSuccess =
#endif
rImporter.GetMM100UnitConverter().convertBool(bValue, _rReadCharacters);
OSL_ENSURE(bSuccess,
::rtl::OStringBuffer("OXMLControlProperty::convertString: could not convert \"").
append(::rtl::OUStringToOString(_rReadCharacters, RTL_TEXTENCODING_ASCII_US)).
append("\" into a boolean!").getStr());
aReturn <<= bValue;
}
break;
case TypeClass_SHORT: // sal_Int16
case TypeClass_LONG: // sal_Int32
{ // it's a real int32/16 property
sal_Int32 nValue(0);
#if OSL_DEBUG_LEVEL > 0
sal_Bool bSuccess =
#endif
rImporter.GetMM100UnitConverter().convertNumber(nValue, _rReadCharacters);
OSL_ENSURE(bSuccess,
::rtl::OStringBuffer("OXMLControlProperty::convertString: could not convert \"").
append(rtl::OUStringToOString(_rReadCharacters, RTL_TEXTENCODING_ASCII_US)).
append("\" into an integer!").getStr());
if (TypeClass_SHORT == _rExpectedType.getTypeClass())
aReturn <<= (sal_Int16)nValue;
else
aReturn <<= (sal_Int32)nValue;
break;
}
case TypeClass_HYPER:
{
OSL_FAIL("OXMLControlProperty::convertString: 64-bit integers not implemented yet!");
}
break;
case TypeClass_DOUBLE:
{
double nValue = 0.0;
#if OSL_DEBUG_LEVEL > 0
sal_Bool bSuccess =
#endif
rImporter.GetMM100UnitConverter().convertDouble(nValue, _rReadCharacters);
OSL_ENSURE(bSuccess,
::rtl::OStringBuffer("OXMLControlProperty::convertString: could not convert \"").
append(::rtl::OUStringToOString(_rReadCharacters, RTL_TEXTENCODING_ASCII_US)).
append("\" into a double!").getStr());
aReturn <<= (double)nValue;
}
break;
case TypeClass_STRING:
aReturn <<= _rReadCharacters;
break;
case TypeClass_STRUCT:
{
// recognized structs:
static ::com::sun::star::uno::Type s_aDateType = ::getCppuType(static_cast< ::com::sun::star::util::Date* >(NULL));
static ::com::sun::star::uno::Type s_aTimeType = ::getCppuType(static_cast< ::com::sun::star::util::Time* >(NULL));
static ::com::sun::star::uno::Type s_aDateTimeType = ::getCppuType(static_cast< ::com::sun::star::util::DateTime* >(NULL));
sal_Int32 nType = 0;
if ( _rExpectedType.equals(s_aDateType) )
nType = TYPE_DATE;
else if ( _rExpectedType.equals(s_aTimeType) )
nType = TYPE_TIME;
else if ( _rExpectedType.equals(s_aDateTimeType) )
nType = TYPE_DATETIME;
if ( !nType )
{
// first extract the double
double nValue = 0;
#if OSL_DEBUG_LEVEL > 0
sal_Bool bSuccess =
#endif
rImporter.GetMM100UnitConverter().convertDouble(nValue, _rReadCharacters);
OSL_ENSURE(bSuccess,
::rtl::OStringBuffer("OPropertyImport::convertString: could not convert \"").
append(rtl::OUStringToOString(_rReadCharacters, RTL_TEXTENCODING_ASCII_US)).
append("\" into a double!").getStr());
// then convert it into the target type
switch (nType)
{
case TYPE_DATE:
{
OSL_ENSURE(((sal_uInt32)nValue) - nValue == 0,
"OPropertyImport::convertString: a Date value with a fractional part?");
aReturn <<= implGetDate(nValue);
}
break;
case TYPE_TIME:
{
OSL_ENSURE(((sal_uInt32)nValue) == 0,
"OPropertyImport::convertString: a Time value with more than a fractional part?");
aReturn <<= implGetTime(nValue);
}
break;
case TYPE_DATETIME:
{
::com::sun::star::util::Time aTime = implGetTime(nValue);
::com::sun::star::util::Date aDate = implGetDate(nValue);
::com::sun::star::util::DateTime aDateTime;
aDateTime.HundredthSeconds = aTime.HundredthSeconds;
aDateTime.Seconds = aTime.Seconds;
aDateTime.Minutes = aTime.Minutes;
aDateTime.Hours = aTime.Hours;
aDateTime.Day = aDate.Day;
aDateTime.Month = aDate.Month;
aDateTime.Year = aDate.Year;
aReturn <<= aDateTime;
}
break;
default:
break;
}
}
else
OSL_FAIL("OPropertyImport::convertString: unsupported property type!");
}
break;
default:
OSL_FAIL("OXMLControlProperty::convertString: invalid type class!");
}
return aReturn;
}
//---------------------------------------------------------------------
::com::sun::star::util::Time OXMLControlProperty::implGetTime(double _nValue)
{
::com::sun::star::util::Time aTime;
sal_uInt32 nIntValue = sal_Int32(_nValue * 8640000);
nIntValue *= 8640000;
aTime.HundredthSeconds = (sal_uInt16)( nIntValue % 100 );
nIntValue /= 100;
aTime.Seconds = (sal_uInt16)( nIntValue % 60 );
nIntValue /= 60;
aTime.Minutes = (sal_uInt16)( nIntValue % 60 );
nIntValue /= 60;
OSL_ENSURE(nIntValue < 24, "OPropertyImport::implGetTime: more than a day?");
aTime.Hours = static_cast< sal_uInt16 >( nIntValue );
return aTime;
}
//---------------------------------------------------------------------
::com::sun::star::util::Date OXMLControlProperty::implGetDate(double _nValue)
{
Date aToolsDate((sal_uInt32)_nValue);
::com::sun::star::util::Date aDate;
::utl::typeConvert(aToolsDate, aDate);
return aDate;
}
//----------------------------------------------------------------------------
} // namespace rptxml
// -----------------------------------------------------------------------------
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*
Copyright 2005-2007 Adobe Systems Incorporated
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://stlab.adobe.com/licenses.html)
*/
/****************************************************************************************************/
#define ADOBE_DLL_SAFE 0
// button.hpp needs to come before widget_factory to hook the overrides
#include <GG/adobe/future/widgets/headers/platform_button.hpp>
#include <GG/adobe/functional.hpp>
#include <GG/adobe/future/widgets/headers/button_helper.hpp>
#include <GG/adobe/future/widgets/headers/button_factory.hpp>
#include <GG/adobe/future/widgets/headers/widget_factory.hpp>
#include <GG/adobe/future/widgets/headers/widget_factory_registry.hpp>
#include <GG/ClrConstants.h>
/****************************************************************************************************/
namespace {
/****************************************************************************************************/
struct button_item_t
{
button_item_t() : modifier_set_m(adobe::modifiers_none_s)
{ }
button_item_t(const button_item_t& default_item, const adobe::dictionary_t& parameters) :
name_m(default_item.name_m),
alt_text_m(default_item.alt_text_m),
bind_m(default_item.bind_m),
bind_output_m(default_item.bind_output_m),
action_m(default_item.action_m),
bind_signal_m(default_item.bind_signal_m),
expression_m(default_item.expression_m),
value_m(default_item.value_m),
contributing_m(default_item.contributing_m),
modifier_set_m(default_item.modifier_set_m),
signal_id_m(default_item.signal_id_m)
{
get_value(parameters, adobe::key_name, name_m);
get_value(parameters, adobe::key_alt_text, alt_text_m);
get_value(parameters, adobe::key_bind, bind_m);
get_value(parameters, adobe::key_bind_output, bind_output_m);
get_value(parameters, adobe::key_action, action_m);
get_value(parameters, adobe::key_value, value_m);
get_value(parameters, adobe::static_name_t("signal_id"), signal_id_m);
// modifers can be a name or array
/*
REVISIT (sparent) : Old way was with a single modifers key word with multiple
modifers encoded in a single name - new way with a name or array under the
new keyword modifier_set.
*/
adobe::dictionary_t::const_iterator iter(parameters.find(adobe::key_modifiers));
if (iter == parameters.end())
iter = parameters.find(adobe::key_modifier_set);
if (iter != parameters.end())
modifier_set_m |= adobe::value_to_modifier(iter->second);
adobe::any_regular_t clicked_binding;
if (get_value(parameters, adobe::static_name_t("bind_clicked_signal"), clicked_binding)) {
adobe::implementation::cell_and_expression(clicked_binding, bind_signal_m, expression_m);
}
if (!action_m)
action_m = signal_id_m;
if (!signal_id_m)
signal_id_m = action_m;
}
std::string name_m;
std::string alt_text_m;
adobe::name_t bind_m;
adobe::name_t bind_output_m;
adobe::name_t action_m;
adobe::name_t bind_signal_m;
adobe::array_t expression_m;
adobe::any_regular_t value_m;
adobe::dictionary_t contributing_m;
adobe::modifiers_t modifier_set_m;
adobe::name_t signal_id_m;
};
/*************************************************************************************************/
void proxy_button_hit(adobe::button_notifier_t button_notifier,
adobe::sheet_t& sheet,
adobe::name_t bind,
adobe::name_t bind_output,
adobe::name_t action,
const adobe::any_regular_t& value,
const adobe::dictionary_t& contributing)
{
if (bind_output) {
//touch(); // REVISIT (sparent) : We should have per item touch!
sheet.set(bind_output, value);
sheet.update();
} else if (button_notifier) {
if (bind) {
adobe::dictionary_t result;
result.insert(std::make_pair(adobe::key_value, value));
result.insert(std::make_pair(adobe::key_contributing, adobe::any_regular_t(contributing)));
button_notifier(action, adobe::any_regular_t(result));
} else {
button_notifier(action, value);
}
}
}
/****************************************************************************************************/
void handle_clicked_signal(adobe::signal_notifier_t signal_notifier,
adobe::name_t widget_id,
adobe::sheet_t& sheet,
adobe::name_t bind,
adobe::array_t expression,
const adobe::any_regular_t& value)
{
adobe::implementation::handle_signal(signal_notifier,
adobe::static_name_t("button"),
adobe::static_name_t("clicked"),
widget_id,
sheet,
bind,
expression,
value);
}
/*************************************************************************************************/
template <typename Cont>
void state_set_push_back(Cont& state_set, const adobe::factory_token_t& token, const button_item_t& temp)
{
state_set.push_back(adobe::button_state_descriptor_t());
state_set.back().name_m = temp.name_m;
state_set.back().alt_text_m = temp.alt_text_m;
state_set.back().modifier_set_m = temp.modifier_set_m;
state_set.back().hit_proc_m = boost::bind(&proxy_button_hit, token.button_notifier_m,
boost::ref(token.sheet_m), temp.bind_m,
temp.bind_output_m,
temp.action_m, _1, _2);
if (temp.bind_signal_m) {
state_set.back().clicked_proc_m = boost::bind(&handle_clicked_signal,
token.signal_notifier_m,
temp.signal_id_m,
boost::ref(token.sheet_m),
temp.bind_signal_m,
temp.expression_m,
_1);
}
state_set.back().value_m = temp.value_m;
state_set.back().contributing_m = temp.contributing_m;
}
/****************************************************************************************************/
void connect_button_state(adobe::button_t& control,
adobe::assemblage_t& assemblage,
adobe::sheet_t& sheet,
const button_item_t& temp,
adobe::eve_client_holder& /*client_holder*/)
{
if (!temp.bind_m)
return;
/*
REVISIT (sparent) : Don't currently propogate modifier mask past this point.
Not yet wired up.
*/
adobe::display_compositor_t<adobe::button_t, adobe::modifiers_t>*
current_display(adobe::make_display_compositor(control, temp.modifier_set_m));
assemblage.cleanup(boost::bind(adobe::delete_ptr<adobe::display_compositor_t<adobe::button_t, adobe::modifiers_t>*>(), current_display));
assemblage.cleanup(boost::bind(&boost::signals::connection::disconnect,
sheet.monitor_invariant_dependent(
temp.bind_m, boost::bind(&adobe::button_t::enable,
boost::ref(control), _1))));
adobe::attach_view(assemblage, temp.bind_m, *current_display, sheet);
/*
REVISIT (sparent) : Filtering the contributing code here isn't necessarily the right thing -
I think monitor_contributing should remove the filter functionality if possible. For
now I'm passing in an empty dictionary for no filtering.
*/
assemblage.cleanup(boost::bind(&boost::signals::connection::disconnect,
sheet.monitor_contributing(temp.bind_m, adobe::dictionary_t(),
boost::bind(&adobe::button_t::set_contributing,
boost::ref(control),
temp.modifier_set_m, _1))));
}
/****************************************************************************************************/
} // namespace
/****************************************************************************************************/
namespace adobe {
/****************************************************************************************************/
namespace implementation {
/****************************************************************************************************/
button_t* create_button_widget(const dictionary_t& parameters,
const factory_token_t& token,
size_enum_t size)
{
bool is_cancel(false);
bool is_default(false);
modifiers_t modifier_mask(modifiers_none_s);
array_t items;
button_item_t item;
button_state_set_t state_set;
GG::Clr color(GG::CLR_GRAY);
GG::Clr text_color(GG::CLR_BLACK);
dictionary_t image;
get_value(parameters, key_name, item.name_m);
get_value(parameters, key_alt_text, item.alt_text_m);
get_value(parameters, key_bind, item.bind_m);
get_value(parameters, key_bind_output, item.bind_output_m);
get_value(parameters, key_action, item.action_m);
get_value(parameters, key_value, item.value_m);
get_value(parameters, adobe::static_name_t("signal_id"), item.signal_id_m);
get_value(parameters, key_items, items);
get_value(parameters, key_default, is_default);
get_value(parameters, key_cancel, is_cancel);
get_color(parameters, static_name_t("color"), color);
get_color(parameters, static_name_t("text_color"), text_color);
get_value(parameters, key_image, image);
GG::SubTexture unpressed;
GG::SubTexture pressed;
GG::SubTexture rollover;
get_subtexture(image, static_name_t("unpressed"), unpressed);
get_subtexture(image, static_name_t("pressed"), pressed);
get_subtexture(image, static_name_t("rollover"), rollover);
adobe::any_regular_t clicked_binding;
if (get_value(parameters, adobe::static_name_t("bind_clicked_signal"), clicked_binding)) {
adobe::implementation::cell_and_expression(clicked_binding, item.bind_signal_m, item.expression_m);
}
for (array_t::const_iterator iter(items.begin()), last(items.end()); iter != last; ++iter)
state_set_push_back(state_set, token, button_item_t(item, iter->cast<dictionary_t>()));
bool state_set_originally_empty(state_set.empty());
if (state_set_originally_empty)
state_set_push_back(state_set, token, item);
for (button_state_set_t::const_iterator first(state_set.begin()), last(state_set.end()); first != last; ++first)
modifier_mask |= first->modifier_set_m;
button_state_descriptor_t* first_state(state_set.empty() ? 0 : &state_set[0]);
std::size_t n(state_set.size());
button_t* result = new button_t(is_default,
is_cancel,
modifier_mask,
color,
text_color,
unpressed,
pressed,
rollover,
first_state,
first_state + n);
for (array_t::const_iterator iter(items.begin()), last(items.end()); iter != last; ++iter) {
button_item_t temp(item, iter->cast<dictionary_t>());
connect_button_state(*result,
token.client_holder_m.assemblage_m,
token.sheet_m,
temp,
token.client_holder_m);
}
if (state_set_originally_empty) {
connect_button_state(*result,
token.client_holder_m.assemblage_m,
token.sheet_m,
item,
token.client_holder_m);
}
return result;
}
/****************************************************************************************************/
} // namespace implementation
/****************************************************************************************************/
widget_node_t make_button(const dictionary_t& parameters,
const widget_node_t& parent,
const factory_token_t& token,
const widget_factory_t& factory)
{
size_enum_t size(parameters.count(key_size) ?
implementation::enumerate_size(get_value(parameters, key_size).cast<name_t>()) :
parent.size_m);
button_t* widget = implementation::create_button_widget(parameters, token, size);
token.client_holder_m.assemblage_m.cleanup(boost::bind(delete_ptr<button_t*>(),widget));
//
// Call display_insertion to embed the new widget within the view heirarchy
//
platform_display_type display_token(insert(get_main_display(), parent.display_token_m, *widget));
// set up key handler code. We do this all the time because we want the button to be updated
// when modifier keys are pressed during execution of the dialog.
keyboard_t::iterator keyboard_token(
token.client_holder_m.keyboard_m.insert(parent.keyboard_token_m, poly_key_handler_t(boost::ref(*widget))));
//
// As per SF.net bug 1428833, we want to attach the poly_placeable_t
// to Eve before we attach the controller and view to the model
//
eve_t::iterator eve_token;
eve_token = attach_placeable<poly_placeable_t>(parent.eve_token_m, *widget, parameters,
token, factory.is_container(static_name_t("button")),
factory.layout_attributes(static_name_t("button")));
//
// Return the widget_node_t that comprises the tokens created for this widget by the various components
//
return widget_node_t(size, eve_token, display_token, keyboard_token);
}
/****************************************************************************************************/
} // namespace adobe
/****************************************************************************************************/
<commit_msg>Fixed an error in the signal binding code in button_factory.cpp.<commit_after>/*
Copyright 2005-2007 Adobe Systems Incorporated
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://stlab.adobe.com/licenses.html)
*/
/****************************************************************************************************/
#define ADOBE_DLL_SAFE 0
// button.hpp needs to come before widget_factory to hook the overrides
#include <GG/adobe/future/widgets/headers/platform_button.hpp>
#include <GG/adobe/functional.hpp>
#include <GG/adobe/future/widgets/headers/button_helper.hpp>
#include <GG/adobe/future/widgets/headers/button_factory.hpp>
#include <GG/adobe/future/widgets/headers/widget_factory.hpp>
#include <GG/adobe/future/widgets/headers/widget_factory_registry.hpp>
#include <GG/ClrConstants.h>
/****************************************************************************************************/
namespace {
/****************************************************************************************************/
struct button_item_t
{
button_item_t() : modifier_set_m(adobe::modifiers_none_s)
{ }
button_item_t(const button_item_t& default_item, const adobe::dictionary_t& parameters) :
name_m(default_item.name_m),
alt_text_m(default_item.alt_text_m),
bind_m(default_item.bind_m),
bind_output_m(default_item.bind_output_m),
action_m(default_item.action_m),
bind_signal_m(default_item.bind_signal_m),
expression_m(default_item.expression_m),
value_m(default_item.value_m),
contributing_m(default_item.contributing_m),
modifier_set_m(default_item.modifier_set_m),
signal_id_m(default_item.signal_id_m)
{
get_value(parameters, adobe::key_name, name_m);
get_value(parameters, adobe::key_alt_text, alt_text_m);
get_value(parameters, adobe::key_bind, bind_m);
get_value(parameters, adobe::key_bind_output, bind_output_m);
get_value(parameters, adobe::key_action, action_m);
get_value(parameters, adobe::key_value, value_m);
get_value(parameters, adobe::static_name_t("signal_id"), signal_id_m);
// modifers can be a name or array
/*
REVISIT (sparent) : Old way was with a single modifers key word with multiple
modifers encoded in a single name - new way with a name or array under the
new keyword modifier_set.
*/
adobe::dictionary_t::const_iterator iter(parameters.find(adobe::key_modifiers));
if (iter == parameters.end())
iter = parameters.find(adobe::key_modifier_set);
if (iter != parameters.end())
modifier_set_m |= adobe::value_to_modifier(iter->second);
adobe::any_regular_t clicked_binding;
if (get_value(parameters, adobe::static_name_t("bind_clicked_signal"), clicked_binding)) {
adobe::implementation::cell_and_expression(clicked_binding, bind_signal_m, expression_m);
}
if (!action_m)
action_m = signal_id_m;
if (!signal_id_m)
signal_id_m = action_m;
}
std::string name_m;
std::string alt_text_m;
adobe::name_t bind_m;
adobe::name_t bind_output_m;
adobe::name_t action_m;
adobe::name_t bind_signal_m;
adobe::array_t expression_m;
adobe::any_regular_t value_m;
adobe::dictionary_t contributing_m;
adobe::modifiers_t modifier_set_m;
adobe::name_t signal_id_m;
};
/*************************************************************************************************/
void proxy_button_hit(adobe::button_notifier_t button_notifier,
adobe::sheet_t& sheet,
adobe::name_t bind,
adobe::name_t bind_output,
adobe::name_t action,
const adobe::any_regular_t& value,
const adobe::dictionary_t& contributing)
{
if (bind_output) {
//touch(); // REVISIT (sparent) : We should have per item touch!
sheet.set(bind_output, value);
sheet.update();
} else if (button_notifier) {
if (bind) {
adobe::dictionary_t result;
result.insert(std::make_pair(adobe::key_value, value));
result.insert(std::make_pair(adobe::key_contributing, adobe::any_regular_t(contributing)));
button_notifier(action, adobe::any_regular_t(result));
} else {
button_notifier(action, value);
}
}
}
/****************************************************************************************************/
void handle_clicked_signal(adobe::signal_notifier_t signal_notifier,
adobe::name_t widget_id,
adobe::sheet_t& sheet,
adobe::name_t bind,
adobe::array_t expression,
const adobe::any_regular_t& value)
{
adobe::implementation::handle_signal(signal_notifier,
adobe::static_name_t("button"),
adobe::static_name_t("clicked"),
widget_id,
sheet,
bind,
expression,
value);
}
/*************************************************************************************************/
template <typename Cont>
void state_set_push_back(Cont& state_set, const adobe::factory_token_t& token, const button_item_t& temp)
{
state_set.push_back(adobe::button_state_descriptor_t());
state_set.back().name_m = temp.name_m;
state_set.back().alt_text_m = temp.alt_text_m;
state_set.back().modifier_set_m = temp.modifier_set_m;
state_set.back().hit_proc_m = boost::bind(&proxy_button_hit, token.button_notifier_m,
boost::ref(token.sheet_m), temp.bind_m,
temp.bind_output_m,
temp.action_m, _1, _2);
state_set.back().clicked_proc_m = boost::bind(&handle_clicked_signal,
token.signal_notifier_m,
temp.signal_id_m,
boost::ref(token.sheet_m),
temp.bind_signal_m,
temp.expression_m,
_1);
state_set.back().value_m = temp.value_m;
state_set.back().contributing_m = temp.contributing_m;
}
/****************************************************************************************************/
void connect_button_state(adobe::button_t& control,
adobe::assemblage_t& assemblage,
adobe::sheet_t& sheet,
const button_item_t& temp,
adobe::eve_client_holder& /*client_holder*/)
{
if (!temp.bind_m)
return;
/*
REVISIT (sparent) : Don't currently propogate modifier mask past this point.
Not yet wired up.
*/
adobe::display_compositor_t<adobe::button_t, adobe::modifiers_t>*
current_display(adobe::make_display_compositor(control, temp.modifier_set_m));
assemblage.cleanup(boost::bind(adobe::delete_ptr<adobe::display_compositor_t<adobe::button_t, adobe::modifiers_t>*>(), current_display));
assemblage.cleanup(boost::bind(&boost::signals::connection::disconnect,
sheet.monitor_invariant_dependent(
temp.bind_m, boost::bind(&adobe::button_t::enable,
boost::ref(control), _1))));
adobe::attach_view(assemblage, temp.bind_m, *current_display, sheet);
/*
REVISIT (sparent) : Filtering the contributing code here isn't necessarily the right thing -
I think monitor_contributing should remove the filter functionality if possible. For
now I'm passing in an empty dictionary for no filtering.
*/
assemblage.cleanup(boost::bind(&boost::signals::connection::disconnect,
sheet.monitor_contributing(temp.bind_m, adobe::dictionary_t(),
boost::bind(&adobe::button_t::set_contributing,
boost::ref(control),
temp.modifier_set_m, _1))));
}
/****************************************************************************************************/
} // namespace
/****************************************************************************************************/
namespace adobe {
/****************************************************************************************************/
namespace implementation {
/****************************************************************************************************/
button_t* create_button_widget(const dictionary_t& parameters,
const factory_token_t& token,
size_enum_t size)
{
bool is_cancel(false);
bool is_default(false);
modifiers_t modifier_mask(modifiers_none_s);
array_t items;
button_item_t item;
button_state_set_t state_set;
GG::Clr color(GG::CLR_GRAY);
GG::Clr text_color(GG::CLR_BLACK);
dictionary_t image;
get_value(parameters, key_name, item.name_m);
get_value(parameters, key_alt_text, item.alt_text_m);
get_value(parameters, key_bind, item.bind_m);
get_value(parameters, key_bind_output, item.bind_output_m);
get_value(parameters, key_action, item.action_m);
get_value(parameters, key_value, item.value_m);
get_value(parameters, adobe::static_name_t("signal_id"), item.signal_id_m);
get_value(parameters, key_items, items);
get_value(parameters, key_default, is_default);
get_value(parameters, key_cancel, is_cancel);
get_color(parameters, static_name_t("color"), color);
get_color(parameters, static_name_t("text_color"), text_color);
get_value(parameters, key_image, image);
GG::SubTexture unpressed;
GG::SubTexture pressed;
GG::SubTexture rollover;
get_subtexture(image, static_name_t("unpressed"), unpressed);
get_subtexture(image, static_name_t("pressed"), pressed);
get_subtexture(image, static_name_t("rollover"), rollover);
adobe::any_regular_t clicked_binding;
if (get_value(parameters, adobe::static_name_t("bind_clicked_signal"), clicked_binding)) {
adobe::implementation::cell_and_expression(clicked_binding, item.bind_signal_m, item.expression_m);
}
for (array_t::const_iterator iter(items.begin()), last(items.end()); iter != last; ++iter)
state_set_push_back(state_set, token, button_item_t(item, iter->cast<dictionary_t>()));
bool state_set_originally_empty(state_set.empty());
if (state_set_originally_empty)
state_set_push_back(state_set, token, item);
for (button_state_set_t::const_iterator first(state_set.begin()), last(state_set.end()); first != last; ++first)
modifier_mask |= first->modifier_set_m;
button_state_descriptor_t* first_state(state_set.empty() ? 0 : &state_set[0]);
std::size_t n(state_set.size());
button_t* result = new button_t(is_default,
is_cancel,
modifier_mask,
color,
text_color,
unpressed,
pressed,
rollover,
first_state,
first_state + n);
for (array_t::const_iterator iter(items.begin()), last(items.end()); iter != last; ++iter) {
button_item_t temp(item, iter->cast<dictionary_t>());
connect_button_state(*result,
token.client_holder_m.assemblage_m,
token.sheet_m,
temp,
token.client_holder_m);
}
if (state_set_originally_empty) {
connect_button_state(*result,
token.client_holder_m.assemblage_m,
token.sheet_m,
item,
token.client_holder_m);
}
return result;
}
/****************************************************************************************************/
} // namespace implementation
/****************************************************************************************************/
widget_node_t make_button(const dictionary_t& parameters,
const widget_node_t& parent,
const factory_token_t& token,
const widget_factory_t& factory)
{
size_enum_t size(parameters.count(key_size) ?
implementation::enumerate_size(get_value(parameters, key_size).cast<name_t>()) :
parent.size_m);
button_t* widget = implementation::create_button_widget(parameters, token, size);
token.client_holder_m.assemblage_m.cleanup(boost::bind(delete_ptr<button_t*>(),widget));
//
// Call display_insertion to embed the new widget within the view heirarchy
//
platform_display_type display_token(insert(get_main_display(), parent.display_token_m, *widget));
// set up key handler code. We do this all the time because we want the button to be updated
// when modifier keys are pressed during execution of the dialog.
keyboard_t::iterator keyboard_token(
token.client_holder_m.keyboard_m.insert(parent.keyboard_token_m, poly_key_handler_t(boost::ref(*widget))));
//
// As per SF.net bug 1428833, we want to attach the poly_placeable_t
// to Eve before we attach the controller and view to the model
//
eve_t::iterator eve_token;
eve_token = attach_placeable<poly_placeable_t>(parent.eve_token_m, *widget, parameters,
token, factory.is_container(static_name_t("button")),
factory.layout_attributes(static_name_t("button")));
//
// Return the widget_node_t that comprises the tokens created for this widget by the various components
//
return widget_node_t(size, eve_token, display_token, keyboard_token);
}
/****************************************************************************************************/
} // namespace adobe
/****************************************************************************************************/
<|endoftext|> |
<commit_before>/*
Copyright 2005-2007 Adobe Systems Incorporated
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://stlab.adobe.com/licenses.html)
*/
/****************************************************************************************************/
// reveal.hpp needs to come before widget_factory to hook the overrides
#include <GG/adobe/future/widgets/headers/platform_reveal.hpp>
#include <GG/ClrConstants.h>
#include <GG/adobe/future/widgets/headers/reveal_factory.hpp>
#include <GG/adobe/future/widgets/headers/widget_factory.hpp>
#include <GG/adobe/future/widgets/headers/widget_factory_registry.hpp>
/****************************************************************************************************/
namespace adobe {
/****************************************************************************************************/
void create_widget(const dictionary_t& parameters,
size_enum_t size,
reveal_t*& widget)
{
std::string name;
std::string alt_text;
any_regular_t show_value(true);
GG::Clr label_color(GG::CLR_BLACK);
dictionary_t show_image;
dictionary_t hide_image;
get_value(parameters, key_value_on, show_value);
get_value(parameters, key_alt_text, alt_text);
get_value(parameters, key_name, name);
implementation::get_color(parameters, static_name_t("label_color"), label_color);
get_value(parameters, static_name_t("showing_image"), show_image);
GG::SubTexture show_unpressed;
GG::SubTexture show_pressed;
GG::SubTexture show_rollover;
implementation::get_subtexture(show_image, static_name_t("unpressed"), show_unpressed);
implementation::get_subtexture(show_image, static_name_t("pressed"), show_pressed);
implementation::get_subtexture(show_image, static_name_t("rollover"), show_rollover);
get_value(parameters, static_name_t("hiding_image"), hide_image);
GG::SubTexture hide_unpressed;
GG::SubTexture hide_pressed;
GG::SubTexture hide_rollover;
implementation::get_subtexture(hide_image, static_name_t("unpressed"), hide_unpressed);
implementation::get_subtexture(hide_image, static_name_t("pressed"), hide_pressed);
implementation::get_subtexture(hide_image, static_name_t("rollover"), hide_rollover);
widget = new reveal_t(name,
show_value,
alt_text,
label_color,
show_unpressed,
show_pressed,
show_rollover,
hide_unpressed,
hide_pressed,
hide_rollover);
}
/****************************************************************************************************/
template <typename Sheet>
void couple_controller_to_cell(reveal_t& controller,
name_t cell,
Sheet& sheet,
const factory_token_t& token,
const dictionary_t& parameters)
{
attach_monitor(controller, cell, sheet, token, parameters);
}
/****************************************************************************************************/
widget_node_t make_reveal(const dictionary_t& parameters,
const widget_node_t& parent,
const factory_token_t& token,
const widget_factory_t& factory)
{
return create_and_hookup_widget<reveal_t, poly_placeable_t>(parameters, parent, token,
factory.is_container(static_name_t("reveal")),
factory.layout_attributes(static_name_t("reveal")));
}
/****************************************************************************************************/
} // namespace adobe
/****************************************************************************************************/
<commit_msg>Added color bindings to reveal.<commit_after>/*
Copyright 2005-2007 Adobe Systems Incorporated
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://stlab.adobe.com/licenses.html)
*/
/****************************************************************************************************/
// reveal.hpp needs to come before widget_factory to hook the overrides
#include <GG/adobe/future/widgets/headers/platform_reveal.hpp>
#include <GG/ClrConstants.h>
#include <GG/adobe/future/widgets/headers/reveal_factory.hpp>
#include <GG/adobe/future/widgets/headers/widget_factory.hpp>
#include <GG/adobe/future/widgets/headers/widget_factory_registry.hpp>
/****************************************************************************************************/
namespace adobe {
/****************************************************************************************************/
void create_widget(const dictionary_t& parameters,
size_enum_t size,
reveal_t*& widget)
{
std::string name;
std::string alt_text;
any_regular_t show_value(true);
GG::Clr label_color(GG::CLR_BLACK);
dictionary_t show_image;
dictionary_t hide_image;
get_value(parameters, key_value_on, show_value);
get_value(parameters, key_alt_text, alt_text);
get_value(parameters, key_name, name);
implementation::get_color(parameters, static_name_t("label_color"), label_color);
get_value(parameters, static_name_t("showing_image"), show_image);
GG::SubTexture show_unpressed;
GG::SubTexture show_pressed;
GG::SubTexture show_rollover;
implementation::get_subtexture(show_image, static_name_t("unpressed"), show_unpressed);
implementation::get_subtexture(show_image, static_name_t("pressed"), show_pressed);
implementation::get_subtexture(show_image, static_name_t("rollover"), show_rollover);
get_value(parameters, static_name_t("hiding_image"), hide_image);
GG::SubTexture hide_unpressed;
GG::SubTexture hide_pressed;
GG::SubTexture hide_rollover;
implementation::get_subtexture(hide_image, static_name_t("unpressed"), hide_unpressed);
implementation::get_subtexture(hide_image, static_name_t("pressed"), hide_pressed);
implementation::get_subtexture(hide_image, static_name_t("rollover"), hide_rollover);
widget = new reveal_t(name,
show_value,
alt_text,
label_color,
show_unpressed,
show_pressed,
show_rollover,
hide_unpressed,
hide_pressed,
hide_rollover);
}
/****************************************************************************************************/
template <typename Sheet>
void couple_controller_to_cell(reveal_t& control,
name_t cell,
Sheet& sheet,
const factory_token_t& token,
const dictionary_t& parameters)
{
attach_monitor(control, cell, sheet, token, parameters);
adobe::attach_view(control.name_m.color_proxy_m, parameters, token, adobe::static_name_t("bind_label_color"));
}
/****************************************************************************************************/
widget_node_t make_reveal(const dictionary_t& parameters,
const widget_node_t& parent,
const factory_token_t& token,
const widget_factory_t& factory)
{
return create_and_hookup_widget<reveal_t, poly_placeable_t>(parameters, parent, token,
factory.is_container(static_name_t("reveal")),
factory.layout_attributes(static_name_t("reveal")));
}
/****************************************************************************************************/
} // namespace adobe
/****************************************************************************************************/
<|endoftext|> |
<commit_before><commit_msg>No.63 : dp<commit_after><|endoftext|> |
<commit_before><commit_msg>[msan] Enable SelectPartial test.<commit_after><|endoftext|> |
<commit_before>#include "sitewindow.h"
#include "ui_sitewindow.h"
#include <QFile>
#include <QPushButton>
#include "models/profile.h"
#include "models/site.h"
#include "models/source.h"
#include "models/source-guesser.h"
#include "helpers.h"
#include "functions.h"
SiteWindow::SiteWindow(Profile *profile, QMap<QString ,Site*> *sites, QWidget *parent)
: QDialog(parent), ui(new Ui::SiteWindow), m_profile(profile), m_sites(sites)
{
setAttribute(Qt::WA_DeleteOnClose);
ui->setupUi(this);
ui->progressBar->hide();
ui->comboBox->setDisabled(true);
ui->checkBox->setChecked(true);
m_sources = Source::getAllSources(nullptr);
for (Source *source : *m_sources)
{
ui->comboBox->addItem(QIcon(savePath("sites/" + source->getName() + "/icon.png")), source->getName());
}
}
SiteWindow::~SiteWindow()
{
delete ui;
}
void SiteWindow::accept()
{
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
m_url = ui->lineEdit->text();
if (ui->checkBox->isChecked())
{
ui->progressBar->setValue(0);
ui->progressBar->setMaximum(m_sources->count());
ui->progressBar->show();
SourceGuesser sourceGuesser(m_url, *m_sources);
connect(&sourceGuesser, &SourceGuesser::progress, ui->progressBar, &QProgressBar::setValue);
connect(&sourceGuesser, &SourceGuesser::finished, this, &SiteWindow::finish);
sourceGuesser.start();
return;
}
Source *src = nullptr;
for (Source *source : *m_sources)
{
if (source->getName() == ui->comboBox->currentText())
{
src = source;
break;
}
}
finish(src);
}
void SiteWindow::finish(Source *src)
{
if (ui->checkBox->isChecked())
{
ui->progressBar->hide();
if (src == nullptr)
{
error(this, tr("Unable to guess site's type. Are you sure about the url?"));
ui->comboBox->setDisabled(false);
ui->checkBox->setChecked(false);
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
ui->progressBar->hide();
return;
}
}
// Remove unnecessary prefix
bool ssl = false;
if (m_url.startsWith("http://"))
{ m_url.mid(7); }
else if (m_url.startsWith("https://"))
{
m_url.mid(8);
ssl = true;
}
Site *site = new Site(m_url, src);
src->getSites().append(site);
m_sites->insert(site->url(), site);
// If the user wrote "https://" in the URL, we enable SSL for this site
if (ssl)
{ site->settings()->setValue("ssl", true); }
// Save new sites
QFile f(src->getPath() + "/sites.txt");
f.open(QIODevice::ReadOnly);
QString sites = f.readAll();
f.close();
sites.replace("\r\n", "\n").replace("\r", "\n").replace("\n", "\r\n");
QStringList stes = sites.split("\r\n", QString::SkipEmptyParts);
stes.append(site->url());
stes.removeDuplicates();
stes.sort();
f.open(QIODevice::WriteOnly);
f.write(stes.join("\r\n").toLatin1());
f.close();
m_profile->addSite(site);
emit accepted();
close();
}
<commit_msg>Fix new sites being added with their full urls<commit_after>#include "sitewindow.h"
#include "ui_sitewindow.h"
#include <QFile>
#include <QPushButton>
#include "models/profile.h"
#include "models/site.h"
#include "models/source.h"
#include "models/source-guesser.h"
#include "helpers.h"
#include "functions.h"
SiteWindow::SiteWindow(Profile *profile, QMap<QString ,Site*> *sites, QWidget *parent)
: QDialog(parent), ui(new Ui::SiteWindow), m_profile(profile), m_sites(sites)
{
setAttribute(Qt::WA_DeleteOnClose);
ui->setupUi(this);
ui->progressBar->hide();
ui->comboBox->setDisabled(true);
ui->checkBox->setChecked(true);
m_sources = Source::getAllSources(nullptr);
for (Source *source : *m_sources)
{
ui->comboBox->addItem(QIcon(savePath("sites/" + source->getName() + "/icon.png")), source->getName());
}
}
SiteWindow::~SiteWindow()
{
delete ui;
}
void SiteWindow::accept()
{
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
m_url = ui->lineEdit->text();
if (ui->checkBox->isChecked())
{
ui->progressBar->setValue(0);
ui->progressBar->setMaximum(m_sources->count());
ui->progressBar->show();
SourceGuesser sourceGuesser(m_url, *m_sources);
connect(&sourceGuesser, &SourceGuesser::progress, ui->progressBar, &QProgressBar::setValue);
connect(&sourceGuesser, &SourceGuesser::finished, this, &SiteWindow::finish);
sourceGuesser.start();
return;
}
Source *src = nullptr;
for (Source *source : *m_sources)
{
if (source->getName() == ui->comboBox->currentText())
{
src = source;
break;
}
}
finish(src);
}
void SiteWindow::finish(Source *src)
{
if (ui->checkBox->isChecked())
{
ui->progressBar->hide();
if (src == nullptr)
{
error(this, tr("Unable to guess site's type. Are you sure about the url?"));
ui->comboBox->setDisabled(false);
ui->checkBox->setChecked(false);
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
ui->progressBar->hide();
return;
}
}
// Remove unnecessary prefix
bool ssl = false;
if (m_url.startsWith("http://"))
{ m_url = m_url.mid(7); }
else if (m_url.startsWith("https://"))
{
m_url = m_url.mid(8);
ssl = true;
}
if (m_url.endsWith('/'))
{ m_url = m_url.left(m_url.length() - 1); }
Site *site = new Site(m_url, src);
src->getSites().append(site);
m_sites->insert(site->url(), site);
// If the user wrote "https://" in the URL, we enable SSL for this site
if (ssl)
{ site->settings()->setValue("ssl", true); }
// Save new sites
QFile f(src->getPath() + "/sites.txt");
f.open(QIODevice::ReadOnly);
QString sites = f.readAll();
f.close();
sites.replace("\r\n", "\n").replace("\r", "\n").replace("\n", "\r\n");
QStringList stes = sites.split("\r\n", QString::SkipEmptyParts);
stes.append(site->url());
stes.removeDuplicates();
stes.sort();
f.open(QIODevice::WriteOnly);
f.write(stes.join("\r\n").toLatin1());
f.close();
m_profile->addSite(site);
emit accepted();
close();
}
<|endoftext|> |
<commit_before>/*
This file is part of SWGANH. For more information, visit http://swganh.com
Copyright (c) 2006 - 2012 The SWG:ANH Team
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <gtest/gtest.h>
#include <boost/random.hpp>
#include "node.h"
#include <swganh/object/object.h>
using namespace quadtree;
///
class NodeTest : public testing::Test {
public:
NodeTest()
: root_node_(ROOT, Region(Point(-3000.0f, -3000.0f), Point(3000.0f, 3000.0f)), 0, 9, nullptr)
{}
~NodeTest()
{}
protected:
virtual void SetUp() { }
Node root_node_;
};
///
TEST_F(NodeTest, CanInsertRemoveObject)
{
std::shared_ptr<swganh::object::Object> obj(new swganh::object::Object());
obj->SetPosition(glm::vec3(10.0f, 10.0f, 10.0f));
root_node_.InsertObject(obj);
EXPECT_EQ(1, root_node_.GetContainedObjects().size());
root_node_.RemoveObject(obj);
EXPECT_EQ(0, root_node_.GetContainedObjects().size());
}
///
TEST_F(NodeTest, VerifyQuadrantSplit)
{
std::shared_ptr<swganh::object::Object> obj1(new swganh::object::Object()), obj2(new swganh::object::Object()), obj3(new swganh::object::Object()), obj4(new swganh::object::Object());
obj1->SetPosition(glm::vec3(10.0f, 0.0f, 10.0f));
obj2->SetPosition(glm::vec3(-10.0f, 0.0f, 10.0f));
obj3->SetPosition(glm::vec3(10.0f, 0.0f, -10.0f));
obj4->SetPosition(glm::vec3(-10.0f, 0.0f, -10.0f));
root_node_.InsertObject(obj1);
root_node_.InsertObject(obj2);
root_node_.InsertObject(obj3);
root_node_.InsertObject(obj4);
EXPECT_EQ(1, root_node_.GetLeafNodes()[NW_QUADRANT]->GetObjects().size());
EXPECT_EQ(1, root_node_.GetLeafNodes()[NE_QUADRANT]->GetObjects().size());
EXPECT_EQ(1, root_node_.GetLeafNodes()[SW_QUADRANT]->GetObjects().size());
EXPECT_EQ(1, root_node_.GetLeafNodes()[SE_QUADRANT]->GetObjects().size());
root_node_.RemoveObject(obj1);
root_node_.RemoveObject(obj2);
root_node_.RemoveObject(obj3);
root_node_.RemoveObject(obj4);
// TODO: Check that all LeafNodes have been disposed of.
}
///
TEST_F(NodeTest, CanInsertRemoveOneThousand)
{
}
///
TEST_F(NodeTest, CanInsertRemoveTenThousand)
{
}
///
TEST_F(NodeTest, CanUpdateObject)
{
}
///
TEST_F(NodeTest, CanQuery)
{
}
/*****************************************************************************/
// Implementation for the test fixture //<commit_msg>CanQuery test.<commit_after>/*
This file is part of SWGANH. For more information, visit http://swganh.com
Copyright (c) 2006 - 2012 The SWG:ANH Team
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <gtest/gtest.h>
#include <boost/random.hpp>
#include "node.h"
#include <swganh/object/object.h>
using namespace quadtree;
///
class NodeTest : public testing::Test {
public:
NodeTest()
: root_node_(ROOT, Region(Point(-3000.0f, -3000.0f), Point(3000.0f, 3000.0f)), 0, 9, nullptr)
{}
~NodeTest()
{}
protected:
virtual void SetUp() { }
Node root_node_;
};
///
TEST_F(NodeTest, CanInsertRemoveObject)
{
std::shared_ptr<swganh::object::Object> obj(new swganh::object::Object());
obj->SetPosition(glm::vec3(10.0f, 10.0f, 10.0f));
root_node_.InsertObject(obj);
EXPECT_EQ(1, root_node_.GetContainedObjects().size());
root_node_.RemoveObject(obj);
EXPECT_EQ(0, root_node_.GetContainedObjects().size());
}
///
TEST_F(NodeTest, VerifyQuadrantSplit)
{
std::shared_ptr<swganh::object::Object> obj1(new swganh::object::Object()), obj2(new swganh::object::Object()), obj3(new swganh::object::Object()), obj4(new swganh::object::Object());
obj1->SetPosition(glm::vec3(10.0f, 0.0f, 10.0f));
obj2->SetPosition(glm::vec3(-10.0f, 0.0f, 10.0f));
obj3->SetPosition(glm::vec3(10.0f, 0.0f, -10.0f));
obj4->SetPosition(glm::vec3(-10.0f, 0.0f, -10.0f));
root_node_.InsertObject(obj1);
root_node_.InsertObject(obj2);
root_node_.InsertObject(obj3);
root_node_.InsertObject(obj4);
EXPECT_EQ(1, root_node_.GetLeafNodes()[NW_QUADRANT]->GetObjects().size());
EXPECT_EQ(1, root_node_.GetLeafNodes()[NE_QUADRANT]->GetObjects().size());
EXPECT_EQ(1, root_node_.GetLeafNodes()[SW_QUADRANT]->GetObjects().size());
EXPECT_EQ(1, root_node_.GetLeafNodes()[SE_QUADRANT]->GetObjects().size());
root_node_.RemoveObject(obj1);
root_node_.RemoveObject(obj2);
root_node_.RemoveObject(obj3);
root_node_.RemoveObject(obj4);
// TODO: Check that all LeafNodes have been disposed of.
}
///
TEST_F(NodeTest, CanQuery)
{
std::shared_ptr<swganh::object::Object> obj(new swganh::object::Object());
obj->SetPosition(glm::vec3(10.0f, 0.0f, 10.0f));
root_node_.InsertObject(obj);
EXPECT_EQ(1, root_node_.Query(QueryBox( Point(0.0f, 0.0f), Point(15.0f, 15.0f) )).size());
root_node_.RemoveObject(obj);
EXPECT_EQ(0, root_node_.Query(QueryBox( Point(0.0f, 0.0f), Point(15.0f, 15.0f) )).size());
}
///
TEST_F(NodeTest, CanUpdateObject)
{
}
///
TEST_F(NodeTest, CanInsertRemoveQueryOneThousand)
{
}
///
TEST_F(NodeTest, CanInsertRemoveQueryTenThousand)
{
}
/*****************************************************************************/
// Implementation for the test fixture //<|endoftext|> |
<commit_before>#include "./constraint_updater.h"
#include <Eigen/Geometry>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point.hpp>
#include <vector>
#include "../graphics/vertex_array.h"
#include "../graphics/render_data.h"
namespace bg = boost::geometry;
typedef bg::model::point<float, 2, bg::cs::cartesian> point;
typedef bg::model::polygon<point, false, true> polygon; // ccw, closed polygon
ConstraintUpdater::ConstraintUpdater(
Graphics::Gl *gl, std::shared_ptr<Graphics::ShaderManager> shaderManager,
int width, int height)
: gl(gl), shaderManager(shaderManager), width(width), height(height)
{
shaderId = shaderManager->addShader(":/shader/constraint.vert",
":/shader/colorImmediate.frag");
Eigen::Affine3f pixelToNDCTransform(
Eigen::Translation3f(Eigen::Vector3f(-1, 1, 0)) *
Eigen::Scaling(Eigen::Vector3f(2.0f / width, -2.0f / height, 1)));
pixelToNDC = pixelToNDCTransform.matrix();
}
void ConstraintUpdater::addLabel(Eigen::Vector2i anchorPosition,
Eigen::Vector2i labelSize,
Eigen::Vector2i lastAnchorPosition,
Eigen::Vector2i lastLabelPosition,
Eigen::Vector2i lastLabelSize)
{
Eigen::Vector2i halfSize = lastLabelSize / 2;
polygon oldLabel;
oldLabel.outer().push_back(point(lastLabelPosition.x() - halfSize.x(),
lastLabelPosition.y() - halfSize.y()));
oldLabel.outer().push_back(point(lastLabelPosition.x() + halfSize.x(),
lastLabelPosition.y() - halfSize.y()));
oldLabel.outer().push_back(point(lastLabelPosition.x() + halfSize.x(),
lastLabelPosition.y() + halfSize.y()));
oldLabel.outer().push_back(point(lastLabelPosition.x() - halfSize.x(),
lastLabelPosition.y() + halfSize.y()));
int border = 2;
polygon newLabelDilation;
newLabelDilation.outer().push_back(
point(-labelSize.x() - border, -labelSize.y() - border));
newLabelDilation.outer().push_back(
point(0.0f + border, -labelSize.y() - border));
newLabelDilation.outer().push_back(point(0.0f + border, 0.0f + border));
newLabelDilation.outer().push_back(
point(-labelSize.x() - border, 0.0f + border));
std::vector<float> positions = { 128, 128, 0, 384, 128, 0, 384, 384, 0 };
Graphics::VertexArray *vertexArray =
new Graphics::VertexArray(gl, GL_TRIANGLES);
vertexArray->addStream(positions);
RenderData renderData;
renderData.modelMatrix = Eigen::Matrix4f::Identity();
renderData.viewMatrix = pixelToNDC;
renderData.projectionMatrix = Eigen::Matrix4f::Identity();
shaderManager->bind(shaderId, renderData);
vertexArray->draw();
}
<commit_msg>Draw label polygon in ConstraintUpdater.<commit_after>#include "./constraint_updater.h"
#include <Eigen/Geometry>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point.hpp>
#include <vector>
#include "../graphics/vertex_array.h"
#include "../graphics/render_data.h"
namespace bg = boost::geometry;
typedef bg::model::point<float, 2, bg::cs::cartesian> point;
typedef bg::model::polygon<point, false, true> polygon; // ccw, closed polygon
ConstraintUpdater::ConstraintUpdater(
Graphics::Gl *gl, std::shared_ptr<Graphics::ShaderManager> shaderManager,
int width, int height)
: gl(gl), shaderManager(shaderManager), width(width), height(height)
{
shaderId = shaderManager->addShader(":/shader/constraint.vert",
":/shader/colorImmediate.frag");
Eigen::Affine3f pixelToNDCTransform(
Eigen::Translation3f(Eigen::Vector3f(-1, 1, 0)) *
Eigen::Scaling(Eigen::Vector3f(2.0f / width, -2.0f / height, 1)));
pixelToNDC = pixelToNDCTransform.matrix();
}
void ConstraintUpdater::addLabel(Eigen::Vector2i anchorPosition,
Eigen::Vector2i labelSize,
Eigen::Vector2i lastAnchorPosition,
Eigen::Vector2i lastLabelPosition,
Eigen::Vector2i lastLabelSize)
{
Eigen::Vector2i halfSize = lastLabelSize / 2;
polygon oldLabel;
oldLabel.outer().push_back(point(lastLabelPosition.x() - halfSize.x(),
lastLabelPosition.y() - halfSize.y()));
oldLabel.outer().push_back(point(lastLabelPosition.x() + halfSize.x(),
lastLabelPosition.y() - halfSize.y()));
oldLabel.outer().push_back(point(lastLabelPosition.x() + halfSize.x(),
lastLabelPosition.y() + halfSize.y()));
oldLabel.outer().push_back(point(lastLabelPosition.x() - halfSize.x(),
lastLabelPosition.y() + halfSize.y()));
int border = 2;
polygon newLabelDilation;
newLabelDilation.outer().push_back(
point(-labelSize.x() - border, -labelSize.y() - border));
newLabelDilation.outer().push_back(
point(0.0f + border, -labelSize.y() - border));
newLabelDilation.outer().push_back(point(0.0f + border, 0.0f + border));
newLabelDilation.outer().push_back(
point(-labelSize.x() - border, 0.0f + border));
std::vector<float> positions;
if (oldLabel.outer().size() > 0)
{
auto point = oldLabel.outer()[0];
positions.push_back(point.get<0>());
positions.push_back(height - point.get<1>());
positions.push_back(0.0f);
}
for (auto point : oldLabel.outer())
{
positions.push_back(point.get<0>());
positions.push_back(height - point.get<1>());
positions.push_back(0.0f);
}
Graphics::VertexArray *vertexArray =
new Graphics::VertexArray(gl, GL_TRIANGLE_FAN);
vertexArray->addStream(positions);
RenderData renderData;
renderData.modelMatrix = Eigen::Matrix4f::Identity();
renderData.viewMatrix = pixelToNDC;
renderData.projectionMatrix = Eigen::Matrix4f::Identity();
shaderManager->bind(shaderId, renderData);
vertexArray->draw();
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 - 2013 Jolla Ltd.
** Contact: http://jolla.com/
**
** This file is part of Qt Creator.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Digia.
**
****************************************************************************/
#include "merdevicefactory.h"
#include "merdeviceconfigurationwizard.h"
#include "merdevice.h"
#include "merconstants.h"
#include <utils/qtcassert.h>
namespace Mer {
namespace Internal {
MerDeviceFactory::MerDeviceFactory()
{
setObjectName(QLatin1String("MerDeviceFactory"));
}
QString MerDeviceFactory::displayNameForId(Core::Id type) const
{
if (type == Constants::MER_DEVICE_TYPE_I486)
return tr("Mer i486 Device ");
if (type == Constants::MER_DEVICE_TYPE_ARM)
return tr("Mer ARM Device");
return QString();
}
bool MerDeviceFactory::canCreate(Core::Id type)
{
return type == Core::Id(Constants::MER_DEVICE_TYPE_I486) ||
type == Core::Id(Constants::MER_DEVICE_TYPE_ARM);
}
QList<Core::Id> MerDeviceFactory::availableCreationIds() const
{
return QList<Core::Id>() << Core::Id(Constants::MER_DEVICE_TYPE_I486)
<< Core::Id(Constants::MER_DEVICE_TYPE_ARM);
}
ProjectExplorer::IDevice::Ptr MerDeviceFactory::create(Core::Id id) const
{
QTC_ASSERT(canCreate(id), return ProjectExplorer::IDevice::Ptr());
MerDeviceConfigurationWizard wizard(id);
if (wizard.exec() != QDialog::Accepted)
return ProjectExplorer::IDevice::Ptr();
return wizard.device();
}
bool MerDeviceFactory::canRestore(const QVariantMap &map) const
{
return canCreate(ProjectExplorer::IDevice::typeFromMap(map));
}
ProjectExplorer::IDevice::Ptr MerDeviceFactory::restore(const QVariantMap &map) const
{
QTC_ASSERT(canRestore(map), return ProjectExplorer::IDevice::Ptr());
const ProjectExplorer::IDevice::Ptr device = MerDevice::create();
device->fromMap(map);
return device;
}
} // Internal
} // Mer
<commit_msg>Mer: "Mer i486 Device " -> "Mer i486 Device"<commit_after>/****************************************************************************
**
** Copyright (C) 2012 - 2013 Jolla Ltd.
** Contact: http://jolla.com/
**
** This file is part of Qt Creator.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Digia.
**
****************************************************************************/
#include "merdevicefactory.h"
#include "merdeviceconfigurationwizard.h"
#include "merdevice.h"
#include "merconstants.h"
#include <utils/qtcassert.h>
namespace Mer {
namespace Internal {
MerDeviceFactory::MerDeviceFactory()
{
setObjectName(QLatin1String("MerDeviceFactory"));
}
QString MerDeviceFactory::displayNameForId(Core::Id type) const
{
if (type == Constants::MER_DEVICE_TYPE_I486)
return tr("Mer i486 Device");
if (type == Constants::MER_DEVICE_TYPE_ARM)
return tr("Mer ARM Device");
return QString();
}
bool MerDeviceFactory::canCreate(Core::Id type)
{
return type == Core::Id(Constants::MER_DEVICE_TYPE_I486) ||
type == Core::Id(Constants::MER_DEVICE_TYPE_ARM);
}
QList<Core::Id> MerDeviceFactory::availableCreationIds() const
{
return QList<Core::Id>() << Core::Id(Constants::MER_DEVICE_TYPE_I486)
<< Core::Id(Constants::MER_DEVICE_TYPE_ARM);
}
ProjectExplorer::IDevice::Ptr MerDeviceFactory::create(Core::Id id) const
{
QTC_ASSERT(canCreate(id), return ProjectExplorer::IDevice::Ptr());
MerDeviceConfigurationWizard wizard(id);
if (wizard.exec() != QDialog::Accepted)
return ProjectExplorer::IDevice::Ptr();
return wizard.device();
}
bool MerDeviceFactory::canRestore(const QVariantMap &map) const
{
return canCreate(ProjectExplorer::IDevice::typeFromMap(map));
}
ProjectExplorer::IDevice::Ptr MerDeviceFactory::restore(const QVariantMap &map) const
{
QTC_ASSERT(canRestore(map), return ProjectExplorer::IDevice::Ptr());
const ProjectExplorer::IDevice::Ptr device = MerDevice::create();
device->fromMap(map);
return device;
}
} // Internal
} // Mer
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmallocpool_p.h"
#include <qglobal.h>
struct malloc_state;
QTM_BEGIN_NAMESPACE
static void* qmallocpool_sbrk(intptr_t increment);
#define USE_DL_PREFIX
#define MORECORE QTM_NAMESPACE::qmallocpool_sbrk
#define HAVE_MMAP 0
#define __STD_C 1
#ifdef Q_OS_WINCE
#define WIN32
#define LACKS_ERRNO_H
#define MALLOC_FAILURE_ACTION
#endif
static QMallocPoolPrivate * qmallocpool_instance = 0;
static struct malloc_state * qmallocpool_state(QMallocPoolPrivate *);
#define get_malloc_state() (QTM_NAMESPACE::qmallocpool_state(QTM_NAMESPACE::qmallocpool_instance))
QTM_END_NAMESPACE
#include "dlmalloc.c"
QTM_BEGIN_NAMESPACE
class QMallocPoolPrivate
{
public:
QMallocPoolPrivate(void * _pool, unsigned int _poolLen,
QMallocPool::PoolType type, const QString &_name)
: name(_name), pool((char *)_pool), poolLength(_poolLen), poolPtr(0)
{
Q_ASSERT(pool);
Q_ASSERT(poolLength > 0);
if(QMallocPool::Owned == type) {
qMemSet(&owned_mstate, 0, sizeof(struct malloc_state));
mstate = &owned_mstate;
} else if(QMallocPool::NewShared == type) {
Q_ASSERT(poolLength >= sizeof(struct malloc_state));
qMemSet(pool, 0, sizeof(struct malloc_state));
mstate = (struct malloc_state *)pool;
pool += sizeof(struct malloc_state);
poolLength -= sizeof(struct malloc_state);
} else if(QMallocPool::Shared == type) {
Q_ASSERT(poolLength >= sizeof(struct malloc_state));
mstate = (struct malloc_state *)pool;
pool += sizeof(struct malloc_state);
poolLength -= sizeof(struct malloc_state);
}
}
QString name;
char * pool;
unsigned int poolLength;
unsigned int poolPtr;
struct malloc_state *mstate;
struct malloc_state owned_mstate;
};
static struct malloc_state * qmallocpool_state(QMallocPoolPrivate *d)
{
Q_ASSERT(d);
return d->mstate;
}
static void* qmallocpool_sbrk(intptr_t increment)
{
Q_ASSERT(qmallocpool_instance);
QMallocPoolPrivate * const d = qmallocpool_instance;
if(increment > 0) {
if((unsigned)increment > d->poolLength ||
(d->poolLength - increment) < d->poolPtr)
// Failure
return (void *)MORECORE_FAILURE;
void * rv = (void *)(d->pool + d->poolPtr);
d->poolPtr += increment;
return rv;
} else /* increment <= 0 */ {
Q_ASSERT(d->poolPtr >= (unsigned)(-1 * increment));
d->poolPtr += increment;
return (void *)(d->pool + d->poolPtr);
}
}
struct QMallocPtr
{
QMallocPtr(QMallocPoolPrivate * d)
{
Q_ASSERT(!qmallocpool_instance);
qmallocpool_instance = d;
}
~QMallocPtr()
{
Q_ASSERT(qmallocpool_instance);
qmallocpool_instance = 0;
}
};
/*!
\class QMallocPool
\internal
\ingroup publishsubscribe
\brief The QMallocPool class allows management of allocations within a
designated memory region.
QMallocPool provides heap management capabilities into a fixed region of
memory. Primarily this is useful for managing allocations in a shared
memory region, but could be used in other scenarios.
The QMallocPool class provides equivalents for most standard memory management
functions, such as \c {malloc}, \c {calloc}, \c {realloc} and \c {free}.
However, unlike these standard functions which acquire their memory from the
system kernel, QMallocPool operators on a region of memory provided to it
during construction.
QMallocPool is based on dlmalloc, a public domain malloc implementation
written by Doug Lea. dlmalloc is used as the default allocator in many
projects, including several versions of Linux libc.
QMallocPool is not thread safe.
*/
/*!
\enum QMallocPool::PoolType
Controls the type of pool to be created. In order to manage memory, a small
amount of book keeping information is maintained. While this information is
not required for reading from the managed pool, it is required for
allocations. The PoolType controls where this bookkeeping data is stored.
\value Owned
The bookkeeping data is maintained in the QMallocPool instance. Allocation to
the pool is only possible via this instance.
\value NewShared
The bookkeeping data is maintained in the managed region itself. This allows
multiple QMallocPool instances, possibly in separate processes, to allocate
from the pool.
The NewShared PoolType also initializes this bookkeeping data to its default
state. Thus, while the bookkeeping data is shared, only one of the sharing
instances should use a NewShared type. All other instances should use the
Shared pool type.
The malloc pool bookkeeping data contains absolute pointers. As such, if
multiple processes intend to allocate into the malloc pool, is is essential
that they map the memory region to the same virtual address location.
\value Shared
The bookkeeping data is stored in the managed region, and has previously been
initialized by another QMallocPool instance constructed using the NewShared
pool type.
The malloc pool bookkeeping data contains absolute pointers. As such, if
multiple processes intend to allocate into the malloc pool, is is essential
that they map the memory region to the same virtual address location.
*/
/*!
Creates an invalid QMallocPool.
*/
QMallocPool::QMallocPool()
: d(0)
{
}
/*!
Creates a QMallocPool on the memory region \a poolBase of length
\a poolLength. The pool will be constructed with the passed \a type and
\a name. The \a name is used for diagnostics purposes only.
*/
QMallocPool::QMallocPool(void * poolBase, unsigned int poolLength,
PoolType type, const QString& name)
: d(0)
{
if((type == NewShared || Shared == type) &&
poolLength < sizeof(struct malloc_state))
return;
d = new QMallocPoolPrivate(poolBase, poolLength, type, name);
}
/*!
Destroys the malloc pool.
*/
QMallocPool::~QMallocPool()
{
if(d)
delete d;
d = 0;
}
/*!
Returns the allocated size of \a mem, assuming \a mem was previously returned
by malloc(), calloc() or realloc().
*/
size_t QMallocPool::size_of(void *mem)
{
return chunksize(mem2chunk(mem)) - sizeof(mchunkptr);
}
/*!
Allocates memory for an array of \a nmemb elements of \a size each and returns
a pointer to the allocated memory. The memory is set to zero. Returns 0 if
the memory could not be allocated.
*/
void *QMallocPool::calloc(size_t nmemb, size_t size)
{
Q_ASSERT(d && "Cannot operate on a null malloc pool");
QMallocPtr p(d);
return dlcalloc(nmemb, size);
}
/*!
Allocates \a size bytes and returns a pointer to the allocated memory. The
memory is not cleared. Returns 0 if the memory could not be allocated.
*/
void *QMallocPool::malloc(size_t size)
{
Q_ASSERT(d && "Cannot operate on a null malloc pool");
QMallocPtr p(d);
return dlmalloc(size);
}
/*!
Frees the memory space pointed to by \a ptr, which must have been returned
by a previous call to malloc(), calloc() or realloc(). Otherwise, or if
\c {free(ptr)} has already been called before, undefined behavior
occurs. If \a ptr is 0, no operation is performed.
*/
void QMallocPool::free(void *ptr)
{
Q_ASSERT(d && "Cannot operate on a null malloc pool");
QMallocPtr p(d);
dlfree(ptr);
}
/*!
Changes the size of the memory block pointed to by \a ptr to \a size bytes.
The contents will be unchanged to the minimum of the old and new sizes; newly
allocated memory will be uninitialized. If \a ptr is 0, the call is
equivalent to malloc(size); if size is equal to zero, the call is equivalent
to free(ptr). Unless ptr is 0, it must have been returned by an earlier call
to malloc(), calloc() or realloc(). If the area pointed to was moved, a
free(ptr) is done.
*/
void *QMallocPool::realloc(void *ptr, size_t size)
{
Q_ASSERT(d && "Cannot operate on a null malloc pool");
QMallocPtr p(d);
return dlrealloc(ptr, size);
}
/*!
Returns true if this is a valid malloc pool. Invalid malloc pools cannot be
allocated from.
*/
bool QMallocPool::isValid() const
{
return d;
}
/*!
Returns a MemoryStats structure containing information about the memory use
of this pool.
*/
QMallocPool::MemoryStats QMallocPool::memoryStatistics() const
{
Q_ASSERT(d && "Cannot operate on a null malloc pool");
QMallocPtr p(d);
struct mallinfo info = dlmallinfo();
MemoryStats rv = { d->poolLength,
(unsigned long)info.usmblks,
(unsigned long)info.arena,
(unsigned long)info.uordblks,
(unsigned long)info.keepcost };
return rv;
}
QTM_END_NAMESPACE
<commit_msg>Fix compilation on Linux: intptr_t is defined somewhere else<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmallocpool_p.h"
#include <qglobal.h>
struct malloc_state;
QTM_BEGIN_NAMESPACE
static void* qmallocpool_sbrk(qptrdiff increment);
#define USE_DL_PREFIX
#define MORECORE QTM_NAMESPACE::qmallocpool_sbrk
#define HAVE_MMAP 0
#define __STD_C 1
#ifdef Q_OS_WINCE
#define WIN32
#define LACKS_ERRNO_H
#define MALLOC_FAILURE_ACTION
#endif
static QMallocPoolPrivate * qmallocpool_instance = 0;
static struct malloc_state * qmallocpool_state(QMallocPoolPrivate *);
#define get_malloc_state() (QTM_NAMESPACE::qmallocpool_state(QTM_NAMESPACE::qmallocpool_instance))
QTM_END_NAMESPACE
#include "dlmalloc.c"
QTM_BEGIN_NAMESPACE
class QMallocPoolPrivate
{
public:
QMallocPoolPrivate(void * _pool, unsigned int _poolLen,
QMallocPool::PoolType type, const QString &_name)
: name(_name), pool((char *)_pool), poolLength(_poolLen), poolPtr(0)
{
Q_ASSERT(pool);
Q_ASSERT(poolLength > 0);
if(QMallocPool::Owned == type) {
qMemSet(&owned_mstate, 0, sizeof(struct malloc_state));
mstate = &owned_mstate;
} else if(QMallocPool::NewShared == type) {
Q_ASSERT(poolLength >= sizeof(struct malloc_state));
qMemSet(pool, 0, sizeof(struct malloc_state));
mstate = (struct malloc_state *)pool;
pool += sizeof(struct malloc_state);
poolLength -= sizeof(struct malloc_state);
} else if(QMallocPool::Shared == type) {
Q_ASSERT(poolLength >= sizeof(struct malloc_state));
mstate = (struct malloc_state *)pool;
pool += sizeof(struct malloc_state);
poolLength -= sizeof(struct malloc_state);
}
}
QString name;
char * pool;
unsigned int poolLength;
unsigned int poolPtr;
struct malloc_state *mstate;
struct malloc_state owned_mstate;
};
static struct malloc_state * qmallocpool_state(QMallocPoolPrivate *d)
{
Q_ASSERT(d);
return d->mstate;
}
static void* qmallocpool_sbrk(qptrdiff increment)
{
Q_ASSERT(qmallocpool_instance);
QMallocPoolPrivate * const d = qmallocpool_instance;
if(increment > 0) {
if((unsigned)increment > d->poolLength ||
(d->poolLength - increment) < d->poolPtr)
// Failure
return (void *)MORECORE_FAILURE;
void * rv = (void *)(d->pool + d->poolPtr);
d->poolPtr += increment;
return rv;
} else /* increment <= 0 */ {
Q_ASSERT(d->poolPtr >= (unsigned)(-1 * increment));
d->poolPtr += increment;
return (void *)(d->pool + d->poolPtr);
}
}
struct QMallocPtr
{
QMallocPtr(QMallocPoolPrivate * d)
{
Q_ASSERT(!qmallocpool_instance);
qmallocpool_instance = d;
}
~QMallocPtr()
{
Q_ASSERT(qmallocpool_instance);
qmallocpool_instance = 0;
}
};
/*!
\class QMallocPool
\internal
\ingroup publishsubscribe
\brief The QMallocPool class allows management of allocations within a
designated memory region.
QMallocPool provides heap management capabilities into a fixed region of
memory. Primarily this is useful for managing allocations in a shared
memory region, but could be used in other scenarios.
The QMallocPool class provides equivalents for most standard memory management
functions, such as \c {malloc}, \c {calloc}, \c {realloc} and \c {free}.
However, unlike these standard functions which acquire their memory from the
system kernel, QMallocPool operators on a region of memory provided to it
during construction.
QMallocPool is based on dlmalloc, a public domain malloc implementation
written by Doug Lea. dlmalloc is used as the default allocator in many
projects, including several versions of Linux libc.
QMallocPool is not thread safe.
*/
/*!
\enum QMallocPool::PoolType
Controls the type of pool to be created. In order to manage memory, a small
amount of book keeping information is maintained. While this information is
not required for reading from the managed pool, it is required for
allocations. The PoolType controls where this bookkeeping data is stored.
\value Owned
The bookkeeping data is maintained in the QMallocPool instance. Allocation to
the pool is only possible via this instance.
\value NewShared
The bookkeeping data is maintained in the managed region itself. This allows
multiple QMallocPool instances, possibly in separate processes, to allocate
from the pool.
The NewShared PoolType also initializes this bookkeeping data to its default
state. Thus, while the bookkeeping data is shared, only one of the sharing
instances should use a NewShared type. All other instances should use the
Shared pool type.
The malloc pool bookkeeping data contains absolute pointers. As such, if
multiple processes intend to allocate into the malloc pool, is is essential
that they map the memory region to the same virtual address location.
\value Shared
The bookkeeping data is stored in the managed region, and has previously been
initialized by another QMallocPool instance constructed using the NewShared
pool type.
The malloc pool bookkeeping data contains absolute pointers. As such, if
multiple processes intend to allocate into the malloc pool, is is essential
that they map the memory region to the same virtual address location.
*/
/*!
Creates an invalid QMallocPool.
*/
QMallocPool::QMallocPool()
: d(0)
{
}
/*!
Creates a QMallocPool on the memory region \a poolBase of length
\a poolLength. The pool will be constructed with the passed \a type and
\a name. The \a name is used for diagnostics purposes only.
*/
QMallocPool::QMallocPool(void * poolBase, unsigned int poolLength,
PoolType type, const QString& name)
: d(0)
{
if((type == NewShared || Shared == type) &&
poolLength < sizeof(struct malloc_state))
return;
d = new QMallocPoolPrivate(poolBase, poolLength, type, name);
}
/*!
Destroys the malloc pool.
*/
QMallocPool::~QMallocPool()
{
if(d)
delete d;
d = 0;
}
/*!
Returns the allocated size of \a mem, assuming \a mem was previously returned
by malloc(), calloc() or realloc().
*/
size_t QMallocPool::size_of(void *mem)
{
return chunksize(mem2chunk(mem)) - sizeof(mchunkptr);
}
/*!
Allocates memory for an array of \a nmemb elements of \a size each and returns
a pointer to the allocated memory. The memory is set to zero. Returns 0 if
the memory could not be allocated.
*/
void *QMallocPool::calloc(size_t nmemb, size_t size)
{
Q_ASSERT(d && "Cannot operate on a null malloc pool");
QMallocPtr p(d);
return dlcalloc(nmemb, size);
}
/*!
Allocates \a size bytes and returns a pointer to the allocated memory. The
memory is not cleared. Returns 0 if the memory could not be allocated.
*/
void *QMallocPool::malloc(size_t size)
{
Q_ASSERT(d && "Cannot operate on a null malloc pool");
QMallocPtr p(d);
return dlmalloc(size);
}
/*!
Frees the memory space pointed to by \a ptr, which must have been returned
by a previous call to malloc(), calloc() or realloc(). Otherwise, or if
\c {free(ptr)} has already been called before, undefined behavior
occurs. If \a ptr is 0, no operation is performed.
*/
void QMallocPool::free(void *ptr)
{
Q_ASSERT(d && "Cannot operate on a null malloc pool");
QMallocPtr p(d);
dlfree(ptr);
}
/*!
Changes the size of the memory block pointed to by \a ptr to \a size bytes.
The contents will be unchanged to the minimum of the old and new sizes; newly
allocated memory will be uninitialized. If \a ptr is 0, the call is
equivalent to malloc(size); if size is equal to zero, the call is equivalent
to free(ptr). Unless ptr is 0, it must have been returned by an earlier call
to malloc(), calloc() or realloc(). If the area pointed to was moved, a
free(ptr) is done.
*/
void *QMallocPool::realloc(void *ptr, size_t size)
{
Q_ASSERT(d && "Cannot operate on a null malloc pool");
QMallocPtr p(d);
return dlrealloc(ptr, size);
}
/*!
Returns true if this is a valid malloc pool. Invalid malloc pools cannot be
allocated from.
*/
bool QMallocPool::isValid() const
{
return d;
}
/*!
Returns a MemoryStats structure containing information about the memory use
of this pool.
*/
QMallocPool::MemoryStats QMallocPool::memoryStatistics() const
{
Q_ASSERT(d && "Cannot operate on a null malloc pool");
QMallocPtr p(d);
struct mallinfo info = dlmallinfo();
MemoryStats rv = { d->poolLength,
(unsigned long)info.usmblks,
(unsigned long)info.arena,
(unsigned long)info.uordblks,
(unsigned long)info.keepcost };
return rv;
}
QTM_END_NAMESPACE
<|endoftext|> |
<commit_before>///
/// @file retdec/internal/service_impl.cpp
/// @copyright (c) 2015-2016 by Petr Zemek ([email protected]) and contributors
/// @license MIT, see the @c LICENSE file for more details
/// @brief Implementation of the base class of private service
/// implementations.
///
#include "retdec/internal/service_impl.h"
#include "retdec/resource_arguments.h"
namespace retdec {
namespace internal {
///
/// Constructs a private implementation.
///
/// @param[in] settings Settings for the service.
/// @param[in] connectionManager Manager of connections.
/// @param[in] serviceName Name of the service.
///
ServiceImpl::ServiceImpl(const Settings &settings,
const std::shared_ptr<ConnectionManager> &connectionManager,
const std::string &serviceName):
settings(settings),
connectionManager(connectionManager),
baseUrl(settings.apiUrl() + "/" + serviceName) {}
///
/// Destructs the private implementation.
///
ServiceImpl::~ServiceImpl() = default;
///
/// Constructs Connection::RequestArguments from the given decompilation
/// arguments.
///
Connection::RequestArguments ServiceImpl::createRequestArguments(
const ResourceArguments &args) const {
Connection::RequestArguments requestArgs;
for (auto i = args.argumentsBegin(), e = args.argumentsEnd(); i != e; ++i) {
requestArgs.emplace_back(i->first, i->second);
}
return requestArgs;
}
///
/// Constructs Connection::RequestFiles from the given decompilation arguments.
///
Connection::RequestFiles ServiceImpl::createRequestFiles(
const ResourceArguments &args) const {
Connection::RequestFiles requestFiles;
for (auto i = args.filesBegin(), e = args.filesEnd(); i != e; ++i) {
requestFiles.emplace(i->first, i->second);
}
return requestFiles;
}
} // namespace internal
} // namespace retdec
<commit_msg>Refactor creation of request arguments and files.<commit_after>///
/// @file retdec/internal/service_impl.cpp
/// @copyright (c) 2015-2016 by Petr Zemek ([email protected]) and contributors
/// @license MIT, see the @c LICENSE file for more details
/// @brief Implementation of the base class of private service
/// implementations.
///
#include "retdec/internal/service_impl.h"
#include "retdec/resource_arguments.h"
namespace retdec {
namespace internal {
///
/// Constructs a private implementation.
///
/// @param[in] settings Settings for the service.
/// @param[in] connectionManager Manager of connections.
/// @param[in] serviceName Name of the service.
///
ServiceImpl::ServiceImpl(const Settings &settings,
const std::shared_ptr<ConnectionManager> &connectionManager,
const std::string &serviceName):
settings(settings),
connectionManager(connectionManager),
baseUrl(settings.apiUrl() + "/" + serviceName) {}
///
/// Destructs the private implementation.
///
ServiceImpl::~ServiceImpl() = default;
///
/// Constructs Connection::RequestArguments from the given decompilation
/// arguments.
///
Connection::RequestArguments ServiceImpl::createRequestArguments(
const ResourceArguments &args) const {
return Connection::RequestArguments(
args.argumentsBegin(), args.argumentsEnd()
);
}
///
/// Constructs Connection::RequestFiles from the given decompilation arguments.
///
Connection::RequestFiles ServiceImpl::createRequestFiles(
const ResourceArguments &args) const {
return Connection::RequestFiles(
args.filesBegin(), args.filesEnd()
);
}
} // namespace internal
} // namespace retdec
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/control/control_component.h"
#include <iomanip>
#include <string>
#include "cybertron/common/log.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/time/time.h"
#include "modules/common/util/file.h"
#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include "modules/control/common/control_gflags.h"
namespace apollo {
namespace control {
using apollo::canbus::Chassis;
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::VehicleStateProvider;
using apollo::common::time::Clock;
using apollo::control::ControlCommand;
using apollo::control::PadMessage;
using apollo::localization::LocalizationEstimate;
using apollo::planning::ADCTrajectory;
ControlComponent::ControlComponent()
: monitor_logger_buffer_(common::monitor::MonitorMessageItem::CONTROL) {}
bool ControlComponent::Init() {
// init_time_ = Clock::NowInSeconds();
AINFO << "Control init, starting ...";
AINFO << "Loading gflag from file: " << ConfigFilePath();
google::SetCommandLineOption("flagfile", ConfigFilePath().c_str());
CHECK(apollo::common::util::GetProtoFromFile(FLAGS_control_conf_file,
&control_conf_))
<< "Unable to load control conf file: " + FLAGS_control_conf_file;
AINFO << "Conf file: " << FLAGS_control_conf_file << " is loaded.";
AINFO << "Conf file: " << ConfigFilePath() << " is loaded.";
// set controller
if (!controller_agent_.Init(&control_conf_).ok()) {
monitor_logger_buffer_.ERROR("Control init controller failed! Stopping...");
return false;
}
cybertron::ReaderConfig chassis_reader_config;
chassis_reader_config.channel_name = FLAGS_chassis_topic;
chassis_reader_config.pending_queue_size = FLAGS_chassis_pending_queue_size;
chassis_reader_ = node_->CreateReader<Chassis>(
chassis_reader_config,
std::bind(&ControlComponent::OnChassis, this, std::placeholders::_1));
CHECK(chassis_reader_ != nullptr);
cybertron::ReaderConfig planning_reader_config;
planning_reader_config.channel_name = FLAGS_planning_trajectory_topic;
planning_reader_config.pending_queue_size = FLAGS_planning_pending_queue_size;
trajectory_reader_ = node_->CreateReader<ADCTrajectory>(
planning_reader_config,
std::bind(&ControlComponent::OnPlanning, this, std::placeholders::_1));
CHECK(trajectory_reader_ != nullptr);
cybertron::ReaderConfig localization_reader_config;
localization_reader_config.channel_name = FLAGS_localization_topic;
localization_reader_config.pending_queue_size =
FLAGS_localization_pending_queue_size;
localization_reader_ = node_->CreateReader<LocalizationEstimate>(
localization_reader_config, std::bind(&ControlComponent::OnLocalization,
this, std::placeholders::_1));
CHECK(localization_reader_ != nullptr);
cybertron::ReaderConfig pad_msg_reader_config;
pad_msg_reader_config.channel_name = FLAGS_pad_topic;
pad_msg_reader_config.pending_queue_size = FLAGS_pad_msg_pending_queue_size;
pad_msg_reader_ = node_->CreateReader<PadMessage>(
pad_msg_reader_config,
std::bind(&ControlComponent::OnPad, this, std::placeholders::_1));
CHECK(pad_msg_reader_ != nullptr);
control_cmd_writer_ =
node_->CreateWriter<ControlCommand>(FLAGS_control_command_topic);
CHECK(control_cmd_writer_ != nullptr);
// set initial vehicle state by cmd
// need to sleep, because advertised channel is not ready immediately
// simple test shows a short delay of 80 ms or so
AINFO << "Control resetting vehicle state, sleeping for 1000 ms ...";
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
// should init_vehicle first, let car enter work status, then use status msg
// trigger control
AINFO << "Control default driving action is "
<< DrivingAction_Name(control_conf_.action());
pad_msg_.set_action(control_conf_.action());
return true;
}
void ControlComponent::OnPad(const std::shared_ptr<PadMessage> &pad) {
pad_msg_.CopyFrom(*pad);
ADEBUG << "Received Pad Msg:" << pad_msg_.DebugString();
AERROR_IF(!pad_msg_.has_action()) << "pad message check failed!";
// do something according to pad message
if (pad_msg_.action() == DrivingAction::RESET) {
AINFO << "Control received RESET action!";
estop_ = false;
estop_reason_.clear();
}
pad_received_ = true;
}
void ControlComponent::OnChassis(const std::shared_ptr<Chassis> &chassis) {
ADEBUG << "Received chassis data: run chassis callback.";
std::lock_guard<std::mutex> lock(mutex_);
latest_chassis_.CopyFrom(*chassis);
}
void ControlComponent::OnPlanning(
const std::shared_ptr<ADCTrajectory> &trajectory) {
ADEBUG << "Received chassis data: run trajectory callback.";
std::lock_guard<std::mutex> lock(mutex_);
latest_trajectory_.CopyFrom(*trajectory);
}
void ControlComponent::OnLocalization(
const std::shared_ptr<LocalizationEstimate> &localization) {
ADEBUG << "Received control data: run localization message callback.";
std::lock_guard<std::mutex> lock(mutex_);
latest_localization_.CopyFrom(*localization);
}
void ControlComponent::OnMonitor(
const common::monitor::MonitorMessage &monitor_message) {
for (const auto &item : monitor_message.item()) {
if (item.log_level() == common::monitor::MonitorMessageItem::FATAL) {
estop_ = true;
return;
}
}
}
Status ControlComponent::ProduceControlCommand(
ControlCommand *control_command) {
{
std::lock_guard<std::mutex> lock(mutex_);
local_view_.chassis = latest_chassis_;
local_view_.trajectory = latest_trajectory_;
local_view_.localization = latest_localization_;
}
Status status = CheckInput(&local_view_);
// check data
if (!status.ok()) {
AERROR_EVERY(100) << "Control input data failed: "
<< status.error_message();
control_command->mutable_engage_advice()->set_advice(
apollo::common::EngageAdvice::DISALLOW_ENGAGE);
control_command->mutable_engage_advice()->set_reason(
status.error_message());
estop_ = true;
estop_reason_ = status.error_message();
} else {
Status status_ts = CheckTimestamp(local_view_);
if (!status_ts.ok()) {
AERROR << "Input messages timeout";
// estop_ = true;
status = status_ts;
if (local_view_.chassis.driving_mode() !=
apollo::canbus::Chassis::COMPLETE_AUTO_DRIVE) {
control_command->mutable_engage_advice()->set_advice(
apollo::common::EngageAdvice::DISALLOW_ENGAGE);
control_command->mutable_engage_advice()->set_reason(
status.error_message());
}
} else {
control_command->mutable_engage_advice()->set_advice(
apollo::common::EngageAdvice::READY_TO_ENGAGE);
}
}
// check estop
estop_ = control_conf_.enable_persistent_estop()
? estop_ || local_view_.trajectory.estop().is_estop()
: local_view_.trajectory.estop().is_estop();
if (local_view_.trajectory.estop().is_estop()) {
estop_reason_ = "estop from planning";
}
// if planning set estop, then no control process triggered
if (!estop_) {
if (local_view_.chassis.driving_mode() == Chassis::COMPLETE_MANUAL) {
controller_agent_.Reset();
AINFO_EVERY(100) << "Reset Controllers in Manual Mode";
}
auto debug = control_command->mutable_debug()->mutable_input_debug();
debug->mutable_localization_header()->CopyFrom(
local_view_.localization.header());
debug->mutable_canbus_header()->CopyFrom(local_view_.chassis.header());
debug->mutable_trajectory_header()->CopyFrom(
local_view_.trajectory.header());
Status status_compute = controller_agent_.ComputeControlCommand(
&local_view_.localization, &local_view_.chassis,
&local_view_.trajectory, control_command);
if (!status_compute.ok()) {
AERROR << "Control main function failed"
<< " with localization: "
<< local_view_.localization.ShortDebugString()
<< " with chassis: " << local_view_.chassis.ShortDebugString()
<< " with trajectory: "
<< local_view_.trajectory.ShortDebugString()
<< " with cmd: " << control_command->ShortDebugString()
<< " status:" << status_compute.error_message();
estop_ = true;
estop_reason_ = status_compute.error_message();
status = status_compute;
}
}
if (estop_) {
AWARN_EVERY(100) << "Estop triggered! No control core method executed!";
// set Estop command
control_command->set_speed(0);
control_command->set_throttle(0);
control_command->set_brake(control_conf_.soft_estop_brake());
control_command->set_gear_location(Chassis::GEAR_DRIVE);
}
// check signal
if (local_view_.trajectory.decision().has_vehicle_signal()) {
control_command->mutable_signal()->CopyFrom(
local_view_.trajectory.decision().vehicle_signal());
}
return status;
}
bool ControlComponent::Proc() {
double start_timestamp = Clock::NowInSeconds();
if (control_conf_.is_control_test_mode() &&
control_conf_.control_test_duration() > 0 &&
(start_timestamp - init_time_) > control_conf_.control_test_duration()) {
AERROR << "Control finished testing. exit";
return false;
}
ControlCommand control_command;
Status status = ProduceControlCommand(&control_command);
AERROR_IF(!status.ok()) << "Failed to produce control command:"
<< status.error_message();
double end_timestamp = Clock::NowInSeconds();
if (pad_received_) {
control_command.mutable_pad_msg()->CopyFrom(pad_msg_);
pad_received_ = false;
}
const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;
control_command.mutable_latency_stats()->set_total_time_ms(time_diff_ms);
control_command.mutable_latency_stats()->set_total_time_exceeded(
time_diff_ms < control_conf_.control_period());
ADEBUG << "control cycle time is: " << time_diff_ms << " ms.";
status.Save(control_command.mutable_header()->mutable_status());
// forward estop reason among following control frames.
if (estop_) {
control_command.mutable_header()->mutable_status()->set_msg(estop_reason_);
}
// set header
control_command.mutable_header()->set_lidar_timestamp(
local_view_.trajectory.header().lidar_timestamp());
control_command.mutable_header()->set_camera_timestamp(
local_view_.trajectory.header().camera_timestamp());
control_command.mutable_header()->set_radar_timestamp(
local_view_.trajectory.header().radar_timestamp());
common::util::FillHeader(node_->Name(), &control_command);
ADEBUG << control_command.ShortDebugString();
if (control_conf_.is_control_test_mode()) {
ADEBUG << "Skip publish control command in test mode";
return true;
}
control_cmd_writer_->Write(std::make_shared<ControlCommand>(control_command));
return true;
}
Status ControlComponent::CheckInput(LocalView *local_view) {
ADEBUG << "Received localization:"
<< local_view->localization.ShortDebugString();
ADEBUG << "Received chassis:" << local_view->chassis.ShortDebugString();
if (!local_view->trajectory.estop().is_estop() &&
local_view->trajectory.trajectory_point_size() == 0) {
AWARN_EVERY(100) << "planning has no trajectory point. ";
return Status(ErrorCode::CONTROL_COMPUTE_ERROR,
"planning has no trajectory point.");
}
for (auto &trajectory_point :
*local_view->trajectory.mutable_trajectory_point()) {
if (trajectory_point.v() < control_conf_.minimum_speed_resolution()) {
trajectory_point.set_v(0.0);
trajectory_point.set_a(0.0);
}
}
VehicleStateProvider::Instance()->Update(local_view->localization,
local_view->chassis);
return Status::OK();
}
Status ControlComponent::CheckTimestamp(const LocalView &local_view) {
if (!control_conf_.enable_input_timestamp_check() ||
control_conf_.is_control_test_mode()) {
ADEBUG << "Skip input timestamp check by gflags.";
return Status::OK();
}
double current_timestamp = Clock::NowInSeconds();
double localization_diff =
current_timestamp - local_view.localization.header().timestamp_sec();
if (localization_diff > (control_conf_.max_localization_miss_num() *
control_conf_.localization_period())) {
AERROR << "Localization msg lost for " << std::setprecision(6)
<< localization_diff << "s";
monitor_logger_buffer_.ERROR("Localization msg lost");
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Localization msg timeout");
}
double chassis_diff =
current_timestamp - local_view.chassis.header().timestamp_sec();
if (chassis_diff >
(control_conf_.max_chassis_miss_num() * control_conf_.chassis_period())) {
AERROR << "Chassis msg lost for " << std::setprecision(6) << chassis_diff
<< "s";
monitor_logger_buffer_.ERROR("Chassis msg lost");
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Chassis msg timeout");
}
double trajectory_diff =
current_timestamp - local_view.trajectory.header().timestamp_sec();
if (trajectory_diff > (control_conf_.max_planning_miss_num() *
control_conf_.trajectory_period())) {
AERROR << "Trajectory msg lost for " << std::setprecision(6)
<< trajectory_diff << "s";
monitor_logger_buffer_.ERROR("Trajectory msg lost");
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Trajectory msg timeout");
}
return Status::OK();
}
} // namespace control
} // namespace apollo
<commit_msg>Control: Add Cybertron GetLatestObserve<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/control/control_component.h"
#include <iomanip>
#include <string>
#include "cybertron/common/log.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/time/time.h"
#include "modules/common/util/file.h"
#include "modules/common/vehicle_state/vehicle_state_provider.h"
#include "modules/control/common/control_gflags.h"
namespace apollo {
namespace control {
using apollo::canbus::Chassis;
using apollo::common::ErrorCode;
using apollo::common::Status;
using apollo::common::VehicleStateProvider;
using apollo::common::time::Clock;
using apollo::control::ControlCommand;
using apollo::control::PadMessage;
using apollo::localization::LocalizationEstimate;
using apollo::planning::ADCTrajectory;
ControlComponent::ControlComponent()
: monitor_logger_buffer_(common::monitor::MonitorMessageItem::CONTROL) {}
bool ControlComponent::Init() {
// init_time_ = Clock::NowInSeconds();
AINFO << "Control init, starting ...";
AINFO << "Loading gflag from file: " << ConfigFilePath();
google::SetCommandLineOption("flagfile", ConfigFilePath().c_str());
CHECK(apollo::common::util::GetProtoFromFile(FLAGS_control_conf_file,
&control_conf_))
<< "Unable to load control conf file: " + FLAGS_control_conf_file;
AINFO << "Conf file: " << FLAGS_control_conf_file << " is loaded.";
AINFO << "Conf file: " << ConfigFilePath() << " is loaded.";
// set controller
if (!controller_agent_.Init(&control_conf_).ok()) {
monitor_logger_buffer_.ERROR("Control init controller failed! Stopping...");
return false;
}
cybertron::ReaderConfig chassis_reader_config;
chassis_reader_config.channel_name = FLAGS_chassis_topic;
chassis_reader_config.pending_queue_size = FLAGS_chassis_pending_queue_size;
chassis_reader_ = node_->CreateReader<Chassis>(
chassis_reader_config, nullptr);
CHECK(chassis_reader_ != nullptr);
cybertron::ReaderConfig planning_reader_config;
planning_reader_config.channel_name = FLAGS_planning_trajectory_topic;
planning_reader_config.pending_queue_size = FLAGS_planning_pending_queue_size;
trajectory_reader_ = node_->CreateReader<ADCTrajectory>(
planning_reader_config, nullptr);
CHECK(trajectory_reader_ != nullptr);
cybertron::ReaderConfig localization_reader_config;
localization_reader_config.channel_name = FLAGS_localization_topic;
localization_reader_config.pending_queue_size =
FLAGS_localization_pending_queue_size;
localization_reader_ = node_->CreateReader<LocalizationEstimate>(
localization_reader_config, nullptr);
CHECK(localization_reader_ != nullptr);
cybertron::ReaderConfig pad_msg_reader_config;
pad_msg_reader_config.channel_name = FLAGS_pad_topic;
pad_msg_reader_config.pending_queue_size = FLAGS_pad_msg_pending_queue_size;
pad_msg_reader_ = node_->CreateReader<PadMessage>(
pad_msg_reader_config, nullptr);
CHECK(pad_msg_reader_ != nullptr);
control_cmd_writer_ =
node_->CreateWriter<ControlCommand>(FLAGS_control_command_topic);
CHECK(control_cmd_writer_ != nullptr);
// set initial vehicle state by cmd
// need to sleep, because advertised channel is not ready immediately
// simple test shows a short delay of 80 ms or so
AINFO << "Control resetting vehicle state, sleeping for 1000 ms ...";
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
// should init_vehicle first, let car enter work status, then use status msg
// trigger control
AINFO << "Control default driving action is "
<< DrivingAction_Name(control_conf_.action());
pad_msg_.set_action(control_conf_.action());
return true;
}
void ControlComponent::OnPad(const std::shared_ptr<PadMessage> &pad) {
pad_msg_.CopyFrom(*pad);
ADEBUG << "Received Pad Msg:" << pad_msg_.DebugString();
AERROR_IF(!pad_msg_.has_action()) << "pad message check failed!";
// do something according to pad message
if (pad_msg_.action() == DrivingAction::RESET) {
AINFO << "Control received RESET action!";
estop_ = false;
estop_reason_.clear();
}
pad_received_ = true;
}
void ControlComponent::OnChassis(const std::shared_ptr<Chassis> &chassis) {
ADEBUG << "Received chassis data: run chassis callback.";
std::lock_guard<std::mutex> lock(mutex_);
latest_chassis_.CopyFrom(*chassis);
}
void ControlComponent::OnPlanning(
const std::shared_ptr<ADCTrajectory> &trajectory) {
ADEBUG << "Received chassis data: run trajectory callback.";
std::lock_guard<std::mutex> lock(mutex_);
latest_trajectory_.CopyFrom(*trajectory);
}
void ControlComponent::OnLocalization(
const std::shared_ptr<LocalizationEstimate> &localization) {
ADEBUG << "Received control data: run localization message callback.";
std::lock_guard<std::mutex> lock(mutex_);
latest_localization_.CopyFrom(*localization);
}
void ControlComponent::OnMonitor(
const common::monitor::MonitorMessage &monitor_message) {
for (const auto &item : monitor_message.item()) {
if (item.log_level() == common::monitor::MonitorMessageItem::FATAL) {
estop_ = true;
return;
}
}
}
Status ControlComponent::ProduceControlCommand(
ControlCommand *control_command) {
{
std::lock_guard<std::mutex> lock(mutex_);
local_view_.chassis = latest_chassis_;
local_view_.trajectory = latest_trajectory_;
local_view_.localization = latest_localization_;
}
Status status = CheckInput(&local_view_);
// check data
if (!status.ok()) {
AERROR_EVERY(100) << "Control input data failed: "
<< status.error_message();
control_command->mutable_engage_advice()->set_advice(
apollo::common::EngageAdvice::DISALLOW_ENGAGE);
control_command->mutable_engage_advice()->set_reason(
status.error_message());
estop_ = true;
estop_reason_ = status.error_message();
} else {
Status status_ts = CheckTimestamp(local_view_);
if (!status_ts.ok()) {
AERROR << "Input messages timeout";
// estop_ = true;
status = status_ts;
if (local_view_.chassis.driving_mode() !=
apollo::canbus::Chassis::COMPLETE_AUTO_DRIVE) {
control_command->mutable_engage_advice()->set_advice(
apollo::common::EngageAdvice::DISALLOW_ENGAGE);
control_command->mutable_engage_advice()->set_reason(
status.error_message());
}
} else {
control_command->mutable_engage_advice()->set_advice(
apollo::common::EngageAdvice::READY_TO_ENGAGE);
}
}
// check estop
estop_ = control_conf_.enable_persistent_estop()
? estop_ || local_view_.trajectory.estop().is_estop()
: local_view_.trajectory.estop().is_estop();
if (local_view_.trajectory.estop().is_estop()) {
estop_reason_ = "estop from planning";
}
// if planning set estop, then no control process triggered
if (!estop_) {
if (local_view_.chassis.driving_mode() == Chassis::COMPLETE_MANUAL) {
controller_agent_.Reset();
AINFO_EVERY(100) << "Reset Controllers in Manual Mode";
}
auto debug = control_command->mutable_debug()->mutable_input_debug();
debug->mutable_localization_header()->CopyFrom(
local_view_.localization.header());
debug->mutable_canbus_header()->CopyFrom(local_view_.chassis.header());
debug->mutable_trajectory_header()->CopyFrom(
local_view_.trajectory.header());
Status status_compute = controller_agent_.ComputeControlCommand(
&local_view_.localization, &local_view_.chassis,
&local_view_.trajectory, control_command);
if (!status_compute.ok()) {
AERROR << "Control main function failed"
<< " with localization: "
<< local_view_.localization.ShortDebugString()
<< " with chassis: " << local_view_.chassis.ShortDebugString()
<< " with trajectory: "
<< local_view_.trajectory.ShortDebugString()
<< " with cmd: " << control_command->ShortDebugString()
<< " status:" << status_compute.error_message();
estop_ = true;
estop_reason_ = status_compute.error_message();
status = status_compute;
}
}
if (estop_) {
AWARN_EVERY(100) << "Estop triggered! No control core method executed!";
// set Estop command
control_command->set_speed(0);
control_command->set_throttle(0);
control_command->set_brake(control_conf_.soft_estop_brake());
control_command->set_gear_location(Chassis::GEAR_DRIVE);
}
// check signal
if (local_view_.trajectory.decision().has_vehicle_signal()) {
control_command->mutable_signal()->CopyFrom(
local_view_.trajectory.decision().vehicle_signal());
}
return status;
}
bool ControlComponent::Proc() {
double start_timestamp = Clock::NowInSeconds();
chassis_reader_->Observe();
const auto& chassis_msg = chassis_reader_->GetLatestObserved();
OnChassis(chassis_msg);
trajectory_reader_->Observe();
const auto& trajectory_msg = trajectory_reader_->GetLatestObserved();
OnPlanning(trajectory_msg);
localization_reader_->Observe();
const auto& localization_msg = localization_reader_->GetLatestObserved();
OnLocalization(localization_msg);
pad_msg_reader_->Observe();
const auto& pad_msg = pad_msg_reader_->GetLatestObserved();
OnPad(pad_msg);
if (control_conf_.is_control_test_mode() &&
control_conf_.control_test_duration() > 0 &&
(start_timestamp - init_time_) > control_conf_.control_test_duration()) {
AERROR << "Control finished testing. exit";
return false;
}
ControlCommand control_command;
Status status = ProduceControlCommand(&control_command);
AERROR_IF(!status.ok()) << "Failed to produce control command:"
<< status.error_message();
double end_timestamp = Clock::NowInSeconds();
if (pad_received_) {
control_command.mutable_pad_msg()->CopyFrom(pad_msg_);
pad_received_ = false;
}
const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;
control_command.mutable_latency_stats()->set_total_time_ms(time_diff_ms);
control_command.mutable_latency_stats()->set_total_time_exceeded(
time_diff_ms < control_conf_.control_period());
ADEBUG << "control cycle time is: " << time_diff_ms << " ms.";
status.Save(control_command.mutable_header()->mutable_status());
// forward estop reason among following control frames.
if (estop_) {
control_command.mutable_header()->mutable_status()->set_msg(estop_reason_);
}
// set header
control_command.mutable_header()->set_lidar_timestamp(
local_view_.trajectory.header().lidar_timestamp());
control_command.mutable_header()->set_camera_timestamp(
local_view_.trajectory.header().camera_timestamp());
control_command.mutable_header()->set_radar_timestamp(
local_view_.trajectory.header().radar_timestamp());
common::util::FillHeader(node_->Name(), &control_command);
ADEBUG << control_command.ShortDebugString();
if (control_conf_.is_control_test_mode()) {
ADEBUG << "Skip publish control command in test mode";
return true;
}
control_cmd_writer_->Write(std::make_shared<ControlCommand>(control_command));
return true;
}
Status ControlComponent::CheckInput(LocalView *local_view) {
ADEBUG << "Received localization:"
<< local_view->localization.ShortDebugString();
ADEBUG << "Received chassis:" << local_view->chassis.ShortDebugString();
if (!local_view->trajectory.estop().is_estop() &&
local_view->trajectory.trajectory_point_size() == 0) {
AWARN_EVERY(100) << "planning has no trajectory point. ";
return Status(ErrorCode::CONTROL_COMPUTE_ERROR,
"planning has no trajectory point.");
}
for (auto &trajectory_point :
*local_view->trajectory.mutable_trajectory_point()) {
if (trajectory_point.v() < control_conf_.minimum_speed_resolution()) {
trajectory_point.set_v(0.0);
trajectory_point.set_a(0.0);
}
}
VehicleStateProvider::Instance()->Update(local_view->localization,
local_view->chassis);
return Status::OK();
}
Status ControlComponent::CheckTimestamp(const LocalView &local_view) {
if (!control_conf_.enable_input_timestamp_check() ||
control_conf_.is_control_test_mode()) {
ADEBUG << "Skip input timestamp check by gflags.";
return Status::OK();
}
double current_timestamp = Clock::NowInSeconds();
double localization_diff =
current_timestamp - local_view.localization.header().timestamp_sec();
if (localization_diff > (control_conf_.max_localization_miss_num() *
control_conf_.localization_period())) {
AERROR << "Localization msg lost for " << std::setprecision(6)
<< localization_diff << "s";
monitor_logger_buffer_.ERROR("Localization msg lost");
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Localization msg timeout");
}
double chassis_diff =
current_timestamp - local_view.chassis.header().timestamp_sec();
if (chassis_diff >
(control_conf_.max_chassis_miss_num() * control_conf_.chassis_period())) {
AERROR << "Chassis msg lost for " << std::setprecision(6) << chassis_diff
<< "s";
monitor_logger_buffer_.ERROR("Chassis msg lost");
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Chassis msg timeout");
}
double trajectory_diff =
current_timestamp - local_view.trajectory.header().timestamp_sec();
if (trajectory_diff > (control_conf_.max_planning_miss_num() *
control_conf_.trajectory_period())) {
AERROR << "Trajectory msg lost for " << std::setprecision(6)
<< trajectory_diff << "s";
monitor_logger_buffer_.ERROR("Trajectory msg lost");
return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Trajectory msg timeout");
}
return Status::OK();
}
} // namespace control
} // namespace apollo
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2008-2010 Appcelerator, 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 "NetworkStatus.h"
#include <kroll/thread_manager.h>
#include "Network.h"
namespace Titanium {
NetworkStatus::NetworkStatus(Network* binding)
: StaticBoundObject("Network.NetworkStatus")
, binding(binding)
, running(true)
{
}
NetworkStatus::~NetworkStatus()
{
this->Shutdown();
}
void NetworkStatus::Start()
{
this->adapter = new Poco::RunnableAdapter<NetworkStatus>(
*this, &NetworkStatus::StatusLoop);
this->thread = new Poco::Thread();
this->thread->start(*this->adapter);
}
void NetworkStatus::Shutdown(bool async)
{
if (!this->running)
return;
this->running = false;
if (!async)
this->thread->join();
}
void NetworkStatus::StatusLoop()
{
START_KROLL_THREAD;
this->InitializeLoop();
// We want to wake up and detect if we are running more
// often than we want to test reachability, so we only
// test reachability every 25 * .2s
int count = 0;
bool firedAtAll = false;
bool previousStatus = false;
while (this->running)
{
if (count == 0)
{
bool online = this->GetStatus();
if (!firedAtAll || online != previousStatus)
{
firedAtAll = true;
previousStatus = online;
binding->NetworkStatusChange(online);
}
}
if (count == 25)
count = 0;
else
count++;
Poco::Thread::sleep(200);
}
this->CleanupLoop();
END_KROLL_THREAD;
}
} // namespace Titanium
<commit_msg>fix the memory leak on windows in GetStatus() as well as fixing the crash on osx when a proxy is present. See Lighthouse #515 and #483<commit_after>/*
* Copyright (c) 2008-2010 Appcelerator, 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 "NetworkStatus.h"
#include <kroll/thread_manager.h>
#include "Network.h"
namespace Titanium {
NetworkStatus::NetworkStatus(Network* binding)
: StaticBoundObject("Network.NetworkStatus")
, binding(binding)
, running(true)
{
}
NetworkStatus::~NetworkStatus()
{
this->Shutdown();
}
void NetworkStatus::Start()
{
this->adapter = new Poco::RunnableAdapter<NetworkStatus>(
*this, &NetworkStatus::StatusLoop);
this->thread = new Poco::Thread();
this->thread->start(*this->adapter);
}
void NetworkStatus::Shutdown(bool async)
{
if (!this->running)
return;
this->running = false;
if (!async)
this->thread->join();
}
void NetworkStatus::StatusLoop()
{
START_KROLL_THREAD;
this->InitializeLoop();
// We want to wake up and detect if we are running more
// often than we want to test reachability, so we only
// test reachability every 25 * .2s
int count = 0;
bool firedAtAll = false;
bool previousStatus = false;
while (this->running)
{
if (count == 0)
{
// this causes several problem, on windows there's a memory leak
// when GetStatus() is called, and on osx when a proxy is present,
// Titanium Developer crashes. This will need to be looked at later.
// bool online = this->GetStatus();
bool online = true;
if (!firedAtAll || online != previousStatus)
{
firedAtAll = true;
previousStatus = online;
binding->NetworkStatusChange(online);
}
}
if (count == 25)
count = 0;
else
count++;
Poco::Thread::sleep(200);
}
this->CleanupLoop();
END_KROLL_THREAD;
}
} // namespace Titanium
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <multimedia/qabstractmediaservice.h>
#include <multimedia/qabstractmediaservice_p.h>
#include <multimedia/qaudiodevicecontrol.h>
#include <multimedia/qvideodevicecontrol.h>
#include <QtCore/qtimer.h>
/*!
\class QAbstractMediaService
\brief The QAbstractMediaService class provides a common base class for media service
implementations.
\preliminary
*/
/*!
\enum QAbstractMediaService::MediaEndpoint
Enumerates the possible end points a media service may have.
\value VideoInput A video input end point.
\value VideoOutput A video output end point.
\value AudioInput An audio input end point.
\value AudioOutput An audio output end point.
\value StreamInput A data stream input end point
\value StreamOutput A data stream output end point.
*/
/*!
Construct a QAbstractMediaService with \a parent. This class is meant as a
base class for Multimedia services so this constructor is protected.
*/
QAbstractMediaService::QAbstractMediaService(QObject *parent)
: QObject(parent)
, d_ptr(new QAbstractMediaServicePrivate)
{
d_ptr->q_ptr = this;
}
/*!
\internal
*/
QAbstractMediaService::QAbstractMediaService(QAbstractMediaServicePrivate &dd, QObject *parent)
: QObject(parent)
, d_ptr(&dd)
{
d_ptr->q_ptr = this;
}
/*!
Destroys a media service.
*/
QAbstractMediaService::~QAbstractMediaService()
{
delete d_ptr;
}
/*!
Return true if \a endpointType is available.
*/
bool QAbstractMediaService::isEndpointSupported(QAbstractMediaService::MediaEndpoint endpointType)
{
QAudioDeviceControl *audioControl = control<QAudioDeviceControl *>();
QVideoDeviceControl *videoControl = control<QVideoDeviceControl *>();
switch(endpointType) {
case QAbstractMediaService::AudioInput:
case QAbstractMediaService::AudioOutput:
if(audioControl) return true;
break;
case QAbstractMediaService::VideoInput:
case QAbstractMediaService::VideoOutput:
if(videoControl) return true;
break;
case QAbstractMediaService::StreamInput:
case QAbstractMediaService::StreamOutput:
return true;
default:
return false;
}
return false;
}
/*!
Sets the data input \a stream of a media service.
*/
void QAbstractMediaService::setInputStream(QIODevice* stream)
{
d_ptr->inputStream = stream;
}
/*!
Returns the data input stream a media service.
*/
QIODevice* QAbstractMediaService::inputStream() const
{
return d_ptr->inputStream;
}
/*!
Sets the data output \a stream of a media service.
*/
void QAbstractMediaService::setOutputStream(QIODevice* stream)
{
d_ptr->outputStream = stream;
}
/*!
Returns the data output stream of a media service.
*/
QIODevice* QAbstractMediaService::outputStream() const
{
return d_ptr->outputStream;
}
/*!
Returns a list of currently active endpoints for \a endpointType.
*/
QList<QString> QAbstractMediaService::activeEndpoints(QAbstractMediaService::MediaEndpoint endpointType)
{
QList<QString> ret;
int idx = 0;
QAudioDeviceControl *audioControl = control<QAudioDeviceControl *>();
QVideoDeviceControl *videoControl = control<QVideoDeviceControl *>();
switch(endpointType) {
case QAbstractMediaService::AudioInput:
if(audioControl) {
idx = audioControl->selectedDevice();
ret << audioControl->name(idx);
}
break;
case QAbstractMediaService::AudioOutput:
if(audioControl) {
idx = audioControl->selectedDevice();
ret << audioControl->name(idx);
}
break;
case QAbstractMediaService::VideoInput:
if(videoControl) {
idx = videoControl->selectedDevice();
ret << videoControl->name(idx);
}
break;
case QAbstractMediaService::VideoOutput:
if(videoControl) {
idx = videoControl->selectedDevice();
ret << videoControl->name(idx);
}
break;
default:
ret.clear();
}
return ret;
}
/*!
Returns true if set of the active endpoint for \a endpointType to \a endpoint succeeds.
*/
bool QAbstractMediaService::setActiveEndpoint(QAbstractMediaService::MediaEndpoint endpointType, const QString& endpoint)
{
int numDevices = 0;
QAudioDeviceControl *audioControl = control<QAudioDeviceControl *>();
QVideoDeviceControl *videoControl = control<QVideoDeviceControl *>();
switch(endpointType) {
case QAbstractMediaService::AudioInput:
if(audioControl) {
numDevices = audioControl->deviceCount();
for(int i=0;i<numDevices;i++) {
if(qstrcmp(endpoint.toLocal8Bit().constData(),audioControl->name(i).toLocal8Bit().constData()) == 0) {
audioControl->setSelectedDevice(i);
return true;
break;
}
}
}
break;
case QAbstractMediaService::AudioOutput:
if(audioControl) {
numDevices = audioControl->deviceCount();
for(int i=0;i<numDevices;i++) {
if(qstrcmp(endpoint.toLocal8Bit().constData(),audioControl->name(i).toLocal8Bit().constData()) == 0) {
audioControl->setSelectedDevice(i);
return true;
break;
}
}
}
break;
case QAbstractMediaService::VideoInput:
if(videoControl) {
numDevices = videoControl->deviceCount();
for(int i=0;i<numDevices;i++) {
if(qstrcmp(endpoint.toLocal8Bit().constData(),videoControl->name(i).toLocal8Bit().constData()) == 0) {
videoControl->setSelectedDevice(i);
return true;
break;
}
}
}
break;
case QAbstractMediaService::VideoOutput:
if(videoControl) {
numDevices = videoControl->deviceCount();
for(int i=0;i<numDevices;i++) {
if(qstrcmp(endpoint.toLocal8Bit().constData(),videoControl->name(i).toLocal8Bit().constData()) == 0) {
videoControl->setSelectedDevice(i);
return true;
break;
}
}
}
break;
default:
return false;
}
return false;
}
/*!
Returns the description of the \a endpoint for the \a endpointType.
*/
QString QAbstractMediaService::endpointDescription(QAbstractMediaService::MediaEndpoint endpointType, const QString& endpoint)
{
QString desc;
//TODO
return desc;
}
/*!
Returns a list of endpoints available for the \a endpointType.
*/
QList<QString> QAbstractMediaService::supportedEndpoints(QAbstractMediaService::MediaEndpoint endpointType) const
{
int numDevices = 0;
QList<QString> list;
QAudioDeviceControl *audioControl = control<QAudioDeviceControl *>();
QVideoDeviceControl *videoControl = control<QVideoDeviceControl *>();
if(endpointType == QAbstractMediaService::AudioInput && audioControl) {
numDevices = audioControl->deviceCount();
for(int i=0;i<numDevices;i++)
list.append(audioControl->name(i));
} else if(endpointType == QAbstractMediaService::VideoInput && videoControl) {
numDevices = videoControl->deviceCount();
for(int i=0;i<numDevices;i++)
list.append(videoControl->name(i));
} else if(endpointType == QAbstractMediaService::AudioOutput && audioControl) {
numDevices = audioControl->deviceCount();
for(int i=0;i<numDevices;i++)
list.append(audioControl->name(i));
} else if(endpointType == QAbstractMediaService::VideoOutput && videoControl) {
numDevices = videoControl->deviceCount();
for(int i=0;i<numDevices;i++)
list.append(videoControl->name(i));
}
return list;
}
/*!
\fn QAbstractMediaService::control(const char *interface) const
Returns a pointer to the media control implementing \a interface.
If the service does not implement the control a null pointer is returned instead.
*/
/*!
\fn QAbstractMediaService::control() const
Returns a pointer to the media control of type T implemented by a media service.
If the service does not implment the control a null pointer is returned instead.
*/
<commit_msg>QAbstractMediaService::setActiveEndpoint cleanup<commit_after>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <multimedia/qabstractmediaservice.h>
#include <multimedia/qabstractmediaservice_p.h>
#include <multimedia/qaudiodevicecontrol.h>
#include <multimedia/qvideodevicecontrol.h>
#include <QtCore/qtimer.h>
/*!
\class QAbstractMediaService
\brief The QAbstractMediaService class provides a common base class for media service
implementations.
\preliminary
*/
/*!
\enum QAbstractMediaService::MediaEndpoint
Enumerates the possible end points a media service may have.
\value VideoInput A video input end point.
\value VideoOutput A video output end point.
\value AudioInput An audio input end point.
\value AudioOutput An audio output end point.
\value StreamInput A data stream input end point
\value StreamOutput A data stream output end point.
*/
/*!
Construct a QAbstractMediaService with \a parent. This class is meant as a
base class for Multimedia services so this constructor is protected.
*/
QAbstractMediaService::QAbstractMediaService(QObject *parent)
: QObject(parent)
, d_ptr(new QAbstractMediaServicePrivate)
{
d_ptr->q_ptr = this;
}
/*!
\internal
*/
QAbstractMediaService::QAbstractMediaService(QAbstractMediaServicePrivate &dd, QObject *parent)
: QObject(parent)
, d_ptr(&dd)
{
d_ptr->q_ptr = this;
}
/*!
Destroys a media service.
*/
QAbstractMediaService::~QAbstractMediaService()
{
delete d_ptr;
}
/*!
Return true if \a endpointType is available.
*/
bool QAbstractMediaService::isEndpointSupported(QAbstractMediaService::MediaEndpoint endpointType)
{
QAudioDeviceControl *audioControl = control<QAudioDeviceControl *>();
QVideoDeviceControl *videoControl = control<QVideoDeviceControl *>();
switch(endpointType) {
case QAbstractMediaService::AudioInput:
case QAbstractMediaService::AudioOutput:
if(audioControl) return true;
break;
case QAbstractMediaService::VideoInput:
case QAbstractMediaService::VideoOutput:
if(videoControl) return true;
break;
case QAbstractMediaService::StreamInput:
case QAbstractMediaService::StreamOutput:
return true;
default:
return false;
}
return false;
}
/*!
Sets the data input \a stream of a media service.
*/
void QAbstractMediaService::setInputStream(QIODevice* stream)
{
d_ptr->inputStream = stream;
}
/*!
Returns the data input stream a media service.
*/
QIODevice* QAbstractMediaService::inputStream() const
{
return d_ptr->inputStream;
}
/*!
Sets the data output \a stream of a media service.
*/
void QAbstractMediaService::setOutputStream(QIODevice* stream)
{
d_ptr->outputStream = stream;
}
/*!
Returns the data output stream of a media service.
*/
QIODevice* QAbstractMediaService::outputStream() const
{
return d_ptr->outputStream;
}
/*!
Returns a list of currently active endpoints for \a endpointType.
*/
QList<QString> QAbstractMediaService::activeEndpoints(QAbstractMediaService::MediaEndpoint endpointType)
{
QList<QString> ret;
int idx = 0;
QAudioDeviceControl *audioControl = control<QAudioDeviceControl *>();
QVideoDeviceControl *videoControl = control<QVideoDeviceControl *>();
switch(endpointType) {
case QAbstractMediaService::AudioInput:
if(audioControl) {
idx = audioControl->selectedDevice();
ret << audioControl->name(idx);
}
break;
case QAbstractMediaService::AudioOutput:
if(audioControl) {
idx = audioControl->selectedDevice();
ret << audioControl->name(idx);
}
break;
case QAbstractMediaService::VideoInput:
if(videoControl) {
idx = videoControl->selectedDevice();
ret << videoControl->name(idx);
}
break;
case QAbstractMediaService::VideoOutput:
if(videoControl) {
idx = videoControl->selectedDevice();
ret << videoControl->name(idx);
}
break;
default:
ret.clear();
}
return ret;
}
/*!
Returns true if set of the active endpoint for \a endpointType to \a endpoint succeeds.
*/
bool QAbstractMediaService::setActiveEndpoint(QAbstractMediaService::MediaEndpoint endpointType, const QString& endpoint)
{
int numDevices = 0;
QAudioDeviceControl *audioControl = control<QAudioDeviceControl *>();
QVideoDeviceControl *videoControl = control<QVideoDeviceControl *>();
switch(endpointType) {
case QAbstractMediaService::AudioInput:
case QAbstractMediaService::AudioOutput:
if(audioControl) {
numDevices = audioControl->deviceCount();
for(int i=0;i<numDevices;i++) {
if (endpoint == audioControl->name(i)) {
audioControl->setSelectedDevice(i);
return true;
}
}
}
break;
case QAbstractMediaService::VideoInput:
case QAbstractMediaService::VideoOutput:
if(videoControl) {
numDevices = videoControl->deviceCount();
for(int i=0;i<numDevices;i++) {
if (endpoint == videoControl->name(i)) {
videoControl->setSelectedDevice(i);
return true;
}
}
}
break;
default:
return false;
}
return false;
}
/*!
Returns the description of the \a endpoint for the \a endpointType.
*/
QString QAbstractMediaService::endpointDescription(QAbstractMediaService::MediaEndpoint endpointType, const QString& endpoint)
{
QString desc;
//TODO
return desc;
}
/*!
Returns a list of endpoints available for the \a endpointType.
*/
QList<QString> QAbstractMediaService::supportedEndpoints(QAbstractMediaService::MediaEndpoint endpointType) const
{
int numDevices = 0;
QList<QString> list;
QAudioDeviceControl *audioControl = control<QAudioDeviceControl *>();
QVideoDeviceControl *videoControl = control<QVideoDeviceControl *>();
if(endpointType == QAbstractMediaService::AudioInput && audioControl) {
numDevices = audioControl->deviceCount();
for(int i=0;i<numDevices;i++)
list.append(audioControl->name(i));
} else if(endpointType == QAbstractMediaService::VideoInput && videoControl) {
numDevices = videoControl->deviceCount();
for(int i=0;i<numDevices;i++)
list.append(videoControl->name(i));
} else if(endpointType == QAbstractMediaService::AudioOutput && audioControl) {
numDevices = audioControl->deviceCount();
for(int i=0;i<numDevices;i++)
list.append(audioControl->name(i));
} else if(endpointType == QAbstractMediaService::VideoOutput && videoControl) {
numDevices = videoControl->deviceCount();
for(int i=0;i<numDevices;i++)
list.append(videoControl->name(i));
}
return list;
}
/*!
\fn QAbstractMediaService::control(const char *interface) const
Returns a pointer to the media control implementing \a interface.
If the service does not implement the control a null pointer is returned instead.
*/
/*!
\fn QAbstractMediaService::control() const
Returns a pointer to the media control of type T implemented by a media service.
If the service does not implment the control a null pointer is returned instead.
*/
<|endoftext|> |
<commit_before>
#include "parseArgs/parseArgs.h"
#include "au/daemonize.h"
#include "au/log/LogServer.h"
#include "au/log/LogCommon.h"
#define LOC "localhost"
#define LS_PORT AU_LOG_SERVER_PORT
#define LS_QUERY_PORT AU_LOG_SERVER_QUERY_PORT
#define LS_LOG_DIR AU_LOG_SERVER_DIRECTORY
bool fg;
int query_port;
int target_port;
char log_directory[1024];
PaArgument paArgs[] =
{
{ "-fg", &fg, "", PaBool, PaOpt,
false,
false,
true,
"don't start as daemon" },
{ "-port", &target_port, "", PaInt, PaOpt,
LS_PORT,
1, 99999,
"Port for default log channel" },
{ "-query_port", &query_port, "", PaInt, PaOpt,
LS_QUERY_PORT, 1, 99999,
"Port for logClient connections" },
{ "-dir", log_directory, "", PaString, PaOpt,
_i LS_LOG_DIR, PaNL, PaNL,
"Directory for default channel logs" },
PA_END_OF_ARGS
};
static const char *manSynopsis = "logServer [-port X] [-query_port X] [-dir X]";
static const char *manShortDescription = "logServer is a server to collect logs from diferent nodes in a cluster\n";
static const char *manDescription =
"\n"
"logServer is a server to collect logs from diferent nodes in a cluster\n"
"\n";
static const char *manExitStatus = "0 if OK\n 1-255 error\n";
static const char *manAuthor = "Written by Andreu Urruela, Ken Zangelin and J.Gregorio Escalada.";
static const char *manReportingBugs = "bugs to [email protected]\n";
static const char *manCopyright = "Copyright (C) 2011 Telefonica Digital";
static const char *manVersion = "0.1";
int logFd = -1;
void captureSIGPIPE(int s) {
LM_LM(("Captured SIGPIPE %d", s));
}
int main(int argC, const char *argV[]) {
paConfig("prefix", (void *)"LOG_CLIENT_");
paConfig("usage and exit on any warning", (void *)true);
paConfig("log to screen", (void *)true);
paConfig("log file line format", (void *)"TYPE:DATE:EXEC-AUX/FILE[LINE](p.PID)(t.TID) FUNC: TEXT");
paConfig("screen line format", (void *)"TYPE: TEXT");
paConfig("log to file", (void *)false);
paConfig("log to stderr", (void *)true);
paConfig("man synopsis", (void *)manSynopsis);
paConfig("man shortdescription", (void *)manShortDescription);
paConfig("man description", (void *)manDescription);
paConfig("man exitstatus", (void *)manExitStatus);
paConfig("man author", (void *)manAuthor);
paConfig("man reportingbugs", (void *)manReportingBugs);
paConfig("man copyright", (void *)manCopyright);
paConfig("man version", (void *)manVersion);
paParse(paArgs, argC, (char **)argV, 1, true);
// lmAux((char*) "father");
logFd = lmFirstDiskFileDescriptor();
if (fg == false) {
LM_M(("logServer running in background"));
Daemonize();
} else {
LM_M(("logServer running in foreground"));
}
if (signal(SIGPIPE, captureSIGPIPE) == SIG_ERR) {
LM_W(("SIGPIPE cannot be handled"));
}
// Log server
au::LogServer log_server;
// Sleep forever
while (true) {
sleep(1);
}
return 0;
}
<commit_msg>Fix bug of missing include<commit_after>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <errno.h>
#include <pwd.h>
#include <signal.h>
#include <netinet/in.h>
#include <sys/mman.h>
#include "parseArgs/parseArgs.h"
#include "au/daemonize.h"
#include "au/log/LogServer.h"
#include "au/log/LogCommon.h"
#define LOC "localhost"
#define LS_PORT AU_LOG_SERVER_PORT
#define LS_QUERY_PORT AU_LOG_SERVER_QUERY_PORT
#define LS_LOG_DIR AU_LOG_SERVER_DIRECTORY
bool fg;
int query_port;
int target_port;
char log_directory[1024];
PaArgument paArgs[] =
{
{ "-fg", &fg, "", PaBool, PaOpt,
false,
false,
true,
"don't start as daemon" },
{ "-port", &target_port, "", PaInt, PaOpt,
LS_PORT,
1, 99999,
"Port for default log channel" },
{ "-query_port", &query_port, "", PaInt, PaOpt,
LS_QUERY_PORT, 1, 99999,
"Port for logClient connections" },
{ "-dir", log_directory, "", PaString, PaOpt,
_i LS_LOG_DIR, PaNL, PaNL,
"Directory for default channel logs" },
PA_END_OF_ARGS
};
static const char *manSynopsis = "logServer [-port X] [-query_port X] [-dir X]";
static const char *manShortDescription = "logServer is a server to collect logs from diferent nodes in a cluster\n";
static const char *manDescription =
"\n"
"logServer is a server to collect logs from diferent nodes in a cluster\n"
"\n";
static const char *manExitStatus = "0 if OK\n 1-255 error\n";
static const char *manAuthor = "Written by Andreu Urruela, Ken Zangelin and J.Gregorio Escalada.";
static const char *manReportingBugs = "bugs to [email protected]\n";
static const char *manCopyright = "Copyright (C) 2011 Telefonica Digital";
static const char *manVersion = "0.1";
int logFd = -1;
void captureSIGPIPE(int s) {
LM_LM(("Captured SIGPIPE %d", s));
}
int main(int argC, const char *argV[]) {
paConfig("prefix", (void *)"LOG_CLIENT_");
paConfig("usage and exit on any warning", (void *)true);
paConfig("log to screen", (void *)true);
paConfig("log file line format", (void *)"TYPE:DATE:EXEC-AUX/FILE[LINE](p.PID)(t.TID) FUNC: TEXT");
paConfig("screen line format", (void *)"TYPE: TEXT");
paConfig("log to file", (void *)false);
paConfig("log to stderr", (void *)true);
paConfig("man synopsis", (void *)manSynopsis);
paConfig("man shortdescription", (void *)manShortDescription);
paConfig("man description", (void *)manDescription);
paConfig("man exitstatus", (void *)manExitStatus);
paConfig("man author", (void *)manAuthor);
paConfig("man reportingbugs", (void *)manReportingBugs);
paConfig("man copyright", (void *)manCopyright);
paConfig("man version", (void *)manVersion);
paParse(paArgs, argC, (char **)argV, 1, true);
// lmAux((char*) "father");
logFd = lmFirstDiskFileDescriptor();
if (fg == false) {
LM_M(("logServer running in background"));
Daemonize();
} else {
LM_M(("logServer running in foreground"));
}
if (signal(SIGPIPE, captureSIGPIPE) == SIG_ERR) {
LM_W(("SIGPIPE cannot be handled"));
}
// Log server
au::LogServer log_server;
// Sleep forever
while (true) {
sleep(1);
}
return 0;
}
<|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 "chrome/browser/ui/webui/chromeos/mobile_setup_dialog.h"
#include "base/bind.h"
#include "base/memory/singleton.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/platform_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/webui/web_dialog_delegate.h"
#include "chrome/common/url_constants.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
using content::BrowserThread;
using content::WebContents;
using content::WebUIMessageHandler;
class MobileSetupDialogDelegate : public WebDialogDelegate {
public:
static MobileSetupDialogDelegate* GetInstance();
void ShowDialog();
protected:
friend struct DefaultSingletonTraits<MobileSetupDialogDelegate>;
MobileSetupDialogDelegate();
virtual ~MobileSetupDialogDelegate();
void OnCloseDialog();
// WebDialogDelegate overrides.
virtual ui::ModalType GetDialogModalType() const OVERRIDE;
virtual string16 GetDialogTitle() const OVERRIDE;
virtual GURL GetDialogContentURL() const OVERRIDE;
virtual void GetWebUIMessageHandlers(
std::vector<WebUIMessageHandler*>* handlers) const OVERRIDE;
virtual void GetDialogSize(gfx::Size* size) const OVERRIDE;
virtual std::string GetDialogArgs() const OVERRIDE;
virtual void OnDialogClosed(const std::string& json_retval) OVERRIDE;
virtual void OnCloseContents(WebContents* source,
bool* out_close_dialog) OVERRIDE;
virtual bool ShouldShowDialogTitle() const OVERRIDE;
virtual bool HandleContextMenu(
const content::ContextMenuParams& params) OVERRIDE;
private:
DISALLOW_COPY_AND_ASSIGN(MobileSetupDialogDelegate);
};
// static
void MobileSetupDialog::Show() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
MobileSetupDialogDelegate::GetInstance()->ShowDialog();
}
// static
MobileSetupDialogDelegate* MobileSetupDialogDelegate::GetInstance() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
return Singleton<MobileSetupDialogDelegate>::get();
}
MobileSetupDialogDelegate::MobileSetupDialogDelegate() {
}
MobileSetupDialogDelegate::~MobileSetupDialogDelegate() {
}
void MobileSetupDialogDelegate::ShowDialog() {
Browser* browser = BrowserList::GetLastActive();
if (!browser)
return;
browser->BrowserShowWebDialog(this, NULL);
}
ui::ModalType MobileSetupDialogDelegate::GetDialogModalType() const {
return ui::MODAL_TYPE_SYSTEM;
}
string16 MobileSetupDialogDelegate::GetDialogTitle() const {
return l10n_util::GetStringUTF16(IDS_MOBILE_SETUP_TITLE);
}
GURL MobileSetupDialogDelegate::GetDialogContentURL() const {
return GURL(chrome::kChromeUIMobileSetupURL);
}
void MobileSetupDialogDelegate::GetWebUIMessageHandlers(
std::vector<WebUIMessageHandler*>* handlers) const{
}
void MobileSetupDialogDelegate::GetDialogSize(gfx::Size* size) const {
#if defined(POST_PORTAL)
size->SetSize(850, 650);
#else
size->SetSize(1100, 700);
#endif
}
std::string MobileSetupDialogDelegate::GetDialogArgs() const {
return std::string();
}
void MobileSetupDialogDelegate::OnDialogClosed(const std::string& json_retval) {
}
void MobileSetupDialogDelegate::OnCloseContents(WebContents* source,
bool* out_close_dialog) {
*out_close_dialog = true;
}
bool MobileSetupDialogDelegate::ShouldShowDialogTitle() const {
return true;
}
bool MobileSetupDialogDelegate::HandleContextMenu(
const content::ContextMenuParams& params) {
return true;
}
<commit_msg>Use browser::ShowWebDialog() directly in MobileSetup rather than using BrowserList.<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 "chrome/browser/ui/webui/chromeos/mobile_setup_dialog.h"
#include "base/bind.h"
#include "base/memory/singleton.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/platform_util.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/webui/web_dialog_delegate.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/browser_thread.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/size.h"
using content::BrowserThread;
using content::WebContents;
using content::WebUIMessageHandler;
class MobileSetupDialogDelegate : public WebDialogDelegate {
public:
static MobileSetupDialogDelegate* GetInstance();
void ShowDialog();
protected:
friend struct DefaultSingletonTraits<MobileSetupDialogDelegate>;
MobileSetupDialogDelegate();
virtual ~MobileSetupDialogDelegate();
void OnCloseDialog();
// WebDialogDelegate overrides.
virtual ui::ModalType GetDialogModalType() const OVERRIDE;
virtual string16 GetDialogTitle() const OVERRIDE;
virtual GURL GetDialogContentURL() const OVERRIDE;
virtual void GetWebUIMessageHandlers(
std::vector<WebUIMessageHandler*>* handlers) const OVERRIDE;
virtual void GetDialogSize(gfx::Size* size) const OVERRIDE;
virtual std::string GetDialogArgs() const OVERRIDE;
virtual void OnDialogClosed(const std::string& json_retval) OVERRIDE;
virtual void OnCloseContents(WebContents* source,
bool* out_close_dialog) OVERRIDE;
virtual bool ShouldShowDialogTitle() const OVERRIDE;
virtual bool HandleContextMenu(
const content::ContextMenuParams& params) OVERRIDE;
private:
DISALLOW_COPY_AND_ASSIGN(MobileSetupDialogDelegate);
};
// static
void MobileSetupDialog::Show() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
MobileSetupDialogDelegate::GetInstance()->ShowDialog();
}
// static
MobileSetupDialogDelegate* MobileSetupDialogDelegate::GetInstance() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
return Singleton<MobileSetupDialogDelegate>::get();
}
MobileSetupDialogDelegate::MobileSetupDialogDelegate() {
}
MobileSetupDialogDelegate::~MobileSetupDialogDelegate() {
}
void MobileSetupDialogDelegate::ShowDialog() {
browser::ShowWebDialog(NULL,
ProfileManager::GetDefaultProfileOrOffTheRecord(),
NULL,
this);
}
ui::ModalType MobileSetupDialogDelegate::GetDialogModalType() const {
return ui::MODAL_TYPE_SYSTEM;
}
string16 MobileSetupDialogDelegate::GetDialogTitle() const {
return l10n_util::GetStringUTF16(IDS_MOBILE_SETUP_TITLE);
}
GURL MobileSetupDialogDelegate::GetDialogContentURL() const {
return GURL(chrome::kChromeUIMobileSetupURL);
}
void MobileSetupDialogDelegate::GetWebUIMessageHandlers(
std::vector<WebUIMessageHandler*>* handlers) const{
}
void MobileSetupDialogDelegate::GetDialogSize(gfx::Size* size) const {
#if defined(POST_PORTAL)
size->SetSize(850, 650);
#else
size->SetSize(1100, 700);
#endif
}
std::string MobileSetupDialogDelegate::GetDialogArgs() const {
return std::string();
}
void MobileSetupDialogDelegate::OnDialogClosed(const std::string& json_retval) {
}
void MobileSetupDialogDelegate::OnCloseContents(WebContents* source,
bool* out_close_dialog) {
*out_close_dialog = true;
}
bool MobileSetupDialogDelegate::ShouldShowDialogTitle() const {
return true;
}
bool MobileSetupDialogDelegate::HandleContextMenu(
const content::ContextMenuParams& params) {
return true;
}
<|endoftext|> |
<commit_before>
/**
* Copyright 2012 Washington University in St Louis
*
* 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 "pna.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include <list>
#include <map>
#include <stdint.h>
#include <cstdlib>
#include <string.h>
#include <string>
#include <zlib.h>
// C++11 includes
#include <forward_list>
#include <memory>
using namespace std;
// Trailer for gzip compression
struct gzip_trailer
{
uint32_t crc32; // Cyclic Redundancy Check value
uint32_t uncomp_len; // Uncompressed length of original input data
};
#define GZIP_TRAILER_LEN 8
// Parser returns
#define PARSE_SUCCESS 1
#define PARSE_FAILURE 0
// HTTP text options
#define NONE 0
#define COMPRESSED 1
#define CHUNKED 2
#define BOTH 3
// Either make the host global or make it an argument through
// 3 functions where it's only needed in the last one.
// Shitty, I know...
string host;
int parseHTML(char *buf, size_t buf_len)
{
forward_list<string> page;
forward_list<string>::iterator it;
istringstream iss(buf);
string str;
// size_t offset;
// Put each line in the forward iterator.
// I put the buffer in the string stream to have access to getline.
it = page.before_begin();
if (iss.good())
{
while(!iss.eof())
{
getline(iss,str);
page.emplace_after(it, str);
}
}
else
return PARSE_FAILURE;
// // Print the list of html lines.
// for (it = page.begin(); it != page.end(); ++it)
// cout << *it << endl;
//collect all of the links in a page
// list<string> links;
// list<string>::iterator itr;
// for (it = page.begin(); it != page.end(); ++it)
// {
// offset = it->find("href=\"");
// if (offset != string::npos)
// links.push_back(*it);
// }
// for (itr = links.begin(); itr != links.end(); ++it)
// cout << *itr << endl;
// cout << "num links: " << links.size() << endl;
// check if a lot of the links navigate outside of the website
return PARSE_SUCCESS;
}
int decompress(string compression, unique_ptr<char[]> pBuf, size_t buf_len)
{
// zlib should work on the gzip and deflate encodings.
// Need to test deflate though, can't find one that uses it (so maybe I don't need to worry about it).
if (strncmp(compression.c_str(), "gzip", 4) == 0 || strncmp(compression.c_str(), "deflate", 7) == 0)
{
struct gzip_trailer *gz_trailer = (struct gzip_trailer *)(pBuf.get() + buf_len - GZIP_TRAILER_LEN);
int err, ret;
uLongf uncomp_len = (uLongf)gz_trailer->uncomp_len;
unique_ptr<Bytef[]> pUncomp(new Bytef[uncomp_len]);
// Set up the z_stream.
z_stream d_stream;
d_stream.zalloc = Z_NULL;
d_stream.zfree = Z_NULL;
d_stream.opaque = (voidpf)0;
d_stream.next_in = (Bytef *)pBuf.get();
d_stream.avail_in = (uInt)buf_len;
// Prep for inflate.
err = inflateInit2(&d_stream, 47);
if (err != Z_OK)
cout << "inflateInit Error: " << err << endl;
// Inflate so that it decompresses the whole buffer.
d_stream.next_out = pUncomp.get();
d_stream.avail_out = uncomp_len;
err = inflate(&d_stream, Z_FINISH);
if (err < 0)
cout << "inflate Error: " << err << ": " << d_stream.msg << endl;
//cout.write((char *)pUncomp.get(), uncomp_len);
ret = parseHTML((char *)pUncomp.get(), uncomp_len);
return ret;
}
else
cout << "Error! not in gzip for decompression" << endl;
return PARSE_FAILURE;
}
int parseHTTP(ifstream& in, map<string, string>& header)
{
map<string, string>::iterator itr;
string line;
size_t length;
// Initialized return value to PARSE_FAILURE.
// Let the returns from decompression and parseHTML turn it into PARSE_SUCCESS.
int ret = PARSE_FAILURE;
// Tally for what combination of Chunked and/or Compressed it is.
int text_option = 0;
// Check to see if it is chunked.
itr = header.find("Transfer-Encoding");
if (itr != header.end())
text_option += CHUNKED;
// Check to see if it is compressed.
itr = header.find("Content-Encoding");
if (itr != header.end())
text_option += COMPRESSED;
// Let it be known, the abnormal { } for the cases are to induce explicit
// scope restrictions, so that the unique_ptr is cleaned immediately.
switch (text_option) {
case NONE:
{
if (strncmp(itr->second.c_str(), "text/html", 9) == 0)
{
length = atoi(header["Content-Length"].c_str());
unique_ptr<char[]> pBuf(new char[length]);
in.read(pBuf.get(), length);
//cout.write(buf.get(), length);
ret = parseHTML((char *)pBuf.get(), length);
}
else if (strncmp(itr->second.c_str(), "text/css", 8))
{
length = atoi(header["Content-Length"].c_str());
unique_ptr<char[]> pBuf(new char[length]);
in.read(pBuf.get(), length);
//cout.write(buf.get(), length);
ret = parseHTML((char *)pBuf.get(), length);
}
break;
}
case CHUNKED:
{
// Get the first chunk length.
getline(in,line);
length = strtoul(line.c_str(),NULL,16);
// Repeat reading the buffer and new chunk length until the length is 0.
// 0 is the value in concordance with the HTTP spec, it signifies the end of the chunks.
while (length != 0)
{
unique_ptr<char[]> pBuf(new char[length]);
in.read(pBuf.get(), length);
// Consume the trailing CLRF before the length.
getline(in,line);
// Consume the new chunk length or the terminating zero.
getline(in,line);
// I have to use strtoul with base 16 because the HTTP spec
// says the chunked encoding length is presented in hex.
length = strtoul(line.c_str(),NULL,16);
//cout.write(buf,length);
parseHTML((char *)pBuf.get(), length);
}
// Once it gets to this point, the chunked length last fed was 0
// Get last CLRF and quit
getline(in,line);
// TODO: Return value for this. Multiple parseHTML calls equates to...?
ret = PARSE_SUCCESS;
break;
}
case COMPRESSED:
{
// Read the compressed data into a buffer and ship off to be decompressed.
length = atoi(header["Content-Length"].c_str());
unique_ptr<char[]> pBuf(new char[length]);
in.read(pBuf.get(), length);
ret = decompress(header["Content-Encoding"], std::move(pBuf), length);
break;
}
case BOTH:
{
// Same as the CHUNKED case but with decompression. Comments included again for verbosity.
// TODO: figure out way to combine this and CHUNKED to eliminate repetitive code
// Get the first chunk length.
getline(in,line);
length = strtoul(line.c_str(),NULL,16);
// Repeat reading the buffer and new chunk length until the length is 0.
// 0 is the value in concordance with the HTTP spec, it signifies the end of the chunks.
while (length != 0)
{
unique_ptr<char[]> pBuf(new char[length]);
in.read(pBuf.get(), length);
decompress(header["Content-Encoding"],std::move(pBuf),length);
// Consume the trailing CLRF before the length.
getline(in,line);
// Consume the new chunk length or the terminating zero.
getline(in,line);
// I have to use strtoul with base 16 because the HTTP spec
// says the chunked encoding length is presented in hex.
length = strtoul(line.c_str(),NULL,16);
}
// Once it gets to this point, the chunked length last fed was 0
// Get last CLRF and quit
getline(in,line);
// TODO: Return value for this. Multiple decompress calls equates to...?
ret = PARSE_SUCCESS;
break;
}
default:
break;
}
return ret;
}
int main(int argc, char **argv)
{
string line;
string host;
size_t offset;
size_t host_off;
// If argc is two, a pcap input file should be given.
if (argc == 3)
{
map<string, string> header;
ifstream in;
int outbound;
int inbound;
char port[5];
/*
* Check the destination port of the first file.
* If it is 80, then it's the outbound file.
* If not, then it's the inbound file.
* Set the file's argument number accordingly.
*/
strncpy(port, argv[1] + strlen(argv[1]) - 5, 5);
if (atoi(port) == 80) {
outbound = 1;
inbound = 2;
} else {
inbound = 1;
outbound = 2;
}
// Get the hostname
in.open(argv[outbound]);
if (in.is_open()) {
while (!in.eof()) {
// search for a GET request that specifies the host
// should be the first line, so quit after we find it
getline(in, line);
host_off = line.find("Host: ");
if (host_off != string::npos) {
host = line.substr(host_off + 6);
break;
}
}
}
in.close();
cout << "host: " << host << endl;
// Let's parse some replies!
in.open(argv[inbound]);
if (in.is_open())
{
while (!in.eof())
{
// Search for the "HTTP/1.1 200 OK" line.
getline(in, line);
offset = line.find("HTTP/1.1 200 OK");
if (offset != string::npos)
{
// We found the reply.
header["HTTP/1.1"] = "200 OK";
// Read the HTTP header labels and values into our map.
// The header ending is denoted by a carriage return '\r'.
getline(in, line);
while (line != "\r")
{
offset = line.find(":");
header[line.substr(0, offset)] = line.substr(offset + 2);
getline(in, line);
}
// Print the http header
// map<string, string>::iterator it;
// for (it = header.begin(); it != header.end(); ++it)
// cout << it->first << ": " << it->second << endl;
// cout << endl;
// Send the HTTP header and our ifstream to parseHTTP.
parseHTTP(in, header);
// Clear the header map for the next reply found in the file.
header.clear();
}
}
}
else
cout << "Error! File did not open correctly." << endl;
in.close();
}
// Input is piped to our program from stdout with our pcap_wrap format.
else if (argc == 1)
{
map<string, string> key;
string first, second;
unsigned long length;
size_t span;
while(!cin.eof())
{
// Get the six lines pertinent to our TCP flows, put them in our key map.
for (int i = 0; i < 6; ++i)
{
getline(cin, line);
offset = line.find("->");
span = line.find(":");
if (offset != string::npos && span != string::npos)
{
second = line.substr(span+2);
first = line.substr(offset+2, span - offset - 2);
key[first] = second;
}
}
// Print the key.
map<string, string>::iterator it;
for (it = key.begin(); it != key.end(); ++it)
cout << it->first << ": " << it->second << endl;
// Get the packet information. This line specifically is packet length.
getline(cin, line);
offset = line.find(":");
if (offset != string::npos)
{
// The length line exists. Read that length of data from cin soon.
length = atoi(line.substr(offset+2).c_str());
unique_ptr<char[]> pBuf(new char[length]);
// Consume the packet_data label.
getline(cin, line);
// Get the packet data.
cin.read(pBuf.get(), length);
// TODO: Here is the exit point from main.
// Guessing this will go to the hashmap? We'll see when it's developed.
cout.write(pBuf.get(), length);
}
// Clear the key map for other packet keys.
key.clear();
}
} else {
cout << "Usage: html_parser outbound-flow inbound-flow" << endl;
cout << "[NOTE] the flow order is not important" << endl;
}
return 0;
}
<commit_msg>fixed a magic number, commented code a little more.<commit_after>
/**
* Copyright 2012 Washington University in St Louis
*
* 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 "pna.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include <list>
#include <map>
#include <stdint.h>
#include <cstdlib>
#include <string.h>
#include <string>
#include <zlib.h>
// C++11 includes
#include <forward_list>
#include <memory>
using namespace std;
// Trailer for gzip compression
struct gzip_trailer
{
uint32_t crc32; // Cyclic Redundancy Check value
uint32_t uncomp_len; // Uncompressed length of original input data
};
#define GZIP_TRAILER_LEN 8
// Parser returns
#define PARSE_SUCCESS 1
#define PARSE_FAILURE 0
// HTTP text options
#define NONE 0
#define COMPRESSED 1
#define CHUNKED 2
#define BOTH 3
// Either make the host global or make it an argument through
// 3 functions where it's only needed in the last one.
// Shitty, I know...
string host;
int parseHTML(char *buf, size_t buf_len)
{
forward_list<string> page;
forward_list<string>::iterator it;
istringstream iss(buf);
string str;
// size_t offset;
// Put each line in the forward iterator.
// I put the buffer in the string stream to have access to getline.
it = page.before_begin();
if (iss.good())
{
while(!iss.eof())
{
getline(iss,str);
page.emplace_after(it, str);
}
}
else
return PARSE_FAILURE;
// // Print the list of html lines.
// for (it = page.begin(); it != page.end(); ++it)
// cout << *it << endl;
//collect all of the links in a page
// list<string> links;
// list<string>::iterator itr;
// for (it = page.begin(); it != page.end(); ++it)
// {
// offset = it->find("href=\"");
// if (offset != string::npos)
// links.push_back(*it);
// }
// for (itr = links.begin(); itr != links.end(); ++it)
// cout << *itr << endl;
// cout << "num links: " << links.size() << endl;
// check if a lot of the links navigate outside of the website
return PARSE_SUCCESS;
}
int decompress(string compression, unique_ptr<char[]> pBuf, size_t buf_len)
{
// zlib should work on the gzip and deflate encodings.
// Need to test deflate though, can't find one that uses it (so maybe I don't need to worry about it).
if (strncmp(compression.c_str(), "gzip", 4) == 0 || strncmp(compression.c_str(), "deflate", 7) == 0)
{
struct gzip_trailer *gz_trailer = (struct gzip_trailer *)(pBuf.get() + buf_len - GZIP_TRAILER_LEN);
int err, ret;
uLongf uncomp_len = (uLongf)gz_trailer->uncomp_len;
unique_ptr<Bytef[]> pUncomp(new Bytef[uncomp_len]);
// Set up the z_stream.
z_stream d_stream;
d_stream.zalloc = Z_NULL;
d_stream.zfree = Z_NULL;
d_stream.opaque = (voidpf)0;
d_stream.next_in = (Bytef *)pBuf.get();
d_stream.avail_in = (uInt)buf_len;
// Prep for inflate.
err = inflateInit2(&d_stream, 47);
if (err != Z_OK)
cout << "inflateInit Error: " << err << endl;
// Inflate so that it decompresses the whole buffer.
d_stream.next_out = pUncomp.get();
d_stream.avail_out = uncomp_len;
err = inflate(&d_stream, Z_FINISH);
if (err < 0)
cout << "inflate Error: " << err << ": " << d_stream.msg << endl;
//cout.write((char *)pUncomp.get(), uncomp_len);
ret = parseHTML((char *)pUncomp.get(), uncomp_len);
return ret;
}
else
cout << "Error! not in gzip for decompression" << endl;
return PARSE_FAILURE;
}
int parseHTTP(ifstream& in, map<string, string>& header)
{
map<string, string>::iterator itr;
string line;
size_t length;
// Initialized return value to PARSE_FAILURE.
// Let the returns from decompression and parseHTML turn it into PARSE_SUCCESS.
int ret = PARSE_FAILURE;
// Tally for what combination of Chunked and/or Compressed it is.
int text_option = 0;
// Check to see if it is chunked.
itr = header.find("Transfer-Encoding");
if (itr != header.end())
text_option += CHUNKED;
// Check to see if it is compressed.
itr = header.find("Content-Encoding");
if (itr != header.end())
text_option += COMPRESSED;
// Let it be known, the abnormal { } for the cases are to induce explicit
// scope restrictions, so that the unique_ptr is cleaned immediately.
switch (text_option) {
case NONE:
{
if (strncmp(itr->second.c_str(), "text/html", 9) == 0)
{
length = atoi(header["Content-Length"].c_str());
unique_ptr<char[]> pBuf(new char[length]);
in.read(pBuf.get(), length);
//cout.write(buf.get(), length);
ret = parseHTML((char *)pBuf.get(), length);
}
else if (strncmp(itr->second.c_str(), "text/css", 8))
{
length = atoi(header["Content-Length"].c_str());
unique_ptr<char[]> pBuf(new char[length]);
in.read(pBuf.get(), length);
//cout.write(buf.get(), length);
ret = parseHTML((char *)pBuf.get(), length);
}
break;
}
case CHUNKED:
{
// Get the first chunk length.
getline(in,line);
length = strtoul(line.c_str(),NULL,16);
// Repeat reading the buffer and new chunk length until the length is 0.
// 0 is the value in concordance with the HTTP spec, it signifies the end of the chunks.
while (length != 0)
{
unique_ptr<char[]> pBuf(new char[length]);
in.read(pBuf.get(), length);
// Consume the trailing CLRF before the length.
getline(in,line);
// Consume the new chunk length or the terminating zero.
getline(in,line);
// I have to use strtoul with base 16 because the HTTP spec
// says the chunked encoding length is presented in hex.
length = strtoul(line.c_str(),NULL,16);
//cout.write(buf,length);
parseHTML((char *)pBuf.get(), length);
}
// Once it gets to this point, the chunked length last fed was 0
// Get last CLRF and quit
getline(in,line);
// TODO: Return value for this. Multiple parseHTML calls equates to...?
ret = PARSE_SUCCESS;
break;
}
case COMPRESSED:
{
// Read the compressed data into a buffer and ship off to be decompressed.
length = atoi(header["Content-Length"].c_str());
unique_ptr<char[]> pBuf(new char[length]);
in.read(pBuf.get(), length);
ret = decompress(header["Content-Encoding"], std::move(pBuf), length);
break;
}
case BOTH:
{
// Same as the CHUNKED case but with decompression. Comments included again for verbosity.
// TODO: figure out way to combine this and CHUNKED to eliminate repetitive code
// Get the first chunk length.
getline(in,line);
length = strtoul(line.c_str(),NULL,16);
// Repeat reading the buffer and new chunk length until the length is 0.
// 0 is the value in concordance with the HTTP spec, it signifies the end of the chunks.
while (length != 0)
{
unique_ptr<char[]> pBuf(new char[length]);
in.read(pBuf.get(), length);
decompress(header["Content-Encoding"],std::move(pBuf),length);
// Consume the trailing CLRF before the length.
getline(in,line);
// Consume the new chunk length or the terminating zero.
getline(in,line);
// I have to use strtoul with base 16 because the HTTP spec
// says the chunked encoding length is presented in hex.
length = strtoul(line.c_str(),NULL,16);
}
// Once it gets to this point, the chunked length last fed was 0
// Get last CLRF and quit
getline(in,line);
// TODO: Return value for this. Multiple decompress calls equates to...?
ret = PARSE_SUCCESS;
break;
}
default:
break;
}
return ret;
}
int main(int argc, char **argv)
{
string line;
string host;
size_t offset;
size_t host_off;
// If argc is two, a pcap input file should be given.
if (argc == 3)
{
map<string, string> header;
ifstream in;
int outbound;
int inbound;
char port[5];
/*
* Eliminate some magic numbers
* I did have 5 as a const size_t, but it threw a warning for strncpy...
* Live with the magic number. Spoilers: it's the length of a port number.
*/
const int tcp_port = 80;
/*
* Check the destination port of the first file.
* If it is 80, then it's the outbound file.
* If not, then it's the inbound file.
* Set the file's argument number accordingly.
*/
strncpy(port, argv[1] + strlen(argv[1]) - 5, 5);
if (atoi(port) == tcp_port) {
outbound = 1;
inbound = 2;
} else {
inbound = 1;
outbound = 2;
}
// Get the hostname
in.open(argv[outbound]);
if (in.is_open()) {
while (!in.eof()) {
// search for a GET request that specifies the host
// should be the first line, so quit after we find it
getline(in, line);
host_off = line.find("Host: ");
if (host_off != string::npos) {
host = line.substr(host_off + 6);
break;
}
}
}
in.close();
cout << "host: " << host << endl;
// Let's parse some replies!
in.open(argv[inbound]);
if (in.is_open())
{
while (!in.eof())
{
// Search for the "HTTP/1.1 200 OK" line.
getline(in, line);
offset = line.find("HTTP/1.1 200 OK");
if (offset != string::npos)
{
// We found the reply.
header["HTTP/1.1"] = "200 OK";
// Read the HTTP header labels and values into our map.
// The header ending is denoted by a carriage return '\r'.
getline(in, line);
while (line != "\r")
{
offset = line.find(":");
header[line.substr(0, offset)] = line.substr(offset + 2);
getline(in, line);
}
// Print the http header
// map<string, string>::iterator it;
// for (it = header.begin(); it != header.end(); ++it)
// cout << it->first << ": " << it->second << endl;
// cout << endl;
// Send the HTTP header and our ifstream to parseHTTP.
parseHTTP(in, header);
// Clear the header map for the next reply found in the file.
header.clear();
}
}
}
else
cout << "Error! File did not open correctly." << endl;
in.close();
}
// Input is piped to our program from stdout with our pcap_wrap format.
else if (argc == 1)
{
map<string, string> key;
string first, second;
unsigned long length;
size_t span;
while(!cin.eof())
{
// Get the six lines pertinent to our TCP flows, put them in our key map.
for (int i = 0; i < 6; ++i)
{
getline(cin, line);
offset = line.find("->");
span = line.find(":");
if (offset != string::npos && span != string::npos)
{
second = line.substr(span+2);
first = line.substr(offset+2, span - offset - 2);
key[first] = second;
}
}
// Print the key.
map<string, string>::iterator it;
for (it = key.begin(); it != key.end(); ++it)
cout << it->first << ": " << it->second << endl;
// Get the packet information. This line specifically is packet length.
getline(cin, line);
offset = line.find(":");
if (offset != string::npos)
{
// The length line exists. Read that length of data from cin soon.
length = atoi(line.substr(offset+2).c_str());
unique_ptr<char[]> pBuf(new char[length]);
// Consume the packet_data label.
getline(cin, line);
// Get the packet data.
cin.read(pBuf.get(), length);
// TODO: Here is the exit point from main.
// Guessing this will go to the hashmap? We'll see when it's developed.
cout.write(pBuf.get(), length);
}
// Clear the key map for other packet keys.
key.clear();
}
} else {
cout << "Usage: html_parser outbound-flow inbound-flow" << endl;
cout << "[NOTE] the flow order is not important" << endl;
}
return 0;
}
<|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 <vector>
#include "base/ref_counted.h"
#include "base/string16.h"
#include "base/task.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autocomplete_history_manager.h"
#include "chrome/browser/webdata/web_data_service.h"
#include "chrome/test/testing_profile.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/glue/form_data.h"
using testing::_;
using webkit_glue::FormData;
class MockWebDataService : public WebDataService {
public:
MOCK_METHOD1(AddFormFields,
void(const std::vector<webkit_glue::FormField>&)); // NOLINT
};
class AutocompleteHistoryManagerTest : public testing::Test {
protected:
AutocompleteHistoryManagerTest()
: ui_thread_(ChromeThread::UI, &message_loop_) {
}
virtual void SetUp() {
web_data_service_ = new MockWebDataService();
autocomplete_manager_.reset(
new AutocompleteHistoryManager(&profile_, web_data_service_));
}
MessageLoopForUI message_loop_;
ChromeThread ui_thread_;
TestingProfile profile_;
scoped_refptr<MockWebDataService> web_data_service_;
scoped_ptr<AutocompleteHistoryManager> autocomplete_manager_;
};
// Tests that credit card numbers are not sent to the WebDatabase to be saved.
TEST_F(AutocompleteHistoryManagerTest, CreditCardNumberValue) {
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.method = ASCIIToUTF16("POST");
form.origin = GURL("http://myform.com/form.html");
form.action = GURL("http://myform.com/submit.html");
// Valid Visa credit card number pulled from the paypal help site.
webkit_glue::FormField valid_cc(ASCIIToUTF16("Credit Card"),
ASCIIToUTF16("ccnum"),
ASCIIToUTF16("4012888888881881"),
ASCIIToUTF16("text"),
20);
form.fields.push_back(valid_cc);
EXPECT_CALL(*web_data_service_, AddFormFields(_)).Times(0);
autocomplete_manager_->FormSubmitted(form);
}
// Contrary test to AutocompleteHistoryManagerTest.CreditCardNumberValue. The
// value being submitted is not a valid credit card number, so it will be sent
// to the WebDatabase to be saved.
TEST_F(AutocompleteHistoryManagerTest, NonCreditCardNumberValue) {
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.method = ASCIIToUTF16("POST");
form.origin = GURL("http://myform.com/form.html");
form.action = GURL("http://myform.com/submit.html");
// Invalid credit card number.
webkit_glue::FormField invalid_cc(ASCIIToUTF16("Credit Card"),
ASCIIToUTF16("ccnum"),
ASCIIToUTF16("4580123456789012"),
ASCIIToUTF16("text"),
20);
form.fields.push_back(invalid_cc);
EXPECT_CALL(*(web_data_service_.get()), AddFormFields(_)).Times(1);
autocomplete_manager_->FormSubmitted(form);
}
// Tests that SSNs are not sent to the WebDatabase to be saved.
TEST_F(AutocompleteHistoryManagerTest, SSNValue) {
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.method = ASCIIToUTF16("POST");
form.origin = GURL("http://myform.com/form.html");
form.action = GURL("http://myform.com/submit.html");
webkit_glue::FormField ssn(ASCIIToUTF16("Social Security Number"),
ASCIIToUTF16("ssn"),
ASCIIToUTF16("078-05-1120"),
ASCIIToUTF16("text"),
20);
form.fields.push_back(ssn);
EXPECT_CALL(*web_data_service_, AddFormFields(_)).Times(0);
autocomplete_manager_->FormSubmitted(form);
}
<commit_msg>Unittest fix. Need to put usersubmitted = true for unittests.<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 <vector>
#include "base/ref_counted.h"
#include "base/string16.h"
#include "base/task.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/autocomplete_history_manager.h"
#include "chrome/browser/webdata/web_data_service.h"
#include "chrome/test/testing_profile.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/glue/form_data.h"
using testing::_;
using webkit_glue::FormData;
class MockWebDataService : public WebDataService {
public:
MOCK_METHOD1(AddFormFields,
void(const std::vector<webkit_glue::FormField>&)); // NOLINT
};
class AutocompleteHistoryManagerTest : public testing::Test {
protected:
AutocompleteHistoryManagerTest()
: ui_thread_(ChromeThread::UI, &message_loop_) {
}
virtual void SetUp() {
web_data_service_ = new MockWebDataService();
autocomplete_manager_.reset(
new AutocompleteHistoryManager(&profile_, web_data_service_));
}
MessageLoopForUI message_loop_;
ChromeThread ui_thread_;
TestingProfile profile_;
scoped_refptr<MockWebDataService> web_data_service_;
scoped_ptr<AutocompleteHistoryManager> autocomplete_manager_;
};
// Tests that credit card numbers are not sent to the WebDatabase to be saved.
TEST_F(AutocompleteHistoryManagerTest, CreditCardNumberValue) {
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.method = ASCIIToUTF16("POST");
form.origin = GURL("http://myform.com/form.html");
form.action = GURL("http://myform.com/submit.html");
form.user_submitted = true;
// Valid Visa credit card number pulled from the paypal help site.
webkit_glue::FormField valid_cc(ASCIIToUTF16("Credit Card"),
ASCIIToUTF16("ccnum"),
ASCIIToUTF16("4012888888881881"),
ASCIIToUTF16("text"),
20);
form.fields.push_back(valid_cc);
EXPECT_CALL(*web_data_service_, AddFormFields(_)).Times(0);
autocomplete_manager_->FormSubmitted(form);
}
// Contrary test to AutocompleteHistoryManagerTest.CreditCardNumberValue. The
// value being submitted is not a valid credit card number, so it will be sent
// to the WebDatabase to be saved.
TEST_F(AutocompleteHistoryManagerTest, NonCreditCardNumberValue) {
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.method = ASCIIToUTF16("POST");
form.origin = GURL("http://myform.com/form.html");
form.action = GURL("http://myform.com/submit.html");
form.user_submitted = true;
// Invalid credit card number.
webkit_glue::FormField invalid_cc(ASCIIToUTF16("Credit Card"),
ASCIIToUTF16("ccnum"),
ASCIIToUTF16("4580123456789012"),
ASCIIToUTF16("text"),
20);
form.fields.push_back(invalid_cc);
EXPECT_CALL(*(web_data_service_.get()), AddFormFields(_)).Times(1);
autocomplete_manager_->FormSubmitted(form);
}
// Tests that SSNs are not sent to the WebDatabase to be saved.
TEST_F(AutocompleteHistoryManagerTest, SSNValue) {
FormData form;
form.name = ASCIIToUTF16("MyForm");
form.method = ASCIIToUTF16("POST");
form.origin = GURL("http://myform.com/form.html");
form.action = GURL("http://myform.com/submit.html");
form.user_submitted = true;
webkit_glue::FormField ssn(ASCIIToUTF16("Social Security Number"),
ASCIIToUTF16("ssn"),
ASCIIToUTF16("078-05-1120"),
ASCIIToUTF16("text"),
20);
form.fields.push_back(ssn);
EXPECT_CALL(*web_data_service_, AddFormFields(_)).Times(0);
autocomplete_manager_->FormSubmitted(form);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: accessiblecomponenthelper.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 02:24:35 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
#define COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECOMPONENT_HPP_
#include <com/sun/star/accessibility/XAccessibleComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEXTENDEDCOMPONENT_HPP_
#include <com/sun/star/accessibility/XAccessibleExtendedComponent.hpp>
#endif
#ifndef COMPHELPER_ACCESSIBLE_CONTEXT_HELPER_HXX
#include <comphelper/accessiblecontexthelper.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include "comphelper/comphelperdllapi.h"
#endif
//.........................................................................
namespace comphelper
{
//.........................................................................
//=====================================================================
//= OCommonAccessibleComponent
//=====================================================================
/** base class encapsulating common functionality for the helper classes implementing
the XAccessibleComponent respectively XAccessibleExtendendComponent
*/
class COMPHELPER_DLLPUBLIC OCommonAccessibleComponent : public OAccessibleContextHelper
{
protected:
OCommonAccessibleComponent();
/// see the respective base class ctor for an extensive comment on this, please
OCommonAccessibleComponent( IMutex* _pExternalLock );
~OCommonAccessibleComponent();
protected:
/// implements the calculation of the bounding rectangle - still waiting to be overwritten
virtual ::com::sun::star::awt::Rectangle SAL_CALL implGetBounds( ) throw (::com::sun::star::uno::RuntimeException) = 0;
protected:
/** non-virtual versions of the methods which can be implemented using <method>implGetBounds</method>
note: getLocationOnScreen relies on a valid parent (XAccessibleContext::getParent()->getAccessibleContext()),
which itself implements XAccessibleComponent
*/
sal_Bool SAL_CALL containsPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::awt::Point SAL_CALL getLocation( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::awt::Point SAL_CALL getLocationOnScreen( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::awt::Size SAL_CALL getSize( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::awt::Rectangle SAL_CALL getBounds( ) throw (::com::sun::star::uno::RuntimeException);
};
//=====================================================================
//= OAccessibleComponentHelper
//=====================================================================
struct OAccessibleComponentHelper_Base :
public ::cppu::ImplHelper1< ::com::sun::star::accessibility::XAccessibleComponent >
{};
/** a helper class for implementing an AccessibleContext which at the same time
supports an XAccessibleComponent interface.
*/
class COMPHELPER_DLLPUBLIC OAccessibleComponentHelper
:public OCommonAccessibleComponent
,public OAccessibleComponentHelper_Base
{
protected:
OAccessibleComponentHelper( );
/// see the respective base class ctor for an extensive comment on this, please
OAccessibleComponentHelper( IMutex* _pExternalLock );
public:
// XInterface
DECLARE_XINTERFACE( )
DECLARE_XTYPEPROVIDER( )
// XAccessibleComponent - default implementations
virtual sal_Bool SAL_CALL containsPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Point SAL_CALL getLocation( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Size SAL_CALL getSize( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds( ) throw (::com::sun::star::uno::RuntimeException);
};
//=====================================================================
//= OAccessibleExtendedComponentHelper
//=====================================================================
typedef ::cppu::ImplHelper1 < ::com::sun::star::accessibility::XAccessibleExtendedComponent
> OAccessibleExtendedComponentHelper_Base;
/** a helper class for implementing an AccessibleContext which at the same time
supports an XAccessibleExtendedComponent interface.
*/
class COMPHELPER_DLLPUBLIC OAccessibleExtendedComponentHelper
:public OCommonAccessibleComponent
,public OAccessibleExtendedComponentHelper_Base
{
protected:
OAccessibleExtendedComponentHelper( );
/// see the respective base class ctor for an extensive comment on this, please
OAccessibleExtendedComponentHelper( IMutex* _pExternalLock );
public:
// XInterface
DECLARE_XINTERFACE( )
DECLARE_XTYPEPROVIDER( )
// XAccessibleComponent - default implementations
virtual sal_Bool SAL_CALL containsPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Point SAL_CALL getLocation( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Size SAL_CALL getSize( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds( ) throw (::com::sun::star::uno::RuntimeException);
};
//.........................................................................
} // namespace comphelper
//.........................................................................
#endif // COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.6.246); FILE MERGED 2008/04/01 15:05:17 thb 1.6.246.3: #i85898# Stripping all external header guards 2008/04/01 12:26:23 thb 1.6.246.2: #i85898# Stripping all external header guards 2008/03/31 12:19:26 rt 1.6.246.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: accessiblecomponenthelper.hxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
#define COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
#include <com/sun/star/accessibility/XAccessibleComponent.hpp>
#include <com/sun/star/accessibility/XAccessibleExtendedComponent.hpp>
#include <comphelper/accessiblecontexthelper.hxx>
#include <cppuhelper/implbase1.hxx>
#include <comphelper/uno3.hxx>
#include "comphelper/comphelperdllapi.h"
//.........................................................................
namespace comphelper
{
//.........................................................................
//=====================================================================
//= OCommonAccessibleComponent
//=====================================================================
/** base class encapsulating common functionality for the helper classes implementing
the XAccessibleComponent respectively XAccessibleExtendendComponent
*/
class COMPHELPER_DLLPUBLIC OCommonAccessibleComponent : public OAccessibleContextHelper
{
protected:
OCommonAccessibleComponent();
/// see the respective base class ctor for an extensive comment on this, please
OCommonAccessibleComponent( IMutex* _pExternalLock );
~OCommonAccessibleComponent();
protected:
/// implements the calculation of the bounding rectangle - still waiting to be overwritten
virtual ::com::sun::star::awt::Rectangle SAL_CALL implGetBounds( ) throw (::com::sun::star::uno::RuntimeException) = 0;
protected:
/** non-virtual versions of the methods which can be implemented using <method>implGetBounds</method>
note: getLocationOnScreen relies on a valid parent (XAccessibleContext::getParent()->getAccessibleContext()),
which itself implements XAccessibleComponent
*/
sal_Bool SAL_CALL containsPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::awt::Point SAL_CALL getLocation( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::awt::Point SAL_CALL getLocationOnScreen( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::awt::Size SAL_CALL getSize( ) throw (::com::sun::star::uno::RuntimeException);
::com::sun::star::awt::Rectangle SAL_CALL getBounds( ) throw (::com::sun::star::uno::RuntimeException);
};
//=====================================================================
//= OAccessibleComponentHelper
//=====================================================================
struct OAccessibleComponentHelper_Base :
public ::cppu::ImplHelper1< ::com::sun::star::accessibility::XAccessibleComponent >
{};
/** a helper class for implementing an AccessibleContext which at the same time
supports an XAccessibleComponent interface.
*/
class COMPHELPER_DLLPUBLIC OAccessibleComponentHelper
:public OCommonAccessibleComponent
,public OAccessibleComponentHelper_Base
{
protected:
OAccessibleComponentHelper( );
/// see the respective base class ctor for an extensive comment on this, please
OAccessibleComponentHelper( IMutex* _pExternalLock );
public:
// XInterface
DECLARE_XINTERFACE( )
DECLARE_XTYPEPROVIDER( )
// XAccessibleComponent - default implementations
virtual sal_Bool SAL_CALL containsPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Point SAL_CALL getLocation( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Size SAL_CALL getSize( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds( ) throw (::com::sun::star::uno::RuntimeException);
};
//=====================================================================
//= OAccessibleExtendedComponentHelper
//=====================================================================
typedef ::cppu::ImplHelper1 < ::com::sun::star::accessibility::XAccessibleExtendedComponent
> OAccessibleExtendedComponentHelper_Base;
/** a helper class for implementing an AccessibleContext which at the same time
supports an XAccessibleExtendedComponent interface.
*/
class COMPHELPER_DLLPUBLIC OAccessibleExtendedComponentHelper
:public OCommonAccessibleComponent
,public OAccessibleExtendedComponentHelper_Base
{
protected:
OAccessibleExtendedComponentHelper( );
/// see the respective base class ctor for an extensive comment on this, please
OAccessibleExtendedComponentHelper( IMutex* _pExternalLock );
public:
// XInterface
DECLARE_XINTERFACE( )
DECLARE_XTYPEPROVIDER( )
// XAccessibleComponent - default implementations
virtual sal_Bool SAL_CALL containsPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Point SAL_CALL getLocation( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Size SAL_CALL getSize( ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::awt::Rectangle SAL_CALL getBounds( ) throw (::com::sun::star::uno::RuntimeException);
};
//.........................................................................
} // namespace comphelper
//.........................................................................
#endif // COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "op_spreadsheet.hxx"
#include "formulagroup.hxx"
#include "document.hxx"
#include "formulacell.hxx"
#include "tokenarray.hxx"
#include "compiler.hxx"
#include "interpre.hxx"
#include <formula/vectortoken.hxx>
#include <sstream>
using namespace formula;
namespace sc { namespace opencl {
void OpVLookup::GenSlidingWindowFunction(std::stringstream &ss,
const std::string &sSymName, SubArguments &vSubArguments)
{
ss << "\ndouble " << sSymName;
ss << "_"<< BinFuncName() <<"(";
for (unsigned i = 0; i < vSubArguments.size(); i++)
{
if (i)
ss << ",";
vSubArguments[i]->GenSlidingWindowDecl(ss);
}
ss << ")\n {\n";
ss << " int gid0=get_global_id(0);\n";
ss << " double tmp = NAN;\n";
ss << " double intermediate = DBL_MAX;\n";
ss << " int singleIndex = gid0;\n";
ss << " int rowNum = -1;\n";
GenTmpVariables(ss,vSubArguments);
int arg=0;
CheckSubArgumentIsNan(ss,vSubArguments,arg++);
int secondParaWidth = 1;
if(vSubArguments[1]->GetFormulaToken()->GetType() ==
formula::svDoubleVectorRef)
{
FormulaToken *tmpCur = vSubArguments[1]->GetFormulaToken();
const formula::DoubleVectorRefToken*pCurDVR= static_cast<const
formula::DoubleVectorRefToken *>(tmpCur);
secondParaWidth = pCurDVR->GetArrays().size();
}
arg+=secondParaWidth;
CheckSubArgumentIsNan(ss,vSubArguments,arg++);
if(vSubArguments.size() == (unsigned int)(3+(secondParaWidth-1)))
{
ss << " double tmp";
ss << 3+(secondParaWidth-1);
ss << "= 1;\n";
}
else
{
CheckSubArgumentIsNan(ss,vSubArguments,arg++);
}
if(vSubArguments[1]->GetFormulaToken()->GetType() ==
formula::svDoubleVectorRef)
{
FormulaToken *tmpCur = vSubArguments[1]->GetFormulaToken();
const formula::DoubleVectorRefToken*pCurDVR= static_cast<const
formula::DoubleVectorRefToken *>(tmpCur);
size_t nCurWindowSize = pCurDVR->GetArrayLength() <
pCurDVR->GetRefRowSize() ? pCurDVR->GetArrayLength():
pCurDVR->GetRefRowSize() ;
int unrollSize = 8;
ss << " int loop;\n";
if (!pCurDVR->IsStartFixed() && pCurDVR->IsEndFixed()) {
ss << " loop = ("<<nCurWindowSize<<" - gid0)/";
ss << unrollSize<<";\n";
} else if (pCurDVR->IsStartFixed() && !pCurDVR->IsEndFixed()) {
ss << " loop = ("<<nCurWindowSize<<" + gid0)/";
ss << unrollSize<<";\n";
} else {
ss << " loop = "<<nCurWindowSize<<"/"<< unrollSize<<";\n";
}
for(int i=0;i<secondParaWidth;i++)
{
ss << " for ( int j = 0;j< loop; j++)\n";
ss << " {\n";
ss << " int i = ";
if (!pCurDVR->IsStartFixed()&& pCurDVR->IsEndFixed()) {
ss << "gid0 + j * "<< unrollSize <<";\n";
}else {
ss << "j * "<< unrollSize <<";\n";
}
if(!pCurDVR->IsStartFixed() && !pCurDVR->IsEndFixed())
{
ss << " int doubleIndex = i+gid0;\n";
}else
{
ss << " int doubleIndex = i;\n";
}
ss << " if(tmp";
ss << 3+(secondParaWidth-1);
ss << " == 1)\n";
ss << " {\n";
for(int j =0;j < unrollSize;j++)
{
CheckSubArgumentIsNan(ss,vSubArguments,1+i);
ss << " if((tmp0 - tmp";
ss << 1+i;
ss << ")>=0 && intermediate > ( tmp0 -tmp";
ss << 1+i;
ss << "))\n";
ss << " {\n";
ss << " rowNum = doubleIndex;\n";
ss << " intermediate = tmp0 - tmp";
ss << 1+i;
ss << ";\n";
ss << " }\n";
ss << " i++;\n";
ss << " doubleIndex++;\n";
}
ss << " }else\n";
ss << " {\n";
for(int j =0;j < unrollSize;j++)
{
CheckSubArgumentIsNan(ss,vSubArguments,1+i);
ss << " if(tmp0 == tmp";
ss << 1+i;
ss << " && rowNum == -1)\n";
ss << " {\n";
ss << " rowNum = doubleIndex;\n";
ss << " }\n";
ss << " i++;\n";
ss << " doubleIndex++;\n";
}
ss << " }\n\n";
ss << " }\n";
ss << " if(rowNum!=-1)\n";
ss << " {\n";
for(int j=0;j< secondParaWidth; j++)
{
ss << " if(tmp";
ss << 2+(secondParaWidth-1);
ss << " == ";
ss << j+1;
ss << ")\n";
if( !(vSubArguments[1+j]->IsMixedArgument()))
{
ss << "{";
ss << " tmp = ";
vSubArguments[1+j]->GenDeclRef(ss);
ss << "[rowNum];\n";
ss << "}";
}
else
{
ss << "{";
ss << " tmp = isNan(";
vSubArguments[1+j]->GenNumDeclRef(ss);
ss << "[rowNum])?";
vSubArguments[1+j]->GenNumDeclRef(ss);
ss << "[rowNum]:";
vSubArguments[1+j]->GenStringDeclRef(ss);
ss << "[rowNum];\n";
ss << "}";
}
}
ss << " return tmp;\n";
ss << " }\n";
ss << " for (int i = ";
if (!pCurDVR->IsStartFixed() && pCurDVR->IsEndFixed()) {
ss << "gid0 + loop *"<<unrollSize<<"; i < ";
ss << nCurWindowSize <<"; i++)\n";
} else if (pCurDVR->IsStartFixed() && !pCurDVR->IsEndFixed()) {
ss << "0 + loop *"<<unrollSize<<"; i < gid0+";
ss << nCurWindowSize <<"; i++)\n";
} else {
ss << "0 + loop *"<<unrollSize<<"; i < ";
ss << nCurWindowSize <<"; i++)\n";
}
ss << " {\n";
if(!pCurDVR->IsStartFixed() && !pCurDVR->IsEndFixed())
{
ss << " int doubleIndex = i+gid0;\n";
}else
{
ss << " int doubleIndex = i;\n";
}
CheckSubArgumentIsNan(ss,vSubArguments,1+i);
ss << " if(tmp";
ss << 3+(secondParaWidth-1);
ss << " == 1)\n";
ss << " {\n";
ss << " if((tmp0 - tmp";
ss << 1+i;
ss << ")>=0 && intermediate > ( tmp0 -tmp";
ss << 1+i;
ss << "))\n";
ss << " {\n";
ss << " rowNum = doubleIndex;\n";
ss << " intermediate = tmp0 - tmp";
ss << 1+i;
ss << ";\n";
ss << " }\n";
ss << " }else\n";
ss << " {\n";
ss << " if(tmp0 == tmp";
ss << 1+i;
ss << " && rowNum == -1)\n";
ss << " {\n";
ss << " rowNum = doubleIndex;\n";
ss << " }\n";
ss << " }\n";
ss << " }\n\n";
ss << " if(rowNum!=-1)\n";
ss << " {\n";
for(int j=0;j< secondParaWidth; j++)
{
ss << " if(tmp";
ss << 2+(secondParaWidth-1);
ss << " == ";
ss << j+1;
ss << ")\n";
///Add MixedArguments for string support in Vlookup.
if( !(vSubArguments[1+j]->IsMixedArgument()))
{
ss << " tmp = ";
vSubArguments[1+j]->GenDeclRef(ss);
ss << "[rowNum];\n";
}
else
{
ss << " tmp = isNan(";
vSubArguments[1+j]->GenNumDeclRef(ss);
ss << "[rowNum])?";
vSubArguments[1+j]->GenNumDeclRef(ss);
ss << "[rowNum]:";
vSubArguments[1+j]->GenStringDeclRef(ss);
ss << "[rowNum];\n";
}
}
ss << " return tmp;\n";
ss << " }\n";
}
}
else
{
CheckSubArgumentIsNan(ss,vSubArguments,1);
ss << " if(tmp3 == 1)\n";
ss << " {\n";
ss << " tmp = tmp1;\n";
ss << " }else\n";
ss << " {\n";
ss << " if(tmp0 == tmp1)\n";
ss << " tmp = tmp1;\n";
ss << " }\n";
}
ss << " return tmp;\n";
ss << "}";
}
}}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Indent the generated OpenCL a bit saner<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "op_spreadsheet.hxx"
#include "formulagroup.hxx"
#include "document.hxx"
#include "formulacell.hxx"
#include "tokenarray.hxx"
#include "compiler.hxx"
#include "interpre.hxx"
#include <formula/vectortoken.hxx>
#include <sstream>
using namespace formula;
namespace sc { namespace opencl {
void OpVLookup::GenSlidingWindowFunction(std::stringstream &ss,
const std::string &sSymName, SubArguments &vSubArguments)
{
ss << "\ndouble " << sSymName;
ss << "_"<< BinFuncName() <<"(";
for (unsigned i = 0; i < vSubArguments.size(); i++)
{
if (i)
ss << ",";
vSubArguments[i]->GenSlidingWindowDecl(ss);
}
ss << ")\n {\n";
ss << " int gid0=get_global_id(0);\n";
ss << " double tmp = NAN;\n";
ss << " double intermediate = DBL_MAX;\n";
ss << " int singleIndex = gid0;\n";
ss << " int rowNum = -1;\n";
GenTmpVariables(ss,vSubArguments);
int arg=0;
CheckSubArgumentIsNan(ss,vSubArguments,arg++);
int secondParaWidth = 1;
if(vSubArguments[1]->GetFormulaToken()->GetType() ==
formula::svDoubleVectorRef)
{
FormulaToken *tmpCur = vSubArguments[1]->GetFormulaToken();
const formula::DoubleVectorRefToken*pCurDVR= static_cast<const
formula::DoubleVectorRefToken *>(tmpCur);
secondParaWidth = pCurDVR->GetArrays().size();
}
arg+=secondParaWidth;
CheckSubArgumentIsNan(ss,vSubArguments,arg++);
if(vSubArguments.size() == (unsigned int)(3+(secondParaWidth-1)))
{
ss << " double tmp";
ss << 3+(secondParaWidth-1);
ss << "= 1;\n";
}
else
{
CheckSubArgumentIsNan(ss,vSubArguments,arg++);
}
if(vSubArguments[1]->GetFormulaToken()->GetType() ==
formula::svDoubleVectorRef)
{
FormulaToken *tmpCur = vSubArguments[1]->GetFormulaToken();
const formula::DoubleVectorRefToken*pCurDVR= static_cast<const
formula::DoubleVectorRefToken *>(tmpCur);
size_t nCurWindowSize = pCurDVR->GetArrayLength() <
pCurDVR->GetRefRowSize() ? pCurDVR->GetArrayLength():
pCurDVR->GetRefRowSize() ;
int unrollSize = 8;
ss << " int loop;\n";
if (!pCurDVR->IsStartFixed() && pCurDVR->IsEndFixed()) {
ss << " loop = ("<<nCurWindowSize<<" - gid0)/";
ss << unrollSize<<";\n";
} else if (pCurDVR->IsStartFixed() && !pCurDVR->IsEndFixed()) {
ss << " loop = ("<<nCurWindowSize<<" + gid0)/";
ss << unrollSize<<";\n";
} else {
ss << " loop = "<<nCurWindowSize<<"/"<< unrollSize<<";\n";
}
for(int i=0;i<secondParaWidth;i++)
{
ss << " for ( int j = 0;j< loop; j++)\n";
ss << " {\n";
ss << " int i = ";
if (!pCurDVR->IsStartFixed()&& pCurDVR->IsEndFixed()) {
ss << "gid0 + j * "<< unrollSize <<";\n";
}else {
ss << "j * "<< unrollSize <<";\n";
}
if(!pCurDVR->IsStartFixed() && !pCurDVR->IsEndFixed())
{
ss << " int doubleIndex = i+gid0;\n";
}else
{
ss << " int doubleIndex = i;\n";
}
ss << " if(tmp";
ss << 3+(secondParaWidth-1);
ss << " == 1)\n";
ss << " {\n";
for(int j =0;j < unrollSize;j++)
{
CheckSubArgumentIsNan(ss,vSubArguments,1+i);
ss << " if((tmp0 - tmp";
ss << 1+i;
ss << ")>=0 && intermediate > ( tmp0 -tmp";
ss << 1+i;
ss << "))\n";
ss << " {\n";
ss << " rowNum = doubleIndex;\n";
ss << " intermediate = tmp0 - tmp";
ss << 1+i;
ss << ";\n";
ss << " }\n";
ss << " i++;\n";
ss << " doubleIndex++;\n";
}
ss << " }else\n";
ss << " {\n";
for(int j =0;j < unrollSize;j++)
{
CheckSubArgumentIsNan(ss,vSubArguments,1+i);
ss << " if(tmp0 == tmp";
ss << 1+i;
ss << " && rowNum == -1)\n";
ss << " {\n";
ss << " rowNum = doubleIndex;\n";
ss << " }\n";
ss << " i++;\n";
ss << " doubleIndex++;\n";
}
ss << " }\n\n";
ss << " }\n";
ss << " if(rowNum!=-1)\n";
ss << " {\n";
for(int j=0;j< secondParaWidth; j++)
{
ss << " if(tmp";
ss << 2+(secondParaWidth-1);
ss << " == ";
ss << j+1;
ss << ")\n";
if( !(vSubArguments[1+j]->IsMixedArgument()))
{
ss << " {\n";
ss << " tmp = ";
vSubArguments[1+j]->GenDeclRef(ss);
ss << "[rowNum];\n";
ss << " }\n";
}
else
{
ss << " {\n";
ss << " tmp = isNan(";
vSubArguments[1+j]->GenNumDeclRef(ss);
ss << "[rowNum])?";
vSubArguments[1+j]->GenNumDeclRef(ss);
ss << "[rowNum]:";
vSubArguments[1+j]->GenStringDeclRef(ss);
ss << "[rowNum];\n";
ss << " }\n";
}
}
ss << " return tmp;\n";
ss << " }\n";
ss << " for (int i = ";
if (!pCurDVR->IsStartFixed() && pCurDVR->IsEndFixed()) {
ss << "gid0 + loop *"<<unrollSize<<"; i < ";
ss << nCurWindowSize <<"; i++)\n";
} else if (pCurDVR->IsStartFixed() && !pCurDVR->IsEndFixed()) {
ss << "0 + loop *"<<unrollSize<<"; i < gid0+";
ss << nCurWindowSize <<"; i++)\n";
} else {
ss << "0 + loop *"<<unrollSize<<"; i < ";
ss << nCurWindowSize <<"; i++)\n";
}
ss << " {\n";
if(!pCurDVR->IsStartFixed() && !pCurDVR->IsEndFixed())
{
ss << " int doubleIndex = i+gid0;\n";
}else
{
ss << " int doubleIndex = i;\n";
}
CheckSubArgumentIsNan(ss,vSubArguments,1+i);
ss << " if(tmp";
ss << 3+(secondParaWidth-1);
ss << " == 1)\n";
ss << " {\n";
ss << " if((tmp0 - tmp";
ss << 1+i;
ss << ")>=0 && intermediate > ( tmp0 -tmp";
ss << 1+i;
ss << "))\n";
ss << " {\n";
ss << " rowNum = doubleIndex;\n";
ss << " intermediate = tmp0 - tmp";
ss << 1+i;
ss << ";\n";
ss << " }\n";
ss << " }\n";
ss << " else\n";
ss << " {\n";
ss << " if(tmp0 == tmp";
ss << 1+i;
ss << " && rowNum == -1)\n";
ss << " {\n";
ss << " rowNum = doubleIndex;\n";
ss << " }\n";
ss << " }\n";
ss << " }\n\n";
ss << " if(rowNum!=-1)\n";
ss << " {\n";
for(int j=0;j< secondParaWidth; j++)
{
ss << " if(tmp";
ss << 2+(secondParaWidth-1);
ss << " == ";
ss << j+1;
ss << ")\n";
///Add MixedArguments for string support in Vlookup.
if( !(vSubArguments[1+j]->IsMixedArgument()))
{
ss << " tmp = ";
vSubArguments[1+j]->GenDeclRef(ss);
ss << "[rowNum];\n";
}
else
{
ss << " tmp = isNan(";
vSubArguments[1+j]->GenNumDeclRef(ss);
ss << "[rowNum])?";
vSubArguments[1+j]->GenNumDeclRef(ss);
ss << "[rowNum]:";
vSubArguments[1+j]->GenStringDeclRef(ss);
ss << "[rowNum];\n";
}
}
ss << " return tmp;\n";
ss << " }\n";
}
}
else
{
CheckSubArgumentIsNan(ss,vSubArguments,1);
ss << " if(tmp3 == 1)\n";
ss << " {\n";
ss << " tmp = tmp1;\n";
ss << " }else\n";
ss << " {\n";
ss << " if(tmp0 == tmp1)\n";
ss << " tmp = tmp1;\n";
ss << " }\n";
}
ss << " return tmp;\n";
ss << "}";
}
}}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: http://www.qt-project.org/
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**************************************************************************/
#include "nodeinstanceserverinterface.h"
#include <qmetatype.h>
#include "propertyabstractcontainer.h"
#include "propertyvaluecontainer.h"
#include "propertybindingcontainer.h"
#include "instancecontainer.h"
#include "createinstancescommand.h"
#include "createscenecommand.h"
#include "changevaluescommand.h"
#include "changebindingscommand.h"
#include "changeauxiliarycommand.h"
#include "changefileurlcommand.h"
#include "removeinstancescommand.h"
#include "clearscenecommand.h"
#include "removepropertiescommand.h"
#include "reparentinstancescommand.h"
#include "changeidscommand.h"
#include "changestatecommand.h"
#include "completecomponentcommand.h"
#include "addimportcontainer.h"
#include "changenodesourcecommand.h"
#include "informationchangedcommand.h"
#include "pixmapchangedcommand.h"
#include "valueschangedcommand.h"
#include "childrenchangedcommand.h"
#include "imagecontainer.h"
#include "statepreviewimagechangedcommand.h"
#include "componentcompletedcommand.h"
#include "synchronizecommand.h"
#include "tokencommand.h"
#include "removesharedmemorycommand.h"
#include "endpuppetcommand.h"
namespace QmlDesigner {
static bool isRegistered=false;
NodeInstanceServerInterface::NodeInstanceServerInterface(QObject *parent) :
QObject(parent)
{
registerCommands();
}
void NodeInstanceServerInterface::registerCommands()
{
if (isRegistered)
return;
isRegistered = true;
qRegisterMetaType<CreateInstancesCommand>("CreateInstancesCommand");
qRegisterMetaTypeStreamOperators<CreateInstancesCommand>("CreateInstancesCommand");
qRegisterMetaType<ClearSceneCommand>("ClearSceneCommand");
qRegisterMetaTypeStreamOperators<ClearSceneCommand>("ClearSceneCommand");
qRegisterMetaType<CreateSceneCommand>("CreateSceneCommand");
qRegisterMetaTypeStreamOperators<CreateSceneCommand>("CreateSceneCommand");
qRegisterMetaType<ChangeBindingsCommand>("ChangeBindingsCommand");
qRegisterMetaTypeStreamOperators<ChangeBindingsCommand>("ChangeBindingsCommand");
qRegisterMetaType<ChangeValuesCommand>("ChangeValuesCommand");
qRegisterMetaTypeStreamOperators<ChangeValuesCommand>("ChangeValuesCommand");
qRegisterMetaType<ChangeFileUrlCommand>("ChangeFileUrlCommand");
qRegisterMetaTypeStreamOperators<ChangeFileUrlCommand>("ChangeFileUrlCommand");
qRegisterMetaType<ChangeStateCommand>("ChangeStateCommand");
qRegisterMetaTypeStreamOperators<ChangeStateCommand>("ChangeStateCommand");
qRegisterMetaType<RemoveInstancesCommand>("RemoveInstancesCommand");
qRegisterMetaTypeStreamOperators<RemoveInstancesCommand>("RemoveInstancesCommand");
qRegisterMetaType<RemovePropertiesCommand>("RemovePropertiesCommand");
qRegisterMetaTypeStreamOperators<RemovePropertiesCommand>("RemovePropertiesCommand");
qRegisterMetaType<ReparentInstancesCommand>("ReparentInstancesCommand");
qRegisterMetaTypeStreamOperators<ReparentInstancesCommand>("ReparentInstancesCommand");
qRegisterMetaType<ChangeIdsCommand>("ChangeIdsCommand");
qRegisterMetaTypeStreamOperators<ChangeIdsCommand>("ChangeIdsCommand");
qRegisterMetaType<ChangeStateCommand>("ChangeStateCommand");
qRegisterMetaTypeStreamOperators<ChangeStateCommand>("ChangeStateCommand");
qRegisterMetaType<InformationChangedCommand>("InformationChangedCommand");
qRegisterMetaTypeStreamOperators<InformationChangedCommand>("InformationChangedCommand");
qRegisterMetaType<ValuesChangedCommand>("ValuesChangedCommand");
qRegisterMetaTypeStreamOperators<ValuesChangedCommand>("ValuesChangedCommand");
qRegisterMetaType<PixmapChangedCommand>("PixmapChangedCommand");
qRegisterMetaTypeStreamOperators<PixmapChangedCommand>("PixmapChangedCommand");
qRegisterMetaType<InformationContainer>("InformationContainer");
qRegisterMetaTypeStreamOperators<InformationContainer>("InformationContainer");
qRegisterMetaType<PropertyValueContainer>("PropertyValueContainer");
qRegisterMetaTypeStreamOperators<PropertyValueContainer>("PropertyValueContainer");
qRegisterMetaType<PropertyBindingContainer>("PropertyBindingContainer");
qRegisterMetaTypeStreamOperators<PropertyBindingContainer>("PropertyBindingContainer");
qRegisterMetaType<PropertyAbstractContainer>("PropertyAbstractContainer");
qRegisterMetaTypeStreamOperators<PropertyAbstractContainer>("PropertyAbstractContainer");
qRegisterMetaType<InstanceContainer>("InstanceContainer");
qRegisterMetaTypeStreamOperators<InstanceContainer>("InstanceContainer");
qRegisterMetaType<IdContainer>("IdContainer");
qRegisterMetaTypeStreamOperators<IdContainer>("IdContainer");
qRegisterMetaType<ChildrenChangedCommand>("ChildrenChangedCommand");
qRegisterMetaTypeStreamOperators<ChildrenChangedCommand>("ChildrenChangedCommand");
qRegisterMetaType<ImageContainer>("ImageContainer");
qRegisterMetaTypeStreamOperators<ImageContainer>("ImageContainer");
qRegisterMetaType<StatePreviewImageChangedCommand>("StatePreviewImageChangedCommand");
qRegisterMetaTypeStreamOperators<StatePreviewImageChangedCommand>("StatePreviewImageChangedCommand");
qRegisterMetaType<CompleteComponentCommand>("CompleteComponentCommand");
qRegisterMetaTypeStreamOperators<CompleteComponentCommand>("CompleteComponentCommand");
qRegisterMetaType<ComponentCompletedCommand>("ComponentCompletedCommand");
qRegisterMetaTypeStreamOperators<ComponentCompletedCommand>("ComponentCompletedCommand");
qRegisterMetaType<AddImportContainer>("AddImportContainer");
qRegisterMetaTypeStreamOperators<AddImportContainer>("AddImportContainer");
qRegisterMetaType<SynchronizeCommand>("SynchronizeCommand");
qRegisterMetaTypeStreamOperators<SynchronizeCommand>("SynchronizeCommand");
qRegisterMetaType<ChangeNodeSourceCommand>("ChangeNodeSourceCommand");
qRegisterMetaTypeStreamOperators<ChangeNodeSourceCommand>("ChangeNodeSourceCommand");
qRegisterMetaType<ChangeAuxiliaryCommand>("ChangeAuxiliaryCommand");
qRegisterMetaTypeStreamOperators<ChangeAuxiliaryCommand>("ChangeAuxiliaryCommand");
qRegisterMetaType<TokenCommand>("TokenCommand");
qRegisterMetaTypeStreamOperators<TokenCommand>("TokenCommand");
qRegisterMetaType<RemoveSharedMemoryCommand>("RemoveSharedMemoryCommand");
qRegisterMetaTypeStreamOperators<RemoveSharedMemoryCommand>("RemoveSharedMemoryCommand");
qRegisterMetaType<EndPuppetCommand>("EndPuppetCommand");
qRegisterMetaTypeStreamOperators<EndPuppetCommand>("EndPuppetCommand");
}
}
<commit_msg>QmlDesigner.NodeInstances: Fix type registration<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: http://www.qt-project.org/
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**************************************************************************/
#include "nodeinstanceserverinterface.h"
#include <qmetatype.h>
#include "propertyabstractcontainer.h"
#include "propertyvaluecontainer.h"
#include "propertybindingcontainer.h"
#include "instancecontainer.h"
#include "createinstancescommand.h"
#include "createscenecommand.h"
#include "changevaluescommand.h"
#include "changebindingscommand.h"
#include "changeauxiliarycommand.h"
#include "changefileurlcommand.h"
#include "removeinstancescommand.h"
#include "clearscenecommand.h"
#include "removepropertiescommand.h"
#include "reparentinstancescommand.h"
#include "changeidscommand.h"
#include "changestatecommand.h"
#include "completecomponentcommand.h"
#include "addimportcontainer.h"
#include "changenodesourcecommand.h"
#include "informationchangedcommand.h"
#include "pixmapchangedcommand.h"
#include "valueschangedcommand.h"
#include "childrenchangedcommand.h"
#include "imagecontainer.h"
#include "statepreviewimagechangedcommand.h"
#include "componentcompletedcommand.h"
#include "synchronizecommand.h"
#include "tokencommand.h"
#include "removesharedmemorycommand.h"
#include "endpuppetcommand.h"
namespace QmlDesigner {
static bool isRegistered=false;
NodeInstanceServerInterface::NodeInstanceServerInterface(QObject *parent) :
QObject(parent)
{
registerCommands();
}
void NodeInstanceServerInterface::registerCommands()
{
if (isRegistered)
return;
isRegistered = true;
qRegisterMetaType<CreateInstancesCommand>("CreateInstancesCommand");
qRegisterMetaTypeStreamOperators<CreateInstancesCommand>("CreateInstancesCommand");
qRegisterMetaType<ClearSceneCommand>("ClearSceneCommand");
qRegisterMetaTypeStreamOperators<ClearSceneCommand>("ClearSceneCommand");
qRegisterMetaType<CreateSceneCommand>("CreateSceneCommand");
qRegisterMetaTypeStreamOperators<CreateSceneCommand>("CreateSceneCommand");
qRegisterMetaType<ChangeBindingsCommand>("ChangeBindingsCommand");
qRegisterMetaTypeStreamOperators<ChangeBindingsCommand>("ChangeBindingsCommand");
qRegisterMetaType<ChangeValuesCommand>("ChangeValuesCommand");
qRegisterMetaTypeStreamOperators<ChangeValuesCommand>("ChangeValuesCommand");
qRegisterMetaType<ChangeFileUrlCommand>("ChangeFileUrlCommand");
qRegisterMetaTypeStreamOperators<ChangeFileUrlCommand>("ChangeFileUrlCommand");
qRegisterMetaType<ChangeStateCommand>("ChangeStateCommand");
qRegisterMetaTypeStreamOperators<ChangeStateCommand>("ChangeStateCommand");
qRegisterMetaType<RemoveInstancesCommand>("RemoveInstancesCommand");
qRegisterMetaTypeStreamOperators<RemoveInstancesCommand>("RemoveInstancesCommand");
qRegisterMetaType<RemovePropertiesCommand>("RemovePropertiesCommand");
qRegisterMetaTypeStreamOperators<RemovePropertiesCommand>("RemovePropertiesCommand");
qRegisterMetaType<ReparentInstancesCommand>("ReparentInstancesCommand");
qRegisterMetaTypeStreamOperators<ReparentInstancesCommand>("ReparentInstancesCommand");
qRegisterMetaType<ChangeIdsCommand>("ChangeIdsCommand");
qRegisterMetaTypeStreamOperators<ChangeIdsCommand>("ChangeIdsCommand");
qRegisterMetaType<PropertyAbstractContainer>("PropertyAbstractContainer");
qRegisterMetaTypeStreamOperators<PropertyAbstractContainer>("PropertyAbstractContainer");
qRegisterMetaType<InformationChangedCommand>("InformationChangedCommand");
qRegisterMetaTypeStreamOperators<InformationChangedCommand>("InformationChangedCommand");
qRegisterMetaType<ValuesChangedCommand>("ValuesChangedCommand");
qRegisterMetaTypeStreamOperators<ValuesChangedCommand>("ValuesChangedCommand");
qRegisterMetaType<PixmapChangedCommand>("PixmapChangedCommand");
qRegisterMetaTypeStreamOperators<PixmapChangedCommand>("PixmapChangedCommand");
qRegisterMetaType<InformationContainer>("InformationContainer");
qRegisterMetaTypeStreamOperators<InformationContainer>("InformationContainer");
qRegisterMetaType<PropertyValueContainer>("PropertyValueContainer");
qRegisterMetaTypeStreamOperators<PropertyValueContainer>("PropertyValueContainer");
qRegisterMetaType<PropertyBindingContainer>("PropertyBindingContainer");
qRegisterMetaTypeStreamOperators<PropertyBindingContainer>("PropertyBindingContainer");
qRegisterMetaType<PropertyAbstractContainer>("PropertyAbstractContainer");
qRegisterMetaTypeStreamOperators<PropertyAbstractContainer>("PropertyAbstractContainer");
qRegisterMetaType<InstanceContainer>("InstanceContainer");
qRegisterMetaTypeStreamOperators<InstanceContainer>("InstanceContainer");
qRegisterMetaType<IdContainer>("IdContainer");
qRegisterMetaTypeStreamOperators<IdContainer>("IdContainer");
qRegisterMetaType<ChildrenChangedCommand>("ChildrenChangedCommand");
qRegisterMetaTypeStreamOperators<ChildrenChangedCommand>("ChildrenChangedCommand");
qRegisterMetaType<ImageContainer>("ImageContainer");
qRegisterMetaTypeStreamOperators<ImageContainer>("ImageContainer");
qRegisterMetaType<StatePreviewImageChangedCommand>("StatePreviewImageChangedCommand");
qRegisterMetaTypeStreamOperators<StatePreviewImageChangedCommand>("StatePreviewImageChangedCommand");
qRegisterMetaType<CompleteComponentCommand>("CompleteComponentCommand");
qRegisterMetaTypeStreamOperators<CompleteComponentCommand>("CompleteComponentCommand");
qRegisterMetaType<ComponentCompletedCommand>("ComponentCompletedCommand");
qRegisterMetaTypeStreamOperators<ComponentCompletedCommand>("ComponentCompletedCommand");
qRegisterMetaType<AddImportContainer>("AddImportContainer");
qRegisterMetaTypeStreamOperators<AddImportContainer>("AddImportContainer");
qRegisterMetaType<SynchronizeCommand>("SynchronizeCommand");
qRegisterMetaTypeStreamOperators<SynchronizeCommand>("SynchronizeCommand");
qRegisterMetaType<ChangeNodeSourceCommand>("ChangeNodeSourceCommand");
qRegisterMetaTypeStreamOperators<ChangeNodeSourceCommand>("ChangeNodeSourceCommand");
qRegisterMetaType<ChangeAuxiliaryCommand>("ChangeAuxiliaryCommand");
qRegisterMetaTypeStreamOperators<ChangeAuxiliaryCommand>("ChangeAuxiliaryCommand");
qRegisterMetaType<TokenCommand>("TokenCommand");
qRegisterMetaTypeStreamOperators<TokenCommand>("TokenCommand");
qRegisterMetaType<RemoveSharedMemoryCommand>("RemoveSharedMemoryCommand");
qRegisterMetaTypeStreamOperators<RemoveSharedMemoryCommand>("RemoveSharedMemoryCommand");
qRegisterMetaType<EndPuppetCommand>("EndPuppetCommand");
qRegisterMetaTypeStreamOperators<EndPuppetCommand>("EndPuppetCommand");
}
}
<|endoftext|> |
<commit_before>#include "App.h"
#include "helpers.h"
/* This function pushes data to the uSockets mock */
extern "C" void us_loop_read_mocked_data(struct us_loop *loop, char *data, unsigned int size);
uWS::TemplatedApp<false> *app;
us_listen_socket_t *listenSocket;
extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) {
app = new uWS::TemplatedApp<false>(uWS::App().get("/*", [](auto *res, auto *req) {
/*if (req->getHeader("use_write").length()) {
res->writeStatus("200 OK")->writeHeader("write", "true")->write("Hello");
res->write(" world!");
res->end();
} else */if (req->getQuery().length()) {
res->close();
} else {
res->end("Hello world!");
}
}).post("/*", [](auto *res, auto *req) {
res->onAborted([]() {
});
res->onData([res](std::string_view chunk, bool isEnd) {
if (isEnd) {
res->end(chunk);
}
});
}).listen(9001, [](us_listen_socket_t *listenSocket) {
if (listenSocket) {
std::cout << "Listening on port " << 9001 << std::endl;
::listenSocket = listenSocket;
}
}));
return 0;
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
us_loop_read_mocked_data((struct us_loop *) uWS::Loop::get(), (char *) makePadded(data, size), size);
return 0;
}
<commit_msg>More investigation<commit_after>#include "App.h"
#include "helpers.h"
/* This function pushes data to the uSockets mock */
extern "C" void us_loop_read_mocked_data(struct us_loop *loop, char *data, unsigned int size);
uWS::TemplatedApp<false> *app;
us_listen_socket_t *listenSocket;
extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) {
app = new uWS::TemplatedApp<false>(uWS::App().get("/*", [](auto *res, auto *req) {
if (req->getHeader("use_write").length()) {
res->writeStatus("200 OK")->writeHeader("write", "true")->write("Hello");
res->write(" world!");
res->end();
} else if (req->getQuery().length()) {
res->close();
} else {
res->end("Hello world!");
}
})/*.post("/*", [](auto *res, auto *req) {
res->onAborted([]() {
});
res->onData([res](std::string_view chunk, bool isEnd) {
if (isEnd) {
res->end(chunk);
}
});
})*/.listen(9001, [](us_listen_socket_t *listenSocket) {
if (listenSocket) {
std::cout << "Listening on port " << 9001 << std::endl;
::listenSocket = listenSocket;
}
}));
return 0;
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
us_loop_read_mocked_data((struct us_loop *) uWS::Loop::get(), (char *) makePadded(data, size), size);
return 0;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.