commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
5de403cfda1751154787950694979c8ae172f48f
|
kalarm/repetition.cpp
|
kalarm/repetition.cpp
|
/*
* repetition.cpp - pushbutton and dialogue to specify alarm repetition
* Program: kalarm
* Copyright (c) 2004, 2005 by David Jarvie <[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; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "kalarm.h"
#include <qtimer.h>
#include <QLabel>
#include <QGroupBox>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <kdialog.h>
#include <kseparator.h>
#include <klocale.h>
#include "buttongroup.h"
#include "radiobutton.h"
#include "spinbox.h"
#include "timeperiod.h"
#include "timeselector.h"
#include "repetition.moc"
/*=============================================================================
= Class RepetitionButton
= Button to display the Simple Alarm Repetition dialogue.
=============================================================================*/
RepetitionButton::RepetitionButton(const QString& caption, bool waitForInitialisation, QWidget* parent)
: QPushButton(caption, parent),
mDialog(0),
mInterval(0),
mCount(0),
mMaxDuration(-1),
mDateOnly(false),
mWaitForInit(waitForInitialisation),
mReadOnly(false)
{
connect(this, SIGNAL(clicked()), SLOT(slotPressed()));
}
/******************************************************************************
* Set the data for the dialog.
*/
void RepetitionButton::set(int interval, int count, bool dateOnly, int maxDuration)
{
mInterval = interval;
mCount = count;
mMaxDuration = maxDuration;
mDateOnly = dateOnly;
}
/******************************************************************************
* Create the alarm repetition dialog.
* If 'waitForInitialisation' is true, the dialog won't be displayed until set()
* is called to initialise its data.
*/
void RepetitionButton::activate(bool waitForInitialisation)
{
if (!mDialog)
mDialog = new RepetitionDlg(i18n("Alarm Repetition"), mReadOnly, this);
mDialog->set(mInterval, mCount, mDateOnly, mMaxDuration);
if (waitForInitialisation)
emit needsInitialisation(); // request dialog initialisation
else
displayDialog(); // display the dialog now
}
/******************************************************************************
* Set the data for the dialog and display it.
* To be called only after needsInitialisation() has been emitted.
*/
void RepetitionButton::initialise(int interval, int count, bool dateOnly, int maxDuration)
{
mInterval = interval;
mCount = count;
mMaxDuration = maxDuration;
mDateOnly = dateOnly;
if (mDialog)
{
mDialog->set(interval, count, dateOnly, maxDuration);
displayDialog(); // display the dialog now
}
}
/******************************************************************************
* Display the simple alarm repetition dialog.
* Alarm repetition has the following restrictions:
* 1) Not allowed for a repeat-at-login alarm
* 2) For a date-only alarm, the repeat interval must be a whole number of days.
* 3) The overall repeat duration must be less than the recurrence interval.
*/
void RepetitionButton::displayDialog()
{
if (mReadOnly)
{
mDialog->setReadOnly(true);
mDialog->exec();
}
else if (mDialog->exec() == QDialog::Accepted)
{
mCount = mDialog->count();
mInterval = mDialog->interval();
emit changed();
}
delete mDialog;
mDialog = 0;
}
/*=============================================================================
= Class RepetitionDlg
= Simple alarm repetition dialogue.
* Note that the displayed repetition count is one greater than the value set or
* returned in the external methods.
=============================================================================*/
static const int MAX_COUNT = 9999; // maximum range for count spinbox
RepetitionDlg::RepetitionDlg(const QString& caption, bool readOnly, QWidget* parent, const char* name)
: KDialogBase(parent, name, true, caption, Ok|Cancel),
mMaxDuration(-1),
mDateOnly(false),
mReadOnly(readOnly)
{
int spacing = spacingHint();
QWidget* page = new QWidget(this);
setMainWidget(page);
QVBoxLayout* topLayout = new QVBoxLayout(page);
topLayout->setMargin(0);
topLayout->setSpacing(spacing);
QHBoxLayout* layout = new QHBoxLayout();
layout->setMargin(0);
layout->setSpacing(0);
topLayout->addLayout(layout);
int hintMargin = 2*marginHint();
layout->addSpacing(hintMargin);
QLabel* hintLabel = new QLabel(
i18n("Use this dialog either:\n"
"- instead of the Recurrence tab, or\n"
"- after using the Recurrence tab, to set up a repetition within a repetition."),
page);
hintLabel->setFrameStyle(QFrame::Panel | QFrame::Sunken);
hintLabel->setLineWidth(2);
hintLabel->setMargin(marginHint());
hintLabel->setWordWrap(true);
#warning Wrapping doesn't work
// hintLabel->setTextFormat(Qt::RichText);
layout->addWidget(hintLabel);
layout->addSpacing(hintMargin);
topLayout->addSpacing(spacing);
// Group the other controls together so that the minimum width can be found easily
QWidget* controls = new QWidget(page);
topLayout->addWidget(controls);
topLayout = new QVBoxLayout(controls);
topLayout->setMargin(0);
topLayout->setSpacing(spacing);
mTimeSelector = new TimeSelector(i18n("Repeat every 10 minutes", "&Repeat every"), QString(),
i18n("Check to repeat the alarm each time it recurs. "
"Instead of the alarm triggering once at each recurrence, "
"this option makes the alarm trigger multiple times at each recurrence."),
i18n("Enter the time between repetitions of the alarm"),
true, controls);
mTimeSelector->setFixedSize(mTimeSelector->sizeHint());
connect(mTimeSelector, SIGNAL(valueChanged(int)), SLOT(intervalChanged(int)));
connect(mTimeSelector, SIGNAL(toggled(bool)), SLOT(repetitionToggled(bool)));
topLayout->addWidget(mTimeSelector, 0, Qt::AlignLeft);
mButtonBox = new QGroupBox(controls);
topLayout->addWidget(mButtonBox);
mButtonGroup = new ButtonGroup(mButtonBox);
connect(mButtonGroup, SIGNAL(buttonSet(QAbstractButton*)), SLOT(typeClicked()));
QVBoxLayout* vlayout = new QVBoxLayout(mButtonBox);
vlayout->setMargin(marginHint());
vlayout->setSpacing(spacing);
layout = new QHBoxLayout();
layout->setMargin(0);
vlayout->addLayout(layout);
mCountButton = new RadioButton(i18n("&Number of repetitions:"), mButtonBox);
mCountButton->setFixedSize(mCountButton->sizeHint());
mCountButton->setWhatsThis(i18n("Check to specify the number of times the alarm should repeat after each recurrence"));
mButtonGroup->addButton(mCountButton);
layout->addWidget(mCountButton);
mCount = new SpinBox(1, MAX_COUNT, 1, mButtonBox);
mCount->setFixedSize(mCount->sizeHint());
mCount->setSingleShiftStep(10);
mCount->setSelectOnStep(false);
connect(mCount, SIGNAL(valueChanged(int)), SLOT(countChanged(int)));
mCount->setWhatsThis(i18n("Enter the number of times to trigger the alarm after its initial occurrence"));
layout->addWidget(mCount);
mCountButton->setFocusWidget(mCount);
layout->addStretch();
layout = new QHBoxLayout();
layout->setMargin(0);
vlayout->addLayout(layout);
mDurationButton = new RadioButton(i18n("&Duration:"), mButtonBox);
mDurationButton->setFixedSize(mDurationButton->sizeHint());
mDurationButton->setWhatsThis(i18n("Check to specify how long the alarm is to be repeated"));
mButtonGroup->addButton(mDurationButton);
layout->addWidget(mDurationButton);
mDuration = new TimePeriod(true, mButtonBox);
mDuration->setFixedSize(mDuration->sizeHint());
connect(mDuration, SIGNAL(valueChanged(int)), SLOT(durationChanged(int)));
mDuration->setWhatsThis(i18n("Enter the length of time to repeat the alarm"));
layout->addWidget(mDuration);
mDurationButton->setFocusWidget(mDuration);
layout->addStretch();
hintLabel->setMinimumWidth(controls->sizeHint().width() - 2*hintMargin); // this enables a minimum size for the dialogue
mCountButton->setChecked(true);
repetitionToggled(false);
setReadOnly(mReadOnly);
}
/******************************************************************************
* Set the state of all controls to reflect the data in the specified alarm.
*/
void RepetitionDlg::set(int interval, int count, bool dateOnly, int maxDuration)
{
if (!interval)
count = 0;
else if (!count)
interval = 0;
if (dateOnly != mDateOnly)
{
mDateOnly = dateOnly;
mTimeSelector->setDateOnly(mDateOnly);
mDuration->setDateOnly(mDateOnly);
}
mMaxDuration = maxDuration;
if (mMaxDuration)
{
int maxhm = (mMaxDuration > 0) ? mMaxDuration : 9999;
int maxdw = (mMaxDuration > 0) ? mMaxDuration / 1440 : 9999;
mTimeSelector->setMaximum(maxhm, maxdw);
mDuration->setMaximum(maxhm, maxdw);
}
if (!mMaxDuration || !count)
mTimeSelector->setChecked(false);
else
{
TimePeriod::Units units = mDateOnly ? TimePeriod::DAYS : TimePeriod::HOURS_MINUTES;
mTimeSelector->setMinutes(interval, mDateOnly, units);
bool on = mTimeSelector->isChecked();
repetitionToggled(on); // enable/disable controls
if (on)
intervalChanged(interval); // ensure mCount range is set
mCount->setValue(count);
mDuration->setMinutes(count * interval, mDateOnly, units);
mCountButton->setChecked(true);
}
setReadOnly(!mMaxDuration);
}
/******************************************************************************
* Set the read-only status.
*/
void RepetitionDlg::setReadOnly(bool ro)
{
ro = ro || mReadOnly;
mTimeSelector->setReadOnly(ro);
mCountButton->setReadOnly(ro);
mCount->setReadOnly(ro);
mDurationButton->setReadOnly(ro);
mDuration->setReadOnly(ro);
}
/******************************************************************************
* Get the period between repetitions in minutes.
*/
int RepetitionDlg::interval() const
{
return mTimeSelector->minutes();
}
/******************************************************************************
* Set the entered repeat count.
*/
int RepetitionDlg::count() const
{
int interval = mTimeSelector->minutes();
if (interval)
{
if (mCountButton->isChecked())
return mCount->value();
if (mDurationButton->isChecked())
return mDuration->minutes() / interval;
}
return 0; // no repetition
}
/******************************************************************************
* Called when the time interval widget has changed value.
* Adjust the maximum repetition count accordingly.
*/
void RepetitionDlg::intervalChanged(int minutes)
{
if (mTimeSelector->isChecked())
{
mCount->setRange(1, (mMaxDuration >= 0 ? mMaxDuration / minutes : MAX_COUNT));
if (mCountButton->isChecked())
countChanged(mCount->value());
else
durationChanged(mDuration->minutes());
}
}
/******************************************************************************
* Called when the count spinbox has changed value.
* Adjust the duration accordingly.
*/
void RepetitionDlg::countChanged(int count)
{
int interval = mTimeSelector->minutes();
if (interval)
{
bool blocked = mDuration->signalsBlocked();
mDuration->blockSignals(true);
mDuration->setMinutes(count * interval, mDateOnly,
(mDateOnly ? TimePeriod::DAYS : TimePeriod::HOURS_MINUTES));
mDuration->blockSignals(blocked);
}
}
/******************************************************************************
* Called when the duration widget has changed value.
* Adjust the count accordingly.
*/
void RepetitionDlg::durationChanged(int minutes)
{
int interval = mTimeSelector->minutes();
if (interval)
{
bool blocked = mCount->signalsBlocked();
mCount->blockSignals(true);
mCount->setValue(minutes / interval);
mCount->blockSignals(blocked);
}
}
/******************************************************************************
* Called when the time period widget is toggled on or off.
*/
void RepetitionDlg::repetitionToggled(bool on)
{
if (mMaxDuration == 0)
on = false;
mButtonBox->setEnabled(on);
mCount->setEnabled(on && mCountButton->isChecked());
mDuration->setEnabled(on && mDurationButton->isChecked());
}
/******************************************************************************
* Called when one of the count or duration radio buttons is toggled.
*/
void RepetitionDlg::typeClicked()
{
if (mTimeSelector->isChecked())
{
mCount->setEnabled(mCountButton->isChecked());
mDuration->setEnabled(mDurationButton->isChecked());
}
}
|
/*
* repetition.cpp - pushbutton and dialogue to specify alarm repetition
* Program: kalarm
* Copyright (c) 2004, 2005 by David Jarvie <[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; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "kalarm.h"
#include <qtimer.h>
#include <QLabel>
#include <QGroupBox>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <kdialog.h>
#include <kseparator.h>
#include <klocale.h>
#include "buttongroup.h"
#include "radiobutton.h"
#include "spinbox.h"
#include "timeperiod.h"
#include "timeselector.h"
#include "repetition.moc"
/*=============================================================================
= Class RepetitionButton
= Button to display the Simple Alarm Repetition dialogue.
=============================================================================*/
RepetitionButton::RepetitionButton(const QString& caption, bool waitForInitialisation, QWidget* parent)
: QPushButton(caption, parent),
mDialog(0),
mInterval(0),
mCount(0),
mMaxDuration(-1),
mDateOnly(false),
mWaitForInit(waitForInitialisation),
mReadOnly(false)
{
connect(this, SIGNAL(clicked()), SLOT(slotPressed()));
}
/******************************************************************************
* Set the data for the dialog.
*/
void RepetitionButton::set(int interval, int count, bool dateOnly, int maxDuration)
{
mInterval = interval;
mCount = count;
mMaxDuration = maxDuration;
mDateOnly = dateOnly;
}
/******************************************************************************
* Create the alarm repetition dialog.
* If 'waitForInitialisation' is true, the dialog won't be displayed until set()
* is called to initialise its data.
*/
void RepetitionButton::activate(bool waitForInitialisation)
{
if (!mDialog)
mDialog = new RepetitionDlg(i18n("Alarm Repetition"), mReadOnly, this);
mDialog->set(mInterval, mCount, mDateOnly, mMaxDuration);
if (waitForInitialisation)
emit needsInitialisation(); // request dialog initialisation
else
displayDialog(); // display the dialog now
}
/******************************************************************************
* Set the data for the dialog and display it.
* To be called only after needsInitialisation() has been emitted.
*/
void RepetitionButton::initialise(int interval, int count, bool dateOnly, int maxDuration)
{
mInterval = interval;
mCount = count;
mMaxDuration = maxDuration;
mDateOnly = dateOnly;
if (mDialog)
{
mDialog->set(interval, count, dateOnly, maxDuration);
displayDialog(); // display the dialog now
}
}
/******************************************************************************
* Display the simple alarm repetition dialog.
* Alarm repetition has the following restrictions:
* 1) Not allowed for a repeat-at-login alarm
* 2) For a date-only alarm, the repeat interval must be a whole number of days.
* 3) The overall repeat duration must be less than the recurrence interval.
*/
void RepetitionButton::displayDialog()
{
if (mReadOnly)
{
mDialog->setReadOnly(true);
mDialog->exec();
}
else if (mDialog->exec() == QDialog::Accepted)
{
mCount = mDialog->count();
mInterval = mDialog->interval();
emit changed();
}
delete mDialog;
mDialog = 0;
}
/*=============================================================================
= Class RepetitionDlg
= Simple alarm repetition dialogue.
* Note that the displayed repetition count is one greater than the value set or
* returned in the external methods.
=============================================================================*/
static const int MAX_COUNT = 9999; // maximum range for count spinbox
RepetitionDlg::RepetitionDlg(const QString& caption, bool readOnly, QWidget* parent, const char* name)
: KDialogBase(parent, name, true, caption, Ok|Cancel),
mMaxDuration(-1),
mDateOnly(false),
mReadOnly(readOnly)
{
int spacing = spacingHint();
QWidget* page = new QWidget(this);
setMainWidget(page);
QVBoxLayout* topLayout = new QVBoxLayout(page);
topLayout->setMargin(0);
topLayout->setSpacing(spacing);
QHBoxLayout* layout = new QHBoxLayout();
layout->setMargin(0);
layout->setSpacing(0);
topLayout->addLayout(layout);
int hintMargin = 2*marginHint();
layout->addSpacing(hintMargin);
QLabel* hintLabel = new QLabel(
i18n("Use this dialog either:\n"
"- instead of the Recurrence tab, or\n"
"- after using the Recurrence tab, to set up a repetition within a repetition."),
page);
hintLabel->setFrameStyle(QFrame::Panel | QFrame::Sunken);
hintLabel->setLineWidth(2);
hintLabel->setMargin(marginHint());
hintLabel->setWordWrap(true);
#warning Wrapping does not work
// hintLabel->setTextFormat(Qt::RichText);
layout->addWidget(hintLabel);
layout->addSpacing(hintMargin);
topLayout->addSpacing(spacing);
// Group the other controls together so that the minimum width can be found easily
QWidget* controls = new QWidget(page);
topLayout->addWidget(controls);
topLayout = new QVBoxLayout(controls);
topLayout->setMargin(0);
topLayout->setSpacing(spacing);
mTimeSelector = new TimeSelector(i18n("Repeat every 10 minutes", "&Repeat every"), QString(),
i18n("Check to repeat the alarm each time it recurs. "
"Instead of the alarm triggering once at each recurrence, "
"this option makes the alarm trigger multiple times at each recurrence."),
i18n("Enter the time between repetitions of the alarm"),
true, controls);
mTimeSelector->setFixedSize(mTimeSelector->sizeHint());
connect(mTimeSelector, SIGNAL(valueChanged(int)), SLOT(intervalChanged(int)));
connect(mTimeSelector, SIGNAL(toggled(bool)), SLOT(repetitionToggled(bool)));
topLayout->addWidget(mTimeSelector, 0, Qt::AlignLeft);
mButtonBox = new QGroupBox(controls);
topLayout->addWidget(mButtonBox);
mButtonGroup = new ButtonGroup(mButtonBox);
connect(mButtonGroup, SIGNAL(buttonSet(QAbstractButton*)), SLOT(typeClicked()));
QVBoxLayout* vlayout = new QVBoxLayout(mButtonBox);
vlayout->setMargin(marginHint());
vlayout->setSpacing(spacing);
layout = new QHBoxLayout();
layout->setMargin(0);
vlayout->addLayout(layout);
mCountButton = new RadioButton(i18n("&Number of repetitions:"), mButtonBox);
mCountButton->setFixedSize(mCountButton->sizeHint());
mCountButton->setWhatsThis(i18n("Check to specify the number of times the alarm should repeat after each recurrence"));
mButtonGroup->addButton(mCountButton);
layout->addWidget(mCountButton);
mCount = new SpinBox(1, MAX_COUNT, 1, mButtonBox);
mCount->setFixedSize(mCount->sizeHint());
mCount->setSingleShiftStep(10);
mCount->setSelectOnStep(false);
connect(mCount, SIGNAL(valueChanged(int)), SLOT(countChanged(int)));
mCount->setWhatsThis(i18n("Enter the number of times to trigger the alarm after its initial occurrence"));
layout->addWidget(mCount);
mCountButton->setFocusWidget(mCount);
layout->addStretch();
layout = new QHBoxLayout();
layout->setMargin(0);
vlayout->addLayout(layout);
mDurationButton = new RadioButton(i18n("&Duration:"), mButtonBox);
mDurationButton->setFixedSize(mDurationButton->sizeHint());
mDurationButton->setWhatsThis(i18n("Check to specify how long the alarm is to be repeated"));
mButtonGroup->addButton(mDurationButton);
layout->addWidget(mDurationButton);
mDuration = new TimePeriod(true, mButtonBox);
mDuration->setFixedSize(mDuration->sizeHint());
connect(mDuration, SIGNAL(valueChanged(int)), SLOT(durationChanged(int)));
mDuration->setWhatsThis(i18n("Enter the length of time to repeat the alarm"));
layout->addWidget(mDuration);
mDurationButton->setFocusWidget(mDuration);
layout->addStretch();
hintLabel->setMinimumWidth(controls->sizeHint().width() - 2*hintMargin); // this enables a minimum size for the dialogue
mCountButton->setChecked(true);
repetitionToggled(false);
setReadOnly(mReadOnly);
}
/******************************************************************************
* Set the state of all controls to reflect the data in the specified alarm.
*/
void RepetitionDlg::set(int interval, int count, bool dateOnly, int maxDuration)
{
if (!interval)
count = 0;
else if (!count)
interval = 0;
if (dateOnly != mDateOnly)
{
mDateOnly = dateOnly;
mTimeSelector->setDateOnly(mDateOnly);
mDuration->setDateOnly(mDateOnly);
}
mMaxDuration = maxDuration;
if (mMaxDuration)
{
int maxhm = (mMaxDuration > 0) ? mMaxDuration : 9999;
int maxdw = (mMaxDuration > 0) ? mMaxDuration / 1440 : 9999;
mTimeSelector->setMaximum(maxhm, maxdw);
mDuration->setMaximum(maxhm, maxdw);
}
if (!mMaxDuration || !count)
mTimeSelector->setChecked(false);
else
{
TimePeriod::Units units = mDateOnly ? TimePeriod::DAYS : TimePeriod::HOURS_MINUTES;
mTimeSelector->setMinutes(interval, mDateOnly, units);
bool on = mTimeSelector->isChecked();
repetitionToggled(on); // enable/disable controls
if (on)
intervalChanged(interval); // ensure mCount range is set
mCount->setValue(count);
mDuration->setMinutes(count * interval, mDateOnly, units);
mCountButton->setChecked(true);
}
setReadOnly(!mMaxDuration);
}
/******************************************************************************
* Set the read-only status.
*/
void RepetitionDlg::setReadOnly(bool ro)
{
ro = ro || mReadOnly;
mTimeSelector->setReadOnly(ro);
mCountButton->setReadOnly(ro);
mCount->setReadOnly(ro);
mDurationButton->setReadOnly(ro);
mDuration->setReadOnly(ro);
}
/******************************************************************************
* Get the period between repetitions in minutes.
*/
int RepetitionDlg::interval() const
{
return mTimeSelector->minutes();
}
/******************************************************************************
* Set the entered repeat count.
*/
int RepetitionDlg::count() const
{
int interval = mTimeSelector->minutes();
if (interval)
{
if (mCountButton->isChecked())
return mCount->value();
if (mDurationButton->isChecked())
return mDuration->minutes() / interval;
}
return 0; // no repetition
}
/******************************************************************************
* Called when the time interval widget has changed value.
* Adjust the maximum repetition count accordingly.
*/
void RepetitionDlg::intervalChanged(int minutes)
{
if (mTimeSelector->isChecked())
{
mCount->setRange(1, (mMaxDuration >= 0 ? mMaxDuration / minutes : MAX_COUNT));
if (mCountButton->isChecked())
countChanged(mCount->value());
else
durationChanged(mDuration->minutes());
}
}
/******************************************************************************
* Called when the count spinbox has changed value.
* Adjust the duration accordingly.
*/
void RepetitionDlg::countChanged(int count)
{
int interval = mTimeSelector->minutes();
if (interval)
{
bool blocked = mDuration->signalsBlocked();
mDuration->blockSignals(true);
mDuration->setMinutes(count * interval, mDateOnly,
(mDateOnly ? TimePeriod::DAYS : TimePeriod::HOURS_MINUTES));
mDuration->blockSignals(blocked);
}
}
/******************************************************************************
* Called when the duration widget has changed value.
* Adjust the count accordingly.
*/
void RepetitionDlg::durationChanged(int minutes)
{
int interval = mTimeSelector->minutes();
if (interval)
{
bool blocked = mCount->signalsBlocked();
mCount->blockSignals(true);
mCount->setValue(minutes / interval);
mCount->blockSignals(blocked);
}
}
/******************************************************************************
* Called when the time period widget is toggled on or off.
*/
void RepetitionDlg::repetitionToggled(bool on)
{
if (mMaxDuration == 0)
on = false;
mButtonBox->setEnabled(on);
mCount->setEnabled(on && mCountButton->isChecked());
mDuration->setEnabled(on && mDurationButton->isChecked());
}
/******************************************************************************
* Called when one of the count or duration radio buttons is toggled.
*/
void RepetitionDlg::typeClicked()
{
if (mTimeSelector->isChecked())
{
mCount->setEnabled(mCountButton->isChecked());
mDuration->setEnabled(mDurationButton->isChecked());
}
}
|
Fix message extraction (xgettext does not like the unterminated single quote) (goutte)
|
Fix message extraction
(xgettext does not like the unterminated single quote)
(goutte)
svn path=/trunk/KDE/kdepim/; revision=495302
|
C++
|
lgpl-2.1
|
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
|
0f4b7a84006d4006fa23e715ffe9134413df99e6
|
libtbag/util/TestUtils.hpp
|
libtbag/util/TestUtils.hpp
|
/**
* @file TestUtils.hpp
* @brief Google-test utilities.
* @author zer0
* @date 2016-06-30
* @date 2018-03-24 (Rename: tester/DemoAsset -> libtbag/util/TestUtils)
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_UTIL_TESTUTILS_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_UTIL_TESTUTILS_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/predef.hpp>
#include <libtbag/Noncopyable.hpp>
#include <libtbag/filesystem/TempDirGuard.hpp>
#include <string>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace util {
namespace test {
namespace behaviour {
struct TBAG_API Scenario
{
std::string const NAME;
std::string const TAG;
Scenario(std::string const & name);
Scenario(std::string const & name, std::string const & tag);
~Scenario();
inline operator bool() const TBAG_NOEXCEPT { return true; }
};
struct TBAG_API Given
{
Scenario const & SCENARIO;
std::string const NAME;
Given(Scenario & parent, std::string const & name);
~Given();
inline operator bool() const TBAG_NOEXCEPT { return true; }
};
struct TBAG_API When
{
Given const & GIVEN;
std::string const NAME;
When(Given & parent, std::string const & name);
~When();
inline operator bool() const TBAG_NOEXCEPT { return true; }
};
struct TBAG_API Then
{
When const & WHEN;
std::string const NAME;
Then(When const & parent, std::string const & name);
~Then();
inline operator bool() const TBAG_NOEXCEPT { return true; }
};
#define TBAG_SCENARIO_NAME __require_scenario__
#define TBAG_GIVEN_NAME __require_given__
#define TBAG_WHEN_NAME __require_when__
#define TBAG_THEN_NAME __require_then__
#ifndef TBAG_SCENARIO
#define TBAG_SCENARIO(.../*name, tag*/) if (auto TBAG_SCENARIO_NAME = ::libtbag::util::test::behaviour::Scenario(__VA_ARGS__))
#endif
#ifndef TBAG_GIVEN
#define TBAG_GIVEN(name) if (auto TBAG_GIVEN_NAME = ::libtbag::util::test::behaviour::Given(TBAG_SCENARIO_NAME, name))
#endif
#ifndef TBAG_WHEN
#define TBAG_WHEN(name) if (auto TBAG_WHEN_NAME = ::libtbag::util::test::behaviour::When(TBAG_GIVEN_NAME, name))
#endif
#ifndef TBAG_THEN
#define TBAG_THEN(name) if (auto TBAG_THEN_NAME = ::libtbag::util::test::behaviour::Then(TBAG_WHEN_NAME, name))
#endif
} // namespace behaviour
} // namespace test
} // namespace util
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#ifndef TBAG_TEST_TEMP_DIR_NAME
#define TBAG_TEST_TEMP_DIR_NAME __tbag_tester_temp_dir__
#endif
/**
* @def TBAG_TEST_TEMP_DIR
* @brief Tbag Test Temp Directory.
*/
#ifndef TBAG_TEST_TEMP_DIR
#define TBAG_TEST_TEMP_DIR(case_name, name, first_create, last_remove) \
::libtbag::filesystem::TempDirGuard TBAG_TEST_TEMP_DIR_NAME( \
case_name, name, first_create, last_remove); \
ASSERT_TRUE(TBAG_TEST_TEMP_DIR_NAME.getDir().isDirectory());
#endif
#ifndef TBAG_TEST_TEMP_DIR2
#define TBAG_TEST_TEMP_DIR2(first_create, last_remove) \
TBAG_TEST_TEMP_DIR(test_info_->test_case_name(), \
test_info_->name(), \
first_create, last_remove)
#endif
/**
* @def TBAG_TEST_TEMP_DIR_GET
* @brief Obtain the current temp directory.
*/
#ifndef TBAG_TEST_TEMP_DIR_GET
#define TBAG_TEST_TEMP_DIR_GET() TBAG_TEST_TEMP_DIR_NAME.getDir()
#endif
#ifndef tttDir
#define tttDir(c, r) TBAG_TEST_TEMP_DIR2(c, r)
#endif
#ifndef tttDir_Automatic
#define tttDir_Automatic() tttDir(true, true)
#endif
#ifndef tttDir_AutoCreate
#define tttDir_AutoCreate() tttDir(true, false)
#endif
#ifndef tttDir_AutoRemove
#define tttDir_AutoRemove() tttDir(false, true)
#endif
#ifndef tttDir_Manually
#define tttDir_Manually() tttDir(false, false)
#endif
#ifndef tttDir_Get
#define tttDir_Get() TBAG_TEST_TEMP_DIR_GET()
#endif
#endif // __INCLUDE_LIBTBAG__LIBTBAG_UTIL_TESTUTILS_HPP__
|
/**
* @file TestUtils.hpp
* @brief Google-test utilities.
* @author zer0
* @date 2016-06-30
* @date 2018-03-24 (Rename: tester/DemoAsset -> libtbag/util/TestUtils)
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_UTIL_TESTUTILS_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_UTIL_TESTUTILS_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/predef.hpp>
#include <libtbag/Noncopyable.hpp>
#include <libtbag/filesystem/TempDirGuard.hpp>
#include <string>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace util {
namespace test {
namespace behaviour {
struct TBAG_API Scenario
{
std::string const NAME;
std::string const TAG;
Scenario(std::string const & name);
Scenario(std::string const & name, std::string const & tag);
~Scenario();
inline operator bool() const TBAG_NOEXCEPT { return true; }
};
struct TBAG_API Given
{
Scenario const & SCENARIO;
std::string const NAME;
Given(Scenario & parent, std::string const & name);
~Given();
inline operator bool() const TBAG_NOEXCEPT { return true; }
};
struct TBAG_API When
{
Given const & GIVEN;
std::string const NAME;
When(Given & parent, std::string const & name);
~When();
inline operator bool() const TBAG_NOEXCEPT { return true; }
};
struct TBAG_API Then
{
When const & WHEN;
std::string const NAME;
Then(When const & parent, std::string const & name);
~Then();
inline operator bool() const TBAG_NOEXCEPT { return true; }
};
#define TBAG_SCENARIO_NAME __require_scenario__
#define TBAG_GIVEN_NAME __require_given__
#define TBAG_WHEN_NAME __require_when__
#define TBAG_THEN_NAME __require_then__
#ifndef TBAG_SCENARIO
#define TBAG_SCENARIO(.../*name, tag*/) if (auto TBAG_SCENARIO_NAME = ::libtbag::util::test::behaviour::Scenario(__VA_ARGS__))
#endif
#ifndef TBAG_GIVEN
#define TBAG_GIVEN(name) if (auto TBAG_GIVEN_NAME = ::libtbag::util::test::behaviour::Given(TBAG_SCENARIO_NAME, name))
#endif
#ifndef TBAG_WHEN
#define TBAG_WHEN(name) if (auto TBAG_WHEN_NAME = ::libtbag::util::test::behaviour::When(TBAG_GIVEN_NAME, name))
#endif
#ifndef TBAG_THEN
#define TBAG_THEN(name) if (auto TBAG_THEN_NAME = ::libtbag::util::test::behaviour::Then(TBAG_WHEN_NAME, name))
#endif
} // namespace behaviour
} // namespace test
} // namespace util
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#ifndef TBAG_TEST_TEMP_DIR_NAME
#define TBAG_TEST_TEMP_DIR_NAME __tbag_tester_temp_dir__
#endif
/**
* @def TBAG_TEST_TEMP_DIR
* @brief Tbag Test Temp Directory.
*/
#ifndef TBAG_TEST_TEMP_DIR
#define TBAG_TEST_TEMP_DIR(case_name, name, first_create, last_remove) \
::libtbag::filesystem::TempDirGuard TBAG_TEST_TEMP_DIR_NAME( \
case_name, name, first_create, last_remove); \
ASSERT_TRUE(TBAG_TEST_TEMP_DIR_NAME.getDir().isDirectory());
#endif
#ifndef TBAG_TEST_TEMP_DIR2
#define TBAG_TEST_TEMP_DIR2(first_create, last_remove) \
TBAG_TEST_TEMP_DIR(test_info_->test_case_name(), \
test_info_->name(), \
first_create, last_remove)
#endif
/**
* @def TBAG_TEST_TEMP_DIR_GET
* @brief Obtain the current temp directory.
*/
#ifndef TBAG_TEST_TEMP_DIR_GET
#define TBAG_TEST_TEMP_DIR_GET() TBAG_TEST_TEMP_DIR_NAME.getDir()
#endif
#ifndef tttDir
#define tttDir(c, r) TBAG_TEST_TEMP_DIR2(c, r)
#endif
#ifndef tttDir_Automatic
#define tttDir_Automatic() tttDir(true, true)
#endif
#ifndef tttDir_AutoCreate
#define tttDir_AutoCreate() tttDir(true, false)
#endif
#ifndef tttDir_AutoRemove
#define tttDir_AutoRemove() tttDir(false, true)
#endif
#ifndef tttDir_Manually
#define tttDir_Manually() tttDir(false, false)
#endif
#ifndef tttDir_Get
#define tttDir_Get() TBAG_TEST_TEMP_DIR_GET()
#endif
#ifndef TEST_DEFAULT_CONSTRUCTOR
#define TEST_DEFAULT_CONSTRUCTOR(class_name, value_prefix) \
/* Default constructor. */ \
class_name value_prefix##_default; \
\
/* Copy constructor. */ \
class_name value_prefix##_copied; \
class_name value_prefix##_copy = value_prefix##_copied; \
\
/* Move constructor. */ \
class_name value_prefix##_moved; \
class_name value_prefix##_move = std::move(value_prefix##_moved); \
/* -- END -- */
#endif
#ifndef TEST_DEFAULT_ASSIGNMENT
#define TEST_DEFAULT_ASSIGNMENT(class_name, value_prefix) \
/* Copy assignment. */ \
class_name value_prefix##_copied_assign; \
class_name value_prefix##_copy_assign; \
value_prefix##_copy_assign = value_prefix##_copied_assign; \
\
/* Move assignment. */ \
class_name value_prefix##_moved_assign; \
class_name value_prefix##_move_assign; \
value_prefix##_move_assign = std::move(value_prefix##_moved_assign); \
/* -- END -- */
#endif
#endif // __INCLUDE_LIBTBAG__LIBTBAG_UTIL_TESTUTILS_HPP__
|
Create TEST_DEFAULT_* macros.
|
Create TEST_DEFAULT_* macros.
|
C++
|
mit
|
osom8979/tbag,osom8979/tbag,osom8979/tbag,osom8979/tbag,osom8979/tbag
|
de94ff7d8b386bc57c30477c4f1786dab6aee923
|
src/overhead_benchmark.cpp
|
src/overhead_benchmark.cpp
|
#include <cmath>
#include <chrono>
#include <random>
#include <vector>
#include <cassert>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <numeric>
#include <sstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <unordered_map>
#include "caf/all.hpp"
#include "caf/opencl/all.hpp"
#include "caf/opencl/mem_ref.hpp"
#include "caf/opencl/actor_facade_phase.hpp"
using namespace std;
using namespace std::chrono;
using namespace caf;
using namespace caf::opencl;
// required to allow sending mem_ref<int> in messages
namespace caf {
template <>
struct allowed_unsafe_message_type<mem_ref<uint32_t>> : std::true_type {};
}
namespace {
using vec = std::vector<uint32_t>;
using val = vec::value_type;
using add_atom = atom_constant<atom("add")>;
using init_atom = atom_constant<atom("init")>;
using quit_atom = atom_constant<atom("quit")>;
using index_atom = atom_constant<atom("index")>;
constexpr const char* kernel_file_09 = "./include/empty_kernel.cl";
const size_t NUM_LOOPS = 10;
//constexpr const char* kernel_name_01a = "kernel_wah_index";
/*****************************************************************************\
JUST FOR OUTPUT
\*****************************************************************************/
template <class T>
void valid_or_exit(T expr, const std::string& str = "") {
if (expr)
return;
if (str.empty()) {
cout << "[!!!] Something went wrong" << endl;
} else {
cout << "[!!!] " << str << endl;
}
exit(-1);
}
template<class T>
string as_binary(T num) {
stringstream s;
auto num_bits = (sizeof(T) * 8);
auto added_bits = 0;
T mask = T(0x1) << (num_bits - 1);
while (mask > 0) {
if (added_bits == 32) {
s << " ";
added_bits = 0;
}
s << ((num & mask) ? "1" : "0");
mask >>= 1;
++added_bits;
}
return s.str();
}
/*****************************************************************************\
INTRODUCE SOME CLI ARGUMENTS
\*****************************************************************************/
class config : public actor_system_config {
public:
size_t iterations = 1;
string filename = "";
val bound = 0;
string device_name = "";//"GeForce GTX 780M";
bool print_results;
config() {
load<opencl::manager>();
opt_group{custom_options_, "global"}
.add(filename, "data-file,f", "file with test data (one value per line)")
.add(bound, "bound,b", "maximum value (0 will scan values)")
.add(device_name, "device,d", "device for computation (GeForce GTX 780M, "
"empty string will take first available device)")
.add(print_results, "print,p", "print resulting bitmap index")
.add(iterations, "iterations,i", "Number of times the empty kernel is supposed to run");
}
};
} // namespace <anonymous>
/*****************************************************************************\
MAIN!
\*****************************************************************************/
void caf_main(actor_system& system, const config& cfg) {
auto& mngr = system.opencl_manager();
// get device
auto opt = mngr.get_device_if([&](const device& dev) {
if (cfg.device_name.empty())
return true;
return dev.get_name() == cfg.device_name;
});
if (!opt) {
cerr << "Device " << cfg.device_name << " not found." << endl;
return;
} else {
cout << "Using device named '" << opt->get_name() << "'." << endl;
}
auto dev = *opt;
// load kernels
auto prog_overhead = mngr.create_program_from_file(kernel_file_09, "", dev);
// create spawn configuration
auto n = 128;
auto index_space_overhead = spawn_config{dim_vec{n}};
// buffers for execution
vec config{static_cast<val>(n)};
{
// create phases
auto overhead = mngr.spawn_phase<uint*>(prog_overhead, "empty_kernel", index_space_overhead);
// kernel executions
// temp_ref used as rids buffer
scoped_actor self{system};
auto conf_ref = dev.global_argument(config, buffer_type::input);
auto start = high_resolution_clock::now();
for(size_t i = 0; i < cfg.iterations; ++i) {
self->send(overhead, conf_ref);
self->receive(
[&](mem_ref<val>&) {
//nop
}
);
}
auto stop = high_resolution_clock::now();
//TODO check if microseconds are good enough or if we should use nanoseconds instead
cout << "Time: '"
<< duration_cast<microseconds>(stop - start).count()
<< "' us" << endl;
}
// clean up
system.await_all_actors_done();
}
CAF_MAIN()
|
#include <cmath>
#include <chrono>
#include <random>
#include <vector>
#include <cassert>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <numeric>
#include <sstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <unordered_map>
#include "caf/all.hpp"
#include "caf/opencl/all.hpp"
#include "caf/opencl/mem_ref.hpp"
#include "caf/opencl/actor_facade_phase.hpp"
using namespace std;
using namespace std::chrono;
using namespace caf;
using namespace caf::opencl;
// required to allow sending mem_ref<int> in messages
namespace caf {
template <>
struct allowed_unsafe_message_type<mem_ref<uint32_t>> : std::true_type {};
}
namespace {
using vec = std::vector<uint32_t>;
using val = vec::value_type;
using add_atom = atom_constant<atom("add")>;
using init_atom = atom_constant<atom("init")>;
using quit_atom = atom_constant<atom("quit")>;
using index_atom = atom_constant<atom("index")>;
constexpr const char* kernel_file_09 = "./include/empty_kernel.cl";
//constexpr const char* kernel_name_01a = "kernel_wah_index";
/*****************************************************************************\
JUST FOR OUTPUT
\*****************************************************************************/
template <class T>
void valid_or_exit(T expr, const std::string& str = "") {
if (expr)
return;
if (str.empty()) {
cout << "[!!!] Something went wrong" << endl;
} else {
cout << "[!!!] " << str << endl;
}
exit(-1);
}
template<class T>
string as_binary(T num) {
stringstream s;
auto num_bits = (sizeof(T) * 8);
auto added_bits = 0;
T mask = T(0x1) << (num_bits - 1);
while (mask > 0) {
if (added_bits == 32) {
s << " ";
added_bits = 0;
}
s << ((num & mask) ? "1" : "0");
mask >>= 1;
++added_bits;
}
return s.str();
}
/*****************************************************************************\
INTRODUCE SOME CLI ARGUMENTS
\*****************************************************************************/
class config : public actor_system_config {
public:
size_t iterations = 1000;
size_t threshold = 1500;
string filename = "";
val bound = 0;
string device_name = "";//"GeForce GTX 780M";
bool print_results;
config() {
load<opencl::manager>();
opt_group{custom_options_, "global"}
.add(filename, "data-file,f", "file with test data (one value per line)")
.add(bound, "bound,b", "maximum value (0 will scan values)")
.add(device_name, "device,d", "device for computation (GeForce GTX 780M, "
"empty string will take first available device)")
.add(print_results, "print,p", "print resulting bitmap index")
.add(threshold, "threshold,t", "Threshold for output (1500)")
.add(iterations, "iterations,i", "Number of times the empty kernel is supposed to run (1000)");
}
};
} // namespace <anonymous>
/*****************************************************************************\
MAIN!
\*****************************************************************************/
void caf_main(actor_system& system, const config& cfg) {
auto& mngr = system.opencl_manager();
// get device
auto opt = mngr.get_device_if([&](const device& dev) {
if (cfg.device_name.empty())
return true;
return dev.get_name() == cfg.device_name;
});
if (!opt) {
cerr << "Device " << cfg.device_name << " not found." << endl;
return;
} else {
cout << "Using device named '" << opt->get_name() << "'." << endl;
}
auto dev = *opt;
// load kernels
auto prog_overhead = mngr.create_program_from_file(kernel_file_09, "", dev);
// create spawn configuration
size_t n = 1;
auto index_space_overhead = spawn_config{dim_vec{n}};
// buffers for execution
vec config{static_cast<val>(n)};
{
// create phases
auto overhead = mngr.spawn_phase<uint*>(prog_overhead, "empty_kernel", index_space_overhead);
// kernel executions
// temp_ref used as rids buffer
scoped_actor self{system};
auto conf_ref = dev.global_argument(config, buffer_type::input);
auto start = high_resolution_clock::now();
auto stop = start;
vector<size_t> measurements(cfg.iterations);
for(size_t i = 0; i < cfg.iterations; ++i) {
start = high_resolution_clock::now();
self->send(overhead, conf_ref);
self->receive([&](mem_ref<val>&) {
stop = high_resolution_clock::now();
});
measurements[i] = duration_cast<microseconds>(stop - start).count();
}
auto amount = 0;
auto threshold = cfg.threshold;
auto brk = 0;
for (size_t i = 0; i < measurements.size(); ++i) {
if (measurements[i] > threshold) {
cout << setw(4) << i << " (" << setw(5) << measurements[i] << ") "; // << endl;
amount += 1;
++brk;
if (brk > 13) {
cout << endl;
brk = 0;
}
}
}
if (brk != 0)
cout << endl;
cout << amount << " of " << cfg.iterations << " values were above " << threshold << endl;
//auto stop = high_resolution_clock::now();
//TODO check if microseconds are good enough or if we should use nanoseconds instead
/*
cout << "Time: '"
<< duration_cast<microseconds>(stop - start).count()
<< "' us" << endl;
*/
}
// clean up
system.await_all_actors_done();
}
CAF_MAIN()
|
Change time measurements
|
Change time measurements
|
C++
|
bsd-3-clause
|
josephnoir/indexing,josephnoir/indexing,josephnoir/indexing,josephnoir/indexing
|
a229859afe49ff00b8936dc11f4c1f9074e04569
|
src/layerPart.cpp
|
src/layerPart.cpp
|
//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "layerPart.h"
#include "sliceDataStorage.h"
#include "slicer.h"
#include "settings/EnumSettings.h" //For ESurfaceMode.
#include "settings/Settings.h"
#include "progress/Progress.h"
#include "utils/SVG.h" // debug output
/*
The layer-part creation step is the first step in creating actual useful data for 3D printing.
It takes the result of the Slice step, which is an unordered list of polygons, and makes groups of polygons,
each of these groups is called a "part", which sometimes are also known as "islands". These parts represent
isolated areas in the 2D layer with possible holes.
Creating "parts" is an important step, as all elements in a single part should be printed before going to another part.
And all every bit inside a single part can be printed without the nozzle leaving the boundary of this part.
It's also the first step that stores the result in the "data storage" so all other steps can access it.
*/
namespace cura {
void createLayerWithParts(const Settings& settings, SliceLayer& storageLayer, SlicerLayer* layer)
{
storageLayer.openPolyLines = layer->openPolylines;
const bool union_all_remove_holes = settings.get<bool>("meshfix_union_all_remove_holes");
if (union_all_remove_holes)
{
for(unsigned int i=0; i<layer->polygons.size(); i++)
{
if (layer->polygons[i].orientation())
layer->polygons[i].reverse();
}
}
std::vector<PolygonsPart> result;
const bool union_layers = settings.get<bool>("meshfix_union_all");
const ESurfaceMode surface_only = settings.get<ESurfaceMode>("magic_mesh_surface_mode");
if (surface_only == ESurfaceMode::SURFACE && !union_layers)
{ // Don't do anything with overlapping areas; no union nor xor
result.reserve(layer->polygons.size());
for (const PolygonRef poly : layer->polygons)
{
result.emplace_back();
result.back().add(poly);
}
}
else
{
result = layer->polygons.splitIntoParts(union_layers || union_all_remove_holes);
}
const coord_t hole_offset = settings.get<coord_t>("hole_xy_offset");
for(auto & part : result)
{
storageLayer.parts.emplace_back();
if (hole_offset != 0)
{
// holes are to be expanded or shrunk
Polygons outline;
Polygons holes;
for (const PolygonRef poly : part)
{
if (poly.orientation())
{
outline.add(poly);
}
else
{
holes.add(poly.offset(hole_offset));
}
}
storageLayer.parts.back().outline.add(outline.difference(holes.unionPolygons()));
}
else
{
storageLayer.parts.back().outline = part;
}
storageLayer.parts.back().boundaryBox.calculate(storageLayer.parts.back().outline);
if (storageLayer.parts.back().outline.empty())
{
storageLayer.parts.pop_back();
}
}
}
void createLayerParts(SliceMeshStorage& mesh, Slicer* slicer)
{
const auto total_layers = slicer->layers.size();
assert(mesh.layers.size() == total_layers);
// OpenMP compatibility fix for GCC <= 8 and GCC >= 9
// See https://www.gnu.org/software/gcc/gcc-9/porting_to.html, section "OpenMP data sharing"
#if defined(__GNUC__) && __GNUC__ <= 8 && !defined(__clang__)
#pragma omp parallel for default(none) shared(mesh, slicer) schedule(dynamic)
#else
#pragma omp parallel for default(none) shared(mesh, slicer, total_layers) schedule(dynamic)
#endif // defined(__GNUC__) && __GNUC__ <= 8
// Use a signed type for the loop counter so MSVC compiles (because it uses OpenMP 2.0, an old version).
for (int layer_nr = 0; layer_nr < static_cast<int>(total_layers); layer_nr++)
{
SliceLayer& layer_storage = mesh.layers[layer_nr];
SlicerLayer& slice_layer = slicer->layers[layer_nr];
createLayerWithParts(mesh.settings, layer_storage, &slice_layer);
}
for (LayerIndex layer_nr = total_layers - 1; layer_nr >= 0; layer_nr--)
{
SliceLayer& layer_storage = mesh.layers[layer_nr];
if (layer_storage.parts.size() > 0 || (mesh.settings.get<ESurfaceMode>("magic_mesh_surface_mode") != ESurfaceMode::NORMAL && layer_storage.openPolyLines.size() > 0))
{
mesh.layer_nr_max_filled_layer = layer_nr; // last set by the highest non-empty layer
break;
}
}
}
}//namespace cura
|
//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "layerPart.h"
#include "sliceDataStorage.h"
#include "slicer.h"
#include "settings/EnumSettings.h" //For ESurfaceMode.
#include "settings/Settings.h"
#include "progress/Progress.h"
#include "utils/SVG.h" // debug output
/*
The layer-part creation step is the first step in creating actual useful data for 3D printing.
It takes the result of the Slice step, which is an unordered list of polygons, and makes groups of polygons,
each of these groups is called a "part", which sometimes are also known as "islands". These parts represent
isolated areas in the 2D layer with possible holes.
Creating "parts" is an important step, as all elements in a single part should be printed before going to another part.
And all every bit inside a single part can be printed without the nozzle leaving the boundary of this part.
It's also the first step that stores the result in the "data storage" so all other steps can access it.
*/
namespace cura {
void createLayerWithParts(const Settings& settings, SliceLayer& storageLayer, SlicerLayer* layer)
{
storageLayer.openPolyLines = layer->openPolylines;
const coord_t maximum_resolution = settings.get<coord_t>("meshfix_maximum_resolution");
const coord_t maximum_deviation = settings.get<coord_t>("meshfix_maximum_deviation");
storageLayer.openPolyLines.simplifyPolylines(maximum_resolution, maximum_deviation);
const bool union_all_remove_holes = settings.get<bool>("meshfix_union_all_remove_holes");
if (union_all_remove_holes)
{
for(unsigned int i=0; i<layer->polygons.size(); i++)
{
if (layer->polygons[i].orientation())
layer->polygons[i].reverse();
}
}
std::vector<PolygonsPart> result;
const bool union_layers = settings.get<bool>("meshfix_union_all");
const ESurfaceMode surface_only = settings.get<ESurfaceMode>("magic_mesh_surface_mode");
if (surface_only == ESurfaceMode::SURFACE && !union_layers)
{ // Don't do anything with overlapping areas; no union nor xor
result.reserve(layer->polygons.size());
for (const PolygonRef poly : layer->polygons)
{
result.emplace_back();
result.back().add(poly);
}
}
else
{
result = layer->polygons.splitIntoParts(union_layers || union_all_remove_holes);
}
const coord_t hole_offset = settings.get<coord_t>("hole_xy_offset");
for(auto & part : result)
{
storageLayer.parts.emplace_back();
if (hole_offset != 0)
{
// holes are to be expanded or shrunk
Polygons outline;
Polygons holes;
for (const PolygonRef poly : part)
{
if (poly.orientation())
{
outline.add(poly);
}
else
{
holes.add(poly.offset(hole_offset));
}
}
storageLayer.parts.back().outline.add(outline.difference(holes.unionPolygons()));
}
else
{
storageLayer.parts.back().outline = part;
}
storageLayer.parts.back().boundaryBox.calculate(storageLayer.parts.back().outline);
if (storageLayer.parts.back().outline.empty())
{
storageLayer.parts.pop_back();
}
}
}
void createLayerParts(SliceMeshStorage& mesh, Slicer* slicer)
{
const auto total_layers = slicer->layers.size();
assert(mesh.layers.size() == total_layers);
// OpenMP compatibility fix for GCC <= 8 and GCC >= 9
// See https://www.gnu.org/software/gcc/gcc-9/porting_to.html, section "OpenMP data sharing"
#if defined(__GNUC__) && __GNUC__ <= 8 && !defined(__clang__)
#pragma omp parallel for default(none) shared(mesh, slicer) schedule(dynamic)
#else
#pragma omp parallel for default(none) shared(mesh, slicer, total_layers) schedule(dynamic)
#endif // defined(__GNUC__) && __GNUC__ <= 8
// Use a signed type for the loop counter so MSVC compiles (because it uses OpenMP 2.0, an old version).
for (int layer_nr = 0; layer_nr < static_cast<int>(total_layers); layer_nr++)
{
SliceLayer& layer_storage = mesh.layers[layer_nr];
SlicerLayer& slice_layer = slicer->layers[layer_nr];
createLayerWithParts(mesh.settings, layer_storage, &slice_layer);
}
for (LayerIndex layer_nr = total_layers - 1; layer_nr >= 0; layer_nr--)
{
SliceLayer& layer_storage = mesh.layers[layer_nr];
if (layer_storage.parts.size() > 0 || (mesh.settings.get<ESurfaceMode>("magic_mesh_surface_mode") != ESurfaceMode::NORMAL && layer_storage.openPolyLines.size() > 0))
{
mesh.layer_nr_max_filled_layer = layer_nr; // last set by the highest non-empty layer
break;
}
}
}
}//namespace cura
|
simplify for surface mode
|
fix: simplify for surface mode
|
C++
|
agpl-3.0
|
Ultimaker/CuraEngine,Ultimaker/CuraEngine
|
0ccc0dde33ee78003367cb41a05156c16429dc71
|
tools/llc/llc.cpp
|
tools/llc/llc.cpp
|
//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the llc code generator driver. It provides a convenient
// command-line interface for generating native assembly-language code
// or C code, given LLVM bitcode.
//
//===----------------------------------------------------------------------===//
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/IRReader.h"
#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
#include "llvm/CodeGen/LinkAllCodegenComponents.h"
#include "llvm/Config/config.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/Signals.h"
#include "llvm/Target/SubtargetFeature.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Target/TargetSelect.h"
#include <memory>
using namespace llvm;
// General options for llc. Other pass-specific options are specified
// within the corresponding llc passes, and target-specific options
// and back-end code generation options are specified with the target machine.
//
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
static cl::opt<std::string>
OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
// Determine optimization level.
static cl::opt<char>
OptLevel("O",
cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
"(default = '-O2')"),
cl::Prefix,
cl::ZeroOrMore,
cl::init(' '));
static cl::opt<std::string>
TargetTriple("mtriple", cl::desc("Override target triple for module"));
static cl::opt<std::string>
MArch("march", cl::desc("Architecture to generate code for (see --version)"));
static cl::opt<std::string>
MCPU("mcpu",
cl::desc("Target a specific cpu type (-mcpu=help for details)"),
cl::value_desc("cpu-name"),
cl::init(""));
static cl::list<std::string>
MAttrs("mattr",
cl::CommaSeparated,
cl::desc("Target specific attributes (-mattr=help for details)"),
cl::value_desc("a1,+a2,-a3,..."));
static cl::opt<bool>
RelaxAll("mc-relax-all",
cl::desc("When used with filetype=obj, "
"relax all fixups in the emitted object file"));
cl::opt<TargetMachine::CodeGenFileType>
FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
cl::desc("Choose a file type (not all types are supported by all targets):"),
cl::values(
clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
"Emit an assembly ('.s') file"),
clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
"Emit a native object ('.o') file [experimental]"),
clEnumValN(TargetMachine::CGFT_Null, "null",
"Emit nothing, for performance testing"),
clEnumValEnd));
cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
cl::desc("Do not verify input module"));
cl::opt<bool> DisableDotLoc("disable-dot-loc", cl::Hidden,
cl::desc("Do not use .loc entries"));
static cl::opt<bool>
DisableRedZone("disable-red-zone",
cl::desc("Do not emit code that uses the red zone."),
cl::init(false));
static cl::opt<bool>
NoImplicitFloats("no-implicit-float",
cl::desc("Don't generate implicit floating point instructions (x86-only)"),
cl::init(false));
// GetFileNameRoot - Helper function to get the basename of a filename.
static inline std::string
GetFileNameRoot(const std::string &InputFilename) {
std::string IFN = InputFilename;
std::string outputFilename;
int Len = IFN.length();
if ((Len > 2) &&
IFN[Len-3] == '.' &&
((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
(IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
} else {
outputFilename = IFN;
}
return outputFilename;
}
static tool_output_file *GetOutputStream(const char *TargetName,
Triple::OSType OS,
const char *ProgName) {
// If we don't yet have an output filename, make one.
if (OutputFilename.empty()) {
if (InputFilename == "-")
OutputFilename = "-";
else {
OutputFilename = GetFileNameRoot(InputFilename);
switch (FileType) {
default: assert(0 && "Unknown file type");
case TargetMachine::CGFT_AssemblyFile:
if (TargetName[0] == 'c') {
if (TargetName[1] == 0)
OutputFilename += ".cbe.c";
else if (TargetName[1] == 'p' && TargetName[2] == 'p')
OutputFilename += ".cpp";
else
OutputFilename += ".s";
} else
OutputFilename += ".s";
break;
case TargetMachine::CGFT_ObjectFile:
if (OS == Triple::Win32)
OutputFilename += ".obj";
else
OutputFilename += ".o";
break;
case TargetMachine::CGFT_Null:
OutputFilename += ".null";
break;
}
}
}
// Decide if we need "binary" output.
bool Binary = false;
switch (FileType) {
default: assert(0 && "Unknown file type");
case TargetMachine::CGFT_AssemblyFile:
break;
case TargetMachine::CGFT_ObjectFile:
case TargetMachine::CGFT_Null:
Binary = true;
break;
}
// Open the file.
std::string error;
unsigned OpenFlags = 0;
if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
OpenFlags);
if (!error.empty()) {
errs() << error << '\n';
delete FDOut;
return 0;
}
return FDOut;
}
// main - Entry point for the llc compiler.
//
int main(int argc, char **argv) {
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
// Enable debug stream buffering.
EnableDebugBuffering = true;
LLVMContext &Context = getGlobalContext();
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
// Initialize targets first, so that --version shows registered targets.
InitializeAllTargets();
InitializeAllAsmPrinters();
InitializeAllAsmParsers();
cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
// Load the module to be compiled...
SMDiagnostic Err;
std::auto_ptr<Module> M;
M.reset(ParseIRFile(InputFilename, Err, Context));
if (M.get() == 0) {
Err.Print(argv[0], errs());
return 1;
}
Module &mod = *M.get();
// If we are supposed to override the target triple, do so now.
if (!TargetTriple.empty())
mod.setTargetTriple(Triple::normalize(TargetTriple));
Triple TheTriple(mod.getTargetTriple());
if (TheTriple.getTriple().empty())
TheTriple.setTriple(sys::getHostTriple());
// Allocate target machine. First, check whether the user has explicitly
// specified an architecture to compile for. If so we have to look it up by
// name, because it might be a backend that has no mapping to a target triple.
const Target *TheTarget = 0;
if (!MArch.empty()) {
for (TargetRegistry::iterator it = TargetRegistry::begin(),
ie = TargetRegistry::end(); it != ie; ++it) {
if (MArch == it->getName()) {
TheTarget = &*it;
break;
}
}
if (!TheTarget) {
errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
return 1;
}
// Adjust the triple to match (if known), otherwise stick with the
// module/host triple.
Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
if (Type != Triple::UnknownArch)
TheTriple.setArch(Type);
} else {
std::string Err;
TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
if (TheTarget == 0) {
errs() << argv[0] << ": error auto-selecting target for module '"
<< Err << "'. Please use the -march option to explicitly "
<< "pick a target.\n";
return 1;
}
}
// Package up features to be passed to target/subtarget
std::string FeaturesStr;
if (MCPU.size() || MAttrs.size()) {
SubtargetFeatures Features;
Features.setCPU(MCPU);
for (unsigned i = 0; i != MAttrs.size(); ++i)
Features.AddFeature(MAttrs[i]);
FeaturesStr = Features.getString();
}
std::auto_ptr<TargetMachine>
target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr));
assert(target.get() && "Could not allocate target machine!");
TargetMachine &Target = *target.get();
if (DisableDotLoc)
Target.setMCUseLoc(false);
// Disable .loc support for older OS X versions.
if (TheTriple.isMacOSX() &&
TheTriple.isMacOSXVersionLT(10, 5))
Target.setMCUseLoc(false);
// Figure out where we are going to send the output...
OwningPtr<tool_output_file> Out
(GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
if (!Out) return 1;
CodeGenOpt::Level OLvl = CodeGenOpt::Default;
switch (OptLevel) {
default:
errs() << argv[0] << ": invalid optimization level.\n";
return 1;
case ' ': break;
case '0': OLvl = CodeGenOpt::None; break;
case '1': OLvl = CodeGenOpt::Less; break;
case '2': OLvl = CodeGenOpt::Default; break;
case '3': OLvl = CodeGenOpt::Aggressive; break;
}
// Build up all of the passes that we want to do to the module.
PassManager PM;
// Add the target data from the target machine, if it exists, or the module.
if (const TargetData *TD = Target.getTargetData())
PM.add(new TargetData(*TD));
else
PM.add(new TargetData(&mod));
// Override default to generate verbose assembly.
Target.setAsmVerbosityDefault(true);
if (RelaxAll) {
if (FileType != TargetMachine::CGFT_ObjectFile)
errs() << argv[0]
<< ": warning: ignoring -mc-relax-all because filetype != obj";
else
Target.setMCRelaxAll(true);
}
{
formatted_raw_ostream FOS(Out->os());
// Ask the target to add backend passes as necessary.
if (Target.addPassesToEmitFile(PM, FOS, FileType, OLvl, NoVerify)) {
errs() << argv[0] << ": target does not support generation of this"
<< " file type!\n";
return 1;
}
// Before executing passes, print the final values of the LLVM options.
cl::PrintOptionValues();
PM.run(mod);
}
// Declare success.
Out->keep();
return 0;
}
|
//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the llc code generator driver. It provides a convenient
// command-line interface for generating native assembly-language code
// or C code, given LLVM bitcode.
//
//===----------------------------------------------------------------------===//
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/IRReader.h"
#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
#include "llvm/CodeGen/LinkAllCodegenComponents.h"
#include "llvm/Config/config.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/Signals.h"
#include "llvm/Target/SubtargetFeature.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Target/TargetSelect.h"
#include <memory>
using namespace llvm;
// General options for llc. Other pass-specific options are specified
// within the corresponding llc passes, and target-specific options
// and back-end code generation options are specified with the target machine.
//
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
static cl::opt<std::string>
OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
// Determine optimization level.
static cl::opt<char>
OptLevel("O",
cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
"(default = '-O2')"),
cl::Prefix,
cl::ZeroOrMore,
cl::init(' '));
static cl::opt<std::string>
TargetTriple("mtriple", cl::desc("Override target triple for module"));
static cl::opt<std::string>
MArch("march", cl::desc("Architecture to generate code for (see --version)"));
static cl::opt<std::string>
MCPU("mcpu",
cl::desc("Target a specific cpu type (-mcpu=help for details)"),
cl::value_desc("cpu-name"),
cl::init(""));
static cl::list<std::string>
MAttrs("mattr",
cl::CommaSeparated,
cl::desc("Target specific attributes (-mattr=help for details)"),
cl::value_desc("a1,+a2,-a3,..."));
static cl::opt<bool>
RelaxAll("mc-relax-all",
cl::desc("When used with filetype=obj, "
"relax all fixups in the emitted object file"));
cl::opt<TargetMachine::CodeGenFileType>
FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
cl::desc("Choose a file type (not all types are supported by all targets):"),
cl::values(
clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
"Emit an assembly ('.s') file"),
clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
"Emit a native object ('.o') file [experimental]"),
clEnumValN(TargetMachine::CGFT_Null, "null",
"Emit nothing, for performance testing"),
clEnumValEnd));
cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
cl::desc("Do not verify input module"));
cl::opt<bool> DisableDotLoc("disable-dot-loc", cl::Hidden,
cl::desc("Do not use .loc entries"));
static cl::opt<bool>
DisableRedZone("disable-red-zone",
cl::desc("Do not emit code that uses the red zone."),
cl::init(false));
static cl::opt<bool>
NoImplicitFloats("no-implicit-float",
cl::desc("Don't generate implicit floating point instructions (x86-only)"),
cl::init(false));
// GetFileNameRoot - Helper function to get the basename of a filename.
static inline std::string
GetFileNameRoot(const std::string &InputFilename) {
std::string IFN = InputFilename;
std::string outputFilename;
int Len = IFN.length();
if ((Len > 2) &&
IFN[Len-3] == '.' &&
((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
(IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
} else {
outputFilename = IFN;
}
return outputFilename;
}
static tool_output_file *GetOutputStream(const char *TargetName,
Triple::OSType OS,
const char *ProgName) {
// If we don't yet have an output filename, make one.
if (OutputFilename.empty()) {
if (InputFilename == "-")
OutputFilename = "-";
else {
OutputFilename = GetFileNameRoot(InputFilename);
switch (FileType) {
default: assert(0 && "Unknown file type");
case TargetMachine::CGFT_AssemblyFile:
if (TargetName[0] == 'c') {
if (TargetName[1] == 0)
OutputFilename += ".cbe.c";
else if (TargetName[1] == 'p' && TargetName[2] == 'p')
OutputFilename += ".cpp";
else
OutputFilename += ".s";
} else
OutputFilename += ".s";
break;
case TargetMachine::CGFT_ObjectFile:
if (OS == Triple::Win32)
OutputFilename += ".obj";
else
OutputFilename += ".o";
break;
case TargetMachine::CGFT_Null:
OutputFilename += ".null";
break;
}
}
}
// Decide if we need "binary" output.
bool Binary = false;
switch (FileType) {
default: assert(0 && "Unknown file type");
case TargetMachine::CGFT_AssemblyFile:
break;
case TargetMachine::CGFT_ObjectFile:
case TargetMachine::CGFT_Null:
Binary = true;
break;
}
// Open the file.
std::string error;
unsigned OpenFlags = 0;
if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
OpenFlags);
if (!error.empty()) {
errs() << error << '\n';
delete FDOut;
return 0;
}
return FDOut;
}
// main - Entry point for the llc compiler.
//
int main(int argc, char **argv) {
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
// Enable debug stream buffering.
EnableDebugBuffering = true;
LLVMContext &Context = getGlobalContext();
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
// Initialize targets first, so that --version shows registered targets.
InitializeAllTargets();
InitializeAllAsmPrinters();
InitializeAllAsmParsers();
cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
// Load the module to be compiled...
SMDiagnostic Err;
std::auto_ptr<Module> M;
M.reset(ParseIRFile(InputFilename, Err, Context));
if (M.get() == 0) {
Err.Print(argv[0], errs());
return 1;
}
Module &mod = *M.get();
// If we are supposed to override the target triple, do so now.
if (!TargetTriple.empty())
mod.setTargetTriple(Triple::normalize(TargetTriple));
Triple TheTriple(mod.getTargetTriple());
if (TheTriple.getTriple().empty())
TheTriple.setTriple(sys::getHostTriple());
// Allocate target machine. First, check whether the user has explicitly
// specified an architecture to compile for. If so we have to look it up by
// name, because it might be a backend that has no mapping to a target triple.
const Target *TheTarget = 0;
if (!MArch.empty()) {
for (TargetRegistry::iterator it = TargetRegistry::begin(),
ie = TargetRegistry::end(); it != ie; ++it) {
if (MArch == it->getName()) {
TheTarget = &*it;
break;
}
}
if (!TheTarget) {
errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
return 1;
}
// Adjust the triple to match (if known), otherwise stick with the
// module/host triple.
Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
if (Type != Triple::UnknownArch)
TheTriple.setArch(Type);
} else {
std::string Err;
TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
if (TheTarget == 0) {
errs() << argv[0] << ": error auto-selecting target for module '"
<< Err << "'. Please use the -march option to explicitly "
<< "pick a target.\n";
return 1;
}
}
// Package up features to be passed to target/subtarget
std::string FeaturesStr;
if (MCPU.size() || MAttrs.size()) {
SubtargetFeatures Features;
Features.setCPU(MCPU);
for (unsigned i = 0; i != MAttrs.size(); ++i)
Features.AddFeature(MAttrs[i]);
FeaturesStr = Features.getString();
}
std::auto_ptr<TargetMachine>
target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr));
assert(target.get() && "Could not allocate target machine!");
TargetMachine &Target = *target.get();
if (DisableDotLoc)
Target.setMCUseLoc(false);
// Disable .loc support for older OS X versions.
if (TheTriple.isMacOSX() &&
TheTriple.isMacOSXVersionLT(10, 6))
Target.setMCUseLoc(false);
// Figure out where we are going to send the output...
OwningPtr<tool_output_file> Out
(GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
if (!Out) return 1;
CodeGenOpt::Level OLvl = CodeGenOpt::Default;
switch (OptLevel) {
default:
errs() << argv[0] << ": invalid optimization level.\n";
return 1;
case ' ': break;
case '0': OLvl = CodeGenOpt::None; break;
case '1': OLvl = CodeGenOpt::Less; break;
case '2': OLvl = CodeGenOpt::Default; break;
case '3': OLvl = CodeGenOpt::Aggressive; break;
}
// Build up all of the passes that we want to do to the module.
PassManager PM;
// Add the target data from the target machine, if it exists, or the module.
if (const TargetData *TD = Target.getTargetData())
PM.add(new TargetData(*TD));
else
PM.add(new TargetData(&mod));
// Override default to generate verbose assembly.
Target.setAsmVerbosityDefault(true);
if (RelaxAll) {
if (FileType != TargetMachine::CGFT_ObjectFile)
errs() << argv[0]
<< ": warning: ignoring -mc-relax-all because filetype != obj";
else
Target.setMCRelaxAll(true);
}
{
formatted_raw_ostream FOS(Out->os());
// Ask the target to add backend passes as necessary.
if (Target.addPassesToEmitFile(PM, FOS, FileType, OLvl, NoVerify)) {
errs() << argv[0] << ": target does not support generation of this"
<< " file type!\n";
return 1;
}
// Before executing passes, print the final values of the LLVM options.
cl::PrintOptionValues();
PM.run(mod);
}
// Declare success.
Out->keep();
return 0;
}
|
Fix a refacto, .loc support didn't work before 10.6.
|
llc: Fix a refacto, .loc support didn't work before 10.6.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@129841 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
bsd-2-clause
|
dslab-epfl/asap,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,chubbymaggie/asap,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap
|
0c0e8a28c6dd3d2181d10eca7fdffa8d610a314e
|
protocols/skype/skypecalldialog.cpp
|
protocols/skype/skypecalldialog.cpp
|
/* This file is part of the KDE project
Copyright (C) 2005 Michal Vaner <[email protected]>
Copyright (C) 2008 Pali Rohár <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <qstring.h>
#include <kdebug.h>
#include <qlabel.h>
#include <klocale.h>
#include <qpushbutton.h>
#include <qtimer.h>
#include <kglobal.h>
#include <qdatetime.h>
#include "skypecalldialog.h"
#include "skypeaccount.h"
typedef enum {
csNotRunning,
csOnHold,
csInProgress,
csShuttingDown
} callStatus;
class SkypeCallDialogPrivate {
public:
///The call is done by some account
SkypeAccount *account;
///The other side
QString userId;
///Id of the call
QString callId;
///Was there some error?
bool error;
///The timer for updating call info
QTimer *updater;
///The status of the call
callStatus status;
///The time the call is running or on hold (in halfes of seconds)
int totalTime;
///The time the call is actually running (in halfes of seconds)
int callTime;
///Did I reported the ed of call already?
bool callEnded;
///Report that the call has ended, please
void endCall() {
if (!callEnded) {
callEnded = true;
account->endCall();
}
};
};
SkypeCallDialog::SkypeCallDialog(const QString &callId, const QString &userId, SkypeAccount *account) : KDialog() {
kDebug() << k_funcinfo << endl;//some debug info
setButtons( KDialog::None ); //dont add any buttons
setDefaultButton( KDialog::None );
QWidget *w = new QWidget( this );
dialog = new Ui::SkypeCallDialogBase();
dialog->setupUi( w );
setMainWidget( w );
//Initialize values
d = new SkypeCallDialogPrivate();
d->account = account;
d->callId = callId;
d->userId = userId;
d->error = false;
d->status = csNotRunning;
d->totalTime = 0;
d->callTime = 0;
d->callEnded = false;
d->updater = new QTimer();
connect(d->updater, SIGNAL(timeout()), this, SLOT(updateCallInfo()));
d->updater->start(500);
dialog->NameLabel->setText(account->getUserLabel(userId));
setCaption(i18n("Call with %1", account->getUserLabel(userId)));
connect(dialog->AcceptButton, SIGNAL(clicked()), this, SLOT(acceptCall()));
connect(dialog->HangButton, SIGNAL(clicked()), this, SLOT(hangUp()));
connect(dialog->HoldButton, SIGNAL(clicked()), this, SLOT(holdCall()));
connect(dialog->ChatButton, SIGNAL(clicked()), this, SLOT(chatUser()));
}
SkypeCallDialog::~SkypeCallDialog(){
kDebug() << k_funcinfo << endl;//some debug info
emit callFinished(d->callId);
d->endCall();
delete d->updater;
delete d;
delete dialog;
}
void SkypeCallDialog::updateStatus(const QString &callId, const QString &status) {
kDebug() << k_funcinfo << "Status: " << status << endl;//some debug info
if (callId == d->callId) {
if (status == "CANCELLED") {
dialog->HoldButton->setEnabled(false);
dialog->HangButton->setEnabled(false);
dialog->AcceptButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("Canceled"));
closeLater();
d->status = csNotRunning;
} else if (status == "BUSY") {
dialog->HoldButton->setEnabled(false);
dialog->HangButton->setEnabled(false);
dialog->AcceptButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("Other person is busy"));
closeLater();
d->status = csNotRunning;
} else if (status == "REFUSED") {
dialog->HoldButton->setEnabled(false);
dialog->HangButton->setEnabled(false);
dialog->AcceptButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("Refused"));
closeLater();
d->status = csNotRunning;
} else if (status == "MISSED") {
dialog->HoldButton->setEnabled(false);
dialog->HangButton->setEnabled(false);
dialog->AcceptButton->setEnabled(true);
dialog->AcceptButton->setText(i18n("Call Back"));
dialog->StatusLabel->setText(i18n("Missed"));
d->status = csNotRunning;
disconnect(dialog->AcceptButton, SIGNAL(clicked()), this, SLOT(acceptCall()));
connect(dialog->AcceptButton, SIGNAL(clicked()), this, SLOT(callBack()));
} else if (status == "FINISHED") {
dialog->HoldButton->setEnabled(false);
dialog->HangButton->setEnabled(false);
dialog->AcceptButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("Finished"));
closeLater();
d->status = csNotRunning;
} else if (status == "LOCALHOLD") {
dialog->HoldButton->setEnabled(true);
dialog->HoldButton->setText(i18n("Resume"));
dialog->HangButton->setEnabled(true);
dialog->AcceptButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("On hold (local)"));
d->status = csOnHold;
} else if (status == "REMOTEHOLD") {
dialog->HoldButton->setEnabled(false);
dialog->HangButton->setEnabled(true);
dialog->AcceptButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("On hold (remote)"));
d->status = csOnHold;
} else if (status == "ONHOLD") {
dialog->HoldButton->setEnabled(true);
dialog->HangButton->setEnabled(true);
dialog->AcceptButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("On hold"));
d->status = csOnHold;
} else if (status == "INPROGRESS") {
dialog->HoldButton->setEnabled(true);
dialog->HoldButton->setText(i18n("Hold"));
dialog->HangButton->setEnabled(true);
dialog->AcceptButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("In progress"));
d->status=csInProgress;
} else if (status == "RINGING") {
dialog->HoldButton->setEnabled(false);
dialog->AcceptButton->setEnabled(d->account->isCallIncoming(callId));
dialog->HangButton->setEnabled(true);
dialog->StatusLabel->setText(i18n("Ringing"));
d->status = csNotRunning;
} else if (status == "FAILED") {
if (d->error) //This one is already handled
return;
dialog->HoldButton->setEnabled(false);
dialog->AcceptButton->setEnabled(false);
dialog->HangButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("Failed"));
d->status = csNotRunning;
} else if (status == "ROUTING") {
dialog->HoldButton->setEnabled(false);
dialog->AcceptButton->setEnabled(false);
dialog->HangButton->setEnabled(true);
dialog->StatusLabel->setText(i18n("Connecting"));
d->status = csNotRunning;
} else if (status == "EARLYMEDIA") {
dialog->HoldButton->setEnabled(false);
dialog->AcceptButton->setEnabled(false);
dialog->HangButton->setEnabled(true);
dialog->StatusLabel->setText(i18n("Early media (waiting for operator...)"));
d->status = csNotRunning;
} else if (status == "UNPLACED") {//Ups, whats that, how that call got here?
//deleteLater();//Just give up, this one is odd
dialog->StatusLabel->setText(i18n("Unplaced (please wait...)"));
//it is when user create call after hangup, so dont close dialog and wait
}
}
}
void SkypeCallDialog::acceptCall() {
d->account->startCall();
emit acceptTheCall(d->callId);
}
void SkypeCallDialog::hangUp() {
emit hangTheCall(d->callId);
}
void SkypeCallDialog::holdCall() {
emit toggleHoldCall(d->callId);
}
void SkypeCallDialog::closeEvent(QCloseEvent *) {
emit hangTheCall(d->callId);//Finish the call before you give up
deleteLater();//some kind of suicide
}
void SkypeCallDialog::deathTimeout() {
kDebug() << k_funcinfo << endl;//some debug info
deleteLater();//OK, the death is here :-)
}
void SkypeCallDialog::closeLater() {
kDebug() << k_funcinfo << endl;//some debug info
d->endCall();
if ((d->account->closeCallWindowTimeout()) && (d->status != csShuttingDown)) {
QTimer::singleShot(1000 * d->account->closeCallWindowTimeout(), this, SLOT(deathTimeout()));
d->status = csShuttingDown;
}
}
void SkypeCallDialog::updateError(const QString &callId, const QString &message) {
kDebug() << k_funcinfo << endl;//some debug info
if (callId == d->callId) {
dialog->AcceptButton->setEnabled(false);
dialog->HangButton->setEnabled(false);
dialog->HoldButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("Failed (%1)", message));
closeLater();
d->error = true;
}
}
void SkypeCallDialog::updateCallInfo() {
switch (d->status) {
case csInProgress:
if (d->callTime % 20 == 0)
emit updateSkypeOut();//update the skype out
++d->callTime;
//Do not break, do that as well
case csOnHold:
++d->totalTime;
default:
;//Get rid of that stupid warning about not handled value in switch
}
const QString &activeTime = KGlobal::locale()->formatTime(QTime().addSecs(d->callTime / 2), true, true);
const QString &totalTime = KGlobal::locale()->formatTime(QTime().addSecs(d->totalTime / 2), true, true);
dialog->TimeLabel->setText(i18n("%1 active\n%2 total", activeTime, totalTime));
}
void SkypeCallDialog::skypeOutInfo(int balance, const QString ¤cy) {
float part;//How to change the balance before showing (multiply by this)
QString symbol;//The symbol of the currency is
int digits;
if (currency == "EUR") {
part = 0.01;//It's in cent's not in euros
symbol = i18n("€");
digits = 2;
} else {
dialog->CreditLabel->setText(i18n("Skypeout inactive"));
return;
}
float value = balance * part;
dialog->CreditLabel->setText(KGlobal::locale()->formatMoney(value, symbol, digits));
}
void SkypeCallDialog::chatUser() {
d->account->chatUser(d->userId);
}
void SkypeCallDialog::callBack() {
deleteLater();//close this window
d->account->makeCall(d->userId);
}
#include "skypecalldialog.moc"
|
/* This file is part of the KDE project
Copyright (C) 2005 Michal Vaner <[email protected]>
Copyright (C) 2008 Pali Rohár <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <qstring.h>
#include <kdebug.h>
#include <qlabel.h>
#include <klocale.h>
#include <qpushbutton.h>
#include <qtimer.h>
#include <kglobal.h>
#include <qdatetime.h>
#include "skypecalldialog.h"
#include "skypeaccount.h"
typedef enum {
csNotRunning,
csOnHold,
csInProgress,
csShuttingDown
} callStatus;
class SkypeCallDialogPrivate {
public:
///The call is done by some account
SkypeAccount *account;
///The other side
QString userId;
///Id of the call
QString callId;
///Was there some error?
bool error;
///The timer for updating call info
QTimer *updater;
///The status of the call
callStatus status;
///The time the call is running or on hold (in halfes of seconds)
int totalTime;
///The time the call is actually running (in halfes of seconds)
int callTime;
///Did I reported the ed of call already?
bool callEnded;
///Report that the call has ended, please
void endCall() {
if (!callEnded) {
callEnded = true;
account->endCall();
}
};
};
SkypeCallDialog::SkypeCallDialog(const QString &callId, const QString &userId, SkypeAccount *account) : KDialog() {
kDebug() << k_funcinfo << endl;//some debug info
setButtons( KDialog::None ); //dont add any buttons
setDefaultButton( KDialog::None );
QWidget *w = new QWidget( this );
dialog = new Ui::SkypeCallDialogBase();
dialog->setupUi( w );
setMainWidget( w );
//Initialize values
d = new SkypeCallDialogPrivate();
d->account = account;
d->callId = callId;
d->userId = userId;
d->error = false;
d->status = csNotRunning;
d->totalTime = 0;
d->callTime = 0;
d->callEnded = false;
d->updater = new QTimer();
connect(d->updater, SIGNAL(timeout()), this, SLOT(updateCallInfo()));
d->updater->start(500);
dialog->NameLabel->setText(account->getUserLabel(userId));
setCaption(i18n("Call with %1", account->getUserLabel(userId)));
connect(dialog->AcceptButton, SIGNAL(clicked()), this, SLOT(acceptCall()));
connect(dialog->HangButton, SIGNAL(clicked()), this, SLOT(hangUp()));
connect(dialog->HoldButton, SIGNAL(clicked()), this, SLOT(holdCall()));
connect(dialog->ChatButton, SIGNAL(clicked()), this, SLOT(chatUser()));
}
SkypeCallDialog::~SkypeCallDialog(){
kDebug() << k_funcinfo << endl;//some debug info
emit callFinished(d->callId);
d->endCall();
delete d->updater;
delete d;
delete dialog;
}
void SkypeCallDialog::updateStatus(const QString &callId, const QString &status) {
kDebug() << k_funcinfo << "Status: " << status << endl;//some debug info
if (callId == d->callId) {
if (status == "CANCELLED") {
dialog->HoldButton->setEnabled(false);
dialog->HangButton->setEnabled(false);
dialog->AcceptButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("Canceled"));
closeLater();
d->status = csNotRunning;
} else if (status == "BUSY") {
dialog->HoldButton->setEnabled(false);
dialog->HangButton->setEnabled(false);
dialog->AcceptButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("Other person is busy"));
closeLater();
d->status = csNotRunning;
} else if (status == "REFUSED") {
dialog->HoldButton->setEnabled(false);
dialog->HangButton->setEnabled(false);
dialog->AcceptButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("Refused"));
closeLater();
d->status = csNotRunning;
} else if (status == "MISSED") {
dialog->HoldButton->setEnabled(false);
dialog->HangButton->setEnabled(false);
dialog->AcceptButton->setEnabled(true);
dialog->AcceptButton->setText(i18n("Call Back"));
dialog->StatusLabel->setText(i18n("Missed"));
d->status = csNotRunning;
disconnect(dialog->AcceptButton, SIGNAL(clicked()), this, SLOT(acceptCall()));
connect(dialog->AcceptButton, SIGNAL(clicked()), this, SLOT(callBack()));
} else if (status == "FINISHED") {
dialog->HoldButton->setEnabled(false);
dialog->HangButton->setEnabled(false);
dialog->AcceptButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("Finished"));
closeLater();
d->status = csNotRunning;
} else if (status == "LOCALHOLD") {
dialog->HoldButton->setEnabled(true);
dialog->HoldButton->setText(i18n("Resume"));
dialog->HangButton->setEnabled(true);
dialog->AcceptButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("On hold (local)"));
d->status = csOnHold;
} else if (status == "REMOTEHOLD") {
dialog->HoldButton->setEnabled(false);
dialog->HangButton->setEnabled(true);
dialog->AcceptButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("On hold (remote)"));
d->status = csOnHold;
} else if (status == "ONHOLD") {
dialog->HoldButton->setEnabled(true);
dialog->HangButton->setEnabled(true);
dialog->AcceptButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("On hold"));
d->status = csOnHold;
} else if (status == "INPROGRESS") {
dialog->HoldButton->setEnabled(true);
dialog->HoldButton->setText(i18n("Hold"));
dialog->HangButton->setEnabled(true);
dialog->AcceptButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("In progress"));
d->status=csInProgress;
} else if (status == "RINGING") {
dialog->HoldButton->setEnabled(false);
dialog->AcceptButton->setEnabled(d->account->isCallIncoming(callId));
dialog->HangButton->setEnabled(true);
dialog->StatusLabel->setText(i18n("Ringing"));
d->status = csNotRunning;
} else if (status == "FAILED") {
if (d->error) //This one is already handled
return;
dialog->HoldButton->setEnabled(false);
dialog->AcceptButton->setEnabled(false);
dialog->HangButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("Failed"));
d->status = csNotRunning;
} else if (status == "ROUTING") {
dialog->HoldButton->setEnabled(false);
dialog->AcceptButton->setEnabled(false);
dialog->HangButton->setEnabled(true);
dialog->StatusLabel->setText(i18n("Connecting"));
d->status = csNotRunning;
} else if (status == "EARLYMEDIA") {
dialog->HoldButton->setEnabled(false);
dialog->AcceptButton->setEnabled(false);
dialog->HangButton->setEnabled(true);
dialog->StatusLabel->setText(i18nc("Early media means the media played before the call is established. For example it can be a calling tone or a waiting message such as all operators are busy.", "Early media (waiting for operator...)"));
d->status = csNotRunning;
} else if (status == "UNPLACED") {//Ups, whats that, how that call got here?
//deleteLater();//Just give up, this one is odd
dialog->StatusLabel->setText(i18n("Unplaced (please wait...)"));
//it is when user create call after hangup, so dont close dialog and wait
}
}
}
void SkypeCallDialog::acceptCall() {
d->account->startCall();
emit acceptTheCall(d->callId);
}
void SkypeCallDialog::hangUp() {
emit hangTheCall(d->callId);
}
void SkypeCallDialog::holdCall() {
emit toggleHoldCall(d->callId);
}
void SkypeCallDialog::closeEvent(QCloseEvent *) {
emit hangTheCall(d->callId);//Finish the call before you give up
deleteLater();//some kind of suicide
}
void SkypeCallDialog::deathTimeout() {
kDebug() << k_funcinfo << endl;//some debug info
deleteLater();//OK, the death is here :-)
}
void SkypeCallDialog::closeLater() {
kDebug() << k_funcinfo << endl;//some debug info
d->endCall();
if ((d->account->closeCallWindowTimeout()) && (d->status != csShuttingDown)) {
QTimer::singleShot(1000 * d->account->closeCallWindowTimeout(), this, SLOT(deathTimeout()));
d->status = csShuttingDown;
}
}
void SkypeCallDialog::updateError(const QString &callId, const QString &message) {
kDebug() << k_funcinfo << endl;//some debug info
if (callId == d->callId) {
dialog->AcceptButton->setEnabled(false);
dialog->HangButton->setEnabled(false);
dialog->HoldButton->setEnabled(false);
dialog->StatusLabel->setText(i18n("Failed (%1)", message));
closeLater();
d->error = true;
}
}
void SkypeCallDialog::updateCallInfo() {
switch (d->status) {
case csInProgress:
if (d->callTime % 20 == 0)
emit updateSkypeOut();//update the skype out
++d->callTime;
//Do not break, do that as well
case csOnHold:
++d->totalTime;
default:
;//Get rid of that stupid warning about not handled value in switch
}
const QString &activeTime = KGlobal::locale()->formatTime(QTime().addSecs(d->callTime / 2), true, true);
const QString &totalTime = KGlobal::locale()->formatTime(QTime().addSecs(d->totalTime / 2), true, true);
dialog->TimeLabel->setText(i18n("%1 active\n%2 total", activeTime, totalTime));
}
void SkypeCallDialog::skypeOutInfo(int balance, const QString ¤cy) {
float part;//How to change the balance before showing (multiply by this)
QString symbol;//The symbol of the currency is
int digits;
if (currency == "EUR") {
part = 0.01;//It's in cent's not in euros
symbol = i18n("€");
digits = 2;
} else {
dialog->CreditLabel->setText(i18n("Skypeout inactive"));
return;
}
float value = balance * part;
dialog->CreditLabel->setText(KGlobal::locale()->formatMoney(value, symbol, digits));
}
void SkypeCallDialog::chatUser() {
d->account->chatUser(d->userId);
}
void SkypeCallDialog::callBack() {
deleteLater();//close this window
d->account->makeCall(d->userId);
}
#include "skypecalldialog.moc"
|
add context to what early media means
|
add context to what early media means
svn path=/trunk/kdereview/kopete/protocols/skype/; revision=924428
|
C++
|
lgpl-2.1
|
Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,josh-wambua/kopete,josh-wambua/kopete,josh-wambua/kopete,josh-wambua/kopete,josh-wambua/kopete,josh-wambua/kopete
|
f3bafc10438a70d5a65d65b7bc42d7798b7fe14b
|
tools/opt/opt.cpp
|
tools/opt/opt.cpp
|
//===----------------------------------------------------------------------===//
// LLVM Modular Optimizer Utility: opt
//
// Optimizations may be specified an arbitrary number of times on the command
// line, they are run in the order specified.
//
//===----------------------------------------------------------------------===//
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Bytecode/Reader.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetMachineImpls.h"
#include "llvm/Support/PassNameParser.h"
#include "Support/Signals.h"
#include <fstream>
#include <memory>
#include <algorithm>
using std::cerr;
using std::string;
// The OptimizationList is automatically populated with registered Passes by the
// PassNameParser.
//
static cl::list<const PassInfo*, bool,
FilteredPassNameParser<PassInfo::Optimization> >
OptimizationList(cl::desc("Optimizations available:"));
// Other command line options...
//
static cl::opt<string>
InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
static cl::opt<string>
OutputFilename("o", cl::desc("Override output filename"),
cl::value_desc("filename"));
static cl::opt<bool>
Force("f", cl::desc("Overwrite output files"));
static cl::opt<bool>
PrintEachXForm("p", cl::desc("Print module after each transformation"));
static cl::opt<bool>
NoOutput("no-output", cl::desc("Do not write result bytecode file"), cl::Hidden);
static cl::opt<bool>
Quiet("q", cl::desc("Don't print 'program modified' message"));
static cl::alias
QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
//===----------------------------------------------------------------------===//
// main for opt
//
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv,
" llvm .bc -> .bc modular optimizer\n");
// FIXME: The choice of target should be controllable on the command line.
TargetData TD("opt target");
// Allocate a full target machine description only if necessary...
// FIXME: The choice of target should be controllable on the command line.
std::auto_ptr<TargetMachine> target;
TargetMachine* TM = NULL;
// Load the input module...
std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
if (M.get() == 0) {
cerr << argv[0] << ": bytecode didn't read correctly.\n";
return 1;
}
// Figure out what stream we are supposed to write to...
std::ostream *Out = &std::cout; // Default to printing to stdout...
if (OutputFilename != "") {
if (!Force && std::ifstream(OutputFilename.c_str())) {
// If force is not specified, make sure not to overwrite a file!
cerr << argv[0] << ": error opening '" << OutputFilename
<< "': file exists!\n"
<< "Use -f command line argument to force output\n";
return 1;
}
Out = new std::ofstream(OutputFilename.c_str());
if (!Out->good()) {
cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
return 1;
}
// Make sure that the Output file gets unlink'd from the disk if we get a
// SIGINT
RemoveFileOnSignal(OutputFilename);
}
// Create a PassManager to hold and optimize the collection of passes we are
// about to build...
//
PassManager Passes;
// Create a new optimization pass for each one specified on the command line
for (unsigned i = 0; i < OptimizationList.size(); ++i) {
const PassInfo *Opt = OptimizationList[i];
if (Opt->getNormalCtor())
Passes.add(Opt->getNormalCtor()());
else if (Opt->getDataCtor())
Passes.add(Opt->getDataCtor()(TD)); // Provide dummy target data...
else if (Opt->getTargetCtor()) {
if (target.get() == NULL)
target.reset(allocateSparcTargetMachine()); // FIXME: target option
assert(target.get() && "Could not allocate target machine!");
Passes.add(Opt->getTargetCtor()(*target.get()));
} else
cerr << argv[0] << ": cannot create pass: " << Opt->getPassName() << "\n";
if (PrintEachXForm)
Passes.add(new PrintModulePass(&cerr));
}
// Check that the module is well formed on completion of optimization
Passes.add(createVerifierPass());
// Write bytecode out to disk or cout as the last step...
if (!NoOutput)
Passes.add(new WriteBytecodePass(Out, Out != &std::cout));
// Now that we have all of the passes ready, run them.
if (Passes.run(*M.get()) && !Quiet)
cerr << "Program modified.\n";
return 0;
}
|
//===----------------------------------------------------------------------===//
// LLVM Modular Optimizer Utility: opt
//
// Optimizations may be specified an arbitrary number of times on the command
// line, they are run in the order specified.
//
//===----------------------------------------------------------------------===//
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Bytecode/Reader.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetMachineImpls.h"
#include "llvm/Support/PassNameParser.h"
#include "Support/Signals.h"
#include <fstream>
#include <memory>
#include <algorithm>
using std::cerr;
using std::string;
// The OptimizationList is automatically populated with registered Passes by the
// PassNameParser.
//
static cl::list<const PassInfo*, bool,
FilteredPassNameParser<PassInfo::Optimization> >
OptimizationList(cl::desc("Optimizations available:"));
// Other command line options...
//
static cl::opt<string>
InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
static cl::opt<string>
OutputFilename("o", cl::desc("Override output filename"),
cl::value_desc("filename"));
static cl::opt<bool>
Force("f", cl::desc("Overwrite output files"));
static cl::opt<bool>
PrintEachXForm("p", cl::desc("Print module after each transformation"));
static cl::opt<bool>
NoOutput("no-output", cl::desc("Do not write result bytecode file"), cl::Hidden);
static cl::opt<bool>
NoVerify("no-verify", cl::desc("Do not verify result module"), cl::Hidden);
static cl::opt<bool>
Quiet("q", cl::desc("Don't print 'program modified' message"));
static cl::alias
QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
//===----------------------------------------------------------------------===//
// main for opt
//
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv,
" llvm .bc -> .bc modular optimizer\n");
// FIXME: The choice of target should be controllable on the command line.
TargetData TD("opt target");
// Allocate a full target machine description only if necessary...
// FIXME: The choice of target should be controllable on the command line.
std::auto_ptr<TargetMachine> target;
TargetMachine* TM = NULL;
// Load the input module...
std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));
if (M.get() == 0) {
cerr << argv[0] << ": bytecode didn't read correctly.\n";
return 1;
}
// Figure out what stream we are supposed to write to...
std::ostream *Out = &std::cout; // Default to printing to stdout...
if (OutputFilename != "") {
if (!Force && std::ifstream(OutputFilename.c_str())) {
// If force is not specified, make sure not to overwrite a file!
cerr << argv[0] << ": error opening '" << OutputFilename
<< "': file exists!\n"
<< "Use -f command line argument to force output\n";
return 1;
}
Out = new std::ofstream(OutputFilename.c_str());
if (!Out->good()) {
cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
return 1;
}
// Make sure that the Output file gets unlink'd from the disk if we get a
// SIGINT
RemoveFileOnSignal(OutputFilename);
}
// Create a PassManager to hold and optimize the collection of passes we are
// about to build...
//
PassManager Passes;
// Create a new optimization pass for each one specified on the command line
for (unsigned i = 0; i < OptimizationList.size(); ++i) {
const PassInfo *Opt = OptimizationList[i];
if (Opt->getNormalCtor())
Passes.add(Opt->getNormalCtor()());
else if (Opt->getDataCtor())
Passes.add(Opt->getDataCtor()(TD)); // Provide dummy target data...
else if (Opt->getTargetCtor()) {
if (target.get() == NULL)
target.reset(allocateSparcTargetMachine()); // FIXME: target option
assert(target.get() && "Could not allocate target machine!");
Passes.add(Opt->getTargetCtor()(*target.get()));
} else
cerr << argv[0] << ": cannot create pass: " << Opt->getPassName() << "\n";
if (PrintEachXForm)
Passes.add(new PrintModulePass(&cerr));
}
// Check that the module is well formed on completion of optimization
if (!NoVerify)
Passes.add(createVerifierPass());
// Write bytecode out to disk or cout as the last step...
if (!NoOutput)
Passes.add(new WriteBytecodePass(Out, Out != &std::cout));
// Now that we have all of the passes ready, run them.
if (Passes.run(*M.get()) && !Quiet)
cerr << "Program modified.\n";
return 0;
}
|
Add new -no-verify option
|
Add new -no-verify option
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@5542 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,dslab-epfl/asap
|
31b72a563ad1b6c3c3be5e58d76b75650562b52d
|
content/browser/gpu/compositor_util.cc
|
content/browser/gpu/compositor_util.cc
|
// 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 "content/browser/gpu/compositor_util.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/strings/string_number_conversions.h"
#include "build/build_config.h"
#include "cc/base/switches.h"
#include "content/browser/gpu/gpu_data_manager_impl.h"
#include "content/public/common/content_switches.h"
#include "gpu/config/gpu_feature_type.h"
namespace content {
namespace {
static bool IsGpuRasterizationBlacklisted() {
GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance();
return manager->IsFeatureBlacklisted(
gpu::GPU_FEATURE_TYPE_GPU_RASTERIZATION);
}
const char* kGpuCompositingFeatureName = "gpu_compositing";
const char* kWebGLFeatureName = "webgl";
const char* kRasterizationFeatureName = "rasterization";
const char* kThreadedRasterizationFeatureName = "threaded_rasterization";
const char* kMultipleRasterThreadsFeatureName = "multiple_raster_threads";
const int kMinRasterThreads = 1;
const int kMaxRasterThreads = 64;
struct GpuFeatureInfo {
std::string name;
bool blocked;
bool disabled;
std::string disabled_description;
bool fallback_to_software;
};
const GpuFeatureInfo GetGpuFeatureInfo(size_t index, bool* eof) {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance();
const GpuFeatureInfo kGpuFeatureInfo[] = {
{
"2d_canvas",
manager->IsFeatureBlacklisted(
gpu::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS),
command_line.HasSwitch(switches::kDisableAccelerated2dCanvas) ||
!GpuDataManagerImpl::GetInstance()->
GetGPUInfo().SupportsAccelerated2dCanvas(),
"Accelerated 2D canvas is unavailable: either disabled at the command"
" line or not supported by the current system.",
true
},
{
kGpuCompositingFeatureName,
manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_GPU_COMPOSITING),
command_line.HasSwitch(switches::kDisableGpuCompositing),
"Gpu compositing has been disabled, either via about:flags or"
" command line. The browser will fall back to software compositing"
" and hardware acceleration will be unavailable.",
true
},
{
kWebGLFeatureName,
manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_WEBGL),
command_line.HasSwitch(switches::kDisableExperimentalWebGL),
"WebGL has been disabled, either via about:flags or command line.",
false
},
{
"flash_3d",
manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_FLASH3D),
command_line.HasSwitch(switches::kDisableFlash3d),
"Using 3d in flash has been disabled, either via about:flags or"
" command line.",
true
},
{
"flash_stage3d",
manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D),
command_line.HasSwitch(switches::kDisableFlashStage3d),
"Using Stage3d in Flash has been disabled, either via about:flags or"
" command line.",
true
},
{
"flash_stage3d_baseline",
manager->IsFeatureBlacklisted(
gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D_BASELINE) ||
manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D),
command_line.HasSwitch(switches::kDisableFlashStage3d),
"Using Stage3d Baseline profile in Flash has been disabled, either"
" via about:flags or command line.",
true
},
{
"video_decode",
manager->IsFeatureBlacklisted(
gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE),
command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode),
"Accelerated video decode has been disabled, either via about:flags"
" or command line.",
true
},
#if defined(ENABLE_WEBRTC)
{
"video_encode",
manager->IsFeatureBlacklisted(
gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_ENCODE),
command_line.HasSwitch(switches::kDisableWebRtcHWEncoding),
"Accelerated video encode has been disabled, either via about:flags"
" or command line.",
true
},
#endif
#if defined(OS_CHROMEOS)
{
"panel_fitting",
manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_PANEL_FITTING),
command_line.HasSwitch(switches::kDisablePanelFitting),
"Panel fitting has been disabled, either via about:flags or command"
" line.",
false
},
#endif
{
kRasterizationFeatureName,
IsGpuRasterizationBlacklisted() &&
!IsGpuRasterizationEnabled() && !IsForceGpuRasterizationEnabled(),
!IsGpuRasterizationEnabled() && !IsForceGpuRasterizationEnabled() &&
!IsGpuRasterizationBlacklisted(),
"Accelerated rasterization has been disabled, either via about:flags"
" or command line.",
true
},
{
kThreadedRasterizationFeatureName,
false,
!IsImplSidePaintingEnabled(),
"Threaded rasterization has not been enabled or"
" is not supported by the current system.",
false
},
{
kMultipleRasterThreadsFeatureName,
false,
NumberOfRendererRasterThreads() == 1,
"Raster is using a single thread.",
false
},
};
DCHECK(index < arraysize(kGpuFeatureInfo));
*eof = (index == arraysize(kGpuFeatureInfo) - 1);
return kGpuFeatureInfo[index];
}
} // namespace
bool IsPinchVirtualViewportEnabled() {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
// Command line switches take precedence over platform default.
if (command_line.HasSwitch(cc::switches::kDisablePinchVirtualViewport))
return false;
if (command_line.HasSwitch(cc::switches::kEnablePinchVirtualViewport))
return true;
#if defined(OS_CHROMEOS)
return true;
#else
return false;
#endif
}
bool IsDelegatedRendererEnabled() {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
bool enabled = false;
#if defined(USE_AURA) || defined(OS_MACOSX)
// Enable on Aura and Mac.
enabled = true;
#endif
// Flags override.
enabled |= command_line.HasSwitch(switches::kEnableDelegatedRenderer);
enabled &= !command_line.HasSwitch(switches::kDisableDelegatedRenderer);
return enabled;
}
bool IsImplSidePaintingEnabled() {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kDisableImplSidePainting))
return false;
else if (command_line.HasSwitch(switches::kEnableImplSidePainting))
return true;
else if (command_line.HasSwitch(
switches::kEnableBleedingEdgeRenderingFastPaths))
return true;
return true;
}
int NumberOfRendererRasterThreads() {
int num_raster_threads = 1;
int force_num_raster_threads = ForceNumberOfRendererRasterThreads();
if (force_num_raster_threads)
num_raster_threads = force_num_raster_threads;
return num_raster_threads;
}
int ForceNumberOfRendererRasterThreads() {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
if (!command_line.HasSwitch(switches::kNumRasterThreads))
return 0;
std::string string_value =
command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
int force_num_raster_threads = 0;
if (base::StringToInt(string_value, &force_num_raster_threads) &&
force_num_raster_threads >= kMinRasterThreads &&
force_num_raster_threads <= kMaxRasterThreads) {
return force_num_raster_threads;
} else {
LOG(WARNING) << "Failed to parse switch " <<
switches::kNumRasterThreads << ": " << string_value;
return 0;
}
}
bool IsGpuRasterizationEnabled() {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
if (!IsImplSidePaintingEnabled())
return false;
if (command_line.HasSwitch(switches::kDisableGpuRasterization))
return false;
else if (command_line.HasSwitch(switches::kEnableGpuRasterization))
return true;
if (IsGpuRasterizationBlacklisted()) {
return false;
}
return true;
}
bool IsForceGpuRasterizationEnabled() {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
if (!IsImplSidePaintingEnabled())
return false;
return command_line.HasSwitch(switches::kForceGpuRasterization);
}
bool UseSurfacesEnabled() {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
return command_line.HasSwitch(switches::kUseSurfaces);
}
base::Value* GetFeatureStatus() {
GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance();
std::string gpu_access_blocked_reason;
bool gpu_access_blocked =
!manager->GpuAccessAllowed(&gpu_access_blocked_reason);
base::DictionaryValue* feature_status_dict = new base::DictionaryValue();
bool eof = false;
for (size_t i = 0; !eof; ++i) {
const GpuFeatureInfo gpu_feature_info = GetGpuFeatureInfo(i, &eof);
std::string status;
if (gpu_feature_info.disabled) {
status = "disabled";
if (gpu_feature_info.fallback_to_software)
status += "_software";
else
status += "_off";
if (gpu_feature_info.name == kThreadedRasterizationFeatureName)
status += "_ok";
} else if (gpu_feature_info.blocked ||
gpu_access_blocked) {
status = "unavailable";
if (gpu_feature_info.fallback_to_software)
status += "_software";
else
status += "_off";
} else {
status = "enabled";
if (gpu_feature_info.name == kWebGLFeatureName &&
manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_GPU_COMPOSITING))
status += "_readback";
if (gpu_feature_info.name == kRasterizationFeatureName) {
if (IsForceGpuRasterizationEnabled())
status += "_force";
}
if (gpu_feature_info.name == kMultipleRasterThreadsFeatureName) {
if (ForceNumberOfRendererRasterThreads() > 0)
status += "_force";
}
if (gpu_feature_info.name == kThreadedRasterizationFeatureName ||
gpu_feature_info.name == kMultipleRasterThreadsFeatureName)
status += "_on";
}
if (gpu_feature_info.name == kWebGLFeatureName &&
(gpu_feature_info.blocked || gpu_access_blocked) &&
manager->ShouldUseSwiftShader()) {
status = "unavailable_software";
}
feature_status_dict->SetString(
gpu_feature_info.name.c_str(), status.c_str());
}
return feature_status_dict;
}
base::Value* GetProblems() {
GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance();
std::string gpu_access_blocked_reason;
bool gpu_access_blocked =
!manager->GpuAccessAllowed(&gpu_access_blocked_reason);
base::ListValue* problem_list = new base::ListValue();
manager->GetBlacklistReasons(problem_list);
if (gpu_access_blocked) {
base::DictionaryValue* problem = new base::DictionaryValue();
problem->SetString("description",
"GPU process was unable to boot: " + gpu_access_blocked_reason);
problem->Set("crBugs", new base::ListValue());
problem->Set("webkitBugs", new base::ListValue());
base::ListValue* disabled_features = new base::ListValue();
disabled_features->AppendString("all");
problem->Set("affectedGpuSettings", disabled_features);
problem->SetString("tag", "disabledFeatures");
problem_list->Insert(0, problem);
}
bool eof = false;
for (size_t i = 0; !eof; ++i) {
const GpuFeatureInfo gpu_feature_info = GetGpuFeatureInfo(i, &eof);
if (gpu_feature_info.disabled) {
base::DictionaryValue* problem = new base::DictionaryValue();
problem->SetString(
"description", gpu_feature_info.disabled_description);
problem->Set("crBugs", new base::ListValue());
problem->Set("webkitBugs", new base::ListValue());
base::ListValue* disabled_features = new base::ListValue();
disabled_features->AppendString(gpu_feature_info.name);
problem->Set("affectedGpuSettings", disabled_features);
problem->SetString("tag", "disabledFeatures");
problem_list->Append(problem);
}
}
return problem_list;
}
base::Value* GetDriverBugWorkarounds() {
base::ListValue* workaround_list = new base::ListValue();
GpuDataManagerImpl::GetInstance()->GetDriverBugWorkarounds(workaround_list);
return workaround_list;
}
} // namespace content
|
// 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 "content/browser/gpu/compositor_util.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/strings/string_number_conversions.h"
#include "build/build_config.h"
#include "cc/base/switches.h"
#include "content/browser/gpu/gpu_data_manager_impl.h"
#include "content/public/common/content_switches.h"
#include "gpu/config/gpu_feature_type.h"
namespace content {
namespace {
static bool IsGpuRasterizationBlacklisted() {
GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance();
return manager->IsFeatureBlacklisted(
gpu::GPU_FEATURE_TYPE_GPU_RASTERIZATION);
}
const char* kGpuCompositingFeatureName = "gpu_compositing";
const char* kWebGLFeatureName = "webgl";
const char* kRasterizationFeatureName = "rasterization";
const char* kThreadedRasterizationFeatureName = "threaded_rasterization";
const char* kMultipleRasterThreadsFeatureName = "multiple_raster_threads";
const int kMinRasterThreads = 1;
const int kMaxRasterThreads = 64;
struct GpuFeatureInfo {
std::string name;
bool blocked;
bool disabled;
std::string disabled_description;
bool fallback_to_software;
};
const GpuFeatureInfo GetGpuFeatureInfo(size_t index, bool* eof) {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance();
const GpuFeatureInfo kGpuFeatureInfo[] = {
{
"2d_canvas",
manager->IsFeatureBlacklisted(
gpu::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS),
command_line.HasSwitch(switches::kDisableAccelerated2dCanvas) ||
!GpuDataManagerImpl::GetInstance()->
GetGPUInfo().SupportsAccelerated2dCanvas(),
"Accelerated 2D canvas is unavailable: either disabled at the command"
" line or not supported by the current system.",
true
},
{
kGpuCompositingFeatureName,
manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_GPU_COMPOSITING),
command_line.HasSwitch(switches::kDisableGpuCompositing),
"Gpu compositing has been disabled, either via about:flags or"
" command line. The browser will fall back to software compositing"
" and hardware acceleration will be unavailable.",
true
},
{
kWebGLFeatureName,
manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_WEBGL),
command_line.HasSwitch(switches::kDisableExperimentalWebGL),
"WebGL has been disabled, either via about:flags or command line.",
false
},
{
"flash_3d",
manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_FLASH3D),
command_line.HasSwitch(switches::kDisableFlash3d),
"Using 3d in flash has been disabled, either via about:flags or"
" command line.",
true
},
{
"flash_stage3d",
manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D),
command_line.HasSwitch(switches::kDisableFlashStage3d),
"Using Stage3d in Flash has been disabled, either via about:flags or"
" command line.",
true
},
{
"flash_stage3d_baseline",
manager->IsFeatureBlacklisted(
gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D_BASELINE) ||
manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D),
command_line.HasSwitch(switches::kDisableFlashStage3d),
"Using Stage3d Baseline profile in Flash has been disabled, either"
" via about:flags or command line.",
true
},
{
"video_decode",
manager->IsFeatureBlacklisted(
gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE),
command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode),
"Accelerated video decode has been disabled, either via about:flags"
" or command line.",
true
},
#if defined(ENABLE_WEBRTC)
{
"video_encode",
manager->IsFeatureBlacklisted(
gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_ENCODE),
command_line.HasSwitch(switches::kDisableWebRtcHWEncoding),
"Accelerated video encode has been disabled, either via about:flags"
" or command line.",
true
},
#endif
#if defined(OS_CHROMEOS)
{
"panel_fitting",
manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_PANEL_FITTING),
command_line.HasSwitch(switches::kDisablePanelFitting),
"Panel fitting has been disabled, either via about:flags or command"
" line.",
false
},
#endif
{
kRasterizationFeatureName,
IsGpuRasterizationBlacklisted() &&
!IsGpuRasterizationEnabled() && !IsForceGpuRasterizationEnabled(),
!IsGpuRasterizationEnabled() && !IsForceGpuRasterizationEnabled() &&
!IsGpuRasterizationBlacklisted(),
"Accelerated rasterization has been disabled, either via about:flags"
" or command line.",
true
},
{
kThreadedRasterizationFeatureName,
false,
!IsImplSidePaintingEnabled(),
"Threaded rasterization has not been enabled or"
" is not supported by the current system.",
false
},
{
kMultipleRasterThreadsFeatureName,
false,
NumberOfRendererRasterThreads() == 1,
"Raster is using a single thread.",
false
},
};
DCHECK(index < arraysize(kGpuFeatureInfo));
*eof = (index == arraysize(kGpuFeatureInfo) - 1);
return kGpuFeatureInfo[index];
}
} // namespace
bool IsPinchVirtualViewportEnabled() {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
// Command line switches take precedence over platform default.
if (command_line.HasSwitch(cc::switches::kDisablePinchVirtualViewport))
return false;
if (command_line.HasSwitch(cc::switches::kEnablePinchVirtualViewport))
return true;
#if defined(OS_CHROMEOS)
return true;
#else
return false;
#endif
}
bool IsDelegatedRendererEnabled() {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
bool enabled = false;
#if defined(USE_AURA) || defined(OS_MACOSX)
// Enable on Aura and Mac.
enabled = true;
#endif
// Flags override.
enabled |= command_line.HasSwitch(switches::kEnableDelegatedRenderer);
enabled &= !command_line.HasSwitch(switches::kDisableDelegatedRenderer);
return enabled;
}
bool IsImplSidePaintingEnabled() {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kEnableImplSidePainting))
return true;
else if (command_line.HasSwitch(switches::kDisableImplSidePainting))
return false;
return true;
}
int NumberOfRendererRasterThreads() {
int num_raster_threads = 1;
int force_num_raster_threads = ForceNumberOfRendererRasterThreads();
if (force_num_raster_threads)
num_raster_threads = force_num_raster_threads;
return num_raster_threads;
}
int ForceNumberOfRendererRasterThreads() {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
if (!command_line.HasSwitch(switches::kNumRasterThreads))
return 0;
std::string string_value =
command_line.GetSwitchValueASCII(switches::kNumRasterThreads);
int force_num_raster_threads = 0;
if (base::StringToInt(string_value, &force_num_raster_threads) &&
force_num_raster_threads >= kMinRasterThreads &&
force_num_raster_threads <= kMaxRasterThreads) {
return force_num_raster_threads;
} else {
LOG(WARNING) << "Failed to parse switch " <<
switches::kNumRasterThreads << ": " << string_value;
return 0;
}
}
bool IsGpuRasterizationEnabled() {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
if (!IsImplSidePaintingEnabled())
return false;
if (command_line.HasSwitch(switches::kDisableGpuRasterization))
return false;
else if (command_line.HasSwitch(switches::kEnableGpuRasterization))
return true;
if (IsGpuRasterizationBlacklisted()) {
return false;
}
return true;
}
bool IsForceGpuRasterizationEnabled() {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
if (!IsImplSidePaintingEnabled())
return false;
return command_line.HasSwitch(switches::kForceGpuRasterization);
}
bool UseSurfacesEnabled() {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
return command_line.HasSwitch(switches::kUseSurfaces);
}
base::Value* GetFeatureStatus() {
GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance();
std::string gpu_access_blocked_reason;
bool gpu_access_blocked =
!manager->GpuAccessAllowed(&gpu_access_blocked_reason);
base::DictionaryValue* feature_status_dict = new base::DictionaryValue();
bool eof = false;
for (size_t i = 0; !eof; ++i) {
const GpuFeatureInfo gpu_feature_info = GetGpuFeatureInfo(i, &eof);
std::string status;
if (gpu_feature_info.disabled) {
status = "disabled";
if (gpu_feature_info.fallback_to_software)
status += "_software";
else
status += "_off";
if (gpu_feature_info.name == kThreadedRasterizationFeatureName)
status += "_ok";
} else if (gpu_feature_info.blocked ||
gpu_access_blocked) {
status = "unavailable";
if (gpu_feature_info.fallback_to_software)
status += "_software";
else
status += "_off";
} else {
status = "enabled";
if (gpu_feature_info.name == kWebGLFeatureName &&
manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_GPU_COMPOSITING))
status += "_readback";
if (gpu_feature_info.name == kRasterizationFeatureName) {
if (IsForceGpuRasterizationEnabled())
status += "_force";
}
if (gpu_feature_info.name == kMultipleRasterThreadsFeatureName) {
if (ForceNumberOfRendererRasterThreads() > 0)
status += "_force";
}
if (gpu_feature_info.name == kThreadedRasterizationFeatureName ||
gpu_feature_info.name == kMultipleRasterThreadsFeatureName)
status += "_on";
}
if (gpu_feature_info.name == kWebGLFeatureName &&
(gpu_feature_info.blocked || gpu_access_blocked) &&
manager->ShouldUseSwiftShader()) {
status = "unavailable_software";
}
feature_status_dict->SetString(
gpu_feature_info.name.c_str(), status.c_str());
}
return feature_status_dict;
}
base::Value* GetProblems() {
GpuDataManagerImpl* manager = GpuDataManagerImpl::GetInstance();
std::string gpu_access_blocked_reason;
bool gpu_access_blocked =
!manager->GpuAccessAllowed(&gpu_access_blocked_reason);
base::ListValue* problem_list = new base::ListValue();
manager->GetBlacklistReasons(problem_list);
if (gpu_access_blocked) {
base::DictionaryValue* problem = new base::DictionaryValue();
problem->SetString("description",
"GPU process was unable to boot: " + gpu_access_blocked_reason);
problem->Set("crBugs", new base::ListValue());
problem->Set("webkitBugs", new base::ListValue());
base::ListValue* disabled_features = new base::ListValue();
disabled_features->AppendString("all");
problem->Set("affectedGpuSettings", disabled_features);
problem->SetString("tag", "disabledFeatures");
problem_list->Insert(0, problem);
}
bool eof = false;
for (size_t i = 0; !eof; ++i) {
const GpuFeatureInfo gpu_feature_info = GetGpuFeatureInfo(i, &eof);
if (gpu_feature_info.disabled) {
base::DictionaryValue* problem = new base::DictionaryValue();
problem->SetString(
"description", gpu_feature_info.disabled_description);
problem->Set("crBugs", new base::ListValue());
problem->Set("webkitBugs", new base::ListValue());
base::ListValue* disabled_features = new base::ListValue();
disabled_features->AppendString(gpu_feature_info.name);
problem->Set("affectedGpuSettings", disabled_features);
problem->SetString("tag", "disabledFeatures");
problem_list->Append(problem);
}
}
return problem_list;
}
base::Value* GetDriverBugWorkarounds() {
base::ListValue* workaround_list = new base::ListValue();
GpuDataManagerImpl::GetInstance()->GetDriverBugWorkarounds(workaround_list);
return workaround_list;
}
} // namespace content
|
Make enable override disable impl-side painting
|
Make enable override disable impl-side painting
In order to turn on impl-side painting for layout tests incrementally,
it'd be convenient to have a positive flag that can be added to each
suite as it is ready. Rather than adding some override force flag,
just make the presence of enable override disable. The only user
of disable is currently content shell.
[email protected]
BUG=381919
Review URL: https://codereview.chromium.org/670253002
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#300946}
|
C++
|
bsd-3-clause
|
krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,M4sse/chromium.src,fujunwei/chromium-crosswalk,Chilledheart/chromium,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,chuan9/chromium-crosswalk,jaruba/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,ltilve/chromium,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,chuan9/chromium-crosswalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,markYoungH/chromium.src,ltilve/chromium,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,ltilve/chromium,chuan9/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,dednal/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,Chilledheart/chromium,M4sse/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,Jonekee/chromium.src,fujunwei/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,M4sse/chromium.src,jaruba/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,dednal/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,dushu1203/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,Just-D/chromium-1,Chilledheart/chromium,hgl888/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,ltilve/chromium,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,dednal/chromium.src,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,ltilve/chromium,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,Chilledheart/chromium,markYoungH/chromium.src,Jonekee/chromium.src,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,markYoungH/chromium.src,markYoungH/chromium.src,axinging/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,krieger-od/nwjs_chromium.src,dednal/chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,jaruba/chromium.src,fujunwei/chromium-crosswalk,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,M4sse/chromium.src,ltilve/chromium,M4sse/chromium.src,jaruba/chromium.src,Jonekee/chromium.src,axinging/chromium-crosswalk,dushu1203/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,M4sse/chromium.src,markYoungH/chromium.src,Just-D/chromium-1,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk
|
9f543dd7b0fa2291230ca9baf594c4d00ddea12e
|
lima_linguisticprocessing/src/linguisticProcessing/core/FlatTokenizer/Text.cpp
|
lima_linguisticprocessing/src/linguisticProcessing/core/FlatTokenizer/Text.cpp
|
/*
Copyright 2002-2013 CEA LIST
This file is part of LIMA.
LIMA 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.
LIMA is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with LIMA. If not, see <http://www.gnu.org/licenses/>
*/
// NAUTITIA
//
// jys 24-JUL-2002
//
// Text is the class which reads original text and does its
// 1st transformation into characters classes string.
#include "Text.h"
#include "CharChart.h"
#include "common/Data/strwstrtools.h"
#include "linguisticProcessing/client/LinguisticProcessingException.h"
#include "linguisticProcessing/core/LinguisticAnalysisStructure/Token.h"
#include "linguisticProcessing/core/LinguisticAnalysisStructure/TStatus.h"
#include "linguisticProcessing/core/LinguisticAnalysisStructure/MorphoSyntacticData.h"
using namespace Lima;
using namespace Lima::LinguisticProcessing::LinguisticAnalysisStructure;
using namespace Lima::Common::Misc;
namespace Lima
{
namespace LinguisticProcessing
{
namespace FlatTokenizer
{
Text::Text(MediaId lang, const CharChart* charChart) :
m_text(),
_curPtr(0),
_debPtr(0),
_curSettings(),
_tTokenGraph(0),
_currentVx(0),
_lastVx(0),
_isDone(false),
_thereIsUnknown(false),
_stringsPool(0),
m_charChart(charChart)
{
_stringsPool=&Common::MediaticData::MediaticData::changeable().stringsPool(lang);
}
Text::~Text()
{
// cout << "Text::~Text" << endl;
}
void Text::setText(const Lima::LimaString& text)
{
m_text = text;
_curPtr = 0;
_debPtr = 0;
_tTokenGraph = 0;
_currentVx = 0;
_lastVx = 0;
_isDone = false;
_thereIsUnknown = false;
}
// Clear the entirely class and structure to accept new text
void Text::clear()
{
// _tTokenList = NULL; Not destroyed here
_thereIsUnknown = false;
}
void Text::setGraph(LinguisticGraphVertex position,LinguisticGraph* graph)
{
_currentVx=position;
_tTokenGraph=graph;
// go one step forward on the new path
LinguisticGraphAdjacencyIt adjItr,adjItrEnd;
boost::tie (adjItr,adjItrEnd) = adjacent_vertices(_currentVx,*_tTokenGraph);
if (adjItr==adjItrEnd)
{
TOKENIZERLOGINIT;
LERROR << "Tokenizer Text : no token forward !";
throw LinguisticProcessingException();
}
_lastVx=*adjItr;
if (++adjItr!=adjItrEnd) {
TOKENIZERLOGINIT;
LERROR << "Tokenizer Text : more than one next token !";
throw LinguisticProcessingException();
}
//remove_edge(_currentVx,_lastVx,*_tTokenGraph);
}
void Text::finalizeAndUnsetGraph()
{
add_edge(_currentVx,_lastVx,*_tTokenGraph);
_tTokenGraph=0;
}
// increments text pointer
Lima::LimaChar Text::advance()
{
TOKENIZERLOGINIT;
if (_curPtr+1 >= static_cast<uint64_t>(m_text.size()))
{
LDEBUG << "Trying to move after text end.";
_curPtr++;
return 0;
}
if (m_text[_curPtr] >= 0xD800)
{
_curPtr++;
}
_curPtr++;
LDEBUG << "Text::advance : new current=" << _curPtr << " from='" << Common::Misc::limastring2utf8stdstring(LimaString()+m_text[_curPtr-1]) << "' to='" << Common::Misc::limastring2utf8stdstring(LimaString()+m_text[_curPtr]) << "'";
return m_text[_curPtr];
}
const CharClass* Text::currentClass() const
{
// TOKENIZERLOGINIT;
// LDEBUG << "currentClass() at " << _curPtr << ", for " << m_text[_curPtr];
if (_curPtr+1 >= static_cast<uint64_t>(m_text.size()))
{
return m_charChart->charClass(0);
}
if (m_text[_curPtr] >= 0xD800)
{
return m_charChart->charClass( m_text[_curPtr], m_text[_curPtr+1] );
}
else
{
return m_charChart->charClass( m_text[_curPtr] );
}
}
// flushes current token
void Text::flush()
{
_debPtr = _curPtr;
}
// takes a token
LimaString Text::token()
{
TOKENIZERLOGINIT;
// Creates a new token
uint64_t delta = _curPtr;
if (m_text[_curPtr] >= 0xD800 || _curPtr == _debPtr)
{
delta++;
}
if (_debPtr >= static_cast<uint64_t>(m_text.size()))
{
LERROR << "Empty token !";
_debPtr = delta;
_curSettings.reset();
return utf8stdstring2limastring("");
}
LimaString str=m_text.mid( _debPtr, (delta-_debPtr));
LDEBUG << " Adding token '" << str << "'";
StringsPoolIndex form=(*_stringsPool)[str];
Token *tToken = new Token(form,str,_debPtr+1,(delta-_debPtr));
if (tToken == NULL) throw MemoryErrorException();
// @todo: set default status here, according to structured status (alpha,numeric etc...)
// instead of setting it at each change of status (setAlphaCapital, setNumeric etc...)
tToken->setStatus(_curSettings);
// LDEBUG << " _curSettings is " << _curSettings.toString();
LDEBUG << " status is " << tToken->status().toString();
// Adds on the path
LinguisticGraphVertex newVx=add_vertex(*_tTokenGraph);
put(vertex_token,*_tTokenGraph,newVx,tToken);
put(vertex_data,*_tTokenGraph,newVx,new MorphoSyntacticData());
add_edge(_currentVx,newVx,*_tTokenGraph);
_currentVx=newVx;
_debPtr = delta;
_curSettings.reset();
return str;
}
// performs a trace
void Text::trace()
{}
LimaChar Text::operator[] (int i) const {
if (((static_cast<int>(_curPtr)+i) < 0) || (static_cast<int>(_curPtr)+i >= m_text.size()))
throw BoundsErrorException();
return m_text[_curPtr+i];
}
void Text::setAlphaCapital(const LinguisticAnalysisStructure::AlphaCapitalType alphaCapital)
{
TOKENIZERLOGINIT;
LDEBUG << "Text::setAlphaCapital " << alphaCapital;
_curSettings.setAlphaCapital(alphaCapital);
switch (alphaCapital)
{
case T_CAPITAL:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_capital"));
break;
case T_SMALL:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_small"));
break;
case T_CAPITAL_1ST:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_capital_1st"));
break;
case T_ACRONYM:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_acronym"));
break;
case T_CAPITAL_SMALL:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_capital_small"));
break;
default:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_small"));
}
}
void Text::setAlphaRoman(const LinguisticAnalysisStructure::AlphaRomanType alphaRoman)
{
TOKENIZERLOGINIT;
LDEBUG << "Text::setAlphaRoman " << alphaRoman;
_curSettings.setAlphaRoman(alphaRoman);
switch (alphaRoman)
{
case T_CARDINAL_ROMAN:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_cardinal_roman"));
break;
case T_ORDINAL_ROMAN:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_ordinal_roman"));
break;
case T_NOT_ROMAN:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_not_roman"));
break;
default:;
}
}
void Text::setAlphaHyphen(const unsigned char isAlphaHyphen)
{
TOKENIZERLOGINIT;
LDEBUG << "Text::setAlphaHyphen " << isAlphaHyphen;
_curSettings.setAlphaHyphen(isAlphaHyphen);
}
void Text::setAlphaPossessive(const unsigned char isAlphaPossessive)
{
TOKENIZERLOGINIT;
LDEBUG << "Text::setAlphaPossessive " << isAlphaPossessive;
_curSettings.setAlphaPossessive(isAlphaPossessive);
/* if (isAlphaPossessive > 0)
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_alpha_possessive"));*/
}
void Text::setAlphaConcatAbbrev(const unsigned char isConcatAbbreviation)
{
TOKENIZERLOGINIT;
LDEBUG << "Text::setAlphaConcatAbbrev " << isConcatAbbreviation;
_curSettings.setAlphaConcatAbbrev(isConcatAbbreviation);
if (isConcatAbbreviation> 0)
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_alpha_concat_abbrev"));
}
void Text::setTwitter(const unsigned char isTwitter)
{
TOKENIZERLOGINIT;
LDEBUG << "Text::setTwitter " << isTwitter;
_curSettings.setTwitter(isTwitter);
if (isTwitter> 0)
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_twitter"));
}
void Text::setNumeric(const LinguisticAnalysisStructure::NumericType numeric)
{
TOKENIZERLOGINIT;
LDEBUG << "Text::setNumeric " << numeric;
_curSettings.setNumeric(numeric);
switch (numeric)
{
case T_INTEGER:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_integer"));
break;
case T_COMMA_NUMBER:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_comma_number"));
break;
case T_DOT_NUMBER:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_dot_number"));
break;
case T_FRACTION:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_fraction"));
break;
case T_ORDINAL_INTEGER:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_ordinal_integer"));
break;
default:;
}
}
void Text::setStatus(const LinguisticAnalysisStructure::StatusType status)
{
TOKENIZERLOGINIT;
LDEBUG << "Text::setStatus " << status;
LinguisticAnalysisStructure::StatusType previousStatus = _curSettings.getStatus();
_curSettings.setStatus(status);
switch (status)
{
case T_ALPHA:
if (previousStatus != T_ALPHA)
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_alphanumeric"));
break;
case T_NUMERIC:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_alphanumeric"));
break;
case T_ALPHANUMERIC:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_alphanumeric"));
break;
case T_PATTERN:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_pattern"));
break;
case T_WORD_BRK:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_word_brk"));
break;
case T_SENTENCE_BRK:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_sentence_brk"));
break;
case T_PARAGRAPH_BRK:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_paragraph_brk"));
break;
default:;
}
}
void Text::setDefaultKey(const Lima::LimaString& defaultKey)
{
TOKENIZERLOGINIT;
LDEBUG << "Text::setDefaultKey " << Common::Misc::limastring2utf8stdstring(defaultKey);
_curSettings.setDefaultKey(defaultKey);
}
// set default key in status according to other elements in status
void Text::computeDefaultStatus()
{
std::string defaultKey;
switch (_curSettings.getStatus()) {
case T_ALPHA : {
switch (_curSettings.getAlphaCapital()) {
case T_CAPITAL : defaultKey = "t_capital" ; break;
case T_SMALL : defaultKey = "t_small" ; break;
case T_CAPITAL_1ST : defaultKey = "t_capital_1st" ; break;
case T_ACRONYM : defaultKey = "t_acronym" ; break;
case T_CAPITAL_SMALL : defaultKey = "t_capital_small"; break;
default : break;
}
switch (_curSettings.getAlphaRoman()) { // Roman supersedes Cardinal
case T_CARDINAL_ROMAN : defaultKey = "t_cardinal_roman"; break;
case T_ORDINAL_ROMAN : defaultKey = "t_ordinal_roman" ; break;
case T_NOT_ROMAN : defaultKey = "t_not_roman" ; break;
default : break;
}
if (_curSettings.isAlphaHyphen()) {
//no change
//defaultKey = "t_alpha_hyphen";
}
if (_curSettings.isAlphaPossessive()) {
defaultKey = "t_alpha_possessive";
}
break;
} // end T_ALPHA
case T_NUMERIC : {
switch (_curSettings.getNumeric()) {
case T_INTEGER : defaultKey = "t_integer" ; break;
case T_COMMA_NUMBER : defaultKey = "t_comma_number" ; break;
case T_DOT_NUMBER : defaultKey = "t_dot_number" ; break;
case T_FRACTION : defaultKey = "t_fraction" ; break;
case T_ORDINAL_INTEGER : defaultKey = "t_ordinal_integer"; break;
default: break;
}
break;
}
case T_ALPHANUMERIC : defaultKey = "t_alphanumeric" ; break;
case T_PATTERN : defaultKey = "t_pattern" ; break;
case T_WORD_BRK : defaultKey = "t_word_brk" ; break;
case T_SENTENCE_BRK : defaultKey = "t_sentence_brk" ; break;
case T_PARAGRAPH_BRK: defaultKey = "t_paragraph_brk" ; break;
default: defaultKey = "t_fallback";
}
TOKENIZERLOGINIT;
LDEBUG << "Text::computeDefaultKey " << defaultKey;
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring(defaultKey));
}
} //namespace FlatTokenizer
} // namespace LinguisticProcessing
} // namespace Lima
|
/*
Copyright 2002-2013 CEA LIST
This file is part of LIMA.
LIMA 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.
LIMA is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with LIMA. If not, see <http://www.gnu.org/licenses/>
*/
// NAUTITIA
//
// jys 24-JUL-2002
//
// Text is the class which reads original text and does its
// 1st transformation into characters classes string.
#include "Text.h"
#include "CharChart.h"
#include "common/Data/strwstrtools.h"
#include "linguisticProcessing/client/LinguisticProcessingException.h"
#include "linguisticProcessing/core/LinguisticAnalysisStructure/Token.h"
#include "linguisticProcessing/core/LinguisticAnalysisStructure/TStatus.h"
#include "linguisticProcessing/core/LinguisticAnalysisStructure/MorphoSyntacticData.h"
using namespace Lima;
using namespace Lima::LinguisticProcessing::LinguisticAnalysisStructure;
using namespace Lima::Common::Misc;
namespace Lima
{
namespace LinguisticProcessing
{
namespace FlatTokenizer
{
Text::Text(MediaId lang, const CharChart* charChart) :
m_text(),
_curPtr(0),
_debPtr(0),
_curSettings(),
_tTokenGraph(0),
_currentVx(0),
_lastVx(0),
_isDone(false),
_thereIsUnknown(false),
_stringsPool(0),
m_charChart(charChart)
{
_stringsPool=&Common::MediaticData::MediaticData::changeable().stringsPool(lang);
}
Text::~Text()
{
// cout << "Text::~Text" << endl;
}
void Text::setText(const Lima::LimaString& text)
{
m_text = text;
_curPtr = 0;
_debPtr = 0;
_tTokenGraph = 0;
_currentVx = 0;
_lastVx = 0;
_isDone = false;
_thereIsUnknown = false;
}
// Clear the entirely class and structure to accept new text
void Text::clear()
{
// _tTokenList = 0; Not destroyed here
_thereIsUnknown = false;
}
void Text::setGraph(LinguisticGraphVertex position,LinguisticGraph* graph)
{
_currentVx=position;
_tTokenGraph=graph;
// go one step forward on the new path
LinguisticGraphAdjacencyIt adjItr,adjItrEnd;
boost::tie (adjItr,adjItrEnd) = adjacent_vertices(_currentVx,*_tTokenGraph);
if (adjItr==adjItrEnd)
{
TOKENIZERLOGINIT;
LERROR << "Tokenizer Text : no token forward !";
throw LinguisticProcessingException();
}
_lastVx=*adjItr;
if (++adjItr!=adjItrEnd) {
TOKENIZERLOGINIT;
LERROR << "Tokenizer Text : more than one next token !";
throw LinguisticProcessingException();
}
//remove_edge(_currentVx,_lastVx,*_tTokenGraph);
}
void Text::finalizeAndUnsetGraph()
{
add_edge(_currentVx,_lastVx,*_tTokenGraph);
_tTokenGraph=0;
}
// increments text pointer
Lima::LimaChar Text::advance()
{
TOKENIZERLOGINIT;
if (_curPtr+1 >= m_text.size())
{
LDEBUG << "Trying to move after text end.";
_curPtr++;
return 0;
}
if (m_text[_curPtr] >= 0xD800)
{
_curPtr++;
}
_curPtr++;
LDEBUG << "Text::advance : new current=" << _curPtr << " from='" << Common::Misc::limastring2utf8stdstring(LimaString()+m_text[_curPtr-1]) << "' to='" << Common::Misc::limastring2utf8stdstring(LimaString()+m_text[_curPtr]) << "'";
return m_text[_curPtr];
}
const CharClass* Text::currentClass() const
{
// TOKENIZERLOGINIT;
// LDEBUG << "currentClass() at " << _curPtr << ", for " << m_text[_curPtr];
if (_curPtr+1 >= m_text.size())
{
return m_charChart->charClass(0);
}
if (m_text[_curPtr] >= 0xD800)
{
return m_charChart->charClass( m_text[_curPtr], m_text[_curPtr+1] );
}
else
{
return m_charChart->charClass( m_text[_curPtr] );
}
}
// flushes current token
void Text::flush()
{
_debPtr = _curPtr;
}
// takes a token
LimaString Text::token()
{
TOKENIZERLOGINIT;
// Creates a new token
uint64_t delta = _curPtr;
if (m_text[_curPtr] >= 0xD800 || _curPtr == _debPtr)
{
delta++;
}
if (_debPtr >= m_text.size())
{
LERROR << "Empty token !";
_debPtr = delta;
_curSettings.reset();
return utf8stdstring2limastring("");
}
LimaString str=m_text.mid( _debPtr, (delta-_debPtr));
LDEBUG << " Adding token '" << str << "'";
StringsPoolIndex form=(*_stringsPool)[str];
Token *tToken = new Token(form,str,_debPtr+1,(delta-_debPtr));
if (tToken == 0) throw MemoryErrorException();
// @todo: set default status here, according to structured status (alpha,numeric etc...)
// instead of setting it at each change of status (setAlphaCapital, setNumeric etc...)
tToken->setStatus(_curSettings);
// LDEBUG << " _curSettings is " << _curSettings.toString();
LDEBUG << " status is " << tToken->status().toString();
// Adds on the path
LinguisticGraphVertex newVx=add_vertex(*_tTokenGraph);
put(vertex_token,*_tTokenGraph,newVx,tToken);
put(vertex_data,*_tTokenGraph,newVx,new MorphoSyntacticData());
add_edge(_currentVx,newVx,*_tTokenGraph);
_currentVx=newVx;
_debPtr = delta;
_curSettings.reset();
return str;
}
// performs a trace
void Text::trace()
{}
LimaChar Text::operator[] (int i) const {
if (((static_cast<int>(_curPtr)+i) < 0) || (static_cast<int>(_curPtr)+i >= m_text.size()))
throw BoundsErrorException();
return m_text[_curPtr+i];
}
void Text::setAlphaCapital(const LinguisticAnalysisStructure::AlphaCapitalType alphaCapital)
{
TOKENIZERLOGINIT;
LDEBUG << "Text::setAlphaCapital " << alphaCapital;
_curSettings.setAlphaCapital(alphaCapital);
switch (alphaCapital)
{
case T_CAPITAL:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_capital"));
break;
case T_SMALL:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_small"));
break;
case T_CAPITAL_1ST:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_capital_1st"));
break;
case T_ACRONYM:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_acronym"));
break;
case T_CAPITAL_SMALL:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_capital_small"));
break;
default:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_small"));
}
}
void Text::setAlphaRoman(const LinguisticAnalysisStructure::AlphaRomanType alphaRoman)
{
TOKENIZERLOGINIT;
LDEBUG << "Text::setAlphaRoman " << alphaRoman;
_curSettings.setAlphaRoman(alphaRoman);
switch (alphaRoman)
{
case T_CARDINAL_ROMAN:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_cardinal_roman"));
break;
case T_ORDINAL_ROMAN:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_ordinal_roman"));
break;
case T_NOT_ROMAN:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_not_roman"));
break;
default:;
}
}
void Text::setAlphaHyphen(const unsigned char isAlphaHyphen)
{
TOKENIZERLOGINIT;
LDEBUG << "Text::setAlphaHyphen " << isAlphaHyphen;
_curSettings.setAlphaHyphen(isAlphaHyphen);
}
void Text::setAlphaPossessive(const unsigned char isAlphaPossessive)
{
TOKENIZERLOGINIT;
LDEBUG << "Text::setAlphaPossessive " << isAlphaPossessive;
_curSettings.setAlphaPossessive(isAlphaPossessive);
/* if (isAlphaPossessive > 0)
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_alpha_possessive"));*/
}
void Text::setAlphaConcatAbbrev(const unsigned char isConcatAbbreviation)
{
TOKENIZERLOGINIT;
LDEBUG << "Text::setAlphaConcatAbbrev " << isConcatAbbreviation;
_curSettings.setAlphaConcatAbbrev(isConcatAbbreviation);
if (isConcatAbbreviation> 0)
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_alpha_concat_abbrev"));
}
void Text::setTwitter(const unsigned char isTwitter)
{
TOKENIZERLOGINIT;
LDEBUG << "Text::setTwitter " << isTwitter;
_curSettings.setTwitter(isTwitter);
if (isTwitter> 0)
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_twitter"));
}
void Text::setNumeric(const LinguisticAnalysisStructure::NumericType numeric)
{
TOKENIZERLOGINIT;
LDEBUG << "Text::setNumeric " << numeric;
_curSettings.setNumeric(numeric);
switch (numeric)
{
case T_INTEGER:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_integer"));
break;
case T_COMMA_NUMBER:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_comma_number"));
break;
case T_DOT_NUMBER:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_dot_number"));
break;
case T_FRACTION:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_fraction"));
break;
case T_ORDINAL_INTEGER:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_ordinal_integer"));
break;
default:;
}
}
void Text::setStatus(const LinguisticAnalysisStructure::StatusType status)
{
TOKENIZERLOGINIT;
LDEBUG << "Text::setStatus " << status;
LinguisticAnalysisStructure::StatusType previousStatus = _curSettings.getStatus();
_curSettings.setStatus(status);
switch (status)
{
case T_ALPHA:
if (previousStatus != T_ALPHA)
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_alphanumeric"));
break;
case T_NUMERIC:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_alphanumeric"));
break;
case T_ALPHANUMERIC:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_alphanumeric"));
break;
case T_PATTERN:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_pattern"));
break;
case T_WORD_BRK:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_word_brk"));
break;
case T_SENTENCE_BRK:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_sentence_brk"));
break;
case T_PARAGRAPH_BRK:
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring("t_paragraph_brk"));
break;
default:;
}
}
void Text::setDefaultKey(const Lima::LimaString& defaultKey)
{
TOKENIZERLOGINIT;
LDEBUG << "Text::setDefaultKey " << Common::Misc::limastring2utf8stdstring(defaultKey);
_curSettings.setDefaultKey(defaultKey);
}
// set default key in status according to other elements in status
void Text::computeDefaultStatus()
{
std::string defaultKey;
switch (_curSettings.getStatus()) {
case T_ALPHA : {
switch (_curSettings.getAlphaCapital()) {
case T_CAPITAL : defaultKey = "t_capital" ; break;
case T_SMALL : defaultKey = "t_small" ; break;
case T_CAPITAL_1ST : defaultKey = "t_capital_1st" ; break;
case T_ACRONYM : defaultKey = "t_acronym" ; break;
case T_CAPITAL_SMALL : defaultKey = "t_capital_small"; break;
default : break;
}
switch (_curSettings.getAlphaRoman()) { // Roman supersedes Cardinal
case T_CARDINAL_ROMAN : defaultKey = "t_cardinal_roman"; break;
case T_ORDINAL_ROMAN : defaultKey = "t_ordinal_roman" ; break;
case T_NOT_ROMAN : defaultKey = "t_not_roman" ; break;
default : break;
}
if (_curSettings.isAlphaHyphen()) {
//no change
//defaultKey = "t_alpha_hyphen";
}
if (_curSettings.isAlphaPossessive()) {
defaultKey = "t_alpha_possessive";
}
break;
} // end T_ALPHA
case T_NUMERIC : {
switch (_curSettings.getNumeric()) {
case T_INTEGER : defaultKey = "t_integer" ; break;
case T_COMMA_NUMBER : defaultKey = "t_comma_number" ; break;
case T_DOT_NUMBER : defaultKey = "t_dot_number" ; break;
case T_FRACTION : defaultKey = "t_fraction" ; break;
case T_ORDINAL_INTEGER : defaultKey = "t_ordinal_integer"; break;
default: break;
}
break;
}
case T_ALPHANUMERIC : defaultKey = "t_alphanumeric" ; break;
case T_PATTERN : defaultKey = "t_pattern" ; break;
case T_WORD_BRK : defaultKey = "t_word_brk" ; break;
case T_SENTENCE_BRK : defaultKey = "t_sentence_brk" ; break;
case T_PARAGRAPH_BRK: defaultKey = "t_paragraph_brk" ; break;
default: defaultKey = "t_fallback";
}
TOKENIZERLOGINIT;
LDEBUG << "Text::computeDefaultKey " << defaultKey;
_curSettings.setDefaultKey(Common::Misc::utf8stdstring2limastring(defaultKey));
}
} //namespace FlatTokenizer
} // namespace LinguisticProcessing
} // namespace Lima
|
Correct some compilation warnings
|
Correct some compilation warnings
|
C++
|
agpl-3.0
|
FaizaGara/lima,FaizaGara/lima,FaizaGara/lima,FaizaGara/lima,FaizaGara/lima,FaizaGara/lima,FaizaGara/lima
|
f3788e8f227ba53916c9193709e427dd224a4f58
|
moveit_ros/visualization/motion_planning_rviz_plugin/src/motion_planning_frame_planning.cpp
|
moveit_ros/visualization/motion_planning_rviz_plugin/src/motion_planning_frame_planning.cpp
|
/*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. 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: Ioan Sucan */
#include <moveit/motion_planning_rviz_plugin/motion_planning_frame.h>
#include <moveit/motion_planning_rviz_plugin/motion_planning_display.h>
#include <moveit/kinematic_constraints/utils.h>
#include <moveit/robot_state/conversions.h>
#include "ui_motion_planning_rviz_plugin_frame.h"
namespace moveit_rviz_plugin
{
void MotionPlanningFrame::planButtonClicked()
{
planning_display_->addBackgroundJob(boost::bind(&MotionPlanningFrame::computePlanButtonClicked, this));
}
void MotionPlanningFrame::executeButtonClicked()
{
ui_->execute_button->setEnabled(false);
planning_display_->addBackgroundJob(boost::bind(&MotionPlanningFrame::computeExecuteButtonClicked, this));
}
void MotionPlanningFrame::planAndExecuteButtonClicked()
{
ui_->plan_and_execute_button->setEnabled(false);
ui_->execute_button->setEnabled(false);
planning_display_->addBackgroundJob(boost::bind(&MotionPlanningFrame::computePlanAndExecuteButtonClicked, this));
}
void MotionPlanningFrame::allowReplanningToggled(bool checked)
{
if (move_group_)
move_group_->allowReplanning(checked);
}
void MotionPlanningFrame::allowLookingToggled(bool checked)
{
if (move_group_)
move_group_->allowLooking(checked);
}
void MotionPlanningFrame::pathConstraintsIndexChanged(int index)
{
if (move_group_)
{
if (index > 0)
move_group_->setPathConstraints(ui_->path_constraints_combo_box->itemText(index).toStdString());
else
move_group_->clearPathConstraints();
}
}
void MotionPlanningFrame::computePlanButtonClicked()
{
if (!move_group_)
return;
configureForPlanning();
current_plan_.reset(new move_group_interface::MoveGroup::Plan());
if (move_group_->plan(*current_plan_))
ui_->execute_button->setEnabled(true);
else
current_plan_.reset();
}
void MotionPlanningFrame::computeExecuteButtonClicked()
{
if (move_group_ && current_plan_)
move_group_->execute(*current_plan_);
}
void MotionPlanningFrame::computePlanAndExecuteButtonClicked()
{
if (!move_group_)
return;
configureForPlanning();
move_group_->move();
ui_->plan_and_execute_button->setEnabled(true);
}
void MotionPlanningFrame::useStartStateButtonClicked()
{
robot_state::RobotState start = *planning_display_->getQueryStartState();
updateQueryStateHelper(start, ui_->start_state_selection->currentText().toStdString());
planning_display_->setQueryStartState(start);
}
void MotionPlanningFrame::useGoalStateButtonClicked()
{
robot_state::RobotState goal = *planning_display_->getQueryGoalState();
updateQueryStateHelper(goal, ui_->goal_state_selection->currentText().toStdString());
planning_display_->setQueryGoalState(goal);
}
void MotionPlanningFrame::updateQueryStateHelper(robot_state::RobotState &state, const std::string &v)
{
if (v == "<random>")
{
configureWorkspace();
if (robot_state::JointStateGroup *jsg = state.getJointStateGroup(planning_display_->getCurrentPlanningGroup()))
jsg->setToRandomValues();
}
else
if (v == "<current>")
{
const planning_scene_monitor::LockedPlanningSceneRO &ps = planning_display_->getPlanningSceneRO();
if (ps)
state = ps->getCurrentState();
}
else
if (v == "<same as goal>")
{
state = *planning_display_->getQueryGoalState();
}
else
if (v == "<same as start>")
{
state = *planning_display_->getQueryStartState();
}
else
{
// maybe it is a named state
if (robot_state::JointStateGroup *jsg = state.getJointStateGroup(planning_display_->getCurrentPlanningGroup()))
jsg->setToDefaultState(v);
}
}
void MotionPlanningFrame::populatePlannersList(const moveit_msgs::PlannerInterfaceDescription &desc)
{
std::string group = planning_display_->getCurrentPlanningGroup();
ui_->planning_algorithm_combo_box->clear();
// set the label for the planning library
ui_->library_label->setText(QString::fromStdString(desc.name));
ui_->library_label->setStyleSheet("QLabel { color : green; font: bold }");
bool found_group = false;
// the name of a planner is either "GROUP[planner_id]" or "planner_id"
if (!group.empty())
for (std::size_t i = 0 ; i < desc.planner_ids.size() ; ++i)
if (desc.planner_ids[i] == group)
found_group = true;
else
if (desc.planner_ids[i].substr(0, group.length()) == group)
{
std::string id = desc.planner_ids[i].substr(group.length());
if (id.size() > 2)
{
id.resize(id.length() - 1);
ui_->planning_algorithm_combo_box->addItem(QString::fromStdString(id.substr(1)));
}
}
if (ui_->planning_algorithm_combo_box->count() == 0 && !found_group)
for (std::size_t i = 0 ; i < desc.planner_ids.size() ; ++i)
ui_->planning_algorithm_combo_box->addItem(QString::fromStdString(desc.planner_ids[i]));
ui_->planning_algorithm_combo_box->insertItem(0, "<unspecified>");
ui_->planning_algorithm_combo_box->setCurrentIndex(0);
}
void MotionPlanningFrame::populateConstraintsList()
{
if (move_group_)
{
// add some artificial wait time (but in the background) for the constraints DB to connect
double dt = (ros::WallTime::now() - move_group_construction_time_).toSec();
if (dt < 0.2)
ros::WallDuration(0.1).sleep();
planning_display_->addMainLoopJob(boost::bind(&MotionPlanningFrame::populateConstraintsList, this, move_group_->getKnownConstraints()));
}
}
void MotionPlanningFrame::populateConstraintsList(const std::vector<std::string> &constr)
{
ui_->path_constraints_combo_box->clear();
ui_->path_constraints_combo_box->addItem("None");
for (std::size_t i = 0 ; i < constr.size() ; ++i)
ui_->path_constraints_combo_box->addItem(QString::fromStdString(constr[i]));
}
void MotionPlanningFrame::constructPlanningRequest(moveit_msgs::MotionPlanRequest &mreq)
{
mreq.group_name = planning_display_->getCurrentPlanningGroup();
mreq.num_planning_attempts = 1;
mreq.allowed_planning_time = ui_->planning_time->value();
robot_state::robotStateToRobotStateMsg(*planning_display_->getQueryStartState(), mreq.start_state);
mreq.workspace_parameters.min_corner.x = ui_->wcenter_x->value() - ui_->wsize_x->value() / 2.0;
mreq.workspace_parameters.min_corner.y = ui_->wcenter_y->value() - ui_->wsize_y->value() / 2.0;
mreq.workspace_parameters.min_corner.z = ui_->wcenter_z->value() - ui_->wsize_z->value() / 2.0;
mreq.workspace_parameters.max_corner.x = ui_->wcenter_x->value() + ui_->wsize_x->value() / 2.0;
mreq.workspace_parameters.max_corner.y = ui_->wcenter_y->value() + ui_->wsize_y->value() / 2.0;
mreq.workspace_parameters.max_corner.z = ui_->wcenter_z->value() + ui_->wsize_z->value() / 2.0;
const robot_state::JointStateGroup *jsg = planning_display_->getQueryGoalState()->getJointStateGroup(mreq.group_name);
if (jsg)
{
mreq.goal_constraints.resize(1);
mreq.goal_constraints[0] = kinematic_constraints::constructGoalConstraints(jsg);
}
}
void MotionPlanningFrame::configureWorkspace()
{
kinematic_model::JointModel::Bounds b(3);
b[0].first = ui_->wcenter_x->value() - ui_->wsize_x->value() / 2.0;
b[0].second = ui_->wcenter_x->value() + ui_->wsize_x->value() / 2.0;
b[1].first = ui_->wcenter_y->value() - ui_->wsize_y->value() / 2.0;
b[1].second = ui_->wcenter_y->value() + ui_->wsize_y->value() / 2.0;
b[2].first = ui_->wcenter_z->value() - ui_->wsize_z->value() / 2.0;
b[2].second = ui_->wcenter_z->value() + ui_->wsize_z->value() / 2.0;
if (move_group_)
move_group_->setWorkspace(b[0].first, b[1].first, b[2].first,
b[0].second, b[1].second, b[2].second);
// get non-const access to the kmodel and update planar & floating joints as indicated by the workspace settings
if (planning_display_->getPlanningSceneMonitor() && planning_display_->getPlanningSceneMonitor()->getKinematicModelLoader() &&
planning_display_->getPlanningSceneMonitor()->getKinematicModelLoader()->getModel())
{
const kinematic_model::KinematicModelPtr &kmodel = planning_display_->getPlanningSceneMonitor()->getKinematicModelLoader()->getModel();
const std::vector<kinematic_model::JointModel*> &jm = kmodel->getJointModels();
for (std::size_t i = 0 ; i < jm.size() ; ++i)
if (jm[i]->getType() == kinematic_model::JointModel::PLANAR)
{
jm[i]->setVariableBounds(jm[i]->getName() + "/x", b[0]);
jm[i]->setVariableBounds(jm[i]->getName() + "/y", b[1]);
}
else
if (jm[i]->getType() == kinematic_model::JointModel::FLOATING)
{
jm[i]->setVariableBounds(jm[i]->getName() + "/x", b[0]);
jm[i]->setVariableBounds(jm[i]->getName() + "/y", b[1]);
jm[i]->setVariableBounds(jm[i]->getName() + "/z", b[2]);
}
}
}
void MotionPlanningFrame::configureForPlanning()
{
move_group_->setStartState(*planning_display_->getQueryStartState());
move_group_->setJointValueTarget(*planning_display_->getQueryGoalState());
move_group_->setPlanningTime(ui_->planning_time->value());
configureWorkspace();
}
}
|
/*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. 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: Ioan Sucan */
#include <moveit/motion_planning_rviz_plugin/motion_planning_frame.h>
#include <moveit/motion_planning_rviz_plugin/motion_planning_display.h>
#include <moveit/kinematic_constraints/utils.h>
#include <moveit/robot_state/conversions.h>
#include "ui_motion_planning_rviz_plugin_frame.h"
namespace moveit_rviz_plugin
{
void MotionPlanningFrame::planButtonClicked()
{
planning_display_->addBackgroundJob(boost::bind(&MotionPlanningFrame::computePlanButtonClicked, this));
}
void MotionPlanningFrame::executeButtonClicked()
{
ui_->execute_button->setEnabled(false);
planning_display_->addBackgroundJob(boost::bind(&MotionPlanningFrame::computeExecuteButtonClicked, this));
}
void MotionPlanningFrame::planAndExecuteButtonClicked()
{
ui_->plan_and_execute_button->setEnabled(false);
ui_->execute_button->setEnabled(false);
planning_display_->addBackgroundJob(boost::bind(&MotionPlanningFrame::computePlanAndExecuteButtonClicked, this));
}
void MotionPlanningFrame::allowReplanningToggled(bool checked)
{
if (move_group_)
move_group_->allowReplanning(checked);
}
void MotionPlanningFrame::allowLookingToggled(bool checked)
{
if (move_group_)
move_group_->allowLooking(checked);
}
void MotionPlanningFrame::pathConstraintsIndexChanged(int index)
{
if (move_group_)
{
if (index > 0)
move_group_->setPathConstraints(ui_->path_constraints_combo_box->itemText(index).toStdString());
else
move_group_->clearPathConstraints();
}
}
void MotionPlanningFrame::computePlanButtonClicked()
{
if (!move_group_)
return;
configureForPlanning();
current_plan_.reset(new move_group_interface::MoveGroup::Plan());
if (move_group_->plan(*current_plan_))
ui_->execute_button->setEnabled(true);
else
current_plan_.reset();
}
void MotionPlanningFrame::computeExecuteButtonClicked()
{
if (move_group_ && current_plan_)
move_group_->execute(*current_plan_);
}
void MotionPlanningFrame::computePlanAndExecuteButtonClicked()
{
if (!move_group_)
return;
configureForPlanning();
move_group_->move();
ui_->plan_and_execute_button->setEnabled(true);
}
void MotionPlanningFrame::useStartStateButtonClicked()
{
robot_state::RobotState start = *planning_display_->getQueryStartState();
updateQueryStateHelper(start, ui_->start_state_selection->currentText().toStdString());
planning_display_->setQueryStartState(start);
}
void MotionPlanningFrame::useGoalStateButtonClicked()
{
robot_state::RobotState goal = *planning_display_->getQueryGoalState();
updateQueryStateHelper(goal, ui_->goal_state_selection->currentText().toStdString());
planning_display_->setQueryGoalState(goal);
}
void MotionPlanningFrame::updateQueryStateHelper(robot_state::RobotState &state, const std::string &v)
{
if (v == "<random>")
{
configureWorkspace();
if (robot_state::JointStateGroup *jsg = state.getJointStateGroup(planning_display_->getCurrentPlanningGroup()))
jsg->setToRandomValues();
}
else
if (v == "<current>")
{
const planning_scene_monitor::LockedPlanningSceneRO &ps = planning_display_->getPlanningSceneRO();
if (ps)
state = ps->getCurrentState();
}
else
if (v == "<same as goal>")
{
state = *planning_display_->getQueryGoalState();
}
else
if (v == "<same as start>")
{
state = *planning_display_->getQueryStartState();
}
else
{
// maybe it is a named state
if (robot_state::JointStateGroup *jsg = state.getJointStateGroup(planning_display_->getCurrentPlanningGroup()))
jsg->setToDefaultState(v);
}
}
void MotionPlanningFrame::populatePlannersList(const moveit_msgs::PlannerInterfaceDescription &desc)
{
std::string group = planning_display_->getCurrentPlanningGroup();
ui_->planning_algorithm_combo_box->clear();
// set the label for the planning library
ui_->library_label->setText(QString::fromStdString(desc.name));
ui_->library_label->setStyleSheet("QLabel { color : green; font: bold }");
bool found_group = false;
// the name of a planner is either "GROUP[planner_id]" or "planner_id"
if (!group.empty())
for (std::size_t i = 0 ; i < desc.planner_ids.size() ; ++i)
if (desc.planner_ids[i] == group)
found_group = true;
else
if (desc.planner_ids[i].substr(0, group.length()) == group)
{
if (desc.planner_ids[i].size() > group.length() && desc.planner_ids[i][group.length()] == '[')
{
std::string id = desc.planner_ids[i].substr(group.length());
if (id.size() > 2)
{
id.resize(id.length() - 1);
ui_->planning_algorithm_combo_box->addItem(QString::fromStdString(id.substr(1)));
}
}
}
if (ui_->planning_algorithm_combo_box->count() == 0 && !found_group)
for (std::size_t i = 0 ; i < desc.planner_ids.size() ; ++i)
ui_->planning_algorithm_combo_box->addItem(QString::fromStdString(desc.planner_ids[i]));
ui_->planning_algorithm_combo_box->insertItem(0, "<unspecified>");
ui_->planning_algorithm_combo_box->setCurrentIndex(0);
}
void MotionPlanningFrame::populateConstraintsList()
{
if (move_group_)
{
// add some artificial wait time (but in the background) for the constraints DB to connect
double dt = (ros::WallTime::now() - move_group_construction_time_).toSec();
if (dt < 0.2)
ros::WallDuration(0.1).sleep();
planning_display_->addMainLoopJob(boost::bind(&MotionPlanningFrame::populateConstraintsList, this, move_group_->getKnownConstraints()));
}
}
void MotionPlanningFrame::populateConstraintsList(const std::vector<std::string> &constr)
{
ui_->path_constraints_combo_box->clear();
ui_->path_constraints_combo_box->addItem("None");
for (std::size_t i = 0 ; i < constr.size() ; ++i)
ui_->path_constraints_combo_box->addItem(QString::fromStdString(constr[i]));
}
void MotionPlanningFrame::constructPlanningRequest(moveit_msgs::MotionPlanRequest &mreq)
{
mreq.group_name = planning_display_->getCurrentPlanningGroup();
mreq.num_planning_attempts = 1;
mreq.allowed_planning_time = ui_->planning_time->value();
robot_state::robotStateToRobotStateMsg(*planning_display_->getQueryStartState(), mreq.start_state);
mreq.workspace_parameters.min_corner.x = ui_->wcenter_x->value() - ui_->wsize_x->value() / 2.0;
mreq.workspace_parameters.min_corner.y = ui_->wcenter_y->value() - ui_->wsize_y->value() / 2.0;
mreq.workspace_parameters.min_corner.z = ui_->wcenter_z->value() - ui_->wsize_z->value() / 2.0;
mreq.workspace_parameters.max_corner.x = ui_->wcenter_x->value() + ui_->wsize_x->value() / 2.0;
mreq.workspace_parameters.max_corner.y = ui_->wcenter_y->value() + ui_->wsize_y->value() / 2.0;
mreq.workspace_parameters.max_corner.z = ui_->wcenter_z->value() + ui_->wsize_z->value() / 2.0;
const robot_state::JointStateGroup *jsg = planning_display_->getQueryGoalState()->getJointStateGroup(mreq.group_name);
if (jsg)
{
mreq.goal_constraints.resize(1);
mreq.goal_constraints[0] = kinematic_constraints::constructGoalConstraints(jsg);
}
}
void MotionPlanningFrame::configureWorkspace()
{
kinematic_model::JointModel::Bounds b(3);
b[0].first = ui_->wcenter_x->value() - ui_->wsize_x->value() / 2.0;
b[0].second = ui_->wcenter_x->value() + ui_->wsize_x->value() / 2.0;
b[1].first = ui_->wcenter_y->value() - ui_->wsize_y->value() / 2.0;
b[1].second = ui_->wcenter_y->value() + ui_->wsize_y->value() / 2.0;
b[2].first = ui_->wcenter_z->value() - ui_->wsize_z->value() / 2.0;
b[2].second = ui_->wcenter_z->value() + ui_->wsize_z->value() / 2.0;
if (move_group_)
move_group_->setWorkspace(b[0].first, b[1].first, b[2].first,
b[0].second, b[1].second, b[2].second);
// get non-const access to the kmodel and update planar & floating joints as indicated by the workspace settings
if (planning_display_->getPlanningSceneMonitor() && planning_display_->getPlanningSceneMonitor()->getKinematicModelLoader() &&
planning_display_->getPlanningSceneMonitor()->getKinematicModelLoader()->getModel())
{
const kinematic_model::KinematicModelPtr &kmodel = planning_display_->getPlanningSceneMonitor()->getKinematicModelLoader()->getModel();
const std::vector<kinematic_model::JointModel*> &jm = kmodel->getJointModels();
for (std::size_t i = 0 ; i < jm.size() ; ++i)
if (jm[i]->getType() == kinematic_model::JointModel::PLANAR)
{
jm[i]->setVariableBounds(jm[i]->getName() + "/x", b[0]);
jm[i]->setVariableBounds(jm[i]->getName() + "/y", b[1]);
}
else
if (jm[i]->getType() == kinematic_model::JointModel::FLOATING)
{
jm[i]->setVariableBounds(jm[i]->getName() + "/x", b[0]);
jm[i]->setVariableBounds(jm[i]->getName() + "/y", b[1]);
jm[i]->setVariableBounds(jm[i]->getName() + "/z", b[2]);
}
}
}
void MotionPlanningFrame::configureForPlanning()
{
move_group_->setStartState(*planning_display_->getQueryStartState());
move_group_->setJointValueTarget(*planning_display_->getQueryGoalState());
move_group_->setPlanningTime(ui_->planning_time->value());
configureWorkspace();
}
}
|
fix the detection of available planner names
|
fix the detection of available planner names
|
C++
|
bsd-3-clause
|
v4hn/moveit,davetcoleman/moveit,davetcoleman/moveit,v4hn/moveit,davetcoleman/moveit,ros-planning/moveit,v4hn/moveit,ros-planning/moveit,v4hn/moveit,ros-planning/moveit,ros-planning/moveit,ros-planning/moveit,davetcoleman/moveit
|
e1c192c9c55dbd836e4a3ae2a57e1f348d06d465
|
map/coverage_generator.cpp
|
map/coverage_generator.cpp
|
#include "../base/SRC_FIRST.hpp"
#include "coverage_generator.hpp"
#include "screen_coverage.hpp"
#include "tile_renderer.hpp"
#include "tile_set.hpp"
#include "../yg/skin.hpp"
#include "../yg/rendercontext.hpp"
#include "../base/logging.hpp"
#include "../std/bind.hpp"
bool g_coverageGeneratorDestroyed = false;
CoverageGenerator::CoverageGenerator(
string const & skinName,
TileRenderer * tileRenderer,
shared_ptr<WindowHandle> const & windowHandle,
shared_ptr<yg::gl::RenderContext> const & primaryRC,
shared_ptr<yg::ResourceManager> const & rm,
yg::gl::PacketsQueue * glQueue,
RenderPolicy::TCountryNameFn countryNameFn)
: m_queue(1),
m_tileRenderer(tileRenderer),
m_sequenceID(0),
m_windowHandle(windowHandle),
m_countryNameFn(countryNameFn),
m_glQueue(glQueue),
m_skinName(skinName),
m_fenceManager(2),
m_currentFenceID(-1)
{
g_coverageGeneratorDestroyed = false;
m_resourceManager = rm;
if (!m_glQueue)
m_renderContext = primaryRC->createShared();
m_workCoverage = CreateCoverage();
m_currentCoverage = CreateCoverage();
m_queue.AddInitCommand(bind(&CoverageGenerator::InitializeThreadGL, this));
m_queue.AddFinCommand(bind(&CoverageGenerator::FinalizeThreadGL, this));
m_queue.Start();
}
ScreenCoverage * CoverageGenerator::CreateCoverage()
{
yg::gl::Screen::Params params;
params.m_resourceManager = m_resourceManager;
params.m_renderQueue = m_glQueue;
params.m_doUnbindRT = false;
params.m_isSynchronized = false;
params.m_glyphCacheID = m_resourceManager->cacheThreadGlyphCacheID();
shared_ptr<yg::gl::Screen> screen(new yg::gl::Screen(params));
shared_ptr<yg::Skin> skin(loadSkin(m_resourceManager, m_skinName));
screen->setSkin(skin);
return new ScreenCoverage(m_tileRenderer, this, screen);
}
void CoverageGenerator::InitializeThreadGL()
{
if (m_renderContext)
m_renderContext->makeCurrent();
}
void CoverageGenerator::FinalizeThreadGL()
{
if (m_renderContext)
m_renderContext->endThreadDrawing();
}
CoverageGenerator::~CoverageGenerator()
{
LOG(LINFO, ("cancelling coverage thread"));
Cancel();
LOG(LINFO, ("deleting workCoverage"));
delete m_workCoverage;
m_workCoverage = 0;
LOG(LINFO, ("deleting currentCoverage"));
delete m_currentCoverage;
m_currentCoverage = 0;
g_coverageGeneratorDestroyed = true;
}
void CoverageGenerator::Cancel()
{
m_queue.Cancel();
}
void CoverageGenerator::InvalidateTilesImpl(m2::AnyRectD const & r, int startScale)
{
{
threads::MutexGuard g(m_mutex);
m_currentCoverage->RemoveTiles(r, startScale);
}
TileCache & tileCache = m_tileRenderer->GetTileCache();
tileCache.Lock();
/// here we should copy elements as we've delete some of them later
set<Tiler::RectInfo> k = tileCache.Keys();
for (set<Tiler::RectInfo>::const_iterator it = k.begin(); it != k.end(); ++it)
{
Tiler::RectInfo const & ri = *it;
if ((ri.m_tileScale >= startScale) && r.IsIntersect(m2::AnyRectD(ri.m_rect)))
{
ASSERT(tileCache.LockCount(ri) == 0, ());
tileCache.Remove(ri);
}
}
tileCache.Unlock();
}
void CoverageGenerator::InvalidateTiles(m2::AnyRectD const & r, int startScale)
{
if (m_sequenceID == numeric_limits<int>::max())
return;
/// this automatically will skip the previous CoverScreen commands
/// and MergeTiles commands from previously generated ScreenCoverages
++m_sequenceID;
m_queue.AddCommand(bind(&CoverageGenerator::InvalidateTilesImpl, this, r, startScale));
}
void CoverageGenerator::AddCoverScreenTask(ScreenBase const & screen, bool doForce)
{
if ((screen == m_currentScreen) && (!doForce))
return;
if (m_sequenceID == numeric_limits<int>::max())
return;
m_currentScreen = screen;
++m_sequenceID;
m_queue.AddCommand(bind(&CoverageGenerator::CoverScreen, this, screen, m_sequenceID));
}
int CoverageGenerator::InsertBenchmarkFence()
{
m_currentFenceID = m_fenceManager.insertFence();
return m_currentFenceID;
}
void CoverageGenerator::JoinBenchmarkFence(int fenceID)
{
CHECK(fenceID == m_currentFenceID, ("InsertBenchmarkFence without corresponding SignalBenchmarkFence detected"));
m_fenceManager.joinFence(fenceID);
}
void CoverageGenerator::SignalBenchmarkFence()
{
m_fenceManager.signalFence(m_currentFenceID);
}
void CoverageGenerator::CoverScreen(ScreenBase const & screen, int sequenceID)
{
if (sequenceID < m_sequenceID)
return;
m_currentCoverage->CopyInto(*m_workCoverage);
m_workCoverage->SetSequenceID(sequenceID);
m_workCoverage->SetScreen(screen);
if (!m_workCoverage->IsPartialCoverage() && m_workCoverage->IsEmptyDrawingCoverage())
{
m_workCoverage->ResetEmptyModelAtCoverageCenter();
AddCheckEmptyModelTask(sequenceID);
}
m_workCoverage->Cache();
{
threads::MutexGuard g(m_mutex);
swap(m_currentCoverage, m_workCoverage);
}
m_workCoverage->Clear();
m_windowHandle->invalidate();
}
void CoverageGenerator::AddMergeTileTask(Tiler::RectInfo const & rectInfo,
int sequenceID)
{
if (g_coverageGeneratorDestroyed)
return;
m_queue.AddCommand(bind(&CoverageGenerator::MergeTile, this, rectInfo, sequenceID));
}
void CoverageGenerator::MergeTile(Tiler::RectInfo const & rectInfo, int sequenceID)
{
if (sequenceID < m_sequenceID)
{
m_tileRenderer->RemoveActiveTile(rectInfo);
return;
}
m_currentCoverage->CopyInto(*m_workCoverage);
m_workCoverage->SetSequenceID(sequenceID);
m_workCoverage->Merge(rectInfo);
if (!m_workCoverage->IsPartialCoverage() && m_workCoverage->IsEmptyDrawingCoverage())
{
m_workCoverage->ResetEmptyModelAtCoverageCenter();
AddCheckEmptyModelTask(sequenceID);
}
m_workCoverage->Cache();
{
threads::MutexGuard g(m_mutex);
swap(m_currentCoverage, m_workCoverage);
}
m_workCoverage->Clear();
m_windowHandle->invalidate();
}
void CoverageGenerator::AddCheckEmptyModelTask(int sequenceID)
{
m_queue.AddCommand(bind(&CoverageGenerator::CheckEmptyModel, this, sequenceID));
}
void CoverageGenerator::CheckEmptyModel(int sequenceID)
{
if (sequenceID < m_sequenceID)
return;
m_currentCoverage->CheckEmptyModelAtCoverageCenter();
m_windowHandle->invalidate();
}
void CoverageGenerator::AddFinishSequenceTask(int sequenceID)
{
m_queue.AddCommand(bind(&CoverageGenerator::FinishSequence, this, sequenceID));
}
void CoverageGenerator::FinishSequence(int sequenceID)
{
/* if (sequenceID < m_sequenceID)
{
LOG(LINFO, ("sequence", sequenceID, "was cancelled"));
return;
}*/
SignalBenchmarkFence();
}
void CoverageGenerator::WaitForEmptyAndFinished()
{
m_queue.Join();
}
ScreenCoverage & CoverageGenerator::CurrentCoverage()
{
return *m_currentCoverage;
}
threads::Mutex & CoverageGenerator::Mutex()
{
return m_mutex;
}
void CoverageGenerator::SetSequenceID(int sequenceID)
{
m_sequenceID = sequenceID;
}
shared_ptr<yg::ResourceManager> const & CoverageGenerator::resourceManager() const
{
return m_resourceManager;
}
string CoverageGenerator::GetCountryName(m2::PointD const & pt) const
{
return m_countryNameFn(pt);
}
|
#include "../base/SRC_FIRST.hpp"
#include "coverage_generator.hpp"
#include "screen_coverage.hpp"
#include "tile_renderer.hpp"
#include "tile_set.hpp"
#include "../yg/skin.hpp"
#include "../yg/rendercontext.hpp"
#include "../base/logging.hpp"
#include "../std/bind.hpp"
bool g_coverageGeneratorDestroyed = false;
CoverageGenerator::CoverageGenerator(
string const & skinName,
TileRenderer * tileRenderer,
shared_ptr<WindowHandle> const & windowHandle,
shared_ptr<yg::gl::RenderContext> const & primaryRC,
shared_ptr<yg::ResourceManager> const & rm,
yg::gl::PacketsQueue * glQueue,
RenderPolicy::TCountryNameFn countryNameFn)
: m_queue(1),
m_tileRenderer(tileRenderer),
m_sequenceID(0),
m_windowHandle(windowHandle),
m_countryNameFn(countryNameFn),
m_glQueue(glQueue),
m_skinName(skinName),
m_fenceManager(2),
m_currentFenceID(-1)
{
g_coverageGeneratorDestroyed = false;
m_resourceManager = rm;
if (!m_glQueue)
m_renderContext = primaryRC->createShared();
m_workCoverage = CreateCoverage();
m_currentCoverage = CreateCoverage();
m_queue.AddInitCommand(bind(&CoverageGenerator::InitializeThreadGL, this));
m_queue.AddFinCommand(bind(&CoverageGenerator::FinalizeThreadGL, this));
m_queue.Start();
}
ScreenCoverage * CoverageGenerator::CreateCoverage()
{
yg::gl::Screen::Params params;
params.m_resourceManager = m_resourceManager;
params.m_renderQueue = m_glQueue;
params.m_doUnbindRT = false;
params.m_isSynchronized = false;
params.m_glyphCacheID = m_resourceManager->cacheThreadGlyphCacheID();
shared_ptr<yg::gl::Screen> screen(new yg::gl::Screen(params));
shared_ptr<yg::Skin> skin(loadSkin(m_resourceManager, m_skinName));
screen->setSkin(skin);
return new ScreenCoverage(m_tileRenderer, this, screen);
}
void CoverageGenerator::InitializeThreadGL()
{
if (m_renderContext)
m_renderContext->makeCurrent();
}
void CoverageGenerator::FinalizeThreadGL()
{
if (m_renderContext)
m_renderContext->endThreadDrawing();
}
CoverageGenerator::~CoverageGenerator()
{
LOG(LINFO, ("cancelling coverage thread"));
Cancel();
LOG(LINFO, ("deleting workCoverage"));
delete m_workCoverage;
m_workCoverage = 0;
LOG(LINFO, ("deleting currentCoverage"));
delete m_currentCoverage;
m_currentCoverage = 0;
g_coverageGeneratorDestroyed = true;
}
void CoverageGenerator::Cancel()
{
m_queue.Cancel();
}
void CoverageGenerator::InvalidateTilesImpl(m2::AnyRectD const & r, int startScale)
{
{
threads::MutexGuard g(m_mutex);
m_currentCoverage->RemoveTiles(r, startScale);
}
TileCache & tileCache = m_tileRenderer->GetTileCache();
tileCache.Lock();
/// here we should copy elements as we've delete some of them later
set<Tiler::RectInfo> k = tileCache.Keys();
for (set<Tiler::RectInfo>::const_iterator it = k.begin(); it != k.end(); ++it)
{
Tiler::RectInfo const & ri = *it;
if ((ri.m_tileScale >= startScale) && r.IsIntersect(m2::AnyRectD(ri.m_rect)))
{
ASSERT(tileCache.LockCount(ri) == 0, ());
tileCache.Remove(ri);
}
}
tileCache.Unlock();
}
void CoverageGenerator::InvalidateTiles(m2::AnyRectD const & r, int startScale)
{
if (m_sequenceID == numeric_limits<int>::max())
return;
/// this automatically will skip the previous CoverScreen commands
/// and MergeTiles commands from previously generated ScreenCoverages
++m_sequenceID;
m_queue.AddCommand(bind(&CoverageGenerator::InvalidateTilesImpl, this, r, startScale));
}
void CoverageGenerator::AddCoverScreenTask(ScreenBase const & screen, bool doForce)
{
if ((screen == m_currentScreen) && (!doForce))
return;
if (m_sequenceID == numeric_limits<int>::max())
return;
m_currentScreen = screen;
++m_sequenceID;
m_queue.AddCommand(bind(&CoverageGenerator::CoverScreen, this, screen, m_sequenceID));
}
int CoverageGenerator::InsertBenchmarkFence()
{
m_currentFenceID = m_fenceManager.insertFence();
return m_currentFenceID;
}
void CoverageGenerator::JoinBenchmarkFence(int fenceID)
{
CHECK(fenceID == m_currentFenceID, ("InsertBenchmarkFence without corresponding SignalBenchmarkFence detected"));
m_fenceManager.joinFence(fenceID);
}
void CoverageGenerator::SignalBenchmarkFence()
{
if (m_currentFenceID != -1)
m_fenceManager.signalFence(m_currentFenceID);
}
void CoverageGenerator::CoverScreen(ScreenBase const & screen, int sequenceID)
{
if (sequenceID < m_sequenceID)
return;
m_currentCoverage->CopyInto(*m_workCoverage);
m_workCoverage->SetSequenceID(sequenceID);
m_workCoverage->SetScreen(screen);
if (!m_workCoverage->IsPartialCoverage() && m_workCoverage->IsEmptyDrawingCoverage())
{
m_workCoverage->ResetEmptyModelAtCoverageCenter();
AddCheckEmptyModelTask(sequenceID);
}
m_workCoverage->Cache();
{
threads::MutexGuard g(m_mutex);
swap(m_currentCoverage, m_workCoverage);
}
m_workCoverage->Clear();
m_windowHandle->invalidate();
}
void CoverageGenerator::AddMergeTileTask(Tiler::RectInfo const & rectInfo,
int sequenceID)
{
if (g_coverageGeneratorDestroyed)
return;
m_queue.AddCommand(bind(&CoverageGenerator::MergeTile, this, rectInfo, sequenceID));
}
void CoverageGenerator::MergeTile(Tiler::RectInfo const & rectInfo, int sequenceID)
{
if (sequenceID < m_sequenceID)
{
m_tileRenderer->RemoveActiveTile(rectInfo);
return;
}
m_currentCoverage->CopyInto(*m_workCoverage);
m_workCoverage->SetSequenceID(sequenceID);
m_workCoverage->Merge(rectInfo);
if (!m_workCoverage->IsPartialCoverage() && m_workCoverage->IsEmptyDrawingCoverage())
{
m_workCoverage->ResetEmptyModelAtCoverageCenter();
AddCheckEmptyModelTask(sequenceID);
}
m_workCoverage->Cache();
{
threads::MutexGuard g(m_mutex);
swap(m_currentCoverage, m_workCoverage);
}
m_workCoverage->Clear();
m_windowHandle->invalidate();
}
void CoverageGenerator::AddCheckEmptyModelTask(int sequenceID)
{
m_queue.AddCommand(bind(&CoverageGenerator::CheckEmptyModel, this, sequenceID));
}
void CoverageGenerator::CheckEmptyModel(int sequenceID)
{
if (sequenceID < m_sequenceID)
return;
m_currentCoverage->CheckEmptyModelAtCoverageCenter();
m_windowHandle->invalidate();
}
void CoverageGenerator::AddFinishSequenceTask(int sequenceID)
{
m_queue.AddCommand(bind(&CoverageGenerator::FinishSequence, this, sequenceID));
}
void CoverageGenerator::FinishSequence(int sequenceID)
{
/* if (sequenceID < m_sequenceID)
{
LOG(LINFO, ("sequence", sequenceID, "was cancelled"));
return;
}*/
SignalBenchmarkFence();
}
void CoverageGenerator::WaitForEmptyAndFinished()
{
m_queue.Join();
}
ScreenCoverage & CoverageGenerator::CurrentCoverage()
{
return *m_currentCoverage;
}
threads::Mutex & CoverageGenerator::Mutex()
{
return m_mutex;
}
void CoverageGenerator::SetSequenceID(int sequenceID)
{
m_sequenceID = sequenceID;
}
shared_ptr<yg::ResourceManager> const & CoverageGenerator::resourceManager() const
{
return m_resourceManager;
}
string CoverageGenerator::GetCountryName(m2::PointD const & pt) const
{
return m_countryNameFn(pt);
}
|
check for invalid fence id to reduce logging.
|
check for invalid fence id to reduce logging.
|
C++
|
apache-2.0
|
Transtech/omim,programming086/omim,matsprea/omim,simon247/omim,wersoo/omim,vladon/omim,yunikkk/omim,dkorolev/omim,matsprea/omim,dobriy-eeh/omim,Komzpa/omim,andrewshadura/omim,65apps/omim,trashkalmar/omim,Saicheg/omim,mpimenov/omim,igrechuhin/omim,UdjinM6/omim,mapsme/omim,mgsergio/omim,syershov/omim,augmify/omim,rokuz/omim,65apps/omim,sidorov-panda/omim,mapsme/omim,Transtech/omim,programming086/omim,vng/omim,edl00k/omim,65apps/omim,trashkalmar/omim,stangls/omim,mpimenov/omim,Endika/omim,vng/omim,goblinr/omim,rokuz/omim,vasilenkomike/omim,dkorolev/omim,felipebetancur/omim,therearesomewhocallmetim/omim,augmify/omim,krasin/omim,gardster/omim,Zverik/omim,programming086/omim,augmify/omim,mgsergio/omim,yunikkk/omim,lydonchandra/omim,rokuz/omim,UdjinM6/omim,dkorolev/omim,vladon/omim,rokuz/omim,jam891/omim,syershov/omim,augmify/omim,syershov/omim,albertshift/omim,syershov/omim,darina/omim,mpimenov/omim,krasin/omim,Volcanoscar/omim,victorbriz/omim,Transtech/omim,Transtech/omim,ygorshenin/omim,wersoo/omim,65apps/omim,wersoo/omim,felipebetancur/omim,edl00k/omim,augmify/omim,therearesomewhocallmetim/omim,Zverik/omim,matsprea/omim,edl00k/omim,darina/omim,dkorolev/omim,vasilenkomike/omim,kw217/omim,UdjinM6/omim,victorbriz/omim,Zverik/omim,Volcanoscar/omim,Endika/omim,mpimenov/omim,mpimenov/omim,igrechuhin/omim,Zverik/omim,igrechuhin/omim,AlexanderMatveenko/omim,bykoianko/omim,vng/omim,felipebetancur/omim,jam891/omim,vladon/omim,sidorov-panda/omim,Endika/omim,UdjinM6/omim,darina/omim,lydonchandra/omim,trashkalmar/omim,therearesomewhocallmetim/omim,wersoo/omim,syershov/omim,mpimenov/omim,dobriy-eeh/omim,lydonchandra/omim,igrechuhin/omim,Endika/omim,matsprea/omim,mgsergio/omim,Komzpa/omim,albertshift/omim,yunikkk/omim,VladiMihaylenko/omim,felipebetancur/omim,rokuz/omim,Saicheg/omim,kw217/omim,lydonchandra/omim,mapsme/omim,dobriy-eeh/omim,kw217/omim,sidorov-panda/omim,wersoo/omim,jam891/omim,ygorshenin/omim,mgsergio/omim,Komzpa/omim,augmify/omim,victorbriz/omim,krasin/omim,programming086/omim,gardster/omim,yunikkk/omim,Endika/omim,milchakov/omim,andrewshadura/omim,65apps/omim,stangls/omim,65apps/omim,goblinr/omim,ygorshenin/omim,therearesomewhocallmetim/omim,ygorshenin/omim,stangls/omim,dobriy-eeh/omim,programming086/omim,VladiMihaylenko/omim,guard163/omim,dkorolev/omim,Zverik/omim,augmify/omim,lydonchandra/omim,albertshift/omim,vasilenkomike/omim,vng/omim,kw217/omim,rokuz/omim,AlexanderMatveenko/omim,bykoianko/omim,mapsme/omim,mpimenov/omim,programming086/omim,Saicheg/omim,albertshift/omim,therearesomewhocallmetim/omim,ygorshenin/omim,darina/omim,rokuz/omim,gardster/omim,milchakov/omim,alexzatsepin/omim,kw217/omim,yunikkk/omim,syershov/omim,Zverik/omim,ygorshenin/omim,kw217/omim,wersoo/omim,ygorshenin/omim,guard163/omim,kw217/omim,trashkalmar/omim,Volcanoscar/omim,vladon/omim,mapsme/omim,UdjinM6/omim,yunikkk/omim,vng/omim,bykoianko/omim,Endika/omim,igrechuhin/omim,TimurTarasenko/omim,mgsergio/omim,stangls/omim,edl00k/omim,goblinr/omim,jam891/omim,Transtech/omim,dobriy-eeh/omim,alexzatsepin/omim,syershov/omim,goblinr/omim,guard163/omim,simon247/omim,Komzpa/omim,matsprea/omim,VladiMihaylenko/omim,dkorolev/omim,augmify/omim,Zverik/omim,programming086/omim,Komzpa/omim,Komzpa/omim,vng/omim,igrechuhin/omim,UdjinM6/omim,milchakov/omim,VladiMihaylenko/omim,alexzatsepin/omim,Zverik/omim,dobriy-eeh/omim,therearesomewhocallmetim/omim,Volcanoscar/omim,VladiMihaylenko/omim,Volcanoscar/omim,felipebetancur/omim,bykoianko/omim,65apps/omim,trashkalmar/omim,AlexanderMatveenko/omim,alexzatsepin/omim,alexzatsepin/omim,darina/omim,rokuz/omim,vladon/omim,65apps/omim,vng/omim,mpimenov/omim,victorbriz/omim,andrewshadura/omim,syershov/omim,jam891/omim,mgsergio/omim,guard163/omim,Komzpa/omim,wersoo/omim,Zverik/omim,Zverik/omim,VladiMihaylenko/omim,matsprea/omim,albertshift/omim,mpimenov/omim,bykoianko/omim,vng/omim,andrewshadura/omim,UdjinM6/omim,milchakov/omim,alexzatsepin/omim,TimurTarasenko/omim,bykoianko/omim,yunikkk/omim,victorbriz/omim,TimurTarasenko/omim,albertshift/omim,darina/omim,therearesomewhocallmetim/omim,albertshift/omim,vladon/omim,milchakov/omim,darina/omim,krasin/omim,VladiMihaylenko/omim,lydonchandra/omim,darina/omim,felipebetancur/omim,gardster/omim,andrewshadura/omim,edl00k/omim,rokuz/omim,jam891/omim,goblinr/omim,VladiMihaylenko/omim,gardster/omim,edl00k/omim,andrewshadura/omim,vasilenkomike/omim,Transtech/omim,igrechuhin/omim,augmify/omim,VladiMihaylenko/omim,sidorov-panda/omim,ygorshenin/omim,syershov/omim,sidorov-panda/omim,65apps/omim,krasin/omim,vladon/omim,vng/omim,ygorshenin/omim,ygorshenin/omim,Saicheg/omim,Saicheg/omim,Volcanoscar/omim,igrechuhin/omim,TimurTarasenko/omim,alexzatsepin/omim,lydonchandra/omim,sidorov-panda/omim,mgsergio/omim,trashkalmar/omim,gardster/omim,rokuz/omim,AlexanderMatveenko/omim,alexzatsepin/omim,AlexanderMatveenko/omim,syershov/omim,jam891/omim,Saicheg/omim,matsprea/omim,Volcanoscar/omim,simon247/omim,goblinr/omim,VladiMihaylenko/omim,bykoianko/omim,mapsme/omim,kw217/omim,ygorshenin/omim,Transtech/omim,vladon/omim,Transtech/omim,Transtech/omim,programming086/omim,dobriy-eeh/omim,syershov/omim,Komzpa/omim,milchakov/omim,guard163/omim,kw217/omim,darina/omim,krasin/omim,Zverik/omim,goblinr/omim,mgsergio/omim,gardster/omim,alexzatsepin/omim,Endika/omim,yunikkk/omim,guard163/omim,goblinr/omim,felipebetancur/omim,milchakov/omim,felipebetancur/omim,albertshift/omim,mgsergio/omim,Endika/omim,vng/omim,rokuz/omim,rokuz/omim,matsprea/omim,mapsme/omim,Zverik/omim,milchakov/omim,Saicheg/omim,edl00k/omim,felipebetancur/omim,TimurTarasenko/omim,dkorolev/omim,yunikkk/omim,therearesomewhocallmetim/omim,goblinr/omim,syershov/omim,victorbriz/omim,dobriy-eeh/omim,bykoianko/omim,wersoo/omim,albertshift/omim,Endika/omim,krasin/omim,trashkalmar/omim,gardster/omim,victorbriz/omim,dkorolev/omim,mapsme/omim,dobriy-eeh/omim,Transtech/omim,Transtech/omim,milchakov/omim,simon247/omim,igrechuhin/omim,mapsme/omim,dobriy-eeh/omim,bykoianko/omim,krasin/omim,victorbriz/omim,UdjinM6/omim,Komzpa/omim,trashkalmar/omim,stangls/omim,darina/omim,mgsergio/omim,therearesomewhocallmetim/omim,Saicheg/omim,matsprea/omim,65apps/omim,yunikkk/omim,trashkalmar/omim,TimurTarasenko/omim,bykoianko/omim,guard163/omim,matsprea/omim,kw217/omim,AlexanderMatveenko/omim,Zverik/omim,simon247/omim,trashkalmar/omim,vasilenkomike/omim,stangls/omim,edl00k/omim,milchakov/omim,dobriy-eeh/omim,TimurTarasenko/omim,dkorolev/omim,TimurTarasenko/omim,dobriy-eeh/omim,Volcanoscar/omim,augmify/omim,gardster/omim,vladon/omim,alexzatsepin/omim,simon247/omim,mapsme/omim,Volcanoscar/omim,Komzpa/omim,wersoo/omim,stangls/omim,therearesomewhocallmetim/omim,goblinr/omim,igrechuhin/omim,ygorshenin/omim,mgsergio/omim,bykoianko/omim,simon247/omim,Saicheg/omim,lydonchandra/omim,mpimenov/omim,bykoianko/omim,Volcanoscar/omim,vasilenkomike/omim,yunikkk/omim,jam891/omim,andrewshadura/omim,simon247/omim,Saicheg/omim,milchakov/omim,andrewshadura/omim,AlexanderMatveenko/omim,VladiMihaylenko/omim,stangls/omim,jam891/omim,goblinr/omim,TimurTarasenko/omim,gardster/omim,darina/omim,vasilenkomike/omim,goblinr/omim,VladiMihaylenko/omim,AlexanderMatveenko/omim,simon247/omim,andrewshadura/omim,krasin/omim,UdjinM6/omim,vasilenkomike/omim,trashkalmar/omim,wersoo/omim,vasilenkomike/omim,milchakov/omim,simon247/omim,lydonchandra/omim,vladon/omim,mpimenov/omim,trashkalmar/omim,dkorolev/omim,Transtech/omim,jam891/omim,vasilenkomike/omim,sidorov-panda/omim,programming086/omim,goblinr/omim,andrewshadura/omim,milchakov/omim,sidorov-panda/omim,lydonchandra/omim,darina/omim,mgsergio/omim,programming086/omim,alexzatsepin/omim,stangls/omim,guard163/omim,rokuz/omim,victorbriz/omim,alexzatsepin/omim,mapsme/omim,sidorov-panda/omim,VladiMihaylenko/omim,mpimenov/omim,syershov/omim,albertshift/omim,alexzatsepin/omim,guard163/omim,65apps/omim,AlexanderMatveenko/omim,krasin/omim,stangls/omim,AlexanderMatveenko/omim,mapsme/omim,edl00k/omim,mpimenov/omim,TimurTarasenko/omim,felipebetancur/omim,victorbriz/omim,mapsme/omim,darina/omim,edl00k/omim,Endika/omim,UdjinM6/omim,bykoianko/omim,dobriy-eeh/omim,sidorov-panda/omim,stangls/omim,guard163/omim
|
9d2fee17e08fce89e46f4502fd28e974e81c19a1
|
src/qt/sendcoinsdialog.cpp
|
src/qt/sendcoinsdialog.cpp
|
#include "sendcoinsdialog.h"
#include "ui_sendcoinsdialog.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "optionsmodel.h"
#include "sendcoinsentry.h"
#include "guiutil.h"
#include "askpassphrasedialog.h"
#include "base58.h"
#include <QMessageBox>
#include <QTextDocument>
#include <QScrollBar>
SendCoinsDialog::SendCoinsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SendCoinsDialog),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
#endif
addEntry();
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
fNewRecipientAllowed = true;
}
void SendCoinsDialog::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel())
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setModel(model);
}
}
setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance());
connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
}
}
SendCoinsDialog::~SendCoinsDialog()
{
delete ui;
}
void SendCoinsDialog::on_sendButton_clicked()
{
if(!model || !model->getOptionsModel())
return;
QList<SendCoinsRecipient> recipients;
bool valid = true;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
if(entry->validate())
{
recipients.append(entry->getValue());
}
else
{
valid = false;
}
}
}
if(!valid || recipients.isEmpty())
{
return;
}
// Format confirmation message
QStringList formatted;
foreach(const SendCoinsRecipient &rcp, recipients)
{
QString amount = BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount);
if (rcp.authenticatedMerchant.isEmpty())
{
QString address = rcp.address;
#if QT_VERSION < 0x050000
QString to = Qt::escape(rcp.label);
#else
QString to = rcp.label.toHtmlEscaped();
#endif
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(amount, to, address));
}
else
{
#if QT_VERSION < 0x050000
QString merchant = Qt::escape(rcp.authenticatedMerchant);
#else
QString merchant = rcp.authenticatedMerchant.toHtmlEscaped();
#endif
formatted.append(tr("<b>%1</b> to %2").arg(amount, merchant));
}
}
fNewRecipientAllowed = false;
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval != QMessageBox::Yes)
{
fNewRecipientAllowed = true;
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
fNewRecipientAllowed = true;
return;
}
WalletModel::SendCoinsReturn sendstatus = model->sendCoins(recipients);
switch(sendstatus.status)
{
case WalletModel::InvalidAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("The recipient address is not valid, please recheck."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::InvalidAmount:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount to pay must be larger than 0."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount exceeds your balance."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountWithFeeExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The total exceeds your balance when the %1 transaction fee is included.").
arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), sendstatus.fee)),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::DuplicateAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("Duplicate address found, can only send to each address once per send operation."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCreationFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: Transaction creation failed!"),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCommitFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::Aborted: // User aborted, nothing to do
break;
case WalletModel::OK:
accept();
break;
}
fNewRecipientAllowed = true;
}
void SendCoinsDialog::clear()
{
// Remove entries until only one left
while(ui->entries->count())
{
delete ui->entries->takeAt(0)->widget();
}
addEntry();
updateRemoveEnabled();
ui->sendButton->setDefault(true);
}
void SendCoinsDialog::reject()
{
clear();
}
void SendCoinsDialog::accept()
{
clear();
}
SendCoinsEntry *SendCoinsDialog::addEntry()
{
SendCoinsEntry *entry = new SendCoinsEntry(this);
entry->setModel(model);
ui->entries->addWidget(entry);
connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));
updateRemoveEnabled();
// Focus the field, so that entry can start immediately
entry->clear();
entry->setFocus();
ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
qApp->processEvents();
QScrollBar* bar = ui->scrollArea->verticalScrollBar();
if(bar)
bar->setSliderPosition(bar->maximum());
return entry;
}
void SendCoinsDialog::updateRemoveEnabled()
{
// Remove buttons are enabled as soon as there is more than one send-entry
bool enabled = (ui->entries->count() > 1);
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setRemoveEnabled(enabled);
}
}
setupTabChain(0);
}
void SendCoinsDialog::removeEntry(SendCoinsEntry* entry)
{
delete entry;
updateRemoveEnabled();
}
QWidget *SendCoinsDialog::setupTabChain(QWidget *prev)
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
prev = entry->setupTabChain(prev);
}
}
QWidget::setTabOrder(prev, ui->addButton);
QWidget::setTabOrder(ui->addButton, ui->sendButton);
return ui->sendButton;
}
void SendCoinsDialog::setAddress(const QString &address)
{
SendCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setAddress(address);
}
void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)
{
if(!fNewRecipientAllowed)
return;
SendCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setValue(rv);
}
bool SendCoinsDialog::handlePaymentRequest(const SendCoinsRecipient &rv)
{
if (!rv.authenticatedMerchant.isEmpty()) {
// Expired payment request?
const payments::PaymentDetails& details = rv.paymentRequest.getDetails();
if (details.has_expires() && (int64)details.expires() < GetTime())
{
QMessageBox::warning(this, tr("Send Coins"),
tr("Payment request expired"));
return false;
}
}
else {
CBitcoinAddress address(rv.address.toStdString());
if (!address.IsValid()) {
QString strAddress(address.ToString().c_str());
QMessageBox::warning(this, tr("Send Coins"),
tr("Invalid payment address %1").arg(strAddress));
return false;
}
}
pasteEntry(rv);
return true;
}
void SendCoinsDialog::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance)
{
Q_UNUSED(unconfirmedBalance);
Q_UNUSED(immatureBalance);
if(model && model->getOptionsModel())
{
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), balance));
}
}
void SendCoinsDialog::updateDisplayUnit()
{
setBalance(model->getBalance(), 0, 0);
}
|
#include "sendcoinsdialog.h"
#include "ui_sendcoinsdialog.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "optionsmodel.h"
#include "sendcoinsentry.h"
#include "guiutil.h"
#include "askpassphrasedialog.h"
#include "base58.h"
#include <QMessageBox>
#include <QTextDocument>
#include <QScrollBar>
SendCoinsDialog::SendCoinsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SendCoinsDialog),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
#endif
addEntry();
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
fNewRecipientAllowed = true;
}
void SendCoinsDialog::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel())
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setModel(model);
}
}
setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance());
connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
}
}
SendCoinsDialog::~SendCoinsDialog()
{
delete ui;
}
void SendCoinsDialog::on_sendButton_clicked()
{
if(!model || !model->getOptionsModel())
return;
QList<SendCoinsRecipient> recipients;
bool valid = true;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
if(entry->validate())
{
recipients.append(entry->getValue());
}
else
{
valid = false;
}
}
}
if(!valid || recipients.isEmpty())
{
return;
}
// Format confirmation message
QStringList formatted;
foreach(const SendCoinsRecipient &rcp, recipients)
{
QString amount = BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount);
if (rcp.authenticatedMerchant.isEmpty())
{
QString address = rcp.address;
QString to = GUIUtil::HtmlEscape(rcp.label);
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(amount, to, address));
}
else
{
QString merchant = GUIUtil::HtmlEscape(rcp.authenticatedMerchant);
formatted.append(tr("<b>%1</b> to %2").arg(amount, merchant));
}
}
fNewRecipientAllowed = false;
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval != QMessageBox::Yes)
{
fNewRecipientAllowed = true;
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
fNewRecipientAllowed = true;
return;
}
WalletModel::SendCoinsReturn sendstatus = model->sendCoins(recipients);
switch(sendstatus.status)
{
case WalletModel::InvalidAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("The recipient address is not valid, please recheck."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::InvalidAmount:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount to pay must be larger than 0."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount exceeds your balance."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountWithFeeExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The total exceeds your balance when the %1 transaction fee is included.").
arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), sendstatus.fee)),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::DuplicateAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("Duplicate address found, can only send to each address once per send operation."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCreationFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: Transaction creation failed!"),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCommitFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::Aborted: // User aborted, nothing to do
break;
case WalletModel::OK:
accept();
break;
}
fNewRecipientAllowed = true;
}
void SendCoinsDialog::clear()
{
// Remove entries until only one left
while(ui->entries->count())
{
delete ui->entries->takeAt(0)->widget();
}
addEntry();
updateRemoveEnabled();
ui->sendButton->setDefault(true);
}
void SendCoinsDialog::reject()
{
clear();
}
void SendCoinsDialog::accept()
{
clear();
}
SendCoinsEntry *SendCoinsDialog::addEntry()
{
SendCoinsEntry *entry = new SendCoinsEntry(this);
entry->setModel(model);
ui->entries->addWidget(entry);
connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));
updateRemoveEnabled();
// Focus the field, so that entry can start immediately
entry->clear();
entry->setFocus();
ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
qApp->processEvents();
QScrollBar* bar = ui->scrollArea->verticalScrollBar();
if(bar)
bar->setSliderPosition(bar->maximum());
return entry;
}
void SendCoinsDialog::updateRemoveEnabled()
{
// Remove buttons are enabled as soon as there is more than one send-entry
bool enabled = (ui->entries->count() > 1);
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setRemoveEnabled(enabled);
}
}
setupTabChain(0);
}
void SendCoinsDialog::removeEntry(SendCoinsEntry* entry)
{
delete entry;
updateRemoveEnabled();
}
QWidget *SendCoinsDialog::setupTabChain(QWidget *prev)
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
prev = entry->setupTabChain(prev);
}
}
QWidget::setTabOrder(prev, ui->addButton);
QWidget::setTabOrder(ui->addButton, ui->sendButton);
return ui->sendButton;
}
void SendCoinsDialog::setAddress(const QString &address)
{
SendCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setAddress(address);
}
void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)
{
if(!fNewRecipientAllowed)
return;
SendCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setValue(rv);
}
bool SendCoinsDialog::handlePaymentRequest(const SendCoinsRecipient &rv)
{
if (!rv.authenticatedMerchant.isEmpty()) {
// Expired payment request?
const payments::PaymentDetails& details = rv.paymentRequest.getDetails();
if (details.has_expires() && (int64)details.expires() < GetTime())
{
QMessageBox::warning(this, tr("Send Coins"),
tr("Payment request expired"));
return false;
}
}
else {
CBitcoinAddress address(rv.address.toStdString());
if (!address.IsValid()) {
QString strAddress(address.ToString().c_str());
QMessageBox::warning(this, tr("Send Coins"),
tr("Invalid payment address %1").arg(strAddress));
return false;
}
}
pasteEntry(rv);
return true;
}
void SendCoinsDialog::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance)
{
Q_UNUSED(unconfirmedBalance);
Q_UNUSED(immatureBalance);
if(model && model->getOptionsModel())
{
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), balance));
}
}
void SendCoinsDialog::updateDisplayUnit()
{
setBalance(model->getBalance(), 0, 0);
}
|
Use GUIUtil::HtmlEscape to escape HTML
|
qt: Use GUIUtil::HtmlEscape to escape HTML
This is why we created this function. Avoids some #ifdef.
|
C++
|
mit
|
BigBlueCeiling/augmentacoin,josephbisch/namecoin-core,rat4/bitcoin,GroundRod/anoncoin,zcoinofficial/zcoin,lbrtcoin/albertcoin,PRabahy/bitcoin,nathan-at-least/zcash,gmaxwell/bitcoin,myriadteam/myriadcoin,isle2983/bitcoin,millennial83/bitcoin,ionomy/ion,RHavar/bitcoin,ZiftrCOIN/ziftrcoin,REAP720801/bitcoin,gravio-net/graviocoin,donaloconnor/bitcoin,marcusdiaz/BitcoinUnlimited,xuyangcn/opalcoin,brishtiteveja/sherlockcoin,h4x3rotab/BTCGPU,wangxinxi/litecoin,sdaftuar/bitcoin,dexX7/bitcoin,fujicoin/fujicoin,cmgustavo/bitcoin,cheehieu/bitcoin,DGCDev/argentum,jaromil/faircoin2,wbchen99/bitcoin-hnote0,bitcoinec/bitcoinec,alejandromgk/Lunar,1185/starwels,pouta/bitcoin,awemany/BitcoinUnlimited,Cocosoft/bitcoin,josephbisch/namecoin-core,bitcoinsSG/zcash,mrbandrews/bitcoin,maaku/bitcoin,shelvenzhou/BTCGPU,cannabiscoindev/cannabiscoin420,MazaCoin/mazacoin-new,lakepay/lake,isghe/bitcoinxt,tmagik/catcoin,wiggi/huntercore,OmniLayer/omnicore,jtimon/bitcoin,m0gliE/fastcoin-cli,superjudge/bitcoin,phplaboratory/psiacoin,matlongsi/micropay,litecoin-project/litecoin,ardsu/bitcoin,tjps/bitcoin,Rav3nPL/PLNcoin,droark/bitcoin,ahmedbodi/vertcoin,misdess/bitcoin,hasanatkazmi/bitcoin,marcusdiaz/BitcoinUnlimited,deuscoin/deuscoin,ahmedbodi/temp_vert,bitcoin-hivemind/hivemind,npccoin/npccoin,kazcw/bitcoin,neuroidss/bitcoin,djpnewton/bitcoin,sarielsaz/sarielsaz,Krellan/bitcoin,stevemyers/bitcoinxt,sirk390/bitcoin,cerebrus29301/crowncoin,RazorLove/cloaked-octo-spice,dmrtsvetkov/flowercoin,SoreGums/bitcoinxt,dpayne9000/Rubixz-Coin,rdqw/sscoin,botland/bitcoin,DSPay/DSPay,namecoin/namecore,Metronotes/bitcoin,digideskio/namecoin,phelix/namecore,andreaskern/bitcoin,habibmasuro/bitcoinxt,romanornr/viacoin,nathaniel-mahieu/bitcoin,Kcoin-project/kcoin,sickpig/BitcoinUnlimited,ivansib/sib16,genavarov/lamacoin,alecalve/bitcoin,sipsorcery/bitcoin,mycointest/owncoin,NunoEdgarGub1/elements,ajweiss/bitcoin,core-bitcoin/bitcoin,JeremyRand/namecoin-core,EthanHeilman/bitcoin,mastercoin-MSC/mastercore,gjhiggins/vcoincore,koharjidan/bitcoin,qtumproject/qtum,MazaCoin/maza,bcpki/testblocks,m0gliE/fastcoin-cli,fullcoins/fullcoin,nbenoit/bitcoin,NateBrune/bitcoin-nate,XertroV/bitcoin-nulldata,shaolinfry/litecoin,thrasher-/litecoin,destenson/bitcoin--bitcoin,namecoin/namecoin-core,puticcoin/putic,ahmedbodi/terracoin,putinclassic/putic,jarymoth/dogecoin,REAP720801/bitcoin,bitcoinsSG/bitcoin,prark/bitcoinxt,EthanHeilman/bitcoin,worldbit/worldbit,bitcoin/bitcoin,rustyrussell/bitcoin,bitcoinknots/bitcoin,joshrabinowitz/bitcoin,martindale/elements,instagibbs/bitcoin,jn2840/bitcoin,chaincoin/chaincoin,40thoughts/Coin-QualCoin,11755033isaprimenumber/Feathercoin,FinalHashLLC/namecore,lbrtcoin/albertcoin,krzysztofwos/BitcoinUnlimited,elecoin/elecoin,apoelstra/elements,patricklodder/dogecoin,TheBlueMatt/bitcoin,puticcoin/putic,jarymoth/dogecoin,deuscoin/deuscoin,kallewoof/elements,namecoin/namecore,crowning2/dash,MazaCoin/maza,dgarage/bc3,namecoin/namecore,AdrianaDinca/bitcoin,NunoEdgarGub1/elements,fsb4000/bitcoin,litecoin-project/litecore-litecoin,benosa/bitcoin,jaromil/faircoin2,credits-currency/credits,balajinandhu/bitcoin,nbenoit/bitcoin,bitjson/hivemind,syscoin/syscoin,ashleyholman/bitcoin,xuyangcn/opalcoin,axelxod/braincoin,torresalyssa/bitcoin,bitcoinsSG/bitcoin,jonasschnelli/bitcoin,parvez3019/bitcoin,myriadcoin/myriadcoin,rawodb/bitcoin,florincoin/florincoin,knolza/gamblr,Rav3nPL/polcoin,my-first/octocoin,antonio-fr/bitcoin,itmanagerro/tresting,Sjors/bitcoin,jtimon/bitcoin,oklink-dev/bitcoin,bitcoinclassic/bitcoinclassic,BitcoinHardfork/bitcoin,lakepay/lake,hophacker/bitcoin_malleability,rebroad/bitcoin,pstratem/bitcoin,jameshilliard/bitcoin,npccoin/npccoin,dgenr8/bitcoin,starwels/starwels,tmagik/catcoin,cerebrus29301/crowncoin,KibiCoin/kibicoin,greencoin-dev/digitalcoin,acid1789/bitcoin,cotner/bitcoin,nikkitan/bitcoin,n1bor/bitcoin,thrasher-/litecoin,capitalDIGI/DIGI-v-0-10-4,PIVX-Project/PIVX,senadmd/coinmarketwatch,oklink-dev/bitcoin_block,TGDiamond/Diamond,roques/bitcoin,TrainMAnB/vcoincore,maaku/bitcoin,my-first/octocoin,JeremyRand/namecore,ionomy/ion,my-first/octocoin,Bitcoinsulting/bitcoinxt,zotherstupidguy/bitcoin,inutoshi/inutoshi,lbrtcoin/albertcoin,wangliu/bitcoin,SoreGums/bitcoinxt,CryptArc/bitcoin,thormuller/yescoin2,midnightmagic/bitcoin,truthcoin/truthcoin-cpp,aniemerg/zcash,XertroV/bitcoin-nulldata,ryanofsky/bitcoin,isghe/bitcoinxt,174high/bitcoin,domob1812/bitcoin,gravio-net/graviocoin,odemolliens/bitcoinxt,phelix/bitcoin,dexX7/bitcoin,markf78/dollarcoin,11755033isaprimenumber/Feathercoin,metacoin/florincoin,AllanDoensen/BitcoinUnlimited,daliwangi/bitcoin,rawodb/bitcoin,Jeff88Ho/bitcoin,digibyte/digibyte,bcpki/nonce2testblocks,apoelstra/elements,likecoin-dev/bitcoin,rnicoll/bitcoin,pastday/bitcoinproject,coinkeeper/2015-06-22_18-36_darkcoin,bcpki/nonce2,welshjf/bitcoin,error10/bitcoin,Bushstar/UFO-Project,mm-s/bitcoin,truthcoin/truthcoin-cpp,digibyte/digibyte,pascalguru/florincoin,antonio-fr/bitcoin,rebroad/bitcoin,TheBlueMatt/bitcoin,earonesty/bitcoin,mitchellcash/bitcoin,robvanbentem/bitcoin,plncoin/PLNcoin_Core,bitreserve/bitcoin,rnicoll/dogecoin,bitjson/hivemind,stevemyers/bitcoinxt,HashUnlimited/Einsteinium-Unlimited,simonmulser/bitcoin,lbrtcoin/albertcoin,simdeveloper/bitcoin,thelazier/dash,pelorusjack/BlockDX,Vsync-project/Vsync,vtafaucet/virtacoin,Lucky7Studio/bitcoin,nlgcoin/guldencoin-official,Mrs-X/Darknet,appop/bitcoin,mikehearn/bitcoin,amaivsimau/bitcoin,scippio/bitcoin,crowning-/dash,x-kalux/bitcoin_WiG-B,senadmd/coinmarketwatch,Bitcoin-ABC/bitcoin-abc,tecnovert/particl-core,GreenParhelia/bitcoin,tedlz123/Bitcoin,martindale/elements,ctwiz/stardust,theuni/bitcoin,biblepay/biblepay,oklink-dev/bitcoin,gandrewstone/BitcoinUnlimited,kleetus/bitcoinxt,Anoncoin/anoncoin,Kore-Core/kore,nmarley/dash,cotner/bitcoin,GroestlCoin/bitcoin,lateminer/bitcoin,BitzenyCoreDevelopers/bitzeny,simdeveloper/bitcoin,skaht/bitcoin,pataquets/namecoin-core,s-matthew-english/bitcoin,Mrs-X/Darknet,svost/bitcoin,Cocosoft/bitcoin,ajtowns/bitcoin,chaincoin/chaincoin,dagurval/bitcoinxt,xieta/mincoin,BTCfork/hardfork_prototype_1_mvf-core,sbellem/bitcoin,dan-mi-sun/bitcoin,emc2foundation/einsteinium,coinkeeper/2015-06-22_18-31_bitcoin,upgradeadvice/MUE-Src,haobtc/bitcoin,imharrywu/fastcoin,namecoin/namecoin-core,EthanHeilman/bitcoin,zander/bitcoinclassic,BTCGPU/BTCGPU,FinalHashLLC/namecore,roques/bitcoin,genavarov/lamacoin,willwray/dash,daveperkins-github/bitcoin-dev,hasanatkazmi/bitcoin,RHavar/bitcoin,joshrabinowitz/bitcoin,instagibbs/bitcoin,dgarage/bc3,midnight-miner/LasVegasCoin,atgreen/bitcoin,misdess/bitcoin,ravenbyron/phtevencoin,Metronotes/bitcoin,jambolo/bitcoin,RyanLucchese/energi,dscotese/bitcoin,robvanbentem/bitcoin,leofidus/glowing-octo-ironman,Horrorcoin/horrorcoin,earonesty/bitcoin,willwray/dash,capitalDIGI/litecoin,djpnewton/bitcoin,GreenParhelia/bitcoin,dmrtsvetkov/flowercoin,scmorse/bitcoin,Kangmo/bitcoin,kirkalx/bitcoin,ryanxcharles/bitcoin,capitalDIGI/litecoin,dashpay/dash,segwit/atbcoin-insight,constantine001/bitcoin,bdelzell/creditcoin-org-creditcoin,HeliumGas/helium,kevcooper/bitcoin,acid1789/bitcoin,nlgcoin/guldencoin-official,midnightmagic/bitcoin,rromanchuk/bitcoinxt,collapsedev/cashwatt,nvmd/bitcoin,funbucks/notbitcoinxt,rnicoll/bitcoin,myriadteam/myriadcoin,DigitalPandacoin/pandacoin,BTCfork/hardfork_prototype_1_mvf-bu,NicolasDorier/bitcoin,senadmd/coinmarketwatch,ahmedbodi/vertcoin,gazbert/bitcoin,UFOCoins/ufo,genavarov/brcoin,digideskio/namecoin,kirkalx/bitcoin,MonetaryUnit/MUE-Src,btc1/bitcoin,wiggi/huntercore,prusnak/bitcoin,langerhans/dogecoin,funkshelper/woodcoin-b,hsavit1/bitcoin,dagurval/bitcoinxt,DGCDev/argentum,jmgilbert2/energi,morcos/bitcoin,goku1997/bitcoin,lbryio/lbrycrd,mikehearn/bitcoin,fedoracoin-dev/fedoracoin,bitcoinknots/bitcoin,joulecoin/joulecoin,OstlerDev/florincoin,multicoins/marycoin,petertodd/bitcoin,vtafaucet/virtacoin,domob1812/huntercore,millennial83/bitcoin,globaltoken/globaltoken,ivansib/sibcoin,Michagogo/bitcoin,iosdevzone/bitcoin,bitbrazilcoin-project/bitbrazilcoin,czr5014iph/bitcoin4e,BTCTaras/bitcoin,40thoughts/Coin-QualCoin,LIMXTEC/DMDv3,MasterX1582/bitcoin-becoin,GroestlCoin/GroestlCoin,droark/elements,isocolsky/bitcoinxt,bittylicious/bitcoin,GwangJin/gwangmoney-core,fsb4000/bitcoin,rjshaver/bitcoin,BTCfork/hardfork_prototype_1_mvf-bu,Krellan/bitcoin,bitcoin-hivemind/hivemind,kirkalx/bitcoin,Kangmo/bitcoin,amaivsimau/bitcoin,vtafaucet/virtacoin,patricklodder/dogecoin,jonasschnelli/bitcoin,butterflypay/bitcoin,antcheck/antcoin,ingresscoin/ingresscoin,habibmasuro/bitcoin,gandrewstone/BitcoinUnlimited,21E14/bitcoin,cryptoprojects/ultimateonlinecash,Metronotes/bitcoin,Gazer022/bitcoin,ericshawlinux/bitcoin,hsavit1/bitcoin,arnuschky/bitcoin,Tetpay/bitcoin,BTCGPU/BTCGPU,itmanagerro/tresting,goldcoin/Goldcoin-GLD,174high/bitcoin,omefire/bitcoin,Exgibichi/statusquo,achow101/bitcoin,isle2983/bitcoin,Xekyo/bitcoin,axelxod/braincoin,millennial83/bitcoin,domob1812/i0coin,MikeAmy/bitcoin,TierNolan/bitcoin,octocoin-project/octocoin,wangxinxi/litecoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,anditto/bitcoin,Flurbos/Flurbo,destenson/bitcoin--bitcoin,JeremyRand/bitcoin,grumpydevelop/singularity,chaincoin/chaincoin,jambolo/bitcoin,Mrs-X/Darknet,111t8e/bitcoin,anditto/bitcoin,goldcoin/Goldcoin-GLD,janko33bd/bitcoin,Mrs-X/PIVX,Bloom-Project/Bloom,joulecoin/joulecoin,Chancoin-core/CHANCOIN,monacoinproject/monacoin,okinc/bitcoin,Christewart/bitcoin,vertcoin/vertcoin,constantine001/bitcoin,Gazer022/bitcoin,pinheadmz/bitcoin,Bitcoin-ABC/bitcoin-abc,Kogser/bitcoin,vericoin/vericoin-core,ivansib/sib16,jonghyeopkim/bitcoinxt,syscoin/syscoin2,mastercoin-MSC/mastercore,TheBlueMatt/bitcoin,mruddy/bitcoin,truthcoin/blocksize-market,pastday/bitcoinproject,ediston/energi,KnCMiner/bitcoin,gmaxwell/bitcoin,Bitcoinsulting/bitcoinxt,ahmedbodi/test2,1185/starwels,rjshaver/bitcoin,AkioNak/bitcoin,starwels/starwels,vmp32k/litecoin,gzuser01/zetacoin-bitcoin,Justaphf/BitcoinUnlimited,marlengit/hardfork_prototype_1_mvf-bu,aciddude/Feathercoin,aspanta/bitcoin,andres-root/bitcoinxt,arruah/ensocoin,botland/bitcoin,haisee/dogecoin,wbchen99/bitcoin-hnote0,ticclassic/ic,cannabiscoindev/cannabiscoin420,spiritlinxl/BTCGPU,BigBlueCeiling/augmentacoin,UASF/bitcoin,bitreserve/bitcoin,peercoin/peercoin,coinkeeper/2015-06-22_18-52_viacoin,kleetus/bitcoinxt,Anoncoin/anoncoin,torresalyssa/bitcoin,AdrianaDinca/bitcoin,JeremyRand/namecoin-core,coinkeeper/2015-06-22_18-52_viacoin,TeamBitBean/bitcoin-core,truthcoin/truthcoin-cpp,haobtc/bitcoin,mrbandrews/bitcoin,sipa/bitcoin,core-bitcoin/bitcoin,se3000/bitcoin,jimmykiselak/lbrycrd,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,GlobalBoost/GlobalBoost,LIMXTEC/DMDv3,kevcooper/bitcoin,pouta/bitcoin,gandrewstone/bitcoinxt,cdecker/bitcoin,dagurval/bitcoinxt,r8921039/bitcoin,CodeShark/bitcoin,crowning-/dash,wcwu/bitcoin,40thoughts/Coin-QualCoin,dgarage/bc3,MeshCollider/bitcoin,tropa/axecoin,marcusdiaz/BitcoinUnlimited,slingcoin/sling-market,thrasher-/litecoin,PRabahy/bitcoin,Kore-Core/kore,ryanxcharles/bitcoin,Vsync-project/Vsync,ppcoin/ppcoin,JeremyRand/bitcoin,Flurbos/Flurbo,bcpki/nonce2testblocks,bcpki/testblocks,vcoin-project/vcoincore,cmgustavo/bitcoin,shelvenzhou/BTCGPU,initaldk/bitcoin,wtogami/bitcoin,schinzelh/dash,Chancoin-core/CHANCOIN,CoinProjects/AmsterdamCoin-v4,litecoin-project/bitcoinomg,lbrtcoin/albertcoin,bitpay/bitcoin,HeliumGas/helium,worldbit/worldbit,GlobalBoost/GlobalBoost,CryptArc/bitcoin,pinkevich/dash,jl2012/litecoin,wederw/bitcoin,BitcoinPOW/BitcoinPOW,zixan/bitcoin,antcheck/antcoin,vtafaucet/virtacoin,kleetus/bitcoin,xieta/mincoin,kbccoin/kbc,isocolsky/bitcoinxt,ticclassic/ic,aburan28/elements,NateBrune/bitcoin-nate,brandonrobertz/namecoin-core,nailtaras/nailcoin,okinc/bitcoin,btc1/bitcoin,leofidus/glowing-octo-ironman,dev1972/Satellitecoin,jimmysong/bitcoin,zcoinofficial/zcoin,meighti/bitcoin,npccoin/npccoin,syscoin/syscoin2,yenliangl/bitcoin,czr5014iph/bitcoin4e,puticcoin/putic,deeponion/deeponion,HashUnlimited/Einsteinium-Unlimited,dmrtsvetkov/flowercoin,jimmysong/bitcoin,Har01d/bitcoin,aspanta/bitcoin,NateBrune/bitcoin-fio,parvez3019/bitcoin,rawodb/bitcoin,stamhe/bitcoin,terracoin/terracoin,NateBrune/bitcoin-nate,blocktrail/bitcoin,nailtaras/nailcoin,trippysalmon/bitcoin,apoelstra/bitcoin,nlgcoin/guldencoin-official,Mrs-X/PIVX,NateBrune/bitcoin-fio,lakepay/lake,koharjidan/dogecoin,reddink/reddcoin,cannabiscoindev/cannabiscoin420,HashUnlimited/Einsteinium-Unlimited,daliwangi/bitcoin,ahmedbodi/terracoin,nvmd/bitcoin,TierNolan/bitcoin,brishtiteveja/truthcoin-cpp,robvanbentem/bitcoin,bitbrazilcoin-project/bitbrazilcoin,rustyrussell/bitcoin,keesdewit82/LasVegasCoin,gandrewstone/bitcoinxt,Darknet-Crypto/Darknet,hyperwang/bitcoin,bittylicious/bitcoin,greenaddress/bitcoin,Anfauglith/iop-hd,zcoinofficial/zcoin,ptschip/bitcoinxt,safecoin/safecoin,Jeff88Ho/bitcoin,skaht/bitcoin,NateBrune/bitcoin-fio,DogTagRecon/Still-Leraning,wangxinxi/litecoin,amaivsimau/bitcoin,reddcoin-project/reddcoin,NicolasDorier/bitcoin,josephbisch/namecoin-core,dan-mi-sun/bitcoin,paveljanik/bitcoin,bmp02050/ReddcoinUpdates,bespike/litecoin,truthcoin/blocksize-market,zotherstupidguy/bitcoin,GroundRod/anoncoin,yenliangl/bitcoin,gmaxwell/bitcoin,oklink-dev/bitcoin_block,ardsu/bitcoin,greencoin-dev/digitalcoin,cybermatatu/bitcoin,constantine001/bitcoin,pascalguru/florincoin,aspirecoin/aspire,unsystemizer/bitcoin,ShwoognationHQ/bitcoin,earonesty/bitcoin,Flowdalic/bitcoin,Friedbaumer/litecoin,wtogami/bitcoin,oklink-dev/bitcoin_block,Krellan/bitcoin,rawodb/bitcoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,gzuser01/zetacoin-bitcoin,gavinandresen/bitcoin-git,gameunits/gameunits,rsdevgun16e/energi,nmarley/dash,phelix/bitcoin,MarcoFalke/bitcoin,pastday/bitcoinproject,stamhe/bitcoin,isghe/bitcoinxt,alejandromgk/Lunar,yenliangl/bitcoin,CodeShark/bitcoin,mycointest/owncoin,nsacoin/nsacoin,putinclassic/putic,jmcorgan/bitcoin,Tetpay/bitcoin,accraze/bitcoin,sirk390/bitcoin,dscotese/bitcoin,AllanDoensen/BitcoinUnlimited,daliwangi/bitcoin,jn2840/bitcoin,elliotolds/bitcoin,ahmedbodi/terracoin,StarbuckBG/BTCGPU,MazaCoin/mazacoin-new,paveljanik/bitcoin,cdecker/bitcoin,gazbert/bitcoin,jmcorgan/bitcoin,koharjidan/litecoin,bankonmecoin/bitcoin,RazorLove/cloaked-octo-spice,florincoin/florincoin,nomnombtc/bitcoin,nathan-at-least/zcash,jmgilbert2/energi,octocoin-project/octocoin,DSPay/DSPay,ericshawlinux/bitcoin,bitpay/bitcoin,wiggi/huntercore,Darknet-Crypto/Darknet,fujicoin/fujicoin,funkshelper/woodcoin-b,robvanbentem/bitcoin,janko33bd/bitcoin,koharjidan/litecoin,PIVX-Project/PIVX,deeponion/deeponion,diggcoin/diggcoin,fujicoin/fujicoin,greenaddress/bitcoin,SartoNess/BitcoinUnlimited,REAP720801/bitcoin,greencoin-dev/digitalcoin,randy-waterhouse/bitcoin,litecoin-project/litecore-litecoin,kallewoof/elements,steakknife/bitcoin-qt,zsulocal/bitcoin,drwasho/bitcoinxt,Metronotes/bitcoin,Mrs-X/Darknet,my-first/octocoin,RibbitFROG/ribbitcoin,bitcoinxt/bitcoinxt,rdqw/sscoin,domob1812/huntercore,tjps/bitcoin,mockcoin/mockcoin,Alex-van-der-Peet/bitcoin,appop/bitcoin,jamesob/bitcoin,habibmasuro/bitcoin,bitcoinknots/bitcoin,fussl/elements,48thct2jtnf/P,se3000/bitcoin,coinkeeper/2015-06-22_18-31_bitcoin,arnuschky/bitcoin,goku1997/bitcoin,kbccoin/kbc,dgarage/bc3,patricklodder/dogecoin,theuni/bitcoin,genavarov/ladacoin,rat4/bitcoin,capitalDIGI/DIGI-v-0-10-4,m0gliE/fastcoin-cli,ArgonToken/ArgonToken,phelix/namecore,zander/bitcoinclassic,174high/bitcoin,svost/bitcoin,BitcoinPOW/BitcoinPOW,aburan28/elements,TrainMAnB/vcoincore,ediston/energi,gandrewstone/BitcoinUnlimited,gapcoin/gapcoin,bcpki/testblocks,Alonzo-Coeus/bitcoin,Vector2000/bitcoin,droark/elements,nigeriacoin/nigeriacoin,domob1812/i0coin,XertroV/bitcoin-nulldata,pstratem/elements,oklink-dev/bitcoin,imharrywu/fastcoin,mb300sd/bitcoin,shaulkf/bitcoin,reorder/viacoin,dscotese/bitcoin,FinalHashLLC/namecore,neuroidss/bitcoin,phelix/namecore,laudaa/bitcoin,RHavar/bitcoin,pstratem/elements,particl/particl-core,omefire/bitcoin,ColossusCoinXT/ColossusCoinXT,wiggi/huntercore,48thct2jtnf/P,bitcoin/bitcoin,joshrabinowitz/bitcoin,vlajos/bitcoin,dexX7/mastercore,romanornr/viacoin,Exgibichi/statusquo,practicalswift/bitcoin,111t8e/bitcoin,royosherove/bitcoinxt,brishtiteveja/sherlockcoin,error10/bitcoin,sugruedes/bitcoinxt,jrmithdobbs/bitcoin,MazaCoin/mazacoin-new,vlajos/bitcoin,amaivsimau/bitcoin,shaolinfry/litecoin,appop/bitcoin,putinclassic/putic,ludbb/bitcoin,JeremyRubin/bitcoin,xawksow/GroestlCoin,zsulocal/bitcoin,sugruedes/bitcoin,ctwiz/stardust,zenywallet/bitzeny,gameunits/gameunits,sipa/elements,genavarov/ladacoin,yenliangl/bitcoin,marcusdiaz/BitcoinUnlimited,Christewart/bitcoin,zottejos/merelcoin,jtimon/elements,Thracky/monkeycoin,dcousens/bitcoin,11755033isaprimenumber/Feathercoin,habibmasuro/bitcoin,1185/starwels,faircoin/faircoin,JeremyRand/namecore,midnight-miner/LasVegasCoin,bitpay/bitcoin,cyrixhero/bitcoin,sebrandon1/bitcoin,world-bank/unpay-core,wellenreiter01/Feathercoin,tropa/axecoin,segwit/atbcoin-insight,Diapolo/bitcoin,isocolsky/bitcoinxt,KaSt/ekwicoin,marklai9999/Taiwancoin,Kogser/bitcoin,lclc/bitcoin,mobicoins/mobicoin-core,NateBrune/bitcoin-fio,GroundRod/anoncoin,ahmedbodi/test2,OmniLayer/omnicore,cddjr/BitcoinUnlimited,kleetus/bitcoinxt,cddjr/BitcoinUnlimited,wangxinxi/litecoin,untrustbank/litecoin,daveperkins-github/bitcoin-dev,Gazer022/bitcoin,ixcoinofficialpage/master,Rav3nPL/bitcoin,JeremyRubin/bitcoin,cryptodev35/icash,DMDcoin/Diamond,misdess/bitcoin,knolza/gamblr,HeliumGas/helium,coinkeeper/2015-06-22_18-31_bitcoin,truthcoin/truthcoin-cpp,Exceltior/dogecoin,BitcoinPOW/BitcoinPOW,cerebrus29301/crowncoin,rnicoll/dogecoin,ixcoinofficialpage/master,shouhuas/bitcoin,skaht/bitcoin,guncoin/guncoin,antonio-fr/bitcoin,xurantju/bitcoin,apoelstra/bitcoin,BTCDDev/bitcoin,jameshilliard/bitcoin,dagurval/bitcoinxt,afk11/bitcoin,ajweiss/bitcoin,fullcoins/fullcoin,ShadowMyst/creativechain-core,Rav3nPL/polcoin,lbrtcoin/albertcoin,ekankyesme/bitcoinxt,bitcoin/bitcoin,pastday/bitcoinproject,FarhanHaque/bitcoin,ericshawlinux/bitcoin,ftrader-bitcoinabc/bitcoin-abc,dgarage/bc2,maaku/bitcoin,jmcorgan/bitcoin,NicolasDorier/bitcoin,bitcoinplusorg/xbcwalletsource,Kogser/bitcoin,masterbraz/dg,elecoin/elecoin,48thct2jtnf/P,ShwoognationHQ/bitcoin,dgarage/bc2,PandaPayProject/PandaPay,slingcoin/sling-market,Alex-van-der-Peet/bitcoin,StarbuckBG/BTCGPU,error10/bitcoin,apoelstra/elements,rsdevgun16e/energi,benzmuircroft/REWIRE.io,vmp32k/litecoin,Jcing95/iop-hd,scmorse/bitcoin,adpg211/bitcoin-master,TeamBitBean/bitcoin-core,kallewoof/bitcoin,qtumproject/qtum,langerhans/dogecoin,EthanHeilman/bitcoin,midnightmagic/bitcoin,Rav3nPL/polcoin,lclc/bitcoin,morcos/bitcoin,digibyte/digibyte,Jcing95/iop-hd,zcoinofficial/zcoin,Flurbos/Flurbo,aburan28/elements,nvmd/bitcoin,Jcing95/iop-hd,coinkeeper/2015-06-22_18-31_bitcoin,Darknet-Crypto/Darknet,UFOCoins/ufo,presstab/PIVX,sstone/bitcoin,royosherove/bitcoinxt,jmgilbert2/energi,bitcoinsSG/zcash,Gazer022/bitcoin,syscoin/syscoin,Cocosoft/bitcoin,zcoinofficial/zcoin,jrmithdobbs/bitcoin,haraldh/bitcoin,EntropyFactory/creativechain-core,DigitalPandacoin/pandacoin,Kogser/bitcoin,ivansib/sib16,pstratem/elements,isle2983/bitcoin,nathaniel-mahieu/bitcoin,DigiByte-Team/digibyte,Thracky/monkeycoin,jiangyonghang/bitcoin,daliwangi/bitcoin,scippio/bitcoin,174high/bitcoin,loxal/zcash,tecnovert/particl-core,zixan/bitcoin,bcpki/nonce2testblocks,MazaCoin/maza,coinwarp/dogecoin,sstone/bitcoin,deuscoin/deuscoin,sipa/elements,aspirecoin/aspire,Cocosoft/bitcoin,cmgustavo/bitcoin,bitcoinclassic/bitcoinclassic,bdelzell/creditcoin-org-creditcoin,fullcoins/fullcoin,knolza/gamblr,blocktrail/bitcoin,TrainMAnB/vcoincore,Ziftr/bitcoin,elliotolds/bitcoin,lbryio/lbrycrd,parvez3019/bitcoin,tedlz123/Bitcoin,kallewoof/bitcoin,myriadcoin/myriadcoin,nlgcoin/guldencoin-official,zsulocal/bitcoin,koharjidan/dogecoin,h4x3rotab/BTCGPU,simdeveloper/bitcoin,superjudge/bitcoin,SoreGums/bitcoinxt,xuyangcn/opalcoin,UFOCoins/ufo,HashUnlimited/Einsteinium-Unlimited,crowning-/dash,Flurbos/Flurbo,rnicoll/dogecoin,reorder/viacoin,Mirobit/bitcoin,balajinandhu/bitcoin,ShadowMyst/creativechain-core,fsb4000/bitcoin,initaldk/bitcoin,brishtiteveja/sherlockcoin,LIMXTEC/DMDv3,sbaks0820/bitcoin,nikkitan/bitcoin,DigiByte-Team/digibyte,dgenr8/bitcoinxt,imharrywu/fastcoin,Kogser/bitcoin,mincoin-project/mincoin,butterflypay/bitcoin,ajweiss/bitcoin,grumpydevelop/singularity,isle2983/bitcoin,fedoracoin-dev/fedoracoin,shaulkf/bitcoin,kaostao/bitcoin,multicoins/marycoin,RongxinZhang/bitcoinxt,ericshawlinux/bitcoin,Rav3nPL/PLNcoin,StarbuckBG/BTCGPU,coinkeeper/2015-06-22_18-39_feathercoin,Bitcoin-com/BUcash,m0gliE/fastcoin-cli,cddjr/BitcoinUnlimited,dogecoin/dogecoin,dcousens/bitcoin,Rav3nPL/doubloons-0.10,gwillen/elements,rnicoll/bitcoin,rromanchuk/bitcoinxt,Rav3nPL/doubloons-0.10,BitcoinPOW/BitcoinPOW,cqtenq/feathercoin_core,Bloom-Project/Bloom,scippio/bitcoin,wtogami/bitcoin,marcusdiaz/BitcoinUnlimited,Mrs-X/PIVX,awemany/BitcoinUnlimited,deadalnix/bitcoin,wederw/bitcoin,Petr-Economissa/gvidon,freelion93/mtucicoin,inutoshi/inutoshi,CoinProjects/AmsterdamCoin-v4,GroestlCoin/GroestlCoin,gameunits/gameunits,Michagogo/bitcoin,ediston/energi,CoinProjects/AmsterdamCoin-v4,shomeser/bitcoin,thrasher-/litecoin,droark/bitcoin,prark/bitcoinxt,StarbuckBG/BTCGPU,schildbach/bitcoin,worldbit/worldbit,multicoins/marycoin,Kixunil/keynescoin,benzmuircroft/REWIRE.io,AllanDoensen/BitcoinUnlimited,iQcoin/iQcoin,cybermatatu/bitcoin,Kixunil/keynescoin,xuyangcn/opalcoin,MazaCoin/maza,pataquets/namecoin-core,crowning2/dash,untrustbank/litecoin,jeromewu/bitcoin-opennet,presstab/PIVX,superjudge/bitcoin,jameshilliard/bitcoin,denverl/bitcoin,genavarov/brcoin,andres-root/bitcoinxt,shomeser/bitcoin,sugruedes/bitcoin,Alex-van-der-Peet/bitcoin,jonghyeopkim/bitcoinxt,DynamicCoinOrg/DMC,acid1789/bitcoin,FinalHashLLC/namecore,phplaboratory/psiacoin,Bitcoinsulting/bitcoinxt,phelix/namecore,bitcoinplusorg/xbcwalletsource,ripper234/bitcoin,itmanagerro/tresting,isghe/bitcoinxt,multicoins/marycoin,EntropyFactory/creativechain-core,wcwu/bitcoin,ShwoognationHQ/bitcoin,marlengit/BitcoinUnlimited,ixcoinofficialpage/master,namecoin/namecoin-core,aburan28/elements,Alonzo-Coeus/bitcoin,kleetus/bitcoin,namecoin/namecore,sickpig/BitcoinUnlimited,balajinandhu/bitcoin,Vsync-project/Vsync,ivansib/sibcoin,vcoin-project/vcoincore,terracoin/terracoin,kazcw/bitcoin,kbccoin/kbc,Bitcoin-ABC/bitcoin-abc,TrainMAnB/vcoincore,llluiop/bitcoin,iQcoin/iQcoin,HashUnlimited/Einsteinium-Unlimited,h4x3rotab/BTCGPU,puticcoin/putic,Kcoin-project/kcoin,prusnak/bitcoin,hyperwang/bitcoin,mastercoin-MSC/mastercore,dev1972/Satellitecoin,paveljanik/bitcoin,Mrs-X/PIVX,n1bor/bitcoin,Alonzo-Coeus/bitcoin,UdjinM6/dash,neuroidss/bitcoin,viacoin/viacoin,trippysalmon/bitcoin,PandaPayProject/PandaPay,KibiCoin/kibicoin,cryptoprojects/ultimateonlinecash,Bitcoin-ABC/bitcoin-abc,riecoin/riecoin,bmp02050/ReddcoinUpdates,jtimon/elements,aspirecoin/aspire,Flowdalic/bitcoin,achow101/bitcoin,jlopp/statoshi,vericoin/vericoin-core,OmniLayer/omnicore,Darknet-Crypto/Darknet,patricklodder/dogecoin,segsignal/bitcoin,TierNolan/bitcoin,wangxinxi/litecoin,biblepay/biblepay,fsb4000/bitcoin,FeatherCoin/Feathercoin,UASF/bitcoin,bitcoinplusorg/xbcwalletsource,Diapolo/bitcoin,BTCGPU/BTCGPU,Anfauglith/iop-hd,hophacker/bitcoin_malleability,achow101/bitcoin,Lucky7Studio/bitcoin,oleganza/bitcoin-duo,goku1997/bitcoin,biblepay/biblepay,marklai9999/Taiwancoin,brandonrobertz/namecoin-core,gandrewstone/bitcoinxt,xieta/mincoin,kirkalx/bitcoin,rat4/bitcoin,oleganza/bitcoin-duo,guncoin/guncoin,TrainMAnB/vcoincore,alejandromgk/Lunar,myriadcoin/myriadcoin,arnuschky/bitcoin,tdudz/elements,rdqw/sscoin,btc1/bitcoin,TierNolan/bitcoin,inkvisit/sarmacoins,jrick/bitcoin,sipsorcery/bitcoin,dogecoin/dogecoin,nbenoit/bitcoin,digideskio/namecoin,octocoin-project/octocoin,irvingruan/bitcoin,PIVX-Project/PIVX,lateminer/bitcoin,kaostao/bitcoin,ptschip/bitcoinxt,Alonzo-Coeus/bitcoin,jtimon/elements,sdaftuar/bitcoin,Michagogo/bitcoin,DGCDev/argentum,cybermatatu/bitcoin,KnCMiner/bitcoin,s-matthew-english/bitcoin,MikeAmy/bitcoin,Vsync-project/Vsync,cyrixhero/bitcoin,UFOCoins/ufo,braydonf/bitcoin,xurantju/bitcoin,multicoins/marycoin,deadalnix/bitcoin,ppcoin/ppcoin,tecnovert/particl-core,supcoin/supcoin,Xekyo/bitcoin,metacoin/florincoin,meighti/bitcoin,mapineda/litecoin,drwasho/bitcoinxt,vertcoin/vertcoin,HeliumGas/helium,21E14/bitcoin,argentumproject/argentum,keo/bitcoin,capitalDIGI/litecoin,bitcoinclassic/bitcoinclassic,xawksow/GroestlCoin,alecalve/bitcoin,putinclassic/putic,segsignal/bitcoin,x-kalux/bitcoin_WiG-B,kallewoof/elements,mycointest/owncoin,alecalve/bitcoin,mockcoin/mockcoin,Christewart/bitcoin,domob1812/huntercore,mm-s/bitcoin,Flurbos/Flurbo,maaku/bitcoin,MarcoFalke/bitcoin,BTCfork/hardfork_prototype_1_mvf-bu,coinwarp/dogecoin,senadmd/coinmarketwatch,BTCfork/hardfork_prototype_1_mvf-core,untrustbank/litecoin,brishtiteveja/truthcoin-cpp,domob1812/i0coin,ShwoognationHQ/bitcoin,mastercoin-MSC/mastercore,Rav3nPL/doubloons-0.10,diggcoin/diggcoin,gwillen/elements,Anoncoin/anoncoin,Justaphf/BitcoinUnlimited,morcos/bitcoin,nigeriacoin/nigeriacoin,globaltoken/globaltoken,sebrandon1/bitcoin,jimmykiselak/lbrycrd,FarhanHaque/bitcoin,GlobalBoost/GlobalBoost,CryptArc/bitcoinxt,phelix/namecore,Kixunil/keynescoin,ivansib/sibcoin,jonasnick/bitcoin,awemany/BitcoinUnlimited,atgreen/bitcoin,Justaphf/BitcoinUnlimited,RongxinZhang/bitcoinxt,reddcoin-project/reddcoin,antonio-fr/bitcoin,Kogser/bitcoin,donaloconnor/bitcoin,bitcoin/bitcoin,Anfauglith/iop-hd,litecoin-project/litecoin,greencoin-dev/digitalcoin,simonmulser/bitcoin,ashleyholman/bitcoin,anditto/bitcoin,koharjidan/litecoin,pelorusjack/BlockDX,bdelzell/creditcoin-org-creditcoin,HeliumGas/helium,thesoftwarejedi/bitcoin,Christewart/bitcoin,collapsedev/cashwatt,arruah/ensocoin,AkioNak/bitcoin,reorder/viacoin,jlopp/statoshi,funbucks/notbitcoinxt,sbaks0820/bitcoin,antcheck/antcoin,bitbrazilcoin-project/bitbrazilcoin,crowning-/dash,NateBrune/bitcoin-fio,jtimon/elements,Mrs-X/Darknet,awemany/BitcoinUnlimited,dogecoin/dogecoin,reorder/viacoin,drwasho/bitcoinxt,CodeShark/bitcoin,ahmedbodi/vertcoin,andres-root/bitcoinxt,ashleyholman/bitcoin,Bushstar/UFO-Project,faircoin/faircoin,Exceltior/dogecoin,Friedbaumer/litecoin,s-matthew-english/bitcoin,Flowdalic/bitcoin,nailtaras/nailcoin,Bloom-Project/Bloom,bankonmecoin/bitcoin,sbellem/bitcoin,Xekyo/bitcoin,haobtc/bitcoin,argentumproject/argentum,hsavit1/bitcoin,ElementsProject/elements,cculianu/bitcoin-abc,StarbuckBG/BTCGPU,marlengit/hardfork_prototype_1_mvf-bu,sbaks0820/bitcoin,funkshelper/woodcore,jimmysong/bitcoin,Rav3nPL/polcoin,ryanxcharles/bitcoin,bitcoinec/bitcoinec,kfitzgerald/titcoin,Cloudsy/bitcoin,keesdewit82/LasVegasCoin,Diapolo/bitcoin,rjshaver/bitcoin,projectinterzone/ITZ,digideskio/namecoin,presstab/PIVX,braydonf/bitcoin,peercoin/peercoin,MeshCollider/bitcoin,wbchen99/bitcoin-hnote0,upgradeadvice/MUE-Src,capitalDIGI/DIGI-v-0-10-4,credits-currency/credits,ingresscoin/ingresscoin,nvmd/bitcoin,thrasher-/litecoin,benzmuircroft/REWIRE.io,Mirobit/bitcoin,jrmithdobbs/bitcoin,ShadowMyst/creativechain-core,brishtiteveja/sherlockcoin,llluiop/bitcoin,Bitcoin-ABC/bitcoin-abc,riecoin/riecoin,elliotolds/bitcoin,Flurbos/Flurbo,litecoin-project/litecore-litecoin,shaolinfry/litecoin,FeatherCoin/Feathercoin,cryptodev35/icash,bitcoinclassic/bitcoinclassic,sugruedes/bitcoinxt,GwangJin/gwangmoney-core,Har01d/bitcoin,jimmykiselak/lbrycrd,Michagogo/bitcoin,thesoftwarejedi/bitcoin,mb300sd/bitcoin,superjudge/bitcoin,RongxinZhang/bitcoinxt,aciddude/Feathercoin,gazbert/bitcoin,vericoin/vericoin-core,viacoin/viacoin,jakeva/bitcoin-pwcheck,rat4/bitcoin,litecoin-project/bitcoinomg,aniemerg/zcash,Anfauglith/iop-hd,Domer85/dogecoin,shaolinfry/litecoin,CryptArc/bitcoin,faircoin/faircoin,cerebrus29301/crowncoin,segsignal/bitcoin,mycointest/owncoin,fanquake/bitcoin,truthcoin/truthcoin-cpp,xieta/mincoin,ptschip/bitcoin,inkvisit/sarmacoins,faircoin/faircoin,diggcoin/diggcoin,habibmasuro/bitcoin,donaloconnor/bitcoin,elecoin/elecoin,jameshilliard/bitcoin,dannyperez/bolivarcoin,nathaniel-mahieu/bitcoin,uphold/bitcoin,zetacoin/zetacoin,DigiByte-Team/digibyte,jonasschnelli/bitcoin,btcdrak/bitcoin,lakepay/lake,schildbach/bitcoin,GwangJin/gwangmoney-core,joroob/reddcoin,sipsorcery/bitcoin,Cloudsy/bitcoin,martindale/elements,pstratem/bitcoin,cdecker/bitcoin,jiangyonghang/bitcoin,langerhans/dogecoin,guncoin/guncoin,dgarage/bc3,ElementsProject/elements,droark/elements,coinkeeper/2015-06-22_18-36_darkcoin,appop/bitcoin,cmgustavo/bitcoin,bitcoinsSG/zcash,ftrader-bitcoinabc/bitcoin-abc,bittylicious/bitcoin,knolza/gamblr,cybermatatu/bitcoin,digibyte/digibyte,jl2012/litecoin,vlajos/bitcoin,initaldk/bitcoin,coinkeeper/2015-06-22_18-37_dogecoin,dgenr8/bitcoin,llluiop/bitcoin,MazaCoin/mazacoin-new,cerebrus29301/crowncoin,HeliumGas/helium,Xekyo/bitcoin,upgradeadvice/MUE-Src,Metronotes/bitcoin,ftrader-bitcoinabc/bitcoin-abc,tuaris/bitcoin,dexX7/bitcoin,fussl/elements,vcoin-project/vcoincore,nomnombtc/bitcoin,omefire/bitcoin,CryptArc/bitcoinxt,itmanagerro/tresting,Christewart/bitcoin,jonasnick/bitcoin,benzmuircroft/REWIRE.io,jameshilliard/bitcoin,alecalve/bitcoin,sebrandon1/bitcoin,supcoin/supcoin,MonetaryUnit/MUE-Src,ColossusCoinXT/ColossusCoinXT,presstab/PIVX,cculianu/bitcoin-abc,Kenwhite23/litecoin,marlengit/hardfork_prototype_1_mvf-bu,nomnombtc/bitcoin,odemolliens/bitcoinxt,Bitcoin-ABC/bitcoin-abc,meighti/bitcoin,emc2foundation/einsteinium,bitcoinsSG/zcash,imton/bitcoin,nikkitan/bitcoin,bespike/litecoin,ripper234/bitcoin,ekankyesme/bitcoinxt,florincoin/florincoin,funkshelper/woodcoin-b,Kenwhite23/litecoin,ixcoinofficialpage/master,shea256/bitcoin,mruddy/bitcoin,ahmedbodi/vertcoin,coinkeeper/2015-06-22_18-52_viacoin,CryptArc/bitcoin,parvez3019/bitcoin,DGCDev/digitalcoin,dpayne9000/Rubixz-Coin,EntropyFactory/creativechain-core,sickpig/BitcoinUnlimited,freelion93/mtucicoin,leofidus/glowing-octo-ironman,koharjidan/bitcoin,jakeva/bitcoin-pwcheck,FeatherCoin/Feathercoin,coinkeeper/2015-06-22_18-36_darkcoin,bitcoinsSG/bitcoin,gandrewstone/BitcoinUnlimited,axelxod/braincoin,aspanta/bitcoin,iosdevzone/bitcoin,GroundRod/anoncoin,lclc/bitcoin,Diapolo/bitcoin,bespike/litecoin,syscoin/syscoin2,xawksow/GroestlCoin,h4x3rotab/BTCGPU,dperel/bitcoin,Alex-van-der-Peet/bitcoin,UASF/bitcoin,namecoin/namecoin-core,BTCTaras/bitcoin,jmcorgan/bitcoin,aspanta/bitcoin,millennial83/bitcoin,my-first/octocoin,MasterX1582/bitcoin-becoin,dogecoin/dogecoin,gzuser01/zetacoin-bitcoin,BigBlueCeiling/augmentacoin,mapineda/litecoin,CoinProjects/AmsterdamCoin-v4,reddink/reddcoin,octocoin-project/octocoin,accraze/bitcoin,dpayne9000/Rubixz-Coin,1185/starwels,TheBlueMatt/bitcoin,mapineda/litecoin,amaivsimau/bitcoin,nigeriacoin/nigeriacoin,NateBrune/bitcoin-nate,metacoin/florincoin,21E14/bitcoin,fedoracoin-dev/fedoracoin,btcdrak/bitcoin,ionomy/ion,nailtaras/nailcoin,kfitzgerald/titcoin,ftrader-bitcoinabc/bitcoin-abc,cculianu/bitcoin-abc,NateBrune/bitcoin-nate,Kcoin-project/kcoin,TheBlueMatt/bitcoin,bcpki/nonce2,Bitcoin-ABC/bitcoin-abc,globaltoken/globaltoken,cheehieu/bitcoin,sipa/elements,JeremyRand/bitcoin,sipsorcery/bitcoin,denverl/bitcoin,Rav3nPL/bitcoin,inutoshi/inutoshi,butterflypay/bitcoin,rnicoll/dogecoin,ptschip/bitcoin,CryptArc/bitcoinxt,Bloom-Project/Bloom,basicincome/unpcoin-core,Kore-Core/kore,world-bank/unpay-core,sdaftuar/bitcoin,vmp32k/litecoin,zottejos/merelcoin,senadmd/coinmarketwatch,particl/particl-core,royosherove/bitcoinxt,sbellem/bitcoin,tuaris/bitcoin,slingcoin/sling-market,acid1789/bitcoin,haraldh/bitcoin,adpg211/bitcoin-master,cddjr/BitcoinUnlimited,nigeriacoin/nigeriacoin,ekankyesme/bitcoinxt,dgenr8/bitcoin,fullcoins/fullcoin,magacoin/magacoin,Thracky/monkeycoin,sipa/bitcoin,wiggi/huntercore,gzuser01/zetacoin-bitcoin,brishtiteveja/truthcoin-cpp,Rav3nPL/bitcoin,gazbert/bitcoin,phelix/bitcoin,NunoEdgarGub1/elements,romanornr/viacoin,millennial83/bitcoin,fussl/elements,ryanxcharles/bitcoin,koharjidan/dogecoin,jiangyonghang/bitcoin,ingresscoin/ingresscoin,truthcoin/truthcoin-cpp,shomeser/bitcoin,atgreen/bitcoin,torresalyssa/bitcoin,ryanofsky/bitcoin,shouhuas/bitcoin,vcoin-project/vcoincore,sugruedes/bitcoinxt,elecoin/elecoin,Domer85/dogecoin,ArgonToken/ArgonToken,rnicoll/bitcoin,JeremyRand/namecoin-core,Exceltior/dogecoin,CryptArc/bitcoin,jamesob/bitcoin,daliwangi/bitcoin,ardsu/bitcoin,deadalnix/bitcoin,sugruedes/bitcoin,bitcoinclassic/bitcoinclassic,langerhans/dogecoin,gazbert/bitcoin,benma/bitcoin,21E14/bitcoin,ptschip/bitcoinxt,patricklodder/dogecoin,BlockchainTechLLC/3dcoin,practicalswift/bitcoin,kazcw/bitcoin,40thoughts/Coin-QualCoin,dscotese/bitcoin,Justaphf/BitcoinUnlimited,experiencecoin/experiencecoin,wellenreiter01/Feathercoin,JeremyRand/bitcoin,petertodd/bitcoin,syscoin/syscoin,dan-mi-sun/bitcoin,zetacoin/zetacoin,UFOCoins/ufo,cqtenq/feathercoin_core,iQcoin/iQcoin,destenson/bitcoin--bitcoin,bespike/litecoin,spiritlinxl/BTCGPU,particl/particl-core,btcdrak/bitcoin,AdrianaDinca/bitcoin,hasanatkazmi/bitcoin,GreenParhelia/bitcoin,skaht/bitcoin,coinkeeper/2015-06-22_19-07_digitalcoin,dexX7/mastercore,Sjors/bitcoin,Vector2000/bitcoin,nathaniel-mahieu/bitcoin,thelazier/dash,zander/bitcoinclassic,jarymoth/dogecoin,karek314/bitcoin,faircoin/faircoin2,bankonmecoin/bitcoin,1185/starwels,BitzenyCoreDevelopers/bitzeny,marlengit/BitcoinUnlimited,roques/bitcoin,markf78/dollarcoin,loxal/zcash,domob1812/i0coin,collapsedev/cashwatt,sirk390/bitcoin,jrmithdobbs/bitcoin,deeponion/deeponion,sipa/elements,globaltoken/globaltoken,trippysalmon/bitcoin,PandaPayProject/PandaPay,collapsedev/cashwatt,ptschip/bitcoin,plncoin/PLNcoin_Core,morcos/bitcoin,atgreen/bitcoin,bmp02050/ReddcoinUpdates,dgenr8/bitcoin,donaloconnor/bitcoin,goldcoin/Goldcoin-GLD,deadalnix/bitcoin,rat4/bitcoin,segsignal/bitcoin,ionomy/ion,tjps/bitcoin,jamesob/bitcoin,Justaphf/BitcoinUnlimited,funkshelper/woodcore,MeshCollider/bitcoin,Exgibichi/statusquo,fussl/elements,syscoin/syscoin,tmagik/catcoin,nlgcoin/guldencoin-official,JeremyRand/namecoin-core,fujicoin/fujicoin,domob1812/i0coin,RibbitFROG/ribbitcoin,hasanatkazmi/bitcoin,TBoehm/greedynode,elliotolds/bitcoin,scmorse/bitcoin,Mirobit/bitcoin,sstone/bitcoin,braydonf/bitcoin,nathan-at-least/zcash,imton/bitcoin,Tetpay/bitcoin,ahmedbodi/vertcoin,LIMXTEC/DMDv3,emc2foundation/einsteinium,terracoin/terracoin,ticclassic/ic,Bitcoin-ABC/bitcoin-abc,argentumproject/argentum,paveljanik/bitcoin,trippysalmon/bitcoin,ajtowns/bitcoin,cryptoprojects/ultimateonlinecash,DMDcoin/Diamond,plncoin/PLNcoin_Core,upgradeadvice/MUE-Src,ClusterCoin/ClusterCoin,irvingruan/bitcoin,tdudz/elements,dmrtsvetkov/flowercoin,cqtenq/feathercoin_core,Bitcoin-com/BUcash,TierNolan/bitcoin,sdaftuar/bitcoin,haobtc/bitcoin,welshjf/bitcoin,scippio/bitcoin,magacoin/magacoin,jn2840/bitcoin,Alonzo-Coeus/bitcoin,rustyrussell/bitcoin,jiangyonghang/bitcoin,donaloconnor/bitcoin,jrmithdobbs/bitcoin,MonetaryUnit/MUE-Src,bitpay/bitcoin,bitcoinknots/bitcoin,Kogser/bitcoin,awemany/BitcoinUnlimited,steakknife/bitcoin-qt,se3000/bitcoin,kaostao/bitcoin,bitcoinsSG/bitcoin,apoelstra/elements,odemolliens/bitcoinxt,ctwiz/stardust,greenaddress/bitcoin,GroestlCoin/bitcoin,torresalyssa/bitcoin,stevemyers/bitcoinxt,tjth/lotterycoin,petertodd/bitcoin,sarielsaz/sarielsaz,pastday/bitcoinproject,magacoin/magacoin,mockcoin/mockcoin,Ziftr/bitcoin,deeponion/deeponion,deuscoin/deuscoin,skaht/bitcoin,jakeva/bitcoin-pwcheck,nikkitan/bitcoin,ctwiz/stardust,nailtaras/nailcoin,jnewbery/bitcoin,dcousens/bitcoin,presstab/PIVX,jimmykiselak/lbrycrd,cqtenq/feathercoin_core,unsystemizer/bitcoin,RyanLucchese/energi,zottejos/merelcoin,upgradeadvice/MUE-Src,safecoin/safecoin,credits-currency/credits,nathan-at-least/zcash,nmarley/dash,jlopp/statoshi,benosa/bitcoin,fullcoins/fullcoin,fanquake/bitcoin,ardsu/bitcoin,kazcw/bitcoin,anditto/bitcoin,willwray/dash,Darknet-Crypto/Darknet,puticcoin/putic,brishtiteveja/sherlockcoin,habibmasuro/bitcoinxt,kallewoof/elements,pataquets/namecoin-core,Petr-Economissa/gvidon,dmrtsvetkov/flowercoin,segwit/atbcoin-insight,alejandromgk/Lunar,pascalguru/florincoin,phplaboratory/psiacoin,deadalnix/bitcoin,genavarov/brcoin,daveperkins-github/bitcoin-dev,experiencecoin/experiencecoin,Rav3nPL/PLNcoin,sickpig/BitcoinUnlimited,CodeShark/bitcoin,shomeser/bitcoin,OstlerDev/florincoin,EthanHeilman/bitcoin,OstlerDev/florincoin,gapcoin/gapcoin,CryptArc/bitcoin,wangliu/bitcoin,nigeriacoin/nigeriacoin,shaolinfry/litecoin,bitcoinclassic/bitcoinclassic,nsacoin/nsacoin,faircoin/faircoin,aciddude/Feathercoin,koharjidan/bitcoin,odemolliens/bitcoinxt,coinwarp/dogecoin,domob1812/huntercore,KaSt/ekwicoin,hasanatkazmi/bitcoin,GreenParhelia/bitcoin,vlajos/bitcoin,cdecker/bitcoin,droark/elements,Kcoin-project/kcoin,octocoin-project/octocoin,inutoshi/inutoshi,monacoinproject/monacoin,pinheadmz/bitcoin,cyrixhero/bitcoin,zottejos/merelcoin,ionomy/ion,superjudge/bitcoin,koharjidan/litecoin,florincoin/florincoin,kfitzgerald/titcoin,Cloudsy/bitcoin,shaulkf/bitcoin,habibmasuro/bitcoinxt,apoelstra/elements,wcwu/bitcoin,stamhe/bitcoin,Gazer022/bitcoin,blood2/bloodcoin-0.9,ryanofsky/bitcoin,RyanLucchese/energi,capitalDIGI/litecoin,SoreGums/bitcoinxt,Domer85/dogecoin,droark/elements,imharrywu/fastcoin,mobicoins/mobicoin-core,matlongsi/micropay,bitreserve/bitcoin,shaulkf/bitcoin,ripper234/bitcoin,dannyperez/bolivarcoin,zixan/bitcoin,ryanofsky/bitcoin,initaldk/bitcoin,PRabahy/bitcoin,janko33bd/bitcoin,KaSt/ekwicoin,RyanLucchese/energi,gandrewstone/bitcoinxt,bitbrazilcoin-project/bitbrazilcoin,kirkalx/bitcoin,mikehearn/bitcoinxt,BigBlueCeiling/augmentacoin,stamhe/bitcoin,haobtc/bitcoin,afk11/bitcoin,tdudz/elements,shaolinfry/litecoin,petertodd/bitcoin,myriadteam/myriadcoin,CTRoundTable/Encrypted.Cash,masterbraz/dg,diggcoin/diggcoin,bitcoinec/bitcoinec,funbucks/notbitcoinxt,tecnovert/particl-core,dexX7/mastercore,psionin/smartcoin,BTCfork/hardfork_prototype_1_mvf-core,NunoEdgarGub1/elements,btc1/bitcoin,randy-waterhouse/bitcoin,GreenParhelia/bitcoin,braydonf/bitcoin,botland/bitcoin,BTCGPU/BTCGPU,hyperwang/bitcoin,imton/bitcoin,jambolo/bitcoin,florincoin/florincoin,TeamBitBean/bitcoin-core,TripleSpeeder/bitcoin,digideskio/namecoin,gameunits/gameunits,Friedbaumer/litecoin,TGDiamond/Diamond,bitjson/hivemind,ashleyholman/bitcoin,pinheadmz/bitcoin,spiritlinxl/BTCGPU,XertroV/bitcoin-nulldata,TrainMAnB/vcoincore,yenliangl/bitcoin,aciddude/Feathercoin,SoreGums/bitcoinxt,rdqw/sscoin,ahmedbodi/temp_vert,mockcoin/mockcoin,psionin/smartcoin,FarhanHaque/bitcoin,ingresscoin/ingresscoin,koharjidan/dogecoin,karek314/bitcoin,cddjr/BitcoinUnlimited,okinc/bitcoin,sebrandon1/bitcoin,ajweiss/bitcoin,Ziftr/bitcoin,cannabiscoindev/cannabiscoin420,JeremyRubin/bitcoin,wederw/bitcoin,jtimon/bitcoin,CoinProjects/AmsterdamCoin-v4,AkioNak/bitcoin,Chancoin-core/CHANCOIN,RazorLove/cloaked-octo-spice,coinerd/krugercoin,Flowdalic/bitcoin,Domer85/dogecoin,meighti/bitcoin,botland/bitcoin,jonasschnelli/bitcoin,KibiCoin/kibicoin,scippio/bitcoin,jl2012/litecoin,mitchellcash/bitcoin,mb300sd/bitcoin,shaulkf/bitcoin,mm-s/bitcoin,instagibbs/bitcoin,gmaxwell/bitcoin,RongxinZhang/bitcoinxt,Christewart/bitcoin,r8921039/bitcoin,leofidus/glowing-octo-ironman,JeremyRand/bitcoin,sbaks0820/bitcoin,gandrewstone/BitcoinUnlimited,GIJensen/bitcoin,guncoin/guncoin,BitcoinHardfork/bitcoin,rdqw/sscoin,BlockchainTechLLC/3dcoin,atgreen/bitcoin,achow101/bitcoin,scippio/bitcoin,wederw/bitcoin,litecoin-project/litecoin,apoelstra/bitcoin,KnCMiner/bitcoin,millennial83/bitcoin,czr5014iph/bitcoin4e,Darknet-Crypto/Darknet,theuni/bitcoin,projectinterzone/ITZ,genavarov/ladacoin,faircoin/faircoin2,droark/bitcoin,TeamBitBean/bitcoin-core,BitcoinHardfork/bitcoin,MonetaryUnit/MUE-Src,supcoin/supcoin,40thoughts/Coin-QualCoin,MazaCoin/mazacoin-new,DGCDev/argentum,RHavar/bitcoin,trippysalmon/bitcoin,DogTagRecon/Still-Leraning,mikehearn/bitcoin,masterbraz/dg,vtafaucet/virtacoin,rsdevgun16e/energi,accraze/bitcoin,puticcoin/putic,Diapolo/bitcoin,lbryio/lbrycrd,segsignal/bitcoin,coinkeeper/2015-06-22_18-37_dogecoin,rnicoll/bitcoin,genavarov/brcoin,credits-currency/credits,core-bitcoin/bitcoin,stamhe/bitcoin,benma/bitcoin,andreaskern/bitcoin,jameshilliard/bitcoin,fedoracoin-dev/fedoracoin,thesoftwarejedi/bitcoin,bitcoin-hivemind/hivemind,cculianu/bitcoin-abc,kbccoin/kbc,DigitalPandacoin/pandacoin,GroestlCoin/GroestlCoin,ivansib/sibcoin,argentumproject/argentum,Thracky/monkeycoin,ravenbyron/phtevencoin,PandaPayProject/PandaPay,Kangmo/bitcoin,joulecoin/joulecoin,diggcoin/diggcoin,Gazer022/bitcoin,GroestlCoin/bitcoin,constantine001/bitcoin,bitcoinxt/bitcoinxt,wbchen99/bitcoin-hnote0,hyperwang/bitcoin,viacoin/viacoin,jakeva/bitcoin-pwcheck,bcpki/nonce2testblocks,coinwarp/dogecoin,OmniLayer/omnicore,oleganza/bitcoin-duo,Michagogo/bitcoin,Kangmo/bitcoin,wangliu/bitcoin,SartoNess/BitcoinUnlimited,ivansib/sibcoin,Vector2000/bitcoin,world-bank/unpay-core,tjps/bitcoin,JeremyRand/bitcoin,phplaboratory/psiacoin,vericoin/vericoin-core,randy-waterhouse/bitcoin,Bushstar/UFO-Project,zenywallet/bitzeny,sarielsaz/sarielsaz,crowning2/dash,Kore-Core/kore,pelorusjack/BlockDX,collapsedev/cashwatt,kbccoin/kbc,Jcing95/iop-hd,cmgustavo/bitcoin,AdrianaDinca/bitcoin,TGDiamond/Diamond,GIJensen/bitcoin,mitchellcash/bitcoin,accraze/bitcoin,argentumproject/argentum,pelorusjack/BlockDX,kleetus/bitcoinxt,midnightmagic/bitcoin,botland/bitcoin,ivansib/sib16,apoelstra/bitcoin,czr5014iph/bitcoin4e,keo/bitcoin,maaku/bitcoin,kleetus/bitcoin,UdjinM6/dash,litecoin-project/litecore-litecoin,syscoin/syscoin2,DogTagRecon/Still-Leraning,174high/bitcoin,djpnewton/bitcoin,Vector2000/bitcoin,Petr-Economissa/gvidon,coinkeeper/2015-06-22_18-31_bitcoin,florincoin/florincoin,aspanta/bitcoin,joroob/reddcoin,AkioNak/bitcoin,jambolo/bitcoin,arnuschky/bitcoin,bitjson/hivemind,Theshadow4all/ShadowCoin,Bitcoin-ABC/bitcoin-abc,ravenbyron/phtevencoin,2XL/bitcoin,jmgilbert2/energi,lbrtcoin/albertcoin,andres-root/bitcoinxt,phelix/bitcoin,zcoinofficial/zcoin,ftrader-bitcoinabc/bitcoin-abc,irvingruan/bitcoin,basicincome/unpcoin-core,RongxinZhang/bitcoinxt,pinkevich/dash,monacoinproject/monacoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,Theshadow4all/ShadowCoin,basicincome/unpcoin-core,earonesty/bitcoin,bitcoinsSG/bitcoin,Rav3nPL/doubloons-0.10,mitchellcash/bitcoin,bittylicious/bitcoin,TBoehm/greedynode,digibyte/digibyte,Exceltior/dogecoin,CTRoundTable/Encrypted.Cash,thormuller/yescoin2,Krellan/bitcoin,kleetus/bitcoinxt,rustyrussell/bitcoin,dan-mi-sun/bitcoin,uphold/bitcoin,Lucky7Studio/bitcoin,mobicoins/mobicoin-core,mincoin-project/mincoin,zotherstupidguy/bitcoin,acid1789/bitcoin,experiencecoin/experiencecoin,npccoin/npccoin,gjhiggins/vcoincore,bitcoinsSG/bitcoin,domob1812/namecore,blocktrail/bitcoin,DMDcoin/Diamond,joulecoin/joulecoin,Kore-Core/kore,odemolliens/bitcoinxt,ZiftrCOIN/ziftrcoin,laudaa/bitcoin,SartoNess/BitcoinUnlimited,NateBrune/bitcoin-fio,xieta/mincoin,pouta/bitcoin,rebroad/bitcoin,zetacoin/zetacoin,chaincoin/chaincoin,neuroidss/bitcoin,kevcooper/bitcoin,Rav3nPL/PLNcoin,tecnovert/particl-core,PIVX-Project/PIVX,Chancoin-core/CHANCOIN,likecoin-dev/bitcoin,gravio-net/graviocoin,capitalDIGI/DIGI-v-0-10-4,AdrianaDinca/bitcoin,zcoinofficial/zcoin,zotherstupidguy/bitcoin,vlajos/bitcoin,coinkeeper/2015-06-22_19-00_ziftrcoin,Bitcoinsulting/bitcoinxt,ColossusCoinXT/ColossusCoinXT,sbaks0820/bitcoin,m0gliE/fastcoin-cli,fussl/elements,DGCDev/digitalcoin,projectinterzone/ITZ,syscoin/syscoin,genavarov/brcoin,itmanagerro/tresting,haobtc/bitcoin,uphold/bitcoin,DynamicCoinOrg/DMC,mycointest/owncoin,21E14/bitcoin,worldbit/worldbit,chaincoin/chaincoin,petertodd/bitcoin,ColossusCoinXT/ColossusCoinXT,litecoin-project/bitcoinomg,JeremyRubin/bitcoin,vertcoin/vertcoin,ShadowMyst/creativechain-core,shea256/bitcoin,PIVX-Project/PIVX,basicincome/unpcoin-core,n1bor/bitcoin,habibmasuro/bitcoin,joroob/reddcoin,kevcooper/bitcoin,uphold/bitcoin,ryanxcharles/bitcoin,bankonmecoin/bitcoin,nlgcoin/guldencoin-official,mikehearn/bitcoinxt,hsavit1/bitcoin,okinc/bitcoin,MazaCoin/mazacoin-new,supcoin/supcoin,kaostao/bitcoin,Rav3nPL/bitcoin,alecalve/bitcoin,xurantju/bitcoin,gjhiggins/vcoincore,pstratem/elements,laudaa/bitcoin,particl/particl-core,monacoinproject/monacoin,bankonmecoin/bitcoin,xawksow/GroestlCoin,upgradeadvice/MUE-Src,trippysalmon/bitcoin,stevemyers/bitcoinxt,bcpki/testblocks,slingcoin/sling-market,xurantju/bitcoin,sbaks0820/bitcoin,Kogser/bitcoin,nmarley/dash,DMDcoin/Diamond,AkioNak/bitcoin,psionin/smartcoin,xawksow/GroestlCoin,UdjinM6/dash,benma/bitcoin,LIMXTEC/DMDv3,MarcoFalke/bitcoin,DigiByte-Team/digibyte,untrustbank/litecoin,Har01d/bitcoin,cheehieu/bitcoin,prark/bitcoinxt,goldcoin/Goldcoin-GLD,fujicoin/fujicoin,dexX7/bitcoin,btc1/bitcoin,BlockchainTechLLC/3dcoin,peercoin/peercoin,Cocosoft/bitcoin,jmcorgan/bitcoin,bitreserve/bitcoin,pelorusjack/BlockDX,BTCDDev/bitcoin,octocoin-project/octocoin,destenson/bitcoin--bitcoin,steakknife/bitcoin-qt,iosdevzone/bitcoin,dan-mi-sun/bitcoin,dagurval/bitcoinxt,nightlydash/darkcoin,peercoin/peercoin,BitcoinPOW/BitcoinPOW,BTCfork/hardfork_prototype_1_mvf-core,donaloconnor/bitcoin,gwillen/elements,aniemerg/zcash,tjth/lotterycoin,biblepay/biblepay,DynamicCoinOrg/DMC,qtumproject/qtum,ahmedbodi/temp_vert,marklai9999/Taiwancoin,jl2012/litecoin,lbrtcoin/albertcoin,JeremyRand/namecore,brandonrobertz/namecoin-core,thesoftwarejedi/bitcoin,dashpay/dash,midnightmagic/bitcoin,Bitcoin-ABC/bitcoin-abc,dperel/bitcoin,GroestlCoin/bitcoin,romanornr/viacoin,BigBlueCeiling/augmentacoin,sarielsaz/sarielsaz,FeatherCoin/Feathercoin,truthcoin/blocksize-market,krzysztofwos/BitcoinUnlimited,hasanatkazmi/bitcoin,myriadteam/myriadcoin,bitcoin-hivemind/hivemind,sickpig/BitcoinUnlimited,xuyangcn/opalcoin,accraze/bitcoin,shouhuas/bitcoin,REAP720801/bitcoin,reorder/viacoin,zander/bitcoinclassic,blocktrail/bitcoin,BitzenyCoreDevelopers/bitzeny,ctwiz/stardust,maaku/bitcoin,BTCTaras/bitcoin,genavarov/ladacoin,jamesob/bitcoin,BTCfork/hardfork_prototype_1_mvf-core,CryptArc/bitcoinxt,zotherstupidguy/bitcoin,drwasho/bitcoinxt,greenaddress/bitcoin,nomnombtc/bitcoin,jeromewu/bitcoin-opennet,vlajos/bitcoin,DMDcoin/Diamond,Alonzo-Coeus/bitcoin,keo/bitcoin,josephbisch/namecoin-core,Alex-van-der-Peet/bitcoin,nsacoin/nsacoin,gapcoin/gapcoin,roques/bitcoin,cryptoprojects/ultimateonlinecash,Cloudsy/bitcoin,ajtowns/bitcoin,Friedbaumer/litecoin,zander/bitcoinclassic,dscotese/bitcoin,namecoin/namecoin-core,joshrabinowitz/bitcoin,Electronic-Gulden-Foundation/egulden,andreaskern/bitcoin,cryptodev35/icash,TeamBitBean/bitcoin-core,lakepay/lake,coinerd/krugercoin,segsignal/bitcoin,Kenwhite23/litecoin,kleetus/bitcoin,gavinandresen/bitcoin-git,masterbraz/dg,TripleSpeeder/bitcoin,sdaftuar/bitcoin,mitchellcash/bitcoin,oklink-dev/bitcoin_block,iosdevzone/bitcoin,cheehieu/bitcoin,mruddy/bitcoin,bitcoin-hivemind/hivemind,denverl/bitcoin,UdjinM6/dash,gmaxwell/bitcoin,nsacoin/nsacoin,MikeAmy/bitcoin,mincoin-project/mincoin,wtogami/bitcoin,zottejos/merelcoin,acid1789/bitcoin,litecoin-project/litecoin,zenywallet/bitzeny,mincoin-project/mincoin,stamhe/bitcoin,parvez3019/bitcoin,Exceltior/dogecoin,peercoin/peercoin,mm-s/bitcoin,mobicoins/mobicoin-core,mb300sd/bitcoin,coinwarp/dogecoin,grumpydevelop/singularity,MikeAmy/bitcoin,Har01d/bitcoin,afk11/bitcoin,myriadteam/myriadcoin,ryanofsky/bitcoin,tedlz123/Bitcoin,misdess/bitcoin,capitalDIGI/litecoin,n1bor/bitcoin,CTRoundTable/Encrypted.Cash,simonmulser/bitcoin,Horrorcoin/horrorcoin,magacoin/magacoin,unsystemizer/bitcoin,r8921039/bitcoin,Sjors/bitcoin,afk11/bitcoin,bitcoin/bitcoin,cculianu/bitcoin-abc,prark/bitcoinxt,mb300sd/bitcoin,KnCMiner/bitcoin,janko33bd/bitcoin,BTCfork/hardfork_prototype_1_mvf-core,dashpay/dash,bitcoinsSG/zcash,chaincoin/chaincoin,cotner/bitcoin,knolza/gamblr,JeremyRubin/bitcoin,thelazier/dash,domob1812/namecore,mm-s/bitcoin,simdeveloper/bitcoin,jlopp/statoshi,aspirecoin/aspire,11755033isaprimenumber/Feathercoin,ashleyholman/bitcoin,emc2foundation/einsteinium,Earlz/renamedcoin,zsulocal/bitcoin,kazcw/bitcoin,loxal/zcash,bitcoinplusorg/xbcwalletsource,fujicoin/fujicoin,mockcoin/mockcoin,grumpydevelop/singularity,Xekyo/bitcoin,MasterX1582/bitcoin-becoin,MasterX1582/bitcoin-becoin,Kcoin-project/kcoin,nbenoit/bitcoin,practicalswift/bitcoin,Jeff88Ho/bitcoin,ripper234/bitcoin,namecoin/namecore,argentumproject/argentum,domob1812/bitcoin,karek314/bitcoin,royosherove/bitcoinxt,ericshawlinux/bitcoin,blood2/bloodcoin-0.9,wiggi/huntercore,oleganza/bitcoin-duo,sdaftuar/bitcoin,haraldh/bitcoin,MazaCoin/maza,isocolsky/bitcoinxt,okinc/bitcoin,Kore-Core/kore,UASF/bitcoin,monacoinproject/monacoin,pstratem/elements,ArgonToken/ArgonToken,mapineda/litecoin,cryptoprojects/ultimateonlinecash,svost/bitcoin,Mirobit/bitcoin,segwit/atbcoin-insight,Anfauglith/iop-hd,afk11/bitcoin,rjshaver/bitcoin,freelion93/mtucicoin,robvanbentem/bitcoin,vertcoin/vertcoin,vertcoin/vertcoin,REAP720801/bitcoin,destenson/bitcoin--bitcoin,freelion93/mtucicoin,phelix/namecore,Mrs-X/PIVX,rustyrussell/bitcoin,haraldh/bitcoin,xawksow/GroestlCoin,nathan-at-least/zcash,Electronic-Gulden-Foundation/egulden,Cocosoft/bitcoin,Jcing95/iop-hd,ahmedbodi/temp_vert,psionin/smartcoin,djpnewton/bitcoin,111t8e/bitcoin,bitpay/bitcoin,NateBrune/bitcoin-nate,brandonrobertz/namecoin-core,koharjidan/dogecoin,GroestlCoin/bitcoin,arruah/ensocoin,bitcoinplusorg/xbcwalletsource,bitcoinec/bitcoinec,jn2840/bitcoin,nightlydash/darkcoin,roques/bitcoin,jonasschnelli/bitcoin,shelvenzhou/BTCGPU,rustyrussell/bitcoin,viacoin/viacoin,anditto/bitcoin,DGCDev/digitalcoin,Exgibichi/statusquo,gzuser01/zetacoin-bitcoin,dexX7/mastercore,BigBlueCeiling/augmentacoin,sipa/bitcoin,misdess/bitcoin,wangxinxi/litecoin,midnight-miner/LasVegasCoin,isghe/bitcoinxt,tjps/bitcoin,ahmedbodi/test2,Flowdalic/bitcoin,NicolasDorier/bitcoin,parvez3019/bitcoin,guncoin/guncoin,randy-waterhouse/bitcoin,ekankyesme/bitcoinxt,rawodb/bitcoin,simonmulser/bitcoin,sstone/bitcoin,likecoin-dev/bitcoin,kevcooper/bitcoin,Sjors/bitcoin,langerhans/dogecoin,wangliu/bitcoin,rawodb/bitcoin,mapineda/litecoin,DSPay/DSPay,phelix/bitcoin,genavarov/lamacoin,balajinandhu/bitcoin,meighti/bitcoin,Rav3nPL/polcoin,sbellem/bitcoin,constantine001/bitcoin,daveperkins-github/bitcoin-dev,MarcoFalke/bitcoin,koharjidan/dogecoin,core-bitcoin/bitcoin,coinkeeper/2015-06-22_18-36_darkcoin,matlongsi/micropay,terracoin/terracoin,ShwoognationHQ/bitcoin,benma/bitcoin,se3000/bitcoin,40thoughts/Coin-QualCoin,instagibbs/bitcoin,Chancoin-core/CHANCOIN,bcpki/nonce2testblocks,Kixunil/keynescoin,krzysztofwos/BitcoinUnlimited,Anoncoin/anoncoin,TBoehm/greedynode,MasterX1582/bitcoin-becoin,RibbitFROG/ribbitcoin,zcoinofficial/zcoin,Rav3nPL/PLNcoin,myriadteam/myriadcoin,arnuschky/bitcoin,XertroV/bitcoin-nulldata,FarhanHaque/bitcoin,initaldk/bitcoin,masterbraz/dg,marlengit/hardfork_prototype_1_mvf-bu,apoelstra/bitcoin,crowning2/dash,aciddude/Feathercoin,oleganza/bitcoin-duo,zenywallet/bitzeny,axelxod/braincoin,ashleyholman/bitcoin,Jeff88Ho/bitcoin,welshjf/bitcoin,langerhans/dogecoin,lateminer/bitcoin,antcheck/antcoin,NicolasDorier/bitcoin,viacoin/viacoin,greencoin-dev/digitalcoin,yenliangl/bitcoin,SartoNess/BitcoinUnlimited,sickpig/BitcoinUnlimited,tjth/lotterycoin,loxal/zcash,jonghyeopkim/bitcoinxt,zsulocal/bitcoin,isle2983/bitcoin,RazorLove/cloaked-octo-spice,gravio-net/graviocoin,aniemerg/zcash,FinalHashLLC/namecore,accraze/bitcoin,TGDiamond/Diamond,faircoin/faircoin2,wellenreiter01/Feathercoin,myriadcoin/myriadcoin,domob1812/i0coin,LIMXTEC/DMDv3,KibiCoin/kibicoin,DGCDev/digitalcoin,mruddy/bitcoin,basicincome/unpcoin-core,ElementsProject/elements,ediston/energi,TripleSpeeder/bitcoin,bcpki/nonce2,sugruedes/bitcoin,untrustbank/litecoin,janko33bd/bitcoin,GlobalBoost/GlobalBoost,111t8e/bitcoin,zcoinofficial/zcoin,elliotolds/bitcoin,BTCGPU/BTCGPU,dgenr8/bitcoinxt,qtumproject/qtum,pstratem/bitcoin,PRabahy/bitcoin,thelazier/dash,alecalve/bitcoin,Earlz/renamedcoin,qtumproject/qtum,SartoNess/BitcoinUnlimited,omefire/bitcoin,ripper234/bitcoin,ticclassic/ic,phplaboratory/psiacoin,rsdevgun16e/energi,karek314/bitcoin,CodeShark/bitcoin,habibmasuro/bitcoin,coinkeeper/2015-06-22_18-52_viacoin,reddcoin-project/reddcoin,imharrywu/fastcoin,diggcoin/diggcoin,thormuller/yescoin2,Bitcoin-com/BUcash,lbrtcoin/albertcoin,apoelstra/bitcoin,GreenParhelia/bitcoin,habibmasuro/bitcoinxt,cddjr/BitcoinUnlimited,randy-waterhouse/bitcoin,cyrixhero/bitcoin,npccoin/npccoin,sipa/elements,Exgibichi/statusquo,aniemerg/zcash,dashpay/dash,CTRoundTable/Encrypted.Cash,namecoin/namecore,tjth/lotterycoin,Jeff88Ho/bitcoin,jnewbery/bitcoin,bitpay/bitcoin,ardsu/bitcoin,oleganza/bitcoin-duo,btcdrak/bitcoin,simdeveloper/bitcoin,gravio-net/graviocoin,antcheck/antcoin,bespike/litecoin,djpnewton/bitcoin,coinkeeper/2015-06-22_19-07_digitalcoin,dogecoin/dogecoin,sipa/elements,gravio-net/graviocoin,RyanLucchese/energi,habibmasuro/bitcoinxt,matlongsi/micropay,dgarage/bc2,lbrtcoin/albertcoin,jonghyeopkim/bitcoinxt,nightlydash/darkcoin,antonio-fr/bitcoin,blocktrail/bitcoin,litecoin-project/litecore-litecoin,11755033isaprimenumber/Feathercoin,ftrader-bitcoinabc/bitcoin-abc,gavinandresen/bitcoin-git,mruddy/bitcoin,pinheadmz/bitcoin,joshrabinowitz/bitcoin,vertcoin/vertcoin,achow101/bitcoin,itmanagerro/tresting,reddink/reddcoin,jmcorgan/bitcoin,cdecker/bitcoin,Mrs-X/PIVX,BlockchainTechLLC/3dcoin,gazbert/bitcoin,nailtaras/nailcoin,RHavar/bitcoin,Ziftr/bitcoin,myriadcoin/myriadcoin,joroob/reddcoin,sipsorcery/bitcoin,EntropyFactory/creativechain-core,dev1972/Satellitecoin,wangliu/bitcoin,ahmedbodi/vertcoin,MeshCollider/bitcoin,rromanchuk/bitcoinxt,AdrianaDinca/bitcoin,Friedbaumer/litecoin,kfitzgerald/titcoin,cheehieu/bitcoin,roques/bitcoin,butterflypay/bitcoin,qtumproject/qtum,dexX7/bitcoin,error10/bitcoin,laudaa/bitcoin,nightlydash/darkcoin,cotner/bitcoin,tjps/bitcoin,Vector2000/bitcoin,ivansib/sib16,krzysztofwos/BitcoinUnlimited,REAP720801/bitcoin,pinkevich/dash,vericoin/vericoin-core,JeremyRand/namecore,jtimon/elements,StarbuckBG/BTCGPU,starwels/starwels,Michagogo/bitcoin,thormuller/yescoin2,Bitcoin-com/BUcash,GroundRod/anoncoin,EntropyFactory/creativechain-core,SartoNess/BitcoinUnlimited,dcousens/bitcoin,bickojima/bitzeny,marlengit/BitcoinUnlimited,mapineda/litecoin,odemolliens/bitcoinxt,ahmedbodi/test2,dgenr8/bitcoin,XertroV/bitcoin-nulldata,tropa/axecoin,faircoin/faircoin2,gavinandresen/bitcoin-git,bitcoinxt/bitcoinxt,Earlz/renamedcoin,sstone/bitcoin,ixcoinofficialpage/master,BlockchainTechLLC/3dcoin,namecoin/namecoin-core,jonasnick/bitcoin,experiencecoin/experiencecoin,steakknife/bitcoin-qt,jnewbery/bitcoin,rjshaver/bitcoin,willwray/dash,lclc/bitcoin,marlengit/hardfork_prototype_1_mvf-bu,jeromewu/bitcoin-opennet,unsystemizer/bitcoin,JeremyRand/namecore,gameunits/gameunits,CodeShark/bitcoin,oklink-dev/bitcoin,habibmasuro/bitcoinxt,ardsu/bitcoin,BitzenyCoreDevelopers/bitzeny,awemany/BitcoinUnlimited,btcdrak/bitcoin,tuaris/bitcoin,fsb4000/bitcoin,OmniLayer/omnicore,coinerd/krugercoin,jnewbery/bitcoin,lclc/bitcoin,digibyte/digibyte,ClusterCoin/ClusterCoin,nmarley/dash,schildbach/bitcoin,dperel/bitcoin,droark/bitcoin,KaSt/ekwicoin,andres-root/bitcoinxt,earonesty/bitcoin,DGCDev/argentum,torresalyssa/bitcoin,omefire/bitcoin,bitjson/hivemind,uphold/bitcoin,simonmulser/bitcoin,jamesob/bitcoin,gameunits/gameunits,ptschip/bitcoinxt,jrick/bitcoin,daveperkins-github/bitcoin-dev,funkshelper/woodcore,josephbisch/namecoin-core,TierNolan/bitcoin,dcousens/bitcoin,mrbandrews/bitcoin,reddink/reddcoin,nmarley/dash,Diapolo/bitcoin,dcousens/bitcoin,hophacker/bitcoin_malleability,marlengit/BitcoinUnlimited,haraldh/bitcoin,biblepay/biblepay,robvanbentem/bitcoin,koharjidan/bitcoin,jiangyonghang/bitcoin,OstlerDev/florincoin,ludbb/bitcoin,DSPay/DSPay,reddink/reddcoin,andreaskern/bitcoin,koharjidan/bitcoin,experiencecoin/experiencecoin,ryanxcharles/bitcoin,plncoin/PLNcoin_Core,shouhuas/bitcoin,goku1997/bitcoin,rnicoll/bitcoin,aspirecoin/aspire,GwangJin/gwangmoney-core,jaromil/faircoin2,48thct2jtnf/P,bitreserve/bitcoin,OstlerDev/florincoin,ColossusCoinXT/ColossusCoinXT,BitcoinUnlimited/BitcoinUnlimited,isocolsky/bitcoinxt,jambolo/bitcoin,cculianu/bitcoin-abc,knolza/gamblr,Bitcoin-ABC/bitcoin-abc,rebroad/bitcoin,axelxod/braincoin,earonesty/bitcoin,coinkeeper/2015-06-22_18-31_bitcoin,genavarov/ladacoin,Lucky7Studio/bitcoin,dpayne9000/Rubixz-Coin,shea256/bitcoin,dperel/bitcoin,irvingruan/bitcoin,markf78/dollarcoin,ajtowns/bitcoin,DogTagRecon/Still-Leraning,ahmedbodi/test2,shaulkf/bitcoin,okinc/bitcoin,n1bor/bitcoin,ludbb/bitcoin,ajtowns/bitcoin,ppcoin/ppcoin,goldcoin/goldcoin,litecoin-project/litecoin,mikehearn/bitcoinxt,slingcoin/sling-market,bankonmecoin/bitcoin,jn2840/bitcoin,BTCDDev/bitcoin,Bitcoin-ABC/bitcoin-abc,jamesob/bitcoin,wellenreiter01/Feathercoin,funkshelper/woodcore,zsulocal/bitcoin,ingresscoin/ingresscoin,bcpki/nonce2,Kogser/bitcoin,deadalnix/bitcoin,Chancoin-core/CHANCOIN,ctwiz/stardust,deeponion/deeponion,BTCfork/hardfork_prototype_1_mvf-bu,amaivsimau/bitcoin,bitcoinec/bitcoinec,coinkeeper/2015-06-22_18-39_feathercoin,capitalDIGI/litecoin,domob1812/namecore,goku1997/bitcoin,schinzelh/dash,kallewoof/bitcoin,UASF/bitcoin,lbryio/lbrycrd,PIVX-Project/PIVX,ftrader-bitcoinabc/bitcoin-abc,BlockchainTechLLC/3dcoin,tuaris/bitcoin,2XL/bitcoin,x-kalux/bitcoin_WiG-B,Petr-Economissa/gvidon,48thct2jtnf/P,cybermatatu/bitcoin,kleetus/bitcoinxt,constantine001/bitcoin,Theshadow4all/ShadowCoin,grumpydevelop/singularity,morcos/bitcoin,safecoin/safecoin,fullcoins/fullcoin,bcpki/testblocks,Kenwhite23/litecoin,Mrs-X/Darknet,jakeva/bitcoin-pwcheck,genavarov/ladacoin,BitcoinUnlimited/BitcoinUnlimited,PIVX-Project/PIVX,Kangmo/bitcoin,truthcoin/blocksize-market,shea256/bitcoin,bcpki/nonce2,shelvenzhou/BTCGPU,core-bitcoin/bitcoin,EthanHeilman/bitcoin,AllanDoensen/BitcoinUnlimited,dannyperez/bolivarcoin,truthcoin/blocksize-market,BitzenyCoreDevelopers/bitzeny,cqtenq/feathercoin_core,bitcoinplusorg/xbcwalletsource,oklink-dev/bitcoin,ClusterCoin/ClusterCoin,butterflypay/bitcoin,practicalswift/bitcoin,metacoin/florincoin,emc2foundation/einsteinium,BitcoinUnlimited/BitcoinUnlimited,scmorse/bitcoin,tedlz123/Bitcoin,nmarley/dash,GroestlCoin/GroestlCoin,dpayne9000/Rubixz-Coin,keo/bitcoin,theuni/bitcoin,GroestlCoin/GroestlCoin,Sjors/bitcoin,ptschip/bitcoin,capitalDIGI/DIGI-v-0-10-4,kallewoof/elements,marlengit/BitcoinUnlimited,gjhiggins/vcoincore,jimmysong/bitcoin,stevemyers/bitcoinxt,sugruedes/bitcoin,bdelzell/creditcoin-org-creditcoin,KnCMiner/bitcoin,ludbb/bitcoin,ingresscoin/ingresscoin,MarcoFalke/bitcoin,ahmedbodi/terracoin,pinheadmz/bitcoin,Cloudsy/bitcoin,torresalyssa/bitcoin,BitcoinHardfork/bitcoin,oklink-dev/bitcoin,kallewoof/bitcoin,kleetus/bitcoin,tjth/lotterycoin,gzuser01/zetacoin-bitcoin,litecoin-project/litecoin,rebroad/bitcoin,ShadowMyst/creativechain-core,GlobalBoost/GlobalBoost,shelvenzhou/BTCGPU,BTCTaras/bitcoin,error10/bitcoin,Anfauglith/iop-hd,lbryio/lbrycrd,fussl/elements,reddcoin-project/reddcoin,pinkevich/dash,dgenr8/bitcoinxt,sugruedes/bitcoin,lateminer/bitcoin,Horrorcoin/horrorcoin,practicalswift/bitcoin,svost/bitcoin,matlongsi/micropay,schildbach/bitcoin,Bloom-Project/Bloom,bickojima/bitzeny,denverl/bitcoin,MarcoFalke/bitcoin,wellenreiter01/Feathercoin,ftrader-bitcoinabc/bitcoin-abc,dgarage/bc3,cculianu/bitcoin-abc,psionin/smartcoin,Bitcoinsulting/bitcoinxt,andreaskern/bitcoin,ZiftrCOIN/ziftrcoin,Horrorcoin/horrorcoin,ahmedbodi/terracoin,theuni/bitcoin,vmp32k/litecoin,stevemyers/bitcoinxt,haisee/dogecoin,bitcoin/bitcoin,brishtiteveja/truthcoin-cpp,terracoin/terracoin,joulecoin/joulecoin,destenson/bitcoin--bitcoin,nsacoin/nsacoin,genavarov/lamacoin,brishtiteveja/truthcoin-cpp,ElementsProject/elements,sugruedes/bitcoinxt,jimmykiselak/lbrycrd,gmaxwell/bitcoin,kirkalx/bitcoin,royosherove/bitcoinxt,sbellem/bitcoin,GIJensen/bitcoin,cybermatatu/bitcoin,aspanta/bitcoin,ArgonToken/ArgonToken,jiangyonghang/bitcoin,sipa/bitcoin,MasterX1582/bitcoin-becoin,jonasnick/bitcoin,bdelzell/creditcoin-org-creditcoin,ajtowns/bitcoin,wederw/bitcoin,MeshCollider/bitcoin,ftrader-bitcoinabc/bitcoin-abc,jlopp/statoshi,dgenr8/bitcoinxt,domob1812/bitcoin,bitcoinxt/bitcoinxt,antonio-fr/bitcoin,bitcoinxt/bitcoinxt,litecoin-project/litecore-litecoin,bickojima/bitzeny,coinkeeper/2015-06-22_18-37_dogecoin,21E14/bitcoin,gavinandresen/bitcoin-git,blood2/bloodcoin-0.9,starwels/starwels,projectinterzone/ITZ,mrbandrews/bitcoin,magacoin/magacoin,dev1972/Satellitecoin,MikeAmy/bitcoin,DMDcoin/Diamond,gwillen/elements,dev1972/Satellitecoin,welshjf/bitcoin,scmorse/bitcoin,balajinandhu/bitcoin,janko33bd/bitcoin,lateminer/bitcoin,RyanLucchese/energi,slingcoin/sling-market,coinkeeper/2015-06-22_19-07_digitalcoin,particl/particl-core,UFOCoins/ufo,thrasher-/litecoin,MazaCoin/maza,steakknife/bitcoin-qt,supcoin/supcoin,tecnovert/particl-core,Horrorcoin/horrorcoin,goldcoin/goldcoin,MikeAmy/bitcoin,projectinterzone/ITZ,morcos/bitcoin,faircoin/faircoin2,ekankyesme/bitcoinxt,svost/bitcoin,PRabahy/bitcoin,nightlydash/darkcoin,ZiftrCOIN/ziftrcoin,mycointest/owncoin,gjhiggins/vcoincore,sugruedes/bitcoinxt,Cloudsy/bitcoin,Lucky7Studio/bitcoin,jtimon/elements,wcwu/bitcoin,BTCfork/hardfork_prototype_1_mvf-bu,bmp02050/ReddcoinUpdates,iQcoin/iQcoin,kevcooper/bitcoin,zotherstupidguy/bitcoin,welshjf/bitcoin,inkvisit/sarmacoins,sebrandon1/bitcoin,domob1812/bitcoin,biblepay/biblepay,cryptodev35/icash,zetacoin/zetacoin,goldcoin/Goldcoin-GLD,pataquets/namecoin-core,thesoftwarejedi/bitcoin,ahmedbodi/temp_vert,sirk390/bitcoin,jonghyeopkim/bitcoinxt,coinkeeper/2015-06-22_18-52_viacoin,ajweiss/bitcoin,laudaa/bitcoin,fedoracoin-dev/fedoracoin,midnight-miner/LasVegasCoin,paveljanik/bitcoin,sebrandon1/bitcoin,wcwu/bitcoin,gavinandresen/bitcoin-git,keo/bitcoin,riecoin/riecoin,npccoin/npccoin,pouta/bitcoin,irvingruan/bitcoin,untrustbank/litecoin,pataquets/namecoin-core,spiritlinxl/BTCGPU,ravenbyron/phtevencoin,JeremyRubin/bitcoin,rnicoll/dogecoin,iQcoin/iQcoin,RibbitFROG/ribbitcoin,cannabiscoindev/cannabiscoin420,ticclassic/ic,mruddy/bitcoin,putinclassic/putic,adpg211/bitcoin-master,llluiop/bitcoin,arnuschky/bitcoin,coinkeeper/2015-06-22_19-07_digitalcoin,czr5014iph/bitcoin4e,midnight-miner/LasVegasCoin,bitjson/hivemind,meighti/bitcoin,r8921039/bitcoin,keesdewit82/LasVegasCoin,jambolo/bitcoin,bitcoinsSG/zcash,brandonrobertz/namecoin-core,domob1812/bitcoin,GlobalBoost/GlobalBoost,fanquake/bitcoin,brandonrobertz/namecoin-core,Jeff88Ho/bitcoin,credits-currency/credits,MonetaryUnit/MUE-Src,gandrewstone/BitcoinUnlimited,multicoins/marycoin,gandrewstone/bitcoinxt,cryptodev35/icash,senadmd/coinmarketwatch,TeamBitBean/bitcoin-core,supcoin/supcoin,safecoin/safecoin,mikehearn/bitcoin,drwasho/bitcoinxt,Rav3nPL/polcoin,Bloom-Project/Bloom,imton/bitcoin,llluiop/bitcoin,greenaddress/bitcoin,Alex-van-der-Peet/bitcoin,willwray/dash,likecoin-dev/bitcoin,lbrtcoin/albertcoin,bitcoinec/bitcoinec,aburan28/elements,pascalguru/florincoin,reddcoin-project/reddcoin,hsavit1/bitcoin,UdjinM6/dash,zenywallet/bitzeny,Har01d/bitcoin,syscoin/syscoin,GIJensen/bitcoin,bitcoin-hivemind/hivemind,imton/bitcoin,deuscoin/deuscoin,presstab/PIVX,emc2foundation/einsteinium,denverl/bitcoin,dagurval/bitcoinxt,ElementsProject/elements,jrick/bitcoin,welshjf/bitcoin,coinkeeper/2015-06-22_18-39_feathercoin,111t8e/bitcoin,cyrixhero/bitcoin,pascalguru/florincoin,sipa/bitcoin,gandrewstone/bitcoinxt,leofidus/glowing-octo-ironman,goldcoin/goldcoin,2XL/bitcoin,magacoin/magacoin,dscotese/bitcoin,TripleSpeeder/bitcoin,daveperkins-github/bitcoin-dev,goldcoin/goldcoin,shouhuas/bitcoin,KnCMiner/bitcoin,ppcoin/ppcoin,koharjidan/litecoin,my-first/octocoin,benzmuircroft/REWIRE.io,2XL/bitcoin,ptschip/bitcoin,brishtiteveja/truthcoin-cpp,jeromewu/bitcoin-opennet,BitzenyCoreDevelopers/bitzeny,ElementsProject/elements,botland/bitcoin,wbchen99/bitcoin-hnote0,benma/bitcoin,elliotolds/bitcoin,jonasnick/bitcoin,prark/bitcoinxt,droark/bitcoin,loxal/zcash,cotner/bitcoin,bickojima/bitzeny,tjth/lotterycoin,dperel/bitcoin,shelvenzhou/BTCGPU,tdudz/elements,bitjson/hivemind,nbenoit/bitcoin,GIJensen/bitcoin,deeponion/deeponion,xuyangcn/opalcoin,sugruedes/bitcoinxt,fanquake/bitcoin,gapcoin/gapcoin,haraldh/bitcoin,ColossusCoinXT/ColossusCoinXT,Electronic-Gulden-Foundation/egulden,svost/bitcoin,jonghyeopkim/bitcoinxt,martindale/elements,andres-root/bitcoinxt,kallewoof/elements,coinkeeper/2015-06-22_19-00_ziftrcoin,wellenreiter01/Feathercoin,psionin/smartcoin,simdeveloper/bitcoin,scmorse/bitcoin,Kenwhite23/litecoin,domob1812/namecore,likecoin-dev/bitcoin,ajweiss/bitcoin,Kixunil/keynescoin,gjhiggins/vcoincore,mb300sd/bitcoin,ivansib/sib16,litecoin-project/bitcoinomg,fanquake/bitcoin,RibbitFROG/ribbitcoin,s-matthew-english/bitcoin,pstratem/bitcoin,tdudz/elements,freelion93/mtucicoin,ClusterCoin/ClusterCoin,adpg211/bitcoin-master,jimmysong/bitcoin,lakepay/lake,arruah/ensocoin,pinkevich/dash,misdess/bitcoin,AllanDoensen/BitcoinUnlimited,Electronic-Gulden-Foundation/egulden,prusnak/bitcoin,cyrixhero/bitcoin,kleetus/bitcoin,bespike/litecoin,unsystemizer/bitcoin,marcusdiaz/BitcoinUnlimited,qtumproject/qtum,plncoin/PLNcoin_Core,schinzelh/dash,wtogami/bitcoin,karek314/bitcoin,coinkeeper/2015-06-22_19-00_ziftrcoin,rromanchuk/bitcoinxt,Bitcoinsulting/bitcoinxt,Kenwhite23/litecoin,sarielsaz/sarielsaz,reorder/viacoin,benosa/bitcoin,daliwangi/bitcoin,vcoin-project/vcoincore,JeremyRand/namecoin-core,bitcoin-hivemind/hivemind,adpg211/bitcoin-master,xurantju/bitcoin,shouhuas/bitcoin,x-kalux/bitcoin_WiG-B,1185/starwels,BitcoinHardfork/bitcoin,hyperwang/bitcoin,tropa/axecoin,marklai9999/Taiwancoin,goldcoin/Goldcoin-GLD,djpnewton/bitcoin,neuroidss/bitcoin,braydonf/bitcoin,laudaa/bitcoin,Kogser/bitcoin,genavarov/lamacoin,dgarage/bc2,DGCDev/digitalcoin,dannyperez/bolivarcoin,mobicoins/mobicoin-core,mrbandrews/bitcoin,dpayne9000/Rubixz-Coin,FeatherCoin/Feathercoin,tdudz/elements,funbucks/notbitcoinxt,spiritlinxl/BTCGPU,bittylicious/bitcoin,mikehearn/bitcoinxt,MeshCollider/bitcoin,cerebrus29301/crowncoin,BTCDDev/bitcoin,TheBlueMatt/bitcoin,DynamicCoinOrg/DMC,metacoin/florincoin,keesdewit82/LasVegasCoin,aniemerg/zcash,globaltoken/globaltoken,simonmulser/bitcoin,llluiop/bitcoin,nathan-at-least/zcash,denverl/bitcoin,jrick/bitcoin,coinkeeper/2015-06-22_18-52_viacoin,pstratem/bitcoin,Vector2000/bitcoin,thormuller/yescoin2,Theshadow4all/ShadowCoin,BTCGPU/BTCGPU,kfitzgerald/titcoin,ludbb/bitcoin,randy-waterhouse/bitcoin,fedoracoin-dev/fedoracoin,theuni/bitcoin,unsystemizer/bitcoin,pinheadmz/bitcoin,OmniLayer/omnicore,btc1/bitcoin,putinclassic/putic,pstratem/bitcoin,sipsorcery/bitcoin,atgreen/bitcoin,sarielsaz/sarielsaz,dexX7/bitcoin,wederw/bitcoin,karek314/bitcoin,Bitcoin-com/BUcash,BitcoinHardfork/bitcoin,blood2/bloodcoin-0.9,rjshaver/bitcoin,andreaskern/bitcoin,coinkeeper/2015-06-22_19-07_digitalcoin,zixan/bitcoin,Flowdalic/bitcoin,schildbach/bitcoin,mincoin-project/mincoin,Bushstar/UFO-Project,gwillen/elements,crowning-/dash,tedlz123/Bitcoin,segwit/atbcoin-insight,particl/particl-core,capitalDIGI/DIGI-v-0-10-4,DigitalPandacoin/pandacoin,jmgilbert2/energi,phelix/bitcoin,coinkeeper/2015-06-22_18-37_dogecoin,jrick/bitcoin,Har01d/bitcoin,tropa/axecoin,kaostao/bitcoin,elecoin/elecoin,guncoin/guncoin,mrbandrews/bitcoin,goldcoin/goldcoin,cannabiscoindev/cannabiscoin420,domob1812/huntercore,m0gliE/fastcoin-cli,SartoNess/BitcoinUnlimited,funkshelper/woodcoin-b,ptschip/bitcoinxt,bickojima/bitzeny,n1bor/bitcoin,jaromil/faircoin2,Earlz/renamedcoin,bitcoinxt/bitcoinxt,bitcoinknots/bitcoin,crowning-/dash,Jcing95/iop-hd,xurantju/bitcoin,coinkeeper/2015-06-22_18-39_feathercoin,DigiByte-Team/digibyte,jtimon/bitcoin,marlengit/BitcoinUnlimited,ahmedbodi/test2,drwasho/bitcoinxt,PIVX-Project/PIVX,syscoin/syscoin2,funkshelper/woodcoin-b,aspirecoin/aspire,Anoncoin/anoncoin,GIJensen/bitcoin,metacoin/florincoin,alejandromgk/Lunar,goku1997/bitcoin,Rav3nPL/bitcoin,nikkitan/bitcoin,BitcoinUnlimited/BitcoinUnlimited,faircoin/faircoin,practicalswift/bitcoin,lateminer/bitcoin,mitchellcash/bitcoin,keo/bitcoin,xieta/mincoin,se3000/bitcoin,mincoin-project/mincoin,GroestlCoin/GroestlCoin,Rav3nPL/PLNcoin,bitbrazilcoin-project/bitbrazilcoin,goldcoin/goldcoin,haisee/dogecoin,NicolasDorier/bitcoin,inkvisit/sarmacoins,BTCTaras/bitcoin,prark/bitcoinxt,lbryio/lbrycrd,dperel/bitcoin,Petr-Economissa/gvidon,s-matthew-english/bitcoin,bittylicious/bitcoin,coinkeeper/2015-06-22_18-36_darkcoin,elecoin/elecoin,droark/elements,jl2012/litecoin,CTRoundTable/Encrypted.Cash,inkvisit/sarmacoins,DigitalPandacoin/pandacoin,isocolsky/bitcoinxt,ShadowMyst/creativechain-core,RHavar/bitcoin,alejandromgk/Lunar,Bitcoin-com/BUcash,peercoin/peercoin,Bushstar/UFO-Project,ArgonToken/ArgonToken,cmgustavo/bitcoin,ShwoognationHQ/bitcoin,MonetaryUnit/MUE-Src,zetacoin/zetacoin,domob1812/huntercore,jn2840/bitcoin,butterflypay/bitcoin,jtimon/bitcoin,KibiCoin/kibicoin,syscoin/syscoin,48thct2jtnf/P,koharjidan/litecoin,myriadcoin/myriadcoin,iosdevzone/bitcoin,zcoinofficial/zcoin,schinzelh/dash,coinkeeper/2015-06-22_18-37_dogecoin,nomnombtc/bitcoin,oklink-dev/bitcoin_block,cculianu/bitcoin-abc,benosa/bitcoin,zottejos/merelcoin,starwels/starwels,mastercoin-MSC/mastercore,nomnombtc/bitcoin,FarhanHaque/bitcoin,Ziftr/bitcoin,KaSt/ekwicoin,zetacoin/zetacoin,DynamicCoinOrg/DMC,cheehieu/bitcoin,s-matthew-english/bitcoin,pastday/bitcoinproject,Kogser/bitcoin,Thracky/monkeycoin,arruah/ensocoin,ahmedbodi/temp_vert,BitcoinPOW/BitcoinPOW,martindale/elements,ticclassic/ic,AkioNak/bitcoin,faircoin/faircoin2,2XL/bitcoin,BitcoinUnlimited/BitcoinUnlimited,keesdewit82/LasVegasCoin,kallewoof/bitcoin,OstlerDev/florincoin,biblepay/biblepay,segwit/atbcoin-insight,BTCfork/hardfork_prototype_1_mvf-bu,rromanchuk/bitcoinxt,hophacker/bitcoin_malleability,Kcoin-project/kcoin,ahmedbodi/terracoin,tmagik/catcoin,Earlz/renamedcoin,ixcoinofficialpage/master,rsdevgun16e/energi,syscoin/syscoin,ericshawlinux/bitcoin,prusnak/bitcoin,funbucks/notbitcoinxt,pouta/bitcoin,Lucky7Studio/bitcoin,Electronic-Gulden-Foundation/egulden,worldbit/worldbit,starwels/starwels,funbucks/notbitcoinxt,Bitcoin-ABC/bitcoin-abc,instagibbs/bitcoin,superjudge/bitcoin,anditto/bitcoin,krzysztofwos/BitcoinUnlimited,TripleSpeeder/bitcoin,rdqw/sscoin,vcoin-project/vcoincore,omefire/bitcoin,CoinProjects/AmsterdamCoin-v4,aburan28/elements,UASF/bitcoin,Theshadow4all/ShadowCoin,DynamicCoinOrg/DMC,imharrywu/fastcoin,vtafaucet/virtacoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,keesdewit82/LasVegasCoin,shomeser/bitcoin,jrick/bitcoin,RazorLove/cloaked-octo-spice,czr5014iph/bitcoin4e,matlongsi/micropay,dev1972/Satellitecoin,jlopp/statoshi,bitbrazilcoin-project/bitbrazilcoin,Justaphf/BitcoinUnlimited,wcwu/bitcoin,bdelzell/creditcoin-org-creditcoin,dgarage/bc2,dmrtsvetkov/flowercoin,GroestlCoin/bitcoin,hyperwang/bitcoin,rromanchuk/bitcoinxt,ptschip/bitcoinxt,zixan/bitcoin,Petr-Economissa/gvidon,paveljanik/bitcoin,tuaris/bitcoin,jaromil/faircoin2,core-bitcoin/bitcoin,coinkeeper/2015-06-22_18-39_feathercoin,jeromewu/bitcoin-opennet,inkvisit/sarmacoins,hsavit1/bitcoin,coinkeeper/2015-06-22_19-00_ziftrcoin,tmagik/catcoin,ludbb/bitcoin,PandaPayProject/PandaPay,nvmd/bitcoin,sbellem/bitcoin,fanquake/bitcoin,jimmykiselak/lbrycrd,Tetpay/bitcoin,r8921039/bitcoin,prusnak/bitcoin,josephbisch/namecoin-core,markf78/dollarcoin,iosdevzone/bitcoin,rat4/bitcoin,irvingruan/bitcoin,oklink-dev/bitcoin_block,jrmithdobbs/bitcoin,mikehearn/bitcoinxt,dan-mi-sun/bitcoin,ivansib/sibcoin,Thracky/monkeycoin,genavarov/brcoin,pascalguru/florincoin,PandaPayProject/PandaPay,schinzelh/dash,adpg211/bitcoin-master,FeatherCoin/Feathercoin,vmp32k/litecoin,cryptoprojects/ultimateonlinecash,apoelstra/elements,DogTagRecon/Still-Leraning,Krellan/bitcoin,experiencecoin/experiencecoin,dogecoin/dogecoin,CTRoundTable/Encrypted.Cash,reddcoin-project/reddcoin,coinkeeper/2015-06-22_19-00_ziftrcoin,Rav3nPL/doubloons-0.10,ptschip/bitcoin,111t8e/bitcoin,isle2983/bitcoin,rsdevgun16e/energi,Electronic-Gulden-Foundation/egulden,thelazier/dash,nikkitan/bitcoin,blood2/bloodcoin-0.9,Krellan/bitcoin,jimmysong/bitcoin,fsb4000/bitcoin,dexX7/bitcoin,royosherove/bitcoinxt,droark/bitcoin,PIVX-Project/PIVX,prusnak/bitcoin,martindale/elements,AllanDoensen/BitcoinUnlimited,joulecoin/joulecoin,rebroad/bitcoin,CryptArc/bitcoinxt,jakeva/bitcoin-pwcheck,ravenbyron/phtevencoin,neuroidss/bitcoin,funkshelper/woodcore,error10/bitcoin,phplaboratory/psiacoin,nathaniel-mahieu/bitcoin,zixan/bitcoin,ftrader-bitcoinabc/bitcoin-abc,ekankyesme/bitcoinxt,BTCDDev/bitcoin,benzmuircroft/REWIRE.io,ZiftrCOIN/ziftrcoin,afk11/bitcoin,coinerd/krugercoin,axelxod/braincoin,world-bank/unpay-core,Tetpay/bitcoin,cdecker/bitcoin,biblepay/biblepay,vericoin/vericoin-core,sirk390/bitcoin,instagibbs/bitcoin,arruah/ensocoin,spiritlinxl/BTCGPU,romanornr/viacoin,tuaris/bitcoin,antcheck/antcoin,ediston/energi,bitreserve/bitcoin,worldbit/worldbit,loxal/zcash,x-kalux/bitcoin_WiG-B,dannyperez/bolivarcoin,vmp32k/litecoin,jmgilbert2/energi,jnewbery/bitcoin,domob1812/namecore,uphold/bitcoin,ryanofsky/bitcoin,genavarov/lamacoin,ClusterCoin/ClusterCoin,thesoftwarejedi/bitcoin,gwillen/elements,ediston/energi,174high/bitcoin,syscoin/syscoin2,wbchen99/bitcoin-hnote0,btcdrak/bitcoin,riecoin/riecoin,BTCDDev/bitcoin,jl2012/litecoin,mm-s/bitcoin,braydonf/bitcoin,schinzelh/dash,RibbitFROG/ribbitcoin,pinkevich/dash,Friedbaumer/litecoin,h4x3rotab/BTCGPU,crowning2/dash,domob1812/bitcoin,se3000/bitcoin,marlengit/hardfork_prototype_1_mvf-bu,FarhanHaque/bitcoin,freelion93/mtucicoin,KibiCoin/kibicoin,initaldk/bitcoin,safecoin/safecoin,appop/bitcoin,domob1812/namecore,CryptArc/bitcoinxt,jaromil/faircoin2,balajinandhu/bitcoin,lbrtcoin/albertcoin,achow101/bitcoin,DigiByte-Team/digibyte,nbenoit/bitcoin,bmp02050/ReddcoinUpdates,appop/bitcoin,plncoin/PLNcoin_Core,BitcoinUnlimited/BitcoinUnlimited,romanornr/viacoin,shea256/bitcoin,HashUnlimited/Einsteinium-Unlimited,Bushstar/UFO-Project,blocktrail/bitcoin,TBoehm/greedynode,truthcoin/blocksize-market,dannyperez/bolivarcoin,haisee/dogecoin,h4x3rotab/BTCGPU,TGDiamond/Diamond,ionomy/ion,mikehearn/bitcoin,Vsync-project/Vsync,hophacker/bitcoin_malleability,Theshadow4all/ShadowCoin,Vsync-project/Vsync,Exgibichi/statusquo,kazcw/bitcoin,argentumproject/argentum,ravenbyron/phtevencoin,kallewoof/bitcoin,Rav3nPL/bitcoin,jarymoth/dogecoin,pstratem/elements,willwray/dash,pataquets/namecoin-core,joroob/reddcoin,lclc/bitcoin,globaltoken/globaltoken,koharjidan/bitcoin,x-kalux/bitcoin_WiG-B,Kogser/bitcoin,midnight-miner/LasVegasCoin,2XL/bitcoin,pelorusjack/BlockDX,BTCTaras/bitcoin,Xekyo/bitcoin,Mirobit/bitcoin,grumpydevelop/singularity,Rav3nPL/doubloons-0.10,RongxinZhang/bitcoinxt,DigitalPandacoin/pandacoin,DSPay/DSPay,world-bank/unpay-core,isghe/bitcoinxt,NunoEdgarGub1/elements,NunoEdgarGub1/elements,nvmd/bitcoin,benosa/bitcoin,tropa/axecoin,viacoin/viacoin,joshrabinowitz/bitcoin,SoreGums/bitcoinxt,dashpay/dash,markf78/dollarcoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,mockcoin/mockcoin,haisee/dogecoin,ArgonToken/ArgonToken,midnightmagic/bitcoin,nathaniel-mahieu/bitcoin,Kangmo/bitcoin,zander/bitcoinclassic,Mirobit/bitcoin,pouta/bitcoin,sstone/bitcoin,lbryio/lbrycrd,PRabahy/bitcoin,jarymoth/dogecoin,GlobalBoost/GlobalBoost,krzysztofwos/BitcoinUnlimited,r8921039/bitcoin,dgarage/bc2,riecoin/riecoin,mikehearn/bitcoinxt,monacoinproject/monacoin,terracoin/terracoin,jtimon/bitcoin,EntropyFactory/creativechain-core
|
dc685f2061c1436aed598184934b532d205a56a2
|
common/timing.cc
|
common/timing.cc
|
/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2018 David Shah <[email protected]>
*
* 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.
*
*/
#include "timing.h"
#include <algorithm>
#include <unordered_map>
#include <utility>
#include "log.h"
#include "util.h"
NEXTPNR_NAMESPACE_BEGIN
typedef std::vector<const PortRef *> PortRefVector;
typedef std::map<int, unsigned> DelayFrequency;
struct Timing
{
Context *ctx;
bool update;
delay_t min_slack;
PortRefVector current_path;
PortRefVector *crit_path;
DelayFrequency *slack_histogram;
Timing(Context *ctx, bool update, PortRefVector *crit_path = nullptr, DelayFrequency *slack_histogram = nullptr)
: ctx(ctx), update(update), min_slack(1.0e12 / ctx->target_freq), crit_path(crit_path),
slack_histogram(slack_histogram)
{
}
delay_t follow_net(NetInfo *net, int path_length, delay_t slack)
{
delay_t net_budget = slack / (path_length + 1);
for (auto &usr : net->users) {
if (crit_path)
current_path.push_back(&usr);
// If budget override is less than existing budget, then do not increment
// path length
int pl = path_length + 1;
auto budget = ctx->getBudgetOverride(net, usr, net_budget);
if (budget < net_budget) {
net_budget = budget;
pl = std::max(1, path_length);
}
auto delay = ctx->getNetinfoRouteDelay(net, usr);
net_budget = std::min(net_budget, follow_user_port(usr, pl, slack - delay));
if (update)
usr.budget = std::min(usr.budget, delay + net_budget);
if (crit_path)
current_path.pop_back();
}
return net_budget;
}
// Follow a path, returning budget to annotate
delay_t follow_user_port(PortRef &user, int path_length, delay_t slack)
{
delay_t value;
if (ctx->getPortClock(user.cell, user.port) != IdString()) {
// At the end of a timing path (arguably, should check setup time
// here too)
value = slack / path_length;
if (slack < min_slack) {
min_slack = slack;
if (crit_path)
*crit_path = current_path;
}
if (slack_histogram) {
int slack_ps = ctx->getDelayNS(slack) * 1000;
(*slack_histogram)[slack_ps]++;
}
} else {
// Default to the path ending here, if no further paths found
value = slack / path_length;
// Follow outputs of the user
for (auto port : user.cell->ports) {
if (port.second.type == PORT_OUT) {
DelayInfo comb_delay;
// Look up delay through this path
bool is_path = ctx->getCellDelay(user.cell, user.port, port.first, comb_delay);
if (is_path) {
NetInfo *net = port.second.net;
if (net) {
delay_t path_budget = follow_net(net, path_length, slack - comb_delay.maxDelay());
value = std::min(value, path_budget);
}
}
}
}
}
return value;
}
delay_t walk_paths()
{
delay_t default_slack = delay_t(1.0e12 / ctx->target_freq);
// Go through all clocked drivers and distribute the available path
// slack evenly into the budget of every sink on the path
for (auto &cell : ctx->cells) {
for (auto port : cell.second->ports) {
if (port.second.type == PORT_OUT) {
IdString clock_domain = ctx->getPortClock(cell.second.get(), port.first);
if (clock_domain != IdString()) {
delay_t slack = default_slack; // TODO: clock constraints
DelayInfo clkToQ;
if (ctx->getCellDelay(cell.second.get(), clock_domain, port.first, clkToQ))
slack -= clkToQ.maxDelay();
if (port.second.net)
follow_net(port.second.net, 0, slack);
}
}
}
}
return min_slack;
}
void assign_budget()
{
// Clear delays to a very high value first
delay_t default_slack = delay_t(1.0e12 / ctx->target_freq);
for (auto &net : ctx->nets) {
for (auto &usr : net.second->users) {
usr.budget = default_slack;
}
}
walk_paths();
}
};
void assign_budget(Context *ctx, bool quiet)
{
if (!quiet) {
log_break();
log_info("Annotating ports with timing budgets for target frequency %.2f MHz\n", ctx->target_freq/1e6);
}
Timing timing(ctx, true /* update */);
timing.assign_budget();
if (!quiet || ctx->verbose) {
for (auto &net : ctx->nets) {
for (auto &user : net.second->users) {
// Post-update check
if (!ctx->auto_freq && user.budget < 0)
log_warning("port %s.%s, connected to net '%s', has negative "
"timing budget of %fns\n",
user.cell->name.c_str(ctx), user.port.c_str(ctx), net.first.c_str(ctx),
ctx->getDelayNS(user.budget));
else if (ctx->verbose)
log_info("port %s.%s, connected to net '%s', has "
"timing budget of %fns\n",
user.cell->name.c_str(ctx), user.port.c_str(ctx), net.first.c_str(ctx),
ctx->getDelayNS(user.budget));
}
}
}
// For slack redistribution, if user has not specified a frequency
// dynamically adjust the target frequency to be the currently
// achieved maximum
if (ctx->auto_freq && ctx->slack_redist_iter > 0) {
delay_t default_slack = delay_t(1.0e12 / ctx->target_freq);
ctx->target_freq = 1e12 / (default_slack - timing.min_slack);
if (ctx->verbose)
log_info("minimum slack for this assign = %d, target Fmax for next "
"update = %.2f MHz\n",
timing.min_slack, ctx->target_freq / 1e6);
}
if (!quiet)
log_info("Checksum: 0x%08x\n", ctx->checksum());
}
void timing_analysis(Context *ctx, bool print_histogram, bool print_path)
{
PortRefVector crit_path;
DelayFrequency slack_histogram;
Timing timing(ctx, false /* update */, print_path ? &crit_path : nullptr,
print_histogram ? &slack_histogram : nullptr);
auto min_slack = timing.walk_paths();
if (print_path) {
if (crit_path.empty()) {
log_info("Design contains no timing paths\n");
} else {
delay_t total = 0;
log_break();
log_info("Critical path report:\n");
log_info("curr total\n");
auto &front = crit_path.front();
auto &front_port = front->cell->ports.at(front->port);
auto &front_driver = front_port.net->driver;
auto last_port = ctx->getPortClock(front_driver.cell, front_driver.port);
for (auto sink : crit_path) {
auto sink_cell = sink->cell;
auto &port = sink_cell->ports.at(sink->port);
auto net = port.net;
auto &driver = net->driver;
auto driver_cell = driver.cell;
DelayInfo comb_delay;
ctx->getCellDelay(sink_cell, last_port, driver.port, comb_delay);
total += comb_delay.maxDelay();
log_info("%4d %4d Source %s.%s\n", comb_delay.maxDelay(), total, driver_cell->name.c_str(ctx),
driver.port.c_str(ctx));
auto net_delay = ctx->getNetinfoRouteDelay(net, *sink);
total += net_delay;
auto driver_loc = ctx->getBelLocation(driver_cell->bel);
auto sink_loc = ctx->getBelLocation(sink_cell->bel);
log_info("%4d %4d Net %s budget %d (%d,%d) -> (%d,%d)\n", net_delay, total, net->name.c_str(ctx),
sink->budget, driver_loc.x, driver_loc.y, sink_loc.x, sink_loc.y);
log_info(" Sink %s.%s\n", sink_cell->name.c_str(ctx), sink->port.c_str(ctx));
last_port = sink->port;
}
log_break();
}
}
delay_t default_slack = delay_t(1.0e12 / ctx->target_freq);
log_info("estimated Fmax = %.2f MHz\n", 1e6 / (default_slack - min_slack));
if (print_histogram && slack_histogram.size() > 0) {
constexpr unsigned num_bins = 20;
unsigned bar_width = 60;
auto min_slack = slack_histogram.begin()->first;
auto max_slack = slack_histogram.rbegin()->first;
auto bin_size = (max_slack - min_slack) / num_bins;
std::vector<unsigned> bins(num_bins + 1);
unsigned max_freq = 0;
for (const auto &i : slack_histogram) {
auto &bin = bins[(i.first - min_slack) / bin_size];
bin += i.second;
max_freq = std::max(max_freq, bin);
}
bar_width = std::min(bar_width, max_freq);
log_break();
log_info("Slack histogram:\n");
log_info(" legend: * represents %d endpoint(s)\n", max_freq / bar_width);
for (unsigned i = 0; i < bins.size(); ++i)
log_info("%6d < ps < %6d |%s\n", min_slack + bin_size * i, min_slack + bin_size * (i + 1),
std::string(bins[i] * bar_width / max_freq, '*').c_str());
}
}
NEXTPNR_NAMESPACE_END
|
/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2018 David Shah <[email protected]>
*
* 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.
*
*/
#include "timing.h"
#include <algorithm>
#include <unordered_map>
#include <utility>
#include "log.h"
#include "util.h"
NEXTPNR_NAMESPACE_BEGIN
typedef std::vector<const PortRef *> PortRefVector;
typedef std::map<int, unsigned> DelayFrequency;
struct Timing
{
Context *ctx;
bool update;
delay_t min_slack;
PortRefVector current_path;
PortRefVector *crit_path;
DelayFrequency *slack_histogram;
Timing(Context *ctx, bool update, PortRefVector *crit_path = nullptr, DelayFrequency *slack_histogram = nullptr)
: ctx(ctx), update(update), min_slack(1.0e12 / ctx->target_freq), crit_path(crit_path),
slack_histogram(slack_histogram)
{
}
delay_t follow_net(NetInfo *net, int path_length, delay_t slack)
{
delay_t net_budget = slack / (path_length + 1);
for (auto &usr : net->users) {
if (crit_path)
current_path.push_back(&usr);
// If budget override is less than existing budget, then do not increment
// path length
int pl = path_length + 1;
auto budget = ctx->getBudgetOverride(net, usr, net_budget);
if (budget < net_budget) {
net_budget = budget;
pl = std::max(1, path_length);
}
auto delay = ctx->getNetinfoRouteDelay(net, usr);
net_budget = std::min(net_budget, follow_user_port(usr, pl, slack - delay));
if (update)
usr.budget = std::min(usr.budget, delay + net_budget);
if (crit_path)
current_path.pop_back();
}
return net_budget;
}
// Follow a path, returning budget to annotate
delay_t follow_user_port(PortRef &user, int path_length, delay_t slack)
{
delay_t value;
if (ctx->getPortClock(user.cell, user.port) != IdString()) {
// At the end of a timing path (arguably, should check setup time
// here too)
value = slack / path_length;
if (slack < min_slack) {
min_slack = slack;
if (crit_path)
*crit_path = current_path;
}
if (slack_histogram) {
int slack_ps = ctx->getDelayNS(slack) * 1000;
(*slack_histogram)[slack_ps]++;
}
} else {
// Default to the path ending here, if no further paths found
value = slack / path_length;
// Follow outputs of the user
for (auto port : user.cell->ports) {
if (port.second.type == PORT_OUT) {
DelayInfo comb_delay;
// Look up delay through this path
bool is_path = ctx->getCellDelay(user.cell, user.port, port.first, comb_delay);
if (is_path) {
NetInfo *net = port.second.net;
if (net) {
delay_t path_budget = follow_net(net, path_length, slack - comb_delay.maxDelay());
value = std::min(value, path_budget);
}
}
}
}
}
return value;
}
delay_t walk_paths()
{
delay_t default_slack = delay_t(1.0e12 / ctx->target_freq);
// Go through all clocked drivers and distribute the available path
// slack evenly into the budget of every sink on the path
for (auto &cell : ctx->cells) {
for (auto port : cell.second->ports) {
if (port.second.type == PORT_OUT) {
IdString clock_domain = ctx->getPortClock(cell.second.get(), port.first);
if (clock_domain != IdString()) {
delay_t slack = default_slack; // TODO: clock constraints
DelayInfo clkToQ;
if (ctx->getCellDelay(cell.second.get(), clock_domain, port.first, clkToQ))
slack -= clkToQ.maxDelay();
if (port.second.net)
follow_net(port.second.net, 0, slack);
}
}
}
}
return min_slack;
}
void assign_budget()
{
// Clear delays to a very high value first
delay_t default_slack = delay_t(1.0e12 / ctx->target_freq);
for (auto &net : ctx->nets) {
for (auto &usr : net.second->users) {
usr.budget = default_slack;
}
}
walk_paths();
}
};
void assign_budget(Context *ctx, bool quiet)
{
if (!quiet) {
log_break();
log_info("Annotating ports with timing budgets for target frequency %.2f MHz\n", ctx->target_freq/1e6);
}
Timing timing(ctx, true /* update */);
timing.assign_budget();
if (!quiet || ctx->verbose) {
for (auto &net : ctx->nets) {
for (auto &user : net.second->users) {
// Post-update check
if (!ctx->auto_freq && user.budget < 0)
log_warning("port %s.%s, connected to net '%s', has negative "
"timing budget of %fns\n",
user.cell->name.c_str(ctx), user.port.c_str(ctx), net.first.c_str(ctx),
ctx->getDelayNS(user.budget));
else if (ctx->verbose)
log_info("port %s.%s, connected to net '%s', has "
"timing budget of %fns\n",
user.cell->name.c_str(ctx), user.port.c_str(ctx), net.first.c_str(ctx),
ctx->getDelayNS(user.budget));
}
}
}
// For slack redistribution, if user has not specified a frequency
// dynamically adjust the target frequency to be the currently
// achieved maximum
if (ctx->auto_freq && ctx->slack_redist_iter > 0) {
delay_t default_slack = delay_t(1.0e12 / ctx->target_freq);
ctx->target_freq = 1e12 / (default_slack - timing.min_slack);
if (ctx->verbose)
log_info("minimum slack for this assign = %d, target Fmax for next "
"update = %.2f MHz\n",
timing.min_slack, ctx->target_freq / 1e6);
}
if (!quiet)
log_info("Checksum: 0x%08x\n", ctx->checksum());
}
void timing_analysis(Context *ctx, bool print_histogram, bool print_path)
{
PortRefVector crit_path;
DelayFrequency slack_histogram;
Timing timing(ctx, false /* update */, print_path ? &crit_path : nullptr,
print_histogram ? &slack_histogram : nullptr);
auto min_slack = timing.walk_paths();
if (print_path) {
if (crit_path.empty()) {
log_info("Design contains no timing paths\n");
} else {
delay_t total = 0;
log_break();
log_info("Critical path report:\n");
log_info("curr total\n");
auto &front = crit_path.front();
auto &front_port = front->cell->ports.at(front->port);
auto &front_driver = front_port.net->driver;
auto last_port = ctx->getPortClock(front_driver.cell, front_driver.port);
for (auto sink : crit_path) {
auto sink_cell = sink->cell;
auto &port = sink_cell->ports.at(sink->port);
auto net = port.net;
auto &driver = net->driver;
auto driver_cell = driver.cell;
DelayInfo comb_delay;
ctx->getCellDelay(sink_cell, last_port, driver.port, comb_delay);
total += comb_delay.maxDelay();
log_info("%4d %4d Source %s.%s\n", comb_delay.maxDelay(), total, driver_cell->name.c_str(ctx),
driver.port.c_str(ctx));
auto net_delay = ctx->getNetinfoRouteDelay(net, *sink);
total += net_delay;
auto driver_loc = ctx->getBelLocation(driver_cell->bel);
auto sink_loc = ctx->getBelLocation(sink_cell->bel);
log_info("%4d %4d Net %s budget %d (%d,%d) -> (%d,%d)\n", net_delay, total, net->name.c_str(ctx),
sink->budget, driver_loc.x, driver_loc.y, sink_loc.x, sink_loc.y);
log_info(" Sink %s.%s\n", sink_cell->name.c_str(ctx), sink->port.c_str(ctx));
last_port = sink->port;
}
log_break();
}
}
delay_t default_slack = delay_t(1.0e12 / ctx->target_freq);
log_info("estimated Fmax = %.2f MHz\n", 1e6 / (default_slack - min_slack));
if (print_histogram && slack_histogram.size() > 0) {
constexpr unsigned num_bins = 20;
unsigned bar_width = 60;
auto min_slack = slack_histogram.begin()->first;
auto max_slack = slack_histogram.rbegin()->first;
auto bin_size = (max_slack - min_slack) / num_bins;
std::vector<unsigned> bins(num_bins + 1);
unsigned max_freq = 0;
for (const auto &i : slack_histogram) {
auto &bin = bins[(i.first - min_slack) / bin_size];
bin += i.second;
max_freq = std::max(max_freq, bin);
}
bar_width = std::min(bar_width, max_freq);
log_break();
log_info("Slack histogram:\n");
log_info(" legend: * represents %d endpoint(s)\n", max_freq / bar_width);
log_info(" + represents [1,%d) endpoint(s)\n", max_freq / bar_width);
for (unsigned i = 0; i < bins.size(); ++i)
log_info("[%6d, %6d) |%s%c\n", min_slack + bin_size * i, min_slack + bin_size * (i + 1),
std::string(bins[i] * bar_width / max_freq, '*').c_str(),
(bins[i] * bar_width) % max_freq > 0 ? '+' : ' ');
}
}
NEXTPNR_NAMESPACE_END
|
Enhance slack histogram with '+' to indicate less-than-granularity
|
Enhance slack histogram with '+' to indicate less-than-granularity
|
C++
|
isc
|
YosysHQ/nextpnr,SymbiFlow/nextpnr,SymbiFlow/nextpnr,YosysHQ/nextpnr,YosysHQ/nextpnr,SymbiFlow/nextpnr,YosysHQ/nextpnr,SymbiFlow/nextpnr
|
3aa919df2730d506ce5f1f526472446b5e8f805d
|
lib/Lex/MacroInfo.cpp
|
lib/Lex/MacroInfo.cpp
|
//===--- MacroInfo.cpp - Information about #defined identifiers -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the MacroInfo interface.
//
//===----------------------------------------------------------------------===//
#include "clang/Lex/MacroInfo.h"
#include "clang/Lex/Preprocessor.h"
using namespace clang;
MacroInfo::MacroInfo(SourceLocation DefLoc)
: Location(DefLoc),
ArgumentList(nullptr),
NumArguments(0),
IsDefinitionLengthCached(false),
IsFunctionLike(false),
IsC99Varargs(false),
IsGNUVarargs(false),
IsBuiltinMacro(false),
HasCommaPasting(false),
IsDisabled(false),
IsUsed(false),
IsAllowRedefinitionsWithoutWarning(false),
IsWarnIfUnused(false),
FromASTFile(false),
UsedForHeaderGuard(false) {
}
unsigned MacroInfo::getDefinitionLengthSlow(SourceManager &SM) const {
assert(!IsDefinitionLengthCached);
IsDefinitionLengthCached = true;
if (ReplacementTokens.empty())
return (DefinitionLength = 0);
const Token &firstToken = ReplacementTokens.front();
const Token &lastToken = ReplacementTokens.back();
SourceLocation macroStart = firstToken.getLocation();
SourceLocation macroEnd = lastToken.getLocation();
assert(macroStart.isValid() && macroEnd.isValid());
assert((macroStart.isFileID() || firstToken.is(tok::comment)) &&
"Macro defined in macro?");
assert((macroEnd.isFileID() || lastToken.is(tok::comment)) &&
"Macro defined in macro?");
std::pair<FileID, unsigned>
startInfo = SM.getDecomposedExpansionLoc(macroStart);
std::pair<FileID, unsigned>
endInfo = SM.getDecomposedExpansionLoc(macroEnd);
assert(startInfo.first == endInfo.first &&
"Macro definition spanning multiple FileIDs ?");
assert(startInfo.second <= endInfo.second);
DefinitionLength = endInfo.second - startInfo.second;
DefinitionLength += lastToken.getLength();
return DefinitionLength;
}
/// \brief Return true if the specified macro definition is equal to
/// this macro in spelling, arguments, and whitespace.
///
/// \param Syntactically if true, the macro definitions can be identical even
/// if they use different identifiers for the function macro parameters.
/// Otherwise the comparison is lexical and this implements the rules in
/// C99 6.10.3.
bool MacroInfo::isIdenticalTo(const MacroInfo &Other, Preprocessor &PP,
bool Syntactically) const {
bool Lexically = !Syntactically;
// Check # tokens in replacement, number of args, and various flags all match.
if (ReplacementTokens.size() != Other.ReplacementTokens.size() ||
getNumArgs() != Other.getNumArgs() ||
isFunctionLike() != Other.isFunctionLike() ||
isC99Varargs() != Other.isC99Varargs() ||
isGNUVarargs() != Other.isGNUVarargs())
return false;
if (Lexically) {
// Check arguments.
for (arg_iterator I = arg_begin(), OI = Other.arg_begin(), E = arg_end();
I != E; ++I, ++OI)
if (*I != *OI) return false;
}
// Check all the tokens.
for (unsigned i = 0, e = ReplacementTokens.size(); i != e; ++i) {
const Token &A = ReplacementTokens[i];
const Token &B = Other.ReplacementTokens[i];
if (A.getKind() != B.getKind())
return false;
// If this isn't the first first token, check that the whitespace and
// start-of-line characteristics match.
if (i != 0 &&
(A.isAtStartOfLine() != B.isAtStartOfLine() ||
A.hasLeadingSpace() != B.hasLeadingSpace()))
return false;
// If this is an identifier, it is easy.
if (A.getIdentifierInfo() || B.getIdentifierInfo()) {
if (A.getIdentifierInfo() == B.getIdentifierInfo())
continue;
if (Lexically)
return false;
// With syntactic equivalence the parameter names can be different as long
// as they are used in the same place.
int AArgNum = getArgumentNum(A.getIdentifierInfo());
if (AArgNum == -1)
return false;
if (AArgNum != Other.getArgumentNum(B.getIdentifierInfo()))
return false;
continue;
}
// Otherwise, check the spelling.
if (PP.getSpelling(A) != PP.getSpelling(B))
return false;
}
return true;
}
void MacroInfo::dump() const {
llvm::raw_ostream &Out = llvm::errs();
// FIXME: Dump locations.
Out << "MacroInfo " << this;
if (IsBuiltinMacro) Out << " builtin";
if (IsDisabled) Out << " disabled";
if (IsUsed) Out << " used";
if (IsAllowRedefinitionsWithoutWarning)
Out << " allow_redefinitions_without_warning";
if (IsWarnIfUnused) Out << " warn_if_unused";
if (FromASTFile) Out << " imported";
if (UsedForHeaderGuard) Out << " header_guard";
Out << "\n #define <macro>";
if (IsFunctionLike) {
Out << "(";
for (unsigned I = 0; I != NumArguments; ++I) {
if (I) Out << ", ";
Out << ArgumentList[I]->getName();
}
if (IsC99Varargs || IsGNUVarargs) {
if (NumArguments && IsC99Varargs) Out << ", ";
Out << "...";
}
Out << ")";
}
for (const Token &Tok : ReplacementTokens) {
Out << " ";
if (const char *Punc = tok::getPunctuatorSpelling(Tok.getKind()))
Out << Punc;
else if (const char *Kwd = tok::getKeywordSpelling(Tok.getKind()))
Out << Kwd;
else if (Tok.is(tok::identifier))
Out << Tok.getIdentifierInfo()->getName();
else if (Tok.isLiteral() && Tok.getLiteralData())
Out << StringRef(Tok.getLiteralData(), Tok.getLength());
else
Out << Tok.getName();
}
}
MacroDirective::DefInfo MacroDirective::getDefinition() {
MacroDirective *MD = this;
SourceLocation UndefLoc;
Optional<bool> isPublic;
for (; MD; MD = MD->getPrevious()) {
if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
return DefInfo(DefMD, UndefLoc,
!isPublic.hasValue() || isPublic.getValue());
if (UndefMacroDirective *UndefMD = dyn_cast<UndefMacroDirective>(MD)) {
UndefLoc = UndefMD->getLocation();
continue;
}
VisibilityMacroDirective *VisMD = cast<VisibilityMacroDirective>(MD);
if (!isPublic.hasValue())
isPublic = VisMD->isPublic();
}
return DefInfo(nullptr, UndefLoc,
!isPublic.hasValue() || isPublic.getValue());
}
const MacroDirective::DefInfo
MacroDirective::findDirectiveAtLoc(SourceLocation L, SourceManager &SM) const {
assert(L.isValid() && "SourceLocation is invalid.");
for (DefInfo Def = getDefinition(); Def; Def = Def.getPreviousDefinition()) {
if (Def.getLocation().isInvalid() || // For macros defined on the command line.
SM.isBeforeInTranslationUnit(Def.getLocation(), L))
return (!Def.isUndefined() ||
SM.isBeforeInTranslationUnit(L, Def.getUndefLocation()))
? Def : DefInfo();
}
return DefInfo();
}
void MacroDirective::dump() const {
llvm::raw_ostream &Out = llvm::errs();
switch (getKind()) {
case MD_Define: Out << "DefMacroDirective"; break;
case MD_Undefine: Out << "UndefMacroDirective"; break;
case MD_Visibility: Out << "VisibilityMacroDirective"; break;
}
Out << " " << this;
// FIXME: Dump SourceLocation.
if (auto *Prev = getPrevious())
Out << " prev " << Prev;
if (IsFromPCH) Out << " from_pch";
if (isa<VisibilityMacroDirective>(this))
Out << (IsPublic ? " public" : " private");
if (auto *DMD = dyn_cast<DefMacroDirective>(this)) {
if (auto *Info = DMD->getInfo()) {
Out << "\n ";
Info->dump();
}
}
Out << "\n";
}
ModuleMacro *ModuleMacro::create(Preprocessor &PP, Module *OwningModule,
IdentifierInfo *II, MacroInfo *Macro,
ArrayRef<ModuleMacro *> Overrides) {
void *Mem = PP.getPreprocessorAllocator().Allocate(
sizeof(ModuleMacro) + sizeof(ModuleMacro *) * Overrides.size(),
llvm::alignOf<ModuleMacro>());
return new (Mem) ModuleMacro(OwningModule, II, Macro, Overrides);
}
|
//===--- MacroInfo.cpp - Information about #defined identifiers -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the MacroInfo interface.
//
//===----------------------------------------------------------------------===//
#include "clang/Lex/MacroInfo.h"
#include "clang/Lex/Preprocessor.h"
using namespace clang;
MacroInfo::MacroInfo(SourceLocation DefLoc)
: Location(DefLoc),
ArgumentList(nullptr),
NumArguments(0),
IsDefinitionLengthCached(false),
IsFunctionLike(false),
IsC99Varargs(false),
IsGNUVarargs(false),
IsBuiltinMacro(false),
HasCommaPasting(false),
IsDisabled(false),
IsUsed(false),
IsAllowRedefinitionsWithoutWarning(false),
IsWarnIfUnused(false),
FromASTFile(false),
UsedForHeaderGuard(false) {
}
unsigned MacroInfo::getDefinitionLengthSlow(SourceManager &SM) const {
assert(!IsDefinitionLengthCached);
IsDefinitionLengthCached = true;
if (ReplacementTokens.empty())
return (DefinitionLength = 0);
const Token &firstToken = ReplacementTokens.front();
const Token &lastToken = ReplacementTokens.back();
SourceLocation macroStart = firstToken.getLocation();
SourceLocation macroEnd = lastToken.getLocation();
assert(macroStart.isValid() && macroEnd.isValid());
assert((macroStart.isFileID() || firstToken.is(tok::comment)) &&
"Macro defined in macro?");
assert((macroEnd.isFileID() || lastToken.is(tok::comment)) &&
"Macro defined in macro?");
std::pair<FileID, unsigned>
startInfo = SM.getDecomposedExpansionLoc(macroStart);
std::pair<FileID, unsigned>
endInfo = SM.getDecomposedExpansionLoc(macroEnd);
assert(startInfo.first == endInfo.first &&
"Macro definition spanning multiple FileIDs ?");
assert(startInfo.second <= endInfo.second);
DefinitionLength = endInfo.second - startInfo.second;
DefinitionLength += lastToken.getLength();
return DefinitionLength;
}
/// \brief Return true if the specified macro definition is equal to
/// this macro in spelling, arguments, and whitespace.
///
/// \param Syntactically if true, the macro definitions can be identical even
/// if they use different identifiers for the function macro parameters.
/// Otherwise the comparison is lexical and this implements the rules in
/// C99 6.10.3.
bool MacroInfo::isIdenticalTo(const MacroInfo &Other, Preprocessor &PP,
bool Syntactically) const {
bool Lexically = !Syntactically;
// Check # tokens in replacement, number of args, and various flags all match.
if (ReplacementTokens.size() != Other.ReplacementTokens.size() ||
getNumArgs() != Other.getNumArgs() ||
isFunctionLike() != Other.isFunctionLike() ||
isC99Varargs() != Other.isC99Varargs() ||
isGNUVarargs() != Other.isGNUVarargs())
return false;
if (Lexically) {
// Check arguments.
for (arg_iterator I = arg_begin(), OI = Other.arg_begin(), E = arg_end();
I != E; ++I, ++OI)
if (*I != *OI) return false;
}
// Check all the tokens.
for (unsigned i = 0, e = ReplacementTokens.size(); i != e; ++i) {
const Token &A = ReplacementTokens[i];
const Token &B = Other.ReplacementTokens[i];
if (A.getKind() != B.getKind())
return false;
// If this isn't the first first token, check that the whitespace and
// start-of-line characteristics match.
if (i != 0 &&
(A.isAtStartOfLine() != B.isAtStartOfLine() ||
A.hasLeadingSpace() != B.hasLeadingSpace()))
return false;
// If this is an identifier, it is easy.
if (A.getIdentifierInfo() || B.getIdentifierInfo()) {
if (A.getIdentifierInfo() == B.getIdentifierInfo())
continue;
if (Lexically)
return false;
// With syntactic equivalence the parameter names can be different as long
// as they are used in the same place.
int AArgNum = getArgumentNum(A.getIdentifierInfo());
if (AArgNum == -1)
return false;
if (AArgNum != Other.getArgumentNum(B.getIdentifierInfo()))
return false;
continue;
}
// Otherwise, check the spelling.
if (PP.getSpelling(A) != PP.getSpelling(B))
return false;
}
return true;
}
void MacroInfo::dump() const {
llvm::raw_ostream &Out = llvm::errs();
// FIXME: Dump locations.
Out << "MacroInfo " << this;
if (IsBuiltinMacro) Out << " builtin";
if (IsDisabled) Out << " disabled";
if (IsUsed) Out << " used";
if (IsAllowRedefinitionsWithoutWarning)
Out << " allow_redefinitions_without_warning";
if (IsWarnIfUnused) Out << " warn_if_unused";
if (FromASTFile) Out << " imported";
if (UsedForHeaderGuard) Out << " header_guard";
Out << "\n #define <macro>";
if (IsFunctionLike) {
Out << "(";
for (unsigned I = 0; I != NumArguments; ++I) {
if (I) Out << ", ";
Out << ArgumentList[I]->getName();
}
if (IsC99Varargs || IsGNUVarargs) {
if (NumArguments && IsC99Varargs) Out << ", ";
Out << "...";
}
Out << ")";
}
bool First = true;
for (const Token &Tok : ReplacementTokens) {
// Leading space is semantically meaningful in a macro definition,
// so preserve it in the dump output.
if (First || Tok.hasLeadingSpace())
Out << " ";
First = false;
if (const char *Punc = tok::getPunctuatorSpelling(Tok.getKind()))
Out << Punc;
else if (Tok.isLiteral() && Tok.getLiteralData())
Out << StringRef(Tok.getLiteralData(), Tok.getLength());
else if (auto *II = Tok.getIdentifierInfo())
Out << II->getName();
else
Out << Tok.getName();
}
}
MacroDirective::DefInfo MacroDirective::getDefinition() {
MacroDirective *MD = this;
SourceLocation UndefLoc;
Optional<bool> isPublic;
for (; MD; MD = MD->getPrevious()) {
if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
return DefInfo(DefMD, UndefLoc,
!isPublic.hasValue() || isPublic.getValue());
if (UndefMacroDirective *UndefMD = dyn_cast<UndefMacroDirective>(MD)) {
UndefLoc = UndefMD->getLocation();
continue;
}
VisibilityMacroDirective *VisMD = cast<VisibilityMacroDirective>(MD);
if (!isPublic.hasValue())
isPublic = VisMD->isPublic();
}
return DefInfo(nullptr, UndefLoc,
!isPublic.hasValue() || isPublic.getValue());
}
const MacroDirective::DefInfo
MacroDirective::findDirectiveAtLoc(SourceLocation L, SourceManager &SM) const {
assert(L.isValid() && "SourceLocation is invalid.");
for (DefInfo Def = getDefinition(); Def; Def = Def.getPreviousDefinition()) {
if (Def.getLocation().isInvalid() || // For macros defined on the command line.
SM.isBeforeInTranslationUnit(Def.getLocation(), L))
return (!Def.isUndefined() ||
SM.isBeforeInTranslationUnit(L, Def.getUndefLocation()))
? Def : DefInfo();
}
return DefInfo();
}
void MacroDirective::dump() const {
llvm::raw_ostream &Out = llvm::errs();
switch (getKind()) {
case MD_Define: Out << "DefMacroDirective"; break;
case MD_Undefine: Out << "UndefMacroDirective"; break;
case MD_Visibility: Out << "VisibilityMacroDirective"; break;
}
Out << " " << this;
// FIXME: Dump SourceLocation.
if (auto *Prev = getPrevious())
Out << " prev " << Prev;
if (IsFromPCH) Out << " from_pch";
if (isa<VisibilityMacroDirective>(this))
Out << (IsPublic ? " public" : " private");
if (auto *DMD = dyn_cast<DefMacroDirective>(this)) {
if (auto *Info = DMD->getInfo()) {
Out << "\n ";
Info->dump();
}
}
Out << "\n";
}
ModuleMacro *ModuleMacro::create(Preprocessor &PP, Module *OwningModule,
IdentifierInfo *II, MacroInfo *Macro,
ArrayRef<ModuleMacro *> Overrides) {
void *Mem = PP.getPreprocessorAllocator().Allocate(
sizeof(ModuleMacro) + sizeof(ModuleMacro *) * Overrides.size(),
llvm::alignOf<ModuleMacro>());
return new (Mem) ModuleMacro(OwningModule, II, Macro, Overrides);
}
|
Improve macro dumping to preserve semantically-relevant spelling information.
|
Improve macro dumping to preserve semantically-relevant spelling information.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@252206 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang
|
edb596dccea2ea6a5458f305f3ff58dee1d933f1
|
app/src/main/pre_process/image.cpp
|
app/src/main/pre_process/image.cpp
|
#include <iostream>
#include "image.hpp"
// the __init__ of Image.
// args:
// n int,
// m int,
// array double array
// return:
// no return value.
Image::Image(int n, int m, int* array):vector()
{
this->resize(m);
for (size_t i = 0; i < m; i++) {
(*this)[i].resize(n);
for (size_t j = 0; j < n; j++) {
(*this)[i][j] = array[i*n + j];
}
}
}
// the hist table of image.
// args:
// none,
// return:
// std::map<int, int>
std::map<int, int> Image::imageHist()
{
std::map<int, int> res;
// Image::iterator is a std::vector<std::vector<int>>::iterator.
for (auto i = this->begin(); i != this->end(); i++) {
for (auto j = i->begin(); j != i->end(); j++) {
if (res.find(*j) != res.end()) {
res[*j] += 1;
}
else {
res[*j] = 1;
}
}
}
return res;
}
// Invert the image. Be ware of that this func doesn't return a Image.
// also do the 2-value work.
void Image::imageInvert(int threshold)
{
for (auto i = this->begin(); i != this->end(); i++) {
for (auto j = i->begin(); j != i->end(); j++) {
if (*j > threshold) {
*j = 0;
}
else {
*j = 255;
}
}
}
}
// change the image to a 2-value image.
void Image::imageTwoValue(int threshold)
{
for (auto i = this->begin(); i != this->end(); i++) {
for (auto j = i->begin(); j != i->end(); j++) {
if (*j > threshold) {
*j = 255;
}
else {
*j = 0;
}
}
}
}
// use the hist table to smart choose a threshold.
// automate do the Invert when needed.
// the stardand image means a black background (0) and white text (255)
void Image::imageStandard()
{
std::map<int, int> hist = this->imageHist();
auto maxItem = hist.begin();
for (auto i = hist.begin(); i != hist.end(); i++) {
if (i->second > maxItem->second) {
maxItem = i;
}
}
int downloadCnt = 0;
auto minItem = maxItem;
auto preItem = hist.begin();
for (auto i = hist.begin(); i != maxItem; ++i) {
if (i->second < preItem->second) {
downloadCnt ++;
}
else if (downloadCnt < 3) {
downloadCnt = 0;
}
preItem = i;
if (i->second < minItem->second && downloadCnt >= 3) {
minItem = i;
}
}
// if the background is white (255), then invert it.
if (maxItem->first > 128) {
this->imageInvert(minItem->first);
}
else {
this->imageTwoValue(minItem->first);
}
}
// return the Grid that contain at least one pixels is white(255).
// return :
// res [[0, 1, 2, 3], ..., ]
// each of vector in stand of a grid [x1, y1, x2, y2]
// (x1, y2) ... (x2, y2)
// ... ... ...
// (x1, y1) ... (x2, y1)
// you should turn this Image to a 2-value first.
std::vector<std::vector<int>> Image::findGrid()
{
int dir[8][2] = {
{0, 1},
{0, -1},
{1, 0},
{-1, 0},
{1, 1},
{1, -1},
{-1, 1},
{-1, -1}
};
std::set<std::pair<int, int>> vis;
std::vector<std::vector<int>> res;
std::queue<std::pair<int, int>> bfsQueue;
// find grids.
for (auto i = this->begin(); i != this->end(); ++i) {
for (auto j = i->begin(); j != i->end(); ++j) {
// white = 255.
if (*j == 255) {
// bfs
int nowX = i - this->begin();
int nowY = j - i->begin();
// the start point.
std::pair<int, int> coordinate(nowX, nowY);
// check whether this point has been visited.
if (vis.find(coordinate) != vis.end()) {
continue;
}
// the begin of bfs.
bfsQueue.push(coordinate);
// the edge of Grid.
// [x1, y1, x2, y2]
// (x1, y2) ... (x2, y2)
// ... ... ...
// (x1, y1) ... (x2, y1)
std::vector<int> edge;
edge.resize(4);
// x1, x2
edge[0] = edge[2] = nowX;
// y1, y2
edge[1] = edge[3] = nowY;
// bfs cycle.
while (!bfsQueue.empty()) {
coordinate = bfsQueue.front();
bfsQueue.pop();
// if this point has been visited.
if (vis.find(coordinate) != vis.end()) {
continue;
}
// mark this point as visited.
vis.insert(coordinate);
// update nowPoint.
nowX = coordinate.first;
nowY = coordinate.second;
// update edge.
// x1, x2
if (nowX < edge[0]) {
edge[0] = nowX;
}
else if (nowX > edge[2]) {
edge[2] = nowX;
}
// y1, y2
if (nowY < edge[1]) {
edge[1] = nowY;
}
else if (nowY > edge[3]) {
edge[3] = nowY;
}
int nextX = 0;
int nextY = 0;
for (size_t k = 0; k < 8; k++) {
// next point.
nextX = nowX + dir[k][0];
nextY = nowY + dir[k][1];
std::pair<int, int> nextCoordinate(nextX, nextY);
// prevent that array out of range.
if (nextX >= this->size() || nextX < 0) {
continue;
}
if (nextY >= i->size() || nextY < 0) {
continue;
}
// reflash edge
if ((*this)[nextX][nextY] == 255 &&
vis.find(nextCoordinate) == vis.end()) {
// if not visited next point.
bfsQueue.push(nextCoordinate);
}
}
}
if (this->gridJudge(edge)) {
res.push_back(edge);
}
}
}
}
// merge the grids.
std::vector<std::vector<int>> mergeRes;
std::set<std::vector<std::vector<int>>::iterator> mergeVis;
for (auto base = res.begin(); base != res.end(); ++base) {
int mergeFlag = 0;
// merge aim into base.
if (mergeVis.find(base) != mergeVis.end()) {
continue;
}
int baseX1 = (*base)[0];
int baseX2 = (*base)[2];
int baseY1 = (*base)[1];
int baseY2 = (*base)[3];
std::pair<int, int> baseCenter(
(baseX1 + baseX2)/2, (baseY1 + baseY2)/2
);
for (auto aim = base; aim != res.end(); ++aim) {
// jump the first one.
if (aim == base) {
continue;
}
if (mergeVis.find(aim) != mergeVis.end()) {
continue;
}
// judge.
int aimX1 = (*aim)[0];
int aimX2 = (*aim)[2];
int aimY1 = (*aim)[1];
int aimY2 = (*aim)[3];
std::pair<int, int> aimCenter(
(aimX1 + aimX2)/2, (aimY1 + aimY2)/2
);
if ((aimCenter.second >= baseY1 && aimCenter.second <= baseY2) ||
(baseCenter.second >= aimY1 && baseCenter.second <= aimY2)) {
int disX = aimCenter.first - baseCenter.first;
if (disX < 0) {
disX *= -1;
}
// judge if disX is small enough.
if (disX <= (baseX2-baseX1) || disX <= (aimX2 - aimX1)) {
// merge the aim into base.
std::vector<int> mergeBaseAim;
mergeBaseAim.resize(4);
mergeBaseAim[0] = std::min((*base)[0], (*aim)[0]);
mergeBaseAim[1] = std::min((*base)[1], (*aim)[1]);
mergeBaseAim[2] = std::max((*base)[2], (*aim)[2]);
mergeBaseAim[3] = std::max((*base)[3], (*aim)[3]);
mergeRes.push_back(mergeBaseAim);
mergeVis.insert(aim);
mergeFlag = 1;
break;
}
}
}
mergeVis.insert(base);
if (mergeFlag == 0) {
mergeRes.push_back(*base);
}
}
// return res;
return mergeRes;
}
// judge whether a grid is big enough.
bool Image::gridJudge(std::vector<int> edge)
{
if (edge.size() != 4) {
return false;
}
int col = edge[2] - edge[0] + 1;
int row = edge[3] - edge[1] + 1;
if (col < 2 || row < 2) {
return false;
}
return true;
}
// the resize func.
std::vector<std::vector<int>> Image::resizeGrid(std::vector<int> grid)
{
// res is a 28*28 2-d vector.
std::vector<std::vector<int>> res;
res.resize(28);
for (auto i = res.begin(); i != res.end(); ++i) {
i->resize(28);
}
int x1 = grid[0];
int y1 = grid[1];
int x2 = grid[2];
int y2 = grid[3];
int lenX = x2 - x1 + 1;
int lenY = y2 - y1 + 1;
// the norm of operator.
int lamX = (lenX + 27) / 28;
int lamY = (lenY + 27) / 28;
for (int i = 0; i < 28; ++i) {
for (int j = 0; j < 28; ++j) {
int maxPixel = 0;
for (int li = 0; li < lamX; ++li) {
int nowX = i*lamX + li + x1;
if (nowX > x2) {
break;
}
for (int lj = 0; lj < lamY; ++lj) {
int nowY = j*lamY + lj + y1;
if (nowY > y2) {
break;
}
// if this pixel is white, then use it.
if ((*this)[nowX][nowY] > 0) {
maxPixel = 255;
break;
}
}
if (maxPixel == 255) {
break;
}
}
res[i][j] = maxPixel;
}
}
return res;
}
|
#include <iostream>
#include "image.hpp"
// the __init__ of Image.
// args:
// n int,
// m int,
// array double array
// return:
// no return value.
Image::Image(int n, int m, int* array):vector()
{
this->resize(m);
for (size_t i = 0; i < m; i++) {
(*this)[i].resize(n);
for (size_t j = 0; j < n; j++) {
(*this)[i][j] = array[i*n + j];
}
}
}
// the hist table of image.
// args:
// none,
// return:
// std::map<int, int>
std::map<int, int> Image::imageHist()
{
std::map<int, int> res;
// Image::iterator is a std::vector<std::vector<int>>::iterator.
for (auto i = this->begin(); i != this->end(); i++) {
for (auto j = i->begin(); j != i->end(); j++) {
if (res.find(*j) != res.end()) {
res[*j] += 1;
}
else {
res[*j] = 1;
}
}
}
return res;
}
// Invert the image. Be ware of that this func doesn't return a Image.
// also do the 2-value work.
void Image::imageInvert(int threshold)
{
for (auto i = this->begin(); i != this->end(); i++) {
for (auto j = i->begin(); j != i->end(); j++) {
if (*j > threshold) {
*j = 0;
}
else {
*j = 255;
}
}
}
}
// change the image to a 2-value image.
void Image::imageTwoValue(int threshold)
{
for (auto i = this->begin(); i != this->end(); i++) {
for (auto j = i->begin(); j != i->end(); j++) {
if (*j > threshold) {
*j = 255;
}
else {
*j = 0;
}
}
}
}
// use the hist table to smart choose a threshold.
// automate do the Invert when needed.
// the stardand image means a black background (0) and white text (255)
void Image::imageStandard()
{
std::map<int, int> hist = this->imageHist();
auto maxItem = hist.begin();
for (auto i = hist.begin(); i != hist.end(); i++) {
if (i->second > maxItem->second) {
maxItem = i;
}
}
int downloadCnt = 0;
auto minItem = maxItem;
auto preItem = hist.begin();
for (auto i = hist.begin(); i != maxItem; ++i) {
if (i->second < preItem->second) {
downloadCnt ++;
}
else if (downloadCnt < 3) {
downloadCnt = 0;
}
preItem = i;
if (i->second < minItem->second && downloadCnt >= 3) {
minItem = i;
}
}
// if the background is white (255), then invert it.
if (maxItem->first > 128) {
this->imageInvert(minItem->first);
}
else {
this->imageTwoValue(minItem->first);
}
}
// return the Grid that contain at least one pixels is white(255).
// return :
// res [[0, 1, 2, 3], ..., ]
// each of vector in stand of a grid [x1, y1, x2, y2]
// (x1, y2) ... (x2, y2)
// ... ... ...
// (x1, y1) ... (x2, y1)
// you should turn this Image to a 2-value first.
std::vector<std::vector<int>> Image::findGrid()
{
int dir[8][2] = {
{0, 1},
{0, -1},
{1, 0},
{-1, 0},
{1, 1},
{1, -1},
{-1, 1},
{-1, -1}
};
std::set<std::pair<int, int>> vis;
std::vector<std::vector<int>> res;
std::queue<std::pair<int, int>> bfsQueue;
// find grids.
for (auto i = this->begin(); i != this->end(); ++i) {
for (auto j = i->begin(); j != i->end(); ++j) {
// white = 255.
if (*j == 255) {
// bfs
int nowX = i - this->begin();
int nowY = j - i->begin();
// the start point.
std::pair<int, int> coordinate(nowX, nowY);
// check whether this point has been visited.
if (vis.find(coordinate) != vis.end()) {
continue;
}
// the begin of bfs.
bfsQueue.push(coordinate);
// the edge of Grid.
// [x1, y1, x2, y2]
// (x1, y2) ... (x2, y2)
// ... ... ...
// (x1, y1) ... (x2, y1)
std::vector<int> edge;
edge.resize(4);
// x1, x2
edge[0] = edge[2] = nowX;
// y1, y2
edge[1] = edge[3] = nowY;
// bfs cycle.
while (!bfsQueue.empty()) {
coordinate = bfsQueue.front();
bfsQueue.pop();
// if this point has been visited.
if (vis.find(coordinate) != vis.end()) {
continue;
}
// mark this point as visited.
vis.insert(coordinate);
// update nowPoint.
nowX = coordinate.first;
nowY = coordinate.second;
// update edge.
// x1, x2
if (nowX < edge[0]) {
edge[0] = nowX;
}
else if (nowX > edge[2]) {
edge[2] = nowX;
}
// y1, y2
if (nowY < edge[1]) {
edge[1] = nowY;
}
else if (nowY > edge[3]) {
edge[3] = nowY;
}
int nextX = 0;
int nextY = 0;
for (size_t k = 0; k < 8; k++) {
// next point.
nextX = nowX + dir[k][0];
nextY = nowY + dir[k][1];
std::pair<int, int> nextCoordinate(nextX, nextY);
// prevent that array out of range.
if (nextX >= this->size() || nextX < 0) {
continue;
}
if (nextY >= i->size() || nextY < 0) {
continue;
}
// reflash edge
if ((*this)[nextX][nextY] == 255 &&
vis.find(nextCoordinate) == vis.end()) {
// if not visited next point.
bfsQueue.push(nextCoordinate);
}
}
}
if (this->gridJudge(edge)) {
res.push_back(edge);
}
}
}
}
// merge the grids.
std::vector<std::vector<int>> mergeRes;
std::set<std::vector<std::vector<int>>::iterator> mergeVis;
for (auto base = res.begin(); base != res.end(); ++base) {
int mergeFlag = 0;
// merge aim into base.
if (mergeVis.find(base) != mergeVis.end()) {
continue;
}
int baseX1 = (*base)[0];
int baseX2 = (*base)[2];
int baseY1 = (*base)[1];
int baseY2 = (*base)[3];
std::pair<int, int> baseCenter(
(baseX1 + baseX2)/2, (baseY1 + baseY2)/2
);
for (auto aim = base; aim != res.end(); ++aim) {
// jump the first one.
if (aim == base) {
continue;
}
if (mergeVis.find(aim) != mergeVis.end()) {
continue;
}
// judge.
int aimX1 = (*aim)[0];
int aimX2 = (*aim)[2];
int aimY1 = (*aim)[1];
int aimY2 = (*aim)[3];
std::pair<int, int> aimCenter(
(aimX1 + aimX2)/2, (aimY1 + aimY2)/2
);
if ((aimCenter.second >= baseY1 && aimCenter.second <= baseY2) ||
(baseCenter.second >= aimY1 && baseCenter.second <= aimY2)) {
int disX = aimCenter.first - baseCenter.first;
if (disX < 0) {
disX *= -1;
}
// judge if disX is small enough.
if (disX <= (baseX2-baseX1) || disX <= (aimX2 - aimX1)) {
// merge the aim into base.
std::vector<int> mergeBaseAim;
mergeBaseAim.resize(4);
mergeBaseAim[0] = std::min((*base)[0], (*aim)[0]);
mergeBaseAim[1] = std::min((*base)[1], (*aim)[1]);
mergeBaseAim[2] = std::max((*base)[2], (*aim)[2]);
mergeBaseAim[3] = std::max((*base)[3], (*aim)[3]);
mergeRes.push_back(mergeBaseAim);
mergeVis.insert(aim);
mergeFlag = 1;
break;
}
}
}
mergeVis.insert(base);
if (mergeFlag == 0) {
mergeRes.push_back(*base);
}
}
// return res;
return mergeRes;
}
// judge whether a grid is big enough.
bool Image::gridJudge(std::vector<int> edge)
{
if (edge.size() != 4) {
return false;
}
int col = edge[2] - edge[0] + 1;
int row = edge[3] - edge[1] + 1;
if (col < 2 || row < 2) {
return false;
}
return true;
}
// the resize func.
// use max filter.
std::vector<std::vector<int>> Image::resizeGrid(std::vector<int> grid)
{
// res is a 28*28 2-d vector.
std::vector<std::vector<int>> res;
res.resize(28);
for (auto i = res.begin(); i != res.end(); ++i) {
i->resize(28);
}
int x1 = grid[0];
int y1 = grid[1];
int x2 = grid[2];
int y2 = grid[3];
int lenX = x2 - x1 + 1;
int lenY = y2 - y1 + 1;
// the norm of operator.
int lamX = (lenX + 27) / 28;
int lamY = (lenY + 27) / 28;
// the scale of zoom. use to fix window.
double scaleZoomX = (double)lenX/28.0;
double scaleZoomY = (double)lenY/28.0;
for (int i = 0; i < 28; ++i) {
for (int j = 0; j < 28; ++j) {
int maxPixel = 0;
for (int li = 0; li < lamX; ++li) {
int nowX = i*scaleZoomX + li + x1;
if (nowX > x2) {
break;
}
for (int lj = 0; lj < lamY; ++lj) {
int nowY = j*scaleZoomY + lj + y1;
if (nowY > y2) {
break;
}
// if this pixel is white, then use it.
if ((*this)[nowX][nowY] > 0) {
maxPixel = 255;
break;
}
}
if (maxPixel == 255) {
break;
}
}
res[i][j] = maxPixel;
}
}
return res;
}
|
use double scale to fix window
|
use double scale to fix window
|
C++
|
mit
|
jxfn-develop-group/jxfn,jxfn-develop-group/jxfn,jxfn-develop-group/jxfn,jxfn-develop-group/jxfn
|
c05d9c6192d666b2f5bf9de9055c3597c3ac2156
|
src/mc0d_main.cpp
|
src/mc0d_main.cpp
|
#include "broker.h"
#include "logger.h"
#include <boost/program_options.hpp>
namespace po = boost::program_options;
int main(int argc, char *argv[]) {
po::options_description desc("Allowed options");
desc.add_options()
("help", "display help")
("bind", po::value<std::string>()->default_value("tcp://*:61616"), "address to bind")
("curve-private-key", po::value<std::string>()->required(), "private key")
("logger-config", po::value<std::string>()->default_value(""), "log4cxx properties file")
;
po::variables_map vm;
po::store(parse_command_line(argc, argv, desc), vm);
if (vm.count("help")) {
std::cout << desc;
return 0;
}
mc0::Logger logger(vm["logger-config"].as<std::string>());
mc0::Broker broker(vm["bind"].as<std::string>(), vm["curve-private-key"].as<std::string>());
broker.main_loop();
return 0;
}
|
#include "broker.h"
#include "logger.h"
#include <boost/program_options.hpp>
#include <string>
namespace po = boost::program_options;
int main(int argc, char *argv[]) {
po::options_description desc("Allowed options");
desc.add_options()
("help", "display help")
("bind", po::value<std::string>()->default_value("*"), "address to bind")
("port", po::value<int>()->default_value(61616), "port to bind")
("curve-private-key", po::value<std::string>()->required(), "private key")
("logger-config", po::value<std::string>()->default_value(""), "log4cxx properties file")
;
po::variables_map vm;
po::store(parse_command_line(argc, argv, desc), vm);
if (vm.count("help")) {
std::cout << desc;
return 0;
}
mc0::Logger logger(vm["logger-config"].as<std::string>());
std::string endpoint("tcp://" + vm["bind"].as<std::string>() + ":" + std::to_string(vm["port"].as<int>()));
mc0::Broker broker(endpoint, vm["curve-private-key"].as<std::string>());
broker.main_loop();
return 0;
}
|
split out bind address and port
|
split out bind address and port
We always want the endpoint to be tcp for the stream semantics, so formulate
the endpoint from the equivalent of "tcp://%s:%d"
|
C++
|
apache-2.0
|
puppetlabs/mc0d,puppetlabs/mc0d
|
019c5a0c35da934359c27b5efd5299db21cd3605
|
chromium_src/chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.cc
|
chromium_src/chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.cc
|
// Copyright 2016 The Brave Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is meant to override chrome_extensions_dispatch_delegate to provide
// alternate functionality for Brave. It is not a copy and there are significant
// change from Chrome
#include "chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.h"
#include <set>
#include <string>
#include "atom/common/javascript_bindings.h"
#include "atom/grit/atom_resources.h" // NOLINT: This file is generated
#include "atom/grit/electron_api_resources.h" // NOLINT: This file is generated
#include "base/win/windows_version.h"
#include "brave/common/extensions/url_bindings.h"
#include "brave/grit/brave_resources.h" // NOLINT: This file is generated
#include "brave/renderer/extensions/content_settings_bindings.h"
#include "brave/renderer/extensions/web_frame_bindings.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/crash_keys.h"
#include "chrome/grit/renderer_resources.h" // NOLINT: This file is generated
#include "content/public/common/bindings_policy.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "extensions/common/extension.h"
#include "extensions/renderer/css_native_handler.h"
#include "extensions/renderer/i18n_custom_bindings.h"
#include "extensions/renderer/lazy_background_page_native_handler.h"
#include "extensions/renderer/resource_bundle_source_map.h"
#include "extensions/renderer/v8_helpers.h"
#include "gin/converter.h"
#include "vendor/node/src/node_version.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
using extensions::Manifest;
using extensions::NativeHandler;
using extensions::ScriptContext;
using extensions::v8_helpers::ToV8StringUnsafe;
namespace {
#if defined(OS_MACOSX)
const char* kPlatform = "darwin";
#elif defined(OS_LINUX)
const char* kPlatform = "linux";
#elif defined(OS_WIN)
const char* kPlatform = "win32";
#else
const char* kPlatform = "unknown";
#endif
v8::Local<v8::Value> GetOrCreateProcess(ScriptContext* context) {
v8::Local<v8::String> process_string(
v8::String::NewFromUtf8(context->isolate(), "process"));
v8::Local<v8::Object> global(context->v8_context()->Global());
v8::Local<v8::Value> process(global->Get(process_string));
if (process->IsUndefined()) {
process = v8::Object::New(context->isolate());
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "type"),
ToV8StringUnsafe(context->isolate(), "renderer"));
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "version"),
ToV8StringUnsafe(context->isolate(), NODE_VERSION_STRING));
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "platform"),
ToV8StringUnsafe(context->isolate(), kPlatform));
#if defined(OS_WIN)
switch (base::win::GetVersion()) {
case base::win::VERSION_WIN7:
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "platformVersion"),
ToV8StringUnsafe(context->isolate(), "win7"));
break;
case base::win::VERSION_WIN8:
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "platformVersion"),
ToV8StringUnsafe(context->isolate(), "win8"));
break;
case base::win::VERSION_WIN8_1:
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "platformVersion"),
ToV8StringUnsafe(context->isolate(), "win8_1"));
break;
case base::win::VERSION_WIN10:
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "platformVersion"),
ToV8StringUnsafe(context->isolate(), "win10"));
break;
case base::win::VERSION_WIN10_TH2:
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "platformVersion"),
ToV8StringUnsafe(context->isolate(), "win10_th2"));
break;
default:
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "platformVersion"),
ToV8StringUnsafe(context->isolate(), ""));
break;
}
#else
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "platformVersion"),
ToV8StringUnsafe(context->isolate(), ""));
#endif
// TODO(bridiver) - add a function to return env vars
// std::unique_ptr<base::Environment> env(base::Environment::Create());
// gin::SetProperty(context->isolate(), process.As<v8::Object>(),
// ToV8StringUnsafe(context->isolate(), "env"),
// ToV8StringUnsafe(context->isolate(), "TODO"));
global->Set(process_string, process);
}
return process;
}
// Returns |value| cast to an object if possible, else an empty handle.
v8::Local<v8::Object> AsObjectOrEmpty(v8::Local<v8::Value> value) {
return value->IsObject() ? value.As<v8::Object>() : v8::Local<v8::Object>();
}
}
ChromeExtensionsDispatcherDelegate::ChromeExtensionsDispatcherDelegate() {
}
ChromeExtensionsDispatcherDelegate::~ChromeExtensionsDispatcherDelegate() {
}
void ChromeExtensionsDispatcherDelegate::InitOriginPermissions(
const extensions::Extension* extension,
bool is_extension_active) {
}
void ChromeExtensionsDispatcherDelegate::RegisterNativeHandlers(
extensions::Dispatcher* dispatcher,
extensions::ModuleSystem* module_system,
extensions::ScriptContext* context) {
module_system->RegisterNativeHandler(
"atom",
std::unique_ptr<NativeHandler>(
new atom::JavascriptBindings(
context->GetRenderFrame()->GetRenderView(), context)));
module_system->RegisterNativeHandler(
"contentSettings",
std::unique_ptr<NativeHandler>(
new brave::ContentSettingsBindings(context)));
module_system->RegisterNativeHandler(
"webFrame",
std::unique_ptr<NativeHandler>(
new brave::WebFrameBindings(context)));
// The following are native handlers that are defined in //extensions, but
// are only used for APIs defined in Chrome.
// See chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.cc
module_system->RegisterNativeHandler(
"i18n", std::unique_ptr<NativeHandler>(
new extensions::I18NCustomBindings(context)));
module_system->RegisterNativeHandler(
"lazy_background_page",
std::unique_ptr<NativeHandler>(
new extensions::LazyBackgroundPageNativeHandler(context)));
module_system->RegisterNativeHandler(
"css_natives", std::unique_ptr<NativeHandler>(
new extensions::CssNativeHandler(context)));
}
void ChromeExtensionsDispatcherDelegate::PopulateSourceMap(
extensions::ResourceBundleSourceMap* source_map) {
// TODO(bridiver) - add a permission for these
// so only component extensions can use
// blessed extension??
source_map->RegisterSource("event_emitter", IDR_ATOM_EVENT_EMITTER_JS);
source_map->RegisterSource("ipcRenderer", IDR_BRAVE_IPC_RENDERER_JS);
source_map->RegisterSource("ipc_utils", IDR_ATOM_IPC_INTERNAL_JS);
source_map->RegisterSource("webFrame",
IDR_ATOM_WEB_FRAME_BINDINGS_JS);
source_map->RegisterSource("remote",
IDR_ELECTRON_REMOTE_BINDINGS_JS);
source_map->RegisterSource("buffer",
IDR_ELECTRON_BUFFER_BINDINGS_JS);
source_map->RegisterSource("is-promise",
IDR_ELECTRON_IS_PROMISE_BINDINGS_JS);
source_map->RegisterSource("callbacks-registry",
IDR_ELECTRON_CALLBACKS_REGISTRY_BINDINGS_JS);
source_map->RegisterSource("guest-view-internal",
IDR_ELECTRON_GUEST_VIEW_INTERNAL_BINDINGS_JS);
source_map->RegisterSource("browserAction",
IDR_ATOM_BROWSER_ACTION_BINDINGS_JS);
source_map->RegisterSource("permissions", IDR_ATOM_PERMISSIONS_BINDINGS_JS);
source_map->RegisterSource("privacy", IDR_ATOM_PRIVACY_BINDINGS_JS);
source_map->RegisterSource("tabs",
IDR_ATOM_TABS_BINDINGS_JS);
source_map->RegisterSource("contextMenus",
IDR_ATOM_CONTEXT_MENUS_BINDINGS_JS);
source_map->RegisterSource("contentSettings",
IDR_ATOM_CONTENT_SETTINGS_BINDINGS_JS);
source_map->RegisterSource("windows",
IDR_ATOM_WINDOWS_BINDINGS_JS);
source_map->RegisterSource("cookies",
IDR_ATOM_COOKIES_BINDINGS_JS);
source_map->RegisterSource("ChromeSetting", IDR_CHROME_SETTING_JS);
source_map->RegisterSource("ContentSetting", IDR_CONTENT_SETTING_JS);
source_map->RegisterSource("ChromeDirectSetting",
IDR_CHROME_DIRECT_SETTING_JS);
source_map->RegisterSource("webViewInternal",
IDR_ATOM_WEB_VIEW_INTERNAL_BINDINGS_JS);
source_map->RegisterSource("tabViewInternal",
IDR_ATOM_TAB_VIEW_INTERNAL_BINDINGS_JS);
source_map->RegisterSource("webViewApiMethods",
IDR_ATOM_WEB_VIEW_API_BINDINGS_JS);
source_map->RegisterSource("webViewEventsApiMethods",
IDR_ATOM_WEB_VIEW_EVENTS_API_BINDINGS_JS);
source_map->RegisterSource("guestViewApiMethods",
IDR_ATOM_GUEST_VIEW_API_BINDINGS_JS);
}
void ChromeExtensionsDispatcherDelegate::RequireAdditionalModules(
extensions::ScriptContext* context) {
extensions::ModuleSystem* module_system = context->module_system();
extensions::Feature::Context context_type = context->context_type();
if (context_type == extensions::Feature::WEBUI_CONTEXT) {
module_system->Require("webView");
module_system->Require("tabViewInternal");
module_system->Require("webViewInternal");
module_system->Require("webViewApiMethods");
module_system->Require("webViewAttributes");
module_system->Require("webViewEventsApiMethods");
module_system->Require("guestViewApiMethods");
}
if (context_type == extensions::Feature::WEBUI_CONTEXT ||
(context->extension() && context->extension()->is_extension() &&
Manifest::IsComponentLocation(context->extension()->location()))) {
v8::Local<v8::Object> process =
AsObjectOrEmpty(GetOrCreateProcess(context));
v8::Local<v8::Object> global = context->v8_context()->Global();
v8::Local<v8::Object> muon = v8::Object::New(context->isolate());
global->Set(v8::String::NewFromUtf8(context->isolate(), "muon"), muon);
v8::Local<v8::Object> url =
brave::URLBindings::API(context);
muon->Set(v8::String::NewFromUtf8(context->isolate(), "url"), url);
}
}
void ChromeExtensionsDispatcherDelegate::OnActiveExtensionsUpdated(
const std::set<std::string>& extension_ids) {
crash_keys::SetActiveExtensions(extension_ids);
}
|
// Copyright 2016 The Brave Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is meant to override chrome_extensions_dispatch_delegate to provide
// alternate functionality for Brave. It is not a copy and there are significant
// change from Chrome
#include "chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.h"
#include <set>
#include <string>
#include "atom/common/javascript_bindings.h"
#include "atom/grit/atom_resources.h" // NOLINT: This file is generated
#include "atom/grit/electron_api_resources.h" // NOLINT: This file is generated
#include "base/win/windows_version.h"
#include "brave/common/extensions/url_bindings.h"
#include "brave/grit/brave_resources.h" // NOLINT: This file is generated
#include "brave/renderer/extensions/content_settings_bindings.h"
#include "brave/renderer/extensions/web_frame_bindings.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/crash_keys.h"
#include "chrome/grit/renderer_resources.h" // NOLINT: This file is generated
#include "content/public/common/bindings_policy.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "extensions/common/extension.h"
#include "extensions/renderer/css_native_handler.h"
#include "extensions/renderer/i18n_custom_bindings.h"
#include "extensions/renderer/lazy_background_page_native_handler.h"
#include "extensions/renderer/resource_bundle_source_map.h"
#include "extensions/renderer/v8_helpers.h"
#include "gin/converter.h"
#include "vendor/node/src/node_version.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
using extensions::Manifest;
using extensions::NativeHandler;
using extensions::ScriptContext;
using extensions::v8_helpers::ToV8StringUnsafe;
namespace {
#if defined(OS_MACOSX)
const char* kPlatform = "darwin";
#elif defined(OS_LINUX)
const char* kPlatform = "linux";
#elif defined(OS_WIN)
const char* kPlatform = "win32";
#else
const char* kPlatform = "unknown";
#endif
v8::Local<v8::Value> GetOrCreateProcess(ScriptContext* context) {
v8::Local<v8::String> process_string(
v8::String::NewFromUtf8(context->isolate(), "process"));
v8::Local<v8::Object> global(context->v8_context()->Global());
v8::Local<v8::Value> process(global->Get(process_string));
if (process->IsUndefined()) {
process = v8::Object::New(context->isolate());
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "type"),
ToV8StringUnsafe(context->isolate(), "renderer"));
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "version"),
ToV8StringUnsafe(context->isolate(), NODE_VERSION_STRING));
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "platform"),
ToV8StringUnsafe(context->isolate(), kPlatform));
#if defined(OS_WIN)
switch (base::win::GetVersion()) {
case base::win::VERSION_WIN7:
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "platformVersion"),
ToV8StringUnsafe(context->isolate(), "win7"));
break;
case base::win::VERSION_WIN8:
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "platformVersion"),
ToV8StringUnsafe(context->isolate(), "win8"));
break;
case base::win::VERSION_WIN8_1:
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "platformVersion"),
ToV8StringUnsafe(context->isolate(), "win8_1"));
break;
case base::win::VERSION_WIN10:
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "platformVersion"),
ToV8StringUnsafe(context->isolate(), "win10"));
break;
case base::win::VERSION_WIN10_TH2:
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "platformVersion"),
ToV8StringUnsafe(context->isolate(), "win10_th2"));
break;
default:
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "platformVersion"),
ToV8StringUnsafe(context->isolate(), ""));
break;
}
#else
gin::SetProperty(context->isolate(), process.As<v8::Object>(),
ToV8StringUnsafe(context->isolate(), "platformVersion"),
ToV8StringUnsafe(context->isolate(), ""));
#endif
// TODO(bridiver) - add a function to return env vars
// std::unique_ptr<base::Environment> env(base::Environment::Create());
// gin::SetProperty(context->isolate(), process.As<v8::Object>(),
// ToV8StringUnsafe(context->isolate(), "env"),
// ToV8StringUnsafe(context->isolate(), "TODO"));
global->Set(process_string, process);
}
return process;
}
// Returns |value| cast to an object if possible, else an empty handle.
v8::Local<v8::Object> AsObjectOrEmpty(v8::Local<v8::Value> value) {
return value->IsObject() ? value.As<v8::Object>() : v8::Local<v8::Object>();
}
}
ChromeExtensionsDispatcherDelegate::ChromeExtensionsDispatcherDelegate() {
}
ChromeExtensionsDispatcherDelegate::~ChromeExtensionsDispatcherDelegate() {
}
void ChromeExtensionsDispatcherDelegate::InitOriginPermissions(
const extensions::Extension* extension,
bool is_extension_active) {
}
void ChromeExtensionsDispatcherDelegate::RegisterNativeHandlers(
extensions::Dispatcher* dispatcher,
extensions::ModuleSystem* module_system,
extensions::ExtensionBindingsSystem* bindings_system,
extensions::ScriptContext* context) {
module_system->RegisterNativeHandler(
"atom",
std::unique_ptr<NativeHandler>(
new atom::JavascriptBindings(
context->GetRenderFrame()->GetRenderView(), context)));
module_system->RegisterNativeHandler(
"contentSettings",
std::unique_ptr<NativeHandler>(
new brave::ContentSettingsBindings(context)));
module_system->RegisterNativeHandler(
"webFrame",
std::unique_ptr<NativeHandler>(
new brave::WebFrameBindings(context)));
// The following are native handlers that are defined in //extensions, but
// are only used for APIs defined in Chrome.
// See chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.cc
module_system->RegisterNativeHandler(
"i18n", std::unique_ptr<NativeHandler>(
new extensions::I18NCustomBindings(context)));
module_system->RegisterNativeHandler(
"lazy_background_page",
std::unique_ptr<NativeHandler>(
new extensions::LazyBackgroundPageNativeHandler(context)));
module_system->RegisterNativeHandler(
"css_natives", std::unique_ptr<NativeHandler>(
new extensions::CssNativeHandler(context)));
}
void ChromeExtensionsDispatcherDelegate::PopulateSourceMap(
extensions::ResourceBundleSourceMap* source_map) {
// TODO(bridiver) - add a permission for these
// so only component extensions can use
// blessed extension??
source_map->RegisterSource("event_emitter", IDR_ATOM_EVENT_EMITTER_JS);
source_map->RegisterSource("ipcRenderer", IDR_BRAVE_IPC_RENDERER_JS);
source_map->RegisterSource("ipc_utils", IDR_ATOM_IPC_INTERNAL_JS);
source_map->RegisterSource("webFrame",
IDR_ATOM_WEB_FRAME_BINDINGS_JS);
source_map->RegisterSource("remote",
IDR_ELECTRON_REMOTE_BINDINGS_JS);
source_map->RegisterSource("buffer",
IDR_ELECTRON_BUFFER_BINDINGS_JS);
source_map->RegisterSource("is-promise",
IDR_ELECTRON_IS_PROMISE_BINDINGS_JS);
source_map->RegisterSource("callbacks-registry",
IDR_ELECTRON_CALLBACKS_REGISTRY_BINDINGS_JS);
source_map->RegisterSource("guest-view-internal",
IDR_ELECTRON_GUEST_VIEW_INTERNAL_BINDINGS_JS);
source_map->RegisterSource("browserAction",
IDR_ATOM_BROWSER_ACTION_BINDINGS_JS);
source_map->RegisterSource("permissions", IDR_ATOM_PERMISSIONS_BINDINGS_JS);
source_map->RegisterSource("privacy", IDR_ATOM_PRIVACY_BINDINGS_JS);
source_map->RegisterSource("tabs",
IDR_ATOM_TABS_BINDINGS_JS);
source_map->RegisterSource("contextMenus",
IDR_ATOM_CONTEXT_MENUS_BINDINGS_JS);
source_map->RegisterSource("contentSettings",
IDR_ATOM_CONTENT_SETTINGS_BINDINGS_JS);
source_map->RegisterSource("windows",
IDR_ATOM_WINDOWS_BINDINGS_JS);
source_map->RegisterSource("cookies",
IDR_ATOM_COOKIES_BINDINGS_JS);
source_map->RegisterSource("ChromeSetting", IDR_CHROME_SETTING_JS);
source_map->RegisterSource("ContentSetting", IDR_CONTENT_SETTING_JS);
source_map->RegisterSource("ChromeDirectSetting",
IDR_CHROME_DIRECT_SETTING_JS);
source_map->RegisterSource("webViewInternal",
IDR_ATOM_WEB_VIEW_INTERNAL_BINDINGS_JS);
source_map->RegisterSource("tabViewInternal",
IDR_ATOM_TAB_VIEW_INTERNAL_BINDINGS_JS);
source_map->RegisterSource("webViewApiMethods",
IDR_ATOM_WEB_VIEW_API_BINDINGS_JS);
source_map->RegisterSource("webViewEventsApiMethods",
IDR_ATOM_WEB_VIEW_EVENTS_API_BINDINGS_JS);
source_map->RegisterSource("guestViewApiMethods",
IDR_ATOM_GUEST_VIEW_API_BINDINGS_JS);
}
void ChromeExtensionsDispatcherDelegate::RequireAdditionalModules(
extensions::ScriptContext* context) {
extensions::ModuleSystem* module_system = context->module_system();
extensions::Feature::Context context_type = context->context_type();
if (context_type == extensions::Feature::WEBUI_CONTEXT) {
module_system->Require("webView");
module_system->Require("tabViewInternal");
module_system->Require("webViewInternal");
module_system->Require("webViewApiMethods");
module_system->Require("webViewAttributes");
module_system->Require("webViewEventsApiMethods");
module_system->Require("guestViewApiMethods");
}
if (context_type == extensions::Feature::WEBUI_CONTEXT ||
(context->extension() && context->extension()->is_extension() &&
Manifest::IsComponentLocation(context->extension()->location()))) {
v8::Local<v8::Object> process =
AsObjectOrEmpty(GetOrCreateProcess(context));
v8::Local<v8::Object> global = context->v8_context()->Global();
v8::Local<v8::Object> muon = v8::Object::New(context->isolate());
global->Set(v8::String::NewFromUtf8(context->isolate(), "muon"), muon);
v8::Local<v8::Object> url =
brave::URLBindings::API(context);
muon->Set(v8::String::NewFromUtf8(context->isolate(), "url"), url);
}
}
void ChromeExtensionsDispatcherDelegate::OnActiveExtensionsUpdated(
const std::set<std::string>& extension_ids) {
crash_keys::SetActiveExtensions(extension_ids);
}
|
Fix signature of RegisterNativeHandlers
|
Fix signature of RegisterNativeHandlers
|
C++
|
mit
|
brave/electron,brave/electron,brave/muon,brave/muon,brave/electron,brave/electron,brave/muon,brave/muon,brave/muon,brave/electron,brave/muon,brave/electron
|
2a8167bca2d2c6252b7753ccc552a4b9e71e8b5c
|
test/itkHessianImageFilterTest.cxx
|
test/itkHessianImageFilterTest.cxx
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkHessianImageFilter.h"
#include "itkGaussianImageSource.h"
#include "itkImageFileReader.h"
int itkHessianImageFilterTest( int , char *[] )
{
const unsigned int Dimension = 3;
typedef itk::Image< float, Dimension > ImageType;
const unsigned int imageSize = 64;
ImageType::SizeType size;
size.Fill( imageSize );
ImageType::SpacingType spacing;
spacing.Fill( 1.0 );
spacing[0] = 1.0;
typedef itk::GaussianImageSource<ImageType> GaussianSourceType;
GaussianSourceType::Pointer gaussianSource = GaussianSourceType::New();
gaussianSource->SetSize( size );
gaussianSource->SetSpacing( spacing );
gaussianSource->SetMean( itk::FixedArray< double, Dimension>( imageSize/2 ) );
gaussianSource->SetSigma( itk::FixedArray< double, Dimension>( 10.0 ) );
gaussianSource->SetNormalized( false );
gaussianSource->SetScale( 1.0 ); // dark blob
typedef itk::HessianImageFilter< ImageType > HessianFilterType;
HessianFilterType::Pointer hessian = HessianFilterType::New();
hessian->SetInput( gaussianSource->GetOutput() );
hessian->Update();
HessianFilterType:: OutputPixelType H;
ImageType::IndexType idx;
idx.Fill( imageSize/2 );
H = hessian->GetOutput()->GetPixel( idx );
--idx[0];
std::cout << hessian->GetOutput()->GetPixel( idx ) << std::endl ;
--idx[1];
std::cout << hessian->GetOutput()->GetPixel( idx ) << std::endl;
return 0;
}
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkHessianImageFilter.h"
#include "itkGaussianImageSource.h"
#include "itkImageFileReader.h"
int itkHessianImageFilterTest( int , char *[] )
{
const unsigned int Dimension = 3;
typedef itk::Image< float, Dimension > ImageType;
const unsigned int imageSize = 64;
ImageType::SizeType size;
size.Fill( imageSize );
ImageType::SpacingType spacing;
spacing.Fill( 1.0 );
spacing[0] = 1.0;
typedef itk::GaussianImageSource<ImageType> GaussianSourceType;
GaussianSourceType::Pointer gaussianSource = GaussianSourceType::New();
gaussianSource->SetSize( size );
gaussianSource->SetSpacing( spacing );
gaussianSource->SetMean( itk::FixedArray< double, Dimension>( imageSize/2 ) );
gaussianSource->SetSigma( itk::FixedArray< double, Dimension>( 10.0 ) );
gaussianSource->SetNormalized( false );
gaussianSource->SetScale( 1.0 ); // dark blob
typedef itk::HessianImageFilter< ImageType > HessianFilterType;
HessianFilterType::Pointer hessian = HessianFilterType::New();
hessian->SetInput( gaussianSource->GetOutput() );
hessian->Update();
HessianFilterType:: OutputPixelType H;
ImageType::IndexType idx;
idx.Fill( imageSize/2 );
H = hessian->GetOutput()->GetPixel( idx );
--idx[0];
std::cout << hessian->GetOutput()->GetPixel( idx ) << std::endl;
--idx[1];
std::cout << hessian->GetOutput()->GetPixel( idx ) << std::endl;
return 0;
}
|
fix style with erroneous space before ;
|
fix style with erroneous space before ;
|
C++
|
apache-2.0
|
SimpleITK/itkSimpleITKFiltersModule,SimpleITK/itkSimpleITKFiltersModule
|
8faed13a4dd27fd9181d0e606fe7ff64b27dae65
|
moveit_ros/move_group/src/default_capabilities/kinematics_service_capability.cpp
|
moveit_ros/move_group/src/default_capabilities/kinematics_service_capability.cpp
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage 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: Ioan Sucan */
#include "kinematics_service_capability.h"
#include <moveit/robot_state/conversions.h>
#include <moveit/utils/message_checks.h>
#include <tf2_eigen/tf2_eigen.h>
#include <moveit/move_group/capability_names.h>
namespace move_group
{
MoveGroupKinematicsService::MoveGroupKinematicsService() : MoveGroupCapability("KinematicsService")
{
}
void MoveGroupKinematicsService::initialize()
{
fk_service_ =
root_node_handle_.advertiseService(FK_SERVICE_NAME, &MoveGroupKinematicsService::computeFKService, this);
ik_service_ =
root_node_handle_.advertiseService(IK_SERVICE_NAME, &MoveGroupKinematicsService::computeIKService, this);
}
namespace
{
bool isIKSolutionValid(const planning_scene::PlanningScene* planning_scene,
const kinematic_constraints::KinematicConstraintSet* constraint_set,
moveit::core::RobotState* state, const moveit::core::JointModelGroup* jmg,
const double* ik_solution)
{
state->setJointGroupPositions(jmg, ik_solution);
state->update();
return (!planning_scene || !planning_scene->isStateColliding(*state, jmg->getName())) &&
(!constraint_set || constraint_set->decide(*state).satisfied);
}
} // namespace
void MoveGroupKinematicsService::computeIK(moveit_msgs::PositionIKRequest& req, moveit_msgs::RobotState& solution,
moveit_msgs::MoveItErrorCodes& error_code, moveit::core::RobotState& rs,
const moveit::core::GroupStateValidityCallbackFn& constraint) const
{
const moveit::core::JointModelGroup* jmg = rs.getJointModelGroup(req.group_name);
if (jmg)
{
moveit::core::robotStateMsgToRobotState(req.robot_state, rs);
const std::string& default_frame = context_->planning_scene_monitor_->getRobotModel()->getModelFrame();
if (req.pose_stamped_vector.empty() || req.pose_stamped_vector.size() == 1)
{
geometry_msgs::PoseStamped req_pose =
req.pose_stamped_vector.empty() ? req.pose_stamped : req.pose_stamped_vector[0];
std::string ik_link = (!req.pose_stamped_vector.empty()) ?
(req.ik_link_names.empty() ? "" : req.ik_link_names[0]) :
req.ik_link_name;
if (performTransform(req_pose, default_frame))
{
bool result_ik = false;
if (ik_link.empty())
result_ik = rs.setFromIK(jmg, req_pose.pose, req.timeout.toSec(), constraint);
else
result_ik = rs.setFromIK(jmg, req_pose.pose, ik_link, req.timeout.toSec(), constraint);
if (result_ik)
{
moveit::core::robotStateToRobotStateMsg(rs, solution, false);
error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
}
else
error_code.val = moveit_msgs::MoveItErrorCodes::NO_IK_SOLUTION;
}
else
error_code.val = moveit_msgs::MoveItErrorCodes::FRAME_TRANSFORM_FAILURE;
}
else
{
if (req.pose_stamped_vector.size() != req.ik_link_names.size())
error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_LINK_NAME;
else
{
bool ok = true;
EigenSTL::vector_Isometry3d req_poses(req.pose_stamped_vector.size());
for (std::size_t k = 0; k < req.pose_stamped_vector.size(); ++k)
{
geometry_msgs::PoseStamped msg = req.pose_stamped_vector[k];
if (performTransform(msg, default_frame))
tf2::fromMsg(msg.pose, req_poses[k]);
else
{
error_code.val = moveit_msgs::MoveItErrorCodes::FRAME_TRANSFORM_FAILURE;
ok = false;
break;
}
}
if (ok)
{
if (rs.setFromIK(jmg, req_poses, req.ik_link_names, req.timeout.toSec(), constraint))
{
moveit::core::robotStateToRobotStateMsg(rs, solution, false);
error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
}
else
error_code.val = moveit_msgs::MoveItErrorCodes::NO_IK_SOLUTION;
}
}
}
}
else
error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_GROUP_NAME;
}
bool MoveGroupKinematicsService::computeIKService(moveit_msgs::GetPositionIK::Request& req,
moveit_msgs::GetPositionIK::Response& res)
{
context_->planning_scene_monitor_->updateFrameTransforms();
// check if the planning scene needs to be kept locked; if so, call computeIK() in the scope of the lock
if (req.ik_request.avoid_collisions || !moveit::core::isEmpty(req.ik_request.constraints))
{
planning_scene_monitor::LockedPlanningSceneRO ls(context_->planning_scene_monitor_);
kinematic_constraints::KinematicConstraintSet kset(ls->getRobotModel());
moveit::core::RobotState rs = ls->getCurrentState();
kset.add(req.ik_request.constraints, ls->getTransforms());
computeIK(req.ik_request, res.solution, res.error_code, rs,
boost::bind(&isIKSolutionValid,
req.ik_request.avoid_collisions ?
static_cast<const planning_scene::PlanningSceneConstPtr&>(ls).get() :
nullptr,
kset.empty() ? nullptr : &kset, _1, _2, _3));
}
else
{
// compute unconstrained IK, no lock to planning scene maintained
moveit::core::RobotState rs =
planning_scene_monitor::LockedPlanningSceneRO(context_->planning_scene_monitor_)->getCurrentState();
computeIK(req.ik_request, res.solution, res.error_code, rs);
}
return true;
}
bool MoveGroupKinematicsService::computeFKService(moveit_msgs::GetPositionFK::Request& req,
moveit_msgs::GetPositionFK::Response& res)
{
if (req.fk_link_names.empty())
{
ROS_ERROR_NAMED(getName(), "No links specified for FK request");
res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_LINK_NAME;
return true;
}
context_->planning_scene_monitor_->updateFrameTransforms();
const std::string& default_frame = context_->planning_scene_monitor_->getRobotModel()->getModelFrame();
bool do_transform = !req.header.frame_id.empty() &&
!moveit::core::Transforms::sameFrame(req.header.frame_id, default_frame) &&
context_->planning_scene_monitor_->getTFClient();
bool tf_problem = false;
moveit::core::RobotState rs =
planning_scene_monitor::LockedPlanningSceneRO(context_->planning_scene_monitor_)->getCurrentState();
moveit::core::robotStateMsgToRobotState(req.robot_state, rs);
for (std::size_t i = 0; i < req.fk_link_names.size(); ++i)
if (rs.getRobotModel()->hasLinkModel(req.fk_link_names[i]))
{
res.pose_stamped.resize(res.pose_stamped.size() + 1);
res.pose_stamped.back().pose = tf2::toMsg(rs.getGlobalLinkTransform(req.fk_link_names[i]));
res.pose_stamped.back().header.frame_id = default_frame;
res.pose_stamped.back().header.stamp = ros::Time::now();
if (do_transform)
if (!performTransform(res.pose_stamped.back(), req.header.frame_id))
tf_problem = true;
res.fk_link_names.push_back(req.fk_link_names[i]);
}
if (tf_problem)
res.error_code.val = moveit_msgs::MoveItErrorCodes::FRAME_TRANSFORM_FAILURE;
else if (res.fk_link_names.size() == req.fk_link_names.size())
res.error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
else
res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_LINK_NAME;
return true;
}
} // namespace move_group
#include <class_loader/class_loader.hpp>
CLASS_LOADER_REGISTER_CLASS(move_group::MoveGroupKinematicsService, move_group::MoveGroupCapability)
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage 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: Ioan Sucan */
#include "kinematics_service_capability.h"
#include <moveit/robot_state/conversions.h>
#include <moveit/utils/message_checks.h>
#include <tf2_eigen/tf2_eigen.h>
#include <moveit/move_group/capability_names.h>
namespace move_group
{
MoveGroupKinematicsService::MoveGroupKinematicsService() : MoveGroupCapability("KinematicsService")
{
}
void MoveGroupKinematicsService::initialize()
{
fk_service_ =
root_node_handle_.advertiseService(FK_SERVICE_NAME, &MoveGroupKinematicsService::computeFKService, this);
ik_service_ =
root_node_handle_.advertiseService(IK_SERVICE_NAME, &MoveGroupKinematicsService::computeIKService, this);
}
namespace
{
bool isIKSolutionValid(const planning_scene::PlanningScene* planning_scene,
const kinematic_constraints::KinematicConstraintSet* constraint_set,
moveit::core::RobotState* state, const moveit::core::JointModelGroup* jmg,
const double* ik_solution)
{
state->setJointGroupPositions(jmg, ik_solution);
state->update();
return (!planning_scene || !planning_scene->isStateColliding(*state, jmg->getName())) &&
(!constraint_set || constraint_set->decide(*state).satisfied);
}
} // namespace
void MoveGroupKinematicsService::computeIK(moveit_msgs::PositionIKRequest& req, moveit_msgs::RobotState& solution,
moveit_msgs::MoveItErrorCodes& error_code, moveit::core::RobotState& rs,
const moveit::core::GroupStateValidityCallbackFn& constraint) const
{
const moveit::core::JointModelGroup* jmg = rs.getJointModelGroup(req.group_name);
if (jmg)
{
if (!moveit::core::isEmpty(req.robot_state))
{
moveit::core::robotStateMsgToRobotState(req.robot_state, rs);
}
const std::string& default_frame = context_->planning_scene_monitor_->getRobotModel()->getModelFrame();
if (req.pose_stamped_vector.empty() || req.pose_stamped_vector.size() == 1)
{
geometry_msgs::PoseStamped req_pose =
req.pose_stamped_vector.empty() ? req.pose_stamped : req.pose_stamped_vector[0];
std::string ik_link = (!req.pose_stamped_vector.empty()) ?
(req.ik_link_names.empty() ? "" : req.ik_link_names[0]) :
req.ik_link_name;
if (performTransform(req_pose, default_frame))
{
bool result_ik = false;
if (ik_link.empty())
result_ik = rs.setFromIK(jmg, req_pose.pose, req.timeout.toSec(), constraint);
else
result_ik = rs.setFromIK(jmg, req_pose.pose, ik_link, req.timeout.toSec(), constraint);
if (result_ik)
{
moveit::core::robotStateToRobotStateMsg(rs, solution, false);
error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
}
else
error_code.val = moveit_msgs::MoveItErrorCodes::NO_IK_SOLUTION;
}
else
error_code.val = moveit_msgs::MoveItErrorCodes::FRAME_TRANSFORM_FAILURE;
}
else
{
if (req.pose_stamped_vector.size() != req.ik_link_names.size())
error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_LINK_NAME;
else
{
bool ok = true;
EigenSTL::vector_Isometry3d req_poses(req.pose_stamped_vector.size());
for (std::size_t k = 0; k < req.pose_stamped_vector.size(); ++k)
{
geometry_msgs::PoseStamped msg = req.pose_stamped_vector[k];
if (performTransform(msg, default_frame))
tf2::fromMsg(msg.pose, req_poses[k]);
else
{
error_code.val = moveit_msgs::MoveItErrorCodes::FRAME_TRANSFORM_FAILURE;
ok = false;
break;
}
}
if (ok)
{
if (rs.setFromIK(jmg, req_poses, req.ik_link_names, req.timeout.toSec(), constraint))
{
moveit::core::robotStateToRobotStateMsg(rs, solution, false);
error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
}
else
error_code.val = moveit_msgs::MoveItErrorCodes::NO_IK_SOLUTION;
}
}
}
}
else
error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_GROUP_NAME;
}
bool MoveGroupKinematicsService::computeIKService(moveit_msgs::GetPositionIK::Request& req,
moveit_msgs::GetPositionIK::Response& res)
{
context_->planning_scene_monitor_->updateFrameTransforms();
// check if the planning scene needs to be kept locked; if so, call computeIK() in the scope of the lock
if (req.ik_request.avoid_collisions || !moveit::core::isEmpty(req.ik_request.constraints))
{
planning_scene_monitor::LockedPlanningSceneRO ls(context_->planning_scene_monitor_);
kinematic_constraints::KinematicConstraintSet kset(ls->getRobotModel());
moveit::core::RobotState rs = ls->getCurrentState();
kset.add(req.ik_request.constraints, ls->getTransforms());
computeIK(req.ik_request, res.solution, res.error_code, rs,
boost::bind(&isIKSolutionValid,
req.ik_request.avoid_collisions ?
static_cast<const planning_scene::PlanningSceneConstPtr&>(ls).get() :
nullptr,
kset.empty() ? nullptr : &kset, _1, _2, _3));
}
else
{
// compute unconstrained IK, no lock to planning scene maintained
moveit::core::RobotState rs =
planning_scene_monitor::LockedPlanningSceneRO(context_->planning_scene_monitor_)->getCurrentState();
computeIK(req.ik_request, res.solution, res.error_code, rs);
}
return true;
}
bool MoveGroupKinematicsService::computeFKService(moveit_msgs::GetPositionFK::Request& req,
moveit_msgs::GetPositionFK::Response& res)
{
if (req.fk_link_names.empty())
{
ROS_ERROR_NAMED(getName(), "No links specified for FK request");
res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_LINK_NAME;
return true;
}
context_->planning_scene_monitor_->updateFrameTransforms();
const std::string& default_frame = context_->planning_scene_monitor_->getRobotModel()->getModelFrame();
bool do_transform = !req.header.frame_id.empty() &&
!moveit::core::Transforms::sameFrame(req.header.frame_id, default_frame) &&
context_->planning_scene_monitor_->getTFClient();
bool tf_problem = false;
moveit::core::RobotState rs =
planning_scene_monitor::LockedPlanningSceneRO(context_->planning_scene_monitor_)->getCurrentState();
moveit::core::robotStateMsgToRobotState(req.robot_state, rs);
for (std::size_t i = 0; i < req.fk_link_names.size(); ++i)
if (rs.getRobotModel()->hasLinkModel(req.fk_link_names[i]))
{
res.pose_stamped.resize(res.pose_stamped.size() + 1);
res.pose_stamped.back().pose = tf2::toMsg(rs.getGlobalLinkTransform(req.fk_link_names[i]));
res.pose_stamped.back().header.frame_id = default_frame;
res.pose_stamped.back().header.stamp = ros::Time::now();
if (do_transform)
if (!performTransform(res.pose_stamped.back(), req.header.frame_id))
tf_problem = true;
res.fk_link_names.push_back(req.fk_link_names[i]);
}
if (tf_problem)
res.error_code.val = moveit_msgs::MoveItErrorCodes::FRAME_TRANSFORM_FAILURE;
else if (res.fk_link_names.size() == req.fk_link_names.size())
res.error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
else
res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_LINK_NAME;
return true;
}
} // namespace move_group
#include <class_loader/class_loader.hpp>
CLASS_LOADER_REGISTER_CLASS(move_group::MoveGroupKinematicsService, move_group::MoveGroupCapability)
|
Fix missing isEmpty check in compute_ik service (#2544)
|
Fix missing isEmpty check in compute_ik service (#2544)
|
C++
|
bsd-3-clause
|
ros-planning/moveit,ros-planning/moveit,ros-planning/moveit,ros-planning/moveit,ros-planning/moveit
|
3294d7cfd6b58963dd949c2eaa261d7d1584a256
|
MarsLander/main.cpp
|
MarsLander/main.cpp
|
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int surfaceN; // the number of points used to draw the surface of Mars.
cin >> surfaceN; cin.ignore();
for (int i = 0; i < surfaceN; i++) {
int landX; // X coordinate of a surface point. (0 to 6999)
int landY; // Y coordinate of a surface point. By linking all the points together in a sequential fashion, you form the surface of Mars.
cin >> landX >> landY; cin.ignore();
}
// game loop
while (1) {
int X;
int Y;
int hSpeed; // the horizontal speed (in m/s), can be negative.
int vSpeed; // the vertical speed (in m/s), can be negative.
int fuel; // the quantity of remaining fuel in liters.
int rotate; // the rotation angle in degrees (-90 to 90).
int power; // the thrust power (0 to 4).
cin >> X >> Y >> hSpeed >> vSpeed >> fuel >> rotate >> power; cin.ignore();
// Write an action using cout. DON'T FORGET THE "<< endl"
// To debug: cerr << "Debug messages..." << endl;
// 2 integers: rotate power. rotate is the desired rotation angle (should be 0 for level 1), power is the desired thrust power (0 to 4).
cout << "0 3" << endl;
}
}
|
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
class SurfaceMngr {
public:
class Surface {
public:
int x;
int y;
};
SurfaceMngr(int nbSurfaces) : _nbSurfaces(nbSurfaces) {
_surfaces = new Surface[_nbSurfaces];
}
virtual ~SurfaceMngr() {
delete[] _surfaces;
}
Surface& operator[](int index) {
return _surfaces[index];
}
int groundAltitude(int x) {
if(!_nbSurfaces) return -1;
Surface& previousSurface = _surfaces[0];
for(int index = 1; index < _nbSurfaces; ++index) {
if(x >= previousSurface.x && x<= _surfaces[index].x ) {
int y1 = previousSurface.y;
int y2 = _surfaces[index].y;
int x1 = previousSurface.x;
int x2 = _surfaces[index].x;
return y1+((y2-y1)/(x2-x1));
}
previousSurface = _surfaces[index];
}
}
private:
int _nbSurfaces;
Surface* _surfaces;
};
int main()
{
const int maxVSpeed(40);
const int altitudePonderation(100);
int surfaceN; // the number of points used to draw the surface of Mars.
cin >> surfaceN; cin.ignore();
SurfaceMngr surfaceMngr(surfaceN);
for (int i = 0; i < surfaceN; i++) {
int landX; // X coordinate of a surface point. (0 to 6999)
int landY; // Y coordinate of a surface point. By linking all the points together in a sequential fashion, you form the surface of Mars.
cin >> landX >> landY; cin.ignore();
surfaceMngr[i].x = landX;
surfaceMngr[i].y = landY;
}
// game loop
while (1) {
int X;
int Y;
int hSpeed; // the horizontal speed (in m/s), can be negative.
int vSpeed; // the vertical speed (in m/s), can be negative.
int fuel; // the quantity of remaining fuel in liters.
int rotate; // the rotation angle in degrees (-90 to 90).
int power; // the thrust power (0 to 4).
cin >> X >> Y >> hSpeed >> vSpeed >> fuel >> rotate >> power; cin.ignore();
int groundAltitude = surfaceMngr.groundAltitude(X);
cerr << "Ground alt : " << groundAltitude << endl;
int deltaAlt = Y - groundAltitude;
int deltaVSpeedPonderateWithAlt = (maxVSpeed + vSpeed) * (deltaAlt / altitudePonderation);
int newPower = 4 - min(4, max(deltaVSpeedPonderateWithAlt, 0));
// 2 integers: rotate power. rotate is the desired rotation angle (should be 0 for level 1), power is the desired thrust power (0 to 4).
cout << "0 "<< newPower << endl;
}
}
|
add MarsLander
|
add MarsLander
|
C++
|
apache-2.0
|
pbouamriou/CodinGame
|
2bfc6abbd42cb77f416beb600f38e20cfe9f1cfe
|
unicorn/regex.hpp
|
unicorn/regex.hpp
|
#pragma once
#include "unicorn/core.hpp"
#include "unicorn/utf.hpp"
#include <algorithm>
#include <functional>
#include <memory>
#include <stdexcept>
#include <type_traits>
#include <vector>
namespace RS::Unicorn {
// Forward declarations
class Match;
class MatchIterator;
class Regex;
class RegexFormat;
class SplitIterator;
using MatchRange = Irange<MatchIterator>;
using SplitRange = Irange<SplitIterator>;
namespace UnicornDetail {
// Reference counted PCRE handle
class PcreRef {
public:
PcreRef() noexcept: pc(nullptr), ex(nullptr) {}
PcreRef(void* p, void* x) noexcept: pc(p), ex(x) { inc(); }
PcreRef(const PcreRef& p) noexcept: pc(p.pc), ex(p.ex) { inc(); }
PcreRef(PcreRef&& p) noexcept: pc(p.pc), ex(p.ex) { p.pc = p.ex = nullptr; }
~PcreRef() noexcept { dec(); }
PcreRef& operator=(const PcreRef& p) noexcept { auto q(p); swap(q); return *this; }
PcreRef& operator=(PcreRef&& p) noexcept { auto q(p); swap(q); return *this; }
size_t count_groups() const noexcept;
void* get_pc_ptr() const noexcept { return pc; }
void* get_ex_ptr() const noexcept { return ex; }
size_t named_group(const Ustring& name) const noexcept;
void swap(PcreRef& p) noexcept { std::swap(pc, p.pc); std::swap(ex, p.ex); }
explicit operator bool() const noexcept { return pc; }
private:
void* pc;
void* ex;
void inc() noexcept;
void dec() noexcept;
};
}
// Exceptions
class RegexError:
public std::runtime_error {
public:
RegexError(int error, const Ustring& pattern, const Ustring& message = {});
int error() const noexcept { return err; }
const char* pattern() const noexcept { return pat->data(); }
private:
int err;
std::shared_ptr<Ustring> pat;
static Ustring assemble(int error, const Ustring& pattern, const Ustring& message);
static Ustring translate(int error);
};
// Regex match class
class Match {
public:
Ustring operator[](size_t i) const { return str(i); }
operator Ustring() const { return str(); }
explicit operator bool() const noexcept { return matched(); }
bool operator!() const noexcept { return ! matched(); }
size_t count(size_t i = 0) const noexcept { return is_group(i) ? ofs[2 * i + 1] - ofs[2 * i] : 0; }
bool empty() const noexcept { return ! *this || ofs[0] == ofs[1]; }
size_t endpos(size_t i = 0) const noexcept { return is_group(i) ? ofs[2 * i + 1] : npos; }
Ustring first() const;
Ustring last() const;
bool full_or_partial() const noexcept { return matched() || partial(); }
size_t groups() const noexcept { return std::max(status, 0); }
bool matched(size_t i = 0) const noexcept { return status >= 0 && (i == 0 || is_group(i)); }
Ustring named(const Ustring& name) const { return ref ? str(ref.named_group(name)) : Ustring(); }
size_t offset(size_t i = 0) const noexcept { return is_group(i) ? ofs[2 * i] : npos; }
bool partial() const noexcept { return status == -12; } // PCRE_ERROR_PARTIAL
Ustring::const_iterator s_begin(size_t i = 0) const noexcept;
Ustring::const_iterator s_end(size_t i = 0) const noexcept;
Irange<Ustring::const_iterator> s_range(size_t i = 0) const noexcept { return {s_begin(i), s_end(i)}; }
Ustring str(size_t i = 0) const;
void swap(Match& m) noexcept;
Utf8Iterator u_begin(size_t i = 0) const noexcept;
Utf8Iterator u_end(size_t i = 0) const noexcept;
Irange<Utf8Iterator> u_range(size_t i = 0) const noexcept { return {u_begin(i), u_end(i)}; }
private:
friend class MatchIterator;
friend class Regex;
friend class SplitIterator;
std::vector<int> ofs;
uint32_t fset = 0;
UnicornDetail::PcreRef ref;
int status = -1;
const Ustring* text = nullptr;
void init(const Regex& r, const Ustring& s);
void next(const Ustring& pattern, size_t start, int anchors);
bool is_group(size_t i) const noexcept { return i < groups() && ofs[2 * i] >= 0 && ofs[2 * i + 1] >= 0; }
};
inline void swap(Match& lhs, Match& rhs) noexcept { lhs.swap(rhs); }
// Regular expression class
class Regex:
public LessThanComparable<Regex> {
public:
static constexpr uint32_t byte = 1ul << 0; // Byte mode matching ~PCRE_UTF8
static constexpr uint32_t caseless = 1ul << 1; // Case insensitive matching PCRE_CASELESS
static constexpr uint32_t dfa = 1ul << 2; // Use the alternative DFA algorithm pcre_dfa_exec()
static constexpr uint32_t dollarnewline = 1ul << 3; // $ may match line break at end ~PCRE_DOLLAR_ENDONLY
static constexpr uint32_t dotinline = 1ul << 4; // . does not match newlines ~PCRE_DOTALL
static constexpr uint32_t extended = 1ul << 5; // Free-form mode (ignore whitespace and comments) PCRE_EXTENDED
static constexpr uint32_t firstline = 1ul << 6; // Must match in first line PCRE_FIRSTLINE
static constexpr uint32_t multiline = 1ul << 7; // Multiline mode (^ and $ match BOL/EOL) PCRE_MULTILINE
static constexpr uint32_t newlineanycrlf = 1ul << 8; // Line break is any of CR, LF, CRLF PCRE_NEWLINE_ANYCRLF
static constexpr uint32_t newlinecr = 1ul << 9; // Line break is CR only PCRE_NEWLINE_CR
static constexpr uint32_t newlinecrlf = 1ul << 10; // Line break is CRLF only PCRE_NEWLINE_CRLF
static constexpr uint32_t newlinelf = 1ul << 11; // Line break is LF only PCRE_NEWLINE_LF
static constexpr uint32_t noautocapture = 1ul << 12; // No automatic captures PCRE_NO_AUTO_CAPTURE
static constexpr uint32_t nostartoptimize = 1ul << 13; // No startup optimization PCRE_NO_START_OPTIMIZE
static constexpr uint32_t notbol = 1ul << 14; // Start of text is not a line break PCRE_NOTBOL
static constexpr uint32_t notempty = 1ul << 15; // Do not match an empty Ustring PCRE_NOTEMPTY
static constexpr uint32_t notemptyatstart = 1ul << 16; // Match an empty Ustring only at the start PCRE_NOTEMPTY_ATSTART
static constexpr uint32_t noteol = 1ul << 17; // End of text is not a line break PCRE_NOTEOL
static constexpr uint32_t noutfcheck = 1ul << 18; // Skip UTF validity checks PCRE_NO_UTF8_CHECK
static constexpr uint32_t optimize = 1ul << 19; // Take extra effort to optimize the regex PCRE_STUDY_JIT_COMPILE
static constexpr uint32_t partialhard = 1ul << 20; // Hard partial matching (prefer over full match) PCRE_PARTIAL_HARD
static constexpr uint32_t partialsoft = 1ul << 21; // Soft partial matching (only if no full match) PCRE_PARTIAL_SOFT
static constexpr uint32_t prefershort = 1ul << 22; // Non-greedy quantifiers, or shorter DFA matches PCRE_UNGREEDY,PCRE_DFA_SHORTEST
static constexpr uint32_t ucp = 1ul << 23; // Use Unicode properties in escape charsets PCRE_UCP
Regex(): Regex({}, 0) {}
explicit Regex(const Ustring& pattern, uint32_t flags = 0);
Match operator()(const Ustring& text, size_t offset = 0) const { return search(text, offset); }
Match operator()(const Utf8Iterator& start) const { return search(start.source(), start.offset()); }
Match anchor(const Ustring& text, size_t offset = 0) const { return exec(text, offset, 1); }
Match anchor(const Utf8Iterator& start) const { return anchor(start.source(), start.offset()); }
Match match(const Ustring& text, size_t offset = 0) const { return exec(text, offset, 2); }
Match match(const Utf8Iterator& start) const { return match(start.source(), start.offset()); }
Match search(const Ustring& text, size_t offset = 0) const { return exec(text, offset, 0); }
Match search(const Utf8Iterator& start) const { return search(start.source(), start.offset()); }
size_t count(const Ustring& text) const;
bool empty() const noexcept { return pat.empty(); }
Ustring extract(const Ustring& fmt, const Ustring& text, size_t n = npos) const;
Ustring format(const Ustring& fmt, const Ustring& text, size_t n = npos) const;
MatchRange grep(const Ustring& text) const;
size_t groups() const noexcept { return ref.count_groups(); }
size_t named(const Ustring& name) const noexcept { return ref.named_group(name); }
Ustring pattern() const { return pat; }
uint32_t flags() const noexcept { return fset; }
SplitRange split(const Ustring& text) const;
void swap(Regex& r) noexcept;
template <typename F> Ustring transform(const Ustring& text, F f, size_t n = npos) const;
template <typename F> void transform_in(Ustring& text, F f, size_t n = npos) const;
static Ustring escape(const Ustring& str);
static Version pcre_version() noexcept;
static Version unicode_version() noexcept;
friend bool operator==(const Regex& lhs, const Regex& rhs) noexcept;
friend bool operator<(const Regex& lhs, const Regex& rhs) noexcept;
private:
friend class MatchIterator;
friend class Match;
Ustring pat;
uint32_t fset = 0;
UnicornDetail::PcreRef ref;
Match exec(const Ustring& text, size_t offset, int anchors) const;
};
namespace UnicornDetail {
void regex_match_transform(const Regex& re, const Ustring& src, Ustring& dst, std::function<Ustring(const Match&)> f, size_t n);
void regex_string_transform(const Regex& re, const Ustring& src, Ustring& dst, std::function<Ustring(const Ustring&)> f, size_t n);
template <typename F, bool S = std::is_convertible<F, std::function<Ustring(const Ustring&)>>::value>
struct RegexTransform ;
template <typename F>
struct RegexTransform<F, false> {
void operator()(const Regex& re, const Ustring& src, Ustring& dst, F f, size_t n) const {
regex_match_transform(re, src, dst, f, n);
}
};
template <typename F>
struct RegexTransform<F, true> {
void operator()(const Regex& re, const Ustring& src, Ustring& dst, F f, size_t n) const {
regex_string_transform(re, src, dst, f, n);
}
};
}
template <typename F>
Ustring Regex::transform(const Ustring& text, F f, size_t n) const {
Ustring dst;
UnicornDetail::RegexTransform<F>()(*this, text, dst, f, n);
return dst;
}
template <typename F>
void Regex::transform_in(Ustring& text, F f, size_t n) const {
Ustring dst;
UnicornDetail::RegexTransform<F>()(*this, text, dst, f, n);
text = move(dst);
}
inline void swap(Regex& lhs, Regex& rhs) noexcept { lhs.swap(rhs); }
namespace Literals {
inline Regex operator"" _re(const char* ptr, size_t len) { return Regex(cstr(ptr, len)); }
inline Regex operator"" _re_b(const char* ptr, size_t len) { return Regex(cstr(ptr, len), Regex::byte); }
inline Regex operator"" _re_i(const char* ptr, size_t len) { return Regex(cstr(ptr, len), Regex::caseless); }
}
// Regex formatting class
class RegexFormat {
public:
RegexFormat() = default;
RegexFormat(const Regex& pattern, const Ustring& format);
RegexFormat(const Ustring& pattern, const Ustring& format, uint32_t flags = 0);
Ustring operator()(const Ustring& text, size_t n = npos) const { return format(text, n); }
uint32_t flags() const noexcept { return reg.flags(); }
Ustring extract(const Ustring& text, size_t n = npos) const { return apply(text, n, false); }
Ustring format() const { return fmt; }
Ustring format(const Ustring& text, size_t n = npos) const { return apply(text, n, true); }
Ustring pattern() const { return reg.pattern(); }
Regex regex() const { return reg; }
void swap(RegexFormat& r) noexcept;
private:
// Index field in element record indicates what to substitute
// >= 0 => numbered capture group
// -1 => literal text
// -2 => named capture group
// < -2 => escape code
static constexpr int literal = -1, named = -2;
struct element {
int index;
Ustring text;
};
using sequence = std::vector<element>;
Ustring fmt;
Regex reg;
sequence seq;
void add_escape(char c);
void add_literal(const Ustring& text);
void add_literal(const Ustring& text, size_t offset, size_t count);
void add_literal(char32_t u);
void add_named(const Ustring& name) { seq.push_back({named, name}); }
void add_tag(int tag) { seq.push_back({tag, {}}); }
Ustring apply(const Ustring& text, size_t n, bool full) const;
void parse();
};
inline void swap(RegexFormat& lhs, RegexFormat& rhs) noexcept { lhs.swap(rhs); }
// Iterator over regex matches
class MatchIterator:
public ForwardIterator<MatchIterator, const Match> {
public:
MatchIterator() = default;
MatchIterator(const Regex& re, const Ustring& text);
const Match& operator*() const noexcept { return mat; }
MatchIterator& operator++();
friend bool operator==(const MatchIterator& lhs, const MatchIterator& rhs) noexcept;
private:
Match mat;
Ustring pat;
};
// Iterator over substrings between matches
class SplitIterator:
public ForwardIterator<SplitIterator, const Ustring> {
public:
SplitIterator() = default;
SplitIterator(const Regex& re, const Ustring& text);
const Ustring& operator*() const noexcept { return value; }
SplitIterator& operator++();
friend bool operator==(const SplitIterator& lhs, const SplitIterator& rhs) noexcept;
private:
MatchIterator iter;
size_t start = npos;
Ustring value;
void update();
};
}
|
#pragma once
#include "unicorn/core.hpp"
#include "unicorn/utf.hpp"
#include <algorithm>
#include <functional>
#include <memory>
#include <stdexcept>
#include <type_traits>
#include <vector>
RS_LDLIB(pcre);
namespace RS::Unicorn {
// Forward declarations
class Match;
class MatchIterator;
class Regex;
class RegexFormat;
class SplitIterator;
using MatchRange = Irange<MatchIterator>;
using SplitRange = Irange<SplitIterator>;
namespace UnicornDetail {
// Reference counted PCRE handle
class PcreRef {
public:
PcreRef() noexcept: pc(nullptr), ex(nullptr) {}
PcreRef(void* p, void* x) noexcept: pc(p), ex(x) { inc(); }
PcreRef(const PcreRef& p) noexcept: pc(p.pc), ex(p.ex) { inc(); }
PcreRef(PcreRef&& p) noexcept: pc(p.pc), ex(p.ex) { p.pc = p.ex = nullptr; }
~PcreRef() noexcept { dec(); }
PcreRef& operator=(const PcreRef& p) noexcept { auto q(p); swap(q); return *this; }
PcreRef& operator=(PcreRef&& p) noexcept { auto q(p); swap(q); return *this; }
size_t count_groups() const noexcept;
void* get_pc_ptr() const noexcept { return pc; }
void* get_ex_ptr() const noexcept { return ex; }
size_t named_group(const Ustring& name) const noexcept;
void swap(PcreRef& p) noexcept { std::swap(pc, p.pc); std::swap(ex, p.ex); }
explicit operator bool() const noexcept { return pc; }
private:
void* pc;
void* ex;
void inc() noexcept;
void dec() noexcept;
};
}
// Exceptions
class RegexError:
public std::runtime_error {
public:
RegexError(int error, const Ustring& pattern, const Ustring& message = {});
int error() const noexcept { return err; }
const char* pattern() const noexcept { return pat->data(); }
private:
int err;
std::shared_ptr<Ustring> pat;
static Ustring assemble(int error, const Ustring& pattern, const Ustring& message);
static Ustring translate(int error);
};
// Regex match class
class Match {
public:
Ustring operator[](size_t i) const { return str(i); }
operator Ustring() const { return str(); }
explicit operator bool() const noexcept { return matched(); }
bool operator!() const noexcept { return ! matched(); }
size_t count(size_t i = 0) const noexcept { return is_group(i) ? ofs[2 * i + 1] - ofs[2 * i] : 0; }
bool empty() const noexcept { return ! *this || ofs[0] == ofs[1]; }
size_t endpos(size_t i = 0) const noexcept { return is_group(i) ? ofs[2 * i + 1] : npos; }
Ustring first() const;
Ustring last() const;
bool full_or_partial() const noexcept { return matched() || partial(); }
size_t groups() const noexcept { return std::max(status, 0); }
bool matched(size_t i = 0) const noexcept { return status >= 0 && (i == 0 || is_group(i)); }
Ustring named(const Ustring& name) const { return ref ? str(ref.named_group(name)) : Ustring(); }
size_t offset(size_t i = 0) const noexcept { return is_group(i) ? ofs[2 * i] : npos; }
bool partial() const noexcept { return status == -12; } // PCRE_ERROR_PARTIAL
Ustring::const_iterator s_begin(size_t i = 0) const noexcept;
Ustring::const_iterator s_end(size_t i = 0) const noexcept;
Irange<Ustring::const_iterator> s_range(size_t i = 0) const noexcept { return {s_begin(i), s_end(i)}; }
Ustring str(size_t i = 0) const;
void swap(Match& m) noexcept;
Utf8Iterator u_begin(size_t i = 0) const noexcept;
Utf8Iterator u_end(size_t i = 0) const noexcept;
Irange<Utf8Iterator> u_range(size_t i = 0) const noexcept { return {u_begin(i), u_end(i)}; }
private:
friend class MatchIterator;
friend class Regex;
friend class SplitIterator;
std::vector<int> ofs;
uint32_t fset = 0;
UnicornDetail::PcreRef ref;
int status = -1;
const Ustring* text = nullptr;
void init(const Regex& r, const Ustring& s);
void next(const Ustring& pattern, size_t start, int anchors);
bool is_group(size_t i) const noexcept { return i < groups() && ofs[2 * i] >= 0 && ofs[2 * i + 1] >= 0; }
};
inline void swap(Match& lhs, Match& rhs) noexcept { lhs.swap(rhs); }
// Regular expression class
class Regex:
public LessThanComparable<Regex> {
public:
static constexpr uint32_t byte = 1ul << 0; // Byte mode matching ~PCRE_UTF8
static constexpr uint32_t caseless = 1ul << 1; // Case insensitive matching PCRE_CASELESS
static constexpr uint32_t dfa = 1ul << 2; // Use the alternative DFA algorithm pcre_dfa_exec()
static constexpr uint32_t dollarnewline = 1ul << 3; // $ may match line break at end ~PCRE_DOLLAR_ENDONLY
static constexpr uint32_t dotinline = 1ul << 4; // . does not match newlines ~PCRE_DOTALL
static constexpr uint32_t extended = 1ul << 5; // Free-form mode (ignore whitespace and comments) PCRE_EXTENDED
static constexpr uint32_t firstline = 1ul << 6; // Must match in first line PCRE_FIRSTLINE
static constexpr uint32_t multiline = 1ul << 7; // Multiline mode (^ and $ match BOL/EOL) PCRE_MULTILINE
static constexpr uint32_t newlineanycrlf = 1ul << 8; // Line break is any of CR, LF, CRLF PCRE_NEWLINE_ANYCRLF
static constexpr uint32_t newlinecr = 1ul << 9; // Line break is CR only PCRE_NEWLINE_CR
static constexpr uint32_t newlinecrlf = 1ul << 10; // Line break is CRLF only PCRE_NEWLINE_CRLF
static constexpr uint32_t newlinelf = 1ul << 11; // Line break is LF only PCRE_NEWLINE_LF
static constexpr uint32_t noautocapture = 1ul << 12; // No automatic captures PCRE_NO_AUTO_CAPTURE
static constexpr uint32_t nostartoptimize = 1ul << 13; // No startup optimization PCRE_NO_START_OPTIMIZE
static constexpr uint32_t notbol = 1ul << 14; // Start of text is not a line break PCRE_NOTBOL
static constexpr uint32_t notempty = 1ul << 15; // Do not match an empty Ustring PCRE_NOTEMPTY
static constexpr uint32_t notemptyatstart = 1ul << 16; // Match an empty Ustring only at the start PCRE_NOTEMPTY_ATSTART
static constexpr uint32_t noteol = 1ul << 17; // End of text is not a line break PCRE_NOTEOL
static constexpr uint32_t noutfcheck = 1ul << 18; // Skip UTF validity checks PCRE_NO_UTF8_CHECK
static constexpr uint32_t optimize = 1ul << 19; // Take extra effort to optimize the regex PCRE_STUDY_JIT_COMPILE
static constexpr uint32_t partialhard = 1ul << 20; // Hard partial matching (prefer over full match) PCRE_PARTIAL_HARD
static constexpr uint32_t partialsoft = 1ul << 21; // Soft partial matching (only if no full match) PCRE_PARTIAL_SOFT
static constexpr uint32_t prefershort = 1ul << 22; // Non-greedy quantifiers, or shorter DFA matches PCRE_UNGREEDY,PCRE_DFA_SHORTEST
static constexpr uint32_t ucp = 1ul << 23; // Use Unicode properties in escape charsets PCRE_UCP
Regex(): Regex({}, 0) {}
explicit Regex(const Ustring& pattern, uint32_t flags = 0);
Match operator()(const Ustring& text, size_t offset = 0) const { return search(text, offset); }
Match operator()(const Utf8Iterator& start) const { return search(start.source(), start.offset()); }
Match anchor(const Ustring& text, size_t offset = 0) const { return exec(text, offset, 1); }
Match anchor(const Utf8Iterator& start) const { return anchor(start.source(), start.offset()); }
Match match(const Ustring& text, size_t offset = 0) const { return exec(text, offset, 2); }
Match match(const Utf8Iterator& start) const { return match(start.source(), start.offset()); }
Match search(const Ustring& text, size_t offset = 0) const { return exec(text, offset, 0); }
Match search(const Utf8Iterator& start) const { return search(start.source(), start.offset()); }
size_t count(const Ustring& text) const;
bool empty() const noexcept { return pat.empty(); }
Ustring extract(const Ustring& fmt, const Ustring& text, size_t n = npos) const;
Ustring format(const Ustring& fmt, const Ustring& text, size_t n = npos) const;
MatchRange grep(const Ustring& text) const;
size_t groups() const noexcept { return ref.count_groups(); }
size_t named(const Ustring& name) const noexcept { return ref.named_group(name); }
Ustring pattern() const { return pat; }
uint32_t flags() const noexcept { return fset; }
SplitRange split(const Ustring& text) const;
void swap(Regex& r) noexcept;
template <typename F> Ustring transform(const Ustring& text, F f, size_t n = npos) const;
template <typename F> void transform_in(Ustring& text, F f, size_t n = npos) const;
static Ustring escape(const Ustring& str);
static Version pcre_version() noexcept;
static Version unicode_version() noexcept;
friend bool operator==(const Regex& lhs, const Regex& rhs) noexcept;
friend bool operator<(const Regex& lhs, const Regex& rhs) noexcept;
private:
friend class MatchIterator;
friend class Match;
Ustring pat;
uint32_t fset = 0;
UnicornDetail::PcreRef ref;
Match exec(const Ustring& text, size_t offset, int anchors) const;
};
namespace UnicornDetail {
void regex_match_transform(const Regex& re, const Ustring& src, Ustring& dst, std::function<Ustring(const Match&)> f, size_t n);
void regex_string_transform(const Regex& re, const Ustring& src, Ustring& dst, std::function<Ustring(const Ustring&)> f, size_t n);
template <typename F, bool S = std::is_convertible<F, std::function<Ustring(const Ustring&)>>::value>
struct RegexTransform ;
template <typename F>
struct RegexTransform<F, false> {
void operator()(const Regex& re, const Ustring& src, Ustring& dst, F f, size_t n) const {
regex_match_transform(re, src, dst, f, n);
}
};
template <typename F>
struct RegexTransform<F, true> {
void operator()(const Regex& re, const Ustring& src, Ustring& dst, F f, size_t n) const {
regex_string_transform(re, src, dst, f, n);
}
};
}
template <typename F>
Ustring Regex::transform(const Ustring& text, F f, size_t n) const {
Ustring dst;
UnicornDetail::RegexTransform<F>()(*this, text, dst, f, n);
return dst;
}
template <typename F>
void Regex::transform_in(Ustring& text, F f, size_t n) const {
Ustring dst;
UnicornDetail::RegexTransform<F>()(*this, text, dst, f, n);
text = move(dst);
}
inline void swap(Regex& lhs, Regex& rhs) noexcept { lhs.swap(rhs); }
namespace Literals {
inline Regex operator"" _re(const char* ptr, size_t len) { return Regex(cstr(ptr, len)); }
inline Regex operator"" _re_b(const char* ptr, size_t len) { return Regex(cstr(ptr, len), Regex::byte); }
inline Regex operator"" _re_i(const char* ptr, size_t len) { return Regex(cstr(ptr, len), Regex::caseless); }
}
// Regex formatting class
class RegexFormat {
public:
RegexFormat() = default;
RegexFormat(const Regex& pattern, const Ustring& format);
RegexFormat(const Ustring& pattern, const Ustring& format, uint32_t flags = 0);
Ustring operator()(const Ustring& text, size_t n = npos) const { return format(text, n); }
uint32_t flags() const noexcept { return reg.flags(); }
Ustring extract(const Ustring& text, size_t n = npos) const { return apply(text, n, false); }
Ustring format() const { return fmt; }
Ustring format(const Ustring& text, size_t n = npos) const { return apply(text, n, true); }
Ustring pattern() const { return reg.pattern(); }
Regex regex() const { return reg; }
void swap(RegexFormat& r) noexcept;
private:
// Index field in element record indicates what to substitute
// >= 0 => numbered capture group
// -1 => literal text
// -2 => named capture group
// < -2 => escape code
static constexpr int literal = -1, named = -2;
struct element {
int index;
Ustring text;
};
using sequence = std::vector<element>;
Ustring fmt;
Regex reg;
sequence seq;
void add_escape(char c);
void add_literal(const Ustring& text);
void add_literal(const Ustring& text, size_t offset, size_t count);
void add_literal(char32_t u);
void add_named(const Ustring& name) { seq.push_back({named, name}); }
void add_tag(int tag) { seq.push_back({tag, {}}); }
Ustring apply(const Ustring& text, size_t n, bool full) const;
void parse();
};
inline void swap(RegexFormat& lhs, RegexFormat& rhs) noexcept { lhs.swap(rhs); }
// Iterator over regex matches
class MatchIterator:
public ForwardIterator<MatchIterator, const Match> {
public:
MatchIterator() = default;
MatchIterator(const Regex& re, const Ustring& text);
const Match& operator*() const noexcept { return mat; }
MatchIterator& operator++();
friend bool operator==(const MatchIterator& lhs, const MatchIterator& rhs) noexcept;
private:
Match mat;
Ustring pat;
};
// Iterator over substrings between matches
class SplitIterator:
public ForwardIterator<SplitIterator, const Ustring> {
public:
SplitIterator() = default;
SplitIterator(const Regex& re, const Ustring& text);
const Ustring& operator*() const noexcept { return value; }
SplitIterator& operator++();
friend bool operator==(const SplitIterator& lhs, const SplitIterator& rhs) noexcept;
private:
MatchIterator iter;
size_t start = npos;
Ustring value;
void update();
};
}
|
Add import macro for pcre
|
Add import macro for pcre
|
C++
|
mit
|
CaptainCrowbar/unicorn-lib,CaptainCrowbar/unicorn-lib,CaptainCrowbar/unicorn-lib
|
c1c85cfd0049b10d3395f6963fd926156d436e63
|
src/Core/Algorithms/Legacy/Fields/MeshDerivatives/SplitByConnectedRegion.cc
|
src/Core/Algorithms/Legacy/Fields/MeshDerivatives/SplitByConnectedRegion.cc
|
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Core/Algorithms/Base/AlgorithmPreconditions.h>
#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/SplitByConnectedRegion.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/Legacy/Field/Mesh.h>
#include <Core/Datatypes/Legacy/Field/VMesh.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
using namespace SCIRun;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
AlgorithmInputName SplitFieldByConnectedRegionAlgo::InputField("InputField");
AlgorithmOutputName SplitFieldByConnectedRegionAlgo::OutputField1("OutputField1");
AlgorithmOutputName SplitFieldByConnectedRegionAlgo::OutputField2("OutputField2");
AlgorithmOutputName SplitFieldByConnectedRegionAlgo::OutputField3("OutputField3");
AlgorithmOutputName SplitFieldByConnectedRegionAlgo::OutputField4("OutputField4");
AlgorithmOutputName SplitFieldByConnectedRegionAlgo::OutputField5("OutputField5");
AlgorithmOutputName SplitFieldByConnectedRegionAlgo::OutputField6("OutputField6");
AlgorithmOutputName SplitFieldByConnectedRegionAlgo::OutputField7("OutputField7");
AlgorithmOutputName SplitFieldByConnectedRegionAlgo::OutputField8("OutputField8");
AlgorithmParameterName SplitFieldByConnectedRegionAlgo::SortDomainBySize() { return AlgorithmParameterName("SortDomainBySize"); }
AlgorithmParameterName SplitFieldByConnectedRegionAlgo::SortAscending() { return AlgorithmParameterName("SortAscending"); }
/// TODO: These should be refactored to hold const std::vector<double>& rather than double*
class SortSizes : public std::binary_function<index_type,index_type,bool>
{
public:
SortSizes(double* sizes) : sizes_(sizes) {}
bool operator()(index_type i1, index_type i2)
{
return (sizes_[i1] > sizes_[i2]);
}
private:
double* sizes_;
};
/// TODO: These should be refactored to hold const std::vector<double>& rather than double*
class AscSortSizes : public std::binary_function<index_type,index_type,bool>
{
public:
AscSortSizes(double* sizes) : sizes_(sizes) {}
bool operator()(index_type i1, index_type i2)
{
return (sizes_[i1] < sizes_[i2]);
}
private:
double* sizes_;
};
SplitFieldByConnectedRegionAlgo::SplitFieldByConnectedRegionAlgo()
{
addParameter(SortDomainBySize(), false);
addParameter(SortAscending(), false);
}
std::vector<FieldHandle> SplitFieldByConnectedRegionAlgo::run(FieldHandle input) const
{
bool sortDomainBySize = get(SortDomainBySize()).toBool();
bool sortAscending = get(SortAscending()).toBool();
if (!input)
{
THROW_ALGORITHM_INPUT_ERROR("Input mesh is empty.");
}
std::vector<FieldHandle> output;
/// Figure out what the input type and output type have to be
FieldInformation fi(input);
/// We do not yet support Quadratic and Cubic Meshes here
if (fi.is_nonlinear())
{
THROW_ALGORITHM_INPUT_ERROR("This function has not yet been defined for non-linear elements.");
}
if (!(fi.is_unstructuredmesh()))
{
output.push_back(input);
remark("Structured meshes consist always of one piece. Hence there is no algorithm to perform.");
}
if (fi.is_pointcloudmesh())
{
THROW_ALGORITHM_INPUT_ERROR("This algorithm has not yet been defined for point clouds.");
}
VField* ifield = input->vfield();
VMesh* imesh = input->vmesh();
VField::index_type k = 0;
VMesh::size_type num_nodes = imesh->num_nodes();
VMesh::size_type num_elems = imesh->num_elems();
VField::size_type surfsize = static_cast<VField::size_type>(pow(num_elems, 2.0 / 3.0));
std::vector<VMesh::Elem::index_type> buffer;
buffer.reserve(surfsize);
imesh->synchronize(Mesh::NODE_NEIGHBORS_E|Mesh::ELEM_NEIGHBORS_E|Mesh::DELEMS_E);
std::vector<index_type> elemmap(num_elems, 0);
std::vector<index_type> nodemap(num_nodes, 0);
std::vector<index_type> renumber(num_nodes,0);
std::vector<short> visited(num_elems, 0);
VMesh::Node::array_type nnodes;
VMesh::Elem::array_type neighbors;
for (VMesh::Elem::index_type idx=0; idx<num_elems; idx++)
{
// if list of elements to process is empty ad the next one
if (buffer.size() == 0)
{
if(visited[idx] == 0) { buffer.push_back(idx); k++; }
}
if (buffer.size() > 0)
{
for (size_t i=0; i< buffer.size(); i++)
{
VField::index_type j = buffer[i];
if (visited[j] > 0) { continue; }
visited[j] = 1;
imesh->get_nodes(nnodes,buffer[i]);
for (size_t q=0; q<nnodes.size(); q++)
{
imesh->get_elems(neighbors,nnodes[q]);
for (size_t p=0; p<neighbors.size(); p++)
{
if(visited[neighbors[p]] == 0)
{
buffer.push_back(neighbors[p]);
visited[neighbors[p]] = -1;
}
}
}
if (j >= static_cast<index_type>(elemmap.size())) elemmap.resize(j+1);
elemmap[j] = k;
for (size_t p=0;p<nnodes.size();p++)
{
if (static_cast<size_t>(nnodes[p]) >= nodemap.size())
nodemap.resize(nnodes[p]+1);
nodemap[nnodes[p]] = k;
}
}
buffer.clear();
}
}
output.resize(k);
for (size_type p=0; p<k; p++)
{
VField* ofield;
VMesh* omesh;
MeshHandle mesh;
FieldHandle field;
VField::size_type nn = 0;
VField::size_type ne = 0;
for (VField::index_type q=0;q<num_nodes;q++) if (nodemap[q] == p+1) nn++;
for (VField::index_type q=0;q<num_elems;q++) if (elemmap[q] == p+1) ne++;
mesh = CreateMesh(fi);
if (!mesh)
{
THROW_ALGORITHM_INPUT_ERROR("Could not create output field.");
}
omesh = mesh->vmesh();
omesh->node_reserve(nn);
omesh->elem_reserve(ne);
field = CreateField(fi,mesh);
if (field == nullptr)
{
THROW_ALGORITHM_INPUT_ERROR("Could not create output field");
}
ofield = field->vfield();
output[p] = field;
Point point;
for (index_type q=0;q<num_nodes;q++)
{
if (nodemap[q] == p+1)
{
imesh->get_center(point,VMesh::Node::index_type(q));
renumber[q] = omesh->add_point(point);
}
}
VMesh::Node::array_type elemnodes;
for (index_type q=0;q<num_elems;q++)
{
if (elemmap[q] == p+1)
{
imesh->get_nodes(elemnodes,VMesh::Elem::index_type(q));
for (size_t r=0; r< elemnodes.size(); r++)
{
elemnodes[r] = VMesh::Node::index_type(renumber[elemnodes[r]]);
}
omesh->add_elem(elemnodes);
}
}
ofield->resize_fdata();
if (ifield->basis_order() == 1)
{
VField::index_type qq = 0;
for (VField::index_type q=0;q<num_nodes;q++)
{
if (nodemap[q] == p+1)
{
ofield->copy_value(ifield,q,qq); qq++;
}
}
}
if (ifield->basis_order() == 0)
{
VField::index_type qq = 0;
for (VField::index_type q=0;q<num_elems;q++)
{
if (elemmap[q] == p+1)
{
ofield->copy_value(ifield,q,qq); qq++;
}
}
}
#ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER
ofield->copy_properties(ifield);
#endif
}
if (sortDomainBySize)
{
std::vector<double> sizes(output.size());
std::vector<index_type> order(output.size());
std::vector<FieldHandle> temp(output.size());
for (size_t j=0; j<output.size(); j++)
{
VMesh* mesh = output[j]->vmesh();
VMesh::Elem::size_type num_elems = mesh->num_elems();
double size = 0.0;
for (VMesh::Elem::index_type idx=0; idx<num_elems; idx++)
{
size += mesh->get_size(idx);
}
sizes[j] = size;
order[j] = j;
temp[j] = output[j];
}
if (sortAscending)
{
std::sort(order.begin(),order.end(),AscSortSizes(&(sizes[0])));
}
else
{
std::sort(order.begin(),order.end(),SortSizes(&(sizes[0])));
}
for (size_t j=0; j<output.size(); j++)
{
output[j] = temp[order[j]];
}
}
return output;
}
AlgorithmOutput SplitFieldByConnectedRegionAlgo::run(const AlgorithmInput& input) const
{
AlgorithmOutput output;
auto mesh_ = input.get<Field>(Variables::InputField);
if (!mesh_)
THROW_ALGORITHM_INPUT_ERROR("Input mesh is empty.");
std::vector<FieldHandle> output_fields=run(mesh_);
if (output_fields.empty())
{
THROW_ALGORITHM_INPUT_ERROR(" No input fields given ");
}
if (output_fields.size()>8)
{
remark(" Not all output meshes could be sent to the eight field output ports. ");
}
if (output_fields.size() > 0)
output[OutputField1]=output_fields[0];
if (output_fields.size() > 1)
output[OutputField2]=output_fields[1];
if (output_fields.size() > 2)
output[OutputField3]=output_fields[2];
if (output_fields.size() > 3)
output[OutputField4]=output_fields[3];
if (output_fields.size() > 4)
output[OutputField5]=output_fields[4];
if (output_fields.size() > 5)
output[OutputField6]=output_fields[5];
if (output_fields.size() > 6)
output[OutputField7]=output_fields[6];
if (output_fields.size() > 7)
output[OutputField8]=output_fields[7];
/// TODO: enable dynamic output ports
return output;
}
|
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Core/Algorithms/Base/AlgorithmPreconditions.h>
#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/SplitByConnectedRegion.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/Legacy/Field/Mesh.h>
#include <Core/Datatypes/Legacy/Field/VMesh.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
using namespace SCIRun;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
AlgorithmInputName SplitFieldByConnectedRegionAlgo::InputField("InputField");
AlgorithmOutputName SplitFieldByConnectedRegionAlgo::OutputField1("OutputField1");
AlgorithmOutputName SplitFieldByConnectedRegionAlgo::OutputField2("OutputField2");
AlgorithmOutputName SplitFieldByConnectedRegionAlgo::OutputField3("OutputField3");
AlgorithmOutputName SplitFieldByConnectedRegionAlgo::OutputField4("OutputField4");
AlgorithmOutputName SplitFieldByConnectedRegionAlgo::OutputField5("OutputField5");
AlgorithmOutputName SplitFieldByConnectedRegionAlgo::OutputField6("OutputField6");
AlgorithmOutputName SplitFieldByConnectedRegionAlgo::OutputField7("OutputField7");
AlgorithmOutputName SplitFieldByConnectedRegionAlgo::OutputField8("OutputField8");
AlgorithmParameterName SplitFieldByConnectedRegionAlgo::SortDomainBySize() { return AlgorithmParameterName("SortDomainBySize"); }
AlgorithmParameterName SplitFieldByConnectedRegionAlgo::SortAscending() { return AlgorithmParameterName("SortAscending"); }
/// TODO: These should be refactored to hold const std::vector<double>& rather than double*
class SortSizes : public std::binary_function<index_type,index_type,bool>
{
public:
SortSizes(double* sizes) : sizes_(sizes) {}
bool operator()(index_type i1, index_type i2)
{
return (sizes_[i1] > sizes_[i2]);
}
private:
double* sizes_;
};
/// TODO: These should be refactored to hold const std::vector<double>& rather than double*
class AscSortSizes : public std::binary_function<index_type,index_type,bool>
{
public:
AscSortSizes(double* sizes) : sizes_(sizes) {}
bool operator()(index_type i1, index_type i2)
{
return (sizes_[i1] < sizes_[i2]);
}
private:
double* sizes_;
};
SplitFieldByConnectedRegionAlgo::SplitFieldByConnectedRegionAlgo()
{
addParameter(SortDomainBySize(), false);
addParameter(SortAscending(), false);
}
std::vector<FieldHandle> SplitFieldByConnectedRegionAlgo::run(FieldHandle input) const
{
bool sortDomainBySize = get(SortDomainBySize()).toBool();
bool sortAscending = get(SortAscending()).toBool();
if (!input)
{
THROW_ALGORITHM_INPUT_ERROR("Input mesh is empty.");
}
std::vector<FieldHandle> output;
/// Figure out what the input type and output type have to be
FieldInformation fi(input);
/// We do not yet support Quadratic and Cubic Meshes here
if (fi.is_nonlinear())
{
THROW_ALGORITHM_INPUT_ERROR("This function has not yet been defined for non-linear elements.");
}
if (!(fi.is_unstructuredmesh()))
{
output.push_back(input);
remark("Structured meshes consist always of one piece. Hence there is no algorithm to perform.");
}
if (fi.is_pointcloudmesh())
{
THROW_ALGORITHM_INPUT_ERROR("This algorithm has not yet been defined for point clouds.");
}
VField* ifield = input->vfield();
VMesh* imesh = input->vmesh();
VField::index_type k = 0;
VMesh::size_type num_nodes = imesh->num_nodes();
VMesh::size_type num_elems = imesh->num_elems();
VField::size_type surfsize = static_cast<VField::size_type>(pow(num_elems, 2.0 / 3.0));
std::vector<VMesh::Elem::index_type> buffer;
buffer.reserve(surfsize);
imesh->synchronize(Mesh::NODE_NEIGHBORS_E|Mesh::ELEM_NEIGHBORS_E|Mesh::DELEMS_E);
std::vector<index_type> elemmap(num_elems, 0);
std::vector<index_type> nodemap(num_nodes, 0);
std::vector<index_type> renumber(num_nodes,0);
std::vector<short> visited(num_elems, 0);
VMesh::Node::array_type nnodes;
VMesh::Elem::array_type neighbors;
for (VMesh::Elem::index_type idx=0; idx<num_elems; idx++)
{
// if list of elements to process is empty ad the next one
if (buffer.size() == 0)
{
if(visited[idx] == 0) { buffer.push_back(idx); k++; }
}
if (buffer.size() > 0)
{
for (size_t i=0; i< buffer.size(); i++)
{
VField::index_type j = buffer[i];
if (visited[j] > 0) { continue; }
visited[j] = 1;
imesh->get_nodes(nnodes,buffer[i]);
for (size_t q=0; q<nnodes.size(); q++)
{
imesh->get_elems(neighbors,nnodes[q]);
for (size_t p=0; p<neighbors.size(); p++)
{
if(visited[neighbors[p]] == 0)
{
buffer.push_back(neighbors[p]);
visited[neighbors[p]] = -1;
}
}
}
if (j >= static_cast<index_type>(elemmap.size())) elemmap.resize(j+1);
elemmap[j] = k;
for (size_t p=0;p<nnodes.size();p++)
{
if (static_cast<size_t>(nnodes[p]) >= nodemap.size())
nodemap.resize(nnodes[p]+1);
nodemap[nnodes[p]] = k;
}
}
buffer.clear();
}
}
output.resize(k);
for (size_type p=0; p<k; p++)
{
VField* ofield;
VMesh* omesh;
MeshHandle mesh;
FieldHandle field;
VField::size_type nn = 0;
VField::size_type ne = 0;
for (VField::index_type q=0;q<num_nodes;q++) if (nodemap[q] == p+1) nn++;
for (VField::index_type q=0;q<num_elems;q++) if (elemmap[q] == p+1) ne++;
mesh = CreateMesh(fi);
if (!mesh)
{
THROW_ALGORITHM_INPUT_ERROR("Could not create output field.");
}
omesh = mesh->vmesh();
omesh->node_reserve(nn);
omesh->elem_reserve(ne);
field = CreateField(fi,mesh);
if (field == nullptr)
{
THROW_ALGORITHM_INPUT_ERROR("Could not create output field");
}
ofield = field->vfield();
output[p] = field;
Point point;
for (index_type q=0;q<num_nodes;q++)
{
if (nodemap[q] == p+1)
{
imesh->get_center(point,VMesh::Node::index_type(q));
renumber[q] = omesh->add_point(point);
}
}
VMesh::Node::array_type elemnodes;
for (index_type q=0;q<num_elems;q++)
{
if (elemmap[q] == p+1)
{
imesh->get_nodes(elemnodes,VMesh::Elem::index_type(q));
for (size_t r=0; r< elemnodes.size(); r++)
{
elemnodes[r] = VMesh::Node::index_type(renumber[elemnodes[r]]);
}
omesh->add_elem(elemnodes);
}
}
ofield->resize_fdata();
if (ifield->basis_order() == 1)
{
VField::index_type qq = 0;
for (VField::index_type q=0;q<num_nodes;q++)
{
if (nodemap[q] == p+1)
{
ofield->copy_value(ifield,q,qq); qq++;
}
}
}
if (ifield->basis_order() == 0)
{
VField::index_type qq = 0;
for (VField::index_type q=0;q<num_elems;q++)
{
if (elemmap[q] == p+1)
{
ofield->copy_value(ifield,q,qq); qq++;
}
}
}
#ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER
ofield->copy_properties(ifield);
#endif
}
if (sortDomainBySize)
{
std::vector<double> sizes(output.size());
std::vector<index_type> order(output.size());
std::vector<FieldHandle> temp(output.size());
for (size_t j=0; j<output.size(); j++)
{
VMesh* mesh = output[j]->vmesh();
VMesh::Elem::size_type num_elems = mesh->num_elems();
double size = 0.0;
for (VMesh::Elem::index_type idx=0; idx<num_elems; idx++)
{
size += mesh->get_size(idx);
}
sizes[j] = size;
order[j] = j;
temp[j] = output[j];
}
if (!sizes.empty())
{
if (sortAscending)
{
std::sort(order.begin(), order.end(), AscSortSizes(&(sizes[0])));
}
else
{
std::sort(order.begin(), order.end(), SortSizes(&(sizes[0])));
}
}
for (size_t j=0; j<output.size(); j++)
{
output[j] = temp[order[j]];
}
}
return output;
}
AlgorithmOutput SplitFieldByConnectedRegionAlgo::run(const AlgorithmInput& input) const
{
AlgorithmOutput output;
auto mesh_ = input.get<Field>(Variables::InputField);
if (!mesh_)
THROW_ALGORITHM_INPUT_ERROR("Input mesh is empty.");
std::vector<FieldHandle> output_fields=run(mesh_);
if (output_fields.empty())
{
THROW_ALGORITHM_INPUT_ERROR(" No input fields given ");
}
if (output_fields.size()>8)
{
remark(" Not all output meshes could be sent to the eight field output ports. ");
}
if (output_fields.size() > 0)
output[OutputField1]=output_fields[0];
if (output_fields.size() > 1)
output[OutputField2]=output_fields[1];
if (output_fields.size() > 2)
output[OutputField3]=output_fields[2];
if (output_fields.size() > 3)
output[OutputField4]=output_fields[3];
if (output_fields.size() > 4)
output[OutputField5]=output_fields[4];
if (output_fields.size() > 5)
output[OutputField6]=output_fields[5];
if (output_fields.size() > 6)
output[OutputField7]=output_fields[6];
if (output_fields.size() > 7)
output[OutputField8]=output_fields[7];
/// TODO: enable dynamic output ports
return output;
}
|
Fix crash
|
Fix crash
|
C++
|
mit
|
collint8/SCIRun,jessdtate/SCIRun,jessdtate/SCIRun,jcollfont/SCIRun,moritzdannhauer/SCIRunGUIPrototype,ajanson/SCIRun,jessdtate/SCIRun,moritzdannhauer/SCIRunGUIPrototype,moritzdannhauer/SCIRunGUIPrototype,jessdtate/SCIRun,collint8/SCIRun,jcollfont/SCIRun,jessdtate/SCIRun,moritzdannhauer/SCIRunGUIPrototype,ajanson/SCIRun,jessdtate/SCIRun,jcollfont/SCIRun,collint8/SCIRun,jcollfont/SCIRun,collint8/SCIRun,moritzdannhauer/SCIRunGUIPrototype,ajanson/SCIRun,moritzdannhauer/SCIRunGUIPrototype,moritzdannhauer/SCIRunGUIPrototype,collint8/SCIRun,collint8/SCIRun,ajanson/SCIRun,ajanson/SCIRun,jessdtate/SCIRun,jcollfont/SCIRun,collint8/SCIRun,collint8/SCIRun,ajanson/SCIRun,jcollfont/SCIRun,ajanson/SCIRun,jcollfont/SCIRun,jessdtate/SCIRun
|
393c507498d5645d3fc8461147f72d5704575bc3
|
src/runtime/posix_math.cpp
|
src/runtime/posix_math.cpp
|
#include <stdint.h>
#define INLINE inline __attribute__((used)) __attribute__((always_inline)) __attribute__((nothrow)) __attribute__((pure))
extern "C" {
INLINE uint8_t maxval_u8() {return 0xff;}
INLINE uint8_t minval_u8() {return 0;}
INLINE uint16_t maxval_u16() {return 0xffff;}
INLINE uint16_t minval_u16() {return 0;}
INLINE uint32_t maxval_u32() {return 0xffffffff;}
INLINE uint32_t minval_u32() {return 0;}
INLINE uint64_t maxval_u64() {return __UINT64_C(0xffffffffffffffff);}
INLINE uint64_t minval_u64() {return 0;}
INLINE int8_t maxval_s8() {return 0x7f;}
INLINE int8_t minval_s8() {return 0x80;}
INLINE int16_t maxval_s16() {return 0x7fff;}
INLINE int16_t minval_s16() {return 0x8000;}
INLINE int32_t maxval_s32() {return 0x7fffffff;}
INLINE int32_t minval_s32() {return 0x80000000;}
INLINE int64_t maxval_s64() {return __INT64_C(0x7fffffffffffffff);}
INLINE int64_t minval_s64() {return __INT64_C(0x8000000000000000);}
INLINE int8_t abs_i8(int8_t a) {return a >= 0 ? a : -a;}
INLINE int16_t abs_i16(int16_t a) {return a >= 0 ? a : -a;}
INLINE int32_t abs_i32(int32_t a) {return a >= 0 ? a : -a;}
INLINE int64_t abs_i64(int64_t a) {return a >= 0 ? a : -a;}
INLINE float float_from_bits(uint32_t bits) {
union {
uint32_t as_uint;
float as_float;
} u;
u.as_uint = bits;
return u.as_float;
}
INLINE float nan_f32() {
return float_from_bits(0x7fc00000);
}
INLINE float neg_inf_f32() {
return float_from_bits(0xff800000);
}
INLINE float inf_f32() {
return float_from_bits(0x7f800000);
}
INLINE float maxval_f32() {
return float_from_bits(0x7f7fffff);
}
INLINE float minval_f32() {
return float_from_bits(0x00800000);
}
INLINE double double_from_bits(uint64_t bits) {
union {
uint64_t as_uint;
double as_double;
} u;
u.as_uint = bits;
return u.as_double;
}
INLINE double maxval_f64() {
return double_from_bits(__UINT64_C(0x7fefffffffffffff));
}
INLINE double minval_f64() {
return double_from_bits(__UINT64_C(0x0010000000000000));
}
}
|
#include <stdint.h>
#define INLINE inline __attribute__((used)) __attribute__((always_inline)) __attribute__((nothrow)) __attribute__((pure))
extern "C" {
INLINE uint8_t maxval_u8() {return 0xff;}
INLINE uint8_t minval_u8() {return 0;}
INLINE uint16_t maxval_u16() {return 0xffff;}
INLINE uint16_t minval_u16() {return 0;}
INLINE uint32_t maxval_u32() {return 0xffffffff;}
INLINE uint32_t minval_u32() {return 0;}
INLINE uint64_t maxval_u64() {return UINT64_C(0xffffffffffffffff);}
INLINE uint64_t minval_u64() {return 0;}
INLINE int8_t maxval_s8() {return 0x7f;}
INLINE int8_t minval_s8() {return 0x80;}
INLINE int16_t maxval_s16() {return 0x7fff;}
INLINE int16_t minval_s16() {return 0x8000;}
INLINE int32_t maxval_s32() {return 0x7fffffff;}
INLINE int32_t minval_s32() {return 0x80000000;}
INLINE int64_t maxval_s64() {return INT64_C(0x7fffffffffffffff);}
INLINE int64_t minval_s64() {return INT64_C(0x8000000000000000);}
INLINE int8_t abs_i8(int8_t a) {return a >= 0 ? a : -a;}
INLINE int16_t abs_i16(int16_t a) {return a >= 0 ? a : -a;}
INLINE int32_t abs_i32(int32_t a) {return a >= 0 ? a : -a;}
INLINE int64_t abs_i64(int64_t a) {return a >= 0 ? a : -a;}
INLINE float float_from_bits(uint32_t bits) {
union {
uint32_t as_uint;
float as_float;
} u;
u.as_uint = bits;
return u.as_float;
}
INLINE float nan_f32() {
return float_from_bits(0x7fc00000);
}
INLINE float neg_inf_f32() {
return float_from_bits(0xff800000);
}
INLINE float inf_f32() {
return float_from_bits(0x7f800000);
}
INLINE float maxval_f32() {
return float_from_bits(0x7f7fffff);
}
INLINE float minval_f32() {
return float_from_bits(0x00800000);
}
INLINE double double_from_bits(uint64_t bits) {
union {
uint64_t as_uint;
double as_double;
} u;
u.as_uint = bits;
return u.as_double;
}
INLINE double maxval_f64() {
return double_from_bits(UINT64_C(0x7fefffffffffffff));
}
INLINE double minval_f64() {
return double_from_bits(UINT64_C(0x0010000000000000));
}
}
|
Remove some dubious underscores on int constant macros.
|
Remove some dubious underscores on int constant macros.
|
C++
|
mit
|
dan-tull/Halide,psuriana/Halide,aam/Halide,kenkuang1213/Halide,damienfir/Halide,delcypher/Halide,mcanthony/Halide,ayanazmat/Halide,myrtleTree33/Halide,fengzhyuan/Halide,dan-tull/Halide,jiawen/Halide,rodrigob/Halide,mikeseven/Halide,dan-tull/Halide,fengzhyuan/Halide,dougkwan/Halide,myrtleTree33/Halide,damienfir/Halide,ronen/Halide,dougkwan/Halide,gchauras/Halide,psuriana/Halide,gchauras/Halide,smxlong/Halide,kenkuang1213/Halide,jiawen/Halide,damienfir/Halide,myrtleTree33/Halide,delcypher/Halide,ronen/Halide,dougkwan/Halide,lglucin/Halide,delcypher/Halide,kgnk/Halide,smxlong/Halide,ayanazmat/Halide,kgnk/Halide,kenkuang1213/Halide,adasworks/Halide,gchauras/Halide,adasworks/Halide,myrtleTree33/Halide,mcanthony/Halide,smxlong/Halide,adasworks/Halide,jiawen/Halide,kenkuang1213/Halide,delcypher/Halide,aam/Halide,dan-tull/Halide,kenkuang1213/Halide,fengzhyuan/Halide,damienfir/Halide,delcypher/Halide,aam/Halide,kgnk/Halide,fengzhyuan/Halide,kgnk/Halide,myrtleTree33/Halide,adasworks/Halide,gchauras/Halide,lglucin/Halide,mcanthony/Halide,dougkwan/Halide,jiawen/Halide,ronen/Halide,psuriana/Halide,gchauras/Halide,adasworks/Halide,kenkuang1213/Halide,delcypher/Halide,rodrigob/Halide,psuriana/Halide,fengzhyuan/Halide,jiawen/Halide,damienfir/Halide,fengzhyuan/Halide,psuriana/Halide,aam/Halide,tdenniston/Halide,psuriana/Halide,dan-tull/Halide,adasworks/Halide,rodrigob/Halide,tdenniston/Halide,myrtleTree33/Halide,ayanazmat/Halide,ronen/Halide,tdenniston/Halide,rodrigob/Halide,tdenniston/Halide,mikeseven/Halide,dougkwan/Halide,smxlong/Halide,damienfir/Halide,mcanthony/Halide,aam/Halide,kgnk/Halide,damienfir/Halide,gchauras/Halide,fengzhyuan/Halide,ronen/Halide,mikeseven/Halide,mikeseven/Halide,lglucin/Halide,kgnk/Halide,psuriana/Halide,myrtleTree33/Halide,ayanazmat/Halide,adasworks/Halide,rodrigob/Halide,dougkwan/Halide,mcanthony/Halide,rodrigob/Halide,mikeseven/Halide,myrtleTree33/Halide,lglucin/Halide,ayanazmat/Halide,smxlong/Halide,smxlong/Halide,ronen/Halide,tdenniston/Halide,jiawen/Halide,tdenniston/Halide,mcanthony/Halide,dougkwan/Halide,kenkuang1213/Halide,ayanazmat/Halide,dan-tull/Halide,aam/Halide,rodrigob/Halide,kgnk/Halide,kgnk/Halide,lglucin/Halide,ayanazmat/Halide,smxlong/Halide,dan-tull/Halide,adasworks/Halide,tdenniston/Halide,smxlong/Halide,rodrigob/Halide,delcypher/Halide,aam/Halide,tdenniston/Halide,ronen/Halide,mcanthony/Halide,delcypher/Halide,jiawen/Halide,dougkwan/Halide,dan-tull/Halide,lglucin/Halide,fengzhyuan/Halide,damienfir/Halide,lglucin/Halide,kenkuang1213/Halide,ronen/Halide,ayanazmat/Halide,mcanthony/Halide
|
52b774d4dcc543395214ebc570bab7a9856d8195
|
layout/mainwindow.cpp
|
layout/mainwindow.cpp
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QProcess>
#include <QDebug>
#include <QTextCodec>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
initButtonGroups();
signalMapperCategory = new QSignalMapper(this);
signalMapperFunction = new QSignalMapper(this);
initActionsConnections();
m_category = 0;
m_function = 0;
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
m_conf = new QSettings("/home/rasmus/test-tool.conf", QSettings::IniFormat);
m_conf->setIniCodec(codec);
initCategory();
ui->textEdit->setReadOnly(true);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::initButtonGroups()
{
#define INITCATEGORYBTN(n) \
btnCategoryGroup[n] = ui->btnCategory##n ; \
btnCategoryGroup[n]->setText(composeString("cat", n)); \
btnCategoryGroup[n]->setEnabled(false);
//btnCategoryGroup[n]->setVisible(false);
INITCATEGORYBTN(0);
INITCATEGORYBTN(1);
INITCATEGORYBTN(2);
INITCATEGORYBTN(3);
INITCATEGORYBTN(4);
#undef INITCATEGORYBTN
#define INITFUNCTIONBTN(n) \
btnFunctionGroup[n] = ui->btnFunc##n ; \
btnFunctionGroup[n]->setText(composeString("func", n)); \
btnFunctionGroup[n]->setEnabled(false);
INITFUNCTIONBTN(0);
INITFUNCTIONBTN(1);
INITFUNCTIONBTN(2);
INITFUNCTIONBTN(3);
INITFUNCTIONBTN(4);
INITFUNCTIONBTN(5);
INITFUNCTIONBTN(6);
INITFUNCTIONBTN(7);
INITFUNCTIONBTN(8);
INITFUNCTIONBTN(9);
#undef INITFUNCTIONBTN
}
void MainWindow::initActionsConnections()
{
// for btnCategory##
for (int i = 0; i < MAX_CATEGORY; ++i) {
connect(btnCategoryGroup[i], SIGNAL(clicked()), signalMapperCategory, SLOT(map()));
signalMapperCategory->setMapping(btnCategoryGroup[i], i);
}
connect(signalMapperCategory, SIGNAL(mapped(int)), this, SLOT(categoryClicked(int)));
// for btnFunc##
for (int i = 0; i < MAX_FUNCTION; ++i) {
connect(btnFunctionGroup[i], SIGNAL(clicked()), signalMapperFunction, SLOT(map()));
signalMapperFunction->setMapping(btnFunctionGroup[i], i);
}
connect(signalMapperFunction, SIGNAL(mapped(int)), this, SLOT(functionClicked(int)));
connect(ui->actionClear, SIGNAL(triggered()), this, SLOT(clearTextArea()));
connect(ui->actionQuit, SIGNAL(triggered()), this, SLOT(close()));
connect(ui->lineEdit, SIGNAL(editingFinished()), this, SLOT(runLineCommand()));
}
// this SLOT will know which btnCategory## is clicked
void MainWindow::categoryClicked(int i)
{
m_category = i;
//qDebug() << "execCategory() " << m_category;
QString cat_name = m_conf->value(QString::number(i)).toString();
m_conf->beginGroup(cat_name);
int t = m_conf->value("total", 0).toInt();
//qDebug() << "t: " << t;
for (int i=0; i<MAX_FUNCTION; i++) {
if (i<t) {
QString but_name = QString("button") + QString::number(i);
QString but_text = m_conf->value(but_name, "").toString();
if (but_text == "") {
btnFunctionGroup[i]->setText( "" );
btnFunctionGroup[i]->setEnabled(false);
} else {
btnFunctionGroup[i]->setText( but_text );
btnFunctionGroup[i]->setEnabled(true);
}
} else {
btnFunctionGroup[i]->setText( "n/a" );
btnFunctionGroup[i]->setEnabled(false);
}
}
m_conf->endGroup();
}
// this SLOT will know which btnFunc## is clicked
void MainWindow::functionClicked(int i)
{
m_function = i;
//qDebug() << "execFunction() " << m_function << " of category " << m_category;
QString cat_name = m_conf->value(QString::number(m_category),"").toString();
if (cat_name == "") {
qDebug() << "cat_name is empty, exit...";
return;
}
//qDebug() << "cat_name: " << cat_name;
m_conf->beginGroup(cat_name);
QString act_name = "action" + QString::number(m_function);
QString act_value = m_conf->value(act_name, "").toString();
QString res, cmd;
res = "cat_name: " + cat_name + " action: " + act_name + " act_value: " + act_value;
cmd = act_value;
addline(cmd);
m_conf->endGroup();
if (cmd != "") {
runCommand(cmd);
}
}
QString MainWindow::composeString(const QString s, int i)
{
QString res;
res = s + QString::number(i);
return res;
}
void MainWindow::test()
{
}
void MainWindow::initCategory()
{
QString s;
int total = m_conf->value("total", MAX_CATEGORY).toInt();
//qDebug() << "total: " << total;
for (int i=0; i<total; i++) {
s = m_conf->value(s.number(i)).toString();
//qDebug() << "s: " << s;
if (i < MAX_CATEGORY) {
btnCategoryGroup[i]->setText( s );
btnCategoryGroup[i]->setEnabled(true);
} else {
ui->cbxCategory->addItem( s );
}
//qDebug() << m_conf->value(s.number(i)).toString();
}
}
void MainWindow::runCommand(const QString& cmd)
{
QProcess process;
process.start(cmd);
process.waitForFinished(-1); // will wait forever until finished
QString stdout = process.readAllStandardOutput();
QString stderr = process.readAllStandardError();
//qDebug() << "stdout: " << stdout;
//qDebug() << "stderr: " << stderr;
addline("========== stdout ==========");
addline(stdout);
if (stderr != "") {
addline("========== stderr ==========");
addline(stderr);
}
}
void MainWindow::addline(const QString &s)
{
ui->textEdit->append(s);
}
void MainWindow::clearTextArea()
{
ui->textEdit->clear();
}
void MainWindow::runLineCommand()
{
QString cmd = ui->lineEdit->text();
if (cmd != "") {
addline(cmd);
runCommand(cmd);
}
}
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QProcess>
#include <QDebug>
#include <QTextCodec>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
initButtonGroups();
signalMapperCategory = new QSignalMapper(this);
signalMapperFunction = new QSignalMapper(this);
initActionsConnections();
m_category = 0;
m_function = 0;
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
m_conf = new QSettings("/home/rasmus/test-tool.conf", QSettings::IniFormat);
m_conf->setIniCodec(codec);
initCategory();
ui->textEdit->setReadOnly(true);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::initButtonGroups()
{
#define INITCATEGORYBTN(n) \
btnCategoryGroup[n] = ui->btnCategory##n ; \
btnCategoryGroup[n]->setText(composeString("cat", n)); \
btnCategoryGroup[n]->setEnabled(false);
//btnCategoryGroup[n]->setVisible(false);
INITCATEGORYBTN(0);
INITCATEGORYBTN(1);
INITCATEGORYBTN(2);
INITCATEGORYBTN(3);
INITCATEGORYBTN(4);
#undef INITCATEGORYBTN
#define INITFUNCTIONBTN(n) \
btnFunctionGroup[n] = ui->btnFunc##n ; \
btnFunctionGroup[n]->setText(composeString("func", n)); \
btnFunctionGroup[n]->setEnabled(false);
INITFUNCTIONBTN(0);
INITFUNCTIONBTN(1);
INITFUNCTIONBTN(2);
INITFUNCTIONBTN(3);
INITFUNCTIONBTN(4);
INITFUNCTIONBTN(5);
INITFUNCTIONBTN(6);
INITFUNCTIONBTN(7);
INITFUNCTIONBTN(8);
INITFUNCTIONBTN(9);
#undef INITFUNCTIONBTN
}
void MainWindow::initActionsConnections()
{
// for btnCategory##
for (int i = 0; i < MAX_CATEGORY; ++i) {
connect(btnCategoryGroup[i], SIGNAL(clicked()), signalMapperCategory, SLOT(map()));
signalMapperCategory->setMapping(btnCategoryGroup[i], i);
}
connect(signalMapperCategory, SIGNAL(mapped(int)), this, SLOT(categoryClicked(int)));
// for btnFunc##
for (int i = 0; i < MAX_FUNCTION; ++i) {
connect(btnFunctionGroup[i], SIGNAL(clicked()), signalMapperFunction, SLOT(map()));
signalMapperFunction->setMapping(btnFunctionGroup[i], i);
}
connect(signalMapperFunction, SIGNAL(mapped(int)), this, SLOT(functionClicked(int)));
connect(ui->actionClear, SIGNAL(triggered()), this, SLOT(clearTextArea()));
connect(ui->actionQuit, SIGNAL(triggered()), this, SLOT(close()));
connect(ui->lineEdit, SIGNAL(returnPressed()), this, SLOT(runLineCommand()));
}
// this SLOT will know which btnCategory## is clicked
void MainWindow::categoryClicked(int i)
{
m_category = i;
//qDebug() << "execCategory() " << m_category;
QString cat_name = m_conf->value(QString::number(i)).toString();
m_conf->beginGroup(cat_name);
int t = m_conf->value("total", 0).toInt();
//qDebug() << "t: " << t;
for (int i=0; i<MAX_FUNCTION; i++) {
if (i<t) {
QString but_name = QString("button") + QString::number(i);
QString but_text = m_conf->value(but_name, "").toString();
if (but_text == "") {
btnFunctionGroup[i]->setText( "" );
btnFunctionGroup[i]->setEnabled(false);
} else {
btnFunctionGroup[i]->setText( but_text );
btnFunctionGroup[i]->setEnabled(true);
}
} else {
btnFunctionGroup[i]->setText( "n/a" );
btnFunctionGroup[i]->setEnabled(false);
}
}
m_conf->endGroup();
}
// this SLOT will know which btnFunc## is clicked
void MainWindow::functionClicked(int i)
{
m_function = i;
//qDebug() << "execFunction() " << m_function << " of category " << m_category;
QString cat_name = m_conf->value(QString::number(m_category),"").toString();
if (cat_name == "") {
qDebug() << "cat_name is empty, exit...";
return;
}
//qDebug() << "cat_name: " << cat_name;
m_conf->beginGroup(cat_name);
QString act_name = "action" + QString::number(m_function);
QString act_value = m_conf->value(act_name, "").toString();
QString res, cmd;
res = "cat_name: " + cat_name + " action: " + act_name + " act_value: " + act_value;
cmd = act_value;
addline(cmd);
m_conf->endGroup();
if (cmd != "") {
runCommand(cmd);
}
}
QString MainWindow::composeString(const QString s, int i)
{
QString res;
res = s + QString::number(i);
return res;
}
void MainWindow::test()
{
}
void MainWindow::initCategory()
{
QString s;
int total = m_conf->value("total", MAX_CATEGORY).toInt();
//qDebug() << "total: " << total;
for (int i=0; i<total; i++) {
s = m_conf->value(s.number(i)).toString();
//qDebug() << "s: " << s;
if (i < MAX_CATEGORY) {
btnCategoryGroup[i]->setText( s );
btnCategoryGroup[i]->setEnabled(true);
} else {
ui->cbxCategory->addItem( s );
}
//qDebug() << m_conf->value(s.number(i)).toString();
}
}
void MainWindow::runCommand(const QString& cmd)
{
QProcess process;
process.start(cmd);
process.waitForFinished(-1); // will wait forever until finished
QString stdout = process.readAllStandardOutput();
QString stderr = process.readAllStandardError();
//qDebug() << "stdout: " << stdout;
//qDebug() << "stderr: " << stderr;
addline("========== stdout ==========");
addline(stdout);
if (stderr != "") {
addline("========== stderr ==========");
addline(stderr);
}
}
void MainWindow::addline(const QString &s)
{
ui->textEdit->append(s);
}
void MainWindow::clearTextArea()
{
ui->textEdit->clear();
}
void MainWindow::runLineCommand()
{
QString cmd = ui->lineEdit->text();
if (cmd != "") {
addline(cmd);
runCommand(cmd);
}
}
|
update layout, use returnPressed() for QLineEdit
|
update layout, use returnPressed() for QLineEdit
|
C++
|
mit
|
ericosur/myqt,ericosur/myqt,ericosur/myqt,ericosur/myqt,ericosur/myqt,ericosur/myqt
|
7ed2c4ba86b40723c1db1ca12736b39e0d885a3e
|
src/kvazzupcontroller.cpp
|
src/kvazzupcontroller.cpp
|
#include "kvazzupcontroller.h"
#include "statisticsinterface.h"
#include "common.h"
#include <QSettings>
#include <QHostAddress>
KvazzupController::KvazzupController():
states_(),
media_(),
sip_(),
window_(nullptr),
stats_(nullptr),
delayAutoAccept_(),
delayedAutoAccept_(0)
{}
void KvazzupController::init()
{
printImportant(this, "Kvazzup initiation Started");
window_.init(this);
window_.show();
stats_ = window_.createStatsWindow();
sip_.init(this, stats_, window_.getStatusView());
// register the GUI signals indicating GUI changes to be handled
// approrietly in a system wide manner
QObject::connect(&window_, SIGNAL(settingsChanged()), this, SLOT(updateSettings()));
QObject::connect(&window_, SIGNAL(micStateSwitch()), this, SLOT(micState()));
QObject::connect(&window_, SIGNAL(cameraStateSwitch()), this, SLOT(cameraState()));
QObject::connect(&window_, SIGNAL(shareStateSwitch()), this, SLOT(shareState()));
QObject::connect(&window_, SIGNAL(endCall()), this, SLOT(endTheCall()));
QObject::connect(&window_, SIGNAL(closed()), this, SLOT(windowClosed()));
QObject::connect(&window_, &CallWindow::callAccepted,
this, &KvazzupController::userAcceptsCall);
QObject::connect(&window_, &CallWindow::callRejected,
this, &KvazzupController::userRejectsCall);
QObject::connect(&window_, &CallWindow::callCancelled,
this, &KvazzupController::userCancelsCall);
QObject::connect(&sip_, &SIPManager::nominationSucceeded,
this, &KvazzupController::iceCompleted);
QObject::connect(&sip_, &SIPManager::nominationFailed,
this, &KvazzupController::iceFailed);
media_.init(window_.getViewFactory(), stats_);
printImportant(this, "Kvazzup initiation finished");
}
void KvazzupController::uninit()
{
// for politeness, we send BYE messages to all our call participants.
endTheCall();
sip_.uninit();
media_.uninit();
}
void KvazzupController::windowClosed()
{
uninit();
}
uint32_t KvazzupController::callToParticipant(QString name, QString username, QString ip)
{
QString ip_str = ip;
SIP_URI uri;
uri.host = ip_str;
uri.realname = name;
uri.username = username;
uri.port = 0;
//start negotiations for this connection
printNormal(this, "Starting call with contact", {"Contact"}, {uri.realname});
return sip_.startCall(uri);
}
uint32_t KvazzupController::chatWithParticipant(QString name, QString username,
QString ip)
{
printDebug(DEBUG_NORMAL, this, "Starting a chat with contact",
{"ip", "Name", "Username"}, {ip, name, username});
return 0;
}
void KvazzupController::outgoingCall(uint32_t sessionID, QString callee)
{
window_.displayOutgoingCall(sessionID, callee);
if(states_.find(sessionID) == states_.end())
{
states_[sessionID] = CALLINGTHEM;
}
}
bool KvazzupController::incomingCall(uint32_t sessionID, QString caller)
{
if(states_.find(sessionID) != states_.end())
{
printProgramError(this, "Incoming call is overwriting an existing session!");
}
QSettings settings("kvazzup.ini", QSettings::IniFormat);
int autoAccept = settings.value("local/Auto-Accept").toInt();
if(autoAccept == 1)
{
printNormal(this, "Incoming call auto-accepted");
// make sure there are no ongoing auto-accepts
while (delayedAutoAccept_ != 0)
{
qSleep(10);
}
delayedAutoAccept_ = sessionID;
delayAutoAccept_.singleShot(100, this, &KvazzupController::delayedAutoAccept);
return false;
}
else
{
printNormal(this, "Showing incoming call");
states_[sessionID] = CALLRINGINGWITHUS;
window_.displayIncomingCall(sessionID, caller);
}
return false;
}
void KvazzupController::delayedAutoAccept()
{
userAcceptsCall(delayedAutoAccept_);
delayedAutoAccept_ = 0;
}
void KvazzupController::callRinging(uint32_t sessionID)
{
// TODO_RFC 3261: Enable cancelling the request at this point
// to make sure the original request has been received
if(states_.find(sessionID) != states_.end() && states_[sessionID] == CALLINGTHEM)
{
printNormal(this, "Our call is ringing");
window_.displayRinging(sessionID);
states_[sessionID] = CALLRINGINWITHTHEM;
}
else
{
printPeerError(this, "Got call ringing for nonexisting call",
{"SessionID"}, {sessionID});
}
}
void KvazzupController::peerAccepted(uint32_t sessionID)
{
if(states_.find(sessionID) != states_.end())
{
if(states_[sessionID] == CALLRINGINWITHTHEM || states_[sessionID] == CALLINGTHEM)
{
printImportant(this, "They accepted our call!");
states_[sessionID] = CALLNEGOTIATING;
}
else
{
printPeerError(this, "Got an accepted call even though we have not yet called them!");
}
}
else
{
printPeerError(this, "Peer accepted a session which is not in Controller.");
}
}
void KvazzupController::iceCompleted(quint32 sessionID)
{
printNormal(this, "ICE has been successfully completed",
{"SessionID"}, {QString::number(sessionID)});
startCall(sessionID, true);
}
void KvazzupController::callNegotiated(uint32_t sessionID)
{
printNormal(this, "Call negotiated");
startCall(sessionID, false);
}
void KvazzupController::startCall(uint32_t sessionID, bool iceNominationComplete)
{
if (iceNominationComplete)
{
if(states_.find(sessionID) != states_.end())
{
if(states_[sessionID] == CALLNEGOTIATING || states_[sessionID] == CALLONGOING)
{
if (states_[sessionID] == CALLONGOING)
{
// we have to remove previous media so we do not double them.
media_.removeParticipant(sessionID);
window_.removeParticipant(sessionID);
}
createSingleCall(sessionID);
}
else
{
printPeerError(this, "Got call successful negotiation "
"even though we are not there yet.",
"State", {states_[sessionID]});
}
}
else
{
printProgramError(this, "The call state does not exist when starting the call.",
{"SessionID"}, {sessionID});
}
}
printNormal(this, "Waiting for the ICE to finish before starting the call.");
}
void KvazzupController::iceFailed(uint32_t sessionID)
{
printError(this, "ICE has failed");
// TODO: Tell sip manager to send an error for ICE
printUnimplemented(this, "Send SIP error code for ICE failure");
endCall(sessionID);
}
void KvazzupController::createSingleCall(uint32_t sessionID)
{
printNormal(this, "Call has been agreed upon with peer.",
"SessionID", {QString::number(sessionID)});
std::shared_ptr<SDPMessageInfo> localSDP;
std::shared_ptr<SDPMessageInfo> remoteSDP;
sip_.getSDPs(sessionID,
localSDP,
remoteSDP);
for (auto& media : localSDP->media)
{
if (media.type == "video" && (media.flagAttributes.empty()
|| media.flagAttributes.at(0) == A_SENDRECV
|| media.flagAttributes.at(0) == A_RECVONLY))
{
window_.addVideoStream(sessionID);
}
}
if(localSDP == nullptr || remoteSDP == nullptr)
{
printError(this, "Failed to get SDP. Error should be detected earlier.");
return;
}
if (stats_)
{
stats_->addSession(sessionID);
}
media_.addParticipant(sessionID, remoteSDP, localSDP); states_[sessionID] = CALLONGOING;
}
void KvazzupController::cancelIncomingCall(uint32_t sessionID)
{
removeSession(sessionID, "They cancelled", true);
}
void KvazzupController::endCall(uint32_t sessionID)
{
printNormal(this, "Ending the call", {"SessionID"}, {sessionID});
if (states_.find(sessionID) != states_.end() &&
states_[sessionID] == CALLONGOING)
{
media_.removeParticipant(sessionID);
}
removeSession(sessionID, "Call ended", true);
sip_.uninitSession(sessionID);
}
void KvazzupController::failure(uint32_t sessionID, QString error)
{
if (states_.find(sessionID) != states_.end())
{
if (states_[sessionID] == CALLINGTHEM)
{
printImportant(this, "Our call failed. Invalid sip address?");
}
else if(states_[sessionID] == CALLRINGINWITHTHEM)
{
printImportant(this, "Our call has been rejected!");
}
else
{
printPeerError(this, "Got reject when we weren't calling them", "SessionID", {sessionID});
}
removeSession(sessionID, error, false);
}
else
{
printPeerError(this, "Got reject for nonexisting call", "SessionID", {sessionID});
printPeerError(this, "", "Ongoing sessions", {QString::number(states_.size())});
}
}
void KvazzupController::registeredToServer()
{
printImportant(this, "We have been registered to a SIP server.");
// TODO: indicate to user in some small detail
}
void KvazzupController::registeringFailed()
{
printError(this, "Failed to register to a SIP server.");
// TODO: indicate error to user
}
void KvazzupController::updateSettings()
{
media_.updateSettings();
sip_.updateSettings();
}
void KvazzupController::userAcceptsCall(uint32_t sessionID)
{
printNormal(this, "We accept");
states_[sessionID] = CALLNEGOTIATING;
sip_.acceptCall(sessionID);
}
void KvazzupController::userRejectsCall(uint32_t sessionID)
{
printNormal(this, "We reject");
sip_.rejectCall(sessionID);
removeSession(sessionID, "Rejected", true);
}
void KvazzupController::userCancelsCall(uint32_t sessionID)
{
printNormal(this, "We cancel our call");
sip_.cancelCall(sessionID);
removeSession(sessionID, "Cancelled", true);
}
void KvazzupController::endTheCall()
{
printImportant(this, "We end the call");
sip_.endAllCalls();
}
void KvazzupController::micState()
{
// TODO: Get this to change the icon faster
window_.setMicState(media_.toggleMic());
}
void KvazzupController::cameraState()
{
// TODO: Get this to change the icon faster
window_.setCameraState(media_.toggleCamera());
}
void KvazzupController::shareState()
{
printNormal(this, "Toggling screen sharing");
media_.toggleScreenShare();
}
void KvazzupController::removeSession(uint32_t sessionID, QString message,
bool temporaryMessage)
{
if (message == "" || message.isEmpty())
{
window_.removeParticipant(sessionID);
}
else
{
window_.removeWithMessage(sessionID, message, temporaryMessage);
}
auto it = states_.find(sessionID);
if(it != states_.end())
{
states_.erase(it);
}
if (stats_)
{
stats_->removeSession(sessionID);
}
}
|
#include "kvazzupcontroller.h"
#include "statisticsinterface.h"
#include "common.h"
#include <QSettings>
#include <QHostAddress>
KvazzupController::KvazzupController():
states_(),
media_(),
sip_(),
window_(nullptr),
stats_(nullptr),
delayAutoAccept_(),
delayedAutoAccept_(0)
{}
void KvazzupController::init()
{
printImportant(this, "Kvazzup initiation Started");
window_.init(this);
window_.show();
stats_ = window_.createStatsWindow();
sip_.init(this, stats_, window_.getStatusView());
// register the GUI signals indicating GUI changes to be handled
// approrietly in a system wide manner
QObject::connect(&window_, SIGNAL(settingsChanged()), this, SLOT(updateSettings()));
QObject::connect(&window_, SIGNAL(micStateSwitch()), this, SLOT(micState()));
QObject::connect(&window_, SIGNAL(cameraStateSwitch()), this, SLOT(cameraState()));
QObject::connect(&window_, SIGNAL(shareStateSwitch()), this, SLOT(shareState()));
QObject::connect(&window_, SIGNAL(endCall()), this, SLOT(endTheCall()));
QObject::connect(&window_, SIGNAL(closed()), this, SLOT(windowClosed()));
QObject::connect(&window_, &CallWindow::callAccepted,
this, &KvazzupController::userAcceptsCall);
QObject::connect(&window_, &CallWindow::callRejected,
this, &KvazzupController::userRejectsCall);
QObject::connect(&window_, &CallWindow::callCancelled,
this, &KvazzupController::userCancelsCall);
QObject::connect(&sip_, &SIPManager::nominationSucceeded,
this, &KvazzupController::iceCompleted);
QObject::connect(&sip_, &SIPManager::nominationFailed,
this, &KvazzupController::iceFailed);
media_.init(window_.getViewFactory(), stats_);
printImportant(this, "Kvazzup initiation finished");
}
void KvazzupController::uninit()
{
// for politeness, we send BYE messages to all our call participants.
endTheCall();
sip_.uninit();
media_.uninit();
}
void KvazzupController::windowClosed()
{
uninit();
}
uint32_t KvazzupController::callToParticipant(QString name, QString username, QString ip)
{
QString ip_str = ip;
SIP_URI uri;
uri.host = ip_str;
uri.realname = name;
uri.username = username;
uri.port = 0;
//start negotiations for this connection
printNormal(this, "Starting call with contact", {"Contact"}, {uri.realname});
return sip_.startCall(uri);
}
uint32_t KvazzupController::chatWithParticipant(QString name, QString username,
QString ip)
{
printDebug(DEBUG_NORMAL, this, "Starting a chat with contact",
{"ip", "Name", "Username"}, {ip, name, username});
return 0;
}
void KvazzupController::outgoingCall(uint32_t sessionID, QString callee)
{
window_.displayOutgoingCall(sessionID, callee);
if(states_.find(sessionID) == states_.end())
{
states_[sessionID] = CALLINGTHEM;
}
}
bool KvazzupController::incomingCall(uint32_t sessionID, QString caller)
{
if(states_.find(sessionID) != states_.end())
{
printProgramError(this, "Incoming call is overwriting an existing session!");
}
QSettings settings("kvazzup.ini", QSettings::IniFormat);
int autoAccept = settings.value("local/Auto-Accept").toInt();
if(autoAccept == 1)
{
printNormal(this, "Incoming call auto-accepted");
// make sure there are no ongoing auto-accepts
while (delayedAutoAccept_ != 0)
{
qSleep(10);
}
delayedAutoAccept_ = sessionID;
delayAutoAccept_.singleShot(100, this, &KvazzupController::delayedAutoAccept);
return false;
}
else
{
printNormal(this, "Showing incoming call");
states_[sessionID] = CALLRINGINGWITHUS;
window_.displayIncomingCall(sessionID, caller);
}
return false;
}
void KvazzupController::delayedAutoAccept()
{
userAcceptsCall(delayedAutoAccept_);
delayedAutoAccept_ = 0;
}
void KvazzupController::callRinging(uint32_t sessionID)
{
// TODO_RFC 3261: Enable cancelling the request at this point
// to make sure the original request has been received
if(states_.find(sessionID) != states_.end() && states_[sessionID] == CALLINGTHEM)
{
printNormal(this, "Our call is ringing");
window_.displayRinging(sessionID);
states_[sessionID] = CALLRINGINWITHTHEM;
}
else
{
printPeerError(this, "Got call ringing for nonexisting call",
{"SessionID"}, {sessionID});
}
}
void KvazzupController::peerAccepted(uint32_t sessionID)
{
if(states_.find(sessionID) != states_.end())
{
if(states_[sessionID] == CALLRINGINWITHTHEM || states_[sessionID] == CALLINGTHEM)
{
printImportant(this, "They accepted our call!");
states_[sessionID] = CALLNEGOTIATING;
}
else
{
printPeerError(this, "Got an accepted call even though we have not yet called them!");
}
}
else
{
printPeerError(this, "Peer accepted a session which is not in Controller.");
}
}
void KvazzupController::iceCompleted(quint32 sessionID)
{
printNormal(this, "ICE has been successfully completed",
{"SessionID"}, {QString::number(sessionID)});
startCall(sessionID, true);
}
void KvazzupController::callNegotiated(uint32_t sessionID)
{
printNormal(this, "Call negotiated");
startCall(sessionID, false);
}
void KvazzupController::startCall(uint32_t sessionID, bool iceNominationComplete)
{
if (iceNominationComplete)
{
if(states_.find(sessionID) != states_.end())
{
if(states_[sessionID] == CALLNEGOTIATING || states_[sessionID] == CALLONGOING)
{
if (states_[sessionID] == CALLONGOING)
{
// we have to remove previous media so we do not double them.
media_.removeParticipant(sessionID);
window_.removeParticipant(sessionID);
}
createSingleCall(sessionID);
}
else
{
printPeerError(this, "Got call successful negotiation "
"even though we are not there yet.",
"State", {states_[sessionID]});
}
}
else
{
printProgramError(this, "The call state does not exist when starting the call.",
{"SessionID"}, {sessionID});
}
}
printNormal(this, "Waiting for the ICE to finish before starting the call.");
}
void KvazzupController::iceFailed(uint32_t sessionID)
{
printError(this, "ICE has failed");
// TODO: Tell sip manager to send an error for ICE
printUnimplemented(this, "Send SIP error code for ICE failure");
endCall(sessionID);
}
void KvazzupController::createSingleCall(uint32_t sessionID)
{
printNormal(this, "Call has been agreed upon with peer.",
"SessionID", {QString::number(sessionID)});
std::shared_ptr<SDPMessageInfo> localSDP;
std::shared_ptr<SDPMessageInfo> remoteSDP;
sip_.getSDPs(sessionID,
localSDP,
remoteSDP);
for (auto& media : localSDP->media)
{
if (media.type == "video" && (media.flagAttributes.empty()
|| media.flagAttributes.at(0) == A_SENDRECV
|| media.flagAttributes.at(0) == A_RECVONLY))
{
window_.addVideoStream(sessionID);
}
}
if(localSDP == nullptr || remoteSDP == nullptr)
{
printError(this, "Failed to get SDP. Error should be detected earlier.");
return;
}
if (stats_)
{
stats_->addSession(sessionID);
}
media_.addParticipant(sessionID, remoteSDP, localSDP); states_[sessionID] = CALLONGOING;
}
void KvazzupController::cancelIncomingCall(uint32_t sessionID)
{
removeSession(sessionID, "They cancelled", true);
}
void KvazzupController::endCall(uint32_t sessionID)
{
printNormal(this, "Ending the call", {"SessionID"}, {QString::number(sessionID)});
if (states_.find(sessionID) != states_.end() &&
states_[sessionID] == CALLONGOING)
{
media_.removeParticipant(sessionID);
}
removeSession(sessionID, "Call ended", true);
sip_.uninitSession(sessionID);
}
void KvazzupController::failure(uint32_t sessionID, QString error)
{
if (states_.find(sessionID) != states_.end())
{
if (states_[sessionID] == CALLINGTHEM)
{
printImportant(this, "Our call failed. Invalid sip address?");
}
else if(states_[sessionID] == CALLRINGINWITHTHEM)
{
printImportant(this, "Our call has been rejected!");
}
else
{
printPeerError(this, "Got reject when we weren't calling them", "SessionID", {sessionID});
}
removeSession(sessionID, error, false);
}
else
{
printPeerError(this, "Got reject for nonexisting call", "SessionID", {sessionID});
printPeerError(this, "", "Ongoing sessions", {QString::number(states_.size())});
}
}
void KvazzupController::registeredToServer()
{
printImportant(this, "We have been registered to a SIP server.");
// TODO: indicate to user in some small detail
}
void KvazzupController::registeringFailed()
{
printError(this, "Failed to register to a SIP server.");
// TODO: indicate error to user
}
void KvazzupController::updateSettings()
{
media_.updateSettings();
sip_.updateSettings();
}
void KvazzupController::userAcceptsCall(uint32_t sessionID)
{
printNormal(this, "We accept");
states_[sessionID] = CALLNEGOTIATING;
sip_.acceptCall(sessionID);
}
void KvazzupController::userRejectsCall(uint32_t sessionID)
{
printNormal(this, "We reject");
sip_.rejectCall(sessionID);
removeSession(sessionID, "Rejected", true);
}
void KvazzupController::userCancelsCall(uint32_t sessionID)
{
printNormal(this, "We cancel our call");
sip_.cancelCall(sessionID);
removeSession(sessionID, "Cancelled", true);
}
void KvazzupController::endTheCall()
{
printImportant(this, "We end the call");
sip_.endAllCalls();
}
void KvazzupController::micState()
{
// TODO: Get this to change the icon faster
window_.setMicState(media_.toggleMic());
}
void KvazzupController::cameraState()
{
// TODO: Get this to change the icon faster
window_.setCameraState(media_.toggleCamera());
}
void KvazzupController::shareState()
{
printNormal(this, "Toggling screen sharing");
media_.toggleScreenShare();
}
void KvazzupController::removeSession(uint32_t sessionID, QString message,
bool temporaryMessage)
{
if (message == "" || message.isEmpty())
{
window_.removeParticipant(sessionID);
}
else
{
window_.removeWithMessage(sessionID, message, temporaryMessage);
}
auto it = states_.find(sessionID);
if(it != states_.end())
{
states_.erase(it);
}
if (stats_)
{
stats_->removeSession(sessionID);
}
}
|
Print SessionID correctly
|
fix(Controller): Print SessionID correctly
|
C++
|
isc
|
ultravideo/kvazzup,ultravideo/kvazzup
|
280cf61767ebbea353fb5c99dc1202ef01d93c92
|
ImageProcessing/Utils/imageprocessingutils.cpp
|
ImageProcessing/Utils/imageprocessingutils.cpp
|
#include "imageprocessingutils.h"
#include <cmath>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
#define D_DEBUG 0
// from OpenCV Samples
// finds a cosine of angle between vectors from pt0->pt1 and from pt0->pt2
double image_processing_utils::findAngle(Point p1, Point p2, Point p0)
{
double dx1 = p1.x - p0.x;
double dy1 = p1.y - p0.y;
double dx2 = p2.x - p0.x;
double dy2 = p2.y - p0.y;
return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
}
// from OpenCV Samples
// returns sequence of squares detected on the image, with a specific size in ratio.
std::vector<std::vector<cv::Point>> image_processing_utils::findSquares(const Mat& image, double minAreaPercentageFilter, double maxAreaPercentageFilter, double wholeArea, const int thresh, const int N)
{
std::vector<std::vector<Point>> squares;
Mat pyr, timg, gray0(image.size(), CV_8U), gray;
// down-scale and upscale the image to filter out the noise
pyrDown(image, pyr, Size(image.cols/2, image.rows/2));
pyrUp(pyr, timg, image.size());
vector<vector<Point> > contours;
// find squares in every color plane of the image
for (int c = 0; c < 3; ++c)
{
int ch[] = {c, 0};
mixChannels(&timg, 1, &gray0, 1, ch, 1);
// try several threshold levels
for (int l = 0; l < N; ++l)
{
// hack: use Canny instead of zero threshold level.
// Canny helps to catch squares with gradient shading
if (l == 0)
{
// apply Canny. Take the upper threshold from slider and set the lower to 0 (which forces edges merging)
Canny(gray0, gray, 0, thresh, 5);
// dilate canny output to remove potential holes between edge segments
dilate(gray, gray, Mat(), Point(-1,-1));
}
else
// apply threshold if l!=0: tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
gray = gray0 >= (l+1)*255/N;
// find contours and store them all as a list
findContours(gray, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
vector<Point> approx;
for (auto& contour : contours)
{
// approximate contour with accuracy proportional to the contour perimeter
approxPolyDP(Mat(contour), approx, arcLength(Mat(contour), true)*0.02, true);
// square contours should have 4 vertices after approximation relatively large area (to filter out noisy contours) and be convex.
double area = 100.0*fabs(contourArea(Mat(approx)))/wholeArea;
if (approx.size() == 4 && area >= minAreaPercentageFilter && area <= maxAreaPercentageFilter && isContourConvex(Mat(approx)))
{
double maxCosine = 0;
for ( int j = 2; j < 5; j++ )
// find the maximum cosine of the angle between joint edges
maxCosine = std::max(maxCosine, fabs(image_processing_utils::findAngle(approx[j%4], approx[j-2], approx[j-1])));
// if cosines of all angles are small (all angles are ~90 degree) then write quandrange vertices to resultant sequence
if (maxCosine < 0.3)
squares.push_back(approx);
}
}
}
}
return squares;
}
void image_processing_utils::drawSquares(Mat& image, const std::vector<std::vector<Point>>& squares, bool R, bool G, bool B)
{
for (auto& square : squares)
{
const Point* p = &square[0];
int n = (int)square.size();
char r,g,b;
r = g = b = 0;
if(R)
r = 255;
else if(G)
g = 255;
else if(B)
b = 255;
else
r = g = b = 128;
polylines(image, &p, &n, 1, true, Scalar(r,g,b), 3, CV_AA);
}
}
Mat image_processing_utils::captureSoduku(const int minAreaPercentageFilter, const int maxAreaPercentageFilter, std::vector<Point>& square, const int nbIteration)
{
VideoCapture capture(0);//0 = default and we assume it always exists
int width = capture.get(CV_CAP_PROP_FRAME_WIDTH);
int height = capture.get(CV_CAP_PROP_FRAME_HEIGHT);
bool isASudokuCaptured = false;
Mat sudoku;
namedWindow(image_processing_utils::WEBCAM_WINDOW_TITLE, CV_WINDOW_AUTOSIZE);
int ithIteration = 1;
while(waitKey(10) < 0 && !isASudokuCaptured)
{
Mat frame;
capture >> frame;
std::vector<std::vector<Point>> squares = image_processing_utils::findSquares(frame, minAreaPercentageFilter, maxAreaPercentageFilter, width*height);
if(squares.size() > 0)
{
isASudokuCaptured = ++ithIteration >= nbIteration;
sudoku = frame.clone();
square = *std::min_element(squares.begin(), squares.end(), [](const vector<Point>& p1, const vector<Point>& p2) -> bool {return contourArea(p1) < contourArea(p2);});
squares.clear();
squares.push_back(square);
}
drawSquares(frame, squares);
imshow(image_processing_utils::WEBCAM_WINDOW_TITLE, frame);
}
return sudoku;
}
//Sort the points of a quadrilateral in the following order : TopL, TopR, BoR, BoL
void image_processing_utils::prepareQuadri(std::vector<Point>& quadri)
{
std::sort(quadri.begin(), quadri.end(), [](const Point& a, const Point& b) -> bool {return a.x < b.x;});
//Find topL and botL
Point topL, botL;
bool topLbotL= quadri[0].y > quadri[1].y;
topL = quadri[topLbotL ? 1 : 0];
botL = quadri[topLbotL ? 0 : 1];
Point topR, botR;
bool topRbotR = quadri[2].y > quadri[3].y;
topR = quadri[topRbotR ? 3 : 2];
botR = quadri[topRbotR ? 2 : 3];
quadri.clear();
quadri.push_back(topL);
quadri.push_back(topR);
quadri.push_back(botR);
quadri.push_back(botL);
}
Mat image_processing_utils::cropPicture(const std::vector<Point>& srcQuadri, const Mat& srcImg, const int w, const int h)
{
std::vector<Point> quadri(srcQuadri);
image_processing_utils::prepareQuadri(quadri);
Mat dstImg;
dstImg.create(srcImg.size(), srcImg.type());
Point2f srcPoints[4];
Point2f dstPoints[4];
dstPoints[0] = Point2f(0, 0);
dstPoints[1] = Point2f(w, 0);
dstPoints[2] = Point2f(w, h);
dstPoints[3] = Point2f(0, h);
for(int i = 0; i < quadri.size(); ++i)
srcPoints[i] = quadri[i];
warpPerspective(srcImg, dstImg, getPerspectiveTransform(srcPoints, dstPoints), Size(w, h));
#if D_DEBUG
Mat img = dstImg.clone();
namedWindow(image_processing_utils::CROP_SUDOKU_WINDOW_TITLE, CV_WINDOW_AUTOSIZE);
imshow(image_processing_utils::CROP_SUDOKU_WINDOW_TITLE, img);
#endif
return dstImg;
}
//Return true if we found the 81 squares of the sudoku
bool image_processing_utils::removeDuplicateSquares(std::vector<std::vector<Point>>& squares)
{
std::vector<Rect> rectangles;
for(auto& square : squares)
rectangles.push_back(boundingRect(square));
std::vector<Point> gCenters;
for(auto& square : squares)
{
Point p(0,0);
for(int i = 0; i < 4; ++i)
{
p.x += square[i].x;
p.y += square[i].y;
}
p.x /= 4.0;
p.y /= 4.0;
gCenters.push_back(p);
}
std::vector<std::vector<Point>> squaresCopy(squares);
std::vector<bool> visited(rectangles.size(), false);
squares.clear();
for(auto& g : gCenters)
{
std::vector<std::vector<Point>> rect;
for(int j = 0; j < rectangles.size(); ++j)
if(!visited[j] && rectangles[j].contains(g))
{
visited[j] = true;
rect.push_back(squaresCopy[j]);
}
if(rect.size() > 0)
{
sort(rect.begin(), rect.end(), [](const vector<Point>& p1, const vector<Point>&p2) -> bool {return contourArea(p1) > contourArea(p2);});
squares.push_back(rect[0]);
}
}
return squares.size() == image_processing_utils::SUDOKU_SIZE*image_processing_utils::SUDOKU_SIZE;
}
//Sort the squares by order where they appeared in the sudoku in row major order
std::vector<std::vector<Point>> image_processing_utils::labelling(const std::vector<std::vector<Point>>& squares)
{
std::vector<std::vector<Point>> sortedSquares(squares);
for(auto& square : sortedSquares)
image_processing_utils::prepareQuadri(square);
std::vector<std::vector<Point>> labels;
std::vector<std::vector<Point>> rows;
for(int i = 0; i < image_processing_utils::SUDOKU_SIZE; ++i)
{
rows.clear();
//Sort by row
std::sort(sortedSquares.begin(), sortedSquares.end(), [](const vector<Point>& p1, const vector<Point>& p2) -> bool {return p1[0].y > p2[0].y;});
//Then sort by col
for(int j = 0; j < image_processing_utils::SUDOKU_SIZE; ++j)
{
rows.push_back(sortedSquares.back());
std::sort(rows.begin(), rows.end(), [](const vector<Point>& p1, const vector<Point>& p2) -> bool {return p1[0].x < p2[0].x;});
sortedSquares.pop_back();
}
for(auto& square : rows)
labels.push_back(square);
}
return labels;
}
std::vector<Mat> image_processing_utils::extractBlocks(const std::vector<std::vector<Point>>& unlabeledSquares, const Mat& image)
{
std::vector<std::vector<Point>> squares = image_processing_utils::labelling(unlabeledSquares);
#if D_DEBUG
Mat img = image.clone();
drawSquares(sudoku, squares, 0, true, 0);
int i = 0;
for(auto& square : squares)
{
string lbl = to_string(i++);
putText(img, lbl, Point(15+square[0].x,15+square[0].y), FONT_HERSHEY_SIMPLEX, 1, Scalar(255, 0, 0));
}
namedWindow(image_processing_utils::LABELED_SUDOKU_WINDOW_TITLE, CV_WINDOW_AUTOSIZE);
imshow(image_processing_utils::LABELED_SUDOKU_WINDOW_TITLE, img);
#endif
vector<Mat> blocks;
int w = 0;
int h = 0;
for(auto& square : squares)
{
w += abs(square[1].x-square[0].x);
h += abs(square[3].y-square[0].y);
}
w /= squares.size();
h /= squares.size();
for(auto& square : squares)
blocks.push_back(image_processing_utils::cropPicture(square, image, w, h));
for(auto& b : blocks)
b = b > 128;
return blocks;
}
//Extract digit block with their id, in row major order, starting at 0
std::vector<std::pair<int, Mat>> image_processing_utils::extractDigitBlocks(const std::vector<Mat>& allBlocks, const int w, const int h)
{
std::vector<Mat> blocks(allBlocks);
std::vector<std::pair<int, Mat>> digits;
int id = 0;
for(auto& b : blocks)
{
++id;
double white = 0;
for(int j = 0; j < b.rows; ++j)
for(int i = 0; i < b.cols; ++i)
if (static_cast<int>(b.at<uchar>(j, i)) == 255)
++white;
//Filter percentage of white
int v = 100*white/(b.rows*b.cols);
if(v < 98 && v > 60)
{
resize(b, b, Size(w, h));
digits.push_back(std::pair<int, Mat>(id-1, b));
}
}
return digits;
}
double image_processing_utils::computeAreaContour(const std::vector<cv::Point>& contour)
{
return cv::contourArea(contour);
}
|
#include "imageprocessingutils.h"
#include <cmath>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
#define D_DEBUG 0
// from OpenCV Samples
// finds a cosine of angle between vectors from pt0->pt1 and from pt0->pt2
double image_processing_utils::findAngle(Point p1, Point p2, Point p0)
{
double dx1 = p1.x - p0.x;
double dy1 = p1.y - p0.y;
double dx2 = p2.x - p0.x;
double dy2 = p2.y - p0.y;
return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
}
// from OpenCV Samples
// returns sequence of squares detected on the image, with a specific size in ratio.
std::vector<std::vector<cv::Point>> image_processing_utils::findSquares(const Mat& image, double minAreaPercentageFilter, double maxAreaPercentageFilter, double wholeArea, const int thresh, const int N)
{
std::vector<std::vector<Point>> squares;
Mat pyr, timg, gray0(image.size(), CV_8U), gray;
// down-scale and upscale the image to filter out the noise
pyrDown(image, pyr, Size(image.cols/2, image.rows/2));
pyrUp(pyr, timg, image.size());
vector<vector<Point> > contours;
// find squares in every color plane of the image
for (int c = 0; c < 3; ++c)
{
int ch[] = {c, 0};
mixChannels(&timg, 1, &gray0, 1, ch, 1);
// try several threshold levels
for (int l = 0; l < N; ++l)
{
// hack: use Canny instead of zero threshold level.
// Canny helps to catch squares with gradient shading
if (l == 0)
{
// apply Canny. Take the upper threshold from slider and set the lower to 0 (which forces edges merging)
Canny(gray0, gray, 0, thresh, 5);
// dilate canny output to remove potential holes between edge segments
dilate(gray, gray, Mat(), Point(-1,-1));
}
else
// apply threshold if l!=0: tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
gray = gray0 >= (l+1)*255/N;
// find contours and store them all as a list
findContours(gray, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
vector<Point> approx;
for (auto& contour : contours)
{
// approximate contour with accuracy proportional to the contour perimeter
approxPolyDP(Mat(contour), approx, arcLength(Mat(contour), true)*0.02, true);
// square contours should have 4 vertices after approximation relatively large area (to filter out noisy contours) and be convex.
double area = 100.0*fabs(contourArea(Mat(approx)))/wholeArea;
if (approx.size() == 4 && area >= minAreaPercentageFilter && area <= maxAreaPercentageFilter && isContourConvex(Mat(approx)))
{
double maxCosine = 0;
for ( int j = 2; j < 5; j++ )
// find the maximum cosine of the angle between joint edges
maxCosine = std::max(maxCosine, fabs(image_processing_utils::findAngle(approx[j%4], approx[j-2], approx[j-1])));
// if cosines of all angles are small (all angles are ~90 degree) then write quandrange vertices to resultant sequence
if (maxCosine < 0.3)
squares.push_back(approx);
}
}
}
}
return squares;
}
void image_processing_utils::drawSquares(Mat& image, const std::vector<std::vector<Point>>& squares, bool R, bool G, bool B)
{
for (auto& square : squares)
{
const Point* p = &square[0];
int n = (int)square.size();
int r,g,b;
r = g = b = 0;
if(R)
r = 255;
else if(G)
g = 255;
else if(B)
b = 255;
else
r = g = b = 128;
polylines(image, &p, &n, 1, true, Scalar(b, g, r), 3, CV_AA);
}
}
Mat image_processing_utils::captureSoduku(const int minAreaPercentageFilter, const int maxAreaPercentageFilter, std::vector<Point>& square, const int nbIteration)
{
VideoCapture capture(0);//0 = default and we assume it always exists
int width = capture.get(CV_CAP_PROP_FRAME_WIDTH);
int height = capture.get(CV_CAP_PROP_FRAME_HEIGHT);
bool isASudokuCaptured = false;
Mat sudoku;
namedWindow(image_processing_utils::WEBCAM_WINDOW_TITLE, CV_WINDOW_AUTOSIZE);
int ithIteration = 1;
while(waitKey(10) < 0 && !isASudokuCaptured)
{
Mat frame;
capture >> frame;
std::vector<std::vector<Point>> squares = image_processing_utils::findSquares(frame, minAreaPercentageFilter, maxAreaPercentageFilter, width*height);
if(squares.size() > 0)
{
isASudokuCaptured = ++ithIteration >= nbIteration;
sudoku = frame.clone();
square = *std::min_element(squares.begin(), squares.end(), [](const vector<Point>& p1, const vector<Point>& p2) -> bool {return contourArea(p1) < contourArea(p2);});
squares.clear();
squares.push_back(square);
}
drawSquares(frame, squares, true);
imshow(image_processing_utils::WEBCAM_WINDOW_TITLE, frame);
}
return sudoku;
}
//Sort the points of a quadrilateral in the following order : TopL, TopR, BoR, BoL
void image_processing_utils::prepareQuadri(std::vector<Point>& quadri)
{
std::sort(quadri.begin(), quadri.end(), [](const Point& a, const Point& b) -> bool {return a.x < b.x;});
//Find topL and botL
Point topL, botL;
bool topLbotL= quadri[0].y > quadri[1].y;
topL = quadri[topLbotL ? 1 : 0];
botL = quadri[topLbotL ? 0 : 1];
Point topR, botR;
bool topRbotR = quadri[2].y > quadri[3].y;
topR = quadri[topRbotR ? 3 : 2];
botR = quadri[topRbotR ? 2 : 3];
quadri.clear();
quadri.push_back(topL);
quadri.push_back(topR);
quadri.push_back(botR);
quadri.push_back(botL);
}
Mat image_processing_utils::cropPicture(const std::vector<Point>& srcQuadri, const Mat& srcImg, const int w, const int h)
{
std::vector<Point> quadri(srcQuadri);
image_processing_utils::prepareQuadri(quadri);
Mat dstImg;
dstImg.create(srcImg.size(), srcImg.type());
Point2f srcPoints[4];
Point2f dstPoints[4];
dstPoints[0] = Point2f(0, 0);
dstPoints[1] = Point2f(w, 0);
dstPoints[2] = Point2f(w, h);
dstPoints[3] = Point2f(0, h);
for(int i = 0; i < quadri.size(); ++i)
srcPoints[i] = quadri[i];
warpPerspective(srcImg, dstImg, getPerspectiveTransform(srcPoints, dstPoints), Size(w, h));
#if D_DEBUG
Mat img = dstImg.clone();
namedWindow(image_processing_utils::CROP_SUDOKU_WINDOW_TITLE, CV_WINDOW_AUTOSIZE);
imshow(image_processing_utils::CROP_SUDOKU_WINDOW_TITLE, img);
#endif
return dstImg;
}
//Return true if we found the 81 squares of the sudoku
bool image_processing_utils::removeDuplicateSquares(std::vector<std::vector<Point>>& squares)
{
std::vector<Rect> rectangles;
for(auto& square : squares)
rectangles.push_back(boundingRect(square));
std::vector<Point> gCenters;
for(auto& square : squares)
{
Point p(0,0);
for(int i = 0; i < 4; ++i)
{
p.x += square[i].x;
p.y += square[i].y;
}
p.x /= 4.0;
p.y /= 4.0;
gCenters.push_back(p);
}
std::vector<std::vector<Point>> squaresCopy(squares);
std::vector<bool> visited(rectangles.size(), false);
squares.clear();
for(auto& g : gCenters)
{
std::vector<std::vector<Point>> rect;
for(int j = 0; j < rectangles.size(); ++j)
if(!visited[j] && rectangles[j].contains(g))
{
visited[j] = true;
rect.push_back(squaresCopy[j]);
}
if(rect.size() > 0)
{
sort(rect.begin(), rect.end(), [](const vector<Point>& p1, const vector<Point>&p2) -> bool {return contourArea(p1) > contourArea(p2);});
squares.push_back(rect[0]);
}
}
return squares.size() == image_processing_utils::SUDOKU_SIZE*image_processing_utils::SUDOKU_SIZE;
}
//Sort the squares by order where they appeared in the sudoku in row major order
std::vector<std::vector<Point>> image_processing_utils::labelling(const std::vector<std::vector<Point>>& squares)
{
std::vector<std::vector<Point>> sortedSquares(squares);
for(auto& square : sortedSquares)
image_processing_utils::prepareQuadri(square);
std::vector<std::vector<Point>> labels;
std::vector<std::vector<Point>> rows;
for(int i = 0; i < image_processing_utils::SUDOKU_SIZE; ++i)
{
rows.clear();
//Sort by row
std::sort(sortedSquares.begin(), sortedSquares.end(), [](const vector<Point>& p1, const vector<Point>& p2) -> bool {return p1[0].y > p2[0].y;});
//Then sort by col
for(int j = 0; j < image_processing_utils::SUDOKU_SIZE; ++j)
{
rows.push_back(sortedSquares.back());
std::sort(rows.begin(), rows.end(), [](const vector<Point>& p1, const vector<Point>& p2) -> bool {return p1[0].x < p2[0].x;});
sortedSquares.pop_back();
}
for(auto& square : rows)
labels.push_back(square);
}
return labels;
}
std::vector<Mat> image_processing_utils::extractBlocks(const std::vector<std::vector<Point>>& unlabeledSquares, const Mat& image)
{
std::vector<std::vector<Point>> squares = image_processing_utils::labelling(unlabeledSquares);
#if D_DEBUG
Mat img = image.clone();
drawSquares(sudoku, squares, 0, true, 0);
int i = 0;
for(auto& square : squares)
{
string lbl = to_string(i++);
putText(img, lbl, Point(15+square[0].x,15+square[0].y), FONT_HERSHEY_SIMPLEX, 1, Scalar(255, 0, 0));
}
namedWindow(image_processing_utils::LABELED_SUDOKU_WINDOW_TITLE, CV_WINDOW_AUTOSIZE);
imshow(image_processing_utils::LABELED_SUDOKU_WINDOW_TITLE, img);
#endif
vector<Mat> blocks;
int w = 0;
int h = 0;
for(auto& square : squares)
{
w += abs(square[1].x-square[0].x);
h += abs(square[3].y-square[0].y);
}
w /= squares.size();
h /= squares.size();
for(auto& square : squares)
blocks.push_back(image_processing_utils::cropPicture(square, image, w, h));
for(auto& b : blocks)
b = b > 128;
return blocks;
}
//Extract digit block with their id, in row major order, starting at 0
std::vector<std::pair<int, Mat>> image_processing_utils::extractDigitBlocks(const std::vector<Mat>& allBlocks, const int w, const int h)
{
std::vector<Mat> blocks(allBlocks);
std::vector<std::pair<int, Mat>> digits;
int id = 0;
for(auto& b : blocks)
{
++id;
double white = 0;
for(int j = 0; j < b.rows; ++j)
for(int i = 0; i < b.cols; ++i)
if (static_cast<int>(b.at<uchar>(j, i)) == 255)
++white;
//Filter percentage of white
int v = 100*white/(b.rows*b.cols);
if(v < 98 && v > 60)
{
resize(b, b, Size(w, h));
digits.push_back(std::pair<int, Mat>(id-1, b));
}
}
return digits;
}
double image_processing_utils::computeAreaContour(const std::vector<cv::Point>& contour)
{
return cv::contourArea(contour);
}
|
Fix bug color
|
Fix bug color
|
C++
|
mit
|
Diego999/Sudoku-Recognition,Diego999/Sudoku-Recognition,Diego999/Sudoku-Recognition
|
5e2acde4e9c33de4563d50ee577d32ebf2ad1881
|
cintex/src/CINTFunctionBuilder.cxx
|
cintex/src/CINTFunctionBuilder.cxx
|
// @(#)root/cintex:$Name: $:$Id: CINTFunctionBuilder.cxx,v 1.12 2006/07/14 06:58:00 roiser Exp $
// Author: Pere Mato 2005
// Copyright CERN, CH-1211 Geneva 23, 2004-2005, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.
#include "Reflex/Reflex.h"
#include "Reflex/Tools.h"
#include "CINTdefs.h"
#include "CINTFunctionBuilder.h"
#include "CINTScopeBuilder.h"
#include "CINTFunctional.h"
#include "CINTTypedefBuilder.h"
#include "Api.h"
using namespace ROOT::Reflex;
using namespace std;
namespace ROOT { namespace Cintex {
CINTFunctionBuilder::CINTFunctionBuilder(const ROOT::Reflex::Member& m)
: fFunction(m) {
// CINTFunctionBuilder constructor.
}
CINTFunctionBuilder::~CINTFunctionBuilder() {
// CINTFunctionBuilder destructor.
}
void CINTFunctionBuilder::Setup() {
// Setup a CINT function.
Scope scope = fFunction.DeclaringScope();
bool global = scope.IsTopScope();
CINTScopeBuilder::Setup(fFunction.TypeOf());
if ( global ) {
G__lastifuncposition();
}
else {
CINTScopeBuilder::Setup(scope);
string sname = scope.Name(SCOPED);
int ns_tag = G__search_tagname(sname.c_str(),'n');
G__tag_memfunc_setup(ns_tag);
}
Setup(fFunction);
if ( global ) {
G__resetifuncposition();
}
else {
G__tag_memfunc_reset();
}
return;
}
void CINTFunctionBuilder::Setup(const Member& function) {
// Setup a CINT function.
Type cl = Type::ByName(function.DeclaringScope().Name(SCOPED));
int access = G__PUBLIC;
int const_ness = 0;
int virtuality = 0;
int reference = 0;
int memory_type = 1; // G__LOCAL; // G__AUTO=-1
int tagnum = CintTag(function.DeclaringScope().Name(SCOPED));
//---Alocate a context
StubContext_t* stub_context = new StubContext_t(function, cl);
//---Function Name and hash value
string funcname = function.Name();
int hash, tmp;
//---Return type ----------------
Type rt = function.TypeOf().ReturnType();
reference = rt.IsReference() ? 1 : 0;
int ret_typedeft = -1;
if ( rt.IsTypedef()) {
ret_typedeft = CINTTypedefBuilder::Setup(rt);
rt = rt.FinalType();
}
//CINTScopeBuilder::Setup( rt );
CintTypeDesc ret_desc = CintType( rt );
char ret_type = rt.IsPointer() ? (ret_desc.first - ('a'-'A')) : ret_desc.first;
int ret_tag = CintTag( ret_desc.second );
if( function.IsOperator() ) {
// remove space between "operator" keywork and the actual operator
if ( funcname[8] == ' ' && ! isalpha( funcname[9] ) )
funcname = "operator" + funcname.substr(9);
}
G__InterfaceMethod stub;
if( function.IsConstructor() ) {
//stub = Constructor_stub;
stub = Allocate_stub_function(stub_context, & Constructor_stub_with_context);
funcname = G__ClassInfo(tagnum).Name();
ret_tag = tagnum;
}
else if ( function.IsDestructor() ) {
//stub = Destructor_stub;
stub = Allocate_stub_function(stub_context, & Destructor_stub_with_context);
funcname = "~";
funcname += G__ClassInfo(tagnum).Name();
}
else {
//stub = Method_stub;
stub = Allocate_stub_function(stub_context, & Method_stub_with_context);
}
if ( function.IsPrivate() )
access = G__PRIVATE;
else if ( function.IsProtected() )
access = G__PROTECTED;
else if ( function.IsPublic() )
access = G__PUBLIC;
if ( function.TypeOf().IsConst() )
const_ness = G__CONSTFUNC;
if ( function.IsVirtual() )
virtuality = 1;
if ( function.IsStatic() )
memory_type += G__CLASSSCOPE;
string signature = CintSignature(function);
int nparam = function.TypeOf().FunctionParameterSize();
//---Cint function hash
G__hash(funcname, hash, tmp);
G__usermemfunc_setup( const_cast<char*>(funcname.c_str()), // function Name
hash, // function Name hash value
(int (*)(void))stub, // method stub function
ret_type, // return type (void)
ret_tag, // return TypeNth tag number
ret_typedeft, // typedef number
reference, // reftype
nparam, // number of paramerters
memory_type, // memory type
access, // access type
const_ness, // CV qualifiers
const_cast<char*>(signature.c_str()), // signature
(char*)NULL, // comment line
(void*)NULL, // true2pf
virtuality, // virtuality
stub_context // user ParameterNth
);
}
}}
|
// @(#)root/cintex:$Name: $:$Id: CINTFunctionBuilder.cxx,v 1.13 2006/11/08 08:33:57 roiser Exp $
// Author: Pere Mato 2005
// Copyright CERN, CH-1211 Geneva 23, 2004-2005, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.
#include "Reflex/Reflex.h"
#include "Reflex/Tools.h"
#include "CINTdefs.h"
#include "CINTFunctionBuilder.h"
#include "CINTScopeBuilder.h"
#include "CINTFunctional.h"
#include "CINTTypedefBuilder.h"
#include "Api.h"
using namespace ROOT::Reflex;
using namespace std;
namespace ROOT { namespace Cintex {
CINTFunctionBuilder::CINTFunctionBuilder(const ROOT::Reflex::Member& m)
: fFunction(m) {
// CINTFunctionBuilder constructor.
}
CINTFunctionBuilder::~CINTFunctionBuilder() {
// CINTFunctionBuilder destructor.
}
void CINTFunctionBuilder::Setup() {
// Setup a CINT function.
Scope scope = fFunction.DeclaringScope();
bool global = scope.IsTopScope();
CINTScopeBuilder::Setup(fFunction.TypeOf());
if ( global ) {
G__lastifuncposition();
}
else {
CINTScopeBuilder::Setup(scope);
string sname = scope.Name(SCOPED);
int ns_tag = G__search_tagname(sname.c_str(),'n');
G__tag_memfunc_setup(ns_tag);
}
Setup(fFunction);
if ( global ) {
G__resetifuncposition();
}
else {
G__tag_memfunc_reset();
}
return;
}
void CINTFunctionBuilder::Setup(const Member& function) {
// Setup a CINT function.
Type cl = Type::ByName(function.DeclaringScope().Name(SCOPED));
int access = G__PUBLIC;
int const_ness = 0;
int virtuality = 0;
int reference = 0;
int memory_type = 1; // G__LOCAL; // G__AUTO=-1
int tagnum = CintTag(function.DeclaringScope().Name(SCOPED));
//---Alocate a context
StubContext_t* stub_context = new StubContext_t(function, cl);
//---Function Name and hash value
string funcname = function.Name();
int hash, tmp;
//---Return type ----------------
Type rt = function.TypeOf().ReturnType();
reference = rt.IsReference() ? 1 : 0;
int ret_typedeft = -1;
if ( rt.IsTypedef()) {
ret_typedeft = CINTTypedefBuilder::Setup(rt);
while ( rt.IsTypedef()) rt = rt.ToType();
}
//CINTScopeBuilder::Setup( rt );
CintTypeDesc ret_desc = CintType( rt );
char ret_type = rt.IsPointer() ? (ret_desc.first - ('a'-'A')) : ret_desc.first;
int ret_tag = CintTag( ret_desc.second );
if( function.IsOperator() ) {
// remove space between "operator" keywork and the actual operator
if ( funcname[8] == ' ' && ! isalpha( funcname[9] ) )
funcname = "operator" + funcname.substr(9);
}
G__InterfaceMethod stub;
if( function.IsConstructor() ) {
//stub = Constructor_stub;
stub = Allocate_stub_function(stub_context, & Constructor_stub_with_context);
funcname = G__ClassInfo(tagnum).Name();
ret_tag = tagnum;
}
else if ( function.IsDestructor() ) {
//stub = Destructor_stub;
stub = Allocate_stub_function(stub_context, & Destructor_stub_with_context);
funcname = "~";
funcname += G__ClassInfo(tagnum).Name();
}
else {
//stub = Method_stub;
stub = Allocate_stub_function(stub_context, & Method_stub_with_context);
}
if ( function.IsPrivate() )
access = G__PRIVATE;
else if ( function.IsProtected() )
access = G__PROTECTED;
else if ( function.IsPublic() )
access = G__PUBLIC;
if ( function.TypeOf().IsConst() )
const_ness = G__CONSTFUNC;
if ( function.IsVirtual() )
virtuality = 1;
if ( function.IsStatic() )
memory_type += G__CLASSSCOPE;
string signature = CintSignature(function);
int nparam = function.TypeOf().FunctionParameterSize();
//---Cint function hash
G__hash(funcname, hash, tmp);
G__usermemfunc_setup( const_cast<char*>(funcname.c_str()), // function Name
hash, // function Name hash value
(int (*)(void))stub, // method stub function
ret_type, // return type (void)
ret_tag, // return TypeNth tag number
ret_typedeft, // typedef number
reference, // reftype
nparam, // number of paramerters
memory_type, // memory type
access, // access type
const_ness, // CV qualifiers
const_cast<char*>(signature.c_str()), // signature
(char*)NULL, // comment line
(void*)NULL, // true2pf
virtuality, // virtuality
stub_context // user ParameterNth
);
}
}}
|
fix problem with return types of functions that are typedefs to unknown types
|
fix problem with return types of functions that are typedefs to unknown types
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@16745 27541ba8-7e3a-0410-8455-c3a389f83636
|
C++
|
lgpl-2.1
|
davidlt/root,omazapa/root,root-mirror/root,nilqed/root,krafczyk/root,gbitzes/root,CristinaCristescu/root,evgeny-boger/root,strykejern/TTreeReader,davidlt/root,krafczyk/root,mattkretz/root,omazapa/root-old,zzxuanyuan/root,evgeny-boger/root,omazapa/root,satyarth934/root,CristinaCristescu/root,buuck/root,root-mirror/root,bbockelm/root,karies/root,kirbyherm/root-r-tools,arch1tect0r/root,evgeny-boger/root,dfunke/root,ffurano/root5,Dr15Jones/root,krafczyk/root,georgtroska/root,omazapa/root,mhuwiler/rootauto,nilqed/root,satyarth934/root,satyarth934/root,ffurano/root5,0x0all/ROOT,perovic/root,Duraznos/root,Dr15Jones/root,sbinet/cxx-root,satyarth934/root,pspe/root,simonpf/root,zzxuanyuan/root-compressor-dummy,root-mirror/root,agarciamontoro/root,vukasinmilosevic/root,Dr15Jones/root,smarinac/root,jrtomps/root,jrtomps/root,Y--/root,dfunke/root,nilqed/root,sawenzel/root,evgeny-boger/root,kirbyherm/root-r-tools,Duraznos/root,cxx-hep/root-cern,esakellari/my_root_for_test,georgtroska/root,mkret2/root,jrtomps/root,thomaskeck/root,thomaskeck/root,gbitzes/root,thomaskeck/root,Dr15Jones/root,Duraznos/root,veprbl/root,alexschlueter/cern-root,vukasinmilosevic/root,mattkretz/root,omazapa/root-old,cxx-hep/root-cern,agarciamontoro/root,vukasinmilosevic/root,smarinac/root,zzxuanyuan/root-compressor-dummy,Duraznos/root,dfunke/root,agarciamontoro/root,evgeny-boger/root,smarinac/root,0x0all/ROOT,mattkretz/root,buuck/root,mkret2/root,sbinet/cxx-root,olifre/root,arch1tect0r/root,omazapa/root-old,abhinavmoudgil95/root,tc3t/qoot,karies/root,agarciamontoro/root,pspe/root,buuck/root,mattkretz/root,gganis/root,gbitzes/root,thomaskeck/root,mhuwiler/rootauto,zzxuanyuan/root,simonpf/root,arch1tect0r/root,alexschlueter/cern-root,vukasinmilosevic/root,sirinath/root,lgiommi/root,olifre/root,CristinaCristescu/root,0x0all/ROOT,root-mirror/root,georgtroska/root,esakellari/my_root_for_test,agarciamontoro/root,alexschlueter/cern-root,lgiommi/root,0x0all/ROOT,sirinath/root,dfunke/root,gbitzes/root,buuck/root,0x0all/ROOT,mhuwiler/rootauto,esakellari/root,tc3t/qoot,Duraznos/root,mkret2/root,esakellari/my_root_for_test,davidlt/root,Dr15Jones/root,sawenzel/root,Dr15Jones/root,abhinavmoudgil95/root,Duraznos/root,0x0all/ROOT,BerserkerTroll/root,perovic/root,pspe/root,sawenzel/root,veprbl/root,esakellari/my_root_for_test,omazapa/root,omazapa/root-old,perovic/root,davidlt/root,CristinaCristescu/root,sirinath/root,arch1tect0r/root,pspe/root,mkret2/root,arch1tect0r/root,sirinath/root,evgeny-boger/root,thomaskeck/root,cxx-hep/root-cern,tc3t/qoot,BerserkerTroll/root,kirbyherm/root-r-tools,alexschlueter/cern-root,karies/root,bbockelm/root,mhuwiler/rootauto,Duraznos/root,omazapa/root,zzxuanyuan/root,zzxuanyuan/root-compressor-dummy,gbitzes/root,zzxuanyuan/root-compressor-dummy,gganis/root,krafczyk/root,zzxuanyuan/root,davidlt/root,strykejern/TTreeReader,tc3t/qoot,tc3t/qoot,abhinavmoudgil95/root,vukasinmilosevic/root,gganis/root,karies/root,thomaskeck/root,root-mirror/root,satyarth934/root,abhinavmoudgil95/root,smarinac/root,perovic/root,arch1tect0r/root,mattkretz/root,dfunke/root,nilqed/root,georgtroska/root,agarciamontoro/root,sawenzel/root,mkret2/root,CristinaCristescu/root,esakellari/root,krafczyk/root,beniz/root,bbockelm/root,karies/root,beniz/root,jrtomps/root,0x0all/ROOT,perovic/root,alexschlueter/cern-root,zzxuanyuan/root,dfunke/root,mattkretz/root,gbitzes/root,satyarth934/root,nilqed/root,mhuwiler/rootauto,davidlt/root,olifre/root,BerserkerTroll/root,zzxuanyuan/root-compressor-dummy,buuck/root,sbinet/cxx-root,Y--/root,karies/root,BerserkerTroll/root,cxx-hep/root-cern,omazapa/root,sbinet/cxx-root,simonpf/root,simonpf/root,nilqed/root,esakellari/root,agarciamontoro/root,gganis/root,mhuwiler/rootauto,krafczyk/root,sawenzel/root,smarinac/root,georgtroska/root,zzxuanyuan/root-compressor-dummy,georgtroska/root,vukasinmilosevic/root,mkret2/root,evgeny-boger/root,lgiommi/root,strykejern/TTreeReader,krafczyk/root,sbinet/cxx-root,veprbl/root,sawenzel/root,kirbyherm/root-r-tools,gganis/root,Duraznos/root,smarinac/root,gganis/root,omazapa/root,lgiommi/root,zzxuanyuan/root,nilqed/root,davidlt/root,tc3t/qoot,mhuwiler/rootauto,pspe/root,ffurano/root5,dfunke/root,Duraznos/root,mattkretz/root,simonpf/root,sbinet/cxx-root,sawenzel/root,lgiommi/root,veprbl/root,karies/root,vukasinmilosevic/root,nilqed/root,ffurano/root5,jrtomps/root,beniz/root,kirbyherm/root-r-tools,sawenzel/root,Dr15Jones/root,esakellari/root,Y--/root,georgtroska/root,agarciamontoro/root,krafczyk/root,lgiommi/root,CristinaCristescu/root,beniz/root,strykejern/TTreeReader,ffurano/root5,krafczyk/root,veprbl/root,kirbyherm/root-r-tools,zzxuanyuan/root,lgiommi/root,tc3t/qoot,olifre/root,BerserkerTroll/root,davidlt/root,sirinath/root,karies/root,0x0all/ROOT,jrtomps/root,mkret2/root,beniz/root,omazapa/root-old,zzxuanyuan/root,evgeny-boger/root,satyarth934/root,karies/root,lgiommi/root,mhuwiler/rootauto,mattkretz/root,davidlt/root,sbinet/cxx-root,sirinath/root,perovic/root,abhinavmoudgil95/root,sawenzel/root,root-mirror/root,CristinaCristescu/root,cxx-hep/root-cern,mattkretz/root,beniz/root,georgtroska/root,evgeny-boger/root,pspe/root,gganis/root,BerserkerTroll/root,alexschlueter/cern-root,tc3t/qoot,arch1tect0r/root,BerserkerTroll/root,tc3t/qoot,vukasinmilosevic/root,esakellari/root,mkret2/root,pspe/root,veprbl/root,bbockelm/root,mhuwiler/rootauto,esakellari/my_root_for_test,esakellari/my_root_for_test,buuck/root,0x0all/ROOT,jrtomps/root,simonpf/root,agarciamontoro/root,CristinaCristescu/root,simonpf/root,satyarth934/root,esakellari/root,sirinath/root,vukasinmilosevic/root,jrtomps/root,gbitzes/root,olifre/root,arch1tect0r/root,zzxuanyuan/root-compressor-dummy,Y--/root,abhinavmoudgil95/root,lgiommi/root,omazapa/root-old,gbitzes/root,perovic/root,olifre/root,bbockelm/root,esakellari/root,sbinet/cxx-root,omazapa/root,simonpf/root,zzxuanyuan/root,simonpf/root,omazapa/root,root-mirror/root,sirinath/root,kirbyherm/root-r-tools,jrtomps/root,abhinavmoudgil95/root,omazapa/root,buuck/root,alexschlueter/cern-root,mkret2/root,simonpf/root,zzxuanyuan/root-compressor-dummy,omazapa/root-old,bbockelm/root,buuck/root,zzxuanyuan/root-compressor-dummy,omazapa/root-old,beniz/root,nilqed/root,veprbl/root,nilqed/root,mhuwiler/rootauto,thomaskeck/root,karies/root,abhinavmoudgil95/root,beniz/root,beniz/root,georgtroska/root,agarciamontoro/root,sirinath/root,olifre/root,Y--/root,sbinet/cxx-root,beniz/root,root-mirror/root,BerserkerTroll/root,sbinet/cxx-root,davidlt/root,georgtroska/root,esakellari/my_root_for_test,olifre/root,sirinath/root,bbockelm/root,zzxuanyuan/root,Y--/root,Y--/root,omazapa/root,buuck/root,esakellari/root,gganis/root,CristinaCristescu/root,esakellari/root,ffurano/root5,cxx-hep/root-cern,Duraznos/root,agarciamontoro/root,root-mirror/root,satyarth934/root,smarinac/root,smarinac/root,satyarth934/root,evgeny-boger/root,vukasinmilosevic/root,esakellari/root,esakellari/my_root_for_test,cxx-hep/root-cern,strykejern/TTreeReader,krafczyk/root,Duraznos/root,pspe/root,Y--/root,zzxuanyuan/root,arch1tect0r/root,gbitzes/root,beniz/root,omazapa/root-old,thomaskeck/root,perovic/root,veprbl/root,bbockelm/root,BerserkerTroll/root,krafczyk/root,olifre/root,abhinavmoudgil95/root,omazapa/root-old,omazapa/root-old,esakellari/my_root_for_test,buuck/root,olifre/root,dfunke/root,karies/root,lgiommi/root,arch1tect0r/root,perovic/root,buuck/root,cxx-hep/root-cern,dfunke/root,pspe/root,sawenzel/root,gbitzes/root,simonpf/root,georgtroska/root,sbinet/cxx-root,zzxuanyuan/root-compressor-dummy,BerserkerTroll/root,thomaskeck/root,smarinac/root,ffurano/root5,mattkretz/root,gbitzes/root,nilqed/root,thomaskeck/root,sirinath/root,olifre/root,sawenzel/root,jrtomps/root,evgeny-boger/root,BerserkerTroll/root,perovic/root,zzxuanyuan/root,mattkretz/root,veprbl/root,pspe/root,abhinavmoudgil95/root,zzxuanyuan/root-compressor-dummy,satyarth934/root,bbockelm/root,abhinavmoudgil95/root,gganis/root,esakellari/root,vukasinmilosevic/root,root-mirror/root,Y--/root,Y--/root,gganis/root,CristinaCristescu/root,CristinaCristescu/root,gganis/root,tc3t/qoot,strykejern/TTreeReader,esakellari/my_root_for_test,bbockelm/root,mhuwiler/rootauto,dfunke/root,arch1tect0r/root,smarinac/root,jrtomps/root,mkret2/root,root-mirror/root,pspe/root,Y--/root,mkret2/root,lgiommi/root,bbockelm/root,veprbl/root,perovic/root,dfunke/root,davidlt/root,strykejern/TTreeReader,veprbl/root
|
9114c87661a824ce034f4f009c17e9e4c5f72862
|
code/rtkReg23ProjectionGeometry.cxx
|
code/rtkReg23ProjectionGeometry.cxx
|
/*=========================================================================
*
* Copyright RTK Consortium
*
* 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.txt
*
* 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 "rtkReg23ProjectionGeometry.h"
//std
#include <math.h>
//ITK
#include <itkVector.h>
#include <itkEuler3DTransform.h>
rtk::Reg23ProjectionGeometry::Reg23ProjectionGeometry()
: rtk::ThreeDCircularProjectionGeometry()
{
}
rtk::Reg23ProjectionGeometry::~Reg23ProjectionGeometry()
{
}
bool rtk::Reg23ProjectionGeometry::VerifyAngles(const double outOfPlaneAngleRAD,
const double gantryAngleRAD, const double inPlaneAngleRAD,
const Matrix3x3Type &referenceMatrix) const
{
typedef itk::Euler3DTransform<double> EulerType;
const Matrix3x3Type &rm = referenceMatrix; // shortcut
const double EPSILON = 1e-6; // internal tolerance for comparison
EulerType::Pointer euler = EulerType::New();
euler->SetComputeZYX(false); // ZXY order
euler->SetRotation(outOfPlaneAngleRAD, gantryAngleRAD, inPlaneAngleRAD);
Matrix3x3Type m = euler->GetMatrix(); // resultant matrix
for (int i = 0; i < 3; i++) // check whether matrices match
for (int j = 0; j < 3; j++)
if (fabs(rm[i][j] - m[i][j]) > EPSILON)
return false;
return true;
}
bool rtk::Reg23ProjectionGeometry::FixAngles(double &outOfPlaneAngleRAD,
double &gantryAngleRAD, double &inPlaneAngleRAD,
const Matrix3x3Type &referenceMatrix) const
{
const Matrix3x3Type &rm = referenceMatrix; // shortcut
const double EPSILON = 1e-6; // internal tolerance for comparison
if (fabs(fabs(rm[2][0]) - 1.) > EPSILON)
{
double oa, ga, ia;
// @see Slabaugh, GG, "Computing Euler angles from a rotation matrix"
// first trial:
oa = asin(rm[2][1]);
double coa = cos(oa);
ga = atan2(-rm[2][0] / coa, rm[2][2] / coa);
ia = atan2(-rm[0][1] / coa, rm[1][1] / coa);
if (VerifyAngles(oa, ga, ia, rm))
{
outOfPlaneAngleRAD = oa;
gantryAngleRAD = ga;
inPlaneAngleRAD = ia;
return true;
}
// second trial:
oa = 3.1415926535897932384626433832795 /*PI*/ - asin(rm[2][1]);
coa = cos(oa);
ga = atan2(-rm[2][0] / coa, rm[2][2] / coa);
ia = atan2(-rm[0][1] / coa, rm[1][1] / coa);
if (VerifyAngles(oa, ga, ia, rm))
{
outOfPlaneAngleRAD = oa;
gantryAngleRAD = ga;
inPlaneAngleRAD = ia;
return true;
}
return false;
}
return false;
}
bool rtk::Reg23ProjectionGeometry::AddReg23Projection(
const PointType &sourcePosition, const PointType &detectorPosition,
const VectorType &detectorRowVector, const VectorType &detectorColumnVector)
{
typedef itk::Euler3DTransform<double> EulerType;
// these parameters relate absolutely to the WCS (IEC-based):
const VectorType &r = detectorRowVector; // row dir
const VectorType &c = detectorColumnVector; // column dir
VectorType n = itk::CrossProduct(r, c); // normal
const PointType &S = sourcePosition; // source pos
const PointType &R = detectorPosition; // detector pos
if (fabs(r * c) > 1e-6) // non-orthogonal row/column vectors
return false;
// Euler angles (ZXY convention) from detector orientation in IEC-based WCS:
double ga; // gantry angle
double oa; // out-of-plane angle
double ia; // in-plane angle
// extract Euler angles from the orthogonal matrix which is established
// by the detector orientation; however, we would like RTK to internally
// store the inverse of this rotation matrix, therefore the corresponding
// angles are computed here:
Matrix3x3Type rm; // reference matrix
// NOTE: This transposed matrix should internally
// set by rtk::ThreeDProjectionGeometry (inverse)
// of external rotation!
rm[0][0] = r[0]; rm[0][1] = r[1]; rm[0][2] = r[2];
rm[1][0] = c[0]; rm[1][1] = c[1]; rm[1][2] = c[2];
rm[2][0] = n[0]; rm[2][1] = n[1]; rm[2][2] = n[2];
// extract Euler angles by using the standard ITK implementation:
EulerType::Pointer euler = EulerType::New();
euler->SetComputeZYX(false); // ZXY order
euler->SetMatrix(rm);
oa = euler->GetAngleX(); // delivers radians
ga = euler->GetAngleY();
ia = euler->GetAngleZ();
// verify that extracted ZXY angles result in the *desired* matrix:
// (at some angle constellations we may run into numerical troubles, therefore,
// verify angles and try to fix instabilities)
if (!VerifyAngles(oa, ga, ia, rm))
{
if (!FixAngles(oa, ga, ia, rm))
return false;
}
// since rtk::ThreeDCircularProjectionGeometry::AddProjection() mirrors the
// angles (!) internally, let's invert the computed ones in order to
// get at the end what we would like (see above); convert rad->deg:
ga *= -57.29577951308232;
oa *= -57.29577951308232;
ia *= -57.29577951308232;
// SID: distance from source to isocenter along detector normal
double SID = fabs(n[0] * S[0] + n[1] * S[1] + n[2] * S[2]);
// SDD: distance from source to detector along detector normal
double SDD = fabs(n[0] * (S[0] - R[0]) + n[1] * (S[1] - R[1]) + n[2] * (S[2] - R[2]));
if (SDD < 1e-6) // source is in detector plane
return false;
// source offset: compute source's "in-plane" x/y shift off isocenter
VectorType Sv;
Sv[0] = S[0];
Sv[1] = S[1];
Sv[2] = S[2];
double oSx = Sv * r;
double oSy = Sv * c;
// detector offset: compute detector's in-plane x/y shift off isocenter
VectorType Rv;
Rv[0] = R[0];
Rv[1] = R[1];
Rv[2] = R[2];
double oRx = Rv * r;
double oRy = Rv * c;
// configure native RTK geometry
this->Superclass::AddProjection(SID, SDD, ga, oRx, oRy, oa, ia, oSx, oSy);
return true;
}
|
/*=========================================================================
*
* Copyright RTK Consortium
*
* 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.txt
*
* 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 "rtkReg23ProjectionGeometry.h"
//std
#include <math.h>
//ITK
#include <itkVector.h>
#include <itkEuler3DTransform.h>
rtk::Reg23ProjectionGeometry::Reg23ProjectionGeometry()
: rtk::ThreeDCircularProjectionGeometry()
{
}
rtk::Reg23ProjectionGeometry::~Reg23ProjectionGeometry()
{
}
bool rtk::Reg23ProjectionGeometry::VerifyAngles(const double outOfPlaneAngleRAD,
const double gantryAngleRAD, const double inPlaneAngleRAD,
const Matrix3x3Type &referenceMatrix) const
{
typedef itk::Euler3DTransform<double> EulerType;
const Matrix3x3Type &rm = referenceMatrix; // shortcut
const double EPSILON = 1e-6; // internal tolerance for comparison
EulerType::Pointer euler = EulerType::New();
euler->SetComputeZYX(false); // ZXY order
euler->SetRotation(outOfPlaneAngleRAD, gantryAngleRAD, inPlaneAngleRAD);
Matrix3x3Type m = euler->GetMatrix(); // resultant matrix
for (int i = 0; i < 3; i++) // check whether matrices match
for (int j = 0; j < 3; j++)
if (fabs(rm[i][j] - m[i][j]) > EPSILON)
return false;
return true;
}
bool rtk::Reg23ProjectionGeometry::FixAngles(double &outOfPlaneAngleRAD,
double &gantryAngleRAD, double &inPlaneAngleRAD,
const Matrix3x3Type &referenceMatrix) const
{
const Matrix3x3Type &rm = referenceMatrix; // shortcut
const double EPSILON = 1e-6; // internal tolerance for comparison
if (fabs(fabs(rm[2][0]) - 1.) > EPSILON)
{
double oa, ga, ia;
// @see Slabaugh, GG, "Computing Euler angles from a rotation matrix"
// first trial:
oa = asin(rm[2][1]);
double coa = cos(oa);
ga = atan2(-rm[2][0] / coa, rm[2][2] / coa);
ia = atan2(-rm[0][1] / coa, rm[1][1] / coa);
if (VerifyAngles(oa, ga, ia, rm))
{
outOfPlaneAngleRAD = oa;
gantryAngleRAD = ga;
inPlaneAngleRAD = ia;
return true;
}
// second trial:
oa = 3.1415926535897932384626433832795 /*PI*/ - asin(rm[2][1]);
coa = cos(oa);
ga = atan2(-rm[2][0] / coa, rm[2][2] / coa);
ia = atan2(-rm[0][1] / coa, rm[1][1] / coa);
if (VerifyAngles(oa, ga, ia, rm))
{
outOfPlaneAngleRAD = oa;
gantryAngleRAD = ga;
inPlaneAngleRAD = ia;
return true;
}
return false;
}
return false;
}
bool rtk::Reg23ProjectionGeometry::AddReg23Projection(
const PointType &sourcePosition, const PointType &detectorPosition,
const VectorType &detectorRowVector, const VectorType &detectorColumnVector)
{
typedef itk::Euler3DTransform<double> EulerType;
// these parameters relate absolutely to the WCS (IEC-based):
const VectorType &r = detectorRowVector; // row dir
const VectorType &c = detectorColumnVector; // column dir
VectorType n = itk::CrossProduct(r, c); // normal
const PointType &S = sourcePosition; // source pos
const PointType &R = detectorPosition; // detector pos
if (fabs(r * c) > 1e-6) // non-orthogonal row/column vectors
return false;
// Euler angles (ZXY convention) from detector orientation in IEC-based WCS:
double ga; // gantry angle
double oa; // out-of-plane angle
double ia; // in-plane angle
// extract Euler angles from the orthogonal matrix which is established
// by the detector orientation; however, we would like RTK to internally
// store the inverse of this rotation matrix, therefore the corresponding
// angles are computed here:
Matrix3x3Type rm; // reference matrix
// NOTE: This transposed matrix should internally
// set by rtk::ThreeDProjectionGeometry (inverse)
// of external rotation!
rm[0][0] = r[0]; rm[0][1] = r[1]; rm[0][2] = r[2];
rm[1][0] = c[0]; rm[1][1] = c[1]; rm[1][2] = c[2];
rm[2][0] = n[0]; rm[2][1] = n[1]; rm[2][2] = n[2];
// extract Euler angles by using the standard ITK implementation:
EulerType::Pointer euler = EulerType::New();
euler->SetComputeZYX(false); // ZXY order
euler->SetMatrix(rm);
oa = euler->GetAngleX(); // delivers radians
ga = euler->GetAngleY();
ia = euler->GetAngleZ();
// verify that extracted ZXY angles result in the *desired* matrix:
// (at some angle constellations we may run into numerical troubles, therefore,
// verify angles and try to fix instabilities)
if (!VerifyAngles(oa, ga, ia, rm))
{
if (!FixAngles(oa, ga, ia, rm))
return false;
}
// since rtk::ThreeDCircularProjectionGeometry::AddProjection() mirrors the
// angles (!) internally, let's invert the computed ones in order to
// get at the end what we would like (see above); convert rad->deg:
ga *= -57.29577951308232;
oa *= -57.29577951308232;
ia *= -57.29577951308232;
// SID: distance from source to isocenter along detector normal
double SID = n[0] * S[0] + n[1] * S[1] + n[2] * S[2];
// SDD: distance from source to detector along detector normal
double SDD = n[0] * (S[0] - R[0]) + n[1] * (S[1] - R[1]) + n[2] * (S[2] - R[2]);
if (fabs(SDD) < 1e-6) // source is in detector plane
return false;
// source offset: compute source's "in-plane" x/y shift off isocenter
VectorType Sv;
Sv[0] = S[0];
Sv[1] = S[1];
Sv[2] = S[2];
double oSx = Sv * r;
double oSy = Sv * c;
// detector offset: compute detector's in-plane x/y shift off isocenter
VectorType Rv;
Rv[0] = R[0];
Rv[1] = R[1];
Rv[2] = R[2];
double oRx = Rv * r;
double oRy = Rv * c;
// configure native RTK geometry
this->Superclass::AddProjection(SID, SDD, ga, oRx, oRy, oa, ia, oSx, oSy);
return true;
}
|
Allow for negative values in source to detector distance. This is required to compute backscatter.
|
Allow for negative values in source to detector distance. This is
required to compute backscatter.
|
C++
|
apache-2.0
|
fabienmomey/RTK,dsarrut/RTK,dsarrut/RTK,ldqcarbon/RTK,ipsusila/RTK,SimonRit/RTK,ipsusila/RTK,fabienmomey/RTK,dsarrut/RTK,dsarrut/RTK,ipsusila/RTK,fabienmomey/RTK,SimonRit/RTK,ldqcarbon/RTK,dsarrut/RTK,ipsusila/RTK,ipsusila/RTK,SimonRit/RTK,ldqcarbon/RTK,fabienmomey/RTK,fabienmomey/RTK,ldqcarbon/RTK,ipsusila/RTK,ldqcarbon/RTK,dsarrut/RTK,dsarrut/RTK,ldqcarbon/RTK,ldqcarbon/RTK,ipsusila/RTK,fabienmomey/RTK,fabienmomey/RTK,SimonRit/RTK
|
5fdc95a70e03e41777f4a023f222f537110a70b1
|
src/server/events/Mark.hpp
|
src/server/events/Mark.hpp
|
/*
This file is part of Ingen.
Copyright 2007-2016 David Robillard <http://drobilla.net/>
Ingen 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 any later version.
Ingen is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU Affero General Public License for details.
You should have received a copy of the GNU Affero General Public License
along with Ingen. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef INGEN_EVENTS_MARK_HPP
#define INGEN_EVENTS_MARK_HPP
#include "Event.hpp"
namespace Ingen {
namespace Server {
class Engine;
namespace Events {
/** Set properties of a graph object.
* \ingroup engine
*/
class Mark : public Event
{
public:
enum class Type { BUNDLE_START, BUNDLE_END };
Mark(Engine& engine,
SPtr<Interface> client,
int32_t id,
SampleCount timestamp,
Type type);
bool pre_process();
void execute(RunContext& context);
void post_process();
private:
Type _type;
};
} // namespace Events
} // namespace Server
} // namespace Ingen
#endif // INGEN_EVENTS_MARK_HPP
|
/*
This file is part of Ingen.
Copyright 2007-2016 David Robillard <http://drobilla.net/>
Ingen 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 any later version.
Ingen is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU Affero General Public License for details.
You should have received a copy of the GNU Affero General Public License
along with Ingen. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef INGEN_EVENTS_MARK_HPP
#define INGEN_EVENTS_MARK_HPP
#include "Event.hpp"
namespace Ingen {
namespace Server {
class Engine;
namespace Events {
/** Delineate the start or end of a bundle of events.
*
* This is used to mark the ends of an undo transaction, so a single undo can
* undo the effects of many events (such as a paste or a graph load).
*
* \ingroup engine
*/
class Mark : public Event
{
public:
enum class Type { BUNDLE_START, BUNDLE_END };
Mark(Engine& engine,
SPtr<Interface> client,
int32_t id,
SampleCount timestamp,
Type type);
bool pre_process();
void execute(RunContext& context);
void post_process();
private:
Type _type;
};
} // namespace Events
} // namespace Server
} // namespace Ingen
#endif // INGEN_EVENTS_MARK_HPP
|
Fix misleading comment
|
Fix misleading comment
|
C++
|
agpl-3.0
|
drobilla/ingen,drobilla/ingen,drobilla/ingen,drobilla/ingen
|
9391fc1a5e59942b870341df6da0e202f83e7990
|
Sources/hspp/Tasks/BasicTasks/PlaySpellTask.cpp
|
Sources/hspp/Tasks/BasicTasks/PlaySpellTask.cpp
|
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <hspp/Enums/TaskEnums.h>
#include <hspp/Tasks/BasicTasks/ModifyManaTask.h>
#include <hspp/Tasks/BasicTasks/PlaySpellTask.h>
namespace Hearthstonepp::BasicTasks
{
PlaySpellTask::PlaySpellTask(TaskAgent& agent, Entity* source, Entity* target)
: m_source(source),
m_requirement(TaskID::SELECT_TARGET, agent),
m_target(target)
{
// Do nothing
}
TaskID PlaySpellTask::GetTaskID() const
{
return TaskID::PLAY_SPELL;
}
MetaData PlaySpellTask::Impl(Player& player)
{
BYTE position;
if (m_target != nullptr)
{
const auto fieldIter =
std::find(player.field.begin(), player.field.end(), m_target);
position = static_cast<BYTE>(
std::distance(player.field.begin(), fieldIter));
}
else
{
TaskMeta meta;
// Get position response from GameInterface
m_requirement.Interact(player.id, meta);
using ResponsePlaySpell = FlatData::ResponsePlaySpell;
const auto& buffer = meta.GetBuffer();
const auto req = flatbuffers::GetRoot<ResponsePlaySpell>(buffer.get());
if (req == nullptr)
{
return MetaData::PLAY_SPELL_FLATBUFFER_NULLPTR;
}
position = req->position();
}
// Verify field position
if (position > player.field.size())
{
return MetaData::PLAY_SPELL_POSITION_OUT_OF_RANGE;
}
// Verify valid target
if (player.field[position] == nullptr)
{
return MetaData::PLAY_SPELL_INVALID_TARGET;
}
const BYTE cost = static_cast<BYTE>(m_source->card->cost);
const MetaData modified =
ModifyManaTask(ManaOperator::SUB, ManaType::EXIST, cost).Run(player);
// Process PowerTasks
if (m_source->card->power != nullptr)
{
for (auto& power : m_source->card->power->powerTask)
{
power->target = player.field[position];
power->Run(player);
}
}
if (modified == MetaData::MODIFY_MANA_SUCCESS)
{
return MetaData::PLAY_SPELL_SUCCESS;
}
return MetaData::PLAY_SPELL_MODIFY_MANA_FAIL;
}
} // namespace Hearthstonepp::BasicTasks
|
// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <hspp/Enums/TaskEnums.h>
#include <hspp/Tasks/BasicTasks/ModifyManaTask.h>
#include <hspp/Tasks/BasicTasks/PlaySpellTask.h>
namespace Hearthstonepp::BasicTasks
{
PlaySpellTask::PlaySpellTask(TaskAgent& agent, Entity* source, Entity* target)
: m_source(source),
m_requirement(TaskID::SELECT_TARGET, agent),
m_target(target)
{
// Do nothing
}
TaskID PlaySpellTask::GetTaskID() const
{
return TaskID::PLAY_SPELL;
}
MetaData PlaySpellTask::Impl(Player& player)
{
BYTE position;
if (m_target != nullptr)
{
const auto fieldIter =
std::find(player.field.begin(), player.field.end(), m_target);
position = static_cast<BYTE>(
std::distance(player.field.begin(), fieldIter));
}
else
{
TaskMeta meta;
// Get position response from GameInterface
m_requirement.Interact(player.id, meta);
using ResponsePlaySpell = FlatData::ResponsePlaySpell;
const auto& buffer = meta.GetBuffer();
const auto req = flatbuffers::GetRoot<ResponsePlaySpell>(buffer.get());
if (req == nullptr)
{
return MetaData::PLAY_SPELL_FLATBUFFER_NULLPTR;
}
position = req->position();
}
// Verify field position
if (position > player.field.size())
{
return MetaData::PLAY_SPELL_POSITION_OUT_OF_RANGE;
}
// Verify valid target
if (player.field[position] == nullptr)
{
return MetaData::PLAY_SPELL_INVALID_TARGET;
}
const BYTE cost = static_cast<BYTE>(m_source->card->cost);
const MetaData modified =
ModifyManaTask(ManaOperator::SUB, ManaType::EXIST, cost).Run(player);
// Process PowerTasks
if (m_source->card->power != nullptr)
{
for (auto& power : m_source->card->power->powerTask)
{
power->SetTarget(player.field[position]);
power->Run(player);
}
}
if (modified == MetaData::MODIFY_MANA_SUCCESS)
{
return MetaData::PLAY_SPELL_SUCCESS;
}
return MetaData::PLAY_SPELL_MODIFY_MANA_FAIL;
}
} // namespace Hearthstonepp::BasicTasks
|
Apply changes of 'm_source' and 'm_target'
|
feat(task): Apply changes of 'm_source' and 'm_target'
|
C++
|
mit
|
Hearthstonepp/Hearthstonepp,Hearthstonepp/Hearthstonepp
|
c567432c4440e30a16b2f6ade7d8b1c32dd8ba09
|
SurgSim/Collision/DefaultContactCalculation.cpp
|
SurgSim/Collision/DefaultContactCalculation.cpp
|
// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Collision/DefaultContactCalculation.h"
#include "SurgSim/Collision/CollisionPair.h"
#include "SurgSim/Collision/Representation.h"
#include "SurgSim/Framework/Log.h"
#include "SurgSim/Math/Shape.h"
namespace SurgSim
{
namespace Collision
{
DefaultContactCalculation::DefaultContactCalculation(bool doAssert) :
m_doAssert(doAssert)
{
}
DefaultContactCalculation::~DefaultContactCalculation()
{
}
std::pair<int,int> DefaultContactCalculation::getShapeTypes()
{
return std::pair<int,int>(SurgSim::Math::SHAPE_TYPE_NONE, SurgSim::Math::SHAPE_TYPE_NONE);
}
void DefaultContactCalculation::doCalculateContact(std::shared_ptr<CollisionPair> pair)
{
SURGSIM_ASSERT(!m_doAssert) << "Contact calculation not implemented for pairs with types ("<<
pair->getFirst()->getShapeType() << ", " << pair->getSecond()->getShapeType() << ").";
SURGSIM_LOG_INFO(SurgSim::Framework::Logger::getDefaultLogger()) <<
"Contact calculation not implemented for pairs with types (" <<
pair->getFirst()->getShapeType() << ", " << pair->getSecond()->getShapeType() << ").";
}
}; // namespace Collision
}; // namespace SurgSim
|
// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Collision/DefaultContactCalculation.h"
#include "SurgSim/Collision/CollisionPair.h"
#include "SurgSim/Collision/Representation.h"
#include "SurgSim/Framework/Log.h"
#include "SurgSim/Math/Shape.h"
namespace SurgSim
{
namespace Collision
{
DefaultContactCalculation::DefaultContactCalculation(bool doAssert) :
m_doAssert(doAssert)
{
}
DefaultContactCalculation::~DefaultContactCalculation()
{
}
std::pair<int, int> DefaultContactCalculation::getShapeTypes()
{
return std::pair<int, int>(SurgSim::Math::SHAPE_TYPE_NONE, SurgSim::Math::SHAPE_TYPE_NONE);
}
void DefaultContactCalculation::doCalculateContact(std::shared_ptr<CollisionPair> pair)
{
SURGSIM_ASSERT(!m_doAssert)
<< "Contact calculation not implemented for pairs with types ("
<< pair->getFirst()->getShapeType() << ", " << pair->getSecond()->getShapeType() << ").";
SURGSIM_LOG_ONCE(SurgSim::Framework::Logger::getDefaultLogger(), WARNING)
<< "Contact calculation not implemented for pairs with types ("
<< pair->getFirst()->getShapeType() << ", " << pair->getSecond()->getShapeType() << ").";
}
}; // namespace Collision
}; // namespace SurgSim
|
Reduce error message spam
|
Reduce error message spam
|
C++
|
apache-2.0
|
simquest/opensurgsim,simquest/opensurgsim,simquest/opensurgsim,simquest/opensurgsim
|
4b93ea2e9a35749ed3610487fb2630346713ea63
|
src/llmq/quorums_init.cpp
|
src/llmq/quorums_init.cpp
|
// Copyright (c) 2018-2021 The Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <llmq/quorums_init.h>
#include <llmq/quorums.h>
#include <llmq/quorums_blockprocessor.h>
#include <llmq/quorums_commitment.h>
#include <llmq/quorums_chainlocks.h>
#include <llmq/quorums_debug.h>
#include <llmq/quorums_dkgsessionmgr.h>
#include <llmq/quorums_instantsend.h>
#include <llmq/quorums_signing.h>
#include <llmq/quorums_signing_shares.h>
#include <llmq/quorums_utils.h>
#include <dbwrapper.h>
namespace llmq
{
CBLSWorker* blsWorker;
CDBWrapper* llmqDb;
void InitLLMQSystem(CEvoDB& evoDb, bool unitTests, bool fWipe)
{
llmqDb = new CDBWrapper(unitTests ? "" : (GetDataDir() / "llmq"), 1 << 20, unitTests, fWipe);
blsWorker = new CBLSWorker();
quorumDKGDebugManager = new CDKGDebugManager();
quorumBlockProcessor = new CQuorumBlockProcessor(evoDb);
quorumDKGSessionManager = new CDKGSessionManager(*llmqDb, *blsWorker);
quorumManager = new CQuorumManager(evoDb, *blsWorker, *quorumDKGSessionManager);
quorumSigSharesManager = new CSigSharesManager();
quorumSigningManager = new CSigningManager(*llmqDb, unitTests);
chainLocksHandler = new CChainLocksHandler();
quorumInstantSendManager = new CInstantSendManager(*llmqDb);
}
void DestroyLLMQSystem()
{
delete quorumInstantSendManager;
quorumInstantSendManager = nullptr;
delete chainLocksHandler;
chainLocksHandler = nullptr;
delete quorumSigningManager;
quorumSigningManager = nullptr;
delete quorumSigSharesManager;
quorumSigSharesManager = nullptr;
delete quorumManager;
quorumManager = nullptr;
delete quorumDKGSessionManager;
quorumDKGSessionManager = nullptr;
delete quorumBlockProcessor;
quorumBlockProcessor = nullptr;
delete quorumDKGDebugManager;
quorumDKGDebugManager = nullptr;
delete blsWorker;
blsWorker = nullptr;
delete llmqDb;
llmqDb = nullptr;
LOCK(cs_llmq_vbc);
llmq_versionbitscache.Clear();
}
void StartLLMQSystem()
{
if (blsWorker) {
blsWorker->Start();
}
if (quorumDKGSessionManager) {
quorumDKGSessionManager->StartThreads();
}
if (quorumManager) {
quorumManager->Start();
}
if (quorumSigSharesManager) {
quorumSigSharesManager->RegisterAsRecoveredSigsListener();
quorumSigSharesManager->StartWorkerThread();
}
if (chainLocksHandler) {
chainLocksHandler->Start();
}
if (quorumInstantSendManager) {
quorumInstantSendManager->Start();
}
}
void StopLLMQSystem()
{
if (quorumInstantSendManager) {
quorumInstantSendManager->Stop();
}
if (chainLocksHandler) {
chainLocksHandler->Stop();
}
if (quorumSigSharesManager) {
quorumSigSharesManager->StopWorkerThread();
quorumSigSharesManager->UnregisterAsRecoveredSigsListener();
}
if (quorumManager) {
quorumManager->Stop();
}
if (quorumDKGSessionManager) {
quorumDKGSessionManager->StopThreads();
}
if (blsWorker) {
blsWorker->Stop();
}
}
void InterruptLLMQSystem()
{
if (quorumSigSharesManager) {
quorumSigSharesManager->InterruptWorkerThread();
}
if (quorumInstantSendManager) {
quorumInstantSendManager->InterruptWorkerThread();
}
}
} // namespace llmq
|
// Copyright (c) 2018-2021 The Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <llmq/quorums_init.h>
#include <llmq/quorums.h>
#include <llmq/quorums_blockprocessor.h>
#include <llmq/quorums_commitment.h>
#include <llmq/quorums_chainlocks.h>
#include <llmq/quorums_debug.h>
#include <llmq/quorums_dkgsessionmgr.h>
#include <llmq/quorums_instantsend.h>
#include <llmq/quorums_signing.h>
#include <llmq/quorums_signing_shares.h>
#include <llmq/quorums_utils.h>
#include <dbwrapper.h>
namespace llmq
{
CBLSWorker* blsWorker;
CDBWrapper* llmqDb;
void InitLLMQSystem(CEvoDB& evoDb, bool unitTests, bool fWipe)
{
llmqDb = new CDBWrapper(unitTests ? "" : (GetDataDir() / "llmq"), 8 << 20, unitTests, fWipe);
blsWorker = new CBLSWorker();
quorumDKGDebugManager = new CDKGDebugManager();
quorumBlockProcessor = new CQuorumBlockProcessor(evoDb);
quorumDKGSessionManager = new CDKGSessionManager(*llmqDb, *blsWorker);
quorumManager = new CQuorumManager(evoDb, *blsWorker, *quorumDKGSessionManager);
quorumSigSharesManager = new CSigSharesManager();
quorumSigningManager = new CSigningManager(*llmqDb, unitTests);
chainLocksHandler = new CChainLocksHandler();
quorumInstantSendManager = new CInstantSendManager(*llmqDb);
}
void DestroyLLMQSystem()
{
delete quorumInstantSendManager;
quorumInstantSendManager = nullptr;
delete chainLocksHandler;
chainLocksHandler = nullptr;
delete quorumSigningManager;
quorumSigningManager = nullptr;
delete quorumSigSharesManager;
quorumSigSharesManager = nullptr;
delete quorumManager;
quorumManager = nullptr;
delete quorumDKGSessionManager;
quorumDKGSessionManager = nullptr;
delete quorumBlockProcessor;
quorumBlockProcessor = nullptr;
delete quorumDKGDebugManager;
quorumDKGDebugManager = nullptr;
delete blsWorker;
blsWorker = nullptr;
delete llmqDb;
llmqDb = nullptr;
LOCK(cs_llmq_vbc);
llmq_versionbitscache.Clear();
}
void StartLLMQSystem()
{
if (blsWorker) {
blsWorker->Start();
}
if (quorumDKGSessionManager) {
quorumDKGSessionManager->StartThreads();
}
if (quorumManager) {
quorumManager->Start();
}
if (quorumSigSharesManager) {
quorumSigSharesManager->RegisterAsRecoveredSigsListener();
quorumSigSharesManager->StartWorkerThread();
}
if (chainLocksHandler) {
chainLocksHandler->Start();
}
if (quorumInstantSendManager) {
quorumInstantSendManager->Start();
}
}
void StopLLMQSystem()
{
if (quorumInstantSendManager) {
quorumInstantSendManager->Stop();
}
if (chainLocksHandler) {
chainLocksHandler->Stop();
}
if (quorumSigSharesManager) {
quorumSigSharesManager->StopWorkerThread();
quorumSigSharesManager->UnregisterAsRecoveredSigsListener();
}
if (quorumManager) {
quorumManager->Stop();
}
if (quorumDKGSessionManager) {
quorumDKGSessionManager->StopThreads();
}
if (blsWorker) {
blsWorker->Stop();
}
}
void InterruptLLMQSystem()
{
if (quorumSigSharesManager) {
quorumSigSharesManager->InterruptWorkerThread();
}
if (quorumInstantSendManager) {
quorumInstantSendManager->InterruptWorkerThread();
}
}
} // namespace llmq
|
Bump llmq leveldb cache size to 8 MiB (#4133)
|
llmq: Bump llmq leveldb cache size to 8 MiB (#4133)
|
C++
|
mit
|
dashpay/dash,UdjinM6/dash,UdjinM6/dash,thelazier/dash,dashpay/dash,UdjinM6/dash,UdjinM6/dash,thelazier/dash,thelazier/dash,dashpay/dash,thelazier/dash,dashpay/dash,thelazier/dash,dashpay/dash,UdjinM6/dash
|
0bf1dfdf1178cb0e244df183f91918da08534ac1
|
Plugins/org.mitk.gui.qt.datamanagerlight/src/internal/QmitkDataManagerLightView.cpp
|
Plugins/org.mitk.gui.qt.datamanagerlight/src/internal/QmitkDataManagerLightView.cpp
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkDataManagerLightView.h"
#include "mitkNodePredicateDataType.h"
#include <QApplication>
#include <QFileDialog>
#include <QGridLayout>
#include <QIcon>
#include <QLabel>
#include <QListWidget>
#include <QMessageBox>
#include <QPushButton>
#include <mitkNodePredicateNot.h>
#include <mitkNodePredicateProperty.h>
#include <mitkIRenderingManager.h>
#include <QmitkIOUtil.h>
const std::string QmitkDataManagerLightView::VIEW_ID = "org.mitk.views.datamanagerlight";
struct QmitkDataManagerLightViewData
{
// static
mitk::NodePredicateBase::Pointer m_Predicate;
QIcon m_ItemIcon;
// data
QList<mitk::DataNode*> m_DataNodes;
int m_CurrentIndex;
// widget
QListWidget* m_ListWidget;
QLabel* m_ImageInfoLabel;
QPushButton* m_RemoveButton;
};
QmitkDataManagerLightView::QmitkDataManagerLightView()
: d( new QmitkDataManagerLightViewData )
{
d->m_Predicate = mitk::NodePredicateDataType::New("Image");
d->m_ItemIcon = QIcon(":/org.mitk.gui.qt.datamanagerlight/Image_24.png");
d->m_CurrentIndex = -1;
d->m_ListWidget = 0;
d->m_ImageInfoLabel = 0;
d->m_RemoveButton = 0;
}
QmitkDataManagerLightView::~QmitkDataManagerLightView()
{
delete d;
}
void QmitkDataManagerLightView::NodeAdded(const mitk::DataNode *node)
{
if( d->m_Predicate->CheckNode(node) )
{
mitk::DataNode* nonConstNode = const_cast<mitk::DataNode*>(node);
d->m_DataNodes.append(nonConstNode);
d->m_ListWidget->addItem( new QListWidgetItem( d->m_ItemIcon, QString::fromStdString( node->GetName() ) ) );
}
}
void QmitkDataManagerLightView::NodeRemoved(const mitk::DataNode *node)
{
this->RemoveNode( const_cast<mitk::DataNode*>(node) );
}
void QmitkDataManagerLightView::NodeChanged(const mitk::DataNode *node)
{
MITK_DEBUG << "NodeChanged";
if( d->m_DataNodes.contains(const_cast<mitk::DataNode*>(node)) )
this->ToggleVisibility();
}
void QmitkDataManagerLightView::RemoveNode(mitk::DataNode *node)
{
mitk::DataNode* nonConstNode = const_cast<mitk::DataNode*>(node);
int index = d->m_DataNodes.indexOf(nonConstNode);
if( index >= 0 )
{
MITK_DEBUG << "removing node at: " << index;
QListWidgetItem* item = d->m_ListWidget->takeItem(index);
delete item;
d->m_DataNodes.removeAt(index);
MITK_DEBUG << "item deleted";
}
}
void QmitkDataManagerLightView::CreateQtPartControl(QWidget* parent)
{
QPushButton* loadButton = new QPushButton(QIcon(":/org.mitk.gui.qt.datamanagerlight/Load_48.png"), "Load");
d->m_RemoveButton = new QPushButton(QIcon(":/org.mitk.gui.qt.datamanagerlight/Remove_48.png"), "Remove");
d->m_RemoveButton->setEnabled(false);
d->m_ListWidget = new QListWidget;
d->m_ImageInfoLabel = new QLabel;
QGridLayout* layout = new QGridLayout;
layout->addWidget( loadButton, 0,0 );
layout->addWidget( d->m_RemoveButton, 0,1 );
layout->addWidget( d->m_ImageInfoLabel, 1,0, 1, 2 );
layout->addWidget( d->m_ListWidget, 2,0,1,2 );
parent->setLayout(layout);
connect(d->m_ListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(on_DataItemList_currentRowChanged(int)) );
connect(loadButton, SIGNAL(pressed()), this, SLOT(on_Load_pressed()) );
connect(d->m_RemoveButton, SIGNAL(pressed()), this, SLOT(on_Remove_pressed()) );
this->ListSelectionChanged();
}
void QmitkDataManagerLightView::SetFocus()
{
d->m_ListWidget->setFocus();
}
void QmitkDataManagerLightView::on_DataItemList_currentRowChanged(int currentRow)
{
MITK_DEBUG << "DataItemList currentRowChanged: " << currentRow;
Q_UNUSED(currentRow)
this->ListSelectionChanged();
}
void QmitkDataManagerLightView::ListSelectionChanged()
{
d->m_CurrentIndex = d->m_ListWidget->currentRow();
MITK_DEBUG << "the currently selected index: " << d->m_CurrentIndex;
QString newLabelText = "Current patient: ";
if( d->m_CurrentIndex >= 0 )
{
// TODO WHERE IS THE PATIENT NAME?
std::string name = d->m_DataNodes.at(d->m_CurrentIndex)->GetName();
newLabelText.append( QString("<strong>%1</strong>" ).arg( QString::fromStdString(name) ) );
d->m_RemoveButton->setEnabled(true);
}
else
{
newLabelText.append("<strong>Unknown</strong>");
d->m_RemoveButton->setEnabled(false);
}
d->m_ImageInfoLabel->setText(newLabelText);
this->ToggleVisibility();
}
void QmitkDataManagerLightView::on_Load_pressed()
{
MITK_DEBUG << "on_Load_pressed";
QStringList fileNames = QFileDialog::getOpenFileNames(nullptr, "Load data", "", QmitkIOUtil::GetFileOpenFilterString());
for ( QStringList::Iterator it = fileNames.begin(); it != fileNames.end(); ++it )
{
FileOpen((*it).toLatin1(), 0);
}
}
void QmitkDataManagerLightView::FileOpen( const char * fileName, mitk::DataNode* /*parentNode*/ )
{
try
{
QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) );
mitk::IOUtil::Load(fileName, *this->GetDataStorage());
mitk::RenderingManager::GetInstance()->InitializeViews();
}
catch ( itk::ExceptionObject & ex )
{
MITK_ERROR << "Exception during file open: " << ex;
}
QApplication::restoreOverrideCursor();
}
void QmitkDataManagerLightView::on_Remove_pressed()
{
d->m_CurrentIndex = d->m_ListWidget->currentRow();
MITK_DEBUG << "the currently selected index: " << d->m_CurrentIndex;
mitk::DataNode* node = d->m_DataNodes.at(d->m_CurrentIndex);
QString question = tr("Do you really want to remove ");
// TODO patient name?
question.append( QString::fromStdString( node->GetName() ) );
question.append(" ?");
QMessageBox::StandardButton answerButton = QMessageBox::question( nullptr
, tr("DataManagerLight")
, question
, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
if(answerButton == QMessageBox::Yes)
{
this->GetDataStorage()->Remove(node);
this->GlobalReinit();
}
}
void QmitkDataManagerLightView::GlobalReinit()
{
mitk::IRenderWindowPart* renderWindow = this->GetRenderWindowPart();
// no render window available
if (renderWindow == nullptr) return;
// get all nodes that have not set "includeInBoundingBox" to false
mitk::NodePredicateNot::Pointer pred
= mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox"
, mitk::BoolProperty::New(false)));
mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred);
// calculate bounding geometry of these nodes
mitk::TimeGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs, "visible");
// initialize the views to the bounding geometry
renderWindow->GetRenderingManager()->InitializeViews(bounds);
}
void QmitkDataManagerLightView::ToggleVisibility()
{
bool changedAnything = false;
bool isVisible = false;
for(size_t i=0; i<d->m_DataNodes.size(); ++i)
{
isVisible = false;
d->m_DataNodes.at(i)->GetVisibility(isVisible, 0 );
if( d->m_CurrentIndex == i && isVisible == false )
{
d->m_DataNodes.at(i)->SetVisibility(true);
changedAnything = true;
}
else if( d->m_CurrentIndex != i && isVisible == true )
{
d->m_DataNodes.at(i)->SetVisibility(false);
changedAnything = true;
}
}
if( changedAnything )
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkDataManagerLightView.h"
#include "mitkNodePredicateDataType.h"
#include <QApplication>
#include <QFileDialog>
#include <QGridLayout>
#include <QIcon>
#include <QLabel>
#include <QListWidget>
#include <QMessageBox>
#include <QPushButton>
#include <mitkNodePredicateNot.h>
#include <mitkNodePredicateProperty.h>
#include <mitkIRenderingManager.h>
#include <QmitkIOUtil.h>
const std::string QmitkDataManagerLightView::VIEW_ID = "org.mitk.views.datamanagerlight";
struct QmitkDataManagerLightViewData
{
// static
mitk::NodePredicateBase::Pointer m_Predicate;
QIcon m_ItemIcon;
// data
QList<mitk::DataNode*> m_DataNodes;
int m_CurrentIndex;
// widget
QListWidget* m_ListWidget;
QLabel* m_ImageInfoLabel;
QPushButton* m_RemoveButton;
};
QmitkDataManagerLightView::QmitkDataManagerLightView()
: d( new QmitkDataManagerLightViewData )
{
d->m_Predicate = mitk::NodePredicateDataType::New("Image");
d->m_ItemIcon = QIcon(":/org.mitk.gui.qt.datamanagerlight/Image_24.png");
d->m_CurrentIndex = -1;
d->m_ListWidget = 0;
d->m_ImageInfoLabel = 0;
d->m_RemoveButton = 0;
}
QmitkDataManagerLightView::~QmitkDataManagerLightView()
{
delete d;
}
void QmitkDataManagerLightView::NodeAdded(const mitk::DataNode *node)
{
if( d->m_Predicate->CheckNode(node) )
{
mitk::DataNode* nonConstNode = const_cast<mitk::DataNode*>(node);
d->m_DataNodes.append(nonConstNode);
d->m_ListWidget->addItem( new QListWidgetItem( d->m_ItemIcon, QString::fromStdString( node->GetName() ) ) );
}
}
void QmitkDataManagerLightView::NodeRemoved(const mitk::DataNode *node)
{
this->RemoveNode( const_cast<mitk::DataNode*>(node) );
}
void QmitkDataManagerLightView::NodeChanged(const mitk::DataNode *node)
{
MITK_DEBUG << "NodeChanged";
if( d->m_DataNodes.contains(const_cast<mitk::DataNode*>(node)) )
this->ToggleVisibility();
}
void QmitkDataManagerLightView::RemoveNode(mitk::DataNode *node)
{
mitk::DataNode* nonConstNode = const_cast<mitk::DataNode*>(node);
int index = d->m_DataNodes.indexOf(nonConstNode);
if( index >= 0 )
{
MITK_DEBUG << "removing node at: " << index;
QListWidgetItem* item = d->m_ListWidget->takeItem(index);
delete item;
d->m_DataNodes.removeAt(index);
MITK_DEBUG << "item deleted";
}
}
void QmitkDataManagerLightView::CreateQtPartControl(QWidget* parent)
{
QPushButton* loadButton = new QPushButton(QIcon(":/org.mitk.gui.qt.datamanagerlight/Load_48.png"), "Load");
d->m_RemoveButton = new QPushButton(QIcon(":/org.mitk.gui.qt.datamanagerlight/Remove_48.png"), "Remove");
d->m_RemoveButton->setEnabled(false);
d->m_ListWidget = new QListWidget;
d->m_ImageInfoLabel = new QLabel;
QGridLayout* layout = new QGridLayout;
layout->addWidget( loadButton, 0,0 );
layout->addWidget( d->m_RemoveButton, 0,1 );
layout->addWidget( d->m_ImageInfoLabel, 1,0, 1, 2 );
layout->addWidget( d->m_ListWidget, 2,0,1,2 );
parent->setLayout(layout);
connect(d->m_ListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(on_DataItemList_currentRowChanged(int)) );
connect(loadButton, SIGNAL(pressed()), this, SLOT(on_Load_pressed()) );
connect(d->m_RemoveButton, SIGNAL(pressed()), this, SLOT(on_Remove_pressed()) );
this->ListSelectionChanged();
}
void QmitkDataManagerLightView::SetFocus()
{
d->m_ListWidget->setFocus();
}
void QmitkDataManagerLightView::on_DataItemList_currentRowChanged(int currentRow)
{
MITK_DEBUG << "DataItemList currentRowChanged: " << currentRow;
Q_UNUSED(currentRow)
this->ListSelectionChanged();
}
void QmitkDataManagerLightView::ListSelectionChanged()
{
d->m_CurrentIndex = d->m_ListWidget->currentRow();
MITK_DEBUG << "the currently selected index: " << d->m_CurrentIndex;
QString newLabelText = "Current patient: ";
if( d->m_CurrentIndex >= 0 )
{
// TODO WHERE IS THE PATIENT NAME?
std::string name = d->m_DataNodes.at(d->m_CurrentIndex)->GetName();
newLabelText.append( QString("<strong>%1</strong>" ).arg( QString::fromStdString(name) ) );
d->m_RemoveButton->setEnabled(true);
}
else
{
newLabelText.append("<strong>Unknown</strong>");
d->m_RemoveButton->setEnabled(false);
}
d->m_ImageInfoLabel->setText(newLabelText);
this->ToggleVisibility();
}
void QmitkDataManagerLightView::on_Load_pressed()
{
MITK_DEBUG << "on_Load_pressed";
QStringList fileNames = QFileDialog::getOpenFileNames(nullptr, "Load data", "", QmitkIOUtil::GetFileOpenFilterString());
for ( QStringList::Iterator it = fileNames.begin(); it != fileNames.end(); ++it )
{
FileOpen((*it).toLatin1(), 0);
}
}
void QmitkDataManagerLightView::FileOpen( const char * fileName, mitk::DataNode* /*parentNode*/ )
{
try
{
QApplication::setOverrideCursor( QCursor(Qt::WaitCursor) );
mitk::IOUtil::Load(fileName, *this->GetDataStorage());
mitk::RenderingManager::GetInstance()->InitializeViews();
}
catch ( itk::ExceptionObject & ex )
{
MITK_ERROR << "Exception during file open: " << ex;
}
QApplication::restoreOverrideCursor();
}
void QmitkDataManagerLightView::on_Remove_pressed()
{
d->m_CurrentIndex = d->m_ListWidget->currentRow();
MITK_DEBUG << "the currently selected index: " << d->m_CurrentIndex;
mitk::DataNode* node = d->m_DataNodes.at(d->m_CurrentIndex);
QString question = tr("Do you really want to remove ");
// TODO patient name?
question.append( QString::fromStdString( node->GetName() ) );
question.append(" ?");
QMessageBox::StandardButton answerButton = QMessageBox::question( nullptr
, tr("DataManagerLight")
, question
, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
if(answerButton == QMessageBox::Yes)
{
this->GetDataStorage()->Remove(node);
this->GlobalReinit();
}
}
void QmitkDataManagerLightView::GlobalReinit()
{
mitk::IRenderWindowPart* renderWindow = this->GetRenderWindowPart();
// no render window available
if (renderWindow == nullptr) return;
// get all nodes that have not set "includeInBoundingBox" to false
mitk::NodePredicateNot::Pointer pred
= mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("includeInBoundingBox"
, mitk::BoolProperty::New(false)));
mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred);
// calculate bounding geometry of these nodes
mitk::TimeGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs, "visible");
// initialize the views to the bounding geometry
renderWindow->GetRenderingManager()->InitializeViews(bounds);
}
void QmitkDataManagerLightView::ToggleVisibility()
{
bool changedAnything = false;
bool isVisible = false;
for(int i=0; i<d->m_DataNodes.size(); ++i)
{
isVisible = false;
d->m_DataNodes.at(i)->GetVisibility(isVisible, 0 );
if( d->m_CurrentIndex == i && isVisible == false )
{
d->m_DataNodes.at(i)->SetVisibility(true);
changedAnything = true;
}
else if( d->m_CurrentIndex != i && isVisible == true )
{
d->m_DataNodes.at(i)->SetVisibility(false);
changedAnything = true;
}
}
if( changedAnything )
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
|
Fix warnings in datamanagerlight plugin
|
Fix warnings in datamanagerlight plugin
|
C++
|
bsd-3-clause
|
fmilano/mitk,MITK/MITK,fmilano/mitk,MITK/MITK,fmilano/mitk,MITK/MITK,fmilano/mitk,fmilano/mitk,MITK/MITK,MITK/MITK,MITK/MITK,fmilano/mitk,fmilano/mitk
|
d9a11b94a68ea8140b48da461dfb98927ea7d313
|
bitreader/src/bitreader_gtest.cpp
|
bitreader/src/bitreader_gtest.cpp
|
#include <gtest/gtest.h>
#include "ruberoid/bitreader/bitreader.hpp"
using namespace rb::common;
//------------------------------------------------------------------------------
TEST(bitreaderTest, setData)
{
const uint8_t data[] = {0xFF, 0x11, 0x22, 0x33};
bitreader br;
EXPECT_NO_THROW(br.set_data(data, sizeof(data)));
EXPECT_EQ(0, br.position());
EXPECT_EQ(32, br.available());
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, read_aligned_nonfull)
{
const uint8_t data[] = {0xFF, 0x11, 0x22, 0x33};
bitreader br;
EXPECT_NO_THROW(br.set_data(data, sizeof(data)));
EXPECT_EQ(0xFF, br.read<uint8_t>(8));
EXPECT_EQ(8, br.position());
EXPECT_EQ(24, br.available());
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, read_aligned_full)
{
const uint8_t data[] = {0xFF, 0x11, 0x22, 0x33};
bitreader br;
EXPECT_NO_THROW(br.set_data(data, sizeof(data)));
EXPECT_EQ(0xFF112233, br.read<uint32_t>(32));
EXPECT_EQ(32, br.position());
EXPECT_EQ(0, br.available());
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, read_nonaligned_nonfull)
{
const uint8_t data[] = {0xFF, 0x11, 0x22, 0x33};
bitreader br;
EXPECT_NO_THROW(br.set_data(data, sizeof(data)));
EXPECT_EQ(0xF, br.read<uint8_t>(4));
EXPECT_EQ(4, br.position());
EXPECT_EQ(28, br.available());
EXPECT_EQ(0xF11223, br.read<uint32_t>(24));
EXPECT_EQ(28, br.position());
EXPECT_EQ(4, br.available());
EXPECT_EQ(0x3, br.read<uint16_t>(4));
EXPECT_EQ(32, br.position());
EXPECT_EQ(0, br.available());
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, read_aligned_64)
{
const uint8_t data[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99};
bitreader br;
EXPECT_NO_THROW(br.set_data(data, sizeof(data)));
EXPECT_EQ(0x1122334455667788, br.read<uint64_t>(64));
EXPECT_EQ(64, br.position());
EXPECT_EQ(8, br.available());
EXPECT_EQ(0x99, br.read<uint8_t>(8));
EXPECT_EQ(72, br.position());
EXPECT_EQ(0, br.available());
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, read_aligned_64_cross)
{
const uint8_t data[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99};
bitreader br;
EXPECT_NO_THROW(br.set_data(data, sizeof(data)));
EXPECT_EQ(0x11, br.read<uint8_t>(8));
EXPECT_EQ(8, br.position());
EXPECT_EQ(64, br.available());
EXPECT_EQ(0x2233445566778899, br.read<uint64_t>(64));
EXPECT_EQ(72, br.position());
EXPECT_EQ(0, br.available());
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, read_nonaligned_64_cross)
{
const uint8_t data[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99};
bitreader br;
EXPECT_NO_THROW(br.set_data(data, sizeof(data)));
EXPECT_EQ(0x01, br.read<uint8_t>(4));
EXPECT_EQ(4, br.position());
EXPECT_EQ(68, br.available());
EXPECT_EQ(0x1223344556677889, br.read<uint64_t>(64));
EXPECT_EQ(68, br.position());
EXPECT_EQ(4, br.available());
EXPECT_EQ(0x09, br.read<uint16_t>(4));
EXPECT_EQ(72, br.position());
EXPECT_EQ(0, br.available());
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, read_signed_aligned)
{
const uint8_t data[] = {0xFE, 0x3F};
bitreader br;
EXPECT_NO_THROW(br.set_data(data, sizeof(data)));
EXPECT_EQ(-2, br.read<int8_t>(8));
EXPECT_EQ(0x3F, br.read<int8_t>(8));
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, read_signed_nonaligned)
{
const uint8_t data[] = {0xFE, 0x3F};
bitreader br;
br.set_data(data, sizeof(data));
EXPECT_NO_THROW(br.skip(10));
EXPECT_EQ(-1, br.read<int8_t>(6));
EXPECT_EQ(16, br.position());
EXPECT_EQ(0, br.available());
}
|
#include <gtest/gtest.h>
#include "ruberoid/bitreader/bitreader.hpp"
using namespace rb::common;
//------------------------------------------------------------------------------
TEST(bitreaderTest, setData)
{
const uint8_t data[] = {0xFF, 0x11, 0x22, 0x33};
bitreader br;
EXPECT_NO_THROW(br.set_data(data, sizeof(data)));
EXPECT_EQ(0, br.position());
EXPECT_EQ(32, br.available());
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, read_aligned_nonfull)
{
const uint8_t data[] = {0xFF, 0x11, 0x22, 0x33};
bitreader br;
EXPECT_NO_THROW(br.set_data(data, sizeof(data)));
EXPECT_EQ(0xFF, br.read<uint8_t>(8));
EXPECT_EQ(8, br.position());
EXPECT_EQ(24, br.available());
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, read_aligned_full)
{
const uint8_t data[] = {0xFF, 0x11, 0x22, 0x33};
bitreader br;
EXPECT_NO_THROW(br.set_data(data, sizeof(data)));
EXPECT_EQ(0xFF112233, br.read<uint32_t>(32));
EXPECT_EQ(32, br.position());
EXPECT_EQ(0, br.available());
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, read_nonaligned_nonfull)
{
const uint8_t data[] = {0xFF, 0x11, 0x22, 0x33};
bitreader br;
EXPECT_NO_THROW(br.set_data(data, sizeof(data)));
EXPECT_EQ(0xF, br.read<uint8_t>(4));
EXPECT_EQ(4, br.position());
EXPECT_EQ(28, br.available());
EXPECT_EQ(0xF11223, br.read<uint32_t>(24));
EXPECT_EQ(28, br.position());
EXPECT_EQ(4, br.available());
EXPECT_EQ(0x3, br.read<uint16_t>(4));
EXPECT_EQ(32, br.position());
EXPECT_EQ(0, br.available());
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, read_aligned_64)
{
const uint8_t data[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99};
bitreader br;
EXPECT_NO_THROW(br.set_data(data, sizeof(data)));
EXPECT_EQ(0x1122334455667788, br.read<uint64_t>(64));
EXPECT_EQ(64, br.position());
EXPECT_EQ(8, br.available());
EXPECT_EQ(0x99, br.read<uint8_t>(8));
EXPECT_EQ(72, br.position());
EXPECT_EQ(0, br.available());
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, read_aligned_64_cross)
{
const uint8_t data[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99};
bitreader br;
EXPECT_NO_THROW(br.set_data(data, sizeof(data)));
EXPECT_EQ(0x11, br.read<uint8_t>(8));
EXPECT_EQ(8, br.position());
EXPECT_EQ(64, br.available());
EXPECT_EQ(0x2233445566778899, br.read<uint64_t>(64));
EXPECT_EQ(72, br.position());
EXPECT_EQ(0, br.available());
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, read_nonaligned_64_cross)
{
const uint8_t data[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99};
bitreader br;
EXPECT_NO_THROW(br.set_data(data, sizeof(data)));
EXPECT_EQ(0x01, br.read<uint8_t>(4));
EXPECT_EQ(4, br.position());
EXPECT_EQ(68, br.available());
EXPECT_EQ(0x1223344556677889, br.read<uint64_t>(64));
EXPECT_EQ(68, br.position());
EXPECT_EQ(4, br.available());
EXPECT_EQ(0x09, br.read<uint16_t>(4));
EXPECT_EQ(72, br.position());
EXPECT_EQ(0, br.available());
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, read_signed_aligned)
{
const uint8_t data[] = {0xFE, 0x3F};
bitreader br;
EXPECT_NO_THROW(br.set_data(data, sizeof(data)));
EXPECT_EQ(-2, br.read<int8_t>(8));
EXPECT_EQ(0x3F, br.read<int8_t>(8));
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, read_signed_nonaligned)
{
const uint8_t data[] = {0xFE, 0x3F};
bitreader br;
br.set_data(data, sizeof(data));
EXPECT_NO_THROW(br.skip(10));
EXPECT_EQ(-1, br.read<int8_t>(6));
EXPECT_EQ(16, br.position());
EXPECT_EQ(0, br.available());
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, skip_non_cross_aligned)
{
const uint8_t data[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99};
bitreader br;
br.set_data(data, sizeof(data));
EXPECT_NO_THROW(br.skip(3*8));
EXPECT_EQ(24, br.position());
EXPECT_EQ(48, br.available());
EXPECT_EQ(0x445, br.read<uint16_t>(12));
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, skip_non_cross_unaligned)
{
const uint8_t data[] = {0x11, 0x22, 0x33, 0x44, 0x55};
bitreader br;
br.set_data(data, sizeof(data));
EXPECT_NO_THROW(br.skip(7));
EXPECT_EQ(7, br.position());
EXPECT_EQ(33, br.available());
EXPECT_EQ(0x122, br.peek<uint16_t>(9));
EXPECT_EQ(7, br.position());
EXPECT_EQ(33, br.available());
EXPECT_NO_THROW(br.skip(21));
EXPECT_EQ(28, br.position());
EXPECT_EQ(12, br.available());
EXPECT_EQ(0x455, br.read<uint16_t>(12));
EXPECT_EQ(40, br.position());
EXPECT_EQ(0, br.available());
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, skip_cross_aligned)
{
const uint8_t data[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA};
bitreader br;
br.set_data(data, sizeof(data));
EXPECT_NO_THROW(br.skip(72));
EXPECT_EQ(72, br.position());
EXPECT_EQ(8, br.available());
EXPECT_EQ(0xAA, br.read<uint8_t>(8));
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, skip_cross_unaligned)
{
const uint8_t data[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA};
bitreader br;
br.set_data(data, sizeof(data));
EXPECT_NO_THROW(br.skip(74));
EXPECT_EQ(74, br.position());
EXPECT_EQ(6, br.available());
EXPECT_EQ(0b10'1010, br.read<uint8_t>(6));
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, peek_non_cross_aligned)
{
const uint8_t data[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA};
bitreader br;
br.set_data(data, sizeof(data));
EXPECT_EQ(0x1122, br.peek<uint16_t>(16));
EXPECT_EQ(0, br.position());
EXPECT_EQ(0x1122, br.read<uint16_t>(16));
EXPECT_EQ(16, br.position());
EXPECT_EQ(0x3344, br.peek<uint16_t>(16));
EXPECT_EQ(16, br.position());
EXPECT_EQ(0x3344, br.read<uint16_t>(16));
EXPECT_EQ(32, br.position());
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, peek_non_cross_unaligned)
{
const uint8_t data[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA};
bitreader br;
br.set_data(data, sizeof(data));
EXPECT_EQ(0x112, br.peek<uint16_t>(12));
EXPECT_EQ(0, br.position());
EXPECT_EQ(0x112, br.read<uint16_t>(12));
EXPECT_EQ(12, br.position());
EXPECT_EQ(0x233, br.peek<uint16_t>(12));
EXPECT_EQ(12, br.position());
EXPECT_EQ(0x23344, br.read<uint32_t>(20));
EXPECT_EQ(32, br.position());
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, peek_cross_aligned)
{
const uint8_t data[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA};
bitreader br;
br.set_data(data, sizeof(data));
EXPECT_NO_THROW(br.skip(48));
EXPECT_EQ(48, br.position());
EXPECT_EQ(0x778899, br.peek<uint32_t>(24));
EXPECT_EQ(48, br.position());
EXPECT_EQ(0x778899AA, br.read<uint32_t>(32));
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, peek_cross_unaligned)
{
const uint8_t data[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA};
bitreader br;
br.set_data(data, sizeof(data));
EXPECT_NO_THROW(br.skip(52));
EXPECT_EQ(52, br.position());
EXPECT_EQ(0x78899A, br.peek<uint32_t>(24));
EXPECT_EQ(52, br.position());
EXPECT_EQ(0x78899AA, br.read<uint32_t>(28));
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, align_lt_byte_aligned)
{
const uint8_t data[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA};
bitreader br;
br.set_data(data, sizeof(data));
EXPECT_NO_THROW(br.align(5));
EXPECT_EQ(0, br.position());
EXPECT_NO_THROW(br.skip(10));
EXPECT_EQ(10, br.position());
EXPECT_NO_THROW(br.align(5));
EXPECT_EQ(10, br.position());
}
//------------------------------------------------------------------------------
TEST(bitreaderTest, align_lt_byte_unaligned)
{
const uint8_t data[] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA};
bitreader br;
br.set_data(data, sizeof(data));
EXPECT_NO_THROW(br.skip(2));
EXPECT_EQ(2, br.position());
EXPECT_NO_THROW(br.align(5));
EXPECT_EQ(5, br.position());
}
|
Add tests for skips and alignment
|
Add tests for skips and alignment
|
C++
|
bsd-3-clause
|
axethrower/ruberoid
|
7afc8ccd5a93011a12d8511bb8173f2da21fcefb
|
moveit_ros/planning/kinematics_plugin_loader/src/kinematics_plugin_loader.cpp
|
moveit_ros/planning/kinematics_plugin_loader/src/kinematics_plugin_loader.cpp
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage 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: Ioan Sucan */
#include <moveit/kinematics_plugin_loader/kinematics_plugin_loader.h>
#include <moveit/rdf_loader/rdf_loader.h>
#include <pluginlib/class_loader.h>
#include <boost/thread/mutex.hpp>
#include <sstream>
#include <vector>
#include <map>
#include <ros/ros.h>
#include <moveit/profiler/profiler.h>
namespace kinematics_plugin_loader
{
class KinematicsPluginLoader::KinematicsLoaderImpl
{
public:
KinematicsLoaderImpl(const std::string &robot_description,
const std::map<std::string, std::vector<std::string> > &possible_kinematics_solvers,
const std::map<std::string, std::vector<double> > &search_res,
const std::map<std::string, std::string> &ik_links) :
robot_description_(robot_description),
possible_kinematics_solvers_(possible_kinematics_solvers),
search_res_(search_res),
ik_links_(ik_links)
{
try
{
kinematics_loader_.reset(new pluginlib::ClassLoader<kinematics::KinematicsBase>("moveit_core", "kinematics::KinematicsBase"));
}
catch(pluginlib::PluginlibException& e)
{
ROS_ERROR("Unable to construct kinematics loader. Error: %s", e.what());
}
}
boost::shared_ptr<kinematics::KinematicsBase> allocKinematicsSolver(const robot_model::JointModelGroup *jmg)
{
boost::shared_ptr<kinematics::KinematicsBase> result;
if (!jmg)
{
ROS_ERROR("Specified group is NULL. Cannot allocate kinematics solver.");
return result;
}
ROS_DEBUG("Received request to allocate kinematics solver for group '%s'", jmg->getName().c_str());
if (kinematics_loader_ && jmg)
{
std::map<std::string, std::vector<std::string> >::const_iterator it = possible_kinematics_solvers_.find(jmg->getName());
if (it != possible_kinematics_solvers_.end())
{
// just to be sure, do not call the same pluginlib instance allocation function in parallel
boost::mutex::scoped_lock slock(lock_);
for (std::size_t i = 0 ; !result && i < it->second.size() ; ++i)
{
try
{
result.reset(kinematics_loader_->createUnmanagedInstance(it->second[i]));
if (result)
{
const std::vector<const robot_model::LinkModel*> &links = jmg->getLinkModels();
if (!links.empty())
{
const std::string &base = links.front()->getParentJointModel()->getParentLinkModel() ?
links.front()->getParentJointModel()->getParentLinkModel()->getName() : jmg->getParentModel().getModelFrame();
std::map<std::string, std::string>::const_iterator ik_it = ik_links_.find(jmg->getName());
const std::string &tip = ik_it != ik_links_.end() ? ik_it->second : links.back()->getName();
double search_res = search_res_.find(jmg->getName())->second[i]; // we know this exists, by construction
if (!result->initialize(robot_description_, jmg->getName(),
(base.empty() || base[0] != '/') ? base : base.substr(1) , tip, search_res))
{
ROS_ERROR("Kinematics solver of type '%s' could not be initialized for group '%s'", it->second[i].c_str(), jmg->getName().c_str());
result.reset();
}
else
{
result->setDefaultTimeout(jmg->getDefaultIKTimeout());
ROS_DEBUG("Successfully allocated and initialized a kinematics solver of type '%s' with search resolution %lf for group '%s' at address %p",
it->second[i].c_str(), search_res, jmg->getName().c_str(), result.get());
}
}
else
ROS_ERROR("No links specified for group '%s'", jmg->getName().c_str());
}
}
catch (pluginlib::PluginlibException& e)
{
ROS_ERROR("The kinematics plugin (%s) failed to load. Error: %s", it->first.c_str(), e.what());
}
}
}
else
ROS_DEBUG("No kinematics solver available for this group");
}
if (!result)
{
ROS_DEBUG("No usable kinematics solver was found for this group.");
ROS_DEBUG("Did you load kinematics.yaml into your node's namespace?");
}
return result;
}
boost::shared_ptr<kinematics::KinematicsBase> allocKinematicsSolverWithCache(const robot_model::JointModelGroup *jmg)
{
{
boost::mutex::scoped_lock slock(lock_);
const std::vector<boost::shared_ptr<kinematics::KinematicsBase> > &vi = instances_[jmg];
for (std::size_t i = 0 ; i < vi.size() ; ++i)
if (vi[i].unique())
{
ROS_DEBUG("Reusing cached kinematics solver for group '%s'", jmg->getName().c_str());
return vi[i]; // this is safe since the shared_ptr is copied on stack BEFORE the destructors in scope get called
}
}
boost::shared_ptr<kinematics::KinematicsBase> res = allocKinematicsSolver(jmg);
{
boost::mutex::scoped_lock slock(lock_);
instances_[jmg].push_back(res);
return res;
}
}
void status() const
{
for (std::map<std::string, std::vector<std::string> >::const_iterator it = possible_kinematics_solvers_.begin() ; it != possible_kinematics_solvers_.end() ; ++it)
for (std::size_t i = 0 ; i < it->second.size() ; ++i)
ROS_INFO("Solver for group '%s': '%s' (search resolution = %lf)", it->first.c_str(), it->second[i].c_str(), search_res_.at(it->first)[i]);
}
private:
std::string robot_description_;
std::map<std::string, std::vector<std::string> > possible_kinematics_solvers_;
std::map<std::string, std::vector<double> > search_res_;
std::map<std::string, std::string> ik_links_;
boost::shared_ptr<pluginlib::ClassLoader<kinematics::KinematicsBase> > kinematics_loader_;
std::map<const robot_model::JointModelGroup*,
std::vector<boost::shared_ptr<kinematics::KinematicsBase> > > instances_;
boost::mutex lock_;
};
}
void kinematics_plugin_loader::KinematicsPluginLoader::status() const
{
if (loader_)
loader_->status();
else
ROS_INFO("Loader function was never required");
}
robot_model::SolverAllocatorFn kinematics_plugin_loader::KinematicsPluginLoader::getLoaderFunction()
{
moveit::tools::Profiler::ScopedStart prof_start;
moveit::tools::Profiler::ScopedBlock prof_block("KinematicsPluginLoader::getLoaderFunction");
if (loader_)
return boost::bind(&KinematicsPluginLoader::KinematicsLoaderImpl::allocKinematicsSolverWithCache, loader_.get(), _1);
rdf_loader::RDFLoader rml(robot_description_);
robot_description_ = rml.getRobotDescription();
return getLoaderFunction(rml.getSRDF());
}
robot_model::SolverAllocatorFn kinematics_plugin_loader::KinematicsPluginLoader::getLoaderFunction(const boost::shared_ptr<srdf::Model> &srdf_model)
{
moveit::tools::Profiler::ScopedStart prof_start;
moveit::tools::Profiler::ScopedBlock prof_block("KinematicsPluginLoader::getLoaderFunction(SRDF)");
if (!loader_)
{
ROS_DEBUG("Configuring kinematics solvers");
groups_.clear();
std::map<std::string, std::vector<std::string> > possible_kinematics_solvers;
std::map<std::string, std::vector<double> > search_res;
std::map<std::string, std::string> ik_links;
if (srdf_model)
{
const std::vector<srdf::Model::Group> &known_groups = srdf_model->getGroups();
if (default_search_resolution_ <= std::numeric_limits<double>::epsilon())
default_search_resolution_ = kinematics::KinematicsBase::DEFAULT_SEARCH_DISCRETIZATION;
if (default_solver_plugin_.empty())
{
ROS_DEBUG("Loading settings for kinematics solvers from the ROS param server ...");
// read data using ROS params
ros::NodeHandle nh("~");
// read the list of plugin names for possible kinematics solvers
for (std::size_t i = 0 ; i < known_groups.size() ; ++i)
{
std::string base_param_name = known_groups[i].name_;
ROS_DEBUG("Looking for param %s ", (base_param_name + "/kinematics_solver").c_str());
std::string ksolver_param_name;
bool found = nh.searchParam(base_param_name + "/kinematics_solver", ksolver_param_name);
if (!found)
{
base_param_name = robot_description_ + "_kinematics";
ROS_DEBUG("Looking for param %s ", (base_param_name + "/kinematics_solver").c_str());
found = nh.searchParam(base_param_name + "/kinematics_solver", ksolver_param_name);
}
if (found)
{
ROS_DEBUG("Found param %s", ksolver_param_name.c_str());
std::string ksolver;
if (nh.getParam(ksolver_param_name, ksolver))
{
std::stringstream ss(ksolver);
bool first = true;
while (ss.good() && !ss.eof())
{
if (first)
{
first = false;
groups_.push_back(known_groups[i].name_);
}
std::string solver; ss >> solver >> std::ws;
possible_kinematics_solvers[known_groups[i].name_].push_back(solver);
ROS_DEBUG("Using kinematics solver '%s' for group '%s'.", solver.c_str(), known_groups[i].name_.c_str());
}
}
}
std::string ksolver_timeout_param_name;
if (nh.searchParam(base_param_name + "/kinematics_solver_timeout", ksolver_timeout_param_name))
{
double ksolver_timeout;
if (nh.getParam(ksolver_timeout_param_name, ksolver_timeout))
ik_timeout_[known_groups[i].name_] = ksolver_timeout;
else
{// just in case this is an int
int ksolver_timeout_i;
if (nh.getParam(ksolver_timeout_param_name, ksolver_timeout_i))
ik_timeout_[known_groups[i].name_] = ksolver_timeout_i;
}
}
std::string ksolver_attempts_param_name;
if (nh.searchParam(base_param_name + "/kinematics_solver_attempts", ksolver_attempts_param_name))
{
int ksolver_attempts;
if (nh.getParam(ksolver_attempts_param_name, ksolver_attempts))
ik_attempts_[known_groups[i].name_] = ksolver_attempts;
}
std::string ksolver_res_param_name;
if (nh.searchParam(base_param_name + "/kinematics_solver_search_resolution", ksolver_res_param_name))
{
std::string ksolver_res;
if (nh.getParam(ksolver_res_param_name, ksolver_res))
{
std::stringstream ss(ksolver_res);
while (ss.good() && !ss.eof())
{
double res; ss >> res >> std::ws;
search_res[known_groups[i].name_].push_back(res);
}
}
else
{ // handle the case this param is just one value and parsed as a double
double res;
if (nh.getParam(ksolver_res_param_name, res))
search_res[known_groups[i].name_].push_back(res);
else
{
int res_i;
if (nh.getParam(ksolver_res_param_name, res_i))
search_res[known_groups[i].name_].push_back(res_i);
}
}
}
std::string ksolver_ik_link_param_name;
if (nh.searchParam(base_param_name + "/kinematics_solver_ik_link", ksolver_ik_link_param_name))
{
std::string ksolver_ik_link;
if (nh.getParam(ksolver_ik_link_param_name, ksolver_ik_link))
ik_links[known_groups[i].name_] = ksolver_ik_link;
}
// make sure there is a default resolution at least specified for every solver (in case it was not specified on the param server)
while (search_res[known_groups[i].name_].size() < possible_kinematics_solvers[known_groups[i].name_].size())
search_res[known_groups[i].name_].push_back(default_search_resolution_);
}
}
else
{
ROS_DEBUG("Using specified default settings for kinematics solvers ...");
for (std::size_t i = 0 ; i < known_groups.size() ; ++i)
{
possible_kinematics_solvers[known_groups[i].name_].resize(1, default_solver_plugin_);
search_res[known_groups[i].name_].resize(1, default_search_resolution_);
ik_timeout_[known_groups[i].name_] = default_solver_timeout_;
ik_attempts_[known_groups[i].name_] = default_ik_attempts_;
groups_.push_back(known_groups[i].name_);
}
}
}
loader_.reset(new KinematicsLoaderImpl(robot_description_, possible_kinematics_solvers, search_res, ik_links));
}
return boost::bind(&KinematicsPluginLoader::KinematicsLoaderImpl::allocKinematicsSolverWithCache, loader_.get(), _1);
}
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage 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: Ioan Sucan */
#include <moveit/kinematics_plugin_loader/kinematics_plugin_loader.h>
#include <moveit/rdf_loader/rdf_loader.h>
#include <pluginlib/class_loader.h>
#include <boost/thread/mutex.hpp>
#include <sstream>
#include <vector>
#include <map>
#include <ros/ros.h>
#include <moveit/profiler/profiler.h>
namespace kinematics_plugin_loader
{
class KinematicsPluginLoader::KinematicsLoaderImpl
{
public:
KinematicsLoaderImpl(const std::string &robot_description,
const std::map<std::string, std::vector<std::string> > &possible_kinematics_solvers,
const std::map<std::string, std::vector<double> > &search_res,
const std::map<std::string, std::string> &ik_links) :
robot_description_(robot_description),
possible_kinematics_solvers_(possible_kinematics_solvers),
search_res_(search_res),
ik_links_(ik_links)
{
try
{
kinematics_loader_.reset(new pluginlib::ClassLoader<kinematics::KinematicsBase>("moveit_core", "kinematics::KinematicsBase"));
}
catch(pluginlib::PluginlibException& e)
{
ROS_ERROR("Unable to construct kinematics loader. Error: %s", e.what());
}
}
boost::shared_ptr<kinematics::KinematicsBase> allocKinematicsSolver(const robot_model::JointModelGroup *jmg)
{
boost::shared_ptr<kinematics::KinematicsBase> result;
if (!jmg)
{
ROS_ERROR("Specified group is NULL. Cannot allocate kinematics solver.");
return result;
}
ROS_DEBUG("Received request to allocate kinematics solver for group '%s'", jmg->getName().c_str());
if (kinematics_loader_ && jmg)
{
std::map<std::string, std::vector<std::string> >::const_iterator it = possible_kinematics_solvers_.find(jmg->getName());
if (it != possible_kinematics_solvers_.end())
{
// just to be sure, do not call the same pluginlib instance allocation function in parallel
boost::mutex::scoped_lock slock(lock_);
for (std::size_t i = 0 ; !result && i < it->second.size() ; ++i)
{
try
{
result.reset(kinematics_loader_->createUnmanagedInstance(it->second[i]));
if (result)
{
const std::vector<const robot_model::LinkModel*> &links = jmg->getLinkModels();
if (!links.empty())
{
const std::string &base = links.front()->getParentJointModel()->getParentLinkModel() ?
links.front()->getParentJointModel()->getParentLinkModel()->getName() : jmg->getParentModel().getModelFrame();
std::map<std::string, std::string>::const_iterator ik_it = ik_links_.find(jmg->getName());
const std::string &tip = ik_it != ik_links_.end() ? ik_it->second : links.back()->getName();
double search_res = search_res_.find(jmg->getName())->second[i]; // we know this exists, by construction
if (!result->initialize(robot_description_, jmg->getName(),
(base.empty() || base[0] != '/') ? base : base.substr(1) , tip, search_res))
{
ROS_ERROR("Kinematics solver of type '%s' could not be initialized for group '%s'", it->second[i].c_str(), jmg->getName().c_str());
result.reset();
}
else
{
result->setDefaultTimeout(jmg->getDefaultIKTimeout());
ROS_DEBUG("Successfully allocated and initialized a kinematics solver of type '%s' with search resolution %lf for group '%s' at address %p",
it->second[i].c_str(), search_res, jmg->getName().c_str(), result.get());
}
}
else
ROS_ERROR("No links specified for group '%s'", jmg->getName().c_str());
}
}
catch (pluginlib::PluginlibException& e)
{
ROS_ERROR("The kinematics plugin (%s) failed to load. Error: %s", it->first.c_str(), e.what());
}
}
}
else
ROS_DEBUG("No kinematics solver available for this group");
}
if (!result)
{
ROS_DEBUG("No usable kinematics solver was found for this group.");
ROS_DEBUG("Did you load kinematics.yaml into your node's namespace?");
}
return result;
}
boost::shared_ptr<kinematics::KinematicsBase> allocKinematicsSolverWithCache(const robot_model::JointModelGroup *jmg)
{
{
boost::mutex::scoped_lock slock(lock_);
const std::vector<boost::shared_ptr<kinematics::KinematicsBase> > &vi = instances_[jmg];
for (std::size_t i = 0 ; i < vi.size() ; ++i)
if (vi[i].unique())
{
ROS_DEBUG("Reusing cached kinematics solver for group '%s'", jmg->getName().c_str());
return vi[i]; // this is safe since the shared_ptr is copied on stack BEFORE the destructors in scope get called
}
}
boost::shared_ptr<kinematics::KinematicsBase> res = allocKinematicsSolver(jmg);
{
boost::mutex::scoped_lock slock(lock_);
instances_[jmg].push_back(res);
return res;
}
}
void status() const
{
for (std::map<std::string, std::vector<std::string> >::const_iterator it = possible_kinematics_solvers_.begin() ; it != possible_kinematics_solvers_.end() ; ++it)
for (std::size_t i = 0 ; i < it->second.size() ; ++i)
ROS_INFO("Solver for group '%s': '%s' (search resolution = %lf)", it->first.c_str(), it->second[i].c_str(), search_res_.at(it->first)[i]);
}
private:
std::string robot_description_;
std::map<std::string, std::vector<std::string> > possible_kinematics_solvers_;
std::map<std::string, std::vector<double> > search_res_;
std::map<std::string, std::string> ik_links_;
boost::shared_ptr<pluginlib::ClassLoader<kinematics::KinematicsBase> > kinematics_loader_;
std::map<const robot_model::JointModelGroup*,
std::vector<boost::shared_ptr<kinematics::KinematicsBase> > > instances_;
boost::mutex lock_;
};
}
void kinematics_plugin_loader::KinematicsPluginLoader::status() const
{
if (loader_)
loader_->status();
else
ROS_INFO("Loader function was never required");
}
robot_model::SolverAllocatorFn kinematics_plugin_loader::KinematicsPluginLoader::getLoaderFunction()
{
moveit::tools::Profiler::ScopedStart prof_start;
moveit::tools::Profiler::ScopedBlock prof_block("KinematicsPluginLoader::getLoaderFunction");
if (loader_)
return boost::bind(&KinematicsPluginLoader::KinematicsLoaderImpl::allocKinematicsSolverWithCache, loader_.get(), _1);
rdf_loader::RDFLoader rml(robot_description_);
robot_description_ = rml.getRobotDescription();
return getLoaderFunction(rml.getSRDF());
}
robot_model::SolverAllocatorFn kinematics_plugin_loader::KinematicsPluginLoader::getLoaderFunction(const boost::shared_ptr<srdf::Model> &srdf_model)
{
moveit::tools::Profiler::ScopedStart prof_start;
moveit::tools::Profiler::ScopedBlock prof_block("KinematicsPluginLoader::getLoaderFunction(SRDF)");
if (!loader_)
{
ROS_DEBUG("Configuring kinematics solvers");
groups_.clear();
std::map<std::string, std::vector<std::string> > possible_kinematics_solvers;
std::map<std::string, std::vector<double> > search_res;
std::map<std::string, std::string> ik_links;
if (srdf_model)
{
const std::vector<srdf::Model::Group> &known_groups = srdf_model->getGroups();
if (default_search_resolution_ <= std::numeric_limits<double>::epsilon())
default_search_resolution_ = kinematics::KinematicsBase::DEFAULT_SEARCH_DISCRETIZATION;
if (default_solver_plugin_.empty())
{
ROS_DEBUG("Loading settings for kinematics solvers from the ROS param server ...");
// read data using ROS params
ros::NodeHandle nh("~");
// read the list of plugin names for possible kinematics solvers
for (std::size_t i = 0 ; i < known_groups.size() ; ++i)
{
std::string base_param_name = known_groups[i].name_;
ROS_DEBUG("Looking for param %s ", (base_param_name + "/kinematics_solver").c_str());
std::string ksolver_param_name;
bool found = nh.searchParam(base_param_name + "/kinematics_solver", ksolver_param_name);
if (!found)
{
base_param_name = robot_description_ + "_kinematics/" + known_groups[i].name_;
ROS_DEBUG("Looking for param %s ", (base_param_name + "/kinematics_solver").c_str());
found = nh.searchParam(base_param_name + "/kinematics_solver", ksolver_param_name);
}
if (found)
{
ROS_DEBUG("Found param %s", ksolver_param_name.c_str());
std::string ksolver;
if (nh.getParam(ksolver_param_name, ksolver))
{
std::stringstream ss(ksolver);
bool first = true;
while (ss.good() && !ss.eof())
{
if (first)
{
first = false;
groups_.push_back(known_groups[i].name_);
}
std::string solver; ss >> solver >> std::ws;
possible_kinematics_solvers[known_groups[i].name_].push_back(solver);
ROS_DEBUG("Using kinematics solver '%s' for group '%s'.", solver.c_str(), known_groups[i].name_.c_str());
}
}
}
std::string ksolver_timeout_param_name;
if (nh.searchParam(base_param_name + "/kinematics_solver_timeout", ksolver_timeout_param_name))
{
double ksolver_timeout;
if (nh.getParam(ksolver_timeout_param_name, ksolver_timeout))
ik_timeout_[known_groups[i].name_] = ksolver_timeout;
else
{// just in case this is an int
int ksolver_timeout_i;
if (nh.getParam(ksolver_timeout_param_name, ksolver_timeout_i))
ik_timeout_[known_groups[i].name_] = ksolver_timeout_i;
}
}
std::string ksolver_attempts_param_name;
if (nh.searchParam(base_param_name + "/kinematics_solver_attempts", ksolver_attempts_param_name))
{
int ksolver_attempts;
if (nh.getParam(ksolver_attempts_param_name, ksolver_attempts))
ik_attempts_[known_groups[i].name_] = ksolver_attempts;
}
std::string ksolver_res_param_name;
if (nh.searchParam(base_param_name + "/kinematics_solver_search_resolution", ksolver_res_param_name))
{
std::string ksolver_res;
if (nh.getParam(ksolver_res_param_name, ksolver_res))
{
std::stringstream ss(ksolver_res);
while (ss.good() && !ss.eof())
{
double res; ss >> res >> std::ws;
search_res[known_groups[i].name_].push_back(res);
}
}
else
{ // handle the case this param is just one value and parsed as a double
double res;
if (nh.getParam(ksolver_res_param_name, res))
search_res[known_groups[i].name_].push_back(res);
else
{
int res_i;
if (nh.getParam(ksolver_res_param_name, res_i))
search_res[known_groups[i].name_].push_back(res_i);
}
}
}
std::string ksolver_ik_link_param_name;
if (nh.searchParam(base_param_name + "/kinematics_solver_ik_link", ksolver_ik_link_param_name))
{
std::string ksolver_ik_link;
if (nh.getParam(ksolver_ik_link_param_name, ksolver_ik_link))
ik_links[known_groups[i].name_] = ksolver_ik_link;
}
// make sure there is a default resolution at least specified for every solver (in case it was not specified on the param server)
while (search_res[known_groups[i].name_].size() < possible_kinematics_solvers[known_groups[i].name_].size())
search_res[known_groups[i].name_].push_back(default_search_resolution_);
}
}
else
{
ROS_DEBUG("Using specified default settings for kinematics solvers ...");
for (std::size_t i = 0 ; i < known_groups.size() ; ++i)
{
possible_kinematics_solvers[known_groups[i].name_].resize(1, default_solver_plugin_);
search_res[known_groups[i].name_].resize(1, default_search_resolution_);
ik_timeout_[known_groups[i].name_] = default_solver_timeout_;
ik_attempts_[known_groups[i].name_] = default_ik_attempts_;
groups_.push_back(known_groups[i].name_);
}
}
}
loader_.reset(new KinematicsLoaderImpl(robot_description_, possible_kinematics_solvers, search_res, ik_links));
}
return boost::bind(&KinematicsPluginLoader::KinematicsLoaderImpl::allocKinematicsSolverWithCache, loader_.get(), _1);
}
|
fix loading of default params
|
fix loading of default params
|
C++
|
bsd-3-clause
|
ros-planning/moveit,v4hn/moveit,davetcoleman/moveit,v4hn/moveit,davetcoleman/moveit,davetcoleman/moveit,ros-planning/moveit,ros-planning/moveit,ros-planning/moveit,v4hn/moveit,davetcoleman/moveit,v4hn/moveit,ros-planning/moveit
|
1053852681aa5425a3495e652390f7abe0da7318
|
src/storage/disk_worker.cc
|
src/storage/disk_worker.cc
|
// Licensed under the Apache License 2.0 (see LICENSE file).
#include "disk_worker.h"
namespace cheesebase {
DiskWorker::DiskWorker(const std::string& filename, OpenMode mode)
: m_fileio(filename, mode)
, m_async(std::async(std::launch::async, [this]() { loop(); }))
{}
DiskWorker::~DiskWorker()
{
m_run = false;
m_queue_notify.notify_all();
}
void DiskWorker::loop()
{
ExLock<Mutex> lck{ m_queue_mtx };
while (m_run) {
AsyncReq last{};
Cond* cond{ nullptr };
while (m_queue.size() > 0) {
auto req = m_queue.dequeue();
lck.unlock();
if (req->which() == 0) {
auto& wreq = boost::get<DiskReq<gsl::span<const byte>>>(*req);
last = m_fileio.write_async(wreq.offset, wreq.buffer);
if (cond) cond->notify_all();
cond = wreq.cb;
} else {
auto& rreq = boost::get<DiskReq<gsl::span<byte>>>(*req);
last = m_fileio.read_async(rreq.offset, rreq.buffer);
if (cond) cond->notify_all();
cond = rreq.cb;
}
lck.lock();
}
last.wait();
if (cond) cond->notify_all();
m_queue_notify.wait(lck);
}
}
void DiskWorker::write(gsl::span<const byte> buffer, Addr disk_addr)
{
ExLock<Mutex> lck{ m_queue_mtx };
Cond cb;
m_queue.enqueue(disk_addr,
std::make_unique<DiskReqVar>(DiskWriteReq({ disk_addr,
buffer,
&cb })));
m_queue_notify.notify_all();
cb.wait(lck);
}
void DiskWorker::read(gsl::span<byte> buffer, Addr disk_addr)
{
ExLock<Mutex> lck{ m_queue_mtx };
Cond cb;
m_queue.enqueue(disk_addr,
std::make_unique<DiskReqVar>(DiskReadReq({ disk_addr,
buffer,
&cb })));
m_queue_notify.notify_all();
cb.wait(lck);
}
} // namespace cheesebase
|
// Licensed under the Apache License 2.0 (see LICENSE file).
#include "disk_worker.h"
namespace cheesebase {
DiskWorker::DiskWorker(const std::string& filename, OpenMode mode)
: m_fileio(filename, mode, true)
, m_async(std::async(std::launch::async, [this]() { loop(); }))
{}
DiskWorker::~DiskWorker()
{
m_run = false;
m_queue_notify.notify_all();
}
void DiskWorker::loop()
{
ExLock<Mutex> lck{ m_queue_mtx };
while (m_run) {
AsyncReq last{};
Cond* cond{ nullptr };
while (m_queue.size() > 0) {
auto req = m_queue.dequeue();
lck.unlock();
if (req->which() == 0) {
auto& wreq = boost::get<DiskReq<gsl::span<const byte>>>(*req);
last = m_fileio.write_async(wreq.offset, wreq.buffer);
if (cond) cond->notify_all();
cond = wreq.cb;
} else {
auto& rreq = boost::get<DiskReq<gsl::span<byte>>>(*req);
last = m_fileio.read_async(rreq.offset, rreq.buffer);
if (cond) cond->notify_all();
cond = rreq.cb;
}
lck.lock();
}
last.wait();
if (cond) cond->notify_all();
m_queue_notify.wait(lck);
}
}
void DiskWorker::write(gsl::span<const byte> buffer, Addr disk_addr)
{
ExLock<Mutex> lck{ m_queue_mtx };
Cond cb;
m_queue.enqueue(disk_addr,
std::make_unique<DiskReqVar>(DiskWriteReq({ disk_addr,
buffer,
&cb })));
m_queue_notify.notify_all();
cb.wait(lck);
}
void DiskWorker::read(gsl::span<byte> buffer, Addr disk_addr)
{
if (disk_addr >= m_fileio.size()) return;
ExLock<Mutex> lck{ m_queue_mtx };
Cond cb;
m_queue.enqueue(disk_addr,
std::make_unique<DiskReqVar>(DiskReadReq({ disk_addr,
buffer,
&cb })));
m_queue_notify.notify_all();
cb.wait(lck);
}
} // namespace cheesebase
|
use direct file access
|
use direct file access
|
C++
|
apache-2.0
|
mcheese/cheesebase,mcheese/cheesebase
|
22f61318eb399fc79cea3b5a59733a358bf0a431
|
leetcode/ThreeSum.cpp
|
leetcode/ThreeSum.cpp
|
//
// Created by zeph on 11/18/16.
//
#include <iostream>
#include <cassert>
#include <vector>
#include <set>
#include "../helpers/coutFriends.cpp"
/***
From: https://leetcode.com/problems/3sum/
Given an array V of n integers, are there elements a, b, c in V such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example:
```
Given array V = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
```
At this point, it is probably no easier to solve N-sum than solving 3-sum specificially.
P(V, N, s):
Given array V, number of summands N, and a target sum s:
Find all distinct N-tuples of V which add up to s.
Pseudocode:
Base case: P(V, 0, s)
If s = 0: return () the 0-tuple
Else: return no-solution
N-1 => N:
Let T = {}
For each i in V:
T = T U {i} X P(V-{i}, N-1, s-i) // Note that when P(V-{i}, N-1, s-i) is empty, we just skip all processing
Run time analysis:
VTEP N-1 => N:
T(|V|, N) = |V| * T(|V|-1, N-1)
= |V| * |V-1| * T(|V| - 2, N-2)
.... assuming N < |V|...
= |V|! / (|V| - N)! = O(|V|^N)
So if the running time is measured in terms of n = |V| with k = number of summands,
this is O(n^k) - which is polynomial time in n with degree k- the number of summands.
****/
//----- MODIFY EVERYTHING BELOW HERE:
/**
* Input:
* nums - T array of summable
* target - sum to search for
*
* Output:
* Indices of first two DISTINCT elements of nums which add up to target
* IF THIS EXISTS
* pair(0,0) - if these don't exist
*/
using namespace std;
typedef pair<unsigned int, unsigned int> indexPair;
void stdSetTest ();
void stdMultisetTest ();
void setOfMultisetTest ();
void testCase0();
//template<typename T>
//indexPair TwoSum(const vector<T>& nums, const T& target) {
// size_t L = nums.size();
// for(unsigned i=0; i<L-1; i++){
// T currTarget = target - nums[i];
// for(unsigned j=i+1; j<L; j++){
// if(nums[j] == currTarget)
// return indexPair(i, j);
// }
// }
// return indexPair(0,0);
//}
//
//template <typename T>
//indexPair runExample(const vector<T> &nums, T target) {
// cout << "Given: nums = ";
// Printer<T>::prettyPrint(nums);
// cout << "\t\t target = " << target << endl;
//
// auto solution = TwoSum(nums, target);
// cout << "Solution = ";
// Printer<T>::prettyPrint(solution);
// cout << endl;
// return solution;
//}
//template<typename T>
//indexPair TwoSum(const vector<T>& nums, const T& target) {
template<typename T>
set<multiset<T>> NSum(vector<T> V, const size_t& N, const T& target){
if (N == 0)
return target == 0 ? set<multiset<T>>{{}} : set<multiset<T>>{};
throw "NOT YET IMPLEMENTED";
}
int main()
{
stdSetTest();
stdMultisetTest();
setOfMultisetTest();
testCase0();
// vector<int> nums = {2, 7, 11, 15};
// int target = 9;
//
// indexPair solution = runExample(nums, target);
// assert(solution.first == 0);
// assert(solution.second == 1);
//
// nums = {1,2,3,4,5,6,7,8,9,10};
// target = 11;
// solution = runExample(nums, target);
// assert(solution.first == 0);
// assert(solution.second == 9);
//
// target = 14;
// solution = runExample(nums, target);
// assert(solution.first == 3);
// assert(solution.second == 9);
//
// target = -5;
// solution = runExample(nums, target);
// assert(solution.first == 0);
// assert(solution.second == 0);
return 0;
}
void stdMultisetTest () {
cout << "stdMultisetTest ():" << endl;
multiset<int> t1{1, 2, 3}, t2{1, 2, 2}, t3{1, 2, 3};
cout << "t1.size() = " << t1.size() << endl;
cout << "t2.size() = " << t2.size() << endl;
cout << "t1 = " << endl << t1 << endl;
cout << endl;
cout << "t2 = " << endl << t2 << endl;
cout << "t1 <= t1 = " << boolalpha << (t1 <= t1) << endl;
cout << "t1 < t2 = " << boolalpha << (t1 < t2) << endl;
cout << "t2 < t1 = " << boolalpha << (t2 < t1) << endl;
cout << "t1 == t3 = " << boolalpha << (t1 == t3) << endl;
multiset<int> empty{};
cout << "empty.size() = " << empty.size() << endl;
cout << "empty = " << endl << empty << endl;
}
void stdSetTest () {
cout << "stdSetTest ():" << endl;
set<int> S{1, 4, 3, 1, 2, -7};
cout << "S.size() = " << S.size() << endl;
cout << "S = " << endl << S << endl;
}
void setOfMultisetTest () {
cout << "setOfMultisetTest ():" << endl;
set<multiset<int>> empty{{}};
cout << "empty.size() = " << empty.size() << endl;
cout << "empty = " << endl << empty << endl;
}
void testCase0(){
cout << "testCase0():" << endl;
vector<int> V{-1, 3, 4, 5, -5};
int targetSolution = 0, targetNoSolution = 4;
unsigned N = 0;
cout << "For V = " << endl << V << endl;
cout << " and target = " << targetSolution << endl;
cout << "the set of all " << N << "-tuples that sum to target is:" << endl;
cout << NSum(V, N, targetSolution) << endl;
cout << "For V = " << endl << V << endl;
cout << " and target = " << targetNoSolution << endl;
cout << "the set of all " << N << "-tuples that sum to target is:" << endl;
cout << NSum(V, N, targetNoSolution) << endl;
}
|
//
// Created by zeph on 11/18/16.
//
#include <iostream>
#include <cassert>
#include <vector>
#include <set>
#include <exception>
#include "../helpers/coutFriends.cpp"
/***
From: https://leetcode.com/problems/3sum/
Given an array V of n integers, are there elements a, b, c in V such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example:
```
Given array V = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
```
At this point, it is probably no easier to solve N-sum than solving 3-sum specificially.
P(V, N, s):
Given array V, number of summands N, and a target sum s:
Find all distinct N-tuples of V which add up to s.
Pseudocode:
Base case: P(V, 0, s)
If s = 0: return () the 0-tuple
Else: return no-solution
N-1 => N:
Let T = {}
For each i in V:
T = T U {i} X P(V-{i}, N-1, s-i) // Note that when P(V-{i}, N-1, s-i) is empty, we just skip all processing
Run time analysis:
VTEP N-1 => N:
T(|V|, N) = |V| * T(|V|-1, N-1)
= |V| * |V-1| * T(|V| - 2, N-2)
.... assuming N < |V|...
= |V|! / (|V| - N)! = O(|V|^N)
So if the running time is measured in terms of n = |V| with k = number of summands,
this is O(n^k) - which is polynomial time in n with degree k- the number of summands.
****/
//----- MODIFY EVERYTHING BELOW HERE:
/**
* Input:
* nums - T array of summable
* target - sum to search for
*
* Output:
* Indices of first two DISTINCT elements of nums which add up to target
* IF THIS EXISTS
* pair(0,0) - if these don't exist
*/
using namespace std;
typedef pair<unsigned int, unsigned int> indexPair;
void stdSetTest ();
void stdMultisetTest ();
void setOfMultisetTest ();
void testCase0();
//template<typename T>
//indexPair TwoSum(const vector<T>& nums, const T& target) {
// size_t L = nums.size();
// for(unsigned i=0; i<L-1; i++){
// T currTarget = target - nums[i];
// for(unsigned j=i+1; j<L; j++){
// if(nums[j] == currTarget)
// return indexPair(i, j);
// }
// }
// return indexPair(0,0);
//}
//
//template <typename T>
//indexPair runExample(const vector<T> &nums, T target) {
// cout << "Given: nums = ";
// Printer<T>::prettyPrint(nums);
// cout << "\t\t target = " << target << endl;
//
// auto solution = TwoSum(nums, target);
// cout << "Solution = ";
// Printer<T>::prettyPrint(solution);
// cout << endl;
// return solution;
//}
//template<typename T>
//indexPair TwoSum(const vector<T>& nums, const T& target) {
template<typename T>
set<multiset<T>> NSum(vector<T> V, const size_t& N, const T& target){
if (N == 0)
return target == 0 ? set<multiset<T>>{{}} : set<multiset<T>>{};
throw runtime_error("NOT YET IMPLEMENTED");
}
int main()
{
stdSetTest();
stdMultisetTest();
setOfMultisetTest();
testCase0();
// vector<int> nums = {2, 7, 11, 15};
// int target = 9;
//
// indexPair solution = runExample(nums, target);
// assert(solution.first == 0);
// assert(solution.second == 1);
//
// nums = {1,2,3,4,5,6,7,8,9,10};
// target = 11;
// solution = runExample(nums, target);
// assert(solution.first == 0);
// assert(solution.second == 9);
//
// target = 14;
// solution = runExample(nums, target);
// assert(solution.first == 3);
// assert(solution.second == 9);
//
// target = -5;
// solution = runExample(nums, target);
// assert(solution.first == 0);
// assert(solution.second == 0);
return 0;
}
void stdMultisetTest () {
cout << "stdMultisetTest ():" << endl;
multiset<int> t1{1, 2, 3}, t2{1, 2, 2}, t3{1, 2, 3};
cout << "t1.size() = " << t1.size() << endl;
cout << "t2.size() = " << t2.size() << endl;
cout << "t1 = " << endl << t1 << endl;
cout << endl;
cout << "t2 = " << endl << t2 << endl;
cout << "t1 <= t1 = " << boolalpha << (t1 <= t1) << endl;
cout << "t1 < t2 = " << boolalpha << (t1 < t2) << endl;
cout << "t2 < t1 = " << boolalpha << (t2 < t1) << endl;
cout << "t1 == t3 = " << boolalpha << (t1 == t3) << endl;
multiset<int> empty{};
cout << "empty.size() = " << empty.size() << endl;
cout << "empty = " << endl << empty << endl;
}
void stdSetTest () {
cout << "stdSetTest ():" << endl;
set<int> S{1, 4, 3, 1, 2, -7};
cout << "S.size() = " << S.size() << endl;
cout << "S = " << endl << S << endl;
}
void setOfMultisetTest () {
cout << "setOfMultisetTest ():" << endl;
set<multiset<int>> empty{{}};
cout << "empty.size() = " << empty.size() << endl;
cout << "empty = " << endl << empty << endl;
}
void testCase0(){
cout << "testCase0():" << endl;
vector<int> V{-1, 3, 4, 5, -5};
int targetSolution = 0, targetNoSolution = 4;
unsigned N = 0;
cout << "For V = " << endl << V << endl;
cout << " and target = " << targetSolution << endl;
cout << "the set of all " << N << "-tuples that sum to target is:" << endl;
cout << NSum(V, N, targetSolution) << endl;
V = vector<int>{2, 7, 11, 15};
N = 2;
int target = 9;
cout << "For V = " << endl << V << endl;
cout << " and target = " << target << endl;
cout << "the set of all " << N << "-tuples that sum to target is:" << endl;
cout << NSum(V, N, targetNoSolution) << endl;
}
|
use runtime_error instead of throwing a string
|
use runtime_error instead of throwing a string
|
C++
|
mit
|
tzaffi/cpp,tzaffi/cpp,tzaffi/cpp
|
b835edbf90823a92ac56cd8f23e93605813f6d8f
|
rmw_connext_cpp/src/rmw_publish.cpp
|
rmw_connext_cpp/src/rmw_publish.cpp
|
// Copyright 2014-2017 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <limits>
#include "rmw/error_handling.h"
#include "rmw/rmw.h"
#include "rmw/types.h"
#include "rmw/impl/cpp/macros.hpp"
#include "rmw_connext_cpp/identifier.hpp"
#include "connext_static_publisher_info.hpp"
// include patched generated code from the build folder
#include "connext_static_serialized_dataSupport.h"
bool
publish(DDS::DataWriter * dds_data_writer, const rcutils_uint8_array_t * cdr_stream)
{
ConnextStaticSerializedDataDataWriter * data_writer =
ConnextStaticSerializedDataDataWriter::narrow(dds_data_writer);
if (!data_writer) {
RMW_SET_ERROR_MSG("failed to narrow data writer");
return false;
}
ConnextStaticSerializedData * instance = ConnextStaticSerializedDataTypeSupport::create_data();
if (!instance) {
RMW_SET_ERROR_MSG("failed to create dds message instance");
return false;
}
DDS::ReturnCode_t status = DDS::RETCODE_ERROR;
instance->serialized_data.maximum(0);
if (cdr_stream->buffer_length > static_cast<size_t>((std::numeric_limits<DDS_Long>::max)())) {
RMW_SET_ERROR_MSG("cdr_stream->buffer_length unexpectedly larger than DDS_Long's max value");
return false;
}
if (!instance->serialized_data.loan_contiguous(
reinterpret_cast<DDS::Octet *>(cdr_stream->buffer),
static_cast<DDS::Long>(cdr_stream->buffer_length),
static_cast<DDS::Long>(cdr_stream->buffer_length)))
{
RMW_SET_ERROR_MSG("failed to loan memory for message");
goto cleanup;
}
status = data_writer->write(*instance, DDS::HANDLE_NIL);
cleanup:
if (instance) {
if (!instance->serialized_data.unloan()) {
fprintf(stderr, "failed to return loaned memory\n");
status = DDS::RETCODE_ERROR;
}
ConnextStaticSerializedDataTypeSupport::delete_data(instance);
}
return status == DDS::RETCODE_OK;
}
extern "C"
{
rmw_ret_t
rmw_publish(
const rmw_publisher_t * publisher,
const void * ros_message,
rmw_publisher_allocation_t * allocation)
{
(void) allocation;
if (!publisher) {
RMW_SET_ERROR_MSG("publisher handle is null");
return RMW_RET_ERROR;
}
if (publisher->implementation_identifier != rti_connext_identifier) {
RMW_SET_ERROR_MSG("publisher handle is not from this rmw implementation");
return RMW_RET_ERROR;
}
if (!ros_message) {
RMW_SET_ERROR_MSG("ros message handle is null");
return RMW_RET_ERROR;
}
ConnextStaticPublisherInfo * publisher_info =
static_cast<ConnextStaticPublisherInfo *>(publisher->data);
if (!publisher_info) {
RMW_SET_ERROR_MSG("publisher info handle is null");
return RMW_RET_ERROR;
}
const message_type_support_callbacks_t * callbacks = publisher_info->callbacks_;
if (!callbacks) {
RMW_SET_ERROR_MSG("callbacks handle is null");
return RMW_RET_ERROR;
}
DDS::DataWriter * topic_writer = publisher_info->topic_writer_;
if (!topic_writer) {
RMW_SET_ERROR_MSG("topic writer handle is null");
return RMW_RET_ERROR;
}
auto ret = RMW_RET_OK;
rcutils_uint8_array_t cdr_stream = rcutils_get_zero_initialized_uint8_array();
cdr_stream.allocator = rcutils_get_default_allocator();
if (!callbacks->to_cdr_stream(ros_message, &cdr_stream)) {
RMW_SET_ERROR_MSG("failed to convert ros_message to cdr stream");
ret = RMW_RET_ERROR;
goto fail;
}
if (cdr_stream.buffer_length == 0) {
RMW_SET_ERROR_MSG("no message length set");
ret = RMW_RET_ERROR;
goto fail;
}
if (!cdr_stream.buffer) {
RMW_SET_ERROR_MSG("no serialized message attached");
ret = RMW_RET_ERROR;
goto fail;
}
if (!publish(topic_writer, &cdr_stream)) {
RMW_SET_ERROR_MSG("failed to publish message");
ret = RMW_RET_ERROR;
goto fail;
}
fail:
cdr_stream.allocator.deallocate(cdr_stream.buffer, cdr_stream.allocator.state);
return ret;
}
rmw_ret_t
rmw_publish_serialized_message(
const rmw_publisher_t * publisher,
const rmw_serialized_message_t * serialized_message,
rmw_publisher_allocation_t * allocation)
{
(void) allocation;
RMW_CHECK_FOR_NULL_WITH_MSG(
publisher, "publisher handle is null",
return RMW_RET_INVALID_ARGUMENT);
RMW_CHECK_TYPE_IDENTIFIERS_MATCH(
publisher, publisher->implementation_identifier, rti_connext_identifier,
return RMW_RET_INCORRECT_RMW_IMPLEMENTATION);
RMW_CHECK_FOR_NULL_WITH_MSG(
serialized_message, "serialized message handle is null",
return RMW_RET_INVALID_ARGUMENT);
ConnextStaticPublisherInfo * publisher_info =
static_cast<ConnextStaticPublisherInfo *>(publisher->data);
if (!publisher_info) {
RMW_SET_ERROR_MSG("publisher info handle is null");
return RMW_RET_ERROR;
}
const message_type_support_callbacks_t * callbacks = publisher_info->callbacks_;
if (!callbacks) {
RMW_SET_ERROR_MSG("callbacks handle is null");
return RMW_RET_ERROR;
}
DDS::DataWriter * topic_writer = publisher_info->topic_writer_;
if (!topic_writer) {
RMW_SET_ERROR_MSG("topic writer handle is null");
return RMW_RET_ERROR;
}
bool published = publish(topic_writer, serialized_message);
if (!published) {
RMW_SET_ERROR_MSG("failed to publish message");
return RMW_RET_ERROR;
}
return RMW_RET_OK;
}
rmw_ret_t
rmw_publish_loaned_message(
const rmw_publisher_t * publisher,
void * ros_message,
rmw_publisher_allocation_t * allocation)
{
(void) publisher;
(void) ros_message;
(void) allocation;
RMW_SET_ERROR_MSG("rmw_publish_loaned_message not implemented for rmw_connext_cpp");
return RMW_RET_UNSUPPORTED;
}
} // extern "C"
|
// Copyright 2014-2017 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <limits>
#include "rmw/error_handling.h"
#include "rmw/rmw.h"
#include "rmw/types.h"
#include "rmw/impl/cpp/macros.hpp"
#include "rmw_connext_cpp/identifier.hpp"
#include "connext_static_publisher_info.hpp"
// include patched generated code from the build folder
#include "connext_static_serialized_dataSupport.h"
bool
publish(DDS::DataWriter * dds_data_writer, const rcutils_uint8_array_t * cdr_stream)
{
ConnextStaticSerializedDataDataWriter * data_writer =
ConnextStaticSerializedDataDataWriter::narrow(dds_data_writer);
if (!data_writer) {
RMW_SET_ERROR_MSG("failed to narrow data writer");
return false;
}
ConnextStaticSerializedData * instance = ConnextStaticSerializedDataTypeSupport::create_data();
if (!instance) {
RMW_SET_ERROR_MSG("failed to create dds message instance");
return false;
}
DDS::ReturnCode_t status = DDS::RETCODE_ERROR;
instance->serialized_data.maximum(0);
if (cdr_stream->buffer_length > static_cast<size_t>((std::numeric_limits<DDS_Long>::max)())) {
RMW_SET_ERROR_MSG("cdr_stream->buffer_length unexpectedly larger than DDS_Long's max value");
return false;
}
if (!instance->serialized_data.loan_contiguous(
reinterpret_cast<DDS::Octet *>(cdr_stream->buffer),
static_cast<DDS::Long>(cdr_stream->buffer_length),
static_cast<DDS::Long>(cdr_stream->buffer_length)))
{
RMW_SET_ERROR_MSG("failed to loan memory for message");
goto cleanup;
}
status = data_writer->write(*instance, DDS::HANDLE_NIL);
cleanup:
if (instance) {
if (!instance->serialized_data.unloan()) {
fprintf(stderr, "failed to return loaned memory\n");
status = DDS::RETCODE_ERROR;
}
ConnextStaticSerializedDataTypeSupport::delete_data(instance);
}
return status == DDS::RETCODE_OK;
}
extern "C"
{
rmw_ret_t
rmw_publish(
const rmw_publisher_t * publisher,
const void * ros_message,
rmw_publisher_allocation_t * allocation)
{
(void) allocation;
RMW_CHECK_FOR_NULL_WITH_MSG(
publisher, "publisher handle is null",
return RMW_RET_INVALID_ARGUMENT);
RMW_CHECK_TYPE_IDENTIFIERS_MATCH(
publisher, publisher->implementation_identifier, rti_connext_identifier,
return RMW_RET_INCORRECT_RMW_IMPLEMENTATION);
RMW_CHECK_FOR_NULL_WITH_MSG(
ros_message, "ros message handle is null",
return RMW_RET_INVALID_ARGUMENT);
ConnextStaticPublisherInfo * publisher_info =
static_cast<ConnextStaticPublisherInfo *>(publisher->data);
if (!publisher_info) {
RMW_SET_ERROR_MSG("publisher info handle is null");
return RMW_RET_ERROR;
}
const message_type_support_callbacks_t * callbacks = publisher_info->callbacks_;
if (!callbacks) {
RMW_SET_ERROR_MSG("callbacks handle is null");
return RMW_RET_ERROR;
}
DDS::DataWriter * topic_writer = publisher_info->topic_writer_;
if (!topic_writer) {
RMW_SET_ERROR_MSG("topic writer handle is null");
return RMW_RET_ERROR;
}
auto ret = RMW_RET_OK;
rcutils_uint8_array_t cdr_stream = rcutils_get_zero_initialized_uint8_array();
cdr_stream.allocator = rcutils_get_default_allocator();
if (!callbacks->to_cdr_stream(ros_message, &cdr_stream)) {
RMW_SET_ERROR_MSG("failed to convert ros_message to cdr stream");
ret = RMW_RET_ERROR;
goto fail;
}
if (cdr_stream.buffer_length == 0) {
RMW_SET_ERROR_MSG("no message length set");
ret = RMW_RET_ERROR;
goto fail;
}
if (!cdr_stream.buffer) {
RMW_SET_ERROR_MSG("no serialized message attached");
ret = RMW_RET_ERROR;
goto fail;
}
if (!publish(topic_writer, &cdr_stream)) {
RMW_SET_ERROR_MSG("failed to publish message");
ret = RMW_RET_ERROR;
goto fail;
}
fail:
cdr_stream.allocator.deallocate(cdr_stream.buffer, cdr_stream.allocator.state);
return ret;
}
rmw_ret_t
rmw_publish_serialized_message(
const rmw_publisher_t * publisher,
const rmw_serialized_message_t * serialized_message,
rmw_publisher_allocation_t * allocation)
{
(void) allocation;
RMW_CHECK_FOR_NULL_WITH_MSG(
publisher, "publisher handle is null",
return RMW_RET_INVALID_ARGUMENT);
RMW_CHECK_TYPE_IDENTIFIERS_MATCH(
publisher, publisher->implementation_identifier, rti_connext_identifier,
return RMW_RET_INCORRECT_RMW_IMPLEMENTATION);
RMW_CHECK_FOR_NULL_WITH_MSG(
serialized_message, "serialized message handle is null",
return RMW_RET_INVALID_ARGUMENT);
ConnextStaticPublisherInfo * publisher_info =
static_cast<ConnextStaticPublisherInfo *>(publisher->data);
if (!publisher_info) {
RMW_SET_ERROR_MSG("publisher info handle is null");
return RMW_RET_ERROR;
}
const message_type_support_callbacks_t * callbacks = publisher_info->callbacks_;
if (!callbacks) {
RMW_SET_ERROR_MSG("callbacks handle is null");
return RMW_RET_ERROR;
}
DDS::DataWriter * topic_writer = publisher_info->topic_writer_;
if (!topic_writer) {
RMW_SET_ERROR_MSG("topic writer handle is null");
return RMW_RET_ERROR;
}
bool published = publish(topic_writer, serialized_message);
if (!published) {
RMW_SET_ERROR_MSG("failed to publish message");
return RMW_RET_ERROR;
}
return RMW_RET_OK;
}
rmw_ret_t
rmw_publish_loaned_message(
const rmw_publisher_t * publisher,
void * ros_message,
rmw_publisher_allocation_t * allocation)
{
(void) publisher;
(void) ros_message;
(void) allocation;
RMW_SET_ERROR_MSG("rmw_publish_loaned_message not implemented for rmw_connext_cpp");
return RMW_RET_UNSUPPORTED;
}
} // extern "C"
|
Update rmw_publish() error returns (#452)
|
Update rmw_publish() error returns (#452)
Signed-off-by: lobotuerk <[email protected]>
|
C++
|
apache-2.0
|
ros2/rmw_connext,ros2/rmw_connext,ros2/rmw_connext
|
9b25c16980c659e8ea5a99c9416287388c6f86cd
|
atom/browser/ui/message_box_gtk.cc
|
atom/browser/ui/message_box_gtk.cc
|
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/ui/message_box.h"
#include "atom/browser/browser.h"
#include "atom/browser/native_window.h"
#include "base/callback.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/ui/libgtk2ui/gtk2_signal.h"
#include "chrome/browser/ui/libgtk2ui/gtk2_util.h"
#include "chrome/browser/ui/libgtk2ui/skia_utils_gtk2.h"
#include "ui/views/widget/desktop_aura/x11_desktop_handler.h"
#define ANSI_FOREGROUND_RED "\x1b[31m"
#define ANSI_FOREGROUND_BLACK "\x1b[30m"
#define ANSI_TEXT_BOLD "\x1b[1m"
#define ANSI_BACKGROUND_GRAY "\x1b[47m"
#define ANSI_RESET "\x1b[0m"
namespace atom {
namespace {
class GtkMessageBox {
public:
GtkMessageBox(NativeWindow* parent_window,
MessageBoxType type,
const std::vector<std::string>& buttons,
const std::string& title,
const std::string& message,
const std::string& detail,
const gfx::ImageSkia& icon)
: dialog_scope_(parent_window),
cancel_id_(0) {
// Create dialog.
dialog_ = gtk_message_dialog_new(
nullptr, // parent
static_cast<GtkDialogFlags>(0), // no flags
GetMessageType(type), // type
GTK_BUTTONS_NONE, // no buttons
"%s", message.c_str());
gtk_message_dialog_format_secondary_text(
GTK_MESSAGE_DIALOG(dialog_),
"%s", detail.empty() ? nullptr : detail.c_str());
// Set dialog's icon.
if (!icon.isNull()) {
GdkPixbuf* pixbuf = libgtk2ui::GdkPixbufFromSkBitmap(*icon.bitmap());
GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
gtk_message_dialog_set_image(GTK_MESSAGE_DIALOG(dialog_), image);
gtk_widget_show(image);
g_object_unref(pixbuf);
}
// Add buttons.
for (size_t i = 0; i < buttons.size(); ++i) {
gtk_dialog_add_button(GTK_DIALOG(dialog_),
TranslateToStock(i, buttons[i]),
i);
}
// Parent window.
if (parent_window) {
gfx::NativeWindow window = parent_window->GetNativeWindow();
libgtk2ui::SetGtkTransientForAura(dialog_, window);
}
}
~GtkMessageBox() {
gtk_widget_destroy(dialog_);
}
GtkMessageType GetMessageType(MessageBoxType type) {
switch (type) {
case MESSAGE_BOX_TYPE_INFORMATION:
return GTK_MESSAGE_INFO;
case MESSAGE_BOX_TYPE_WARNING:
return GTK_MESSAGE_WARNING;
case MESSAGE_BOX_TYPE_QUESTION:
return GTK_MESSAGE_QUESTION;
case MESSAGE_BOX_TYPE_ERROR:
return GTK_MESSAGE_ERROR;
default:
return GTK_MESSAGE_OTHER;
}
}
const char* TranslateToStock(int id, const std::string& text) {
std::string lower = base::StringToLowerASCII(text);
if (lower == "cancel") {
cancel_id_ = id;
return GTK_STOCK_CANCEL;
} else if (lower == "no") {
cancel_id_ = id;
return GTK_STOCK_NO;
} else if (lower == "ok") {
return GTK_STOCK_OK;
} else if (lower == "yes") {
return GTK_STOCK_YES;
} else {
return text.c_str();
}
}
void Show() {
gtk_widget_show_all(dialog_);
// We need to call gtk_window_present after making the widgets visible to
// make sure window gets correctly raised and gets focus.
int time = views::X11DesktopHandler::get()->wm_user_time_ms();
gtk_window_present_with_time(GTK_WINDOW(dialog_), time);
}
int RunSynchronous() {
gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE);
Show();
int response = gtk_dialog_run(GTK_DIALOG(dialog_));
if (response < 0)
return cancel_id_;
else
return response;
}
void RunAsynchronous(const MessageBoxCallback& callback) {
callback_ = callback;
g_signal_connect(dialog_, "delete-event",
G_CALLBACK(gtk_widget_hide_on_delete), nullptr);
g_signal_connect(dialog_, "response",
G_CALLBACK(OnResponseDialogThunk), this);
Show();
}
CHROMEGTK_CALLBACK_1(GtkMessageBox, void, OnResponseDialog, int);
private:
atom::NativeWindow::DialogScope dialog_scope_;
// The id to return when the dialog is closed without pressing buttons.
int cancel_id_;
GtkWidget* dialog_;
MessageBoxCallback callback_;
DISALLOW_COPY_AND_ASSIGN(GtkMessageBox);
};
void GtkMessageBox::OnResponseDialog(GtkWidget* widget, int response) {
gtk_widget_hide_all(dialog_);
if (response < 0)
callback_.Run(cancel_id_);
else
callback_.Run(response);
delete this;
}
} // namespace
int ShowMessageBox(NativeWindow* parent,
MessageBoxType type,
const std::vector<std::string>& buttons,
const std::string& title,
const std::string& message,
const std::string& detail,
const gfx::ImageSkia& icon) {
return GtkMessageBox(parent, type, buttons, title, message, detail,
icon).RunSynchronous();
}
void ShowMessageBox(NativeWindow* parent,
MessageBoxType type,
const std::vector<std::string>& buttons,
const std::string& title,
const std::string& message,
const std::string& detail,
const gfx::ImageSkia& icon,
const MessageBoxCallback& callback) {
(new GtkMessageBox(parent, type, buttons, title, message, detail,
icon))->RunAsynchronous(callback);
}
void ShowErrorBox(const base::string16& title, const base::string16& content) {
if (Browser::Get()->is_ready()) {
GtkMessageBox(nullptr, MESSAGE_BOX_TYPE_ERROR, { "OK" }, "Error",
base::UTF16ToUTF8(title).c_str(),
base::UTF16ToUTF8(content).c_str(),
gfx::ImageSkia()).RunSynchronous();
} else {
fprintf(stderr,
ANSI_TEXT_BOLD ANSI_BACKGROUND_GRAY
ANSI_FOREGROUND_RED "%s\n"
ANSI_FOREGROUND_BLACK "%s"
ANSI_RESET "\n",
base::UTF16ToUTF8(title).c_str(),
base::UTF16ToUTF8(content).c_str());
}
}
} // namespace atom
|
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/ui/message_box.h"
#include "atom/browser/browser.h"
#include "atom/browser/native_window.h"
#include "base/callback.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/ui/libgtk2ui/gtk2_signal.h"
#include "chrome/browser/ui/libgtk2ui/gtk2_util.h"
#include "chrome/browser/ui/libgtk2ui/skia_utils_gtk2.h"
#include "ui/views/widget/desktop_aura/x11_desktop_handler.h"
#define ANSI_FOREGROUND_RED "\x1b[31m"
#define ANSI_FOREGROUND_BLACK "\x1b[30m"
#define ANSI_TEXT_BOLD "\x1b[1m"
#define ANSI_BACKGROUND_GRAY "\x1b[47m"
#define ANSI_RESET "\x1b[0m"
namespace atom {
namespace {
class GtkMessageBox {
public:
GtkMessageBox(NativeWindow* parent_window,
MessageBoxType type,
const std::vector<std::string>& buttons,
const std::string& title,
const std::string& message,
const std::string& detail,
const gfx::ImageSkia& icon)
: dialog_scope_(parent_window),
cancel_id_(0) {
// Create dialog.
dialog_ = gtk_message_dialog_new(
nullptr, // parent
static_cast<GtkDialogFlags>(0), // no flags
GetMessageType(type), // type
GTK_BUTTONS_NONE, // no buttons
"%s", message.c_str());
if (!detail.empty())
gtk_message_dialog_format_secondary_text(
GTK_MESSAGE_DIALOG(dialog_), "%s", detail.c_str());
// Set dialog's icon.
if (!icon.isNull()) {
GdkPixbuf* pixbuf = libgtk2ui::GdkPixbufFromSkBitmap(*icon.bitmap());
GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
gtk_message_dialog_set_image(GTK_MESSAGE_DIALOG(dialog_), image);
gtk_widget_show(image);
g_object_unref(pixbuf);
}
// Add buttons.
for (size_t i = 0; i < buttons.size(); ++i) {
gtk_dialog_add_button(GTK_DIALOG(dialog_),
TranslateToStock(i, buttons[i]),
i);
}
// Parent window.
if (parent_window) {
gfx::NativeWindow window = parent_window->GetNativeWindow();
libgtk2ui::SetGtkTransientForAura(dialog_, window);
}
}
~GtkMessageBox() {
gtk_widget_destroy(dialog_);
}
GtkMessageType GetMessageType(MessageBoxType type) {
switch (type) {
case MESSAGE_BOX_TYPE_INFORMATION:
return GTK_MESSAGE_INFO;
case MESSAGE_BOX_TYPE_WARNING:
return GTK_MESSAGE_WARNING;
case MESSAGE_BOX_TYPE_QUESTION:
return GTK_MESSAGE_QUESTION;
case MESSAGE_BOX_TYPE_ERROR:
return GTK_MESSAGE_ERROR;
default:
return GTK_MESSAGE_OTHER;
}
}
const char* TranslateToStock(int id, const std::string& text) {
std::string lower = base::StringToLowerASCII(text);
if (lower == "cancel") {
cancel_id_ = id;
return GTK_STOCK_CANCEL;
} else if (lower == "no") {
cancel_id_ = id;
return GTK_STOCK_NO;
} else if (lower == "ok") {
return GTK_STOCK_OK;
} else if (lower == "yes") {
return GTK_STOCK_YES;
} else {
return text.c_str();
}
}
void Show() {
gtk_widget_show_all(dialog_);
// We need to call gtk_window_present after making the widgets visible to
// make sure window gets correctly raised and gets focus.
int time = views::X11DesktopHandler::get()->wm_user_time_ms();
gtk_window_present_with_time(GTK_WINDOW(dialog_), time);
}
int RunSynchronous() {
gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE);
Show();
int response = gtk_dialog_run(GTK_DIALOG(dialog_));
if (response < 0)
return cancel_id_;
else
return response;
}
void RunAsynchronous(const MessageBoxCallback& callback) {
callback_ = callback;
g_signal_connect(dialog_, "delete-event",
G_CALLBACK(gtk_widget_hide_on_delete), nullptr);
g_signal_connect(dialog_, "response",
G_CALLBACK(OnResponseDialogThunk), this);
Show();
}
CHROMEGTK_CALLBACK_1(GtkMessageBox, void, OnResponseDialog, int);
private:
atom::NativeWindow::DialogScope dialog_scope_;
// The id to return when the dialog is closed without pressing buttons.
int cancel_id_;
GtkWidget* dialog_;
MessageBoxCallback callback_;
DISALLOW_COPY_AND_ASSIGN(GtkMessageBox);
};
void GtkMessageBox::OnResponseDialog(GtkWidget* widget, int response) {
gtk_widget_hide_all(dialog_);
if (response < 0)
callback_.Run(cancel_id_);
else
callback_.Run(response);
delete this;
}
} // namespace
int ShowMessageBox(NativeWindow* parent,
MessageBoxType type,
const std::vector<std::string>& buttons,
const std::string& title,
const std::string& message,
const std::string& detail,
const gfx::ImageSkia& icon) {
return GtkMessageBox(parent, type, buttons, title, message, detail,
icon).RunSynchronous();
}
void ShowMessageBox(NativeWindow* parent,
MessageBoxType type,
const std::vector<std::string>& buttons,
const std::string& title,
const std::string& message,
const std::string& detail,
const gfx::ImageSkia& icon,
const MessageBoxCallback& callback) {
(new GtkMessageBox(parent, type, buttons, title, message, detail,
icon))->RunAsynchronous(callback);
}
void ShowErrorBox(const base::string16& title, const base::string16& content) {
if (Browser::Get()->is_ready()) {
GtkMessageBox(nullptr, MESSAGE_BOX_TYPE_ERROR, { "OK" }, "Error",
base::UTF16ToUTF8(title).c_str(),
base::UTF16ToUTF8(content).c_str(),
gfx::ImageSkia()).RunSynchronous();
} else {
fprintf(stderr,
ANSI_TEXT_BOLD ANSI_BACKGROUND_GRAY
ANSI_FOREGROUND_RED "%s\n"
ANSI_FOREGROUND_BLACK "%s"
ANSI_RESET "\n",
base::UTF16ToUTF8(title).c_str(),
base::UTF16ToUTF8(content).c_str());
}
}
} // namespace atom
|
Allow "detail" to be empty
|
Allow "detail" to be empty
|
C++
|
mit
|
thingsinjars/electron,jaanus/electron,carsonmcdonald/electron,bruce/electron,pandoraui/electron,shockone/electron,mhkeller/electron,RIAEvangelist/electron,takashi/electron,mjaniszew/electron,destan/electron,nicholasess/electron,mhkeller/electron,ervinb/electron,brave/electron,rajatsingla28/electron,bpasero/electron,thingsinjars/electron,takashi/electron,mattotodd/electron,shockone/electron,stevemao/electron,ervinb/electron,abhishekgahlot/electron,oiledCode/electron,bruce/electron,thompsonemerson/electron,noikiy/electron,farmisen/electron,kenmozi/electron,mrwizard82d1/electron,kenmozi/electron,carsonmcdonald/electron,jcblw/electron,greyhwndz/electron,miniak/electron,matiasinsaurralde/electron,gabrielPeart/electron,jtburke/electron,cqqccqc/electron,bright-sparks/electron,aaron-goshine/electron,stevemao/electron,mhkeller/electron,rajatsingla28/electron,egoist/electron,miniak/electron,gbn972/electron,kenmozi/electron,jcblw/electron,lzpfmh/electron,destan/electron,BionicClick/electron,kazupon/electron,ervinb/electron,LadyNaggaga/electron,Floato/electron,brave/muon,mrwizard82d1/electron,michaelchiche/electron,posix4e/electron,joneit/electron,trigrass2/electron,bpasero/electron,wan-qy/electron,twolfson/electron,baiwyc119/electron,mirrh/electron,soulteary/electron,jjz/electron,eriser/electron,anko/electron,mattotodd/electron,takashi/electron,thomsonreuters/electron,roadev/electron,jsutcodes/electron,simonfork/electron,preco21/electron,Evercoder/electron,shaundunne/electron,tincan24/electron,lrlna/electron,simonfork/electron,tonyganch/electron,fffej/electron,subblue/electron,JussMee15/electron,MaxWhere/electron,Gerhut/electron,bbondy/electron,the-ress/electron,voidbridge/electron,simongregory/electron,leftstick/electron,eric-seekas/electron,eric-seekas/electron,cqqccqc/electron,oiledCode/electron,biblerule/UMCTelnetHub,brave/muon,edulan/electron,howmuchcomputer/electron,saronwei/electron,SufianHassan/electron,tincan24/electron,DivyaKMenon/electron,thomsonreuters/electron,jjz/electron,chriskdon/electron,preco21/electron,webmechanicx/electron,christian-bromann/electron,matiasinsaurralde/electron,etiktin/electron,jsutcodes/electron,trigrass2/electron,Evercoder/electron,roadev/electron,dkfiresky/electron,adamjgray/electron,vipulroxx/electron,electron/electron,bobwol/electron,lzpfmh/electron,xiruibing/electron,tinydew4/electron,zhakui/electron,jsutcodes/electron,vipulroxx/electron,Floato/electron,shiftkey/electron,aaron-goshine/electron,fritx/electron,bbondy/electron,Jonekee/electron,christian-bromann/electron,pirafrank/electron,Evercoder/electron,tonyganch/electron,micalan/electron,arturts/electron,aichingm/electron,jannishuebl/electron,anko/electron,jonatasfreitasv/electron,LadyNaggaga/electron,leftstick/electron,JesselJohn/electron,pirafrank/electron,pombredanne/electron,baiwyc119/electron,etiktin/electron,icattlecoder/electron,xiruibing/electron,JussMee15/electron,pandoraui/electron,abhishekgahlot/electron,Andrey-Pavlov/electron,lzpfmh/electron,roadev/electron,trigrass2/electron,DivyaKMenon/electron,brenca/electron,mjaniszew/electron,leolujuyi/electron,rhencke/electron,jjz/electron,ervinb/electron,JussMee15/electron,saronwei/electron,jhen0409/electron,coderhaoxin/electron,thingsinjars/electron,jsutcodes/electron,vipulroxx/electron,aichingm/electron,pombredanne/electron,cqqccqc/electron,leethomas/electron,simongregory/electron,webmechanicx/electron,shiftkey/electron,jonatasfreitasv/electron,Jacobichou/electron,vHanda/electron,felixrieseberg/electron,yalexx/electron,matiasinsaurralde/electron,brenca/electron,bright-sparks/electron,kcrt/electron,medixdev/electron,renaesop/electron,RobertJGabriel/electron,smczk/electron,vipulroxx/electron,jannishuebl/electron,zhakui/electron,yan-foto/electron,jaanus/electron,fomojola/electron,Neron-X5/electron,joaomoreno/atom-shell,sshiting/electron,thomsonreuters/electron,d-salas/electron,electron/electron,rreimann/electron,rhencke/electron,brave/electron,carsonmcdonald/electron,felixrieseberg/electron,thompsonemerson/electron,beni55/electron,kokdemo/electron,d-salas/electron,vipulroxx/electron,JesselJohn/electron,astoilkov/electron,aichingm/electron,saronwei/electron,farmisen/electron,thomsonreuters/electron,jannishuebl/electron,oiledCode/electron,tomashanacek/electron,JussMee15/electron,farmisen/electron,jlhbaseball15/electron,arusakov/electron,digideskio/electron,christian-bromann/electron,electron/electron,edulan/electron,ervinb/electron,adcentury/electron,aaron-goshine/electron,gerhardberger/electron,adcentury/electron,yan-foto/electron,biblerule/UMCTelnetHub,jonatasfreitasv/electron,Neron-X5/electron,ianscrivener/electron,Rokt33r/electron,edulan/electron,yalexx/electron,smczk/electron,John-Lin/electron,noikiy/electron,stevekinney/electron,beni55/electron,michaelchiche/electron,shaundunne/electron,fritx/electron,kostia/electron,mirrh/electron,arturts/electron,Zagorakiss/electron,MaxWhere/electron,natgolov/electron,benweissmann/electron,egoist/electron,deed02392/electron,kenmozi/electron,howmuchcomputer/electron,RIAEvangelist/electron,jcblw/electron,MaxWhere/electron,cos2004/electron,John-Lin/electron,rhencke/electron,zhakui/electron,shiftkey/electron,lzpfmh/electron,wolfflow/electron,aaron-goshine/electron,John-Lin/electron,stevekinney/electron,pandoraui/electron,sky7sea/electron,mattotodd/electron,soulteary/electron,howmuchcomputer/electron,pombredanne/electron,adamjgray/electron,Jonekee/electron,xiruibing/electron,nekuz0r/electron,arusakov/electron,ankitaggarwal011/electron,dongjoon-hyun/electron,aecca/electron,vHanda/electron,jacksondc/electron,coderhaoxin/electron,kcrt/electron,aecca/electron,systembugtj/electron,trigrass2/electron,vaginessa/electron,oiledCode/electron,fritx/electron,brave/muon,benweissmann/electron,leethomas/electron,evgenyzinoviev/electron,nicobot/electron,baiwyc119/electron,howmuchcomputer/electron,dongjoon-hyun/electron,digideskio/electron,miniak/electron,jhen0409/electron,etiktin/electron,Floato/electron,nicobot/electron,abhishekgahlot/electron,webmechanicx/electron,sircharleswatson/electron,mrwizard82d1/electron,edulan/electron,d-salas/electron,wolfflow/electron,icattlecoder/electron,leftstick/electron,dkfiresky/electron,meowlab/electron,joneit/electron,tinydew4/electron,cos2004/electron,rhencke/electron,shiftkey/electron,gamedevsam/electron,xfstudio/electron,wolfflow/electron,bwiggs/electron,synaptek/electron,tomashanacek/electron,noikiy/electron,joaomoreno/atom-shell,setzer777/electron,shennushi/electron,rajatsingla28/electron,adamjgray/electron,lrlna/electron,robinvandernoord/electron,leethomas/electron,cos2004/electron,Rokt33r/electron,jiaz/electron,destan/electron,posix4e/electron,dongjoon-hyun/electron,Evercoder/electron,joneit/electron,DivyaKMenon/electron,jlhbaseball15/electron,zhakui/electron,gbn972/electron,tylergibson/electron,leftstick/electron,tylergibson/electron,mattotodd/electron,adcentury/electron,vaginessa/electron,robinvandernoord/electron,anko/electron,oiledCode/electron,bbondy/electron,LadyNaggaga/electron,iftekeriba/electron,carsonmcdonald/electron,joneit/electron,medixdev/electron,yan-foto/electron,jonatasfreitasv/electron,fffej/electron,SufianHassan/electron,ianscrivener/electron,leolujuyi/electron,tomashanacek/electron,deed02392/electron,Zagorakiss/electron,deed02392/electron,michaelchiche/electron,leethomas/electron,iftekeriba/electron,gamedevsam/electron,greyhwndz/electron,adamjgray/electron,Neron-X5/electron,zhakui/electron,GoooIce/electron,aichingm/electron,pandoraui/electron,simonfork/electron,brave/electron,farmisen/electron,jacksondc/electron,twolfson/electron,vaginessa/electron,trigrass2/electron,DivyaKMenon/electron,sshiting/electron,synaptek/electron,medixdev/electron,shiftkey/electron,Gerhut/electron,egoist/electron,evgenyzinoviev/electron,arusakov/electron,ankitaggarwal011/electron,jacksondc/electron,seanchas116/electron,IonicaBizauKitchen/electron,zhakui/electron,wolfflow/electron,lrlna/electron,jaanus/electron,biblerule/UMCTelnetHub,Zagorakiss/electron,carsonmcdonald/electron,vaginessa/electron,edulan/electron,jiaz/electron,bruce/electron,beni55/electron,GoooIce/electron,eriser/electron,John-Lin/electron,arusakov/electron,farmisen/electron,vaginessa/electron,d-salas/electron,takashi/electron,dahal/electron,cqqccqc/electron,jtburke/electron,jhen0409/electron,thompsonemerson/electron,dahal/electron,icattlecoder/electron,evgenyzinoviev/electron,seanchas116/electron,egoist/electron,Jacobichou/electron,kostia/electron,fomojola/electron,Andrey-Pavlov/electron,gamedevsam/electron,bpasero/electron,medixdev/electron,kokdemo/electron,GoooIce/electron,leethomas/electron,nicholasess/electron,stevemao/electron,GoooIce/electron,RobertJGabriel/electron,gabrielPeart/electron,greyhwndz/electron,jhen0409/electron,rreimann/electron,yalexx/electron,brenca/electron,aliib/electron,Jonekee/electron,kokdemo/electron,Neron-X5/electron,chriskdon/electron,neutrous/electron,faizalpribadi/electron,bwiggs/electron,rajatsingla28/electron,dongjoon-hyun/electron,JesselJohn/electron,jlhbaseball15/electron,faizalpribadi/electron,joneit/electron,kokdemo/electron,systembugtj/electron,icattlecoder/electron,subblue/electron,lzpfmh/electron,wan-qy/electron,tincan24/electron,kazupon/electron,chriskdon/electron,micalan/electron,faizalpribadi/electron,xfstudio/electron,seanchas116/electron,greyhwndz/electron,kazupon/electron,christian-bromann/electron,jtburke/electron,aaron-goshine/electron,dahal/electron,rreimann/electron,stevekinney/electron,DivyaKMenon/electron,RIAEvangelist/electron,nicobot/electron,saronwei/electron,systembugtj/electron,Jonekee/electron,the-ress/electron,bruce/electron,abhishekgahlot/electron,greyhwndz/electron,LadyNaggaga/electron,fffej/electron,fomojola/electron,bwiggs/electron,joaomoreno/atom-shell,aecca/electron,nicholasess/electron,robinvandernoord/electron,joaomoreno/atom-shell,Jonekee/electron,trankmichael/electron,gbn972/electron,stevekinney/electron,saronwei/electron,baiwyc119/electron,jcblw/electron,fomojola/electron,neutrous/electron,sky7sea/electron,mjaniszew/electron,gamedevsam/electron,aliib/electron,voidbridge/electron,rreimann/electron,iftekeriba/electron,sircharleswatson/electron,sshiting/electron,thompsonemerson/electron,kostia/electron,bobwol/electron,pombredanne/electron,evgenyzinoviev/electron,twolfson/electron,Rokt33r/electron,rhencke/electron,wan-qy/electron,nekuz0r/electron,biblerule/UMCTelnetHub,fffej/electron,brave/electron,trankmichael/electron,gerhardberger/electron,arturts/electron,xfstudio/electron,nekuz0r/electron,shaundunne/electron,tonyganch/electron,bwiggs/electron,mattotodd/electron,LadyNaggaga/electron,evgenyzinoviev/electron,seanchas116/electron,bitemyapp/electron,micalan/electron,BionicClick/electron,mhkeller/electron,gabriel/electron,the-ress/electron,Jacobichou/electron,shockone/electron,subblue/electron,IonicaBizauKitchen/electron,subblue/electron,systembugtj/electron,nekuz0r/electron,rreimann/electron,icattlecoder/electron,bobwol/electron,mrwizard82d1/electron,BionicClick/electron,synaptek/electron,matiasinsaurralde/electron,shennushi/electron,thompsonemerson/electron,xiruibing/electron,renaesop/electron,RobertJGabriel/electron,coderhaoxin/electron,medixdev/electron,seanchas116/electron,roadev/electron,trigrass2/electron,stevemao/electron,adcentury/electron,twolfson/electron,Gerhut/electron,leftstick/electron,yalexx/electron,lrlna/electron,stevekinney/electron,evgenyzinoviev/electron,adamjgray/electron,JesselJohn/electron,cqqccqc/electron,aliib/electron,trankmichael/electron,natgolov/electron,natgolov/electron,stevekinney/electron,bitemyapp/electron,xiruibing/electron,leethomas/electron,setzer777/electron,gabrielPeart/electron,anko/electron,matiasinsaurralde/electron,thingsinjars/electron,jhen0409/electron,felixrieseberg/electron,leolujuyi/electron,GoooIce/electron,jtburke/electron,Evercoder/electron,dkfiresky/electron,arusakov/electron,electron/electron,tinydew4/electron,fomojola/electron,stevemao/electron,dongjoon-hyun/electron,dkfiresky/electron,tylergibson/electron,yan-foto/electron,vHanda/electron,subblue/electron,renaesop/electron,systembugtj/electron,Jonekee/electron,coderhaoxin/electron,gabriel/electron,ankitaggarwal011/electron,gabrielPeart/electron,micalan/electron,gabriel/electron,micalan/electron,brave/muon,shockone/electron,meowlab/electron,subblue/electron,smczk/electron,baiwyc119/electron,vaginessa/electron,thomsonreuters/electron,joaomoreno/atom-shell,chriskdon/electron,jacksondc/electron,gerhardberger/electron,John-Lin/electron,tincan24/electron,vHanda/electron,webmechanicx/electron,simonfork/electron,simongregory/electron,bright-sparks/electron,sky7sea/electron,natgolov/electron,aliib/electron,dahal/electron,gerhardberger/electron,joaomoreno/atom-shell,Gerhut/electron,jlhbaseball15/electron,felixrieseberg/electron,kazupon/electron,faizalpribadi/electron,aliib/electron,LadyNaggaga/electron,voidbridge/electron,edulan/electron,adcentury/electron,preco21/electron,eric-seekas/electron,Andrey-Pavlov/electron,Floato/electron,stevemao/electron,d-salas/electron,tonyganch/electron,GoooIce/electron,coderhaoxin/electron,nekuz0r/electron,MaxWhere/electron,jiaz/electron,noikiy/electron,ankitaggarwal011/electron,etiktin/electron,electron/electron,iftekeriba/electron,pandoraui/electron,takashi/electron,gerhardberger/electron,jonatasfreitasv/electron,robinvandernoord/electron,carsonmcdonald/electron,tincan24/electron,natgolov/electron,faizalpribadi/electron,Neron-X5/electron,twolfson/electron,matiasinsaurralde/electron,bbondy/electron,Evercoder/electron,voidbridge/electron,benweissmann/electron,pombredanne/electron,minggo/electron,trankmichael/electron,brave/muon,xfstudio/electron,sky7sea/electron,simongregory/electron,aliib/electron,iftekeriba/electron,sshiting/electron,gabriel/electron,aecca/electron,fritx/electron,roadev/electron,JesselJohn/electron,brave/electron,tincan24/electron,ianscrivener/electron,yalexx/electron,soulteary/electron,tinydew4/electron,neutrous/electron,aecca/electron,micalan/electron,anko/electron,joneit/electron,kcrt/electron,pirafrank/electron,jannishuebl/electron,bitemyapp/electron,kazupon/electron,bright-sparks/electron,bobwol/electron,Andrey-Pavlov/electron,cos2004/electron,Zagorakiss/electron,nicholasess/electron,bwiggs/electron,jannishuebl/electron,IonicaBizauKitchen/electron,bobwol/electron,the-ress/electron,jonatasfreitasv/electron,minggo/electron,noikiy/electron,posix4e/electron,mjaniszew/electron,minggo/electron,icattlecoder/electron,benweissmann/electron,tonyganch/electron,posix4e/electron,renaesop/electron,tinydew4/electron,shennushi/electron,RIAEvangelist/electron,jhen0409/electron,leftstick/electron,astoilkov/electron,Jacobichou/electron,trankmichael/electron,anko/electron,eric-seekas/electron,webmechanicx/electron,pirafrank/electron,shockone/electron,synaptek/electron,RobertJGabriel/electron,jaanus/electron,wan-qy/electron,wolfflow/electron,gerhardberger/electron,simonfork/electron,BionicClick/electron,aaron-goshine/electron,biblerule/UMCTelnetHub,jjz/electron,Floato/electron,eric-seekas/electron,davazp/electron,RIAEvangelist/electron,wan-qy/electron,meowlab/electron,lzpfmh/electron,baiwyc119/electron,tylergibson/electron,jjz/electron,brave/muon,leolujuyi/electron,preco21/electron,renaesop/electron,ianscrivener/electron,smczk/electron,Rokt33r/electron,nicholasess/electron,digideskio/electron,kokdemo/electron,yalexx/electron,Jacobichou/electron,etiktin/electron,simongregory/electron,jiaz/electron,seanchas116/electron,aichingm/electron,smczk/electron,chriskdon/electron,preco21/electron,dkfiresky/electron,michaelchiche/electron,kokdemo/electron,dahal/electron,jaanus/electron,jlhbaseball15/electron,thompsonemerson/electron,neutrous/electron,sshiting/electron,tomashanacek/electron,meowlab/electron,aecca/electron,cos2004/electron,renaesop/electron,cqqccqc/electron,arturts/electron,jsutcodes/electron,dongjoon-hyun/electron,Neron-X5/electron,gabrielPeart/electron,jacksondc/electron,Gerhut/electron,setzer777/electron,chriskdon/electron,setzer777/electron,bobwol/electron,gbn972/electron,sircharleswatson/electron,simonfork/electron,eriser/electron,thomsonreuters/electron,jcblw/electron,rreimann/electron,vipulroxx/electron,kazupon/electron,sircharleswatson/electron,bpasero/electron,Zagorakiss/electron,tomashanacek/electron,vHanda/electron,bruce/electron,abhishekgahlot/electron,leolujuyi/electron,thingsinjars/electron,astoilkov/electron,christian-bromann/electron,noikiy/electron,gbn972/electron,bitemyapp/electron,soulteary/electron,kostia/electron,jannishuebl/electron,nicobot/electron,the-ress/electron,kostia/electron,mjaniszew/electron,dahal/electron,synaptek/electron,yan-foto/electron,fomojola/electron,natgolov/electron,tomashanacek/electron,Andrey-Pavlov/electron,vHanda/electron,sshiting/electron,Jacobichou/electron,MaxWhere/electron,destan/electron,felixrieseberg/electron,minggo/electron,IonicaBizauKitchen/electron,coderhaoxin/electron,fritx/electron,rajatsingla28/electron,rhencke/electron,howmuchcomputer/electron,saronwei/electron,electron/electron,bright-sparks/electron,rajatsingla28/electron,nicholasess/electron,cos2004/electron,gabriel/electron,destan/electron,wan-qy/electron,dkfiresky/electron,lrlna/electron,soulteary/electron,beni55/electron,Rokt33r/electron,JussMee15/electron,SufianHassan/electron,SufianHassan/electron,michaelchiche/electron,kostia/electron,arturts/electron,mirrh/electron,fffej/electron,fritx/electron,davazp/electron,kcrt/electron,posix4e/electron,fffej/electron,minggo/electron,mrwizard82d1/electron,biblerule/UMCTelnetHub,gamedevsam/electron,greyhwndz/electron,etiktin/electron,shennushi/electron,neutrous/electron,meowlab/electron,pirafrank/electron,gabriel/electron,SufianHassan/electron,felixrieseberg/electron,sircharleswatson/electron,miniak/electron,minggo/electron,bitemyapp/electron,mjaniszew/electron,farmisen/electron,xfstudio/electron,IonicaBizauKitchen/electron,jlhbaseball15/electron,JesselJohn/electron,twolfson/electron,ianscrivener/electron,sircharleswatson/electron,jtburke/electron,astoilkov/electron,setzer777/electron,adcentury/electron,benweissmann/electron,jcblw/electron,gamedevsam/electron,egoist/electron,davazp/electron,yan-foto/electron,Andrey-Pavlov/electron,kenmozi/electron,bpasero/electron,MaxWhere/electron,IonicaBizauKitchen/electron,howmuchcomputer/electron,adamjgray/electron,arusakov/electron,nicobot/electron,thingsinjars/electron,miniak/electron,brenca/electron,trankmichael/electron,bpasero/electron,robinvandernoord/electron,eriser/electron,d-salas/electron,bbondy/electron,BionicClick/electron,beni55/electron,soulteary/electron,shennushi/electron,nekuz0r/electron,gerhardberger/electron,brenca/electron,ankitaggarwal011/electron,arturts/electron,mirrh/electron,webmechanicx/electron,jacksondc/electron,jjz/electron,medixdev/electron,pandoraui/electron,ervinb/electron,jiaz/electron,pirafrank/electron,DivyaKMenon/electron,jsutcodes/electron,simongregory/electron,Zagorakiss/electron,davazp/electron,Rokt33r/electron,brave/electron,mrwizard82d1/electron,davazp/electron,systembugtj/electron,oiledCode/electron,deed02392/electron,digideskio/electron,eriser/electron,iftekeriba/electron,xfstudio/electron,astoilkov/electron,bwiggs/electron,shiftkey/electron,voidbridge/electron,michaelchiche/electron,synaptek/electron,kcrt/electron,JussMee15/electron,sky7sea/electron,bright-sparks/electron,mhkeller/electron,BionicClick/electron,setzer777/electron,Floato/electron,jtburke/electron,xiruibing/electron,bruce/electron,mirrh/electron,shaundunne/electron,ianscrivener/electron,shockone/electron,wolfflow/electron,bpasero/electron,jiaz/electron,christian-bromann/electron,pombredanne/electron,digideskio/electron,eriser/electron,voidbridge/electron,preco21/electron,shaundunne/electron,ankitaggarwal011/electron,kenmozi/electron,posix4e/electron,robinvandernoord/electron,destan/electron,gbn972/electron,gabrielPeart/electron,meowlab/electron,electron/electron,benweissmann/electron,tinydew4/electron,tylergibson/electron,bbondy/electron,John-Lin/electron,lrlna/electron,aichingm/electron,mhkeller/electron,kcrt/electron,nicobot/electron,RobertJGabriel/electron,egoist/electron,digideskio/electron,the-ress/electron,mattotodd/electron,eric-seekas/electron,roadev/electron,bitemyapp/electron,tylergibson/electron,abhishekgahlot/electron,smczk/electron,jaanus/electron,brenca/electron,faizalpribadi/electron,neutrous/electron,takashi/electron,RobertJGabriel/electron,deed02392/electron,miniak/electron,beni55/electron,deed02392/electron,shaundunne/electron,shennushi/electron,mirrh/electron,sky7sea/electron,davazp/electron,tonyganch/electron,SufianHassan/electron,leolujuyi/electron,RIAEvangelist/electron,the-ress/electron,Gerhut/electron,astoilkov/electron
|
9264a00dfd13c18350bbc45a688e4af0fe5fcf6a
|
atom/common/platform_util_linux.cc
|
atom/common/platform_util_linux.cc
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/platform_util.h"
#include <stdio.h>
#include "base/cancelable_callback.h"
#include "base/environment.h"
#include "base/files/file_util.h"
#include "base/nix/xdg_util.h"
#include "base/process/kill.h"
#include "base/process/launch.h"
#include "url/gurl.h"
#define ELECTRON_TRASH "ELECTRON_TRASH"
#define ELECTRON_DEFAULT_TRASH "gvfs-trash"
namespace {
bool XDGUtilV(const std::vector<std::string>& argv, const bool wait_for_exit) {
base::LaunchOptions options;
options.allow_new_privs = true;
// xdg-open can fall back on mailcap which eventually might plumb through
// to a command that needs a terminal. Set the environment variable telling
// it that we definitely don't have a terminal available and that it should
// bring up a new terminal if necessary. See "man mailcap".
options.environ["MM_NOTTTY"] = "1";
base::Process process = base::LaunchProcess(argv, options);
if (!process.IsValid())
return false;
if (!wait_for_exit) {
base::EnsureProcessGetsReaped(process.Pid());
return true;
}
int exit_code = -1;
if (!process.WaitForExit(&exit_code))
return false;
return (exit_code == 0);
}
bool XDGUtil(const std::string& util,
const std::string& arg,
const bool wait_for_exit) {
std::vector<std::string> argv;
argv.push_back(util);
argv.push_back(arg);
return XDGUtilV(argv, wait_for_exit);
}
bool XDGOpen(const std::string& path, const bool wait_for_exit) {
return XDGUtil("xdg-open", path, wait_for_exit);
}
bool XDGEmail(const std::string& email, const bool wait_for_exit) {
return XDGUtil("xdg-email", email, wait_for_exit);
}
} // namespace
namespace platform_util {
// TODO(estade): It would be nice to be able to select the file in the file
// manager, but that probably requires extending xdg-open. For now just
// show the folder.
bool ShowItemInFolder(const base::FilePath& full_path) {
base::FilePath dir = full_path.DirName();
if (!base::DirectoryExists(dir))
return false;
return XDGOpen(dir.value(), false);
}
bool OpenItem(const base::FilePath& full_path) {
return XDGOpen(full_path.value(), false);
}
bool OpenExternal(const GURL& url, bool activate) {
// Don't wait for exit, since we don't want to wait for the browser/email
// client window to close before returning
if (url.SchemeIs("mailto"))
return XDGEmail(url.spec(), false);
else
return XDGOpen(url.spec(), false);
}
void OpenExternal(const GURL& url,
bool activate,
const OpenExternalCallback& callback) {
// TODO(gabriel): Implement async open if callback is specified
callback.Run(OpenExternal(url, activate) ? "" : "Failed to open");
}
bool MoveItemToTrash(const base::FilePath& full_path) {
std::string trash;
if (getenv(ELECTRON_TRASH) != NULL) {
trash = getenv(ELECTRON_TRASH);
} else {
// Determine desktop environment and set accordingly.
std::unique_ptr<base::Environment> env(base::Environment::Create());
base::nix::DesktopEnvironment desktop_env(
base::nix::GetDesktopEnvironment(env.get()));
if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE4 ||
desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE5) {
trash = "kioclient5";
} else if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE3) {
trash = "kioclient";
} else {
trash = ELECTRON_DEFAULT_TRASH;
}
}
std::vector<std::string> argv;
if (trash.compare("kioclient5") == 0 || trash.compare("kioclient") == 0) {
argv.push_back(trash);
argv.push_back("move");
argv.push_back(full_path.value());
argv.push_back("trash:/");
} else if (trash.compare("trash-cli") == 0) {
argv.push_back("trash-put");
argv.push_back(full_path.value());
} else if (trash.compare("gio") == 0) {
argv.push_back("gio");
argv.push_back("trash");
argv.push_back(full_path.value());
} else {
argv.push_back(ELECTRON_DEFAULT_TRASH);
argv.push_back(full_path.value());
}
return XDGUtilV(argv, true);
}
void Beep() {
// echo '\a' > /dev/console
FILE* console = fopen("/dev/console", "r");
if (console == NULL)
return;
fprintf(console, "\a");
fclose(console);
}
} // namespace platform_util
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/platform_util.h"
#include <stdio.h>
#include "base/cancelable_callback.h"
#include "base/environment.h"
#include "base/files/file_util.h"
#include "base/nix/xdg_util.h"
#include "base/process/kill.h"
#include "base/process/launch.h"
#include "url/gurl.h"
#define ELECTRON_TRASH "ELECTRON_TRASH"
#define ELECTRON_DEFAULT_TRASH "gvfs-trash"
namespace {
bool XDGUtilV(const std::vector<std::string>& argv, const bool wait_for_exit) {
base::LaunchOptions options;
options.allow_new_privs = true;
// xdg-open can fall back on mailcap which eventually might plumb through
// to a command that needs a terminal. Set the environment variable telling
// it that we definitely don't have a terminal available and that it should
// bring up a new terminal if necessary. See "man mailcap".
options.environ["MM_NOTTTY"] = "1";
base::Process process = base::LaunchProcess(argv, options);
if (!process.IsValid())
return false;
if (wait_for_exit) {
int exit_code = -1;
if (!process.WaitForExit(&exit_code))
return false;
return (exit_code == 0);
}
base::EnsureProcessGetsReaped(std::move(process));
return true;
}
bool XDGUtil(const std::string& util,
const std::string& arg,
const bool wait_for_exit) {
std::vector<std::string> argv;
argv.push_back(util);
argv.push_back(arg);
return XDGUtilV(argv, wait_for_exit);
}
bool XDGOpen(const std::string& path, const bool wait_for_exit) {
return XDGUtil("xdg-open", path, wait_for_exit);
}
bool XDGEmail(const std::string& email, const bool wait_for_exit) {
return XDGUtil("xdg-email", email, wait_for_exit);
}
} // namespace
namespace platform_util {
// TODO(estade): It would be nice to be able to select the file in the file
// manager, but that probably requires extending xdg-open. For now just
// show the folder.
bool ShowItemInFolder(const base::FilePath& full_path) {
base::FilePath dir = full_path.DirName();
if (!base::DirectoryExists(dir))
return false;
return XDGOpen(dir.value(), false);
}
bool OpenItem(const base::FilePath& full_path) {
return XDGOpen(full_path.value(), false);
}
bool OpenExternal(const GURL& url, bool activate) {
// Don't wait for exit, since we don't want to wait for the browser/email
// client window to close before returning
if (url.SchemeIs("mailto"))
return XDGEmail(url.spec(), false);
else
return XDGOpen(url.spec(), false);
}
void OpenExternal(const GURL& url,
bool activate,
const OpenExternalCallback& callback) {
// TODO(gabriel): Implement async open if callback is specified
callback.Run(OpenExternal(url, activate) ? "" : "Failed to open");
}
bool MoveItemToTrash(const base::FilePath& full_path) {
std::string trash;
if (getenv(ELECTRON_TRASH) != NULL) {
trash = getenv(ELECTRON_TRASH);
} else {
// Determine desktop environment and set accordingly.
std::unique_ptr<base::Environment> env(base::Environment::Create());
base::nix::DesktopEnvironment desktop_env(
base::nix::GetDesktopEnvironment(env.get()));
if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE4 ||
desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE5) {
trash = "kioclient5";
} else if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE3) {
trash = "kioclient";
} else {
trash = ELECTRON_DEFAULT_TRASH;
}
}
std::vector<std::string> argv;
if (trash.compare("kioclient5") == 0 || trash.compare("kioclient") == 0) {
argv.push_back(trash);
argv.push_back("move");
argv.push_back(full_path.value());
argv.push_back("trash:/");
} else if (trash.compare("trash-cli") == 0) {
argv.push_back("trash-put");
argv.push_back(full_path.value());
} else if (trash.compare("gio") == 0) {
argv.push_back("gio");
argv.push_back("trash");
argv.push_back(full_path.value());
} else {
argv.push_back(ELECTRON_DEFAULT_TRASH);
argv.push_back(full_path.value());
}
return XDGUtilV(argv, true);
}
void Beep() {
// echo '\a' > /dev/console
FILE* console = fopen("/dev/console", "r");
if (console == NULL)
return;
fprintf(console, "\a");
fclose(console);
}
} // namespace platform_util
|
Simplify EnsureProcessTerminated() implementations.
|
Simplify EnsureProcessTerminated() implementations.
https://chromium-review.googlesource.com/c/chromium/src/+/920799
|
C++
|
mit
|
the-ress/electron,gerhardberger/electron,gerhardberger/electron,the-ress/electron,the-ress/electron,gerhardberger/electron,bpasero/electron,gerhardberger/electron,gerhardberger/electron,gerhardberger/electron,seanchas116/electron,electron/electron,seanchas116/electron,seanchas116/electron,bpasero/electron,the-ress/electron,bpasero/electron,bpasero/electron,electron/electron,bpasero/electron,electron/electron,seanchas116/electron,seanchas116/electron,seanchas116/electron,gerhardberger/electron,electron/electron,the-ress/electron,electron/electron,bpasero/electron,the-ress/electron,the-ress/electron,electron/electron,bpasero/electron,electron/electron
|
ab75d35b8b7ea7d0c293d2f0034939f77875788c
|
src/ntpclient.cpp
|
src/ntpclient.cpp
|
// Copyright (c) 2018 alex v
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "ntpclient.h"
#include "util.h"
using namespace boost;
using namespace boost::asio;
int64_t CNtpClient::getTimestamp()
{
time_t timeRecv = -1;
io_service io_service;
LogPrint("ntp", "CNtpClient: Opening socket to NTP server %s.\n", sHostName);
try
{
ip::udp::resolver resolver(io_service);
ip::udp::resolver::query query(boost::asio::ip::udp::v4(), sHostName, "ntp");
ip::udp::endpoint receiver_endpoint = *resolver.resolve(query);
ip::udp::socket socket(io_service);
socket.open(ip::udp::v4());
boost::array<unsigned char, 48> sendBuf = {{010,0,0,0,0,0,0,0,0}};
socket.send_to(boost::asio::buffer(sendBuf), receiver_endpoint);
boost::array<unsigned long, 1024> recvBuf;
ip::udp::endpoint sender_endpoint;
try
{
fd_set fileDescriptorSet;
struct timeval timeStruct;
// set the timeout to 5 seconds
timeStruct.tv_sec = GetArg("-ntptimeout", 10);
timeStruct.tv_usec = 0;
FD_ZERO(&fileDescriptorSet);
int nativeSocket = socket.native();
FD_SET(nativeSocket,&fileDescriptorSet);
select(nativeSocket+1,&fileDescriptorSet,NULL,NULL,&timeStruct);
if(!FD_ISSET(nativeSocket,&fileDescriptorSet))
{
LogPrint("ntp", "CNtpClient: Could not read socket from NTP server %s (Read timeout)\n", sHostName);
}
else
{
socket.receive_from(boost::asio::buffer(recvBuf), sender_endpoint);
timeRecv = ntohl((time_t)recvBuf[4]);
timeRecv-= 2208988800U; // Substract 01/01/1970 == 2208988800U
LogPrint("ntp", "CNtpClient: Received timestamp: %ll \n", (uint64_t)timeRecv);
}
}
catch (std::exception& e)
{
LogPrintf("CNtpClient: Could not read clock from NTP server %s (%s)\n", sHostName, e.what());
}
}
catch (std::exception& e)
{
LogPrintf("CNtpClient: Could not open socket to NTP server %s (%s)\n", sHostName, e.what());
}
return (int64_t)timeRecv;
}
|
// Copyright (c) 2018 alex v
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "ntpclient.h"
#include "util.h"
using namespace boost;
using namespace boost::asio;
int64_t CNtpClient::getTimestamp()
{
time_t timeRecv = -1;
io_service io_service;
LogPrint("ntp", "CNtpClient: Opening socket to NTP server %s.\n", sHostName);
try
{
ip::udp::resolver resolver(io_service);
ip::udp::resolver::query query(boost::asio::ip::udp::v4(), sHostName, "ntp");
ip::udp::endpoint receiver_endpoint = *resolver.resolve(query);
ip::udp::socket socket(io_service);
socket.open(ip::udp::v4());
boost::array<unsigned char, 48> sendBuf = {{010,0,0,0,0,0,0,0,0}};
socket.send_to(boost::asio::buffer(sendBuf), receiver_endpoint);
boost::array<unsigned long, 1024> recvBuf;
ip::udp::endpoint sender_endpoint;
try
{
fd_set fileDescriptorSet;
struct timeval timeStruct;
// set the timeout to 10 seconds
timeStruct.tv_sec = GetArg("-ntptimeout", 10);
timeStruct.tv_usec = 0;
FD_ZERO(&fileDescriptorSet);
int nativeSocket = socket.native();
FD_SET(nativeSocket,&fileDescriptorSet);
select(nativeSocket+1,&fileDescriptorSet,NULL,NULL,&timeStruct);
if(!FD_ISSET(nativeSocket,&fileDescriptorSet))
{
LogPrint("ntp", "CNtpClient: Could not read socket from NTP server %s (Read timeout)\n", sHostName);
}
else
{
socket.receive_from(boost::asio::buffer(recvBuf), sender_endpoint);
timeRecv = ntohl((time_t)recvBuf[4]);
timeRecv-= 2208988800U; // Substract 01/01/1970 == 2208988800U
LogPrint("ntp", "CNtpClient: Received timestamp: %ll \n", (uint64_t)timeRecv);
}
}
catch (std::exception& e)
{
LogPrintf("CNtpClient: Could not read clock from NTP server %s (%s)\n", sHostName, e.what());
}
}
catch (std::exception& e)
{
LogPrintf("CNtpClient: Could not open socket to NTP server %s (%s)\n", sHostName, e.what());
}
return (int64_t)timeRecv;
}
|
update comment
|
update comment
|
C++
|
mit
|
navcoindev/navcoin-core,navcoindev/navcoin-core,navcoindev/navcoin-core,navcoindev/navcoin-core,navcoindev/navcoin-core,navcoindev/navcoin-core
|
57627fdffb2409c97e769cd78ee9f172d5d72ae0
|
binpac/passes/scope-builder.cc
|
binpac/passes/scope-builder.cc
|
#include "declaration.h"
#include "expression.h"
#include "function.h"
#include "scope.h"
#include "statement.h"
#include "variable.h"
#include "scope-builder.h"
#include "context.h"
using namespace binpac;
using namespace binpac::passes;
ScopeBuilder::ScopeBuilder(CompilerContext* context) : Pass<AstInfo>("binpac::ScopeBuilder")
{
_context = context;
}
ScopeBuilder::~ScopeBuilder()
{
}
bool ScopeBuilder::run(shared_ptr<ast::NodeBase> module)
{
auto m = ast::checkedCast<Module>(module);
m->body()->scope()->clear();
if ( ! processAllPreOrder(module) )
return false;
for ( auto i : m->importedIDs() ) {
auto m1 = util::strtolower(i->pathAsString());
auto m2 = util::strtolower(m->id()->pathAsString());
if ( m1 == m2 )
continue;
shared_ptr<Module> other = _context->load(i->name());
if ( ! other )
fatalError("import failed");
m->body()->scope()->addChild(other->id(), other->body()->scope());
}
return errors() == 0;
}
// When the scope builder runs, the validator may not yet have been executed.
// So check the stuff we need.
shared_ptr<Scope> ScopeBuilder::_checkDecl(Declaration* decl)
{
auto id = decl->id();
auto is_hook = dynamic_cast<declaration::Hook*>(decl);
if ( ! id ) {
error(decl, "declaration without an ID");
return 0;
}
if ( id->isScoped() && ! is_hook && decl->linkage() != Declaration::IMPORTED ) {
error(decl, "declared ID cannot have a scope");
return 0;
}
auto block = current<statement::Block>();
if ( ! block ) {
error(decl, util::fmt("declaration of %s is not part of a block", decl->id()->name().c_str()));
return 0;
}
return block->scope();
}
void ScopeBuilder::visit(declaration::Variable* v)
{
auto scope = _checkDecl(v);
if ( ! scope )
return;
auto var = v->variable()->sharedPtr<Variable>();
auto expr = std::make_shared<expression::Variable>(var, var->location());
scope->insert(v->id(), expr, true);
}
void ScopeBuilder::visit(declaration::Type* t)
{
auto scope = _checkDecl(t);
if ( ! scope )
return;
auto type = t->type();
auto expr = shared_ptr<expression::Type>(new expression::Type(type, type->location()));
scope->insert(t->id(), expr, true);
// Link in any type-specific scope the type may define.
auto tscope = t->type()->typeScope();
if ( tscope ) {
tscope->setParent(scope);
scope->addChild(t->id(), tscope);
}
t->type()->setID(t->id());
}
void ScopeBuilder::visit(declaration::Constant* c)
{
auto scope = _checkDecl(c);
if ( ! scope )
return;
scope->insert(c->id(), c->constant(), true);
}
void ScopeBuilder::visit(declaration::Function* f)
{
auto scope = _checkDecl(f);
if ( ! scope )
return;
auto func = f->function()->sharedPtr<Function>();
auto expr = shared_ptr<expression::Function>(new expression::Function(func, func->location()));
auto is_hook = dynamic_cast<declaration::Hook*>(f);
if ( ! is_hook )
scope->insert(f->id(), expr, true);
if ( ! func->body() )
// Just a declaration without implementation.
return;
// Add parameters to body's scope.
scope = ast::checkedCast<statement::Block>(func->body())->scope();
for ( auto p : func->type()->parameters() ) {
auto pexpr = shared_ptr<expression::Parameter>(new expression::Parameter(p, p->location()));
scope->insert(p->id(), pexpr, true);
}
}
|
#include "declaration.h"
#include "expression.h"
#include "function.h"
#include "scope.h"
#include "statement.h"
#include "variable.h"
#include "scope-builder.h"
#include "context.h"
namespace binpac {
class ScopeClearer : public ast::Pass<AstInfo>
{
public:
ScopeClearer() : Pass<AstInfo>("binpac::ScopeClearer") {}
virtual ~ScopeClearer() {}
bool run(shared_ptr<ast::NodeBase> module) override { return processAllPreOrder(module); }
protected:
void visit(statement::Block* b) override { b->scope()->clear(); }
};
}
using namespace binpac;
using namespace binpac::passes;
ScopeBuilder::ScopeBuilder(CompilerContext* context) : Pass<AstInfo>("binpac::ScopeBuilder")
{
_context = context;
}
ScopeBuilder::~ScopeBuilder()
{
}
bool ScopeBuilder::run(shared_ptr<ast::NodeBase> module)
{
ScopeClearer clearer;
clearer.run(module);
if ( ! processAllPreOrder(module) )
return false;
auto m = ast::checkedCast<Module>(module);
for ( auto i : m->importedIDs() ) {
auto m1 = util::strtolower(i->pathAsString());
auto m2 = util::strtolower(m->id()->pathAsString());
if ( m1 == m2 )
continue;
shared_ptr<Module> other = _context->load(i->name());
if ( ! other )
fatalError("import failed");
m->body()->scope()->addChild(other->id(), other->body()->scope());
}
return errors() == 0;
}
// When the scope builder runs, the validator may not yet have been executed.
// So check the stuff we need.
shared_ptr<Scope> ScopeBuilder::_checkDecl(Declaration* decl)
{
auto id = decl->id();
auto is_hook = dynamic_cast<declaration::Hook*>(decl);
if ( ! id ) {
error(decl, "declaration without an ID");
return 0;
}
if ( id->isScoped() && ! is_hook && decl->linkage() != Declaration::IMPORTED ) {
error(decl, "declared ID cannot have a scope");
return 0;
}
auto block = current<statement::Block>();
if ( ! block ) {
error(decl, util::fmt("declaration of %s is not part of a block", decl->id()->name().c_str()));
return 0;
}
return block->scope();
}
void ScopeBuilder::visit(declaration::Variable* v)
{
auto scope = _checkDecl(v);
if ( ! scope )
return;
auto var = v->variable()->sharedPtr<Variable>();
auto expr = std::make_shared<expression::Variable>(var, var->location());
scope->insert(v->id(), expr, true);
}
void ScopeBuilder::visit(declaration::Type* t)
{
auto scope = _checkDecl(t);
if ( ! scope )
return;
auto type = t->type();
auto expr = shared_ptr<expression::Type>(new expression::Type(type, type->location()));
scope->insert(t->id(), expr, true);
// Link in any type-specific scope the type may define.
auto tscope = t->type()->typeScope();
if ( tscope ) {
tscope->setParent(scope);
scope->addChild(t->id(), tscope);
}
t->type()->setID(t->id());
}
void ScopeBuilder::visit(declaration::Constant* c)
{
auto scope = _checkDecl(c);
if ( ! scope )
return;
scope->insert(c->id(), c->constant(), true);
}
void ScopeBuilder::visit(declaration::Function* f)
{
auto scope = _checkDecl(f);
if ( ! scope )
return;
auto func = f->function()->sharedPtr<Function>();
auto expr = shared_ptr<expression::Function>(new expression::Function(func, func->location()));
auto is_hook = dynamic_cast<declaration::Hook*>(f);
if ( ! is_hook )
scope->insert(f->id(), expr, true);
if ( ! func->body() )
// Just a declaration without implementation.
return;
// Add parameters to body's scope.
scope = ast::checkedCast<statement::Block>(func->body())->scope();
for ( auto p : func->type()->parameters() ) {
auto pexpr = shared_ptr<expression::Parameter>(new expression::Parameter(p, p->location()));
scope->insert(p->id(), pexpr, true);
}
}
|
Fix allow the scope builder to run multiple times for the same AST.
|
Fix allow the scope builder to run multiple times for the same AST.
|
C++
|
bsd-3-clause
|
rsmmr/hilti,FrozenCaribou/hilti,rsmmr/hilti,FrozenCaribou/hilti,FrozenCaribou/hilti,rsmmr/hilti,rsmmr/hilti,FrozenCaribou/hilti,rsmmr/hilti,FrozenCaribou/hilti
|
930931845d8af0568722c2924033be7027c1e3b1
|
SimpleInformationRetrievalTools/SimpleInformationRetrievalTools/main.cpp
|
SimpleInformationRetrievalTools/SimpleInformationRetrievalTools/main.cpp
|
//
// main.cpp
// SimpleInformationRetrievalTools
//
// Created by SmilENow on 6/9/15.
// Copyright (c) 2015 Jiaquan Yin, Zhendong Cao. All rights reserved.
//
#include <iostream>
#include <string>
#include <unordered_map>
#include "InvertedIndex.h"
#include "BoolQuery.h"
#include "TopK.h"
#include "Synonym.h"
#include "Interpreter.h"
#include "VectorSpaceModel.h"
#include "StaticQualityScore.h"
#include "SpellingChecker.h"
#include "ChampionList.h"
#include "PhraseQuery.h"
#include "ClusterPruning.h"
using namespace std;
InvertedIndex *II = new InvertedIndex();
Synonym *SYN = new Synonym();
Interpreter *IP = new Interpreter();
SpellingChecker *SC = new SpellingChecker();
ChampionList *CL;
VectorSpaceModel *VSM;
StaticQualityScore *SQS;
PhraseQuery *PQ;
TopK *TOPKHEAP;
ClusterPruning *CP;
int main(int argc, const char * argv[]) {
II->LoadStopWordList();
II->BuildFromFiles();
II->PrintInvertedIndexList();
II->PrintPositingList();
SYN->BuildSynonymList();
VSM = new VectorSpaceModel(II->InvertedIndexListMap);
CL = new ChampionList(II->InvertedIndexList);
CP=new ClusterPruning(II->InvertedIndexListMap);
PQ=new PhraseQuery(II->PositingListMap);
cout<<"Inverted Index Size: "<< II->InvertedIndexListMap.size()<<endl;
while(true){
string query;
cout<<"> ";
getline(cin, query);
auto q = IP->ProcessQuery(II, query);
auto oldq=q;
SC->CheckQuery(q);
cout<<"Search type: "<< IP->GetSearchType()<<" TopK mode: " << IP->GetTopKMode() <<" Synonym: "<< IP->GetSynonymMode()<<endl;
if (IP->GetSynonymMode() == SYNONYM_ON) q = SYN->findSynonym(q);
unordered_map<string, double> SQS_score;
if (IP->GetTopKMode() == TOP_K_STATIC_QUALITY_SCORE){
SQS = new StaticQualityScore(II->InvertedIndexList);
SQS_score = SQS->GetStaticQualityScore();
}
for(auto &r:q){
cout <<"op: "<<r.first<<" term: "<<r.second<<endl;
}
vector<pair<string, double>> res;
if (IP->GetTopKMode() == TOP_K_STATIC_QUALITY_SCORE){
res = VSM->GetRankingResult(q, SQS_score);
}
else if (IP->GetTopKMode() == TOP_K_CLUSTER_PRUNING){
res = CP->GetRankingResult(q);
}
else if (IP->GetTopKMode() == TOP_K_CHAMPION_LIST){
res = CL->GetRankingResult(q);
}
else if (IP->GetTopKMode() == TOP_K_HEAP){
res = TOPKHEAP->TopK_Heap(50, CL->GetRankingResult(q));
}
else if (IP->GetSearchType() == BOOL){
res = BoolQuery::FindBoolQuery(q);
}
else if (IP->GetSearchType() == PHRASE_SEARCH){
res=PQ->GetRankingResult(q);
}
else
{
res = VSM->GetRankingResult(q);
}
cout<<"---------------- TOP 50 RESULTS ----------------" <<endl;
int i= 0;
for(auto &r:res){
cout <<"docID: "<<r.first<<" score: "<<r.second<<" SQS: "<< SQS_score[r.first] <<endl;
i++;
if (i == 50){
break;
}
}
cout<<"---------------- TOP 50 RESULTS ----------------" <<endl;
}
return 0;
}
|
//
// main.cpp
// SimpleInformationRetrievalTools
//
// Created by SmilENow on 6/9/15.
// Copyright (c) 2015 Jiaquan Yin, Zhendong Cao. All rights reserved.
//
#include <iostream>
#include <string>
#include <unordered_map>
#include "InvertedIndex.h"
#include "BoolQuery.h"
#include "TopK.h"
#include "Synonym.h"
#include "Interpreter.h"
#include "VectorSpaceModel.h"
#include "StaticQualityScore.h"
#include "SpellingChecker.h"
#include "ChampionList.h"
#include "PhraseQuery.h"
#include "ClusterPruning.h"
using namespace std;
InvertedIndex *II = new InvertedIndex();
Synonym *SYN = new Synonym();
Interpreter *IP = new Interpreter();
SpellingChecker *SC = new SpellingChecker();
ChampionList *CL;
VectorSpaceModel *VSM;
StaticQualityScore *SQS;
PhraseQuery *PQ;
TopK *TOPKHEAP;
ClusterPruning *CP;
int main(int argc, const char * argv[]) {
II->LoadStopWordList();
II->BuildFromFiles();
II->PrintInvertedIndexList();
II->PrintPositingList();
SYN->BuildSynonymList();
VSM = new VectorSpaceModel(II->InvertedIndexListMap);
CL = new ChampionList(II->InvertedIndexList);
CP=new ClusterPruning(II->InvertedIndexListMap);
PQ=new PhraseQuery(II->PositingListMap);
cout<<"Inverted Index Size: "<< II->InvertedIndexListMap.size()<<endl;
while(true){
string query;
cout<<"> ";
getline(cin, query);
auto q = IP->ProcessQuery(II, query);
SC->CheckQuery(q);
cout<<"Search type: "<< IP->GetSearchType()<<" TopK mode: " << IP->GetTopKMode() <<" Synonym: "<< IP->GetSynonymMode()<<endl;
if (IP->GetSynonymMode() == SYNONYM_ON) q = SYN->findSynonym(q);
unordered_map<string, double> SQS_score;
if (IP->GetTopKMode() == TOP_K_STATIC_QUALITY_SCORE){
SQS = new StaticQualityScore(II->InvertedIndexList);
SQS_score = SQS->GetStaticQualityScore();
}
for(auto &r:q){
cout <<"op: "<<r.first<<" term: "<<r.second<<endl;
}
vector<pair<string, double>> res;
if (IP->GetTopKMode() == TOP_K_STATIC_QUALITY_SCORE){
res = VSM->GetRankingResult(q, SQS_score);
}
else if (IP->GetTopKMode() == TOP_K_CLUSTER_PRUNING){
res = CP->GetRankingResult(q);
}
else if (IP->GetTopKMode() == TOP_K_CHAMPION_LIST){
res = CL->GetRankingResult(q);
}
else if (IP->GetTopKMode() == TOP_K_HEAP){
res = TOPKHEAP->TopK_Heap(50, CL->GetRankingResult(q));
}
else if (IP->GetSearchType() == BOOL){
res = BoolQuery::FindBoolQuery(q);
}
else if (IP->GetSearchType() == PHRASE_SEARCH){
res=PQ->GetRankingResult(q);
}
else
{
res = VSM->GetRankingResult(q);
}
cout<<"---------------- TOP 50 RESULTS ----------------" <<endl;
int i= 0;
for(auto &r:res){
cout <<"docID: "<<r.first<<" score: "<<r.second<<" SQS: "<< SQS_score[r.first] <<endl;
i++;
if (i == 50){
break;
}
}
cout<<"---------------- TOP 50 RESULTS ----------------" <<endl;
}
return 0;
}
|
delete debug info in main.cpp
|
delete debug info in main.cpp
东神叼叼叼叼叼叼叼叼叼叼叼叼叼叼叼叼叼叼叼叼叼叼叼叼
|
C++
|
mit
|
smilenow/Information-Retrieval,smilenow/Information-Retrieval
|
0c5bca04abefde65c445df1e415f27108a8227b3
|
tests/auto/declarative/qfxtextinput/tst_qfxtextinput.cpp
|
tests/auto/declarative/qfxtextinput/tst_qfxtextinput.cpp
|
#include <qtest.h>
#include "../../../shared/util.h"
#include <QtDeclarative/qmlengine.h>
#include <QFile>
#include <QtDeclarative/qmlview.h>
#include <QFxTextInput>
#include <QDebug>
class tst_qfxtextinput : public QObject
{
Q_OBJECT
public:
tst_qfxtextinput();
private slots:
void text();
void width();
void font();
void color();
void selection();
void maxLength();
void masks();
void validators();
void cursorDelegate();
void navigation();
private:
void simulateKey(QmlView *, int key);
QmlView *createView(const QString &filename);
QmlEngine engine;
QStringList standard;
QStringList colorStrings;
};
tst_qfxtextinput::tst_qfxtextinput()
{
standard << "the quick brown fox jumped over the lazy dog"
<< "It's supercalifragisiticexpialidocious!"
<< "Hello, world!";
colorStrings << "aliceblue"
<< "antiquewhite"
<< "aqua"
<< "darkkhaki"
<< "darkolivegreen"
<< "dimgray"
<< "palevioletred"
<< "lightsteelblue"
<< "#000000"
<< "#AAAAAA"
<< "#FFFFFF"
<< "#2AC05F";
}
void tst_qfxtextinput::text()
{
{
QmlComponent textinputComponent(&engine, "import Qt 4.6\nTextInput { text: \"\" }", QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->text(), QString(""));
}
for (int i = 0; i < standard.size(); i++)
{
QString componentStr = "import Qt 4.6\nTextInput { text: \"" + standard.at(i) + "\" }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->text(), standard.at(i));
}
}
void tst_qfxtextinput::width()
{
// uses Font metrics to find the width for standard
{
QmlComponent textinputComponent(&engine, "import Qt 4.6\nTextInput { text: \"\" }", QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->width(), 1.);//1 for the cursor
}
for (int i = 0; i < standard.size(); i++)
{
QFont f;
QFontMetrics fm(f);
int metricWidth = fm.size(Qt::TextExpandTabs && Qt::TextShowMnemonic, standard.at(i)).width();
QString componentStr = "import Qt 4.6\nTextInput { text: \"" + standard.at(i) + "\" }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->width(), qreal(metricWidth) + 1.);//1 for the cursor
}
}
void tst_qfxtextinput::font()
{
//test size, then bold, then italic, then family
{
QString componentStr = "import Qt 4.6\nTextInput { font.pointSize: 40; text: \"Hello World\" }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->font().pointSize(), 40);
QCOMPARE(textinputObject->font().bold(), false);
QCOMPARE(textinputObject->font().italic(), false);
}
{
QString componentStr = "import Qt 4.6\nTextInput { font.bold: true; text: \"Hello World\" }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->font().bold(), true);
QCOMPARE(textinputObject->font().italic(), false);
}
{
QString componentStr = "import Qt 4.6\nTextInput { font.italic: true; text: \"Hello World\" }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->font().italic(), true);
QCOMPARE(textinputObject->font().bold(), false);
}
{
QString componentStr = "import Qt 4.6\nTextInput { font.family: \"Helvetica\"; text: \"Hello World\" }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->font().family(), QString("Helvetica"));
QCOMPARE(textinputObject->font().bold(), false);
QCOMPARE(textinputObject->font().italic(), false);
}
{
QString componentStr = "import Qt 4.6\nTextInput { font.family: \"\"; text: \"Hello World\" }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->font().family(), QString(""));
}
}
void tst_qfxtextinput::color()
{
//test style
for (int i = 0; i < colorStrings.size(); i++)
{
QString componentStr = "import Qt 4.6\nTextInput { color: \"" + colorStrings.at(i) + "\"; text: \"Hello World\" }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
//qDebug() << "textinputObject: " << textinputObject->color() << "vs. " << QColor(colorStrings.at(i));
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->color(), QColor(colorStrings.at(i)));
}
{
QString colorStr = "#AA001234";
QColor testColor("#001234");
testColor.setAlpha(170);
QString componentStr = "import Qt 4.6\nTextInput { color: \"" + colorStr + "\"; text: \"Hello World\" }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->color(), testColor);
}
}
void tst_qfxtextinput::selection()
{
QString testStr = standard[0];
QString componentStr = "import Qt 4.6\nTextInput { text: \""+ testStr +"\"; }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
//Test selection follows cursor
for(int i=0; i<= testStr.size(); i++) {
textinputObject->setCursorPosition(i);
QCOMPARE(textinputObject->cursorPosition(), i);
QCOMPARE(textinputObject->selectionStart(), i);
QCOMPARE(textinputObject->selectionEnd(), i);
QVERIFY(textinputObject->selectedText().isNull());
}
textinputObject->setCursorPosition(0);
QVERIFY(textinputObject->cursorPosition() == 0);
QVERIFY(textinputObject->selectionStart() == 0);
QVERIFY(textinputObject->selectionEnd() == 0);
QVERIFY(textinputObject->selectedText().isNull());
//Test selection
for(int i=0; i<= testStr.size(); i++) {
textinputObject->setSelectionEnd(i);
QCOMPARE(testStr.mid(0,i), textinputObject->selectedText());
}
for(int i=0; i<= testStr.size(); i++) {
textinputObject->setSelectionStart(i);
QCOMPARE(testStr.mid(i,testStr.size()-i), textinputObject->selectedText());
}
textinputObject->setCursorPosition(0);
QVERIFY(textinputObject->cursorPosition() == 0);
QVERIFY(textinputObject->selectionStart() == 0);
QVERIFY(textinputObject->selectionEnd() == 0);
QVERIFY(textinputObject->selectedText().isNull());
for(int i=0; i< testStr.size(); i++) {
textinputObject->setSelectionStart(i);
QCOMPARE(textinputObject->selectionEnd(), i);
QCOMPARE(testStr.mid(i,0), textinputObject->selectedText());
textinputObject->setSelectionEnd(i+1);
QCOMPARE(textinputObject->selectionStart(), i);
QCOMPARE(testStr.mid(i,1), textinputObject->selectedText());
}
for(int i= testStr.size() - 1; i>0; i--) {
textinputObject->setSelectionEnd(i);
QCOMPARE(testStr.mid(i,0), textinputObject->selectedText());
textinputObject->setSelectionStart(i-1);
QCOMPARE(testStr.mid(i-1,1), textinputObject->selectedText());
}
//Test Error Ignoring behaviour
textinputObject->setCursorPosition(0);
QVERIFY(textinputObject->selectedText().isNull());
textinputObject->setSelectionStart(-10);
QVERIFY(textinputObject->selectedText().isNull());
textinputObject->setSelectionStart(100);
QVERIFY(textinputObject->selectedText().isNull());
textinputObject->setSelectionEnd(-10);
QVERIFY(textinputObject->selectedText().isNull());
textinputObject->setSelectionEnd(100);
QVERIFY(textinputObject->selectedText().isNull());
textinputObject->setSelectionStart(0);
textinputObject->setSelectionEnd(10);
QVERIFY(textinputObject->selectedText().size() == 10);
textinputObject->setSelectionStart(-10);
QVERIFY(textinputObject->selectedText().size() == 10);
textinputObject->setSelectionStart(100);
QVERIFY(textinputObject->selectedText().size() == 10);
textinputObject->setSelectionEnd(-10);
QVERIFY(textinputObject->selectedText().size() == 10);
textinputObject->setSelectionEnd(100);
QVERIFY(textinputObject->selectedText().size() == 10);
}
void tst_qfxtextinput::maxLength()
{
QmlView *canvas = createView(SRCDIR "/data/navigation.qml");
canvas->execute();
canvas->show();
QVERIFY(canvas->root() != 0);
QFxItem *input = qobject_cast<QFxItem *>(qvariant_cast<QObject *>(canvas->root()->property("myInput")));
QVERIFY(input != 0);
//TODO: Me
}
void tst_qfxtextinput::masks()
{
QmlView *canvas = createView(SRCDIR "/data/navigation.qml");
canvas->execute();
canvas->show();
QVERIFY(canvas->root() != 0);
QFxItem *input = qobject_cast<QFxItem *>(qvariant_cast<QObject *>(canvas->root()->property("myInput")));
QVERIFY(input != 0);
//TODO: Me
}
void tst_qfxtextinput::validators()
{
QmlView *canvas = createView(SRCDIR "/data/navigation.qml");
canvas->execute();
canvas->show();
QVERIFY(canvas->root() != 0);
QFxItem *input = qobject_cast<QFxItem *>(qvariant_cast<QObject *>(canvas->root()->property("myInput")));
QVERIFY(input != 0);
//TODO: Me
}
/*
TextInput element should only handle left/right keys until the cursor reaches
the extent of the text, then they should ignore the keys.
*/
void tst_qfxtextinput::navigation()
{
QmlView *canvas = createView(SRCDIR "/data/navigation.qml");
canvas->execute();
canvas->show();
QVERIFY(canvas->root() != 0);
QFxItem *input = qobject_cast<QFxItem *>(qvariant_cast<QObject *>(canvas->root()->property("myInput")));
QVERIFY(input != 0);
QTRY_VERIFY(input->hasFocus() == true);
simulateKey(canvas, Qt::Key_Left);
QVERIFY(input->hasFocus() == false);
simulateKey(canvas, Qt::Key_Right);
QVERIFY(input->hasFocus() == true);
simulateKey(canvas, Qt::Key_Right);
QVERIFY(input->hasFocus() == false);
simulateKey(canvas, Qt::Key_Left);
QVERIFY(input->hasFocus() == true);
}
void tst_qfxtextinput::cursorDelegate()
{
//TODO:Get the QFxTextInput test passing first
}
void tst_qfxtextinput::simulateKey(QmlView *view, int key)
{
QKeyEvent press(QKeyEvent::KeyPress, key, 0);
QKeyEvent release(QKeyEvent::KeyRelease, key, 0);
QApplication::sendEvent(view, &press);
QApplication::sendEvent(view, &release);
}
QmlView *tst_qfxtextinput::createView(const QString &filename)
{
QmlView *canvas = new QmlView(0);
QFile file(filename);
file.open(QFile::ReadOnly);
QString xml = file.readAll();
canvas->setQml(xml, filename);
return canvas;
}
QTEST_MAIN(tst_qfxtextinput)
#include "tst_qfxtextinput.moc"
|
#include <qtest.h>
#include "../../../shared/util.h"
#include <QtDeclarative/qmlengine.h>
#include <QFile>
#include <QtDeclarative/qmlview.h>
#include <QFxTextInput>
#include <QDebug>
class tst_qfxtextinput : public QObject
{
Q_OBJECT
public:
tst_qfxtextinput();
private slots:
void text();
void width();
void font();
void color();
void selection();
void maxLength();
void masks();
void validators();
void cursorDelegate();
void navigation();
private:
void simulateKey(QmlView *, int key);
QmlView *createView(const QString &filename);
QmlEngine engine;
QStringList standard;
QStringList colorStrings;
};
tst_qfxtextinput::tst_qfxtextinput()
{
standard << "the quick brown fox jumped over the lazy dog"
<< "It's supercalifragisiticexpialidocious!"
<< "Hello, world!";
colorStrings << "aliceblue"
<< "antiquewhite"
<< "aqua"
<< "darkkhaki"
<< "darkolivegreen"
<< "dimgray"
<< "palevioletred"
<< "lightsteelblue"
<< "#000000"
<< "#AAAAAA"
<< "#FFFFFF"
<< "#2AC05F";
}
void tst_qfxtextinput::text()
{
{
QmlComponent textinputComponent(&engine, "import Qt 4.6\nTextInput { text: \"\" }", QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->text(), QString(""));
}
for (int i = 0; i < standard.size(); i++)
{
QString componentStr = "import Qt 4.6\nTextInput { text: \"" + standard.at(i) + "\" }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->text(), standard.at(i));
}
}
void tst_qfxtextinput::width()
{
// uses Font metrics to find the width for standard
{
QmlComponent textinputComponent(&engine, "import Qt 4.6\nTextInput { text: \"\" }", QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->width(), 1.);//1 for the cursor
}
for (int i = 0; i < standard.size(); i++)
{
QFont f;
QFontMetrics fm(f);
int metricWidth = fm.width(standard.at(i));
QString componentStr = "import Qt 4.6\nTextInput { text: \"" + standard.at(i) + "\" }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->width(), qreal(metricWidth) + 1.);//1 for the cursor
}
}
void tst_qfxtextinput::font()
{
//test size, then bold, then italic, then family
{
QString componentStr = "import Qt 4.6\nTextInput { font.pointSize: 40; text: \"Hello World\" }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->font().pointSize(), 40);
QCOMPARE(textinputObject->font().bold(), false);
QCOMPARE(textinputObject->font().italic(), false);
}
{
QString componentStr = "import Qt 4.6\nTextInput { font.bold: true; text: \"Hello World\" }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->font().bold(), true);
QCOMPARE(textinputObject->font().italic(), false);
}
{
QString componentStr = "import Qt 4.6\nTextInput { font.italic: true; text: \"Hello World\" }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->font().italic(), true);
QCOMPARE(textinputObject->font().bold(), false);
}
{
QString componentStr = "import Qt 4.6\nTextInput { font.family: \"Helvetica\"; text: \"Hello World\" }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->font().family(), QString("Helvetica"));
QCOMPARE(textinputObject->font().bold(), false);
QCOMPARE(textinputObject->font().italic(), false);
}
{
QString componentStr = "import Qt 4.6\nTextInput { font.family: \"\"; text: \"Hello World\" }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->font().family(), QString(""));
}
}
void tst_qfxtextinput::color()
{
//test style
for (int i = 0; i < colorStrings.size(); i++)
{
QString componentStr = "import Qt 4.6\nTextInput { color: \"" + colorStrings.at(i) + "\"; text: \"Hello World\" }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
//qDebug() << "textinputObject: " << textinputObject->color() << "vs. " << QColor(colorStrings.at(i));
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->color(), QColor(colorStrings.at(i)));
}
{
QString colorStr = "#AA001234";
QColor testColor("#001234");
testColor.setAlpha(170);
QString componentStr = "import Qt 4.6\nTextInput { color: \"" + colorStr + "\"; text: \"Hello World\" }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QCOMPARE(textinputObject->color(), testColor);
}
}
void tst_qfxtextinput::selection()
{
QString testStr = standard[0];
QString componentStr = "import Qt 4.6\nTextInput { text: \""+ testStr +"\"; }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
//Test selection follows cursor
for(int i=0; i<= testStr.size(); i++) {
textinputObject->setCursorPosition(i);
QCOMPARE(textinputObject->cursorPosition(), i);
QCOMPARE(textinputObject->selectionStart(), i);
QCOMPARE(textinputObject->selectionEnd(), i);
QVERIFY(textinputObject->selectedText().isNull());
}
textinputObject->setCursorPosition(0);
QVERIFY(textinputObject->cursorPosition() == 0);
QVERIFY(textinputObject->selectionStart() == 0);
QVERIFY(textinputObject->selectionEnd() == 0);
QVERIFY(textinputObject->selectedText().isNull());
//Test selection
for(int i=0; i<= testStr.size(); i++) {
textinputObject->setSelectionEnd(i);
QCOMPARE(testStr.mid(0,i), textinputObject->selectedText());
}
for(int i=0; i<= testStr.size(); i++) {
textinputObject->setSelectionStart(i);
QCOMPARE(testStr.mid(i,testStr.size()-i), textinputObject->selectedText());
}
textinputObject->setCursorPosition(0);
QVERIFY(textinputObject->cursorPosition() == 0);
QVERIFY(textinputObject->selectionStart() == 0);
QVERIFY(textinputObject->selectionEnd() == 0);
QVERIFY(textinputObject->selectedText().isNull());
for(int i=0; i< testStr.size(); i++) {
textinputObject->setSelectionStart(i);
QCOMPARE(textinputObject->selectionEnd(), i);
QCOMPARE(testStr.mid(i,0), textinputObject->selectedText());
textinputObject->setSelectionEnd(i+1);
QCOMPARE(textinputObject->selectionStart(), i);
QCOMPARE(testStr.mid(i,1), textinputObject->selectedText());
}
for(int i= testStr.size() - 1; i>0; i--) {
textinputObject->setSelectionEnd(i);
QCOMPARE(testStr.mid(i,0), textinputObject->selectedText());
textinputObject->setSelectionStart(i-1);
QCOMPARE(testStr.mid(i-1,1), textinputObject->selectedText());
}
//Test Error Ignoring behaviour
textinputObject->setCursorPosition(0);
QVERIFY(textinputObject->selectedText().isNull());
textinputObject->setSelectionStart(-10);
QVERIFY(textinputObject->selectedText().isNull());
textinputObject->setSelectionStart(100);
QVERIFY(textinputObject->selectedText().isNull());
textinputObject->setSelectionEnd(-10);
QVERIFY(textinputObject->selectedText().isNull());
textinputObject->setSelectionEnd(100);
QVERIFY(textinputObject->selectedText().isNull());
textinputObject->setSelectionStart(0);
textinputObject->setSelectionEnd(10);
QVERIFY(textinputObject->selectedText().size() == 10);
textinputObject->setSelectionStart(-10);
QVERIFY(textinputObject->selectedText().size() == 10);
textinputObject->setSelectionStart(100);
QVERIFY(textinputObject->selectedText().size() == 10);
textinputObject->setSelectionEnd(-10);
QVERIFY(textinputObject->selectedText().size() == 10);
textinputObject->setSelectionEnd(100);
QVERIFY(textinputObject->selectedText().size() == 10);
}
void tst_qfxtextinput::maxLength()
{
QString componentStr = "import Qt 4.6\nTextInput { maximumLength: 10; }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
QVERIFY(textinputObject->text().isEmpty());
foreach(const QString &str, standard){
QVERIFY(textinputObject->text().length() <= 10);
textinputObject->setText(str);
QVERIFY(textinputObject->text().length() <= 10);
}
//TODO: Simulated keypress input adding 11 chars at a time
}
void tst_qfxtextinput::masks()
{
QString componentStr = "import Qt 4.6\nTextInput { maximumLength: 10; }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
//TODO: Me
}
void tst_qfxtextinput::validators()
{
QString componentStr = "import Qt 4.6\nTextInput { maximumLength: 10; }";
QmlComponent textinputComponent(&engine, componentStr.toLatin1(), QUrl());
QFxTextInput *textinputObject = qobject_cast<QFxTextInput*>(textinputComponent.create());
QVERIFY(textinputObject != 0);
//TODO: Me
}
/*
TextInput element should only handle left/right keys until the cursor reaches
the extent of the text, then they should ignore the keys.
*/
void tst_qfxtextinput::navigation()
{
QmlView *canvas = createView(SRCDIR "/data/navigation.qml");
canvas->execute();
canvas->show();
QVERIFY(canvas->root() != 0);
QFxItem *input = qobject_cast<QFxItem *>(qvariant_cast<QObject *>(canvas->root()->property("myInput")));
QVERIFY(input != 0);
QTRY_VERIFY(input->hasFocus() == true);
simulateKey(canvas, Qt::Key_Left);
QVERIFY(input->hasFocus() == false);
simulateKey(canvas, Qt::Key_Right);
QVERIFY(input->hasFocus() == true);
simulateKey(canvas, Qt::Key_Right);
QVERIFY(input->hasFocus() == false);
simulateKey(canvas, Qt::Key_Left);
QVERIFY(input->hasFocus() == true);
}
void tst_qfxtextinput::cursorDelegate()
{
//TODO:Get the QFxTextEdit test passing first
}
void tst_qfxtextinput::simulateKey(QmlView *view, int key)
{
QKeyEvent press(QKeyEvent::KeyPress, key, 0);
QKeyEvent release(QKeyEvent::KeyRelease, key, 0);
QApplication::sendEvent(view, &press);
QApplication::sendEvent(view, &release);
}
QmlView *tst_qfxtextinput::createView(const QString &filename)
{
QmlView *canvas = new QmlView(0);
QFile file(filename);
file.open(QFile::ReadOnly);
QString xml = file.readAll();
canvas->setQml(xml, filename);
return canvas;
}
QTEST_MAIN(tst_qfxtextinput)
#include "tst_qfxtextinput.moc"
|
fix QFxTextInput Autotest
|
fix QFxTextInput Autotest
Note that a test based on focus is still failing, presumably due to
recent focus changes. Haven't yet investigated if it should be failing
or not.
|
C++
|
lgpl-2.1
|
pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,pruiz/wkhtmltopdf-qt,igor-sfdc/qt-wk,igor-sfdc/qt-wk,igor-sfdc/qt-wk,igor-sfdc/qt-wk,igor-sfdc/qt-wk
|
978a7f7d6dfe432937e20864e19a4b9647369c00
|
src/test/streams_tests.cpp
|
src/test/streams_tests.cpp
|
// Copyright (c) 2012-2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "streams.h"
#include "support/allocators/zeroafterfree.h"
#include "test/test_bitcoin.h"
#include <boost/assign/std/vector.hpp> // for 'operator+=()'
#include <boost/assert.hpp>
#include <boost/test/unit_test.hpp>
using namespace std;
using namespace boost::assign; // bring 'operator+=()' into scope
BOOST_FIXTURE_TEST_SUITE(streams_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(streams_serializedata_xor)
{
std::vector<char> in;
std::vector<char> expected_xor;
std::vector<unsigned char> key;
CDataStream ds(in, 0, 0);
// Degenerate case
key += '\x00','\x00';
ds.Xor(key);
BOOST_CHECK_EQUAL(
std::string(expected_xor.begin(), expected_xor.end()),
std::string(ds.begin(), ds.end()));
in += '\x0f','\xf0';
expected_xor += '\xf0','\x0f';
// Single character key
ds.clear();
ds.insert(ds.begin(), in.begin(), in.end());
key.clear();
key += '\xff';
ds.Xor(key);
BOOST_CHECK_EQUAL(
std::string(expected_xor.begin(), expected_xor.end()),
std::string(ds.begin(), ds.end()));
// Multi character key
in.clear();
expected_xor.clear();
in += '\xf0','\x0f';
expected_xor += '\x0f','\x00';
ds.clear();
ds.insert(ds.begin(), in.begin(), in.end());
key.clear();
key += '\xff','\x0f';
ds.Xor(key);
BOOST_CHECK_EQUAL(
std::string(expected_xor.begin(), expected_xor.end()),
std::string(ds.begin(), ds.end()));
}
BOOST_AUTO_TEST_SUITE_END()
|
// Copyright (c) 2012-2015 The Bitcoin Core developers
// Copyright (c) 2015-2017 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "streams.h"
#include "support/allocators/zeroafterfree.h"
#include "test/test_bitcoin.h"
#include <boost/assign/std/vector.hpp> // for 'operator+=()'
#include <boost/assert.hpp>
#include <boost/test/unit_test.hpp>
using namespace std;
using namespace boost::assign; // bring 'operator+=()' into scope
BOOST_FIXTURE_TEST_SUITE(streams_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(streams_serializedata_xor)
{
std::vector<char> in;
std::vector<char> expected_xor;
std::vector<unsigned char> key;
CDataStream ds(in, 0, 0);
// Degenerate case
key += '\x00','\x00';
ds.Xor(key);
BOOST_CHECK_EQUAL(
std::string(expected_xor.begin(), expected_xor.end()),
std::string(ds.begin(), ds.end()));
in += '\x0f','\xf0';
expected_xor += '\xf0','\x0f';
// Single character key
ds.clear();
ds.insert(ds.begin(), in.begin(), in.end());
key.clear();
key += '\xff';
ds.Xor(key);
BOOST_CHECK_EQUAL(
std::string(expected_xor.begin(), expected_xor.end()),
std::string(ds.begin(), ds.end()));
// Multi character key
in.clear();
expected_xor.clear();
in += '\xf0','\x0f';
expected_xor += '\x0f','\x00';
ds.clear();
ds.insert(ds.begin(), in.begin(), in.end());
key.clear();
key += '\xff','\x0f';
ds.Xor(key);
BOOST_CHECK_EQUAL(
std::string(expected_xor.begin(), expected_xor.end()),
std::string(ds.begin(), ds.end()));
}
BOOST_AUTO_TEST_CASE(streams)
{
// Smallest possible example
CDataStream ssx(SER_DISK, CLIENT_VERSION);
BOOST_CHECK_EQUAL(HexStr(ssx.begin(), ssx.end()), "");
}
BOOST_AUTO_TEST_SUITE_END()
|
Add the smallest example of a stream to streams_tests.cpp
|
Add the smallest example of a stream to streams_tests.cpp
|
C++
|
mit
|
Bitcoin-com/BUcash,BitcoinUnlimited/BitcoinUnlimited,Justaphf/BitcoinUnlimited,BitcoinUnlimited/BitcoinUnlimited,Justaphf/BitcoinUnlimited,Bitcoin-com/BUcash,Justaphf/BitcoinUnlimited,Justaphf/BitcoinUnlimited,BitcoinUnlimited/BitcoinUnlimited,BitcoinUnlimited/BitcoinUnlimited,Justaphf/BitcoinUnlimited,BitcoinUnlimited/BitcoinUnlimited,Bitcoin-com/BUcash,BitcoinUnlimited/BitcoinUnlimited,Justaphf/BitcoinUnlimited,Bitcoin-com/BUcash,Bitcoin-com/BUcash,Bitcoin-com/BUcash
|
4e3e95d27e0db9bde0dfb81c35c538b6fab36996
|
src/qpdf/page.cpp
|
src/qpdf/page.cpp
|
/*
* 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/.
*
* Copyright (C) 2017, James R. Barlow (https://github.com/jbarlow83/)
*/
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cctype>
#include "pikepdf.h"
#include "parsers.h"
#include <qpdf/QPDFPageObjectHelper.hh>
#include <qpdf/QPDFPageLabelDocumentHelper.hh>
#include <qpdf/Pipeline.hh>
#include <qpdf/Pl_Buffer.hh>
py::size_t page_index(QPDF &owner, QPDFObjectHandle page)
{
if (&owner != page.getOwningQPDF())
throw py::value_error("Page is not in this Pdf");
int idx;
try {
idx = owner.findPage(page);
} catch (const QPDFExc &e) {
if (std::string(e.what()).find("page object not referenced") >= 0)
throw py::value_error("Page is not consistently registered with Pdf");
throw e;
}
if (idx < 0) {
// LCOV_EXCL_START
throw std::logic_error("Page index is negative");
// LCOV_EXCL_STOP
}
return idx;
}
std::string label_string_from_dict(QPDFObjectHandle label_dict)
{
auto impl =
py::module_::import("pikepdf._cpphelpers").attr("label_from_label_dict");
py::str result = impl(label_dict);
return result;
}
void init_page(py::module_ &m)
{
py::class_<QPDFPageObjectHelper,
std::shared_ptr<QPDFPageObjectHelper>,
QPDFObjectHelper>(m, "Page")
.def(py::init<QPDFObjectHandle &>())
.def(py::init([](QPDFPageObjectHelper &poh) {
return QPDFPageObjectHelper(poh.getObjectHandle());
}))
.def(
"__copy__", [](QPDFPageObjectHelper &poh) { return poh.shallowCopyPage(); })
.def_property_readonly("_images", &QPDFPageObjectHelper::getImages)
.def("_get_mediabox", &QPDFPageObjectHelper::getMediaBox)
.def("_get_cropbox", &QPDFPageObjectHelper::getCropBox)
.def("_get_trimbox", &QPDFPageObjectHelper::getTrimBox)
.def(
"externalize_inline_images",
[](QPDFPageObjectHelper &poh, size_t min_size = 0, bool shallow = false) {
return poh.externalizeInlineImages(min_size, shallow);
},
py::arg("min_size") = 0,
py::arg("shallow") = false,
R"~~~(
Convert inlines image to normal (external) images.
Args:
min_size (int): minimum size in bytes
shallow (bool): If False, recurse into nested Form XObjects.
If True, do not recurse.
)~~~")
.def("rotate",
&QPDFPageObjectHelper::rotatePage,
py::arg("angle"),
py::arg("relative"),
R"~~~(
Rotate a page.
If ``relative`` is ``False``, set the rotation of the
page to angle. Otherwise, add angle to the rotation of the
page. ``angle`` must be a multiple of ``90``. Adding ``90`` to
the rotation rotates clockwise by ``90`` degrees.
)~~~")
.def("contents_coalesce",
&QPDFPageObjectHelper::coalesceContentStreams,
R"~~~(
Coalesce a page's content streams.
A page's content may be a
stream or an array of streams. If this page's content is an
array, concatenate the streams into a single stream. This can
be useful when working with files that split content streams in
arbitrary spots, such as in the middle of a token, as that can
confuse some software.
)~~~")
.def(
"_contents_add",
[](QPDFPageObjectHelper &poh, QPDFObjectHandle &contents, bool prepend) {
return poh.addPageContents(contents, prepend);
},
py::arg("contents"),
py::kw_only(),
py::arg("prepend") = false)
.def(
"_contents_add",
[](QPDFPageObjectHelper &poh, py::bytes contents, bool prepend) {
auto q = poh.getObjectHandle().getOwningQPDF();
if (!q) {
// LCOV_EXCL_START
throw std::logic_error("QPDFPageObjectHelper not attached to QPDF");
// LCOV_EXCL_STOP
}
auto stream = QPDFObjectHandle::newStream(q, contents);
return poh.addPageContents(stream, prepend);
},
py::arg("contents"),
py::kw_only(),
py::arg("prepend") = false)
.def("remove_unreferenced_resources",
&QPDFPageObjectHelper::removeUnreferencedResources,
R"~~~(
Removes from the resources dictionary any object not referenced in the content stream.
A page's resources dictionary maps names to objects elsewhere
in the file. This method walks through a page's contents and
keeps tracks of which resources are referenced somewhere in the
contents. Then it removes from the resources dictionary any
object that is not referenced in the contents. This
method is used by page splitting code to avoid copying unused
objects in files that used shared resource dictionaries across
multiple pages.
)~~~")
.def("as_form_xobject",
&QPDFPageObjectHelper::getFormXObjectForPage,
py::arg("handle_transformations") = true,
R"~~~(
Return a form XObject that draws this page.
This is useful for
n-up operations, underlay, overlay, thumbnail generation, or
any other case in which it is useful to replicate the contents
of a page in some other context. The dictionaries are shallow
copies of the original page dictionary, and the contents are
coalesced from the page's contents. The resulting object handle
is not referenced anywhere.
Args:
handle_transformations (bool): If True, the resulting form
XObject's ``/Matrix`` will be set to replicate rotation
(``/Rotate``) and scaling (``/UserUnit``) in the page's
dictionary. In this way, the page's transformations will
be preserved when placing this object on another page.
)~~~")
.def(
"calc_form_xobject_placement",
[](QPDFPageObjectHelper &poh,
QPDFObjectHandle formx,
QPDFObjectHandle name,
QPDFObjectHandle::Rectangle rect,
bool invert_transformations,
bool allow_shrink,
bool allow_expand) -> py::bytes {
return py::bytes(poh.placeFormXObject(formx,
name.getName(),
rect,
invert_transformations,
allow_shrink,
allow_expand));
},
py::arg("formx"),
py::arg("name"),
py::arg("rect"),
py::kw_only(),
py::arg("invert_transformations") = true,
py::arg("allow_shrink") = true,
py::arg("allow_expand") = false,
R"~~~(
Generate content stream segment to place a Form XObject on this page.
The content stream segment must be then be added to the page's
content stream.
The default keyword parameters will preserve the aspect ratio.
Args:
formx: The Form XObject to place.
name: The name of the Form XObject in this page's /Resources
dictionary.
rect: Rectangle describing the desired placement of the Form
XObject.
invert_transformations: Apply /Rotate and /UserUnit scaling
when determining FormX Object placement.
allow_shrink: Allow the Form XObject to take less than the
full dimensions of rect.
allow_expand: Expand the Form XObject to occupy all of rect.
.. versionadded:: 2.14
)~~~")
.def(
"get_filtered_contents",
[](QPDFPageObjectHelper &poh,
QPDFObjectHandle::TokenFilter &tf) -> py::bytes {
Pl_Buffer pl_buffer("filter_page");
poh.filterContents(&tf, &pl_buffer);
PointerHolder<Buffer> buf(pl_buffer.getBuffer());
auto data = reinterpret_cast<const char *>(buf->getBuffer());
auto size = buf->getSize();
return py::bytes(data, size);
},
py::arg("tf"),
R"~~~(
Apply a :class:`pikepdf.TokenFilter` to a content stream, without modifying it.
This may be used when the results of a token filter do not need
to be applied, such as when filtering is being used to retrieve
information rather than edit the content stream.
Note that it is possible to create a subclassed ``TokenFilter``
that saves information of interest to its object attributes; it
is not necessary to return data in the content stream.
To modify the content stream, use :meth:`pikepdf.Page.add_content_token_filter`.
Returns:
The modified content stream.
)~~~")
.def(
"add_content_token_filter",
[](QPDFPageObjectHelper &poh,
PointerHolder<QPDFObjectHandle::TokenFilter> tf) {
// TokenFilters may be processed after the Python objects have gone
// out of scope, so we need to keep them alive by attaching them to
// the corresponding QPDF object.
auto pyqpdf = py::cast(poh.getObjectHandle().getOwningQPDF());
auto pytf = py::cast(tf);
py::detail::keep_alive_impl(pyqpdf, pytf);
poh.addContentTokenFilter(tf);
},
py::arg("tf"),
R"~~~(
Attach a :class:`pikepdf.TokenFilter` to a page's content stream.
This function applies token filters lazily, if/when the page's
content stream is read for any reason, such as when the PDF is
saved. If never access, the token filter is not applied.
Multiple token filters may be added to a page/content stream.
Token filters may not be removed after being attached to a Pdf.
Close and reopen the Pdf to remove token filters.
If the page's contents is an array of streams, it is coalesced.
)~~~")
.def(
"parse_contents",
[](QPDFPageObjectHelper &poh, PyParserCallbacks &parsercallbacks) {
poh.parseContents(&parsercallbacks);
},
R"~~~(
Parse a page's content streams using a :class:`pikepdf.StreamParser`.
The content stream may be interpreted by the StreamParser but is
not altered.
If the page's contents is an array of streams, it is coalesced.
)~~~")
.def_property_readonly(
"index",
[](QPDFPageObjectHelper &poh) {
auto this_page = poh.getObjectHandle();
auto p_owner = this_page.getOwningQPDF();
if (!p_owner)
throw py::value_error("Page is not attached to a Pdf");
auto &owner = *p_owner;
return page_index(owner, this_page);
},
R"~~~(
Returns the zero-based index of this page in the pages list.
That is, returns ``n`` such that ``pdf.pages[n] == this_page``.
A ``ValueError`` exception is thrown if the page is not attached
to this ``Pdf``.
.. versionadded:: 2.2
)~~~")
.def_property_readonly(
"label",
[](QPDFPageObjectHelper &poh) {
auto this_page = poh.getObjectHandle();
auto p_owner = this_page.getOwningQPDF();
if (!p_owner)
throw py::value_error("Page is not attached to a Pdf");
auto &owner = *p_owner;
auto index = page_index(owner, this_page);
QPDFPageLabelDocumentHelper pldh(owner);
auto label_dict = pldh.getLabelForPage(index);
if (label_dict.isNull())
return std::to_string(index + 1);
return label_string_from_dict(label_dict);
},
R"~~~(
Returns the page label for this page, accounting for section numbers.
For example, if the PDF defines a preface with lower case Roman
numerals (i, ii, iii...), followed by standard numbers, followed
by an appendix (A-1, A-2, ...), this function returns the appropriate
label as a string.
It is possible for a PDF to define page labels such that multiple
pages have the same labels. Labels are not guaranteed to
be unique.
.. versionadded:: 2.2
.. versionchanged:: 2.9
Returns the ordinary page number if no special rules for page
numbers are defined.
)~~~");
}
|
/*
* 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/.
*
* Copyright (C) 2017, James R. Barlow (https://github.com/jbarlow83/)
*/
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cctype>
#include "pikepdf.h"
#include "parsers.h"
#include <qpdf/QPDFPageObjectHelper.hh>
#include <qpdf/QPDFPageLabelDocumentHelper.hh>
#include <qpdf/Pipeline.hh>
#include <qpdf/Pl_Buffer.hh>
py::size_t page_index(QPDF &owner, QPDFObjectHandle page)
{
if (&owner != page.getOwningQPDF())
throw py::value_error("Page is not in this Pdf");
int idx;
try {
idx = owner.findPage(page);
} catch (const QPDFExc &e) {
if (std::string(e.what()).find("page object not referenced") >= 0)
throw py::value_error("Page is not consistently registered with Pdf");
throw e;
}
if (idx < 0) {
// LCOV_EXCL_START
throw std::logic_error("Page index is negative");
// LCOV_EXCL_STOP
}
return idx;
}
std::string label_string_from_dict(QPDFObjectHandle label_dict)
{
auto impl =
py::module_::import("pikepdf._cpphelpers").attr("label_from_label_dict");
py::str result = impl(label_dict);
return result;
}
void init_page(py::module_ &m)
{
py::class_<QPDFPageObjectHelper,
std::shared_ptr<QPDFPageObjectHelper>,
QPDFObjectHelper>(m, "Page")
.def(py::init<QPDFObjectHandle &>())
.def(py::init([](QPDFPageObjectHelper &poh) {
return QPDFPageObjectHelper(poh.getObjectHandle());
}))
.def(
"__copy__", [](QPDFPageObjectHelper &poh) { return poh.shallowCopyPage(); })
.def_property_readonly("_images", &QPDFPageObjectHelper::getImages)
.def("_get_mediabox", &QPDFPageObjectHelper::getMediaBox)
.def("_get_cropbox", &QPDFPageObjectHelper::getCropBox)
.def("_get_trimbox", &QPDFPageObjectHelper::getTrimBox)
.def(
"externalize_inline_images",
[](QPDFPageObjectHelper &poh, size_t min_size = 0, bool shallow = false) {
return poh.externalizeInlineImages(min_size, shallow);
},
py::arg("min_size") = 0,
py::arg("shallow") = false,
R"~~~(
Convert inlines image to normal (external) images.
Args:
min_size (int): minimum size in bytes
shallow (bool): If False, recurse into nested Form XObjects.
If True, do not recurse.
)~~~")
.def("rotate",
&QPDFPageObjectHelper::rotatePage,
py::arg("angle"),
py::arg("relative"),
R"~~~(
Rotate a page.
If ``relative`` is ``False``, set the rotation of the
page to angle. Otherwise, add angle to the rotation of the
page. ``angle`` must be a multiple of ``90``. Adding ``90`` to
the rotation rotates clockwise by ``90`` degrees.
)~~~")
.def("contents_coalesce",
&QPDFPageObjectHelper::coalesceContentStreams, // LCOV_EXCL_LINE
R"~~~(
Coalesce a page's content streams.
A page's content may be a
stream or an array of streams. If this page's content is an
array, concatenate the streams into a single stream. This can
be useful when working with files that split content streams in
arbitrary spots, such as in the middle of a token, as that can
confuse some software.
)~~~")
.def(
"_contents_add",
[](QPDFPageObjectHelper &poh, QPDFObjectHandle &contents, bool prepend) {
return poh.addPageContents(contents, prepend);
},
py::arg("contents"),
py::kw_only(),
py::arg("prepend") = false)
.def(
"_contents_add",
[](QPDFPageObjectHelper &poh, py::bytes contents, bool prepend) {
auto q = poh.getObjectHandle().getOwningQPDF();
if (!q) {
// LCOV_EXCL_START
throw std::logic_error("QPDFPageObjectHelper not attached to QPDF");
// LCOV_EXCL_STOP
}
auto stream = QPDFObjectHandle::newStream(q, contents);
return poh.addPageContents(stream, prepend);
},
py::arg("contents"),
py::kw_only(),
py::arg("prepend") = false)
.def("remove_unreferenced_resources",
&QPDFPageObjectHelper::removeUnreferencedResources,
R"~~~(
Removes from the resources dictionary any object not referenced in the content stream.
A page's resources dictionary maps names to objects elsewhere
in the file. This method walks through a page's contents and
keeps tracks of which resources are referenced somewhere in the
contents. Then it removes from the resources dictionary any
object that is not referenced in the contents. This
method is used by page splitting code to avoid copying unused
objects in files that used shared resource dictionaries across
multiple pages.
)~~~")
.def("as_form_xobject",
&QPDFPageObjectHelper::getFormXObjectForPage,
py::arg("handle_transformations") = true,
R"~~~(
Return a form XObject that draws this page.
This is useful for
n-up operations, underlay, overlay, thumbnail generation, or
any other case in which it is useful to replicate the contents
of a page in some other context. The dictionaries are shallow
copies of the original page dictionary, and the contents are
coalesced from the page's contents. The resulting object handle
is not referenced anywhere.
Args:
handle_transformations (bool): If True, the resulting form
XObject's ``/Matrix`` will be set to replicate rotation
(``/Rotate``) and scaling (``/UserUnit``) in the page's
dictionary. In this way, the page's transformations will
be preserved when placing this object on another page.
)~~~")
.def(
"calc_form_xobject_placement",
[](QPDFPageObjectHelper &poh,
QPDFObjectHandle formx,
QPDFObjectHandle name,
QPDFObjectHandle::Rectangle rect,
bool invert_transformations,
bool allow_shrink,
bool allow_expand) -> py::bytes {
return py::bytes(poh.placeFormXObject(formx,
name.getName(),
rect,
invert_transformations,
allow_shrink,
allow_expand));
},
py::arg("formx"),
py::arg("name"),
py::arg("rect"),
py::kw_only(),
py::arg("invert_transformations") = true,
py::arg("allow_shrink") = true,
py::arg("allow_expand") = false,
R"~~~(
Generate content stream segment to place a Form XObject on this page.
The content stream segment must be then be added to the page's
content stream.
The default keyword parameters will preserve the aspect ratio.
Args:
formx: The Form XObject to place.
name: The name of the Form XObject in this page's /Resources
dictionary.
rect: Rectangle describing the desired placement of the Form
XObject.
invert_transformations: Apply /Rotate and /UserUnit scaling
when determining FormX Object placement.
allow_shrink: Allow the Form XObject to take less than the
full dimensions of rect.
allow_expand: Expand the Form XObject to occupy all of rect.
.. versionadded:: 2.14
)~~~")
.def(
"get_filtered_contents",
[](QPDFPageObjectHelper &poh,
QPDFObjectHandle::TokenFilter &tf) -> py::bytes {
Pl_Buffer pl_buffer("filter_page");
poh.filterContents(&tf, &pl_buffer);
PointerHolder<Buffer> buf(pl_buffer.getBuffer());
auto data = reinterpret_cast<const char *>(buf->getBuffer());
auto size = buf->getSize();
return py::bytes(data, size);
},
py::arg("tf"),
R"~~~(
Apply a :class:`pikepdf.TokenFilter` to a content stream, without modifying it.
This may be used when the results of a token filter do not need
to be applied, such as when filtering is being used to retrieve
information rather than edit the content stream.
Note that it is possible to create a subclassed ``TokenFilter``
that saves information of interest to its object attributes; it
is not necessary to return data in the content stream.
To modify the content stream, use :meth:`pikepdf.Page.add_content_token_filter`.
Returns:
The modified content stream.
)~~~")
.def(
"add_content_token_filter",
[](QPDFPageObjectHelper &poh,
PointerHolder<QPDFObjectHandle::TokenFilter> tf) {
// TokenFilters may be processed after the Python objects have gone
// out of scope, so we need to keep them alive by attaching them to
// the corresponding QPDF object.
auto pyqpdf = py::cast(poh.getObjectHandle().getOwningQPDF());
auto pytf = py::cast(tf);
py::detail::keep_alive_impl(pyqpdf, pytf);
poh.addContentTokenFilter(tf);
},
py::arg("tf"),
R"~~~(
Attach a :class:`pikepdf.TokenFilter` to a page's content stream.
This function applies token filters lazily, if/when the page's
content stream is read for any reason, such as when the PDF is
saved. If never access, the token filter is not applied.
Multiple token filters may be added to a page/content stream.
Token filters may not be removed after being attached to a Pdf.
Close and reopen the Pdf to remove token filters.
If the page's contents is an array of streams, it is coalesced.
)~~~")
.def(
"parse_contents",
[](QPDFPageObjectHelper &poh, PyParserCallbacks &parsercallbacks) {
poh.parseContents(&parsercallbacks);
},
R"~~~(
Parse a page's content streams using a :class:`pikepdf.StreamParser`.
The content stream may be interpreted by the StreamParser but is
not altered.
If the page's contents is an array of streams, it is coalesced.
)~~~")
.def_property_readonly(
"index",
[](QPDFPageObjectHelper &poh) {
auto this_page = poh.getObjectHandle();
auto p_owner = this_page.getOwningQPDF();
if (!p_owner)
throw py::value_error("Page is not attached to a Pdf");
auto &owner = *p_owner;
return page_index(owner, this_page);
},
R"~~~(
Returns the zero-based index of this page in the pages list.
That is, returns ``n`` such that ``pdf.pages[n] == this_page``.
A ``ValueError`` exception is thrown if the page is not attached
to this ``Pdf``.
.. versionadded:: 2.2
)~~~")
.def_property_readonly(
"label",
[](QPDFPageObjectHelper &poh) {
auto this_page = poh.getObjectHandle();
auto p_owner = this_page.getOwningQPDF();
if (!p_owner)
throw py::value_error("Page is not attached to a Pdf");
auto &owner = *p_owner;
auto index = page_index(owner, this_page);
QPDFPageLabelDocumentHelper pldh(owner);
auto label_dict = pldh.getLabelForPage(index);
if (label_dict.isNull())
return std::to_string(index + 1);
return label_string_from_dict(label_dict);
},
R"~~~(
Returns the page label for this page, accounting for section numbers.
For example, if the PDF defines a preface with lower case Roman
numerals (i, ii, iii...), followed by standard numbers, followed
by an appendix (A-1, A-2, ...), this function returns the appropriate
label as a string.
It is possible for a PDF to define page labels such that multiple
pages have the same labels. Labels are not guaranteed to
be unique.
.. versionadded:: 2.2
.. versionchanged:: 2.9
Returns the ordinary page number if no special rules for page
numbers are defined.
)~~~");
}
|
Exclude from coverag e(since it misses this line)
|
Exclude from coverag e(since it misses this line)
|
C++
|
mpl-2.0
|
pikepdf/pikepdf,pikepdf/pikepdf,pikepdf/pikepdf
|
aefbf4ca73e802a9149ecba19bf9e71e0acd843e
|
src/qpdf/page.cpp
|
src/qpdf/page.cpp
|
// SPDX-FileCopyrightText: 2022 James R. Barlow
// SPDX-License-Identifier: MPL-2.0
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cctype>
#include "pikepdf.h"
#include "parsers.h"
#include <qpdf/QPDFPageObjectHelper.hh>
#include <qpdf/QPDFPageLabelDocumentHelper.hh>
#include <qpdf/Pipeline.hh>
#include <qpdf/Pl_Buffer.hh>
py::size_t page_index(QPDF &owner, QPDFObjectHandle page)
{
if (&owner != page.getOwningQPDF())
throw py::value_error("Page is not in this Pdf");
int idx;
try {
idx = owner.findPage(page);
} catch (const QPDFExc &e) {
if (std::string(e.what()).find("page object not referenced") >= 0)
throw py::value_error("Page is not consistently registered with Pdf");
throw e;
}
if (idx < 0) {
// LCOV_EXCL_START
throw std::logic_error("Page index is negative");
// LCOV_EXCL_STOP
}
return idx;
}
std::string label_string_from_dict(QPDFObjectHandle label_dict)
{
auto impl =
py::module_::import("pikepdf._cpphelpers").attr("label_from_label_dict");
py::str result = impl(label_dict);
return result;
}
void init_page(py::module_ &m)
{
py::class_<QPDFPageObjectHelper,
std::shared_ptr<QPDFPageObjectHelper>,
QPDFObjectHelper>(m, "Page")
.def(py::init<QPDFObjectHandle &>())
.def(py::init([](QPDFPageObjectHelper &poh) {
return QPDFPageObjectHelper(poh.getObjectHandle());
}))
.def(
"__copy__", [](QPDFPageObjectHelper &poh) { return poh.shallowCopyPage(); })
.def_property_readonly("_images", &QPDFPageObjectHelper::getImages)
.def("_get_mediabox", &QPDFPageObjectHelper::getMediaBox)
.def("_get_cropbox", &QPDFPageObjectHelper::getCropBox)
.def("_get_trimbox", &QPDFPageObjectHelper::getTrimBox)
.def(
"externalize_inline_images",
[](QPDFPageObjectHelper &poh, size_t min_size = 0, bool shallow = false) {
return poh.externalizeInlineImages(min_size, shallow);
},
py::arg("min_size") = 0,
py::arg("shallow") = false,
R"~~~(
Convert inlines image to normal (external) images.
Args:
min_size (int): minimum size in bytes
shallow (bool): If False, recurse into nested Form XObjects.
If True, do not recurse.
)~~~")
.def("rotate",
&QPDFPageObjectHelper::rotatePage,
py::arg("angle"),
py::arg("relative"),
R"~~~(
Rotate a page.
If ``relative`` is ``False``, set the rotation of the
page to angle. Otherwise, add angle to the rotation of the
page. ``angle`` must be a multiple of ``90``. Adding ``90`` to
the rotation rotates clockwise by ``90`` degrees.
)~~~")
.def("contents_coalesce",
&QPDFPageObjectHelper::coalesceContentStreams, // LCOV_EXCL_LINE
R"~~~(
Coalesce a page's content streams.
A page's content may be a
stream or an array of streams. If this page's content is an
array, concatenate the streams into a single stream. This can
be useful when working with files that split content streams in
arbitrary spots, such as in the middle of a token, as that can
confuse some software.
)~~~")
.def(
"_contents_add",
[](QPDFPageObjectHelper &poh, QPDFObjectHandle &contents, bool prepend) {
return poh.addPageContents(contents, prepend);
},
py::arg("contents"), // LCOV_EXCL_LINE
py::kw_only(),
py::arg("prepend") = false)
.def(
"_contents_add",
[](QPDFPageObjectHelper &poh, py::bytes contents, bool prepend) {
auto q = poh.getObjectHandle().getOwningQPDF();
if (!q) {
// LCOV_EXCL_START
throw std::logic_error("QPDFPageObjectHelper not attached to QPDF");
// LCOV_EXCL_STOP
}
auto stream = QPDFObjectHandle::newStream(q, contents);
return poh.addPageContents(stream, prepend);
},
py::arg("contents"),
py::kw_only(),
py::arg("prepend") = false)
.def("remove_unreferenced_resources",
&QPDFPageObjectHelper::removeUnreferencedResources,
R"~~~(
Removes from the resources dictionary any object not referenced in the content stream.
A page's resources dictionary maps names to objects elsewhere
in the file. This method walks through a page's contents and
keeps tracks of which resources are referenced somewhere in the
contents. Then it removes from the resources dictionary any
object that is not referenced in the contents. This
method is used by page splitting code to avoid copying unused
objects in files that used shared resource dictionaries across
multiple pages.
)~~~")
.def("as_form_xobject",
&QPDFPageObjectHelper::getFormXObjectForPage, // LCOV_EXCL_LINE
py::arg("handle_transformations") = true,
R"~~~(
Return a form XObject that draws this page.
This is useful for
n-up operations, underlay, overlay, thumbnail generation, or
any other case in which it is useful to replicate the contents
of a page in some other context. The dictionaries are shallow
copies of the original page dictionary, and the contents are
coalesced from the page's contents. The resulting object handle
is not referenced anywhere.
Args:
handle_transformations (bool): If True, the resulting form
XObject's ``/Matrix`` will be set to replicate rotation
(``/Rotate``) and scaling (``/UserUnit``) in the page's
dictionary. In this way, the page's transformations will
be preserved when placing this object on another page.
)~~~")
.def(
"calc_form_xobject_placement",
[](QPDFPageObjectHelper &poh,
QPDFObjectHandle formx,
QPDFObjectHandle name,
QPDFObjectHandle::Rectangle rect,
bool invert_transformations,
bool allow_shrink,
bool allow_expand) -> py::bytes {
return py::bytes(poh.placeFormXObject(formx,
name.getName(),
rect,
invert_transformations,
allow_shrink,
allow_expand));
},
py::arg("formx"), // LCOV_EXCL_LINE
py::arg("name"),
py::arg("rect"),
py::kw_only(), // LCOV_EXCL_LINE
py::arg("invert_transformations") = true,
py::arg("allow_shrink") = true,
py::arg("allow_expand") = false,
R"~~~(
Generate content stream segment to place a Form XObject on this page.
The content stream segment must be then be added to the page's
content stream.
The default keyword parameters will preserve the aspect ratio.
Args:
formx: The Form XObject to place.
name: The name of the Form XObject in this page's /Resources
dictionary.
rect: Rectangle describing the desired placement of the Form
XObject.
invert_transformations: Apply /Rotate and /UserUnit scaling
when determining FormX Object placement.
allow_shrink: Allow the Form XObject to take less than the
full dimensions of rect.
allow_expand: Expand the Form XObject to occupy all of rect.
.. versionadded:: 2.14
)~~~")
.def(
"get_filtered_contents",
[](QPDFPageObjectHelper &poh,
QPDFObjectHandle::TokenFilter &tf) -> py::bytes {
Pl_Buffer pl_buffer("filter_page");
poh.filterContents(&tf, &pl_buffer);
std::shared_ptr<Buffer> buf(pl_buffer.getBuffer());
auto data = reinterpret_cast<const char *>(buf->getBuffer());
auto size = buf->getSize();
return py::bytes(data, size);
},
py::arg("tf"), // LCOV_EXCL_LINE
R"~~~(
Apply a :class:`pikepdf.TokenFilter` to a content stream, without modifying it.
This may be used when the results of a token filter do not need
to be applied, such as when filtering is being used to retrieve
information rather than edit the content stream.
Note that it is possible to create a subclassed ``TokenFilter``
that saves information of interest to its object attributes; it
is not necessary to return data in the content stream.
To modify the content stream, use :meth:`pikepdf.Page.add_content_token_filter`.
Returns:
The modified content stream.
)~~~")
.def(
"add_content_token_filter",
[](QPDFPageObjectHelper &poh,
std::shared_ptr<QPDFObjectHandle::TokenFilter> tf) {
// TokenFilters may be processed after the Python objects have gone
// out of scope, so we need to keep them alive by attaching them to
// the corresponding QPDF object.
auto pyqpdf = py::cast(poh.getObjectHandle().getOwningQPDF());
auto pytf = py::cast(tf);
py::detail::keep_alive_impl(pyqpdf, pytf);
poh.addContentTokenFilter(tf);
},
py::arg("tf"),
R"~~~(
Attach a :class:`pikepdf.TokenFilter` to a page's content stream.
This function applies token filters lazily, if/when the page's
content stream is read for any reason, such as when the PDF is
saved. If never access, the token filter is not applied.
Multiple token filters may be added to a page/content stream.
Token filters may not be removed after being attached to a Pdf.
Close and reopen the Pdf to remove token filters.
If the page's contents is an array of streams, it is coalesced.
)~~~")
.def(
"parse_contents",
[](QPDFPageObjectHelper &poh, PyParserCallbacks &parsercallbacks) {
poh.parseContents(&parsercallbacks);
},
R"~~~(
Parse a page's content streams using a :class:`pikepdf.StreamParser`.
The content stream may be interpreted by the StreamParser but is
not altered.
If the page's contents is an array of streams, it is coalesced.
)~~~")
.def_property_readonly(
"index",
[](QPDFPageObjectHelper &poh) {
auto this_page = poh.getObjectHandle();
auto p_owner = this_page.getOwningQPDF();
if (!p_owner)
throw py::value_error("Page is not attached to a Pdf");
auto &owner = *p_owner;
return page_index(owner, this_page);
},
R"~~~(
Returns the zero-based index of this page in the pages list.
That is, returns ``n`` such that ``pdf.pages[n] == this_page``.
A ``ValueError`` exception is thrown if the page is not attached
to this ``Pdf``.
.. versionadded:: 2.2
)~~~")
.def_property_readonly(
"label",
[](QPDFPageObjectHelper &poh) {
auto this_page = poh.getObjectHandle();
auto p_owner = this_page.getOwningQPDF();
if (!p_owner)
throw py::value_error("Page is not attached to a Pdf");
auto &owner = *p_owner;
auto index = page_index(owner, this_page);
QPDFPageLabelDocumentHelper pldh(owner);
auto label_dict = pldh.getLabelForPage(index);
if (label_dict.isNull())
return std::to_string(index + 1);
return label_string_from_dict(label_dict);
},
R"~~~(
Returns the page label for this page, accounting for section numbers.
For example, if the PDF defines a preface with lower case Roman
numerals (i, ii, iii...), followed by standard numbers, followed
by an appendix (A-1, A-2, ...), this function returns the appropriate
label as a string.
It is possible for a PDF to define page labels such that multiple
pages have the same labels. Labels are not guaranteed to
be unique.
.. versionadded:: 2.2
.. versionchanged:: 2.9
Returns the ordinary page number if no special rules for page
numbers are defined.
)~~~");
}
|
// SPDX-FileCopyrightText: 2022 James R. Barlow
// SPDX-License-Identifier: MPL-2.0
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cctype>
#include "pikepdf.h"
#include "parsers.h"
#include <qpdf/QPDFPageObjectHelper.hh>
#include <qpdf/QPDFPageLabelDocumentHelper.hh>
#include <qpdf/Pipeline.hh>
#include <qpdf/Pl_Buffer.hh>
py::size_t page_index(QPDF &owner, QPDFObjectHandle page)
{
if (&owner != page.getOwningQPDF())
throw py::value_error("Page is not in this Pdf");
int idx;
try {
idx = owner.findPage(page);
} catch (const QPDFExc &e) {
if (std::string(e.what()).find("page object not referenced") >= 0)
throw py::value_error("Page is not consistently registered with Pdf");
throw e;
}
if (idx < 0) {
// LCOV_EXCL_START
throw std::logic_error("Page index is negative");
// LCOV_EXCL_STOP
}
return idx;
}
std::string label_string_from_dict(QPDFObjectHandle label_dict)
{
auto impl =
py::module_::import("pikepdf._cpphelpers").attr("label_from_label_dict");
py::str result = impl(label_dict);
return result;
}
void init_page(py::module_ &m)
{
py::class_<QPDFPageObjectHelper,
std::shared_ptr<QPDFPageObjectHelper>,
QPDFObjectHelper>(m, "Page")
.def(py::init<QPDFObjectHandle &>())
.def(py::init([](QPDFPageObjectHelper &poh) {
return QPDFPageObjectHelper(poh.getObjectHandle());
}))
.def(
"__copy__", [](QPDFPageObjectHelper &poh) { return poh.shallowCopyPage(); })
.def_property_readonly("_images", &QPDFPageObjectHelper::getImages)
.def("_get_mediabox", &QPDFPageObjectHelper::getMediaBox)
.def("_get_cropbox", &QPDFPageObjectHelper::getCropBox)
.def("_get_trimbox", &QPDFPageObjectHelper::getTrimBox)
.def(
"externalize_inline_images",
[](QPDFPageObjectHelper &poh, size_t min_size = 0, bool shallow = false) {
return poh.externalizeInlineImages(min_size, shallow);
},
py::arg("min_size") = 0,
py::arg("shallow") = false,
R"~~~(
Convert inlines image to normal (external) images.
Args:
min_size (int): minimum size in bytes
shallow (bool): If False, recurse into nested Form XObjects.
If True, do not recurse.
)~~~")
.def("rotate",
&QPDFPageObjectHelper::rotatePage,
py::arg("angle"),
py::arg("relative"),
R"~~~(
Rotate a page.
If ``relative`` is ``False``, set the rotation of the
page to angle. Otherwise, add angle to the rotation of the
page. ``angle`` must be a multiple of ``90``. Adding ``90`` to
the rotation rotates clockwise by ``90`` degrees.
)~~~")
.def("contents_coalesce",
&QPDFPageObjectHelper::coalesceContentStreams, // LCOV_EXCL_LINE
R"~~~(
Coalesce a page's content streams.
A page's content may be a
stream or an array of streams. If this page's content is an
array, concatenate the streams into a single stream. This can
be useful when working with files that split content streams in
arbitrary spots, such as in the middle of a token, as that can
confuse some software.
)~~~")
.def(
"_contents_add",
[](QPDFPageObjectHelper &poh, QPDFObjectHandle &contents, bool prepend) {
return poh.addPageContents(contents, prepend);
},
py::arg("contents"), // LCOV_EXCL_LINE
py::kw_only(),
py::arg("prepend") = false)
.def(
"_contents_add",
[](QPDFPageObjectHelper &poh, py::bytes contents, bool prepend) {
auto q = poh.getObjectHandle().getOwningQPDF();
if (!q) {
// LCOV_EXCL_START
throw std::logic_error("QPDFPageObjectHelper not attached to QPDF");
// LCOV_EXCL_STOP
}
auto stream = QPDFObjectHandle::newStream(q, contents);
return poh.addPageContents(stream, prepend);
},
py::arg("contents"),
py::kw_only(),
py::arg("prepend") = false)
.def("remove_unreferenced_resources",
&QPDFPageObjectHelper::removeUnreferencedResources,
R"~~~(
Removes from the resources dictionary any object not referenced in the content stream.
A page's resources dictionary maps names to objects elsewhere
in the file. This method walks through a page's contents and
keeps tracks of which resources are referenced somewhere in the
contents. Then it removes from the resources dictionary any
object that is not referenced in the contents. This
method is used by page splitting code to avoid copying unused
objects in files that used shared resource dictionaries across
multiple pages.
)~~~")
.def("as_form_xobject",
&QPDFPageObjectHelper::getFormXObjectForPage, // LCOV_EXCL_LINE
py::arg("handle_transformations") = true,
R"~~~(
Return a form XObject that draws this page.
This is useful for
n-up operations, underlay, overlay, thumbnail generation, or
any other case in which it is useful to replicate the contents
of a page in some other context. The dictionaries are shallow
copies of the original page dictionary, and the contents are
coalesced from the page's contents. The resulting object handle
is not referenced anywhere.
Args:
handle_transformations (bool): If True, the resulting form
XObject's ``/Matrix`` will be set to replicate rotation
(``/Rotate``) and scaling (``/UserUnit``) in the page's
dictionary. In this way, the page's transformations will
be preserved when placing this object on another page.
)~~~")
.def(
"calc_form_xobject_placement",
[](QPDFPageObjectHelper &poh,
QPDFObjectHandle formx,
QPDFObjectHandle name,
QPDFObjectHandle::Rectangle rect,
bool invert_transformations,
bool allow_shrink,
bool allow_expand) -> py::bytes {
return py::bytes(poh.placeFormXObject(formx,
name.getName(),
rect,
invert_transformations,
allow_shrink,
allow_expand));
},
py::arg("formx"), // LCOV_EXCL_LINE
py::arg("name"),
py::arg("rect"),
py::kw_only(), // LCOV_EXCL_LINE
py::arg("invert_transformations") = true,
py::arg("allow_shrink") = true,
py::arg("allow_expand") = false,
R"~~~(
Generate content stream segment to place a Form XObject on this page.
The content stream segment must be then be added to the page's
content stream.
The default keyword parameters will preserve the aspect ratio.
Args:
formx: The Form XObject to place.
name: The name of the Form XObject in this page's /Resources
dictionary.
rect: Rectangle describing the desired placement of the Form
XObject.
invert_transformations: Apply /Rotate and /UserUnit scaling
when determining FormX Object placement.
allow_shrink: Allow the Form XObject to take less than the
full dimensions of rect.
allow_expand: Expand the Form XObject to occupy all of rect.
.. versionadded:: 2.14
)~~~")
.def(
"get_filtered_contents",
[](QPDFPageObjectHelper &poh,
QPDFObjectHandle::TokenFilter &tf) -> py::bytes {
Pl_Buffer pl_buffer("filter_page");
poh.filterContents(&tf, &pl_buffer);
// Hold .getBuffer in unique_ptr to ensure it is deleted.
// QPDF makes a copy and expects us to delete it.
std::unique_ptr<Buffer> buf(pl_buffer.getBuffer());
auto data = reinterpret_cast<const char *>(buf->getBuffer());
auto size = buf->getSize();
return py::bytes(data, size);
},
py::arg("tf"), // LCOV_EXCL_LINE
R"~~~(
Apply a :class:`pikepdf.TokenFilter` to a content stream, without modifying it.
This may be used when the results of a token filter do not need
to be applied, such as when filtering is being used to retrieve
information rather than edit the content stream.
Note that it is possible to create a subclassed ``TokenFilter``
that saves information of interest to its object attributes; it
is not necessary to return data in the content stream.
To modify the content stream, use :meth:`pikepdf.Page.add_content_token_filter`.
Returns:
The modified content stream.
)~~~")
.def(
"add_content_token_filter",
[](QPDFPageObjectHelper &poh,
std::shared_ptr<QPDFObjectHandle::TokenFilter> tf) {
// TokenFilters may be processed after the Python objects have gone
// out of scope, so we need to keep them alive by attaching them to
// the corresponding QPDF object.
auto pyqpdf = py::cast(poh.getObjectHandle().getOwningQPDF());
auto pytf = py::cast(tf);
py::detail::keep_alive_impl(pyqpdf, pytf);
poh.addContentTokenFilter(tf);
},
py::arg("tf"),
R"~~~(
Attach a :class:`pikepdf.TokenFilter` to a page's content stream.
This function applies token filters lazily, if/when the page's
content stream is read for any reason, such as when the PDF is
saved. If never access, the token filter is not applied.
Multiple token filters may be added to a page/content stream.
Token filters may not be removed after being attached to a Pdf.
Close and reopen the Pdf to remove token filters.
If the page's contents is an array of streams, it is coalesced.
)~~~")
.def(
"parse_contents",
[](QPDFPageObjectHelper &poh, PyParserCallbacks &parsercallbacks) {
poh.parseContents(&parsercallbacks);
},
R"~~~(
Parse a page's content streams using a :class:`pikepdf.StreamParser`.
The content stream may be interpreted by the StreamParser but is
not altered.
If the page's contents is an array of streams, it is coalesced.
)~~~")
.def_property_readonly(
"index",
[](QPDFPageObjectHelper &poh) {
auto this_page = poh.getObjectHandle();
auto p_owner = this_page.getOwningQPDF();
if (!p_owner)
throw py::value_error("Page is not attached to a Pdf");
auto &owner = *p_owner;
return page_index(owner, this_page);
},
R"~~~(
Returns the zero-based index of this page in the pages list.
That is, returns ``n`` such that ``pdf.pages[n] == this_page``.
A ``ValueError`` exception is thrown if the page is not attached
to this ``Pdf``.
.. versionadded:: 2.2
)~~~")
.def_property_readonly(
"label",
[](QPDFPageObjectHelper &poh) {
auto this_page = poh.getObjectHandle();
auto p_owner = this_page.getOwningQPDF();
if (!p_owner)
throw py::value_error("Page is not attached to a Pdf");
auto &owner = *p_owner;
auto index = page_index(owner, this_page);
QPDFPageLabelDocumentHelper pldh(owner);
auto label_dict = pldh.getLabelForPage(index);
if (label_dict.isNull())
return std::to_string(index + 1);
return label_string_from_dict(label_dict);
},
R"~~~(
Returns the page label for this page, accounting for section numbers.
For example, if the PDF defines a preface with lower case Roman
numerals (i, ii, iii...), followed by standard numbers, followed
by an appendix (A-1, A-2, ...), this function returns the appropriate
label as a string.
It is possible for a PDF to define page labels such that multiple
pages have the same labels. Labels are not guaranteed to
be unique.
.. versionadded:: 2.2
.. versionchanged:: 2.9
Returns the ordinary page number if no special rules for page
numbers are defined.
)~~~");
}
|
document reason for unique_ptr<Buffer>
|
page: document reason for unique_ptr<Buffer>
|
C++
|
mpl-2.0
|
pikepdf/pikepdf,pikepdf/pikepdf,pikepdf/pikepdf
|
9d01cd9c83f956c0adc3da5c95bd04b3fa9bf21d
|
src/multiplayer_proxy.cpp
|
src/multiplayer_proxy.cpp
|
#include "multiplayer_proxy.h"
#include "multiplayer_internal.h"
#include "engine.h"
GameServerProxy::GameServerProxy(sf::IpAddress hostname, int hostPort, string password, int listenPort, string proxyName)
: password(password), proxyName(proxyName)
{
LOG(INFO) << "Starting proxy server";
mainSocket = std::unique_ptr<TcpSocket>(new TcpSocket());
if (mainSocket->connect(hostname, hostPort) != sf::Socket::Status::Done)
LOG(INFO) << "Failed to connect to server";
else
LOG(INFO) << "Connected to server";
mainSocket->setBlocking(false);
listenSocket.listen(listenPort);
listenSocket.setBlocking(false);
newSocket = std::unique_ptr<TcpSocket>(new TcpSocket());
newSocket->setBlocking(false);
boardcastServerDelay = 0.0;
if (proxyName != "")
{
if (broadcast_listen_socket.bind(listenPort) != sf::UdpSocket::Done)
{
LOG(ERROR) << "Failed to listen on UDP port: " << listenPort;
}
broadcast_listen_socket.setBlocking(false);
}
lastReceiveTime.restart();
}
GameServerProxy::GameServerProxy(string password, int listenPort, string proxyName)
: password(password), proxyName(proxyName)
{
LOG(INFO) << "Starting listening proxy server";
listenSocket.listen(listenPort);
listenSocket.setBlocking(false);
newSocket = std::unique_ptr<TcpSocket>(new TcpSocket());
newSocket->setBlocking(false);
boardcastServerDelay = 0.0;
if (proxyName != "")
{
if (broadcast_listen_socket.bind(listenPort) != sf::UdpSocket::Done)
{
LOG(ERROR) << "Failed to listen on UDP port: " << listenPort;
}
broadcast_listen_socket.setBlocking(false);
}
lastReceiveTime.restart();
}
GameServerProxy::~GameServerProxy()
{
}
void GameServerProxy::destroy()
{
clientList.clear();
broadcast_listen_socket.unbind();
}
void GameServerProxy::update(float delta)
{
if (mainSocket)
{
mainSocket->update();
sf::Packet packet;
sf::TcpSocket::Status socketStatus;
while((socketStatus = mainSocket->receive(packet)) == sf::TcpSocket::Done)
{
lastReceiveTime.restart();
command_t command;
packet >> command;
switch(command)
{
case CMD_REQUEST_AUTH:
{
bool requirePassword;
packet >> serverVersion >> requirePassword;
sf::Packet reply;
reply << CMD_CLIENT_SEND_AUTH << int32_t(serverVersion) << string(password);
mainSocket->send(reply);
}
break;
case CMD_SET_CLIENT_ID:
packet >> clientId;
break;
case CMD_ALIVE:
{
sf::Packet reply;
reply << CMD_ALIVE_RESP;
mainSocket->send(reply);
}
sendAll(packet);
break;
case CMD_CREATE:
case CMD_DELETE:
case CMD_UPDATE_VALUE:
case CMD_SET_GAME_SPEED:
case CMD_SERVER_COMMAND:
case CMD_AUDIO_COMM_START:
case CMD_AUDIO_COMM_DATA:
case CMD_AUDIO_COMM_STOP:
sendAll(packet);
break;
case CMD_PROXY_TO_CLIENTS:
{
int32_t id;
while(packet >> id)
{
targetClients.insert(id);
}
}
break;
case CMD_SET_PROXY_CLIENT_ID:
{
int32_t tempId, clientId;
packet >> tempId >> clientId;
for(auto& info : clientList)
{
if (!info.validClient && info.clientId == tempId)
{
info.validClient = true;
info.clientId = clientId;
info.receiveState = CRS_Main;
{
sf::Packet packet;
packet << CMD_SET_CLIENT_ID << info.clientId;
info.socket->send(packet);
}
}
}
}
break;
}
}
if (socketStatus == sf::TcpSocket::Disconnected || lastReceiveTime.getElapsedTime().asSeconds() > noDataDisconnectTime)
{
LOG(INFO) << "Disconnected proxy";
mainSocket->disconnect();
engine->shutdown();
}
}
if (proxyName != "")
{
handleBroadcastUDPSocket(delta);
}
if (listenSocket.accept(*newSocket) == sf::Socket::Status::Done)
{
ClientInfo info;
info.socket = std::move(newSocket);
newSocket = std::unique_ptr<TcpSocket>(new TcpSocket());
newSocket->setBlocking(false);
{
sf::Packet packet;
packet << CMD_REQUEST_AUTH << int32_t(serverVersion) << bool(password != "");
info.socket->send(packet);
}
clientList.emplace_back(std::move(info));
}
for(unsigned int n=0; n<clientList.size(); n++)
{
sf::Packet packet;
sf::TcpSocket::Status socketStatus;
auto& info = clientList[n];
info.socket->update();
while(info.socket && (socketStatus = info.socket->receive(packet)) == sf::TcpSocket::Done)
{
command_t command;
packet >> command;
switch(info.receiveState)
{
case CRS_Auth:
switch(command)
{
case CMD_SERVER_CONNECT_TO_PROXY:
if (mainSocket)
{
info.socket->disconnect();
info.socket = NULL;
}
else
{
mainSocket = std::move(info.socket);
lastReceiveTime.restart();
}
break;
case CMD_CLIENT_SEND_AUTH:
{
int32_t clientVersion;
string clientPassword;
packet >> clientVersion >> clientPassword;
if (mainSocket && clientVersion == serverVersion && clientPassword == password)
{
sf::Packet serverUpdate;
serverUpdate << CMD_NEW_PROXY_CLIENT << info.clientId;
mainSocket->send(serverUpdate);
}
else
{
info.socket->disconnect();
info.socket = NULL;
}
}
break;
case CMD_ALIVE_RESP:
break;
default:
LOG(ERROR) << "Unknown command from client: " << command;
break;
}
break;
case CRS_Main:
switch(command)
{
case CMD_CLIENT_COMMAND:
packet >> info.commandObjectId;
info.receiveState = CRS_Command;
break;
case CMD_AUDIO_COMM_START:
case CMD_AUDIO_COMM_DATA:
case CMD_AUDIO_COMM_STOP:
{
int32_t client_id = 0;
packet >> client_id;
if (client_id == info.clientId)
mainSocket->send(packet);
}
break;
case CMD_ALIVE_RESP:
break;
default:
LOG(ERROR) << "Unknown command from client: " << command;
break;
}
break;
case CRS_Command:
{
sf::Packet mainPacket;
mainPacket << CMD_PROXY_CLIENT_COMMAND << info.commandObjectId << info.clientId;
mainSocket->send(mainPacket);
mainSocket->send(packet);
}
info.receiveState = CRS_Main;
break;
}
}
if (socketStatus == sf::TcpSocket::Disconnected || info.socket == NULL)
{
if (info.validClient)
{
sf::Packet serverUpdate;
serverUpdate << CMD_DEL_PROXY_CLIENT << info.clientId;
mainSocket->send(serverUpdate);
}
clientList.erase(clientList.begin() + n);
n--;
}
}
}
void GameServerProxy::sendAll(sf::Packet& packet)
{
if (targetClients.empty())
{
for(auto& info : clientList)
{
if (info.validClient && info.socket)
info.socket->send(packet);
}
}
else
{
for(auto& info : clientList)
{
if (info.validClient && info.socket && targetClients.find(info.clientId) != targetClients.end())
info.socket->send(packet);
}
targetClients.clear();
}
}
void GameServerProxy::handleBroadcastUDPSocket(float delta)
{
sf::IpAddress recvAddress;
unsigned short recvPort;
sf::Packet recvPacket;
if (broadcast_listen_socket.receive(recvPacket, recvAddress, recvPort) == sf::Socket::Status::Done)
{
//We do not care about what we received. Reply that we live!
sf::Packet sendPacket;
sendPacket << int32_t(multiplayerVerficationNumber) << int32_t(serverVersion) << proxyName;
broadcast_listen_socket.send(sendPacket, recvAddress, recvPort);
}
if (boardcastServerDelay > 0.0)
{
boardcastServerDelay -= delta;
}else{
boardcastServerDelay = 5.0;
sf::Packet sendPacket;
sendPacket << int32_t(multiplayerVerficationNumber) << int32_t(serverVersion) << proxyName;
UDPbroadcastPacket(broadcast_listen_socket, sendPacket, broadcast_listen_socket.getLocalPort() + 1);
}
}
|
#include "multiplayer_proxy.h"
#include "multiplayer_internal.h"
#include "engine.h"
GameServerProxy::GameServerProxy(sf::IpAddress hostname, int hostPort, string password, int listenPort, string proxyName)
: password(password), proxyName(proxyName)
{
LOG(INFO) << "Starting proxy server";
mainSocket = std::unique_ptr<TcpSocket>(new TcpSocket());
if (mainSocket->connect(hostname, static_cast<uint16_t>(hostPort)) != sf::Socket::Status::Done)
LOG(INFO) << "Failed to connect to server";
else
LOG(INFO) << "Connected to server";
mainSocket->setBlocking(false);
listenSocket.listen(static_cast<uint16_t>(listenPort));
listenSocket.setBlocking(false);
newSocket = std::unique_ptr<TcpSocket>(new TcpSocket());
newSocket->setBlocking(false);
boardcastServerDelay = 0.0;
if (proxyName != "")
{
if (broadcast_listen_socket.bind(static_cast<uint16_t>(listenPort)) != sf::UdpSocket::Done)
{
LOG(ERROR) << "Failed to listen on UDP port: " << listenPort;
}
broadcast_listen_socket.setBlocking(false);
}
lastReceiveTime.restart();
}
GameServerProxy::GameServerProxy(string password, int listenPort, string proxyName)
: password(password), proxyName(proxyName)
{
LOG(INFO) << "Starting listening proxy server";
listenSocket.listen(static_cast<uint16_t>(listenPort));
listenSocket.setBlocking(false);
newSocket = std::unique_ptr<TcpSocket>(new TcpSocket());
newSocket->setBlocking(false);
boardcastServerDelay = 0.0;
if (proxyName != "")
{
if (broadcast_listen_socket.bind(static_cast<uint16_t>(listenPort)) != sf::UdpSocket::Done)
{
LOG(ERROR) << "Failed to listen on UDP port: " << listenPort;
}
broadcast_listen_socket.setBlocking(false);
}
lastReceiveTime.restart();
}
GameServerProxy::~GameServerProxy()
{
}
void GameServerProxy::destroy()
{
clientList.clear();
broadcast_listen_socket.unbind();
}
void GameServerProxy::update(float delta)
{
if (mainSocket)
{
mainSocket->update();
sf::Packet packet;
sf::TcpSocket::Status socketStatus;
while((socketStatus = mainSocket->receive(packet)) == sf::TcpSocket::Done)
{
lastReceiveTime.restart();
command_t command;
packet >> command;
switch(command)
{
case CMD_REQUEST_AUTH:
{
bool requirePassword;
packet >> serverVersion >> requirePassword;
sf::Packet reply;
reply << CMD_CLIENT_SEND_AUTH << int32_t(serverVersion) << string(password);
mainSocket->send(reply);
}
break;
case CMD_SET_CLIENT_ID:
packet >> clientId;
break;
case CMD_ALIVE:
{
sf::Packet reply;
reply << CMD_ALIVE_RESP;
mainSocket->send(reply);
}
sendAll(packet);
break;
case CMD_CREATE:
case CMD_DELETE:
case CMD_UPDATE_VALUE:
case CMD_SET_GAME_SPEED:
case CMD_SERVER_COMMAND:
case CMD_AUDIO_COMM_START:
case CMD_AUDIO_COMM_DATA:
case CMD_AUDIO_COMM_STOP:
sendAll(packet);
break;
case CMD_PROXY_TO_CLIENTS:
{
int32_t id;
while(packet >> id)
{
targetClients.insert(id);
}
}
break;
case CMD_SET_PROXY_CLIENT_ID:
{
int32_t tempId, proxied_clientId;
packet >> tempId >> proxied_clientId;
for(auto& info : clientList)
{
if (!info.validClient && info.clientId == tempId)
{
info.validClient = true;
info.clientId = proxied_clientId;
info.receiveState = CRS_Main;
{
sf::Packet proxied_packet;
proxied_packet << CMD_SET_CLIENT_ID << info.clientId;
info.socket->send(proxied_packet);
}
}
}
}
break;
}
}
if (socketStatus == sf::TcpSocket::Disconnected || lastReceiveTime.getElapsedTime().asSeconds() > noDataDisconnectTime)
{
LOG(INFO) << "Disconnected proxy";
mainSocket->disconnect();
engine->shutdown();
}
}
if (proxyName != "")
{
handleBroadcastUDPSocket(delta);
}
if (listenSocket.accept(*newSocket) == sf::Socket::Status::Done)
{
ClientInfo info;
info.socket = std::move(newSocket);
newSocket = std::unique_ptr<TcpSocket>(new TcpSocket());
newSocket->setBlocking(false);
{
sf::Packet packet;
packet << CMD_REQUEST_AUTH << int32_t(serverVersion) << bool(password != "");
info.socket->send(packet);
}
clientList.emplace_back(std::move(info));
}
for(unsigned int n=0; n<clientList.size(); n++)
{
sf::Packet packet;
sf::TcpSocket::Status socketStatus{ sf::TcpSocket::Error };
auto& info = clientList[n];
info.socket->update();
while(info.socket && (socketStatus = info.socket->receive(packet)) == sf::TcpSocket::Done)
{
command_t command;
packet >> command;
switch(info.receiveState)
{
case CRS_Auth:
switch(command)
{
case CMD_SERVER_CONNECT_TO_PROXY:
if (mainSocket)
{
info.socket->disconnect();
info.socket = NULL;
}
else
{
mainSocket = std::move(info.socket);
lastReceiveTime.restart();
}
break;
case CMD_CLIENT_SEND_AUTH:
{
int32_t clientVersion;
string clientPassword;
packet >> clientVersion >> clientPassword;
if (mainSocket && clientVersion == serverVersion && clientPassword == password)
{
sf::Packet serverUpdate;
serverUpdate << CMD_NEW_PROXY_CLIENT << info.clientId;
mainSocket->send(serverUpdate);
}
else
{
info.socket->disconnect();
info.socket = NULL;
}
}
break;
case CMD_ALIVE_RESP:
break;
default:
LOG(ERROR) << "Unknown command from client: " << command;
break;
}
break;
case CRS_Main:
switch(command)
{
case CMD_CLIENT_COMMAND:
packet >> info.commandObjectId;
info.receiveState = CRS_Command;
break;
case CMD_AUDIO_COMM_START:
case CMD_AUDIO_COMM_DATA:
case CMD_AUDIO_COMM_STOP:
{
int32_t client_id = 0;
packet >> client_id;
if (client_id == info.clientId)
mainSocket->send(packet);
}
break;
case CMD_ALIVE_RESP:
break;
default:
LOG(ERROR) << "Unknown command from client: " << command;
break;
}
break;
case CRS_Command:
{
sf::Packet mainPacket;
mainPacket << CMD_PROXY_CLIENT_COMMAND << info.commandObjectId << info.clientId;
mainSocket->send(mainPacket);
mainSocket->send(packet);
}
info.receiveState = CRS_Main;
break;
}
}
if (socketStatus == sf::TcpSocket::Disconnected || info.socket == NULL)
{
if (info.validClient)
{
sf::Packet serverUpdate;
serverUpdate << CMD_DEL_PROXY_CLIENT << info.clientId;
mainSocket->send(serverUpdate);
}
clientList.erase(clientList.begin() + n);
n--;
}
}
}
void GameServerProxy::sendAll(sf::Packet& packet)
{
if (targetClients.empty())
{
for(auto& info : clientList)
{
if (info.validClient && info.socket)
info.socket->send(packet);
}
}
else
{
for(auto& info : clientList)
{
if (info.validClient && info.socket && targetClients.find(info.clientId) != targetClients.end())
info.socket->send(packet);
}
targetClients.clear();
}
}
void GameServerProxy::handleBroadcastUDPSocket(float delta)
{
sf::IpAddress recvAddress;
unsigned short recvPort;
sf::Packet recvPacket;
if (broadcast_listen_socket.receive(recvPacket, recvAddress, recvPort) == sf::Socket::Status::Done)
{
//We do not care about what we received. Reply that we live!
sf::Packet sendPacket;
sendPacket << int32_t(multiplayerVerficationNumber) << int32_t(serverVersion) << proxyName;
broadcast_listen_socket.send(sendPacket, recvAddress, recvPort);
}
if (boardcastServerDelay > 0.0)
{
boardcastServerDelay -= delta;
}else{
boardcastServerDelay = 5.0;
sf::Packet sendPacket;
sendPacket << int32_t(multiplayerVerficationNumber) << int32_t(serverVersion) << proxyName;
UDPbroadcastPacket(broadcast_listen_socket, sendPacket, broadcast_listen_socket.getLocalPort() + 1);
}
}
|
Update multiplayer_proxy.cpp (#93)
|
Update multiplayer_proxy.cpp (#93)
* type cast
* shadowing
|
C++
|
mit
|
daid/SeriousProton,daid/SeriousProton,daid/SeriousProton,daid/SeriousProton,daid/SeriousProton,daid/SeriousProton
|
a73a09674be45fa2c7daeabd564838ce6c3410b4
|
lib/Sema/SemaCUDA.cpp
|
lib/Sema/SemaCUDA.cpp
|
//===--- SemaCUDA.cpp - Semantic Analysis for CUDA constructs -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// \brief This file implements semantic analysis for CUDA constructs.
///
//===----------------------------------------------------------------------===//
#include "clang/Sema/Sema.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/ExprCXX.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/SemaDiagnostic.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallVector.h"
using namespace clang;
ExprResult Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
MultiExprArg ExecConfig,
SourceLocation GGGLoc) {
FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
if (!ConfigDecl)
return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
<< "cudaConfigureCall");
QualType ConfigQTy = ConfigDecl->getType();
DeclRefExpr *ConfigDR = new (Context)
DeclRefExpr(ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
MarkFunctionReferenced(LLLLoc, ConfigDecl);
return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, nullptr,
/*IsExecConfig=*/true);
}
/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
if (D->hasAttr<CUDAInvalidTargetAttr>())
return CFT_InvalidTarget;
if (D->hasAttr<CUDAGlobalAttr>())
return CFT_Global;
if (D->hasAttr<CUDADeviceAttr>()) {
if (D->hasAttr<CUDAHostAttr>())
return CFT_HostDevice;
return CFT_Device;
} else if (D->hasAttr<CUDAHostAttr>()) {
return CFT_Host;
} else if (D->isImplicit()) {
// Some implicit declarations (like intrinsic functions) are not marked.
// Set the most lenient target on them for maximal flexibility.
return CFT_HostDevice;
}
return CFT_Host;
}
// * CUDA Call preference table
//
// F - from,
// T - to
// Ph - preference in host mode
// Pd - preference in device mode
// H - handled in (x)
// Preferences: N:native, HD:host-device, SS:same side, WS:wrong side, --:never.
//
// | F | T | Ph | Pd | H |
// |----+----+-----+-----+-----+
// | d | d | N | N | (c) |
// | d | g | -- | -- | (a) |
// | d | h | -- | -- | (e) |
// | d | hd | HD | HD | (b) |
// | g | d | N | N | (c) |
// | g | g | -- | -- | (a) |
// | g | h | -- | -- | (e) |
// | g | hd | HD | HD | (b) |
// | h | d | -- | -- | (e) |
// | h | g | N | N | (c) |
// | h | h | N | N | (c) |
// | h | hd | HD | HD | (b) |
// | hd | d | WS | SS | (d) |
// | hd | g | SS | -- |(d/a)|
// | hd | h | SS | WS | (d) |
// | hd | hd | HD | HD | (b) |
Sema::CUDAFunctionPreference
Sema::IdentifyCUDAPreference(const FunctionDecl *Caller,
const FunctionDecl *Callee) {
assert(Callee && "Callee must be valid.");
CUDAFunctionTarget CalleeTarget = IdentifyCUDATarget(Callee);
CUDAFunctionTarget CallerTarget =
(Caller != nullptr) ? IdentifyCUDATarget(Caller) : Sema::CFT_Host;
// If one of the targets is invalid, the check always fails, no matter what
// the other target is.
if (CallerTarget == CFT_InvalidTarget || CalleeTarget == CFT_InvalidTarget)
return CFP_Never;
// (a) Can't call global from some contexts until we support CUDA's
// dynamic parallelism.
if (CalleeTarget == CFT_Global &&
(CallerTarget == CFT_Global || CallerTarget == CFT_Device ||
(CallerTarget == CFT_HostDevice && getLangOpts().CUDAIsDevice)))
return CFP_Never;
// (b) Calling HostDevice is OK for everyone.
if (CalleeTarget == CFT_HostDevice)
return CFP_HostDevice;
// (c) Best case scenarios
if (CalleeTarget == CallerTarget ||
(CallerTarget == CFT_Host && CalleeTarget == CFT_Global) ||
(CallerTarget == CFT_Global && CalleeTarget == CFT_Device))
return CFP_Native;
// (d) HostDevice behavior depends on compilation mode.
if (CallerTarget == CFT_HostDevice) {
// It's OK to call a compilation-mode matching function from an HD one.
if ((getLangOpts().CUDAIsDevice && CalleeTarget == CFT_Device) ||
(!getLangOpts().CUDAIsDevice &&
(CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)))
return CFP_SameSide;
// Calls from HD to non-mode-matching functions (i.e., to host functions
// when compiling in device mode or to device functions when compiling in
// host mode) are allowed at the sema level, but eventually rejected if
// they're ever codegened. TODO: Reject said calls earlier.
return CFP_WrongSide;
}
// (e) Calling across device/host boundary is not something you should do.
if ((CallerTarget == CFT_Host && CalleeTarget == CFT_Device) ||
(CallerTarget == CFT_Device && CalleeTarget == CFT_Host) ||
(CallerTarget == CFT_Global && CalleeTarget == CFT_Host))
return CFP_Never;
llvm_unreachable("All cases should've been handled by now.");
}
template <typename T>
static void EraseUnwantedCUDAMatchesImpl(
Sema &S, const FunctionDecl *Caller, llvm::SmallVectorImpl<T> &Matches,
std::function<const FunctionDecl *(const T &)> FetchDecl) {
if (Matches.size() <= 1)
return;
// Gets the CUDA function preference for a call from Caller to Match.
auto GetCFP = [&](const T &Match) {
return S.IdentifyCUDAPreference(Caller, FetchDecl(Match));
};
// Find the best call preference among the functions in Matches.
Sema::CUDAFunctionPreference BestCFP = GetCFP(*std::max_element(
Matches.begin(), Matches.end(),
[&](const T &M1, const T &M2) { return GetCFP(M1) < GetCFP(M2); }));
// Erase all functions with lower priority.
Matches.erase(llvm::remove_if(
Matches, [&](const T &Match) { return GetCFP(Match) < BestCFP; }));
}
void Sema::EraseUnwantedCUDAMatches(const FunctionDecl *Caller,
SmallVectorImpl<FunctionDecl *> &Matches){
EraseUnwantedCUDAMatchesImpl<FunctionDecl *>(
*this, Caller, Matches, [](const FunctionDecl *item) { return item; });
}
void Sema::EraseUnwantedCUDAMatches(const FunctionDecl *Caller,
SmallVectorImpl<DeclAccessPair> &Matches) {
EraseUnwantedCUDAMatchesImpl<DeclAccessPair>(
*this, Caller, Matches, [](const DeclAccessPair &item) {
return dyn_cast<FunctionDecl>(item.getDecl());
});
}
void Sema::EraseUnwantedCUDAMatches(
const FunctionDecl *Caller,
SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches){
EraseUnwantedCUDAMatchesImpl<std::pair<DeclAccessPair, FunctionDecl *>>(
*this, Caller, Matches,
[](const std::pair<DeclAccessPair, FunctionDecl *> &item) {
return dyn_cast<FunctionDecl>(item.second);
});
}
/// When an implicitly-declared special member has to invoke more than one
/// base/field special member, conflicts may occur in the targets of these
/// members. For example, if one base's member __host__ and another's is
/// __device__, it's a conflict.
/// This function figures out if the given targets \param Target1 and
/// \param Target2 conflict, and if they do not it fills in
/// \param ResolvedTarget with a target that resolves for both calls.
/// \return true if there's a conflict, false otherwise.
static bool
resolveCalleeCUDATargetConflict(Sema::CUDAFunctionTarget Target1,
Sema::CUDAFunctionTarget Target2,
Sema::CUDAFunctionTarget *ResolvedTarget) {
// Only free functions and static member functions may be global.
assert(Target1 != Sema::CFT_Global);
assert(Target2 != Sema::CFT_Global);
if (Target1 == Sema::CFT_HostDevice) {
*ResolvedTarget = Target2;
} else if (Target2 == Sema::CFT_HostDevice) {
*ResolvedTarget = Target1;
} else if (Target1 != Target2) {
return true;
} else {
*ResolvedTarget = Target1;
}
return false;
}
bool Sema::inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
CXXSpecialMember CSM,
CXXMethodDecl *MemberDecl,
bool ConstRHS,
bool Diagnose) {
llvm::Optional<CUDAFunctionTarget> InferredTarget;
// We're going to invoke special member lookup; mark that these special
// members are called from this one, and not from its caller.
ContextRAII MethodContext(*this, MemberDecl);
// Look for special members in base classes that should be invoked from here.
// Infer the target of this member base on the ones it should call.
// Skip direct and indirect virtual bases for abstract classes.
llvm::SmallVector<const CXXBaseSpecifier *, 16> Bases;
for (const auto &B : ClassDecl->bases()) {
if (!B.isVirtual()) {
Bases.push_back(&B);
}
}
if (!ClassDecl->isAbstract()) {
for (const auto &VB : ClassDecl->vbases()) {
Bases.push_back(&VB);
}
}
for (const auto *B : Bases) {
const RecordType *BaseType = B->getType()->getAs<RecordType>();
if (!BaseType) {
continue;
}
CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sema::SpecialMemberOverloadResult *SMOR =
LookupSpecialMember(BaseClassDecl, CSM,
/* ConstArg */ ConstRHS,
/* VolatileArg */ false,
/* RValueThis */ false,
/* ConstThis */ false,
/* VolatileThis */ false);
if (!SMOR || !SMOR->getMethod()) {
continue;
}
CUDAFunctionTarget BaseMethodTarget = IdentifyCUDATarget(SMOR->getMethod());
if (!InferredTarget.hasValue()) {
InferredTarget = BaseMethodTarget;
} else {
bool ResolutionError = resolveCalleeCUDATargetConflict(
InferredTarget.getValue(), BaseMethodTarget,
InferredTarget.getPointer());
if (ResolutionError) {
if (Diagnose) {
Diag(ClassDecl->getLocation(),
diag::note_implicit_member_target_infer_collision)
<< (unsigned)CSM << InferredTarget.getValue() << BaseMethodTarget;
}
MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
return true;
}
}
}
// Same as for bases, but now for special members of fields.
for (const auto *F : ClassDecl->fields()) {
if (F->isInvalidDecl()) {
continue;
}
const RecordType *FieldType =
Context.getBaseElementType(F->getType())->getAs<RecordType>();
if (!FieldType) {
continue;
}
CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(FieldType->getDecl());
Sema::SpecialMemberOverloadResult *SMOR =
LookupSpecialMember(FieldRecDecl, CSM,
/* ConstArg */ ConstRHS && !F->isMutable(),
/* VolatileArg */ false,
/* RValueThis */ false,
/* ConstThis */ false,
/* VolatileThis */ false);
if (!SMOR || !SMOR->getMethod()) {
continue;
}
CUDAFunctionTarget FieldMethodTarget =
IdentifyCUDATarget(SMOR->getMethod());
if (!InferredTarget.hasValue()) {
InferredTarget = FieldMethodTarget;
} else {
bool ResolutionError = resolveCalleeCUDATargetConflict(
InferredTarget.getValue(), FieldMethodTarget,
InferredTarget.getPointer());
if (ResolutionError) {
if (Diagnose) {
Diag(ClassDecl->getLocation(),
diag::note_implicit_member_target_infer_collision)
<< (unsigned)CSM << InferredTarget.getValue()
<< FieldMethodTarget;
}
MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
return true;
}
}
}
if (InferredTarget.hasValue()) {
if (InferredTarget.getValue() == CFT_Device) {
MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
} else if (InferredTarget.getValue() == CFT_Host) {
MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
} else {
MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
}
} else {
// If no target was inferred, mark this member as __host__ __device__;
// it's the least restrictive option that can be invoked from any target.
MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
}
return false;
}
bool Sema::isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD) {
if (!CD->isDefined() && CD->isTemplateInstantiation())
InstantiateFunctionDefinition(Loc, CD->getFirstDecl());
// (E.2.3.1, CUDA 7.5) A constructor for a class type is considered
// empty at a point in the translation unit, if it is either a
// trivial constructor
if (CD->isTrivial())
return true;
// ... or it satisfies all of the following conditions:
// The constructor function has been defined.
// The constructor function has no parameters,
// and the function body is an empty compound statement.
if (!(CD->hasTrivialBody() && CD->getNumParams() == 0))
return false;
// Its class has no virtual functions and no virtual base classes.
if (CD->getParent()->isDynamicClass())
return false;
// The only form of initializer allowed is an empty constructor.
// This will recursively checks all base classes and member initializers
if (!llvm::all_of(CD->inits(), [&](const CXXCtorInitializer *CI) {
if (const CXXConstructExpr *CE =
dyn_cast<CXXConstructExpr>(CI->getInit()))
return isEmptyCudaConstructor(Loc, CE->getConstructor());
return false;
}))
return false;
return true;
}
|
//===--- SemaCUDA.cpp - Semantic Analysis for CUDA constructs -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// \brief This file implements semantic analysis for CUDA constructs.
///
//===----------------------------------------------------------------------===//
#include "clang/Sema/Sema.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/ExprCXX.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/SemaDiagnostic.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallVector.h"
using namespace clang;
ExprResult Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
MultiExprArg ExecConfig,
SourceLocation GGGLoc) {
FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
if (!ConfigDecl)
return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
<< "cudaConfigureCall");
QualType ConfigQTy = ConfigDecl->getType();
DeclRefExpr *ConfigDR = new (Context)
DeclRefExpr(ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
MarkFunctionReferenced(LLLLoc, ConfigDecl);
return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, nullptr,
/*IsExecConfig=*/true);
}
/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
if (D->hasAttr<CUDAInvalidTargetAttr>())
return CFT_InvalidTarget;
if (D->hasAttr<CUDAGlobalAttr>())
return CFT_Global;
if (D->hasAttr<CUDADeviceAttr>()) {
if (D->hasAttr<CUDAHostAttr>())
return CFT_HostDevice;
return CFT_Device;
} else if (D->hasAttr<CUDAHostAttr>()) {
return CFT_Host;
} else if (D->isImplicit()) {
// Some implicit declarations (like intrinsic functions) are not marked.
// Set the most lenient target on them for maximal flexibility.
return CFT_HostDevice;
}
return CFT_Host;
}
// * CUDA Call preference table
//
// F - from,
// T - to
// Ph - preference in host mode
// Pd - preference in device mode
// H - handled in (x)
// Preferences: N:native, SS:same side, HD:host-device, WS:wrong side, --:never.
//
// | F | T | Ph | Pd | H |
// |----+----+-----+-----+-----+
// | d | d | N | N | (c) |
// | d | g | -- | -- | (a) |
// | d | h | -- | -- | (e) |
// | d | hd | HD | HD | (b) |
// | g | d | N | N | (c) |
// | g | g | -- | -- | (a) |
// | g | h | -- | -- | (e) |
// | g | hd | HD | HD | (b) |
// | h | d | -- | -- | (e) |
// | h | g | N | N | (c) |
// | h | h | N | N | (c) |
// | h | hd | HD | HD | (b) |
// | hd | d | WS | SS | (d) |
// | hd | g | SS | -- |(d/a)|
// | hd | h | SS | WS | (d) |
// | hd | hd | HD | HD | (b) |
Sema::CUDAFunctionPreference
Sema::IdentifyCUDAPreference(const FunctionDecl *Caller,
const FunctionDecl *Callee) {
assert(Callee && "Callee must be valid.");
CUDAFunctionTarget CalleeTarget = IdentifyCUDATarget(Callee);
CUDAFunctionTarget CallerTarget =
(Caller != nullptr) ? IdentifyCUDATarget(Caller) : Sema::CFT_Host;
// If one of the targets is invalid, the check always fails, no matter what
// the other target is.
if (CallerTarget == CFT_InvalidTarget || CalleeTarget == CFT_InvalidTarget)
return CFP_Never;
// (a) Can't call global from some contexts until we support CUDA's
// dynamic parallelism.
if (CalleeTarget == CFT_Global &&
(CallerTarget == CFT_Global || CallerTarget == CFT_Device ||
(CallerTarget == CFT_HostDevice && getLangOpts().CUDAIsDevice)))
return CFP_Never;
// (b) Calling HostDevice is OK for everyone.
if (CalleeTarget == CFT_HostDevice)
return CFP_HostDevice;
// (c) Best case scenarios
if (CalleeTarget == CallerTarget ||
(CallerTarget == CFT_Host && CalleeTarget == CFT_Global) ||
(CallerTarget == CFT_Global && CalleeTarget == CFT_Device))
return CFP_Native;
// (d) HostDevice behavior depends on compilation mode.
if (CallerTarget == CFT_HostDevice) {
// It's OK to call a compilation-mode matching function from an HD one.
if ((getLangOpts().CUDAIsDevice && CalleeTarget == CFT_Device) ||
(!getLangOpts().CUDAIsDevice &&
(CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)))
return CFP_SameSide;
// Calls from HD to non-mode-matching functions (i.e., to host functions
// when compiling in device mode or to device functions when compiling in
// host mode) are allowed at the sema level, but eventually rejected if
// they're ever codegened. TODO: Reject said calls earlier.
return CFP_WrongSide;
}
// (e) Calling across device/host boundary is not something you should do.
if ((CallerTarget == CFT_Host && CalleeTarget == CFT_Device) ||
(CallerTarget == CFT_Device && CalleeTarget == CFT_Host) ||
(CallerTarget == CFT_Global && CalleeTarget == CFT_Host))
return CFP_Never;
llvm_unreachable("All cases should've been handled by now.");
}
template <typename T>
static void EraseUnwantedCUDAMatchesImpl(
Sema &S, const FunctionDecl *Caller, llvm::SmallVectorImpl<T> &Matches,
std::function<const FunctionDecl *(const T &)> FetchDecl) {
if (Matches.size() <= 1)
return;
// Gets the CUDA function preference for a call from Caller to Match.
auto GetCFP = [&](const T &Match) {
return S.IdentifyCUDAPreference(Caller, FetchDecl(Match));
};
// Find the best call preference among the functions in Matches.
Sema::CUDAFunctionPreference BestCFP = GetCFP(*std::max_element(
Matches.begin(), Matches.end(),
[&](const T &M1, const T &M2) { return GetCFP(M1) < GetCFP(M2); }));
// Erase all functions with lower priority.
Matches.erase(llvm::remove_if(
Matches, [&](const T &Match) { return GetCFP(Match) < BestCFP; }));
}
void Sema::EraseUnwantedCUDAMatches(const FunctionDecl *Caller,
SmallVectorImpl<FunctionDecl *> &Matches){
EraseUnwantedCUDAMatchesImpl<FunctionDecl *>(
*this, Caller, Matches, [](const FunctionDecl *item) { return item; });
}
void Sema::EraseUnwantedCUDAMatches(const FunctionDecl *Caller,
SmallVectorImpl<DeclAccessPair> &Matches) {
EraseUnwantedCUDAMatchesImpl<DeclAccessPair>(
*this, Caller, Matches, [](const DeclAccessPair &item) {
return dyn_cast<FunctionDecl>(item.getDecl());
});
}
void Sema::EraseUnwantedCUDAMatches(
const FunctionDecl *Caller,
SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches){
EraseUnwantedCUDAMatchesImpl<std::pair<DeclAccessPair, FunctionDecl *>>(
*this, Caller, Matches,
[](const std::pair<DeclAccessPair, FunctionDecl *> &item) {
return dyn_cast<FunctionDecl>(item.second);
});
}
/// When an implicitly-declared special member has to invoke more than one
/// base/field special member, conflicts may occur in the targets of these
/// members. For example, if one base's member __host__ and another's is
/// __device__, it's a conflict.
/// This function figures out if the given targets \param Target1 and
/// \param Target2 conflict, and if they do not it fills in
/// \param ResolvedTarget with a target that resolves for both calls.
/// \return true if there's a conflict, false otherwise.
static bool
resolveCalleeCUDATargetConflict(Sema::CUDAFunctionTarget Target1,
Sema::CUDAFunctionTarget Target2,
Sema::CUDAFunctionTarget *ResolvedTarget) {
// Only free functions and static member functions may be global.
assert(Target1 != Sema::CFT_Global);
assert(Target2 != Sema::CFT_Global);
if (Target1 == Sema::CFT_HostDevice) {
*ResolvedTarget = Target2;
} else if (Target2 == Sema::CFT_HostDevice) {
*ResolvedTarget = Target1;
} else if (Target1 != Target2) {
return true;
} else {
*ResolvedTarget = Target1;
}
return false;
}
bool Sema::inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
CXXSpecialMember CSM,
CXXMethodDecl *MemberDecl,
bool ConstRHS,
bool Diagnose) {
llvm::Optional<CUDAFunctionTarget> InferredTarget;
// We're going to invoke special member lookup; mark that these special
// members are called from this one, and not from its caller.
ContextRAII MethodContext(*this, MemberDecl);
// Look for special members in base classes that should be invoked from here.
// Infer the target of this member base on the ones it should call.
// Skip direct and indirect virtual bases for abstract classes.
llvm::SmallVector<const CXXBaseSpecifier *, 16> Bases;
for (const auto &B : ClassDecl->bases()) {
if (!B.isVirtual()) {
Bases.push_back(&B);
}
}
if (!ClassDecl->isAbstract()) {
for (const auto &VB : ClassDecl->vbases()) {
Bases.push_back(&VB);
}
}
for (const auto *B : Bases) {
const RecordType *BaseType = B->getType()->getAs<RecordType>();
if (!BaseType) {
continue;
}
CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sema::SpecialMemberOverloadResult *SMOR =
LookupSpecialMember(BaseClassDecl, CSM,
/* ConstArg */ ConstRHS,
/* VolatileArg */ false,
/* RValueThis */ false,
/* ConstThis */ false,
/* VolatileThis */ false);
if (!SMOR || !SMOR->getMethod()) {
continue;
}
CUDAFunctionTarget BaseMethodTarget = IdentifyCUDATarget(SMOR->getMethod());
if (!InferredTarget.hasValue()) {
InferredTarget = BaseMethodTarget;
} else {
bool ResolutionError = resolveCalleeCUDATargetConflict(
InferredTarget.getValue(), BaseMethodTarget,
InferredTarget.getPointer());
if (ResolutionError) {
if (Diagnose) {
Diag(ClassDecl->getLocation(),
diag::note_implicit_member_target_infer_collision)
<< (unsigned)CSM << InferredTarget.getValue() << BaseMethodTarget;
}
MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
return true;
}
}
}
// Same as for bases, but now for special members of fields.
for (const auto *F : ClassDecl->fields()) {
if (F->isInvalidDecl()) {
continue;
}
const RecordType *FieldType =
Context.getBaseElementType(F->getType())->getAs<RecordType>();
if (!FieldType) {
continue;
}
CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(FieldType->getDecl());
Sema::SpecialMemberOverloadResult *SMOR =
LookupSpecialMember(FieldRecDecl, CSM,
/* ConstArg */ ConstRHS && !F->isMutable(),
/* VolatileArg */ false,
/* RValueThis */ false,
/* ConstThis */ false,
/* VolatileThis */ false);
if (!SMOR || !SMOR->getMethod()) {
continue;
}
CUDAFunctionTarget FieldMethodTarget =
IdentifyCUDATarget(SMOR->getMethod());
if (!InferredTarget.hasValue()) {
InferredTarget = FieldMethodTarget;
} else {
bool ResolutionError = resolveCalleeCUDATargetConflict(
InferredTarget.getValue(), FieldMethodTarget,
InferredTarget.getPointer());
if (ResolutionError) {
if (Diagnose) {
Diag(ClassDecl->getLocation(),
diag::note_implicit_member_target_infer_collision)
<< (unsigned)CSM << InferredTarget.getValue()
<< FieldMethodTarget;
}
MemberDecl->addAttr(CUDAInvalidTargetAttr::CreateImplicit(Context));
return true;
}
}
}
if (InferredTarget.hasValue()) {
if (InferredTarget.getValue() == CFT_Device) {
MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
} else if (InferredTarget.getValue() == CFT_Host) {
MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
} else {
MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
}
} else {
// If no target was inferred, mark this member as __host__ __device__;
// it's the least restrictive option that can be invoked from any target.
MemberDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
MemberDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
}
return false;
}
bool Sema::isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD) {
if (!CD->isDefined() && CD->isTemplateInstantiation())
InstantiateFunctionDefinition(Loc, CD->getFirstDecl());
// (E.2.3.1, CUDA 7.5) A constructor for a class type is considered
// empty at a point in the translation unit, if it is either a
// trivial constructor
if (CD->isTrivial())
return true;
// ... or it satisfies all of the following conditions:
// The constructor function has been defined.
// The constructor function has no parameters,
// and the function body is an empty compound statement.
if (!(CD->hasTrivialBody() && CD->getNumParams() == 0))
return false;
// Its class has no virtual functions and no virtual base classes.
if (CD->getParent()->isDynamicClass())
return false;
// The only form of initializer allowed is an empty constructor.
// This will recursively checks all base classes and member initializers
if (!llvm::all_of(CD->inits(), [&](const CXXCtorInitializer *CI) {
if (const CXXConstructExpr *CE =
dyn_cast<CXXConstructExpr>(CI->getInit()))
return isEmptyCudaConstructor(Loc, CE->getConstructor());
return false;
}))
return false;
return true;
}
|
Fix order of overloading preferences in comment.
|
[CUDA] Fix order of overloading preferences in comment.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@264741 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang
|
3f5ee1cf8c9e840426e3110644180fed5a1dbcb0
|
src/sim/system.cc
|
src/sim/system.cc
|
/*
* Copyright (c) 2011-2012 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2003-2006 The Regents of The University of Michigan
* Copyright (c) 2011 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 copyright holders 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.
*
* Authors: Steve Reinhardt
* Lisa Hsu
* Nathan Binkert
* Ali Saidi
* Rick Strong
*/
#include "arch/isa_traits.hh"
#include "arch/remote_gdb.hh"
#include "arch/utility.hh"
#include "arch/vtophys.hh"
#include "base/loader/object_file.hh"
#include "base/loader/symtab.hh"
#include "base/str.hh"
#include "base/trace.hh"
#include "config/the_isa.hh"
#include "cpu/thread_context.hh"
#include "debug/Loader.hh"
#include "debug/WorkItems.hh"
#include "kern/kernel_stats.hh"
#include "mem/physical.hh"
#include "params/System.hh"
#include "sim/byteswap.hh"
#include "sim/debug.hh"
#include "sim/full_system.hh"
#include "sim/system.hh"
using namespace std;
using namespace TheISA;
vector<System *> System::systemList;
int System::numSystemsRunning = 0;
System::System(Params *p)
: MemObject(p), _systemPort("system_port", this),
_numContexts(0),
pagePtr(0),
init_param(p->init_param),
physProxy(_systemPort),
virtProxy(_systemPort),
loadAddrMask(p->load_addr_mask),
nextPID(0),
physmem(p->memories),
memoryMode(p->mem_mode),
workItemsBegin(0),
workItemsEnd(0),
numWorkIds(p->num_work_ids),
_params(p),
totalNumInsts(0),
instEventQueue("system instruction-based event queue")
{
// add self to global system list
systemList.push_back(this);
if (FullSystem) {
kernelSymtab = new SymbolTable;
if (!debugSymbolTable)
debugSymbolTable = new SymbolTable;
}
// Get the generic system master IDs
MasterID tmp_id M5_VAR_USED;
tmp_id = getMasterId("writebacks");
assert(tmp_id == Request::wbMasterId);
tmp_id = getMasterId("functional");
assert(tmp_id == Request::funcMasterId);
tmp_id = getMasterId("interrupt");
assert(tmp_id == Request::intMasterId);
if (FullSystem) {
if (params()->kernel == "") {
inform("No kernel set for full system simulation. "
"Assuming you know what you're doing\n");
kernel = NULL;
} else {
// Get the kernel code
kernel = createObjectFile(params()->kernel);
inform("kernel located at: %s", params()->kernel);
if (kernel == NULL)
fatal("Could not load kernel file %s", params()->kernel);
// setup entry points
kernelStart = kernel->textBase();
kernelEnd = kernel->bssBase() + kernel->bssSize();
kernelEntry = kernel->entryPoint();
// load symbols
if (!kernel->loadGlobalSymbols(kernelSymtab))
fatal("could not load kernel symbols\n");
if (!kernel->loadLocalSymbols(kernelSymtab))
fatal("could not load kernel local symbols\n");
if (!kernel->loadGlobalSymbols(debugSymbolTable))
fatal("could not load kernel symbols\n");
if (!kernel->loadLocalSymbols(debugSymbolTable))
fatal("could not load kernel local symbols\n");
// Loading only needs to happen once and after memory system is
// connected so it will happen in initState()
}
}
// increment the number of running systms
numSystemsRunning++;
// Set back pointers to the system in all memories
for (int x = 0; x < params()->memories.size(); x++)
params()->memories[x]->system(this);
}
System::~System()
{
delete kernelSymtab;
delete kernel;
for (uint32_t j = 0; j < numWorkIds; j++)
delete workItemStats[j];
}
void
System::init()
{
// check that the system port is connected
if (!_systemPort.isConnected())
panic("System port on %s is not connected.\n", name());
}
MasterPort&
System::getMasterPort(const std::string &if_name, int idx)
{
// no need to distinguish at the moment (besides checking)
return _systemPort;
}
void
System::setMemoryMode(Enums::MemoryMode mode)
{
assert(getState() == Drained);
memoryMode = mode;
}
bool System::breakpoint()
{
if (remoteGDB.size())
return remoteGDB[0]->breakpoint();
return false;
}
/**
* Setting rgdb_wait to a positive integer waits for a remote debugger to
* connect to that context ID before continuing. This should really
be a parameter on the CPU object or something...
*/
int rgdb_wait = -1;
int
System::registerThreadContext(ThreadContext *tc, int assigned)
{
int id;
if (assigned == -1) {
for (id = 0; id < threadContexts.size(); id++) {
if (!threadContexts[id])
break;
}
if (threadContexts.size() <= id)
threadContexts.resize(id + 1);
} else {
if (threadContexts.size() <= assigned)
threadContexts.resize(assigned + 1);
id = assigned;
}
if (threadContexts[id])
fatal("Cannot have two CPUs with the same id (%d)\n", id);
threadContexts[id] = tc;
_numContexts++;
int port = getRemoteGDBPort();
if (port) {
RemoteGDB *rgdb = new RemoteGDB(this, tc);
GDBListener *gdbl = new GDBListener(rgdb, port + id);
gdbl->listen();
if (rgdb_wait != -1 && rgdb_wait == id)
gdbl->accept();
if (remoteGDB.size() <= id) {
remoteGDB.resize(id + 1);
}
remoteGDB[id] = rgdb;
}
activeCpus.push_back(false);
return id;
}
int
System::numRunningContexts()
{
int running = 0;
for (int i = 0; i < _numContexts; ++i) {
if (threadContexts[i]->status() != ThreadContext::Halted)
++running;
}
return running;
}
void
System::initState()
{
if (FullSystem) {
for (int i = 0; i < threadContexts.size(); i++)
TheISA::startupCPU(threadContexts[i], i);
// Moved from the constructor to here since it relies on the
// address map being resolved in the interconnect
/**
* Load the kernel code into memory
*/
if (params()->kernel != "") {
// Load program sections into memory
kernel->loadSections(physProxy, loadAddrMask);
DPRINTF(Loader, "Kernel start = %#x\n", kernelStart);
DPRINTF(Loader, "Kernel end = %#x\n", kernelEnd);
DPRINTF(Loader, "Kernel entry = %#x\n", kernelEntry);
DPRINTF(Loader, "Kernel loaded...\n");
}
}
activeCpus.clear();
}
void
System::replaceThreadContext(ThreadContext *tc, int context_id)
{
if (context_id >= threadContexts.size()) {
panic("replaceThreadContext: bad id, %d >= %d\n",
context_id, threadContexts.size());
}
threadContexts[context_id] = tc;
if (context_id < remoteGDB.size())
remoteGDB[context_id]->replaceThreadContext(tc);
}
Addr
System::allocPhysPages(int npages)
{
Addr return_addr = pagePtr << LogVMPageSize;
pagePtr += npages;
if ((pagePtr << LogVMPageSize) > physmem.totalSize())
fatal("Out of memory, please increase size of physical memory.");
return return_addr;
}
Addr
System::memSize() const
{
return physmem.totalSize();
}
Addr
System::freeMemSize() const
{
return physmem.totalSize() - (pagePtr << LogVMPageSize);
}
bool
System::isMemAddr(Addr addr) const
{
return physmem.isMemAddr(addr);
}
void
System::resume()
{
SimObject::resume();
totalNumInsts = 0;
}
void
System::serialize(ostream &os)
{
if (FullSystem)
kernelSymtab->serialize("kernel_symtab", os);
SERIALIZE_SCALAR(pagePtr);
SERIALIZE_SCALAR(nextPID);
}
void
System::unserialize(Checkpoint *cp, const string §ion)
{
if (FullSystem)
kernelSymtab->unserialize("kernel_symtab", cp, section);
UNSERIALIZE_SCALAR(pagePtr);
UNSERIALIZE_SCALAR(nextPID);
}
void
System::regStats()
{
for (uint32_t j = 0; j < numWorkIds ; j++) {
workItemStats[j] = new Stats::Histogram();
stringstream namestr;
ccprintf(namestr, "work_item_type%d", j);
workItemStats[j]->init(20)
.name(name() + "." + namestr.str())
.desc("Run time stat for" + namestr.str())
.prereq(*workItemStats[j]);
}
}
void
System::workItemEnd(uint32_t tid, uint32_t workid)
{
std::pair<uint32_t,uint32_t> p(tid, workid);
if (!lastWorkItemStarted.count(p))
return;
Tick samp = curTick() - lastWorkItemStarted[p];
DPRINTF(WorkItems, "Work item end: %d\t%d\t%lld\n", tid, workid, samp);
if (workid >= numWorkIds)
fatal("Got workid greater than specified in system configuration\n");
workItemStats[workid]->sample(samp);
lastWorkItemStarted.erase(p);
}
void
System::printSystems()
{
vector<System *>::iterator i = systemList.begin();
vector<System *>::iterator end = systemList.end();
for (; i != end; ++i) {
System *sys = *i;
cerr << "System " << sys->name() << ": " << hex << sys << endl;
}
}
void
printSystems()
{
System::printSystems();
}
MasterID
System::getMasterId(std::string master_name)
{
// strip off system name if the string starts with it
if (startswith(master_name, name()))
master_name = master_name.erase(0, name().size() + 1);
// CPUs in switch_cpus ask for ids again after switching
for (int i = 0; i < masterIds.size(); i++) {
if (masterIds[i] == master_name) {
return i;
}
}
// Verify that the statistics haven't been enabled yet
// Otherwise objects will have sized their stat buckets and
// they will be too small
if (Stats::enabled())
fatal("Can't request a masterId after regStats(). \
You must do so in init().\n");
masterIds.push_back(master_name);
return masterIds.size() - 1;
}
std::string
System::getMasterName(MasterID master_id)
{
if (master_id >= masterIds.size())
fatal("Invalid master_id passed to getMasterName()\n");
return masterIds[master_id];
}
const char *System::MemoryModeStrings[3] = {"invalid", "atomic",
"timing"};
System *
SystemParams::create()
{
return new System(this);
}
|
/*
* Copyright (c) 2011-2012 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2003-2006 The Regents of The University of Michigan
* Copyright (c) 2011 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 copyright holders 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.
*
* Authors: Steve Reinhardt
* Lisa Hsu
* Nathan Binkert
* Ali Saidi
* Rick Strong
*/
#include "arch/isa_traits.hh"
#include "arch/remote_gdb.hh"
#include "arch/utility.hh"
#include "arch/vtophys.hh"
#include "base/loader/object_file.hh"
#include "base/loader/symtab.hh"
#include "base/str.hh"
#include "base/trace.hh"
#include "config/the_isa.hh"
#include "cpu/thread_context.hh"
#include "debug/Loader.hh"
#include "debug/WorkItems.hh"
#include "kern/kernel_stats.hh"
#include "mem/physical.hh"
#include "params/System.hh"
#include "sim/byteswap.hh"
#include "sim/debug.hh"
#include "sim/full_system.hh"
#include "sim/system.hh"
using namespace std;
using namespace TheISA;
vector<System *> System::systemList;
int System::numSystemsRunning = 0;
System::System(Params *p)
: MemObject(p), _systemPort("system_port", this),
_numContexts(0),
pagePtr(0),
init_param(p->init_param),
physProxy(_systemPort),
virtProxy(_systemPort),
loadAddrMask(p->load_addr_mask),
nextPID(0),
physmem(p->memories),
memoryMode(p->mem_mode),
workItemsBegin(0),
workItemsEnd(0),
numWorkIds(p->num_work_ids),
_params(p),
totalNumInsts(0),
instEventQueue("system instruction-based event queue")
{
// add self to global system list
systemList.push_back(this);
if (FullSystem) {
kernelSymtab = new SymbolTable;
if (!debugSymbolTable)
debugSymbolTable = new SymbolTable;
}
// Get the generic system master IDs
MasterID tmp_id M5_VAR_USED;
tmp_id = getMasterId("writebacks");
assert(tmp_id == Request::wbMasterId);
tmp_id = getMasterId("functional");
assert(tmp_id == Request::funcMasterId);
tmp_id = getMasterId("interrupt");
assert(tmp_id == Request::intMasterId);
if (FullSystem) {
if (params()->kernel == "") {
inform("No kernel set for full system simulation. "
"Assuming you know what you're doing\n");
kernel = NULL;
} else {
// Get the kernel code
kernel = createObjectFile(params()->kernel);
inform("kernel located at: %s", params()->kernel);
if (kernel == NULL)
fatal("Could not load kernel file %s", params()->kernel);
// setup entry points
kernelStart = kernel->textBase();
kernelEnd = kernel->bssBase() + kernel->bssSize();
kernelEntry = kernel->entryPoint();
// load symbols
if (!kernel->loadGlobalSymbols(kernelSymtab))
fatal("could not load kernel symbols\n");
if (!kernel->loadLocalSymbols(kernelSymtab))
fatal("could not load kernel local symbols\n");
if (!kernel->loadGlobalSymbols(debugSymbolTable))
fatal("could not load kernel symbols\n");
if (!kernel->loadLocalSymbols(debugSymbolTable))
fatal("could not load kernel local symbols\n");
// Loading only needs to happen once and after memory system is
// connected so it will happen in initState()
}
}
// increment the number of running systms
numSystemsRunning++;
// Set back pointers to the system in all memories
for (int x = 0; x < params()->memories.size(); x++)
params()->memories[x]->system(this);
}
System::~System()
{
delete kernelSymtab;
delete kernel;
for (uint32_t j = 0; j < numWorkIds; j++)
delete workItemStats[j];
}
void
System::init()
{
// check that the system port is connected
if (!_systemPort.isConnected())
panic("System port on %s is not connected.\n", name());
}
MasterPort&
System::getMasterPort(const std::string &if_name, int idx)
{
// no need to distinguish at the moment (besides checking)
return _systemPort;
}
void
System::setMemoryMode(Enums::MemoryMode mode)
{
assert(getState() == Drained);
memoryMode = mode;
}
bool System::breakpoint()
{
if (remoteGDB.size())
return remoteGDB[0]->breakpoint();
return false;
}
/**
* Setting rgdb_wait to a positive integer waits for a remote debugger to
* connect to that context ID before continuing. This should really
be a parameter on the CPU object or something...
*/
int rgdb_wait = -1;
int
System::registerThreadContext(ThreadContext *tc, int assigned)
{
int id;
if (assigned == -1) {
for (id = 0; id < threadContexts.size(); id++) {
if (!threadContexts[id])
break;
}
if (threadContexts.size() <= id)
threadContexts.resize(id + 1);
} else {
if (threadContexts.size() <= assigned)
threadContexts.resize(assigned + 1);
id = assigned;
}
if (threadContexts[id])
fatal("Cannot have two CPUs with the same id (%d)\n", id);
threadContexts[id] = tc;
_numContexts++;
int port = getRemoteGDBPort();
if (port) {
RemoteGDB *rgdb = new RemoteGDB(this, tc);
GDBListener *gdbl = new GDBListener(rgdb, port + id);
gdbl->listen();
if (rgdb_wait != -1 && rgdb_wait == id)
gdbl->accept();
if (remoteGDB.size() <= id) {
remoteGDB.resize(id + 1);
}
remoteGDB[id] = rgdb;
}
activeCpus.push_back(false);
return id;
}
int
System::numRunningContexts()
{
int running = 0;
for (int i = 0; i < _numContexts; ++i) {
if (threadContexts[i]->status() != ThreadContext::Halted)
++running;
}
return running;
}
void
System::initState()
{
if (FullSystem) {
for (int i = 0; i < threadContexts.size(); i++)
TheISA::startupCPU(threadContexts[i], i);
// Moved from the constructor to here since it relies on the
// address map being resolved in the interconnect
/**
* Load the kernel code into memory
*/
if (params()->kernel != "") {
// Validate kernel mapping before loading binary
if (!(isMemAddr(kernelStart & loadAddrMask) &&
isMemAddr(kernelEnd & loadAddrMask))) {
fatal("Kernel is mapped to invalid location (not memory). "
"kernelStart 0x(%x) - kernelEnd 0x(%x)\n", kernelStart,
kernelEnd);
}
// Load program sections into memory
kernel->loadSections(physProxy, loadAddrMask);
DPRINTF(Loader, "Kernel start = %#x\n", kernelStart);
DPRINTF(Loader, "Kernel end = %#x\n", kernelEnd);
DPRINTF(Loader, "Kernel entry = %#x\n", kernelEntry);
DPRINTF(Loader, "Kernel loaded...\n");
}
}
activeCpus.clear();
}
void
System::replaceThreadContext(ThreadContext *tc, int context_id)
{
if (context_id >= threadContexts.size()) {
panic("replaceThreadContext: bad id, %d >= %d\n",
context_id, threadContexts.size());
}
threadContexts[context_id] = tc;
if (context_id < remoteGDB.size())
remoteGDB[context_id]->replaceThreadContext(tc);
}
Addr
System::allocPhysPages(int npages)
{
Addr return_addr = pagePtr << LogVMPageSize;
pagePtr += npages;
if ((pagePtr << LogVMPageSize) > physmem.totalSize())
fatal("Out of memory, please increase size of physical memory.");
return return_addr;
}
Addr
System::memSize() const
{
return physmem.totalSize();
}
Addr
System::freeMemSize() const
{
return physmem.totalSize() - (pagePtr << LogVMPageSize);
}
bool
System::isMemAddr(Addr addr) const
{
return physmem.isMemAddr(addr);
}
void
System::resume()
{
SimObject::resume();
totalNumInsts = 0;
}
void
System::serialize(ostream &os)
{
if (FullSystem)
kernelSymtab->serialize("kernel_symtab", os);
SERIALIZE_SCALAR(pagePtr);
SERIALIZE_SCALAR(nextPID);
}
void
System::unserialize(Checkpoint *cp, const string §ion)
{
if (FullSystem)
kernelSymtab->unserialize("kernel_symtab", cp, section);
UNSERIALIZE_SCALAR(pagePtr);
UNSERIALIZE_SCALAR(nextPID);
}
void
System::regStats()
{
for (uint32_t j = 0; j < numWorkIds ; j++) {
workItemStats[j] = new Stats::Histogram();
stringstream namestr;
ccprintf(namestr, "work_item_type%d", j);
workItemStats[j]->init(20)
.name(name() + "." + namestr.str())
.desc("Run time stat for" + namestr.str())
.prereq(*workItemStats[j]);
}
}
void
System::workItemEnd(uint32_t tid, uint32_t workid)
{
std::pair<uint32_t,uint32_t> p(tid, workid);
if (!lastWorkItemStarted.count(p))
return;
Tick samp = curTick() - lastWorkItemStarted[p];
DPRINTF(WorkItems, "Work item end: %d\t%d\t%lld\n", tid, workid, samp);
if (workid >= numWorkIds)
fatal("Got workid greater than specified in system configuration\n");
workItemStats[workid]->sample(samp);
lastWorkItemStarted.erase(p);
}
void
System::printSystems()
{
vector<System *>::iterator i = systemList.begin();
vector<System *>::iterator end = systemList.end();
for (; i != end; ++i) {
System *sys = *i;
cerr << "System " << sys->name() << ": " << hex << sys << endl;
}
}
void
printSystems()
{
System::printSystems();
}
MasterID
System::getMasterId(std::string master_name)
{
// strip off system name if the string starts with it
if (startswith(master_name, name()))
master_name = master_name.erase(0, name().size() + 1);
// CPUs in switch_cpus ask for ids again after switching
for (int i = 0; i < masterIds.size(); i++) {
if (masterIds[i] == master_name) {
return i;
}
}
// Verify that the statistics haven't been enabled yet
// Otherwise objects will have sized their stat buckets and
// they will be too small
if (Stats::enabled())
fatal("Can't request a masterId after regStats(). \
You must do so in init().\n");
masterIds.push_back(master_name);
return masterIds.size() - 1;
}
std::string
System::getMasterName(MasterID master_id)
{
if (master_id >= masterIds.size())
fatal("Invalid master_id passed to getMasterName()\n");
return masterIds[master_id];
}
const char *System::MemoryModeStrings[3] = {"invalid", "atomic",
"timing"};
System *
SystemParams::create()
{
return new System(this);
}
|
add validation to make sure there is memory where we're loading the kernel
|
sim: add validation to make sure there is memory where we're loading the kernel
|
C++
|
bsd-3-clause
|
zlfben/gem5,markoshorro/gem5,briancoutinho0905/2dsampling,joerocklin/gem5,qizenguf/MLC-STT,markoshorro/gem5,TUD-OS/gem5-dtu,briancoutinho0905/2dsampling,Weil0ng/gem5,gedare/gem5,samueldotj/TeeRISC-Simulator,KuroeKurose/gem5,cancro7/gem5,aclifton/cpeg853-gem5,aclifton/cpeg853-gem5,joerocklin/gem5,KuroeKurose/gem5,SanchayanMaity/gem5,powerjg/gem5-ci-test,qizenguf/MLC-STT,austinharris/gem5-riscv,kaiyuanl/gem5,gedare/gem5,qizenguf/MLC-STT,HwisooSo/gemV-update,rjschof/gem5,austinharris/gem5-riscv,SanchayanMaity/gem5,zlfben/gem5,rallylee/gem5,sobercoder/gem5,qizenguf/MLC-STT,qizenguf/MLC-STT,rallylee/gem5,KuroeKurose/gem5,rjschof/gem5,gedare/gem5,markoshorro/gem5,KuroeKurose/gem5,samueldotj/TeeRISC-Simulator,yb-kim/gemV,rallylee/gem5,powerjg/gem5-ci-test,gedare/gem5,kaiyuanl/gem5,aclifton/cpeg853-gem5,samueldotj/TeeRISC-Simulator,Weil0ng/gem5,austinharris/gem5-riscv,briancoutinho0905/2dsampling,markoshorro/gem5,zlfben/gem5,samueldotj/TeeRISC-Simulator,aclifton/cpeg853-gem5,cancro7/gem5,gem5/gem5,Weil0ng/gem5,cancro7/gem5,yb-kim/gemV,sobercoder/gem5,zlfben/gem5,zlfben/gem5,gedare/gem5,briancoutinho0905/2dsampling,TUD-OS/gem5-dtu,qizenguf/MLC-STT,austinharris/gem5-riscv,rjschof/gem5,kaiyuanl/gem5,powerjg/gem5-ci-test,austinharris/gem5-riscv,TUD-OS/gem5-dtu,Weil0ng/gem5,rallylee/gem5,samueldotj/TeeRISC-Simulator,yb-kim/gemV,rjschof/gem5,Weil0ng/gem5,SanchayanMaity/gem5,joerocklin/gem5,TUD-OS/gem5-dtu,Weil0ng/gem5,rjschof/gem5,cancro7/gem5,HwisooSo/gemV-update,yb-kim/gemV,joerocklin/gem5,yb-kim/gemV,powerjg/gem5-ci-test,gem5/gem5,rjschof/gem5,TUD-OS/gem5-dtu,KuroeKurose/gem5,SanchayanMaity/gem5,HwisooSo/gemV-update,austinharris/gem5-riscv,powerjg/gem5-ci-test,HwisooSo/gemV-update,SanchayanMaity/gem5,samueldotj/TeeRISC-Simulator,austinharris/gem5-riscv,qizenguf/MLC-STT,powerjg/gem5-ci-test,rallylee/gem5,TUD-OS/gem5-dtu,gem5/gem5,SanchayanMaity/gem5,sobercoder/gem5,kaiyuanl/gem5,briancoutinho0905/2dsampling,gedare/gem5,KuroeKurose/gem5,gem5/gem5,sobercoder/gem5,aclifton/cpeg853-gem5,gedare/gem5,rallylee/gem5,KuroeKurose/gem5,markoshorro/gem5,joerocklin/gem5,briancoutinho0905/2dsampling,joerocklin/gem5,joerocklin/gem5,rjschof/gem5,TUD-OS/gem5-dtu,powerjg/gem5-ci-test,zlfben/gem5,kaiyuanl/gem5,cancro7/gem5,yb-kim/gemV,yb-kim/gemV,aclifton/cpeg853-gem5,markoshorro/gem5,Weil0ng/gem5,aclifton/cpeg853-gem5,joerocklin/gem5,HwisooSo/gemV-update,sobercoder/gem5,cancro7/gem5,sobercoder/gem5,HwisooSo/gemV-update,sobercoder/gem5,kaiyuanl/gem5,markoshorro/gem5,cancro7/gem5,SanchayanMaity/gem5,samueldotj/TeeRISC-Simulator,yb-kim/gemV,zlfben/gem5,gem5/gem5,briancoutinho0905/2dsampling,gem5/gem5,HwisooSo/gemV-update,kaiyuanl/gem5,gem5/gem5,rallylee/gem5
|
640f45a5b3c2990b7fe8ec466946e87d61ba59d0
|
browser/net/adapter_request_job.cc
|
browser/net/adapter_request_job.cc
|
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "browser/net/adapter_request_job.h"
#include "browser/net/url_request_string_job.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/net_errors.h"
#include "net/url_request/url_request_error_job.h"
#include "net/url_request/url_request_file_job.h"
namespace atom {
AdapterRequestJob::AdapterRequestJob(ProtocolHandler* protocol_handler,
net::URLRequest* request,
net::NetworkDelegate* network_delegate)
: URLRequestJob(request, network_delegate),
protocol_handler_(protocol_handler),
weak_factory_(this) {
}
void AdapterRequestJob::Start() {
DCHECK(!real_job_);
content::BrowserThread::PostTask(
content::BrowserThread::UI,
FROM_HERE,
base::Bind(&AdapterRequestJob::GetJobTypeInUI,
weak_factory_.GetWeakPtr()));
}
void AdapterRequestJob::Kill() {
DCHECK(real_job_);
real_job_->Kill();
}
bool AdapterRequestJob::ReadRawData(net::IOBuffer* buf,
int buf_size,
int *bytes_read) {
DCHECK(real_job_);
return real_job_->ReadRawData(buf, buf_size, bytes_read);
}
bool AdapterRequestJob::IsRedirectResponse(GURL* location,
int* http_status_code) {
DCHECK(real_job_);
return real_job_->IsRedirectResponse(location, http_status_code);
}
net::Filter* AdapterRequestJob::SetupFilter() const {
DCHECK(real_job_);
return real_job_->SetupFilter();
}
bool AdapterRequestJob::GetMimeType(std::string* mime_type) const {
DCHECK(real_job_);
return real_job_->GetMimeType(mime_type);
}
bool AdapterRequestJob::GetCharset(std::string* charset) {
DCHECK(real_job_);
return real_job_->GetCharset(charset);
}
base::WeakPtr<AdapterRequestJob> AdapterRequestJob::GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
void AdapterRequestJob::CreateErrorJobAndStart(int error_code) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
real_job_ = new net::URLRequestErrorJob(
request(), network_delegate(), error_code);
real_job_->Start();
}
void AdapterRequestJob::CreateStringJobAndStart(const std::string& mime_type,
const std::string& charset,
const std::string& data) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
real_job_ = new URLRequestStringJob(
request(), network_delegate(), mime_type, charset, data);
real_job_->Start();
}
void AdapterRequestJob::CreateFileJobAndStart(const base::FilePath& path) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
real_job_ = new net::URLRequestFileJob(request(), network_delegate(), path);
real_job_->Start();
}
void AdapterRequestJob::CreateJobFromProtocolHandlerAndStart() {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
DCHECK(protocol_handler_);
real_job_ = protocol_handler_->MaybeCreateJob(request(),
network_delegate());
if (!real_job_.get())
CreateErrorJobAndStart(net::ERR_NOT_IMPLEMENTED);
else
real_job_->Start();
}
} // namespace atom
|
// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "browser/net/adapter_request_job.h"
#include "browser/net/url_request_string_job.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/net_errors.h"
#include "net/url_request/url_request_error_job.h"
#include "net/url_request/url_request_file_job.h"
namespace atom {
AdapterRequestJob::AdapterRequestJob(ProtocolHandler* protocol_handler,
net::URLRequest* request,
net::NetworkDelegate* network_delegate)
: URLRequestJob(request, network_delegate),
protocol_handler_(protocol_handler),
weak_factory_(this) {
}
void AdapterRequestJob::Start() {
DCHECK(!real_job_);
content::BrowserThread::PostTask(
content::BrowserThread::UI,
FROM_HERE,
base::Bind(&AdapterRequestJob::GetJobTypeInUI,
weak_factory_.GetWeakPtr()));
}
void AdapterRequestJob::Kill() {
if (real_job_) // Kill could happen when real_job_ is created.
real_job_->Kill();
}
bool AdapterRequestJob::ReadRawData(net::IOBuffer* buf,
int buf_size,
int *bytes_read) {
DCHECK(real_job_);
return real_job_->ReadRawData(buf, buf_size, bytes_read);
}
bool AdapterRequestJob::IsRedirectResponse(GURL* location,
int* http_status_code) {
DCHECK(real_job_);
return real_job_->IsRedirectResponse(location, http_status_code);
}
net::Filter* AdapterRequestJob::SetupFilter() const {
DCHECK(real_job_);
return real_job_->SetupFilter();
}
bool AdapterRequestJob::GetMimeType(std::string* mime_type) const {
DCHECK(real_job_);
return real_job_->GetMimeType(mime_type);
}
bool AdapterRequestJob::GetCharset(std::string* charset) {
DCHECK(real_job_);
return real_job_->GetCharset(charset);
}
base::WeakPtr<AdapterRequestJob> AdapterRequestJob::GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
void AdapterRequestJob::CreateErrorJobAndStart(int error_code) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
real_job_ = new net::URLRequestErrorJob(
request(), network_delegate(), error_code);
real_job_->Start();
}
void AdapterRequestJob::CreateStringJobAndStart(const std::string& mime_type,
const std::string& charset,
const std::string& data) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
real_job_ = new URLRequestStringJob(
request(), network_delegate(), mime_type, charset, data);
real_job_->Start();
}
void AdapterRequestJob::CreateFileJobAndStart(const base::FilePath& path) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
real_job_ = new net::URLRequestFileJob(request(), network_delegate(), path);
real_job_->Start();
}
void AdapterRequestJob::CreateJobFromProtocolHandlerAndStart() {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
DCHECK(protocol_handler_);
real_job_ = protocol_handler_->MaybeCreateJob(request(),
network_delegate());
if (!real_job_.get())
CreateErrorJobAndStart(net::ERR_NOT_IMPLEMENTED);
else
real_job_->Start();
}
} // namespace atom
|
Fix a possible crash when calling AdapterRequestJob::Kill().
|
Fix a possible crash when calling AdapterRequestJob::Kill().
|
C++
|
mit
|
minggo/electron,Neron-X5/electron,jlhbaseball15/electron,leolujuyi/electron,jhen0409/electron,ankitaggarwal011/electron,saronwei/electron,shennushi/electron,carsonmcdonald/electron,Faiz7412/electron,abhishekgahlot/electron,pandoraui/electron,matiasinsaurralde/electron,kcrt/electron,jlord/electron,meowlab/electron,electron/electron,egoist/electron,icattlecoder/electron,coderhaoxin/electron,rsvip/electron,rsvip/electron,jaanus/electron,leethomas/electron,howmuchcomputer/electron,voidbridge/electron,kikong/electron,tinydew4/electron,gabriel/electron,sshiting/electron,yan-foto/electron,nicobot/electron,fffej/electron,Andrey-Pavlov/electron,MaxWhere/electron,sshiting/electron,bbondy/electron,joneit/electron,Floato/electron,mhkeller/electron,leolujuyi/electron,bobwol/electron,brave/electron,benweissmann/electron,jacksondc/electron,aichingm/electron,tylergibson/electron,bwiggs/electron,Andrey-Pavlov/electron,aecca/electron,nagyistoce/electron-atom-shell,pombredanne/electron,gstack/infinium-shell,SufianHassan/electron,Evercoder/electron,dahal/electron,mhkeller/electron,shockone/electron,thomsonreuters/electron,meowlab/electron,aaron-goshine/electron,kcrt/electron,systembugtj/electron,rajatsingla28/electron,rprichard/electron,jsutcodes/electron,iftekeriba/electron,nekuz0r/electron,anko/electron,fffej/electron,ankitaggarwal011/electron,d-salas/electron,Floato/electron,thomsonreuters/electron,carsonmcdonald/electron,pombredanne/electron,destan/electron,roadev/electron,jiaz/electron,preco21/electron,mrwizard82d1/electron,RIAEvangelist/electron,trigrass2/electron,mjaniszew/electron,medixdev/electron,MaxWhere/electron,jjz/electron,mrwizard82d1/electron,joaomoreno/atom-shell,kokdemo/electron,sky7sea/electron,adcentury/electron,mjaniszew/electron,cos2004/electron,felixrieseberg/electron,John-Lin/electron,vipulroxx/electron,zhakui/electron,chriskdon/electron,fireball-x/atom-shell,eriser/electron,JussMee15/electron,adcentury/electron,nicobot/electron,Andrey-Pavlov/electron,christian-bromann/electron,gamedevsam/electron,gabriel/electron,trigrass2/electron,timruffles/electron,Gerhut/electron,etiktin/electron,leethomas/electron,Floato/electron,medixdev/electron,gbn972/electron,MaxGraey/electron,bobwol/electron,brave/muon,wan-qy/electron,Jonekee/electron,cos2004/electron,trigrass2/electron,brave/muon,takashi/electron,Jacobichou/electron,meowlab/electron,tylergibson/electron,eric-seekas/electron,oiledCode/electron,deed02392/electron,soulteary/electron,aliib/electron,minggo/electron,natgolov/electron,benweissmann/electron,JesselJohn/electron,joaomoreno/atom-shell,Ivshti/electron,pandoraui/electron,ervinb/electron,bpasero/electron,jjz/electron,baiwyc119/electron,John-Lin/electron,evgenyzinoviev/electron,mattotodd/electron,webmechanicx/electron,digideskio/electron,mirrh/electron,eric-seekas/electron,jannishuebl/electron,Zagorakiss/electron,jonatasfreitasv/electron,kcrt/electron,bobwol/electron,robinvandernoord/electron,cqqccqc/electron,vipulroxx/electron,shennushi/electron,micalan/electron,soulteary/electron,LadyNaggaga/electron,pirafrank/electron,Jacobichou/electron,twolfson/electron,mattdesl/electron,cos2004/electron,rreimann/electron,Gerhut/electron,hokein/atom-shell,icattlecoder/electron,aichingm/electron,gabrielPeart/electron,howmuchcomputer/electron,meowlab/electron,cqqccqc/electron,takashi/electron,gamedevsam/electron,preco21/electron,tinydew4/electron,webmechanicx/electron,benweissmann/electron,jsutcodes/electron,fomojola/electron,takashi/electron,jsutcodes/electron,Floato/electron,leftstick/electron,dkfiresky/electron,digideskio/electron,abhishekgahlot/electron,fomojola/electron,jtburke/electron,faizalpribadi/electron,webmechanicx/electron,kenmozi/electron,gerhardberger/electron,roadev/electron,dahal/electron,seanchas116/electron,pandoraui/electron,smczk/electron,thomsonreuters/electron,ianscrivener/electron,stevekinney/electron,the-ress/electron,noikiy/electron,voidbridge/electron,lzpfmh/electron,fabien-d/electron,webmechanicx/electron,Jacobichou/electron,jjz/electron,kokdemo/electron,iftekeriba/electron,leftstick/electron,fritx/electron,felixrieseberg/electron,gabrielPeart/electron,wan-qy/electron,evgenyzinoviev/electron,edulan/electron,setzer777/electron,d-salas/electron,thingsinjars/electron,brave/electron,Rokt33r/electron,synaptek/electron,coderhaoxin/electron,fireball-x/atom-shell,vHanda/electron,jtburke/electron,coderhaoxin/electron,bpasero/electron,christian-bromann/electron,Jonekee/electron,John-Lin/electron,lzpfmh/electron,sky7sea/electron,nagyistoce/electron-atom-shell,arusakov/electron,ianscrivener/electron,John-Lin/electron,gamedevsam/electron,SufianHassan/electron,fomojola/electron,jlhbaseball15/electron,systembugtj/electron,arturts/electron,twolfson/electron,zhakui/electron,brenca/electron,smczk/electron,MaxGraey/electron,mrwizard82d1/electron,nicholasess/electron,pirafrank/electron,nagyistoce/electron-atom-shell,thompsonemerson/electron,Jonekee/electron,bitemyapp/electron,adcentury/electron,mubassirhayat/electron,ankitaggarwal011/electron,minggo/electron,tylergibson/electron,fomojola/electron,bitemyapp/electron,stevekinney/electron,deepak1556/atom-shell,MaxWhere/electron,greyhwndz/electron,wolfflow/electron,benweissmann/electron,d-salas/electron,stevekinney/electron,electron/electron,renaesop/electron,shennushi/electron,etiktin/electron,ervinb/electron,mhkeller/electron,iftekeriba/electron,electron/electron,smczk/electron,Faiz7412/electron,evgenyzinoviev/electron,nicobot/electron,seanchas116/electron,LadyNaggaga/electron,RIAEvangelist/electron,cqqccqc/electron,mirrh/electron,chrisswk/electron,baiwyc119/electron,carsonmcdonald/electron,edulan/electron,pirafrank/electron,brave/electron,etiktin/electron,fffej/electron,wan-qy/electron,minggo/electron,dahal/electron,John-Lin/electron,fritx/electron,michaelchiche/electron,IonicaBizauKitchen/electron,jonatasfreitasv/electron,matiasinsaurralde/electron,xfstudio/electron,jlhbaseball15/electron,iftekeriba/electron,thompsonemerson/electron,Zagorakiss/electron,howmuchcomputer/electron,jannishuebl/electron,soulteary/electron,kostia/electron,cos2004/electron,Neron-X5/electron,greyhwndz/electron,evgenyzinoviev/electron,edulan/electron,subblue/electron,chriskdon/electron,joneit/electron,rreimann/electron,mhkeller/electron,felixrieseberg/electron,rprichard/electron,rreimann/electron,tomashanacek/electron,leftstick/electron,tomashanacek/electron,neutrous/electron,pirafrank/electron,Floato/electron,brenca/electron,tinydew4/electron,iftekeriba/electron,Faiz7412/electron,mirrh/electron,jtburke/electron,icattlecoder/electron,thingsinjars/electron,neutrous/electron,aliib/electron,simongregory/electron,mrwizard82d1/electron,mattotodd/electron,deepak1556/atom-shell,miniak/electron,the-ress/electron,etiktin/electron,mubassirhayat/electron,shiftkey/electron,robinvandernoord/electron,Neron-X5/electron,xiruibing/electron,aliib/electron,tomashanacek/electron,the-ress/electron,anko/electron,mattotodd/electron,kenmozi/electron,sircharleswatson/electron,jlhbaseball15/electron,tincan24/electron,rhencke/electron,lrlna/electron,shaundunne/electron,twolfson/electron,deed02392/electron,greyhwndz/electron,RobertJGabriel/electron,xfstudio/electron,yalexx/electron,JussMee15/electron,trankmichael/electron,shiftkey/electron,noikiy/electron,bruce/electron,gerhardberger/electron,JesselJohn/electron,pirafrank/electron,electron/electron,yan-foto/electron,tomashanacek/electron,systembugtj/electron,kazupon/electron,kikong/electron,oiledCode/electron,mrwizard82d1/electron,digideskio/electron,saronwei/electron,sircharleswatson/electron,Gerhut/electron,bobwol/electron,carsonmcdonald/electron,ervinb/electron,gbn972/electron,baiwyc119/electron,adcentury/electron,bright-sparks/electron,subblue/electron,gerhardberger/electron,chriskdon/electron,GoooIce/electron,tinydew4/electron,bright-sparks/electron,brave/muon,vaginessa/electron,xfstudio/electron,aichingm/electron,bpasero/electron,posix4e/electron,jcblw/electron,Rokt33r/electron,mhkeller/electron,lrlna/electron,faizalpribadi/electron,Ivshti/electron,dkfiresky/electron,Andrey-Pavlov/electron,d-salas/electron,tonyganch/electron,meowlab/electron,beni55/electron,mrwizard82d1/electron,kikong/electron,aaron-goshine/electron,fomojola/electron,faizalpribadi/electron,deepak1556/atom-shell,tincan24/electron,timruffles/electron,shaundunne/electron,arusakov/electron,soulteary/electron,Zagorakiss/electron,fffej/electron,Jonekee/electron,benweissmann/electron,gbn972/electron,dkfiresky/electron,jaanus/electron,bwiggs/electron,nicholasess/electron,shockone/electron,bruce/electron,LadyNaggaga/electron,aaron-goshine/electron,rsvip/electron,gabriel/electron,kokdemo/electron,GoooIce/electron,fomojola/electron,preco21/electron,miniak/electron,gbn972/electron,yan-foto/electron,zhakui/electron,brenca/electron,tylergibson/electron,brenca/electron,twolfson/electron,wolfflow/electron,jacksondc/electron,d-salas/electron,baiwyc119/electron,ankitaggarwal011/electron,ankitaggarwal011/electron,mjaniszew/electron,voidbridge/electron,tylergibson/electron,jacksondc/electron,oiledCode/electron,thingsinjars/electron,jcblw/electron,natgolov/electron,subblue/electron,miniak/electron,zhakui/electron,eriser/electron,jhen0409/electron,christian-bromann/electron,electron/electron,gerhardberger/electron,IonicaBizauKitchen/electron,mirrh/electron,kazupon/electron,vipulroxx/electron,digideskio/electron,minggo/electron,tonyganch/electron,JussMee15/electron,farmisen/electron,bpasero/electron,Rokt33r/electron,aliib/electron,rreimann/electron,biblerule/UMCTelnetHub,RobertJGabriel/electron,seanchas116/electron,micalan/electron,renaesop/electron,JussMee15/electron,sshiting/electron,abhishekgahlot/electron,eriser/electron,hokein/atom-shell,pombredanne/electron,abhishekgahlot/electron,baiwyc119/electron,mattdesl/electron,thomsonreuters/electron,kikong/electron,gbn972/electron,eric-seekas/electron,jaanus/electron,jonatasfreitasv/electron,sshiting/electron,trigrass2/electron,shaundunne/electron,vaginessa/electron,jjz/electron,nekuz0r/electron,deed02392/electron,icattlecoder/electron,nicholasess/electron,fireball-x/atom-shell,Ivshti/electron,leolujuyi/electron,RobertJGabriel/electron,fritx/electron,stevemao/electron,zhakui/electron,natgolov/electron,Gerhut/electron,nekuz0r/electron,jaanus/electron,dongjoon-hyun/electron,destan/electron,bruce/electron,biblerule/UMCTelnetHub,timruffles/electron,fritx/electron,neutrous/electron,rsvip/electron,synaptek/electron,simongregory/electron,Evercoder/electron,rhencke/electron,trigrass2/electron,subblue/electron,pombredanne/electron,jannishuebl/electron,mattdesl/electron,rhencke/electron,stevemao/electron,rajatsingla28/electron,shockone/electron,twolfson/electron,howmuchcomputer/electron,dongjoon-hyun/electron,jannishuebl/electron,stevekinney/electron,seanchas116/electron,dongjoon-hyun/electron,seanchas116/electron,bwiggs/electron,ianscrivener/electron,mirrh/electron,dkfiresky/electron,preco21/electron,rajatsingla28/electron,jsutcodes/electron,aichingm/electron,trankmichael/electron,chriskdon/electron,lrlna/electron,nicholasess/electron,xfstudio/electron,RobertJGabriel/electron,renaesop/electron,mubassirhayat/electron,Gerhut/electron,ianscrivener/electron,DivyaKMenon/electron,farmisen/electron,systembugtj/electron,bbondy/electron,chrisswk/electron,rhencke/electron,beni55/electron,joaomoreno/atom-shell,pandoraui/electron,gerhardberger/electron,yalexx/electron,cqqccqc/electron,Andrey-Pavlov/electron,abhishekgahlot/electron,tinydew4/electron,vaginessa/electron,joneit/electron,gabriel/electron,pandoraui/electron,bruce/electron,Zagorakiss/electron,Floato/electron,medixdev/electron,davazp/electron,jhen0409/electron,michaelchiche/electron,adcentury/electron,biblerule/UMCTelnetHub,SufianHassan/electron,natgolov/electron,systembugtj/electron,fffej/electron,saronwei/electron,gabriel/electron,saronwei/electron,mattdesl/electron,d-salas/electron,shennushi/electron,fabien-d/electron,jhen0409/electron,davazp/electron,RobertJGabriel/electron,preco21/electron,destan/electron,greyhwndz/electron,JesselJohn/electron,aecca/electron,Jacobichou/electron,sshiting/electron,brenca/electron,kenmozi/electron,tincan24/electron,webmechanicx/electron,joneit/electron,aecca/electron,smczk/electron,medixdev/electron,benweissmann/electron,nicholasess/electron,brave/muon,BionicClick/electron,Jonekee/electron,bitemyapp/electron,MaxGraey/electron,bruce/electron,Faiz7412/electron,abhishekgahlot/electron,wan-qy/electron,hokein/atom-shell,smczk/electron,synaptek/electron,robinvandernoord/electron,voidbridge/electron,Rokt33r/electron,mubassirhayat/electron,jonatasfreitasv/electron,bwiggs/electron,kostia/electron,rprichard/electron,aaron-goshine/electron,RIAEvangelist/electron,stevemao/electron,bpasero/electron,yan-foto/electron,jacksondc/electron,simongregory/electron,bbondy/electron,pombredanne/electron,xfstudio/electron,BionicClick/electron,matiasinsaurralde/electron,bitemyapp/electron,subblue/electron,brave/electron,simonfork/electron,Zagorakiss/electron,lzpfmh/electron,IonicaBizauKitchen/electron,vaginessa/electron,deed02392/electron,kcrt/electron,evgenyzinoviev/electron,ankitaggarwal011/electron,jacksondc/electron,joaomoreno/atom-shell,thomsonreuters/electron,MaxGraey/electron,posix4e/electron,nicobot/electron,davazp/electron,stevekinney/electron,bright-sparks/electron,kazupon/electron,SufianHassan/electron,felixrieseberg/electron,simongregory/electron,smczk/electron,fireball-x/atom-shell,gstack/infinium-shell,noikiy/electron,eric-seekas/electron,faizalpribadi/electron,gabrielPeart/electron,anko/electron,arturts/electron,brave/muon,leolujuyi/electron,miniak/electron,maxogden/atom-shell,sky7sea/electron,shaundunne/electron,deed02392/electron,jannishuebl/electron,edulan/electron,sircharleswatson/electron,jcblw/electron,eric-seekas/electron,jaanus/electron,robinvandernoord/electron,medixdev/electron,ianscrivener/electron,dongjoon-hyun/electron,beni55/electron,joaomoreno/atom-shell,arusakov/electron,gamedevsam/electron,jhen0409/electron,kostia/electron,felixrieseberg/electron,vHanda/electron,jacksondc/electron,ervinb/electron,setzer777/electron,micalan/electron,roadev/electron,egoist/electron,bitemyapp/electron,DivyaKMenon/electron,astoilkov/electron,iftekeriba/electron,systembugtj/electron,davazp/electron,posix4e/electron,egoist/electron,vaginessa/electron,jlord/electron,setzer777/electron,tylergibson/electron,thompsonemerson/electron,chriskdon/electron,gerhardberger/electron,shiftkey/electron,darwin/electron,joneit/electron,christian-bromann/electron,pandoraui/electron,meowlab/electron,destan/electron,thingsinjars/electron,jiaz/electron,aecca/electron,vHanda/electron,mjaniszew/electron,leftstick/electron,voidbridge/electron,renaesop/electron,davazp/electron,Evercoder/electron,IonicaBizauKitchen/electron,neutrous/electron,leftstick/electron,greyhwndz/electron,gabrielPeart/electron,nekuz0r/electron,oiledCode/electron,MaxGraey/electron,kenmozi/electron,setzer777/electron,RIAEvangelist/electron,matiasinsaurralde/electron,LadyNaggaga/electron,gabrielPeart/electron,davazp/electron,trigrass2/electron,mattotodd/electron,aichingm/electron,simonfork/electron,gamedevsam/electron,Neron-X5/electron,jlord/electron,anko/electron,bitemyapp/electron,maxogden/atom-shell,darwin/electron,Rokt33r/electron,bbondy/electron,sky7sea/electron,brave/electron,mattdesl/electron,jcblw/electron,chrisswk/electron,stevemao/electron,leftstick/electron,sircharleswatson/electron,simonfork/electron,BionicClick/electron,jjz/electron,carsonmcdonald/electron,adamjgray/electron,electron/electron,DivyaKMenon/electron,fritx/electron,JussMee15/electron,BionicClick/electron,arturts/electron,Faiz7412/electron,the-ress/electron,natgolov/electron,the-ress/electron,carsonmcdonald/electron,jlhbaseball15/electron,noikiy/electron,shiftkey/electron,ianscrivener/electron,JesselJohn/electron,icattlecoder/electron,arusakov/electron,lrlna/electron,digideskio/electron,BionicClick/electron,mattotodd/electron,Rokt33r/electron,michaelchiche/electron,kokdemo/electron,nekuz0r/electron,roadev/electron,rreimann/electron,aecca/electron,joneit/electron,vipulroxx/electron,arturts/electron,dkfiresky/electron,christian-bromann/electron,astoilkov/electron,JesselJohn/electron,tincan24/electron,kostia/electron,noikiy/electron,setzer777/electron,shennushi/electron,adamjgray/electron,chrisswk/electron,tonyganch/electron,takashi/electron,tonyganch/electron,digideskio/electron,deepak1556/atom-shell,noikiy/electron,DivyaKMenon/electron,takashi/electron,xfstudio/electron,rhencke/electron,edulan/electron,posix4e/electron,biblerule/UMCTelnetHub,jtburke/electron,Neron-X5/electron,cqqccqc/electron,yan-foto/electron,natgolov/electron,thompsonemerson/electron,eriser/electron,gabrielPeart/electron,nicobot/electron,farmisen/electron,SufianHassan/electron,darwin/electron,michaelchiche/electron,simonfork/electron,icattlecoder/electron,brave/electron,maxogden/atom-shell,yalexx/electron,medixdev/electron,bpasero/electron,SufianHassan/electron,vipulroxx/electron,michaelchiche/electron,jaanus/electron,tinydew4/electron,lzpfmh/electron,vaginessa/electron,hokein/atom-shell,bbondy/electron,kikong/electron,gstack/infinium-shell,posix4e/electron,simonfork/electron,jonatasfreitasv/electron,sircharleswatson/electron,neutrous/electron,nicobot/electron,sircharleswatson/electron,fritx/electron,DivyaKMenon/electron,jlhbaseball15/electron,synaptek/electron,John-Lin/electron,gbn972/electron,takashi/electron,pirafrank/electron,dahal/electron,synaptek/electron,jiaz/electron,tonyganch/electron,farmisen/electron,adcentury/electron,DivyaKMenon/electron,farmisen/electron,gerhardberger/electron,kostia/electron,beni55/electron,zhakui/electron,jtburke/electron,thomsonreuters/electron,shockone/electron,jiaz/electron,trankmichael/electron,synaptek/electron,BionicClick/electron,sky7sea/electron,bright-sparks/electron,kcrt/electron,cos2004/electron,wolfflow/electron,greyhwndz/electron,hokein/atom-shell,ervinb/electron,oiledCode/electron,renaesop/electron,rajatsingla28/electron,jtburke/electron,soulteary/electron,leolujuyi/electron,robinvandernoord/electron,destan/electron,kazupon/electron,thingsinjars/electron,aliib/electron,wan-qy/electron,Ivshti/electron,etiktin/electron,eric-seekas/electron,wolfflow/electron,aaron-goshine/electron,JesselJohn/electron,kenmozi/electron,deepak1556/atom-shell,gamedevsam/electron,roadev/electron,leolujuyi/electron,leethomas/electron,rsvip/electron,bobwol/electron,jjz/electron,simongregory/electron,trankmichael/electron,Jonekee/electron,Jacobichou/electron,mattotodd/electron,brave/muon,darwin/electron,jannishuebl/electron,Ivshti/electron,setzer777/electron,rreimann/electron,xiruibing/electron,jhen0409/electron,leethomas/electron,adamjgray/electron,the-ress/electron,LadyNaggaga/electron,rajatsingla28/electron,darwin/electron,vipulroxx/electron,kenmozi/electron,deed02392/electron,sshiting/electron,rhencke/electron,shaundunne/electron,matiasinsaurralde/electron,preco21/electron,dkfiresky/electron,gstack/infinium-shell,seanchas116/electron,mattdesl/electron,bobwol/electron,astoilkov/electron,aliib/electron,stevekinney/electron,lzpfmh/electron,IonicaBizauKitchen/electron,gabriel/electron,Evercoder/electron,yan-foto/electron,IonicaBizauKitchen/electron,cos2004/electron,neutrous/electron,coderhaoxin/electron,roadev/electron,tincan24/electron,shockone/electron,GoooIce/electron,kokdemo/electron,shaundunne/electron,mirrh/electron,stevemao/electron,nicholasess/electron,kokdemo/electron,egoist/electron,GoooIce/electron,Jacobichou/electron,anko/electron,bwiggs/electron,astoilkov/electron,trankmichael/electron,eriser/electron,gstack/infinium-shell,soulteary/electron,destan/electron,vHanda/electron,saronwei/electron,RobertJGabriel/electron,bwiggs/electron,lrlna/electron,aaron-goshine/electron,jsutcodes/electron,renaesop/electron,nekuz0r/electron,MaxWhere/electron,coderhaoxin/electron,adamjgray/electron,Evercoder/electron,RIAEvangelist/electron,kazupon/electron,shiftkey/electron,beni55/electron,tincan24/electron,tomashanacek/electron,twolfson/electron,mjaniszew/electron,arturts/electron,eriser/electron,maxogden/atom-shell,egoist/electron,jsutcodes/electron,dahal/electron,xiruibing/electron,aecca/electron,jcblw/electron,micalan/electron,MaxWhere/electron,Gerhut/electron,Evercoder/electron,xiruibing/electron,xiruibing/electron,jlord/electron,JussMee15/electron,Andrey-Pavlov/electron,nagyistoce/electron-atom-shell,farmisen/electron,miniak/electron,oiledCode/electron,trankmichael/electron,michaelchiche/electron,bbondy/electron,simonfork/electron,yalexx/electron,kostia/electron,bruce/electron,howmuchcomputer/electron,jlord/electron,jcblw/electron,nagyistoce/electron-atom-shell,jonatasfreitasv/electron,fabien-d/electron,yalexx/electron,egoist/electron,fabien-d/electron,astoilkov/electron,biblerule/UMCTelnetHub,sky7sea/electron,micalan/electron,lrlna/electron,MaxWhere/electron,robinvandernoord/electron,shiftkey/electron,matiasinsaurralde/electron,bpasero/electron,kcrt/electron,maxogden/atom-shell,lzpfmh/electron,mubassirhayat/electron,minggo/electron,voidbridge/electron,fireball-x/atom-shell,chriskdon/electron,xiruibing/electron,timruffles/electron,GoooIce/electron,GoooIce/electron,jiaz/electron,arusakov/electron,mjaniszew/electron,astoilkov/electron,Zagorakiss/electron,the-ress/electron,leethomas/electron,simongregory/electron,subblue/electron,dongjoon-hyun/electron,micalan/electron,adamjgray/electron,christian-bromann/electron,cqqccqc/electron,saronwei/electron,coderhaoxin/electron,edulan/electron,arturts/electron,evgenyzinoviev/electron,Neron-X5/electron,miniak/electron,wolfflow/electron,chrisswk/electron,anko/electron,thingsinjars/electron,rajatsingla28/electron,joaomoreno/atom-shell,mhkeller/electron,tomashanacek/electron,pombredanne/electron,electron/electron,thompsonemerson/electron,ervinb/electron,vHanda/electron,etiktin/electron,posix4e/electron,adamjgray/electron,jiaz/electron,faizalpribadi/electron,rprichard/electron,bright-sparks/electron,aichingm/electron,LadyNaggaga/electron,brenca/electron,yalexx/electron,fffej/electron,dongjoon-hyun/electron,bright-sparks/electron,beni55/electron,vHanda/electron,dahal/electron,shennushi/electron,webmechanicx/electron,wan-qy/electron,biblerule/UMCTelnetHub,fabien-d/electron,timruffles/electron,tonyganch/electron,RIAEvangelist/electron,shockone/electron,wolfflow/electron,kazupon/electron,leethomas/electron,stevemao/electron,thompsonemerson/electron,felixrieseberg/electron,arusakov/electron,baiwyc119/electron,faizalpribadi/electron,howmuchcomputer/electron
|
1e669de380053a40b1ba48f14de1d8caac27000e
|
tinkerforge_laser_transform/src/laser_transform_node.cpp
|
tinkerforge_laser_transform/src/laser_transform_node.cpp
|
#include <iostream>
#include "ros/ros.h"
#include "sensor_msgs/PointCloud2.h"
#include "sensor_msgs/NavSatFix.h"
#include "sensor_msgs/MagneticField.h"
#include "sensor_msgs/Imu.h"
#include "sensor_msgs/JointState.h"
#include "nav_msgs/Odometry.h"
#include "laser_transform_core.h"
using std::string;
int main (int argc, char **argv)
{
ros::init(argc, argv, "laser_transform");
ros::NodeHandle n;
// Declare variables thar can be modified by launch file or command line.
int rate;
int imu_convergence_speed;
bool imu_msgs;
bool mf_msgs;
bool gps_msgs;
bool odo_msgs;
string pcl_in_topic;
string pcl_out_topic;
string mf_topic;
string imu_topic;
string gps_topic;
string odo_topic;
string odo_topic_filtered;
// Create a new LaserTransformer object.
LaserTransform *node_lt = new LaserTransform();
node_lt->init();
// while using different parameters.
ros::NodeHandle private_node_handle_("~");
private_node_handle_.param("rate", rate, int(10));
private_node_handle_.param("mf_msgs", mf_msgs, bool(false));
private_node_handle_.param("imu_msgs", imu_msgs, bool(true));
private_node_handle_.param("gps_msgs", gps_msgs, bool(false));
private_node_handle_.param("odo_msgs", odo_msgs, bool(true));
private_node_handle_.param("pcl_in_topic", pcl_in_topic, string("/cloud"));
private_node_handle_.param("pcl_out_topic", pcl_out_topic, string("/cloud_world"));
private_node_handle_.param("mf_topic", mf_topic, string("magnetic/data"));
private_node_handle_.param("imu_topic", imu_topic, string("/imu/data"));
private_node_handle_.param("gps_topic", gps_topic, string("/gps/fix"));
private_node_handle_.param("odo_topic", odo_topic, string("odom"));
private_node_handle_.param("odo_filtered", odo_topic_filtered, string("/odometry/filtered"));
private_node_handle_.param("imu_convergence_speed", imu_convergence_speed, int(20));
// Create a subscriber for laser scanner plc data
ros::Subscriber sub_pcl = n.subscribe(pcl_in_topic.c_str(), 1000, &LaserTransform::callbackPcl, node_lt);
// Create a subscriber for filtered odometry data
ros::Subscriber sub_odo = n.subscribe(odo_topic_filtered.c_str(), 1000, &LaserTransform::callbackOdometryFiltered, node_lt);
// Create a publisher for transformed plc msgs
ros::Publisher pcl_pub = n.advertise<sensor_msgs::PointCloud2>(pcl_out_topic.c_str(), 50);
node_lt->setPclPublisher(&pcl_pub);
// Create a publisher for transformed plc msgs
//ros::Publisher pub_joint = n.advertise<sensor_msgs::JointState Message>("fix_multicar", 50);
// Create a publisher for magnetic field msgs
ros::Publisher mf_pub = n.advertise<sensor_msgs::MagneticField>(mf_topic.c_str(), 50);
// Create a publisher for IMU msgs
ros::Publisher imu_pub = n.advertise<sensor_msgs::Imu>(imu_topic.c_str(), 50);
// Create a publisher for GPS msgs
ros::Publisher gps_pub = n.advertise<sensor_msgs::NavSatFix>(gps_topic.c_str(), 50);
// Create a publisher for odometry mesgs
ros::Publisher odo_pub = n.advertise<nav_msgs::Odometry>(odo_topic.c_str(),50);
ros::Rate r(rate);
while (n.ok())
{
//node_lt->publishPclMessage(&pcl_pub);
if (imu_msgs)
node_lt->publishImuMessage(&imu_pub);
if (gps_msgs)
node_lt->publishNavSatFixMessage(&gps_pub);
if (mf_msgs)
node_lt->publishMagneticFieldMessage(&mf_pub);
if (odo_msgs)
node_lt->publishOdometryMessage(&odo_pub);
ros::spinOnce();
r.sleep();
}
return 0;
// end main
}
|
#include <iostream>
#include "ros/ros.h"
#include "sensor_msgs/PointCloud2.h"
#include "sensor_msgs/NavSatFix.h"
#include "sensor_msgs/MagneticField.h"
#include "sensor_msgs/Imu.h"
#include "sensor_msgs/JointState.h"
#include "nav_msgs/Odometry.h"
#include "laser_transform_core.h"
using std::string;
int main (int argc, char **argv)
{
ros::init(argc, argv, "laser_transform");
ros::NodeHandle n;
// Declare variables thar can be modified by launch file or command line.
int rate;
int imu_convergence_speed;
bool imu_msgs;
bool mf_msgs;
bool gps_msgs;
bool odo_msgs;
string pcl_in_topic;
string pcl_out_topic;
string mf_topic;
string imu_topic;
string gps_topic;
string odo_topic;
string odo_topic_filtered;
XmlRpc::XmlRpcValue v;
// Create a new LaserTransformer object.
LaserTransform *node_lt = new LaserTransform();
node_lt->init();
// while using different parameters.
ros::NodeHandle private_node_handle_("~");
private_node_handle_.param("rate", rate, int(10));
private_node_handle_.param("mf_msgs", mf_msgs, bool(false));
private_node_handle_.param("imu_msgs", imu_msgs, bool(true));
private_node_handle_.param("gps_msgs", gps_msgs, bool(false));
private_node_handle_.param("odo_msgs", odo_msgs, bool(true));
private_node_handle_.param("pcl_in_topic", pcl_in_topic, string("/cloud"));
private_node_handle_.param("pcl_out_topic", pcl_out_topic, string("/cloud_world"));
private_node_handle_.param("mf_topic", mf_topic, string("magnetic/data"));
private_node_handle_.param("imu_topic", imu_topic, string("/imu/data"));
private_node_handle_.param("gps_topic", gps_topic, string("/gps/fix"));
private_node_handle_.param("odo_topic", odo_topic, string("odom"));
private_node_handle_.param("odo_filtered", odo_topic_filtered, string("/odometry/filtered"));
private_node_handle_.param("imu_convergence_speed", imu_convergence_speed, int(20));
private_node_handle_.param("laser_pose", v, v);
if (v.size() == 6 )//&& v.getType() == XmlRpc::XmlRpcValue::TypeArray)
{
node_lt->setLaserPose(static_cast<double>(v[0]), static_cast<double>(v[1]),
static_cast<double>(v[2]), static_cast<double>(v[3]), static_cast<double>(v[4]),
static_cast<double>(v[5]));
}
else
{
node_lt->setLaserPose(0.0,0.0,0.0,0.0,0.0,0.0);
}
// Create a subscriber for laser scanner plc data
ros::Subscriber sub_pcl = n.subscribe(pcl_in_topic.c_str(), 1000, &LaserTransform::callbackPcl, node_lt);
// Create a subscriber for filtered odometry data
ros::Subscriber sub_odo = n.subscribe(odo_topic_filtered.c_str(), 1000, &LaserTransform::callbackOdometryFiltered, node_lt);
// Create a publisher for transformed plc msgs
ros::Publisher pcl_pub = n.advertise<sensor_msgs::PointCloud2>(pcl_out_topic.c_str(), 50);
node_lt->setPclPublisher(&pcl_pub);
// Create a publisher for magnetic field msgs
ros::Publisher mf_pub = n.advertise<sensor_msgs::MagneticField>(mf_topic.c_str(), 50);
// Create a publisher for IMU msgs
ros::Publisher imu_pub = n.advertise<sensor_msgs::Imu>(imu_topic.c_str(), 50);
// Create a publisher for GPS msgs
ros::Publisher gps_pub = n.advertise<sensor_msgs::NavSatFix>(gps_topic.c_str(), 50);
// Create a publisher for odometry mesgs
ros::Publisher odo_pub = n.advertise<nav_msgs::Odometry>(odo_topic.c_str(),50);
ros::Rate r(rate);
while (n.ok())
{
//node_lt->publishPclMessage(&pcl_pub);
if (imu_msgs)
node_lt->publishImuMessage(&imu_pub);
if (gps_msgs)
node_lt->publishNavSatFixMessage(&gps_pub);
if (mf_msgs)
node_lt->publishMagneticFieldMessage(&mf_pub);
if (odo_msgs)
node_lt->publishOdometryMessage(&odo_pub);
ros::spinOnce();
r.sleep();
}
return 0;
}
|
add parameter laser pose
|
add parameter laser pose
|
C++
|
mit
|
gus484/ros,gus484/ros
|
ac4c75ba8253dbd918d0cb5aa8614d8f4f7d7ad7
|
lib/VMCore/Module.cpp
|
lib/VMCore/Module.cpp
|
//===-- Module.cpp - Implement the Module class ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Module class for the VMCore library.
//
//===----------------------------------------------------------------------===//
#include "llvm/Module.h"
#include "llvm/InstrTypes.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/LeakDetector.h"
#include "SymbolTableListTraitsImpl.h"
#include <algorithm>
#include <cstdarg>
#include <cstdlib>
#include <iostream>
#include <map>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Methods to implement the globals and functions lists.
//
Function *ilist_traits<Function>::createSentinel() {
FunctionType *FTy =
FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false);
Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage);
// This should not be garbage monitored.
LeakDetector::removeGarbageObject(Ret);
return Ret;
}
GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
GlobalVariable *Ret = new GlobalVariable(Type::IntTy, false,
GlobalValue::ExternalLinkage);
// This should not be garbage monitored.
LeakDetector::removeGarbageObject(Ret);
return Ret;
}
iplist<Function> &ilist_traits<Function>::getList(Module *M) {
return M->getFunctionList();
}
iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
return M->getGlobalList();
}
// Explicit instantiations of SymbolTableListTraits since some of the methods
// are not in the public header file.
template class SymbolTableListTraits<GlobalVariable, Module, Module>;
template class SymbolTableListTraits<Function, Module, Module>;
//===----------------------------------------------------------------------===//
// Primitive Module methods.
//
Module::Module(const std::string &MID)
: ModuleID(MID), DataLayout("") {
FunctionList.setItemParent(this);
FunctionList.setParent(this);
GlobalList.setItemParent(this);
GlobalList.setParent(this);
SymTab = new SymbolTable();
}
Module::~Module() {
dropAllReferences();
GlobalList.clear();
GlobalList.setParent(0);
FunctionList.clear();
FunctionList.setParent(0);
LibraryList.clear();
delete SymTab;
}
// Module::dump() - Allow printing from debugger
void Module::dump() const {
print(std::cerr);
}
/// Target endian information...
Module::Endianness Module::getEndianness() const {
std::string temp = DataLayout;
while (temp.length() > 0) {
std::string token = getToken(temp, "-");
if (token[0] == 'e') {
return LittleEndian;
} else if (token[0] == 'E') {
return BigEndian;
}
}
return AnyEndianness;
}
void Module::setEndianness(Endianness E) {
if (DataLayout.compare("") != 0 && E != AnyEndianness)
DataLayout.insert(0, "-");
if (E == LittleEndian)
DataLayout.insert(0, "e");
else if (E == BigEndian)
DataLayout.insert(0, "E");
}
/// Target Pointer Size information...
Module::PointerSize Module::getPointerSize() const {
std::string temp = DataLayout;
while (temp.length() > 0) {
std::string token = getToken(temp, "-");
char signal = getToken(token, ":")[0];
if (signal == 'p') {
int size = atoi(getToken(token, ":").c_str());
if (size == 32)
return Pointer32;
else if (size == 64)
return Pointer64;
}
}
return AnyPointerSize;
}
void Module::setPointerSize(PointerSize PS) {
if (DataLayout.compare("") != 0 && PS != AnyPointerSize)
DataLayout.insert(0, "-");
if (PS == Pointer32)
DataLayout.insert(0, "p:32:32");
else if (PS == Pointer64)
DataLayout.insert(0, "p:64:64");
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the functions in the module.
//
// getOrInsertFunction - Look up the specified function in the module symbol
// table. If it does not exist, add a prototype for the function and return
// it. This is nice because it allows most passes to get away with not handling
// the symbol table directly for this common task.
//
Function *Module::getOrInsertFunction(const std::string &Name,
const FunctionType *Ty) {
SymbolTable &SymTab = getSymbolTable();
// See if we have a definitions for the specified function already...
if (Value *V = SymTab.lookup(PointerType::get(Ty), Name)) {
return cast<Function>(V); // Yup, got it
} else { // Nope, add one
Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
FunctionList.push_back(New);
return New; // Return the new prototype...
}
}
// getOrInsertFunction - Look up the specified function in the module symbol
// table. If it does not exist, add a prototype for the function and return it.
// This version of the method takes a null terminated list of function
// arguments, which makes it easier for clients to use.
//
Function *Module::getOrInsertFunction(const std::string &Name,
const Type *RetTy, ...) {
va_list Args;
va_start(Args, RetTy);
// Build the list of argument types...
std::vector<const Type*> ArgTys;
while (const Type *ArgTy = va_arg(Args, const Type*))
ArgTys.push_back(ArgTy);
va_end(Args);
// Build the function type and chain to the other getOrInsertFunction...
return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
}
// getFunction - Look up the specified function in the module symbol table.
// If it does not exist, return null.
//
Function *Module::getFunction(const std::string &Name, const FunctionType *Ty) {
SymbolTable &SymTab = getSymbolTable();
return cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name));
}
/// getMainFunction - This function looks up main efficiently. This is such a
/// common case, that it is a method in Module. If main cannot be found, a
/// null pointer is returned.
///
Function *Module::getMainFunction() {
std::vector<const Type*> Params;
// int main(void)...
if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
Params, false)))
return F;
// void main(void)...
if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
Params, false)))
return F;
Params.push_back(Type::IntTy);
// int main(int argc)...
if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
Params, false)))
return F;
// void main(int argc)...
if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
Params, false)))
return F;
for (unsigned i = 0; i != 2; ++i) { // Check argv and envp
Params.push_back(PointerType::get(PointerType::get(Type::SByteTy)));
// int main(int argc, char **argv)...
if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
Params, false)))
return F;
// void main(int argc, char **argv)...
if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
Params, false)))
return F;
}
// Ok, try to find main the hard way...
return getNamedFunction("main");
}
/// getNamedFunction - Return the first function in the module with the
/// specified name, of arbitrary type. This method returns null if a function
/// with the specified name is not found.
///
Function *Module::getNamedFunction(const std::string &Name) {
// Loop over all of the functions, looking for the function desired
Function *Found = 0;
for (iterator I = begin(), E = end(); I != E; ++I)
if (I->getName() == Name)
if (I->isExternal())
Found = I;
else
return I;
return Found; // Non-external function not found...
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the global variables in the module.
//
/// getGlobalVariable - Look up the specified global variable in the module
/// symbol table. If it does not exist, return null. The type argument
/// should be the underlying type of the global, i.e., it should not have
/// the top-level PointerType, which represents the address of the global.
/// If AllowInternal is set to true, this function will return types that
/// have InternalLinkage. By default, these types are not returned.
///
GlobalVariable *Module::getGlobalVariable(const std::string &Name,
const Type *Ty, bool AllowInternal) {
if (Value *V = getSymbolTable().lookup(PointerType::get(Ty), Name)) {
GlobalVariable *Result = cast<GlobalVariable>(V);
if (AllowInternal || !Result->hasInternalLinkage())
return Result;
}
return 0;
}
/// getNamedGlobal - Return the first global variable in the module with the
/// specified name, of arbitrary type. This method returns null if a global
/// with the specified name is not found.
///
GlobalVariable *Module::getNamedGlobal(const std::string &Name) {
// FIXME: This would be much faster with a symbol table that doesn't
// discriminate based on type!
for (global_iterator I = global_begin(), E = global_end();
I != E; ++I)
if (I->getName() == Name)
return I;
return 0;
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the types in the module.
//
// addTypeName - Insert an entry in the symbol table mapping Str to Type. If
// there is already an entry for this name, true is returned and the symbol
// table is not modified.
//
bool Module::addTypeName(const std::string &Name, const Type *Ty) {
SymbolTable &ST = getSymbolTable();
if (ST.lookupType(Name)) return true; // Already in symtab...
// Not in symbol table? Set the name with the Symtab as an argument so the
// type knows what to update...
ST.insert(Name, Ty);
return false;
}
/// getTypeByName - Return the type with the specified name in this module, or
/// null if there is none by that name.
const Type *Module::getTypeByName(const std::string &Name) const {
const SymbolTable &ST = getSymbolTable();
return cast_or_null<Type>(ST.lookupType(Name));
}
// getTypeName - If there is at least one entry in the symbol table for the
// specified type, return it.
//
std::string Module::getTypeName(const Type *Ty) const {
const SymbolTable &ST = getSymbolTable();
SymbolTable::type_const_iterator TI = ST.type_begin();
SymbolTable::type_const_iterator TE = ST.type_end();
if ( TI == TE ) return ""; // No names for types
while (TI != TE && TI->second != Ty)
++TI;
if (TI != TE) // Must have found an entry!
return TI->first;
return ""; // Must not have found anything...
}
//===----------------------------------------------------------------------===//
// Other module related stuff.
//
// dropAllReferences() - This function causes all the subelementss to "let go"
// of all references that they are maintaining. This allows one to 'delete' a
// whole module at a time, even though there may be circular references... first
// all references are dropped, and all use counts go to zero. Then everything
// is deleted for real. Note that no operations are valid on an object that
// has "dropped all references", except operator delete.
//
void Module::dropAllReferences() {
for(Module::iterator I = begin(), E = end(); I != E; ++I)
I->dropAllReferences();
for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
I->dropAllReferences();
}
|
//===-- Module.cpp - Implement the Module class ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Module class for the VMCore library.
//
//===----------------------------------------------------------------------===//
#include "llvm/Module.h"
#include "llvm/InstrTypes.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/LeakDetector.h"
#include "SymbolTableListTraitsImpl.h"
#include <algorithm>
#include <cstdarg>
#include <cstdlib>
#include <iostream>
#include <map>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Methods to implement the globals and functions lists.
//
Function *ilist_traits<Function>::createSentinel() {
FunctionType *FTy =
FunctionType::get(Type::VoidTy, std::vector<const Type*>(), false);
Function *Ret = new Function(FTy, GlobalValue::ExternalLinkage);
// This should not be garbage monitored.
LeakDetector::removeGarbageObject(Ret);
return Ret;
}
GlobalVariable *ilist_traits<GlobalVariable>::createSentinel() {
GlobalVariable *Ret = new GlobalVariable(Type::IntTy, false,
GlobalValue::ExternalLinkage);
// This should not be garbage monitored.
LeakDetector::removeGarbageObject(Ret);
return Ret;
}
iplist<Function> &ilist_traits<Function>::getList(Module *M) {
return M->getFunctionList();
}
iplist<GlobalVariable> &ilist_traits<GlobalVariable>::getList(Module *M) {
return M->getGlobalList();
}
// Explicit instantiations of SymbolTableListTraits since some of the methods
// are not in the public header file.
template class SymbolTableListTraits<GlobalVariable, Module, Module>;
template class SymbolTableListTraits<Function, Module, Module>;
//===----------------------------------------------------------------------===//
// Primitive Module methods.
//
Module::Module(const std::string &MID)
: ModuleID(MID), DataLayout("") {
FunctionList.setItemParent(this);
FunctionList.setParent(this);
GlobalList.setItemParent(this);
GlobalList.setParent(this);
SymTab = new SymbolTable();
}
Module::~Module() {
dropAllReferences();
GlobalList.clear();
GlobalList.setParent(0);
FunctionList.clear();
FunctionList.setParent(0);
LibraryList.clear();
delete SymTab;
}
// Module::dump() - Allow printing from debugger
void Module::dump() const {
print(std::cerr);
}
/// Target endian information...
Module::Endianness Module::getEndianness() const {
std::string temp = DataLayout;
Module::Endianness ret = AnyEndianness;
while (!temp.empty()) {
std::string token = getToken(temp, "-");
if (token[0] == 'e') {
ret = LittleEndian;
} else if (token[0] == 'E') {
ret = BigEndian;
}
}
return ret;
}
void Module::setEndianness(Endianness E) {
if (!DataLayout.empty() && E != AnyEndianness)
DataLayout += "-";
if (E == LittleEndian)
DataLayout += "e";
else if (E == BigEndian)
DataLayout += "E";
}
/// Target Pointer Size information...
Module::PointerSize Module::getPointerSize() const {
std::string temp = DataLayout;
Module::PointerSize ret = AnyPointerSize;
while (!temp.empty()) {
std::string token = getToken(temp, "-");
char signal = getToken(token, ":")[0];
if (signal == 'p') {
int size = atoi(getToken(token, ":").c_str());
if (size == 32)
ret = Pointer32;
else if (size == 64)
ret = Pointer64;
}
}
return ret;
}
void Module::setPointerSize(PointerSize PS) {
if (!DataLayout.empty() && PS != AnyPointerSize)
DataLayout += "-";
if (PS == Pointer32)
DataLayout += "p:32:32";
else if (PS == Pointer64)
DataLayout += "p:64:64";
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the functions in the module.
//
// getOrInsertFunction - Look up the specified function in the module symbol
// table. If it does not exist, add a prototype for the function and return
// it. This is nice because it allows most passes to get away with not handling
// the symbol table directly for this common task.
//
Function *Module::getOrInsertFunction(const std::string &Name,
const FunctionType *Ty) {
SymbolTable &SymTab = getSymbolTable();
// See if we have a definitions for the specified function already...
if (Value *V = SymTab.lookup(PointerType::get(Ty), Name)) {
return cast<Function>(V); // Yup, got it
} else { // Nope, add one
Function *New = new Function(Ty, GlobalVariable::ExternalLinkage, Name);
FunctionList.push_back(New);
return New; // Return the new prototype...
}
}
// getOrInsertFunction - Look up the specified function in the module symbol
// table. If it does not exist, add a prototype for the function and return it.
// This version of the method takes a null terminated list of function
// arguments, which makes it easier for clients to use.
//
Function *Module::getOrInsertFunction(const std::string &Name,
const Type *RetTy, ...) {
va_list Args;
va_start(Args, RetTy);
// Build the list of argument types...
std::vector<const Type*> ArgTys;
while (const Type *ArgTy = va_arg(Args, const Type*))
ArgTys.push_back(ArgTy);
va_end(Args);
// Build the function type and chain to the other getOrInsertFunction...
return getOrInsertFunction(Name, FunctionType::get(RetTy, ArgTys, false));
}
// getFunction - Look up the specified function in the module symbol table.
// If it does not exist, return null.
//
Function *Module::getFunction(const std::string &Name, const FunctionType *Ty) {
SymbolTable &SymTab = getSymbolTable();
return cast_or_null<Function>(SymTab.lookup(PointerType::get(Ty), Name));
}
/// getMainFunction - This function looks up main efficiently. This is such a
/// common case, that it is a method in Module. If main cannot be found, a
/// null pointer is returned.
///
Function *Module::getMainFunction() {
std::vector<const Type*> Params;
// int main(void)...
if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
Params, false)))
return F;
// void main(void)...
if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
Params, false)))
return F;
Params.push_back(Type::IntTy);
// int main(int argc)...
if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
Params, false)))
return F;
// void main(int argc)...
if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
Params, false)))
return F;
for (unsigned i = 0; i != 2; ++i) { // Check argv and envp
Params.push_back(PointerType::get(PointerType::get(Type::SByteTy)));
// int main(int argc, char **argv)...
if (Function *F = getFunction("main", FunctionType::get(Type::IntTy,
Params, false)))
return F;
// void main(int argc, char **argv)...
if (Function *F = getFunction("main", FunctionType::get(Type::VoidTy,
Params, false)))
return F;
}
// Ok, try to find main the hard way...
return getNamedFunction("main");
}
/// getNamedFunction - Return the first function in the module with the
/// specified name, of arbitrary type. This method returns null if a function
/// with the specified name is not found.
///
Function *Module::getNamedFunction(const std::string &Name) {
// Loop over all of the functions, looking for the function desired
Function *Found = 0;
for (iterator I = begin(), E = end(); I != E; ++I)
if (I->getName() == Name)
if (I->isExternal())
Found = I;
else
return I;
return Found; // Non-external function not found...
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the global variables in the module.
//
/// getGlobalVariable - Look up the specified global variable in the module
/// symbol table. If it does not exist, return null. The type argument
/// should be the underlying type of the global, i.e., it should not have
/// the top-level PointerType, which represents the address of the global.
/// If AllowInternal is set to true, this function will return types that
/// have InternalLinkage. By default, these types are not returned.
///
GlobalVariable *Module::getGlobalVariable(const std::string &Name,
const Type *Ty, bool AllowInternal) {
if (Value *V = getSymbolTable().lookup(PointerType::get(Ty), Name)) {
GlobalVariable *Result = cast<GlobalVariable>(V);
if (AllowInternal || !Result->hasInternalLinkage())
return Result;
}
return 0;
}
/// getNamedGlobal - Return the first global variable in the module with the
/// specified name, of arbitrary type. This method returns null if a global
/// with the specified name is not found.
///
GlobalVariable *Module::getNamedGlobal(const std::string &Name) {
// FIXME: This would be much faster with a symbol table that doesn't
// discriminate based on type!
for (global_iterator I = global_begin(), E = global_end();
I != E; ++I)
if (I->getName() == Name)
return I;
return 0;
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the types in the module.
//
// addTypeName - Insert an entry in the symbol table mapping Str to Type. If
// there is already an entry for this name, true is returned and the symbol
// table is not modified.
//
bool Module::addTypeName(const std::string &Name, const Type *Ty) {
SymbolTable &ST = getSymbolTable();
if (ST.lookupType(Name)) return true; // Already in symtab...
// Not in symbol table? Set the name with the Symtab as an argument so the
// type knows what to update...
ST.insert(Name, Ty);
return false;
}
/// getTypeByName - Return the type with the specified name in this module, or
/// null if there is none by that name.
const Type *Module::getTypeByName(const std::string &Name) const {
const SymbolTable &ST = getSymbolTable();
return cast_or_null<Type>(ST.lookupType(Name));
}
// getTypeName - If there is at least one entry in the symbol table for the
// specified type, return it.
//
std::string Module::getTypeName(const Type *Ty) const {
const SymbolTable &ST = getSymbolTable();
SymbolTable::type_const_iterator TI = ST.type_begin();
SymbolTable::type_const_iterator TE = ST.type_end();
if ( TI == TE ) return ""; // No names for types
while (TI != TE && TI->second != Ty)
++TI;
if (TI != TE) // Must have found an entry!
return TI->first;
return ""; // Must not have found anything...
}
//===----------------------------------------------------------------------===//
// Other module related stuff.
//
// dropAllReferences() - This function causes all the subelementss to "let go"
// of all references that they are maintaining. This allows one to 'delete' a
// whole module at a time, even though there may be circular references... first
// all references are dropped, and all use counts go to zero. Then everything
// is deleted for real. Note that no operations are valid on an object that
// has "dropped all references", except operator delete.
//
void Module::dropAllReferences() {
for(Module::iterator I = begin(), E = end(); I != E; ++I)
I->dropAllReferences();
for(Module::global_iterator I = global_begin(), E = global_end(); I != E; ++I)
I->dropAllReferences();
}
|
Fix some think-o's in my last commit. Thanks to Chris for pointing them out.
|
Fix some think-o's in my last commit. Thanks to Chris for pointing them out.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@28380 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,chubbymaggie/asap,dslab-epfl/asap,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,chubbymaggie/asap,dslab-epfl/asap,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap
|
b01f3bafe6a74a21109355573328b2dd8c35a5b9
|
src/components/transport_manager/src/bluetooth/bluetooth_socket_connection.cc
|
src/components/transport_manager/src/bluetooth/bluetooth_socket_connection.cc
|
/*
*
* Copyright (c) 2013, Ford Motor Company
* 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 Ford Motor Company 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 "transport_manager/bluetooth/bluetooth_socket_connection.h"
#include <unistd.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
#include <bluetooth/sdp.h>
#include <bluetooth/sdp_lib.h>
#include <bluetooth/rfcomm.h>
#include "transport_manager/bluetooth/bluetooth_device.h"
#include "transport_manager/transport_adapter/transport_adapter_controller.h"
#include "utils/logger.h"
namespace transport_manager {
namespace transport_adapter {
CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
BluetoothSocketConnection::BluetoothSocketConnection(
const DeviceUID& device_uid, const ApplicationHandle& app_handle,
TransportAdapterController* controller)
: ThreadedSocketConnection(device_uid, app_handle, controller) {
}
BluetoothSocketConnection::~BluetoothSocketConnection() {
}
bool BluetoothSocketConnection::Establish(ConnectError** error) {
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_, "error: " << error);
DeviceSptr device = controller()->FindDevice(device_handle());
BluetoothDevice* bluetooth_device =
static_cast<BluetoothDevice*>(device.get());
uint8_t rfcomm_channel;
if (!bluetooth_device->GetRfcommChannel(application_handle(),
&rfcomm_channel)) {
LOG4CXX_DEBUG(logger_,
"Application " << application_handle() << " not found");
*error = new ConnectError();
LOG4CXX_TRACE(logger_, "exit with FALSE");
return false;
}
struct sockaddr_rc remoteSocketAddress = { 0 };
remoteSocketAddress.rc_family = AF_BLUETOOTH;
memcpy(&remoteSocketAddress.rc_bdaddr, &bluetooth_device->address(),
sizeof(bdaddr_t));
remoteSocketAddress.rc_channel = rfcomm_channel;
int rfcomm_socket;
int attempts = 4;
int connect_status = 0;
LOG4CXX_DEBUG(logger_, "start rfcomm Connect attempts");
do {
rfcomm_socket = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
if (-1 == rfcomm_socket) {
LOG4CXX_ERROR_WITH_ERRNO(logger_,
"Failed to create RFCOMM socket for device " << device_handle());
*error = new ConnectError();
LOG4CXX_TRACE(logger_, "exit with FALSE");
return false;
}
connect_status = ::connect(rfcomm_socket,
(struct sockaddr*) &remoteSocketAddress,
sizeof(remoteSocketAddress));
if (0 == connect_status) {
LOG4CXX_DEBUG(logger_, "rfcomm Connect ok");
break;
}
if (errno != 111 && errno != 104) {
LOG4CXX_DEBUG(logger_, "rfcomm Connect errno " << errno);
break;
}
if (errno) {
LOG4CXX_DEBUG(logger_, "rfcomm Connect errno " << errno);
close(rfcomm_socket);
}
sleep(2);
} while (--attempts > 0);
LOG4CXX_INFO(logger_, "rfcomm Connect attempts finished");
if (0 != connect_status) {
LOG4CXX_DEBUG(logger_,
"Failed to Connect to remote device " << BluetoothDevice::GetUniqueDeviceId(
remoteSocketAddress.rc_bdaddr) << " for session " << this);
*error = new ConnectError();
close(rfcomm_socket);
LOG4CXX_TRACE(logger_, "exit with FALSE");
return false;
}
set_socket(rfcomm_socket);
LOG4CXX_TRACE(logger_, "exit with TRUE");
return true;
}
} // namespace transport_adapter
} // namespace transport_manager
|
/*
*
* Copyright (c) 2013, Ford Motor Company
* 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 Ford Motor Company 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 "transport_manager/bluetooth/bluetooth_socket_connection.h"
#include <unistd.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
#include <bluetooth/sdp.h>
#include <bluetooth/sdp_lib.h>
#include <bluetooth/rfcomm.h>
#include "transport_manager/bluetooth/bluetooth_device.h"
#include "transport_manager/transport_adapter/transport_adapter_controller.h"
#include "utils/logger.h"
namespace transport_manager {
namespace transport_adapter {
CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
BluetoothSocketConnection::BluetoothSocketConnection(
const DeviceUID& device_uid, const ApplicationHandle& app_handle,
TransportAdapterController* controller)
: ThreadedSocketConnection(device_uid, app_handle, controller) {
}
BluetoothSocketConnection::~BluetoothSocketConnection() {
}
bool BluetoothSocketConnection::Establish(ConnectError** error) {
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_, "error: " << error);
DeviceSptr device = controller()->FindDevice(device_handle());
BluetoothDevice* bluetooth_device =
static_cast<BluetoothDevice*>(device.get());
uint8_t rfcomm_channel;
if (!bluetooth_device->GetRfcommChannel(application_handle(),
&rfcomm_channel)) {
LOG4CXX_DEBUG(logger_,
"Application " << application_handle() << " not found");
*error = new ConnectError();
LOG4CXX_TRACE(logger_, "exit with FALSE");
return false;
}
struct sockaddr_rc remoteSocketAddress = { 0 };
remoteSocketAddress.rc_family = AF_BLUETOOTH;
memcpy(&remoteSocketAddress.rc_bdaddr, &bluetooth_device->address(),
sizeof(bdaddr_t));
remoteSocketAddress.rc_channel = rfcomm_channel;
int rfcomm_socket;
int attempts = 4;
int connect_status = 0;
LOG4CXX_DEBUG(logger_, "start rfcomm Connect attempts");
do {
rfcomm_socket = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
if (-1 == rfcomm_socket) {
LOG4CXX_ERROR_WITH_ERRNO(logger_,
"Failed to create RFCOMM socket for device " << device_handle());
*error = new ConnectError();
LOG4CXX_TRACE(logger_, "exit with FALSE");
return false;
}
connect_status = ::connect(rfcomm_socket,
(struct sockaddr*) &remoteSocketAddress,
sizeof(remoteSocketAddress));
if (0 == connect_status) {
LOG4CXX_DEBUG(logger_, "rfcomm Connect ok");
break;
} else { // If connect_status is not 0, an errno is returned
LOG4CXX_WARN_WITH_ERRNO(logger_, "rfcomm Connect failed");
close(rfcomm_socket); // Always close the socket upon error
if (errno != ECONNREFUSED && errno != ECONNRESET) {
break;
}
}
sleep(2);
} while (--attempts > 0);
LOG4CXX_INFO(logger_, "rfcomm Connect attempts finished");
if (0 != connect_status) {
LOG4CXX_DEBUG(logger_,
"Failed to Connect to remote device " << BluetoothDevice::GetUniqueDeviceId(
remoteSocketAddress.rc_bdaddr) << " for session " << this);
*error = new ConnectError();
LOG4CXX_TRACE(logger_, "exit with FALSE");
return false;
}
set_socket(rfcomm_socket);
LOG4CXX_TRACE(logger_, "exit with TRUE");
return true;
}
} // namespace transport_adapter
} // namespace transport_manager
|
Change socket close logic to prevent double close (CID 137866)
|
Change socket close logic to prevent double close (CID 137866)
This simplifies the logic used to connect to bluetooth sockets. It
prevents the rfcomm_socket from being closed twice or being left
unclosed.
|
C++
|
bsd-3-clause
|
APCVSRepo/sdl_core,smartdevicelink/sdl_core,smartdevicelink/sdl_core,LuxoftAKutsan/sdl_core,APCVSRepo/sdl_core,APCVSRepo/sdl_core,LuxoftAKutsan/sdl_core,LuxoftAKutsan/sdl_core,LuxoftAKutsan/sdl_core,APCVSRepo/sdl_core,LuxoftAKutsan/sdl_core,LuxoftAKutsan/sdl_core,smartdevicelink/sdl_core,smartdevicelink/sdl_core,APCVSRepo/sdl_core
|
46d5ab694bcb040d8a5bb438f63c46643a9979b1
|
lib/inc/CSVParser.hpp
|
lib/inc/CSVParser.hpp
|
#pragma once
#include <stdexcept>
#include <vector>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
#include "Utility.hpp"
/*
Helper Functions
*/
namespace detail
{
inline bool isTrimChar(char c)
{
return false;
}
template<class... TrimChar>
inline bool isTrimChar(char c, char trim_char, TrimChar... other_trim_char)
{
return c == trim_char || isTrimChar(c, other_trim_char...);
}
template<class T>
inline void parse(const std::string& cell, T& object)
{
std::istringstream iss(cell);
iss >> object;
}
template<>
inline void parse(const std::string& cell, bool& object)
{
std::string buffer = cell;
std::for_each(buffer.begin(), buffer.end(),
[](char& c)
{
c = std::tolower(c);
});
std::istringstream iss(buffer);
iss.imbue({ iss.getloc(), new boolyesno() });
iss >> std::boolalpha >> object;
}
template<>
inline void parse(const std::string& cell, std::string& object)
{
object.assign(cell.begin(), cell.end());
}
}
/*
TrimChars Policy
*/
template<char... TrimChar>
struct TrimChars
{
static void trim(std::string& line)
{
auto found_iter = std::remove_if(line.begin(), line.end(),
[](char c)
{
return ::detail::isTrimChar(c, TrimChar...);
});
found_iter = line.erase(found_iter, line.end());
}
};
/*
QuoteEscape Policy
*/
template<char sep>
struct NoQuoteEscape
{
static std::string split(std::string& line)
{
std::string result;
std::size_t found_pos = line.find_first_of(sep, 0);
if (found_pos == std::string::npos)
{
result = line;
line.clear();
}
else
{
result = line.substr(0, found_pos);
line = line.substr(found_pos + 1);
}
return result;
}
static void unescape(std::string& line)
{
}
};
template<char sep, char quote>
struct DoubleQuoteEscape
{
static std::string split(std::string& line)
{
std::string result;
std::size_t sep_pos = line.find_first_of(sep, 0);
std::size_t quote_start_pos = line.find_first_of(quote, 0);
std::size_t quote_end_pos = line.find_first_of(quote, quote_start_pos + 1);
if (quote_start_pos != std::string::npos &&
((quote_end_pos != std::string::npos && sep_pos < quote_end_pos) ||
quote_end_pos == std::string::npos))
{
throw std::runtime_error("No ending escape string was found!");
}
if (sep_pos == std::string::npos)
{
result = line;
line.clear();
}
else
{
result = line.substr(0, sep_pos);
line = line.substr(sep_pos + 1);
}
return result;
}
static void unescape(std::string& line)
{
for (std::size_t next = line.find(quote);
next != std::string::npos;
next = line.find(quote, next)
)
{
line.erase(next, 1);
next += 1;
}
}
};
/*
Comment Policy
*/
struct NoComment
{
static bool isComment(const std::string& line)
{
return false;
}
};
struct EmptyLineComment
{
static bool isComment(const std::string& line)
{
if (line.empty())
{
return true;
}
std::string buffer = line;
auto found_iter = std::remove(buffer.begin(), buffer.end(), ' ');
found_iter = buffer.erase(found_iter, buffer.end());
found_iter = std::remove(buffer.begin(), buffer.end(), '\t');
found_iter = buffer.erase(found_iter, buffer.end());
if (buffer.empty())
{
return true;
}
return false;
}
};
/*
CSV Parser
*/
template
<
unsigned int column_num,
class CommentPolicy = EmptyLineComment,
class QuotePolicy = NoQuoteEscape<','>,
class TrimPolicy = TrimChars<'\t'>
>
class CSVParser
{
public:
explicit CSVParser(const std::string& data)
{
header_columns.resize(column_num);
reader << data;
}
explicit CSVParser(const std::ifstream& file)
{
header_columns.resize(column_num);
reader << file.rdbuf();
}
template<class ...ColumnTypes>
void readHeader(ColumnTypes&... header_columns)
{
constexpr std::size_t column_count = sizeof...(ColumnTypes);
static_assert(column_count >= column_num, "Header columns out of bounds");
static_assert(column_count <= column_num, "Header columns out of bounds");
setHeaderColumns(header_columns...);
std::string line;
do
{
std::getline(reader, line);
if (line.empty())
{
throw std::runtime_error("Header row is missing!");
}
} while (CommentPolicy::isComment(line));
std::vector<bool> found_columns(column_count);
std::fill(found_columns.begin(), found_columns.end(), false);
while (!line.empty())
{
std::string column = QuotePolicy::split(line);
TrimPolicy::trim(column);
QuotePolicy::unescape(column);
auto column_iter = std::find(this->header_columns.begin(), this->header_columns.end(), column);
if (column_iter == this->header_columns.end())
{
throw std::runtime_error("Column not found!");
}
std::size_t index = std::distance(this->header_columns.begin(), column_iter);
column_skip.push_back(index);
found_columns[index] = true;
}
}
template<class ...ColumnTypes>
bool readRow(ColumnTypes&... column_types)
{
constexpr std::size_t column_cout = sizeof...(ColumnTypes);
static_assert(column_cout >= column_num, "Row columns out of bounds");
static_assert(column_cout <= column_num, "Row columns out of bounds");
row_columns.clear();
std::string line;
do
{
std::getline(reader, line);
if (line.empty())
{
return false;
}
} while (CommentPolicy::isComment(line));
std::for_each(column_skip.begin(), column_skip.end(),
[&](std::int32_t skip_column)
{
std::string cell = QuotePolicy::split(line);
if (skip_column < 0)
{
row_columns.push_back(std::string());
}
else
{
TrimPolicy::trim(cell);
QuotePolicy::unescape(cell);
row_columns.push_back(cell);
}
});
setRowColumns(0, column_types...);
return true;
}
template<unsigned int index>
std::string getHeaderColumn()
{
static_assert(index < column_num, "Header column index out of bounds 1");
static_assert(index >= 0, "Header column index out of bounds 2");
return header_columns.at(index);
}
private:
std::stringstream reader;
std::vector<std::string> header_columns;
std::vector<std::int32_t> column_skip;
std::vector<std::string> row_columns;
template<class ...ColumnTypes>
void setHeaderColumns(const std::string& column_name, ColumnTypes... column_types)
{
constexpr std::size_t column_left = sizeof...(ColumnTypes);
header_columns[column_num - column_left - 1] = std::move(column_name);
setHeaderColumns(std::forward<ColumnTypes>(column_types)...);
}
void setHeaderColumns()
{
}
template<class T, class ...ColumnTypes>
void setRowColumns(std::size_t index, T& object, ColumnTypes&... column_types)
{
std::string cell = row_columns.at(index);
if (column_skip.at(index) != -1)
{
::detail::parse<T>(cell, object);
}
setRowColumns(index + 1, column_types...);
}
void setRowColumns(std::size_t index)
{
}
};
|
#pragma once
#include <stdexcept>
#include <vector>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
#include "Utility.hpp"
/*
Helper Functions
*/
namespace detail
{
inline bool isTrimChar(char c)
{
return false;
}
template<class... TrimChar>
inline bool isTrimChar(char c, char trim_char, TrimChar... other_trim_char)
{
return c == trim_char || isTrimChar(c, other_trim_char...);
}
template<class T>
inline void parse(const std::string& cell, T& object)
{
std::istringstream iss(cell);
iss >> object;
}
template<>
inline void parse(const std::string& cell, bool& object)
{
std::string buffer = cell;
std::for_each(buffer.begin(), buffer.end(),
[](char& c)
{
c = std::tolower(c);
});
std::istringstream iss(buffer);
iss.imbue({ iss.getloc(), new boolyesno() });
iss >> std::boolalpha >> object;
}
template<>
inline void parse(const std::string& cell, std::string& object)
{
object.assign(cell.begin(), cell.end());
}
}
/*
TrimChars Policy
*/
template<char... TrimChar>
struct TrimChars
{
static void trim(std::string& line)
{
auto found_iter = std::remove_if(line.begin(), line.end(),
[](char c)
{
return ::detail::isTrimChar(c, TrimChar...);
});
found_iter = line.erase(found_iter, line.end());
}
};
/*
QuoteEscape Policy
*/
template<char sep>
struct NoQuoteEscape
{
static std::string split(std::string& line)
{
std::string result;
std::size_t found_pos = line.find_first_of(sep, 0);
if (found_pos == std::string::npos)
{
result = line;
line.clear();
}
else
{
result = line.substr(0, found_pos);
line = line.substr(found_pos + 1);
}
return result;
}
static void unescape(std::string& line)
{
}
};
template<char sep, char quote>
struct DoubleQuoteEscape
{
static std::string split(std::string& line)
{
std::string result;
std::size_t sep_pos = line.find_first_of(sep, 0);
std::size_t quote_start_pos = line.find_first_of(quote, 0);
std::size_t quote_end_pos = line.find_first_of(quote, quote_start_pos + 1);
if (quote_start_pos != std::string::npos &&
((quote_end_pos != std::string::npos && sep_pos < quote_end_pos) ||
quote_end_pos == std::string::npos))
{
throw std::runtime_error("No ending escape string was found!");
}
if (sep_pos == std::string::npos)
{
result = line;
line.clear();
}
else
{
result = line.substr(0, sep_pos);
line = line.substr(sep_pos + 1);
}
return result;
}
static void unescape(std::string& line)
{
for (std::size_t next = line.find(quote);
next != std::string::npos;
next = line.find(quote, next)
)
{
line.erase(next, 1);
next += 1;
}
}
};
/*
Comment Policy
*/
struct NoComment
{
static bool isComment(const std::string& line)
{
return false;
}
};
struct EmptyLineComment
{
static bool isComment(const std::string& line)
{
if (line.empty())
{
return true;
}
std::string buffer = line;
auto found_iter = std::remove(buffer.begin(), buffer.end(), ' ');
found_iter = buffer.erase(found_iter, buffer.end());
found_iter = std::remove(buffer.begin(), buffer.end(), '\t');
found_iter = buffer.erase(found_iter, buffer.end());
if (buffer.empty())
{
return true;
}
return false;
}
};
/*
CSV Parser
*/
template
<
unsigned int column_num,
class CommentPolicy = EmptyLineComment,
class QuotePolicy = NoQuoteEscape<','>,
class TrimPolicy = TrimChars<'\t'>
>
class CSVParser
{
public:
explicit CSVParser(const std::string& data)
{
header_columns.resize(column_num);
reader << data;
}
explicit CSVParser(const std::ifstream& file)
{
header_columns.resize(column_num);
reader << file.rdbuf();
}
template<class ...ColumnTypes>
void readHeader(ColumnTypes&... header_columns)
{
constexpr std::size_t column_count = sizeof...(ColumnTypes);
static_assert(column_count >= column_num, "Header columns out of bounds");
static_assert(column_count <= column_num, "Header columns out of bounds");
setHeaderColumns(header_columns...);
std::string line;
do
{
std::getline(reader, line);
if (line.empty())
{
throw std::runtime_error("Header row is missing!");
}
} while (CommentPolicy::isComment(line));
std::vector<bool> found_columns(column_count);
std::fill(found_columns.begin(), found_columns.end(), false);
while (!line.empty())
{
std::string column = QuotePolicy::split(line);
TrimPolicy::trim(column);
QuotePolicy::unescape(column);
auto column_iter = std::find(this->header_columns.begin(), this->header_columns.end(), column);
if (column_iter == this->header_columns.end())
{
throw std::runtime_error("Column not found!");
}
std::size_t index = std::distance(this->header_columns.begin(), column_iter);
column_skip.push_back(index);
found_columns[index] = true;
}
}
template<class ...ColumnTypes>
bool readRow(ColumnTypes&... column_types)
{
constexpr std::size_t column_cout = sizeof...(ColumnTypes);
static_assert(column_cout >= column_num, "Row columns out of bounds");
static_assert(column_cout <= column_num, "Row columns out of bounds");
row_columns.clear();
std::string line;
do
{
std::getline(reader, line);
if (line.empty())
{
return false;
}
} while (CommentPolicy::isComment(line));
std::for_each(column_skip.begin(), column_skip.end(),
[&](std::int32_t skip_column)
{
std::string cell = QuotePolicy::split(line);
if (cell.empty())
{
throw std::runtime_error("Too few columns in the current row!");
}
if (skip_column < 0)
{
row_columns.push_back(std::string());
}
else
{
TrimPolicy::trim(cell);
QuotePolicy::unescape(cell);
row_columns.push_back(cell);
}
});
setRowColumns(0, column_types...);
if (!line.empty())
{
throw std::runtime_error("Too many columns in the current row!");
}
return true;
}
template<unsigned int index>
std::string getHeaderColumn()
{
static_assert(index < column_num, "Header column index out of bounds 1");
static_assert(index >= 0, "Header column index out of bounds 2");
return header_columns.at(index);
}
private:
std::stringstream reader;
std::vector<std::string> header_columns;
std::vector<std::int32_t> column_skip;
std::vector<std::string> row_columns;
template<class ...ColumnTypes>
void setHeaderColumns(const std::string& column_name, ColumnTypes... column_types)
{
constexpr std::size_t column_left = sizeof...(ColumnTypes);
header_columns[column_num - column_left - 1] = std::move(column_name);
setHeaderColumns(std::forward<ColumnTypes>(column_types)...);
}
void setHeaderColumns()
{
}
template<class T, class ...ColumnTypes>
void setRowColumns(std::size_t index, T& object, ColumnTypes&... column_types)
{
std::string cell = row_columns.at(index);
if (column_skip.at(index) != -1)
{
::detail::parse<T>(cell, object);
}
setRowColumns(index + 1, column_types...);
}
void setRowColumns(std::size_t index)
{
}
};
|
Add report errors if a column is invalid.
|
Add report errors if a column is invalid.
|
C++
|
mit
|
cristian-szabo/bt-code-test
|
15fcbb44ef6725f9cf567dac47885980ae3c8072
|
src/parser/parser-impl.cc
|
src/parser/parser-impl.cc
|
/*
* Copyright (C) 2009, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file parser/parser-impl.cc
#include <kernel/config.h> // YYDEBUG.
//#define ENABLE_DEBUG_TRACES
#include <libport/compiler.hh>
#include <libport/cassert>
#include <libport/cstdlib>
#include <fstream>
#include <sstream>
#include <string>
#include <libport/finally.hh>
#include <libport/foreach.hh>
#include <ast/nary.hh>
#include <ast/print.hh>
#include <parser/parser-impl.hh>
#include <parser/parser-utils.hh>
#include <parser/utoken.hh>
#include <kernel/server-timer.hh>
namespace parser
{
/*-------------.
| ParserImpl. |
`-------------*/
static bool yydebug = getenv("YYDEBUG");
ParserImpl::ParserImpl()
: loc_()
, synclines_()
, result_(0)
, debug_(yydebug)
, meta_(false)
, factory_()
{
}
bool
ParserImpl::meta() const
{
return meta_;
}
void
ParserImpl::meta(bool b)
{
meta_ = b;
}
void
ParserImpl::parse_(std::istream& source, const location_type* l)
{
TIMER_PUSH("parse");
// Set up result_.
// FIXME: This check will evaluate (void)*result_ in NDEBUG,
// entailing an abortion since result_ == 0. Passert should
// probably be fixed.
// passert(*result_, !result_.get());
result_.reset(new ParseResult);
// Set up scanner.
yyFlexLexer scanner;
scanner.switch_streams(&source, 0);
// Set up parser.
parser_type p(*this, scanner);
#if defined YYDEBUG && YYDEBUG
p.set_debug_level(debug_);
#endif
// Save the current location so that we can restore it afterwards
// (when reading the input flow, we want to be able to restore the
// cursor after having handled a load command).
libport::Finally finally;
if (l)
finally << libport::scoped_set(loc_, *l);
// Parse.
if (debug_)
LIBPORT_ECHO(loc_ << "====================== Parse begin");
result_->status = p.parse();
if (debug_)
LIBPORT_ECHO("====================== Parse end:" << std::endl
<< *result_);
TIMER_POP("parse");
}
parse_result_type
ParserImpl::parse(const std::string& s, const location_type* l)
{
if (debug_)
LIBPORT_ECHO("Parsing: " << s);
std::istringstream is(s);
parse_(is, l);
if (debug_)
LIBPORT_ECHO("Result: " << *result_);
return result_;
}
parse_result_type
ParserImpl::parse_file(const std::string& fn)
{
std::ifstream f(fn.c_str());
if (!f.good())
{
// Return an error instead of creating a valid empty ast.
result_.reset(new ParseResult);
result_->status = 1;
}
else
{
// FIXME: Leaks.
location_type loc(new libport::Symbol(fn));
parse_(f, &loc);
}
return result_;
}
void
ParserImpl::error(const location_type& l, const std::string& msg)
{
result_->error(l, msg);
}
void
ParserImpl::warn(const location_type& l, const std::string& msg)
{
result_->warn(l, msg);
}
}
|
/*
* Copyright (C) 2009, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file parser/parser-impl.cc
#include <kernel/config.h> // YYDEBUG.
//#define ENABLE_DEBUG_TRACES
#include <libport/compiler.hh>
#include <libport/cassert>
#include <libport/cstdlib>
#include <fstream>
#include <sstream>
#include <string>
#include <libport/finally.hh>
#include <libport/foreach.hh>
#include <ast/nary.hh>
#include <ast/print.hh>
#include <parser/parser-impl.hh>
#include <parser/parser-utils.hh>
#include <parser/utoken.hh>
#include <kernel/server-timer.hh>
namespace parser
{
/*-------------.
| ParserImpl. |
`-------------*/
static bool yydebug = getenv("YYDEBUG");
ParserImpl::ParserImpl()
: loc_()
, synclines_()
, result_(0)
, debug_(yydebug)
, meta_(false)
, factory_(new ast::Factory)
{
}
bool
ParserImpl::meta() const
{
return meta_;
}
void
ParserImpl::meta(bool b)
{
meta_ = b;
}
void
ParserImpl::parse_(std::istream& source, const location_type* l)
{
TIMER_PUSH("parse");
// Set up result_.
// FIXME: This check will evaluate (void)*result_ in NDEBUG,
// entailing an abortion since result_ == 0. Passert should
// probably be fixed.
// passert(*result_, !result_.get());
result_.reset(new ParseResult);
// Set up scanner.
yyFlexLexer scanner;
scanner.switch_streams(&source, 0);
// Set up parser.
parser_type p(*this, scanner);
#if defined YYDEBUG && YYDEBUG
p.set_debug_level(debug_);
#endif
// Save the current location so that we can restore it afterwards
// (when reading the input flow, we want to be able to restore the
// cursor after having handled a load command).
libport::Finally finally;
if (l)
finally << libport::scoped_set(loc_, *l);
// Parse.
if (debug_)
LIBPORT_ECHO(loc_ << "====================== Parse begin");
result_->status = p.parse();
if (debug_)
LIBPORT_ECHO("====================== Parse end:" << std::endl
<< *result_);
TIMER_POP("parse");
}
parse_result_type
ParserImpl::parse(const std::string& s, const location_type* l)
{
if (debug_)
LIBPORT_ECHO("Parsing: " << s);
std::istringstream is(s);
parse_(is, l);
if (debug_)
LIBPORT_ECHO("Result: " << *result_);
return result_;
}
parse_result_type
ParserImpl::parse_file(const std::string& fn)
{
std::ifstream f(fn.c_str());
if (!f.good())
{
// Return an error instead of creating a valid empty ast.
result_.reset(new ParseResult);
result_->status = 1;
}
else
{
// FIXME: Leaks.
location_type loc(new libport::Symbol(fn));
parse_(f, &loc);
}
return result_;
}
void
ParserImpl::error(const location_type& l, const std::string& msg)
{
result_->error(l, msg);
}
void
ParserImpl::warn(const location_type& l, const std::string& msg)
{
result_->warn(l, msg);
}
}
|
create the factor we use.
|
parser: create the factor we use.
* src/parser/parser-impl.cc (ParserImpl::ParserImpl): Create
factory_. It is extraordinary that Windows and OS X work without
it (well, it is true that we use only static member functions).
|
C++
|
bsd-3-clause
|
urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi
|
470c1cbd7d3069502afaf1c0cf85214646ad5bb8
|
cc/dual_net/inference_server.cc
|
cc/dual_net/inference_server.cc
|
// Copyright 2018 Google LLC
//
// 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 "cc/dual_net/inference_server.h"
#include <atomic>
#include <functional>
#include <map>
#include <string>
#include <utility>
#include <vector>
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/time/time.h"
#include "cc/check.h"
#include "grpc++/grpc++.h"
#include "proto/inference_service.grpc.pb.h"
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using grpc::StatusCode;
namespace minigo {
namespace internal {
// Implementation of the InferenceService.
// The client InferenceServer pushes inference requests onto
// InferenceServiceImpl's request queue.
class InferenceServiceImpl final : public InferenceService::Service {
public:
InferenceServiceImpl(int virtual_losses, int games_per_inference)
: virtual_losses_(virtual_losses),
games_per_inference_(games_per_inference),
batch_id_(1) {}
Status GetConfig(ServerContext* context, const GetConfigRequest* request,
GetConfigResponse* response) override {
response->set_board_size(kN);
response->set_virtual_losses(virtual_losses_);
response->set_games_per_inference(games_per_inference_);
return Status::OK;
}
Status GetFeatures(ServerContext* context, const GetFeaturesRequest* request,
GetFeaturesResponse* response) override {
std::vector<RemoteInference> inferences;
{
// std::cerr << absl::Now() << " START GetFeatures\n";
// Lock get_features_mutex_ while popping inference requests off the
// request_queue_: we want make sure that each request fills up as much
// of a batch as possible. If multiple threads all popped inference
// requests off the queue in parallel, we'd likely end up with multiple
// partially empty batches.
absl::MutexLock lock(&get_features_mutex_);
// std::cerr << "### GetFeatures" << std::endl;
// Each client is guaranteed to never request more than
// virtual_losses_ inferences in each RemoteInference. Additionally,
// each client is only able to have one pending RemoteInference at a
// time, and the time between inference requests is very small (typically
// less than a millisecond).
//
// With this in mind, the inference server accumulates RemoteInference
// requests into a single batch until one of the following occurs:
// 1) It has accumulated one RemoteInference request from event client.
// 2) The current batch has grown large enough that we won't be able to
// fit another virtual_losses_ inferences.
//
// Since a client can terminate (e.g. when a game is complete) while the
// inference server is in the middle of processing a GetFeatures request,
// we repeatedly pop with a timeout to allow us to periodically check the
// current number of clients. Client terminations are rare, so it doesn't
// really matter if we hold up one inference batch for a few tens of
// milliseconds occasionally.
auto timeout = absl::Milliseconds(50);
RemoteInference game;
while (inferences.size() < num_clients_ &&
inferences.size() < games_per_inference_) {
if (request_queue_.PopWithTimeout(&game, timeout)) {
inferences.push_back(game);
} else if (context->IsCancelled()) {
return Status(StatusCode::CANCELLED, "connection terminated");
}
}
}
std::string byte_features(
games_per_inference_ * virtual_losses_ * DualNet::kNumBoardFeatures, 0);
int i = 0;
for (const auto& game : inferences) {
for (const auto& features : game.features) {
for (float f : features) {
byte_features[i++] = f != 0 ? 1 : 0;
}
}
}
response->set_batch_id(batch_id_++);
response->set_features(std::move(byte_features));
{
absl::MutexLock lock(&pending_inferences_mutex_);
pending_inferences_[response->batch_id()] = std::move(inferences);
}
// std::cerr << absl::Now() << " DONE GetFeatures\n";
return Status::OK;
}
Status PutOutputs(ServerContext* context, const PutOutputsRequest* request,
PutOutputsResponse* response) override {
// std::cerr << absl::Now() << " START PutOutputs\n";
std::vector<RemoteInference> inferences;
{
// std::cerr << "### PutOutputs" << std::endl;
absl::MutexLock lock(&pending_inferences_mutex_);
auto it = pending_inferences_.find(request->batch_id());
MG_CHECK(it != pending_inferences_.end());
inferences = std::move(it->second);
pending_inferences_.erase(it);
}
// Check we got the expected number of values.
// (Note that if the prior GetFeatures response was padded, we may have
// more values than batch_.size()).
MG_CHECK(request->value().size() ==
static_cast<int>(virtual_losses_ * games_per_inference_))
<< "Expected " << virtual_losses_ << "*" << games_per_inference_
<< " values, got " << request->value().size();
// There should be kNumMoves policy values for each inference.
MG_CHECK(request->policy().size() ==
static_cast<int>(request->value().size() * kNumMoves));
size_t src_policy_idx = 0;
size_t src_value_idx = 0;
for (auto& game : inferences) {
for (size_t vloss = 0; vloss < game.outputs.size(); ++vloss) {
auto& dst_policy = game.outputs[vloss].policy;
for (int i = 0; i < kNumMoves; ++i) {
dst_policy[i] = request->policy(src_policy_idx++);
}
game.outputs[vloss].value = request->value(src_value_idx++);
}
game.notification->Notify();
}
return Status::OK;
}
private:
// Guaranteed maximum batch size that each client will send.
const size_t virtual_losses_;
// Target size of the batch sent in response to each GetFeaturesRequest.
const size_t games_per_inference_;
std::atomic<int32_t> batch_id_{1};
std::atomic<size_t> num_clients_{0};
// After successfully popping the first request off request_queue, GetFeatures
// will wait for up to the batch_timeout_ for more inference requests before
// replying.
absl::Duration batch_timeout_;
ThreadSafeQueue<RemoteInference> request_queue_;
// Mutex that is locked while popping inference requests off request_queue_
// (see GetFeatures() for why this is needed).
absl::Mutex get_features_mutex_;
// Mutex that protects access to pending_inferences_.
absl::Mutex pending_inferences_mutex_;
// Map from batch ID to list of remote inference requests in that batch.
std::map<int32_t, std::vector<RemoteInference>> pending_inferences_
GUARDED_BY(&pending_inferences_mutex_);
friend class InferenceClient;
};
class InferenceClient : public DualNet {
public:
explicit InferenceClient(InferenceServiceImpl* service) : service_(service) {
service_->num_clients_++;
}
~InferenceClient() {
service_->num_clients_--;
}
void RunMany(absl::Span<const BoardFeatures> features,
absl::Span<Output> outputs) override {
MG_CHECK(features.size() <= service_->virtual_losses_);
absl::Notification notification;
service_->request_queue_.Push({features, outputs, ¬ification});
notification.WaitForNotification();
}
private:
InferenceServiceImpl* service_;
};
} // namespace internal
InferenceServer::InferenceServer(
int virtual_losses, int games_per_inference, int port) {
auto server_address = absl::StrCat("0.0.0.0:", port);
service_ = absl::make_unique<internal::InferenceServiceImpl>(
virtual_losses, games_per_inference);
ServerBuilder builder;
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
builder.RegisterService(service_.get());
server_ = builder.BuildAndStart();
std::cerr << "Inference server listening on port " << port << std::endl;
thread_ = std::thread([this]() { server_->Wait(); });
}
InferenceServer::~InferenceServer() {
// Passing gpr_inf_past to Shutdown makes it shutdown immediately.
server_->Shutdown(gpr_inf_past(GPR_CLOCK_REALTIME));
thread_.join();
}
std::unique_ptr<DualNet> InferenceServer::NewDualNet() {
return absl::make_unique<internal::InferenceClient>(service_.get());
}
} // namespace minigo
|
// Copyright 2018 Google LLC
//
// 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 "cc/dual_net/inference_server.h"
#include <atomic>
#include <functional>
#include <map>
#include <string>
#include <utility>
#include <vector>
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/time/time.h"
#include "cc/check.h"
#include "grpc++/grpc++.h"
#include "proto/inference_service.grpc.pb.h"
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using grpc::StatusCode;
namespace minigo {
namespace internal {
// Implementation of the InferenceService.
// The client InferenceServer pushes inference requests onto
// InferenceServiceImpl's request queue.
class InferenceServiceImpl final : public InferenceService::Service {
public:
InferenceServiceImpl(int virtual_losses, int games_per_inference)
: virtual_losses_(virtual_losses),
games_per_inference_(games_per_inference),
batch_id_(1) {}
Status GetConfig(ServerContext* context, const GetConfigRequest* request,
GetConfigResponse* response) override {
response->set_board_size(kN);
response->set_virtual_losses(virtual_losses_);
response->set_games_per_inference(games_per_inference_);
return Status::OK;
}
Status GetFeatures(ServerContext* context, const GetFeaturesRequest* request,
GetFeaturesResponse* response) override {
std::vector<RemoteInference> inferences;
{
// Lock get_features_mutex_ while popping inference requests off the
// request_queue_: we want make sure that each request fills up as much
// of a batch as possible. If multiple threads all popped inference
// requests off the queue in parallel, we'd likely end up with multiple
// partially empty batches.
absl::MutexLock lock(&get_features_mutex_);
// Each client is guaranteed to never request more than
// virtual_losses_ inferences in each RemoteInference. Additionally,
// each client is only able to have one pending RemoteInference at a
// time, and the time between inference requests is very small (typically
// less than a millisecond).
//
// With this in mind, the inference server accumulates RemoteInference
// requests into a single batch until one of the following occurs:
// 1) It has accumulated one RemoteInference request from every client.
// 2) The current batch has grown large enough that we won't be able to
// fit another virtual_losses_ inferences.
//
// Since a client can terminate (e.g. when a game is complete) while the
// inference server is in the middle of processing a GetFeatures request,
// we repeatedly pop with a timeout to allow us to periodically check the
// current number of clients. Client terminations are rare, so it doesn't
// really matter if we hold up one inference batch for a few tens of
// milliseconds occasionally.
auto timeout = absl::Milliseconds(50);
RemoteInference game;
while (inferences.size() < num_clients_ &&
inferences.size() < games_per_inference_) {
if (request_queue_.PopWithTimeout(&game, timeout)) {
inferences.push_back(game);
} else if (context->IsCancelled()) {
return Status(StatusCode::CANCELLED, "connection terminated");
}
}
}
std::string byte_features(
games_per_inference_ * virtual_losses_ * DualNet::kNumBoardFeatures, 0);
int i = 0;
for (const auto& game : inferences) {
for (const auto& features : game.features) {
for (float f : features) {
byte_features[i++] = f != 0 ? 1 : 0;
}
}
}
response->set_batch_id(batch_id_++);
response->set_features(std::move(byte_features));
{
absl::MutexLock lock(&pending_inferences_mutex_);
pending_inferences_[response->batch_id()] = std::move(inferences);
}
// std::cerr << absl::Now() << " DONE GetFeatures\n";
return Status::OK;
}
Status PutOutputs(ServerContext* context, const PutOutputsRequest* request,
PutOutputsResponse* response) override {
// std::cerr << absl::Now() << " START PutOutputs\n";
std::vector<RemoteInference> inferences;
{
// std::cerr << "### PutOutputs" << std::endl;
absl::MutexLock lock(&pending_inferences_mutex_);
auto it = pending_inferences_.find(request->batch_id());
MG_CHECK(it != pending_inferences_.end());
inferences = std::move(it->second);
pending_inferences_.erase(it);
}
// Check we got the expected number of values.
// (Note that if the prior GetFeatures response was padded, we may have
// more values than batch_.size()).
MG_CHECK(request->value().size() ==
static_cast<int>(virtual_losses_ * games_per_inference_))
<< "Expected " << virtual_losses_ << "*" << games_per_inference_
<< " values, got " << request->value().size();
// There should be kNumMoves policy values for each inference.
MG_CHECK(request->policy().size() ==
static_cast<int>(request->value().size() * kNumMoves));
size_t src_policy_idx = 0;
size_t src_value_idx = 0;
for (auto& game : inferences) {
for (size_t vloss = 0; vloss < game.outputs.size(); ++vloss) {
auto& dst_policy = game.outputs[vloss].policy;
for (int i = 0; i < kNumMoves; ++i) {
dst_policy[i] = request->policy(src_policy_idx++);
}
game.outputs[vloss].value = request->value(src_value_idx++);
}
game.notification->Notify();
}
return Status::OK;
}
private:
// Guaranteed maximum batch size that each client will send.
const size_t virtual_losses_;
// Target size of the batch sent in response to each GetFeaturesRequest.
const size_t games_per_inference_;
std::atomic<int32_t> batch_id_{1};
std::atomic<size_t> num_clients_{0};
// After successfully popping the first request off request_queue, GetFeatures
// will wait for up to the batch_timeout_ for more inference requests before
// replying.
absl::Duration batch_timeout_;
ThreadSafeQueue<RemoteInference> request_queue_;
// Mutex that is locked while popping inference requests off request_queue_
// (see GetFeatures() for why this is needed).
absl::Mutex get_features_mutex_;
// Mutex that protects access to pending_inferences_.
absl::Mutex pending_inferences_mutex_;
// Map from batch ID to list of remote inference requests in that batch.
std::map<int32_t, std::vector<RemoteInference>> pending_inferences_
GUARDED_BY(&pending_inferences_mutex_);
friend class InferenceClient;
};
class InferenceClient : public DualNet {
public:
explicit InferenceClient(InferenceServiceImpl* service) : service_(service) {
service_->num_clients_++;
}
~InferenceClient() {
service_->num_clients_--;
}
void RunMany(absl::Span<const BoardFeatures> features,
absl::Span<Output> outputs) override {
MG_CHECK(features.size() <= service_->virtual_losses_);
absl::Notification notification;
service_->request_queue_.Push({features, outputs, ¬ification});
notification.WaitForNotification();
}
private:
InferenceServiceImpl* service_;
};
} // namespace internal
InferenceServer::InferenceServer(
int virtual_losses, int games_per_inference, int port) {
auto server_address = absl::StrCat("0.0.0.0:", port);
service_ = absl::make_unique<internal::InferenceServiceImpl>(
virtual_losses, games_per_inference);
ServerBuilder builder;
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
builder.RegisterService(service_.get());
server_ = builder.BuildAndStart();
std::cerr << "Inference server listening on port " << port << std::endl;
thread_ = std::thread([this]() { server_->Wait(); });
}
InferenceServer::~InferenceServer() {
// Passing gpr_inf_past to Shutdown makes it shutdown immediately.
server_->Shutdown(gpr_inf_past(GPR_CLOCK_REALTIME));
thread_.join();
}
std::unique_ptr<DualNet> InferenceServer::NewDualNet() {
return absl::make_unique<internal::InferenceClient>(service_.get());
}
} // namespace minigo
|
Fix a typo
|
Fix a typo
|
C++
|
apache-2.0
|
tensorflow/minigo,tensorflow/minigo,tensorflow/minigo,tensorflow/minigo,tensorflow/minigo,tensorflow/minigo
|
35939cc840a3836fff0bfb00ead7a34a5c4aa0f0
|
EHTest.cpp
|
EHTest.cpp
|
#ifdef _WIN32
#define NOMINMAX
#include <windows.h>
#include "call_stack.hpp"
const DWORD NT_EXCEPTION = 0xE06D7363; // 'msc' | 0xE0000000
const DWORD EH_MAGIC1 = 0x19930520;
const DWORD EH_PURE_MAGIC1 = 0x01994000;
// inhibit optimization of frames
//#pragma optimize("y",off)
typedef unsigned __int64 * PULONG_PTR;
#if (defined(_M_IA64) || defined(_M_AMD64) || defined(_M_ARM_NT) || defined(_M_ARM64))
#define _EH_RELATIVE_OFFSETS 1
#else
#define _EH_RELATIVE_OFFSETS 0
#endif
__declspec (noreturn)
extern "C"
void __stdcall _CxxThrowException(void* pExceptionObject,
_ThrowInfo* pTI)
{
#if _EH_RELATIVE_OFFSETS
PVOID ThrowImageBase = RtlPcToFileHeader((PVOID)pTI, &ThrowImageBase);
#else
PVOID ThrowImageBase = nullptr;
#endif
bool pureModule = pTI && (
((*pTI).attributes & 8) //TI_IsPure)
#if _EH_RELATIVE_OFFSETS
|| !ThrowImageBase
#endif
);
stacktrace::call_stack cs(1);
std::string s = cs.to_string();
printf("\n--------\nException occured: %s\n--------\n", s.c_str());
const ULONG_PTR args[] = { pureModule ? EH_PURE_MAGIC1 : EH_MAGIC1,
(ULONG_PTR)pExceptionObject,
(ULONG_PTR)pTI
#if _EH_RELATIVE_OFFSETS
,(ULONG_PTR)ThrowImageBase // Image base of thrown object
#endif
};
RaiseException(NT_EXCEPTION,
EXCEPTION_NONCONTINUABLE,
sizeof(args) / sizeof(args[0]),
args);
}
//restore optimization settings
#pragma optimize("",on)
#endif
|
// http://stacktrace.sourceforge.net
#ifdef _WIN32
#define NOMINMAX
#include <windows.h>
#include "call_stack.hpp"
const DWORD NT_EXCEPTION = 0xE06D7363; // 'msc' | 0xE0000000
const DWORD EH_MAGIC1 = 0x19930520;
const DWORD EH_PURE_MAGIC1 = 0x01994000;
// inhibit optimization of frames
//#pragma optimize("y",off)
typedef unsigned __int64 * PULONG_PTR;
#if (defined(_M_IA64) || defined(_M_AMD64) || defined(_M_ARM_NT) || defined(_M_ARM64))
#define _EH_RELATIVE_OFFSETS 1
#else
#define _EH_RELATIVE_OFFSETS 0
#endif
__declspec (noreturn)
extern "C"
void __stdcall _CxxThrowException(void* pExceptionObject,
_ThrowInfo* pTI)
{
#if _EH_RELATIVE_OFFSETS
PVOID ThrowImageBase = RtlPcToFileHeader((PVOID)pTI, &ThrowImageBase);
#else
PVOID ThrowImageBase = nullptr;
#endif
bool pureModule = pTI && (
((*pTI).attributes & 8) //TI_IsPure)
#if _EH_RELATIVE_OFFSETS
|| !ThrowImageBase
#endif
);
stacktrace::call_stack cs(1);
std::string s = cs.to_string();
printf("\n--------\nException occured: %s\n--------\n", s.c_str());
const ULONG_PTR args[] = { pureModule ? EH_PURE_MAGIC1 : EH_MAGIC1,
(ULONG_PTR)pExceptionObject,
(ULONG_PTR)pTI
#if _EH_RELATIVE_OFFSETS
,(ULONG_PTR)ThrowImageBase // Image base of thrown object
#endif
};
RaiseException(NT_EXCEPTION,
EXCEPTION_NONCONTINUABLE,
sizeof(args) / sizeof(args[0]),
args);
}
//restore optimization settings
#pragma optimize("",on)
#endif
|
add link
|
add link
|
C++
|
mpl-2.0
|
Trass3r/cxxcore,Trass3r/cxxcore
|
65690fb2bb3a260d5ca9019e7fc4f828ce028499
|
eval/src/vespa/eval/eval/test/gen_spec.cpp
|
eval/src/vespa/eval/eval/test/gen_spec.cpp
|
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "gen_spec.h"
#include <vespa/eval/eval/string_stuff.h>
#include <vespa/vespalib/util/stringfmt.h>
using vespalib::make_string_short::fmt;
namespace vespalib::eval::test {
//-----------------------------------------------------------------------------
Sequence N(double bias) {
return [bias](size_t i) noexcept { return (i + bias); };
}
Sequence AX_B(double a, double b) {
return [a,b](size_t i) noexcept { return (a * i) + b; };
}
Sequence Div16(const Sequence &seq) {
return [seq](size_t i) { return (seq(i) / 16.0); };
}
Sequence Sub2(const Sequence &seq) {
return [seq](size_t i) { return (seq(i) - 2.0); };
}
Sequence OpSeq(const Sequence &seq, map_fun_t op) {
return [seq,op](size_t i) { return op(seq(i)); };
}
Sequence SigmoidF(const Sequence &seq) {
return [seq](size_t i) { return (float)operation::Sigmoid::f(seq(i)); };
}
Sequence Seq(const std::vector<double> &seq) {
assert(!seq.empty());
return [seq](size_t i) noexcept { return seq[i % seq.size()]; };
}
//-----------------------------------------------------------------------------
DimSpec::~DimSpec() = default;
std::vector<vespalib::string>
DimSpec::make_dict(size_t size, size_t stride, const vespalib::string &prefix)
{
std::vector<vespalib::string> dict;
for (size_t i = 0; i < size; ++i) {
dict.push_back(fmt("%s%zu", prefix.c_str(), i * stride));
}
return dict;
}
namespace {
auto is_dim_name = [](char c) {
return ((c >= 'a') && (c <= 'z'))
|| ((c >= 'A') && (c <= 'Z')); };
}
// 'a2' -> DimSpec("a", 2);
// 'b2_3' -> DimSpec("b", make_dict(2, 3, ""));
DimSpec
DimSpec::from_desc(const vespalib::string &desc)
{
size_t idx = 0;
vespalib::string name;
auto is_num = [](char c) { return ((c >= '0') && (c <= '9')); };
auto as_num = [](char c) { return size_t(c - '0'); };
auto is_map_tag = [](char c) { return (c == '_'); };
auto extract_number = [&]() {
assert(idx < desc.size());
assert(is_num(desc[idx]));
size_t num = as_num(desc[idx++]);
while ((idx < desc.size()) && is_num(desc[idx])) {
num = (num * 10) + as_num(desc[idx++]);
}
return num;
};
assert(!desc.empty());
assert(is_dim_name(desc[idx]));
name.push_back(desc[idx++]);
size_t size = extract_number();
if (idx < desc.size()) {
// mapped
assert(is_map_tag(desc[idx++]));
size_t stride = extract_number();
assert(idx == desc.size());
return {name, make_dict(size, stride, "")};
} else {
// indexed
return {name, size};
}
}
// 'a2b12c5' -> GenSpec().idx("a", 2).idx("b", 12).idx("c", 5);
// 'a2_1b3_2c5_1' -> GenSpec().map("a", 2).map("b", 3, 2).map("c", 5);
GenSpec
GenSpec::from_desc(const vespalib::string &desc)
{
size_t idx = 0;
vespalib::string dim_desc;
std::vector<DimSpec> dim_list;
while (idx < desc.size()) {
dim_desc.clear();
assert(is_dim_name(desc[idx]));
dim_desc.push_back(desc[idx++]);
while ((idx < desc.size()) && !is_dim_name(desc[idx])) {
dim_desc.push_back(desc[idx++]);
}
dim_list.push_back(DimSpec::from_desc(dim_desc));
}
return {std::move(dim_list)};
}
GenSpec::GenSpec(GenSpec &&other) = default;
GenSpec::GenSpec(const GenSpec &other) = default;
GenSpec &GenSpec::operator=(GenSpec &&other) = default;
GenSpec &GenSpec::operator=(const GenSpec &other) = default;
GenSpec::~GenSpec() = default;
bool
GenSpec::bad_scalar() const
{
return (_dims.empty() && (_cells != CellType::DOUBLE));
}
ValueType
GenSpec::type() const
{
std::vector<ValueType::Dimension> dim_types;
for (const auto &dim: _dims) {
dim_types.push_back(dim.type());
}
auto type = ValueType::make_type(_cells, dim_types);
assert(!type.is_error());
return type;
}
TensorSpec
GenSpec::gen() const
{
size_t idx = 0;
TensorSpec::Address addr;
assert(!bad_scalar());
TensorSpec result(type().to_spec());
std::function<void(size_t)> add_cells = [&](size_t dim_idx) {
if (dim_idx == _dims.size()) {
result.add(addr, _seq(idx++));
} else {
const auto &dim = _dims[dim_idx];
for (size_t i = 0; i < dim.size(); ++i) {
addr.insert_or_assign(dim.name(), dim.label(i));
add_cells(dim_idx + 1);
}
}
};
add_cells(0);
return result.normalize();
}
} // namespace
|
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "gen_spec.h"
#include <vespa/eval/eval/string_stuff.h>
#include <vespa/vespalib/util/require.h>
#include <vespa/vespalib/util/stringfmt.h>
using vespalib::make_string_short::fmt;
namespace vespalib::eval::test {
//-----------------------------------------------------------------------------
Sequence N(double bias) {
return [bias](size_t i) noexcept { return (i + bias); };
}
Sequence AX_B(double a, double b) {
return [a,b](size_t i) noexcept { return (a * i) + b; };
}
Sequence Div16(const Sequence &seq) {
return [seq](size_t i) { return (seq(i) / 16.0); };
}
Sequence Sub2(const Sequence &seq) {
return [seq](size_t i) { return (seq(i) - 2.0); };
}
Sequence OpSeq(const Sequence &seq, map_fun_t op) {
return [seq,op](size_t i) { return op(seq(i)); };
}
Sequence SigmoidF(const Sequence &seq) {
return [seq](size_t i) { return (float)operation::Sigmoid::f(seq(i)); };
}
Sequence Seq(const std::vector<double> &seq) {
REQUIRE(!seq.empty());
return [seq](size_t i) noexcept { return seq[i % seq.size()]; };
}
//-----------------------------------------------------------------------------
DimSpec::~DimSpec() = default;
std::vector<vespalib::string>
DimSpec::make_dict(size_t size, size_t stride, const vespalib::string &prefix)
{
std::vector<vespalib::string> dict;
for (size_t i = 0; i < size; ++i) {
dict.push_back(fmt("%s%zu", prefix.c_str(), i * stride));
}
return dict;
}
namespace {
auto is_dim_name = [](char c) {
return ((c >= 'a') && (c <= 'z'))
|| ((c >= 'A') && (c <= 'Z')); };
}
// 'a2' -> DimSpec("a", 2);
// 'b2_3' -> DimSpec("b", make_dict(2, 3, ""));
DimSpec
DimSpec::from_desc(const vespalib::string &desc)
{
size_t idx = 0;
vespalib::string name;
auto is_num = [](char c) { return ((c >= '0') && (c <= '9')); };
auto as_num = [](char c) { return size_t(c - '0'); };
auto is_map_tag = [](char c) { return (c == '_'); };
auto extract_number = [&]() {
REQUIRE(idx < desc.size());
REQUIRE(is_num(desc[idx]));
size_t num = as_num(desc[idx++]);
while ((idx < desc.size()) && is_num(desc[idx])) {
num = (num * 10) + as_num(desc[idx++]);
}
return num;
};
REQUIRE(!desc.empty());
REQUIRE(is_dim_name(desc[idx]));
name.push_back(desc[idx++]);
size_t size = extract_number();
if (idx < desc.size()) {
// mapped
REQUIRE(is_map_tag(desc[idx++]));
size_t stride = extract_number();
REQUIRE(idx == desc.size());
return {name, make_dict(size, stride, "")};
} else {
// indexed
return {name, size};
}
}
// 'a2b12c5' -> GenSpec().idx("a", 2).idx("b", 12).idx("c", 5);
// 'a2_1b3_2c5_1' -> GenSpec().map("a", 2).map("b", 3, 2).map("c", 5);
GenSpec
GenSpec::from_desc(const vespalib::string &desc)
{
size_t idx = 0;
vespalib::string dim_desc;
std::vector<DimSpec> dim_list;
while (idx < desc.size()) {
dim_desc.clear();
REQUIRE(is_dim_name(desc[idx]));
dim_desc.push_back(desc[idx++]);
while ((idx < desc.size()) && !is_dim_name(desc[idx])) {
dim_desc.push_back(desc[idx++]);
}
dim_list.push_back(DimSpec::from_desc(dim_desc));
}
return {std::move(dim_list)};
}
GenSpec::GenSpec(GenSpec &&other) = default;
GenSpec::GenSpec(const GenSpec &other) = default;
GenSpec &GenSpec::operator=(GenSpec &&other) = default;
GenSpec &GenSpec::operator=(const GenSpec &other) = default;
GenSpec::~GenSpec() = default;
bool
GenSpec::bad_scalar() const
{
return (_dims.empty() && (_cells != CellType::DOUBLE));
}
ValueType
GenSpec::type() const
{
std::vector<ValueType::Dimension> dim_types;
for (const auto &dim: _dims) {
dim_types.push_back(dim.type());
}
auto type = ValueType::make_type(_cells, dim_types);
REQUIRE(!type.is_error());
return type;
}
TensorSpec
GenSpec::gen() const
{
size_t idx = 0;
TensorSpec::Address addr;
REQUIRE(!bad_scalar());
TensorSpec result(type().to_spec());
std::function<void(size_t)> add_cells = [&](size_t dim_idx) {
if (dim_idx == _dims.size()) {
result.add(addr, _seq(idx++));
} else {
const auto &dim = _dims[dim_idx];
for (size_t i = 0; i < dim.size(); ++i) {
addr.insert_or_assign(dim.name(), dim.label(i));
add_cells(dim_idx + 1);
}
}
};
add_cells(0);
return result.normalize();
}
} // namespace
|
use REQUIRE not assert
|
use REQUIRE not assert
|
C++
|
apache-2.0
|
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
|
cbe04ce1be626eb8d2cc1f96c484a2c950501c75
|
src/platform/XDisplay.cxx
|
src/platform/XDisplay.cxx
|
/* bzflag
* Copyright (c) 1993-2011 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "XDisplay.h"
#include "XWindow.h"
#include "BzfEvent.h"
#include <string.h>
#include <X11/keysym.h>
//
// XDisplay::Rep
//
XDisplay::Rep::Rep(const char* displayName) :
refCount(1),
display(NULL),
screen(0)
{
// open display
display = XOpenDisplay(displayName);
if (!display) return;
// other initialization
screen = DefaultScreen(display);
}
XDisplay::Rep::~Rep()
{
if (display) XCloseDisplay(display);
}
void XDisplay::Rep::ref()
{
refCount++;
}
void XDisplay::Rep::unref()
{
if (--refCount <= 0) delete this;
}
Window XDisplay::Rep::getRootWindow() const
{
return display ? RootWindow(display, screen) : None;
}
//
// XDisplay
//
XDisplay::XDisplay(const char* displayName, XDisplayMode* _mode) :
rep(NULL),
mode(_mode)
{
// open display
rep = new Rep(displayName);
// make default mode changer if one wasn't supplied
if (!mode)
mode = new XDisplayMode;
if (rep->getDisplay()) {
// get resolutions
int numModes, currentMode;
ResInfo** resInfo = mode->init(this, numModes, currentMode);
// if no modes then make default
if (!resInfo) {
resInfo = new ResInfo*[1];
resInfo[0] = new ResInfo("default",
DisplayWidth(rep->getDisplay(), rep->getScreen()),
DisplayHeight(rep->getDisplay(), rep->getScreen()), 0);
numModes = 1;
currentMode = 0;
}
// register modes
initResolutions(resInfo, numModes, currentMode);
}
}
XDisplay::~XDisplay()
{
setDefaultResolution();
delete mode;
rep->unref();
}
bool XDisplay::isValid() const
{
return rep->getDisplay() != NULL;
}
bool XDisplay::isEventPending() const
{
return (XPending(rep->getDisplay()) != 0);
}
bool XDisplay::getEvent(BzfEvent& event) const
{
XEvent xevent;
XNextEvent(rep->getDisplay(), &xevent);
return setupEvent(event, xevent);
}
bool XDisplay::peekEvent(BzfEvent& event) const
{
XEvent xevent;
XPeekEvent(rep->getDisplay(), &xevent);
return setupEvent(event, xevent);
}
bool XDisplay::setupEvent(BzfEvent& event, const XEvent& xevent) const
{
switch (xevent.type) {
case Expose:
case ConfigureNotify:
case MotionNotify:
case MapNotify:
case UnmapNotify:
case ButtonPress:
case ButtonRelease:
case KeyPress:
case KeyRelease:
case ClientMessage:
event.window = XWindow::lookupWindow(xevent.xexpose.window);
if (!event.window) return false;
break;
default:
return false;
}
switch (xevent.type) {
case Expose:
if (xevent.xexpose.count != 0) return false;
event.type = BzfEvent::Redraw;
break;
case ConfigureNotify: {
/* attempt to filter out non-size changes, but getSize() returns the
* current size so it always matches the size in the event.
int width, height;
event.window->getSize(width, height);
if (width == xevent.xconfigure.width &&
height == xevent.xconfigure.height)
return false;
*/
event.type = BzfEvent::Resize;
event.resize.width = xevent.xconfigure.width;
event.resize.height = xevent.xconfigure.height;
break;
}
case MotionNotify:
event.type = BzfEvent::MouseMove;
event.mouseMove.x = xevent.xmotion.x;
event.mouseMove.y = xevent.xmotion.y;
break;
case MapNotify:
event.type = BzfEvent::Map;
break;
case UnmapNotify:
event.type = BzfEvent::Unmap;
break;
case ButtonPress:
event.type = BzfEvent::KeyDown;
event.keyDown.ascii = 0;
event.keyDown.shift = 0;
switch (xevent.xbutton.button) {
case Button1: event.keyDown.button = BzfKeyEvent::LeftMouse; break;
case Button2: event.keyDown.button = BzfKeyEvent::MiddleMouse; break;
case Button3: event.keyDown.button = BzfKeyEvent::RightMouse; break;
default: return false;
}
break;
case ButtonRelease:
event.type = BzfEvent::KeyUp;
event.keyUp.ascii = 0;
event.keyUp.shift = 0;
switch (xevent.xbutton.button) {
case Button1: event.keyUp.button = BzfKeyEvent::LeftMouse; break;
case Button2: event.keyUp.button = BzfKeyEvent::MiddleMouse; break;
case Button3: event.keyUp.button = BzfKeyEvent::RightMouse; break;
default: return false;
}
break;
case KeyPress:
event.type = BzfEvent::KeyDown;
if (!getKey(xevent, event.keyDown)) return false;
break;
case KeyRelease:
event.type = BzfEvent::KeyUp;
if (!getKey(xevent, event.keyUp)) return false;
break;
case ClientMessage: {
XClientMessageEvent* cme = (XClientMessageEvent*)&xevent;
if (cme->format == 32) {
if ((Atom)cme->data.l[0] == XInternAtom(rep->getDisplay(),
"WM_DELETE_WINDOW", true)) {
event.type = BzfEvent::Quit;
break;
}
}
return false;
}
}
return true;
}
bool XDisplay::getKey(const XEvent& xevent,
BzfKeyEvent& key) const
{
char buf[3];
KeySym keysym;
if (XLookupString((XKeyEvent*)&xevent.xkey, buf, 1, &keysym, NULL) == 1) {
key.ascii = buf[0];
key.button = BzfKeyEvent::NoButton;
if (keysym == XK_Delete) {
key.ascii = 0;
key.button = BzfKeyEvent::Delete;
}
}
else {
key.ascii = 0;
switch (keysym) {
case XK_Pause: key.button = BzfKeyEvent::Pause; break;
case XK_Home: key.button = BzfKeyEvent::Home; break;
case XK_End: key.button = BzfKeyEvent::End; break;
case XK_Left: key.button = BzfKeyEvent::Left; break;
case XK_Right: key.button = BzfKeyEvent::Right; break;
case XK_Up: key.button = BzfKeyEvent::Up; break;
case XK_Down: key.button = BzfKeyEvent::Down; break;
case XK_Page_Up: key.button = BzfKeyEvent::PageUp; break;
case XK_Page_Down: key.button = BzfKeyEvent::PageDown; break;
case XK_Insert: key.button = BzfKeyEvent::Insert; break;
case XK_Delete: key.button = BzfKeyEvent::Delete; break;
case XK_F1: key.button = BzfKeyEvent::F1; break;
case XK_F2: key.button = BzfKeyEvent::F2; break;
case XK_F3: key.button = BzfKeyEvent::F3; break;
case XK_F4: key.button = BzfKeyEvent::F4; break;
case XK_F5: key.button = BzfKeyEvent::F5; break;
case XK_F6: key.button = BzfKeyEvent::F6; break;
case XK_F7: key.button = BzfKeyEvent::F7; break;
case XK_F8: key.button = BzfKeyEvent::F8; break;
case XK_F9: key.button = BzfKeyEvent::F9; break;
case XK_F10: key.button = BzfKeyEvent::F10; break;
case XK_F11: key.button = BzfKeyEvent::F11; break;
case XK_F12: key.button = BzfKeyEvent::F12; break;
default: return false;
}
}
key.shift = 0;
if (xevent.xkey.state & ShiftMask) key.shift |= BzfKeyEvent::ShiftKey;
if (xevent.xkey.state & ControlMask) key.shift |= BzfKeyEvent::ControlKey;
if (xevent.xkey.state & Mod1Mask) key.shift |= BzfKeyEvent::AltKey;
return true;
}
bool XDisplay::doSetResolution(int modeIndex)
{
return mode->set(modeIndex);
}
bool XDisplay::doSetDefaultResolution()
{
return mode->setDefault(getDefaultResolution());
}
//
// XDisplayMode
//
XDisplayMode::XDisplayMode()
{
// do nothing
}
XDisplayMode::~XDisplayMode()
{
// do nothing
}
XDisplayMode::ResInfo** XDisplayMode::init(XDisplay*, int&, int&)
{
// no switching
return NULL;
}
bool XDisplayMode::set(int)
{
// no switching
return false;
}
bool XDisplayMode::setDefault(int mode)
{
return set(mode);
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
|
/* bzflag
* Copyright (c) 1993-2011 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "XDisplay.h"
#include "XWindow.h"
#include "BzfEvent.h"
#include <string.h>
#include <X11/keysym.h>
//
// XDisplay::Rep
//
XDisplay::Rep::Rep(const char* displayName) :
refCount(1),
display(NULL),
screen(0)
{
// open display
display = XOpenDisplay(displayName);
if (!display) return;
// other initialization
screen = DefaultScreen(display);
}
XDisplay::Rep::~Rep()
{
if (display) XCloseDisplay(display);
}
void XDisplay::Rep::ref()
{
refCount++;
}
void XDisplay::Rep::unref()
{
if (--refCount <= 0) delete this;
}
Window XDisplay::Rep::getRootWindow() const
{
return display ? RootWindow(display, screen) : None;
}
//
// XDisplay
//
XDisplay::XDisplay(const char* displayName, XDisplayMode* _mode) :
rep(NULL),
mode(_mode)
{
// open display
rep = new Rep(displayName);
// make default mode changer if one wasn't supplied
if (!mode)
mode = new XDisplayMode;
if (rep->getDisplay()) {
// get resolutions
int numModes, currentMode;
ResInfo** resInfo = mode->init(this, numModes, currentMode);
// if no modes then make default
if (!resInfo) {
resInfo = new ResInfo*[1];
resInfo[0] = new ResInfo("default",
DisplayWidth(rep->getDisplay(), rep->getScreen()),
DisplayHeight(rep->getDisplay(), rep->getScreen()), 0);
numModes = 1;
currentMode = 0;
}
// register modes
initResolutions(resInfo, numModes, currentMode);
}
}
XDisplay::~XDisplay()
{
setDefaultResolution();
delete mode;
rep->unref();
}
bool XDisplay::isValid() const
{
return rep->getDisplay() != NULL;
}
bool XDisplay::isEventPending() const
{
return (XPending(rep->getDisplay()) != 0);
}
bool XDisplay::getEvent(BzfEvent& event) const
{
XEvent xevent;
XNextEvent(rep->getDisplay(), &xevent);
return setupEvent(event, xevent);
}
bool XDisplay::peekEvent(BzfEvent& event) const
{
XEvent xevent;
XPeekEvent(rep->getDisplay(), &xevent);
return setupEvent(event, xevent);
}
bool XDisplay::setupEvent(BzfEvent& event, const XEvent& xevent) const
{
switch (xevent.type) {
case Expose:
case ConfigureNotify:
case MotionNotify:
case MapNotify:
case UnmapNotify:
case ButtonPress:
case ButtonRelease:
case KeyPress:
case KeyRelease:
case ClientMessage:
event.window = XWindow::lookupWindow(xevent.xexpose.window);
if (!event.window) return false;
break;
default:
return false;
}
switch (xevent.type) {
case Expose:
if (xevent.xexpose.count != 0) return false;
event.type = BzfEvent::Redraw;
break;
case ConfigureNotify: {
/* attempt to filter out non-size changes, but getSize() returns the
* current size so it always matches the size in the event.
int width, height;
event.window->getSize(width, height);
if (width == xevent.xconfigure.width &&
height == xevent.xconfigure.height)
return false;
*/
event.type = BzfEvent::Resize;
event.resize.width = xevent.xconfigure.width;
event.resize.height = xevent.xconfigure.height;
break;
}
case MotionNotify:
event.type = BzfEvent::MouseMove;
event.mouseMove.x = xevent.xmotion.x;
event.mouseMove.y = xevent.xmotion.y;
break;
case MapNotify:
event.type = BzfEvent::Map;
break;
case UnmapNotify:
event.type = BzfEvent::Unmap;
break;
case ButtonPress:
event.type = BzfEvent::KeyDown;
event.keyDown.ascii = 0;
event.keyDown.shift = 0;
switch (xevent.xbutton.button) {
case Button1: event.keyDown.button = BzfKeyEvent::LeftMouse; break;
case Button2: event.keyDown.button = BzfKeyEvent::MiddleMouse; break;
case Button3: event.keyDown.button = BzfKeyEvent::RightMouse; break;
default: return false;
}
break;
case ButtonRelease:
event.type = BzfEvent::KeyUp;
event.keyUp.ascii = 0;
event.keyUp.shift = 0;
switch (xevent.xbutton.button) {
case Button1: event.keyUp.button = BzfKeyEvent::LeftMouse; break;
case Button2: event.keyUp.button = BzfKeyEvent::MiddleMouse; break;
case Button3: event.keyUp.button = BzfKeyEvent::RightMouse; break;
default: return false;
}
break;
case KeyPress:
event.type = BzfEvent::KeyDown;
if (!getKey(xevent, event.keyDown)) return false;
break;
case KeyRelease:
event.type = BzfEvent::KeyUp;
if (!getKey(xevent, event.keyUp)) return false;
break;
case ClientMessage: {
XClientMessageEvent* cme = (XClientMessageEvent*)&xevent;
if (cme->format == 32) {
if ((Atom)cme->data.l[0] == XInternAtom(rep->getDisplay(),
"WM_DELETE_WINDOW", true)) {
event.type = BzfEvent::Quit;
break;
}
}
return false;
}
}
return true;
}
bool XDisplay::getKey(const XEvent& xevent,
BzfKeyEvent& key) const
{
char buf[3];
KeySym keysym;
if (XLookupString((XKeyEvent*)&xevent.xkey, buf, 1, &keysym, NULL) == 1) {
key.ascii = buf[0];
key.button = BzfKeyEvent::NoButton;
if (keysym == XK_Delete) {
key.ascii = 0;
key.button = BzfKeyEvent::Delete;
}
}
else {
key.ascii = 0;
switch (keysym) {
case XK_Pause: key.button = BzfKeyEvent::Pause; break;
case XK_Home: key.button = BzfKeyEvent::Home; break;
case XK_End: key.button = BzfKeyEvent::End; break;
case XK_Left: key.button = BzfKeyEvent::Left; break;
case XK_Right: key.button = BzfKeyEvent::Right; break;
case XK_Up: key.button = BzfKeyEvent::Up; break;
case XK_Down: key.button = BzfKeyEvent::Down; break;
case XK_Page_Up: key.button = BzfKeyEvent::PageUp; break;
case XK_Page_Down: key.button = BzfKeyEvent::PageDown; break;
case XK_Insert: key.button = BzfKeyEvent::Insert; break;
case XK_Delete: key.button = BzfKeyEvent::Delete; break;
case XK_F1: key.button = BzfKeyEvent::F1; break;
case XK_F2: key.button = BzfKeyEvent::F2; break;
case XK_F3: key.button = BzfKeyEvent::F3; break;
case XK_F4: key.button = BzfKeyEvent::F4; break;
case XK_F5: key.button = BzfKeyEvent::F5; break;
case XK_F6: key.button = BzfKeyEvent::F6; break;
case XK_F7: key.button = BzfKeyEvent::F7; break;
case XK_F8: key.button = BzfKeyEvent::F8; break;
case XK_F9: key.button = BzfKeyEvent::F9; break;
case XK_F10: key.button = BzfKeyEvent::F10; break;
case XK_F11: key.button = BzfKeyEvent::F11; break;
case XK_F12: key.button = BzfKeyEvent::F12; break;
default: return false;
}
}
key.shift = 0;
if (xevent.xkey.state & ShiftMask) key.shift |= BzfKeyEvent::ShiftKey;
if (xevent.xkey.state & ControlMask) key.shift |= BzfKeyEvent::ControlKey;
if (xevent.xkey.state & Mod1Mask) key.shift |= BzfKeyEvent::AltKey;
return true;
}
bool XDisplay::doSetResolution(int _modeIndex)
{
return mode->set(_modeIndex);
}
bool XDisplay::doSetDefaultResolution()
{
return mode->setDefault(getDefaultResolution());
}
//
// XDisplayMode
//
XDisplayMode::XDisplayMode()
{
// do nothing
}
XDisplayMode::~XDisplayMode()
{
// do nothing
}
XDisplayMode::ResInfo** XDisplayMode::init(XDisplay*, int&, int&)
{
// no switching
return NULL;
}
bool XDisplayMode::set(int)
{
// no switching
return false;
}
bool XDisplayMode::setDefault(int mode)
{
return set(mode);
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
|
Rename variable from "modeIndex" to "_modeIndex" to avoid conflict with the BzfDisplay::modeIndex class element.
|
Rename variable from "modeIndex" to "_modeIndex" to avoid conflict with the BzfDisplay::modeIndex class element.
git-svn-id: 67bf12f30ddf2081c31403e0b02b2123541f1680@21898 08b3d480-bf2c-0410-a26f-811ee3361c24
|
C++
|
lgpl-2.1
|
kongr45gpen/bzflag,kongr45gpen/bzflag,adamsdadakaeti/bzflag,khonkhortisan/bzflag,adamsdadakaeti/bzflag,adamsdadakaeti/bzflag,khonkhortisan/bzflag,khonkhortisan/bzflag,kongr45gpen/bzflag,adamsdadakaeti/bzflag,kongr45gpen/bzflag,adamsdadakaeti/bzflag,adamsdadakaeti/bzflag,kongr45gpen/bzflag,kongr45gpen/bzflag,khonkhortisan/bzflag,kongr45gpen/bzflag,kongr45gpen/bzflag,khonkhortisan/bzflag,adamsdadakaeti/bzflag,khonkhortisan/bzflag,khonkhortisan/bzflag
|
2a498e793e1fd90ba1f4be56a20d53e8c564389c
|
sstd/src/encode_decode.hpp
|
sstd/src/encode_decode.hpp
|
#pragma once
#include <stdio.h>
#include <string.h>
#include <string> // std::string
#include "typeDef.h"
namespace sstd{
std::string base64_encode(const uchar* str, size_t strLen);
std::string base64_encode(const uchar* str);
std::string base64_encode(const std::string& str);
std::string base64_decode(const uchar* str, size_t strLen); // when it was error, return 0 size std::string.
std::string base64_decode(const uchar* str); // when it was error, return 0 size std::string.
std::string base64_decode(const std::string& str); // when it was error, return 0 size std::string.
void print_base64_decode_table(); // for developers
extern const char bin2str_table[256][3];
std::string url_encode(const char* str, size_t strLen);
std::string url_encode(const char* str);
std::string url_encode(std::string& str);
std::string url_encode_type2(const char* str, size_t strLen); // for developers
void url_encode_compare_speed(); // for developers
std::string url_decode(const char* str, size_t strLen); // when it was error, return 0 size std::string.
std::string url_decode(const char* str); // when it was error, return 0 size std::string.
std::string url_decode(std::string& str); // when it was error, return 0 size std::string.
void print_url_decode_table(); // for developers
// std::u16string utf8_to_utf16(const std::string& str);
// std::string utf16_to_utf8(const std::u16string& str);
// utf functions are not checked yet.
std::u32string utf16_to_utf32(const std::u16string& str);
std::u16string utf32_to_utf16(const std::u32string& str);
std:: string utf32_to_utf8 (const std::u32string& str);
std::u32string utf8_to_utf32(const std:: string& str);
std::u16string utf8_to_utf16(const std:: string& str);
std:: string utf16_to_utf8 (const std::u16string& str);
extern const uchar str2bin_table[256];
std::string unicodeEscape_encode(const std::u16string& str);
std::u16string unicodeEscape_decode(const char* str, size_t strLen);
std::u16string unicodeEscape_decode(const char* str);
std::u16string unicodeEscape_decode(const std::string& str);
std::u16string unicodeEscape_decode_type2(const char* str, size_t strLen); // for developers
void unicodeEscape_compare_speed(); // for developers
void print_unicodeEscape_decode_table();
};
|
#pragma once
#include <stdio.h>
#include <string.h>
#include <string> // std::string
#include "typeDef.h"
namespace sstd{
std::string base64_encode(const uchar* str, size_t strLen);
std::string base64_encode(const uchar* str);
std::string base64_encode(const std::string& str);
std::string base64_decode(const uchar* str, size_t strLen); // when it was an error, 0 size std::string is returned.
std::string base64_decode(const uchar* str); // when it was an error, 0 size std::string is returned.
std::string base64_decode(const std::string& str); // when it was an error, 0 size std::string is returned.
void print_base64_decode_table(); // for developers
extern const char bin2str_table[256][3];
std::string url_encode(const char* str, size_t strLen);
std::string url_encode(const char* str);
std::string url_encode(std::string& str);
std::string url_encode_type2(const char* str, size_t strLen); // for developers
void url_encode_compare_speed(); // for developers
std::string url_decode(const char* str, size_t strLen); // when it was an error, 0 size std::string is returned.
std::string url_decode(const char* str); // when it was an error, 0 size std::string is returned.
std::string url_decode(std::string& str); // when it was an error, 0 size std::string is returned.
void print_url_decode_table(); // for developers
// std::u16string utf8_to_utf16(const std::string& str);
// std::string utf16_to_utf8(const std::u16string& str);
// utf functions are not checked yet.
std::u32string utf16_to_utf32(const std::u16string& str);
std::u16string utf32_to_utf16(const std::u32string& str);
std:: string utf32_to_utf8 (const std::u32string& str);
std::u32string utf8_to_utf32(const std:: string& str);
std::u16string utf8_to_utf16(const std:: string& str);
std:: string utf16_to_utf8 (const std::u16string& str);
extern const uchar str2bin_table[256];
std::string unicodeEscape_encode(const std::u16string& str);
std::u16string unicodeEscape_decode(const char* str, size_t strLen);
std::u16string unicodeEscape_decode(const char* str);
std::u16string unicodeEscape_decode(const std::string& str);
std::u16string unicodeEscape_decode_type2(const char* str, size_t strLen); // for developers
void unicodeEscape_compare_speed(); // for developers
void print_unicodeEscape_decode_table();
};
|
fix comment
|
fix comment
|
C++
|
mit
|
admiswalker/SubStandardLibrary,admiswalker/SubStandardLibrary,admiswalker/SubStandardLibrary
|
974750d3efe696e3c1b486e5beb817b8b2d300e3
|
BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpSearchView.cpp
|
BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpSearchView.cpp
|
/*=========================================================================
Program: BlueBerry Platform
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifdef __MINGW32__
// We need to inlclude winbase.h here in order to declare
// atomic intrinsics like InterlockedIncrement correctly.
// Otherwhise, they would be declared wrong within qatomic_windows.h .
#include <windows.h>
#endif
#include "berryHelpSearchView.h"
#include "berryHelpPluginActivator.h"
#include "berryQHelpEngineWrapper.h"
#include "berryHelpEditorInput.h"
#include "berryHelpEditor.h"
#include <QLayout>
#include <QMenu>
#include <QEvent>
#include <QMouseEvent>
#include <QTextBrowser>
#include <QClipboard>
#include <QHelpSearchQueryWidget>
#include <QHelpSearchResultWidget>
#include <QApplication>
namespace berry {
HelpSearchView::HelpSearchView()
: m_ZoomCount(0)
, m_Parent(0)
, m_SearchEngine(HelpPluginActivator::getInstance()->getQHelpEngine().searchEngine())
, m_ResultWidget(0)
, m_QueryWidget(0)
{
}
HelpSearchView::~HelpSearchView()
{
// prevent deletion of the widget
m_ResultWidget->setParent(0);
}
void HelpSearchView::CreateQtPartControl(QWidget* parent)
{
if (m_ResultWidget == 0)
{
m_Parent = parent;
QVBoxLayout* vLayout = new QVBoxLayout(parent);
// This will be lead to strange behavior when using multiple instances of this view
// because the QHelpSearchResultWidget instance is shared. The new view will
// reparent the widget.
m_ResultWidget = m_SearchEngine->resultWidget();
m_QueryWidget = new QHelpSearchQueryWidget();
vLayout->addWidget(m_QueryWidget);
vLayout->addWidget(m_ResultWidget);
connect(m_QueryWidget, SIGNAL(search()), this, SLOT(search()));
connect(m_ResultWidget, SIGNAL(requestShowLink(QUrl)), this,
SLOT(requestShowLink(QUrl)));
connect(m_SearchEngine, SIGNAL(searchingStarted()), this,
SLOT(searchingStarted()));
connect(m_SearchEngine, SIGNAL(searchingFinished(int)), this,
SLOT(searchingFinished(int)));
QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget);
if (browser) // Will be null if QtHelp was configured not to use CLucene.
{
browser->viewport()->installEventFilter(this);
browser->setContextMenuPolicy(Qt::CustomContextMenu);
connect(browser, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(showContextMenu(QPoint)));
}
}
}
void HelpSearchView::SetFocus()
{
if (!(m_ResultWidget->hasFocus()))
{
m_QueryWidget->setFocus();
}
}
void HelpSearchView::zoomIn()
{
QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget);
if (browser && m_ZoomCount != 10)
{
m_ZoomCount++;
browser->zoomIn();
}
}
void HelpSearchView::zoomOut()
{
QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget);
if (browser && m_ZoomCount != -5)
{
m_ZoomCount--;
browser->zoomOut();
}
}
void HelpSearchView::resetZoom()
{
if (m_ZoomCount == 0)
return;
QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget);
if (browser)
{
browser->zoomOut(m_ZoomCount);
m_ZoomCount = 0;
}
}
void HelpSearchView::search() const
{
QList<QHelpSearchQuery> query = m_SearchEngine->queryWidget()->query();
m_SearchEngine->search(query);
}
void HelpSearchView::searchingStarted()
{
m_Parent->setCursor(QCursor(Qt::WaitCursor));
}
void HelpSearchView::searchingFinished(int hits)
{
Q_UNUSED(hits)
m_Parent->unsetCursor();
//qApp->restoreOverrideCursor();
}
void HelpSearchView::requestShowLink(const QUrl &link)
{
HelpPluginActivator::linkActivated(this->GetSite()->GetPage(), link);
}
bool HelpSearchView::eventFilter(QObject* o, QEvent *e)
{
QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget);
if (browser && o == browser->viewport()
&& e->type() == QEvent::MouseButtonRelease)
{
QMouseEvent* me = static_cast<QMouseEvent*>(e);
QUrl link = m_ResultWidget->linkAt(me->pos());
if (!link.isEmpty() || link.isValid())
{
bool controlPressed = me->modifiers() & Qt::ControlModifier;
if((me->button() == Qt::LeftButton && controlPressed)
|| (me->button() == Qt::MidButton))
{
IEditorInput::Pointer input(new HelpEditorInput(link));
this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID);
}
}
}
return QObject::eventFilter(o,e);
}
void HelpSearchView::showContextMenu(const QPoint& point)
{
QMenu menu;
QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget);
if (!browser)
return;
// QPoint point = browser->mapFromGlobal(pos);
// if (!browser->rect().contains(point, true))
// return;
QUrl link = browser->anchorAt(point);
QKeySequence keySeq(QKeySequence::Copy);
QAction *copyAction = menu.addAction(tr("&Copy") + QLatin1String("\t") +
keySeq.toString(QKeySequence::NativeText));
copyAction->setEnabled(QTextCursor(browser->textCursor()).hasSelection());
QAction *copyAnchorAction = menu.addAction(tr("Copy &Link Location"));
copyAnchorAction->setEnabled(!link.isEmpty() && link.isValid());
keySeq = QKeySequence(Qt::CTRL);
QAction *newTabAction = menu.addAction(tr("Open Link in New Tab") +
QLatin1String("\t") + keySeq.toString(QKeySequence::NativeText) +
QLatin1String("LMB"));
newTabAction->setEnabled(!link.isEmpty() && link.isValid());
menu.addSeparator();
keySeq = QKeySequence::SelectAll;
QAction *selectAllAction = menu.addAction(tr("Select All") +
QLatin1String("\t") + keySeq.toString(QKeySequence::NativeText));
QAction *usedAction = menu.exec(browser->mapToGlobal(point));
if (usedAction == copyAction)
{
QTextCursor cursor = browser->textCursor();
if (!cursor.isNull() && cursor.hasSelection())
{
QString selectedText = cursor.selectedText();
QMimeData *data = new QMimeData();
data->setText(selectedText);
QApplication::clipboard()->setMimeData(data);
}
}
else if (usedAction == copyAnchorAction)
{
QApplication::clipboard()->setText(link.toString());
}
else if (usedAction == newTabAction)
{
IEditorInput::Pointer input(new HelpEditorInput(link));
this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID);
}
else if (usedAction == selectAllAction)
{
browser->selectAll();
}
}
}
|
/*=========================================================================
Program: BlueBerry Platform
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifdef __MINGW32__
// We need to inlclude winbase.h here in order to declare
// atomic intrinsics like InterlockedIncrement correctly.
// Otherwhise, they would be declared wrong within qatomic_windows.h .
#include <windows.h>
#endif
#include "berryHelpSearchView.h"
#include "berryHelpPluginActivator.h"
#include "berryQHelpEngineWrapper.h"
#include "berryHelpEditorInput.h"
#include "berryHelpEditor.h"
#include <QLayout>
#include <QMenu>
#include <QEvent>
#include <QMouseEvent>
#include <QTextBrowser>
#include <QClipboard>
#include <QHelpSearchQueryWidget>
#include <QHelpSearchResultWidget>
#include <QApplication>
namespace berry {
HelpSearchView::HelpSearchView()
: m_ZoomCount(0)
, m_Parent(0)
, m_SearchEngine(HelpPluginActivator::getInstance()->getQHelpEngine().searchEngine())
, m_ResultWidget(0)
, m_QueryWidget(0)
{
}
HelpSearchView::~HelpSearchView()
{
// prevent deletion of the widget
m_ResultWidget->setParent(0);
}
void HelpSearchView::CreateQtPartControl(QWidget* parent)
{
if (m_ResultWidget == 0)
{
m_Parent = parent;
QVBoxLayout* vLayout = new QVBoxLayout(parent);
// This will be lead to strange behavior when using multiple instances of this view
// because the QHelpSearchResultWidget instance is shared. The new view will
// reparent the widget.
m_ResultWidget = m_SearchEngine->resultWidget();
m_QueryWidget = new QHelpSearchQueryWidget();
vLayout->addWidget(m_QueryWidget);
vLayout->addWidget(m_ResultWidget);
connect(m_QueryWidget, SIGNAL(search()), this, SLOT(search()));
connect(m_ResultWidget, SIGNAL(requestShowLink(QUrl)), this,
SLOT(requestShowLink(QUrl)));
connect(m_SearchEngine, SIGNAL(searchingStarted()), this,
SLOT(searchingStarted()));
connect(m_SearchEngine, SIGNAL(searchingFinished(int)), this,
SLOT(searchingFinished(int)));
QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget);
if (browser) // Will be null if QtHelp was configured not to use CLucene.
{
browser->viewport()->installEventFilter(this);
browser->setContextMenuPolicy(Qt::CustomContextMenu);
connect(browser, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(showContextMenu(QPoint)));
}
}
}
void HelpSearchView::SetFocus()
{
if (!(m_ResultWidget->hasFocus()))
{
m_QueryWidget->setFocus();
}
}
void HelpSearchView::zoomIn()
{
QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget);
if (browser && m_ZoomCount != 10)
{
m_ZoomCount++;
browser->zoomIn();
}
}
void HelpSearchView::zoomOut()
{
QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget);
if (browser && m_ZoomCount != -5)
{
m_ZoomCount--;
browser->zoomOut();
}
}
void HelpSearchView::resetZoom()
{
if (m_ZoomCount == 0)
return;
QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget);
if (browser)
{
browser->zoomOut(m_ZoomCount);
m_ZoomCount = 0;
}
}
void HelpSearchView::search() const
{
QList<QHelpSearchQuery> query = m_QueryWidget->query();
m_SearchEngine->search(query);
}
void HelpSearchView::searchingStarted()
{
m_Parent->setCursor(QCursor(Qt::WaitCursor));
}
void HelpSearchView::searchingFinished(int hits)
{
Q_UNUSED(hits)
m_Parent->unsetCursor();
//qApp->restoreOverrideCursor();
}
void HelpSearchView::requestShowLink(const QUrl &link)
{
HelpPluginActivator::linkActivated(this->GetSite()->GetPage(), link);
}
bool HelpSearchView::eventFilter(QObject* o, QEvent *e)
{
QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget);
if (browser && o == browser->viewport()
&& e->type() == QEvent::MouseButtonRelease)
{
QMouseEvent* me = static_cast<QMouseEvent*>(e);
QUrl link = m_ResultWidget->linkAt(me->pos());
if (!link.isEmpty() || link.isValid())
{
bool controlPressed = me->modifiers() & Qt::ControlModifier;
if((me->button() == Qt::LeftButton && controlPressed)
|| (me->button() == Qt::MidButton))
{
IEditorInput::Pointer input(new HelpEditorInput(link));
this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID);
}
}
}
return QObject::eventFilter(o,e);
}
void HelpSearchView::showContextMenu(const QPoint& point)
{
QMenu menu;
QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget);
if (!browser)
return;
// QPoint point = browser->mapFromGlobal(pos);
// if (!browser->rect().contains(point, true))
// return;
QUrl link = browser->anchorAt(point);
QKeySequence keySeq(QKeySequence::Copy);
QAction *copyAction = menu.addAction(tr("&Copy") + QLatin1String("\t") +
keySeq.toString(QKeySequence::NativeText));
copyAction->setEnabled(QTextCursor(browser->textCursor()).hasSelection());
QAction *copyAnchorAction = menu.addAction(tr("Copy &Link Location"));
copyAnchorAction->setEnabled(!link.isEmpty() && link.isValid());
keySeq = QKeySequence(Qt::CTRL);
QAction *newTabAction = menu.addAction(tr("Open Link in New Tab") +
QLatin1String("\t") + keySeq.toString(QKeySequence::NativeText) +
QLatin1String("LMB"));
newTabAction->setEnabled(!link.isEmpty() && link.isValid());
menu.addSeparator();
keySeq = QKeySequence::SelectAll;
QAction *selectAllAction = menu.addAction(tr("Select All") +
QLatin1String("\t") + keySeq.toString(QKeySequence::NativeText));
QAction *usedAction = menu.exec(browser->mapToGlobal(point));
if (usedAction == copyAction)
{
QTextCursor cursor = browser->textCursor();
if (!cursor.isNull() && cursor.hasSelection())
{
QString selectedText = cursor.selectedText();
QMimeData *data = new QMimeData();
data->setText(selectedText);
QApplication::clipboard()->setMimeData(data);
}
}
else if (usedAction == copyAnchorAction)
{
QApplication::clipboard()->setText(link.toString());
}
else if (usedAction == newTabAction)
{
IEditorInput::Pointer input(new HelpEditorInput(link));
this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID);
}
else if (usedAction == selectAllAction)
{
browser->selectAll();
}
}
}
|
Use correct query widget.
|
Use correct query widget.
|
C++
|
bsd-3-clause
|
lsanzdiaz/MITK-BiiG,nocnokneo/MITK,RabadanLab/MITKats,MITK/MITK,nocnokneo/MITK,rfloca/MITK,danielknorr/MITK,fmilano/mitk,NifTK/MITK,RabadanLab/MITKats,MITK/MITK,MITK/MITK,iwegner/MITK,fmilano/mitk,lsanzdiaz/MITK-BiiG,danielknorr/MITK,rfloca/MITK,danielknorr/MITK,iwegner/MITK,fmilano/mitk,nocnokneo/MITK,RabadanLab/MITKats,nocnokneo/MITK,NifTK/MITK,rfloca/MITK,lsanzdiaz/MITK-BiiG,nocnokneo/MITK,NifTK/MITK,rfloca/MITK,NifTK/MITK,rfloca/MITK,lsanzdiaz/MITK-BiiG,nocnokneo/MITK,fmilano/mitk,NifTK/MITK,fmilano/mitk,fmilano/mitk,danielknorr/MITK,lsanzdiaz/MITK-BiiG,danielknorr/MITK,MITK/MITK,lsanzdiaz/MITK-BiiG,MITK/MITK,lsanzdiaz/MITK-BiiG,MITK/MITK,nocnokneo/MITK,iwegner/MITK,iwegner/MITK,RabadanLab/MITKats,danielknorr/MITK,RabadanLab/MITKats,rfloca/MITK,iwegner/MITK,RabadanLab/MITKats,danielknorr/MITK,NifTK/MITK,lsanzdiaz/MITK-BiiG,iwegner/MITK,rfloca/MITK,fmilano/mitk
|
86d7b23d98070a7f480d47402b7dc64f8a4bd3e6
|
connections/serialbusconnection.cpp
|
connections/serialbusconnection.cpp
|
#include "serialbusconnection.h"
#include "canconmanager.h"
#include <QCanBus>
#include <QCanBusFrame>
#include <QDateTime>
#include <QDebug>
/***********************************/
/**** class definition ****/
/***********************************/
SerialBusConnection::SerialBusConnection(QString portName) :
CANConnection(portName, CANCon::SOCKETCAN, 1, 4000, true),
mTimer(this) /*NB: set connection as parent of timer to manage it from working thread */
{
}
SerialBusConnection::~SerialBusConnection()
{
stop();
}
void SerialBusConnection::piStarted()
{
connect(&mTimer, SIGNAL(timeout()), this, SLOT(testConnection()));
mTimer.setInterval(1000);
mTimer.setSingleShot(false); //keep ticking
mTimer.start();
mBusData[0].mBus.setEnabled(true);
mBusData[0].mConfigured = true;
}
void SerialBusConnection::piSuspend(bool pSuspend)
{
/* update capSuspended */
setCapSuspended(pSuspend);
/* flush queue if we are suspended */
if(isCapSuspended())
getQueue().flush();
}
void SerialBusConnection::piStop() {
mTimer.stop();
disconnectDevice();
}
bool SerialBusConnection::piGetBusSettings(int pBusIdx, CANBus& pBus)
{
return getBusConfig(pBusIdx, pBus);
}
void SerialBusConnection::piSetBusSettings(int pBusIdx, CANBus bus)
{
CANConStatus stats;
/* sanity checks */
if(0 != pBusIdx)
return;
/* disconnect device if we have one connected */
disconnectDevice();
/* copy bus config */
setBusConfig(0, bus);
/* if bus is not active we are done */
if(!bus.active)
return;
/* create device */
QString errorString;
mDev_p = QCanBus::instance()->createDevice("socketcan", getPort(), &errorString);
if (!mDev_p) {
disconnectDevice();
qDebug() << "Error: createDevice(" << getType() << getPort() << "):" << errorString;
return;
}
/* connect slots */
connect(mDev_p, &QCanBusDevice::errorOccurred, this, &SerialBusConnection::errorReceived);
connect(mDev_p, &QCanBusDevice::framesWritten, this, &SerialBusConnection::framesWritten);
connect(mDev_p, &QCanBusDevice::framesReceived, this, &SerialBusConnection::framesReceived);
/* set configuration */
/*if (p.useConfigurationEnabled) {
foreach (const SettingsDialog::ConfigurationItem &item, p.configurations)
mDev->setConfigurationParameter(item.first, item.second);
}*/
//You cannot set the speed of a socketcan interface, it has to be set with console commands.
//mDev_p->setConfigurationParameter(QCanBusDevice::BitRateKey, bus.speed);
/* connect device */
if (!mDev_p->connectDevice()) {
disconnectDevice();
qDebug() << "can't connect device";
}
}
bool SerialBusConnection::piSendFrame(const CANFrame& pFrame)
{
/* sanity checks */
if(0 != pFrame.bus || pFrame.len>8)
return false;
if (!mDev_p) return false;
/* fill frame */
QCanBusFrame frame;
frame.setFrameId(pFrame.ID);
frame.setExtendedFrameFormat(pFrame.extended);
frame.setPayload(QByteArray(reinterpret_cast<const char *>(pFrame.data),
static_cast<int>(pFrame.len)));
return mDev_p->writeFrame(frame);
}
/***********************************/
/**** private methods ****/
/***********************************/
/* disconnect device */
void SerialBusConnection::disconnectDevice() {
if(mDev_p) {
mDev_p->disconnectDevice();
delete mDev_p;
mDev_p = nullptr;
}
}
void SerialBusConnection::errorReceived(QCanBusDevice::CanBusError error) const
{
switch (error) {
case QCanBusDevice::ReadError:
case QCanBusDevice::WriteError:
case QCanBusDevice::ConnectionError:
case QCanBusDevice::ConfigurationError:
case QCanBusDevice::UnknownError:
qWarning() << mDev_p->errorString();
break;
default:
break;
}
}
void SerialBusConnection::framesWritten(qint64 count)
{
Q_UNUSED(count);
//qDebug() << "Number of frames written:" << count;
}
void SerialBusConnection::framesReceived()
{
uint64_t timeBasis = CANConManager::getInstance()->getTimeBasis();
/* sanity checks */
if(!mDev_p)
return;
/* read frame */
while(true)
{
const QCanBusFrame recFrame = mDev_p->readFrame();
/* exit case */
if(!recFrame.isValid())
break;
/* drop frame if capture is suspended */
if(isCapSuspended())
continue;
/* check frame */
if (recFrame.payload().length() <= 8) {
CANFrame* frame_p = getQueue().get();
if(frame_p) {
frame_p->len = static_cast<uint32_t>(recFrame.payload().length());
frame_p->bus = 0;
memcpy(frame_p->data, recFrame.payload().data(), frame_p->len);
frame_p->extended = recFrame.hasExtendedFrameFormat();
frame_p->ID = recFrame.frameId();
frame_p->isReceived = true;
if (useSystemTime) {
frame_p->timestamp = QDateTime::currentMSecsSinceEpoch() * 1000ul;
}
else frame_p->timestamp = (recFrame.timeStamp().seconds() * 1000000ul + recFrame.timeStamp().microSeconds()) - timeBasis;
checkTargettedFrame(*frame_p);
/* enqueue frame */
getQueue().queue();
}
#if 0
else
qDebug() << "can't get a frame, ERROR";
#endif
}
}
}
void SerialBusConnection::testConnection() {
QCanBusDevice* dev_p = QCanBus::instance()->createDevice("socketcan", getPort());
CANConStatus stats;
switch(getStatus())
{
case CANCon::CONNECTED:
if (!dev_p || !dev_p->connectDevice()) {
/* we have lost connectivity */
disconnectDevice();
setStatus(CANCon::NOT_CONNECTED);
stats.conStatus = getStatus();
stats.numHardwareBuses = mNumBuses;
emit status(stats);
}
break;
case CANCon::NOT_CONNECTED:
if (dev_p && dev_p->connectDevice()) {
if(!mDev_p) {
/* try to reconnect */
CANBus bus;
if(getBusConfig(0, bus))
{
bus.setEnabled(true);
setBusSettings(0, bus);
}
}
/* disconnect test instance */
dev_p->disconnectDevice();
setStatus(CANCon::CONNECTED);
stats.conStatus = getStatus();
stats.numHardwareBuses = mNumBuses;
emit status(stats);
}
break;
default: {}
}
if(dev_p)
delete dev_p;
}
|
#include "serialbusconnection.h"
#include "canconmanager.h"
#include <QCanBus>
#include <QCanBusFrame>
#include <QDateTime>
#include <QDebug>
/***********************************/
/**** class definition ****/
/***********************************/
SerialBusConnection::SerialBusConnection(QString portName) :
CANConnection(portName, CANCon::SOCKETCAN, 1, 4000, true),
mTimer(this) /*NB: set connection as parent of timer to manage it from working thread */
{
}
SerialBusConnection::~SerialBusConnection()
{
stop();
}
void SerialBusConnection::piStarted()
{
connect(&mTimer, SIGNAL(timeout()), this, SLOT(testConnection()));
mTimer.setInterval(1000);
mTimer.setSingleShot(false); //keep ticking
mTimer.start();
mBusData[0].mBus.setEnabled(true);
mBusData[0].mConfigured = true;
}
void SerialBusConnection::piSuspend(bool pSuspend)
{
/* update capSuspended */
setCapSuspended(pSuspend);
/* flush queue if we are suspended */
if(isCapSuspended())
getQueue().flush();
}
void SerialBusConnection::piStop() {
mTimer.stop();
disconnectDevice();
}
bool SerialBusConnection::piGetBusSettings(int pBusIdx, CANBus& pBus)
{
return getBusConfig(pBusIdx, pBus);
}
void SerialBusConnection::piSetBusSettings(int pBusIdx, CANBus bus)
{
CANConStatus stats;
/* sanity checks */
if(0 != pBusIdx)
return;
/* disconnect device if we have one connected */
disconnectDevice();
/* copy bus config */
setBusConfig(0, bus);
/* if bus is not active we are done */
if(!bus.active)
return;
/* create device */
QString errorString;
mDev_p = QCanBus::instance()->createDevice("socketcan", getPort(), &errorString);
if (!mDev_p) {
disconnectDevice();
qDebug() << "Error: createDevice(" << getType() << getPort() << "):" << errorString;
return;
}
/* connect slots */
connect(mDev_p, &QCanBusDevice::errorOccurred, this, &SerialBusConnection::errorReceived);
connect(mDev_p, &QCanBusDevice::framesWritten, this, &SerialBusConnection::framesWritten);
connect(mDev_p, &QCanBusDevice::framesReceived, this, &SerialBusConnection::framesReceived);
/* set configuration */
/*if (p.useConfigurationEnabled) {
foreach (const SettingsDialog::ConfigurationItem &item, p.configurations)
mDev->setConfigurationParameter(item.first, item.second);
}*/
//You cannot set the speed of a socketcan interface, it has to be set with console commands.
//mDev_p->setConfigurationParameter(QCanBusDevice::BitRateKey, bus.speed);
/* connect device */
if (!mDev_p->connectDevice()) {
disconnectDevice();
qDebug() << "can't connect device";
}
}
bool SerialBusConnection::piSendFrame(const CANFrame& pFrame)
{
/* sanity checks */
if(0 != pFrame.bus || pFrame.len>8)
return false;
if (!mDev_p) return false;
/* fill frame */
QCanBusFrame frame;
frame.setFrameId(pFrame.ID);
frame.setExtendedFrameFormat(pFrame.extended);
frame.setPayload(QByteArray(reinterpret_cast<const char *>(pFrame.data),
static_cast<int>(pFrame.len)));
return mDev_p->writeFrame(frame);
}
/***********************************/
/**** private methods ****/
/***********************************/
/* disconnect device */
void SerialBusConnection::disconnectDevice() {
if(mDev_p) {
mDev_p->disconnectDevice();
delete mDev_p;
mDev_p = nullptr;
}
}
void SerialBusConnection::errorReceived(QCanBusDevice::CanBusError error) const
{
switch (error) {
case QCanBusDevice::ReadError:
case QCanBusDevice::WriteError:
case QCanBusDevice::ConnectionError:
case QCanBusDevice::ConfigurationError:
case QCanBusDevice::UnknownError:
qWarning() << mDev_p->errorString();
break;
default:
break;
}
}
void SerialBusConnection::framesWritten(qint64 count)
{
Q_UNUSED(count);
//qDebug() << "Number of frames written:" << count;
}
void SerialBusConnection::framesReceived()
{
uint64_t timeBasis = CANConManager::getInstance()->getTimeBasis();
/* sanity checks */
if(!mDev_p)
return;
/* read frame */
while(true)
{
const QCanBusFrame recFrame = mDev_p->readFrame();
/* exit case */
if(!recFrame.isValid())
break;
/* drop frame if capture is suspended */
if(isCapSuspended())
continue;
/* check frame */
if (recFrame.payload().length() <= 8) {
CANFrame* frame_p = getQueue().get();
if(frame_p) {
frame_p->len = static_cast<uint32_t>(recFrame.payload().length());
frame_p->bus = 0;
if (recFrame.frameType() == QCanBusFrame::ErrorFrame) {
// Constants defined in include/uapi/linux/can/error.h
switch (recFrame.error()) {
case QCanBusFrame::TransmissionTimeoutError:
frame_p->ID = 0x20000001;
break;
case QCanBusFrame::LostArbitrationError:
frame_p->ID = 0x20000002;
break;
case QCanBusFrame::ControllerError:
frame_p->ID = 0x20000004;
break;
case QCanBusFrame::ProtocolViolationError:
frame_p->ID = 0x20000008;
break;
case QCanBusFrame::TransceiverError:
frame_p->ID = 0x20000010;
break;
case QCanBusFrame::MissingAcknowledgmentError:
frame_p->ID = 0x20000020;
break;
case QCanBusFrame::BusOffError:
frame_p->ID = 0x20000040;
break;
case QCanBusFrame::BusError:
frame_p->ID = 0x20000080;
break;
case QCanBusFrame::ControllerRestartError:
frame_p->ID = 0x20000100;
break;
default:
break;
}
frame_p->extended = true;
} else {
frame_p->extended = recFrame.hasExtendedFrameFormat();
frame_p->ID = recFrame.frameId();
}
frame_p->isReceived = true;
if (useSystemTime) {
frame_p->timestamp = QDateTime::currentMSecsSinceEpoch() * 1000ul;
}
else frame_p->timestamp = (recFrame.timeStamp().seconds() * 1000000ul + recFrame.timeStamp().microSeconds()) - timeBasis;
checkTargettedFrame(*frame_p);
/* enqueue frame */
getQueue().queue();
}
#if 0
else
qDebug() << "can't get a frame, ERROR";
#endif
}
}
}
void SerialBusConnection::testConnection() {
QCanBusDevice* dev_p = QCanBus::instance()->createDevice("socketcan", getPort());
CANConStatus stats;
switch(getStatus())
{
case CANCon::CONNECTED:
if (!dev_p || !dev_p->connectDevice()) {
/* we have lost connectivity */
disconnectDevice();
setStatus(CANCon::NOT_CONNECTED);
stats.conStatus = getStatus();
stats.numHardwareBuses = mNumBuses;
emit status(stats);
}
break;
case CANCon::NOT_CONNECTED:
if (dev_p && dev_p->connectDevice()) {
if(!mDev_p) {
/* try to reconnect */
CANBus bus;
if(getBusConfig(0, bus))
{
bus.setEnabled(true);
setBusSettings(0, bus);
}
}
/* disconnect test instance */
dev_p->disconnectDevice();
setStatus(CANCon::CONNECTED);
stats.conStatus = getStatus();
stats.numHardwareBuses = mNumBuses;
emit status(stats);
}
break;
default: {}
}
if(dev_p)
delete dev_p;
}
|
Fix reception of error frames in socketcan interface.
|
Fix reception of error frames in socketcan interface.
|
C++
|
mit
|
collin80/SavvyCAN,collin80/SavvyCAN,collin80/SavvyCAN,collin80/SavvyCAN,collin80/SavvyCAN
|
203eb96dfc62486d7227a165266635a1e39ed368
|
libcaf_net/src/ip.cpp
|
libcaf_net/src/ip.cpp
|
/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2019 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/net/ip.hpp"
#include <cstddef>
#include <string>
#include <utility>
#include <vector>
#include "caf/config.hpp"
#include "caf/detail/socket_sys_includes.hpp"
#include "caf/error.hpp"
#include "caf/ip_address.hpp"
#include "caf/ip_subnet.hpp"
#include "caf/ipv4_address.hpp"
#include "caf/logger.hpp"
#include "caf/string_algorithms.hpp"
#include "caf/string_view.hpp"
#ifdef CAF_WINDOWS
# ifndef _WIN32_WINNT
# define _WIN32_WINNT 0x0600
# endif
# include <iphlpapi.h>
# include <winsock.h>
#else
# include <ifaddrs.h>
# include <net/if.h>
# include <netdb.h>
# include <sys/ioctl.h>
#endif
#ifndef HOST_NAME_MAX
# define HOST_NAME_MAX 255
#endif
using std::pair;
using std::string;
using std::vector;
namespace caf {
namespace net {
namespace ip {
namespace {
// Dummy port to resolve empty string with getaddrinfo.
constexpr string_view dummy_port = "42";
constexpr string_view localhost = "localhost";
void* fetch_in_addr(int family, sockaddr* addr) {
if (family == AF_INET)
return &reinterpret_cast<sockaddr_in*>(addr)->sin_addr;
return &reinterpret_cast<sockaddr_in6*>(addr)->sin6_addr;
}
int fetch_addr_str(char (&buf)[INET6_ADDRSTRLEN], sockaddr* addr) {
if (addr == nullptr)
return AF_UNSPEC;
auto family = addr->sa_family;
auto in_addr = fetch_in_addr(family, addr);
return (family == AF_INET || family == AF_INET6)
&& inet_ntop(family, in_addr, buf, INET6_ADDRSTRLEN) == buf
? family
: AF_UNSPEC;
}
#ifdef CAF_WINDOWS
template <class F>
void for_each_adapter(F f, bool is_link_local = false) {
using adapters_ptr = std::unique_ptr<IP_ADAPTER_ADDRESSES, void (*)(void*)>;
ULONG len = 0;
if (GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, nullptr, nullptr,
&len)
!= ERROR_BUFFER_OVERFLOW) {
CAF_LOG_ERROR("failed to get adapter addresses buffer length");
return;
}
auto adapters = adapters_ptr{reinterpret_cast<IP_ADAPTER_ADDRESSES*>(
::malloc(len)),
free};
if (!adapters) {
CAF_LOG_ERROR("malloc failed");
return;
}
// TODO: The Microsoft WIN32 API example propopses to try three times, other
// examples online just perform the call once. If we notice the call to be
// unreliable, we might adapt that behavior.
if (GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, nullptr,
adapters.get(), &len)
!= ERROR_SUCCESS) {
CAF_LOG_ERROR("failed to get adapter addresses");
return;
}
char ip_buf[INET6_ADDRSTRLEN];
char name_buf[HOST_NAME_MAX];
std::vector<std::pair<std::string, ip_address>> interfaces;
for (auto* it = adapters.get(); it != nullptr; it = it->Next) {
memset(name_buf, 0, HOST_NAME_MAX);
WideCharToMultiByte(CP_ACP, 0, it->FriendlyName, wcslen(it->FriendlyName),
name_buf, HOST_NAME_MAX, nullptr, nullptr);
std::string name{name_buf};
for (auto* addr = it->FirstUnicastAddress; addr != nullptr;
addr = addr->Next) {
memset(ip_buf, 0, INET6_ADDRSTRLEN);
getnameinfo(addr->Address.lpSockaddr, addr->Address.iSockaddrLength,
ip_buf, sizeof(ip_buf), nullptr, 0, NI_NUMERICHOST);
ip_address ip;
if (!is_link_local && starts_with(ip_buf, "fe80:")) {
CAF_LOG_DEBUG("skipping link-local address: " << ip_buf);
continue;
} else if (auto err = parse(ip_buf, ip))
continue;
f(name_buf, ip);
}
}
}
#else // CAF_WINDOWS
template <class F>
void for_each_adapter(F f, bool is_link_local = false) {
ifaddrs* tmp = nullptr;
if (getifaddrs(&tmp) != 0)
return;
std::unique_ptr<ifaddrs, decltype(freeifaddrs)*> addrs{tmp, freeifaddrs};
char buffer[INET6_ADDRSTRLEN];
std::vector<std::pair<std::string, ip_address>> interfaces;
for (auto i = addrs.get(); i != nullptr; i = i->ifa_next) {
auto family = fetch_addr_str(buffer, i->ifa_addr);
if (family != AF_UNSPEC) {
ip_address ip;
if (!is_link_local && starts_with(buffer, "fe80:")) {
CAF_LOG_DEBUG("skipping link-local address: " << buffer);
continue;
} else if (auto err = parse(buffer, ip)) {
CAF_LOG_ERROR("could not parse into ip address " << buffer);
continue;
}
f({i->ifa_name, strlen(i->ifa_name)}, ip);
}
}
}
#endif // CAF_WINDOWS
} // namespace
std::vector<ip_address> resolve(string_view host) {
addrinfo hint;
memset(&hint, 0, sizeof(hint));
hint.ai_socktype = SOCK_STREAM;
hint.ai_family = AF_UNSPEC;
if (host.empty())
hint.ai_flags = AI_PASSIVE;
addrinfo* tmp = nullptr;
std::string host_str{host.begin(), host.end()};
if (getaddrinfo(host.empty() ? nullptr : host_str.c_str(),
host.empty() ? dummy_port.data() : nullptr, &hint, &tmp)
!= 0)
return {};
std::unique_ptr<addrinfo, decltype(freeaddrinfo)*> addrs{tmp, freeaddrinfo};
char buffer[INET6_ADDRSTRLEN];
std::vector<ip_address> results;
for (auto i = addrs.get(); i != nullptr; i = i->ai_next) {
auto family = fetch_addr_str(buffer, i->ai_addr);
if (family != AF_UNSPEC) {
ip_address ip;
if (auto err = parse(buffer, ip))
CAF_LOG_ERROR("could not parse IP address: " << buffer);
else
results.emplace_back(ip);
}
}
// TODO: Should we just prefer ipv6 or use a config option?
// std::stable_sort(std::begin(results), std::end(results),
// [](const ip_address& lhs, const ip_address& rhs) {
// return !lhs.embeds_v4() && rhs.embeds_v4();
// });
return results;
}
std::vector<ip_address> resolve(ip_address host) {
return resolve(to_string(host));
}
std::vector<ip_address> local_addresses(string_view host) {
ip_address host_ip;
std::vector<ip_address> results;
if (host.empty()) {
for_each_adapter(
[&](string_view, ip_address ip) { results.push_back(ip); });
} else if (host == localhost) {
auto v6_local = ip_address{{0}, {0x1}};
auto v4_local = ip_address{make_ipv4_address(127, 0, 0, 1)};
for_each_adapter([&](string_view, ip_address ip) {
if (ip == v4_local || ip == v6_local)
results.push_back(ip);
});
} else if (auto err = parse(host, host_ip)) {
for_each_adapter([&](string_view iface, ip_address ip) {
if (iface == host)
results.push_back(ip);
});
} else {
return local_addresses(host_ip);
}
return results;
}
std::vector<ip_address> local_addresses(ip_address host) {
auto v6_any = ip_address{{0}, {0}};
auto v4_any = ip_address{make_ipv4_address(0, 0, 0, 0)};
// TODO: If is any addr, call resolve with PR #23.
if (host == v4_any)
return {ip_address{make_ipv4_address(0, 0, 0, 0)}};
if (host == v6_any)
return {ip_address{}};
auto link_local = ip_address({0xfe, 0x8, 0x0, 0x0}, {0x0, 0x0, 0x0, 0x0});
auto ll_prefix = ip_subnet(link_local, 10);
// Unless explicitly specified we are going to skip link-local addresses.
auto is_link_local = ll_prefix.contains(host);
std::vector<ip_address> results;
for_each_adapter(
[&](string_view, ip_address ip) {
if (host == ip)
results.push_back(ip);
},
is_link_local);
return results;
}
std::string hostname() {
char buf[HOST_NAME_MAX + 1];
buf[HOST_NAME_MAX] = '\0';
gethostname(buf, HOST_NAME_MAX);
return buf;
}
} // namespace ip
} // namespace net
} // namespace caf
|
/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2019 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/net/ip.hpp"
#include <cstddef>
#include <string>
#include <utility>
#include <vector>
#include "caf/config.hpp"
#include "caf/detail/socket_sys_includes.hpp"
#include "caf/error.hpp"
#include "caf/ip_address.hpp"
#include "caf/ip_subnet.hpp"
#include "caf/ipv4_address.hpp"
#include "caf/logger.hpp"
#include "caf/string_algorithms.hpp"
#include "caf/string_view.hpp"
#ifdef CAF_WINDOWS
# ifndef _WIN32_WINNT
# define _WIN32_WINNT 0x0600
# endif
# include <iphlpapi.h>
# include <winsock.h>
#else
# include <ifaddrs.h>
# include <net/if.h>
# include <netdb.h>
# include <sys/ioctl.h>
#endif
#ifndef HOST_NAME_MAX
# define HOST_NAME_MAX 255
#endif
using std::pair;
using std::string;
using std::vector;
namespace caf {
namespace net {
namespace ip {
namespace {
// Dummy port to resolve empty string with getaddrinfo.
constexpr string_view dummy_port = "42";
constexpr string_view localhost = "localhost";
void* fetch_in_addr(int family, sockaddr* addr) {
if (family == AF_INET)
return &reinterpret_cast<sockaddr_in*>(addr)->sin_addr;
return &reinterpret_cast<sockaddr_in6*>(addr)->sin6_addr;
}
int fetch_addr_str(char (&buf)[INET6_ADDRSTRLEN], sockaddr* addr) {
if (addr == nullptr)
return AF_UNSPEC;
auto family = addr->sa_family;
auto in_addr = fetch_in_addr(family, addr);
return (family == AF_INET || family == AF_INET6)
&& inet_ntop(family, in_addr, buf, INET6_ADDRSTRLEN) == buf
? family
: AF_UNSPEC;
}
#ifdef CAF_WINDOWS
template <class F>
void for_each_adapter(F f, bool is_link_local = false) {
using adapters_ptr = std::unique_ptr<IP_ADAPTER_ADDRESSES, void (*)(void*)>;
ULONG len = 0;
if (GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, nullptr, nullptr,
&len)
!= ERROR_BUFFER_OVERFLOW) {
CAF_LOG_ERROR("failed to get adapter addresses buffer length");
return;
}
auto adapters = adapters_ptr{reinterpret_cast<IP_ADAPTER_ADDRESSES*>(
::malloc(len)),
free};
if (!adapters) {
CAF_LOG_ERROR("malloc failed");
return;
}
// TODO: The Microsoft WIN32 API example propopses to try three times, other
// examples online just perform the call once. If we notice the call to be
// unreliable, we might adapt that behavior.
if (GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, nullptr,
adapters.get(), &len)
!= ERROR_SUCCESS) {
CAF_LOG_ERROR("failed to get adapter addresses");
return;
}
char ip_buf[INET6_ADDRSTRLEN];
char name_buf[HOST_NAME_MAX];
std::vector<std::pair<std::string, ip_address>> interfaces;
for (auto* it = adapters.get(); it != nullptr; it = it->Next) {
memset(name_buf, 0, HOST_NAME_MAX);
WideCharToMultiByte(CP_ACP, 0, it->FriendlyName, wcslen(it->FriendlyName),
name_buf, HOST_NAME_MAX, nullptr, nullptr);
std::string name{name_buf};
for (auto* addr = it->FirstUnicastAddress; addr != nullptr;
addr = addr->Next) {
memset(ip_buf, 0, INET6_ADDRSTRLEN);
getnameinfo(addr->Address.lpSockaddr, addr->Address.iSockaddrLength,
ip_buf, sizeof(ip_buf), nullptr, 0, NI_NUMERICHOST);
ip_address ip;
if (!is_link_local && starts_with(ip_buf, "fe80:")) {
CAF_LOG_DEBUG("skipping link-local address: " << ip_buf);
continue;
} else if (auto err = parse(ip_buf, ip))
continue;
f(name_buf, ip);
}
}
}
#else // CAF_WINDOWS
template <class F>
void for_each_adapter(F f, bool is_link_local = false) {
ifaddrs* tmp = nullptr;
if (getifaddrs(&tmp) != 0)
return;
std::unique_ptr<ifaddrs, decltype(freeifaddrs)*> addrs{tmp, freeifaddrs};
char buffer[INET6_ADDRSTRLEN];
std::vector<std::pair<std::string, ip_address>> interfaces;
for (auto i = addrs.get(); i != nullptr; i = i->ifa_next) {
auto family = fetch_addr_str(buffer, i->ifa_addr);
if (family != AF_UNSPEC) {
ip_address ip;
if (!is_link_local && starts_with(buffer, "fe80:")) {
CAF_LOG_DEBUG("skipping link-local address: " << buffer);
continue;
} else if (auto err = parse(buffer, ip)) {
CAF_LOG_ERROR("could not parse into ip address " << buffer);
continue;
}
f({i->ifa_name, strlen(i->ifa_name)}, ip);
}
}
}
#endif // CAF_WINDOWS
} // namespace
std::vector<ip_address> resolve(string_view host) {
addrinfo hint;
memset(&hint, 0, sizeof(hint));
hint.ai_socktype = SOCK_STREAM;
hint.ai_family = AF_UNSPEC;
if (host.empty())
hint.ai_flags = AI_PASSIVE;
addrinfo* tmp = nullptr;
std::string host_str{host.begin(), host.end()};
if (getaddrinfo(host.empty() ? nullptr : host_str.c_str(),
host.empty() ? dummy_port.data() : nullptr, &hint, &tmp)
!= 0)
return {};
std::unique_ptr<addrinfo, decltype(freeaddrinfo)*> addrs{tmp, freeaddrinfo};
char buffer[INET6_ADDRSTRLEN];
std::vector<ip_address> results;
for (auto i = addrs.get(); i != nullptr; i = i->ai_next) {
auto family = fetch_addr_str(buffer, i->ai_addr);
if (family != AF_UNSPEC) {
ip_address ip;
if (auto err = parse(buffer, ip))
CAF_LOG_ERROR("could not parse IP address: " << buffer);
else
results.emplace_back(ip);
}
}
// TODO: Should we just prefer ipv6 or use a config option?
// std::stable_sort(std::begin(results), std::end(results),
// [](const ip_address& lhs, const ip_address& rhs) {
// return !lhs.embeds_v4() && rhs.embeds_v4();
// });
return results;
}
std::vector<ip_address> resolve(ip_address host) {
return resolve(to_string(host));
}
std::vector<ip_address> local_addresses(string_view host) {
ip_address host_ip;
std::vector<ip_address> results;
if (host.empty()) {
for_each_adapter(
[&](string_view, ip_address ip) { results.push_back(ip); });
} else if (host == localhost) {
auto v6_local = ip_address{{0}, {0x1}};
auto v4_local = ip_address{make_ipv4_address(127, 0, 0, 1)};
for_each_adapter([&](string_view, ip_address ip) {
if (ip == v4_local || ip == v6_local)
results.push_back(ip);
});
} else if (auto err = parse(host, host_ip)) {
for_each_adapter([&](string_view iface, ip_address ip) {
if (iface == host)
results.push_back(ip);
});
} else {
return local_addresses(host_ip);
}
return results;
}
std::vector<ip_address> local_addresses(ip_address host) {
static auto v6_any = ip_address{{0}, {0}};
static auto v4_any = ip_address{make_ipv4_address(0, 0, 0, 0)};
if (host == v4_any || host == v6_any)
return resolve("");
auto link_local = ip_address({0xfe, 0x8, 0x0, 0x0}, {0x0, 0x0, 0x0, 0x0});
auto ll_prefix = ip_subnet(link_local, 10);
// Unless explicitly specified we are going to skip link-local addresses.
auto is_link_local = ll_prefix.contains(host);
std::vector<ip_address> results;
for_each_adapter(
[&](string_view, ip_address ip) {
if (host == ip)
results.push_back(ip);
},
is_link_local);
return results;
}
std::string hostname() {
char buf[HOST_NAME_MAX + 1];
buf[HOST_NAME_MAX] = '\0';
gethostname(buf, HOST_NAME_MAX);
return buf;
}
} // namespace ip
} // namespace net
} // namespace caf
|
Use resolve to get local addresses for any addr
|
Use resolve to get local addresses for any addr
|
C++
|
bsd-3-clause
|
DavadDi/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework,actor-framework/actor-framework,actor-framework/actor-framework,DavadDi/actor-framework,DavadDi/actor-framework,actor-framework/actor-framework
|
8399379750aaf8a65b3f7637aa3efcf898b591f1
|
lib/flow/ir/Instr.cpp
|
lib/flow/ir/Instr.cpp
|
/*
* This file is part of the x0 web server project and is released under AGPL-3.
* http://www.xzero.io/
*
* (c) 2009-2014 Christian Parpart <[email protected]>
*/
#include <x0/flow/ir/Instr.h>
#include <x0/flow/ir/ConstantValue.h>
#include <x0/flow/ir/IRBuiltinHandler.h>
#include <x0/flow/ir/IRBuiltinFunction.h>
#include <x0/flow/ir/BasicBlock.h>
#include <utility>
#include <assert.h>
namespace x0 {
using namespace FlowVM;
Instr::Instr(const Instr& v) :
Value(v),
parent_(nullptr),
operands_(v.operands_)
{
for (Value* op: operands_) {
if (op) {
op->addUse(this);
}
}
}
Instr::Instr(FlowType ty, const std::vector<Value*>& ops, const std::string& name) :
Value(ty, name),
parent_(nullptr),
operands_(ops)
{
for (Value* op: operands_) {
if (op) {
op->addUse(this);
}
}
}
Instr::~Instr()
{
for (Value* op: operands_) {
if (!op)
continue;
op->removeUse(this);
if (!parent())
continue;
if (BasicBlock* oldBB = dynamic_cast<BasicBlock*>(op)) {
parent()->unlinkSuccessor(oldBB);
}
}
}
void Instr::addOperand(Value* value)
{
operands_.push_back(value);
value->addUse(this);
if (BasicBlock* newBB = dynamic_cast<BasicBlock*>(value)) {
parent()->linkSuccessor(newBB);
}
}
Value* Instr::setOperand(size_t i, Value* value)
{
Value* old = operands_[i];
operands_[i] = value;
if (old) {
old->removeUse(this);
if (BasicBlock* oldBB = dynamic_cast<BasicBlock*>(old)) {
parent()->unlinkSuccessor(oldBB);
}
}
if (value) {
value->addUse(this);
if (BasicBlock* newBB = dynamic_cast<BasicBlock*>(value)) {
parent()->linkSuccessor(newBB);
}
}
return old;
}
size_t Instr::replaceOperand(Value* old, Value* replacement)
{
size_t count = 0;
for (size_t i = 0, e = operands_.size(); i != e; ++i) {
if (operands_[i] == old) {
setOperand(i, replacement);
++count;
}
}
return count;
}
void Instr::dumpOne(const char* mnemonic)
{
if (type() != FlowType::Void) {
printf("\t%%%s = %s", name().c_str() ?: "?", mnemonic);
} else {
printf("\t%s", mnemonic);
}
for (size_t i = 0, e = operands_.size(); i != e; ++i) {
printf(i ? ", " : " ");
Value* arg = operands_[i];
if (dynamic_cast<Constant*>(arg)) {
if (auto i = dynamic_cast<ConstantInt*>(arg)) {
printf("%li", i->get());
continue;
}
if (auto s = dynamic_cast<ConstantString*>(arg)) {
printf("\"%s\"", s->get().c_str());
continue;
}
if (auto ip = dynamic_cast<ConstantIP*>(arg)) {
printf("%s", ip->get().c_str());
continue;
}
if (auto cidr = dynamic_cast<ConstantCidr*>(arg)) {
printf("%s", cidr->get().str().c_str());
continue;
}
if (auto re = dynamic_cast<ConstantRegExp*>(arg)) {
printf("/%s/", re->get().pattern().c_str());
continue;
}
if (auto bh = dynamic_cast<IRBuiltinHandler*>(arg)) {
printf("%s", bh->get().to_s().c_str());
continue;
}
if (auto bf = dynamic_cast<IRBuiltinFunction*>(arg)) {
printf("%s", bf->get().to_s().c_str());
continue;
}
}
printf("%%%s", arg->name().c_str());
}
printf("\n");
}
} // namespace x0
|
/*
* This file is part of the x0 web server project and is released under AGPL-3.
* http://www.xzero.io/
*
* (c) 2009-2014 Christian Parpart <[email protected]>
*/
#include <x0/flow/ir/Instr.h>
#include <x0/flow/ir/ConstantValue.h>
#include <x0/flow/ir/ConstantArray.h>
#include <x0/flow/ir/IRBuiltinHandler.h>
#include <x0/flow/ir/IRBuiltinFunction.h>
#include <x0/flow/ir/BasicBlock.h>
#include <utility>
#include <assert.h>
namespace x0 {
using namespace FlowVM;
Instr::Instr(const Instr& v) :
Value(v),
parent_(nullptr),
operands_(v.operands_)
{
for (Value* op: operands_) {
if (op) {
op->addUse(this);
}
}
}
Instr::Instr(FlowType ty, const std::vector<Value*>& ops, const std::string& name) :
Value(ty, name),
parent_(nullptr),
operands_(ops)
{
for (Value* op: operands_) {
if (op) {
op->addUse(this);
}
}
}
Instr::~Instr()
{
for (Value* op: operands_) {
if (!op)
continue;
op->removeUse(this);
if (!parent())
continue;
if (BasicBlock* oldBB = dynamic_cast<BasicBlock*>(op)) {
parent()->unlinkSuccessor(oldBB);
}
}
}
void Instr::addOperand(Value* value)
{
operands_.push_back(value);
value->addUse(this);
if (BasicBlock* newBB = dynamic_cast<BasicBlock*>(value)) {
parent()->linkSuccessor(newBB);
}
}
Value* Instr::setOperand(size_t i, Value* value)
{
Value* old = operands_[i];
operands_[i] = value;
if (old) {
old->removeUse(this);
if (BasicBlock* oldBB = dynamic_cast<BasicBlock*>(old)) {
parent()->unlinkSuccessor(oldBB);
}
}
if (value) {
value->addUse(this);
if (BasicBlock* newBB = dynamic_cast<BasicBlock*>(value)) {
parent()->linkSuccessor(newBB);
}
}
return old;
}
size_t Instr::replaceOperand(Value* old, Value* replacement)
{
size_t count = 0;
for (size_t i = 0, e = operands_.size(); i != e; ++i) {
if (operands_[i] == old) {
setOperand(i, replacement);
++count;
}
}
return count;
}
void Instr::dumpOne(const char* mnemonic)
{
if (type() != FlowType::Void) {
printf("\t%%%s = %s", name().c_str() ?: "?", mnemonic);
} else {
printf("\t%s", mnemonic);
}
for (size_t i = 0, e = operands_.size(); i != e; ++i) {
printf(i ? ", " : " ");
Value* arg = operands_[i];
if (dynamic_cast<Constant*>(arg)) {
if (auto i = dynamic_cast<ConstantInt*>(arg)) {
printf("%li", i->get());
continue;
}
if (auto s = dynamic_cast<ConstantString*>(arg)) {
printf("\"%s\"", s->get().c_str());
continue;
}
if (auto ip = dynamic_cast<ConstantIP*>(arg)) {
printf("%s", ip->get().c_str());
continue;
}
if (auto cidr = dynamic_cast<ConstantCidr*>(arg)) {
printf("%s", cidr->get().str().c_str());
continue;
}
if (auto re = dynamic_cast<ConstantRegExp*>(arg)) {
printf("/%s/", re->get().pattern().c_str());
continue;
}
if (auto bh = dynamic_cast<IRBuiltinHandler*>(arg)) {
printf("%s", bh->get().to_s().c_str());
continue;
}
if (auto bf = dynamic_cast<IRBuiltinFunction*>(arg)) {
printf("%s", bf->get().to_s().c_str());
continue;
}
if (auto ar = dynamic_cast<ConstantArray*>(arg)) {
printf("[");
size_t i = 0;
switch (ar->type()) {
case FlowType::IntArray:
for (const auto& v: ar->get()) {
if (i) printf(", ");
printf("%li", static_cast<ConstantInt*>(v)->get());
++i;
}
break;
case FlowType::StringArray:
for (const auto& v: ar->get()) {
if (i) printf(", ");
printf("\"%s\"", static_cast<ConstantString*>(v)->get().c_str());
++i;
}
break;
case FlowType::IPAddrArray:
for (const auto& v: ar->get()) {
if (i) printf(", ");
printf("%s", static_cast<ConstantIP*>(v)->get().str().c_str());
++i;
}
break;
case FlowType::CidrArray:
for (const auto& v: ar->get()) {
if (i) printf(", ");
printf("\"%s\"", static_cast<ConstantCidr*>(v)->get().str().c_str());
++i;
}
break;
default:
abort();
}
printf("]");
continue;
}
}
printf("%%%s", arg->name().c_str());
}
printf("\n");
}
} // namespace x0
|
print arrays in IR dumps also.
|
[flow] print arrays in IR dumps also.
|
C++
|
mit
|
xzero/x0,xzero/x0,xzero/x0,christianparpart/x0,xzero/x0,xzero/x0,christianparpart/x0,christianparpart/x0,christianparpart/x0,xzero/x0,christianparpart/x0,christianparpart/x0,christianparpart/x0
|
c19e13a861f12e2053229e2f97e92c79b2e2815e
|
framework/source/threadhelp/fairrwlock.cxx
|
framework/source/threadhelp/fairrwlock.cxx
|
/*************************************************************************
*
* $RCSfile: fairrwlock.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: as $ $Date: 2001-05-02 13:00:51 $
*
* 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): _______________________________________
*
*
************************************************************************/
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_THREADHELP_FAIRRWLOCK_HXX_
#include <threadhelp/fairrwlock.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// const
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
namespace framework{
//_________________________________________________________________________________________________________________
// non exported const
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// non exported declarations
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// definitions
//_________________________________________________________________________________________________________________
/*-****************************************************************************************************//**
@short standard ctor
@descr Initialize instance with right start values for correct working.
no reader could exist => m_nReadCount = 0
don't block first comming writer => m_aWriteCondition.set()
@seealso -
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
FairRWLock::FairRWLock()
: m_nReadCount( 0 )
{
m_aWriteCondition.set();
}
/*-****************************************************************************************************//**
@short set lock for reading
@descr A guard should call this method to acquire read access on your member.
Writing isn't allowed then - but nobody could check it for you!
@seealso method releaseReadAccess()
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
void SAL_CALL FairRWLock::acquireReadAccess()
{
// Put call in "SERIALIZE"-queue!
// After successful acquiring this mutex we are alone ...
ResetableGuard aSerializeGuard( m_aSerializer );
// ... but we should synchronize us with other reader!
// May be - they will unregister himself by using releaseReadAccess()!
ResetableGuard aAccessGuard( m_aAccessLock );
// Now we must register us as reader by increasing counter.
// If this the first writer we must close door for possible writer.
// Other reader don't look for this barrier - they work parallel to us!
if( m_nReadCount == 0 )
{
m_aWriteCondition.reset();
}
++m_nReadCount;
}
/*-****************************************************************************************************//**
@short reset lock for reading
@descr A guard should call this method to release read access on your member.
@seealso method acquireReadAccess()
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
void SAL_CALL FairRWLock::releaseReadAccess()
{
// The access lock is enough at this point
// because it's not allowed to wait for all reader or writer here!
// That will cause a deadlock!
ResetableGuard aAccessGuard( m_aAccessLock );
// Unregister as reader first!
// Open writer barrier then if it was the last reader.
--m_nReadCount;
if( m_nReadCount == 0 )
{
m_aWriteCondition.set();
}
}
/*-****************************************************************************************************//**
@short set lock for writing
@descr A guard should call this method to acquire write access on your member.
Reading is allowed too - of course.
After successfully calling of this method you are the only writer.
@seealso method setWorkingMode()
@seealso method releaseWriteAccess()
@param "eRejectReason" , is the reason for rejected calls.
@param "eExceptionMode" , use to enable/disable throwing exceptions automaticly for rejected calls
@return -
@onerror -
*//*-*****************************************************************************************************/
void SAL_CALL FairRWLock::acquireWriteAccess()
{
// You have to stand in our serialize-queue till all reader
// are registered (not for releasing them!) or writer finished their work!
// Don't use a guard to do so - because you must hold the mutex till
// you call releaseWriteAccess()!
// After succesfull acquire you have to wait for current working reader.
// Used condition will open by last gone reader object.
m_aSerializer.acquire();
m_aWriteCondition.wait();
#ifdef ENABLE_MUTEXDEBUG
// A writer is an exclusiv accessor!
LOG_ASSERT2( m_nReadCount!=0, "FairRWLock::acquireWriteAccess()", "No threadsafe code detected ... : Read count != 0!" )
#endif
}
/*-****************************************************************************************************//**
@short reset lock for writing
@descr A guard should call this method to release write access on your member.
@seealso method acquireWriteAccess()
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
void SAL_CALL FairRWLock::releaseWriteAccess()
{
// The only one you have to do here is to release
// hold seriliaze-mutex. All other user of these instance are blocked
// by these mutex!
// You don't need any other mutex here - you are the only one in the moment!
#ifdef ENABLE_MUTEXDEBUG
// A writer is an exclusiv accessor!
LOG_ASSERT2( m_nReadCount!=0, "FairRWLock::releaseWriteAccess()", "No threadsafe code detected ... : Read count != 0!" )
#endif
m_aSerializer.release();
}
/*-****************************************************************************************************//**
@short downgrade a write access to a read access
@descr A guard should call this method to change a write to a read access.
New readers can work too - new writer are blocked!
@attention Don't call this method if you are not a writer!
Results are not defined then ...
An upgrade can't be implemented realy ... because acquiring new access
will be the same - there no differences!
@seealso -
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
void SAL_CALL FairRWLock::downgradeWriteAccess()
{
// You must be a writer to call this method!
// We can't check it - but otherwise it's your problem ...
// Thats why you don't need any mutex here.
#ifdef ENABLE_MUTEXDEBUG
// A writer is an exclusiv accessor!
LOG_ASSERT2( m_nReadCount!=0, "FairRWLock::downgradeWriteAccess()", "No threadsafe code detected ... : Read count != 0!" )
#endif
// Register himself as "new" reader.
// This value must be 0 before - because we support single writer access only!
++m_nReadCount;
// Close barrier for other writer!
// Why?
// You hold the serializer mutex - next one can be a reader OR a writer.
// They must blocked then - because you will be a reader after this call
// and writer use this condition to wait for current reader!
m_aWriteCondition.reset();
// Open door for next waiting thread in serialize queue!
m_aSerializer.release();
}
} // namespace framework
|
/*************************************************************************
*
* $RCSfile: fairrwlock.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: as $ $Date: 2001-05-04 13:13:55 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_THREADHELP_FAIRRWLOCK_HXX_
#include <threadhelp/fairrwlock.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// const
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
namespace framework{
//_________________________________________________________________________________________________________________
// non exported const
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// non exported declarations
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// definitions
//_________________________________________________________________________________________________________________
/*-****************************************************************************************************//**
@short standard ctor
@descr Initialize instance with right start values for correct working.
no reader could exist => m_nReadCount = 0
don't block first comming writer => m_aWriteCondition.set()
@seealso -
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
FairRWLock::FairRWLock()
: m_nReadCount( 0 )
{
m_aWriteCondition.set();
}
/*-****************************************************************************************************//**
@short set lock for reading
@descr A guard should call this method to acquire read access on your member.
Writing isn't allowed then - but nobody could check it for you!
@seealso method releaseReadAccess()
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
void SAL_CALL FairRWLock::acquireReadAccess()
{
// Put call in "SERIALIZE"-queue!
// After successful acquiring this mutex we are alone ...
ResetableGuard aSerializeGuard( m_aSerializer );
// ... but we should synchronize us with other reader!
// May be - they will unregister himself by using releaseReadAccess()!
ResetableGuard aAccessGuard( m_aAccessLock );
// Now we must register us as reader by increasing counter.
// If this the first writer we must close door for possible writer.
// Other reader don't look for this barrier - they work parallel to us!
if( m_nReadCount == 0 )
{
m_aWriteCondition.reset();
}
++m_nReadCount;
}
/*-****************************************************************************************************//**
@short reset lock for reading
@descr A guard should call this method to release read access on your member.
@seealso method acquireReadAccess()
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
void SAL_CALL FairRWLock::releaseReadAccess()
{
// The access lock is enough at this point
// because it's not allowed to wait for all reader or writer here!
// That will cause a deadlock!
ResetableGuard aAccessGuard( m_aAccessLock );
// Unregister as reader first!
// Open writer barrier then if it was the last reader.
--m_nReadCount;
if( m_nReadCount == 0 )
{
m_aWriteCondition.set();
}
}
/*-****************************************************************************************************//**
@short set lock for writing
@descr A guard should call this method to acquire write access on your member.
Reading is allowed too - of course.
After successfully calling of this method you are the only writer.
@seealso method setWorkingMode()
@seealso method releaseWriteAccess()
@param "eRejectReason" , is the reason for rejected calls.
@param "eExceptionMode" , use to enable/disable throwing exceptions automaticly for rejected calls
@return -
@onerror -
*//*-*****************************************************************************************************/
void SAL_CALL FairRWLock::acquireWriteAccess()
{
// You have to stand in our serialize-queue till all reader
// are registered (not for releasing them!) or writer finished their work!
// Don't use a guard to do so - because you must hold the mutex till
// you call releaseWriteAccess()!
// After succesfull acquire you have to wait for current working reader.
// Used condition will open by last gone reader object.
m_aSerializer.acquire();
m_aWriteCondition.wait();
#ifdef ENABLE_MUTEXDEBUG
// A writer is an exclusiv accessor!
LOG_ASSERT2( m_nReadCount!=0, "FairRWLock::acquireWriteAccess()", "No threadsafe code detected ... : Read count != 0!" )
#endif
}
/*-****************************************************************************************************//**
@short reset lock for writing
@descr A guard should call this method to release write access on your member.
@seealso method acquireWriteAccess()
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
void SAL_CALL FairRWLock::releaseWriteAccess()
{
// The only one you have to do here is to release
// hold seriliaze-mutex. All other user of these instance are blocked
// by these mutex!
// You don't need any other mutex here - you are the only one in the moment!
#ifdef ENABLE_MUTEXDEBUG
// A writer is an exclusiv accessor!
LOG_ASSERT2( m_nReadCount!=0, "FairRWLock::releaseWriteAccess()", "No threadsafe code detected ... : Read count != 0!" )
#endif
m_aSerializer.release();
}
/*-****************************************************************************************************//**
@short downgrade a write access to a read access
@descr A guard should call this method to change a write to a read access.
New readers can work too - new writer are blocked!
@attention Don't call this method if you are not a writer!
Results are not defined then ...
An upgrade can't be implemented realy ... because acquiring new access
will be the same - there no differences!
@seealso -
@param -
@return -
@onerror -
*//*-*****************************************************************************************************/
void SAL_CALL FairRWLock::downgradeWriteAccess()
{
// You must be a writer to call this method!
// We can't check it - but otherwise it's your problem ...
// Thats why you don't need any mutex here.
#ifdef ENABLE_MUTEXDEBUG
// A writer is an exclusiv accessor!
LOG_ASSERT2( m_nReadCount!=0, "FairRWLock::downgradeWriteAccess()", "No threadsafe code detected ... : Read count != 0!" )
#endif
// Register himself as "new" reader.
// This value must be 0 before - because we support single writer access only!
++m_nReadCount;
// Close barrier for other writer!
// Why?
// You hold the serializer mutex - next one can be a reader OR a writer.
// They must blocked then - because you will be a reader after this call
// and writer use this condition to wait for current reader!
m_aWriteCondition.reset();
// Open door for next waiting thread in serialize queue!
m_aSerializer.release();
}
} // namespace framework
|
include debug macros
|
include debug macros
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
9e3db86e1142e8c05b5a0a042bcd118b11edf020
|
config_parser.cc
|
config_parser.cc
|
// Copyright 2009 Daniel Erat <[email protected]>
// All rights reserved.
#include "config_parser.h"
#include <cassert>
#include <cerrno>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <vector>
#include "setting.h"
using std::map;
using std::string;
using std::vector;
namespace xsettingsd {
ConfigParser::ConfigParser(CharStream* stream)
: stream_(NULL),
error_line_num_(0) {
Reset(stream);
}
ConfigParser::~ConfigParser() {
delete stream_;
}
string ConfigParser::FormatError() const {
if (error_line_num_ == 0)
return error_str_;
return StringPrintf("%d: %s", error_line_num_, error_str_.c_str());
}
void ConfigParser::Reset(CharStream* stream) {
assert(stream);
delete stream_;
stream_ = stream;
error_line_num_ = 0;
error_str_.clear();
}
bool ConfigParser::Parse(SettingsMap* settings,
const SettingsMap* prev_settings,
uint32_t serial) {
assert(settings);
settings->mutable_map()->clear();
string stream_error;
if (!stream_->Init(&stream_error)) {
SetErrorF("Couldn't init stream (%s)", stream_error.c_str());
return false;
}
enum State {
// At the beginning of a line, before we've encountered a setting name.
NO_SETTING_NAME = 0,
// We've gotten the setting name but not its value.
GOT_SETTING_NAME,
// We've got the value.
GOT_VALUE,
};
State state = NO_SETTING_NAME;
string setting_name;
bool in_comment = false;
while (!stream_->AtEOF()) {
char ch = stream_->GetChar();
if (ch == '#') {
in_comment = true;
continue;
}
if (ch == '\n') {
if (state == GOT_SETTING_NAME) {
SetErrorF("No value for setting \"%s\"", setting_name.c_str());
return false;
}
state = NO_SETTING_NAME;
setting_name.clear();
in_comment = false;
}
if (in_comment || isspace(ch))
continue;
stream_->UngetChar(ch);
switch (state) {
case NO_SETTING_NAME:
if (!ReadSettingName(&setting_name))
return false;
if (settings->map().count(setting_name)) {
SetErrorF("Got duplicate setting name \"%s\"", setting_name.c_str());
return false;
}
state = GOT_SETTING_NAME;
break;
case GOT_SETTING_NAME:
{
Setting* setting = NULL;
if (!ReadValue(&setting))
return false;
const Setting* prev_setting =
prev_settings ? prev_settings->GetSetting(setting_name) : NULL;
setting->UpdateSerial(prev_setting, serial);
settings->mutable_map()->insert(make_pair(setting_name, setting));
}
state = GOT_VALUE;
break;
case GOT_VALUE:
SetErrorF("Got unexpected text after value");
return false;
}
}
if (state != NO_SETTING_NAME && state != GOT_VALUE) {
SetErrorF("Unexpected end of file");
return false;
}
return true;
}
bool ConfigParser::CharStream::Init(string* error_out) {
assert(!initialized_);
initialized_ = true;
return InitImpl(error_out);
}
bool ConfigParser::CharStream::AtEOF() {
assert(initialized_);
return (!have_buffered_char_ && AtEOFImpl());
}
char ConfigParser::CharStream::GetChar() {
assert(initialized_);
prev_at_line_end_ = at_line_end_;
if (at_line_end_) {
line_num_++;
at_line_end_ = false;
}
char ch = 0;
if (have_buffered_char_) {
have_buffered_char_ = false;
ch = buffered_char_;
} else {
ch = GetCharImpl();
}
if (ch == '\n')
at_line_end_ = true;
return ch;
}
void ConfigParser::CharStream::UngetChar(char ch) {
if (prev_at_line_end_)
line_num_--;
at_line_end_ = prev_at_line_end_;
assert(initialized_);
assert(!have_buffered_char_);
buffered_char_ = ch;
have_buffered_char_ = true;
}
ConfigParser::FileCharStream::FileCharStream(const string& filename)
: filename_(filename),
file_(NULL) {
}
ConfigParser::FileCharStream::~FileCharStream() {
if (file_) {
fclose(file_);
file_ = NULL;
}
}
bool ConfigParser::FileCharStream::InitImpl(string* error_out) {
assert(!file_);
file_ = fopen(filename_.c_str(), "r");
if (!file_) {
if (error_out)
*error_out = strerror(errno);
return false;
}
return true;
}
bool ConfigParser::FileCharStream::AtEOFImpl() {
assert(file_);
int ch = GetChar();
UngetChar(ch);
return ch == EOF;
}
char ConfigParser::FileCharStream::GetCharImpl() {
assert(file_);
int ch = fgetc(file_);
return ch;
}
ConfigParser::StringCharStream::StringCharStream(const string& data)
: data_(data),
pos_(0) {
}
bool ConfigParser::StringCharStream::AtEOFImpl() {
return pos_ == data_.size();
}
char ConfigParser::StringCharStream::GetCharImpl() {
return data_.at(pos_++);
}
bool ConfigParser::ReadSettingName(string* name_out) {
assert(name_out);
name_out->clear();
bool prev_was_slash = false;
while (true) {
if (stream_->AtEOF())
break;
char ch = stream_->GetChar();
if (isspace(ch) || ch == '#') {
stream_->UngetChar(ch);
break;
}
if (!(ch >= 'A' && ch <= 'Z') &&
!(ch >= 'a' && ch <= 'z') &&
!(ch >= '0' && ch <= '9') &&
!(ch == '_' || ch == '/')) {
SetErrorF("Got invalid character '%c' in setting name", ch);
return false;
}
if (ch == '/' && name_out->empty()) {
SetErrorF("Got leading slash in setting name");
return false;
}
if (prev_was_slash) {
if (ch == '/') {
SetErrorF("Got two consecutive slashes in setting name");
return false;
}
if (ch >= '0' && ch <= '9') {
SetErrorF("Got digit after slash in setting name");
return false;
}
}
name_out->push_back(ch);
prev_was_slash = (ch == '/');
}
if (name_out->empty()) {
SetErrorF("Got empty setting name");
return false;
}
if (name_out->at(name_out->size() - 1) == '/') {
SetErrorF("Got trailing slash in setting name");
return false;
}
return true;
}
bool ConfigParser::ReadValue(Setting** setting_ptr) {
assert(setting_ptr);
*setting_ptr = NULL;
if (stream_->AtEOF()) {
SetErrorF("Got EOF when starting to read value");
return false;
}
char ch = stream_->GetChar();
stream_->UngetChar(ch);
if (ch >= '0' && ch <= '9') {
int32_t value = 0;
if (!ReadInteger(&value))
return false;
*setting_ptr = new IntegerSetting(value);
} else if (ch == '"') {
string value;
if (!ReadString(&value))
return false;
*setting_ptr = new StringSetting(value);
} else if (ch == '(') {
uint16_t red, green, blue, alpha;
if (!ReadColor(&red, &green, &blue, &alpha))
return false;
*setting_ptr = new ColorSetting(red, green, blue, alpha);
} else {
SetErrorF("Got invalid setting value");
return false;
}
return true;
}
bool ConfigParser::ReadInteger(int32_t* int_out) {
assert(int_out);
*int_out = 0;
bool got_digit = false;
bool negative = false;
while (true) {
if (stream_->AtEOF())
break;
char ch = stream_->GetChar();
if (isspace(ch) || ch == '#') {
stream_->UngetChar(ch);
break;
}
if (ch == '-') {
if (negative) {
SetErrorF("Got extra '-' before integer");
return false;
}
if (!got_digit) {
negative = true;
continue;
} else {
SetErrorF("Got '-' mid-integer");
return false;
}
}
if (!(ch >= '0' && ch <= '9')) {
SetErrorF("Got non-numeric character '%c'", ch);
return false;
}
got_digit = true;
*int_out *= 10;
*int_out += (ch - '0');
// TODO: Check for integer overflow (not a security hole; it'd just be
// nice to warn the user that their setting is going to wrap).
}
if (!got_digit) {
SetErrorF("Got empty integer");
return false;
}
if (negative)
*int_out *= -1;
return true;
}
bool ConfigParser::ReadString(string* str_out) {
assert(str_out);
str_out->clear();
bool in_backslash = false;
if (stream_->AtEOF() || stream_->GetChar() != '\"') {
SetErrorF("String is missing initial double-quote");
return false;
}
while (true) {
if (stream_->AtEOF()) {
SetErrorF("Open string at end of file");
return false;
}
char ch = stream_->GetChar();
if (ch == '\n') {
SetErrorF("Got newline mid-string");
return false;
}
if (!in_backslash) {
if (ch == '"')
break;
if (ch == '\\') {
in_backslash = true;
continue;
}
}
if (in_backslash) {
in_backslash = false;
if (ch == 'n') ch = '\n';
else if (ch == 't') ch = '\t';
}
str_out->push_back(ch);
}
return true;
}
bool ConfigParser::ReadColor(uint16_t* red_out,
uint16_t* green_out,
uint16_t* blue_out,
uint16_t* alpha_out) {
assert(red_out);
assert(green_out);
assert(blue_out);
assert(alpha_out);
if (stream_->AtEOF() || stream_->GetChar() != '(') {
SetErrorF("Color is missing initial parethesis");
return false;
}
vector<uint16_t> nums;
enum State {
BEFORE_NUM,
IN_NUM,
AFTER_NUM,
};
int num = 0;
State state = BEFORE_NUM;
while (true) {
if (stream_->AtEOF()) {
SetErrorF("Got EOF mid-color");
return false;
}
char ch = stream_->GetChar();
if (ch == '\n') {
SetErrorF("Got newline mid-color");
return false;
}
if (ch == ')') {
if (state == BEFORE_NUM) {
SetErrorF("Expected number but got ')'");
return false;
}
if (state == IN_NUM)
nums.push_back(num);
break;
}
if (isspace(ch)) {
if (state == IN_NUM) {
state = AFTER_NUM;
nums.push_back(num);
}
continue;
}
if (ch == ',') {
if (state == BEFORE_NUM) {
SetErrorF("Got unexpected comma");
return false;
}
if (state == IN_NUM)
nums.push_back(num);
state = BEFORE_NUM;
continue;
}
if (!(ch >= '0' && ch <= '9')) {
SetErrorF("Got non-numeric character '%c'", ch);
return false;
}
if (state == AFTER_NUM) {
SetErrorF("Got unexpected digit '%c'", ch);
return false;
}
if (state == BEFORE_NUM) {
state = IN_NUM;
num = 0;
}
num = num * 10 + (ch - '0');
// TODO: Check for integer overflow (not a security hole; it'd just be
// nice to warn the user that their setting is going to wrap).
}
if (nums.size() < 3 || nums.size() > 4) {
SetErrorF("Got %d number%s instead of 3 or 4",
nums.size(), (nums.size() == 1 ? "" : "s"));
return false;
}
*red_out = nums.at(0);
*green_out = nums.at(1);
*blue_out = nums.at(2);
*alpha_out = (nums.size() == 4) ? nums.at(3) : 65535;
return true;
}
void ConfigParser::SetErrorF(const char* format, ...) {
char buffer[1024];
va_list argp;
va_start(argp, format);
vsnprintf(buffer, sizeof(buffer), format, argp);
va_end(argp);
error_line_num_ = stream_->line_num();
error_str_.assign(buffer);
}
} // namespace xsettingsd
|
// Copyright 2009 Daniel Erat <[email protected]>
// All rights reserved.
#include "config_parser.h"
#include <cassert>
#include <cerrno>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <vector>
#include "setting.h"
using std::map;
using std::string;
using std::vector;
namespace xsettingsd {
ConfigParser::ConfigParser(CharStream* stream)
: stream_(NULL),
error_line_num_(0) {
Reset(stream);
}
ConfigParser::~ConfigParser() {
delete stream_;
}
string ConfigParser::FormatError() const {
if (error_line_num_ == 0)
return error_str_;
return StringPrintf("%d: %s", error_line_num_, error_str_.c_str());
}
void ConfigParser::Reset(CharStream* stream) {
assert(stream);
delete stream_;
stream_ = stream;
error_line_num_ = 0;
error_str_.clear();
}
bool ConfigParser::Parse(SettingsMap* settings,
const SettingsMap* prev_settings,
uint32_t serial) {
assert(settings);
settings->mutable_map()->clear();
string stream_error;
if (!stream_->Init(&stream_error)) {
SetErrorF("Couldn't init stream (%s)", stream_error.c_str());
return false;
}
enum State {
// At the beginning of a line, before we've encountered a setting name.
NO_SETTING_NAME = 0,
// We've gotten the setting name but not its value.
GOT_SETTING_NAME,
// We've got the value.
GOT_VALUE,
};
State state = NO_SETTING_NAME;
string setting_name;
bool in_comment = false;
while (!stream_->AtEOF()) {
char ch = stream_->GetChar();
if (ch == '#') {
in_comment = true;
continue;
}
if (ch == '\n') {
if (state == GOT_SETTING_NAME) {
SetErrorF("No value for setting \"%s\"", setting_name.c_str());
return false;
}
state = NO_SETTING_NAME;
setting_name.clear();
in_comment = false;
}
if (in_comment || isspace(ch))
continue;
stream_->UngetChar(ch);
switch (state) {
case NO_SETTING_NAME:
if (!ReadSettingName(&setting_name))
return false;
if (settings->map().count(setting_name)) {
SetErrorF("Got duplicate setting name \"%s\"", setting_name.c_str());
return false;
}
state = GOT_SETTING_NAME;
break;
case GOT_SETTING_NAME:
{
Setting* setting = NULL;
if (!ReadValue(&setting))
return false;
const Setting* prev_setting =
prev_settings ? prev_settings->GetSetting(setting_name) : NULL;
setting->UpdateSerial(prev_setting, serial);
settings->mutable_map()->insert(make_pair(setting_name, setting));
}
state = GOT_VALUE;
break;
case GOT_VALUE:
SetErrorF("Got unexpected text after value");
return false;
}
}
if (state != NO_SETTING_NAME && state != GOT_VALUE) {
SetErrorF("Unexpected end of file");
return false;
}
return true;
}
bool ConfigParser::CharStream::Init(string* error_out) {
assert(!initialized_);
initialized_ = true;
return InitImpl(error_out);
}
bool ConfigParser::CharStream::AtEOF() {
assert(initialized_);
return (!have_buffered_char_ && AtEOFImpl());
}
char ConfigParser::CharStream::GetChar() {
assert(initialized_);
prev_at_line_end_ = at_line_end_;
if (at_line_end_) {
line_num_++;
at_line_end_ = false;
}
char ch = 0;
if (have_buffered_char_) {
have_buffered_char_ = false;
ch = buffered_char_;
} else {
ch = GetCharImpl();
}
if (ch == '\n')
at_line_end_ = true;
return ch;
}
void ConfigParser::CharStream::UngetChar(char ch) {
if (prev_at_line_end_)
line_num_--;
at_line_end_ = prev_at_line_end_;
assert(initialized_);
assert(!have_buffered_char_);
buffered_char_ = ch;
have_buffered_char_ = true;
}
ConfigParser::FileCharStream::FileCharStream(const string& filename)
: filename_(filename),
file_(NULL) {
}
ConfigParser::FileCharStream::~FileCharStream() {
if (file_) {
fclose(file_);
file_ = NULL;
}
}
bool ConfigParser::FileCharStream::InitImpl(string* error_out) {
assert(!file_);
file_ = fopen(filename_.c_str(), "r");
if (!file_) {
if (error_out)
*error_out = strerror(errno);
return false;
}
return true;
}
bool ConfigParser::FileCharStream::AtEOFImpl() {
assert(file_);
int ch = GetChar();
UngetChar(ch);
return ch == EOF;
}
char ConfigParser::FileCharStream::GetCharImpl() {
assert(file_);
int ch = fgetc(file_);
return ch;
}
ConfigParser::StringCharStream::StringCharStream(const string& data)
: data_(data),
pos_(0) {
}
bool ConfigParser::StringCharStream::AtEOFImpl() {
return pos_ == data_.size();
}
char ConfigParser::StringCharStream::GetCharImpl() {
return data_.at(pos_++);
}
bool ConfigParser::ReadSettingName(string* name_out) {
assert(name_out);
name_out->clear();
bool prev_was_slash = false;
while (true) {
if (stream_->AtEOF())
break;
char ch = stream_->GetChar();
if (isspace(ch) || ch == '#') {
stream_->UngetChar(ch);
break;
}
if (!(ch >= 'A' && ch <= 'Z') &&
!(ch >= 'a' && ch <= 'z') &&
!(ch >= '0' && ch <= '9') &&
!(ch == '_' || ch == '/')) {
SetErrorF("Got invalid character '%c' in setting name", ch);
return false;
}
if (ch == '/' && name_out->empty()) {
SetErrorF("Got leading slash in setting name");
return false;
}
if (prev_was_slash) {
if (ch == '/') {
SetErrorF("Got two consecutive slashes in setting name");
return false;
}
if (ch >= '0' && ch <= '9') {
SetErrorF("Got digit after slash in setting name");
return false;
}
}
name_out->push_back(ch);
prev_was_slash = (ch == '/');
}
if (name_out->empty()) {
SetErrorF("Got empty setting name");
return false;
}
if (name_out->at(name_out->size() - 1) == '/') {
SetErrorF("Got trailing slash in setting name");
return false;
}
return true;
}
bool ConfigParser::ReadValue(Setting** setting_ptr) {
assert(setting_ptr);
*setting_ptr = NULL;
if (stream_->AtEOF()) {
SetErrorF("Got EOF when starting to read value");
return false;
}
char ch = stream_->GetChar();
stream_->UngetChar(ch);
if ((ch >= '0' && ch <= '9') || ch == '-') {
int32_t value = 0;
if (!ReadInteger(&value))
return false;
*setting_ptr = new IntegerSetting(value);
} else if (ch == '"') {
string value;
if (!ReadString(&value))
return false;
*setting_ptr = new StringSetting(value);
} else if (ch == '(') {
uint16_t red, green, blue, alpha;
if (!ReadColor(&red, &green, &blue, &alpha))
return false;
*setting_ptr = new ColorSetting(red, green, blue, alpha);
} else {
SetErrorF("Got invalid setting value");
return false;
}
return true;
}
bool ConfigParser::ReadInteger(int32_t* int_out) {
assert(int_out);
*int_out = 0;
bool got_digit = false;
bool negative = false;
while (true) {
if (stream_->AtEOF())
break;
char ch = stream_->GetChar();
if (isspace(ch) || ch == '#') {
stream_->UngetChar(ch);
break;
}
if (ch == '-') {
if (negative) {
SetErrorF("Got extra '-' before integer");
return false;
}
if (!got_digit) {
negative = true;
continue;
} else {
SetErrorF("Got '-' mid-integer");
return false;
}
}
if (!(ch >= '0' && ch <= '9')) {
SetErrorF("Got non-numeric character '%c'", ch);
return false;
}
got_digit = true;
*int_out *= 10;
*int_out += (ch - '0');
// TODO: Check for integer overflow (not a security hole; it'd just be
// nice to warn the user that their setting is going to wrap).
}
if (!got_digit) {
SetErrorF("Got empty integer");
return false;
}
if (negative)
*int_out *= -1;
return true;
}
bool ConfigParser::ReadString(string* str_out) {
assert(str_out);
str_out->clear();
bool in_backslash = false;
if (stream_->AtEOF() || stream_->GetChar() != '\"') {
SetErrorF("String is missing initial double-quote");
return false;
}
while (true) {
if (stream_->AtEOF()) {
SetErrorF("Open string at end of file");
return false;
}
char ch = stream_->GetChar();
if (ch == '\n') {
SetErrorF("Got newline mid-string");
return false;
}
if (!in_backslash) {
if (ch == '"')
break;
if (ch == '\\') {
in_backslash = true;
continue;
}
}
if (in_backslash) {
in_backslash = false;
if (ch == 'n') ch = '\n';
else if (ch == 't') ch = '\t';
}
str_out->push_back(ch);
}
return true;
}
bool ConfigParser::ReadColor(uint16_t* red_out,
uint16_t* green_out,
uint16_t* blue_out,
uint16_t* alpha_out) {
assert(red_out);
assert(green_out);
assert(blue_out);
assert(alpha_out);
if (stream_->AtEOF() || stream_->GetChar() != '(') {
SetErrorF("Color is missing initial parethesis");
return false;
}
vector<uint16_t> nums;
enum State {
BEFORE_NUM,
IN_NUM,
AFTER_NUM,
};
int num = 0;
State state = BEFORE_NUM;
while (true) {
if (stream_->AtEOF()) {
SetErrorF("Got EOF mid-color");
return false;
}
char ch = stream_->GetChar();
if (ch == '\n') {
SetErrorF("Got newline mid-color");
return false;
}
if (ch == ')') {
if (state == BEFORE_NUM) {
SetErrorF("Expected number but got ')'");
return false;
}
if (state == IN_NUM)
nums.push_back(num);
break;
}
if (isspace(ch)) {
if (state == IN_NUM) {
state = AFTER_NUM;
nums.push_back(num);
}
continue;
}
if (ch == ',') {
if (state == BEFORE_NUM) {
SetErrorF("Got unexpected comma");
return false;
}
if (state == IN_NUM)
nums.push_back(num);
state = BEFORE_NUM;
continue;
}
if (!(ch >= '0' && ch <= '9')) {
SetErrorF("Got non-numeric character '%c'", ch);
return false;
}
if (state == AFTER_NUM) {
SetErrorF("Got unexpected digit '%c'", ch);
return false;
}
if (state == BEFORE_NUM) {
state = IN_NUM;
num = 0;
}
num = num * 10 + (ch - '0');
// TODO: Check for integer overflow (not a security hole; it'd just be
// nice to warn the user that their setting is going to wrap).
}
if (nums.size() < 3 || nums.size() > 4) {
SetErrorF("Got %d number%s instead of 3 or 4",
nums.size(), (nums.size() == 1 ? "" : "s"));
return false;
}
*red_out = nums.at(0);
*green_out = nums.at(1);
*blue_out = nums.at(2);
*alpha_out = (nums.size() == 4) ? nums.at(3) : 65535;
return true;
}
void ConfigParser::SetErrorF(const char* format, ...) {
char buffer[1024];
va_list argp;
va_start(argp, format);
vsnprintf(buffer, sizeof(buffer), format, argp);
va_end(argp);
error_line_num_ = stream_->line_num();
error_str_.assign(buffer);
}
} // namespace xsettingsd
|
allow negative int values. ConfigParser::ReadInteger can handle these, but ::ReadValue was never calling ::ReadInteger if the leading character was a - (minus) sign. This makes the input to xsettingsd consistent with the output of dump_xsettings.
|
Bugfix: allow negative int values.
ConfigParser::ReadInteger can handle these, but ::ReadValue was never
calling ::ReadInteger if the leading character was a - (minus) sign.
This makes the input to xsettingsd consistent with the output of
dump_xsettings.
|
C++
|
bsd-3-clause
|
derat/xsettingsd,derat/xsettingsd
|
f86bd966767791d34b2bc09234ef1849c43f60ea
|
gpu/command_buffer/client/gles2_demo_cc.cc
|
gpu/command_buffer/client/gles2_demo_cc.cc
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is here so other GLES2 related files can have a common set of
// includes where appropriate.
#include "gpu/command_buffer/client/gles2_demo_cc.h"
#include <math.h>
#include <GLES2/gl2.h>
#include <string>
namespace {
GLuint g_texture = 0;
int g_textureLoc = -1;
GLuint g_programObject = 0;
GLuint g_worldMatrixLoc = 0;
GLuint g_vbo = 0;
GLsizei g_texCoordOffset = 0;
int g_angle = 0;
void CheckGLError(const char* func_name, int line_no) {
#ifndef NDEBUG
GLenum error = GL_NO_ERROR;
while ((error = glGetError()) != GL_NO_ERROR) {
DLOG(ERROR) << "GL Error in " << func_name << " at line " << line_no
<< ": " << error;
}
#endif
}
GLuint LoadShader(GLenum type, const char* shaderSrc) {
CheckGLError("LoadShader", __LINE__);
GLuint shader = glCreateShader(type);
if (shader == 0) {
return 0;
}
// Load the shader source
glShaderSource(shader, 1, &shaderSrc, NULL);
// Compile the shader
glCompileShader(shader);
// Check the compile status
GLint value;
glGetShaderiv(shader, GL_COMPILE_STATUS, &value);
if (value == 0) {
char buffer[1024];
GLsizei length;
glGetShaderInfoLog(shader, sizeof(buffer), &length, buffer);
std::string log(buffer, length);
DLOG(ERROR) << "Error compiling shader:" << log;
glDeleteShader(shader);
return 0;
}
return shader;
}
void InitShaders() {
static const char* vShaderStr =
"uniform mat4 worldMatrix;\n"
"attribute vec3 g_Position;\n"
"attribute vec2 g_TexCoord0;\n"
"varying vec2 texCoord;\n"
"void main()\n"
"{\n"
" gl_Position = worldMatrix *\n"
" vec4(g_Position.x, g_Position.y, g_Position.z, 1.0);\n"
" texCoord = g_TexCoord0;\n"
"}\n";
static const char* fShaderStr =
"uniform sampler2D tex;\n"
"varying vec2 texCoord;\n"
"void main()\n"
"{\n"
" gl_FragColor = texture2D(tex, texCoord);\n"
"}\n";
CheckGLError("InitShaders", __LINE__);
GLuint vertexShader = LoadShader(GL_VERTEX_SHADER, vShaderStr);
GLuint fragmentShader = LoadShader(GL_FRAGMENT_SHADER, fShaderStr);
// Create the program object
GLuint programObject = glCreateProgram();
if (programObject == 0) {
DLOG(ERROR) << "Creating program failed";
return;
}
glAttachShader(programObject, vertexShader);
glAttachShader(programObject, fragmentShader);
// Bind g_Position to attribute 0
// Bind g_TexCoord0 to attribute 1
glBindAttribLocation(programObject, 0, "g_Position");
glBindAttribLocation(programObject, 1, "g_TexCoord0");
// Link the program
glLinkProgram(programObject);
// Check the link status
GLint linked;
glGetProgramiv(programObject, GL_LINK_STATUS, &linked);
if (linked == 0) {
char buffer[1024];
GLsizei length;
glGetProgramInfoLog(programObject, sizeof(buffer), &length, buffer);
std::string log(buffer, length);
DLOG(ERROR) << "Error linking program:" << log;
glDeleteProgram(programObject);
return;
}
g_programObject = programObject;
g_worldMatrixLoc = glGetUniformLocation(g_programObject, "worldMatrix");
g_textureLoc = glGetUniformLocation(g_programObject, "tex");
glGenBuffers(1, &g_vbo);
glBindBuffer(GL_ARRAY_BUFFER, g_vbo);
static float vertices[] = {
0.25, 0.75, 0.0,
-0.75, 0.75, 0.0,
-0.75, -0.25, 0.0,
0.25, 0.75, 0.0,
-0.75, -0.25, 0.0,
0.25, -0.25, 0.0,
};
static float texCoords[] = {
1.0, 1.0,
0.0, 1.0,
0.0, 0.0,
1.0, 1.0,
0.0, 0.0,
1.0, 0.0,
};
g_texCoordOffset = sizeof(vertices);
glBufferData(GL_ARRAY_BUFFER,
sizeof(vertices) + sizeof(texCoords),
NULL,
GL_STATIC_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
glBufferSubData(GL_ARRAY_BUFFER, g_texCoordOffset,
sizeof(texCoords), texCoords);
CheckGLError("InitShaders", __LINE__);
}
GLuint CreateCheckerboardTexture() {
CheckGLError("CreateCheckerboardTexture", __LINE__);
static unsigned char pixels[] = {
255, 255, 255,
0, 0, 0,
0, 0, 0,
255, 255, 255,
};
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_UNSIGNED_BYTE,
pixels);
CheckGLError("CreateCheckerboardTexture", __LINE__);
return texture;
}
} // anonymous namespace.
void GLFromCPPInit() {
CheckGLError("GLFromCPPInit", __LINE__);
glClearColor(0.f, 0.f, .7f, 1.f);
g_texture = CreateCheckerboardTexture();
InitShaders();
CheckGLError("GLFromCPPInit", __LINE__);
}
void GLFromCPPDraw() {
const float kPi = 3.1415926535897932384626433832795f;
CheckGLError("GLFromCPPDraw", __LINE__);
// TODO(kbr): base the angle on time rather than on ticks
g_angle = (g_angle + 1) % 360;
// Rotate about the Z axis
GLfloat rot_matrix[16];
GLfloat cos_angle = cosf(static_cast<GLfloat>(g_angle) * kPi / 180.0f);
GLfloat sin_angle = sinf(static_cast<GLfloat>(g_angle) * kPi / 180.0f);
// OpenGL matrices are column-major
rot_matrix[0] = cos_angle;
rot_matrix[1] = sin_angle;
rot_matrix[2] = 0.0f;
rot_matrix[3] = 0.0f;
rot_matrix[4] = -sin_angle;
rot_matrix[5] = cos_angle;
rot_matrix[6] = 0.0f;
rot_matrix[7] = 0.0f;
rot_matrix[8] = 0.0f;
rot_matrix[9] = 0.0f;
rot_matrix[10] = 1.0f;
rot_matrix[11] = 0.0f;
rot_matrix[12] = 0.0f;
rot_matrix[13] = 0.0f;
rot_matrix[14] = 0.0f;
rot_matrix[15] = 1.0f;
// Note: the viewport is automatically set up to cover the entire Canvas.
// Clear the color buffer
glClear(GL_COLOR_BUFFER_BIT);
CheckGLError("GLFromCPPDraw", __LINE__);
// Use the program object
glUseProgram(g_programObject);
CheckGLError("GLFromCPPDraw", __LINE__);
// Set up the model matrix
glUniformMatrix4fv(g_worldMatrixLoc, 1, GL_FALSE, rot_matrix);
// Load the vertex data
glBindBuffer(GL_ARRAY_BUFFER, g_vbo);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0,
reinterpret_cast<const void*>(g_texCoordOffset));
CheckGLError("GLFromCPPDraw", __LINE__);
// Bind the texture to texture unit 0
glBindTexture(GL_TEXTURE_2D, g_texture);
CheckGLError("GLFromCPPDraw", __LINE__);
// Point the uniform sampler to texture unit 0
glUniform1i(g_textureLoc, 0);
CheckGLError("GLFromCPPDraw", __LINE__);
glDrawArrays(GL_TRIANGLES, 0, 6);
CheckGLError("GLFromCPPDraw", __LINE__);
glFlush();
}
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is here so other GLES2 related files can have a common set of
// includes where appropriate.
#include "gpu/command_buffer/client/gles2_demo_cc.h"
#include <math.h>
#include <GLES2/gl2.h>
#include <string>
namespace {
GLuint g_texture = 0;
int g_textureLoc = -1;
GLuint g_programObject = 0;
GLuint g_worldMatrixLoc = 0;
GLuint g_vbo = 0;
GLsizei g_texCoordOffset = 0;
int g_angle = 0;
void CheckGLError(const char* func_name, int line_no) {
#ifndef NDEBUG
GLenum error = GL_NO_ERROR;
while ((error = glGetError()) != GL_NO_ERROR) {
DLOG(ERROR) << "GL Error in " << func_name << " at line " << line_no
<< ": " << error;
}
#endif
}
GLuint LoadShader(GLenum type, const char* shaderSrc) {
CheckGLError("LoadShader", __LINE__);
GLuint shader = glCreateShader(type);
if (shader == 0) {
return 0;
}
// Load the shader source
glShaderSource(shader, 1, &shaderSrc, NULL);
// Compile the shader
glCompileShader(shader);
// Check the compile status
GLint value;
glGetShaderiv(shader, GL_COMPILE_STATUS, &value);
if (value == 0) {
char buffer[1024];
GLsizei length = 0;
glGetShaderInfoLog(shader, sizeof(buffer), &length, buffer);
std::string log(buffer, length);
DLOG(ERROR) << "Error compiling shader:" << log;
glDeleteShader(shader);
return 0;
}
return shader;
}
void InitShaders() {
static const char* vShaderStr =
"uniform mat4 worldMatrix;\n"
"attribute vec3 g_Position;\n"
"attribute vec2 g_TexCoord0;\n"
"varying vec2 texCoord;\n"
"void main()\n"
"{\n"
" gl_Position = worldMatrix *\n"
" vec4(g_Position.x, g_Position.y, g_Position.z, 1.0);\n"
" texCoord = g_TexCoord0;\n"
"}\n";
static const char* fShaderStr =
"uniform sampler2D tex;\n"
"varying vec2 texCoord;\n"
"void main()\n"
"{\n"
" gl_FragColor = texture2D(tex, texCoord);\n"
"}\n";
CheckGLError("InitShaders", __LINE__);
GLuint vertexShader = LoadShader(GL_VERTEX_SHADER, vShaderStr);
GLuint fragmentShader = LoadShader(GL_FRAGMENT_SHADER, fShaderStr);
// Create the program object
GLuint programObject = glCreateProgram();
if (programObject == 0) {
DLOG(ERROR) << "Creating program failed";
return;
}
glAttachShader(programObject, vertexShader);
glAttachShader(programObject, fragmentShader);
// Bind g_Position to attribute 0
// Bind g_TexCoord0 to attribute 1
glBindAttribLocation(programObject, 0, "g_Position");
glBindAttribLocation(programObject, 1, "g_TexCoord0");
// Link the program
glLinkProgram(programObject);
// Check the link status
GLint linked;
glGetProgramiv(programObject, GL_LINK_STATUS, &linked);
if (linked == 0) {
char buffer[1024];
GLsizei length;
glGetProgramInfoLog(programObject, sizeof(buffer), &length, buffer);
std::string log(buffer, length);
DLOG(ERROR) << "Error linking program:" << log;
glDeleteProgram(programObject);
return;
}
g_programObject = programObject;
g_worldMatrixLoc = glGetUniformLocation(g_programObject, "worldMatrix");
g_textureLoc = glGetUniformLocation(g_programObject, "tex");
glGenBuffers(1, &g_vbo);
glBindBuffer(GL_ARRAY_BUFFER, g_vbo);
static float vertices[] = {
0.25, 0.75, 0.0,
-0.75, 0.75, 0.0,
-0.75, -0.25, 0.0,
0.25, 0.75, 0.0,
-0.75, -0.25, 0.0,
0.25, -0.25, 0.0,
};
static float texCoords[] = {
1.0, 1.0,
0.0, 1.0,
0.0, 0.0,
1.0, 1.0,
0.0, 0.0,
1.0, 0.0,
};
g_texCoordOffset = sizeof(vertices);
glBufferData(GL_ARRAY_BUFFER,
sizeof(vertices) + sizeof(texCoords),
NULL,
GL_STATIC_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
glBufferSubData(GL_ARRAY_BUFFER, g_texCoordOffset,
sizeof(texCoords), texCoords);
CheckGLError("InitShaders", __LINE__);
}
GLuint CreateCheckerboardTexture() {
CheckGLError("CreateCheckerboardTexture", __LINE__);
static unsigned char pixels[] = {
255, 255, 255,
0, 0, 0,
0, 0, 0,
255, 255, 255,
};
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_UNSIGNED_BYTE,
pixels);
CheckGLError("CreateCheckerboardTexture", __LINE__);
return texture;
}
} // anonymous namespace.
void GLFromCPPInit() {
CheckGLError("GLFromCPPInit", __LINE__);
glClearColor(0.f, 0.f, .7f, 1.f);
g_texture = CreateCheckerboardTexture();
InitShaders();
CheckGLError("GLFromCPPInit", __LINE__);
}
void GLFromCPPDraw() {
const float kPi = 3.1415926535897932384626433832795f;
CheckGLError("GLFromCPPDraw", __LINE__);
// TODO(kbr): base the angle on time rather than on ticks
g_angle = (g_angle + 1) % 360;
// Rotate about the Z axis
GLfloat rot_matrix[16];
GLfloat cos_angle = cosf(static_cast<GLfloat>(g_angle) * kPi / 180.0f);
GLfloat sin_angle = sinf(static_cast<GLfloat>(g_angle) * kPi / 180.0f);
// OpenGL matrices are column-major
rot_matrix[0] = cos_angle;
rot_matrix[1] = sin_angle;
rot_matrix[2] = 0.0f;
rot_matrix[3] = 0.0f;
rot_matrix[4] = -sin_angle;
rot_matrix[5] = cos_angle;
rot_matrix[6] = 0.0f;
rot_matrix[7] = 0.0f;
rot_matrix[8] = 0.0f;
rot_matrix[9] = 0.0f;
rot_matrix[10] = 1.0f;
rot_matrix[11] = 0.0f;
rot_matrix[12] = 0.0f;
rot_matrix[13] = 0.0f;
rot_matrix[14] = 0.0f;
rot_matrix[15] = 1.0f;
// Note: the viewport is automatically set up to cover the entire Canvas.
// Clear the color buffer
glClear(GL_COLOR_BUFFER_BIT);
CheckGLError("GLFromCPPDraw", __LINE__);
// Use the program object
glUseProgram(g_programObject);
CheckGLError("GLFromCPPDraw", __LINE__);
// Set up the model matrix
glUniformMatrix4fv(g_worldMatrixLoc, 1, GL_FALSE, rot_matrix);
// Load the vertex data
glBindBuffer(GL_ARRAY_BUFFER, g_vbo);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0,
reinterpret_cast<const void*>(g_texCoordOffset));
CheckGLError("GLFromCPPDraw", __LINE__);
// Bind the texture to texture unit 0
glBindTexture(GL_TEXTURE_2D, g_texture);
CheckGLError("GLFromCPPDraw", __LINE__);
// Point the uniform sampler to texture unit 0
glUniform1i(g_textureLoc, 0);
CheckGLError("GLFromCPPDraw", __LINE__);
glDrawArrays(GL_TRIANGLES, 0, 6);
CheckGLError("GLFromCPPDraw", __LINE__);
glFlush();
}
|
Fix for GL break on Linux build.
|
Fix for GL break on Linux build.
[email protected]
TEST=none
BUG=none
git-svn-id: http://src.chromium.org/svn/trunk/src@40204 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: b83e056d72623b477e39369293528cb50cdb603a
|
C++
|
bsd-3-clause
|
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
|
c75514b1a987c4ccff36adad7bc466d28a2fb396
|
src/sdpb/write_timing.cxx
|
src/sdpb/write_timing.cxx
|
#include "Timers.hxx"
#include "Block_Info.hxx"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
void write_timing(const boost::filesystem::path &out_file,
const boost::filesystem::path &sdp_directory,
const bool &write_block_timing, const Block_Info &block_info,
const Timers &timers)
{
timers.write_profile(out_file.string() + ".profiling."
+ std::to_string(El::mpi::Rank()));
if(write_block_timing)
{
El::Matrix<int32_t> block_timings(block_info.dimensions.size(), 1);
El::Zero(block_timings);
for(auto &index : block_info.block_indices)
{
block_timings(index, 0)
= timers.elapsed_milliseconds(
"run.step.initializeSchurComplementSolver."
"Qcomputation.syrk_"
+ std::to_string(index))
+ timers.elapsed_milliseconds(
"run.step.initializeSchurComplementSolver."
"Qcomputation.solve_"
+ std::to_string(index))
+ timers.elapsed_milliseconds(
"run.step.initializeSchurComplementSolver."
"Qcomputation.cholesky_"
+ std::to_string(index));
}
El::AllReduce(block_timings, El::mpi::COMM_WORLD);
if(El::mpi::Rank() == 0)
{
boost::filesystem::ofstream block_timings_file(sdp_directory
/ "block_timings");
for(int64_t row = 0; row < block_timings.Height(); ++row)
{
block_timings_file << block_timings(row, 0) << "\n";
}
}
}
}
|
#include "Timers.hxx"
#include "Block_Info.hxx"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
void write_timing(const boost::filesystem::path &out_file,
const boost::filesystem::path &sdp_directory,
const bool &write_block_timing, const Block_Info &block_info,
const Timers &timers)
{
if(El::mpi::Rank() == 0)
{
std::cout << timers.front().first << ": "
<< timers.front().second.elapsed_seconds() << "s\n";
}
timers.write_profile(out_file.string() + ".profiling."
+ std::to_string(El::mpi::Rank()));
if(write_block_timing)
{
El::Matrix<int32_t> block_timings(block_info.dimensions.size(), 1);
El::Zero(block_timings);
for(auto &index : block_info.block_indices)
{
block_timings(index, 0)
= timers.elapsed_milliseconds(
"run.step.initializeSchurComplementSolver."
"Qcomputation.syrk_"
+ std::to_string(index))
+ timers.elapsed_milliseconds(
"run.step.initializeSchurComplementSolver."
"Qcomputation.solve_"
+ std::to_string(index))
+ timers.elapsed_milliseconds(
"run.step.initializeSchurComplementSolver."
"Qcomputation.cholesky_"
+ std::to_string(index));
}
El::AllReduce(block_timings, El::mpi::COMM_WORLD);
if(El::mpi::Rank() == 0)
{
boost::filesystem::ofstream block_timings_file(sdp_directory
/ "block_timings");
for(int64_t row = 0; row < block_timings.Height(); ++row)
{
block_timings_file << block_timings(row, 0) << "\n";
}
}
}
}
|
Add solver time to the output.
|
Add solver time to the output.
|
C++
|
mit
|
davidsd/sdpb,davidsd/sdpb,davidsd/sdpb
|
ebc8d043ff1783839e14815d3be0eb4e4ba0d717
|
src/selections/parser.cpp
|
src/selections/parser.cpp
|
/* Chemfiles, an efficient IO library for chemistry file formats
* Copyright (C) 2015 Guillaume Fraux
*
* 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 <sstream>
#include <stack>
#include <algorithm>
#include "chemfiles/selections/parser.hpp"
#include "chemfiles/selections/expr.hpp"
#include "chemfiles/Error.hpp"
using namespace chemfiles;
using namespace selections;
/* Standard shunting-yard algorithm, as described in Wikipedia
* https://en.wikipedia.org/wiki/Shunting-yard_algorithm
*
* This convert infix expressions into an AST-like expression, while checking parentheses.
* The following input:
* name == bar and x <= 56
* is converted to:
* and <= 56 x == bar name
* which is the AST for
* and
* / \
* == <=
* / \ / \
* name bar x 56
*/
static std::vector<Token> shunting_yard(token_iterator_t token, token_iterator_t end) {
std::stack<Token> operators;
std::vector<Token> output;
while (token != end) {
if (token->is_ident() || token->is_number()) {
output.push_back(*token);
} else if (token->is_operator()) {
while (!operators.empty()) {
// All the operators are left-associative
if (token->precedence() <= operators.top().precedence()) {
output.push_back(operators.top());
operators.pop();
} else {
break;
}
}
operators.push(*token);
} else if (token->type() == Token::LPAREN) {
operators.push(*token);
} else if (token->type() == Token::RPAREN) {
while (!operators.empty() && operators.top().type() != Token::LPAREN) {
output.push_back(operators.top());
operators.pop();
}
if (operators.empty() || operators.top().type() != Token::LPAREN) {
throw ParserError("Parentheses mismatched");
} else {
operators.pop();
}
}
token++;
}
while (!operators.empty()) {
if (operators.top().type() == Token::LPAREN || operators.top().type() == Token::RPAREN) {
throw ParserError("Parentheses mismatched");
} else {
output.push_back(operators.top());
operators.pop();
}
}
// AST come out as reverse polish notation, let's reverse it for easier parsing after
std::reverse(std::begin(output), std::end(output));
return output;
}
static bool have_short_form(const std::string& expr) {
return expr == "name" || expr == "index";
}
/* Rewrite the token stream to convert short form for the expressions to the long one.
*
* Short forms are expressions like `name foo` or `index 3`, which are equivalent
* to `name == foo` and `index == 3`.
*/
static std::vector<Token> clean_token_stream(std::vector<Token> stream) {
auto out = std::vector<Token>();
for (auto it=stream.cbegin(); it != stream.cend(); it++) {
if (it->is_ident() && have_short_form(it->ident())) {
auto next = it + 1;
if (next != stream.cend() && !next->is_operator()) {
out.emplace_back(Token(Token::EQ));
}
}
out.emplace_back(*it);
}
return out;
}
Ast selections::dispatch_parsing(token_iterator_t& begin, const token_iterator_t& end) {
if (begin->is_boolean_op()) {
switch (begin->type()) {
case Token::AND:
return parse<AndExpr>(begin, end);
case Token::OR:
return parse<OrExpr>(begin, end);
case Token::NOT:
return parse<NotExpr>(begin, end);
default:
throw std::runtime_error("Hit the default case in dispatch_parsing");
}
} else if (begin->is_binary_op()) {
if ((end - begin) < 3 || begin[2].type() != Token::IDENT) {
std::stringstream tokens;
for (auto tok = end - 1; tok != begin - 1; tok--) {
tokens << tok->str() << " ";
}
throw ParserError("Bad binary operator: " + tokens.str());
}
auto ident = begin[2].ident();
if (ident == "name") {
return parse<NameExpr>(begin, end);
} else if (ident == "index") {
return parse<IndexExpr>(begin, end);
} else if (ident == "x" || ident == "y" || ident == "z") {
return parse<PositionExpr>(begin, end);
} else if (ident == "vx" || ident == "vy" || ident == "vz") {
return parse<VelocityExpr>(begin, end);
} else {
throw ParserError("Unknown operation: " + ident);
}
} else if (begin->is_ident() && begin->ident() == "all") {
return parse<AllExpr>(begin, end);
} else {
throw ParserError("Could not parse the selection");
}
}
Ast selections::parse(std::vector<Token> token_stream) {
token_stream = clean_token_stream(token_stream);
auto rpn = shunting_yard(std::begin(token_stream), std::end(token_stream));
auto begin = rpn.cbegin();
const auto end = rpn.cend();
auto ast = dispatch_parsing(begin, end);
if (begin != end) throw ParserError("Could not parse the end of the selection.");
return ast;
}
|
/* Chemfiles, an efficient IO library for chemistry file formats
* Copyright (C) 2015 Guillaume Fraux
*
* 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 <sstream>
#include <stack>
#include <algorithm>
#include "chemfiles/selections/parser.hpp"
#include "chemfiles/selections/expr.hpp"
#include "chemfiles/Error.hpp"
using namespace chemfiles;
using namespace selections;
/* Standard shunting-yard algorithm, as described in Wikipedia
* https://en.wikipedia.org/wiki/Shunting-yard_algorithm
*
* This convert infix expressions into an AST-like expression, while checking parentheses.
* The following input:
* name == bar and x <= 56
* is converted to:
* and <= 56 x == bar name
* which is the AST for
* and
* / \
* == <=
* / \ / \
* name bar x 56
*/
static std::vector<Token> shunting_yard(token_iterator_t token, token_iterator_t end) {
std::stack<Token> operators;
std::vector<Token> output;
while (token != end) {
if (token->is_ident() || token->is_number()) {
output.push_back(*token);
} else if (token->is_operator()) {
while (!operators.empty()) {
// All the operators are left-associative
if (token->precedence() <= operators.top().precedence()) {
output.push_back(operators.top());
operators.pop();
} else {
break;
}
}
operators.push(*token);
} else if (token->type() == Token::LPAREN) {
operators.push(*token);
} else if (token->type() == Token::RPAREN) {
while (!operators.empty() && operators.top().type() != Token::LPAREN) {
output.push_back(operators.top());
operators.pop();
}
if (operators.empty() || operators.top().type() != Token::LPAREN) {
throw ParserError("Parentheses mismatched");
} else {
operators.pop();
}
}
token++;
}
while (!operators.empty()) {
if (operators.top().type() == Token::LPAREN || operators.top().type() == Token::RPAREN) {
throw ParserError("Parentheses mismatched");
} else {
output.push_back(operators.top());
operators.pop();
}
}
// AST come out as reverse polish notation, let's reverse it for easier parsing after
std::reverse(std::begin(output), std::end(output));
return output;
}
static bool have_short_form(const std::string& expr) {
return expr == "name" || expr == "index";
}
/* Rewrite the token stream to convert short form for the expressions to the long one.
*
* Short forms are expressions like `name foo` or `index 3`, which are equivalent
* to `name == foo` and `index == 3`.
*/
static std::vector<Token> clean_token_stream(std::vector<Token> stream) {
auto out = std::vector<Token>();
for (auto it=stream.cbegin(); it != stream.cend(); it++) {
if (it->is_ident() && have_short_form(it->ident())) {
auto next = it + 1;
if (next != stream.cend() && !next->is_operator()) {
out.emplace_back(Token(Token::EQ));
}
}
out.emplace_back(*it);
}
return out;
}
Ast selections::dispatch_parsing(token_iterator_t& begin, const token_iterator_t& end) {
if (begin->is_boolean_op()) {
switch (begin->type()) {
case Token::AND:
return parse<AndExpr>(begin, end);
case Token::OR:
return parse<OrExpr>(begin, end);
case Token::NOT:
return parse<NotExpr>(begin, end);
default:
throw std::runtime_error("Hit the default case in dispatch_parsing");
}
} else if (begin->is_binary_op()) {
if ((end - begin) < 3 || begin[2].type() != Token::IDENT) {
throw ParserError("Bad binary operation around " + begin->str());
}
auto ident = begin[2].ident();
if (ident == "name") {
return parse<NameExpr>(begin, end);
} else if (ident == "index") {
return parse<IndexExpr>(begin, end);
} else if (ident == "x" || ident == "y" || ident == "z") {
return parse<PositionExpr>(begin, end);
} else if (ident == "vx" || ident == "vy" || ident == "vz") {
return parse<VelocityExpr>(begin, end);
} else {
throw ParserError("Unknown operation: " + ident);
}
} else if (begin->is_ident() && begin->ident() == "all") {
return parse<AllExpr>(begin, end);
} else {
throw ParserError("Could not parse the selection");
}
}
Ast selections::parse(std::vector<Token> token_stream) {
token_stream = clean_token_stream(token_stream);
auto rpn = shunting_yard(std::begin(token_stream), std::end(token_stream));
auto begin = rpn.cbegin();
const auto end = rpn.cend();
auto ast = dispatch_parsing(begin, end);
if (begin != end) throw ParserError("Could not parse the end of the selection.");
return ast;
}
|
Fix out of bound access
|
Fix out of bound access
Thanks MSVC for this one!
|
C++
|
bsd-3-clause
|
lscalfi/chemfiles,chemfiles/chemfiles,chemfiles/chemfiles,lscalfi/chemfiles,lscalfi/chemfiles,lscalfi/chemfiles,chemfiles/chemfiles,chemfiles/chemfiles,Luthaf/Chemharp,Luthaf/Chemharp,Luthaf/Chemharp
|
bf87d7667527c4674f30d8701bf30aa9bbded6f2
|
libcontextsubscriber/update-contextkit-providers/update-contextkit-providers.cpp
|
libcontextsubscriber/update-contextkit-providers/update-contextkit-providers.cpp
|
/*
* Copyright (C) 2008, 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <[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
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QCoreApplication>
#include <QDir>
#include <stdlib.h>
#include "contextregistryinfo.h"
#include "contextpropertyinfo.h"
#include "contextproviderinfo.h"
#include "cdbwriter.h"
#include "fcntl.h"
/*!
\page UpdatingContextProviders
\brief The update tool (\c update-contextkit-providers) is used to regenerate the registry cache database.
\section Overview
Information about keys and providers is normally stored in a system directory in
\b xml format. The xml (being xml) is slow to parse and not efficient as a storage format for
data that is mostly static.
It makes sense to store a cached version of the xml registry in a constant-database
fast-access format and regenerate it when the xml data changes.
Update tool does exactly that - it reads the xml registry and (re)generates a
constant \b tiny-cdb database containing the cached version of the data in the registry.
\section Usage
The \c update-contextkit-providers binary, when launched without parameters, will by default regenerate
the database in the default installation prefix. Most likely: \c "/usr/share/contextkit/providers" .
Obviously, for this to be successful, it needs to be launched with proper privileges.
It's possible to override the registry directory with first parameter:
\code
$> update-contextkit-providers /some/path/to/registry
\endcode
In this case the xml will be read from \c "/some/path/to/registry" and the resulting
database will be written to \c "/some/path/to/registry/cache.cdb" .
Lastly, the \c "CONTEXT_PROVIDERS" environment variable can be used to specify
a directory containing the registry.
\section Implementation
To ensure the registry consistency the regeneration is done atomically: the
new database is first written to a temp-named file and then moved over the old one.
*/
/* Make sure the given directory exists, is readable etc.
If not, bail out with proper error. */
void checkDirectory(const QDir &dir)
{
QByteArray utf8Data = dir.absolutePath().toUtf8();
const char *path = utf8Data.constData();
if (! dir.exists()) {
printf ("ERROR: Directory '%s' does not exist!\n", path);
exit (128);
}
if (! dir.isReadable()) {
printf ("ERROR: Directory '%s' is not readable!\n", path);
exit (128);
}
}
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
QStringList args = app.arguments();
// Check args etc
QString path;
// We first try to use first argument if present, then CONTEXT_PROVIDERS env,
// lastly -- the compiled-in default path.
if (args.size() > 1) {
path = args.at(1);
setenv("CONTEXT_PROVIDERS", path.toUtf8().constData(), 1);
} else if (getenv("CONTEXT_PROVIDERS"))
path = QString(getenv("CONTEXT_PROVIDERS"));
else
path = QString(DEFAULT_CONTEXT_PROVIDERS);
printf("Updating from: '%s'\n", path.toUtf8().constData());
// Force the xml backend
ContextRegistryInfo *context = ContextRegistryInfo::instance("xml");
QDir dir(path);
checkDirectory(dir);
QString tmpDbPath = dir.absoluteFilePath("cache-XXXXXX");
QString finalDbPath = dir.absoluteFilePath("cache.cdb");
QByteArray templ = tmpDbPath.toUtf8();
char *tempPath = templ.data();
CDBWriter writer(mkstemp(tempPath));
chmod(tempPath, 0644);
if (writer.isWritable() == false) {
printf("ERROR: %s is not writable. No permissions?\n", templ.constData());
exit(128);
}
foreach(const QString& key, context->listKeys()) {
ContextPropertyInfo keyInfo(key);
// Write value to list key
writer.add("KEYS", key);
// Write type
writer.replace(key + ":KEYTYPE", keyInfo.type());
// Write doc
writer.replace(key + ":KEYDOC", keyInfo.doc());
// Write the providers
QVariantList providers;
foreach(const ContextProviderInfo info, keyInfo.providers()) {
QHash <QString, QVariant> provider;
provider.insert("plugin", info.plugin);
provider.insert("constructionString", info.constructionString);
providers << QVariant(provider);
}
writer.add(key + ":PROVIDERS", QVariant(providers));
}
if (fsync(writer.fileDescriptor()) != 0) {
printf("ERROR: failed to fsync data on writer to %s.\n", templ.constData());
exit(64);
}
writer.close();
// Atomically rename
if (rename(templ.constData(), finalDbPath.toUtf8().constData()) != 0) {
printf("ERROR: failed to rename %s to %s.\n", templ.constData(), finalDbPath.toUtf8().constData());
exit(64);
}
// All ok
printf("Generated: '%s'\n", finalDbPath.toUtf8().constData());
return 0;
}
|
/*
* Copyright (C) 2008, 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <[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
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QCoreApplication>
#include <QDir>
#include <stdlib.h>
#include "contextregistryinfo.h"
#include "contextpropertyinfo.h"
#include "contextproviderinfo.h"
#include "cdbwriter.h"
#include "fcntl.h"
/*!
\page UpdatingContextProviders
\brief The update tool (\c update-contextkit-providers) is used to regenerate the registry cache database.
\section Overview
Information about keys and providers is normally stored in a system directory in
\b xml format. The xml (being xml) is slow to parse and not efficient as a storage format for
data that is mostly static.
It makes sense to store a cached version of the xml registry in a constant-database
fast-access format and regenerate it when the xml data changes.
Update tool does exactly that - it reads the xml registry and (re)generates a
constant \b tiny-cdb database containing the cached version of the data in the registry.
\section Usage
The \c update-contextkit-providers binary, when launched without parameters, will by default regenerate
the database in the default installation prefix. Most likely: \c "/usr/share/contextkit/providers" .
Obviously, for this to be successful, it needs to be launched with proper privileges.
It's possible to override the registry directory with first parameter:
\code
$> update-contextkit-providers /some/path/to/registry
\endcode
In this case the xml will be read from \c "/some/path/to/registry" and the resulting
database will be written to \c "/some/path/to/registry/cache.cdb" .
Lastly, the \c "CONTEXT_PROVIDERS" environment variable can be used to specify
a directory containing the registry.
\section Implementation
To ensure the registry consistency the regeneration is done atomically: the
new database is first written to a temp-named file and then moved over the old one.
*/
/* Make sure the given directory exists, is readable etc.
If not, bail out with proper error. */
void checkDirectory(const QDir &dir)
{
QByteArray utf8Data = dir.absolutePath().toUtf8();
const char *path = utf8Data.constData();
if (! dir.exists()) {
printf ("ERROR: Directory '%s' does not exist!\n", path);
exit (128);
}
if (! dir.isReadable()) {
printf ("ERROR: Directory '%s' is not readable!\n", path);
exit (128);
}
}
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
QStringList args = app.arguments();
// Check args etc
QString path;
// We first try to use first argument if present, then CONTEXT_PROVIDERS env,
// lastly -- the compiled-in default path.
if (args.size() > 1) {
path = args.at(1);
setenv("CONTEXT_PROVIDERS", path.toUtf8().constData(), 1);
} else if (getenv("CONTEXT_PROVIDERS"))
path = QString(getenv("CONTEXT_PROVIDERS"));
else
path = QString(DEFAULT_CONTEXT_PROVIDERS);
printf("Updating from: '%s'\n", path.toUtf8().constData());
// Force the xml backend
ContextRegistryInfo *context = ContextRegistryInfo::instance("xml");
QDir dir(path);
checkDirectory(dir);
QString tmpDbPath = dir.absoluteFilePath("cache-XXXXXX");
QString finalDbPath = dir.absoluteFilePath("cache.cdb");
QByteArray templ = tmpDbPath.toUtf8();
char *tempPath = templ.data();
CDBWriter writer(mkstemp(tempPath));
chmod(tempPath, 0644);
if (writer.isWritable() == false) {
printf("ERROR: %s is not writable. No permissions?\n", templ.constData());
exit(128);
}
// Write the compatibility string
writer.add("VERSION", BACKEND_COMPATIBILITY_NAMESPACE);
foreach(const QString& key, context->listKeys()) {
ContextPropertyInfo keyInfo(key);
// Write value to list key
writer.add("KEYS", key);
// Write type
writer.replace(key + ":KEYTYPE", keyInfo.type());
// Write doc
writer.replace(key + ":KEYDOC", keyInfo.doc());
// Write the providers
QVariantList providers;
foreach(const ContextProviderInfo info, keyInfo.providers()) {
QHash <QString, QVariant> provider;
provider.insert("plugin", info.plugin);
provider.insert("constructionString", info.constructionString);
providers << QVariant(provider);
}
writer.add(key + ":PROVIDERS", QVariant(providers));
}
if (fsync(writer.fileDescriptor()) != 0) {
printf("ERROR: failed to fsync data on writer to %s.\n", templ.constData());
exit(64);
}
writer.close();
// Atomically rename
if (rename(templ.constData(), finalDbPath.toUtf8().constData()) != 0) {
printf("ERROR: failed to rename %s to %s.\n", templ.constData(), finalDbPath.toUtf8().constData());
exit(64);
}
// All ok
printf("Generated: '%s'\n", finalDbPath.toUtf8().constData());
return 0;
}
|
Write the compatibility string to generated CDB.
|
Write the compatibility string to generated CDB.
|
C++
|
lgpl-2.1
|
rburchell/ck,rburchell/ck,rburchell/ck,rburchell/ck,rburchell/ck
|
054782ecb295db29127777fc6485ed415aee69f5
|
src/src/cache.cpp
|
src/src/cache.cpp
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 Nathan Osman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <qmdnsengine/cache.h>
#include "cache_p.h"
using namespace QMdnsEngine;
CachePrivate::CachePrivate(Cache *cache)
: QObject(cache),
q(cache)
{
connect(&timer, &QTimer::timeout, this, &CachePrivate::onTimeout);
timer.setSingleShot(true);
}
void CachePrivate::onTimeout()
{
QDateTime now = QDateTime::currentDateTime();
// Loop through each of the entries, processing the triggers and searching
// for the next earliest trigger
QDateTime newNextTrigger;
for (auto i = entries.begin(); i != entries.end();) {
auto &triggers = (*i).triggers;
// Loop through the triggers remaining in the entry, removing ones
// that have already passed
bool shouldQuery = false;
for (auto j = triggers.begin(); j != triggers.end();) {
if ((*j) <= now) {
shouldQuery = true;
j = triggers.erase(j);
} else {
++j;
}
}
// If any triggers remain, determine if they are the next earliest; if
// not, remove the entry and indicate the record expired
if (triggers.length()) {
if (newNextTrigger.isNull() || triggers.at(0) < newNextTrigger) {
newNextTrigger = triggers.at(0);
}
if (shouldQuery) {
emit q->shouldQuery((*i).record);
}
++i;
} else {
emit q->recordExpired((*i).record);
i = entries.erase(i);
}
}
// If newNextTrigger contains a value, it will be the time for the next
// trigger and the timer should be started again
nextTrigger = newNextTrigger;
if (!nextTrigger.isNull()) {
timer.start(now.msecsTo(nextTrigger));
}
}
Cache::Cache(QObject *parent)
: QObject(parent),
d(new CachePrivate(this))
{
}
void Cache::addRecord(const Record &record)
{
bool flushCache = record.flushCache();
bool ttlZero = record.ttl() == 0;
for (auto i = d->entries.begin(); i != d->entries.end();) {
if (flushCache && (*i).record.name() == record.name() && (*i).record.type() == record.type() ||
(*i).record == record) {
// If the TTL is set to 0, indicate that the record was removed
if (ttlZero) {
emit recordExpired((*i).record);
}
i = d->entries.erase(i);
// No need to continue further if the TTL was set to 0
if (ttlZero) {
return;
}
} else {
++i;
}
}
// Use the current time to calculate the triggers and add a random offset
QDateTime now = QDateTime::currentDateTime();
qint64 random = qrand() % 20;
QList<QDateTime> triggers{
now.addMSecs(record.ttl() * 500 + random), // 50%
now.addMSecs(record.ttl() * 850 + random), // 85%
now.addMSecs(record.ttl() * 900 + random), // 90%
now.addMSecs(record.ttl() * 950 + random), // 95%
now.addSecs(record.ttl())
};
// Append the record and its triggers
d->entries.append({record, triggers});
// Check if half of this record's lifetime is earlier than the next
// scheduled trigger; if so, restart the timer
if (d->nextTrigger.isNull() || triggers.at(0) < d->nextTrigger) {
d->timer.stop();
d->timer.start(now.msecsTo(triggers.at(0)));
}
}
bool Cache::lookupRecord(const QByteArray &name, quint16 type, Record &record) const
{
QList<Record> records;
if (lookupRecords(name, type, records)) {
record = records.at(0);
return true;
}
return false;
}
bool Cache::lookupRecords(const QByteArray &name, quint16 type, QList<Record> &records) const
{
foreach (CachePrivate::Entry entry, d->entries) {
if ((name.isNull() || entry.record.name() == name) && entry.record.type() == type) {
records.append(entry.record);
}
}
return records.length();
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 Nathan Osman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <qmdnsengine/cache.h>
#include "cache_p.h"
using namespace QMdnsEngine;
CachePrivate::CachePrivate(Cache *cache)
: QObject(cache),
q(cache)
{
connect(&timer, &QTimer::timeout, this, &CachePrivate::onTimeout);
timer.setSingleShot(true);
}
void CachePrivate::onTimeout()
{
QDateTime now = QDateTime::currentDateTime();
// Loop through each of the entries, processing the triggers and searching
// for the next earliest trigger
QDateTime newNextTrigger;
for (auto i = entries.begin(); i != entries.end();) {
auto &triggers = (*i).triggers;
// Loop through the triggers remaining in the entry, removing ones
// that have already passed
bool shouldQuery = false;
for (auto j = triggers.begin(); j != triggers.end();) {
if ((*j) <= now) {
shouldQuery = true;
j = triggers.erase(j);
} else {
++j;
}
}
// If any triggers remain, determine if they are the next earliest; if
// not, remove the entry and indicate the record expired
if (triggers.length()) {
if (newNextTrigger.isNull() || triggers.at(0) < newNextTrigger) {
newNextTrigger = triggers.at(0);
}
if (shouldQuery) {
emit q->shouldQuery((*i).record);
}
++i;
} else {
emit q->recordExpired((*i).record);
i = entries.erase(i);
}
}
// If newNextTrigger contains a value, it will be the time for the next
// trigger and the timer should be started again
nextTrigger = newNextTrigger;
if (!nextTrigger.isNull()) {
timer.start(now.msecsTo(nextTrigger));
}
}
Cache::Cache(QObject *parent)
: QObject(parent),
d(new CachePrivate(this))
{
}
void Cache::addRecord(const Record &record)
{
bool flushCache = record.flushCache();
bool ttlZero = record.ttl() == 0;
for (auto i = d->entries.begin(); i != d->entries.end();) {
if (flushCache && (*i).record.name() == record.name() && (*i).record.type() == record.type() ||
(*i).record == record) {
// If the TTL is set to 0, indicate that the record was removed
if (ttlZero) {
emit recordExpired((*i).record);
}
i = d->entries.erase(i);
// No need to continue further if the TTL was set to 0
if (ttlZero) {
return;
}
} else {
++i;
}
}
// Use the current time to calculate the triggers and add a random offset
QDateTime now = QDateTime::currentDateTime();
qint64 random = qrand() % 20;
QList<QDateTime> triggers{
now.addMSecs(record.ttl() * 500 + random), // 50%
now.addMSecs(record.ttl() * 850 + random), // 85%
now.addMSecs(record.ttl() * 900 + random), // 90%
now.addMSecs(record.ttl() * 950 + random), // 95%
now.addSecs(record.ttl())
};
// Append the record and its triggers
d->entries.append({record, triggers});
// Check if half of this record's lifetime is earlier than the next
// scheduled trigger; if so, restart the timer
if (d->nextTrigger.isNull() || triggers.at(0) < d->nextTrigger) {
d->nextTrigger = triggers.at(0);
d->timer.stop();
d->timer.start(now.msecsTo(d->nextTrigger));
}
}
bool Cache::lookupRecord(const QByteArray &name, quint16 type, Record &record) const
{
QList<Record> records;
if (lookupRecords(name, type, records)) {
record = records.at(0);
return true;
}
return false;
}
bool Cache::lookupRecords(const QByteArray &name, quint16 type, QList<Record> &records) const
{
foreach (CachePrivate::Entry entry, d->entries) {
if ((name.isNull() || entry.record.name() == name) && entry.record.type() == type) {
records.append(entry.record);
}
}
return records.length();
}
|
Fix trigger for next record failing to be set correctly.
|
Fix trigger for next record failing to be set correctly.
|
C++
|
mit
|
nitroshare/qmdnsengine,nitroshare/qmdnsengine
|
cdfb53b517ee8c74e5ac1f843d22e68a7a2d7c7f
|
RX64M/power_cfg.hpp
|
RX64M/power_cfg.hpp
|
#pragma once
//=====================================================================//
/*! @file
@brief RX64M グループ・省電力制御
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2016, 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "RX64M/system.hpp"
#include "RX64M/peripheral.hpp"
#include "common/static_holder.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 省電力制御クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class power_cfg {
struct pad_t {
uint8_t cmt_;
uint8_t tpu_;
pad_t() : cmt_(0), tpu_(0) { }
};
typedef utils::static_holder<pad_t> STH;
static void set_(bool f, uint8_t& pad, peripheral org, peripheral tgt)
{
if(f) {
pad |= 1 << (static_cast<uint16_t>(tgt) - static_cast<uint16_t>(org));
} else {
pad &= ~(1 << (static_cast<uint16_t>(tgt) - static_cast<uint16_t>(org)));
}
}
public:
//-----------------------------------------------------------------//
/*!
@brief 周辺機器に切り替える
@param[in] t 周辺機器タイプ
@param[in] ena オフにする場合「false」
*/
//-----------------------------------------------------------------//
static void turn(peripheral t, bool ena = true)
{
bool f = !ena;
switch(t) {
case peripheral::CMT0:
case peripheral::CMT1:
// CMT0, CMT1 のストップ状態設定
set_(ena, STH::st.cmt_, peripheral::CMT0, t);
SYSTEM::MSTPCRA.MSTPA15 = ((STH::st.cmt_ & 0b0011) == 0);
break;
case peripheral::CMT2:
case peripheral::CMT3:
// CMT2, CMT3 のストップ状態設定
set_(ena, STH::st.cmt_, peripheral::CMT0, t);
SYSTEM::MSTPCRA.MSTPA14 = ((STH::st.cmt_ & 0b1100) == 0);
break;
case peripheral::TPU0:
case peripheral::TPU1:
case peripheral::TPU2:
case peripheral::TPU3:
case peripheral::TPU4:
case peripheral::TPU5:
// TPU0 to TPU5 のストップ状態設定
set_(ena, STH::st.tpu_, peripheral::TPU0, t);
SYSTEM::MSTPCRA.MSTPA13 = (STH::st.tpu_ == 0);
break;
case peripheral::S12AD:
SYSTEM::MSTPCRA.MSTPA17 = f; // S12AD のストップ状態解除
break;
case peripheral::S12AD1:
SYSTEM::MSTPCRA.MSTPA16 = f; // S12AD1 のストップ状態解除
break;
case peripheral::R12DA:
SYSTEM::MSTPCRA.MSTPA19 = f; // R12DA のストップ状態解除
break;
case peripheral::SCI0:
SYSTEM::MSTPCRB.MSTPB31 = f; // B31 (SCI0)のストップ状態解除
break;
case peripheral::SCI1:
SYSTEM::MSTPCRB.MSTPB30 = f; // B30 (SCI1)のストップ状態解除
break;
case peripheral::SCI2:
SYSTEM::MSTPCRB.MSTPB29 = f; // B29 (SCI2)のストップ状態解除
break;
case peripheral::SCI3:
SYSTEM::MSTPCRB.MSTPB28 = f; // B28 (SCI3)のストップ状態解除
break;
case peripheral::SCI4:
SYSTEM::MSTPCRB.MSTPB27 = f; // B27 (SCI4)のストップ状態解除
break;
case peripheral::SCI5:
SYSTEM::MSTPCRB.MSTPB26 = f; // B26 (SCI5)のストップ状態解除
break;
case peripheral::SCI6:
SYSTEM::MSTPCRB.MSTPB25 = f; // B25 (SCI6)のストップ状態解除
break;
case peripheral::SCI7:
SYSTEM::MSTPCRB.MSTPB24 = f; // B24 (SCI7)のストップ状態解除
break;
case peripheral::SCI12:
SYSTEM::MSTPCRB.MSTPB4 = f; // B4 (SCI12)のストップ状態解除
break;
case peripheral::RSPI:
SYSTEM::MSTPCRB.MSTPB17 = f; // RSPI のストップ状態解除
break;
case peripheral::SDHI:
SYSTEM::MSTPCRD.MSTPD19 = f; // SDHI のストップ状態解除
break;
case peripheral::ETHERC0:
case peripheral::ETHERCA:
case peripheral::EDMAC0:
SYSTEM::MSTPCRB.MSTPB15 = f; // ETHER0, EDMAC0 のストップ状態解除
BUS::BEREN.TOEN = 1;
break;
case peripheral::ETHERC1:
case peripheral::EDMAC1:
SYSTEM::MSTPCRB.MSTPB14 = f; // ETHER1, EDMAC1 のストップ状態解除
BUS::BEREN.TOEN = 1;
break;
case peripheral::ECCRAM:
SYSTEM::MSTPCRC.MSTPC6 = f; // ECC RAM のストップ状態解除
break;
case peripheral::STBRAM:
SYSTEM::MSTPCRC.MSTPC7 = f; // STANDBY RAM のストップ状態解除
break;
default:
break;
}
}
};
}
|
#pragma once
//=====================================================================//
/*! @file
@brief RX64M グループ・省電力制御
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2016, 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "RX64M/system.hpp"
#include "RX64M/peripheral.hpp"
#include "common/static_holder.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 省電力制御クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class power_cfg {
struct pad_t {
uint8_t cmt_;
uint8_t tpu_;
pad_t() : cmt_(0), tpu_(0) { }
};
typedef utils::static_holder<pad_t> STH;
static void set_(bool f, uint8_t& pad, peripheral org, peripheral tgt)
{
if(f) {
pad |= 1 << (static_cast<uint16_t>(tgt) - static_cast<uint16_t>(org));
} else {
pad &= ~(1 << (static_cast<uint16_t>(tgt) - static_cast<uint16_t>(org)));
}
}
public:
//-----------------------------------------------------------------//
/*!
@brief 周辺機器に切り替える
@param[in] t 周辺機器タイプ
@param[in] ena オフにする場合「false」
*/
//-----------------------------------------------------------------//
static void turn(peripheral t, bool ena = true)
{
bool f = !ena;
switch(t) {
case peripheral::CMT0:
case peripheral::CMT1:
// CMT0, CMT1 のストップ状態設定
set_(ena, STH::st.cmt_, peripheral::CMT0, t);
SYSTEM::MSTPCRA.MSTPA15 = ((STH::st.cmt_ & 0b0011) == 0);
break;
case peripheral::CMT2:
case peripheral::CMT3:
// CMT2, CMT3 のストップ状態設定
set_(ena, STH::st.cmt_, peripheral::CMT0, t);
SYSTEM::MSTPCRA.MSTPA14 = ((STH::st.cmt_ & 0b1100) == 0);
break;
case peripheral::TPU0:
case peripheral::TPU1:
case peripheral::TPU2:
case peripheral::TPU3:
case peripheral::TPU4:
case peripheral::TPU5:
// TPU0 to TPU5 のストップ状態設定
set_(ena, STH::st.tpu_, peripheral::TPU0, t);
SYSTEM::MSTPCRA.MSTPA13 = (STH::st.tpu_ == 0);
break;
case peripheral::S12AD:
SYSTEM::MSTPCRA.MSTPA17 = f; // S12AD のストップ状態解除
break;
case peripheral::S12AD1:
SYSTEM::MSTPCRA.MSTPA16 = f; // S12AD1 のストップ状態解除
break;
case peripheral::R12DA:
SYSTEM::MSTPCRA.MSTPA19 = f; // R12DA のストップ状態解除
break;
case peripheral::DTC:
SYSTEM::MSTPCRA.MSTPA28 = f; // DMAC/DTC のストップ状態解除
break;
case peripheral::SCI0:
SYSTEM::MSTPCRB.MSTPB31 = f; // B31 (SCI0)のストップ状態解除
break;
case peripheral::SCI1:
SYSTEM::MSTPCRB.MSTPB30 = f; // B30 (SCI1)のストップ状態解除
break;
case peripheral::SCI2:
SYSTEM::MSTPCRB.MSTPB29 = f; // B29 (SCI2)のストップ状態解除
break;
case peripheral::SCI3:
SYSTEM::MSTPCRB.MSTPB28 = f; // B28 (SCI3)のストップ状態解除
break;
case peripheral::SCI4:
SYSTEM::MSTPCRB.MSTPB27 = f; // B27 (SCI4)のストップ状態解除
break;
case peripheral::SCI5:
SYSTEM::MSTPCRB.MSTPB26 = f; // B26 (SCI5)のストップ状態解除
break;
case peripheral::SCI6:
SYSTEM::MSTPCRB.MSTPB25 = f; // B25 (SCI6)のストップ状態解除
break;
case peripheral::SCI7:
SYSTEM::MSTPCRB.MSTPB24 = f; // B24 (SCI7)のストップ状態解除
break;
case peripheral::SCI12:
SYSTEM::MSTPCRB.MSTPB4 = f; // B4 (SCI12)のストップ状態解除
break;
case peripheral::RSPI:
SYSTEM::MSTPCRB.MSTPB17 = f; // RSPI のストップ状態解除
break;
case peripheral::SDHI:
SYSTEM::MSTPCRD.MSTPD19 = f; // SDHI のストップ状態解除
break;
case peripheral::ETHERC0:
case peripheral::ETHERCA:
case peripheral::EDMAC0:
SYSTEM::MSTPCRB.MSTPB15 = f; // ETHER0, EDMAC0 のストップ状態解除
BUS::BEREN.TOEN = 1;
break;
case peripheral::ETHERC1:
case peripheral::EDMAC1:
SYSTEM::MSTPCRB.MSTPB14 = f; // ETHER1, EDMAC1 のストップ状態解除
BUS::BEREN.TOEN = 1;
break;
case peripheral::ECCRAM:
SYSTEM::MSTPCRC.MSTPC6 = f; // ECC RAM のストップ状態解除
break;
case peripheral::STBRAM:
SYSTEM::MSTPCRC.MSTPC7 = f; // STANDBY RAM のストップ状態解除
break;
default:
break;
}
}
};
}
|
update DTC
|
update DTC
|
C++
|
bsd-3-clause
|
hirakuni45/RX,hirakuni45/RX,hirakuni45/RX,hirakuni45/RX
|
822c9eb2f1a652a41b5af0966efaae171b01dd1e
|
include/memory/hadesmem/thread_helpers.hpp
|
include/memory/hadesmem/thread_helpers.hpp
|
// Copyright (C) 2010-2014 Joshua Boyce.
// See the file COPYING for copying permission.
#pragma once
#include <algorithm>
#include <vector>
#include <set>
#include <sstream>
#include <windows.h>
#include <winnt.h>
#include <hadesmem/error.hpp>
#include <hadesmem/config.hpp>
#include <hadesmem/thread.hpp>
#include <hadesmem/thread_list.hpp>
#include <hadesmem/detail/trace.hpp>
#include <hadesmem/thread_entry.hpp>
#include <hadesmem/detail/assert.hpp>
#include <hadesmem/detail/winapi.hpp>
#include <hadesmem/detail/smart_handle.hpp>
namespace hadesmem
{
inline DWORD SuspendThread(Thread const& thread)
{
HADESMEM_DETAIL_TRACE_FORMAT_A("Suspending thread with ID 0n%lu.",
thread.GetId());
DWORD const suspend_count = ::SuspendThread(thread.GetHandle());
if (suspend_count == static_cast<DWORD>(-1))
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(Error()
<< ErrorString("SuspendThread failed.")
<< ErrorCodeWinLast(last_error));
}
return suspend_count;
}
inline DWORD ResumeThread(Thread const& thread)
{
HADESMEM_DETAIL_TRACE_FORMAT_A("Resuming thread with ID 0n%lu.",
thread.GetId());
DWORD const suspend_count = ::ResumeThread(thread.GetHandle());
if (suspend_count == static_cast<DWORD>(-1))
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(Error()
<< ErrorString("ResumeThread failed.")
<< ErrorCodeWinLast(last_error));
}
return suspend_count;
}
inline CONTEXT GetThreadContext(Thread const& thread, DWORD context_flags)
{
if (::GetCurrentThreadId() == thread.GetId() &&
context_flags != CONTEXT_DEBUG_REGISTERS)
{
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("GetThreadContext called for current thread."));
}
CONTEXT context{};
context.ContextFlags = context_flags;
if (!::GetThreadContext(thread.GetHandle(), &context))
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(Error()
<< ErrorString("GetThreadContext failed.")
<< ErrorCodeWinLast(last_error));
}
return context;
}
inline void SetThreadContext(Thread const& thread, CONTEXT const& context)
{
if (!::SetThreadContext(thread.GetHandle(), &context))
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(Error()
<< ErrorString("SetThreadContext failed.")
<< ErrorCodeWinLast(last_error));
}
}
class SuspendedThread
{
public:
explicit SuspendedThread(DWORD thread_id) : thread_(thread_id)
{
SuspendThread(thread_);
}
SuspendedThread(SuspendedThread const& other) = delete;
SuspendedThread& operator=(SuspendedThread const& other) = delete;
SuspendedThread(SuspendedThread&& other) HADESMEM_DETAIL_NOEXCEPT
: thread_(std::move(other.thread_))
{
}
SuspendedThread& operator=(SuspendedThread&& other) HADESMEM_DETAIL_NOEXCEPT
{
ResumeUnchecked();
thread_ = std::move(other.thread_);
return *this;
}
~SuspendedThread() HADESMEM_DETAIL_NOEXCEPT
{
ResumeUnchecked();
}
void Resume()
{
if (thread_.GetHandle())
{
ResumeThread(thread_);
}
}
DWORD GetId() const HADESMEM_DETAIL_NOEXCEPT
{
return thread_.GetId();
}
HANDLE GetHandle() const HADESMEM_DETAIL_NOEXCEPT
{
return thread_.GetHandle();
}
private:
void ResumeUnchecked()
{
try
{
Resume();
}
catch (...)
{
// WARNING: Thread is never resumed if ResumeThread fails...
HADESMEM_DETAIL_TRACE_A(
boost::current_exception_diagnostic_information().c_str());
HADESMEM_DETAIL_ASSERT(false);
}
}
Thread thread_;
};
class SuspendedProcess
{
public:
explicit SuspendedProcess(DWORD pid, DWORD retries = 5)
{
// Multiple retries may be needed to plug a race condition
// whereby after a thread snapshot is taken but before suspension
// takes place, an existing thread launches a new thread which
// would then be missed.
std::set<DWORD> tids;
bool need_retry = false;
do
{
need_retry = false;
ThreadList const threads(pid);
for (auto const& thread_entry : threads)
{
DWORD const current_thread_id = ::GetCurrentThreadId();
if (thread_entry.GetId() != current_thread_id)
{
auto const inserted = tids.insert(thread_entry.GetId());
if (inserted.second)
{
need_retry = true;
try
{
// Close potential race condition whereby after the snapshot is
// taken the thread could terminate and have its TID reused in
// a different process.
Thread const thread(thread_entry.GetId());
VerifyPid(thread, pid);
// Should be safe (with the exception outlined above) to suspend
// the thread now, because we have a handle to the thread open,
// and we've verified it exists in the correct process.
threads_.emplace_back(thread_entry.GetId());
}
catch (std::exception const& /*e*/)
{
tids.erase(inserted.first);
continue;
}
}
}
}
} while (need_retry && retries--);
if (need_retry)
{
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("Failed to suspend all threads in process "
"(too many retries)."));
}
}
SuspendedProcess(SuspendedProcess const& other) = delete;
SuspendedProcess& operator=(SuspendedProcess const& other) = delete;
SuspendedProcess(SuspendedProcess&& other) HADESMEM_DETAIL_NOEXCEPT
: threads_(std::move(other.threads_))
{
}
SuspendedProcess& operator=(SuspendedProcess&& other) HADESMEM_DETAIL_NOEXCEPT
{
threads_ = std::move(other.threads_);
return *this;
}
private:
void VerifyPid(Thread const& thread, DWORD pid) const
{
DWORD const tid_pid = ::GetProcessIdOfThread(thread.GetHandle());
if (!tid_pid)
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("GetProcessIdOfThread failed.")
<< ErrorCodeWinLast(last_error));
}
if (tid_pid != pid)
{
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("PID verification failed."));
}
}
std::vector<SuspendedThread> threads_;
};
}
|
// Copyright (C) 2010-2015 Joshua Boyce.
// See the file COPYING for copying permission.
#pragma once
#include <algorithm>
#include <set>
#include <sstream>
#include <vector>
#include <windows.h>
#include <winnt.h>
#include <hadesmem/config.hpp>
#include <hadesmem/detail/assert.hpp>
#include <hadesmem/detail/smart_handle.hpp>
#include <hadesmem/detail/trace.hpp>
#include <hadesmem/detail/winapi.hpp>
#include <hadesmem/detail/winternl.hpp>
#include <hadesmem/error.hpp>
#include <hadesmem/thread.hpp>
#include <hadesmem/thread_entry.hpp>
#include <hadesmem/thread_list.hpp>
namespace hadesmem
{
inline DWORD SuspendThread(Thread const& thread)
{
HADESMEM_DETAIL_TRACE_FORMAT_A("Suspending thread with ID 0n%lu.",
thread.GetId());
DWORD const suspend_count = ::SuspendThread(thread.GetHandle());
if (suspend_count == static_cast<DWORD>(-1))
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(Error()
<< ErrorString("SuspendThread failed.")
<< ErrorCodeWinLast(last_error));
}
return suspend_count;
}
inline DWORD ResumeThread(Thread const& thread)
{
HADESMEM_DETAIL_TRACE_FORMAT_A("Resuming thread with ID 0n%lu.",
thread.GetId());
DWORD const suspend_count = ::ResumeThread(thread.GetHandle());
if (suspend_count == static_cast<DWORD>(-1))
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(Error()
<< ErrorString("ResumeThread failed.")
<< ErrorCodeWinLast(last_error));
}
return suspend_count;
}
inline CONTEXT GetThreadContext(Thread const& thread, DWORD context_flags)
{
if (::GetCurrentThreadId() == thread.GetId() &&
context_flags != CONTEXT_DEBUG_REGISTERS)
{
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("GetThreadContext called for current thread."));
}
CONTEXT context{};
context.ContextFlags = context_flags;
if (!::GetThreadContext(thread.GetHandle(), &context))
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(Error()
<< ErrorString("GetThreadContext failed.")
<< ErrorCodeWinLast(last_error));
}
return context;
}
inline void SetThreadContext(Thread const& thread, CONTEXT const& context)
{
if (!::SetThreadContext(thread.GetHandle(), &context))
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(Error()
<< ErrorString("SetThreadContext failed.")
<< ErrorCodeWinLast(last_error));
}
}
inline void* GetStartAddress(Thread const& thread)
{
HMODULE const ntdll = GetModuleHandleW(L"ntdll");
if (!ntdll)
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(Error{}
<< ErrorString{"GetModuleHandleW failed."}
<< ErrorCodeWinLast{last_error});
}
FARPROC const nt_query_information_thread_proc =
GetProcAddress(ntdll, "NtQueryInformationThread");
if (!nt_query_information_thread_proc)
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(Error{}
<< ErrorString{"GetProcAddress failed."}
<< ErrorCodeWinLast{last_error});
}
using NtQueryInformationThreadPtr =
NTSTATUS(NTAPI*)(HANDLE thread_handle,
detail::winternl::THREADINFOCLASS thread_information_class,
PVOID thread_information,
ULONG thread_information_length,
PULONG return_length);
auto const nt_query_information_thread =
reinterpret_cast<NtQueryInformationThreadPtr>(
nt_query_information_thread_proc);
void* start_address = nullptr;
NTSTATUS const status = nt_query_information_thread(
thread.GetHandle(),
detail::winternl::ThreadQuerySetWin32StartAddress,
&start_address,
sizeof(start_address),
nullptr);
if (!NT_SUCCESS(status))
{
HADESMEM_DETAIL_THROW_EXCEPTION(
Error{} << ErrorString{"NtQueryInformationThread failed."}
<< ErrorCodeWinStatus{status});
}
return start_address;
}
class SuspendedThread
{
public:
explicit SuspendedThread(DWORD thread_id) : thread_(thread_id)
{
SuspendThread(thread_);
}
SuspendedThread(SuspendedThread const& other) = delete;
SuspendedThread& operator=(SuspendedThread const& other) = delete;
SuspendedThread(SuspendedThread&& other) HADESMEM_DETAIL_NOEXCEPT
: thread_(std::move(other.thread_))
{
}
SuspendedThread& operator=(SuspendedThread&& other) HADESMEM_DETAIL_NOEXCEPT
{
ResumeUnchecked();
thread_ = std::move(other.thread_);
return *this;
}
~SuspendedThread() HADESMEM_DETAIL_NOEXCEPT
{
ResumeUnchecked();
}
void Resume()
{
if (thread_.GetHandle())
{
ResumeThread(thread_);
}
}
DWORD GetId() const HADESMEM_DETAIL_NOEXCEPT
{
return thread_.GetId();
}
HANDLE GetHandle() const HADESMEM_DETAIL_NOEXCEPT
{
return thread_.GetHandle();
}
private:
void ResumeUnchecked()
{
try
{
Resume();
}
catch (...)
{
// WARNING: Thread is never resumed if ResumeThread fails...
HADESMEM_DETAIL_TRACE_A(
boost::current_exception_diagnostic_information().c_str());
HADESMEM_DETAIL_ASSERT(false);
}
}
Thread thread_;
};
class SuspendedProcess
{
public:
explicit SuspendedProcess(DWORD pid, DWORD retries = 5)
{
// Multiple retries may be needed to plug a race condition
// whereby after a thread snapshot is taken but before suspension
// takes place, an existing thread launches a new thread which
// would then be missed.
std::set<DWORD> tids;
bool need_retry = false;
do
{
need_retry = false;
ThreadList const threads(pid);
for (auto const& thread_entry : threads)
{
DWORD const current_thread_id = ::GetCurrentThreadId();
if (thread_entry.GetId() != current_thread_id)
{
auto const inserted = tids.insert(thread_entry.GetId());
if (inserted.second)
{
need_retry = true;
try
{
// Close potential race condition whereby after the snapshot is
// taken the thread could terminate and have its TID reused in
// a different process.
Thread const thread(thread_entry.GetId());
VerifyPid(thread, pid);
// Should be safe (with the exception outlined above) to suspend
// the thread now, because we have a handle to the thread open,
// and we've verified it exists in the correct process.
threads_.emplace_back(thread_entry.GetId());
}
catch (std::exception const& /*e*/)
{
tids.erase(inserted.first);
continue;
}
}
}
}
} while (need_retry && retries--);
if (need_retry)
{
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("Failed to suspend all threads in process "
"(too many retries)."));
}
}
SuspendedProcess(SuspendedProcess const& other) = delete;
SuspendedProcess& operator=(SuspendedProcess const& other) = delete;
SuspendedProcess(SuspendedProcess&& other) HADESMEM_DETAIL_NOEXCEPT
: threads_(std::move(other.threads_))
{
}
SuspendedProcess& operator=(SuspendedProcess&& other) HADESMEM_DETAIL_NOEXCEPT
{
threads_ = std::move(other.threads_);
return *this;
}
private:
void VerifyPid(Thread const& thread, DWORD pid) const
{
DWORD const tid_pid = ::GetProcessIdOfThread(thread.GetHandle());
if (!tid_pid)
{
DWORD const last_error = ::GetLastError();
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("GetProcessIdOfThread failed.")
<< ErrorCodeWinLast(last_error));
}
if (tid_pid != pid)
{
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("PID verification failed."));
}
}
std::vector<SuspendedThread> threads_;
};
}
|
Add GetStartAddress.
|
[Thread] Add GetStartAddress.
|
C++
|
mit
|
geota/hadesmem,capturePointer/hadesmem,geota/hadesmem
|
f5b8ae8bd66e71a32eb80a1d9b1b56e23b86913c
|
chrome/test/ui/npapi_uitest.cpp
|
chrome/test/ui/npapi_uitest.cpp
|
// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. 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.
//
// NPAPI UnitTests.
//
// windows headers
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <atlbase.h>
#include <comutil.h>
// runtime headers
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <ostream>
#include "base/file_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/npapi_test_helper.h"
#include "net/base/net_util.h"
const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
const int kLongWaitTimeout = 30 * 1000;
const int kShortWaitTimeout = 5 * 1000;
std::ostream& operator<<(std::ostream& out, const CComBSTR &str)
{
// I love strings. I really do. That's why I make sure
// to need 4 different types of strings to stream one out.
TCHAR szFinal[1024];
_bstr_t bstrIntermediate(str);
_stprintf_s(szFinal, _T("%s"), (LPCTSTR)bstrIntermediate);
return out << szFinal;
}
// Test passing arguments to a plugin.
TEST_F(NPAPITester, Arguments) {
std::wstring test_case = L"arguments.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("arguments", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Test invoking many plugins within a single page.
TEST_F(NPAPITester, ManyPlugins) {
std::wstring test_case = L"many_plugins.html";
GURL url(GetTestUrl(L"npapi", test_case));
NavigateToURL(url);
WaitForFinish("arguments", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "2", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "3", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "4", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "5", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "6", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "7", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "8", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "9", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "10", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "11", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "12", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "13", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "14", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "15", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Test various calls to GetURL from a plugin.
TEST_F(NPAPITester, GetURL) {
std::wstring test_case = L"geturl.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("geturl", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Test various calls to GetURL for javascript URLs with
// non NULL targets from a plugin.
TEST_F(NPAPITester, GetJavaScriptURL) {
std::wstring test_case = L"get_javascript_url.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("getjavascripturl", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Tests that if an NPObject is proxies back to its original process, the
// original pointer is returned and not a proxy. If this fails the plugin
// will crash.
TEST_F(NPAPITester, NPObjectProxy) {
std::wstring test_case = L"npobject_proxy.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("npobject_proxy", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Tests if a plugin executing a self deleting script using NPN_GetURL
// works without crashing or hanging
TEST_F(NPAPITester, SelfDeletePluginGetUrl) {
std::wstring test_case = L"self_delete_plugin_geturl.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("self_delete_plugin_geturl", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
// Tests if a plugin executing a self deleting script using Invoke
// works without crashing or hanging
TEST_F(NPAPITester, SelfDeletePluginInvoke) {
std::wstring test_case = L"self_delete_plugin_invoke.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("self_delete_plugin_invoke", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
// Tests if a plugin executing a self deleting script in the context of
// a synchronous paint event works correctly
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInvokeInSynchronousPaint) {
if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
show_window_ = true;
std::wstring test_case = L"execute_script_delete_in_paint.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("execute_script_delete_in_paint", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
}
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNewStream) {
if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
show_window_ = true;
std::wstring test_case = L"self_delete_plugin_stream.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("self_delete_plugin_stream", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
}
// Tests if a plugin has a non zero window rect.
TEST_F(NPAPIVisiblePluginTester, VerifyPluginWindowRect) {
show_window_ = true;
std::wstring test_case = L"verify_plugin_window_rect.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("checkwindowrect", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
TEST_F(NPAPIVisiblePluginTester, VerifyNPObjectLifetimeTest) {
if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
show_window_ = true;
std::wstring test_case = L"npobject_lifetime_test.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("npobject_lifetime_test", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
}
// Tests that we don't crash or assert if NPP_New fails
TEST_F(NPAPIVisiblePluginTester, NewFails) {
GURL url = GetTestUrl(L"npapi", L"new_fails.html");
NavigateToURL(url);
WaitForFinish("new_fails", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNPNEvaluate) {
if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
GURL url = GetTestUrl(L"npapi",
L"execute_script_delete_in_npn_evaluate.html");
NavigateToURL(url);
WaitForFinish("npobject_delete_plugin_in_evaluate", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
}
TEST_F(NPAPIVisiblePluginTester, OpenPopupWindowWithPlugin) {
GURL url = GetTestUrl(L"npapi",
L"get_javascript_open_popup_with_plugin.html");
NavigateToURL(url);
WaitForFinish("plugin_popup_with_plugin_target", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
|
// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. 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.
//
// NPAPI UnitTests.
//
// windows headers
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <atlbase.h>
#include <comutil.h>
// runtime headers
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <ostream>
#include "base/file_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/npapi_test_helper.h"
#include "net/base/net_util.h"
const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
const int kLongWaitTimeout = 30 * 1000;
const int kShortWaitTimeout = 5 * 1000;
std::ostream& operator<<(std::ostream& out, const CComBSTR &str)
{
// I love strings. I really do. That's why I make sure
// to need 4 different types of strings to stream one out.
TCHAR szFinal[1024];
_bstr_t bstrIntermediate(str);
_stprintf_s(szFinal, _T("%s"), (LPCTSTR)bstrIntermediate);
return out << szFinal;
}
// Test passing arguments to a plugin.
TEST_F(NPAPITester, Arguments) {
std::wstring test_case = L"arguments.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("arguments", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Test invoking many plugins within a single page.
TEST_F(NPAPITester, DISABLED_ManyPlugins) {
std::wstring test_case = L"many_plugins.html";
GURL url(GetTestUrl(L"npapi", test_case));
NavigateToURL(url);
WaitForFinish("arguments", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "2", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "3", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "4", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "5", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "6", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "7", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "8", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "9", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "10", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "11", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "12", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "13", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "14", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "15", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Test various calls to GetURL from a plugin.
TEST_F(NPAPITester, GetURL) {
std::wstring test_case = L"geturl.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("geturl", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Test various calls to GetURL for javascript URLs with
// non NULL targets from a plugin.
TEST_F(NPAPITester, GetJavaScriptURL) {
std::wstring test_case = L"get_javascript_url.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("getjavascripturl", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Tests that if an NPObject is proxies back to its original process, the
// original pointer is returned and not a proxy. If this fails the plugin
// will crash.
TEST_F(NPAPITester, NPObjectProxy) {
std::wstring test_case = L"npobject_proxy.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("npobject_proxy", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Tests if a plugin executing a self deleting script using NPN_GetURL
// works without crashing or hanging
TEST_F(NPAPITester, SelfDeletePluginGetUrl) {
std::wstring test_case = L"self_delete_plugin_geturl.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("self_delete_plugin_geturl", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
// Tests if a plugin executing a self deleting script using Invoke
// works without crashing or hanging
TEST_F(NPAPITester, SelfDeletePluginInvoke) {
std::wstring test_case = L"self_delete_plugin_invoke.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("self_delete_plugin_invoke", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
// Tests if a plugin executing a self deleting script in the context of
// a synchronous paint event works correctly
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInvokeInSynchronousPaint) {
if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
show_window_ = true;
std::wstring test_case = L"execute_script_delete_in_paint.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("execute_script_delete_in_paint", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
}
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNewStream) {
if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
show_window_ = true;
std::wstring test_case = L"self_delete_plugin_stream.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("self_delete_plugin_stream", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
}
// Tests if a plugin has a non zero window rect.
TEST_F(NPAPIVisiblePluginTester, VerifyPluginWindowRect) {
show_window_ = true;
std::wstring test_case = L"verify_plugin_window_rect.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("checkwindowrect", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
TEST_F(NPAPIVisiblePluginTester, DISABLED_VerifyNPObjectLifetimeTest) {
if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
show_window_ = true;
std::wstring test_case = L"npobject_lifetime_test.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("npobject_lifetime_test", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
}
// Tests that we don't crash or assert if NPP_New fails
TEST_F(NPAPIVisiblePluginTester, NewFails) {
GURL url = GetTestUrl(L"npapi", L"new_fails.html");
NavigateToURL(url);
WaitForFinish("new_fails", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNPNEvaluate) {
if (!UITest::in_process_plugins() && !UITest::in_process_renderer()) {
GURL url = GetTestUrl(L"npapi",
L"execute_script_delete_in_npn_evaluate.html");
NavigateToURL(url);
WaitForFinish("npobject_delete_plugin_in_evaluate", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
}
TEST_F(NPAPIVisiblePluginTester, OpenPopupWindowWithPlugin) {
GURL url = GetTestUrl(L"npapi",
L"get_javascript_open_popup_with_plugin.html");
NavigateToURL(url);
WaitForFinish("plugin_popup_with_plugin_target", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
|
Disable some failing UI tests for now.
|
Disable some failing UI tests for now.
TBR=ojan
BUG=3881
Review URL: http://codereview.chromium.org/8923
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@4231 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
adobe/chromium,gavinp/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,ropik/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium
|
e5529559c3bbe7969170468a4f5f481648b514f8
|
chrome/browser/upgrade_detector.cc
|
chrome/browser/upgrade_detector.cc
|
// 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/upgrade_detector.h"
#include <string>
#include "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/task.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/platform_util.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/pref_names.h"
#include "chrome/installer/util/browser_distribution.h"
#include "content/browser/browser_thread.h"
#include "content/common/notification_service.h"
#include "content/common/notification_type.h"
#if defined(OS_WIN)
#include "chrome/installer/util/install_util.h"
#elif defined(OS_MACOSX)
#include "chrome/browser/cocoa/keystone_glue.h"
#elif defined(OS_POSIX)
#include "base/process_util.h"
#include "base/version.h"
#endif
namespace {
// How often to check for an upgrade.
int GetCheckForUpgradeEveryMs() {
// Check for a value passed via the command line.
int interval_ms;
const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
std::string interval =
cmd_line.GetSwitchValueASCII(switches::kCheckForUpdateIntervalSec);
if (!interval.empty() && base::StringToInt(interval, &interval_ms))
return interval_ms * 1000; // Command line value is in seconds.
// Otherwise check once an hour for dev channel and once a day for all other
// channels/builds.
const std::string channel = platform_util::GetVersionStringModifier();
int hours;
if (channel == "dev")
hours = 1;
else
hours = 24;
return hours * 60 * 60 * 1000;
}
// How long to wait before notifying the user about the upgrade.
const int kNotifyUserAfterMs = 0;
// This task checks the currently running version of Chrome against the
// installed version. If the installed version is newer, it runs the passed
// callback task. Otherwise it just deletes the task.
class DetectUpgradeTask : public Task {
public:
explicit DetectUpgradeTask(Task* upgrade_detected_task)
: upgrade_detected_task_(upgrade_detected_task) {
}
virtual ~DetectUpgradeTask() {
if (upgrade_detected_task_) {
// This has to get deleted on the same thread it was created.
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
new DeleteTask<Task>(upgrade_detected_task_));
}
}
virtual void Run() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
scoped_ptr<Version> installed_version;
#if defined(OS_WIN)
// Get the version of the currently *installed* instance of Chrome,
// which might be newer than the *running* instance if we have been
// upgraded in the background.
// TODO(tommi): Check if using the default distribution is always the right
// thing to do.
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
installed_version.reset(InstallUtil::GetChromeVersion(dist, false));
if (!installed_version.get()) {
// User level Chrome is not installed, check system level.
installed_version.reset(InstallUtil::GetChromeVersion(dist, true));
}
#elif defined(OS_MACOSX)
installed_version.reset(
Version::GetVersionFromString(UTF16ToASCII(
keystone_glue::CurrentlyInstalledVersion())));
#elif defined(OS_POSIX)
// POSIX but not Mac OS X: Linux, etc.
CommandLine command_line(*CommandLine::ForCurrentProcess());
command_line.AppendSwitch(switches::kProductVersion);
std::string reply;
if (!base::GetAppOutput(command_line, &reply)) {
DLOG(ERROR) << "Failed to get current file version";
return;
}
installed_version.reset(Version::GetVersionFromString(reply));
#endif
// Get the version of the currently *running* instance of Chrome.
chrome::VersionInfo version_info;
if (!version_info.is_valid()) {
NOTREACHED() << "Failed to get current file version";
return;
}
scoped_ptr<Version> running_version(
Version::GetVersionFromString(version_info.Version()));
if (running_version.get() == NULL) {
NOTREACHED() << "Failed to parse version info";
return;
}
// |installed_version| may be NULL when the user downgrades on Linux (by
// switching from dev to beta channel, for example). The user needs a
// restart in this case as well. See http://crbug.com/46547
if (!installed_version.get() ||
(installed_version->CompareTo(*running_version) > 0)) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
upgrade_detected_task_);
upgrade_detected_task_ = NULL;
}
}
private:
Task* upgrade_detected_task_;
};
} // namespace
// static
void UpgradeDetector::RegisterPrefs(PrefService* prefs) {
prefs->RegisterBooleanPref(prefs::kRestartLastSessionOnShutdown, false);
}
UpgradeDetector::UpgradeDetector()
: ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)),
notify_upgrade_(false) {
// Windows: only enable upgrade notifications for official builds.
// Mac: only enable them if the updater (Keystone) is present.
// Linux (and other POSIX): always enable regardless of branding.
#if (defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)) || defined(OS_POSIX)
#if defined(OS_MACOSX)
if (keystone_glue::KeystoneEnabled())
#endif
{
detect_upgrade_timer_.Start(
base::TimeDelta::FromMilliseconds(GetCheckForUpgradeEveryMs()),
this, &UpgradeDetector::CheckForUpgrade);
}
#endif
}
UpgradeDetector::~UpgradeDetector() {
}
// static
UpgradeDetector* UpgradeDetector::GetInstance() {
return Singleton<UpgradeDetector>::get();
}
void UpgradeDetector::CheckForUpgrade() {
method_factory_.RevokeAll();
Task* callback_task =
method_factory_.NewRunnableMethod(&UpgradeDetector::UpgradeDetected);
// We use FILE as the thread to run the upgrade detection code on all
// platforms. For Linux, this is because we don't want to block the UI thread
// while launching a background process and reading its output; on the Mac and
// on Windows checking for an upgrade requires reading a file.
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
new DetectUpgradeTask(callback_task));
}
void UpgradeDetector::UpgradeDetected() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Stop the recurring timer (that is checking for changes).
detect_upgrade_timer_.Stop();
NotificationService::current()->Notify(
NotificationType::UPGRADE_DETECTED,
Source<UpgradeDetector>(this),
NotificationService::NoDetails());
// Start the OneShot timer for notifying the user after a certain period.
upgrade_notification_timer_.Start(
base::TimeDelta::FromMilliseconds(kNotifyUserAfterMs),
this, &UpgradeDetector::NotifyOnUpgrade);
}
void UpgradeDetector::NotifyOnUpgrade() {
notify_upgrade_ = true;
NotificationService::current()->Notify(
NotificationType::UPGRADE_RECOMMENDED,
Source<UpgradeDetector>(this),
NotificationService::NoDetails());
}
|
// 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/upgrade_detector.h"
#include <string>
#include "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/task.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/platform_util.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/pref_names.h"
#include "chrome/installer/util/browser_distribution.h"
#include "content/browser/browser_thread.h"
#include "content/common/notification_service.h"
#include "content/common/notification_type.h"
#if defined(OS_WIN)
#include "chrome/installer/util/install_util.h"
#elif defined(OS_MACOSX)
#include "chrome/browser/cocoa/keystone_glue.h"
#elif defined(OS_POSIX)
#include "base/process_util.h"
#include "base/version.h"
#endif
namespace {
// How often to check for an upgrade.
int GetCheckForUpgradeEveryMs() {
// Check for a value passed via the command line.
int interval_ms;
const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
std::string interval =
cmd_line.GetSwitchValueASCII(switches::kCheckForUpdateIntervalSec);
if (!interval.empty() && base::StringToInt(interval, &interval_ms))
return interval_ms * 1000; // Command line value is in seconds.
// Otherwise check once an hour for dev channel and once a day for all other
// channels/builds.
const std::string channel = platform_util::GetVersionStringModifier();
int hours;
if (channel == "dev")
hours = 1;
else
hours = 24;
return hours * 60 * 60 * 1000;
}
// How long to wait before notifying the user about the upgrade.
const int kNotifyUserAfterMs = 0;
// This task checks the currently running version of Chrome against the
// installed version. If the installed version is newer, it runs the passed
// callback task. Otherwise it just deletes the task.
class DetectUpgradeTask : public Task {
public:
explicit DetectUpgradeTask(Task* upgrade_detected_task)
: upgrade_detected_task_(upgrade_detected_task) {
}
virtual ~DetectUpgradeTask() {
if (upgrade_detected_task_) {
// This has to get deleted on the same thread it was created.
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
new DeleteTask<Task>(upgrade_detected_task_));
}
}
virtual void Run() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
scoped_ptr<Version> installed_version;
#if defined(OS_WIN)
// Get the version of the currently *installed* instance of Chrome,
// which might be newer than the *running* instance if we have been
// upgraded in the background.
// TODO(tommi): Check if using the default distribution is always the right
// thing to do.
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
installed_version.reset(InstallUtil::GetChromeVersion(dist, false));
if (!installed_version.get()) {
// User level Chrome is not installed, check system level.
installed_version.reset(InstallUtil::GetChromeVersion(dist, true));
}
#elif defined(OS_MACOSX)
installed_version.reset(
Version::GetVersionFromString(UTF16ToASCII(
keystone_glue::CurrentlyInstalledVersion())));
#elif defined(OS_POSIX)
// POSIX but not Mac OS X: Linux, etc.
CommandLine command_line(*CommandLine::ForCurrentProcess());
command_line.AppendSwitch(switches::kProductVersion);
std::string reply;
if (!base::GetAppOutput(command_line, &reply)) {
DLOG(ERROR) << "Failed to get current file version";
return;
}
installed_version.reset(Version::GetVersionFromString(reply));
#endif
// Get the version of the currently *running* instance of Chrome.
chrome::VersionInfo version_info;
if (!version_info.is_valid()) {
NOTREACHED() << "Failed to get current file version";
return;
}
scoped_ptr<Version> running_version(
Version::GetVersionFromString(version_info.Version()));
if (running_version.get() == NULL) {
NOTREACHED() << "Failed to parse version info";
return;
}
// |installed_version| may be NULL when the user downgrades on Linux (by
// switching from dev to beta channel, for example). The user needs a
// restart in this case as well. See http://crbug.com/46547
if (!installed_version.get() ||
(installed_version->CompareTo(*running_version) > 0)) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
upgrade_detected_task_);
upgrade_detected_task_ = NULL;
}
}
private:
Task* upgrade_detected_task_;
};
} // namespace
// static
void UpgradeDetector::RegisterPrefs(PrefService* prefs) {
prefs->RegisterBooleanPref(prefs::kRestartLastSessionOnShutdown, false);
}
UpgradeDetector::UpgradeDetector()
: ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)),
notify_upgrade_(false) {
CommandLine command_line(*CommandLine::ForCurrentProcess());
if (command_line.HasSwitch(switches::kDisableBackgroundNetworking))
return;
// Windows: only enable upgrade notifications for official builds.
// Mac: only enable them if the updater (Keystone) is present.
// Linux (and other POSIX): always enable regardless of branding.
#if (defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)) || defined(OS_POSIX)
#if defined(OS_MACOSX)
if (keystone_glue::KeystoneEnabled())
#endif
{
detect_upgrade_timer_.Start(
base::TimeDelta::FromMilliseconds(GetCheckForUpgradeEveryMs()),
this, &UpgradeDetector::CheckForUpgrade);
}
#endif
}
UpgradeDetector::~UpgradeDetector() {
}
// static
UpgradeDetector* UpgradeDetector::GetInstance() {
return Singleton<UpgradeDetector>::get();
}
void UpgradeDetector::CheckForUpgrade() {
method_factory_.RevokeAll();
Task* callback_task =
method_factory_.NewRunnableMethod(&UpgradeDetector::UpgradeDetected);
// We use FILE as the thread to run the upgrade detection code on all
// platforms. For Linux, this is because we don't want to block the UI thread
// while launching a background process and reading its output; on the Mac and
// on Windows checking for an upgrade requires reading a file.
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
new DetectUpgradeTask(callback_task));
}
void UpgradeDetector::UpgradeDetected() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Stop the recurring timer (that is checking for changes).
detect_upgrade_timer_.Stop();
NotificationService::current()->Notify(
NotificationType::UPGRADE_DETECTED,
Source<UpgradeDetector>(this),
NotificationService::NoDetails());
// Start the OneShot timer for notifying the user after a certain period.
upgrade_notification_timer_.Start(
base::TimeDelta::FromMilliseconds(kNotifyUserAfterMs),
this, &UpgradeDetector::NotifyOnUpgrade);
}
void UpgradeDetector::NotifyOnUpgrade() {
notify_upgrade_ = true;
NotificationService::current()->Notify(
NotificationType::UPGRADE_RECOMMENDED,
Source<UpgradeDetector>(this),
NotificationService::NoDetails());
}
|
Add the UpgradeDetector to the list of things which don't run when the --disable-background-networking cmdline switch is set.
|
Add the UpgradeDetector to the list of things which don't run when the
--disable-background-networking cmdline switch is set.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/6802018
git-svn-id: http://src.chromium.org/svn/trunk/src@80696 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: 3cddd318d68a9b3eade73f88f5339bc45eb3ebcf
|
C++
|
bsd-3-clause
|
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
|
732c665af5713899c727901759786eef61072e02
|
src/timestamp.cpp
|
src/timestamp.cpp
|
/*
* Copyright (c) 2016, Matias Fontanini
* 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
* 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.
*
*/
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#else
#include <sys/time.h>
#endif
#include "timestamp.h"
namespace Tins {
const int MICROSECONDS_IN_SECOND = 1000000;
Timestamp Timestamp::current_time() {
#ifdef _WIN32
FILETIME file_time;
GetSystemTimeAsFileTime(&file_time);
uint64_t timestamp = file_time.dwHighDateTime;
timestamp = timestamp << 32;
timestamp |= file_time.dwLowDateTime;
// Convert to microseconds
timestamp /= 10;
// Change the epoch to POSIX epoch
timestamp -= 11644473600000000ULL;
return Timestamp(timestamp);
#else
timeval tv;
gettimeofday(&tv, 0);
return tv;
#endif
}
Timestamp::Timestamp()
: timestamp_(0) {
}
Timestamp::Timestamp(const timeval& time_val) {
timestamp_ = time_val.tv_sec * MICROSECONDS_IN_SECOND + time_val.tv_usec;
}
Timestamp::Timestamp(uint64_t value)
: timestamp_(value) {
}
Timestamp::seconds_type Timestamp::seconds() const {
return timestamp_ / MICROSECONDS_IN_SECOND;
}
Timestamp::microseconds_type Timestamp::microseconds() const {
return timestamp_ % MICROSECONDS_IN_SECOND;
}
} // Tins
|
/*
* Copyright (c) 2016, Matias Fontanini
* 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
* 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.
*
*/
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#else
#include <sys/time.h>
#endif
#include "timestamp.h"
namespace Tins {
const int MICROSECONDS_IN_SECOND = 1000000;
Timestamp Timestamp::current_time() {
#ifdef _WIN32
FILETIME file_time;
GetSystemTimeAsFileTime(&file_time);
uint64_t timestamp = file_time.dwHighDateTime;
timestamp = timestamp << 32;
timestamp |= file_time.dwLowDateTime;
// Convert to microseconds
timestamp /= 10;
// Change the epoch to POSIX epoch
timestamp -= 11644473600000000ULL;
return Timestamp(timestamp);
#else
timeval tv;
gettimeofday(&tv, 0);
return tv;
#endif
}
Timestamp::Timestamp()
: timestamp_(0) {
}
Timestamp::Timestamp(const timeval& time_val) {
timestamp_ = time_val.tv_sec * MICROSECONDS_IN_SECOND + time_val.tv_usec;
}
Timestamp::Timestamp(uint64_t value)
: timestamp_(value) {
}
Timestamp::seconds_type Timestamp::seconds() const {
return static_cast<seconds_type>(timestamp_ / MICROSECONDS_IN_SECOND);
}
Timestamp::microseconds_type Timestamp::microseconds() const {
return timestamp_ % MICROSECONDS_IN_SECOND;
}
} // Tins
|
Fix compilation warning on VC
|
Fix compilation warning on VC
|
C++
|
bsd-2-clause
|
viveks9/decrypt80211,UlfWetzker/libtins,mfontanini/libtins,UlfWetzker/libtins,mfontanini/libtins,viveks9/decrypt80211
|
b394fe00bc15378037bbd8bb429ddbe1d5c15d42
|
src/tls/c_kex.cpp
|
src/tls/c_kex.cpp
|
/*
* Client Key Exchange Message
* (C) 2004-2010 Jack Lloyd
*
* Released under the terms of the Botan license
*/
#include <botan/internal/tls_messages.h>
#include <botan/internal/tls_reader.h>
#include <botan/internal/tls_extensions.h>
#include <botan/tls_record.h>
#include <botan/internal/assert.h>
#include <botan/credentials_manager.h>
#include <botan/pubkey.h>
#include <botan/dh.h>
#include <botan/ecdh.h>
#include <botan/rsa.h>
#include <botan/srp6.h>
#include <botan/rng.h>
#include <botan/loadstor.h>
#include <memory>
namespace Botan {
namespace TLS {
namespace {
secure_vector<byte> strip_leading_zeros(const secure_vector<byte>& input)
{
size_t leading_zeros = 0;
for(size_t i = 0; i != input.size(); ++i)
{
if(input[i] != 0)
break;
++leading_zeros;
}
secure_vector<byte> output(&input[leading_zeros],
&input[input.size()-1]);
return output;
}
}
/*
* Create a new Client Key Exchange message
*/
Client_Key_Exchange::Client_Key_Exchange(Record_Writer& writer,
Handshake_State* state,
Credentials_Manager& creds,
const std::vector<X509_Certificate>& peer_certs,
const std::string& hostname,
RandomNumberGenerator& rng)
{
const std::string kex_algo = state->suite.kex_algo();
if(kex_algo == "PSK")
{
std::string identity_hint = "";
if(state->server_kex)
{
TLS_Data_Reader reader(state->server_kex->params());
identity_hint = reader.get_string(2, 0, 65535);
}
const std::string hostname = state->client_hello->sni_hostname();
const std::string psk_identity = creds.psk_identity("tls-client",
hostname,
identity_hint);
append_tls_length_value(key_material, psk_identity, 2);
SymmetricKey psk = creds.psk("tls-client", hostname, psk_identity);
std::vector<byte> zeros(psk.length());
append_tls_length_value(pre_master, zeros, 2);
append_tls_length_value(pre_master, psk.bits_of(), 2);
}
else if(state->server_kex)
{
TLS_Data_Reader reader(state->server_kex->params());
SymmetricKey psk;
if(kex_algo == "DHE_PSK" || kex_algo == "ECDHE_PSK")
{
std::string identity_hint = reader.get_string(2, 0, 65535);
const std::string hostname = state->client_hello->sni_hostname();
const std::string psk_identity = creds.psk_identity("tls-client",
hostname,
identity_hint);
append_tls_length_value(key_material, psk_identity, 2);
psk = creds.psk("tls-client", hostname, psk_identity);
}
if(kex_algo == "DH" || kex_algo == "DHE_PSK")
{
BigInt p = BigInt::decode(reader.get_range<byte>(2, 1, 65535));
BigInt g = BigInt::decode(reader.get_range<byte>(2, 1, 65535));
BigInt Y = BigInt::decode(reader.get_range<byte>(2, 1, 65535));
if(reader.remaining_bytes())
throw Decoding_Error("Bad params size for DH key exchange");
DL_Group group(p, g);
if(!group.verify_group(rng, true))
throw Internal_Error("DH group failed validation, possible attack");
DH_PublicKey counterparty_key(group, Y);
// FIXME Check that public key is residue?
DH_PrivateKey priv_key(rng, group);
PK_Key_Agreement ka(priv_key, "Raw");
secure_vector<byte> dh_secret = strip_leading_zeros(
ka.derive_key(0, counterparty_key.public_value()).bits_of());
if(kex_algo == "DH")
pre_master = dh_secret;
else
{
append_tls_length_value(pre_master, dh_secret, 2);
append_tls_length_value(pre_master, psk.bits_of(), 2);
}
append_tls_length_value(key_material, priv_key.public_value(), 2);
}
else if(kex_algo == "ECDH" || kex_algo == "ECDHE_PSK")
{
const byte curve_type = reader.get_byte();
if(curve_type != 3)
throw Decoding_Error("Server sent non-named ECC curve");
const u16bit curve_id = reader.get_u16bit();
const std::string name = Supported_Elliptic_Curves::curve_id_to_name(curve_id);
if(name == "")
throw Decoding_Error("Server sent unknown named curve " + std::to_string(curve_id));
EC_Group group(name);
std::vector<byte> ecdh_key = reader.get_range<byte>(1, 1, 255);
ECDH_PublicKey counterparty_key(group, OS2ECP(ecdh_key, group.get_curve()));
ECDH_PrivateKey priv_key(rng, group);
PK_Key_Agreement ka(priv_key, "Raw");
secure_vector<byte> ecdh_secret = ka.derive_key(0, counterparty_key.public_value()).bits_of();
if(kex_algo == "ECDH")
pre_master = ecdh_secret;
else
{
append_tls_length_value(pre_master, ecdh_secret, 2);
append_tls_length_value(pre_master, psk.bits_of(), 2);
}
append_tls_length_value(key_material, priv_key.public_value(), 1);
}
else if(kex_algo == "SRP_SHA")
{
const BigInt N = BigInt::decode(reader.get_range<byte>(2, 1, 65535));
const BigInt g = BigInt::decode(reader.get_range<byte>(2, 1, 65535));
std::vector<byte> salt = reader.get_range<byte>(1, 1, 255);
const BigInt B = BigInt::decode(reader.get_range<byte>(2, 1, 65535));
const std::string srp_group = srp6_group_identifier(N, g);
const std::string srp_identifier =
creds.srp_identifier("tls-client", hostname);
const std::string srp_password =
creds.srp_password("tls-client", hostname, srp_identifier);
std::pair<BigInt, SymmetricKey> srp_vals =
srp6_client_agree(srp_identifier,
srp_password,
srp_group,
"SHA-1",
salt,
B,
rng);
append_tls_length_value(key_material, BigInt::encode(srp_vals.first), 2);
pre_master = srp_vals.second.bits_of();
}
else
{
throw Internal_Error("Client_Key_Exchange: Unknown kex " +
kex_algo);
}
reader.assert_done();
}
else
{
// No server key exchange msg better mean RSA kex + RSA key in cert
if(kex_algo != "RSA")
throw Unexpected_Message("No server kex but negotiated kex " + kex_algo);
if(peer_certs.empty())
throw Internal_Error("No certificate and no server key exchange");
std::unique_ptr<Public_Key> pub_key(peer_certs[0].subject_public_key());
if(const RSA_PublicKey* rsa_pub = dynamic_cast<const RSA_PublicKey*>(pub_key.get()))
{
const Protocol_Version pref_version = state->client_hello->version();
pre_master = rng.random_vec(48);
pre_master[0] = pref_version.major_version();
pre_master[1] = pref_version.minor_version();
PK_Encryptor_EME encryptor(*rsa_pub, "PKCS1v15");
std::vector<byte> encrypted_key = encryptor.encrypt(pre_master, rng);
if(state->version() == Protocol_Version::SSL_V3)
key_material = encrypted_key; // no length field
else
append_tls_length_value(key_material, encrypted_key, 2);
}
else
throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
"Expected a RSA key in server cert but got " +
pub_key->algo_name());
}
state->hash.update(writer.send(*this));
}
/*
* Read a Client Key Exchange message
*/
Client_Key_Exchange::Client_Key_Exchange(const std::vector<byte>& contents,
const Handshake_State* state,
Credentials_Manager& creds,
const Policy& policy,
RandomNumberGenerator& rng)
{
const std::string kex_algo = state->suite.kex_algo();
if(kex_algo == "RSA")
{
BOTAN_ASSERT(state->server_certs && !state->server_certs->cert_chain().empty(),
"No server certificate to use for RSA");
const Private_Key* private_key = state->server_rsa_kex_key;
if(!private_key)
throw Internal_Error("Expected RSA kex but no server kex key set");
if(!dynamic_cast<const RSA_PrivateKey*>(private_key))
throw Internal_Error("Expected RSA key but got " + private_key->algo_name());
PK_Decryptor_EME decryptor(*private_key, "PKCS1v15");
Protocol_Version client_version = state->client_hello->version();
try
{
if(state->version() == Protocol_Version::SSL_V3)
{
pre_master = decryptor.decrypt(contents);
}
else
{
TLS_Data_Reader reader(contents);
pre_master = decryptor.decrypt(reader.get_range<byte>(2, 0, 65535));
}
if(pre_master.size() != 48 ||
client_version.major_version() != pre_master[0] ||
client_version.minor_version() != pre_master[1])
{
throw Decoding_Error("Client_Key_Exchange: Secret corrupted");
}
}
catch(...)
{
// Randomize the hide timing channel
pre_master = rng.random_vec(48);
pre_master[0] = client_version.major_version();
pre_master[1] = client_version.minor_version();
}
}
else
{
TLS_Data_Reader reader(contents);
SymmetricKey psk;
if(kex_algo == "PSK" || kex_algo == "DHE_PSK" || kex_algo == "ECDHE_PSK")
{
const std::string psk_identity = reader.get_string(2, 0, 65535);
psk = creds.psk("tls-server",
state->client_hello->sni_hostname(),
psk_identity);
if(psk.length() == 0)
{
if(policy.hide_unknown_users())
psk = SymmetricKey(rng, 16);
else
throw TLS_Exception(Alert::UNKNOWN_PSK_IDENTITY,
"No PSK for identifier " + psk_identity);
}
}
if(kex_algo == "PSK")
{
std::vector<byte> zeros(psk.length());
append_tls_length_value(pre_master, zeros, 2);
append_tls_length_value(pre_master, psk.bits_of(), 2);
}
else if(kex_algo == "SRP_SHA")
{
SRP6_Server_Session& srp = state->server_kex->server_srp_params();
pre_master = srp.step2(BigInt::decode(reader.get_range<byte>(2, 0, 65535))).bits_of();
}
else if(kex_algo == "DH" || kex_algo == "DHE_PSK" ||
kex_algo == "ECDH" || kex_algo == "ECDHE_PSK")
{
const Private_Key& private_key = state->server_kex->server_kex_key();
const PK_Key_Agreement_Key* ka_key =
dynamic_cast<const PK_Key_Agreement_Key*>(&private_key);
if(!ka_key)
throw Internal_Error("Expected key agreement key type but got " +
private_key.algo_name());
try
{
PK_Key_Agreement ka(*ka_key, "Raw");
std::vector<byte> client_pubkey;
if(ka_key->algo_name() == "DH")
client_pubkey = reader.get_range<byte>(2, 0, 65535);
else
client_pubkey = reader.get_range<byte>(1, 0, 255);
secure_vector<byte> shared_secret = ka.derive_key(0, client_pubkey).bits_of();
if(ka_key->algo_name() == "DH")
shared_secret = strip_leading_zeros(shared_secret);
if(kex_algo == "DHE_PSK" || kex_algo == "ECDHE_PSK")
{
append_tls_length_value(pre_master, shared_secret, 2);
append_tls_length_value(pre_master, psk.bits_of(), 2);
}
else
pre_master = shared_secret;
}
catch(std::exception &e)
{
/*
* Something failed in the DH computation. To avoid possible
* timing attacks, randomize the pre-master output and carry
* on, allowing the protocol to fail later in the finished
* checks.
*/
pre_master = rng.random_vec(ka_key->public_value().size());
}
}
else
throw Internal_Error("Client_Key_Exchange: Unknown kex type " + kex_algo);
}
}
}
}
|
/*
* Client Key Exchange Message
* (C) 2004-2010 Jack Lloyd
*
* Released under the terms of the Botan license
*/
#include <botan/internal/tls_messages.h>
#include <botan/internal/tls_reader.h>
#include <botan/internal/tls_extensions.h>
#include <botan/tls_record.h>
#include <botan/internal/assert.h>
#include <botan/credentials_manager.h>
#include <botan/pubkey.h>
#include <botan/dh.h>
#include <botan/ecdh.h>
#include <botan/rsa.h>
#include <botan/srp6.h>
#include <botan/rng.h>
#include <botan/loadstor.h>
#include <memory>
namespace Botan {
namespace TLS {
namespace {
secure_vector<byte> strip_leading_zeros(const secure_vector<byte>& input)
{
size_t leading_zeros = 0;
for(size_t i = 0; i != input.size(); ++i)
{
if(input[i] != 0)
break;
++leading_zeros;
}
secure_vector<byte> output(&input[leading_zeros],
&input[input.size()]);
return output;
}
}
/*
* Create a new Client Key Exchange message
*/
Client_Key_Exchange::Client_Key_Exchange(Record_Writer& writer,
Handshake_State* state,
Credentials_Manager& creds,
const std::vector<X509_Certificate>& peer_certs,
const std::string& hostname,
RandomNumberGenerator& rng)
{
const std::string kex_algo = state->suite.kex_algo();
if(kex_algo == "PSK")
{
std::string identity_hint = "";
if(state->server_kex)
{
TLS_Data_Reader reader(state->server_kex->params());
identity_hint = reader.get_string(2, 0, 65535);
}
const std::string hostname = state->client_hello->sni_hostname();
const std::string psk_identity = creds.psk_identity("tls-client",
hostname,
identity_hint);
append_tls_length_value(key_material, psk_identity, 2);
SymmetricKey psk = creds.psk("tls-client", hostname, psk_identity);
std::vector<byte> zeros(psk.length());
append_tls_length_value(pre_master, zeros, 2);
append_tls_length_value(pre_master, psk.bits_of(), 2);
}
else if(state->server_kex)
{
TLS_Data_Reader reader(state->server_kex->params());
SymmetricKey psk;
if(kex_algo == "DHE_PSK" || kex_algo == "ECDHE_PSK")
{
std::string identity_hint = reader.get_string(2, 0, 65535);
const std::string hostname = state->client_hello->sni_hostname();
const std::string psk_identity = creds.psk_identity("tls-client",
hostname,
identity_hint);
append_tls_length_value(key_material, psk_identity, 2);
psk = creds.psk("tls-client", hostname, psk_identity);
}
if(kex_algo == "DH" || kex_algo == "DHE_PSK")
{
BigInt p = BigInt::decode(reader.get_range<byte>(2, 1, 65535));
BigInt g = BigInt::decode(reader.get_range<byte>(2, 1, 65535));
BigInt Y = BigInt::decode(reader.get_range<byte>(2, 1, 65535));
if(reader.remaining_bytes())
throw Decoding_Error("Bad params size for DH key exchange");
DL_Group group(p, g);
if(!group.verify_group(rng, true))
throw Internal_Error("DH group failed validation, possible attack");
DH_PublicKey counterparty_key(group, Y);
// FIXME Check that public key is residue?
DH_PrivateKey priv_key(rng, group);
PK_Key_Agreement ka(priv_key, "Raw");
secure_vector<byte> dh_secret = strip_leading_zeros(
ka.derive_key(0, counterparty_key.public_value()).bits_of());
if(kex_algo == "DH")
pre_master = dh_secret;
else
{
append_tls_length_value(pre_master, dh_secret, 2);
append_tls_length_value(pre_master, psk.bits_of(), 2);
}
append_tls_length_value(key_material, priv_key.public_value(), 2);
}
else if(kex_algo == "ECDH" || kex_algo == "ECDHE_PSK")
{
const byte curve_type = reader.get_byte();
if(curve_type != 3)
throw Decoding_Error("Server sent non-named ECC curve");
const u16bit curve_id = reader.get_u16bit();
const std::string name = Supported_Elliptic_Curves::curve_id_to_name(curve_id);
if(name == "")
throw Decoding_Error("Server sent unknown named curve " + std::to_string(curve_id));
EC_Group group(name);
std::vector<byte> ecdh_key = reader.get_range<byte>(1, 1, 255);
ECDH_PublicKey counterparty_key(group, OS2ECP(ecdh_key, group.get_curve()));
ECDH_PrivateKey priv_key(rng, group);
PK_Key_Agreement ka(priv_key, "Raw");
secure_vector<byte> ecdh_secret = ka.derive_key(0, counterparty_key.public_value()).bits_of();
if(kex_algo == "ECDH")
pre_master = ecdh_secret;
else
{
append_tls_length_value(pre_master, ecdh_secret, 2);
append_tls_length_value(pre_master, psk.bits_of(), 2);
}
append_tls_length_value(key_material, priv_key.public_value(), 1);
}
else if(kex_algo == "SRP_SHA")
{
const BigInt N = BigInt::decode(reader.get_range<byte>(2, 1, 65535));
const BigInt g = BigInt::decode(reader.get_range<byte>(2, 1, 65535));
std::vector<byte> salt = reader.get_range<byte>(1, 1, 255);
const BigInt B = BigInt::decode(reader.get_range<byte>(2, 1, 65535));
const std::string srp_group = srp6_group_identifier(N, g);
const std::string srp_identifier =
creds.srp_identifier("tls-client", hostname);
const std::string srp_password =
creds.srp_password("tls-client", hostname, srp_identifier);
std::pair<BigInt, SymmetricKey> srp_vals =
srp6_client_agree(srp_identifier,
srp_password,
srp_group,
"SHA-1",
salt,
B,
rng);
append_tls_length_value(key_material, BigInt::encode(srp_vals.first), 2);
pre_master = srp_vals.second.bits_of();
}
else
{
throw Internal_Error("Client_Key_Exchange: Unknown kex " +
kex_algo);
}
reader.assert_done();
}
else
{
// No server key exchange msg better mean RSA kex + RSA key in cert
if(kex_algo != "RSA")
throw Unexpected_Message("No server kex but negotiated kex " + kex_algo);
if(peer_certs.empty())
throw Internal_Error("No certificate and no server key exchange");
std::unique_ptr<Public_Key> pub_key(peer_certs[0].subject_public_key());
if(const RSA_PublicKey* rsa_pub = dynamic_cast<const RSA_PublicKey*>(pub_key.get()))
{
const Protocol_Version pref_version = state->client_hello->version();
pre_master = rng.random_vec(48);
pre_master[0] = pref_version.major_version();
pre_master[1] = pref_version.minor_version();
PK_Encryptor_EME encryptor(*rsa_pub, "PKCS1v15");
std::vector<byte> encrypted_key = encryptor.encrypt(pre_master, rng);
if(state->version() == Protocol_Version::SSL_V3)
key_material = encrypted_key; // no length field
else
append_tls_length_value(key_material, encrypted_key, 2);
}
else
throw TLS_Exception(Alert::HANDSHAKE_FAILURE,
"Expected a RSA key in server cert but got " +
pub_key->algo_name());
}
state->hash.update(writer.send(*this));
}
/*
* Read a Client Key Exchange message
*/
Client_Key_Exchange::Client_Key_Exchange(const std::vector<byte>& contents,
const Handshake_State* state,
Credentials_Manager& creds,
const Policy& policy,
RandomNumberGenerator& rng)
{
const std::string kex_algo = state->suite.kex_algo();
if(kex_algo == "RSA")
{
BOTAN_ASSERT(state->server_certs && !state->server_certs->cert_chain().empty(),
"No server certificate to use for RSA");
const Private_Key* private_key = state->server_rsa_kex_key;
if(!private_key)
throw Internal_Error("Expected RSA kex but no server kex key set");
if(!dynamic_cast<const RSA_PrivateKey*>(private_key))
throw Internal_Error("Expected RSA key but got " + private_key->algo_name());
PK_Decryptor_EME decryptor(*private_key, "PKCS1v15");
Protocol_Version client_version = state->client_hello->version();
try
{
if(state->version() == Protocol_Version::SSL_V3)
{
pre_master = decryptor.decrypt(contents);
}
else
{
TLS_Data_Reader reader(contents);
pre_master = decryptor.decrypt(reader.get_range<byte>(2, 0, 65535));
}
if(pre_master.size() != 48 ||
client_version.major_version() != pre_master[0] ||
client_version.minor_version() != pre_master[1])
{
throw Decoding_Error("Client_Key_Exchange: Secret corrupted");
}
}
catch(...)
{
// Randomize the hide timing channel
pre_master = rng.random_vec(48);
pre_master[0] = client_version.major_version();
pre_master[1] = client_version.minor_version();
}
}
else
{
TLS_Data_Reader reader(contents);
SymmetricKey psk;
if(kex_algo == "PSK" || kex_algo == "DHE_PSK" || kex_algo == "ECDHE_PSK")
{
const std::string psk_identity = reader.get_string(2, 0, 65535);
psk = creds.psk("tls-server",
state->client_hello->sni_hostname(),
psk_identity);
if(psk.length() == 0)
{
if(policy.hide_unknown_users())
psk = SymmetricKey(rng, 16);
else
throw TLS_Exception(Alert::UNKNOWN_PSK_IDENTITY,
"No PSK for identifier " + psk_identity);
}
}
if(kex_algo == "PSK")
{
std::vector<byte> zeros(psk.length());
append_tls_length_value(pre_master, zeros, 2);
append_tls_length_value(pre_master, psk.bits_of(), 2);
}
else if(kex_algo == "SRP_SHA")
{
SRP6_Server_Session& srp = state->server_kex->server_srp_params();
pre_master = srp.step2(BigInt::decode(reader.get_range<byte>(2, 0, 65535))).bits_of();
}
else if(kex_algo == "DH" || kex_algo == "DHE_PSK" ||
kex_algo == "ECDH" || kex_algo == "ECDHE_PSK")
{
const Private_Key& private_key = state->server_kex->server_kex_key();
const PK_Key_Agreement_Key* ka_key =
dynamic_cast<const PK_Key_Agreement_Key*>(&private_key);
if(!ka_key)
throw Internal_Error("Expected key agreement key type but got " +
private_key.algo_name());
try
{
PK_Key_Agreement ka(*ka_key, "Raw");
std::vector<byte> client_pubkey;
if(ka_key->algo_name() == "DH")
client_pubkey = reader.get_range<byte>(2, 0, 65535);
else
client_pubkey = reader.get_range<byte>(1, 0, 255);
secure_vector<byte> shared_secret = ka.derive_key(0, client_pubkey).bits_of();
if(ka_key->algo_name() == "DH")
shared_secret = strip_leading_zeros(shared_secret);
if(kex_algo == "DHE_PSK" || kex_algo == "ECDHE_PSK")
{
append_tls_length_value(pre_master, shared_secret, 2);
append_tls_length_value(pre_master, psk.bits_of(), 2);
}
else
pre_master = shared_secret;
}
catch(std::exception &e)
{
/*
* Something failed in the DH computation. To avoid possible
* timing attacks, randomize the pre-master output and carry
* on, allowing the protocol to fail later in the finished
* checks.
*/
pre_master = rng.random_vec(ka_key->public_value().size());
}
}
else
throw Internal_Error("Client_Key_Exchange: Unknown kex type " + kex_algo);
}
}
}
}
|
Fix for DHE, strip_leading_zeros always took off the last byte
|
Fix for DHE, strip_leading_zeros always took off the last byte
|
C++
|
bsd-2-clause
|
Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,webmaster128/botan,webmaster128/botan,randombit/botan,randombit/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,webmaster128/botan,randombit/botan,randombit/botan
|
e03d7d792c93418928e4b30a79bc7a19a26b7edb
|
tools/clang-format/ClangFormat.cpp
|
tools/clang-format/ClangFormat.cpp
|
//===-- clang-format/ClangFormat.cpp - Clang format tool ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements a clang-format tool that automatically formats
/// (fragments of) C++ code.
///
//===----------------------------------------------------------------------===//
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/Version.h"
#include "clang/Format/Format.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Signals.h"
using namespace llvm;
static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
// Mark all our options with this category, everything else (except for -version
// and -help) will be hidden.
static cl::OptionCategory ClangFormatCategory("Clang-format options");
static cl::list<unsigned>
Offsets("offset",
cl::desc("Format a range starting at this byte offset.\n"
"Multiple ranges can be formatted by specifying\n"
"several -offset and -length pairs.\n"
"Can only be used with one input file."),
cl::cat(ClangFormatCategory));
static cl::list<unsigned>
Lengths("length",
cl::desc("Format a range of this length (in bytes).\n"
"Multiple ranges can be formatted by specifying\n"
"several -offset and -length pairs.\n"
"When only a single -offset is specified without\n"
"-length, clang-format will format up to the end\n"
"of the file.\n"
"Can only be used with one input file."),
cl::cat(ClangFormatCategory));
static cl::list<std::string>
LineRanges("lines", cl::desc("<start line>:<end line> - format a range of\n"
"lines (both 1-based).\n"
"Multiple ranges can be formatted by specifying\n"
"several -lines arguments.\n"
"Can't be used with -offset and -length.\n"
"Can only be used with one input file."),
cl::cat(ClangFormatCategory));
static cl::opt<std::string>
Style("style",
cl::desc(clang::format::StyleOptionHelpDescription),
cl::init("file"), cl::cat(ClangFormatCategory));
static cl::opt<std::string>
FallbackStyle("fallback-style",
cl::desc("The name of the predefined style used as a\n"
"fallback in case clang-format is invoked with\n"
"-style=file, but can not find the .clang-format\n"
"file to use.\n"
"Use -fallback-style=none to skip formatting."),
cl::init("LLVM"), cl::cat(ClangFormatCategory));
static cl::opt<std::string>
AssumeFilename("assume-filename",
cl::desc("When reading from stdin, clang-format assumes this\n"
"filename to look for a style config file (with\n"
"-style=file) and to determine the language."),
cl::cat(ClangFormatCategory));
static cl::opt<bool> Inplace("i",
cl::desc("Inplace edit <file>s, if specified."),
cl::cat(ClangFormatCategory));
static cl::opt<bool> OutputXML("output-replacements-xml",
cl::desc("Output replacements as XML."),
cl::cat(ClangFormatCategory));
static cl::opt<bool>
DumpConfig("dump-config",
cl::desc("Dump configuration options to stdout and exit.\n"
"Can be used with -style option."),
cl::cat(ClangFormatCategory));
static cl::opt<unsigned>
Cursor("cursor",
cl::desc("The position of the cursor when invoking\n"
"clang-format from an editor integration"),
cl::init(0), cl::cat(ClangFormatCategory));
static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
cl::cat(ClangFormatCategory));
namespace clang {
namespace format {
static FileID createInMemoryFile(StringRef FileName, MemoryBuffer *Source,
SourceManager &Sources, FileManager &Files) {
const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
FileName,
Source->getBufferSize(), 0);
Sources.overrideFileContents(Entry, Source, true);
return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
}
// Parses <start line>:<end line> input to a pair of line numbers.
// Returns true on error.
static bool parseLineRange(StringRef Input, unsigned &FromLine,
unsigned &ToLine) {
std::pair<StringRef, StringRef> LineRange = Input.split(':');
return LineRange.first.getAsInteger(0, FromLine) ||
LineRange.second.getAsInteger(0, ToLine);
}
static bool fillRanges(SourceManager &Sources, FileID ID,
const MemoryBuffer *Code,
std::vector<CharSourceRange> &Ranges) {
if (!LineRanges.empty()) {
if (!Offsets.empty() || !Lengths.empty()) {
llvm::errs() << "error: cannot use -lines with -offset/-length\n";
return true;
}
for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
unsigned FromLine, ToLine;
if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
llvm::errs() << "error: invalid <start line>:<end line> pair\n";
return true;
}
if (FromLine > ToLine) {
llvm::errs() << "error: start line should be less than end line\n";
return true;
}
SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
if (Start.isInvalid() || End.isInvalid())
return true;
Ranges.push_back(CharSourceRange::getCharRange(Start, End));
}
return false;
}
if (Offsets.empty())
Offsets.push_back(0);
if (Offsets.size() != Lengths.size() &&
!(Offsets.size() == 1 && Lengths.empty())) {
llvm::errs()
<< "error: number of -offset and -length arguments must match.\n";
return true;
}
for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
if (Offsets[i] >= Code->getBufferSize()) {
llvm::errs() << "error: offset " << Offsets[i]
<< " is outside the file\n";
return true;
}
SourceLocation Start =
Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
SourceLocation End;
if (i < Lengths.size()) {
if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
llvm::errs() << "error: invalid length " << Lengths[i]
<< ", offset + length (" << Offsets[i] + Lengths[i]
<< ") is outside the file.\n";
return true;
}
End = Start.getLocWithOffset(Lengths[i]);
} else {
End = Sources.getLocForEndOfFile(ID);
}
Ranges.push_back(CharSourceRange::getCharRange(Start, End));
}
return false;
}
static void outputReplacementXML(StringRef Text) {
size_t From = 0;
size_t Index;
while ((Index = Text.find_first_of("\n\r", From)) != StringRef::npos) {
llvm::outs() << Text.substr(From, Index - From);
switch (Text[Index]) {
case '\n':
llvm::outs() << " ";
break;
case '\r':
llvm::outs() << " ";
break;
default:
llvm_unreachable("Unexpected character encountered!");
}
From = Index + 1;
}
llvm::outs() << Text.substr(From);
}
// Returns true on error.
static bool format(StringRef FileName) {
FileManager Files((FileSystemOptions()));
DiagnosticsEngine Diagnostics(
IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
new DiagnosticOptions);
SourceManager Sources(Diagnostics, Files);
ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
MemoryBuffer::getFileOrSTDIN(FileName);
if (std::error_code EC = CodeOrErr.getError()) {
llvm::errs() << EC.message() << "\n";
return true;
}
std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get());
if (Code->getBufferSize() == 0)
return false; // Empty files are formatted correctly.
FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
std::vector<CharSourceRange> Ranges;
if (fillRanges(Sources, ID, Code.get(), Ranges))
return true;
FormatStyle FormatStyle = getStyle(
Style, (FileName == "-") ? AssumeFilename : FileName, FallbackStyle);
tooling::Replacements Replaces = reformat(FormatStyle, Sources, ID, Ranges);
if (OutputXML) {
llvm::outs()
<< "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
for (tooling::Replacements::const_iterator I = Replaces.begin(),
E = Replaces.end();
I != E; ++I) {
llvm::outs() << "<replacement "
<< "offset='" << I->getOffset() << "' "
<< "length='" << I->getLength() << "'>";
outputReplacementXML(I->getReplacementText());
llvm::outs() << "</replacement>\n";
}
llvm::outs() << "</replacements>\n";
} else {
Rewriter Rewrite(Sources, LangOptions());
tooling::applyAllReplacements(Replaces, Rewrite);
if (Inplace) {
if (Rewrite.overwriteChangedFiles())
return true;
} else {
if (Cursor.getNumOccurrences() != 0)
outs() << "{ \"Cursor\": "
<< tooling::shiftedCodePosition(Replaces, Cursor) << " }\n";
Rewrite.getEditBuffer(ID).write(outs());
}
}
return false;
}
} // namespace format
} // namespace clang
static void PrintVersion() {
raw_ostream &OS = outs();
OS << clang::getClangToolFullVersion("clang-format") << '\n';
}
int main(int argc, const char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal();
// Hide unrelated options.
StringMap<cl::Option*> Options;
cl::getRegisteredOptions(Options);
for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end();
I != E; ++I) {
if (I->second->Category != &ClangFormatCategory && I->first() != "help" &&
I->first() != "version")
I->second->setHiddenFlag(cl::ReallyHidden);
}
cl::SetVersionPrinter(PrintVersion);
cl::ParseCommandLineOptions(
argc, argv,
"A tool to format C/C++/Obj-C code.\n\n"
"If no arguments are specified, it formats the code from standard input\n"
"and writes the result to the standard output.\n"
"If <file>s are given, it reformats the files. If -i is specified\n"
"together with <file>s, the files are edited in-place. Otherwise, the\n"
"result is written to the standard output.\n");
if (Help)
cl::PrintHelpMessage();
if (DumpConfig) {
std::string Config =
clang::format::configurationAsText(clang::format::getStyle(
Style, FileNames.empty() ? AssumeFilename : FileNames[0],
FallbackStyle));
llvm::outs() << Config << "\n";
return 0;
}
bool Error = false;
switch (FileNames.size()) {
case 0:
Error = clang::format::format("-");
break;
case 1:
Error = clang::format::format(FileNames[0]);
break;
default:
if (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty()) {
llvm::errs() << "error: -offset, -length and -lines can only be used for "
"single file.\n";
return 1;
}
for (unsigned i = 0; i < FileNames.size(); ++i)
Error |= clang::format::format(FileNames[i]);
break;
}
return Error ? 1 : 0;
}
|
//===-- clang-format/ClangFormat.cpp - Clang format tool ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements a clang-format tool that automatically formats
/// (fragments of) C++ code.
///
//===----------------------------------------------------------------------===//
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/Version.h"
#include "clang/Format/Format.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Signals.h"
using namespace llvm;
static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
// Mark all our options with this category, everything else (except for -version
// and -help) will be hidden.
static cl::OptionCategory ClangFormatCategory("Clang-format options");
static cl::list<unsigned>
Offsets("offset",
cl::desc("Format a range starting at this byte offset.\n"
"Multiple ranges can be formatted by specifying\n"
"several -offset and -length pairs.\n"
"Can only be used with one input file."),
cl::cat(ClangFormatCategory));
static cl::list<unsigned>
Lengths("length",
cl::desc("Format a range of this length (in bytes).\n"
"Multiple ranges can be formatted by specifying\n"
"several -offset and -length pairs.\n"
"When only a single -offset is specified without\n"
"-length, clang-format will format up to the end\n"
"of the file.\n"
"Can only be used with one input file."),
cl::cat(ClangFormatCategory));
static cl::list<std::string>
LineRanges("lines", cl::desc("<start line>:<end line> - format a range of\n"
"lines (both 1-based).\n"
"Multiple ranges can be formatted by specifying\n"
"several -lines arguments.\n"
"Can't be used with -offset and -length.\n"
"Can only be used with one input file."),
cl::cat(ClangFormatCategory));
static cl::opt<std::string>
Style("style",
cl::desc(clang::format::StyleOptionHelpDescription),
cl::init("file"), cl::cat(ClangFormatCategory));
static cl::opt<std::string>
FallbackStyle("fallback-style",
cl::desc("The name of the predefined style used as a\n"
"fallback in case clang-format is invoked with\n"
"-style=file, but can not find the .clang-format\n"
"file to use.\n"
"Use -fallback-style=none to skip formatting."),
cl::init("LLVM"), cl::cat(ClangFormatCategory));
static cl::opt<std::string>
AssumeFilename("assume-filename",
cl::desc("When reading from stdin, clang-format assumes this\n"
"filename to look for a style config file (with\n"
"-style=file) and to determine the language."),
cl::cat(ClangFormatCategory));
static cl::opt<bool> Inplace("i",
cl::desc("Inplace edit <file>s, if specified."),
cl::cat(ClangFormatCategory));
static cl::opt<bool> OutputXML("output-replacements-xml",
cl::desc("Output replacements as XML."),
cl::cat(ClangFormatCategory));
static cl::opt<bool>
DumpConfig("dump-config",
cl::desc("Dump configuration options to stdout and exit.\n"
"Can be used with -style option."),
cl::cat(ClangFormatCategory));
static cl::opt<unsigned>
Cursor("cursor",
cl::desc("The position of the cursor when invoking\n"
"clang-format from an editor integration"),
cl::init(0), cl::cat(ClangFormatCategory));
static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
cl::cat(ClangFormatCategory));
namespace clang {
namespace format {
static FileID createInMemoryFile(StringRef FileName, MemoryBuffer *Source,
SourceManager &Sources, FileManager &Files) {
const FileEntry *Entry = Files.getVirtualFile(FileName == "-" ? "<stdin>" :
FileName,
Source->getBufferSize(), 0);
Sources.overrideFileContents(Entry, Source, true);
return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
}
// Parses <start line>:<end line> input to a pair of line numbers.
// Returns true on error.
static bool parseLineRange(StringRef Input, unsigned &FromLine,
unsigned &ToLine) {
std::pair<StringRef, StringRef> LineRange = Input.split(':');
return LineRange.first.getAsInteger(0, FromLine) ||
LineRange.second.getAsInteger(0, ToLine);
}
static bool fillRanges(SourceManager &Sources, FileID ID,
const MemoryBuffer *Code,
std::vector<CharSourceRange> &Ranges) {
if (!LineRanges.empty()) {
if (!Offsets.empty() || !Lengths.empty()) {
llvm::errs() << "error: cannot use -lines with -offset/-length\n";
return true;
}
for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
unsigned FromLine, ToLine;
if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
llvm::errs() << "error: invalid <start line>:<end line> pair\n";
return true;
}
if (FromLine > ToLine) {
llvm::errs() << "error: start line should be less than end line\n";
return true;
}
SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
if (Start.isInvalid() || End.isInvalid())
return true;
Ranges.push_back(CharSourceRange::getCharRange(Start, End));
}
return false;
}
if (Offsets.empty())
Offsets.push_back(0);
if (Offsets.size() != Lengths.size() &&
!(Offsets.size() == 1 && Lengths.empty())) {
llvm::errs()
<< "error: number of -offset and -length arguments must match.\n";
return true;
}
for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
if (Offsets[i] >= Code->getBufferSize()) {
llvm::errs() << "error: offset " << Offsets[i]
<< " is outside the file\n";
return true;
}
SourceLocation Start =
Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
SourceLocation End;
if (i < Lengths.size()) {
if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
llvm::errs() << "error: invalid length " << Lengths[i]
<< ", offset + length (" << Offsets[i] + Lengths[i]
<< ") is outside the file.\n";
return true;
}
End = Start.getLocWithOffset(Lengths[i]);
} else {
End = Sources.getLocForEndOfFile(ID);
}
Ranges.push_back(CharSourceRange::getCharRange(Start, End));
}
return false;
}
static void outputReplacementXML(StringRef Text) {
size_t From = 0;
size_t Index;
while ((Index = Text.find_first_of("\n\r", From)) != StringRef::npos) {
llvm::outs() << Text.substr(From, Index - From);
switch (Text[Index]) {
case '\n':
llvm::outs() << " ";
break;
case '\r':
llvm::outs() << " ";
break;
default:
llvm_unreachable("Unexpected character encountered!");
}
From = Index + 1;
}
llvm::outs() << Text.substr(From);
}
// Returns true on error.
static bool format(StringRef FileName) {
FileManager Files((FileSystemOptions()));
DiagnosticsEngine Diagnostics(
IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
new DiagnosticOptions);
SourceManager Sources(Diagnostics, Files);
ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
MemoryBuffer::getFileOrSTDIN(FileName);
if (std::error_code EC = CodeOrErr.getError()) {
llvm::errs() << EC.message() << "\n";
return true;
}
std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get());
if (Code->getBufferSize() == 0)
return false; // Empty files are formatted correctly.
FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
std::vector<CharSourceRange> Ranges;
if (fillRanges(Sources, ID, Code.get(), Ranges))
return true;
FormatStyle FormatStyle = getStyle(
Style, (FileName == "-") ? AssumeFilename : FileName, FallbackStyle);
tooling::Replacements Replaces = reformat(FormatStyle, Sources, ID, Ranges);
if (OutputXML) {
llvm::outs()
<< "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
if (Cursor.getNumOccurrences() != 0)
llvm::outs() << "<cursor>"
<< tooling::shiftedCodePosition(Replaces, Cursor)
<< "</cursor>\n";
for (tooling::Replacements::const_iterator I = Replaces.begin(),
E = Replaces.end();
I != E; ++I) {
llvm::outs() << "<replacement "
<< "offset='" << I->getOffset() << "' "
<< "length='" << I->getLength() << "'>";
outputReplacementXML(I->getReplacementText());
llvm::outs() << "</replacement>\n";
}
llvm::outs() << "</replacements>\n";
} else {
Rewriter Rewrite(Sources, LangOptions());
tooling::applyAllReplacements(Replaces, Rewrite);
if (Inplace) {
if (Rewrite.overwriteChangedFiles())
return true;
} else {
if (Cursor.getNumOccurrences() != 0)
outs() << "{ \"Cursor\": "
<< tooling::shiftedCodePosition(Replaces, Cursor) << " }\n";
Rewrite.getEditBuffer(ID).write(outs());
}
}
return false;
}
} // namespace format
} // namespace clang
static void PrintVersion() {
raw_ostream &OS = outs();
OS << clang::getClangToolFullVersion("clang-format") << '\n';
}
int main(int argc, const char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal();
// Hide unrelated options.
StringMap<cl::Option*> Options;
cl::getRegisteredOptions(Options);
for (StringMap<cl::Option *>::iterator I = Options.begin(), E = Options.end();
I != E; ++I) {
if (I->second->Category != &ClangFormatCategory && I->first() != "help" &&
I->first() != "version")
I->second->setHiddenFlag(cl::ReallyHidden);
}
cl::SetVersionPrinter(PrintVersion);
cl::ParseCommandLineOptions(
argc, argv,
"A tool to format C/C++/Obj-C code.\n\n"
"If no arguments are specified, it formats the code from standard input\n"
"and writes the result to the standard output.\n"
"If <file>s are given, it reformats the files. If -i is specified\n"
"together with <file>s, the files are edited in-place. Otherwise, the\n"
"result is written to the standard output.\n");
if (Help)
cl::PrintHelpMessage();
if (DumpConfig) {
std::string Config =
clang::format::configurationAsText(clang::format::getStyle(
Style, FileNames.empty() ? AssumeFilename : FileNames[0],
FallbackStyle));
llvm::outs() << Config << "\n";
return 0;
}
bool Error = false;
switch (FileNames.size()) {
case 0:
Error = clang::format::format("-");
break;
case 1:
Error = clang::format::format(FileNames[0]);
break;
default:
if (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty()) {
llvm::errs() << "error: -offset, -length and -lines can only be used for "
"single file.\n";
return 1;
}
for (unsigned i = 0; i < FileNames.size(); ++i)
Error |= clang::format::format(FileNames[i]);
break;
}
return Error ? 1 : 0;
}
|
Add the shifted cursor position to XML output, so it can be used by editor integrations.
|
Add the shifted cursor position to XML output, so it can be used by editor integrations.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@225516 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang
|
5b646886f14bbd31d51bee406fc9ba96783c72cb
|
PWG2/FEMTOSCOPY/AliFemtoUser/AliFemtoTPCInnerCorrFctn.cxx
|
PWG2/FEMTOSCOPY/AliFemtoUser/AliFemtoTPCInnerCorrFctn.cxx
|
////////////////////////////////////////////////////////////////////////////////
/// ///
/// AliFemtoTPCInnerCorrFctn - A correlation function that saves the ///
/// distance at the entrance to the TPC between two tracks as a function ///
/// of qinv ///
/// Authors: Adam Kisiel [email protected] ///
/// ///
////////////////////////////////////////////////////////////////////////////////
#include "AliFemtoTPCInnerCorrFctn.h"
//#include "AliFemtoHisto.hh"
#include <cstdio>
#ifdef __ROOT__
ClassImp(AliFemtoTPCInnerCorrFctn)
#endif
//____________________________
AliFemtoTPCInnerCorrFctn::AliFemtoTPCInnerCorrFctn(char* title, const int& nbins, const float& QinvLo, const float& QinvHi):
fDTPCNumerator(0),
fDTPCDenominator(0),
fRadDNumerator(0),
fRadDDenominator(0),
fRadius(100)
{
// set up numerator
// title = "Num Qinv (MeV/c)";
char tTitNum[100] = "NumDTPC";
strncat(tTitNum,title, 100);
fDTPCNumerator = new TH2D(tTitNum,title,nbins,QinvLo,QinvHi,100,0.0,20.0);
// set up denominator
//title = "Den Qinv (MeV/c)";
char tTitDen[100] = "DenDTPC";
strncat(tTitDen,title, 100);
fDTPCDenominator = new TH2D(tTitDen,title,nbins,QinvLo,QinvHi,100,0.0,20.0);
char tTitNumR[100] = "NumRadD";
strncat(tTitNumR,title, 100);
fRadDNumerator = new TH2D(tTitNumR,title,50,-0.1,0.1,50,-0.1,0.1);
// set up denominator
//title = "Den Qinv (MeV/c)";
char tTitDenR[100] = "DenRadD";
strncat(tTitDenR,title, 100);
fRadDDenominator = new TH2D(tTitDenR,title,50,-0.1,0.1,50,-0.1,0.1);
// to enable error bar calculation...
fDTPCNumerator->Sumw2();
fDTPCDenominator->Sumw2();
fRadDNumerator->Sumw2();
fRadDDenominator->Sumw2();
}
//____________________________
AliFemtoTPCInnerCorrFctn::AliFemtoTPCInnerCorrFctn(const AliFemtoTPCInnerCorrFctn& aCorrFctn) :
AliFemtoCorrFctn(),
fDTPCNumerator(0),
fDTPCDenominator(0),
fRadDNumerator(0),
fRadDDenominator(0),
fRadius(100)
{
// copy constructor
if (aCorrFctn.fDTPCNumerator)
fDTPCNumerator = new TH2D(*aCorrFctn.fDTPCNumerator);
if (aCorrFctn.fDTPCDenominator)
fDTPCDenominator = new TH2D(*aCorrFctn.fDTPCDenominator);
if (aCorrFctn.fRadDNumerator)
fRadDNumerator = new TH2D(*aCorrFctn.fRadDNumerator);
if (aCorrFctn.fRadDDenominator)
fRadDDenominator = new TH2D(*aCorrFctn.fRadDDenominator);
}
//____________________________
AliFemtoTPCInnerCorrFctn::~AliFemtoTPCInnerCorrFctn(){
// destructor
delete fDTPCNumerator;
delete fDTPCDenominator;
delete fRadDNumerator;
delete fRadDDenominator;
}
//_________________________
AliFemtoTPCInnerCorrFctn& AliFemtoTPCInnerCorrFctn::operator=(const AliFemtoTPCInnerCorrFctn& aCorrFctn)
{
// assignment operator
if (this == &aCorrFctn)
return *this;
if (aCorrFctn.fDTPCNumerator)
fDTPCNumerator = new TH2D(*aCorrFctn.fDTPCNumerator);
else
fDTPCNumerator = 0;
if (aCorrFctn.fDTPCDenominator)
fDTPCDenominator = new TH2D(*aCorrFctn.fDTPCDenominator);
else
fDTPCDenominator = 0;
if (aCorrFctn.fRadDNumerator)
fRadDNumerator = new TH2D(*aCorrFctn.fRadDNumerator);
else
fRadDNumerator = 0;
if (aCorrFctn.fRadDDenominator)
fRadDDenominator = new TH2D(*aCorrFctn.fRadDDenominator);
else
fRadDDenominator = 0;
fRadius = aCorrFctn.fRadius;
return *this;
}
//_________________________
void AliFemtoTPCInnerCorrFctn::Finish(){
// here is where we should normalize, fit, etc...
// we should NOT Draw() the histos (as I had done it below),
// since we want to insulate ourselves from root at this level
// of the code. Do it instead at root command line with browser.
// mShareNumerator->Draw();
//mShareDenominator->Draw();
//mRatio->Draw();
}
//____________________________
AliFemtoString AliFemtoTPCInnerCorrFctn::Report(){
// create report
string stemp = "Entrace TPC distance Correlation Function Report:\n";
char ctemp[100];
snprintf(ctemp , 100, "Number of entries in numerator:\t%E\n",fDTPCNumerator->GetEntries());
stemp += ctemp;
snprintf(ctemp , 100, "Number of entries in denominator:\t%E\n",fDTPCDenominator->GetEntries());
stemp += ctemp;
// stemp += mCoulombWeight->Report();
AliFemtoString returnThis = stemp;
return returnThis;
}
//____________________________
void AliFemtoTPCInnerCorrFctn::AddRealPair( AliFemtoPair* pair){
// add real (effect) pair
double tQinv = fabs(pair->QInv()); // note - qInv() will be negative for identical pairs...
double distx = pair->Track1()->Track()->NominalTpcEntrancePoint().x() - pair->Track2()->Track()->NominalTpcEntrancePoint().x();
double disty = pair->Track1()->Track()->NominalTpcEntrancePoint().y() - pair->Track2()->Track()->NominalTpcEntrancePoint().y();
double distz = pair->Track1()->Track()->NominalTpcEntrancePoint().z() - pair->Track2()->Track()->NominalTpcEntrancePoint().z();
double dist = sqrt(distx*distx + disty*disty + distz*distz);
fDTPCNumerator->Fill(tQinv, dist);
double phi1 = pair->Track1()->Track()->P().Phi();
double phi2 = pair->Track2()->Track()->P().Phi();
double chg1 = pair->Track1()->Track()->Charge();
double chg2 = pair->Track2()->Track()->Charge();
double ptv1 = pair->Track1()->Track()->Pt();
double ptv2 = pair->Track2()->Track()->Pt();
double eta1 = pair->Track1()->Track()->P().PseudoRapidity();
double eta2 = pair->Track2()->Track()->P().PseudoRapidity();
dist = phi2 - phi1 + TMath::ASin(-0.3 * 0.5 * chg2 * fRadius/(2*ptv2)) - TMath::ASin(-0.3 * 0.5 * chg1 * fRadius/(2*ptv1));
double etad = eta2 - eta1;
fRadDNumerator->Fill(dist, etad);
}
//____________________________
void AliFemtoTPCInnerCorrFctn::AddMixedPair( AliFemtoPair* pair){
// add mixed (background) pair
double tQinv = fabs(pair->QInv()); // note - qInv() will be negative for identical pairs...
double distx = pair->Track1()->Track()->NominalTpcEntrancePoint().x() - pair->Track2()->Track()->NominalTpcEntrancePoint().x();
double disty = pair->Track1()->Track()->NominalTpcEntrancePoint().y() - pair->Track2()->Track()->NominalTpcEntrancePoint().y();
double distz = pair->Track1()->Track()->NominalTpcEntrancePoint().z() - pair->Track2()->Track()->NominalTpcEntrancePoint().z();
double dist = sqrt(distx*distx + disty*disty + distz*distz);
fDTPCDenominator->Fill(tQinv,dist);
double phi1 = pair->Track1()->Track()->P().Phi();
double phi2 = pair->Track2()->Track()->P().Phi();
double chg1 = pair->Track1()->Track()->Charge();
double chg2 = pair->Track2()->Track()->Charge();
double ptv1 = pair->Track1()->Track()->Pt();
double ptv2 = pair->Track2()->Track()->Pt();
double eta1 = pair->Track1()->Track()->P().PseudoRapidity();
double eta2 = pair->Track2()->Track()->P().PseudoRapidity();
dist = phi2 - phi1 + TMath::ASin(-0.3 * 0.5 * chg2 * fRadius/(2*ptv2)) - TMath::ASin(-0.3 * 0.5 * chg1 * fRadius/(2*ptv1));
double etad = eta2 - eta1;
fRadDDenominator->Fill(dist, etad);
}
void AliFemtoTPCInnerCorrFctn::WriteHistos()
{
// Write out result histograms
fDTPCNumerator->Write();
fDTPCDenominator->Write();
fRadDNumerator->Write();
fRadDDenominator->Write();
}
//______________________________
TList* AliFemtoTPCInnerCorrFctn::GetOutputList()
{
// Prepare the list of objects to be written to the output
TList *tOutputList = new TList();
tOutputList->Add(fDTPCNumerator);
tOutputList->Add(fDTPCDenominator);
tOutputList->Add(fRadDNumerator);
tOutputList->Add(fRadDDenominator);
return tOutputList;
}
void AliFemtoTPCInnerCorrFctn::SetRadius(double rad)
{
fRadius = rad;
}
|
////////////////////////////////////////////////////////////////////////////////
/// ///
/// AliFemtoTPCInnerCorrFctn - A correlation function that saves the ///
/// distance at the entrance to the TPC between two tracks as a function ///
/// of qinv ///
/// Authors: Adam Kisiel [email protected] ///
/// ///
////////////////////////////////////////////////////////////////////////////////
#include "AliFemtoTPCInnerCorrFctn.h"
//#include "AliFemtoHisto.hh"
#include <cstdio>
#ifdef __ROOT__
ClassImp(AliFemtoTPCInnerCorrFctn)
#endif
//____________________________
AliFemtoTPCInnerCorrFctn::AliFemtoTPCInnerCorrFctn(char* title, const int& nbins, const float& QinvLo, const float& QinvHi):
fDTPCNumerator(0),
fDTPCDenominator(0),
fRadDNumerator(0),
fRadDDenominator(0),
fRadius(100)
{
// set up numerator
// title = "Num Qinv (MeV/c)";
char tTitNum[101] = "NumDTPC";
strncat(tTitNum,title, 100);
fDTPCNumerator = new TH2D(tTitNum,title,nbins,QinvLo,QinvHi,100,0.0,20.0);
// set up denominator
//title = "Den Qinv (MeV/c)";
char tTitDen[101] = "DenDTPC";
strncat(tTitDen,title, 100);
fDTPCDenominator = new TH2D(tTitDen,title,nbins,QinvLo,QinvHi,100,0.0,20.0);
char tTitNumR[101] = "NumRadD";
strncat(tTitNumR,title, 100);
fRadDNumerator = new TH2D(tTitNumR,title,50,-0.1,0.1,50,-0.1,0.1);
// set up denominator
//title = "Den Qinv (MeV/c)";
char tTitDenR[101] = "DenRadD";
strncat(tTitDenR,title, 100);
fRadDDenominator = new TH2D(tTitDenR,title,50,-0.1,0.1,50,-0.1,0.1);
// to enable error bar calculation...
fDTPCNumerator->Sumw2();
fDTPCDenominator->Sumw2();
fRadDNumerator->Sumw2();
fRadDDenominator->Sumw2();
}
//____________________________
AliFemtoTPCInnerCorrFctn::AliFemtoTPCInnerCorrFctn(const AliFemtoTPCInnerCorrFctn& aCorrFctn) :
AliFemtoCorrFctn(),
fDTPCNumerator(0),
fDTPCDenominator(0),
fRadDNumerator(0),
fRadDDenominator(0),
fRadius(100)
{
// copy constructor
if (aCorrFctn.fDTPCNumerator)
fDTPCNumerator = new TH2D(*aCorrFctn.fDTPCNumerator);
if (aCorrFctn.fDTPCDenominator)
fDTPCDenominator = new TH2D(*aCorrFctn.fDTPCDenominator);
if (aCorrFctn.fRadDNumerator)
fRadDNumerator = new TH2D(*aCorrFctn.fRadDNumerator);
if (aCorrFctn.fRadDDenominator)
fRadDDenominator = new TH2D(*aCorrFctn.fRadDDenominator);
}
//____________________________
AliFemtoTPCInnerCorrFctn::~AliFemtoTPCInnerCorrFctn(){
// destructor
delete fDTPCNumerator;
delete fDTPCDenominator;
delete fRadDNumerator;
delete fRadDDenominator;
}
//_________________________
AliFemtoTPCInnerCorrFctn& AliFemtoTPCInnerCorrFctn::operator=(const AliFemtoTPCInnerCorrFctn& aCorrFctn)
{
// assignment operator
if (this == &aCorrFctn)
return *this;
if (aCorrFctn.fDTPCNumerator)
fDTPCNumerator = new TH2D(*aCorrFctn.fDTPCNumerator);
else
fDTPCNumerator = 0;
if (aCorrFctn.fDTPCDenominator)
fDTPCDenominator = new TH2D(*aCorrFctn.fDTPCDenominator);
else
fDTPCDenominator = 0;
if (aCorrFctn.fRadDNumerator)
fRadDNumerator = new TH2D(*aCorrFctn.fRadDNumerator);
else
fRadDNumerator = 0;
if (aCorrFctn.fRadDDenominator)
fRadDDenominator = new TH2D(*aCorrFctn.fRadDDenominator);
else
fRadDDenominator = 0;
fRadius = aCorrFctn.fRadius;
return *this;
}
//_________________________
void AliFemtoTPCInnerCorrFctn::Finish(){
// here is where we should normalize, fit, etc...
// we should NOT Draw() the histos (as I had done it below),
// since we want to insulate ourselves from root at this level
// of the code. Do it instead at root command line with browser.
// mShareNumerator->Draw();
//mShareDenominator->Draw();
//mRatio->Draw();
}
//____________________________
AliFemtoString AliFemtoTPCInnerCorrFctn::Report(){
// create report
string stemp = "Entrace TPC distance Correlation Function Report:\n";
char ctemp[100];
snprintf(ctemp , 100, "Number of entries in numerator:\t%E\n",fDTPCNumerator->GetEntries());
stemp += ctemp;
snprintf(ctemp , 100, "Number of entries in denominator:\t%E\n",fDTPCDenominator->GetEntries());
stemp += ctemp;
// stemp += mCoulombWeight->Report();
AliFemtoString returnThis = stemp;
return returnThis;
}
//____________________________
void AliFemtoTPCInnerCorrFctn::AddRealPair( AliFemtoPair* pair){
// add real (effect) pair
if (fPairCut)
if (!fPairCut->Pass(pair)) return;
double pih = TMath::Pi();
double pit = TMath::Pi()*2;
double tQinv = fabs(pair->QInv()); // note - qInv() will be negative for identical pairs...
double distx = pair->Track1()->Track()->NominalTpcEntrancePoint().x() - pair->Track2()->Track()->NominalTpcEntrancePoint().x();
double disty = pair->Track1()->Track()->NominalTpcEntrancePoint().y() - pair->Track2()->Track()->NominalTpcEntrancePoint().y();
double distz = pair->Track1()->Track()->NominalTpcEntrancePoint().z() - pair->Track2()->Track()->NominalTpcEntrancePoint().z();
double dist = sqrt(distx*distx + disty*disty + distz*distz);
fDTPCNumerator->Fill(tQinv, dist);
if (tQinv < 0.1) {
double phi1 = pair->Track1()->Track()->P().Phi();
double phi2 = pair->Track2()->Track()->P().Phi();
double chg1 = pair->Track1()->Track()->Charge();
double chg2 = pair->Track2()->Track()->Charge();
double ptv1 = pair->Track1()->Track()->Pt();
double ptv2 = pair->Track2()->Track()->Pt();
double eta1 = pair->Track1()->Track()->P().PseudoRapidity();
double eta2 = pair->Track2()->Track()->P().PseudoRapidity();
double arg1 = -0.3 * 0.5 * chg1 * fRadius/(2*ptv1);
double arg2 = -0.3 * 0.5 * chg2 * fRadius/(2*ptv2);
double phid = phi2 - phi1 + TMath::ASin(arg2) - TMath::ASin(arg1);
while (phid>pih) phid -= pit;
while (phid<-pih) phid += pit;
// dist = phi2 - phi1 + TMath::ASin(-0.3 * 0.5 * chg2 * fRadius/(2*ptv2)) - TMath::ASin(-0.3 * 0.5 * chg1 * fRadius/(2*ptv1));
double etad = eta2 - eta1;
fRadDNumerator->Fill(phid, etad);
}
}
//____________________________
void AliFemtoTPCInnerCorrFctn::AddMixedPair( AliFemtoPair* pair){
// add mixed (background) pair
if (fPairCut)
if (!fPairCut->Pass(pair)) return;
double pih = TMath::Pi();
double pit = TMath::Pi()*2;
double tQinv = fabs(pair->QInv()); // note - qInv() will be negative for identical pairs...
double distx = pair->Track1()->Track()->NominalTpcEntrancePoint().x() - pair->Track2()->Track()->NominalTpcEntrancePoint().x();
double disty = pair->Track1()->Track()->NominalTpcEntrancePoint().y() - pair->Track2()->Track()->NominalTpcEntrancePoint().y();
double distz = pair->Track1()->Track()->NominalTpcEntrancePoint().z() - pair->Track2()->Track()->NominalTpcEntrancePoint().z();
double dist = sqrt(distx*distx + disty*disty + distz*distz);
fDTPCDenominator->Fill(tQinv,dist);
if (tQinv < 0.1) {
double phi1 = pair->Track1()->Track()->P().Phi();
double phi2 = pair->Track2()->Track()->P().Phi();
double chg1 = pair->Track1()->Track()->Charge();
double chg2 = pair->Track2()->Track()->Charge();
double ptv1 = pair->Track1()->Track()->Pt();
double ptv2 = pair->Track2()->Track()->Pt();
double eta1 = pair->Track1()->Track()->P().PseudoRapidity();
double eta2 = pair->Track2()->Track()->P().PseudoRapidity();
double arg1 = -0.3 * 0.5 * chg1 * fRadius/(2*ptv1);
double arg2 = -0.3 * 0.5 * chg2 * fRadius/(2*ptv2);
double phid = phi2 - phi1 + TMath::ASin(arg2) - TMath::ASin(arg1);
while (phid>pih) phid -= pit;
while (phid<-pih) phid += pit;
// dist = phi2 - phi1 + TMath::ASin(-0.3 * 0.5 * chg2 * fRadius/(2*ptv2)) - TMath::ASin(-0.3 * 0.5 * chg1 * fRadius/(2*ptv1));
double etad = eta2 - eta1;
fRadDDenominator->Fill(phid, etad);
}
}
void AliFemtoTPCInnerCorrFctn::WriteHistos()
{
// Write out result histograms
fDTPCNumerator->Write();
fDTPCDenominator->Write();
fRadDNumerator->Write();
fRadDDenominator->Write();
}
//______________________________
TList* AliFemtoTPCInnerCorrFctn::GetOutputList()
{
// Prepare the list of objects to be written to the output
TList *tOutputList = new TList();
tOutputList->Add(fDTPCNumerator);
tOutputList->Add(fDTPCDenominator);
tOutputList->Add(fRadDNumerator);
tOutputList->Add(fRadDDenominator);
return tOutputList;
}
void AliFemtoTPCInnerCorrFctn::SetRadius(double rad)
{
fRadius = rad;
}
|
Fix Coverity reports, new phistar calculation
|
Fix Coverity reports, new phistar calculation
|
C++
|
bsd-3-clause
|
miranov25/AliRoot,jgrosseo/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,alisw/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,alisw/AliRoot,shahor02/AliRoot,shahor02/AliRoot,alisw/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,jgrosseo/AliRoot,shahor02/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,miranov25/AliRoot,sebaleh/AliRoot,alisw/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,ALICEHLT/AliRoot,sebaleh/AliRoot,jgrosseo/AliRoot,jgrosseo/AliRoot,sebaleh/AliRoot,alisw/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,coppedis/AliRoot,alisw/AliRoot,miranov25/AliRoot,miranov25/AliRoot,jgrosseo/AliRoot,shahor02/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,ecalvovi/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,shahor02/AliRoot,shahor02/AliRoot,alisw/AliRoot,miranov25/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,sebaleh/AliRoot,mkrzewic/AliRoot
|
cf1fd792e1ba17215174f678b4de0d2487d82a2f
|
PWGCF/FEMTOSCOPY/AliFemtoUser/AliFemtoCorrFctnPtKstar.cxx
|
PWGCF/FEMTOSCOPY/AliFemtoUser/AliFemtoCorrFctnPtKstar.cxx
|
////////////////////////////////////////////////////////////////////////////////
// //
// AliFemtoCorrFctnPtKstar - A correlation function that analyzes //
// two particle mass minvariant with various mass assumptions //
// //
// Authors: Małgorzata Janik [email protected]
// //
////////////////////////////////////////////////////////////////////////////////
#include "AliFemtoCorrFctnPtKstar.h"
#include <cstdio>
#include <TMath.h>
#ifdef __ROOT__
ClassImp(AliFemtoCorrFctnPtKstar)
#endif
//____________________________
AliFemtoCorrFctnPtKstar::AliFemtoCorrFctnPtKstar(const char* title):
AliFemtoCorrFctn(),
fPtKstar(0),
fPtKstarDen(0),
fPtKstar2part(0),
fPtKstarDen2part(0),
fPairPtKstar2part(0),
fPairPtKstarDen2part(0),
fKstarBetaT(0)
{
fPtKstar = new TH2D(Form("PtvsKstar1part%s",title),"Pt vs kstar (part 1)",200,0.0,2.0, 200, 0.0, 4.0);
fPtKstarDen = new TH2D(Form("PtvsKstarDen1part%s",title),"Pt vs kstar in mixed events (part 1)",200,0.0,2.0, 200, 0.0, 4.0);
fPtKstar2part = new TH2D(Form("PtvsKstar2part%s",title),"Pt vs kstar (part 2)",200,0.0,2.0, 200, 0.0, 4.0);
fPtKstarDen2part = new TH2D(Form("PtvsKstarDen2part%s",title),"Pt vs kstar in mixed events (part 2)",200,0.0,2.0, 200, 0.0, 4.0);
fPairPtKstar2part = new TH2D(Form("PairPtvsKstar%s",title),"Pair Pt vs kstar ",100,0.0,0.5, 300, 0.0, 6.0);
fPairPtKstarDen2part = new TH2D(Form("PairPtvsKstarDen%s",title),"Pair Pt vs kstar in mixed events ",100,0.0,0.5, 300, 0.0, 6.0);
fKstarBetaT = new TH2D(Form("KstarvsBetaT%s",title),"kstar vs BetaT ",100,0.0,0.5, 30, 0.0, 3.0);
}
//____________________________
AliFemtoCorrFctnPtKstar::AliFemtoCorrFctnPtKstar(const AliFemtoCorrFctnPtKstar& aCorrFctn) :
AliFemtoCorrFctn(),
fPtKstar(0),
fPtKstarDen(0),
fPtKstar2part(0),
fPtKstarDen2part(0),
fPairPtKstar2part(0),
fPairPtKstarDen2part(0),
fKstarBetaT(0)
{
// copy constructor
if (fPtKstar) delete fPtKstar;
fPtKstar = new TH2D(*aCorrFctn.fPtKstar);
if (fPtKstarDen) delete fPtKstarDen;
fPtKstarDen = new TH2D(*aCorrFctn.fPtKstarDen);
}
//____________________________
AliFemtoCorrFctnPtKstar::~AliFemtoCorrFctnPtKstar(){
// destructor
delete fPtKstar;
delete fPtKstarDen;
delete fPtKstar2part;
delete fPtKstarDen2part;
delete fPairPtKstar2part;
delete fPairPtKstarDen2part;
delete fKstarBetaT;
}
//_________________________
AliFemtoCorrFctnPtKstar& AliFemtoCorrFctnPtKstar::operator=(const AliFemtoCorrFctnPtKstar& aCorrFctn)
{
// assignment operator
if (this == &aCorrFctn)
return *this;
if (fPtKstar) delete fPtKstar;
fPtKstar = new TH2D(*aCorrFctn.fPtKstar);
if (fPtKstarDen) delete fPtKstarDen;
fPtKstarDen = new TH2D(*aCorrFctn.fPtKstarDen);
if (fPtKstar2part) delete fPtKstar2part;
fPtKstar2part = new TH2D(*aCorrFctn.fPtKstar2part);
if (fPtKstarDen2part) delete fPtKstarDen2part;
fPtKstarDen2part = new TH2D(*aCorrFctn.fPtKstarDen2part);
if (fPairPtKstar2part) delete fPairPtKstar2part;
fPairPtKstar2part = new TH2D(*aCorrFctn.fPairPtKstar2part);
if (fPairPtKstarDen2part) delete fPairPtKstarDen2part;
fPairPtKstarDen2part = new TH2D(*aCorrFctn.fPairPtKstarDen2part);
if(fKstarBetaT) delete fKstarBetaT;
fKstarBetaT = new TH2D(*aCorrFctn.fKstarBetaT);
return *this;
}
//_________________________
void AliFemtoCorrFctnPtKstar::Finish(){
// here is where we should normalize, fit, etc...
// we should NOT Draw() the histos (as I had done it below),
// since we want to insulate ourselves from root at this level
// of the code. Do it instead at root command line with browser.
// mShareNumerator->Draw();
//mShareDenominator->Draw();
//mRatio->Draw();
}
//____________________________
AliFemtoString AliFemtoCorrFctnPtKstar::Report(){
// create report
string stemp = "Kstar vs Pt Monitor Report\n";
AliFemtoString returnThis = stemp;
return returnThis;
}
//____________________________
void AliFemtoCorrFctnPtKstar::AddRealPair( AliFemtoPair* pair){
double tKStar = fabs(pair->KStar());
double tPairPt = fabs(pair->KT());
double px = pair->Track1()->Track()->P().x();
double py = pair->Track1()->Track()->P().y();
double pT = TMath::Hypot(px, py);
fPtKstar->Fill(tKStar,pT);
double px2 = pair->Track2()->Track()->P().x();
double py2 = pair->Track2()->Track()->P().y();
double pT2 = TMath::Hypot(px2, py2);
fPtKstar2part->Fill(tKStar,pT2);
fPairPtKstar2part->Fill(tKStar,tPairPt);
//--------Pritam's addition----------
//--------Taken from AliFemtoBetaTPairCut.cxx
// Calculate transverse momentum of the pair:
double px1 = pair->Track1()->Track()->P().x();
double px2 = pair->Track2()->Track()->P().x();
double py1 = pair->Track1()->Track()->P().y();
double py2 = pair->Track2()->Track()->P().y();
double pxpair = px1 + px2;
double pypair = py1 + py2;
double pTpair = TMath::Sqrt(pxpair*pxpair + pypair*pypair);
// Calculate energies of particles:
double pz1 = pair->Track1()->Track()->P().z();
double pz2 = pair->Track2()->Track()->P().z();
double pzpair = pz1 + pz2;
double p1 = TMath::Sqrt(px1*px1 + py1*py1 + pz1*pz1);
double p2 = TMath::Sqrt(px2*px2 + py2*py2 + pz2*pz2);
double m1 = fMassPart1;
double m2 = fMassPart2;
double e1 = TMath::Sqrt(p1*p1 + m1*m1);
double e2 = TMath::Sqrt(p2*p2 + m2*m2);
// Calculate transverse mass of the pair:
double mInvpair_2 = m1*m1 + m2*m2 + 2*(e1*e2 - px1*px2 - py1*py2 - pz1*pz2);
double mTpair = TMath::Sqrt(mInvpair_2 + pTpair*pTpair);
// Calculate betaT:
double betaT = pTpair / mTpair;
fKstarBetaT->Fill(tKStar,betaT);
}
//____________________________
void AliFemtoCorrFctnPtKstar::AddMixedPair( AliFemtoPair* pair){
double tKStar = fabs(pair->KStar());
double tPairPt = fabs(pair->KT());
double px = pair->Track1()->Track()->P().x();
double py = pair->Track1()->Track()->P().y();
double pT = TMath::Hypot(px, py);
fPtKstarDen->Fill(tKStar,pT);
fPairPtKstarDen2part->Fill(tKStar,tPairPt);
double px2 = pair->Track2()->Track()->P().x();
double py2 = pair->Track2()->Track()->P().y();
double pT2 = TMath::Hypot(px2, py2);
fPtKstarDen2part->Fill(tKStar,pT2);
}
//____________________________
void AliFemtoCorrFctnPtKstar::WriteHistos()
{
// Write out result histograms
fPtKstar->Write();
fPtKstarDen->Write();
fPtKstar2part->Write();
fPtKstarDen2part->Write();
fPairPtKstar2part->Write();
fPairPtKstarDen2part->Write();
fKstarBetaT->Write();
}
TList* AliFemtoCorrFctnPtKstar::GetOutputList()
{
// Prepare the list of objects to be written to the output
TList *tOutputList = new TList();
tOutputList->Add(fPtKstar);
tOutputList->Add(fPtKstarDen);
tOutputList->Add(fPtKstar2part);
tOutputList->Add(fPtKstarDen2part);
tOutputList->Add(fPairPtKstar2part);
tOutputList->Add(fPairPtKstarDen2part);
tOutputList->Add(fKstarBetaT);
return tOutputList;
}
|
////////////////////////////////////////////////////////////////////////////////
// //
// AliFemtoCorrFctnPtKstar - A correlation function that analyzes //
// two particle mass minvariant with various mass assumptions //
// //
// Authors: Małgorzata Janik [email protected]
// //
////////////////////////////////////////////////////////////////////////////////
#include "AliFemtoCorrFctnPtKstar.h"
#include <cstdio>
#include <TMath.h>
#ifdef __ROOT__
ClassImp(AliFemtoCorrFctnPtKstar)
#endif
//____________________________
AliFemtoCorrFctnPtKstar::AliFemtoCorrFctnPtKstar(const char* title):
AliFemtoCorrFctn(),
fPtKstar(0),
fPtKstarDen(0),
fPtKstar2part(0),
fPtKstarDen2part(0),
fPairPtKstar2part(0),
fPairPtKstarDen2part(0),
fKstarBetaT(0)
{
fPtKstar = new TH2D(Form("PtvsKstar1part%s",title),"Pt vs kstar (part 1)",200,0.0,2.0, 200, 0.0, 4.0);
fPtKstarDen = new TH2D(Form("PtvsKstarDen1part%s",title),"Pt vs kstar in mixed events (part 1)",200,0.0,2.0, 200, 0.0, 4.0);
fPtKstar2part = new TH2D(Form("PtvsKstar2part%s",title),"Pt vs kstar (part 2)",200,0.0,2.0, 200, 0.0, 4.0);
fPtKstarDen2part = new TH2D(Form("PtvsKstarDen2part%s",title),"Pt vs kstar in mixed events (part 2)",200,0.0,2.0, 200, 0.0, 4.0);
fPairPtKstar2part = new TH2D(Form("PairPtvsKstar%s",title),"Pair Pt vs kstar ",100,0.0,0.5, 300, 0.0, 6.0);
fPairPtKstarDen2part = new TH2D(Form("PairPtvsKstarDen%s",title),"Pair Pt vs kstar in mixed events ",100,0.0,0.5, 300, 0.0, 6.0);
fKstarBetaT = new TH2D(Form("KstarvsBetaT%s",title),"kstar vs BetaT ",100,0.0,0.5, 30, 0.0, 3.0);
}
//____________________________
AliFemtoCorrFctnPtKstar::AliFemtoCorrFctnPtKstar(const AliFemtoCorrFctnPtKstar& aCorrFctn) :
AliFemtoCorrFctn(),
fPtKstar(0),
fPtKstarDen(0),
fPtKstar2part(0),
fPtKstarDen2part(0),
fPairPtKstar2part(0),
fPairPtKstarDen2part(0),
fKstarBetaT(0)
{
// copy constructor
if (fPtKstar) delete fPtKstar;
fPtKstar = new TH2D(*aCorrFctn.fPtKstar);
if (fPtKstarDen) delete fPtKstarDen;
fPtKstarDen = new TH2D(*aCorrFctn.fPtKstarDen);
}
//____________________________
AliFemtoCorrFctnPtKstar::~AliFemtoCorrFctnPtKstar(){
// destructor
delete fPtKstar;
delete fPtKstarDen;
delete fPtKstar2part;
delete fPtKstarDen2part;
delete fPairPtKstar2part;
delete fPairPtKstarDen2part;
delete fKstarBetaT;
}
//_________________________
AliFemtoCorrFctnPtKstar& AliFemtoCorrFctnPtKstar::operator=(const AliFemtoCorrFctnPtKstar& aCorrFctn)
{
// assignment operator
if (this == &aCorrFctn)
return *this;
if (fPtKstar) delete fPtKstar;
fPtKstar = new TH2D(*aCorrFctn.fPtKstar);
if (fPtKstarDen) delete fPtKstarDen;
fPtKstarDen = new TH2D(*aCorrFctn.fPtKstarDen);
if (fPtKstar2part) delete fPtKstar2part;
fPtKstar2part = new TH2D(*aCorrFctn.fPtKstar2part);
if (fPtKstarDen2part) delete fPtKstarDen2part;
fPtKstarDen2part = new TH2D(*aCorrFctn.fPtKstarDen2part);
if (fPairPtKstar2part) delete fPairPtKstar2part;
fPairPtKstar2part = new TH2D(*aCorrFctn.fPairPtKstar2part);
if (fPairPtKstarDen2part) delete fPairPtKstarDen2part;
fPairPtKstarDen2part = new TH2D(*aCorrFctn.fPairPtKstarDen2part);
if(fKstarBetaT) delete fKstarBetaT;
fKstarBetaT = new TH2D(*aCorrFctn.fKstarBetaT);
return *this;
}
//_________________________
void AliFemtoCorrFctnPtKstar::Finish(){
// here is where we should normalize, fit, etc...
// we should NOT Draw() the histos (as I had done it below),
// since we want to insulate ourselves from root at this level
// of the code. Do it instead at root command line with browser.
// mShareNumerator->Draw();
//mShareDenominator->Draw();
//mRatio->Draw();
}
//____________________________
AliFemtoString AliFemtoCorrFctnPtKstar::Report(){
// create report
string stemp = "Kstar vs Pt Monitor Report\n";
AliFemtoString returnThis = stemp;
return returnThis;
}
//____________________________
void AliFemtoCorrFctnPtKstar::AddRealPair( AliFemtoPair* pair){
double tKStar = fabs(pair->KStar());
double tPairPt = fabs(pair->KT());
double px = pair->Track1()->Track()->P().x();
double py = pair->Track1()->Track()->P().y();
double pT = TMath::Hypot(px, py);
fPtKstar->Fill(tKStar,pT);
double px2 = pair->Track2()->Track()->P().x();
double py2 = pair->Track2()->Track()->P().y();
double pT2 = TMath::Hypot(px2, py2);
fPtKstar2part->Fill(tKStar,pT2);
fPairPtKstar2part->Fill(tKStar,tPairPt);
//--------Pritam's addition----------
//--------Taken from AliFemtoBetaTPairCut.cxx
// Calculate transverse momentum of the pair:
double px1 = pair->Track1()->Track()->P().x();
double px22 = pair->Track2()->Track()->P().x();
double py1 = pair->Track1()->Track()->P().y();
double py22 = pair->Track2()->Track()->P().y();
double pxpair = px1 + px22;
double pypair = py1 + py22;
double pTpair = TMath::Sqrt(pxpair*pxpair + pypair*pypair);
// Calculate energies of particles:
double pz1 = pair->Track1()->Track()->P().z();
double pz2 = pair->Track2()->Track()->P().z();
double pzpair = pz1 + pz2;
double p1 = TMath::Sqrt(px1*px1 + py1*py1 + pz1*pz1);
double p2 = TMath::Sqrt(px2*px2 + py2*py2 + pz2*pz2);
double m1 = 0.13957; //pion mass
double m2 = 0.493677; //kaon mass
double e1 = TMath::Sqrt(p1*p1 + m1*m1);
double e2 = TMath::Sqrt(p2*p2 + m2*m2);
// Calculate transverse mass of the pair:
double mInvpair_2 = m1*m1 + m2*m2 + 2*(e1*e2 - px1*px2 - py1*py2 - pz1*pz2);
double mTpair = TMath::Sqrt(mInvpair_2 + pTpair*pTpair);
// Calculate betaT:
double betaT = pTpair / mTpair;
fKstarBetaT->Fill(tKStar,betaT);
}
//____________________________
void AliFemtoCorrFctnPtKstar::AddMixedPair( AliFemtoPair* pair){
double tKStar = fabs(pair->KStar());
double tPairPt = fabs(pair->KT());
double px = pair->Track1()->Track()->P().x();
double py = pair->Track1()->Track()->P().y();
double pT = TMath::Hypot(px, py);
fPtKstarDen->Fill(tKStar,pT);
fPairPtKstarDen2part->Fill(tKStar,tPairPt);
double px2 = pair->Track2()->Track()->P().x();
double py2 = pair->Track2()->Track()->P().y();
double pT2 = TMath::Hypot(px2, py2);
fPtKstarDen2part->Fill(tKStar,pT2);
}
//____________________________
void AliFemtoCorrFctnPtKstar::WriteHistos()
{
// Write out result histograms
fPtKstar->Write();
fPtKstarDen->Write();
fPtKstar2part->Write();
fPtKstarDen2part->Write();
fPairPtKstar2part->Write();
fPairPtKstarDen2part->Write();
fKstarBetaT->Write();
}
TList* AliFemtoCorrFctnPtKstar::GetOutputList()
{
// Prepare the list of objects to be written to the output
TList *tOutputList = new TList();
tOutputList->Add(fPtKstar);
tOutputList->Add(fPtKstarDen);
tOutputList->Add(fPtKstar2part);
tOutputList->Add(fPtKstarDen2part);
tOutputList->Add(fPairPtKstar2part);
tOutputList->Add(fPairPtKstarDen2part);
tOutputList->Add(fKstarBetaT);
return tOutputList;
}
|
Update AliFemtoCorrFctnPtKstar.cxx
|
Update AliFemtoCorrFctnPtKstar.cxx
|
C++
|
bsd-3-clause
|
adriansev/AliPhysics,AMechler/AliPhysics,fcolamar/AliPhysics,pchrista/AliPhysics,AMechler/AliPhysics,fcolamar/AliPhysics,victor-gonzalez/AliPhysics,nschmidtALICE/AliPhysics,adriansev/AliPhysics,pchrista/AliPhysics,victor-gonzalez/AliPhysics,rbailhac/AliPhysics,pchrista/AliPhysics,adriansev/AliPhysics,AMechler/AliPhysics,adriansev/AliPhysics,rihanphys/AliPhysics,alisw/AliPhysics,nschmidtALICE/AliPhysics,nschmidtALICE/AliPhysics,AMechler/AliPhysics,victor-gonzalez/AliPhysics,alisw/AliPhysics,mpuccio/AliPhysics,adriansev/AliPhysics,amaringarcia/AliPhysics,mpuccio/AliPhysics,nschmidtALICE/AliPhysics,rihanphys/AliPhysics,alisw/AliPhysics,pchrista/AliPhysics,nschmidtALICE/AliPhysics,rihanphys/AliPhysics,rbailhac/AliPhysics,rbailhac/AliPhysics,mpuccio/AliPhysics,victor-gonzalez/AliPhysics,fcolamar/AliPhysics,fcolamar/AliPhysics,rihanphys/AliPhysics,AMechler/AliPhysics,pchrista/AliPhysics,mpuccio/AliPhysics,alisw/AliPhysics,adriansev/AliPhysics,amaringarcia/AliPhysics,alisw/AliPhysics,fcolamar/AliPhysics,amaringarcia/AliPhysics,nschmidtALICE/AliPhysics,adriansev/AliPhysics,rbailhac/AliPhysics,fcolamar/AliPhysics,mpuccio/AliPhysics,victor-gonzalez/AliPhysics,amaringarcia/AliPhysics,rbailhac/AliPhysics,rbailhac/AliPhysics,victor-gonzalez/AliPhysics,AMechler/AliPhysics,alisw/AliPhysics,nschmidtALICE/AliPhysics,fcolamar/AliPhysics,rihanphys/AliPhysics,pchrista/AliPhysics,rbailhac/AliPhysics,victor-gonzalez/AliPhysics,amaringarcia/AliPhysics,amaringarcia/AliPhysics,AMechler/AliPhysics,mpuccio/AliPhysics,pchrista/AliPhysics,amaringarcia/AliPhysics,alisw/AliPhysics,rihanphys/AliPhysics,rihanphys/AliPhysics,mpuccio/AliPhysics
|
3464fb4d943d4be3314c642fa37a84369cd89751
|
code/ylikuutio/ontology/camera.hpp
|
code/ylikuutio/ontology/camera.hpp
|
#ifndef __CAMERA_HPP_INCLUDED
#define __CAMERA_HPP_INCLUDED
#include "movable.hpp"
#include "universe.hpp"
#include "camera_struct.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <cstddef> // std::size_t
#include <memory> // std::make_shared, std::shared_ptr
#include <queue> // std::queue
#include <string> // std::string
#include <vector> // std::vector
namespace yli
{
namespace ontology
{
class Universe;
class Camera: public yli::ontology::Movable
{
public:
Camera(yli::ontology::Universe* const universe, const CameraStruct& camera_struct)
: Movable(universe, camera_struct.cartesian_coordinates)
{
// constructor.
this->horizontal_angle = camera_struct.horizontal_angle;
this->vertical_angle = camera_struct.vertical_angle;
// variables related to the projection.
this->projection_matrix = glm::mat4(1.0f); // identity matrix (dummy value).
this->view_matrix = glm::mat4(1.0f); // identity matrix (dummy value).
this->parent = camera_struct.parent;
// Get `childID` from the `Scene` and set pointer to this `Camera`.
this->bind_to_parent();
// `yli::ontology::Entity` member variables begin here.
this->type_string = "yli::ontology::Camera*";
}
// destructor.
virtual ~Camera();
yli::ontology::Entity* get_parent() const override;
const glm::vec3& get_direction() const;
const glm::vec3& get_up() const;
const glm::vec3& get_right() const;
void adjust_horizontal_angle(float adjustment);
glm::mat4& get_projection_matrix();
glm::mat4& get_view_matrix();
float get_horizontal_angle() const;
float get_vertical_angle() const;
std::size_t get_number_of_children() const override;
std::size_t get_number_of_descendants() const override;
friend class Universe;
template<class T1>
friend void yli::hierarchy::bind_child_to_parent(T1 child_pointer, std::vector<T1>& child_pointer_vector, std::queue<std::size_t>& free_childID_queue, std::size_t& number_of_children);
private:
void bind_to_parent();
bool compute_and_update_matrices_from_inputs();
// variables related to location and orientation.
yli::ontology::Scene* parent;
// variables related to the projection.
glm::mat4 projection_matrix;
glm::mat4 view_matrix;
double horizontal_angle;
double vertical_angle;
};
}
}
#endif
|
#ifndef __CAMERA_HPP_INCLUDED
#define __CAMERA_HPP_INCLUDED
#include "movable.hpp"
#include "universe.hpp"
#include "camera_struct.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <cstddef> // std::size_t
#include <memory> // std::make_shared, std::shared_ptr
#include <queue> // std::queue
#include <string> // std::string
#include <vector> // std::vector
namespace yli
{
namespace ontology
{
class Universe;
class Camera: public yli::ontology::Movable
{
public:
Camera(yli::ontology::Universe* const universe, const CameraStruct& camera_struct)
: Movable(universe, camera_struct.cartesian_coordinates)
{
// constructor.
this->horizontal_angle = camera_struct.horizontal_angle;
this->vertical_angle = camera_struct.vertical_angle;
// variables related to the projection.
this->projection_matrix = glm::mat4(1.0f); // identity matrix (dummy value).
this->view_matrix = glm::mat4(1.0f); // identity matrix (dummy value).
this->parent = camera_struct.parent;
// Get `childID` from the `Scene` and set pointer to this `Camera`.
this->bind_to_parent();
// `yli::ontology::Entity` member variables begin here.
this->type_string = "yli::ontology::Camera*";
}
Camera(const Camera&) = delete; // Delete copy constructor.
Camera &operator=(const Camera&) = delete; // Delete copy assignment.
// destructor.
virtual ~Camera();
yli::ontology::Entity* get_parent() const override;
const glm::vec3& get_direction() const;
const glm::vec3& get_up() const;
const glm::vec3& get_right() const;
void adjust_horizontal_angle(float adjustment);
glm::mat4& get_projection_matrix();
glm::mat4& get_view_matrix();
float get_horizontal_angle() const;
float get_vertical_angle() const;
std::size_t get_number_of_children() const override;
std::size_t get_number_of_descendants() const override;
friend class Universe;
template<class T1>
friend void yli::hierarchy::bind_child_to_parent(T1 child_pointer, std::vector<T1>& child_pointer_vector, std::queue<std::size_t>& free_childID_queue, std::size_t& number_of_children);
private:
void bind_to_parent();
bool compute_and_update_matrices_from_inputs();
// variables related to location and orientation.
yli::ontology::Scene* parent;
// variables related to the projection.
glm::mat4 projection_matrix;
glm::mat4 view_matrix;
double horizontal_angle;
double vertical_angle;
};
}
}
#endif
|
delete copy constructor and copy assignment.
|
`yli::ontology::Camera`: delete copy constructor and copy assignment.
|
C++
|
agpl-3.0
|
nrz/ylikuutio,nrz/ylikuutio,nrz/ylikuutio,nrz/ylikuutio
|
354269abf3d08e4af52b1b38f1865f0c50595ca9
|
src/uoj348241.cpp
|
src/uoj348241.cpp
|
#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);
int count=0;
void dfs(int n,int p[],int a[],int cur){
if(cur==n){
REP(i,0,n-1){
cout<<a[i];
}
cout<<endl;
count++;
}else{
REP(i,0,n-1){
a[cur]=p[i];
dfs(n,p,a,cur+1)
}
}
}
void Init(){
return ;
}
void Solve(){
int p[]={1,2,3,4};
int a[800];
dfs(4,p,a,0);
return ;
}
int main(){
freopen("uoj348241.in","r",stdin);
int T;
scanf("%d",&T);
while(T--)
Init(),Solve();
return 0;
}
|
#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);
int cou=0;
void dfs(int n,int p[],int a[],int cur){
if(cur==n){
REP(i,0,n-1){
cout<<a[i];
}
cout<<endl;
cou++;
}else{
REP(i,0,n-1){
a[cur]=p[i];
dfs(n,p,a,cur+1);
}
}
}
void Init(){
return ;
}
void Solve(){
int p[]={1,2,3,4};
int a[800];
dfs(4,p,a,0);
return ;
}
int main(){
freopen("uoj348241.in","r",stdin);
int T;
scanf("%d",&T);
while(T--)
Init(),Solve();
return 0;
}
|
update uoj348241
|
update uoj348241
|
C++
|
mit
|
czfshine/my_oj,czfshine/my_oj,czfshine/my_oj,czfshine/my_oj
|
1f028371a9b3917f038d6047d526e24a7944b147
|
src/utils/md5.hpp
|
src/utils/md5.hpp
|
// Copyright (C) 2016 xaizek <[email protected]>
//
// This file is part of uncov.
//
// uncov 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.
//
// uncov is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with uncov. If not, see <http://www.gnu.org/licenses/>.
#ifndef UNCOV__UTILS__MD5_HPP__
#define UNCOV__UTILS__MD5_HPP__
#include <string>
std::string md5(const std::string &str);
#endif // UNCOV__UTILS__MD5_HPP__
|
// Copyright (C) 2016 xaizek <[email protected]>
//
// This file is part of uncov.
//
// uncov 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.
//
// uncov is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with uncov. If not, see <http://www.gnu.org/licenses/>.
#ifndef UNCOV__UTILS__MD5_HPP__
#define UNCOV__UTILS__MD5_HPP__
#include <string>
/**
* @file md5.hpp
*
* @brief A third-party implementation of MD5 algorithm.
*/
/**
* @brief Computes hash of the string.
*
* @param str String to hash.
*
* @returns MD5 hash of the string.
*/
std::string md5(const std::string &str);
#endif // UNCOV__UTILS__MD5_HPP__
|
Document utils/md5.hpp header
|
Document utils/md5.hpp header
|
C++
|
agpl-3.0
|
xaizek/uncov,xaizek/uncov,xaizek/uncov,xaizek/uncov,xaizek/uncov
|
fb359fc981f048328bee206fbcf69f2218ae1ee0
|
training/unicharset_extractor.cpp
|
training/unicharset_extractor.cpp
|
///////////////////////////////////////////////////////////////////////
// File: unicharset_extractor.cpp
// Description: Unicode character/ligature set extractor.
// Author: Thomas Kielbus
// Created: Wed Jun 28 17:05:01 PDT 2006
//
// (C) Copyright 2006, Google 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.
//
///////////////////////////////////////////////////////////////////////
// Given a list of box files or text files on the command line, this program
// normalizes the text according to command-line options and generates
// a unicharset.
#include <cstdlib>
#include "boxread.h"
#include "commandlineflags.h"
#include "genericvector.h"
#include "lang_model_helpers.h"
#include "normstrngs.h"
#include "strngs.h"
#include "tprintf.h"
#include "unicharset.h"
#include "unicharset_training_utils.h"
STRING_PARAM_FLAG(output_unicharset, "unicharset", "Output file path");
INT_PARAM_FLAG(norm_mode, 1,
"Normalization mode: 1=Combine graphemes, "
"2=Split graphemes, 3=Pure unicode");
namespace tesseract {
// Helper normalizes and segments the given strings according to norm_mode, and
// adds the segmented parts to unicharset.
static void AddStringsToUnicharset(const GenericVector<STRING>& strings,
int norm_mode, UNICHARSET* unicharset) {
for (int i = 0; i < strings.size(); ++i) {
std::vector<string> normalized;
if (NormalizeCleanAndSegmentUTF8(UnicodeNormMode::kNFC, OCRNorm::kNone,
static_cast<GraphemeNormMode>(norm_mode),
/*report_errors*/ true,
strings[i].string(), &normalized)) {
for (const string& normed : normalized) {
if (normed.empty() || IsWhitespace(normed[0])) continue;
unicharset->unichar_insert(normed.c_str());
}
} else {
tprintf("Normalization failed for string '%s'\n", strings[i].c_str());
}
}
}
int Main(int argc, char** argv) {
UNICHARSET unicharset;
// Load input files
for (int arg = 1; arg < argc; ++arg) {
STRING file_data = tesseract::ReadFile(argv[arg], /*reader*/ nullptr);
if (file_data.length() == 0) continue;
GenericVector<STRING> texts;
if (ReadMemBoxes(-1, /*skip_blanks*/ true, &file_data[0],
/*continue_on_failure*/ false, /*boxes*/ nullptr,
&texts, /*box_texts*/ nullptr, /*pages*/ nullptr)) {
tprintf("Extracting unicharset from box file %s\n", argv[arg]);
} else {
tprintf("Extracting unicharset from plain text file %s\n", argv[arg]);
texts.truncate(0);
file_data.split('\n', &texts);
}
AddStringsToUnicharset(texts, FLAGS_norm_mode, &unicharset);
}
SetupBasicProperties(/*report_errors*/ true, /*decompose*/ false,
&unicharset);
// Write unicharset file.
if (unicharset.save_to_file(FLAGS_output_unicharset.c_str())) {
tprintf("Wrote unicharset file %s\n", FLAGS_output_unicharset.c_str());
} else {
tprintf("Cannot save unicharset file %s\n",
FLAGS_output_unicharset.c_str());
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
} // namespace tesseract
int main(int argc, char** argv) {
tesseract::ParseCommandLineFlags(argv[0], &argc, &argv, true);
if (argc < 2) {
tprintf(
"Usage: %s [--output_unicharset filename] [--norm_mode mode]"
" box_or_text_file [...]\n",
argv[0]);
tprintf("Where mode means:\n");
tprintf(" 1=combine graphemes (use for Latin and other simple scripts)\n");
tprintf(" 2=split graphemes (use for Indic/Khmer/Myanmar)\n");
tprintf(" 3=pure unicode (use for Arabic/Hebrew/Thai/Tibetan)\n");
tprintf("Reads box or plain text files to extract the unicharset.\n");
return EXIT_FAILURE;
}
return tesseract::Main(argc, argv);
}
|
///////////////////////////////////////////////////////////////////////
// File: unicharset_extractor.cpp
// Description: Unicode character/ligature set extractor.
// Author: Thomas Kielbus
// Created: Wed Jun 28 17:05:01 PDT 2006
//
// (C) Copyright 2006, Google 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.
//
///////////////////////////////////////////////////////////////////////
// Given a list of box files or text files on the command line, this program
// normalizes the text according to command-line options and generates
// a unicharset.
#include <cstdlib>
#include "boxread.h"
#include "commandlineflags.h"
#include "genericvector.h"
#include "lang_model_helpers.h"
#include "normstrngs.h"
#include "strngs.h"
#include "tprintf.h"
#include "unicharset.h"
#include "unicharset_training_utils.h"
STRING_PARAM_FLAG(output_unicharset, "unicharset", "Output file path");
INT_PARAM_FLAG(norm_mode, 1,
"Normalization mode: 1=Combine graphemes, "
"2=Split graphemes, 3=Pure unicode");
namespace tesseract {
// Helper normalizes and segments the given strings according to norm_mode, and
// adds the segmented parts to unicharset.
static void AddStringsToUnicharset(const GenericVector<STRING>& strings,
int norm_mode, UNICHARSET* unicharset) {
for (int i = 0; i < strings.size(); ++i) {
std::vector<string> normalized;
if (NormalizeCleanAndSegmentUTF8(UnicodeNormMode::kNFC, OCRNorm::kNone,
static_cast<GraphemeNormMode>(norm_mode),
/*report_errors*/ true,
strings[i].string(), &normalized)) {
for (const string& normed : normalized) {
// normed is a UTF-8 encoded string
if (normed.empty() || IsUTF8Whitespace(normed.c_str())) continue;
unicharset->unichar_insert(normed.c_str());
}
} else {
tprintf("Normalization failed for string '%s'\n", strings[i].c_str());
}
}
}
int Main(int argc, char** argv) {
UNICHARSET unicharset;
// Load input files
for (int arg = 1; arg < argc; ++arg) {
STRING file_data = tesseract::ReadFile(argv[arg], /*reader*/ nullptr);
if (file_data.length() == 0) continue;
GenericVector<STRING> texts;
if (ReadMemBoxes(-1, /*skip_blanks*/ true, &file_data[0],
/*continue_on_failure*/ false, /*boxes*/ nullptr,
&texts, /*box_texts*/ nullptr, /*pages*/ nullptr)) {
tprintf("Extracting unicharset from box file %s\n", argv[arg]);
} else {
tprintf("Extracting unicharset from plain text file %s\n", argv[arg]);
texts.truncate(0);
file_data.split('\n', &texts);
}
AddStringsToUnicharset(texts, FLAGS_norm_mode, &unicharset);
}
SetupBasicProperties(/*report_errors*/ true, /*decompose*/ false,
&unicharset);
// Write unicharset file.
if (unicharset.save_to_file(FLAGS_output_unicharset.c_str())) {
tprintf("Wrote unicharset file %s\n", FLAGS_output_unicharset.c_str());
} else {
tprintf("Cannot save unicharset file %s\n",
FLAGS_output_unicharset.c_str());
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
} // namespace tesseract
int main(int argc, char** argv) {
tesseract::ParseCommandLineFlags(argv[0], &argc, &argv, true);
if (argc < 2) {
tprintf(
"Usage: %s [--output_unicharset filename] [--norm_mode mode]"
" box_or_text_file [...]\n",
argv[0]);
tprintf("Where mode means:\n");
tprintf(" 1=combine graphemes (use for Latin and other simple scripts)\n");
tprintf(" 2=split graphemes (use for Indic/Khmer/Myanmar)\n");
tprintf(" 3=pure unicode (use for Arabic/Hebrew/Thai/Tibetan)\n");
tprintf("Reads box or plain text files to extract the unicharset.\n");
return EXIT_FAILURE;
}
return tesseract::Main(argc, argv);
}
|
Update unicharset_extractor.cpp (#1153)
|
Update unicharset_extractor.cpp (#1153)
* change IsWhitespace to IsUTF8Whitespace
To solve "Phase UP: Generating unicharset and unichar properties files" ERROR #1147
please reference: [#1147](https://github.com/tesseract-ocr/tesseract/issues/1147)
* Update unicharset_extractor.cpp
fix the "Phase UP: Generating unicharset and unichar properties files" ERROR
* Update unicharset_extractor.cpp
fix "Phase UP: Generating unicharset and unichar properties files" ERROR #1147
* Update unicharset_extractor.cpp
fix the encoding invalid problem and fix the comment
|
C++
|
apache-2.0
|
stweil/tesseract,UB-Mannheim/tesseract,amitdo/tesseract,UB-Mannheim/tesseract,UB-Mannheim/tesseract,tesseract-ocr/tesseract,tesseract-ocr/tesseract,jbarlow83/tesseract,tesseract-ocr/tesseract,jbarlow83/tesseract,UB-Mannheim/tesseract,jbarlow83/tesseract,jbarlow83/tesseract,amitdo/tesseract,tesseract-ocr/tesseract,amitdo/tesseract,stweil/tesseract,amitdo/tesseract,stweil/tesseract,UB-Mannheim/tesseract,stweil/tesseract,jbarlow83/tesseract,stweil/tesseract,amitdo/tesseract,tesseract-ocr/tesseract
|
9c196ac0fc7c7c6cad68d967c1a74959dd7e0f58
|
unittests/AST/StmtPrinterTest.cpp
|
unittests/AST/StmtPrinterTest.cpp
|
//===- unittests/AST/StmtPrinterTest.cpp --- Statement printer tests ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains tests for Stmt::printPretty() and related methods.
//
// Search this file for WRONG to see test cases that are producing something
// completely wrong, invalid C++ or just misleading.
//
// These tests have a coding convention:
// * statements to be printed should be contained within a function named 'A'
// unless it should have some special name (e.g., 'operator+');
// * additional helper declarations are 'Z', 'Y', 'X' and so on.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/SmallString.h"
#include "gtest/gtest.h"
using namespace clang;
using namespace ast_matchers;
using namespace tooling;
namespace {
void PrintStmt(raw_ostream &Out, const ASTContext *Context, const Stmt *S) {
PrintingPolicy Policy = Context->getPrintingPolicy();
S->printPretty(Out, /*Helper*/ 0, Policy);
}
class PrintMatch : public MatchFinder::MatchCallback {
SmallString<1024> Printed;
unsigned NumFoundStmts;
public:
PrintMatch() : NumFoundStmts(0) {}
virtual void run(const MatchFinder::MatchResult &Result) {
const Stmt *S = Result.Nodes.getStmtAs<Stmt>("id");
if (!S)
return;
NumFoundStmts++;
if (NumFoundStmts > 1)
return;
llvm::raw_svector_ostream Out(Printed);
PrintStmt(Out, Result.Context, S);
}
StringRef getPrinted() const {
return Printed;
}
unsigned getNumFoundStmts() const {
return NumFoundStmts;
}
};
::testing::AssertionResult PrintedStmtMatches(
StringRef Code,
const std::vector<std::string> &Args,
const DeclarationMatcher &NodeMatch,
StringRef ExpectedPrinted) {
PrintMatch Printer;
MatchFinder Finder;
Finder.addMatcher(NodeMatch, &Printer);
OwningPtr<FrontendActionFactory> Factory(newFrontendActionFactory(&Finder));
if (!runToolOnCodeWithArgs(Factory->create(), Code, Args))
return testing::AssertionFailure() << "Parsing error in \"" << Code << "\"";
if (Printer.getNumFoundStmts() == 0)
return testing::AssertionFailure()
<< "Matcher didn't find any statements";
if (Printer.getNumFoundStmts() > 1)
return testing::AssertionFailure()
<< "Matcher should match only one statement "
"(found " << Printer.getNumFoundStmts() << ")";
if (Printer.getPrinted() != ExpectedPrinted)
return ::testing::AssertionFailure()
<< "Expected \"" << ExpectedPrinted << "\", "
"got \"" << Printer.getPrinted() << "\"";
return ::testing::AssertionSuccess();
}
::testing::AssertionResult PrintedStmtCXX98Matches(
StringRef Code,
StringRef ContainingFunction,
StringRef ExpectedPrinted) {
std::vector<std::string> Args;
Args.push_back("-std=c++98");
Args.push_back("-Wno-unused-value");
return PrintedStmtMatches(Code,
Args,
functionDecl(hasName(ContainingFunction),
has(compoundStmt(has(stmt().bind("id"))))),
ExpectedPrinted);
}
::testing::AssertionResult PrintedStmtMSMatches(
StringRef Code,
StringRef ContainingFunction,
StringRef ExpectedPrinted) {
std::vector<std::string> Args;
Args.push_back("-std=c++98");
Args.push_back("-fms-extensions");
Args.push_back("-Wno-unused-value");
return PrintedStmtMatches(Code,
Args,
functionDecl(hasName(ContainingFunction),
has(compoundStmt(has(stmt().bind("id"))))),
ExpectedPrinted);
}
} // unnamed namespace
TEST(StmtPrinter, TestIntegerLiteral) {
ASSERT_TRUE(PrintedStmtCXX98Matches(
"void A() {"
" 1, -1, 1U, 1u,"
" 1L, 1l, -1L, 1UL, 1ul,"
" 1LL, -1LL, 1ULL;"
"}",
"A",
"1 , -1 , 1U , 1U , "
"1L , 1L , -1L , 1UL , 1UL , "
"1LL , -1LL , 1ULL"));
// Should be: with semicolon
}
TEST(StmtPrinter, TestMSIntegerLiteral) {
ASSERT_TRUE(PrintedStmtMSMatches(
"void A() {"
" 1i8, -1i8, 1ui8, "
" 1i16, -1i16, 1ui16, "
" 1i32, -1i32, 1ui32, "
" 1i64, -1i64, 1ui64;"
"}",
"A",
"1 , -1 , 1U , "
"1 , -1 , 1U , "
"1L , -1L , 1UL , "
"1LL , -1LL , 1ULL"));
// Should be: with semicolon
// WRONG; all 128-bit literals should be printed as 128-bit.
// (This is because currently we do semantic analysis incorrectly.)
}
TEST(StmtPrinter, TestFloatingPointLiteral) {
ASSERT_TRUE(PrintedStmtCXX98Matches(
"void A() { 1.0f, -1.0f, 1.0, -1.0, 1.0l, -1.0l; }",
"A",
"1.F , -1.F , 1. , -1. , 1.L , -1.L"));
// Should be: with semicolon
}
|
//===- unittests/AST/StmtPrinterTest.cpp --- Statement printer tests ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains tests for Stmt::printPretty() and related methods.
//
// Search this file for WRONG to see test cases that are producing something
// completely wrong, invalid C++ or just misleading.
//
// These tests have a coding convention:
// * statements to be printed should be contained within a function named 'A'
// unless it should have some special name (e.g., 'operator+');
// * additional helper declarations are 'Z', 'Y', 'X' and so on.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/SmallString.h"
#include "gtest/gtest.h"
using namespace clang;
using namespace ast_matchers;
using namespace tooling;
namespace {
void PrintStmt(raw_ostream &Out, const ASTContext *Context, const Stmt *S) {
PrintingPolicy Policy = Context->getPrintingPolicy();
S->printPretty(Out, /*Helper*/ 0, Policy);
}
class PrintMatch : public MatchFinder::MatchCallback {
SmallString<1024> Printed;
unsigned NumFoundStmts;
public:
PrintMatch() : NumFoundStmts(0) {}
virtual void run(const MatchFinder::MatchResult &Result) {
const Stmt *S = Result.Nodes.getStmtAs<Stmt>("id");
if (!S)
return;
NumFoundStmts++;
if (NumFoundStmts > 1)
return;
llvm::raw_svector_ostream Out(Printed);
PrintStmt(Out, Result.Context, S);
}
StringRef getPrinted() const {
return Printed;
}
unsigned getNumFoundStmts() const {
return NumFoundStmts;
}
};
::testing::AssertionResult PrintedStmtMatches(
StringRef Code,
const std::vector<std::string> &Args,
const DeclarationMatcher &NodeMatch,
StringRef ExpectedPrinted) {
PrintMatch Printer;
MatchFinder Finder;
Finder.addMatcher(NodeMatch, &Printer);
OwningPtr<FrontendActionFactory> Factory(newFrontendActionFactory(&Finder));
if (!runToolOnCodeWithArgs(Factory->create(), Code, Args))
return testing::AssertionFailure() << "Parsing error in \"" << Code << "\"";
if (Printer.getNumFoundStmts() == 0)
return testing::AssertionFailure()
<< "Matcher didn't find any statements";
if (Printer.getNumFoundStmts() > 1)
return testing::AssertionFailure()
<< "Matcher should match only one statement "
"(found " << Printer.getNumFoundStmts() << ")";
if (Printer.getPrinted() != ExpectedPrinted)
return ::testing::AssertionFailure()
<< "Expected \"" << ExpectedPrinted << "\", "
"got \"" << Printer.getPrinted() << "\"";
return ::testing::AssertionSuccess();
}
::testing::AssertionResult PrintedStmtCXX98Matches(
StringRef Code,
StringRef ContainingFunction,
StringRef ExpectedPrinted) {
std::vector<std::string> Args;
Args.push_back("-std=c++98");
Args.push_back("-Wno-unused-value");
return PrintedStmtMatches(Code,
Args,
functionDecl(hasName(ContainingFunction),
has(compoundStmt(has(stmt().bind("id"))))),
ExpectedPrinted);
}
::testing::AssertionResult PrintedStmtMSMatches(
StringRef Code,
StringRef ContainingFunction,
StringRef ExpectedPrinted) {
std::vector<std::string> Args;
Args.push_back("-std=c++98");
Args.push_back("-fms-extensions");
Args.push_back("-Wno-unused-value");
return PrintedStmtMatches(Code,
Args,
functionDecl(hasName(ContainingFunction),
has(compoundStmt(has(stmt().bind("id"))))),
ExpectedPrinted);
}
} // unnamed namespace
TEST(StmtPrinter, TestIntegerLiteral) {
ASSERT_TRUE(PrintedStmtCXX98Matches(
"void A() {"
" 1, -1, 1U, 1u,"
" 1L, 1l, -1L, 1UL, 1ul,"
" 1LL, -1LL, 1ULL;"
"}",
"A",
"1 , -1 , 1U , 1U , "
"1L , 1L , -1L , 1UL , 1UL , "
"1LL , -1LL , 1ULL"));
// Should be: with semicolon
}
TEST(StmtPrinter, TestMSIntegerLiteral) {
ASSERT_TRUE(PrintedStmtMSMatches(
"void A() {"
" 1i8, -1i8, 1ui8, "
" 1i16, -1i16, 1ui16, "
" 1i32, -1i32, 1ui32, "
" 1i64, -1i64, 1ui64;"
"}",
"A",
"1 , -1 , 1U , "
"1 , -1 , 1U , "
"1L , -1L , 1UL , "
"1LL , -1LL , 1ULL"));
// Should be: with semicolon
}
TEST(StmtPrinter, TestFloatingPointLiteral) {
ASSERT_TRUE(PrintedStmtCXX98Matches(
"void A() { 1.0f, -1.0f, 1.0, -1.0, 1.0l, -1.0l; }",
"A",
"1.F , -1.F , 1. , -1. , 1.L , -1.L"));
// Should be: with semicolon
}
|
Remove out-of-date comment.
|
Remove out-of-date comment.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@168957 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang
|
4b4adc3107520d4a0ebc5d6562a648fd43a77f96
|
chrome/test/ui/npapi_uitest.cc
|
chrome/test/ui/npapi_uitest.cc
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// windows headers
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <atlbase.h>
#include <comutil.h>
// runtime headers
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <ostream>
#include "base/file_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/npapi_test_helper.h"
#include "net/base/net_util.h"
const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
const int kLongWaitTimeout = 30 * 1000;
const int kShortWaitTimeout = 5 * 1000;
// Test passing arguments to a plugin.
TEST_F(NPAPITester, Arguments) {
std::wstring test_case = L"arguments.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("arguments", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Test invoking many plugins within a single page.
TEST_F(NPAPITester, ManyPlugins) {
std::wstring test_case = L"many_plugins.html";
GURL url(GetTestUrl(L"npapi", test_case));
NavigateToURL(url);
WaitForFinish("arguments", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "2", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "3", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "4", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "5", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "6", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "7", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "8", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "9", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "10", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "11", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "12", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "13", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "14", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "15", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Test various calls to GetURL from a plugin.
TEST_F(NPAPITester, GetURL) {
std::wstring test_case = L"geturl.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("geturl", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Test various calls to GetURL for javascript URLs with
// non NULL targets from a plugin.
TEST_F(NPAPITester, GetJavaScriptURL) {
std::wstring test_case = L"get_javascript_url.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("getjavascripturl", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Tests that if an NPObject is proxies back to its original process, the
// original pointer is returned and not a proxy. If this fails the plugin
// will crash.
TEST_F(NPAPITester, NPObjectProxy) {
std::wstring test_case = L"npobject_proxy.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("npobject_proxy", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Tests if a plugin executing a self deleting script using NPN_GetURL
// works without crashing or hanging
TEST_F(NPAPITester, SelfDeletePluginGetUrl) {
std::wstring test_case = L"self_delete_plugin_geturl.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("self_delete_plugin_geturl", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
// Tests if a plugin executing a self deleting script using Invoke
// works without crashing or hanging
TEST_F(NPAPITester, SelfDeletePluginInvoke) {
std::wstring test_case = L"self_delete_plugin_invoke.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("self_delete_plugin_invoke", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
// Tests if a plugin executing a self deleting script using Invoke with
// a modal dialog showing works without crashing or hanging
TEST_F(NPAPITester, DISABLED_SelfDeletePluginInvokeAlert) {
std::wstring test_case = L"self_delete_plugin_invoke_alert.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
// Wait for the alert dialog and then close it.
automation()->WaitForAppModalDialog(5000);
scoped_refptr<WindowProxy> window(automation()->GetActiveWindow());
ASSERT_TRUE(window.get());
ASSERT_TRUE(window->SimulateOSKeyPress(VK_ESCAPE, 0));
WaitForFinish("self_delete_plugin_invoke_alert", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
// Tests if a plugin executing a self deleting script in the context of
// a synchronous paint event works correctly
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInvokeInSynchronousPaint) {
if (!UITest::in_process_renderer()) {
show_window_ = true;
std::wstring test_case = L"execute_script_delete_in_paint.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("execute_script_delete_in_paint", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
}
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNewStream) {
if (!UITest::in_process_renderer()) {
show_window_ = true;
std::wstring test_case = L"self_delete_plugin_stream.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("self_delete_plugin_stream", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
}
// Tests if a plugin has a non zero window rect.
TEST_F(NPAPIVisiblePluginTester, VerifyPluginWindowRect) {
show_window_ = true;
std::wstring test_case = L"verify_plugin_window_rect.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("checkwindowrect", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Tests that creating a new instance of a plugin while another one is handling
// a paint message doesn't cause deadlock.
TEST_F(NPAPIVisiblePluginTester, CreateInstanceInPaint) {
show_window_ = true;
std::wstring test_case = L"create_instance_in_paint.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("create_instance_in_paint", "2", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
#if defined(OS_WIN)
// Tests that putting up an alert in response to a paint doesn't deadlock.
TEST_F(NPAPIVisiblePluginTester, AlertInWindowMessage) {
show_window_ = true;
std::wstring test_case = L"alert_in_window_message.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
bool modal_dialog_showing = false;
MessageBoxFlags::DialogButton available_buttons;
ASSERT_TRUE(automation()->WaitForAppModalDialog(kShortWaitTimeout));
ASSERT_TRUE(automation()->GetShowingAppModalDialog(&modal_dialog_showing,
&available_buttons));
ASSERT_TRUE(modal_dialog_showing);
ASSERT_TRUE((MessageBoxFlags::DIALOGBUTTON_OK & available_buttons) != 0);
ASSERT_TRUE(automation()->ClickAppModalDialogButton(
MessageBoxFlags::DIALOGBUTTON_OK));
modal_dialog_showing = false;
ASSERT_TRUE(automation()->WaitForAppModalDialog(kShortWaitTimeout));
ASSERT_TRUE(automation()->GetShowingAppModalDialog(&modal_dialog_showing,
&available_buttons));
ASSERT_TRUE(modal_dialog_showing);
ASSERT_TRUE((MessageBoxFlags::DIALOGBUTTON_OK & available_buttons) != 0);
ASSERT_TRUE(automation()->ClickAppModalDialogButton(
MessageBoxFlags::DIALOGBUTTON_OK));
}
#endif
TEST_F(NPAPIVisiblePluginTester, VerifyNPObjectLifetimeTest) {
if (!UITest::in_process_renderer()) {
show_window_ = true;
std::wstring test_case = L"npobject_lifetime_test.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("npobject_lifetime_test", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
}
// Tests that we don't crash or assert if NPP_New fails
TEST_F(NPAPIVisiblePluginTester, NewFails) {
GURL url = GetTestUrl(L"npapi", L"new_fails.html");
NavigateToURL(url);
WaitForFinish("new_fails", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNPNEvaluate) {
if (!UITest::in_process_renderer()) {
GURL url = GetTestUrl(L"npapi",
L"execute_script_delete_in_npn_evaluate.html");
NavigateToURL(url);
WaitForFinish("npobject_delete_plugin_in_evaluate", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
}
TEST_F(NPAPIVisiblePluginTester, OpenPopupWindowWithPlugin) {
GURL url = GetTestUrl(L"npapi",
L"get_javascript_open_popup_with_plugin.html");
NavigateToURL(url);
WaitForFinish("plugin_popup_with_plugin_target", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
action_timeout_ms());
}
// Test checking the privacy mode is off.
TEST_F(NPAPITester, PrivateDisabled) {
if (UITest::in_process_renderer())
return;
GURL url = GetTestUrl(L"npapi", L"private.html");
NavigateToURL(url);
WaitForFinish("private", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Test checking the privacy mode is on.
TEST_F(NPAPIIncognitoTester, PrivateEnabled) {
if (UITest::in_process_renderer())
return;
GURL url = GetTestUrl(L"npapi", L"private.html?private");
NavigateToURL(url);
WaitForFinish("private", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Test a browser hang due to special case of multiple
// plugin instances indulged in sync calls across renderer.
TEST_F(NPAPIVisiblePluginTester, MultipleInstancesSyncCalls) {
if (UITest::in_process_renderer())
return;
GURL url = GetTestUrl(L"npapi", L"multiple_instances_sync_calls.html");
NavigateToURL(url);
WaitForFinish("multiple_instances_sync_calls", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// windows headers
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <atlbase.h>
#include <comutil.h>
// runtime headers
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <ostream>
#include "base/file_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/npapi_test_helper.h"
#include "net/base/net_util.h"
const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
const int kLongWaitTimeout = 30 * 1000;
const int kShortWaitTimeout = 5 * 1000;
// Test passing arguments to a plugin.
TEST_F(NPAPITester, Arguments) {
std::wstring test_case = L"arguments.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("arguments", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Test invoking many plugins within a single page.
TEST_F(NPAPITester, ManyPlugins) {
std::wstring test_case = L"many_plugins.html";
GURL url(GetTestUrl(L"npapi", test_case));
NavigateToURL(url);
WaitForFinish("arguments", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "2", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "3", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "4", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "5", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "6", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "7", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "8", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "9", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "10", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "11", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "12", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "13", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "14", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
WaitForFinish("arguments", "15", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Test various calls to GetURL from a plugin.
TEST_F(NPAPITester, GetURL) {
std::wstring test_case = L"geturl.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("geturl", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Test various calls to GetURL for javascript URLs with
// non NULL targets from a plugin.
TEST_F(NPAPITester, GetJavaScriptURL) {
std::wstring test_case = L"get_javascript_url.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("getjavascripturl", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Tests that if an NPObject is proxies back to its original process, the
// original pointer is returned and not a proxy. If this fails the plugin
// will crash.
TEST_F(NPAPITester, NPObjectProxy) {
std::wstring test_case = L"npobject_proxy.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("npobject_proxy", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Tests if a plugin executing a self deleting script using NPN_GetURL
// works without crashing or hanging
TEST_F(NPAPITester, SelfDeletePluginGetUrl) {
std::wstring test_case = L"self_delete_plugin_geturl.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("self_delete_plugin_geturl", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
// Tests if a plugin executing a self deleting script using Invoke
// works without crashing or hanging
TEST_F(NPAPITester, SelfDeletePluginInvoke) {
std::wstring test_case = L"self_delete_plugin_invoke.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("self_delete_plugin_invoke", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
// Tests if a plugin executing a self deleting script using Invoke with
// a modal dialog showing works without crashing or hanging
TEST_F(NPAPITester, DISABLED_SelfDeletePluginInvokeAlert) {
std::wstring test_case = L"self_delete_plugin_invoke_alert.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
// Wait for the alert dialog and then close it.
automation()->WaitForAppModalDialog(5000);
scoped_refptr<WindowProxy> window(automation()->GetActiveWindow());
ASSERT_TRUE(window.get());
ASSERT_TRUE(window->SimulateOSKeyPress(VK_ESCAPE, 0));
WaitForFinish("self_delete_plugin_invoke_alert", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
// Tests if a plugin executing a self deleting script in the context of
// a synchronous paint event works correctly
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInvokeInSynchronousPaint) {
if (!UITest::in_process_renderer()) {
show_window_ = true;
std::wstring test_case = L"execute_script_delete_in_paint.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("execute_script_delete_in_paint", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
}
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNewStream) {
if (!UITest::in_process_renderer()) {
show_window_ = true;
std::wstring test_case = L"self_delete_plugin_stream.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("self_delete_plugin_stream", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
}
// Tests if a plugin has a non zero window rect.
TEST_F(NPAPIVisiblePluginTester, VerifyPluginWindowRect) {
show_window_ = true;
std::wstring test_case = L"verify_plugin_window_rect.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("checkwindowrect", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Tests that creating a new instance of a plugin while another one is handling
// a paint message doesn't cause deadlock.
TEST_F(NPAPIVisiblePluginTester, CreateInstanceInPaint) {
show_window_ = true;
std::wstring test_case = L"create_instance_in_paint.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("create_instance_in_paint", "2", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
#if defined(OS_WIN)
// Tests that putting up an alert in response to a paint doesn't deadlock.
TEST_F(NPAPIVisiblePluginTester, AlertInWindowMessage) {
show_window_ = true;
std::wstring test_case = L"alert_in_window_message.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
bool modal_dialog_showing = false;
MessageBoxFlags::DialogButton available_buttons;
ASSERT_TRUE(automation()->WaitForAppModalDialog(kShortWaitTimeout));
ASSERT_TRUE(automation()->GetShowingAppModalDialog(&modal_dialog_showing,
&available_buttons));
ASSERT_TRUE(modal_dialog_showing);
ASSERT_TRUE((MessageBoxFlags::DIALOGBUTTON_OK & available_buttons) != 0);
ASSERT_TRUE(automation()->ClickAppModalDialogButton(
MessageBoxFlags::DIALOGBUTTON_OK));
modal_dialog_showing = false;
ASSERT_TRUE(automation()->WaitForAppModalDialog(kShortWaitTimeout));
ASSERT_TRUE(automation()->GetShowingAppModalDialog(&modal_dialog_showing,
&available_buttons));
ASSERT_TRUE(modal_dialog_showing);
ASSERT_TRUE((MessageBoxFlags::DIALOGBUTTON_OK & available_buttons) != 0);
ASSERT_TRUE(automation()->ClickAppModalDialogButton(
MessageBoxFlags::DIALOGBUTTON_OK));
}
#endif
TEST_F(NPAPIVisiblePluginTester, VerifyNPObjectLifetimeTest) {
if (!UITest::in_process_renderer()) {
show_window_ = true;
std::wstring test_case = L"npobject_lifetime_test.html";
GURL url = GetTestUrl(L"npapi", test_case);
NavigateToURL(url);
WaitForFinish("npobject_lifetime_test", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
}
// Tests that we don't crash or assert if NPP_New fails
TEST_F(NPAPIVisiblePluginTester, NewFails) {
GURL url = GetTestUrl(L"npapi", L"new_fails.html");
NavigateToURL(url);
WaitForFinish("new_fails", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
TEST_F(NPAPIVisiblePluginTester, SelfDeletePluginInNPNEvaluate) {
if (!UITest::in_process_renderer()) {
GURL url = GetTestUrl(L"npapi",
L"execute_script_delete_in_npn_evaluate.html");
NavigateToURL(url);
WaitForFinish("npobject_delete_plugin_in_evaluate", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
kShortWaitTimeout);
}
}
// Flaky. See http://crbug.com/17645
TEST_F(NPAPIVisiblePluginTester, DISABLED_OpenPopupWindowWithPlugin) {
GURL url = GetTestUrl(L"npapi",
L"get_javascript_open_popup_with_plugin.html");
NavigateToURL(url);
WaitForFinish("plugin_popup_with_plugin_target", "1", url,
kTestCompleteCookie, kTestCompleteSuccess,
action_timeout_ms());
}
// Test checking the privacy mode is off.
TEST_F(NPAPITester, PrivateDisabled) {
if (UITest::in_process_renderer())
return;
GURL url = GetTestUrl(L"npapi", L"private.html");
NavigateToURL(url);
WaitForFinish("private", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Test checking the privacy mode is on.
TEST_F(NPAPIIncognitoTester, PrivateEnabled) {
if (UITest::in_process_renderer())
return;
GURL url = GetTestUrl(L"npapi", L"private.html?private");
NavigateToURL(url);
WaitForFinish("private", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
// Test a browser hang due to special case of multiple
// plugin instances indulged in sync calls across renderer.
TEST_F(NPAPIVisiblePluginTester, MultipleInstancesSyncCalls) {
if (UITest::in_process_renderer())
return;
GURL url = GetTestUrl(L"npapi", L"multiple_instances_sync_calls.html");
NavigateToURL(url);
WaitForFinish("multiple_instances_sync_calls", "1", url, kTestCompleteCookie,
kTestCompleteSuccess, kShortWaitTimeout);
}
|
Disable NPAPIVisiblePluginTester.OpenPopupWindowWithPlugin, which is flaky.
|
Disable NPAPIVisiblePluginTester.OpenPopupWindowWithPlugin, which is flaky.
BUG=17645
TEST=none
Review URL: http://codereview.chromium.org/159333
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@21514 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C++
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
fb5b60176fb091f0e83e766763cc74f835cd6d1a
|
chrome/common/chrome_constants.cc
|
chrome/common/chrome_constants.cc
|
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/chrome_constants.h"
#include "base/file_path.h"
#define FPL FILE_PATH_LITERAL
namespace chrome {
// The following should not be used for UI strings; they are meant
// for system strings only. UI changes should be made in the GRD.
#if defined(OS_WIN)
const wchar_t kBrowserProcessExecutableName[] = L"chrome.exe";
#elif defined(OS_LINUX)
const wchar_t kBrowserProcessExecutableName[] = L"chrome";
#elif defined(OS_MACOSX)
const wchar_t kBrowserProcessExecutableName[] =
#if defined(GOOGLE_CHROME_BUILD)
L"Chrome";
#else
L"Chromium";
#endif // GOOGLE_CHROME_BUILD
#endif // OS_*
#if defined(OS_WIN)
const wchar_t kBrowserProcessExecutablePath[] = L"chrome.exe";
#elif defined(OS_LINUX)
const wchar_t kBrowserProcessExecutablePath[] = L"chrome";
#elif defined(OS_MACOSX)
const wchar_t kBrowserProcessExecutablePath[] =
#if defined(GOOGLE_CHROME_BUILD)
L"Google Chrome.app/Contents/MacOS/Google Chrome";
#else
L"Chromium.app/Contents/MacOS/Chromium";
#endif // GOOGLE_CHROME_BUILD
#endif // OS_*
#if defined(GOOGLE_CHROME_BUILD)
const wchar_t kBrowserAppName[] = L"Chrome";
const char kStatsFilename[] = "ChromeStats2";
#else
const wchar_t kBrowserAppName[] = L"Chromium";
const char kStatsFilename[] = "ChromiumStats2";
#endif
const wchar_t kExternalTabWindowClass[] = L"Chrome_ExternalTabContainer";
const wchar_t kMessageWindowClass[] = L"Chrome_MessageWindow";
const wchar_t kCrashReportLog[] = L"Reported Crashes.txt";
const wchar_t kTestingInterfaceDLL[] = L"testing_interface.dll";
const wchar_t kNotSignedInProfile[] = L"Default";
const wchar_t kNotSignedInID[] = L"not-signed-in";
const wchar_t kBrowserResourcesDll[] = L"chrome.dll";
const FilePath::CharType kExtensionFileExtension[] = FPL("crx");
// filenames
const FilePath::CharType kArchivedHistoryFilename[] = FPL("Archived History");
const FilePath::CharType kCacheDirname[] = FPL("Cache");
const FilePath::CharType kMediaCacheDirname[] = FPL("Media Cache");
const FilePath::CharType kOffTheRecordMediaCacheDirname[] =
FPL("Incognito Media Cache");
const wchar_t kChromePluginDataDirname[] = L"Plugin Data";
const FilePath::CharType kCookieFilename[] = FPL("Cookies");
const FilePath::CharType kExtensionsCookieFilename[] = FPL("Extension Cookies");
const FilePath::CharType kHistoryFilename[] = FPL("History");
const FilePath::CharType kLocalStateFilename[] = FPL("Local State");
const FilePath::CharType kPreferencesFilename[] = FPL("Preferences");
const FilePath::CharType kSafeBrowsingFilename[] = FPL("Safe Browsing");
// WARNING: SingletonSocket can't contain spaces, because otherwise
// chrome_process_util_linux would be broken.
const FilePath::CharType kSingletonSocketFilename[] = FPL("SingletonSocket");
const FilePath::CharType kThumbnailsFilename[] = FPL("Thumbnails");
const wchar_t kUserDataDirname[] = L"User Data";
const FilePath::CharType kUserScriptsDirname[] = FPL("User Scripts");
const FilePath::CharType kWebDataFilename[] = FPL("Web Data");
const FilePath::CharType kBookmarksFileName[] = FPL("Bookmarks");
const FilePath::CharType kHistoryBookmarksFileName[] =
FPL("Bookmarks From History");
const FilePath::CharType kCustomDictionaryFileName[] =
FPL("Custom Dictionary.txt");
// This number used to be limited to 32 in the past (see b/535234).
const unsigned int kMaxRendererProcessCount = 42;
const int kStatsMaxThreads = 32;
const int kStatsMaxCounters = 300;
// We don't enable record mode in the released product because users could
// potentially be tricked into running a product in record mode without
// knowing it. Enable in debug builds. Playback mode is allowed always,
// because it is useful for testing and not hazardous by itself.
#ifndef NDEBUG
const bool kRecordModeEnabled = true;
#else
const bool kRecordModeEnabled = false;
#endif
} // namespace chrome
|
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/chrome_constants.h"
#include "base/file_path.h"
#define FPL FILE_PATH_LITERAL
namespace chrome {
// The following should not be used for UI strings; they are meant
// for system strings only. UI changes should be made in the GRD.
#if defined(OS_WIN)
const wchar_t kBrowserProcessExecutableName[] = L"chrome.exe";
#elif defined(OS_LINUX)
const wchar_t kBrowserProcessExecutableName[] = L"chrome";
#elif defined(OS_MACOSX)
const wchar_t kBrowserProcessExecutableName[] =
#if defined(GOOGLE_CHROME_BUILD)
L"Google Chrome";
#else
L"Chromium";
#endif // GOOGLE_CHROME_BUILD
#endif // OS_*
#if defined(OS_WIN)
const wchar_t kBrowserProcessExecutablePath[] = L"chrome.exe";
#elif defined(OS_LINUX)
const wchar_t kBrowserProcessExecutablePath[] = L"chrome";
#elif defined(OS_MACOSX)
const wchar_t kBrowserProcessExecutablePath[] =
#if defined(GOOGLE_CHROME_BUILD)
L"Google Chrome.app/Contents/MacOS/Google Chrome";
#else
L"Chromium.app/Contents/MacOS/Chromium";
#endif // GOOGLE_CHROME_BUILD
#endif // OS_*
#if defined(GOOGLE_CHROME_BUILD)
const wchar_t kBrowserAppName[] = L"Chrome";
const char kStatsFilename[] = "ChromeStats2";
#else
const wchar_t kBrowserAppName[] = L"Chromium";
const char kStatsFilename[] = "ChromiumStats2";
#endif
const wchar_t kExternalTabWindowClass[] = L"Chrome_ExternalTabContainer";
const wchar_t kMessageWindowClass[] = L"Chrome_MessageWindow";
const wchar_t kCrashReportLog[] = L"Reported Crashes.txt";
const wchar_t kTestingInterfaceDLL[] = L"testing_interface.dll";
const wchar_t kNotSignedInProfile[] = L"Default";
const wchar_t kNotSignedInID[] = L"not-signed-in";
const wchar_t kBrowserResourcesDll[] = L"chrome.dll";
const FilePath::CharType kExtensionFileExtension[] = FPL("crx");
// filenames
const FilePath::CharType kArchivedHistoryFilename[] = FPL("Archived History");
const FilePath::CharType kCacheDirname[] = FPL("Cache");
const FilePath::CharType kMediaCacheDirname[] = FPL("Media Cache");
const FilePath::CharType kOffTheRecordMediaCacheDirname[] =
FPL("Incognito Media Cache");
const wchar_t kChromePluginDataDirname[] = L"Plugin Data";
const FilePath::CharType kCookieFilename[] = FPL("Cookies");
const FilePath::CharType kExtensionsCookieFilename[] = FPL("Extension Cookies");
const FilePath::CharType kHistoryFilename[] = FPL("History");
const FilePath::CharType kLocalStateFilename[] = FPL("Local State");
const FilePath::CharType kPreferencesFilename[] = FPL("Preferences");
const FilePath::CharType kSafeBrowsingFilename[] = FPL("Safe Browsing");
// WARNING: SingletonSocket can't contain spaces, because otherwise
// chrome_process_util_linux would be broken.
const FilePath::CharType kSingletonSocketFilename[] = FPL("SingletonSocket");
const FilePath::CharType kThumbnailsFilename[] = FPL("Thumbnails");
const wchar_t kUserDataDirname[] = L"User Data";
const FilePath::CharType kUserScriptsDirname[] = FPL("User Scripts");
const FilePath::CharType kWebDataFilename[] = FPL("Web Data");
const FilePath::CharType kBookmarksFileName[] = FPL("Bookmarks");
const FilePath::CharType kHistoryBookmarksFileName[] =
FPL("Bookmarks From History");
const FilePath::CharType kCustomDictionaryFileName[] =
FPL("Custom Dictionary.txt");
// This number used to be limited to 32 in the past (see b/535234).
const unsigned int kMaxRendererProcessCount = 42;
const int kStatsMaxThreads = 32;
const int kStatsMaxCounters = 300;
// We don't enable record mode in the released product because users could
// potentially be tricked into running a product in record mode without
// knowing it. Enable in debug builds. Playback mode is allowed always,
// because it is useful for testing and not hazardous by itself.
#ifndef NDEBUG
const bool kRecordModeEnabled = true;
#else
const bool kRecordModeEnabled = false;
#endif
} // namespace chrome
|
Fix another name I missed. Review URL: http://codereview.chromium.org/113727
|
Fix another name I missed.
Review URL: http://codereview.chromium.org/113727
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@16668 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C++
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
f7fb848079b9bcccc6dadc0f9820f2dd3f2422ae
|
compiler/passes/runInterpreter.cpp
|
compiler/passes/runInterpreter.cpp
|
#include <signal.h>
#include <ctype.h>
#include "alist.h"
#include "driver.h"
#include "filesToAST.h"
#include "runInterpreter.h"
#include "symbol.h"
#include "symtab.h"
#include "map.h"
class IObject;
class IThread;
enum ISlotKind {
EMPTY_SLOT,
UNINITIALIZED_SLOT,
SELECTOR_SLOT,
CLOSURE_SLOT,
OBJECT_SLOT,
IMMEDIATE_SLOT
};
class ISlot : public gc { public:
ISlotKind kind;
union {
IObject *object;
Immediate *imm;
char *selector;
};
void set_selector(char *s) {
kind = SELECTOR_SLOT;
selector = s;
}
ISlot &operator=(ISlot &s) {
kind = s.kind;
object = s.object; // representitive of the union
return *this;
}
ISlot() : kind(EMPTY_SLOT) {}
};
class IObject : public gc { public:
Type *type;
int nslots;
ISlot slot[1]; // nslots for real length
};
struct IFrame : public gc { public:
IThread *thread;
IFrame *parent;
Map<BaseAST *, ISlot *> env;
Vec<Stmt *> stmtStack;
Vec<int> stmtStageStack;
Vec<Expr *> exprStack;
Vec<ISlot *> valStack;
Stmt *stmt;
int stage;
Expr *expr;
BaseAST *ip;
ISlot *islot(BaseAST *ast);
void icall(int nargs);
void run(int timeslice);
IFrame(IThread *t, Stmt *s);
};
struct IThread : public gc { public:
IFrame *frame;
void run();
IThread(Stmt *s);
};
static int single_step = 0;
volatile static int interrupted = 0;
static Vec<IThread *> threads;
IFrame::IFrame(IThread *t, Stmt *s) : thread(t), parent(0), stmt(s), stage(0), expr(0), ip(s) {
assert(s && stmt && ip);
}
IThread::IThread(Stmt *s) : frame(0) {
frame = new IFrame(this, s);
}
ISlot *
IFrame::islot(BaseAST *ast) {
ISlot *s = env.get(ast);
if (!s)
env.put(ast, (s = new ISlot));
return s;
}
#define S(_t) _t *s = (_t *)ip; (void)s; if (trace_level > 0) printf( #_t " %p\n", s)
static void
check_type(BaseAST *ast, ISlot *slot, Type *t) {
if (slot->kind == EMPTY_SLOT)
USR_FATAL(ast, "interpreter: accessed empty variable");
if (slot->kind == UNINITIALIZED_SLOT)
USR_FATAL(ast, "interpreter: accessed uninitialized variable");
return;
}
void
IFrame::icall(int nargs) {
if (valStack.n < nargs)
INT_FATAL(ip, "not enough arguments for call");
char *name = 0;
ISlot **args = &valStack.v[valStack.n-(nargs + 1)];
if (nargs < 1)
USR_FATAL(ip, "call with no arguments");
int done = 0;
do {
if (args[0]->kind == SELECTOR_SLOT) {
name = args[0]->selector;
done = 1;
} else if (args[0]->kind == CLOSURE_SLOT) {
USR_FATAL(ip, "closures not handled yet");
} else
USR_FATAL(ip, "call to something other than function name or closure");
} while (!done);
Vec<FnSymbol *> visible;
ip->parentScope->getVisibleFunctions(&visible, cannonicalize_string(name));
if (visible.n != 1)
USR_FATAL(ip, "unable to resolve function to single function '%s'", name);
return;
}
static void
interactive_usage() {
fprintf(stdout, "chpl Interpreter Interactive Mode Commands:\n");
fprintf(stdout,
"\tp - print\n"
"\tc - continue\n"
"\tq - quit\n"
);
}
static void
handle_interrupt(int sig) {
interrupted = 1;
}
static void
interactive() {
while (1) {
interrupted = 0;
fprintf(stdout, "\n> ");
char cmd_buffer[512], *c = cmd_buffer;
cmd_buffer[0] = 0;
fgets(cmd_buffer, 511, stdin);
while (*c && isspace(*c)) c++;
switch (tolower(*c)) {
default: interactive_usage(); break;
case 'q': exit(0); break;
case 'c': return;
case 'p': break;
}
}
}
#define PUSH_EXPR(_e) do { valStack.add(islot(_e)); exprStack.add(_e); } while (0)
#define EVAL_EXPR(_e) do { exprStack.add(_e); } while (0)
#define EVAL_STMT(_s) do { stmtStageStack.add(stage + 1); stmtStack.add(stmt); stmt = _s; } while (0)
#define PUSH_SELECTOR(_s) do { ISlot *_slot = new ISlot; _slot->set_selector(_s); valStack.add(_slot); } while (0)
#define PUSH_VAL(_s) valStack.add(islot(_s))
#define POP_VAL(_s) *islot(_s) = *valStack.pop();
#define CALL(_n) icall(_n)
void
IThread::run() {
while (frame)
frame->run(0);
}
void
IFrame::run(int timeslice) {
assert(ip && stmt);
while (1) {
LgotoLabel:
if (timeslice && !--timeslice)
return;
if (interrupted || single_step)
interactive();
switch (ip->astType) {
default: INT_FATAL(ip, "interpreter: bad astType: %d", ip->astType);
case STMT: break;
case STMT_EXPR: {
S(ExprStmt);
EVAL_EXPR(s->expr);
break;
}
case STMT_RETURN: {
S(ReturnStmt);
switch (stage++) {
case 0:
PUSH_EXPR(s->expr);
break;
case 1:
stage = 0;
ISlot *slot = valStack.pop();
thread->frame = parent;
if (parent)
parent->valStack.add(slot);
return;
default: INT_FATAL(ip, "interpreter: bad stage %d for astType: %d", stage, ip->astType); break;
}
break;
}
case STMT_BLOCK: {
S(BlockStmt);
EVAL_STMT((Stmt*)s->body->head->next);
break;
}
case STMT_WHILELOOP: {
S(WhileLoopStmt);
switch (stage) {
case 0:
stage = 1;
if (!s->isWhileDo)
EVAL_STMT(s->block);
break;
case 1:
stage = 2;
EVAL_EXPR(s->condition);
break;
case 2: {
ISlot *cond = islot(s->condition);
check_type(ip, cond, dtBoolean);
if (!cond->imm->v_bool)
stage = 0;
else {
stage = 1;
EVAL_STMT(s->block);
}
break;
}
default: INT_FATAL(ip, "interpreter: bad stage %d for astType: %d", stage, ip->astType); break;
}
break;
}
case STMT_FORLOOP: {
S(ForLoopStmt);
if (!s->indices || s->indices->length() != 1)
INT_FATAL(ip, "interpreter: bad number of indices");
if (!s->iterators || s->iterators->length() != 1)
INT_FATAL(ip, "interpreter: bad number of iterators");
Expr *iter = s->iterators->only();
Symbol *indice = s->indices->only()->sym;
BaseAST *loop_var = s;
switch (stage++) {
case 0:
EVAL_EXPR(iter);
break;
case 1:
PUSH_SELECTOR("_forall_start");
PUSH_VAL(iter);
CALL(2);
break;
case 2:
POP_VAL(loop_var);
PUSH_SELECTOR("_forall_valid");
PUSH_VAL(iter);
PUSH_VAL(loop_var);
CALL(3);
break;
case 3: {
ISlot *valid = valStack.pop();
check_type(ip, valid, dtBoolean);
if (!valid->imm->v_bool) {
stage = 0;
break;
}
PUSH_SELECTOR("_forall_index");
PUSH_VAL(iter);
PUSH_VAL(loop_var);
CALL(3);
break;
}
case 4:
POP_VAL(indice);
EVAL_STMT(s->innerStmt);
break;
case 5:
PUSH_SELECTOR("_forall_next");
PUSH_VAL(iter);
PUSH_VAL(loop_var);
CALL(3);
break;
case 6:
stage = 2;
POP_VAL(loop_var);
break;
default: INT_FATAL(ip, "interpreter: bad stage %d for astType: %d", stage, ip->astType); break;
}
break;
}
case STMT_COND: {
S(CondStmt);
switch (stage++) {
case 0:
PUSH_EXPR(s->condExpr);
break;
case 1:
stage = 0;
ISlot *cond = valStack.pop();
check_type(ip, cond, dtBoolean);
if (cond->imm->v_bool)
EVAL_STMT(s->thenStmt);
else
EVAL_STMT(s->elseStmt);
break;
default: INT_FATAL(ip, "interpreter: bad stage %d for astType: %d", stage, ip->astType); break;
}
break;
}
case STMT_WHEN: {
S(WhenStmt);
SelectStmt *select = (SelectStmt*)s->parentStmt;
assert(select->astType == STMT_SELECT);
break;
}
case STMT_SELECT: {
S(SelectStmt);
switch (stage++) {
case 0:
EVAL_EXPR(s->caseExpr);
break;
case 1:
stage = 0;
EVAL_STMT((Stmt*)s->whenStmts->head->next);
break;
default: INT_FATAL(ip, "interpreter: bad stage %d for astType: %d", stage, ip->astType); break;
}
break;
}
case STMT_LABEL: break;
case STMT_GOTO: {
S(GotoStmt);
stage = 0;
valStack.clear();
stmt = s->label->defPoint->parentStmt;
goto LgotoLabel;
}
case EXPR_SYM: {
S(SymExpr);
ISlot *x = env.get(s->var);
if (!x)
USR_FATAL(ip, "unknown variable in SymExpr'%s'", s->var->name ? s->var->name : "");
env.put(s, x);
break;
}
case EXPR_DEF: {
S(DefExpr);
ISlot *slot = new ISlot;
slot->kind = EMPTY_SLOT;
env.put(s->sym, slot);
if (trace_level)
printf(" '%s' %d\n", !s->sym->name ? "" : s->sym->name, (int)s->id);
break;
}
case EXPR_COND: {
S(CondExpr);
switch (stage++) {
case 0:
PUSH_EXPR(s->condExpr);
break;
case 1:
stage = 0;
ISlot *cond = valStack.pop();
check_type(ip, cond, dtBoolean);
if (cond->imm->v_bool) {
EVAL_EXPR(s->thenExpr);
env.put(expr, islot(s->thenExpr));
} else {
EVAL_EXPR(s->elseExpr);
env.put(expr, islot(s->thenExpr));
}
break;
default: INT_FATAL(ip, "interpreter: bad stage %d for astType: %d", stage, ip->astType); break;
}
break;
}
case EXPR_CALL: {
S(CallExpr);
switch (stage++) {
case 0: {
switch (s->opTag) {
default:
INT_FATAL("unhandled CallExpr::opTag: %d\n", s->opTag);
break;
case OP_NONE:
PUSH_EXPR(s->baseExpr);
break;
}
break;
}
default:
if (stage <= s->argList->length()) {
PUSH_EXPR(s->argList->get(stage));
} else {
CALL(s->argList->length());
}
break;
}
}
case EXPR_CAST:
case EXPR_MEMBERACCESS:
case EXPR_REDUCE:
case EXPR_NAMED:
case EXPR_IMPORT:
break;
}
ip = expr = exprStack.pop();
if (!expr) {
if (!stage) {
ip = stmt = (Stmt*)stmt->next;
valStack.clear();
while (!stmt) {
stmt = stmtStack.pop();
stage = stmtStageStack.pop() - 1;
if (!stmt) {
thread->frame = parent;
return;
}
assert(stage >= 0);
ip = stmt = (Stmt*)stmt->next;
}
}
}
}
}
static void
initialize() {
signal(SIGINT, handle_interrupt);
}
void
runInterpreter(void) {
if (!run_interpreter)
return;
if (run_interpreter > 1)
interrupted = 1;
initialize();
forv_Vec(ModuleSymbol, mod, allModules)
(new IThread((Stmt*)mod->stmts->head->next))->run();
exit(0);
}
|
#include <signal.h>
#include <ctype.h>
#include "alist.h"
#include "driver.h"
#include "filesToAST.h"
#include "runInterpreter.h"
#include "symbol.h"
#include "symtab.h"
#include "map.h"
class IObject;
class IThread;
enum ISlotKind {
EMPTY_SLOT,
UNINITIALIZED_SLOT,
SELECTOR_SLOT,
CLOSURE_SLOT,
OBJECT_SLOT,
IMMEDIATE_SLOT
};
class ISlot : public gc { public:
ISlotKind kind;
union {
IObject *object;
Immediate *imm;
char *selector;
};
void set_selector(char *s) {
kind = SELECTOR_SLOT;
selector = s;
}
ISlot &operator=(ISlot &s) {
kind = s.kind;
object = s.object; // representitive of the union
return *this;
}
ISlot() : kind(EMPTY_SLOT) {}
};
class IObject : public gc { public:
Type *type;
int nslots;
ISlot slot[1]; // nslots for real length
};
struct IFrame : public gc { public:
IThread *thread;
IFrame *parent;
Map<BaseAST *, ISlot *> env;
Vec<Stmt *> stmtStack;
Vec<int> stmtStageStack;
Vec<Expr *> exprStack;
Vec<ISlot *> valStack;
Stmt *stmt;
int stage;
Expr *expr;
BaseAST *ip;
ISlot *islot(BaseAST *ast);
void icall(int nargs);
void run(int timeslice);
IFrame(IThread *t, Stmt *s);
};
struct IThread : public gc { public:
IFrame *frame;
void run();
IThread(Stmt *s);
};
static int single_step = 0;
volatile static int interrupted = 0;
static Vec<IThread *> threads;
IFrame::IFrame(IThread *t, Stmt *s) : thread(t), parent(0), stmt(s), stage(0), expr(0), ip(s) {
assert(s && stmt && ip);
}
IThread::IThread(Stmt *s) : frame(0) {
frame = new IFrame(this, s);
}
ISlot *
IFrame::islot(BaseAST *ast) {
ISlot *s = env.get(ast);
if (!s)
env.put(ast, (s = new ISlot));
return s;
}
#define S(_t) _t *s = (_t *)ip; (void)s; if (trace_level > 0) printf( #_t " %p\n", s)
static void
check_type(BaseAST *ast, ISlot *slot, Type *t) {
if (slot->kind == EMPTY_SLOT)
USR_FATAL(ast, "interpreter: accessed empty variable");
if (slot->kind == UNINITIALIZED_SLOT)
USR_FATAL(ast, "interpreter: accessed uninitialized variable");
return;
}
void
IFrame::icall(int nargs) {
if (valStack.n < nargs)
INT_FATAL(ip, "not enough arguments for call");
char *name = 0;
ISlot **args = &valStack.v[valStack.n-(nargs + 1)];
if (nargs < 1)
USR_FATAL(ip, "call with no arguments");
int done = 0;
do {
if (args[0]->kind == SELECTOR_SLOT) {
name = args[0]->selector;
done = 1;
} else if (args[0]->kind == CLOSURE_SLOT) {
USR_FATAL(ip, "closures not handled yet");
} else
USR_FATAL(ip, "call to something other than function name or closure");
} while (!done);
Vec<FnSymbol *> visible;
ip->parentScope->getVisibleFunctions(&visible, cannonicalize_string(name));
if (visible.n != 1)
USR_FATAL(ip, "unable to resolve function to single function '%s'", name);
return;
}
static void
interactive_usage() {
fprintf(stdout, "chpl Interpreter Interactive Mode Commands:\n");
fprintf(stdout,
"\tp - print\n"
"\tc - continue\n"
"\tq - quit\n"
);
}
static void
handle_interrupt(int sig) {
interrupted = 1;
}
static void
interactive() {
while (1) {
interrupted = 0;
fprintf(stdout, "\n> ");
char cmd_buffer[512], *c = cmd_buffer;
cmd_buffer[0] = 0;
fgets(cmd_buffer, 511, stdin);
while (*c && isspace(*c)) c++;
switch (tolower(*c)) {
default: interactive_usage(); break;
case 'q': exit(0); break;
case 'c': return;
case 'p': break;
}
}
}
#define PUSH_EXPR(_e) do { valStack.add(islot(_e)); exprStack.add(_e); } while (0)
#define EVAL_EXPR(_e) do { exprStack.add(_e); } while (0)
#define EVAL_STMT(_s) do { stmtStageStack.add(stage + 1); stmtStack.add(stmt); stmt = _s; } while (0)
#define PUSH_SELECTOR(_s) do { ISlot *_slot = new ISlot; _slot->set_selector(_s); valStack.add(_slot); } while (0)
#define PUSH_VAL(_s) valStack.add(islot(_s))
#define POP_VAL(_s) *islot(_s) = *valStack.pop();
#define CALL(_n) icall(_n)
void
IThread::run() {
while (frame)
frame->run(0);
}
void
IFrame::run(int timeslice) {
assert(ip && stmt);
while (1) {
LgotoLabel:
if (timeslice && !--timeslice)
return;
if (interrupted || single_step)
interactive();
switch (ip->astType) {
default: INT_FATAL(ip, "interpreter: bad astType: %d", ip->astType);
case STMT: break;
case STMT_EXPR: {
S(ExprStmt);
EVAL_EXPR(s->expr);
break;
}
case STMT_RETURN: {
S(ReturnStmt);
switch (stage++) {
case 0:
PUSH_EXPR(s->expr);
break;
case 1: {
stage = 0;
ISlot *slot = valStack.pop();
thread->frame = parent;
if (parent)
parent->valStack.add(slot);
return;
}
default: INT_FATAL(ip, "interpreter: bad stage %d for astType: %d", stage, ip->astType); break;
}
break;
}
case STMT_BLOCK: {
S(BlockStmt);
EVAL_STMT((Stmt*)s->body->head->next);
break;
}
case STMT_WHILELOOP: {
S(WhileLoopStmt);
switch (stage) {
case 0:
stage = 1;
if (!s->isWhileDo)
EVAL_STMT(s->block);
break;
case 1:
stage = 2;
EVAL_EXPR(s->condition);
break;
case 2: {
ISlot *cond = islot(s->condition);
check_type(ip, cond, dtBoolean);
if (!cond->imm->v_bool)
stage = 0;
else {
stage = 1;
EVAL_STMT(s->block);
}
break;
}
default: INT_FATAL(ip, "interpreter: bad stage %d for astType: %d", stage, ip->astType); break;
}
break;
}
case STMT_FORLOOP: {
S(ForLoopStmt);
if (!s->indices || s->indices->length() != 1)
INT_FATAL(ip, "interpreter: bad number of indices");
if (!s->iterators || s->iterators->length() != 1)
INT_FATAL(ip, "interpreter: bad number of iterators");
Expr *iter = s->iterators->only();
Symbol *indice = s->indices->only()->sym;
BaseAST *loop_var = s;
switch (stage++) {
case 0:
EVAL_EXPR(iter);
break;
case 1:
PUSH_SELECTOR("_forall_start");
PUSH_VAL(iter);
CALL(2);
break;
case 2:
POP_VAL(loop_var);
PUSH_SELECTOR("_forall_valid");
PUSH_VAL(iter);
PUSH_VAL(loop_var);
CALL(3);
break;
case 3: {
ISlot *valid = valStack.pop();
check_type(ip, valid, dtBoolean);
if (!valid->imm->v_bool) {
stage = 0;
break;
}
PUSH_SELECTOR("_forall_index");
PUSH_VAL(iter);
PUSH_VAL(loop_var);
CALL(3);
break;
}
case 4:
POP_VAL(indice);
EVAL_STMT(s->innerStmt);
break;
case 5:
PUSH_SELECTOR("_forall_next");
PUSH_VAL(iter);
PUSH_VAL(loop_var);
CALL(3);
break;
case 6:
stage = 2;
POP_VAL(loop_var);
break;
default: INT_FATAL(ip, "interpreter: bad stage %d for astType: %d", stage, ip->astType); break;
}
break;
}
case STMT_COND: {
S(CondStmt);
switch (stage++) {
case 0:
PUSH_EXPR(s->condExpr);
break;
case 1: {
stage = 0;
ISlot *cond = valStack.pop();
check_type(ip, cond, dtBoolean);
if (cond->imm->v_bool)
EVAL_STMT(s->thenStmt);
else
EVAL_STMT(s->elseStmt);
break;
}
default: INT_FATAL(ip, "interpreter: bad stage %d for astType: %d", stage, ip->astType); break;
}
break;
}
case STMT_WHEN: {
S(WhenStmt);
SelectStmt *select = (SelectStmt*)s->parentStmt;
assert(select->astType == STMT_SELECT);
break;
}
case STMT_SELECT: {
S(SelectStmt);
switch (stage++) {
case 0:
EVAL_EXPR(s->caseExpr);
break;
case 1:
stage = 0;
EVAL_STMT((Stmt*)s->whenStmts->head->next);
break;
default: INT_FATAL(ip, "interpreter: bad stage %d for astType: %d", stage, ip->astType); break;
}
break;
}
case STMT_LABEL: break;
case STMT_GOTO: {
S(GotoStmt);
stage = 0;
valStack.clear();
stmt = s->label->defPoint->parentStmt;
goto LgotoLabel;
}
case EXPR_SYM: {
S(SymExpr);
ISlot *x = env.get(s->var);
if (!x)
USR_FATAL(ip, "unknown variable in SymExpr'%s'", s->var->name ? s->var->name : "");
env.put(s, x);
break;
}
case EXPR_DEF: {
S(DefExpr);
ISlot *slot = new ISlot;
slot->kind = EMPTY_SLOT;
env.put(s->sym, slot);
if (trace_level)
printf(" '%s' %d\n", !s->sym->name ? "" : s->sym->name, (int)s->id);
break;
}
case EXPR_COND: {
S(CondExpr);
switch (stage++) {
case 0:
PUSH_EXPR(s->condExpr);
break;
case 1: {
stage = 0;
ISlot *cond = valStack.pop();
check_type(ip, cond, dtBoolean);
if (cond->imm->v_bool) {
EVAL_EXPR(s->thenExpr);
env.put(expr, islot(s->thenExpr));
} else {
EVAL_EXPR(s->elseExpr);
env.put(expr, islot(s->thenExpr));
}
break;
}
default: INT_FATAL(ip, "interpreter: bad stage %d for astType: %d", stage, ip->astType); break;
}
break;
}
case EXPR_CALL: {
S(CallExpr);
switch (stage++) {
case 0: {
switch (s->opTag) {
default:
INT_FATAL("unhandled CallExpr::opTag: %d\n", s->opTag);
break;
case OP_NONE:
PUSH_EXPR(s->baseExpr);
break;
}
break;
}
default:
if (stage <= s->argList->length()) {
PUSH_EXPR(s->argList->get(stage));
} else {
CALL(s->argList->length());
}
break;
}
}
case EXPR_CAST:
case EXPR_MEMBERACCESS:
case EXPR_REDUCE:
case EXPR_NAMED:
case EXPR_IMPORT:
break;
}
ip = expr = exprStack.pop();
if (!expr) {
if (!stage) {
ip = stmt = (Stmt*)stmt->next;
valStack.clear();
while (!stmt) {
stmt = stmtStack.pop();
stage = stmtStageStack.pop() - 1;
if (!stmt) {
thread->frame = parent;
return;
}
assert(stage >= 0);
ip = stmt = (Stmt*)stmt->next;
}
}
}
}
}
static void
initialize() {
signal(SIGINT, handle_interrupt);
}
void
runInterpreter(void) {
if (!run_interpreter)
return;
if (run_interpreter > 1)
interrupted = 1;
initialize();
forv_Vec(ModuleSymbol, mod, allModules)
(new IThread((Stmt*)mod->stmts->head->next))->run();
exit(0);
}
|
Fix compilation issue.
|
Fix compilation issue.
git-svn-id: 88467cb1fb04b8a755be7e1ee1026be4190196ef@4846 3a8e244f-b0f2-452b-bcba-4c88e055c3ca
|
C++
|
apache-2.0
|
sungeunchoi/chapel,sungeunchoi/chapel,sungeunchoi/chapel,chizarlicious/chapel,CoryMcCartan/chapel,hildeth/chapel,CoryMcCartan/chapel,CoryMcCartan/chapel,hildeth/chapel,chizarlicious/chapel,sungeunchoi/chapel,chizarlicious/chapel,chizarlicious/chapel,CoryMcCartan/chapel,hildeth/chapel,sungeunchoi/chapel,sungeunchoi/chapel,hildeth/chapel,CoryMcCartan/chapel,chizarlicious/chapel,sungeunchoi/chapel,hildeth/chapel,hildeth/chapel,CoryMcCartan/chapel,hildeth/chapel,chizarlicious/chapel,chizarlicious/chapel,CoryMcCartan/chapel,sungeunchoi/chapel
|
3a678223ebb531955b2f35d63c94720cfa9bd930
|
tools/unittests/MemoryPoolTest.cpp
|
tools/unittests/MemoryPoolTest.cpp
|
//===- MemoryPoolTest.cpp -------------------------------------------------===//
//
// The Bold Project
//
// This file is distributed under the New BSD License.
// See LICENSE for details.
//
//===----------------------------------------------------------------------===//
#include <pat/pat.h>
#include <bold/Support/MemoryPool.h>
#include <bold/Support/DataTypes.h>
#include <cstring>
using namespace bold;
//===----------------------------------------------------------------------===//
// Testcases
//===----------------------------------------------------------------------===//
namespace {
struct Element {
uint8_t a;
double b;
uint16_t c;
uint64_t d;
};
} // anonymous namespace
PAT_F( MemoryPoolTest, simple_allocate) {
MemoryPool<int, 32> int_array;
int* a = int_array.allocate();
new (a) int(3);
ASSERT_EQ(*a, 3);
ASSERT_EQ(int_array.size(), 1);
}
PAT_F( MemoryPoolTest, simple_allocate_more_than_a_slab) {
MemoryPool<int, 3> int_mem_pool;
int* a = int_mem_pool.allocate();
new (a) int(3);
ASSERT_TRUE(3 == *a);
ASSERT_TRUE(1 == int_mem_pool.size());
a = int_mem_pool.allocate();
new (a) int(2);
ASSERT_TRUE(2 == *a);
ASSERT_TRUE(2 == int_mem_pool.size());
a = int_mem_pool.allocate();
new (a) int(1);
ASSERT_TRUE(1 == *a);
ASSERT_TRUE(3 == int_mem_pool.size());
a = int_mem_pool.allocate();
new (a) int(0);
ASSERT_TRUE(0 == *a);
ASSERT_TRUE(4 == int_mem_pool.size());
int counter = 0;
MemoryPool<int, 3>::iterator it;
MemoryPool<int, 3>::iterator itEnd = int_mem_pool.end();
for (it = int_mem_pool.begin(); it != itEnd; ++it) {
++counter;
}
ASSERT_TRUE(4 == counter);
}
PAT_F( MemoryPoolTest, complex_allocate) {
MemoryPool<Element, 2> e_mempool;
Element* a = e_mempool.allocate();
a->a = '1';
a->b = 2.0;
a->c = 254;
a->d = -1;
ASSERT_TRUE(1 == e_mempool.size());
a = e_mempool.allocate();
ASSERT_TRUE(2 == e_mempool.size());
a = e_mempool.allocate();
ASSERT_TRUE(3 == e_mempool.size());
a = e_mempool.allocate();
ASSERT_TRUE(4 == e_mempool.size());
unsigned int counter = 0;
MemoryPool<Element, 2>::iterator it, End = e_mempool.end();
for (it = e_mempool.begin(); it != End; ++it) {
++counter;
}
ASSERT_TRUE(4 == counter);
}
PAT_F( MemoryPoolTest, complex_iterate) {
MemoryPool<Element, 2> e_mempool;
Element* a = e_mempool.allocate();
a->a = '1';
a->b = 2.0;
a->c = 254;
a->d = -1;
ASSERT_TRUE(1 == e_mempool.size());
MemoryPool<Element, 2>::iterator it = e_mempool.begin();
ASSERT_TRUE('1' == it->a);
ASSERT_TRUE(2.0 == it->b);
ASSERT_TRUE(254 == it->c);
ASSERT_TRUE(-1 == it->d);
a = e_mempool.allocate();
a->a = '2';
a->b = 3.0;
a->c = 253;
a->d = -2;
++it;
ASSERT_TRUE('2' == it->a);
ASSERT_TRUE(3.0 == it->b);
ASSERT_TRUE(253 == it->c);
ASSERT_TRUE(-2 == it->d);
a = e_mempool.allocate();
ASSERT_TRUE(3 == e_mempool.size());
a->a = '3';
a->b = 4.0;
a->c = 252;
a->d = -3;
++it;
ASSERT_TRUE('3' == it->a);
ASSERT_TRUE(4.0 == it->b);
ASSERT_TRUE(252 == it->c);
ASSERT_TRUE(-3 == it->d);
}
PAT_F( MemoryPoolTest, StringPoolTest )
{
MemoryPool<char, 10> str_pool;
char* str1 = str_pool.allocate(7);
str1[0] = 't';
str1[1] = 'h';
str1[2] = 'i';
str1[3] = 's';
str1[4] = ' ';
str1[5] = 'i';
str1[6] = '\0';
ASSERT_TRUE(6 == strlen(str1));
ASSERT_TRUE(7 == str_pool.size());
char* str2 = str_pool.allocate(4);
ASSERT_TRUE(14 == str_pool.size());
str2[0] = 's';
str2[1] = ' ';
str2[2] = 'a';
str2[3] = '\0';
ASSERT_TRUE(3 == strlen(str2));
}
|
//===- MemoryPoolTest.cpp -------------------------------------------------===//
//
// The Bold Project
//
// This file is distributed under the New BSD License.
// See LICENSE for details.
//
//===----------------------------------------------------------------------===//
#include <pat/pat.h>
#include <bold/Support/MemoryPool.h>
#include <bold/Support/DataTypes.h>
#include <cstring>
using namespace bold;
namespace {
struct Element {
uint8_t a;
double b;
uint16_t c;
uint64_t d;
};
} // anonymous namespace
//===----------------------------------------------------------------------===//
// Testcases
//===----------------------------------------------------------------------===//
PAT_F( MemoryPoolTest, simple_allocate)
{
MemoryPool<int, 32> int_array;
int* a = int_array.allocate();
new (a) int(3);
ASSERT_EQ(*a, 3);
ASSERT_EQ(int_array.size(), 1);
}
PAT_F( MemoryPoolTest, simple_allocate_more_than_a_slab)
{
MemoryPool<int, 3> int_mem_pool;
int* a = int_mem_pool.allocate();
new (a) int(3);
ASSERT_EQ(*a, 3);
ASSERT_EQ(int_mem_pool.size(), 1);
a = int_mem_pool.allocate();
new (a) int(2);
ASSERT_EQ(*a, 2);
ASSERT_EQ(int_mem_pool.size(), 2);
a = int_mem_pool.allocate();
new (a) int(1);
ASSERT_TRUE(1 == *a);
ASSERT_TRUE(3 == int_mem_pool.size());
a = int_mem_pool.allocate();
new (a) int(0);
ASSERT_TRUE(0 == *a);
ASSERT_TRUE(4 == int_mem_pool.size());
int counter = 0;
MemoryPool<int, 3>::iterator it;
MemoryPool<int, 3>::iterator itEnd = int_mem_pool.end();
for (it = int_mem_pool.begin(); it != itEnd; ++it) {
++counter;
}
ASSERT_TRUE(4 == counter);
}
PAT_F( MemoryPoolTest, complex_allocate)
{
MemoryPool<Element, 2> e_mempool;
Element* a = e_mempool.allocate();
a->a = '1';
a->b = 2.0;
a->c = 254;
a->d = -1;
EXPECT_EQ(e_mempool.size(), 1);
a = e_mempool.allocate();
ASSERT_TRUE(2 == e_mempool.size());
a = e_mempool.allocate();
ASSERT_TRUE(3 == e_mempool.size());
a = e_mempool.allocate();
ASSERT_TRUE(4 == e_mempool.size());
unsigned int counter = 0;
MemoryPool<Element, 2>::iterator it, End = e_mempool.end();
for (it = e_mempool.begin(); it != End; ++it) {
++counter;
}
ASSERT_TRUE(4 == counter);
}
PAT_F( MemoryPoolTest, complex_iterate)
{
MemoryPool<Element, 2> e_mempool;
Element* a = e_mempool.allocate();
a->a = '1';
a->b = 2.0;
a->c = 254;
a->d = -1;
EXPECT_EQ(e_mempool.size(), 1);
MemoryPool<Element, 2>::iterator it = e_mempool.begin();
ASSERT_TRUE('1' == it->a);
ASSERT_TRUE(2.0 == it->b);
ASSERT_TRUE(254 == it->c);
ASSERT_TRUE(-1 == it->d);
a = e_mempool.allocate();
a->a = '2';
a->b = 3.0;
a->c = 253;
a->d = -2;
++it;
ASSERT_TRUE('2' == it->a);
ASSERT_TRUE(3.0 == it->b);
ASSERT_TRUE(253 == it->c);
ASSERT_TRUE(-2 == it->d);
a = e_mempool.allocate();
ASSERT_TRUE(3 == e_mempool.size());
a->a = '3';
a->b = 4.0;
a->c = 252;
a->d = -3;
++it;
ASSERT_TRUE('3' == it->a);
ASSERT_TRUE(4.0 == it->b);
ASSERT_TRUE(252 == it->c);
ASSERT_TRUE(-3 == it->d);
}
PAT_F( MemoryPoolTest, StringPoolTest )
{
MemoryPool<char, 10> str_pool;
char* str1 = str_pool.allocate(7);
str1[0] = 't';
str1[1] = 'h';
str1[2] = 'i';
str1[3] = 's';
str1[4] = ' ';
str1[5] = 'i';
str1[6] = '\0';
ASSERT_TRUE(6 == strlen(str1));
ASSERT_TRUE(7 == str_pool.size());
char* str2 = str_pool.allocate(4);
ASSERT_TRUE(14 == str_pool.size());
str2[0] = 's';
str2[1] = ' ';
str2[2] = 'a';
str2[3] = '\0';
ASSERT_TRUE(3 == strlen(str2));
}
|
Replace ASSERT_TRUE by EXPECT_EQ if possible.
|
Replace ASSERT_TRUE by EXPECT_EQ if possible.
|
C++
|
bsd-3-clause
|
hjmeric/bold-utils,hjmeric/bold-utils,astrotycoon/bold-utils,astrotycoon/bold-utils
|
aeeeb255327fe6408a4aa24fc7db084ddfda6e13
|
src/test/base58_tests.cpp
|
src/test/base58_tests.cpp
|
#include <boost/test/unit_test.hpp>
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_writer_template.h"
#include "json/json_spirit_utils.h"
#include "base58.h"
#include "util.h"
using namespace json_spirit;
extern Array read_json(const std::string& filename);
BOOST_AUTO_TEST_SUITE(base58_tests)
// Goal: test low-level base58 encoding functionality
BOOST_AUTO_TEST_CASE(base58_EncodeBase58)
{
Array tests = read_json("base58_encode_decode.json");
BOOST_FOREACH(Value& tv, tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 2) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::vector<unsigned char> sourcedata = ParseHex(test[0].get_str());
std::string base58string = test[1].get_str();
BOOST_CHECK_MESSAGE(
EncodeBase58(&sourcedata[0], &sourcedata[sourcedata.size()]) == base58string,
strTest);
}
}
// Goal: test low-level base58 decoding functionality
BOOST_AUTO_TEST_CASE(base58_DecodeBase58)
{
Array tests = read_json("base58_encode_decode.json");
std::vector<unsigned char> result;
BOOST_FOREACH(Value& tv, tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 2) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::vector<unsigned char> expected = ParseHex(test[0].get_str());
std::string base58string = test[1].get_str();
BOOST_CHECK_MESSAGE(DecodeBase58(base58string, result), strTest);
BOOST_CHECK_MESSAGE(result.size() == expected.size() && std::equal(result.begin(), result.end(), expected.begin()), strTest);
}
BOOST_CHECK(!DecodeBase58("invalid", result));
}
// Visitor to check address type
class TestAddrTypeVisitor : public boost::static_visitor<bool>
{
private:
std::string exp_addrType;
public:
TestAddrTypeVisitor(const std::string &exp_addrType) : exp_addrType(exp_addrType) { }
bool operator()(const CKeyID &id) const
{
return (exp_addrType == "pubkey");
}
bool operator()(const CScriptID &id) const
{
return (exp_addrType == "script");
}
bool operator()(const CNoDestination &no) const
{
return (exp_addrType == "none");
}
};
// Visitor to check address payload
class TestPayloadVisitor : public boost::static_visitor<bool>
{
private:
std::vector<unsigned char> exp_payload;
public:
TestPayloadVisitor(std::vector<unsigned char> &exp_payload) : exp_payload(exp_payload) { }
bool operator()(const CKeyID &id) const
{
uint160 exp_key(exp_payload);
return exp_key == id;
}
bool operator()(const CScriptID &id) const
{
uint160 exp_key(exp_payload);
return exp_key == id;
}
bool operator()(const CNoDestination &no) const
{
return exp_payload.size() == 0;
}
};
// Gridcoin, 2017-03-18: Temporarily disable broken tests.
// Possibly due to difference in nVersion from raw data.
#if 0
// Goal: check that parsed keys match test payload
BOOST_AUTO_TEST_CASE(base58_keys_valid_parse)
{
Array tests = read_json("base58_keys_valid.json");
std::vector<unsigned char> result;
CBitcoinSecret secret;
CBitcoinAddress addr;
// Save global state
bool fTestNet_stored = fTestNet;
BOOST_FOREACH(Value& tv, tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 3) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::string exp_base58string = test[0].get_str();
std::vector<unsigned char> exp_payload = ParseHex(test[1].get_str());
const Object &metadata = test[2].get_obj();
bool isPrivkey = find_value(metadata, "isPrivkey").get_bool();
bool isTestnet = find_value(metadata, "isTestnet").get_bool();
fTestNet = isTestnet; // Override testnet flag
if(isPrivkey)
{
bool isCompressed = find_value(metadata, "isCompressed").get_bool();
// Must be valid private key
// Note: CBitcoinSecret::SetString tests isValid, whereas CBitcoinAddress does not!
BOOST_CHECK_MESSAGE(secret.SetString(exp_base58string), "!SetString:"+ strTest);
BOOST_CHECK_MESSAGE(secret.IsValid(), "!IsValid:" + strTest);
bool fCompressedOut = false;
CSecret privkey = secret.GetSecret(fCompressedOut);
BOOST_CHECK_MESSAGE(fCompressedOut == isCompressed, "compressed mismatch:" + strTest);
BOOST_CHECK_MESSAGE(privkey.size() == exp_payload.size() && std::equal(privkey.begin(), privkey.end(), exp_payload.begin()), "key mismatch:" + strTest);
// Private key must be invalid public key
addr.SetString(exp_base58string);
BOOST_CHECK_MESSAGE(!addr.IsValid(), "IsValid privkey as pubkey:" + strTest);
}
else
{
std::string exp_addrType = find_value(metadata, "addrType").get_str(); // "script" or "pubkey"
// Must be valid public key
BOOST_CHECK_MESSAGE(addr.SetString(exp_base58string), "SetString:" + strTest);
BOOST_CHECK_MESSAGE(addr.IsValid(), "!IsValid:" + strTest);
BOOST_CHECK_MESSAGE(addr.IsScript() == (exp_addrType == "script"), "isScript mismatch" + strTest);
CTxDestination dest = addr.Get();
BOOST_CHECK_MESSAGE(boost::apply_visitor(TestAddrTypeVisitor(exp_addrType), dest), "addrType mismatch" + strTest);
// Public key must be invalid private key
secret.SetString(exp_base58string);
BOOST_CHECK_MESSAGE(!secret.IsValid(), "IsValid pubkey as privkey:" + strTest);
}
}
// Restore global state
fTestNet = fTestNet_stored;
}
// Goal: check that generated keys match test vectors
BOOST_AUTO_TEST_CASE(base58_keys_valid_gen)
{
Array tests = read_json("base58_keys_valid.json");
std::vector<unsigned char> result;
// Save global state
bool fTestNet_stored = fTestNet;
BOOST_FOREACH(Value& tv, tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 3) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::string exp_base58string = test[0].get_str();
std::vector<unsigned char> exp_payload = ParseHex(test[1].get_str());
const Object &metadata = test[2].get_obj();
bool isPrivkey = find_value(metadata, "isPrivkey").get_bool();
bool isTestnet = find_value(metadata, "isTestnet").get_bool();
fTestNet = isTestnet; // Override testnet flag
if(isPrivkey)
{
bool isCompressed = find_value(metadata, "isCompressed").get_bool();
CBitcoinSecret secret;
secret.SetSecret(CSecret(exp_payload.begin(), exp_payload.end()), isCompressed);
BOOST_CHECK_MESSAGE(secret.ToString() == exp_base58string, "result mismatch: " + strTest);
}
else
{
std::string exp_addrType = find_value(metadata, "addrType").get_str();
CTxDestination dest;
if(exp_addrType == "pubkey")
{
dest = CKeyID(uint160(exp_payload));
}
else if(exp_addrType == "script")
{
dest = CScriptID(uint160(exp_payload));
}
else if(exp_addrType == "none")
{
dest = CNoDestination();
}
else
{
BOOST_ERROR("Bad addrtype: " << strTest);
continue;
}
CBitcoinAddress addrOut;
BOOST_CHECK_MESSAGE(boost::apply_visitor(CBitcoinAddressVisitor(&addrOut), dest), "encode dest: " + strTest);
BOOST_CHECK_MESSAGE(addrOut.ToString() == exp_base58string, "mismatch: " + strTest);
}
}
// Visiting a CNoDestination must fail
CBitcoinAddress dummyAddr;
CTxDestination nodest = CNoDestination();
BOOST_CHECK(!boost::apply_visitor(CBitcoinAddressVisitor(&dummyAddr), nodest));
// Restore global state
fTestNet = fTestNet_stored;
}
#endif
// Goal: check that base58 parsing code is robust against a variety of corrupted data
BOOST_AUTO_TEST_CASE(base58_keys_invalid)
{
Array tests = read_json("base58_keys_invalid.json"); // Negative testcases
std::vector<unsigned char> result;
CBitcoinSecret secret;
CBitcoinAddress addr;
BOOST_FOREACH(Value& tv, tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 1) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::string exp_base58string = test[0].get_str();
// must be invalid as public and as private key
addr.SetString(exp_base58string);
BOOST_CHECK_MESSAGE(!addr.IsValid(), "IsValid pubkey:" + strTest);
secret.SetString(exp_base58string);
BOOST_CHECK_MESSAGE(!secret.IsValid(), "IsValid privkey:" + strTest);
}
}
BOOST_AUTO_TEST_SUITE_END()
|
#include <boost/test/unit_test.hpp>
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_writer_template.h"
#include "json/json_spirit_utils.h"
#include "base58.h"
#include "util.h"
using namespace json_spirit;
extern Array read_json(const std::string& filename);
BOOST_AUTO_TEST_SUITE(base58_tests)
// Goal: test low-level base58 encoding functionality
BOOST_AUTO_TEST_CASE(base58_EncodeBase58)
{
Array tests = read_json("base58_encode_decode.json");
for(Value& tv : tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 2) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::vector<unsigned char> sourcedata = ParseHex(test[0].get_str());
std::string base58string = test[1].get_str();
BOOST_CHECK_MESSAGE(
EncodeBase58(&sourcedata[0], &sourcedata[sourcedata.size()]) == base58string,
strTest);
}
}
// Goal: test low-level base58 decoding functionality
BOOST_AUTO_TEST_CASE(base58_DecodeBase58)
{
Array tests = read_json("base58_encode_decode.json");
std::vector<unsigned char> result;
for(Value& tv : tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 2) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::vector<unsigned char> expected = ParseHex(test[0].get_str());
std::string base58string = test[1].get_str();
BOOST_CHECK_MESSAGE(DecodeBase58(base58string, result), strTest);
BOOST_CHECK_MESSAGE(result.size() == expected.size() && std::equal(result.begin(), result.end(), expected.begin()), strTest);
}
BOOST_CHECK(!DecodeBase58("invalid", result));
}
// Visitor to check address type
class TestAddrTypeVisitor : public boost::static_visitor<bool>
{
private:
std::string exp_addrType;
public:
TestAddrTypeVisitor(const std::string &exp_addrType) : exp_addrType(exp_addrType) { }
bool operator()(const CKeyID &id) const
{
return (exp_addrType == "pubkey");
}
bool operator()(const CScriptID &id) const
{
return (exp_addrType == "script");
}
bool operator()(const CNoDestination &no) const
{
return (exp_addrType == "none");
}
};
// Visitor to check address payload
class TestPayloadVisitor : public boost::static_visitor<bool>
{
private:
std::vector<unsigned char> exp_payload;
public:
TestPayloadVisitor(std::vector<unsigned char> &exp_payload) : exp_payload(exp_payload) { }
bool operator()(const CKeyID &id) const
{
uint160 exp_key(exp_payload);
return exp_key == id;
}
bool operator()(const CScriptID &id) const
{
uint160 exp_key(exp_payload);
return exp_key == id;
}
bool operator()(const CNoDestination &no) const
{
return exp_payload.size() == 0;
}
};
// Gridcoin, 2017-03-18: Temporarily disable broken tests.
// Possibly due to difference in nVersion from raw data.
#if 0
// Goal: check that parsed keys match test payload
BOOST_AUTO_TEST_CASE(base58_keys_valid_parse)
{
Array tests = read_json("base58_keys_valid.json");
std::vector<unsigned char> result;
CBitcoinSecret secret;
CBitcoinAddress addr;
// Save global state
bool fTestNet_stored = fTestNet;
for(Value& tv : tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 3) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::string exp_base58string = test[0].get_str();
std::vector<unsigned char> exp_payload = ParseHex(test[1].get_str());
const Object &metadata = test[2].get_obj();
bool isPrivkey = find_value(metadata, "isPrivkey").get_bool();
bool isTestnet = find_value(metadata, "isTestnet").get_bool();
fTestNet = isTestnet; // Override testnet flag
if(isPrivkey)
{
bool isCompressed = find_value(metadata, "isCompressed").get_bool();
// Must be valid private key
// Note: CBitcoinSecret::SetString tests isValid, whereas CBitcoinAddress does not!
BOOST_CHECK_MESSAGE(secret.SetString(exp_base58string), "!SetString:"+ strTest);
BOOST_CHECK_MESSAGE(secret.IsValid(), "!IsValid:" + strTest);
bool fCompressedOut = false;
CSecret privkey = secret.GetSecret(fCompressedOut);
BOOST_CHECK_MESSAGE(fCompressedOut == isCompressed, "compressed mismatch:" + strTest);
BOOST_CHECK_MESSAGE(privkey.size() == exp_payload.size() && std::equal(privkey.begin(), privkey.end(), exp_payload.begin()), "key mismatch:" + strTest);
// Private key must be invalid public key
addr.SetString(exp_base58string);
BOOST_CHECK_MESSAGE(!addr.IsValid(), "IsValid privkey as pubkey:" + strTest);
}
else
{
std::string exp_addrType = find_value(metadata, "addrType").get_str(); // "script" or "pubkey"
// Must be valid public key
BOOST_CHECK_MESSAGE(addr.SetString(exp_base58string), "SetString:" + strTest);
BOOST_CHECK_MESSAGE(addr.IsValid(), "!IsValid:" + strTest);
BOOST_CHECK_MESSAGE(addr.IsScript() == (exp_addrType == "script"), "isScript mismatch" + strTest);
CTxDestination dest = addr.Get();
BOOST_CHECK_MESSAGE(boost::apply_visitor(TestAddrTypeVisitor(exp_addrType), dest), "addrType mismatch" + strTest);
// Public key must be invalid private key
secret.SetString(exp_base58string);
BOOST_CHECK_MESSAGE(!secret.IsValid(), "IsValid pubkey as privkey:" + strTest);
}
}
// Restore global state
fTestNet = fTestNet_stored;
}
// Goal: check that generated keys match test vectors
BOOST_AUTO_TEST_CASE(base58_keys_valid_gen)
{
Array tests = read_json("base58_keys_valid.json");
std::vector<unsigned char> result;
// Save global state
bool fTestNet_stored = fTestNet;
for(Value& tv : tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 3) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::string exp_base58string = test[0].get_str();
std::vector<unsigned char> exp_payload = ParseHex(test[1].get_str());
const Object &metadata = test[2].get_obj();
bool isPrivkey = find_value(metadata, "isPrivkey").get_bool();
bool isTestnet = find_value(metadata, "isTestnet").get_bool();
fTestNet = isTestnet; // Override testnet flag
if(isPrivkey)
{
bool isCompressed = find_value(metadata, "isCompressed").get_bool();
CBitcoinSecret secret;
secret.SetSecret(CSecret(exp_payload.begin(), exp_payload.end()), isCompressed);
BOOST_CHECK_MESSAGE(secret.ToString() == exp_base58string, "result mismatch: " + strTest);
}
else
{
std::string exp_addrType = find_value(metadata, "addrType").get_str();
CTxDestination dest;
if(exp_addrType == "pubkey")
{
dest = CKeyID(uint160(exp_payload));
}
else if(exp_addrType == "script")
{
dest = CScriptID(uint160(exp_payload));
}
else if(exp_addrType == "none")
{
dest = CNoDestination();
}
else
{
BOOST_ERROR("Bad addrtype: " << strTest);
continue;
}
CBitcoinAddress addrOut;
BOOST_CHECK_MESSAGE(boost::apply_visitor(CBitcoinAddressVisitor(&addrOut), dest), "encode dest: " + strTest);
BOOST_CHECK_MESSAGE(addrOut.ToString() == exp_base58string, "mismatch: " + strTest);
}
}
// Visiting a CNoDestination must fail
CBitcoinAddress dummyAddr;
CTxDestination nodest = CNoDestination();
BOOST_CHECK(!boost::apply_visitor(CBitcoinAddressVisitor(&dummyAddr), nodest));
// Restore global state
fTestNet = fTestNet_stored;
}
#endif
// Goal: check that base58 parsing code is robust against a variety of corrupted data
BOOST_AUTO_TEST_CASE(base58_keys_invalid)
{
Array tests = read_json("base58_keys_invalid.json"); // Negative testcases
std::vector<unsigned char> result;
CBitcoinSecret secret;
CBitcoinAddress addr;
for(Value& tv : tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 1) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
std::string exp_base58string = test[0].get_str();
// must be invalid as public and as private key
addr.SetString(exp_base58string);
BOOST_CHECK_MESSAGE(!addr.IsValid(), "IsValid pubkey:" + strTest);
secret.SetString(exp_base58string);
BOOST_CHECK_MESSAGE(!secret.IsValid(), "IsValid privkey:" + strTest);
}
}
BOOST_AUTO_TEST_SUITE_END()
|
Use ranged based for loops instead of BOOST_FOREACH in base58_tests.
|
Use ranged based for loops instead of BOOST_FOREACH in base58_tests.
|
C++
|
mit
|
gridcoin/Gridcoin-Research,caraka/gridcoinresearch,fooforever/Gridcoin-Research,tomasbrod/Gridcoin-Research,Lederstrumpf/Gridcoin-Research,Git-Jiro/Gridcoin-Research,caraka/gridcoinresearch,gridcoin/Gridcoin-Research,TheCharlatan/Gridcoin-Research,TheCharlatan/Gridcoin-Research,theMarix/Gridcoin-Research,gridcoin/Gridcoin-Research,Git-Jiro/Gridcoin-Research,fooforever/Gridcoin-Research,theMarix/Gridcoin-Research,gridcoin/Gridcoin-Research,theMarix/Gridcoin-Research,fooforever/Gridcoin-Research,fooforever/Gridcoin-Research,TheCharlatan/Gridcoin-Research,gridcoin/Gridcoin-Research,Lederstrumpf/Gridcoin-Research,caraka/gridcoinresearch,tomasbrod/Gridcoin-Research,Lederstrumpf/Gridcoin-Research,tomasbrod/Gridcoin-Research,Git-Jiro/Gridcoin-Research,Git-Jiro/Gridcoin-Research,caraka/gridcoinresearch,gridcoin/Gridcoin-Research,Lederstrumpf/Gridcoin-Research,theMarix/Gridcoin-Research,tomasbrod/Gridcoin-Research,caraka/gridcoinresearch,Lederstrumpf/Gridcoin-Research,Git-Jiro/Gridcoin-Research,fooforever/Gridcoin-Research,fooforever/Gridcoin-Research,TheCharlatan/Gridcoin-Research,theMarix/Gridcoin-Research,tomasbrod/Gridcoin-Research,caraka/gridcoinresearch,TheCharlatan/Gridcoin-Research,theMarix/Gridcoin-Research,Lederstrumpf/Gridcoin-Research
|
c4979f77c1264f0099d1dfa278b1d9c18340b5f9
|
src/test/bech32_tests.cpp
|
src/test/bech32_tests.cpp
|
// Copyright (c) 2017 Pieter Wuille
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bech32.h>
#include <test/util/str.h>
#include <boost/test/unit_test.hpp>
#include <string>
BOOST_AUTO_TEST_SUITE(bech32_tests)
BOOST_AUTO_TEST_CASE(bech32_testvectors_valid)
{
static const std::string CASES[] = {
"A12UEL5L",
"a12uel5l",
"an83characterlonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1tt5tgs",
"abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw",
"11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqc8247j",
"split1checkupstagehandshakeupstreamerranterredcaperred2y9e3w",
"?1ezyfcl",
};
for (const std::string& str : CASES) {
const auto dec = bech32::Decode(str);
BOOST_CHECK(dec.encoding == bech32::Encoding::BECH32);
std::string recode = bech32::Encode(bech32::Encoding::BECH32, dec.hrp, dec.data);
BOOST_CHECK(!recode.empty());
BOOST_CHECK(CaseInsensitiveEqual(str, recode));
}
}
BOOST_AUTO_TEST_CASE(bech32m_testvectors_valid)
{
static const std::string CASES[] = {
"A1LQFN3A",
"a1lqfn3a",
"an83characterlonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11sg7hg6",
"abcdef1l7aum6echk45nj3s0wdvt2fg8x9yrzpqzd3ryx",
"11llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllludsr8",
"split1checkupstagehandshakeupstreamerranterredcaperredlc445v",
"?1v759aa"
};
for (const std::string& str : CASES) {
const auto dec = bech32::Decode(str);
BOOST_CHECK(dec.encoding == bech32::Encoding::BECH32M);
std::string recode = bech32::Encode(bech32::Encoding::BECH32M, dec.hrp, dec.data);
BOOST_CHECK(!recode.empty());
BOOST_CHECK(CaseInsensitiveEqual(str, recode));
}
}
BOOST_AUTO_TEST_CASE(bech32_testvectors_invalid)
{
static const std::string CASES[] = {
" 1nwldj5",
"\x7f""1axkwrx",
"\x80""1eym55h",
"an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx",
"pzry9x0s0muk",
"1pzry9x0s0muk",
"x1b4n0q5v",
"li1dgmt3",
"de1lg7wt\xff",
"A1G7SGD8",
"10a06t8",
"1qzzfhee",
"a12UEL5L",
"A12uEL5L",
};
for (const std::string& str : CASES) {
const auto dec = bech32::Decode(str);
BOOST_CHECK(dec.encoding == bech32::Encoding::INVALID);
}
}
BOOST_AUTO_TEST_CASE(bech32m_testvectors_invalid)
{
static const std::string CASES[] = {
" 1xj0phk",
"\x7f""1g6xzxy",
"\x80""1vctc34",
"an84characterslonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11d6pts4",
"qyrz8wqd2c9m",
"1qyrz8wqd2c9m",
"y1b0jsk6g",
"lt1igcx5c0",
"in1muywd",
"mm1crxm3i",
"au1s5cgom",
"M1VUXWEZ",
"16plkw9",
"1p2gdwpf"
};
for (const std::string& str : CASES) {
const auto dec = bech32::Decode(str);
BOOST_CHECK(dec.encoding == bech32::Encoding::INVALID);
}
}
BOOST_AUTO_TEST_SUITE_END()
|
// Copyright (c) 2017 Pieter Wuille
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bech32.h>
#include <test/util/str.h>
#include <boost/test/unit_test.hpp>
#include <string>
BOOST_AUTO_TEST_SUITE(bech32_tests)
BOOST_AUTO_TEST_CASE(bech32_testvectors_valid)
{
static const std::string CASES[] = {
"A12UEL5L",
"a12uel5l",
"an83characterlonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1tt5tgs",
"abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw",
"11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqc8247j",
"split1checkupstagehandshakeupstreamerranterredcaperred2y9e3w",
"?1ezyfcl",
};
for (const std::string& str : CASES) {
const auto dec = bech32::Decode(str);
BOOST_CHECK(dec.encoding == bech32::Encoding::BECH32);
std::string recode = bech32::Encode(bech32::Encoding::BECH32, dec.hrp, dec.data);
BOOST_CHECK(!recode.empty());
BOOST_CHECK(CaseInsensitiveEqual(str, recode));
}
}
BOOST_AUTO_TEST_CASE(bech32m_testvectors_valid)
{
static const std::string CASES[] = {
"A1LQFN3A",
"a1lqfn3a",
"an83characterlonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11sg7hg6",
"abcdef1l7aum6echk45nj3s0wdvt2fg8x9yrzpqzd3ryx",
"11llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllludsr8",
"split1checkupstagehandshakeupstreamerranterredcaperredlc445v",
"?1v759aa"
};
for (const std::string& str : CASES) {
const auto dec = bech32::Decode(str);
BOOST_CHECK(dec.encoding == bech32::Encoding::BECH32M);
std::string recode = bech32::Encode(bech32::Encoding::BECH32M, dec.hrp, dec.data);
BOOST_CHECK(!recode.empty());
BOOST_CHECK(CaseInsensitiveEqual(str, recode));
}
}
BOOST_AUTO_TEST_CASE(bech32_testvectors_invalid)
{
static const std::string CASES[] = {
" 1nwldj5",
"\x7f""1axkwrx",
"\x80""1eym55h",
"an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx",
"pzry9x0s0muk",
"1pzry9x0s0muk",
"x1b4n0q5v",
"li1dgmt3",
"de1lg7wt\xff",
"A1G7SGD8",
"10a06t8",
"1qzzfhee",
"a12UEL5L",
"A12uEL5L",
"abcdef1qpzrz9x8gf2tvdw0s3jn54khce6mua7lmqqqxw",
};
static const std::pair<std::string, int> ERRORS[] = {
{"Invalid character or mixed case", 0},
{"Invalid character or mixed case", 0},
{"Invalid character or mixed case", 0},
{"Bech32 string too long", 90},
{"Missing separator", -1},
{"Invalid separator position", 0},
{"Invalid Base 32 character", 2},
{"Invalid separator position", 2},
{"Invalid character or mixed case", 8},
{"Invalid checksum", -1}, // The checksum is calculated using the uppercase form so the entire string is invalid, not just a few characters
{"Invalid separator position", 0},
{"Invalid separator position", 0},
{"Invalid character or mixed case", 3},
{"Invalid character or mixed case", 3},
{"Invalid checksum", 11}
};
int i = 0;
for (const std::string& str : CASES) {
const auto& err = ERRORS[i];
const auto dec = bech32::Decode(str);
BOOST_CHECK(dec.encoding == bech32::Encoding::INVALID);
std::vector<int> error_locations;
std::string error = bech32::LocateErrors(str, error_locations);
BOOST_CHECK_EQUAL(err.first, error);
if (err.second == -1) BOOST_CHECK(error_locations.empty());
else BOOST_CHECK_EQUAL(err.second, error_locations[0]);
i++;
}
}
BOOST_AUTO_TEST_CASE(bech32m_testvectors_invalid)
{
static const std::string CASES[] = {
" 1xj0phk",
"\x7f""1g6xzxy",
"\x80""1vctc34",
"an84characterslonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11d6pts4",
"qyrz8wqd2c9m",
"1qyrz8wqd2c9m",
"y1b0jsk6g",
"lt1igcx5c0",
"in1muywd",
"mm1crxm3i",
"au1s5cgom",
"M1VUXWEZ",
"16plkw9",
"1p2gdwpf",
"abcdef1l7aum6echk45nj2s0wdvt2fg8x9yrzpqzd3ryx",
};
static const std::pair<std::string, int> ERRORS[] = {
{"Invalid character or mixed case", 0},
{"Invalid character or mixed case", 0},
{"Invalid character or mixed case", 0},
{"Bech32 string too long", 90},
{"Missing separator", -1},
{"Invalid separator position", 0},
{"Invalid Base 32 character", 2},
{"Invalid Base 32 character", 3},
{"Invalid separator position", 2},
{"Invalid Base 32 character", 8},
{"Invalid Base 32 character", 7},
{"Invalid checksum", -1},
{"Invalid separator position", 0},
{"Invalid separator position", 0},
{"Invalid checksum", 21},
};
int i = 0;
for (const std::string& str : CASES) {
const auto& err = ERRORS[i];
const auto dec = bech32::Decode(str);
BOOST_CHECK(dec.encoding == bech32::Encoding::INVALID);
std::vector<int> error_locations;
std::string error = bech32::LocateErrors(str, error_locations);
BOOST_CHECK_EQUAL(err.first, error);
if (err.second == -1) BOOST_CHECK(error_locations.empty());
else BOOST_CHECK_EQUAL(err.second, error_locations[0]);
i++;
}
}
BOOST_AUTO_TEST_SUITE_END()
|
Add boost tests for bech32 error detection
|
Add boost tests for bech32 error detection
|
C++
|
mit
|
tecnovert/particl-core,bitcoin/bitcoin,dscotese/bitcoin,sipsorcery/bitcoin,MarcoFalke/bitcoin,particl/particl-core,jlopp/statoshi,Xekyo/bitcoin,mm-s/bitcoin,bitcoinsSG/bitcoin,fanquake/bitcoin,jamesob/bitcoin,namecoin/namecoin-core,jamesob/bitcoin,pataquets/namecoin-core,AkioNak/bitcoin,jamesob/bitcoin,fujicoin/fujicoin,bitcoin/bitcoin,bitcoinsSG/bitcoin,GroestlCoin/GroestlCoin,dscotese/bitcoin,bitcoinknots/bitcoin,jambolo/bitcoin,Xekyo/bitcoin,andreaskern/bitcoin,ajtowns/bitcoin,namecoin/namecore,particl/particl-core,lateminer/bitcoin,fanquake/bitcoin,domob1812/namecore,instagibbs/bitcoin,jamesob/bitcoin,GroestlCoin/bitcoin,GroestlCoin/bitcoin,bitcoinsSG/bitcoin,mruddy/bitcoin,mruddy/bitcoin,lateminer/bitcoin,sipsorcery/bitcoin,anditto/bitcoin,achow101/bitcoin,mruddy/bitcoin,Xekyo/bitcoin,AkioNak/bitcoin,fanquake/bitcoin,kallewoof/bitcoin,kallewoof/bitcoin,AkioNak/bitcoin,namecoin/namecore,andreaskern/bitcoin,jamesob/bitcoin,achow101/bitcoin,jambolo/bitcoin,instagibbs/bitcoin,Xekyo/bitcoin,namecoin/namecore,ajtowns/bitcoin,jlopp/statoshi,AkioNak/bitcoin,kallewoof/bitcoin,fujicoin/fujicoin,ajtowns/bitcoin,Xekyo/bitcoin,mm-s/bitcoin,dscotese/bitcoin,bitcoin/bitcoin,pataquets/namecoin-core,bitcoin/bitcoin,domob1812/namecore,domob1812/namecore,namecoin/namecore,namecoin/namecoin-core,andreaskern/bitcoin,bitcoinsSG/bitcoin,fujicoin/fujicoin,bitcoinsSG/bitcoin,tecnovert/particl-core,bitcoinknots/bitcoin,jambolo/bitcoin,mm-s/bitcoin,MarcoFalke/bitcoin,particl/particl-core,ajtowns/bitcoin,mm-s/bitcoin,namecoin/namecoin-core,anditto/bitcoin,kallewoof/bitcoin,particl/particl-core,bitcoinknots/bitcoin,domob1812/bitcoin,fanquake/bitcoin,jlopp/statoshi,lateminer/bitcoin,GroestlCoin/GroestlCoin,particl/particl-core,namecoin/namecoin-core,GroestlCoin/bitcoin,sipsorcery/bitcoin,jlopp/statoshi,mm-s/bitcoin,bitcoin/bitcoin,fanquake/bitcoin,pataquets/namecoin-core,achow101/bitcoin,pataquets/namecoin-core,sipsorcery/bitcoin,sstone/bitcoin,lateminer/bitcoin,bitcoin/bitcoin,pataquets/namecoin-core,namecoin/namecoin-core,mruddy/bitcoin,sstone/bitcoin,tecnovert/particl-core,sipsorcery/bitcoin,instagibbs/bitcoin,sstone/bitcoin,dscotese/bitcoin,GroestlCoin/bitcoin,tecnovert/particl-core,mm-s/bitcoin,pataquets/namecoin-core,domob1812/bitcoin,MarcoFalke/bitcoin,tecnovert/particl-core,mruddy/bitcoin,domob1812/bitcoin,domob1812/namecore,achow101/bitcoin,particl/particl-core,ajtowns/bitcoin,GroestlCoin/GroestlCoin,jambolo/bitcoin,anditto/bitcoin,fanquake/bitcoin,bitcoinknots/bitcoin,andreaskern/bitcoin,domob1812/bitcoin,MarcoFalke/bitcoin,fujicoin/fujicoin,bitcoinknots/bitcoin,instagibbs/bitcoin,fujicoin/fujicoin,jamesob/bitcoin,fujicoin/fujicoin,kallewoof/bitcoin,anditto/bitcoin,GroestlCoin/GroestlCoin,anditto/bitcoin,Xekyo/bitcoin,kallewoof/bitcoin,andreaskern/bitcoin,domob1812/bitcoin,namecoin/namecoin-core,dscotese/bitcoin,ajtowns/bitcoin,MarcoFalke/bitcoin,namecoin/namecore,GroestlCoin/bitcoin,domob1812/namecore,lateminer/bitcoin,sipsorcery/bitcoin,bitcoinsSG/bitcoin,jambolo/bitcoin,tecnovert/particl-core,AkioNak/bitcoin,domob1812/bitcoin,lateminer/bitcoin,sstone/bitcoin,GroestlCoin/GroestlCoin,dscotese/bitcoin,jlopp/statoshi,achow101/bitcoin,AkioNak/bitcoin,jlopp/statoshi,achow101/bitcoin,GroestlCoin/GroestlCoin,andreaskern/bitcoin,jambolo/bitcoin,GroestlCoin/bitcoin,instagibbs/bitcoin,sstone/bitcoin,MarcoFalke/bitcoin,mruddy/bitcoin,domob1812/namecore,anditto/bitcoin,namecoin/namecore,sstone/bitcoin,instagibbs/bitcoin
|
60aaa761963e1967dfb21d69d0b4a6a0c9f39c57
|
utils/TableGen/CodeEmitterGen.cpp
|
utils/TableGen/CodeEmitterGen.cpp
|
//===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// CodeEmitterGen uses the descriptions of instructions and their fields to
// construct an automated code emitter: a function that, given a MachineInstr,
// returns the (currently, 32-bit unsigned) value of the instruction.
//
//===----------------------------------------------------------------------===//
#include "CodeEmitterGen.h"
#include "CodeGenTarget.h"
#include "Record.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
static cl::opt<bool>
MCEmitter("mc-code-emitter",
cl::desc("Generate CodeEmitter for use with the MC library."),
cl::init(false));
void CodeEmitterGen::reverseBits(std::vector<Record*> &Insts) {
for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();
I != E; ++I) {
Record *R = *I;
if (R->getValueAsString("Namespace") == "TargetOpcode")
continue;
BitsInit *BI = R->getValueAsBitsInit("Inst");
unsigned numBits = BI->getNumBits();
BitsInit *NewBI = new BitsInit(numBits);
for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
unsigned bitSwapIdx = numBits - bit - 1;
Init *OrigBit = BI->getBit(bit);
Init *BitSwap = BI->getBit(bitSwapIdx);
NewBI->setBit(bit, BitSwap);
NewBI->setBit(bitSwapIdx, OrigBit);
}
if (numBits % 2) {
unsigned middle = (numBits + 1) / 2;
NewBI->setBit(middle, BI->getBit(middle));
}
// Update the bits in reversed order so that emitInstrOpBits will get the
// correct endianness.
R->getValue("Inst")->setValue(NewBI);
}
}
// If the VarBitInit at position 'bit' matches the specified variable then
// return the variable bit position. Otherwise return -1.
int CodeEmitterGen::getVariableBit(const std::string &VarName,
BitsInit *BI, int bit) {
if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(BI->getBit(bit))) {
TypedInit *TI = VBI->getVariable();
if (VarInit *VI = dynamic_cast<VarInit*>(TI)) {
if (VI->getName() == VarName) return VBI->getBitNum();
}
}
return -1;
}
void CodeEmitterGen::run(raw_ostream &o) {
CodeGenTarget Target;
std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
// For little-endian instruction bit encodings, reverse the bit order
if (Target.isLittleEndianEncoding()) reverseBits(Insts);
EmitSourceFileHeader("Machine Code Emitter", o);
std::string Namespace = Insts[0]->getValueAsString("Namespace") + "::";
const std::vector<const CodeGenInstruction*> &NumberedInstructions =
Target.getInstructionsByEnumValue();
// Emit function declaration
o << "unsigned " << Target.getName() << "CodeEmitter::"
<< "getBinaryCodeForInstr(const MachineInstr &MI) const {\n";
// Emit instruction base values
o << " static const unsigned InstBits[] = {\n";
for (std::vector<const CodeGenInstruction*>::const_iterator
IN = NumberedInstructions.begin(),
EN = NumberedInstructions.end();
IN != EN; ++IN) {
const CodeGenInstruction *CGI = *IN;
Record *R = CGI->TheDef;
if (R->getValueAsString("Namespace") == "TargetOpcode") {
o << " 0U,\n";
continue;
}
BitsInit *BI = R->getValueAsBitsInit("Inst");
// Start by filling in fixed values...
unsigned Value = 0;
for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) {
Value |= B->getValue() << (e-i-1);
}
}
o << " " << Value << "U," << '\t' << "// " << R->getName() << "\n";
}
o << " 0U\n };\n";
// Map to accumulate all the cases.
std::map<std::string, std::vector<std::string> > CaseMap;
// Construct all cases statement for each opcode
for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
IC != EC; ++IC) {
Record *R = *IC;
if (R->getValueAsString("Namespace") == "TargetOpcode")
continue;
const std::string &InstName = R->getName();
std::string Case("");
BitsInit *BI = R->getValueAsBitsInit("Inst");
const std::vector<RecordVal> &Vals = R->getValues();
CodeGenInstruction &CGI = Target.getInstruction(R);
// Loop over all of the fields in the instruction, determining which are the
// operands to the instruction.
unsigned NumberedOp = 0;
for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
if (!Vals[i].getPrefix() && !Vals[i].getValue()->isComplete()) {
// Is the operand continuous? If so, we can just mask and OR it in
// instead of doing it bit-by-bit, saving a lot in runtime cost.
const std::string &VarName = Vals[i].getName();
bool gotOp = false;
for (int bit = BI->getNumBits()-1; bit >= 0; ) {
int varBit = getVariableBit(VarName, BI, bit);
if (varBit == -1) {
--bit;
} else {
int beginInstBit = bit;
int beginVarBit = varBit;
int N = 1;
for (--bit; bit >= 0;) {
varBit = getVariableBit(VarName, BI, bit);
if (varBit == -1 || varBit != (beginVarBit - N)) break;
++N;
--bit;
}
if (!gotOp) {
// If the operand matches by name, reference according to that
// operand number. Non-matching operands are assumed to be in
// order.
unsigned OpIdx;
if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
// Get the machine operand number for the indicated operand.
OpIdx = CGI.Operands[OpIdx].MIOperandNo;
assert (!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
"Explicitly used operand also marked as not emitted!");
} else {
/// If this operand is not supposed to be emitted by the
/// generated emitter, skip it.
while (CGI.Operands.isFlatOperandNotEmitted(NumberedOp))
++NumberedOp;
OpIdx = NumberedOp++;
}
std::pair<unsigned, unsigned> SO =
CGI.Operands.getSubOperandNumber(OpIdx);
std::string &EncoderMethodName =
CGI.Operands[SO.first].EncoderMethodName;
// If the source operand has a custom encoder, use it. This will
// get the encoding for all of the suboperands.
if (!EncoderMethodName.empty()) {
// A custom encoder has all of the information for the
// sub-operands, if there are more than one, so only
// query the encoder once per source operand.
if (SO.second == 0) {
Case += " // op: " + VarName + "\n"
+ " op = " + EncoderMethodName + "(MI, "
+ utostr(OpIdx) + ");\n";
}
} else {
Case += " // op: " + VarName + "\n"
+ " op = getMachineOpValue(MI, MI.getOperand("
+ utostr(OpIdx) + "));\n";
}
gotOp = true;
}
unsigned opMask = ~0U >> (32-N);
int opShift = beginVarBit - N + 1;
opMask <<= opShift;
opShift = beginInstBit - beginVarBit;
if (opShift > 0) {
Case += " Value |= (op & " + utostr(opMask) + "U) << "
+ itostr(opShift) + ";\n";
} else if (opShift < 0) {
Case += " Value |= (op & " + utostr(opMask) + "U) >> "
+ itostr(-opShift) + ";\n";
} else {
Case += " Value |= op & " + utostr(opMask) + "U;\n";
}
}
}
}
}
std::vector<std::string> &InstList = CaseMap[Case];
InstList.push_back(InstName);
}
// Emit initial function code
o << " const unsigned opcode = MI.getOpcode();\n"
<< " unsigned Value = InstBits[opcode];\n"
<< " unsigned op = 0;\n"
<< " op = op; // suppress warning\n"
<< " switch (opcode) {\n";
// Emit each case statement
std::map<std::string, std::vector<std::string> >::iterator IE, EE;
for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
const std::string &Case = IE->first;
std::vector<std::string> &InstList = IE->second;
for (int i = 0, N = InstList.size(); i < N; i++) {
if (i) o << "\n";
o << " case " << Namespace << InstList[i] << ":";
}
o << " {\n";
o << Case;
o << " break;\n"
<< " }\n";
}
// Default case: unhandled opcode
o << " default:\n"
<< " std::string msg;\n"
<< " raw_string_ostream Msg(msg);\n"
<< " Msg << \"Not supported instr: \" << MI;\n"
<< " report_fatal_error(Msg.str());\n"
<< " }\n"
<< " return Value;\n"
<< "}\n\n";
}
|
//===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// CodeEmitterGen uses the descriptions of instructions and their fields to
// construct an automated code emitter: a function that, given a MachineInstr,
// returns the (currently, 32-bit unsigned) value of the instruction.
//
//===----------------------------------------------------------------------===//
#include "CodeEmitterGen.h"
#include "CodeGenTarget.h"
#include "Record.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
// FIXME: Somewhat hackish to use a command line option for this. There should
// be a CodeEmitter class in the Target.td that controls this sort of thing
// instead.
static cl::opt<bool>
MCEmitter("mc-emitter",
cl::desc("Generate CodeEmitter for use with the MC library."),
cl::init(false));
void CodeEmitterGen::reverseBits(std::vector<Record*> &Insts) {
for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();
I != E; ++I) {
Record *R = *I;
if (R->getValueAsString("Namespace") == "TargetOpcode")
continue;
BitsInit *BI = R->getValueAsBitsInit("Inst");
unsigned numBits = BI->getNumBits();
BitsInit *NewBI = new BitsInit(numBits);
for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
unsigned bitSwapIdx = numBits - bit - 1;
Init *OrigBit = BI->getBit(bit);
Init *BitSwap = BI->getBit(bitSwapIdx);
NewBI->setBit(bit, BitSwap);
NewBI->setBit(bitSwapIdx, OrigBit);
}
if (numBits % 2) {
unsigned middle = (numBits + 1) / 2;
NewBI->setBit(middle, BI->getBit(middle));
}
// Update the bits in reversed order so that emitInstrOpBits will get the
// correct endianness.
R->getValue("Inst")->setValue(NewBI);
}
}
// If the VarBitInit at position 'bit' matches the specified variable then
// return the variable bit position. Otherwise return -1.
int CodeEmitterGen::getVariableBit(const std::string &VarName,
BitsInit *BI, int bit) {
if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(BI->getBit(bit))) {
TypedInit *TI = VBI->getVariable();
if (VarInit *VI = dynamic_cast<VarInit*>(TI)) {
if (VI->getName() == VarName) return VBI->getBitNum();
}
}
return -1;
}
void CodeEmitterGen::run(raw_ostream &o) {
CodeGenTarget Target;
std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
// For little-endian instruction bit encodings, reverse the bit order
if (Target.isLittleEndianEncoding()) reverseBits(Insts);
EmitSourceFileHeader("Machine Code Emitter", o);
std::string Namespace = Insts[0]->getValueAsString("Namespace") + "::";
const std::vector<const CodeGenInstruction*> &NumberedInstructions =
Target.getInstructionsByEnumValue();
// Emit function declaration
o << "unsigned " << Target.getName();
if (MCEmitter)
o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
<< " SmallVectorImpl<MCFixup> &Fixups) const {\n";
else
o << "CodeEmitter::getBinaryCodeForInstr(const MachineInstr &MI) const {\n";
// Emit instruction base values
o << " static const unsigned InstBits[] = {\n";
for (std::vector<const CodeGenInstruction*>::const_iterator
IN = NumberedInstructions.begin(),
EN = NumberedInstructions.end();
IN != EN; ++IN) {
const CodeGenInstruction *CGI = *IN;
Record *R = CGI->TheDef;
if (R->getValueAsString("Namespace") == "TargetOpcode") {
o << " 0U,\n";
continue;
}
BitsInit *BI = R->getValueAsBitsInit("Inst");
// Start by filling in fixed values...
unsigned Value = 0;
for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1))) {
Value |= B->getValue() << (e-i-1);
}
}
o << " " << Value << "U," << '\t' << "// " << R->getName() << "\n";
}
o << " 0U\n };\n";
// Map to accumulate all the cases.
std::map<std::string, std::vector<std::string> > CaseMap;
// Construct all cases statement for each opcode
for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
IC != EC; ++IC) {
Record *R = *IC;
if (R->getValueAsString("Namespace") == "TargetOpcode")
continue;
const std::string &InstName = R->getName();
std::string Case("");
BitsInit *BI = R->getValueAsBitsInit("Inst");
const std::vector<RecordVal> &Vals = R->getValues();
CodeGenInstruction &CGI = Target.getInstruction(R);
// Loop over all of the fields in the instruction, determining which are the
// operands to the instruction.
unsigned NumberedOp = 0;
for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
if (!Vals[i].getPrefix() && !Vals[i].getValue()->isComplete()) {
// Is the operand continuous? If so, we can just mask and OR it in
// instead of doing it bit-by-bit, saving a lot in runtime cost.
const std::string &VarName = Vals[i].getName();
bool gotOp = false;
for (int bit = BI->getNumBits()-1; bit >= 0; ) {
int varBit = getVariableBit(VarName, BI, bit);
if (varBit == -1) {
--bit;
} else {
int beginInstBit = bit;
int beginVarBit = varBit;
int N = 1;
for (--bit; bit >= 0;) {
varBit = getVariableBit(VarName, BI, bit);
if (varBit == -1 || varBit != (beginVarBit - N)) break;
++N;
--bit;
}
if (!gotOp) {
// If the operand matches by name, reference according to that
// operand number. Non-matching operands are assumed to be in
// order.
unsigned OpIdx;
if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
// Get the machine operand number for the indicated operand.
OpIdx = CGI.Operands[OpIdx].MIOperandNo;
assert (!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
"Explicitly used operand also marked as not emitted!");
} else {
/// If this operand is not supposed to be emitted by the
/// generated emitter, skip it.
while (CGI.Operands.isFlatOperandNotEmitted(NumberedOp))
++NumberedOp;
OpIdx = NumberedOp++;
}
std::pair<unsigned, unsigned> SO =
CGI.Operands.getSubOperandNumber(OpIdx);
std::string &EncoderMethodName =
CGI.Operands[SO.first].EncoderMethodName;
// If the source operand has a custom encoder, use it. This will
// get the encoding for all of the suboperands.
if (!EncoderMethodName.empty()) {
// A custom encoder has all of the information for the
// sub-operands, if there are more than one, so only
// query the encoder once per source operand.
if (SO.second == 0) {
Case += " // op: " + VarName + "\n"
+ " op = " + EncoderMethodName + "(MI, "
+ utostr(OpIdx);
if (MCEmitter)
Case += ", Fixups";
Case += ");\n";
}
} else {
Case += " // op: " + VarName + "\n"
+ " op = getMachineOpValue(MI, MI.getOperand("
+ utostr(OpIdx) + ")";
if (MCEmitter)
Case += ", Fixups";
Case += ");\n";
}
gotOp = true;
}
unsigned opMask = ~0U >> (32-N);
int opShift = beginVarBit - N + 1;
opMask <<= opShift;
opShift = beginInstBit - beginVarBit;
if (opShift > 0) {
Case += " Value |= (op & " + utostr(opMask) + "U) << "
+ itostr(opShift) + ";\n";
} else if (opShift < 0) {
Case += " Value |= (op & " + utostr(opMask) + "U) >> "
+ itostr(-opShift) + ";\n";
} else {
Case += " Value |= op & " + utostr(opMask) + "U;\n";
}
}
}
}
}
std::vector<std::string> &InstList = CaseMap[Case];
InstList.push_back(InstName);
}
// Emit initial function code
o << " const unsigned opcode = MI.getOpcode();\n"
<< " unsigned Value = InstBits[opcode];\n"
<< " unsigned op = 0;\n"
<< " op = op; // suppress warning\n"
<< " switch (opcode) {\n";
// Emit each case statement
std::map<std::string, std::vector<std::string> >::iterator IE, EE;
for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
const std::string &Case = IE->first;
std::vector<std::string> &InstList = IE->second;
for (int i = 0, N = InstList.size(); i < N; i++) {
if (i) o << "\n";
o << " case " << Namespace << InstList[i] << ":";
}
o << " {\n";
o << Case;
o << " break;\n"
<< " }\n";
}
// Default case: unhandled opcode
o << " default:\n"
<< " std::string msg;\n"
<< " raw_string_ostream Msg(msg);\n"
<< " Msg << \"Not supported instr: \" << MI;\n"
<< " report_fatal_error(Msg.str());\n"
<< " }\n"
<< " return Value;\n"
<< "}\n\n";
}
|
Support generating an MC'ized CodeEmitter directly. Maintain a reference to the Fixups list for the instruction so the operand encoders can add to it as needed.
|
Support generating an MC'ized CodeEmitter directly. Maintain a reference to the
Fixups list for the instruction so the operand encoders can add to it as
needed.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@118206 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
bsd-2-clause
|
chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,apple/swift-llvm,dslab-epfl/asap,dslab-epfl/asap
|
fd391715c361e8f5dc1ca6915ba49563b3b4d93f
|
Logger.cpp
|
Logger.cpp
|
/*
* Logger.cpp
*
Copyright (c) 2013 Collin Kidder, Michael Neuweiler, Charles Galpin
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "Logger.h"
#include "config.h"
#include "sys_io.h"
#include <due_wire.h>
#include <Wire_EEPROM.h>
#include <SDFat.h>
#include <SdFatUtil.h>
Logger::LogLevel Logger::logLevel = Logger::Info;
uint32_t Logger::lastLogTime = 0;
uint16_t Logger::fileBuffWritePtr = 0;
SdFile Logger::fileRef; //file we're logging to
uint8_t Logger::filebuffer[BUF_SIZE]; //size of buffer for file output
uint32_t Logger::lastWriteTime = 0;
/*
* Output a debug message with a variable amount of parameters.
* printf() style, see Logger::log()
*
*/
void Logger::debug(char *message, ...)
{
if (logLevel > Debug) {
return;
}
va_list args;
va_start(args, message);
Logger::log(Debug, message, args);
va_end(args);
}
/*
* Output a info message with a variable amount of parameters
* printf() style, see Logger::log()
*/
void Logger::info(char *message, ...)
{
if (logLevel > Info) {
return;
}
va_list args;
va_start(args, message);
Logger::log(Info, message, args);
va_end(args);
}
/*
* Output a warning message with a variable amount of parameters
* printf() style, see Logger::log()
*/
void Logger::warn(char *message, ...)
{
if (logLevel > Warn) {
return;
}
va_list args;
va_start(args, message);
Logger::log(Warn, message, args);
va_end(args);
}
/*
* Output a error message with a variable amount of parameters
* printf() style, see Logger::log()
*/
void Logger::error(char *message, ...)
{
if (logLevel > Error) {
return;
}
va_list args;
va_start(args, message);
Logger::log(Error, message, args);
va_end(args);
}
/*
* Output a comnsole message with a variable amount of parameters
* printf() style, see Logger::logMessage()
*/
void Logger::console(char *message, ...)
{
va_list args;
va_start(args, message);
Logger::logMessage(message, args);
va_end(args);
}
void Logger::buffPutChar(char c)
{
*(filebuffer + fileBuffWritePtr++) = c;
}
void Logger::buffPutString(char *c)
{
while (*c) *(filebuffer + fileBuffWritePtr++) = *c++;
}
void Logger::flushFileBuff()
{
Logger::debug("Write to SD Card %i bytes", fileBuffWritePtr);
lastWriteTime = millis();
if (fileRef.write(filebuffer, fileBuffWritePtr) != fileBuffWritePtr) {
Logger::error("Write to SDCard failed!");
SysSettings.useSD = false; //borked so stop trying.
fileBuffWritePtr = 0;
return;
}
fileRef.sync(); //needed in order to update the file if you aren't closing it ever
SysSettings.logToggle = !SysSettings.logToggle;
setLED(SysSettings.LED_LOGGING, SysSettings.logToggle);
fileBuffWritePtr = 0;
}
boolean Logger::setupFile()
{
if (!fileRef.isOpen()) //file not open. Try to open it.
{
String filename;
if (settings.appendFile == 1)
{
filename = String(settings.fileNameBase);
filename.concat(".");
filename.concat(settings.fileNameExt);
fileRef.open(filename.c_str(), O_APPEND | O_WRITE);
}
else {
filename = String(settings.fileNameBase);
filename.concat(settings.fileNum++);
filename.concat(".");
filename.concat(settings.fileNameExt);
EEPROM.write(EEPROM_PAGE, settings); //save settings to save updated filenum
fileRef.open(filename.c_str(), O_CREAT | O_TRUNC | O_WRITE);
}
if (!fileRef.isOpen())
{
Logger::error("open failed");
return false;
}
}
//Before we add the next frame see if the buffer is nearly full. if so flush it first.
if (fileBuffWritePtr > BUF_SIZE - 40)
{
flushFileBuff();
}
return true;
}
void Logger::loop()
{
if (fileBuffWritePtr > 0) {
if (millis() > (lastWriteTime + 1000)) //if it's been at least 1second since the last write and we have data to write
{
flushFileBuff();
}
}
}
void Logger::file(char *message, ...)
{
if (!SysSettings.SDCardInserted) return; // not possible to log without card
char buff[20];
va_list args;
va_start(args, message);
if (!setupFile()) return;
for (; *message != 0; ++message) {
if (*message == '%') {
++message;
if (*message == '\0') {
break;
}
if (*message == '%') {
buffPutChar(*message);
continue;
}
if (*message == 's') {
register char *s = (char *)va_arg(args, int);
buffPutString(s);
continue;
}
if (*message == 'd' || *message == 'i') {
sprintf(buff, "%i", va_arg(args, int));
buffPutString(buff);
continue;
}
if (*message == 'f') {
sprintf(buff, "%f0.2", va_arg(args, double));
buffPutString(buff);
continue;
}
if (*message == 'x') {
sprintf(buff, "%x", va_arg(args, int));
buffPutString(buff);
continue;
}
if (*message == 'X') {
buffPutString("0x");
sprintf(buff, "%x", va_arg(args, int));
buffPutString(buff);
continue;
}
if (*message == 'l') {
sprintf(buff, "%l", va_arg(args, long));
buffPutString(buff);
continue;
}
if (*message == 'c') {
buffPutChar(va_arg(args, int));
continue;
}
if (*message == 't') {
if (va_arg(args, int) == 1) {
buffPutString("T");
}
else {
buffPutString("F");
}
continue;
}
if (*message == 'T') {
if (va_arg(args, int) == 1) {
buffPutString("TRUE");
}
else {
buffPutString("FALSE");
}
continue;
}
}
buffPutChar(*message);
}
buffPutString("\r\n");
va_end(args);
}
void Logger::fileRaw(uint8_t* buff, int sz)
{
if (!SysSettings.SDCardInserted) return; // not possible to log without card
if (!setupFile()) return;
for (int i; i < sz; i++) {
buffPutChar(*buff++);
}
}
/*
* Set the log level. Any output below the specified log level will be omitted.
*/
void Logger::setLoglevel(LogLevel level)
{
logLevel = level;
}
/*
* Retrieve the current log level.
*/
Logger::LogLevel Logger::getLogLevel()
{
return logLevel;
}
/*
* Return a timestamp when the last log entry was made.
*/
uint32_t Logger::getLastLogTime()
{
return lastLogTime;
}
/*
* Returns if debug log level is enabled. This can be used in time critical
* situations to prevent unnecessary string concatenation (if the message won't
* be logged in the end).
*
* Example:
* if (Logger::isDebug()) {
* Logger::debug("current time: %d", millis());
* }
*/
boolean Logger::isDebug()
{
return logLevel == Debug;
}
/*
* Output a log message (called by debug(), info(), warn(), error(), console())
*
* Supports printf() like syntax:
*
* %% - outputs a '%' character
* %s - prints the next parameter as string
* %d - prints the next parameter as decimal
* %f - prints the next parameter as double float
* %x - prints the next parameter as hex value
* %X - prints the next parameter as hex value with '0x' added before
* %b - prints the next parameter as binary value
* %B - prints the next parameter as binary value with '0b' added before
* %l - prints the next parameter as long
* %c - prints the next parameter as a character
* %t - prints the next parameter as boolean ('T' or 'F')
* %T - prints the next parameter as boolean ('true' or 'false')
*/
void Logger::log(LogLevel level, char *format, va_list args)
{
lastLogTime = millis();
SerialUSB.print(lastLogTime);
SerialUSB.print(" - ");
switch (level) {
case Debug:
SerialUSB.print("DEBUG");
break;
case Info:
SerialUSB.print("INFO");
break;
case Warn:
SerialUSB.print("WARNING");
break;
case Error:
SerialUSB.print("ERROR");
break;
}
SerialUSB.print(": ");
logMessage(format, args);
}
/*
* Output a log message (called by log(), console())
*
* Supports printf() like syntax:
*
* %% - outputs a '%' character
* %s - prints the next parameter as string
* %d - prints the next parameter as decimal
* %f - prints the next parameter as double float
* %x - prints the next parameter as hex value
* %X - prints the next parameter as hex value with '0x' added before
* %b - prints the next parameter as binary value
* %B - prints the next parameter as binary value with '0b' added before
* %l - prints the next parameter as long
* %c - prints the next parameter as a character
* %t - prints the next parameter as boolean ('T' or 'F')
* %T - prints the next parameter as boolean ('true' or 'false')
*/
void Logger::logMessage(char *format, va_list args)
{
for (; *format != 0; ++format) {
if (*format == '%') {
++format;
if (*format == '\0') {
break;
}
if (*format == '%') {
SerialUSB.print(*format);
continue;
}
if (*format == 's') {
register char *s = (char *) va_arg(args, int);
SerialUSB.print(s);
continue;
}
if (*format == 'd' || *format == 'i') {
SerialUSB.print(va_arg(args, int), DEC);
continue;
}
if (*format == 'f') {
SerialUSB.print(va_arg(args, double), 2);
continue;
}
if (*format == 'x') {
SerialUSB.print(va_arg(args, int), HEX);
continue;
}
if (*format == 'X') {
SerialUSB.print("0x");
SerialUSB.print(va_arg(args, int), HEX);
continue;
}
if (*format == 'b') {
SerialUSB.print(va_arg(args, int), BIN);
continue;
}
if (*format == 'B') {
SerialUSB.print("0b");
SerialUSB.print(va_arg(args, int), BIN);
continue;
}
if (*format == 'l') {
SerialUSB.print(va_arg(args, long), DEC);
continue;
}
if (*format == 'c') {
SerialUSB.print(va_arg(args, int));
continue;
}
if (*format == 't') {
if (va_arg(args, int) == 1) {
SerialUSB.print("T");
} else {
SerialUSB.print("F");
}
continue;
}
if (*format == 'T') {
if (va_arg(args, int) == 1) {
SerialUSB.print("TRUE");
} else {
SerialUSB.print("FALSE");
}
continue;
}
}
SerialUSB.print(*format);
}
SerialUSB.println();
}
|
/*
* Logger.cpp
*
Copyright (c) 2013 Collin Kidder, Michael Neuweiler, Charles Galpin
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "Logger.h"
#include "config.h"
#include "sys_io.h"
#include <due_wire.h>
#include <Wire_EEPROM.h>
#include <SdFat.h>
#include <SdFatUtil.h>
Logger::LogLevel Logger::logLevel = Logger::Info;
uint32_t Logger::lastLogTime = 0;
uint16_t Logger::fileBuffWritePtr = 0;
SdFile Logger::fileRef; //file we're logging to
uint8_t Logger::filebuffer[BUF_SIZE]; //size of buffer for file output
uint32_t Logger::lastWriteTime = 0;
/*
* Output a debug message with a variable amount of parameters.
* printf() style, see Logger::log()
*
*/
void Logger::debug(char *message, ...)
{
if (logLevel > Debug) {
return;
}
va_list args;
va_start(args, message);
Logger::log(Debug, message, args);
va_end(args);
}
/*
* Output a info message with a variable amount of parameters
* printf() style, see Logger::log()
*/
void Logger::info(char *message, ...)
{
if (logLevel > Info) {
return;
}
va_list args;
va_start(args, message);
Logger::log(Info, message, args);
va_end(args);
}
/*
* Output a warning message with a variable amount of parameters
* printf() style, see Logger::log()
*/
void Logger::warn(char *message, ...)
{
if (logLevel > Warn) {
return;
}
va_list args;
va_start(args, message);
Logger::log(Warn, message, args);
va_end(args);
}
/*
* Output a error message with a variable amount of parameters
* printf() style, see Logger::log()
*/
void Logger::error(char *message, ...)
{
if (logLevel > Error) {
return;
}
va_list args;
va_start(args, message);
Logger::log(Error, message, args);
va_end(args);
}
/*
* Output a comnsole message with a variable amount of parameters
* printf() style, see Logger::logMessage()
*/
void Logger::console(char *message, ...)
{
va_list args;
va_start(args, message);
Logger::logMessage(message, args);
va_end(args);
}
void Logger::buffPutChar(char c)
{
*(filebuffer + fileBuffWritePtr++) = c;
}
void Logger::buffPutString(char *c)
{
while (*c) *(filebuffer + fileBuffWritePtr++) = *c++;
}
void Logger::flushFileBuff()
{
Logger::debug("Write to SD Card %i bytes", fileBuffWritePtr);
lastWriteTime = millis();
if (fileRef.write(filebuffer, fileBuffWritePtr) != fileBuffWritePtr) {
Logger::error("Write to SDCard failed!");
SysSettings.useSD = false; //borked so stop trying.
fileBuffWritePtr = 0;
return;
}
fileRef.sync(); //needed in order to update the file if you aren't closing it ever
SysSettings.logToggle = !SysSettings.logToggle;
setLED(SysSettings.LED_LOGGING, SysSettings.logToggle);
fileBuffWritePtr = 0;
}
boolean Logger::setupFile()
{
if (!fileRef.isOpen()) //file not open. Try to open it.
{
String filename;
if (settings.appendFile == 1)
{
filename = String(settings.fileNameBase);
filename.concat(".");
filename.concat(settings.fileNameExt);
fileRef.open(filename.c_str(), O_APPEND | O_WRITE);
}
else {
filename = String(settings.fileNameBase);
filename.concat(settings.fileNum++);
filename.concat(".");
filename.concat(settings.fileNameExt);
EEPROM.write(EEPROM_PAGE, settings); //save settings to save updated filenum
fileRef.open(filename.c_str(), O_CREAT | O_TRUNC | O_WRITE);
}
if (!fileRef.isOpen())
{
Logger::error("open failed");
return false;
}
}
//Before we add the next frame see if the buffer is nearly full. if so flush it first.
if (fileBuffWritePtr > BUF_SIZE - 40)
{
flushFileBuff();
}
return true;
}
void Logger::loop()
{
if (fileBuffWritePtr > 0) {
if (millis() > (lastWriteTime + 1000)) //if it's been at least 1second since the last write and we have data to write
{
flushFileBuff();
}
}
}
void Logger::file(char *message, ...)
{
if (!SysSettings.SDCardInserted) return; // not possible to log without card
char buff[20];
va_list args;
va_start(args, message);
if (!setupFile()) return;
for (; *message != 0; ++message) {
if (*message == '%') {
++message;
if (*message == '\0') {
break;
}
if (*message == '%') {
buffPutChar(*message);
continue;
}
if (*message == 's') {
register char *s = (char *)va_arg(args, int);
buffPutString(s);
continue;
}
if (*message == 'd' || *message == 'i') {
sprintf(buff, "%i", va_arg(args, int));
buffPutString(buff);
continue;
}
if (*message == 'f') {
sprintf(buff, "%f0.2", va_arg(args, double));
buffPutString(buff);
continue;
}
if (*message == 'x') {
sprintf(buff, "%x", va_arg(args, int));
buffPutString(buff);
continue;
}
if (*message == 'X') {
buffPutString("0x");
sprintf(buff, "%x", va_arg(args, int));
buffPutString(buff);
continue;
}
if (*message == 'l') {
sprintf(buff, "%l", va_arg(args, long));
buffPutString(buff);
continue;
}
if (*message == 'c') {
buffPutChar(va_arg(args, int));
continue;
}
if (*message == 't') {
if (va_arg(args, int) == 1) {
buffPutString("T");
}
else {
buffPutString("F");
}
continue;
}
if (*message == 'T') {
if (va_arg(args, int) == 1) {
buffPutString("TRUE");
}
else {
buffPutString("FALSE");
}
continue;
}
}
buffPutChar(*message);
}
buffPutString("\r\n");
va_end(args);
}
void Logger::fileRaw(uint8_t* buff, int sz)
{
if (!SysSettings.SDCardInserted) return; // not possible to log without card
if (!setupFile()) return;
for (int i; i < sz; i++) {
buffPutChar(*buff++);
}
}
/*
* Set the log level. Any output below the specified log level will be omitted.
*/
void Logger::setLoglevel(LogLevel level)
{
logLevel = level;
}
/*
* Retrieve the current log level.
*/
Logger::LogLevel Logger::getLogLevel()
{
return logLevel;
}
/*
* Return a timestamp when the last log entry was made.
*/
uint32_t Logger::getLastLogTime()
{
return lastLogTime;
}
/*
* Returns if debug log level is enabled. This can be used in time critical
* situations to prevent unnecessary string concatenation (if the message won't
* be logged in the end).
*
* Example:
* if (Logger::isDebug()) {
* Logger::debug("current time: %d", millis());
* }
*/
boolean Logger::isDebug()
{
return logLevel == Debug;
}
/*
* Output a log message (called by debug(), info(), warn(), error(), console())
*
* Supports printf() like syntax:
*
* %% - outputs a '%' character
* %s - prints the next parameter as string
* %d - prints the next parameter as decimal
* %f - prints the next parameter as double float
* %x - prints the next parameter as hex value
* %X - prints the next parameter as hex value with '0x' added before
* %b - prints the next parameter as binary value
* %B - prints the next parameter as binary value with '0b' added before
* %l - prints the next parameter as long
* %c - prints the next parameter as a character
* %t - prints the next parameter as boolean ('T' or 'F')
* %T - prints the next parameter as boolean ('true' or 'false')
*/
void Logger::log(LogLevel level, char *format, va_list args)
{
lastLogTime = millis();
SerialUSB.print(lastLogTime);
SerialUSB.print(" - ");
switch (level) {
case Debug:
SerialUSB.print("DEBUG");
break;
case Info:
SerialUSB.print("INFO");
break;
case Warn:
SerialUSB.print("WARNING");
break;
case Error:
SerialUSB.print("ERROR");
break;
}
SerialUSB.print(": ");
logMessage(format, args);
}
/*
* Output a log message (called by log(), console())
*
* Supports printf() like syntax:
*
* %% - outputs a '%' character
* %s - prints the next parameter as string
* %d - prints the next parameter as decimal
* %f - prints the next parameter as double float
* %x - prints the next parameter as hex value
* %X - prints the next parameter as hex value with '0x' added before
* %b - prints the next parameter as binary value
* %B - prints the next parameter as binary value with '0b' added before
* %l - prints the next parameter as long
* %c - prints the next parameter as a character
* %t - prints the next parameter as boolean ('T' or 'F')
* %T - prints the next parameter as boolean ('true' or 'false')
*/
void Logger::logMessage(char *format, va_list args)
{
for (; *format != 0; ++format) {
if (*format == '%') {
++format;
if (*format == '\0') {
break;
}
if (*format == '%') {
SerialUSB.print(*format);
continue;
}
if (*format == 's') {
register char *s = (char *) va_arg(args, int);
SerialUSB.print(s);
continue;
}
if (*format == 'd' || *format == 'i') {
SerialUSB.print(va_arg(args, int), DEC);
continue;
}
if (*format == 'f') {
SerialUSB.print(va_arg(args, double), 2);
continue;
}
if (*format == 'x') {
SerialUSB.print(va_arg(args, int), HEX);
continue;
}
if (*format == 'X') {
SerialUSB.print("0x");
SerialUSB.print(va_arg(args, int), HEX);
continue;
}
if (*format == 'b') {
SerialUSB.print(va_arg(args, int), BIN);
continue;
}
if (*format == 'B') {
SerialUSB.print("0b");
SerialUSB.print(va_arg(args, int), BIN);
continue;
}
if (*format == 'l') {
SerialUSB.print(va_arg(args, long), DEC);
continue;
}
if (*format == 'c') {
SerialUSB.print(va_arg(args, int));
continue;
}
if (*format == 't') {
if (va_arg(args, int) == 1) {
SerialUSB.print("T");
} else {
SerialUSB.print("F");
}
continue;
}
if (*format == 'T') {
if (va_arg(args, int) == 1) {
SerialUSB.print("TRUE");
} else {
SerialUSB.print("FALSE");
}
continue;
}
}
SerialUSB.print(*format);
}
SerialUSB.println();
}
|
Correct another file case issue with headers
|
Correct another file case issue with headers
|
C++
|
mit
|
collin80/M2RET,collin80/M2RET
|
3ccad31d3963077b9879c9e18921e32213b9c32f
|
tensorflow/compiler/mlir/tensorflow/transforms/guarantee_all_funcs_one_use.cc
|
tensorflow/compiler/mlir/tensorflow/transforms/guarantee_all_funcs_one_use.cc
|
// Copyright 2020 Google LLC
//
// 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
//
// https://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 "llvm/ADT/STLExtras.h"
#include "mlir/IR/SymbolTable.h" // from @llvm-project
#include "mlir/Pass/Pass.h" // from @llvm-project
#include "mlir/Pass/PassRegistry.h" // from @llvm-project
#include "mlir/Support/LLVM.h" // from @llvm-project
#include "mlir/Support/LogicalResult.h" // from @llvm-project
#include "mlir/Transforms/Utils.h" // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
namespace mlir {
namespace TF {
namespace {
// Clones FuncOp's until they have a single use only (or no users).
//
// The tf-shape-inference pass doesn't support functions that have more than
// a single use. But some real code from frontends does end up creating code
// like that. For example, the same LSTM cell function or loop body function
// will be reused.
//
// This pass clones functions as needed to establish the invariant that all
// functions have a single use. This can in principle cause exponential code
// size bloat, and should in general be guided by a proper cost model.
//
// There are two factors which should be considered by a principled replacement
// to this pass:
//
// 1. TF currently relies on "sufficiently good shape inference" for
// correctness so for now the cost of doing this seems acceptable since
// pathological cases haven't hit us yet.
//
// 2. Cloning functions can help by allowing code to be specialized (much as
// inlining does). In fact, tf-shape-inference attempts to do specialization
// of callees which is difficult if callees have multiple uses.
class GuaranteeAllFuncsOneUse
: public PassWrapper<GuaranteeAllFuncsOneUse, OperationPass<ModuleOp>> {
public:
void runOnOperation() override {
if (failed(run())) {
signalPassFailure();
}
}
LogicalResult run() {
auto module = getOperation();
// Overall strategy:
// Fixed point iteration, iteratively applying a rule that clones
// any FuncOp with more than one use to eliminate its uses.
SymbolTable symbol_table(module);
bool made_changes = false;
// This value needs to be low enough to actually stop compilation in a
// reasonable time, but not too low that it blocks real programs.
// This number was chosen semi-randomly.
const int k_max_clones = 1000;
int num_clones = 0;
do {
made_changes = false;
for (auto func : llvm::make_early_inc_range(module.getOps<FuncOp>())) {
auto uses_optional = symbol_table.getSymbolUses(func, module);
if (!uses_optional.hasValue()) {
return func.emitError() << "could not walk uses of func";
}
auto &uses = *uses_optional;
if (llvm::size(uses) <= 1) {
continue;
}
// At this point, we know we are going to change the module.
made_changes = true;
for (const SymbolTable::SymbolUse &use : llvm::drop_begin(uses, 1)) {
if (num_clones++ > k_max_clones) {
return func.emitError()
<< "reached cloning limit (likely recursive call graph or "
"repeated diamond-like call structure "
"or just very large program)";
}
auto new_func = func.clone();
symbol_table.insert(new_func);
new_func.setVisibility(SymbolTable::Visibility::Private);
if (failed(symbol_table.replaceAllSymbolUses(func, new_func.getName(),
use.getUser()))) {
return func.emitError() << "could not replace symbol use";
}
}
}
} while (made_changes);
return success();
}
};
} // namespace
std::unique_ptr<OperationPass<ModuleOp>> CreateGuaranteeAllFuncsOneUsePass() {
return std::make_unique<GuaranteeAllFuncsOneUse>();
}
static PassRegistration<GuaranteeAllFuncsOneUse> pass(
"tf-guarantee-all-funcs-one-use",
"Guarantee all FuncOp's have only a single use.");
} // namespace TF
} // namespace mlir
|
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "llvm/ADT/STLExtras.h"
#include "mlir/IR/SymbolTable.h" // from @llvm-project
#include "mlir/Pass/Pass.h" // from @llvm-project
#include "mlir/Pass/PassRegistry.h" // from @llvm-project
#include "mlir/Support/LLVM.h" // from @llvm-project
#include "mlir/Support/LogicalResult.h" // from @llvm-project
#include "mlir/Transforms/Utils.h" // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
namespace mlir {
namespace TF {
namespace {
// Clones FuncOp's until they have a single use only (or no users).
//
// The tf-shape-inference pass doesn't support functions that have more than
// a single use. But some real code from frontends does end up creating code
// like that. For example, the same LSTM cell function or loop body function
// will be reused.
//
// This pass clones functions as needed to establish the invariant that all
// functions have a single use. This can in principle cause exponential code
// size bloat, and should in general be guided by a proper cost model.
//
// There are two factors which should be considered by a principled replacement
// to this pass:
//
// 1. TF currently relies on "sufficiently good shape inference" for
// correctness so for now the cost of doing this seems acceptable since
// pathological cases haven't hit us yet.
//
// 2. Cloning functions can help by allowing code to be specialized (much as
// inlining does). In fact, tf-shape-inference attempts to do specialization
// of callees which is difficult if callees have multiple uses.
class GuaranteeAllFuncsOneUse
: public PassWrapper<GuaranteeAllFuncsOneUse, OperationPass<ModuleOp>> {
public:
void runOnOperation() override {
if (failed(Run())) {
signalPassFailure();
}
}
LogicalResult Run() {
auto module = getOperation();
// Overall strategy:
// Fixed point iteration, iteratively applying a rule that clones
// any FuncOp with more than one use to eliminate its uses.
SymbolTable symbol_table(module);
bool made_changes = false;
// This value needs to be low enough to actually stop compilation in a
// reasonable time, but not too low that it blocks real programs.
// This number was chosen semi-randomly.
const int k_max_clones = 1000;
int num_clones = 0;
do {
made_changes = false;
for (auto func : llvm::make_early_inc_range(module.getOps<FuncOp>())) {
auto uses_optional = symbol_table.getSymbolUses(func, module);
if (!uses_optional.hasValue()) {
return func.emitError() << "could not walk uses of func";
}
auto &uses = *uses_optional;
if (llvm::size(uses) <= 1) {
continue;
}
// At this point, we know we are going to change the module.
made_changes = true;
for (const SymbolTable::SymbolUse &use : llvm::drop_begin(uses, 1)) {
if (num_clones++ > k_max_clones) {
return func.emitError()
<< "reached cloning limit (likely recursive call graph or "
"repeated diamond-like call structure "
"or just very large program)";
}
auto new_func = func.clone();
symbol_table.insert(new_func);
new_func.setVisibility(SymbolTable::Visibility::Private);
if (failed(symbol_table.replaceAllSymbolUses(func, new_func.getName(),
use.getUser()))) {
return func.emitError() << "could not replace symbol use";
}
}
}
} while (made_changes);
return success();
}
};
} // namespace
std::unique_ptr<OperationPass<ModuleOp>> CreateGuaranteeAllFuncsOneUsePass() {
return std::make_unique<GuaranteeAllFuncsOneUse>();
}
static PassRegistration<GuaranteeAllFuncsOneUse> pass(
"tf-guarantee-all-funcs-one-use",
"Guarantee all FuncOp's have only a single use.");
} // namespace TF
} // namespace mlir
|
Update copyright in GuaranteeAllFuncsOneUse to be of TensorFlow and update function names to match Google C++ Style Guide (NFC).
|
Update copyright in GuaranteeAllFuncsOneUse to be of TensorFlow and update function names to match Google C++ Style Guide (NFC).
PiperOrigin-RevId: 324622347
Change-Id: Ib1d19560afa26e4fef197b1694328e26f53ade8e
|
C++
|
apache-2.0
|
tensorflow/tensorflow-experimental_link_static_libraries_once,petewarden/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,annarev/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,sarvex/tensorflow,Intel-Corporation/tensorflow,karllessard/tensorflow,freedomtan/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,yongtang/tensorflow,annarev/tensorflow,davidzchen/tensorflow,aldian/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,davidzchen/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,cxxgtxy/tensorflow,petewarden/tensorflow,karllessard/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,annarev/tensorflow,freedomtan/tensorflow,frreiss/tensorflow-fred,annarev/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,aam-at/tensorflow,Intel-Corporation/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,davidzchen/tensorflow,sarvex/tensorflow,karllessard/tensorflow,aldian/tensorflow,tensorflow/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,cxxgtxy/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,aam-at/tensorflow,Intel-Corporation/tensorflow,annarev/tensorflow,yongtang/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,davidzchen/tensorflow,yongtang/tensorflow,freedomtan/tensorflow,aldian/tensorflow,tensorflow/tensorflow,karllessard/tensorflow,annarev/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,aam-at/tensorflow,tensorflow/tensorflow,petewarden/tensorflow,aam-at/tensorflow,gautam1858/tensorflow,sarvex/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,davidzchen/tensorflow,aldian/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,frreiss/tensorflow-fred,aam-at/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,annarev/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,aldian/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,frreiss/tensorflow-fred,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,petewarden/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,petewarden/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,annarev/tensorflow,paolodedios/tensorflow,Intel-tensorflow/tensorflow,sarvex/tensorflow,annarev/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow,aam-at/tensorflow,karllessard/tensorflow,davidzchen/tensorflow,aam-at/tensorflow,aam-at/tensorflow,aldian/tensorflow,cxxgtxy/tensorflow,Intel-tensorflow/tensorflow,davidzchen/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,petewarden/tensorflow,petewarden/tensorflow,cxxgtxy/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,gautam1858/tensorflow,frreiss/tensorflow-fred,frreiss/tensorflow-fred,paolodedios/tensorflow,aldian/tensorflow,freedomtan/tensorflow,yongtang/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,davidzchen/tensorflow,annarev/tensorflow,davidzchen/tensorflow,aam-at/tensorflow,aam-at/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,frreiss/tensorflow-fred,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,freedomtan/tensorflow,davidzchen/tensorflow,paolodedios/tensorflow,petewarden/tensorflow,yongtang/tensorflow,petewarden/tensorflow,freedomtan/tensorflow,Intel-Corporation/tensorflow,aam-at/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow,davidzchen/tensorflow,yongtang/tensorflow,freedomtan/tensorflow,sarvex/tensorflow,karllessard/tensorflow,frreiss/tensorflow-fred,gautam1858/tensorflow,sarvex/tensorflow,petewarden/tensorflow,davidzchen/tensorflow,petewarden/tensorflow,cxxgtxy/tensorflow,annarev/tensorflow,cxxgtxy/tensorflow,sarvex/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,aldian/tensorflow,Intel-tensorflow/tensorflow
|
acc884669b91a156fee3d5266f1ee3222ccdad75
|
clang-tidy/tool/ClangTidyMain.cpp
|
clang-tidy/tool/ClangTidyMain.cpp
|
//===--- tools/extra/clang-tidy/ClangTidyMain.cpp - Clang tidy tool -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file This file implements a clang-tidy tool.
///
/// This tool uses the Clang Tooling infrastructure, see
/// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
/// for details on setting it up with LLVM source tree.
///
//===----------------------------------------------------------------------===//
#include "../ClangTidy.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "llvm/Support/Process.h"
using namespace clang::ast_matchers;
using namespace clang::driver;
using namespace clang::tooling;
using namespace llvm;
static cl::OptionCategory ClangTidyCategory("clang-tidy options");
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
static cl::extrahelp ClangTidyHelp(
"Configuration files:\n"
" clang-tidy attempts to read configuration for each source file from a\n"
" .clang-tidy file located in the closest parent directory of the source\n"
" file. If any configuration options have a corresponding command-line\n"
" option, command-line option takes precedence. The effective\n"
" configuration can be inspected using -dump-config:\n"
"\n"
" $ clang-tidy -dump-config - --\n"
" ---\n"
" Checks: '-*,some-check'\n"
" HeaderFilterRegex: ''\n"
" AnalyzeTemporaryDtors: false\n"
" User: user\n"
" CheckOptions: \n"
" - key: some-check.SomeOption\n"
" value: 'some value'\n"
" ...\n"
"\n\n");
const char DefaultChecks[] = // Enable these checks:
"clang-diagnostic-*," // * compiler diagnostics
"clang-analyzer-*," // * Static Analyzer checks
"-clang-analyzer-alpha*"; // * but not alpha checks: many false positives
static cl::opt<std::string>
Checks("checks", cl::desc("Comma-separated list of globs with optional '-'\n"
"prefix. Globs are processed in order of appearance\n"
"in the list. Globs without '-' prefix add checks\n"
"with matching names to the set, globs with the '-'\n"
"prefix remove checks with matching names from the\n"
"set of enabled checks.\n"
"This option's value is appended to the value read\n"
"from a .clang-tidy file, if any."),
cl::init(""), cl::cat(ClangTidyCategory));
static cl::opt<std::string>
HeaderFilter("header-filter",
cl::desc("Regular expression matching the names of the\n"
"headers to output diagnostics from. Diagnostics\n"
"from the main file of each translation unit are\n"
"always displayed.\n"
"Can be used together with -line-filter.\n"
"This option overrides the value read from a\n"
".clang-tidy file."),
cl::init(""), cl::cat(ClangTidyCategory));
static cl::opt<bool>
SystemHeaders("system-headers",
cl::desc("Display the errors from system headers."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<std::string>
LineFilter("line-filter",
cl::desc("List of files with line ranges to filter the\n"
"warnings. Can be used together with\n"
"-header-filter. The format of the list is a JSON\n"
"array of objects:\n"
" [\n"
" {\"name\":\"file1.cpp\",\"lines\":[[1,3],[5,7]]},\n"
" {\"name\":\"file2.h\"}\n"
" ]"),
cl::init(""), cl::cat(ClangTidyCategory));
static cl::opt<bool>
Fix("fix", cl::desc("Apply suggested fixes. Without -fix-errors\n"
"clang-tidy will bail out if any compilation\n"
"errors were found."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<bool>
FixErrors("fix-errors",
cl::desc("Apply suggested fixes even if compilation errors\n"
"were found. If compiler errors have attached\n"
"fix-its, clang-tidy will apply them as well."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<bool>
ListChecks("list-checks",
cl::desc("List all enabled checks and exit. Use with\n"
"-checks=* to list all available checks."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<std::string> Config(
"config",
cl::desc("Specifies a configuration in YAML/JSON format:\n"
" -config=\"{Checks: '*', CheckOptions: [{key: x, value: y}]}\"\n"
"When the value is empty, clang-tidy will attempt to find\n"
"a file named .clang-tidy for each source file in its parent\n"
"directories."),
cl::init(""), cl::cat(ClangTidyCategory));
static cl::opt<bool> DumpConfig(
"dump-config",
cl::desc("Dumps configuration in the YAML format to stdout. This option\n"
"should be used along with a file name (and '--' if the file is\n"
"outside of a project with configured compilation database). The\n"
"configuration used for this file will be printed."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<bool> EnableCheckProfile(
"enable-check-profile",
cl::desc("Enable per-check timing profiles, and print a report to stderr."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<bool> AnalyzeTemporaryDtors(
"analyze-temporary-dtors",
cl::desc("Enable temporary destructor-aware analysis in\n"
"clang-analyzer- checks.\n"
"This option overrides the value read from a\n"
".clang-tidy file."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<std::string> ExportFixes(
"export-fixes",
cl::desc("YAML file to store suggested fixes in. The\n"
"stored fixes can be applied to the input source\n"
"code with clang-apply-replacements."),
cl::value_desc("filename"), cl::cat(ClangTidyCategory));
namespace clang {
namespace tidy {
static void printStats(const ClangTidyStats &Stats) {
if (Stats.errorsIgnored()) {
llvm::errs() << "Suppressed " << Stats.errorsIgnored() << " warnings (";
StringRef Separator = "";
if (Stats.ErrorsIgnoredNonUserCode) {
llvm::errs() << Stats.ErrorsIgnoredNonUserCode << " in non-user code";
Separator = ", ";
}
if (Stats.ErrorsIgnoredLineFilter) {
llvm::errs() << Separator << Stats.ErrorsIgnoredLineFilter
<< " due to line filter";
Separator = ", ";
}
if (Stats.ErrorsIgnoredNOLINT) {
llvm::errs() << Separator << Stats.ErrorsIgnoredNOLINT << " NOLINT";
Separator = ", ";
}
if (Stats.ErrorsIgnoredCheckFilter)
llvm::errs() << Separator << Stats.ErrorsIgnoredCheckFilter
<< " with check filters";
llvm::errs() << ").\n";
if (Stats.ErrorsIgnoredNonUserCode)
llvm::errs() << "Use -header-filter=.* to display errors from all "
"non-system headers.\n";
}
}
static void printProfileData(const ProfileData &Profile,
llvm::raw_ostream &OS) {
// Time is first to allow for sorting by it.
std::vector<std::pair<llvm::TimeRecord, StringRef>> Timers;
TimeRecord Total;
for (const auto& P : Profile.Records) {
Timers.emplace_back(P.getValue(), P.getKey());
Total += P.getValue();
}
std::sort(Timers.begin(), Timers.end());
std::string Line = "===" + std::string(73, '-') + "===\n";
OS << Line;
if (Total.getUserTime())
OS << " ---User Time---";
if (Total.getSystemTime())
OS << " --System Time--";
if (Total.getProcessTime())
OS << " --User+System--";
OS << " ---Wall Time---";
if (Total.getMemUsed())
OS << " ---Mem---";
OS << " --- Name ---\n";
// Loop through all of the timing data, printing it out.
for (auto I = Timers.rbegin(), E = Timers.rend(); I != E; ++I) {
I->first.print(Total, OS);
OS << I->second << '\n';
}
Total.print(Total, OS);
OS << "Total\n";
OS << Line << "\n";
OS.flush();
}
static std::unique_ptr<ClangTidyOptionsProvider> createOptionsProvider() {
ClangTidyGlobalOptions GlobalOptions;
if (std::error_code Err = parseLineFilter(LineFilter, GlobalOptions)) {
llvm::errs() << "Invalid LineFilter: " << Err.message() << "\n\nUsage:\n";
llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
return nullptr;
}
ClangTidyOptions DefaultOptions;
DefaultOptions.Checks = DefaultChecks;
DefaultOptions.HeaderFilterRegex = HeaderFilter;
DefaultOptions.SystemHeaders = SystemHeaders;
DefaultOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
DefaultOptions.User = llvm::sys::Process::GetEnv("USER");
// USERNAME is used on Windows.
if (!DefaultOptions.User)
DefaultOptions.User = llvm::sys::Process::GetEnv("USERNAME");
ClangTidyOptions OverrideOptions;
if (Checks.getNumOccurrences() > 0)
OverrideOptions.Checks = Checks;
if (HeaderFilter.getNumOccurrences() > 0)
OverrideOptions.HeaderFilterRegex = HeaderFilter;
if (SystemHeaders.getNumOccurrences() > 0)
OverrideOptions.SystemHeaders = SystemHeaders;
if (AnalyzeTemporaryDtors.getNumOccurrences() > 0)
OverrideOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
if (!Config.empty()) {
if (llvm::ErrorOr<ClangTidyOptions> ParsedConfig =
parseConfiguration(Config)) {
return llvm::make_unique<DefaultOptionsProvider>(
GlobalOptions, ClangTidyOptions::getDefaults()
.mergeWith(DefaultOptions)
.mergeWith(*ParsedConfig)
.mergeWith(OverrideOptions));
} else {
llvm::errs() << "Error: invalid configuration specified.\n"
<< ParsedConfig.getError().message() << "\n";
return nullptr;
}
}
return llvm::make_unique<FileOptionsProvider>(GlobalOptions, DefaultOptions,
OverrideOptions);
}
static int clangTidyMain(int argc, const char **argv) {
CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
cl::ZeroOrMore);
auto OptionsProvider = createOptionsProvider();
if (!OptionsProvider)
return 1;
StringRef FileName("dummy");
auto PathList = OptionsParser.getSourcePathList();
if (!PathList.empty()) {
FileName = OptionsParser.getSourcePathList().front();
}
ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FileName);
std::vector<std::string> EnabledChecks = getCheckNames(EffectiveOptions);
if (ListChecks) {
llvm::outs() << "Enabled checks:";
for (auto CheckName : EnabledChecks)
llvm::outs() << "\n " << CheckName;
llvm::outs() << "\n\n";
return 0;
}
if (DumpConfig) {
EffectiveOptions.CheckOptions = getCheckOptions(EffectiveOptions);
llvm::outs() << configurationAsText(
ClangTidyOptions::getDefaults().mergeWith(
EffectiveOptions))
<< "\n";
return 0;
}
if (EnabledChecks.empty()) {
llvm::errs() << "Error: no checks enabled.\n";
llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
return 1;
}
if (PathList.empty()) {
llvm::errs() << "Error: no input files specified.\n";
llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
return 1;
}
ProfileData Profile;
std::vector<ClangTidyError> Errors;
ClangTidyStats Stats =
runClangTidy(std::move(OptionsProvider), OptionsParser.getCompilations(),
PathList, &Errors,
EnableCheckProfile ? &Profile : nullptr);
bool FoundErrors =
std::find_if(Errors.begin(), Errors.end(), [](const ClangTidyError &E) {
return E.DiagLevel == ClangTidyError::Error;
}) != Errors.end();
const bool DisableFixes = Fix && FoundErrors && !FixErrors;
// -fix-errors implies -fix.
handleErrors(Errors, (FixErrors || Fix) && !DisableFixes);
if (!ExportFixes.empty() && !Errors.empty()) {
std::error_code EC;
llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None);
if (EC) {
llvm::errs() << "Error opening output file: " << EC.message() << '\n';
return 1;
}
exportReplacements(Errors, OS);
}
printStats(Stats);
if (DisableFixes)
llvm::errs()
<< "Found compiler errors, but -fix-errors was not specified.\n"
"Fixes have NOT been applied.\n\n";
if (EnableCheckProfile)
printProfileData(Profile, llvm::errs());
return 0;
}
// This anchor is used to force the linker to link the LLVMModule.
extern volatile int LLVMModuleAnchorSource;
static int LLVM_ATTRIBUTE_UNUSED LLVMModuleAnchorDestination = LLVMModuleAnchorSource;
// This anchor is used to force the linker to link the GoogleModule.
extern volatile int GoogleModuleAnchorSource;
static int LLVM_ATTRIBUTE_UNUSED GoogleModuleAnchorDestination = GoogleModuleAnchorSource;
// This anchor is used to force the linker to link the MiscModule.
extern volatile int MiscModuleAnchorSource;
static int LLVM_ATTRIBUTE_UNUSED MiscModuleAnchorDestination = MiscModuleAnchorSource;
// This anchor is used to force the linker to link the ModernizeModule.
extern volatile int ModernizeModuleAnchorSource;
static int ModernizeModuleAnchorDestination = ModernizeModuleAnchorSource;
// This anchor is used to force the linker to link the ReadabilityModule.
extern volatile int ReadabilityModuleAnchorSource;
static int LLVM_ATTRIBUTE_UNUSED ReadabilityModuleAnchorDestination = ReadabilityModuleAnchorSource;
} // namespace tidy
} // namespace clang
int main(int argc, const char **argv) {
return clang::tidy::clangTidyMain(argc, argv);
}
|
//===--- tools/extra/clang-tidy/ClangTidyMain.cpp - Clang tidy tool -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file This file implements a clang-tidy tool.
///
/// This tool uses the Clang Tooling infrastructure, see
/// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
/// for details on setting it up with LLVM source tree.
///
//===----------------------------------------------------------------------===//
#include "../ClangTidy.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "llvm/Support/Process.h"
using namespace clang::ast_matchers;
using namespace clang::driver;
using namespace clang::tooling;
using namespace llvm;
static cl::OptionCategory ClangTidyCategory("clang-tidy options");
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
static cl::extrahelp ClangTidyHelp(
"Configuration files:\n"
" clang-tidy attempts to read configuration for each source file from a\n"
" .clang-tidy file located in the closest parent directory of the source\n"
" file. If any configuration options have a corresponding command-line\n"
" option, command-line option takes precedence. The effective\n"
" configuration can be inspected using -dump-config:\n"
"\n"
" $ clang-tidy -dump-config - --\n"
" ---\n"
" Checks: '-*,some-check'\n"
" HeaderFilterRegex: ''\n"
" AnalyzeTemporaryDtors: false\n"
" User: user\n"
" CheckOptions: \n"
" - key: some-check.SomeOption\n"
" value: 'some value'\n"
" ...\n"
"\n\n");
const char DefaultChecks[] = // Enable these checks:
"clang-diagnostic-*," // * compiler diagnostics
"clang-analyzer-*," // * Static Analyzer checks
"-clang-analyzer-alpha*"; // * but not alpha checks: many false positives
static cl::opt<std::string>
Checks("checks", cl::desc("Comma-separated list of globs with optional '-'\n"
"prefix. Globs are processed in order of appearance\n"
"in the list. Globs without '-' prefix add checks\n"
"with matching names to the set, globs with the '-'\n"
"prefix remove checks with matching names from the\n"
"set of enabled checks.\n"
"This option's value is appended to the value read\n"
"from a .clang-tidy file, if any."),
cl::init(""), cl::cat(ClangTidyCategory));
static cl::opt<std::string>
HeaderFilter("header-filter",
cl::desc("Regular expression matching the names of the\n"
"headers to output diagnostics from. Diagnostics\n"
"from the main file of each translation unit are\n"
"always displayed.\n"
"Can be used together with -line-filter.\n"
"This option overrides the value read from a\n"
".clang-tidy file."),
cl::init(""), cl::cat(ClangTidyCategory));
static cl::opt<bool>
SystemHeaders("system-headers",
cl::desc("Display the errors from system headers."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<std::string>
LineFilter("line-filter",
cl::desc("List of files with line ranges to filter the\n"
"warnings. Can be used together with\n"
"-header-filter. The format of the list is a JSON\n"
"array of objects:\n"
" [\n"
" {\"name\":\"file1.cpp\",\"lines\":[[1,3],[5,7]]},\n"
" {\"name\":\"file2.h\"}\n"
" ]"),
cl::init(""), cl::cat(ClangTidyCategory));
static cl::opt<bool>
Fix("fix", cl::desc("Apply suggested fixes. Without -fix-errors\n"
"clang-tidy will bail out if any compilation\n"
"errors were found."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<bool>
FixErrors("fix-errors",
cl::desc("Apply suggested fixes even if compilation errors\n"
"were found. If compiler errors have attached\n"
"fix-its, clang-tidy will apply them as well."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<bool>
ListChecks("list-checks",
cl::desc("List all enabled checks and exit. Use with\n"
"-checks=* to list all available checks."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<std::string> Config(
"config",
cl::desc("Specifies a configuration in YAML/JSON format:\n"
" -config=\"{Checks: '*', CheckOptions: [{key: x, value: y}]}\"\n"
"When the value is empty, clang-tidy will attempt to find\n"
"a file named .clang-tidy for each source file in its parent\n"
"directories."),
cl::init(""), cl::cat(ClangTidyCategory));
static cl::opt<bool> DumpConfig(
"dump-config",
cl::desc("Dumps configuration in the YAML format to stdout. This option\n"
"should be used along with a file name (and '--' if the file is\n"
"outside of a project with configured compilation database). The\n"
"configuration used for this file will be printed."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<bool> EnableCheckProfile(
"enable-check-profile",
cl::desc("Enable per-check timing profiles, and print a report to stderr."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<bool> AnalyzeTemporaryDtors(
"analyze-temporary-dtors",
cl::desc("Enable temporary destructor-aware analysis in\n"
"clang-analyzer- checks.\n"
"This option overrides the value read from a\n"
".clang-tidy file."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<std::string> ExportFixes(
"export-fixes",
cl::desc("YAML file to store suggested fixes in. The\n"
"stored fixes can be applied to the input source\n"
"code with clang-apply-replacements."),
cl::value_desc("filename"), cl::cat(ClangTidyCategory));
namespace clang {
namespace tidy {
static void printStats(const ClangTidyStats &Stats) {
if (Stats.errorsIgnored()) {
llvm::errs() << "Suppressed " << Stats.errorsIgnored() << " warnings (";
StringRef Separator = "";
if (Stats.ErrorsIgnoredNonUserCode) {
llvm::errs() << Stats.ErrorsIgnoredNonUserCode << " in non-user code";
Separator = ", ";
}
if (Stats.ErrorsIgnoredLineFilter) {
llvm::errs() << Separator << Stats.ErrorsIgnoredLineFilter
<< " due to line filter";
Separator = ", ";
}
if (Stats.ErrorsIgnoredNOLINT) {
llvm::errs() << Separator << Stats.ErrorsIgnoredNOLINT << " NOLINT";
Separator = ", ";
}
if (Stats.ErrorsIgnoredCheckFilter)
llvm::errs() << Separator << Stats.ErrorsIgnoredCheckFilter
<< " with check filters";
llvm::errs() << ").\n";
if (Stats.ErrorsIgnoredNonUserCode)
llvm::errs() << "Use -header-filter=.* to display errors from all "
"non-system headers.\n";
}
}
static void printProfileData(const ProfileData &Profile,
llvm::raw_ostream &OS) {
// Time is first to allow for sorting by it.
std::vector<std::pair<llvm::TimeRecord, StringRef>> Timers;
TimeRecord Total;
for (const auto& P : Profile.Records) {
Timers.emplace_back(P.getValue(), P.getKey());
Total += P.getValue();
}
std::sort(Timers.begin(), Timers.end());
std::string Line = "===" + std::string(73, '-') + "===\n";
OS << Line;
if (Total.getUserTime())
OS << " ---User Time---";
if (Total.getSystemTime())
OS << " --System Time--";
if (Total.getProcessTime())
OS << " --User+System--";
OS << " ---Wall Time---";
if (Total.getMemUsed())
OS << " ---Mem---";
OS << " --- Name ---\n";
// Loop through all of the timing data, printing it out.
for (auto I = Timers.rbegin(), E = Timers.rend(); I != E; ++I) {
I->first.print(Total, OS);
OS << I->second << '\n';
}
Total.print(Total, OS);
OS << "Total\n";
OS << Line << "\n";
OS.flush();
}
static std::unique_ptr<ClangTidyOptionsProvider> createOptionsProvider() {
ClangTidyGlobalOptions GlobalOptions;
if (std::error_code Err = parseLineFilter(LineFilter, GlobalOptions)) {
llvm::errs() << "Invalid LineFilter: " << Err.message() << "\n\nUsage:\n";
llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
return nullptr;
}
ClangTidyOptions DefaultOptions;
DefaultOptions.Checks = DefaultChecks;
DefaultOptions.HeaderFilterRegex = HeaderFilter;
DefaultOptions.SystemHeaders = SystemHeaders;
DefaultOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
DefaultOptions.User = llvm::sys::Process::GetEnv("USER");
// USERNAME is used on Windows.
if (!DefaultOptions.User)
DefaultOptions.User = llvm::sys::Process::GetEnv("USERNAME");
ClangTidyOptions OverrideOptions;
if (Checks.getNumOccurrences() > 0)
OverrideOptions.Checks = Checks;
if (HeaderFilter.getNumOccurrences() > 0)
OverrideOptions.HeaderFilterRegex = HeaderFilter;
if (SystemHeaders.getNumOccurrences() > 0)
OverrideOptions.SystemHeaders = SystemHeaders;
if (AnalyzeTemporaryDtors.getNumOccurrences() > 0)
OverrideOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
if (!Config.empty()) {
if (llvm::ErrorOr<ClangTidyOptions> ParsedConfig =
parseConfiguration(Config)) {
return llvm::make_unique<DefaultOptionsProvider>(
GlobalOptions, ClangTidyOptions::getDefaults()
.mergeWith(DefaultOptions)
.mergeWith(*ParsedConfig)
.mergeWith(OverrideOptions));
} else {
llvm::errs() << "Error: invalid configuration specified.\n"
<< ParsedConfig.getError().message() << "\n";
return nullptr;
}
}
return llvm::make_unique<FileOptionsProvider>(GlobalOptions, DefaultOptions,
OverrideOptions);
}
static int clangTidyMain(int argc, const char **argv) {
CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
cl::ZeroOrMore);
auto OptionsProvider = createOptionsProvider();
if (!OptionsProvider)
return 1;
StringRef FileName("dummy");
auto PathList = OptionsParser.getSourcePathList();
if (!PathList.empty()) {
FileName = PathList.front();
}
ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FileName);
std::vector<std::string> EnabledChecks = getCheckNames(EffectiveOptions);
if (ListChecks) {
llvm::outs() << "Enabled checks:";
for (auto CheckName : EnabledChecks)
llvm::outs() << "\n " << CheckName;
llvm::outs() << "\n\n";
return 0;
}
if (DumpConfig) {
EffectiveOptions.CheckOptions = getCheckOptions(EffectiveOptions);
llvm::outs() << configurationAsText(
ClangTidyOptions::getDefaults().mergeWith(
EffectiveOptions))
<< "\n";
return 0;
}
if (EnabledChecks.empty()) {
llvm::errs() << "Error: no checks enabled.\n";
llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
return 1;
}
if (PathList.empty()) {
llvm::errs() << "Error: no input files specified.\n";
llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
return 1;
}
ProfileData Profile;
std::vector<ClangTidyError> Errors;
ClangTidyStats Stats =
runClangTidy(std::move(OptionsProvider), OptionsParser.getCompilations(),
PathList, &Errors,
EnableCheckProfile ? &Profile : nullptr);
bool FoundErrors =
std::find_if(Errors.begin(), Errors.end(), [](const ClangTidyError &E) {
return E.DiagLevel == ClangTidyError::Error;
}) != Errors.end();
const bool DisableFixes = Fix && FoundErrors && !FixErrors;
// -fix-errors implies -fix.
handleErrors(Errors, (FixErrors || Fix) && !DisableFixes);
if (!ExportFixes.empty() && !Errors.empty()) {
std::error_code EC;
llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None);
if (EC) {
llvm::errs() << "Error opening output file: " << EC.message() << '\n';
return 1;
}
exportReplacements(Errors, OS);
}
printStats(Stats);
if (DisableFixes)
llvm::errs()
<< "Found compiler errors, but -fix-errors was not specified.\n"
"Fixes have NOT been applied.\n\n";
if (EnableCheckProfile)
printProfileData(Profile, llvm::errs());
return 0;
}
// This anchor is used to force the linker to link the LLVMModule.
extern volatile int LLVMModuleAnchorSource;
static int LLVM_ATTRIBUTE_UNUSED LLVMModuleAnchorDestination = LLVMModuleAnchorSource;
// This anchor is used to force the linker to link the GoogleModule.
extern volatile int GoogleModuleAnchorSource;
static int LLVM_ATTRIBUTE_UNUSED GoogleModuleAnchorDestination = GoogleModuleAnchorSource;
// This anchor is used to force the linker to link the MiscModule.
extern volatile int MiscModuleAnchorSource;
static int LLVM_ATTRIBUTE_UNUSED MiscModuleAnchorDestination = MiscModuleAnchorSource;
// This anchor is used to force the linker to link the ModernizeModule.
extern volatile int ModernizeModuleAnchorSource;
static int ModernizeModuleAnchorDestination = ModernizeModuleAnchorSource;
// This anchor is used to force the linker to link the ReadabilityModule.
extern volatile int ReadabilityModuleAnchorSource;
static int LLVM_ATTRIBUTE_UNUSED ReadabilityModuleAnchorDestination = ReadabilityModuleAnchorSource;
} // namespace tidy
} // namespace clang
int main(int argc, const char **argv) {
return clang::tidy::clangTidyMain(argc, argv);
}
|
Fix a use-after-free.
|
[clang-tidy] Fix a use-after-free.
git-svn-id: a34e9779ed74578ad5922b3306b3d80a0c825546@245215 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra
|
1ecd9bdefc18b602dd99d0124a2868037b970a0a
|
sstables/types.hh
|
sstables/types.hh
|
/*
* 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 "disk_types.hh"
#include "core/enum.hh"
#include "bytes.hh"
#include "gc_clock.hh"
#include "tombstone.hh"
#include "streaming_histogram.hh"
#include "estimated_histogram.hh"
#include "column_name_helper.hh"
#include "sstables/key.hh"
#include "db/commitlog/replay_position.hh"
#include <vector>
#include <unordered_map>
#include <type_traits>
namespace sstables {
struct option {
disk_string<uint16_t> key;
disk_string<uint16_t> value;
template <typename Describer>
auto describe_type(Describer f) { return f(key, value); }
};
struct filter {
uint32_t hashes;
disk_array<uint32_t, uint64_t> buckets;
template <typename Describer>
auto describe_type(Describer f) { return f(hashes, buckets); }
// Create an always positive filter if nothing else is specified.
filter() : hashes(0), buckets({}) {}
explicit filter(int hashes, std::deque<uint64_t> buckets) : hashes(hashes), buckets({std::move(buckets)}) {}
};
class index_entry {
temporary_buffer<char> _key;
uint64_t _position;
temporary_buffer<char> _promoted_index;
public:
bytes_view get_key_bytes() const {
return bytes_view(reinterpret_cast<const bytes::value_type *>(_key.get()), _key.size());
}
key_view get_key() const {
return { get_key_bytes() };
}
uint64_t position() const {
return _position;
}
index_entry(temporary_buffer<char>&& key, uint64_t position, temporary_buffer<char>&& promoted_index)
: _key(std::move(key)), _position(position), _promoted_index(std::move(promoted_index)) {}
};
struct summary_entry {
bytes key;
uint64_t position;
key_view get_key() const {
return { key };
}
bool operator==(const summary_entry& x) const {
return position == x.position && key == x.key;
}
};
// Note: Sampling level is present in versions ka and higher. We ATM only support ka,
// so it's always there. But we need to make this conditional if we ever want to support
// other formats.
struct summary_ka {
struct header {
// The minimum possible amount of indexes per group (sampling level)
uint32_t min_index_interval;
// The number of entries in the Summary File
uint32_t size;
// The memory to be consumed to map the whole Summary into memory.
uint64_t memory_size;
// The actual sampling level.
uint32_t sampling_level;
// The number of entries the Summary *would* have if the sampling
// level would be equal to min_index_interval.
uint32_t size_at_full_sampling;
} header;
// The position in the Summary file for each of the indexes.
// NOTE1 that its actual size is determined by the "size" parameter, not
// by its preceding size_at_full_sampling
// NOTE2: They are laid out in *MEMORY* order, not BE.
// NOTE3: The sizes in this array represent positions in the memory stream,
// not the file. The memory stream effectively begins after the header,
// so every position here has to be added of sizeof(header).
std::deque<uint32_t> positions; // can be large, so use a deque instead of a vector
std::deque<summary_entry> entries;
disk_string<uint32_t> first_key;
disk_string<uint32_t> last_key;
// Used to determine when a summary entry should be added based on min_index_interval.
// NOTE: keys_written isn't part of on-disk format of summary.
size_t keys_written;
// NOTE4: There is a structure written by Cassandra into the end of the Summary
// file, after the field last_key, that we haven't understand yet, but we know
// that its content isn't related to the summary itself.
// The structure is basically as follow:
// struct { disk_string<uint16_t>; uint32_t; uint64_t; disk_string<uint16_t>; }
// Another interesting fact about this structure is that it is apparently always
// filled with the same data. It's too early to judge that the data is useless.
// However, it was tested that Cassandra loads successfully a Summary file with
// this structure removed from it. Anyway, let's pay attention to it.
/*
* Returns total amount of memory used by the summary
* Similar to origin off heap size
*/
uint64_t memory_footprint() const {
return sizeof(summary_entry) * entries.size() + sizeof(uint32_t) * positions.size() + sizeof(*this);
}
explicit operator bool() const {
return entries.size();
}
};
using summary = summary_ka;
struct metadata {
virtual ~metadata() {}
};
struct validation_metadata : public metadata {
disk_string<uint16_t> partitioner;
double filter_chance;
size_t serialized_size() {
return sizeof(uint16_t) + partitioner.value.size() + sizeof(filter_chance);
}
template <typename Describer>
auto describe_type(Describer f) { return f(partitioner, filter_chance); }
};
struct compaction_metadata : public metadata {
disk_array<uint32_t, uint32_t> ancestors;
disk_array<uint32_t, uint8_t> cardinality;
size_t serialized_size() {
return sizeof(uint32_t) + (ancestors.elements.size() * sizeof(uint32_t)) +
sizeof(uint32_t) + (cardinality.elements.size() * sizeof(uint8_t));
}
template <typename Describer>
auto describe_type(Describer f) { return f(ancestors, cardinality); }
};
struct ka_stats_metadata : public metadata {
estimated_histogram estimated_row_size;
estimated_histogram estimated_column_count;
db::replay_position position;
int64_t min_timestamp;
int64_t max_timestamp;
uint32_t max_local_deletion_time;
double compression_ratio;
streaming_histogram estimated_tombstone_drop_time;
uint32_t sstable_level;
uint64_t repaired_at;
disk_array<uint32_t, disk_string<uint16_t>> min_column_names;
disk_array<uint32_t, disk_string<uint16_t>> max_column_names;
bool has_legacy_counter_shards;
template <typename Describer>
auto describe_type(Describer f) {
return f(
estimated_row_size,
estimated_column_count,
position,
min_timestamp,
max_timestamp,
max_local_deletion_time,
compression_ratio,
estimated_tombstone_drop_time,
sstable_level,
repaired_at,
min_column_names,
max_column_names,
has_legacy_counter_shards
);
}
};
using stats_metadata = ka_stats_metadata;
// Numbers are found on disk, so they do matter. Also, setting their sizes of
// that of an uint32_t is a bit wasteful, but it simplifies the code a lot
// since we can now still use a strongly typed enum without introducing a
// notion of "disk-size" vs "memory-size".
enum class metadata_type : uint32_t {
Validation = 0,
Compaction = 1,
Stats = 2,
};
static constexpr int DEFAULT_CHUNK_SIZE = 65536;
// checksums are generated using adler32 algorithm.
struct checksum {
uint32_t chunk_size;
std::deque<uint32_t> checksums;
template <typename Describer>
auto describe_type(Describer f) { return f(chunk_size, checksums); }
};
}
namespace std {
template <>
struct hash<sstables::metadata_type> : enum_hash<sstables::metadata_type> {};
}
namespace sstables {
struct statistics {
disk_hash<uint32_t, metadata_type, uint32_t> hash;
std::unordered_map<metadata_type, std::unique_ptr<metadata>> contents;
};
struct deletion_time {
int32_t local_deletion_time;
int64_t marked_for_delete_at;
template <typename Describer>
auto describe_type(Describer f) { return f(local_deletion_time, marked_for_delete_at); }
bool live() const {
return (local_deletion_time == std::numeric_limits<int32_t>::max()) &&
(marked_for_delete_at == std::numeric_limits<int64_t>::min());
}
bool operator==(const deletion_time& d) {
return local_deletion_time == d.local_deletion_time &&
marked_for_delete_at == d.marked_for_delete_at;
}
bool operator!=(const deletion_time& d) {
return !(*this == d);
}
explicit operator tombstone() {
return !live() ? tombstone(marked_for_delete_at, gc_clock::time_point(gc_clock::duration(local_deletion_time))) : tombstone();
}
};
enum class column_mask : uint8_t {
none = 0x0,
deletion = 0x01,
expiration = 0x02,
counter = 0x04,
counter_update = 0x08,
range_tombstone = 0x10,
};
inline column_mask operator&(column_mask m1, column_mask m2) {
return column_mask(static_cast<uint8_t>(m1) & static_cast<uint8_t>(m2));
}
inline column_mask operator|(column_mask m1, column_mask m2) {
return column_mask(static_cast<uint8_t>(m1) | static_cast<uint8_t>(m2));
}
}
|
/*
* 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 "disk_types.hh"
#include "core/enum.hh"
#include "bytes.hh"
#include "gc_clock.hh"
#include "tombstone.hh"
#include "streaming_histogram.hh"
#include "estimated_histogram.hh"
#include "column_name_helper.hh"
#include "sstables/key.hh"
#include "db/commitlog/replay_position.hh"
#include <vector>
#include <unordered_map>
#include <type_traits>
namespace sstables {
struct option {
disk_string<uint16_t> key;
disk_string<uint16_t> value;
template <typename Describer>
auto describe_type(Describer f) { return f(key, value); }
};
struct filter {
uint32_t hashes;
disk_array<uint32_t, uint64_t> buckets;
template <typename Describer>
auto describe_type(Describer f) { return f(hashes, buckets); }
// Create an always positive filter if nothing else is specified.
filter() : hashes(0), buckets({}) {}
explicit filter(int hashes, std::deque<uint64_t> buckets) : hashes(hashes), buckets({std::move(buckets)}) {}
};
class index_entry {
temporary_buffer<char> _key;
uint64_t _position;
temporary_buffer<char> _promoted_index;
public:
bytes_view get_key_bytes() const {
return bytes_view(reinterpret_cast<const bytes::value_type *>(_key.get()), _key.size());
}
key_view get_key() const {
return { get_key_bytes() };
}
uint64_t position() const {
return _position;
}
index_entry(temporary_buffer<char>&& key, uint64_t position, temporary_buffer<char>&& promoted_index)
: _key(std::move(key)), _position(position), _promoted_index(std::move(promoted_index)) {}
};
struct summary_entry {
bytes key;
uint64_t position;
key_view get_key() const {
return { key };
}
bool operator==(const summary_entry& x) const {
return position == x.position && key == x.key;
}
};
// Note: Sampling level is present in versions ka and higher. We ATM only support ka,
// so it's always there. But we need to make this conditional if we ever want to support
// other formats.
struct summary_ka {
struct header {
// The minimum possible amount of indexes per group (sampling level)
uint32_t min_index_interval;
// The number of entries in the Summary File
uint32_t size;
// The memory to be consumed to map the whole Summary into memory.
uint64_t memory_size;
// The actual sampling level.
uint32_t sampling_level;
// The number of entries the Summary *would* have if the sampling
// level would be equal to min_index_interval.
uint32_t size_at_full_sampling;
} header;
// The position in the Summary file for each of the indexes.
// NOTE1 that its actual size is determined by the "size" parameter, not
// by its preceding size_at_full_sampling
// NOTE2: They are laid out in *MEMORY* order, not BE.
// NOTE3: The sizes in this array represent positions in the memory stream,
// not the file. The memory stream effectively begins after the header,
// so every position here has to be added of sizeof(header).
std::deque<uint32_t> positions; // can be large, so use a deque instead of a vector
std::deque<summary_entry> entries;
disk_string<uint32_t> first_key;
disk_string<uint32_t> last_key;
// Used to determine when a summary entry should be added based on min_index_interval.
// NOTE: keys_written isn't part of on-disk format of summary.
size_t keys_written;
// NOTE4: There is a structure written by Cassandra into the end of the Summary
// file, after the field last_key, that we haven't understand yet, but we know
// that its content isn't related to the summary itself.
// The structure is basically as follow:
// struct { disk_string<uint16_t>; uint32_t; uint64_t; disk_string<uint16_t>; }
// Another interesting fact about this structure is that it is apparently always
// filled with the same data. It's too early to judge that the data is useless.
// However, it was tested that Cassandra loads successfully a Summary file with
// this structure removed from it. Anyway, let's pay attention to it.
/*
* Returns total amount of memory used by the summary
* Similar to origin off heap size
*/
uint64_t memory_footprint() const {
return sizeof(summary_entry) * entries.size() + sizeof(uint32_t) * positions.size() + sizeof(*this);
}
explicit operator bool() const {
return entries.size();
}
};
using summary = summary_ka;
struct metadata {
virtual ~metadata() {}
};
struct validation_metadata : public metadata {
disk_string<uint16_t> partitioner;
double filter_chance;
size_t serialized_size() {
return sizeof(uint16_t) + partitioner.value.size() + sizeof(filter_chance);
}
template <typename Describer>
auto describe_type(Describer f) { return f(partitioner, filter_chance); }
};
struct compaction_metadata : public metadata {
disk_array<uint32_t, uint32_t> ancestors;
disk_array<uint32_t, uint8_t> cardinality;
size_t serialized_size() {
return sizeof(uint32_t) + (ancestors.elements.size() * sizeof(uint32_t)) +
sizeof(uint32_t) + (cardinality.elements.size() * sizeof(uint8_t));
}
template <typename Describer>
auto describe_type(Describer f) { return f(ancestors, cardinality); }
};
struct ka_stats_metadata : public metadata {
estimated_histogram estimated_row_size;
estimated_histogram estimated_column_count;
db::replay_position position;
int64_t min_timestamp;
int64_t max_timestamp;
int32_t max_local_deletion_time;
double compression_ratio;
streaming_histogram estimated_tombstone_drop_time;
uint32_t sstable_level;
uint64_t repaired_at;
disk_array<uint32_t, disk_string<uint16_t>> min_column_names;
disk_array<uint32_t, disk_string<uint16_t>> max_column_names;
bool has_legacy_counter_shards;
template <typename Describer>
auto describe_type(Describer f) {
return f(
estimated_row_size,
estimated_column_count,
position,
min_timestamp,
max_timestamp,
max_local_deletion_time,
compression_ratio,
estimated_tombstone_drop_time,
sstable_level,
repaired_at,
min_column_names,
max_column_names,
has_legacy_counter_shards
);
}
};
using stats_metadata = ka_stats_metadata;
// Numbers are found on disk, so they do matter. Also, setting their sizes of
// that of an uint32_t is a bit wasteful, but it simplifies the code a lot
// since we can now still use a strongly typed enum without introducing a
// notion of "disk-size" vs "memory-size".
enum class metadata_type : uint32_t {
Validation = 0,
Compaction = 1,
Stats = 2,
};
static constexpr int DEFAULT_CHUNK_SIZE = 65536;
// checksums are generated using adler32 algorithm.
struct checksum {
uint32_t chunk_size;
std::deque<uint32_t> checksums;
template <typename Describer>
auto describe_type(Describer f) { return f(chunk_size, checksums); }
};
}
namespace std {
template <>
struct hash<sstables::metadata_type> : enum_hash<sstables::metadata_type> {};
}
namespace sstables {
struct statistics {
disk_hash<uint32_t, metadata_type, uint32_t> hash;
std::unordered_map<metadata_type, std::unique_ptr<metadata>> contents;
};
struct deletion_time {
int32_t local_deletion_time;
int64_t marked_for_delete_at;
template <typename Describer>
auto describe_type(Describer f) { return f(local_deletion_time, marked_for_delete_at); }
bool live() const {
return (local_deletion_time == std::numeric_limits<int32_t>::max()) &&
(marked_for_delete_at == std::numeric_limits<int64_t>::min());
}
bool operator==(const deletion_time& d) {
return local_deletion_time == d.local_deletion_time &&
marked_for_delete_at == d.marked_for_delete_at;
}
bool operator!=(const deletion_time& d) {
return !(*this == d);
}
explicit operator tombstone() {
return !live() ? tombstone(marked_for_delete_at, gc_clock::time_point(gc_clock::duration(local_deletion_time))) : tombstone();
}
};
enum class column_mask : uint8_t {
none = 0x0,
deletion = 0x01,
expiration = 0x02,
counter = 0x04,
counter_update = 0x08,
range_tombstone = 0x10,
};
inline column_mask operator&(column_mask m1, column_mask m2) {
return column_mask(static_cast<uint8_t>(m1) & static_cast<uint8_t>(m2));
}
inline column_mask operator|(column_mask m1, column_mask m2) {
return column_mask(static_cast<uint8_t>(m1) | static_cast<uint8_t>(m2));
}
}
|
fix type of max_local_deletion_time
|
sstables: fix type of max_local_deletion_time
max_local_deletion_time was incorrectly using an unsigned type
instead of a signed one.
Signed-off-by: Raphael S. Carvalho <[email protected]>
|
C++
|
agpl-3.0
|
duarten/scylla,scylladb/scylla,raphaelsc/scylla,raphaelsc/scylla,scylladb/scylla,duarten/scylla,duarten/scylla,scylladb/scylla,avikivity/scylla,kjniemi/scylla,kjniemi/scylla,kjniemi/scylla,avikivity/scylla,scylladb/scylla,avikivity/scylla,raphaelsc/scylla
|
2d06bed68b7230ae68bdf25307c7855d3ee8b20e
|
example_single_camera/src/ofApp.cpp
|
example_single_camera/src/ofApp.cpp
|
//
// Copyright (c) 2020 Christopher Baker <https://christopherbaker.net>
//
// SPDX-License-Identifier: MIT
//
#include "ofApp.h"
void ofApp::setup()
{
ofSetFrameRate(30);
// Set the camera URL.
// Many axis cameras allow video resolution, fps, etc to be manipulated with url arguments.
grabber.setURI("http://zbc01.elpasotexas.gov/axis-cgi/mjpg/video.cgi?fps=2");
// Connect to the stream.
grabber.connect();
}
void ofApp::update()
{
grabber.update();
if (grabber.isFrameNew())
{
cameraPix = grabber.getPixels();
// Use or modify pixels in some way, e.g. invert the colors.
for (std::size_t x = 0; x < cameraPix.getWidth(); x++)
{
for (std::size_t y = 0; y < cameraPix.getHeight(); y++)
{
cameraPix.setColor(x, y, cameraPix.getColor(x, y).getInverted());
}
}
// Load the texture.
cameraTex.loadData(cameraPix);
}
}
void ofApp::draw()
{
ofSetColor(255);
// Draw the camera.
grabber.draw(0, 0, cameraWidth, cameraHeight);
// Draw the modified pixels if they are available.
if (cameraTex.isAllocated())
{
cameraTex.draw(cameraWidth, 0, cameraWidth, cameraHeight);
}
std::stringstream ss;
// Show connection statistics if desired.
if (showStats)
{
// Metadata about the connection state if needed.
float kbps = grabber.getBitRate() / 1000.0f; // kilobits / second, not kibibits / second
float fps = grabber.getFrameRate();
ss << " NAME: " << grabber.getCameraName() << std::endl;
ss << " HOST: " << grabber.getHost() << std::endl;
ss << " FPS: " << ofToString(fps, 2, 13, ' ') << std::endl;
ss << " Kb/S: " << ofToString(kbps, 2, 13, ' ') << std::endl;
ss << " #Bytes Recv'd: " << ofToString(grabber.getNumBytesReceived(), 0, 10, ' ') << std::endl;
ss << "#Frames Recv'd: " << ofToString(grabber.getNumFramesReceived(), 0, 10, ' ') << std::endl;
ss << "Auto Reconnect: " << (grabber.getAutoReconnect() ? "YES" : "NO") << std::endl;
ss << " Needs Connect: " << (grabber.getNeedsReconnect() ? "YES" : "NO") << std::endl;
ss << "Time Till Next: " << grabber.getTimeTillNextAutoRetry() << " ms" << std::endl;
ss << "Num Reconnects: " << ofToString(grabber.getReconnectCount()) << std::endl;
ss << "Max Reconnects: " << ofToString(grabber.getMaxReconnects()) << std::endl;
ss << " Connect Fail: " << (grabber.hasConnectionFailed() ? "YES" : "NO");
}
else
{
ss << "Press any key to show connection stats.";
}
ofSetColor(255);
ofDrawBitmapStringHighlight(ss.str(), 10, 10+12, ofColor(0, 80));
}
void ofApp::keyPressed(int key)
{
showStats = !showStats;
}
|
//
// Copyright (c) 2020 Christopher Baker <https://christopherbaker.net>
//
// SPDX-License-Identifier: MIT
//
#include "ofApp.h"
void ofApp::setup()
{
ofSetFrameRate(30);
// Set the camera URL.
// Many axis cameras allow video resolution, fps, etc to be manipulated with url arguments.
// N.B. If you don't see an image, the camera may be offline or no longer in service and
// this link may need to be replaced with a valid link.
grabber.setURI("http://107.1.228.34/axis-cgi/mjpg/video.cgi?resolution=320x240");
// Connect to the stream.
grabber.connect();
}
void ofApp::update()
{
grabber.update();
if (grabber.isFrameNew())
{
cameraPix = grabber.getPixels();
// Use or modify pixels in some way, e.g. invert the colors.
for (std::size_t x = 0; x < cameraPix.getWidth(); x++)
{
for (std::size_t y = 0; y < cameraPix.getHeight(); y++)
{
cameraPix.setColor(x, y, cameraPix.getColor(x, y).getInverted());
}
}
// Load the texture.
cameraTex.loadData(cameraPix);
}
}
void ofApp::draw()
{
ofSetColor(255);
// Draw the camera.
grabber.draw(0, 0, cameraWidth, cameraHeight);
// Draw the modified pixels if they are available.
if (cameraTex.isAllocated())
{
cameraTex.draw(cameraWidth, 0, cameraWidth, cameraHeight);
}
std::stringstream ss;
// Show connection statistics if desired.
if (showStats)
{
// Metadata about the connection state if needed.
float kbps = grabber.getBitRate() / 1000.0f; // kilobits / second, not kibibits / second
float fps = grabber.getFrameRate();
ss << " NAME: " << grabber.getCameraName() << std::endl;
ss << " HOST: " << grabber.getHost() << std::endl;
ss << " FPS: " << ofToString(fps, 2, 13, ' ') << std::endl;
ss << " Kb/S: " << ofToString(kbps, 2, 13, ' ') << std::endl;
ss << " #Bytes Recv'd: " << ofToString(grabber.getNumBytesReceived(), 0, 10, ' ') << std::endl;
ss << "#Frames Recv'd: " << ofToString(grabber.getNumFramesReceived(), 0, 10, ' ') << std::endl;
ss << "Auto Reconnect: " << (grabber.getAutoReconnect() ? "YES" : "NO") << std::endl;
ss << " Needs Connect: " << (grabber.getNeedsReconnect() ? "YES" : "NO") << std::endl;
ss << "Time Till Next: " << grabber.getTimeTillNextAutoRetry() << " ms" << std::endl;
ss << "Num Reconnects: " << ofToString(grabber.getReconnectCount()) << std::endl;
ss << "Max Reconnects: " << ofToString(grabber.getMaxReconnects()) << std::endl;
ss << " Connect Fail: " << (grabber.hasConnectionFailed() ? "YES" : "NO");
}
else
{
ss << "Press any key to show connection stats.";
}
ofSetColor(255);
ofDrawBitmapStringHighlight(ss.str(), 10, 10+12, ofColor(0, 80));
}
void ofApp::keyPressed(int key)
{
showStats = !showStats;
}
|
Update link and comment.
|
Update link and comment.
|
C++
|
mit
|
bakercp/ofxIpVideoGrabber
|
0371b277b9110a58d90aa1e82e2ff44c27e01f58
|
modules/perception/obstacle/camera/tracker/cs2d/cs2d_affinity_tracker.cc
|
modules/perception/obstacle/camera/tracker/cs2d/cs2d_affinity_tracker.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/perception/obstacle/camera/tracker/cs2d/cs2d_affinity_tracker.h"
namespace apollo {
namespace perception {
bool CS2DAffinityTracker::Init() {
return true;
}
bool CS2DAffinityTracker::GetAffinityMatrix(
const cv::Mat &img, const std::vector<Tracked> &tracked,
const std::vector<Detected> &detected,
std::vector<std::vector<float>> *affinity_matrix) {
affinity_matrix->clear();
// Return if empty
if (tracked.empty() || detected.empty()) {
return true;
}
// Construct output. Default as 0.0 for not selected entries
affinity_matrix = new std::vector<std::vector<float>>(
tracked.size(), std::vector<float>(detected.size(), 0.0f));
for (size_t i = 0; i < selected_entry_matrix_.size(); ++i) {
cv::Rect box = tracked[i].box_;
float w = static_cast<float>(box.width);
float h = static_cast<float>(box.height);
float c_x = static_cast<float>(box.x) + w / 2;
float c_y = static_cast<float>(box.y) + h / 2;
// 2D center position change limits
float x_min = c_x - pos_range_ * w;
float x_max = c_x + pos_range_ * w;
float y_min = c_y - pos_range_ * h;
float y_max = c_y + pos_range_ * h;
for (size_t j = 0; j < selected_entry_matrix_[0].size(); ++j) {
bool related = true;
cv::Rect box_d = detected[j].box_;
float w_d = static_cast<float>(box_d.width);
float h_d = static_cast<float>(box_d.height);
float c_x_d = static_cast<float>(box_d.x) + w_d / 2;
float c_y_d = static_cast<float>(box_d.y) + h_d / 2;
// 2D size change limits
float ratio_w = w_d / w;
if (ratio_w > (1.0f + sz_lim_) || ratio_w < (1.0f - sz_lim_)) {
related = false;
}
float ratio_h = h_d / h;
if (ratio_h > (1.0f + sz_lim_) || ratio_h < (1.0f - sz_lim_)) {
related = false;
}
// 2D center position change limits
if (c_x_d > x_max || c_x_d < x_min) {
related = false;
}
if (c_y_d > y_max || c_y_d < y_min) {
related = false;
}
if (related) {
(*affinity_matrix)[i][j] = 1.0f;
}
}
}
return true;
}
// TODO(unknown): dummy implementation for pure virtual methdo in base class
bool CS2DAffinityTracker::UpdateTracked(const cv::Mat &img,
const std::vector<Detected> &detected,
std::vector<Tracked> *tracked) {
return true;
}
} // namespace perception
} // namespace apollo
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/perception/obstacle/camera/tracker/cs2d/cs2d_affinity_tracker.h"
namespace apollo {
namespace perception {
bool CS2DAffinityTracker::Init() {
return true;
}
bool CS2DAffinityTracker::GetAffinityMatrix(
const cv::Mat &img, const std::vector<Tracked> &tracked,
const std::vector<Detected> &detected,
std::vector<std::vector<float>> *affinity_matrix) {
affinity_matrix->clear();
// Return if empty
if (tracked.empty() || detected.empty()) {
return true;
}
// Construct output. Default as 0.0 for not selected entries
affinity_matrix = new std::vector<std::vector<float>>(
tracked.size(), std::vector<float>(detected.size(), 0.0f));
for (size_t i = 0; i < selected_entry_matrix_.size(); ++i) {
cv::Rect box = tracked[i].box_;
float w = static_cast<float>(box.width);
float h = static_cast<float>(box.height);
float c_x = static_cast<float>(box.x) + w / 2;
float c_y = static_cast<float>(box.y) + h / 2;
// 2D center position change limits
float x_min = c_x - pos_range_ * w;
float x_max = c_x + pos_range_ * w;
float y_min = c_y - pos_range_ * h;
float y_max = c_y + pos_range_ * h;
for (size_t j = 0; j < selected_entry_matrix_[0].size(); ++j) {
bool related = true;
cv::Rect box_d = detected[j].box_;
float w_d = static_cast<float>(box_d.width);
float h_d = static_cast<float>(box_d.height);
float c_x_d = static_cast<float>(box_d.x) + w_d / 2;
float c_y_d = static_cast<float>(box_d.y) + h_d / 2;
// 2D size change limits
float ratio_w = w_d / w;
if (ratio_w > (1.0f + sz_lim_) || ratio_w < (1.0f - sz_lim_)) {
related = false;
}
float ratio_h = h_d / h;
if (ratio_h > (1.0f + sz_lim_) || ratio_h < (1.0f - sz_lim_)) {
related = false;
}
// 2D center position change limits
if (c_x_d > x_max || c_x_d < x_min) {
related = false;
}
if (c_y_d > y_max || c_y_d < y_min) {
related = false;
}
if (related) {
(*affinity_matrix)[i][j] = 1.0f;
}
}
}
return true;
}
// TODO(unknown): dummy implementation for pure virtual method in base class
bool CS2DAffinityTracker::UpdateTracked(const cv::Mat &img,
const std::vector<Detected> &detected,
std::vector<Tracked> *tracked) {
return true;
}
} // namespace perception
} // namespace apollo
|
Fix typo.
|
Fix typo.
|
C++
|
apache-2.0
|
xiaoxq/apollo,ycool/apollo,ApolloAuto/apollo,xiaoxq/apollo,wanglei828/apollo,ApolloAuto/apollo,ApolloAuto/apollo,ycool/apollo,ApolloAuto/apollo,xiaoxq/apollo,jinghaomiao/apollo,ApolloAuto/apollo,ycool/apollo,ycool/apollo,jinghaomiao/apollo,jinghaomiao/apollo,wanglei828/apollo,xiaoxq/apollo,ycool/apollo,ycool/apollo,jinghaomiao/apollo,xiaoxq/apollo,wanglei828/apollo,wanglei828/apollo,wanglei828/apollo,jinghaomiao/apollo,xiaoxq/apollo,jinghaomiao/apollo,wanglei828/apollo,ApolloAuto/apollo
|
03382bef707f550e3324d47f1dd51049f470cecb
|
src/test/rados-api/aio.cc
|
src/test/rados-api/aio.cc
|
#include "include/rados/librados.h"
#include "test/rados-api/test.h"
#include "gtest/gtest.h"
#include <errno.h>
#include <semaphore.h>
#include <string>
class AioTestData
{
public:
AioTestData()
: m_init(false),
m_complete(false),
m_safe(false)
{
}
~AioTestData()
{
if (m_init) {
rados_ioctx_destroy(m_ioctx);
destroy_one_pool(m_pool_name, &m_cluster);
sem_destroy(&m_sem);
}
}
int init()
{
int ret;
if (sem_init(&m_sem, 0, 0)) {
int err = errno;
sem_destroy(&m_sem);
return err;
}
std::string m_pool_name = get_temp_pool_name();
ret = create_one_pool(m_pool_name, &m_cluster);
if (ret) {
sem_destroy(&m_sem);
return ret;
}
ret = rados_ioctx_create(m_cluster, m_pool_name.c_str(), &m_ioctx);
if (ret) {
sem_destroy(&m_sem);
destroy_one_pool(m_pool_name, &m_cluster);
return ret;
}
m_init = true;
return 0;
}
sem_t m_sem;
rados_t m_cluster;
rados_ioctx_t m_ioctx;
rados_completion_t m_completion;
std::string m_pool_name;
bool m_init;
bool m_complete;
bool m_safe;
};
class TestAlarm
{
public:
TestAlarm() {
alarm(360);
}
~TestAlarm() {
alarm(0);
}
};
void set_completion_complete(rados_completion_t cb, void *arg)
{
AioTestData *test = (AioTestData*)arg;
test->m_complete = true;
sem_post(&test->m_sem);
}
void set_completion_safe(rados_completion_t cb, void *arg)
{
AioTestData *test = (AioTestData*)arg;
test->m_safe = true;
sem_post(&test->m_sem);
}
TEST(LibRadosAio, SimpleWrite) {
AioTestData test_data;
rados_completion_t my_completion;
ASSERT_EQ(0, test_data.init());
ASSERT_EQ(0, rados_aio_create_completion((void*)&test_data,
set_completion_complete, set_completion_safe, &my_completion));
char buf[128];
memset(buf, 0xcc, sizeof(buf));
ASSERT_EQ(0, rados_aio_write(test_data.m_ioctx, "foo",
my_completion, buf, sizeof(buf), 0));
TestAlarm alarm;
sem_wait(&test_data.m_sem);
sem_wait(&test_data.m_sem);
}
|
#include "common/errno.h"
#include "include/rados/librados.h"
#include "test/rados-api/test.h"
#include "gtest/gtest.h"
#include <errno.h>
#include <semaphore.h>
#include <sstream>
#include <string>
using std::ostringstream;
class AioTestData
{
public:
AioTestData()
: m_init(false),
m_complete(false),
m_safe(false)
{
}
~AioTestData()
{
if (m_init) {
rados_ioctx_destroy(m_ioctx);
destroy_one_pool(m_pool_name, &m_cluster);
sem_destroy(&m_sem);
}
}
std::string init()
{
int ret;
if (sem_init(&m_sem, 0, 0)) {
int err = errno;
sem_destroy(&m_sem);
ostringstream oss;
oss << "sem_init failed: " << cpp_strerror(err);
return oss.str();
}
std::string m_pool_name = get_temp_pool_name();
ret = create_one_pool(m_pool_name, &m_cluster);
if (ret) {
sem_destroy(&m_sem);
ostringstream oss;
oss << "create_one_pool(" << m_pool_name << ") failed: error " << ret;
return oss.str();
}
ret = rados_ioctx_create(m_cluster, m_pool_name.c_str(), &m_ioctx);
if (ret) {
sem_destroy(&m_sem);
destroy_one_pool(m_pool_name, &m_cluster);
ostringstream oss;
oss << "rados_ioctx_create failed: error " << ret;
return oss.str();
}
m_init = true;
return "";
}
sem_t m_sem;
rados_t m_cluster;
rados_ioctx_t m_ioctx;
rados_completion_t m_completion;
std::string m_pool_name;
bool m_init;
bool m_complete;
bool m_safe;
};
class TestAlarm
{
public:
TestAlarm() {
alarm(360);
}
~TestAlarm() {
alarm(0);
}
};
void set_completion_complete(rados_completion_t cb, void *arg)
{
AioTestData *test = (AioTestData*)arg;
test->m_complete = true;
sem_post(&test->m_sem);
}
void set_completion_safe(rados_completion_t cb, void *arg)
{
AioTestData *test = (AioTestData*)arg;
test->m_safe = true;
sem_post(&test->m_sem);
}
TEST(LibRadosAio, SimpleWrite) {
AioTestData test_data;
rados_completion_t my_completion;
ASSERT_EQ("", test_data.init());
ASSERT_EQ(0, rados_aio_create_completion((void*)&test_data,
set_completion_complete, set_completion_safe, &my_completion));
char buf[128];
memset(buf, 0xcc, sizeof(buf));
ASSERT_EQ(0, rados_aio_write(test_data.m_ioctx, "foo",
my_completion, buf, sizeof(buf), 0));
TestAlarm alarm;
sem_wait(&test_data.m_sem);
sem_wait(&test_data.m_sem);
}
TEST(LibRadosAio, WaitForSafe) {
AioTestData test_data;
rados_completion_t my_completion;
ASSERT_EQ("", test_data.init());
ASSERT_EQ(0, rados_aio_create_completion((void*)&test_data,
set_completion_complete, set_completion_safe, &my_completion));
char buf[128];
memset(buf, 0xcc, sizeof(buf));
ASSERT_EQ(0, rados_aio_write(test_data.m_ioctx, "foo",
my_completion, buf, sizeof(buf), 0));
TestAlarm alarm;
ASSERT_EQ(0, rados_aio_wait_for_safe(my_completion));
}
TEST(LibRadosAio, RoundTrip) {
AioTestData test_data;
rados_completion_t my_completion;
ASSERT_EQ("", test_data.init());
ASSERT_EQ(0, rados_aio_create_completion((void*)&test_data,
set_completion_complete, set_completion_safe, &my_completion));
char buf[128];
memset(buf, 0xcc, sizeof(buf));
ASSERT_EQ(0, rados_aio_write(test_data.m_ioctx, "foo",
my_completion, buf, sizeof(buf), 0));
{
TestAlarm alarm;
sem_wait(&test_data.m_sem);
sem_wait(&test_data.m_sem);
}
char buf2[128];
memset(buf2, 0, sizeof(buf2));
rados_completion_t my_completion2;
ASSERT_EQ(0, rados_aio_create_completion((void*)&test_data,
set_completion_complete, set_completion_safe, &my_completion2));
ASSERT_EQ(0, rados_aio_read(test_data.m_ioctx, "foo",
my_completion2, buf2, sizeof(buf2), 0));
{
TestAlarm alarm;
ASSERT_EQ(0, rados_aio_wait_for_complete(my_completion2));
}
ASSERT_EQ(0, memcmp(buf, buf2, sizeof(buf)));
}
|
add WaitForSafe, RoundTrip
|
test/rados-api/aio: add WaitForSafe, RoundTrip
Signed-off-by: Colin McCabe <[email protected]>
|
C++
|
lgpl-2.1
|
ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.