Format code using uncrustify

Signed-off-by: Michele Calgaro <michele.calgaro@yahoo.it>
pull/3/head
Michele Calgaro 2 years ago
parent d833de5bbe
commit 430373ae38

@ -37,126 +37,133 @@
\brief The constructor calls the setup function for the ui created by uic and adds
the GPL text to the text edit.
*/
AboutDialog::AboutDialog(TQWidget *parent, TQt::WindowFlags flags) : TQDialog(parent, flags)
, _dialogForm(NULL)
, _timer(NULL)
{
_dialogForm = new Ui::AboutDialog();
_dialogForm->setupUi(this);
_dialogForm->authorTextBrowser->setOpenExternalLinks( true );
_dialogForm->creditsTextBrowser->setOpenExternalLinks( true );
TQString versionString = _dialogForm->versionTextBrowser->toHtml();
versionString = versionString.arg(PROGRAM_VERSION_STRING).arg( UiGuiVersion::getBuildRevision() ).arg( UiGuiVersion::getBuildDate() );
_dialogForm->versionTextBrowser->setHtml(versionString);
_dialogForm->creditsTextBrowser->setHtml("<html><head></head><body>"
"<pre> </br></pre>"
"<h3 align='center'>Thanks go out to</h3>"
"<p align='center'><a href=\"http://www.csie.nctu.edu.tw/~chtai/\"><b>Nelson Tai</b></a> for Chinese translation, good ideas and always fast answers.</p></br>"
"<p align='center'><a href=\"http://www.hartwork.org/\"><b>Sebastian Pipping</b></a> for helping me bring UiGUI into the Debian repository and other good ideas.</p></br>"
"<p align='center'><a href=\"http://korytskyy.lviv.ua/\"><b>Oleksandr</b></a> for Ukrainian and Russian translation.</p></br>"
"<p align='center'><b>Erwan &quot;leg&quot;</b> for French translation and the icon logo.</p></br>"
"<p align='center'>The <a href=\"http://www.scintilla.org/\"><b>Scintilla</b></a> project for their great text editing component.</p></br>"
"<p align='center'><a href=\"http://www.riverbankcomputing.co.uk/software/qscintilla/\"><b>Riverbank</b></a> for their Scintilla TQt wrapper TQScintilla.</p></br>"
"<p align='center'>The <a href=\"http://astyle.sourceforge.net/\"><b>Artistic Style</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://invisible-island.net/bcpp/\"><b>BCPP</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://www.siber.com/sct/tools/cbl-beau.html\"><b>Cobol Beautifier</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://csstidy.sourceforge.net/\"><b>CSSTidy</b></a> project.</p></br>"
"<p align='center'>The <a href=\"ftp://ftp.ifremer.fr/ifremer/ditigo/fortran90/\"><b>Fortran 90 PPR</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://www.gnu.org/software/indent/\"><b>GNU Indent</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://sourceforge.net/projects/gcgreatcode/\"><b>GreatCode</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://linux.com.hk/penguin/man/1/hindent.html\"><b>hindent</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://www.digital-mines.com/htb/\"><b>HTB</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://tidy.sourceforge.net/\"><b>HTML Tidy</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://code.gosu.pl/\"><b>JsDecoder</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://jsppp.sourceforge.net/\"><b>JSPPP</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://perltidy.sourceforge.net/\"><b>Perltidy</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://beautifyphp.sourceforge.net/\"><b>PHP_Beautifier</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://www.waterproof.fr/products/phpCodeBeautifier/\"><b>phpCB</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://sourceforge.net/projects/phpstylist/\"><b>PHP Stylist</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://coverage.livinglogic.de/Tools/scripts/pindent.py.html\"><b>pindent</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://psti.etquinoxbase.com/\"><b>Pl/Sql tidy</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://www.arachnoid.com/ruby/rubyBeautifier.html\"><b>Ruby Beautifier</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://raa.ruby-lang.org/project/ruby_formatter/\"><b>Ruby Formatter</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://www.bolthole.com/AWK.html\"><b>Shell Indent</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://uncrustify.sourceforge.net/\"><b>Uncrustify</b></a> project, specially <b>Ben Gardner</b>.</p></br>"
"<p align='center'>The <a href=\"http://www.daansystems.com/vbsbeaut/\"><b>VBSBeautifier</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://xmlindent.sourceforge.net/\"><b>XML Indent</b></a> project.</p></br>"
"<p align='center'><b>Nirvash</b> for the initial Japanese translation.</p></br>"
"<p align='center'>The <a href=\"http://tango.freedesktop.org/Tango_Desktop_Project/\"><b>Tango Project</b></a> for their icons.</p></br>"
"<p align='center'><a href=\"http://www.famfamfam.com/\"><b>famfamfam</b></a> for the flag icons.</p></br>"
"<p align='center'><a href=\"http://trolltech.com/\"><b>Trolltech</b></a> for their really great GUI framework <img src=\":/aboutDialog/qt_logo.png\"/>.</p></br>"
"<h3 align='center'>My girlfriend (meanwhile also wife) for putting my head right and not sit all the time in front of my computer ;-)</h3>"
"</body></html>");
_scrollDirection = 1;
_scrollSpeed = 100;
_timer = new TQTimer(this);
connect( _timer, SIGNAL(timeout()), this, SLOT(scroll()) );
connect( this, SIGNAL(accepted()), _timer, SLOT(stop()) );
AboutDialog::AboutDialog(TQWidget *parent, TQt::WindowFlags flags) :
TQDialog(parent, flags), _dialogForm(NULL), _timer(NULL)
{
_dialogForm = new Ui::AboutDialog();
_dialogForm->setupUi(this);
_dialogForm->authorTextBrowser->setOpenExternalLinks(true);
_dialogForm->creditsTextBrowser->setOpenExternalLinks(true);
TQString versionString = _dialogForm->versionTextBrowser->toHtml();
versionString =
versionString.arg(PROGRAM_VERSION_STRING).arg(UiGuiVersion::getBuildRevision()).arg(
UiGuiVersion::getBuildDate());
_dialogForm->versionTextBrowser->setHtml(versionString);
_dialogForm->creditsTextBrowser->setHtml("<html><head></head><body>"
"<pre> </br></pre>"
"<h3 align='center'>Thanks go out to</h3>"
"<p align='center'><a href=\"http://www.csie.nctu.edu.tw/~chtai/\"><b>Nelson Tai</b></a> for Chinese translation, good ideas and always fast answers.</p></br>"
"<p align='center'><a href=\"http://www.hartwork.org/\"><b>Sebastian Pipping</b></a> for helping me bring UiGUI into the Debian repository and other good ideas.</p></br>"
"<p align='center'><a href=\"http://korytskyy.lviv.ua/\"><b>Oleksandr</b></a> for Ukrainian and Russian translation.</p></br>"
"<p align='center'><b>Erwan &quot;leg&quot;</b> for French translation and the icon logo.</p></br>"
"<p align='center'>The <a href=\"http://www.scintilla.org/\"><b>Scintilla</b></a> project for their great text editing component.</p></br>"
"<p align='center'><a href=\"http://www.riverbankcomputing.co.uk/software/qscintilla/\"><b>Riverbank</b></a> for their Scintilla TQt wrapper TQScintilla.</p></br>"
"<p align='center'>The <a href=\"http://astyle.sourceforge.net/\"><b>Artistic Style</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://invisible-island.net/bcpp/\"><b>BCPP</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://www.siber.com/sct/tools/cbl-beau.html\"><b>Cobol Beautifier</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://csstidy.sourceforge.net/\"><b>CSSTidy</b></a> project.</p></br>"
"<p align='center'>The <a href=\"ftp://ftp.ifremer.fr/ifremer/ditigo/fortran90/\"><b>Fortran 90 PPR</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://www.gnu.org/software/indent/\"><b>GNU Indent</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://sourceforge.net/projects/gcgreatcode/\"><b>GreatCode</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://linux.com.hk/penguin/man/1/hindent.html\"><b>hindent</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://www.digital-mines.com/htb/\"><b>HTB</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://tidy.sourceforge.net/\"><b>HTML Tidy</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://code.gosu.pl/\"><b>JsDecoder</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://jsppp.sourceforge.net/\"><b>JSPPP</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://perltidy.sourceforge.net/\"><b>Perltidy</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://beautifyphp.sourceforge.net/\"><b>PHP_Beautifier</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://www.waterproof.fr/products/phpCodeBeautifier/\"><b>phpCB</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://sourceforge.net/projects/phpstylist/\"><b>PHP Stylist</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://coverage.livinglogic.de/Tools/scripts/pindent.py.html\"><b>pindent</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://psti.etquinoxbase.com/\"><b>Pl/Sql tidy</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://www.arachnoid.com/ruby/rubyBeautifier.html\"><b>Ruby Beautifier</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://raa.ruby-lang.org/project/ruby_formatter/\"><b>Ruby Formatter</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://www.bolthole.com/AWK.html\"><b>Shell Indent</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://uncrustify.sourceforge.net/\"><b>Uncrustify</b></a> project, specially <b>Ben Gardner</b>.</p></br>"
"<p align='center'>The <a href=\"http://www.daansystems.com/vbsbeaut/\"><b>VBSBeautifier</b></a> project.</p></br>"
"<p align='center'>The <a href=\"http://xmlindent.sourceforge.net/\"><b>XML Indent</b></a> project.</p></br>"
"<p align='center'><b>Nirvash</b> for the initial Japanese translation.</p></br>"
"<p align='center'>The <a href=\"http://tango.freedesktop.org/Tango_Desktop_Project/\"><b>Tango Project</b></a> for their icons.</p></br>"
"<p align='center'><a href=\"http://www.famfamfam.com/\"><b>famfamfam</b></a> for the flag icons.</p></br>"
"<p align='center'><a href=\"http://trolltech.com/\"><b>Trolltech</b></a> for their really great GUI framework <img src=\":/aboutDialog/qt_logo.png\"/>.</p></br>"
"<h3 align='center'>My girlfriend (meanwhile also wife) for putting my head right and not sit all the time in front of my computer ;-)</h3>"
"</body></html>");
_scrollDirection = 1;
_scrollSpeed = 100;
_timer = new TQTimer(this);
connect(_timer, SIGNAL(timeout()), this, SLOT(scroll()));
connect(this, SIGNAL(accepted()), _timer, SLOT(stop()));
}
/*!
\brief Catches language change events and retranslates all needed widgets.
*/
void AboutDialog::changeEvent(TQEvent *event) {
if (event->type() == TQEvent::LanguageChange) {
_dialogForm->retranslateUi(this);
TQString versionString = _dialogForm->versionTextBrowser->toHtml();
versionString = versionString.arg(PROGRAM_VERSION_STRING).arg( UiGuiVersion::getBuildRevision() ).arg( UiGuiVersion::getBuildDate() );
_dialogForm->versionTextBrowser->setHtml(versionString);
}
else {
TQWidget::changeEvent(event);
}
void AboutDialog::changeEvent(TQEvent *event)
{
if (event->type() == TQEvent::LanguageChange)
{
_dialogForm->retranslateUi(this);
TQString versionString = _dialogForm->versionTextBrowser->toHtml();
versionString =
versionString.arg(PROGRAM_VERSION_STRING).arg(UiGuiVersion::getBuildRevision()).arg(
UiGuiVersion::getBuildDate());
_dialogForm->versionTextBrowser->setHtml(versionString);
}
else
{
TQWidget::changeEvent(event);
}
}
/*!
\brief Reimplements the dialog execution function to init the credits scroller.
*/
int AboutDialog::exec() {
//creditsTextBrowser->verticalScrollBar()->setValue(0);
_timer->start(_scrollSpeed);
return TQDialog::exec();
int AboutDialog::exec()
{
//creditsTextBrowser->verticalScrollBar()->setValue(0);
_timer->start(_scrollSpeed);
return TQDialog::exec();
}
/*!
\brief This slot is called each _timer timeout to scroll the credits textbrowser.
Also changes the scroll direction and speed when reaching the start or end.
*/
void AboutDialog::scroll() {
TQScrollBar *scrollBar = _dialogForm->creditsTextBrowser->verticalScrollBar();
scrollBar->setValue( scrollBar->value()+_scrollDirection );
if ( scrollBar->value() == scrollBar->maximum() ) {
// Toggle scroll direction and change scroll speed;
_scrollDirection = -1;
_scrollSpeed = 5;
_timer->stop();
_timer->start(_scrollSpeed);
}
else if ( scrollBar->value() == scrollBar->minimum() ) {
// Toggle scroll direction and change scroll speed;
_scrollDirection = 1;
_scrollSpeed = 100;
_timer->stop();
_timer->start(_scrollSpeed);
}
_dialogForm->creditsTextBrowser->update();
void AboutDialog::scroll()
{
TQScrollBar *scrollBar = _dialogForm->creditsTextBrowser->verticalScrollBar();
scrollBar->setValue(scrollBar->value() + _scrollDirection);
if (scrollBar->value() == scrollBar->maximum())
{
// Toggle scroll direction and change scroll speed;
_scrollDirection = -1;
_scrollSpeed = 5;
_timer->stop();
_timer->start(_scrollSpeed);
}
else if (scrollBar->value() == scrollBar->minimum())
{
// Toggle scroll direction and change scroll speed;
_scrollDirection = 1;
_scrollSpeed = 100;
_timer->stop();
_timer->start(_scrollSpeed);
}
_dialogForm->creditsTextBrowser->update();
}
/*!
\brief Shows the about dialog and also starts the credits scroller.
*/
void AboutDialog::show() {
_timer->start(_scrollSpeed);
TQDialog::show();
void AboutDialog::show()
{
_timer->start(_scrollSpeed);
TQDialog::show();
}

@ -22,32 +22,33 @@
#include <tntqdialog.h>
namespace Ui {
namespace Ui
{
class AboutDialog;
}
class AboutDialog : public TQDialog
{
Q_OBJECT
Q_OBJECT
public:
AboutDialog(TQWidget *parent = NULL, TQt::WindowFlags flags = 0);
public:
AboutDialog(TQWidget *parent = NULL, TQt::WindowFlags flags = 0);
public slots:
int exec();
void show();
public slots:
int exec();
void show();
private slots:
void scroll();
private slots:
void scroll();
private:
void changeEvent(TQEvent *event);
private:
void changeEvent(TQEvent *event);
Ui::AboutDialog* _dialogForm;
int _scrollDirection;
int _scrollSpeed;
TQTimer *_timer;
Ui::AboutDialog *_dialogForm;
int _scrollDirection;
int _scrollSpeed;
TQTimer *_timer;
};
#endif // ABOUTDIALOG_H

@ -39,168 +39,182 @@
/*!
\brief The constructor initializes everything needed for the 3D animation.
*/
AboutDialogGraphicsView::AboutDialogGraphicsView(AboutDialog *aboutDialog, TQWidget *parentWindow) : TQGraphicsView(parentWindow)
, _aboutDialog(NULL)
, _graphicsProxyWidget(NULL)
, _parentWindow(NULL)
, _timeLine(NULL)
, _aboutDialogAsSplashScreen(NULL)
AboutDialogGraphicsView::AboutDialogGraphicsView(AboutDialog *aboutDialog, TQWidget *parentWindow) :
TQGraphicsView(parentWindow), _aboutDialog(NULL), _graphicsProxyWidget(NULL),
_parentWindow(NULL), _timeLine(NULL), _aboutDialogAsSplashScreen(NULL)
{
_parentWindow = parentWindow;
setWindowFlags(TQt::SplashScreen);
_parentWindow = parentWindow;
setWindowFlags(TQt::SplashScreen);
#ifdef Q_OS_LINUX
TQRect availableGeometry = TQApplication::desktop()->availableGeometry();
TQRect newGeometry = TQRect( availableGeometry.x(), availableGeometry.y(), availableGeometry.width(), availableGeometry.height() );
TQRect availableGeometry = TQApplication::desktop()->availableGeometry();
TQRect newGeometry = TQRect(availableGeometry.x(),
availableGeometry.y(), availableGeometry.width(), availableGeometry.height());
#else
TQRect newGeometry = TQRect( -1,-1, TQApplication::desktop()->rect().width()+2, TQApplication::desktop()->rect().height()+2 );
TQRect newGeometry = TQRect(-1, -1,
TQApplication::desktop()->rect().width() + 2,
TQApplication::desktop()->rect().height() + 2);
#endif
setGeometry( newGeometry );
setGeometry(newGeometry);
_aboutDialog = aboutDialog;
_aboutDialog = aboutDialog;
_windowTitleBarWidth = 0;
_windowPosOffset = 0;
_windowTitleBarWidth = 0;
_windowPosOffset = 0;
TQGraphicsScene *scene = new TQGraphicsScene(this);
setSceneRect( newGeometry );
_aboutDialogAsSplashScreen = new TQSplashScreen(this);
_graphicsProxyWidget = scene->addWidget(_aboutDialogAsSplashScreen);
_graphicsProxyWidget->setWindowFlags( TQt::ToolTip );
TQGraphicsScene *scene = new TQGraphicsScene(this);
setSceneRect(newGeometry);
_aboutDialogAsSplashScreen = new TQSplashScreen(this);
_graphicsProxyWidget = scene->addWidget(_aboutDialogAsSplashScreen);
_graphicsProxyWidget->setWindowFlags(TQt::ToolTip);
setScene( scene );
setRenderHint(TQPainter::Antialiasing);
setScene(scene);
setRenderHint(TQPainter::Antialiasing);
setCacheMode(TQGraphicsView::CacheBackground);
setViewportUpdateMode(TQGraphicsView::BoundingRectViewportUpdate);
setCacheMode(TQGraphicsView::CacheBackground);
setViewportUpdateMode(TQGraphicsView::BoundingRectViewportUpdate);
connect(_aboutDialog, SIGNAL(finished(int)), this, SLOT(hide()));
connect(_aboutDialog, SIGNAL(finished(int)), this, SLOT(hide()));
//setWindowOpacity(0.9);
//setWindowOpacity(0.9);
setVerticalScrollBarPolicy(TQt::ScrollBarAlwaysOff);
setHorizontalScrollBarPolicy(TQt::ScrollBarAlwaysOff);
setStyleSheet("AboutDialogGraphicsView { border: 0px; }");
setVerticalScrollBarPolicy(TQt::ScrollBarAlwaysOff);
setHorizontalScrollBarPolicy(TQt::ScrollBarAlwaysOff);
setStyleSheet("AboutDialogGraphicsView { border: 0px; }");
_timeLine = new TQTimeLine(1000, this);
_timeLine->setFrameRange(270, 0);
//_timeLine->setUpdateInterval(10);
//_timeLine->setCurveShape(TQTimeLine::EaseInCurve);
connect(_timeLine, SIGNAL(frameChanged(int)), this, SLOT(updateStep(int)));
_timeLine = new TQTimeLine(1000, this);
_timeLine->setFrameRange(270, 0);
//_timeLine->setUpdateInterval(10);
//_timeLine->setCurveShape(TQTimeLine::EaseInCurve);
connect(_timeLine, SIGNAL(frameChanged(int)), this, SLOT(updateStep(int)));
}
AboutDialogGraphicsView::~AboutDialogGraphicsView(void) {
AboutDialogGraphicsView::~AboutDialogGraphicsView(void)
{
}
/*!
\brief Grabs a screenshot of the full desktop and shows that as background. Above that background the
AboutDialog 3D animation is shown. Also grabs the content of the AboutDialog itself.
*/
void AboutDialogGraphicsView::show() {
// Because on X11 system the window decoration is only available after a widget has been shown once,
// we can detect _windowTitleBarWidth here for the first time.
_windowTitleBarWidth = _parentWindow->geometry().y() - _parentWindow->y();
// If the _windowTitleBarWidth could not be determined, try it a second way. Even the chances are low to get good results.
if ( _windowTitleBarWidth == 0 )
_windowTitleBarWidth = _parentWindow->frameGeometry().height() - _parentWindow->geometry().height();
void AboutDialogGraphicsView::show()
{
// Because on X11 system the window decoration is only available after a widget has been shown
// once,
// we can detect _windowTitleBarWidth here for the first time.
_windowTitleBarWidth = _parentWindow->geometry().y() - _parentWindow->y();
// If the _windowTitleBarWidth could not be determined, try it a second way. Even the chances are
// low to get good results.
if (_windowTitleBarWidth == 0)
{
_windowTitleBarWidth = _parentWindow->frameGeometry().height() -
_parentWindow->geometry().height();
}
#ifdef Q_OS_LINUX
if ( _windowTitleBarWidth == 0 ) {
//TODO: 27 pixel is a fix value for the Ubuntu 10.4 default window theme and so just a workaround for that specific case.
_windowPosOffset = 27;
_windowTitleBarWidth = 27;
}
if (_windowTitleBarWidth == 0)
{
//TODO: 27 pixel is a fix value for the Ubuntu 10.4 default window theme and so just a
// workaround for that specific case.
_windowPosOffset = 27;
_windowTitleBarWidth = 27;
}
#endif
TQPixmap originalPixmap = TQPixmap::grabWindow(TQApplication::desktop()->winId(), TQApplication::desktop()->availableGeometry().x(), TQApplication::desktop()->availableGeometry().y(), geometry().width(), geometry().height() );
TQBrush brush(originalPixmap);
TQTransform transform;
transform.translate(0, TQApplication::desktop()->availableGeometry().y());
brush.setTransform(transform);
setBackgroundBrush(brush);
_aboutDialogAsSplashScreen->setPixmap( TQPixmap::grabWidget(_aboutDialog) );
_graphicsProxyWidget->setGeometry( _aboutDialog->geometry() );
_aboutDialog->hide();
_graphicsProxyWidget->setPos( _parentWindow->geometry().x()+(_parentWindow->geometry().width()-_graphicsProxyWidget->geometry().width()) / 2, _parentWindow->y()+_windowTitleBarWidth-_windowPosOffset);
TQRectF r = _graphicsProxyWidget->boundingRect();
_graphicsProxyWidget->setTransform(TQTransform()
.translate(r.width() / 2, -_windowTitleBarWidth)
.rotate(270, TQt::XAxis)
//.rotate(90, TQt::YAxis)
//.rotate(5, TQt::ZAxis)
//.scale(1 + 1.5 * step, 1 + 1.5 * step)
.translate(-r.width() / 2, _windowTitleBarWidth));
_graphicsProxyWidget->show();
//_aboutDialogAsSplashScreen->show();
TQGraphicsView::show();
connect(_timeLine, SIGNAL(finished()), this, SLOT(showAboutDialog()));
_timeLine->setDirection(TQTimeLine::Forward);
_timeLine->start();
TQPixmap originalPixmap = TQPixmap::grabWindow(
TQApplication::desktop()->winId(),
TQApplication::desktop()->availableGeometry().x(),
TQApplication::desktop()->availableGeometry().y(), geometry().width(),
geometry().height());
TQBrush brush(originalPixmap);
TQTransform transform;
transform.translate(0, TQApplication::desktop()->availableGeometry().y());
brush.setTransform(transform);
setBackgroundBrush(brush);
_aboutDialogAsSplashScreen->setPixmap(TQPixmap::grabWidget(_aboutDialog));
_graphicsProxyWidget->setGeometry(_aboutDialog->geometry());
_aboutDialog->hide();
_graphicsProxyWidget->setPos(_parentWindow->geometry().x() +
(_parentWindow->geometry().width() - _graphicsProxyWidget->geometry().width()) / 2,
_parentWindow->y() + _windowTitleBarWidth - _windowPosOffset);
TQRectF r = _graphicsProxyWidget->boundingRect();
_graphicsProxyWidget->setTransform(TQTransform().translate(
r.width() / 2, -_windowTitleBarWidth).rotate(270, TQt::XAxis)
//.rotate(90, TQt::YAxis)
//.rotate(5, TQt::ZAxis)
//.scale(1 + 1.5 * step, 1 + 1.5 * step)
.translate(-r.width() / 2, _windowTitleBarWidth));
_graphicsProxyWidget->show();
//_aboutDialogAsSplashScreen->show();
TQGraphicsView::show();
connect(_timeLine, SIGNAL(finished()), this, SLOT(showAboutDialog()));
_timeLine->setDirection(TQTimeLine::Forward);
_timeLine->start();
}
/*!
\brief Does the next calculation/transformation step.
*/
void AboutDialogGraphicsView::updateStep(int step) {
TQRectF r = _graphicsProxyWidget->boundingRect();
_graphicsProxyWidget->setTransform(TQTransform()
.translate(r.width() / 2, -_windowTitleBarWidth)
.rotate(step, TQt::XAxis)
//.rotate(step, TQt::YAxis)
//.rotate(step * 5, TQt::ZAxis)
//.scale(1 + 1.5 * step, 1 + 1.5 * step)
.translate(-r.width() / 2, _windowTitleBarWidth));
//update();
void AboutDialogGraphicsView::updateStep(int step)
{
TQRectF r = _graphicsProxyWidget->boundingRect();
_graphicsProxyWidget->setTransform(TQTransform().translate(
r.width() / 2, -_windowTitleBarWidth).rotate(step, TQt::XAxis)
//.rotate(step, TQt::YAxis)
//.rotate(step * 5, TQt::ZAxis)
//.scale(1 + 1.5 * step, 1 + 1.5 * step)
.translate(-r.width() / 2, _windowTitleBarWidth));
//update();
}
/*!
\brief Stops the 3D animation, moves the AboutDialog to the correct place and really shows it.
*/
void AboutDialogGraphicsView::showAboutDialog() {
//hide();
disconnect(_timeLine, SIGNAL(finished()), this, SLOT(showAboutDialog()));
_aboutDialog->move( int(_parentWindow->geometry().x()+(_parentWindow->geometry().width()-_graphicsProxyWidget->geometry().width()) / 2), _parentWindow->y()+_windowTitleBarWidth-_windowPosOffset );
_aboutDialog->exec();
void AboutDialogGraphicsView::showAboutDialog()
{
//hide();
disconnect(_timeLine, SIGNAL(finished()), this, SLOT(showAboutDialog()));
_aboutDialog->move(int(_parentWindow->geometry().x() +
(_parentWindow->geometry().width() - _graphicsProxyWidget->geometry().width()) / 2),
_parentWindow->y() + _windowTitleBarWidth - _windowPosOffset);
_aboutDialog->exec();
}
/*!
\brief Does not directly hide the AboutDialog but instead starts the "fade out" 3D animation.
*/
void AboutDialogGraphicsView::hide() {
_graphicsProxyWidget->setPos( _parentWindow->geometry().x()+(_parentWindow->geometry().width()-_graphicsProxyWidget->geometry().width()) / 2, _parentWindow->y()+_windowTitleBarWidth-_windowPosOffset);
TQRectF r = _graphicsProxyWidget->boundingRect();
_graphicsProxyWidget->setTransform(TQTransform()
.translate(r.width() / 2, -_windowTitleBarWidth)
.rotate(0, TQt::XAxis)
//.rotate(90, TQt::YAxis)
//.rotate(5, TQt::ZAxis)
//.scale(1 + 1.5 * step, 1 + 1.5 * step)
.translate(-r.width() / 2, _windowTitleBarWidth));
_graphicsProxyWidget->show();
//_aboutDialogAsSplashScreen->show();
TQGraphicsView::show();
connect(_timeLine, SIGNAL(finished()), this, SLOT(hideReally()));
_timeLine->setDirection(TQTimeLine::Backward);
_timeLine->start();
void AboutDialogGraphicsView::hide()
{
_graphicsProxyWidget->setPos(_parentWindow->geometry().x() +
(_parentWindow->geometry().width() - _graphicsProxyWidget->geometry().width()) / 2,
_parentWindow->y() + _windowTitleBarWidth - _windowPosOffset);
TQRectF r = _graphicsProxyWidget->boundingRect();
_graphicsProxyWidget->setTransform(TQTransform().translate(
r.width() / 2, -_windowTitleBarWidth).rotate(0, TQt::XAxis)
//.rotate(90, TQt::YAxis)
//.rotate(5, TQt::ZAxis)
//.scale(1 + 1.5 * step, 1 + 1.5 * step)
.translate(-r.width() / 2, _windowTitleBarWidth));
_graphicsProxyWidget->show();
//_aboutDialogAsSplashScreen->show();
TQGraphicsView::show();
connect(_timeLine, SIGNAL(finished()), this, SLOT(hideReally()));
_timeLine->setDirection(TQTimeLine::Backward);
_timeLine->start();
}
/*!
\brief This slot really hides this AboutDialog container.
*/
void AboutDialogGraphicsView::hideReally() {
disconnect(_timeLine, SIGNAL(finished()), this, SLOT(hideReally()));
TQGraphicsView::hide();
_parentWindow->activateWindow();
void AboutDialogGraphicsView::hideReally()
{
disconnect(_timeLine, SIGNAL(finished()), this, SLOT(hideReally()));
TQGraphicsView::hide();
_parentWindow->activateWindow();
}

@ -29,28 +29,29 @@ class TQSplashScreen;
class AboutDialogGraphicsView : public TQGraphicsView
{
Q_OBJECT
public:
AboutDialogGraphicsView(AboutDialog *aboutDialog, TQWidget *parentWindow = NULL);
~AboutDialogGraphicsView(void);
public slots:
void show();
void hide();
private slots:
void updateStep(int step);
void showAboutDialog();
void hideReally();
private:
AboutDialog *_aboutDialog;
TQGraphicsProxyWidget *_graphicsProxyWidget;
TQWidget *_parentWindow;
TQTimeLine *_timeLine;
TQSplashScreen *_aboutDialogAsSplashScreen;
int _windowTitleBarWidth;
int _windowPosOffset;
Q_OBJECT
public:
AboutDialogGraphicsView(AboutDialog *aboutDialog, TQWidget *parentWindow = NULL);
~AboutDialogGraphicsView(void);
public slots:
void show();
void hide();
private slots:
void updateStep(int step);
void showAboutDialog();
void hideReally();
private:
AboutDialog *_aboutDialog;
TQGraphicsProxyWidget *_graphicsProxyWidget;
TQWidget *_parentWindow;
TQTimeLine *_timeLine;
TQSplashScreen *_aboutDialogAsSplashScreen;
int _windowTitleBarWidth;
int _windowPosOffset;
};
#endif // ABOUTDIALOGGRAPHICSVIEW_H

File diff suppressed because it is too large Load Diff

@ -38,146 +38,158 @@ class TQToolBox;
class IndentHandler : public TQWidget
{
Q_OBJECT
public:
IndentHandler(int indenterID, TQWidget *mainWindow = NULL, TQWidget *parent = NULL);
~IndentHandler();
TQString generateShellScript(const TQString &configFilename);
TQString callIndenter(TQString sourceCode, TQString inputFileExtension);
bool loadConfigFile(TQString filePathName);
void resetToDefaultValues();
TQStringList getAvailableIndenters();
TQString getPossibleIndenterFileExtensions();
TQString getParameterString();
TQString getIndenterCfgFile();
TQString getManual();
void retranslateUi();
TQString getCurrentIndenterName();
TQMenu* getIndenterMenu();
TQList<TQAction*> getIndenterMenuActions();
void contextMenuEvent( TQContextMenuEvent *event );
void setParameterChangedCallback( void(*paramChangedCallback)(void) );
void setWindowClosedCallback( void(*winClosedCallback)(void) );
int getIndenterId();
signals:
void indenterSettingsChanged();
void selectedIndenterIndexChanged(int index);
protected:
bool event( TQEvent *event );
void closeEvent(TQCloseEvent *event);
void wheelEvent( TQWheelEvent *event );
private slots:
void setIndenter(int indenterID);
void showIndenterManual();
void openConfigFileDialog();
void saveasIndentCfgFileDialog();
void createIndenterCallShellScript();
void resetIndenterParameter();
void handleChangedIndenterSettings();
void updateDrawing();
private:
TQString callExecutableIndenter(TQString sourceCode, TQString inputFileExtension);
TQString callJavaScriptIndenter(TQString sourceCode);
void saveConfigFile(TQString filePathName, TQString parameterString);
void readIndentIniFile(TQString iniFilePath);
bool createIndenterCallString();
void initIndenterMenu();
//! Holds a reference to all created pages of the parameter categories toolbox and the pages boxlayout
struct IndenterParameterCategoryPage {
TQWidget *widget;
TQVBoxLayout *vboxLayout;
};
TQVector<IndenterParameterCategoryPage> _indenterParameterCategoryPages;
//! Holds a reference to all checkboxes needed for boolean parameter setting and the parameters name
struct ParamBoolean {
TQString paramName;
TQString trueString;
TQString falseString;
TQCheckBox *checkBox;
};
TQVector<ParamBoolean> _paramBooleans;
//! Holds a reference to all line edits needed for parameter setting and the parameters name
struct ParamString {
TQString paramName;
TQString paramCallName;
TQCheckBox *valueEnabledChkBox;
TQLineEdit *lineEdit;
TQLabel *label;
};
TQVector<ParamString> _paramStrings;
//! Hold a reference to all spin boxes needed for parameter setting and the parameters name
struct ParamNumeric {
TQString paramName;
TQString paramCallName;
TQCheckBox *valueEnabledChkBox;
TQSpinBox *spinBox;
TQLabel *label;
};
TQVector<ParamNumeric> _paramNumerics;
//! Hold a reference to all combo boxes needed for parameter setting and the parameters name
struct ParamMultiple {
TQString paramName;
TQString paramCallName;
TQCheckBox *valueEnabledChkBox;
TQComboBox *comboBox;
TQStringList choicesStrings;
TQStringList choicesStringsReadable;
};
TQVector<ParamMultiple> _paramMultiples;
TQComboBox *_indenterSelectionCombobox;
TQToolButton *_indenterParameterHelpButton;
//! Vertical layout box, into which the toolbox will be added
TQVBoxLayout *_toolBoxContainerLayout;
TQToolBox *_indenterParameterCategoriesToolBox;
UiGuiIniFileParser *_indenterSettings;
TQStringList _indenterParameters;
//! The indenters name in a descriptive form
TQString _indenterName;
//! The indenters file name (w/o extension), that is being called
TQString _indenterFileName;
TQString _indenterDirctoryStr;
TQString _tempDirctoryStr;
TQString _settingsDirctoryStr;
TQStringList _indenterIniFileList;
TQString _parameterOrder;
TQString _globalConfigFilename;
TQString _cfgFileParameterEnding;
TQString _inputFileParameter;
TQString _inputFileName;
TQString _outputFileParameter;
TQString _outputFileName;
TQString _fileTypes;
TQString _useCfgFileParameter;
TQString _indenterShowHelpParameter;
TQWidget *_mainWindow;
UiGuiErrorMessage *_errorMessageDialog;
TQString _indenterExecutableCallString;
TQString _indenterExecutableSuffix;
TQMenu *_menuIndenter;
TQAction *_actionLoadIndenterConfigFile;
TQAction *_actionSaveIndenterConfigFile;
TQAction *_actionCreateShellScript;
TQAction *_actionResetIndenterParameters;
//! Needed for the NPP plugin.
void(*_parameterChangedCallback)(void);
//! Needed for the NPP plugin.
void(*_windowClosedCallback)(void);
//TODO: This function should go into a string helper/tool class/file.
TQString encodeToHTML(const TQString &text);
Q_OBJECT
public:
IndentHandler(int indenterID, TQWidget *mainWindow = NULL, TQWidget *parent = NULL);
~IndentHandler();
TQString generateShellScript(const TQString &configFilename);
TQString callIndenter(TQString sourceCode, TQString inputFileExtension);
bool loadConfigFile(TQString filePathName);
void resetToDefaultValues();
TQStringList getAvailableIndenters();
TQString getPossibleIndenterFileExtensions();
TQString getParameterString();
TQString getIndenterCfgFile();
TQString getManual();
void retranslateUi();
TQString getCurrentIndenterName();
TQMenu* getIndenterMenu();
TQList<TQAction*> getIndenterMenuActions();
void contextMenuEvent(TQContextMenuEvent *event);
void setParameterChangedCallback(void (*paramChangedCallback)(void));
void setWindowClosedCallback(void (*winClosedCallback)(void));
int getIndenterId();
signals:
void indenterSettingsChanged();
void selectedIndenterIndexChanged(int index);
protected:
bool event(TQEvent *event);
void closeEvent(TQCloseEvent *event);
void wheelEvent(TQWheelEvent *event);
private slots:
void setIndenter(int indenterID);
void showIndenterManual();
void openConfigFileDialog();
void saveasIndentCfgFileDialog();
void createIndenterCallShellScript();
void resetIndenterParameter();
void handleChangedIndenterSettings();
void updateDrawing();
private:
TQString callExecutableIndenter(TQString sourceCode, TQString inputFileExtension);
TQString callJavaScriptIndenter(TQString sourceCode);
void saveConfigFile(TQString filePathName, TQString parameterString);
void readIndentIniFile(TQString iniFilePath);
bool createIndenterCallString();
void initIndenterMenu();
//! Holds a reference to all created pages of the parameter categories toolbox and the pages
// boxlayout
struct IndenterParameterCategoryPage
{
TQWidget *widget;
TQVBoxLayout *vboxLayout;
};
TQVector<IndenterParameterCategoryPage> _indenterParameterCategoryPages;
//! Holds a reference to all checkboxes needed for boolean parameter setting and the parameters
// name
struct ParamBoolean
{
TQString paramName;
TQString trueString;
TQString falseString;
TQCheckBox *checkBox;
};
TQVector<ParamBoolean> _paramBooleans;
//! Holds a reference to all line edits needed for parameter setting and the parameters name
struct ParamString
{
TQString paramName;
TQString paramCallName;
TQCheckBox *valueEnabledChkBox;
TQLineEdit *lineEdit;
TQLabel *label;
};
TQVector<ParamString> _paramStrings;
//! Hold a reference to all spin boxes needed for parameter setting and the parameters name
struct ParamNumeric
{
TQString paramName;
TQString paramCallName;
TQCheckBox *valueEnabledChkBox;
TQSpinBox *spinBox;
TQLabel *label;
};
TQVector<ParamNumeric> _paramNumerics;
//! Hold a reference to all combo boxes needed for parameter setting and the parameters name
struct ParamMultiple
{
TQString paramName;
TQString paramCallName;
TQCheckBox *valueEnabledChkBox;
TQComboBox *comboBox;
TQStringList choicesStrings;
TQStringList choicesStringsReadable;
};
TQVector<ParamMultiple> _paramMultiples;
TQComboBox *_indenterSelectionCombobox;
TQToolButton *_indenterParameterHelpButton;
//! Vertical layout box, into which the toolbox will be added
TQVBoxLayout *_toolBoxContainerLayout;
TQToolBox *_indenterParameterCategoriesToolBox;
UiGuiIniFileParser *_indenterSettings;
TQStringList _indenterParameters;
//! The indenters name in a descriptive form
TQString _indenterName;
//! The indenters file name (w/o extension), that is being called
TQString _indenterFileName;
TQString _indenterDirctoryStr;
TQString _tempDirctoryStr;
TQString _settingsDirctoryStr;
TQStringList _indenterIniFileList;
TQString _parameterOrder;
TQString _globalConfigFilename;
TQString _cfgFileParameterEnding;
TQString _inputFileParameter;
TQString _inputFileName;
TQString _outputFileParameter;
TQString _outputFileName;
TQString _fileTypes;
TQString _useCfgFileParameter;
TQString _indenterShowHelpParameter;
TQWidget *_mainWindow;
UiGuiErrorMessage *_errorMessageDialog;
TQString _indenterExecutableCallString;
TQString _indenterExecutableSuffix;
TQMenu *_menuIndenter;
TQAction *_actionLoadIndenterConfigFile;
TQAction *_actionSaveIndenterConfigFile;
TQAction *_actionCreateShellScript;
TQAction *_actionResetIndenterParameters;
//! Needed for the NPP plugin.
void (*_parameterChangedCallback)(void);
//! Needed for the NPP plugin.
void (*_windowClosedCallback)(void);
//TODO: This function should go into a string helper/tool class/file.
TQString encodeToHTML(const TQString &text);
};
#endif // INDENTHANDLER_H

File diff suppressed because it is too large Load Diff

@ -30,7 +30,8 @@ class AboutDialogGraphicsView;
class UiGuiHighlighter;
class IndentHandler;
class UpdateCheckDialog;
namespace Ui {
namespace Ui
{
class ToolBarWidget;
class MainWindowUi;
}
@ -45,99 +46,101 @@ class QsciScintilla;
class MainWindow : public TQMainWindow
{
Q_OBJECT
public:
//! Constructor
MainWindow(TQString file2OpenOnStart = "", TQWidget *parent = NULL);
~MainWindow() {
_settings.clear();
}
protected:
void closeEvent( TQCloseEvent *event );
bool eventFilter(TQObject *obj, TQEvent *event);
private slots:
void openSourceFileDialog(TQString fileName = "");
bool saveasSourceFileDialog(TQAction *chosenEncodingAction = NULL);
void saveAsOtherEncoding(TQAction *chosenEncodingAction);
bool saveSourceFile();
void callIndenter();
void updateSourceView();
void turnHighlightOnOff(bool turnOn);
void setWhiteSpaceVisibility(bool visible);
void sourceCodeChangedHelperSlot();
void sourceCodeChangedSlot();
void indentSettingsChangedSlot();
void previewTurnedOnOff(bool turnOn);
void exportToPDF();
void exportToHTML();
void languageChanged(int languageIndex);
void encodingChanged(TQAction *encodingAction);
void numberOfLinesChanged();
void updateRecentlyOpenedList();
void openFileFromRecentlyOpenedList(TQAction* recentlyOpenedAction);
void clearRecentlyOpenedList();
void showAboutDialog();
void setStatusBarCursorPosInfo(int line, int column);
private:
Ui::MainWindowUi *_mainWindowForm;
TQString loadFile(TQString filePath);
TQString openFileDialog(TQString dialogHeaderStr, TQString startPath, TQString fileMaskStr);
void updateWindowTitle();
void loadLastOpenedFile();
void saveSettings();
bool maybeSave();
void createEncodingMenu();
void createHighlighterMenu();
bool initApplicationLanguage();
void initMainWindow();
void initToolBar();
void initTextEditor();
void initSyntaxHighlighter();
void initIndenter();
void changeEvent(TQEvent *event);
void dragEnterEvent(TQDragEnterEvent *event);
void dropEvent(TQDropEvent *event);
QsciScintilla *_qSciSourceCodeEditor;
TQSharedPointer<UiGuiSettings> _settings;
TQString _currentEncoding;
TQString _sourceFileContent;
TQString _sourceFormattedContent;
TQString _sourceViewContent;
UiGuiHighlighter *_highlighter;
TQScrollBar *_textEditVScrollBar;
AboutDialog *_aboutDialog;
AboutDialogGraphicsView *_aboutDialogGraphicsView;
UiGuiSettingsDialog *_settingsDialog;
int _textEditLastScrollPos;
int _currentIndenterID;
bool _loadLastSourceCodeFileOnStartup;
TQString _currentSourceFile;
TQString _currentSourceFileExtension;
TQString _savedSourceContent;
TQActionGroup *_encodingActionGroup;
TQActionGroup *_saveEncodedActionGroup;
TQActionGroup *_highlighterActionGroup;
TQTranslator *_uiGuiTranslator;
TQTranslator *_qTTranslator;
bool _isFirstRunOfThisVersion;
bool _sourceCodeChanged;
bool _scrollPositionChanged;
bool _indentSettingsChanged;
bool _previewToggled;
TQStringList _encodingsList;
Ui::ToolBarWidget *_toolBarWidget;
IndentHandler *_indentHandler;
UpdateCheckDialog *_updateCheckDialog;
TQLabel *_textEditLineColumnInfoLabel;
Q_OBJECT
public:
//! Constructor
MainWindow(TQString file2OpenOnStart = "", TQWidget *parent = NULL);
~MainWindow()
{
_settings.clear();
}
protected:
void closeEvent(TQCloseEvent *event);
bool eventFilter(TQObject *obj, TQEvent *event);
private slots:
void openSourceFileDialog(TQString fileName = "");
bool saveasSourceFileDialog(TQAction *chosenEncodingAction = NULL);
void saveAsOtherEncoding(TQAction *chosenEncodingAction);
bool saveSourceFile();
void callIndenter();
void updateSourceView();
void turnHighlightOnOff(bool turnOn);
void setWhiteSpaceVisibility(bool visible);
void sourceCodeChangedHelperSlot();
void sourceCodeChangedSlot();
void indentSettingsChangedSlot();
void previewTurnedOnOff(bool turnOn);
void exportToPDF();
void exportToHTML();
void languageChanged(int languageIndex);
void encodingChanged(TQAction *encodingAction);
void numberOfLinesChanged();
void updateRecentlyOpenedList();
void openFileFromRecentlyOpenedList(TQAction *recentlyOpenedAction);
void clearRecentlyOpenedList();
void showAboutDialog();
void setStatusBarCursorPosInfo(int line, int column);
private:
Ui::MainWindowUi *_mainWindowForm;
TQString loadFile(TQString filePath);
TQString openFileDialog(TQString dialogHeaderStr, TQString startPath, TQString fileMaskStr);
void updateWindowTitle();
void loadLastOpenedFile();
void saveSettings();
bool maybeSave();
void createEncodingMenu();
void createHighlighterMenu();
bool initApplicationLanguage();
void initMainWindow();
void initToolBar();
void initTextEditor();
void initSyntaxHighlighter();
void initIndenter();
void changeEvent(TQEvent *event);
void dragEnterEvent(TQDragEnterEvent *event);
void dropEvent(TQDropEvent *event);
QsciScintilla *_qSciSourceCodeEditor;
TQSharedPointer<UiGuiSettings> _settings;
TQString _currentEncoding;
TQString _sourceFileContent;
TQString _sourceFormattedContent;
TQString _sourceViewContent;
UiGuiHighlighter *_highlighter;
TQScrollBar *_textEditVScrollBar;
AboutDialog *_aboutDialog;
AboutDialogGraphicsView *_aboutDialogGraphicsView;
UiGuiSettingsDialog *_settingsDialog;
int _textEditLastScrollPos;
int _currentIndenterID;
bool _loadLastSourceCodeFileOnStartup;
TQString _currentSourceFile;
TQString _currentSourceFileExtension;
TQString _savedSourceContent;
TQActionGroup *_encodingActionGroup;
TQActionGroup *_saveEncodedActionGroup;
TQActionGroup *_highlighterActionGroup;
TQTranslator *_uiGuiTranslator;
TQTranslator *_qTTranslator;
bool _isFirstRunOfThisVersion;
bool _sourceCodeChanged;
bool _scrollPositionChanged;
bool _indentSettingsChanged;
bool _previewToggled;
TQStringList _encodingsList;
Ui::ToolBarWidget *_toolBarWidget;
IndentHandler *_indentHandler;
UpdateCheckDialog *_updateCheckDialog;
TQLabel *_textEditLineColumnInfoLabel;
};
#endif // MAINWINDOW_H

@ -37,14 +37,13 @@
paths needed for settings can be retrieved.
*/
bool SettingsPaths::_alreadyInitialized = false;
bool SettingsPaths::_alreadyInitialized = false;
TQString SettingsPaths::_applicationBinaryPath = "";
TQString SettingsPaths::_settingsPath = "";
TQString SettingsPaths::_settingsPath = "";
TQString SettingsPaths::_globalFilesPath = "";
TQString SettingsPaths::_indenterPath = "";
TQString SettingsPaths::_tempPath = "";
bool SettingsPaths::_portableMode = false;
TQString SettingsPaths::_indenterPath = "";
TQString SettingsPaths::_tempPath = "";
bool SettingsPaths::_portableMode = false;
/*!
\brief Initializes all available information about the paths.
@ -56,220 +55,255 @@ bool SettingsPaths::_portableMode = false;
Means also that the directory "indenters" has to be there.
In not portable mode (multiuser mode) only users home directory is used for writing config data.
*/
void SettingsPaths::init() {
_alreadyInitialized = true;
void SettingsPaths::init()
{
_alreadyInitialized = true;
tqDebug() << __LINE__ << " " << __FUNCTION__ << ": Initializing application paths.";
tqDebug() << __LINE__ << " " << __FUNCTION__ << ": Initializing application paths.";
// Get the applications binary path, with respect to MacOSXs use of the .app folder.
_applicationBinaryPath = TQCoreApplication::applicationDirPath();
// Remove any trailing slashes
while ( _applicationBinaryPath.right(1) == "/" ) {
_applicationBinaryPath.chop(1);
}
// Get the applications binary path, with respect to MacOSXs use of the .app folder.
_applicationBinaryPath = TQCoreApplication::applicationDirPath();
// Remove any trailing slashes
while (_applicationBinaryPath.right(1) == "/")
{
_applicationBinaryPath.chop(1);
}
#ifdef UNIVERSALINDENTGUI_NPP_EXPORTS
_applicationBinaryPath += "/plugins/uigui";
_applicationBinaryPath += "/plugins/uigui";
#endif
#ifdef Q_OS_MAC
// Because on Mac universal binaries are used, the binary path is not equal
// to the applications (.app) path. So get the .apps path here.
int indexOfDotApp = _applicationBinaryPath.indexOf(".app");
if ( indexOfDotApp != -1 ) {
// Cut off after the dot of ".app".
_applicationBinaryPath = _applicationBinaryPath.left( indexOfDotApp-1 );
// Cut off after the first slash that was in front of ".app" (normally this is the word "UniversalIndentGUI")
_applicationBinaryPath = _applicationBinaryPath.left( _applicationBinaryPath.lastIndexOf("/") );
}
// Because on Mac universal binaries are used, the binary path is not equal
// to the applications (.app) path. So get the .apps path here.
int indexOfDotApp = _applicationBinaryPath.indexOf(".app");
if (indexOfDotApp != -1)
{
// Cut off after the dot of ".app".
_applicationBinaryPath = _applicationBinaryPath.left(indexOfDotApp - 1);
// Cut off after the first slash that was in front of ".app" (normally this is the word
// "UniversalIndentGUI")
_applicationBinaryPath = _applicationBinaryPath.left(_applicationBinaryPath.lastIndexOf("/"));
}
#endif
// If the "config" directory is a subdir of the applications binary path, use this one (portable mode)
_settingsPath = _applicationBinaryPath + "/config";
if ( TQFile::exists( _settingsPath ) ) {
_portableMode = true;
TQDir dirCreator;
_globalFilesPath = _applicationBinaryPath;
_indenterPath = _applicationBinaryPath + "/indenters";
dirCreator.mkpath( _settingsPath );
_tempPath = _applicationBinaryPath + "/temp";
//TODO: If the portable drive has write protection, use local temp path and clean it up on exit.
dirCreator.mkpath( _tempPath );
}
// ... otherwise use the system specific global application data path.
else {
_portableMode = false;
TQDir dirCreator;
// If the "config" directory is a subdir of the applications binary path, use this one (portable
// mode)
_settingsPath = _applicationBinaryPath + "/config";
if (TQFile::exists(_settingsPath))
{
_portableMode = true;
TQDir dirCreator;
_globalFilesPath = _applicationBinaryPath;
_indenterPath = _applicationBinaryPath + "/indenters";
dirCreator.mkpath(_settingsPath);
_tempPath = _applicationBinaryPath + "/temp";
//TODO: If the portable drive has write protection, use local temp path and clean it up on exit.
dirCreator.mkpath(_tempPath);
}
// ... otherwise use the system specific global application data path.
else
{
_portableMode = false;
TQDir dirCreator;
#ifdef Q_OS_WIN
// Get the local users application settings directory.
// Remove any trailing slashes.
_settingsPath = TQDir::fromNativeSeparators( qgetenv("APPDATA") );
while ( _settingsPath.right(1) == "/" ) {
_settingsPath.chop(1);
}
_settingsPath = _settingsPath + "/UniversalIndentGUI";
// On windows systems the directories "indenters", "translations" are subdirs of the _applicationBinaryPath.
_globalFilesPath = _applicationBinaryPath;
// Get the local users application settings directory.
// Remove any trailing slashes.
_settingsPath = TQDir::fromNativeSeparators(qgetenv("APPDATA"));
while (_settingsPath.right(1) == "/")
{
_settingsPath.chop(1);
}
_settingsPath = _settingsPath + "/UniversalIndentGUI";
// On windows systems the directories "indenters", "translations" are subdirs of the
// _applicationBinaryPath.
_globalFilesPath = _applicationBinaryPath;
#else
// Remove any trailing slashes.
_settingsPath = TQDir::homePath();
while ( _settingsPath.right(1) == "/" ) {
_settingsPath.chop(1);
}
_settingsPath = _settingsPath + "/.universalindentgui";
_globalFilesPath = "/usr/share/universalindentgui";
// Remove any trailing slashes.
_settingsPath = TQDir::homePath();
while (_settingsPath.right(1) == "/")
{
_settingsPath.chop(1);
}
_settingsPath = _settingsPath + "/.universalindentgui";
_globalFilesPath = "/usr/share/universalindentgui";
#endif
dirCreator.mkpath( _settingsPath );
// If a highlighter config file does not exist in the users home config dir
// copy the default config file over there.
if ( !TQFile::exists(_settingsPath+"/UiGuiSyntaxHighlightConfig.ini") ) {
TQFile::copy( _globalFilesPath+"/config/UiGuiSyntaxHighlightConfig.ini", _settingsPath+"/UiGuiSyntaxHighlightConfig.ini" );
}
_indenterPath = _globalFilesPath + "/indenters";
// On different systems it may be that "TQDir::tempPath()" ends with a "/" or not. So check this.
// Remove any trailing slashes.
_tempPath = TQDir::tempPath();
while ( _tempPath.right(1) == "/" ) {
_tempPath.chop(1);
}
_tempPath = _tempPath + "/UniversalIndentGUI";
#if defined(Q_OS_WIN32)
dirCreator.mkpath( _tempPath );
dirCreator.mkpath(_settingsPath);
// If a highlighter config file does not exist in the users home config dir
// copy the default config file over there.
if (!TQFile::exists(_settingsPath + "/UiGuiSyntaxHighlightConfig.ini"))
{
TQFile::copy(_globalFilesPath + "/config/UiGuiSyntaxHighlightConfig.ini",
_settingsPath + "/UiGuiSyntaxHighlightConfig.ini");
}
_indenterPath = _globalFilesPath + "/indenters";
// On different systems it may be that "TQDir::tempPath()" ends with a "/" or not. So check
// this.
// Remove any trailing slashes.
_tempPath = TQDir::tempPath();
while (_tempPath.right(1) == "/")
{
_tempPath.chop(1);
}
_tempPath = _tempPath + "/UniversalIndentGUI";
#if defined (Q_OS_WIN32)
dirCreator.mkpath(_tempPath);
#else
// On Unix based systems create a random temporary directory for security
// reasons. Otherwise an evil human being could create a symbolic link
// to an important existing file which gets overwritten when UiGUI writes
// into this normally temporary but linked file.
char *pathTemplate = new char[_tempPath.length()+8];
TQByteArray pathTemplateTQBA = TQString(_tempPath + "-XXXXXX").toAscii();
delete [] pathTemplate;
pathTemplate = pathTemplateTQBA.data();
pathTemplate = mkdtemp( pathTemplate );
_tempPath = pathTemplate;
// On Unix based systems create a random temporary directory for security
// reasons. Otherwise an evil human being could create a symbolic link
// to an important existing file which gets overwritten when UiGUI writes
// into this normally temporary but linked file.
char *pathTemplate = new char[_tempPath.length() + 8];
TQByteArray pathTemplateTQBA = TQString(_tempPath + "-XXXXXX").toAscii();
delete[] pathTemplate;
pathTemplate = pathTemplateTQBA.data();
pathTemplate = mkdtemp(pathTemplate);
_tempPath = pathTemplate;
#endif
}
tqDebug() << __LINE__ << " " << __FUNCTION__ << ": Paths are:" \
"<ul><li>_applicationBinaryPath=" << _applicationBinaryPath \
<< "</li><li>_settingsPath=" << _settingsPath \
<< "</li><li>_globalFilesPath=" << _globalFilesPath \
<< "</li><li>_indenterPath=" << _indenterPath \
<< "</li><li>_tempPath=" << _tempPath \
<< "</li><li>Running in portable mode=" << _portableMode << "</li></ul>";
}
tqDebug() << __LINE__ << " " << __FUNCTION__ << ": Paths are:" \
"<ul><li>_applicationBinaryPath=" <<
_applicationBinaryPath << "</li><li>_settingsPath=" << _settingsPath <<
"</li><li>_globalFilesPath=" << _globalFilesPath << "</li><li>_indenterPath=" <<
_indenterPath << "</li><li>_tempPath=" << _tempPath <<
"</li><li>Running in portable mode=" << _portableMode << "</li></ul>";
}
/*!
\brief Returns the path of the applications executable.
*/
const TQString SettingsPaths::getApplicationBinaryPath() {
if ( !_alreadyInitialized ) {
SettingsPaths::init();
}
return _applicationBinaryPath;
const TQString SettingsPaths::getApplicationBinaryPath()
{
if (!_alreadyInitialized)
{
SettingsPaths::init();
}
return _applicationBinaryPath;
}
/*!
\brief Returns the path where all settings are being/should be written to.
*/
const TQString SettingsPaths::getSettingsPath() {
if ( !_alreadyInitialized ) {
SettingsPaths::init();
}
return _settingsPath;
const TQString SettingsPaths::getSettingsPath()
{
if (!_alreadyInitialized)
{
SettingsPaths::init();
}
return _settingsPath;
}
/*!
\brief Returns the path where the files concerning all users reside. For example translations.
*/
const TQString SettingsPaths::getGlobalFilesPath() {
if ( !_alreadyInitialized ) {
SettingsPaths::init();
}
return _globalFilesPath;
const TQString SettingsPaths::getGlobalFilesPath()
{
if (!_alreadyInitialized)
{
SettingsPaths::init();
}
return _globalFilesPath;
}
/*!
\brief Returns the path where the indenter executables reside.
*/
const TQString SettingsPaths::getIndenterPath() {
if ( !_alreadyInitialized ) {
SettingsPaths::init();
}
return _indenterPath;
const TQString SettingsPaths::getIndenterPath()
{
if (!_alreadyInitialized)
{
SettingsPaths::init();
}
return _indenterPath;
}
/*!
\brief Returns the path where the where all temporary data should be written to.
*/
const TQString SettingsPaths::getTempPath() {
if ( !_alreadyInitialized ) {
SettingsPaths::init();
}
return _tempPath;
const TQString SettingsPaths::getTempPath()
{
if (!_alreadyInitialized)
{
SettingsPaths::init();
}
return _tempPath;
}
/*!
\brief Returns true if portable mode shall be used.
*/
bool SettingsPaths::getPortableMode() {
if ( !_alreadyInitialized ) {
SettingsPaths::init();
}
return _portableMode;
bool SettingsPaths::getPortableMode()
{
if (!_alreadyInitialized)
{
SettingsPaths::init();
}
return _portableMode;
}
/*!
\brief Completely deletes the created temporary directory with all of its content.
*/
void SettingsPaths::cleanAndRemoveTempDir() {
TQDirIterator dirIterator(_tempPath, TQDirIterator::Subdirectories);
TQStack<TQString> directoryStack;
bool noErrorsOccurred = true;
while ( dirIterator.hasNext() ) {
TQString currentDirOrFile = dirIterator.next();
// If this dummy call isn't done here, calling "dirIterator.fileInfo().isDir()" later somehow fails.
dirIterator.fileInfo();
if ( !currentDirOrFile.isEmpty() && dirIterator.fileName() != "." && dirIterator.fileName() != ".." ) {
// There is a path on the stack but the current path doesn't start with that path.
// So we changed into another parent directory and the one on the stack can be deleted
// since it must be empty.
if ( !directoryStack.isEmpty() && !currentDirOrFile.startsWith(directoryStack.top()) ) {
TQString dirToBeRemoved = directoryStack.pop();
bool couldRemoveDir = TQDir(dirToBeRemoved).rmdir(dirToBeRemoved);
noErrorsOccurred &= couldRemoveDir;
if ( couldRemoveDir == false )
tqWarning() << __LINE__ << " " << __FUNCTION__ << "Could not remove the directory: " << dirToBeRemoved;
//tqDebug() << "Removing Dir " << directoryStack.pop();
}
// If the iterator currently points to a directory push it onto the stack.
if ( dirIterator.fileInfo().isDir() ) {
directoryStack.push( currentDirOrFile );
//tqDebug() << "Pushing onto Stack " << currentDirOrFile;
}
// otherwise it must be a file, so delete it.
else {
bool couldRemoveFile = TQFile::remove( currentDirOrFile );
noErrorsOccurred &= couldRemoveFile;
if ( couldRemoveFile == false )
tqWarning() << __LINE__ << " " << __FUNCTION__ << "Could not remove the file: " << currentDirOrFile;
//tqDebug() << "Removing File " << currentDirOrFile;
}
}
}
noErrorsOccurred &= TQDir(_tempPath).rmdir(_tempPath);
if ( noErrorsOccurred == false )
tqWarning() << __LINE__ << " " << __FUNCTION__ << "While cleaning up the temp dir an error occurred.";
void SettingsPaths::cleanAndRemoveTempDir()
{
TQDirIterator dirIterator(_tempPath, TQDirIterator::Subdirectories);
TQStack<TQString> directoryStack;
bool noErrorsOccurred = true;
while (dirIterator.hasNext())
{
TQString currentDirOrFile = dirIterator.next();
// If this dummy call isn't done here, calling "dirIterator.fileInfo().isDir()" later somehow
// fails.
dirIterator.fileInfo();
if (!currentDirOrFile.isEmpty() && dirIterator.fileName() != "." &&
dirIterator.fileName() != "..")
{
// There is a path on the stack but the current path doesn't start with that path.
// So we changed into another parent directory and the one on the stack can be deleted
// since it must be empty.
if (!directoryStack.isEmpty() && !currentDirOrFile.startsWith(directoryStack.top()))
{
TQString dirToBeRemoved = directoryStack.pop();
bool couldRemoveDir = TQDir(dirToBeRemoved).rmdir(dirToBeRemoved);
noErrorsOccurred &= couldRemoveDir;
if (couldRemoveDir == false)
{
tqWarning() << __LINE__ << " " << __FUNCTION__ << "Could not remove the directory: " <<
dirToBeRemoved;
}
//tqDebug() << "Removing Dir " << directoryStack.pop();
}
// If the iterator currently points to a directory push it onto the stack.
if (dirIterator.fileInfo().isDir())
{
directoryStack.push(currentDirOrFile);
//tqDebug() << "Pushing onto Stack " << currentDirOrFile;
}
// otherwise it must be a file, so delete it.
else
{
bool couldRemoveFile = TQFile::remove(currentDirOrFile);
noErrorsOccurred &= couldRemoveFile;
if (couldRemoveFile == false)
{
tqWarning() << __LINE__ << " " << __FUNCTION__ << "Could not remove the file: " <<
currentDirOrFile;
}
//tqDebug() << "Removing File " << currentDirOrFile;
}
}
}
noErrorsOccurred &= TQDir(_tempPath).rmdir(_tempPath);
if (noErrorsOccurred == false)
{
tqWarning() << __LINE__ << " " << __FUNCTION__ <<
"While cleaning up the temp dir an error occurred.";
}
}

@ -25,26 +25,26 @@ class TQString;
class SettingsPaths
{
public:
static void init();
static const TQString getApplicationBinaryPath();
static const TQString getSettingsPath();
static const TQString getGlobalFilesPath();
static const TQString getIndenterPath();
static const TQString getTempPath();
static bool getPortableMode();
static void cleanAndRemoveTempDir();
public:
static void init();
static const TQString getApplicationBinaryPath();
static const TQString getSettingsPath();
static const TQString getGlobalFilesPath();
static const TQString getIndenterPath();
static const TQString getTempPath();
static bool getPortableMode();
static void cleanAndRemoveTempDir();
private:
SettingsPaths();
private:
SettingsPaths();
static bool _alreadyInitialized;
static TQString _applicationBinaryPath;
static TQString _settingsPath;
static TQString _globalFilesPath;
static TQString _indenterPath;
static TQString _tempPath;
static bool _portableMode;
static bool _alreadyInitialized;
static TQString _applicationBinaryPath;
static TQString _settingsPath;
static TQString _globalFilesPath;
static TQString _indenterPath;
static TQString _tempPath;
static bool _portableMode;
};
#endif // SETTINGSPATHS_H

@ -33,95 +33,95 @@
"__INDENTERCALLSTRING2__" the call string for indenting only one file.
And "__INDENTERCALLSTRINGSCRIPTNAME__" which is only the shown name of the indenter.
*/
const char* TemplateBatchScript::getTemplateBatchScript() {
static const char* templateBatchScript =
#if defined(Q_OS_WIN32)
"@echo off\n"
"\n"
"IF (%1)==() GOTO error\n"
"dir /b /ad %1 >nul 2>nul && GOTO indentDir\n"
"IF NOT EXIST %1 GOTO error\n"
"goto indentFile\n"
"\n"
":indentDir\n"
"set searchdir=%1\n"
"\n"
"IF (%2)==() GOTO assignDefaultSuffix\n"
"set filesuffix=%2\n"
"\n"
"GOTO run\n"
"\n"
":assignDefaultSuffix\n"
"::echo !!!!DEFAULT SUFFIX!!!\n"
"set filesuffix=*\n"
"\n"
":run\n"
"FOR /F \"tokens=*\" %%G IN ('DIR /B /S %searchdir%\\*.%filesuffix%') DO (\n"
"echo Indenting file \"%%G\"\n"
"__INDENTERCALLSTRING1__\n"
")\n"
"GOTO ende\n"
"\n"
":indentFile\n"
"echo Indenting one file %1\n"
"__INDENTERCALLSTRING2__\n"
"\n"
"GOTO ende\n"
"\n"
":error\n"
"echo .\n"
"echo ERROR: As parameter given directory or file does not exist!\n"
"echo Syntax is: __INDENTERCALLSTRINGSCRIPTNAME__ dirname filesuffix\n"
"echo Syntax is: __INDENTERCALLSTRINGSCRIPTNAME__ filename\n"
"echo Example: __INDENTERCALLSTRINGSCRIPTNAME__ temp cpp\n"
"echo .\n"
"\n"
":ende\n";
const char* TemplateBatchScript::getTemplateBatchScript()
{
static const char *templateBatchScript =
#if defined (Q_OS_WIN32)
"@echo off\n"
"\n"
"IF (%1)==() GOTO error\n"
"dir /b /ad %1 >nul 2>nul && GOTO indentDir\n"
"IF NOT EXIST %1 GOTO error\n"
"goto indentFile\n"
"\n"
":indentDir\n"
"set searchdir=%1\n"
"\n"
"IF (%2)==() GOTO assignDefaultSuffix\n"
"set filesuffix=%2\n"
"\n"
"GOTO run\n"
"\n"
":assignDefaultSuffix\n"
"::echo !!!!DEFAULT SUFFIX!!!\n"
"set filesuffix=*\n"
"\n"
":run\n"
"FOR /F \"tokens=*\" %%G IN ('DIR /B /S %searchdir%\\*.%filesuffix%') DO (\n"
"echo Indenting file \"%%G\"\n"
"__INDENTERCALLSTRING1__\n"
")\n"
"GOTO ende\n"
"\n"
":indentFile\n"
"echo Indenting one file %1\n"
"__INDENTERCALLSTRING2__\n"
"\n"
"GOTO ende\n"
"\n"
":error\n"
"echo .\n"
"echo ERROR: As parameter given directory or file does not exist!\n"
"echo Syntax is: __INDENTERCALLSTRINGSCRIPTNAME__ dirname filesuffix\n"
"echo Syntax is: __INDENTERCALLSTRINGSCRIPTNAME__ filename\n"
"echo Example: __INDENTERCALLSTRINGSCRIPTNAME__ temp cpp\n"
"echo .\n"
"\n"
":ende\n";
#else
"#!/bin/sh \n"
"\n"
"if [ ! -n \"$1\" ]; then\n"
"echo \"Syntax is: recurse.sh dirname filesuffix\"\n"
"echo \"Syntax is: recurse.sh filename\"\n"
"echo \"Example: recurse.sh temp cpp\"\n"
"exit 1\n"
"fi\n"
"\n"
"if [ -d \"$1\" ]; then\n"
"#echo \"Dir ${1} exists\"\n"
"if [ -n \"$2\" ]; then\n"
"filesuffix=$2\n"
"else\n"
"filesuffix=\"*\"\n"
"fi\n"
"\n"
"#echo \"Filtering files using suffix ${filesuffix}\"\n"
"\n"
"file_list=`find ${1} -name \"*.${filesuffix}\" -type f`\n"
"for file2indent in $file_list\n"
"do \n"
"echo \"Indenting file $file2indent\"\n"
"__INDENTERCALLSTRING1__\n"
"done\n"
"else\n"
"if [ -f \"$1\" ]; then\n"
"echo \"Indenting one file $1\"\n"
"__INDENTERCALLSTRING2__\n"
"else\n"
"echo \"ERROR: As parameter given directory or file does not exist!\"\n"
"echo \"Syntax is: __INDENTERCALLSTRINGSCRIPTNAME__ dirname filesuffix\"\n"
"echo \"Syntax is: __INDENTERCALLSTRINGSCRIPTNAME__ filename\"\n"
"echo \"Example: __INDENTERCALLSTRINGSCRIPTNAME__ temp cpp\"\n"
"exit 1\n"
"fi\n"
"fi\n";
"#!/bin/sh \n"
"\n"
"if [ ! -n \"$1\" ]; then\n"
"echo \"Syntax is: recurse.sh dirname filesuffix\"\n"
"echo \"Syntax is: recurse.sh filename\"\n"
"echo \"Example: recurse.sh temp cpp\"\n"
"exit 1\n"
"fi\n"
"\n"
"if [ -d \"$1\" ]; then\n"
"#echo \"Dir ${1} exists\"\n"
"if [ -n \"$2\" ]; then\n"
"filesuffix=$2\n"
"else\n"
"filesuffix=\"*\"\n"
"fi\n"
"\n"
"#echo \"Filtering files using suffix ${filesuffix}\"\n"
"\n"
"file_list=`find ${1} -name \"*.${filesuffix}\" -type f`\n"
"for file2indent in $file_list\n"
"do \n"
"echo \"Indenting file $file2indent\"\n"
"__INDENTERCALLSTRING1__\n"
"done\n"
"else\n"
"if [ -f \"$1\" ]; then\n"
"echo \"Indenting one file $1\"\n"
"__INDENTERCALLSTRING2__\n"
"else\n"
"echo \"ERROR: As parameter given directory or file does not exist!\"\n"
"echo \"Syntax is: __INDENTERCALLSTRINGSCRIPTNAME__ dirname filesuffix\"\n"
"echo \"Syntax is: __INDENTERCALLSTRINGSCRIPTNAME__ filename\"\n"
"echo \"Example: __INDENTERCALLSTRINGSCRIPTNAME__ temp cpp\"\n"
"exit 1\n"
"fi\n"
"fi\n";
#endif // #if defined(Q_OS_WIN32)
return templateBatchScript;
return templateBatchScript;
}
/* Here comes the original batch script without the c++ markup
@echo off

@ -22,10 +22,11 @@
class TemplateBatchScript
{
private:
TemplateBatchScript();
public:
static const char* getTemplateBatchScript();
private:
TemplateBatchScript();
public:
static const char* getTemplateBatchScript();
};
#endif // TEMPLATEBATCHSCRIPT_H

@ -36,20 +36,21 @@
Retrieves the object pointer to the \a _showAgainCheckBox check box, sets the dialogs
modality and for a working translation sets the check box text.
*/
UiGuiErrorMessage::UiGuiErrorMessage(TQWidget *parent) : TQErrorMessage(parent) {
_showAgainCheckBox = findChild<TQCheckBox *>();
setWindowModality( TQt::ApplicationModal );
_showAgainCheckBox->setText( tr("Show this message again") );
UiGuiErrorMessage::UiGuiErrorMessage(TQWidget *parent) :
TQErrorMessage(parent)
{
_showAgainCheckBox = findChild<TQCheckBox*>();
setWindowModality(TQt::ApplicationModal);
_showAgainCheckBox->setText(tr("Show this message again"));
}
/*!
\brief Just a lazy nothin doin destructive destructor.
*/
UiGuiErrorMessage::~UiGuiErrorMessage(void) {
UiGuiErrorMessage::~UiGuiErrorMessage(void)
{
}
/*!
\brief Shows an error \a message in a dialog box with \a title.
@ -57,31 +58,36 @@ UiGuiErrorMessage::~UiGuiErrorMessage(void) {
already in that list and "Show this message again" is not checked, that
message will not be shown.
*/
void UiGuiErrorMessage::showMessage( const TQString &title, const TQString &message ) {
bool showAgain = true;
if ( _showAgainCheckBox != 0 ) {
showAgain = _showAgainCheckBox->isChecked();
}
setWindowTitle(title);
if ( !_errorMessageList.contains(message) ) {
_errorMessageList << message;
if ( _showAgainCheckBox != 0 ) {
_showAgainCheckBox->setChecked(true);
}
TQErrorMessage::showMessage( message );
}
else if ( showAgain ) {
TQErrorMessage::showMessage( message );
}
void UiGuiErrorMessage::showMessage(const TQString &title, const TQString &message)
{
bool showAgain = true;
if (_showAgainCheckBox != 0)
{
showAgain = _showAgainCheckBox->isChecked();
}
setWindowTitle(title);
if (!_errorMessageList.contains(message))
{
_errorMessageList << message;
if (_showAgainCheckBox != 0)
{
_showAgainCheckBox->setChecked(true);
}
TQErrorMessage::showMessage(message);
}
else if (showAgain)
{
TQErrorMessage::showMessage(message);
}
}
/*!
\brief For convinience, for showing a dialog box with the default title "UniversalIndentGUI".
*/
void UiGuiErrorMessage::showMessage( const TQString &message ) {
showMessage( "UniversalIndentGUI", message );
void UiGuiErrorMessage::showMessage(const TQString &message)
{
showMessage("UniversalIndentGUI", message);
}

@ -27,17 +27,18 @@ class TQCheckBox;
class UiGuiErrorMessage : public TQErrorMessage
{
Q_OBJECT
Q_OBJECT
public:
UiGuiErrorMessage(TQWidget *parent = 0);
~UiGuiErrorMessage(void);
void showMessage( const TQString &message );
void showMessage( const TQString &title, const TQString &message );
public:
UiGuiErrorMessage(TQWidget *parent = 0);
~UiGuiErrorMessage(void);
private:
TQCheckBox *_showAgainCheckBox;
TQStringList _errorMessageList;
void showMessage(const TQString &message);
void showMessage(const TQString &title, const TQString &message);
private:
TQCheckBox *_showAgainCheckBox;
TQStringList _errorMessageList;
};
#endif // UIGUIERRORMESSAGE_H

@ -36,9 +36,9 @@
#include <Qsci/qscilexercss.h>
#include <Qsci/qscilexerd.h>
#include <Qsci/qscilexerdiff.h>
#if ( TQSCINTILLA_VERSION >= 0x020300 )
#include <Qsci/qscilexerfortran.h>
#include <Qsci/qscilexerfortran77.h>
#if (TQSCINTILLA_VERSION >= 0x020300)
#include <Qsci/qscilexerfortran.h>
#include <Qsci/qscilexerfortran77.h>
#endif
#include <Qsci/qscilexerhtml.h>
#include <Qsci/qscilexeridl.h>
@ -46,32 +46,32 @@
#include <Qsci/qscilexerjavascript.h>
#include <Qsci/qscilexerlua.h>
#include <Qsci/qscilexermakefile.h>
#if ( TQSCINTILLA_VERSION >= 0x020300 )
#include <Qsci/qscilexerpascal.h>
#if (TQSCINTILLA_VERSION >= 0x020300)
#include <Qsci/qscilexerpascal.h>
#endif
#include <Qsci/qscilexerperl.h>
#if ( TQSCINTILLA_VERSION >= 0x020300 )
#include <Qsci/qscilexerpostscript.h>
#if (TQSCINTILLA_VERSION >= 0x020300)
#include <Qsci/qscilexerpostscript.h>
#endif
#include <Qsci/qscilexerpov.h>
#include <Qsci/qscilexerproperties.h>
#include <Qsci/qscilexerpython.h>
#include <Qsci/qscilexerruby.h>
#if ( TQSCINTILLA_VERSION >= 0x020400 )
#include <Qsci/qscilexerspice.h>
#if (TQSCINTILLA_VERSION >= 0x020400)
#include <Qsci/qscilexerspice.h>
#endif
#include <Qsci/qscilexersql.h>
#if ( TQSCINTILLA_VERSION >= 0x020300 )
#include <Qsci/qscilexertcl.h>
#if (TQSCINTILLA_VERSION >= 0x020300)
#include <Qsci/qscilexertcl.h>
#endif
#include <Qsci/qscilexertex.h>
#if ( TQSCINTILLA_VERSION >= 0x020400 )
#include <Qsci/qscilexerverilog.h>
#if (TQSCINTILLA_VERSION >= 0x020400)
#include <Qsci/qscilexerverilog.h>
#endif
#include <Qsci/qscilexervhdl.h>
#if ( TQSCINTILLA_VERSION >= 0x020300 )
#include <Qsci/qscilexerxml.h>
#include <Qsci/qscilexeryaml.h>
#if (TQSCINTILLA_VERSION >= 0x020300)
#include <Qsci/qscilexerxml.h>
#include <Qsci/qscilexeryaml.h>
#endif
//! \defgroup grp_EditorComponent All concerning editor widget.
@ -85,444 +85,520 @@
/*!
\brief The constructor initializes some regular expressions and keywords to identify cpp tokens
*/
UiGuiHighlighter::UiGuiHighlighter(QsciScintilla *parent) : TQObject(parent) {
_qsciEditorParent = parent;
// Create the highlighter _settings object from the UiGuiSyntaxHighlightConfig.ini file.
_settings = new TQSettings(SettingsPaths::getSettingsPath() + "/UiGuiSyntaxHighlightConfig.ini", TQSettings::IniFormat, this);
_highlightningIsOn = true;
_mapHighlighternameToExtension["Bash"] = TQStringList() << "sh";
_mapHighlighternameToExtension["Batch"] = TQStringList() << "bat";
_mapHighlighternameToExtension["CMake"] = TQStringList() << "cmake";
_mapHighlighternameToExtension["C++"] = TQStringList() << "c" << "h" << "cpp" << "hpp" << "cxx" << "hxx";
_mapHighlighternameToExtension["C#"] = TQStringList() << "cs";
_mapHighlighternameToExtension["CSS"] = TQStringList() << "css";
_mapHighlighternameToExtension["D"] = TQStringList() << "d";
_mapHighlighternameToExtension["Diff"] = TQStringList() << "diff";
#if ( TQSCINTILLA_VERSION >= 0x020300 )
_mapHighlighternameToExtension["Fortran"] = TQStringList() << "f" << "for" << "f90";
_mapHighlighternameToExtension["Fortran77"] = TQStringList() << "f77";
UiGuiHighlighter::UiGuiHighlighter(QsciScintilla *parent) :
TQObject(parent)
{
_qsciEditorParent = parent;
// Create the highlighter _settings object from the UiGuiSyntaxHighlightConfig.ini file.
_settings = new TQSettings(
SettingsPaths::getSettingsPath() + "/UiGuiSyntaxHighlightConfig.ini", TQSettings::IniFormat,
this);
_highlightningIsOn = true;
_mapHighlighternameToExtension["Bash"] = TQStringList() << "sh";
_mapHighlighternameToExtension["Batch"] = TQStringList() << "bat";
_mapHighlighternameToExtension["CMake"] = TQStringList() << "cmake";
_mapHighlighternameToExtension["C++"] = TQStringList() << "c" << "h" << "cpp" << "hpp" <<
"cxx" << "hxx";
_mapHighlighternameToExtension["C#"] = TQStringList() << "cs";
_mapHighlighternameToExtension["CSS"] = TQStringList() << "css";
_mapHighlighternameToExtension["D"] = TQStringList() << "d";
_mapHighlighternameToExtension["Diff"] = TQStringList() << "diff";
#if (TQSCINTILLA_VERSION >= 0x020300)
_mapHighlighternameToExtension["Fortran"] = TQStringList() << "f" << "for" << "f90";
_mapHighlighternameToExtension["Fortran77"] = TQStringList() << "f77";
#endif
_mapHighlighternameToExtension["HTML"] = TQStringList() << "html" << "htm";
_mapHighlighternameToExtension["IDL"] = TQStringList() << "idl";
_mapHighlighternameToExtension["Java"] = TQStringList() << "java";
_mapHighlighternameToExtension["JavaScript"] = TQStringList() << "js";
_mapHighlighternameToExtension["LUA"] = TQStringList() << "lua";
_mapHighlighternameToExtension["Makefile"] = TQStringList() << "makefile";
#if ( TQSCINTILLA_VERSION >= 0x020300 )
_mapHighlighternameToExtension["Pascal"] = TQStringList() << "pas";
_mapHighlighternameToExtension["HTML"] = TQStringList() << "html" << "htm";
_mapHighlighternameToExtension["IDL"] = TQStringList() << "idl";
_mapHighlighternameToExtension["Java"] = TQStringList() << "java";
_mapHighlighternameToExtension["JavaScript"] = TQStringList() << "js";
_mapHighlighternameToExtension["LUA"] = TQStringList() << "lua";
_mapHighlighternameToExtension["Makefile"] = TQStringList() << "makefile";
#if (TQSCINTILLA_VERSION >= 0x020300)
_mapHighlighternameToExtension["Pascal"] = TQStringList() << "pas";
#endif
_mapHighlighternameToExtension["Perl"] = TQStringList() << "perl" << "pl" << "pm";
_mapHighlighternameToExtension["PHP"] = TQStringList() << "php";
#if ( TQSCINTILLA_VERSION >= 0x020300 )
_mapHighlighternameToExtension["PostScript"] = TQStringList() << "ps" << "eps" << "pdf" << "ai" << "fh";
_mapHighlighternameToExtension["Perl"] = TQStringList() << "perl" << "pl" << "pm";
_mapHighlighternameToExtension["PHP"] = TQStringList() << "php";
#if (TQSCINTILLA_VERSION >= 0x020300)
_mapHighlighternameToExtension["PostScript"] = TQStringList() << "ps" << "eps" << "pdf" << "ai" <<
"fh";
#endif
_mapHighlighternameToExtension["POV"] = TQStringList() << "pov";
_mapHighlighternameToExtension["Ini"] = TQStringList() << "ini";
_mapHighlighternameToExtension["Python"] = TQStringList() << "py";
_mapHighlighternameToExtension["Ruby"] = TQStringList() << "rub" << "rb";
#if ( TQSCINTILLA_VERSION >= 0x020400 )
_mapHighlighternameToExtension["Spice"] = TQStringList() << "cir";
_mapHighlighternameToExtension["POV"] = TQStringList() << "pov";
_mapHighlighternameToExtension["Ini"] = TQStringList() << "ini";
_mapHighlighternameToExtension["Python"] = TQStringList() << "py";
_mapHighlighternameToExtension["Ruby"] = TQStringList() << "rub" << "rb";
#if (TQSCINTILLA_VERSION >= 0x020400)
_mapHighlighternameToExtension["Spice"] = TQStringList() << "cir";
#endif
_mapHighlighternameToExtension["SQL"] = TQStringList() << "sql";
#if ( TQSCINTILLA_VERSION >= 0x020300 )
_mapHighlighternameToExtension["TCL"] = TQStringList() << "tcl";
_mapHighlighternameToExtension["SQL"] = TQStringList() << "sql";
#if (TQSCINTILLA_VERSION >= 0x020300)
_mapHighlighternameToExtension["TCL"] = TQStringList() << "tcl";
#endif
_mapHighlighternameToExtension["TeX"] = TQStringList() << "tex";
#if ( TQSCINTILLA_VERSION >= 0x020400 )
_mapHighlighternameToExtension["Verilog"] = TQStringList() << "v" << "vh";
_mapHighlighternameToExtension["TeX"] = TQStringList() << "tex";
#if (TQSCINTILLA_VERSION >= 0x020400)
_mapHighlighternameToExtension["Verilog"] = TQStringList() << "v" << "vh";
#endif
_mapHighlighternameToExtension["VHDL"] = TQStringList() << "vhdl";
_mapHighlighternameToExtension["XML"] = TQStringList() << "xml";
#if ( TQSCINTILLA_VERSION >= 0x020300 )
_mapHighlighternameToExtension["YAML"] = TQStringList() << "yaml";
_mapHighlighternameToExtension["VHDL"] = TQStringList() << "vhdl";
_mapHighlighternameToExtension["XML"] = TQStringList() << "xml";
#if (TQSCINTILLA_VERSION >= 0x020300)
_mapHighlighternameToExtension["YAML"] = TQStringList() << "yaml";
#endif
_lexer = NULL;
_lexer = NULL;
// This code is only for testing.
/*
foreach(TQStringList extensionList, _mapHighlighternameToExtension.values() ) {
setLexerForExtension( extensionList.at(0) );
}
*/
// This code is only for testing.
/*
foreach(TQStringList extensionList, _mapHighlighternameToExtension.values() ) {
setLexerForExtension( extensionList.at(0) );
}
*/
// Set default highlighter to C++ highlighter.
setLexerForExtension( "cpp" );
// Set default highlighter to C++ highlighter.
setLexerForExtension("cpp");
}
/*!
\brief Returns the available highlighters as TQStringList.
*/
TQStringList UiGuiHighlighter::getAvailableHighlighters() {
return _mapHighlighternameToExtension.keys();
TQStringList UiGuiHighlighter::getAvailableHighlighters()
{
return _mapHighlighternameToExtension.keys();
}
/*!
\brief This slot handles signals coming from selecting another syntax highlighter.
*/
void UiGuiHighlighter::setHighlighterByAction(TQAction* highlighterAction) {
TQString highlighterName = highlighterAction->text();
setLexerForExtension( _mapHighlighternameToExtension[highlighterName].first() );
//TODO: This is really no nice way. How do it better?
// Need to do this "text update" to update the syntax highlighting. Otherwise highlighting is wrong.
int scrollPos = _qsciEditorParent->verticalScrollBar()->value();
_qsciEditorParent->setText( _qsciEditorParent->text() );
_qsciEditorParent->verticalScrollBar()->setValue(scrollPos);
void UiGuiHighlighter::setHighlighterByAction(TQAction *highlighterAction)
{
TQString highlighterName = highlighterAction->text();
setLexerForExtension(_mapHighlighternameToExtension[highlighterName].first());
//TODO: This is really no nice way. How do it better?
// Need to do this "text update" to update the syntax highlighting. Otherwise highlighting is
// wrong.
int scrollPos = _qsciEditorParent->verticalScrollBar()->value();
_qsciEditorParent->setText(_qsciEditorParent->text());
_qsciEditorParent->verticalScrollBar()->setValue(scrollPos);
}
/*!
\brief Turns the syntax parser on.
*/
void UiGuiHighlighter::turnHighlightOn() {
_highlightningIsOn = true;
_qsciEditorParent->setLexer(_lexer);
readCurrentSettings("");
void UiGuiHighlighter::turnHighlightOn()
{
_highlightningIsOn = true;
_qsciEditorParent->setLexer(_lexer);
readCurrentSettings("");
}
/*!
\brief Turns the syntax parser off.
*/
void UiGuiHighlighter::turnHighlightOff() {
_highlightningIsOn = false;
_qsciEditorParent->setLexer();
#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
_qsciEditorParent->setFont( TQFont("Courier", 10, TQFont::Normal) );
_qsciEditorParent->setMarginsFont( TQFont("Courier", 10, TQFont::Normal) );
void UiGuiHighlighter::turnHighlightOff()
{
_highlightningIsOn = false;
_qsciEditorParent->setLexer();
#if defined (Q_OS_WIN) || defined (Q_OS_MAC)
_qsciEditorParent->setFont(TQFont("Courier", 10, TQFont::Normal));
_qsciEditorParent->setMarginsFont(TQFont("Courier", 10, TQFont::Normal));
#else
_qsciEditorParent->setFont( TQFont("Monospace", 10, TQFont::Normal) );
_qsciEditorParent->setMarginsFont( TQFont("Monospace", 10, TQFont::Normal) );
_qsciEditorParent->setFont(TQFont("Monospace", 10, TQFont::Normal));
_qsciEditorParent->setMarginsFont(TQFont("Monospace", 10, TQFont::Normal));
#endif
}
/*!
\brief Read the settings for the current lexer from the settings file.
*/
//TODO: Refactor this function so that the coding style and variable names suit better.
bool UiGuiHighlighter::readCurrentSettings( const char *prefix ) {
bool ok, flag, rc = true;
int num;
TQString key;
// Reset lists containing fonts and colors for each style
_fontForStyles.clear();
_colorForStyles.clear();
// Read the styles.
for (int i = 0; i < 128; ++i) {
// Ignore invalid styles.
if ( _lexer->description(i).isEmpty() )
continue;
key.sprintf( "%s/%s/style%d/", prefix, _lexer->language(), i );
key.replace("+", "p");
// Read the foreground color.
ok = _settings->contains(key + "color");
num = _settings->value(key + "color", 0).toInt();
if (ok)
setColor( TQColor((num >> 16) & 0xff, (num >> 8) & 0xff, num & 0xff), i );
else
rc = false;
// Read the end-of-line fill.
ok = _settings->contains(key + "eolfill");
flag = _settings->value(key + "eolfill", false).toBool();
if (ok)
_lexer->setEolFill( flag, i );
else
rc = false;
// Read the font
TQStringList fdesc;
ok = _settings->contains(key + "font");
fdesc = _settings->value(key + "font").toStringList();
if (ok && fdesc.count() == 5) {
TQFont f;
#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
f.setFamily(fdesc[0]);
//TODO: Refactor this function so that the coding style and variable names suit better.
bool UiGuiHighlighter::readCurrentSettings(const char *prefix)
{
bool ok, flag, rc = true;
int num;
TQString key;
// Reset lists containing fonts and colors for each style
_fontForStyles.clear();
_colorForStyles.clear();
// Read the styles.
for (int i = 0; i < 128; ++i)
{
// Ignore invalid styles.
if (_lexer->description(i).isEmpty())
{
continue;
}
key.sprintf("%s/%s/style%d/", prefix, _lexer->language(), i);
key.replace("+", "p");
// Read the foreground color.
ok = _settings->contains(key + "color");
num = _settings->value(key + "color", 0).toInt();
if (ok)
{
setColor(TQColor((num >> 16) & 0xff, (num >> 8) & 0xff, num & 0xff), i);
}
else
{
rc = false;
}
// Read the end-of-line fill.
ok = _settings->contains(key + "eolfill");
flag = _settings->value(key + "eolfill", false).toBool();
if (ok)
{
_lexer->setEolFill(flag, i);
}
else
{
rc = false;
}
// Read the font
TQStringList fdesc;
ok = _settings->contains(key + "font");
fdesc = _settings->value(key + "font").toStringList();
if (ok && fdesc.count() == 5)
{
TQFont f;
#if defined (Q_OS_WIN) || defined (Q_OS_MAC)
f.setFamily(fdesc[0]);
#else
if ( fdesc[0].contains("courier", TQt::CaseInsensitive) )
f.setFamily("Monospace");
else
f.setFamily(fdesc[0]);
if (fdesc[0].contains("courier", TQt::CaseInsensitive))
{
f.setFamily("Monospace");
}
else
{
f.setFamily(fdesc[0]);
}
#endif
f.setPointSize(fdesc[1].toInt());
f.setBold(fdesc[2].toInt());
f.setItalic(fdesc[3].toInt());
f.setUnderline(fdesc[4].toInt());
setFont(f, i);
}
else
rc = false;
// Read the background color.
ok = _settings->contains(key + "paper");
num = _settings->value(key + "paper", 0).toInt();
if (ok)
_lexer->setPaper( TQColor((num >> 16) & 0xff, (num >> 8) & 0xff, num & 0xff), i );
else
rc = false;
}
// Read the properties.
key.sprintf( "%s/%s/properties/", prefix, _lexer->language() );
_lexer->refreshProperties();
return rc;
f.setPointSize(fdesc[1].toInt());
f.setBold(fdesc[2].toInt());
f.setItalic(fdesc[3].toInt());
f.setUnderline(fdesc[4].toInt());
setFont(f, i);
}
else
{
rc = false;
}
// Read the background color.
ok = _settings->contains(key + "paper");
num = _settings->value(key + "paper", 0).toInt();
if (ok)
{
_lexer->setPaper(TQColor((num >> 16) & 0xff, (num >> 8) & 0xff, num & 0xff), i);
}
else
{
rc = false;
}
}
// Read the properties.
key.sprintf("%s/%s/properties/", prefix, _lexer->language());
_lexer->refreshProperties();
return rc;
}
/*!
\brief Write the settings for the current lexer to the settings file.
*/
void UiGuiHighlighter::writeCurrentSettings( const char *prefix ) {
TQString key;
// Write the styles.
for (int i = 0; i < 128; ++i) {
// Ignore invalid styles.
if ( _lexer->description(i).isEmpty() )
continue;
int num;
TQColor c;
key.sprintf( "%s/%s/style%d/", prefix, _lexer->language(), i );
key.replace("+", "p");
// Write style name
_settings->setValue( key + "", _lexer->description(i) );
// Write the foreground color.
if ( _colorForStyles.contains(i) ) {
c = _colorForStyles[i];
}
else {
c = _lexer->color(i);
}
num = (c.red() << 16) | (c.green() << 8) | c.blue();
_settings->setValue(key + "color", num);
// Write the end-of-line fill.
_settings->setValue( key + "eolfill", _lexer->eolFill(i) );
// Write the font
TQStringList fdesc;
TQString fmt("%1");
TQFont f;
if ( _fontForStyles.contains(i) ) {
f = _fontForStyles[i];
}
else {
f = _lexer->font(i);
}
fdesc += f.family();
fdesc += fmt.arg( f.pointSize() );
// The casts are for Borland.
fdesc += fmt.arg( (int)f.bold() );
fdesc += fmt.arg( (int)f.italic() );
fdesc += fmt.arg( (int)f.underline() );
_settings->setValue(key + "font", fdesc);
// Write the background color.
c = _lexer->paper(i);
num = (c.red() << 16) | (c.green() << 8) | c.blue();
_settings->setValue(key + "paper", num);
}
void UiGuiHighlighter::writeCurrentSettings(const char *prefix)
{
TQString key;
// Write the styles.
for (int i = 0; i < 128; ++i)
{
// Ignore invalid styles.
if (_lexer->description(i).isEmpty())
{
continue;
}
int num;
TQColor c;
key.sprintf("%s/%s/style%d/", prefix, _lexer->language(), i);
key.replace("+", "p");
// Write style name
_settings->setValue(key + "", _lexer->description(i));
// Write the foreground color.
if (_colorForStyles.contains(i))
{
c = _colorForStyles[i];
}
else
{
c = _lexer->color(i);
}
num = (c.red() << 16) | (c.green() << 8) | c.blue();
_settings->setValue(key + "color", num);
// Write the end-of-line fill.
_settings->setValue(key + "eolfill", _lexer->eolFill(i));
// Write the font
TQStringList fdesc;
TQString fmt("%1");
TQFont f;
if (_fontForStyles.contains(i))
{
f = _fontForStyles[i];
}
else
{
f = _lexer->font(i);
}
fdesc += f.family();
fdesc += fmt.arg(f.pointSize());
// The casts are for Borland.
fdesc += fmt.arg((int)f.bold());
fdesc += fmt.arg((int)f.italic());
fdesc += fmt.arg((int)f.underline());
_settings->setValue(key + "font", fdesc);
// Write the background color.
c = _lexer->paper(i);
num = (c.red() << 16) | (c.green() << 8) | c.blue();
_settings->setValue(key + "paper", num);
}
}
/*!
\brief Sets the \a color for the given \a style.
*/
void UiGuiHighlighter::setColor(const TQColor &color, int style) {
_colorForStyles[style] = color;
_lexer->setColor( color, style );
void UiGuiHighlighter::setColor(const TQColor &color, int style)
{
_colorForStyles[style] = color;
_lexer->setColor(color, style);
}
/*!
\brief Sets the \a font for the given \a style.
*/
void UiGuiHighlighter::setFont(const TQFont &font, int style) {
_fontForStyles[style] = font;
_lexer->setFont( font, style );
void UiGuiHighlighter::setFont(const TQFont &font, int style)
{
_fontForStyles[style] = font;
_lexer->setFont(font, style);
}
/*!
\brief Sets the to be used lexer by giving his name.
*/
void UiGuiHighlighter::setLexerByName( TQString lexerName ) {
setLexerForExtension( _mapHighlighternameToExtension[lexerName].first() );
void UiGuiHighlighter::setLexerByName(TQString lexerName)
{
setLexerForExtension(_mapHighlighternameToExtension[lexerName].first());
}
/*!
\brief Sets the proper highlighter / lexer for the given file \a extension. Returns the index of the used lexer in the list.
*/
int UiGuiHighlighter::setLexerForExtension( TQString extension ) {
int indexOfHighlighter = 0;
extension = extension.toLower();
if ( _lexer != NULL ) {
writeCurrentSettings("");
delete _lexer;
}
if ( extension == "cpp" || extension == "hpp" || extension == "c" || extension == "h" || extension == "cxx" || extension == "hxx" ) {
_lexer = new QsciLexerCPP();
}
else if ( extension == "sh" ) {
_lexer = new QsciLexerBash();
}
else if ( extension == "bat" ) {
_lexer = new QsciLexerBatch();
}
else if ( extension == "cmake" ) {
_lexer = new QsciLexerCMake();
}
else if ( extension == "cs" ) {
_lexer = new QsciLexerCSharp();
}
else if ( extension == "css" ) {
_lexer = new QsciLexerCSS();
}
else if ( extension == "d" ) {
_lexer = new QsciLexerD();
}
else if ( extension == "diff" ) {
_lexer = new QsciLexerDiff();
}
#if ( TQSCINTILLA_VERSION >= 0x020300 )
else if ( extension == "f" || extension == "for" || extension == "f90" ) {
_lexer = new QsciLexerFortran();
}
else if ( extension == "f77" ) {
_lexer = new QsciLexerFortran77();
}
int UiGuiHighlighter::setLexerForExtension(TQString extension)
{
int indexOfHighlighter = 0;
extension = extension.toLower();
if (_lexer != NULL)
{
writeCurrentSettings("");
delete _lexer;
}
if (extension == "cpp" || extension == "hpp" || extension == "c" || extension == "h" ||
extension == "cxx" || extension == "hxx")
{
_lexer = new QsciLexerCPP();
}
else if (extension == "sh")
{
_lexer = new QsciLexerBash();
}
else if (extension == "bat")
{
_lexer = new QsciLexerBatch();
}
else if (extension == "cmake")
{
_lexer = new QsciLexerCMake();
}
else if (extension == "cs")
{
_lexer = new QsciLexerCSharp();
}
else if (extension == "css")
{
_lexer = new QsciLexerCSS();
}
else if (extension == "d")
{
_lexer = new QsciLexerD();
}
else if (extension == "diff")
{
_lexer = new QsciLexerDiff();
}
#if (TQSCINTILLA_VERSION >= 0x020300)
else if (extension == "f" || extension == "for" || extension == "f90")
{
_lexer = new QsciLexerFortran();
}
else if (extension == "f77")
{
_lexer = new QsciLexerFortran77();
}
#endif
else if ( extension == "html" || extension == "htm" ) {
_lexer = new QsciLexerHTML();
}
else if ( extension == "idl" ) {
_lexer = new QsciLexerIDL();
}
else if ( extension == "java" ) {
_lexer = new QsciLexerJava();
}
else if ( extension == "js" ) {
_lexer = new QsciLexerJavaScript();
}
else if ( extension == "lua" ) {
_lexer = new QsciLexerLua();
}
else if ( extension == "makefile" ) {
_lexer = new QsciLexerMakefile();
}
#if ( TQSCINTILLA_VERSION >= 0x020300 )
else if ( extension == "pas" ) {
_lexer = new QsciLexerPascal();
}
else if (extension == "html" || extension == "htm")
{
_lexer = new QsciLexerHTML();
}
else if (extension == "idl")
{
_lexer = new QsciLexerIDL();
}
else if (extension == "java")
{
_lexer = new QsciLexerJava();
}
else if (extension == "js")
{
_lexer = new QsciLexerJavaScript();
}
else if (extension == "lua")
{
_lexer = new QsciLexerLua();
}
else if (extension == "makefile")
{
_lexer = new QsciLexerMakefile();
}
#if (TQSCINTILLA_VERSION >= 0x020300)
else if (extension == "pas")
{
_lexer = new QsciLexerPascal();
}
#endif
else if ( extension == "perl" || extension == "pl" || extension == "pm" ) {
_lexer = new QsciLexerPerl();
}
else if ( extension == "php" ) {
_lexer = new QsciLexerHTML();
}
#if ( TQSCINTILLA_VERSION >= 0x020300 )
else if ( extension == "ps" || extension == "eps" || extension == "pdf" || extension == "ai" || extension == "fh") {
_lexer = new QsciLexerPostScript();
}
else if (extension == "perl" || extension == "pl" || extension == "pm")
{
_lexer = new QsciLexerPerl();
}
else if (extension == "php")
{
_lexer = new QsciLexerHTML();
}
#if (TQSCINTILLA_VERSION >= 0x020300)
else if (extension == "ps" || extension == "eps" || extension == "pdf" || extension == "ai" ||
extension == "fh")
{
_lexer = new QsciLexerPostScript();
}
#endif
else if ( extension == "pov" ) {
_lexer = new QsciLexerPOV();
}
else if ( extension == "ini" ) {
_lexer = new QsciLexerProperties();
}
else if ( extension == "py" ) {
_lexer = new QsciLexerPython();
}
else if ( extension == "rub" || extension == "rb" ) {
_lexer = new QsciLexerRuby();
}
#if ( TQSCINTILLA_VERSION >= 0x020400 )
else if ( extension == "spice?" ) {
_lexer = new QsciLexerSpice();
}
else if (extension == "pov")
{
_lexer = new QsciLexerPOV();
}
else if (extension == "ini")
{
_lexer = new QsciLexerProperties();
}
else if (extension == "py")
{
_lexer = new QsciLexerPython();
}
else if (extension == "rub" || extension == "rb")
{
_lexer = new QsciLexerRuby();
}
#if (TQSCINTILLA_VERSION >= 0x020400)
else if (extension == "spice?")
{
_lexer = new QsciLexerSpice();
}
#endif
else if ( extension == "sql" ) {
_lexer = new QsciLexerSQL();
}
#if ( TQSCINTILLA_VERSION >= 0x020300 )
else if ( extension == "tcl" ) {
_lexer = new QsciLexerTCL();
}
else if (extension == "sql")
{
_lexer = new QsciLexerSQL();
}
#if (TQSCINTILLA_VERSION >= 0x020300)
else if (extension == "tcl")
{
_lexer = new QsciLexerTCL();
}
#endif
else if ( extension == "tex" ) {
_lexer = new QsciLexerTeX();
}
#if ( TQSCINTILLA_VERSION >= 0x020400 )
else if ( extension == "vlog?" ) {
_lexer = new QsciLexerVerilog();
}
else if (extension == "tex")
{
_lexer = new QsciLexerTeX();
}
#if (TQSCINTILLA_VERSION >= 0x020400)
else if (extension == "vlog?")
{
_lexer = new QsciLexerVerilog();
}
#endif
else if ( extension == "vhdl" ) {
_lexer = new QsciLexerVHDL();
}
else if ( extension == "xml" ) {
#if ( TQSCINTILLA_VERSION >= 0x020300 )
_lexer = new QsciLexerXML();
else if (extension == "vhdl")
{
_lexer = new QsciLexerVHDL();
}
else if (extension == "xml")
{
#if (TQSCINTILLA_VERSION >= 0x020300)
_lexer = new QsciLexerXML();
#else
_lexer = new QsciLexerHTML();
_lexer = new QsciLexerHTML();
#endif
}
#if ( TQSCINTILLA_VERSION >= 0x020300 )
else if ( extension == "yaml" ) {
_lexer = new QsciLexerYAML();
}
}
#if (TQSCINTILLA_VERSION >= 0x020300)
else if (extension == "yaml")
{
_lexer = new QsciLexerYAML();
}
#endif
else {
_lexer = new QsciLexerCPP();
extension = "cpp";
}
// Find the index of the selected _lexer.
indexOfHighlighter = 0;
while ( !_mapHighlighternameToExtension.values().at(indexOfHighlighter).contains(extension) ) {
indexOfHighlighter++;
}
// Set the _lexer for the TQScintilla widget.
if ( _highlightningIsOn ) {
_qsciEditorParent->setLexer(_lexer);
}
// Read the _settings for the _lexer properties from file.
readCurrentSettings("");
return indexOfHighlighter;
else
{
_lexer = new QsciLexerCPP();
extension = "cpp";
}
// Find the index of the selected _lexer.
indexOfHighlighter = 0;
while (!_mapHighlighternameToExtension.values().at(indexOfHighlighter).contains(extension))
{
indexOfHighlighter++;
}
// Set the _lexer for the TQScintilla widget.
if (_highlightningIsOn)
{
_qsciEditorParent->setLexer(_lexer);
}
// Read the _settings for the _lexer properties from file.
readCurrentSettings("");
return indexOfHighlighter;
}

@ -34,41 +34,42 @@ class QsciLexer;
class UiGuiHighlighter : public TQObject
{
Q_OBJECT
Q_OBJECT
public:
UiGuiHighlighter(QsciScintilla *parent);
void turnHighlightOff();
void turnHighlightOn();
public:
UiGuiHighlighter(QsciScintilla *parent);
bool readCurrentSettings(const char *prefix);
void writeCurrentSettings(const char *prefix);
TQStringList getAvailableHighlighters();
void turnHighlightOff();
void turnHighlightOn();
public slots:
//! The foreground color for style number \a style is set to \a color. If
//! \a style is -1 then the color is set for all styles.
void setColor(const TQColor &color, int style = -1);
bool readCurrentSettings(const char *prefix);
void writeCurrentSettings(const char *prefix);
TQStringList getAvailableHighlighters();
//! The font for style number \a style is set to \a font. If \a style is
//! -1 then the font is set for all styles.
void setFont(const TQFont &font, int style = -1);
public slots:
//! The foreground color for style number \a style is set to \a color. If
//! \a style is -1 then the color is set for all styles.
void setColor(const TQColor &color, int style = -1);
//! Sets the lexer that is responsible for the given \a extension.
int setLexerForExtension( TQString extension );
//! The font for style number \a style is set to \a font. If \a style is
//! -1 then the font is set for all styles.
void setFont(const TQFont &font, int style = -1);
void setLexerByName( TQString lexerName );
//! Sets the lexer that is responsible for the given \a extension.
int setLexerForExtension(TQString extension);
void setHighlighterByAction(TQAction* highlighterAction);
void setLexerByName(TQString lexerName);
private:
bool _highlightningIsOn;
QsciScintilla *_qsciEditorParent;
TQMap<int, TQFont> _fontForStyles;
TQMap<int, TQColor> _colorForStyles;
QsciLexer* _lexer;
TQSettings *_settings;
TQMap<TQString, TQStringList> _mapHighlighternameToExtension;
void setHighlighterByAction(TQAction *highlighterAction);
private:
bool _highlightningIsOn;
QsciScintilla *_qsciEditorParent;
TQMap<int, TQFont> _fontForStyles;
TQMap<int, TQColor> _colorForStyles;
QsciLexer *_lexer;
TQSettings *_settings;
TQMap<TQString, TQStringList> _mapHighlighternameToExtension;
};
#endif // UIGUIHIGHLIGHTER_H
#endif // UIGUIHIGHLIGHTER_H

@ -43,114 +43,133 @@
matter for which application the plugin/client is developed.
*/
UiGuiIndentServer::UiGuiIndentServer(void) : TQObject() {
_tcpServer = NULL;
_currentClientConnection = NULL;
_readyForHandleRequest = false;
UiGuiIndentServer::UiGuiIndentServer(void) :
TQObject()
{
_tcpServer = NULL;
_currentClientConnection = NULL;
_readyForHandleRequest = false;
}
UiGuiIndentServer::~UiGuiIndentServer(void) {
UiGuiIndentServer::~UiGuiIndentServer(void)
{
}
void UiGuiIndentServer::startServer() {
if ( _tcpServer == NULL ) {
_tcpServer = new TQTcpServer(this);
}
if ( !_tcpServer->isListening() ) {
if ( !_tcpServer->listen(TQHostAddress::Any, tquint16(84484)) ) {
TQMessageBox::critical( NULL, tr("UiGUI Server"), tr("Unable to start the server: %1.").arg(_tcpServer->errorString()) );
return;
}
}
connect( _tcpServer, SIGNAL(newConnection()), this, SLOT(handleNewConnection()) );
_readyForHandleRequest = true;
_blockSize = 0;
void UiGuiIndentServer::startServer()
{
if (_tcpServer == NULL)
{
_tcpServer = new TQTcpServer(this);
}
if (!_tcpServer->isListening())
{
if (!_tcpServer->listen(TQHostAddress::Any, tquint16(84484)))
{
TQMessageBox::critical(NULL, tr("UiGUI Server"),
tr("Unable to start the server: %1.").arg(_tcpServer->errorString()));
return;
}
}
connect(_tcpServer, SIGNAL(newConnection()), this, SLOT(handleNewConnection()));
_readyForHandleRequest = true;
_blockSize = 0;
}
void UiGuiIndentServer::stopServer() {
if ( _tcpServer != NULL ) {
_tcpServer->close();
delete _tcpServer;
_tcpServer = NULL;
}
_currentClientConnection = NULL;
_readyForHandleRequest = false;
void UiGuiIndentServer::stopServer()
{
if (_tcpServer != NULL)
{
_tcpServer->close();
delete _tcpServer;
_tcpServer = NULL;
}
_currentClientConnection = NULL;
_readyForHandleRequest = false;
}
void UiGuiIndentServer::handleNewConnection()
{
TQTcpSocket *clientConnection = _tcpServer->nextPendingConnection();
connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));
void UiGuiIndentServer::handleNewConnection() {
TQTcpSocket *clientConnection = _tcpServer->nextPendingConnection();
connect( clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()) );
connect( clientConnection, SIGNAL(readyRead()), this, SLOT(handleReceivedData()) );
connect(clientConnection, SIGNAL(readyRead()), this, SLOT(handleReceivedData()));
}
void UiGuiIndentServer::handleReceivedData() {
if ( !_readyForHandleRequest ) {
return;
}
_currentClientConnection = qobject_cast<TQTcpSocket*>( sender() );
TQString receivedData = "";
if ( _currentClientConnection != NULL ) {
TQDataStream in(_currentClientConnection);
in.setVersion(TQDataStream::TQt_4_0);
if ( _blockSize == 0 ) {
if ( _currentClientConnection->bytesAvailable() < (int)sizeof(tquint32) )
return;
in >> _blockSize;
}
if ( _currentClientConnection->bytesAvailable() < _blockSize )
return;
TQString receivedMessage;
in >> receivedMessage;
_blockSize = 0;
tqDebug() << "receivedMessage: " << receivedMessage;
if ( receivedMessage == "ts" ) {
sendMessage("Toll");
}
else {
sendMessage("irgendwas");
}
}
void UiGuiIndentServer::handleReceivedData()
{
if (!_readyForHandleRequest)
{
return;
}
_currentClientConnection = qobject_cast<TQTcpSocket*>(sender());
TQString receivedData = "";
if (_currentClientConnection != NULL)
{
TQDataStream in(_currentClientConnection);
in.setVersion(TQDataStream::TQt_4_0);
if (_blockSize == 0)
{
if (_currentClientConnection->bytesAvailable() < (int)sizeof(tquint32))
{
return;
}
in >> _blockSize;
}
if (_currentClientConnection->bytesAvailable() < _blockSize)
{
return;
}
TQString receivedMessage;
in >> receivedMessage;
_blockSize = 0;
tqDebug() << "receivedMessage: " << receivedMessage;
if (receivedMessage == "ts")
{
sendMessage("Toll");
}
else
{
sendMessage("irgendwas");
}
}
}
void UiGuiIndentServer::sendMessage( const TQString &message ) {
_readyForHandleRequest = false;
_dataToSend = "";
TQDataStream out(&_dataToSend, TQIODevice::WriteOnly);
out.setVersion(TQDataStream::TQt_4_0);
out << (tquint32)0;
out << message;
out.device()->seek(0);
out << (tquint32)(_dataToSend.size() - sizeof(tquint32));
connect(_currentClientConnection, SIGNAL(bytesWritten(qint64)), this, SLOT(checkIfReadyForHandleRequest()));
_currentClientConnection->write(_dataToSend);
void UiGuiIndentServer::sendMessage(const TQString &message)
{
_readyForHandleRequest = false;
_dataToSend = "";
TQDataStream out(&_dataToSend, TQIODevice::WriteOnly);
out.setVersion(TQDataStream::TQt_4_0);
out << (tquint32)0;
out << message;
out.device()->seek(0);
out << (tquint32)(_dataToSend.size() - sizeof(tquint32));
connect(_currentClientConnection, SIGNAL(bytesWritten(qint64)), this,
SLOT(checkIfReadyForHandleRequest()));
_currentClientConnection->write(_dataToSend);
}
void UiGuiIndentServer::checkIfReadyForHandleRequest() {
if ( _currentClientConnection->bytesToWrite() == 0 ) {
TQString dataToSendStr = _dataToSend.right( _dataToSend.size() - sizeof(tquint32) );
tqDebug() << "checkIfReadyForHandleRequest _dataToSend was: " << dataToSendStr;
disconnect(_currentClientConnection, SIGNAL(bytesWritten(qint64)), this, SLOT(checkIfReadyForHandleRequest()));
_readyForHandleRequest = true;
}
void UiGuiIndentServer::checkIfReadyForHandleRequest()
{
if (_currentClientConnection->bytesToWrite() == 0)
{
TQString dataToSendStr = _dataToSend.right(_dataToSend.size() - sizeof(tquint32));
tqDebug() << "checkIfReadyForHandleRequest _dataToSend was: " << dataToSendStr;
disconnect(_currentClientConnection, SIGNAL(bytesWritten(qint64)), this,
SLOT(checkIfReadyForHandleRequest()));
_readyForHandleRequest = true;
}
}

@ -28,28 +28,28 @@ class TQTcpSocket;
class UiGuiIndentServer : public TQObject
{
Q_OBJECT
public:
UiGuiIndentServer(void);
~UiGuiIndentServer(void);
public slots:
void startServer();
void stopServer();
private slots:
void handleNewConnection();
void handleReceivedData();
void sendMessage(const TQString &message);
void checkIfReadyForHandleRequest();
private:
TQTcpServer *_tcpServer;
TQByteArray _dataToSend;
bool _readyForHandleRequest;
TQTcpSocket *_currentClientConnection;
tquint32 _blockSize;
Q_OBJECT
public:
UiGuiIndentServer(void);
~UiGuiIndentServer(void);
public slots:
void startServer();
void stopServer();
private slots:
void handleNewConnection();
void handleReceivedData();
void sendMessage(const TQString &message);
void checkIfReadyForHandleRequest();
private:
TQTcpServer *_tcpServer;
TQByteArray _dataToSend;
bool _readyForHandleRequest;
TQTcpSocket *_currentClientConnection;
tquint32 _blockSize;
};
#endif // UIGUIINDENTSERVER_H

@ -43,46 +43,47 @@
/*!
\brief Init and empty all needed lists and strings.
*/
UiGuiIniFileParser::UiGuiIniFileParser(void) {
UiGuiIniFileParser::UiGuiIniFileParser(void)
{
init();
}
/*!
\brief Directly loads and parses the file with name \a iniFileName.
*/
UiGuiIniFileParser::UiGuiIniFileParser(const TQString &iniFileName) {
UiGuiIniFileParser::UiGuiIniFileParser(const TQString &iniFileName)
{
init();
_iniFileName = iniFileName;
parseIniFile();
_iniFileName = iniFileName;
parseIniFile();
}
void UiGuiIniFileParser::init() {
void UiGuiIniFileParser::init()
{
_sections.clear();
_keyValueMap.clear();
_iniFileName = "";
}
UiGuiIniFileParser::~UiGuiIniFileParser(void) {
UiGuiIniFileParser::~UiGuiIniFileParser(void)
{
}
/*!
\brief Returns the group/section names in the same order as they occurr in the ini file as TQStringList.
*/
TQStringList UiGuiIniFileParser::childGroups() {
TQStringList sectionsStringList;
TQStringList UiGuiIniFileParser::childGroups()
{
TQStringList sectionsStringList;
for( unsigned int i = 0; i < _sections.size(); i++ ) {
sectionsStringList << _sections[i];
}
for (unsigned int i = 0; i < _sections.size(); i++)
{
sectionsStringList << _sections[i];
}
return sectionsStringList;
return sectionsStringList;
}
/*!
\brief Returns the value of the defined \a keyName as TQVariant.
@ -91,61 +92,69 @@ TQStringList UiGuiIniFileParser::childGroups() {
<code>[NiceSection]</br>niceKeyName=2</code> you would have to call
value("NiceSection/niceKeyName").
*/
TQVariant UiGuiIniFileParser::value(const TQString &keyName, const TQString &defaultValue) {
return _keyValueMap.value( keyName, defaultValue );
TQVariant UiGuiIniFileParser::value(const TQString &keyName, const TQString &defaultValue)
{
return _keyValueMap.value(keyName, defaultValue);
}
/*!
\brief Parses the ini file and stores the key value pairs in the internal vectors \a keys and \a values.
*/
void UiGuiIniFileParser::parseIniFile() {
TQFile iniFile(_iniFileName);
if ( iniFile.open(TQFile::ReadOnly) ) {
// Clear the vectors holding the keys and values.
_sections.clear();
_keyValueMap.clear();
TQTextStream iniFileStream( &iniFile );
TQString line;
TQString currentSectionName = "";
TQString keyName = "";
TQString valueAsString = "";
while ( !iniFileStream.atEnd() ) {
line = iniFileStream.readLine().trimmed();
// Test if the read line is a section name and if so remeber it.
if ( line.startsWith("[") && line.endsWith("]") ) {
currentSectionName = line.remove(0, 1);
currentSectionName.chop(1);
// Store the section name.
_sections.push_back( currentSectionName );
}
// Otherwise test whether the line has a assign char
else if ( line.contains("=") ) {
int indexOfFirstAssign = line.indexOf("=");
keyName = line.left(indexOfFirstAssign);
if ( !keyName.isEmpty() ) {
valueAsString = line.remove(0, indexOfFirstAssign+1);
// Remove any existing double quotes from the value.
if ( valueAsString.startsWith("\"") && valueAsString.endsWith("\"") ) {
valueAsString = valueAsString.remove(0, 1);
valueAsString.chop(1);
}
// Prepend an eventually section name to the key name.
if ( !currentSectionName.isEmpty() ) {
keyName = currentSectionName + "/" + keyName;
}
// Store the key and value in the map.
_keyValueMap.insert(keyName, valueAsString );
}
}
}
}
void UiGuiIniFileParser::parseIniFile()
{
TQFile iniFile(_iniFileName);
if (iniFile.open(TQFile::ReadOnly))
{
// Clear the vectors holding the keys and values.
_sections.clear();
_keyValueMap.clear();
TQTextStream iniFileStream(&iniFile);
TQString line;
TQString currentSectionName = "";
TQString keyName = "";
TQString valueAsString = "";
while (!iniFileStream.atEnd())
{
line = iniFileStream.readLine().trimmed();
// Test if the read line is a section name and if so remeber it.
if (line.startsWith("[") && line.endsWith("]"))
{
currentSectionName = line.remove(0, 1);
currentSectionName.chop(1);
// Store the section name.
_sections.push_back(currentSectionName);
}
// Otherwise test whether the line has a assign char
else if (line.contains("="))
{
int indexOfFirstAssign = line.indexOf("=");
keyName = line.left(indexOfFirstAssign);
if (!keyName.isEmpty())
{
valueAsString = line.remove(0, indexOfFirstAssign + 1);
// Remove any existing double quotes from the value.
if (valueAsString.startsWith("\"") && valueAsString.endsWith("\""))
{
valueAsString = valueAsString.remove(0, 1);
valueAsString.chop(1);
}
// Prepend an eventually section name to the key name.
if (!currentSectionName.isEmpty())
{
keyName = currentSectionName + "/" + keyName;
}
// Store the key and value in the map.
_keyValueMap.insert(keyName, valueAsString);
}
}
}
}
}

@ -31,22 +31,23 @@ class TQVariant;
class UiGuiIniFileParser
{
public:
UiGuiIniFileParser(void);
UiGuiIniFileParser(const TQString &iniFileName);
~UiGuiIniFileParser(void);
TQVariant value(const TQString &keyName, const TQString &defaultValue = "");
TQStringList childGroups();
protected:
void init();
private:
void parseIniFile();
TQString _iniFileName;
std::vector<TQString> _sections;
TQMap<TQString, TQVariant> _keyValueMap;
public:
UiGuiIniFileParser(void);
UiGuiIniFileParser(const TQString &iniFileName);
~UiGuiIniFileParser(void);
TQVariant value(const TQString &keyName, const TQString &defaultValue = "");
TQStringList childGroups();
protected:
void init();
private:
void parseIniFile();
TQString _iniFileName;
std::vector<TQString> _sections;
TQMap<TQString, TQVariant> _keyValueMap;
};
#endif // UIGUIINIFILEPARSER_H

File diff suppressed because it is too large Load Diff

@ -30,54 +30,66 @@ class TQSettings;
class UiGuiSettings : public TQObject
{
Q_OBJECT
private:
UiGuiSettings();
static TQWeakPointer<UiGuiSettings> _instance;
public:
static TQSharedPointer<UiGuiSettings> getInstance();
~UiGuiSettings();
bool registerObjectProperty(TQObject *obj, const TQString &propertyName, const TQString &settingName);
bool registerObjectPropertyRecursive(TQObject *obj);
bool setObjectPropertyToSettingValue(TQObject *obj, const TQString &propertyName, const TQString &settingName);
bool setObjectPropertyToSettingValueRecursive(TQObject *obj);
bool setSettingToObjectPropertyValue(TQObject *obj, const TQString &propertyName, const TQString &settingName);
bool setSettingToObjectPropertyValueRecursive(TQObject *obj);
bool registerObjectSlot(TQObject *obj, const TQString &slotName, const TQString &settingName);
TQVariant getValueByName(TQString settingName);
TQStringList getAvailableTranslations();
public slots:
void setValueByName(const TQString &settingName, const TQVariant &value);
void unregisterObjectProperty(TQObject *obj);
void unregisterObjectSlot(TQObject *obj, const TQString &slotName = "", const TQString &settingName = "");
protected:
bool initSettings();
bool invokeMethodWithValue(TQObject *obj, TQMetaMethod mMethod, TQVariant value);
bool checkCustomPropertiesAndCallFunction(TQObject *obj, bool (UiGuiSettings::*callBackFunc)(TQObject *obj, const TQString &propertyName, const TQString &settingName));
private slots:
void handleObjectPropertyChange();
private:
void readAvailableTranslations();
//! Stores the mnemonics of the available translations.
TQStringList _availableTranslations;
//! The settings file.
TQSettings *_qsettings;
//! Maps an TQObject to a string list containing the property name and the associated setting name.
TQMap<TQObject*, TQStringList> _registeredObjectProperties;
//! Maps TQObjects to a string list containing the method name and the associated setting name.
TQMultiMap<TQObject*, TQStringList> _registeredObjectSlots;
TQString _indenterDirctoryStr;
Q_OBJECT
private:
UiGuiSettings();
static TQWeakPointer<UiGuiSettings> _instance;
public:
static TQSharedPointer<UiGuiSettings> getInstance();
~UiGuiSettings();
bool registerObjectProperty(TQObject *obj, const TQString &propertyName,
const TQString &settingName);
bool registerObjectPropertyRecursive(TQObject *obj);
bool setObjectPropertyToSettingValue(TQObject *obj, const TQString &propertyName,
const TQString &settingName);
bool setObjectPropertyToSettingValueRecursive(TQObject *obj);
bool setSettingToObjectPropertyValue(TQObject *obj, const TQString &propertyName,
const TQString &settingName);
bool setSettingToObjectPropertyValueRecursive(TQObject *obj);
bool registerObjectSlot(TQObject *obj, const TQString &slotName,
const TQString &settingName);
TQVariant getValueByName(TQString settingName);
TQStringList getAvailableTranslations();
public slots:
void setValueByName(const TQString &settingName, const TQVariant &value);
void unregisterObjectProperty(TQObject *obj);
void unregisterObjectSlot(TQObject *obj, const TQString &slotName = "",
const TQString &settingName = "");
protected:
bool initSettings();
bool invokeMethodWithValue(TQObject *obj, TQMetaMethod mMethod, TQVariant value);
bool checkCustomPropertiesAndCallFunction(TQObject * obj,
bool (UiGuiSettings::*callBackFunc)(TQObject *obj, const TQString &propertyName,
const TQString &settingName));
private slots:
void handleObjectPropertyChange();
private:
void readAvailableTranslations();
//! Stores the mnemonics of the available translations.
TQStringList _availableTranslations;
//! The settings file.
TQSettings *_qsettings;
//! Maps an TQObject to a string list containing the property name and the associated setting
// name.
TQMap<TQObject*, TQStringList> _registeredObjectProperties;
//! Maps TQObjects to a string list containing the method name and the associated setting name.
TQMultiMap<TQObject*, TQStringList> _registeredObjectSlots;
TQString _indenterDirctoryStr;
};
#endif // UIGUISETTINGS_H

@ -31,139 +31,175 @@
/*!
\brief The constructor calls the setup function for the ui created by uic.
*/
UiGuiSettingsDialog::UiGuiSettingsDialog(TQWidget* parent, TQSharedPointer<UiGuiSettings> settings) : TQDialog(parent) {
// Remember pointer to the UiGuiSettings object.
_settings = settings;
// Init the user interface created by the UIC.
_settingsDialogForm = new Ui::SettingsDialog();
_settingsDialogForm->setupUi(this);
//TODO: This call has to be removed when the properties for the highlighters can be set
// with the settings dialog.
_settingsDialogForm->groupBoxSyntaxHighlighterProperties->setToolTip( "(Will be implemented soon)" + _settingsDialogForm->groupBoxSyntaxHighlighterProperties->toolTip() );
// Connect the accepted signal to own function, to write values back to the UiGuiSettings object.
connect(this, SIGNAL(accepted()), this, SLOT(writeWidgetValuesToSettings()) );
// Init the language selection combobox.
initTranslationSelection();
UiGuiSettingsDialog::UiGuiSettingsDialog(TQWidget *parent,
TQSharedPointer<UiGuiSettings> settings) :
TQDialog(parent)
{
// Remember pointer to the UiGuiSettings object.
_settings = settings;
// Init the user interface created by the UIC.
_settingsDialogForm = new Ui::SettingsDialog();
_settingsDialogForm->setupUi(this);
//TODO: This call has to be removed when the properties for the highlighters can be set
// with the settings dialog.
_settingsDialogForm->groupBoxSyntaxHighlighterProperties->setToolTip(
"(Will be implemented soon)" +
_settingsDialogForm->groupBoxSyntaxHighlighterProperties->toolTip());
// Connect the accepted signal to own function, to write values back to the UiGuiSettings object.
connect(this, SIGNAL(accepted()), this, SLOT(writeWidgetValuesToSettings()));
// Init the language selection combobox.
initTranslationSelection();
}
/*!
\brief By calling this function the combobox for selecting the application language will
be initialized.
Also the translation itself will be reinitialized.
*/
void UiGuiSettingsDialog::initTranslationSelection() {
// First empty the combo box.
_settingsDialogForm->languageSelectionComboBox->clear();
// Now add an entry into the box for every language short.
foreach (TQString languageShort, _settings->getAvailableTranslations() ) {
// Identify the language mnemonic and set the full name.
if ( languageShort == "en" ) {
_settingsDialogForm->languageSelectionComboBox->addItem( TQIcon(TQString(":/language/language-"+languageShort+".png")), tr("English") );
}
else if ( languageShort == "fr" ) {
_settingsDialogForm->languageSelectionComboBox->addItem( TQIcon(TQString(":/language/language-"+languageShort+".png")), tr("French") );
}
else if ( languageShort == "de" ) {
_settingsDialogForm->languageSelectionComboBox->addItem( TQIcon(TQString(":/language/language-"+languageShort+".png")), tr("German") );
}
else if ( languageShort == "zh_TW" ) {
_settingsDialogForm->languageSelectionComboBox->addItem( TQIcon(TQString(":/language/language-"+languageShort+".png")), tr("Chinese (Taiwan)") );
}
else if ( languageShort == "ja" ) {
_settingsDialogForm->languageSelectionComboBox->addItem( TQIcon(TQString(":/language/language-"+languageShort+".png")), tr("Japanese") );
}
else if ( languageShort == "ru" ) {
_settingsDialogForm->languageSelectionComboBox->addItem( TQIcon(TQString(":/language/language-"+languageShort+".png")), tr("Russian") );
}
else if ( languageShort == "uk" ) {
_settingsDialogForm->languageSelectionComboBox->addItem( TQIcon(TQString(":/language/language-"+languageShort+".png")), tr("Ukrainian") );
}
else {
_settingsDialogForm->languageSelectionComboBox->addItem( tr("Unknown language mnemonic ") + languageShort );
}
}
void UiGuiSettingsDialog::initTranslationSelection()
{
// First empty the combo box.
_settingsDialogForm->languageSelectionComboBox->clear();
// Now add an entry into the box for every language short.
foreach(TQString languageShort, _settings->getAvailableTranslations())
{
// Identify the language mnemonic and set the full name.
if (languageShort == "en")
{
_settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-"
+ languageShort + ".png")), tr("English"));
}
else if (languageShort == "fr")
{
_settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-"
+ languageShort + ".png")), tr("French"));
}
else if (languageShort == "de")
{
_settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-"
+ languageShort + ".png")), tr("German"));
}
else if (languageShort == "zh_TW")
{
_settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-"
+ languageShort + ".png")), tr("Chinese (Taiwan)"));
}
else if (languageShort == "ja")
{
_settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-"
+ languageShort + ".png")), tr("Japanese"));
}
else if (languageShort == "ru")
{
_settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-"
+ languageShort + ".png")), tr("Russian"));
}
else if (languageShort == "uk")
{
_settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-"
+ languageShort + ".png")), tr("Ukrainian"));
}
else
{
_settingsDialogForm->languageSelectionComboBox->addItem(tr(
"Unknown language mnemonic ") + languageShort);
}
}
}
/*!
\brief Displays the dialog by calling the dialogs exec function.
Before it gets all the values needed from the UiGuiSettings object.
*/
int UiGuiSettingsDialog::showDialog() {
// Init all settings dialog objects with values from settings.
_settings->setObjectPropertyToSettingValueRecursive(this);
int UiGuiSettingsDialog::showDialog()
{
// Init all settings dialog objects with values from settings.
_settings->setObjectPropertyToSettingValueRecursive(this);
// Execute the dialog.
return exec();
// Execute the dialog.
return exec();
}
/*!
\brief This slot is called when the dialog box is closed by pressing the Ok button.
Writes all settings to the UiGuiSettings object.
*/
void UiGuiSettingsDialog::writeWidgetValuesToSettings() {
// Write settings dialog object values to settings.
_settings->setSettingToObjectPropertyValueRecursive(this);
void UiGuiSettingsDialog::writeWidgetValuesToSettings()
{
// Write settings dialog object values to settings.
_settings->setSettingToObjectPropertyValueRecursive(this);
}
/*!
\brief Catches language change events and retranslates all needed widgets.
*/
void UiGuiSettingsDialog::changeEvent(TQEvent *event) {
if (event->type() == TQEvent::LanguageChange) {
_settingsDialogForm->retranslateUi(this);
// If this is not explicit set here, TQt < 4.3.0 does not translate the buttons.
_settingsDialogForm->buttonBox->setStandardButtons(TQDialogButtonBox::Cancel | TQDialogButtonBox::NoButton|TQDialogButtonBox::Ok);
//TODO: This has to be removed when the properties for the highlighters can be set.
_settingsDialogForm->groupBoxSyntaxHighlighterProperties->setToolTip( "(Will be implemented soon)" + _settingsDialogForm->groupBoxSyntaxHighlighterProperties->toolTip() );
TQStringList languageShortList = _settings->getAvailableTranslations();
// Now retranslate every entry in the language selection box.
for (int i = 0; i < languageShortList.size(); i++ ) {
TQString languageShort = languageShortList.at(i);
// Identify the language mnemonic and set the full name.
if ( languageShort == "en" ) {
_settingsDialogForm->languageSelectionComboBox->setItemText( i, tr("English") );
}
else if ( languageShort == "fr" ) {
_settingsDialogForm->languageSelectionComboBox->setItemText( i, tr("French") );
}
else if ( languageShort == "de" ) {
_settingsDialogForm->languageSelectionComboBox->setItemText( i, tr("German") );
}
else if ( languageShort == "zh_TW" ) {
_settingsDialogForm->languageSelectionComboBox->setItemText( i, tr("Chinese (Taiwan)") );
}
else if ( languageShort == "ja" ) {
_settingsDialogForm->languageSelectionComboBox->setItemText( i, tr("Japanese") );
}
else if ( languageShort == "ru" ) {
_settingsDialogForm->languageSelectionComboBox->setItemText( i, tr("Russian") );
}
else if ( languageShort == "uk" ) {
_settingsDialogForm->languageSelectionComboBox->setItemText( i, tr("Ukrainian") );
}
else {
_settingsDialogForm->languageSelectionComboBox->setItemText( i, tr("Unknown language mnemonic ") + languageShort );
}
}
}
else {
TQWidget::changeEvent(event);
}
void UiGuiSettingsDialog::changeEvent(TQEvent *event)
{
if (event->type() == TQEvent::LanguageChange)
{
_settingsDialogForm->retranslateUi(this);
// If this is not explicit set here, TQt < 4.3.0 does not translate the buttons.
_settingsDialogForm->buttonBox->setStandardButtons(
TQDialogButtonBox::Cancel | TQDialogButtonBox::NoButton | TQDialogButtonBox::Ok);
//TODO: This has to be removed when the properties for the highlighters can be set.
_settingsDialogForm->groupBoxSyntaxHighlighterProperties->setToolTip(
"(Will be implemented soon)" +
_settingsDialogForm->groupBoxSyntaxHighlighterProperties->toolTip());
TQStringList languageShortList = _settings->getAvailableTranslations();
// Now retranslate every entry in the language selection box.
for (int i = 0; i < languageShortList.size(); i++)
{
TQString languageShort = languageShortList.at(i);
// Identify the language mnemonic and set the full name.
if (languageShort == "en")
{
_settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("English"));
}
else if (languageShort == "fr")
{
_settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("French"));
}
else if (languageShort == "de")
{
_settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("German"));
}
else if (languageShort == "zh_TW")
{
_settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("Chinese (Taiwan)"));
}
else if (languageShort == "ja")
{
_settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("Japanese"));
}
else if (languageShort == "ru")
{
_settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("Russian"));
}
else if (languageShort == "uk")
{
_settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("Ukrainian"));
}
else
{
_settingsDialogForm->languageSelectionComboBox->setItemText(i,
tr("Unknown language mnemonic ") + languageShort);
}
}
}
else
{
TQWidget::changeEvent(event);
}
}

@ -24,31 +24,32 @@
#include "UiGuiSettings.h"
namespace Ui {
namespace Ui
{
class SettingsDialog;
}
class UiGuiSettingsDialog : public TQDialog
{
Q_OBJECT
Q_OBJECT
public:
UiGuiSettingsDialog(TQWidget* parent, TQSharedPointer<UiGuiSettings> settings);
public:
UiGuiSettingsDialog(TQWidget *parent, TQSharedPointer<UiGuiSettings> settings);
public slots:
int showDialog();
public slots:
int showDialog();
private slots:
void writeWidgetValuesToSettings();
private slots:
void writeWidgetValuesToSettings();
private:
Ui::SettingsDialog *_settingsDialogForm;
private:
Ui::SettingsDialog *_settingsDialogForm;
void changeEvent(TQEvent *event);
void initTranslationSelection();
void changeEvent(TQEvent *event);
void initTranslationSelection();
TQSharedPointer<UiGuiSettings> _settings;
TQSharedPointer<UiGuiSettings> _settings;
};
#endif // UIGUISETTINGSDIALOG_H

@ -24,204 +24,294 @@
#include <tntqprocess.h>
#include <tntqfile.h>
UiGuiSystemInfo::UiGuiSystemInfo() {
UiGuiSystemInfo::UiGuiSystemInfo()
{
}
/*!
\brief Returns the operating system UiGUI is currently running on as one string.
The String contains name and version of the os. E.g. Linux Ubuntu 9.04.
*/
TQString UiGuiSystemInfo::getOperatingSystem() {
TQString operatingSystemString = "";
#if defined(Q_WS_WIN)
switch ( TQSysInfo::WindowsVersion ) {
case TQSysInfo::WV_32s :
operatingSystemString = "Windows 3.1 with Win 32s";
break;
case TQSysInfo::WV_95 :
operatingSystemString = "Windows 95";
break;
case TQSysInfo::WV_98 :
operatingSystemString = "Windows 98";
break;
case TQSysInfo::WV_Me :
operatingSystemString = "Windows Me";
break;
case TQSysInfo::WV_NT :
operatingSystemString = "Windows NT (operating system version 4.0)";
break;
case TQSysInfo::WV_2000 :
operatingSystemString = "Windows 2000 (operating system version 5.0)";
break;
case TQSysInfo::WV_XP :
operatingSystemString = "Windows XP (operating system version 5.1)";
break;
case TQSysInfo::WV_2003 :
operatingSystemString = "Windows Server 2003, Windows Server 2003 R2, Windows Home Server, Windows XP Professional x64 Edition (operating system version 5.2)";
break;
case TQSysInfo::WV_VISTA :
operatingSystemString = "Windows Vista, Windows Server 2008 (operating system version 6.0)";
break;
case TQSysInfo::WV_WINDOWS7 :
operatingSystemString = "Windows 7 (operating system version 6.1)";
break;
case TQSysInfo::WV_CE :
operatingSystemString = "Windows CE";
break;
case TQSysInfo::WV_CENET :
operatingSystemString = "Windows CE .NET";
break;
case TQSysInfo::WV_CE_5 :
operatingSystemString = "Windows CE 5.x";
break;
case TQSysInfo::WV_CE_6 :
operatingSystemString = "Windows CE 6.x";
break;
default :
operatingSystemString = "Unknown Windows operating system.";
break;
}
#elif defined(Q_WS_MAC)
switch ( TQSysInfo::MacintoshVersion ) {
case TQSysInfo::MV_9 :
operatingSystemString = "Mac OS 9 (unsupported)";
break;
case TQSysInfo::MV_10_0 :
operatingSystemString = "Mac OS X 10.0 Cheetah (unsupported)";
break;
case TQSysInfo::MV_10_1 :
operatingSystemString = "Mac OS X 10.1 Puma (unsupported)";
break;
case TQSysInfo::MV_10_2 :
operatingSystemString = "Mac OS X 10.2 Jaguar (unsupported)";
break;
case TQSysInfo::MV_10_3 :
operatingSystemString = "Mac OS X 10.3 Panther";
break;
case TQSysInfo::MV_10_4 :
operatingSystemString = "Mac OS X 10.4 Tiger";
break;
case TQSysInfo::MV_10_5 :
operatingSystemString = "Mac OS X 10.5 Leopard";
break;
case TQSysInfo::MV_10_6 :
operatingSystemString = "Mac OS X 10.6 Snow Leopard";
break;
case TQSysInfo::MV_Unknown :
operatingSystemString = "An unknown and currently unsupported platform";
break;
default :
operatingSystemString = "Unknown Mac operating system.";
break;
}
TQString UiGuiSystemInfo::getOperatingSystem()
{
TQString operatingSystemString = "";
#if defined (Q_WS_WIN)
switch (TQSysInfo::WindowsVersion)
{
case TQSysInfo::WV_32s:
{
operatingSystemString = "Windows 3.1 with Win 32s";
break;
}
case TQSysInfo::WV_95:
{
operatingSystemString = "Windows 95";
break;
}
case TQSysInfo::WV_98:
{
operatingSystemString = "Windows 98";
break;
}
case TQSysInfo::WV_Me:
{
operatingSystemString = "Windows Me";
break;
}
case TQSysInfo::WV_NT:
{
operatingSystemString = "Windows NT (operating system version 4.0)";
break;
}
case TQSysInfo::WV_2000:
{
operatingSystemString = "Windows 2000 (operating system version 5.0)";
break;
}
case TQSysInfo::WV_XP:
{
operatingSystemString = "Windows XP (operating system version 5.1)";
break;
}
case TQSysInfo::WV_2003:
{
operatingSystemString =
"Windows Server 2003, Windows Server 2003 R2, Windows Home Server, Windows XP Professional x64 Edition (operating system version 5.2)";
break;
}
case TQSysInfo::WV_VISTA:
{
operatingSystemString = "Windows Vista, Windows Server 2008 (operating system version 6.0)";
break;
}
case TQSysInfo::WV_WINDOWS7:
{
operatingSystemString = "Windows 7 (operating system version 6.1)";
break;
}
case TQSysInfo::WV_CE:
{
operatingSystemString = "Windows CE";
break;
}
case TQSysInfo::WV_CENET:
{
operatingSystemString = "Windows CE .NET";
break;
}
case TQSysInfo::WV_CE_5:
{
operatingSystemString = "Windows CE 5.x";
break;
}
case TQSysInfo::WV_CE_6:
{
operatingSystemString = "Windows CE 6.x";
break;
}
default:
{
operatingSystemString = "Unknown Windows operating system.";
break;
}
}
#elif defined (Q_WS_MAC)
switch (TQSysInfo::MacintoshVersion)
{
case TQSysInfo::MV_9:
{
operatingSystemString = "Mac OS 9 (unsupported)";
break;
}
case TQSysInfo::MV_10_0:
{
operatingSystemString = "Mac OS X 10.0 Cheetah (unsupported)";
break;
}
case TQSysInfo::MV_10_1:
{
operatingSystemString = "Mac OS X 10.1 Puma (unsupported)";
break;
}
case TQSysInfo::MV_10_2:
{
operatingSystemString = "Mac OS X 10.2 Jaguar (unsupported)";
break;
}
case TQSysInfo::MV_10_3:
{
operatingSystemString = "Mac OS X 10.3 Panther";
break;
}
case TQSysInfo::MV_10_4:
{
operatingSystemString = "Mac OS X 10.4 Tiger";
break;
}
case TQSysInfo::MV_10_5:
{
operatingSystemString = "Mac OS X 10.5 Leopard";
break;
}
case TQSysInfo::MV_10_6:
{
operatingSystemString = "Mac OS X 10.6 Snow Leopard";
break;
}
case TQSysInfo::MV_Unknown:
{
operatingSystemString = "An unknown and currently unsupported platform";
break;
}
default:
{
operatingSystemString = "Unknown Mac operating system.";
break;
}
}
#else
//TODO: Detect Unix, Linux etc. distro as described on http://www.novell.com/coolsolutions/feature/11251.html
operatingSystemString = "Linux";
TQProcess process;
process.start("uname -s");
bool result = process.waitForFinished(1000);
TQString os = process.readAllStandardOutput().trimmed();
process.start("uname -r");
result = process.waitForFinished(1000);
TQString rev = process.readAllStandardOutput().trimmed();
process.start("uname -m");
result = process.waitForFinished(1000);
TQString mach = process.readAllStandardOutput().trimmed();
if ( os == "SunOS" ) {
os = "Solaris";
process.start("uname -p");
result = process.waitForFinished(1000);
TQString arch = process.readAllStandardOutput().trimmed();
process.start("uname -v");
result = process.waitForFinished(1000);
TQString timestamp = process.readAllStandardOutput().trimmed();
operatingSystemString = os + " " + rev + " (" + arch + " " + timestamp + ")";
}
else if ( os == "AIX" ) {
process.start("oslevel -r");
result = process.waitForFinished(1000);
TQString oslevel = process.readAllStandardOutput().trimmed();
operatingSystemString = os + "oslevel " + oslevel;
}
else if ( os == "Linux" ) {
TQString dist;
TQString pseudoname;
TQString kernel = rev;
if ( TQFile::exists("/etc/redhat-release") ) {
dist = "RedHat";
process.start("sh -c \"cat /etc/redhat-release | sed s/.*\\(// | sed s/\\)//\"");
result = process.waitForFinished(1000);
pseudoname = process.readAllStandardOutput().trimmed();
process.start("sh -c \"cat /etc/redhat-release | sed s/.*release\\ // | sed s/\\ .*//\"");
result = process.waitForFinished(1000);
rev = process.readAllStandardOutput().trimmed();
}
else if ( TQFile::exists("/etc/SUSE-release") ) {
process.start("sh -c \"cat /etc/SUSE-release | tr '\\n' ' '| sed s/VERSION.*//\"");
result = process.waitForFinished(1000);
dist = process.readAllStandardOutput().trimmed();
process.start("sh -c \"cat /etc/SUSE-release | tr '\\n' ' ' | sed s/.*=\\ //\"");
result = process.waitForFinished(1000);
rev = process.readAllStandardOutput().trimmed();
}
else if ( TQFile::exists("/etc/mandrake-release") ) {
dist = "Mandrake";
process.start("sh -c \"cat /etc/mandrake-release | sed s/.*\\(// | sed s/\\)//\"");
result = process.waitForFinished(1000);
pseudoname = process.readAllStandardOutput().trimmed();
process.start("sh -c \"cat /etc/mandrake-release | sed s/.*release\\ // | sed s/\\ .*//\"");
result = process.waitForFinished(1000);
rev = process.readAllStandardOutput().trimmed();
}
else if ( TQFile::exists("/etc/lsb-release") ) {
dist = "Ubuntu";
TQString processCall = "sh -c \"cat /etc/lsb-release | tr '\\n' ' ' | sed s/.*DISTRIB_RELEASE=// | sed s/\\ .*//\"";
process.start( processCall );
result = process.waitForFinished(1000);
rev = process.readAllStandardOutput().trimmed();
TQString errorStr = process.readAllStandardError();
process.start("sh -c \"cat /etc/lsb-release | tr '\\n' ' ' | sed s/.*DISTRIB_CODENAME=// | sed s/\\ .*//\"");
result = process.waitForFinished(1000);
pseudoname = process.readAllStandardOutput().trimmed();
}
else if ( TQFile::exists("/etc/debian_version") ) {
dist = "Debian";
process.start("cat /etc/debian_version");
result = process.waitForFinished(1000);
dist += process.readAllStandardOutput().trimmed();
rev = "";
}
if ( TQFile::exists("/etc/UnitedLinux-release") ) {
process.start("sh -c \"cat /etc/UnitedLinux-release | tr '\\n' ' ' | sed s/VERSION.*//\"");
result = process.waitForFinished(1000);
dist += process.readAllStandardOutput().trimmed();
}
operatingSystemString = os + " " + dist + " " + rev + " (" + pseudoname + " " + kernel + " " + mach + ")";
}
//TODO: Detect Unix, Linux etc. distro as described on
// http://www.novell.com/coolsolutions/feature/11251.html
operatingSystemString = "Linux";
TQProcess process;
process.start("uname -s");
bool result = process.waitForFinished(1000);
TQString os = process.readAllStandardOutput().trimmed();
process.start("uname -r");
result = process.waitForFinished(1000);
TQString rev = process.readAllStandardOutput().trimmed();
process.start("uname -m");
result = process.waitForFinished(1000);
TQString mach = process.readAllStandardOutput().trimmed();
if (os == "SunOS")
{
os = "Solaris";
process.start("uname -p");
result = process.waitForFinished(1000);
TQString arch = process.readAllStandardOutput().trimmed();
process.start("uname -v");
result = process.waitForFinished(1000);
TQString timestamp = process.readAllStandardOutput().trimmed();
operatingSystemString = os + " " + rev + " (" + arch + " " + timestamp + ")";
}
else if (os == "AIX")
{
process.start("oslevel -r");
result = process.waitForFinished(1000);
TQString oslevel = process.readAllStandardOutput().trimmed();
operatingSystemString = os + "oslevel " + oslevel;
}
else if (os == "Linux")
{
TQString dist;
TQString pseudoname;
TQString kernel = rev;
if (TQFile::exists("/etc/redhat-release"))
{
dist = "RedHat";
process.start("sh -c \"cat /etc/redhat-release | sed s/.*\\(// | sed s/\\)//\"");
result = process.waitForFinished(1000);
pseudoname = process.readAllStandardOutput().trimmed();
process.start("sh -c \"cat /etc/redhat-release | sed s/.*release\\ // | sed s/\\ .*//\"");
result = process.waitForFinished(1000);
rev = process.readAllStandardOutput().trimmed();
}
else if (TQFile::exists("/etc/SUSE-release"))
{
process.start("sh -c \"cat /etc/SUSE-release | tr '\\n' ' '| sed s/VERSION.*//\"");
result = process.waitForFinished(1000);
dist = process.readAllStandardOutput().trimmed();
process.start("sh -c \"cat /etc/SUSE-release | tr '\\n' ' ' | sed s/.*=\\ //\"");
result = process.waitForFinished(1000);
rev = process.readAllStandardOutput().trimmed();
}
else if (TQFile::exists("/etc/mandrake-release"))
{
dist = "Mandrake";
process.start("sh -c \"cat /etc/mandrake-release | sed s/.*\\(// | sed s/\\)//\"");
result = process.waitForFinished(1000);
pseudoname = process.readAllStandardOutput().trimmed();
process.start("sh -c \"cat /etc/mandrake-release | sed s/.*release\\ // | sed s/\\ .*//\"");
result = process.waitForFinished(1000);
rev = process.readAllStandardOutput().trimmed();
}
else if (TQFile::exists("/etc/lsb-release"))
{
dist = "Ubuntu";
TQString processCall =
"sh -c \"cat /etc/lsb-release | tr '\\n' ' ' | sed s/.*DISTRIB_RELEASE=// | sed s/\\ .*//\"";
process.start(processCall);
result = process.waitForFinished(1000);
rev = process.readAllStandardOutput().trimmed();
TQString errorStr = process.readAllStandardError();
process.start(
"sh -c \"cat /etc/lsb-release | tr '\\n' ' ' | sed s/.*DISTRIB_CODENAME=// | sed s/\\ .*//\"");
result = process.waitForFinished(1000);
pseudoname = process.readAllStandardOutput().trimmed();
}
else if (TQFile::exists("/etc/debian_version"))
{
dist = "Debian";
process.start("cat /etc/debian_version");
result = process.waitForFinished(1000);
dist += process.readAllStandardOutput().trimmed();
rev = "";
}
if (TQFile::exists("/etc/UnitedLinux-release"))
{
process.start("sh -c \"cat /etc/UnitedLinux-release | tr '\\n' ' ' | sed s/VERSION.*//\"");
result = process.waitForFinished(1000);
dist += process.readAllStandardOutput().trimmed();
}
operatingSystemString = os + " " + dist + " " + rev + " (" + pseudoname + " " + kernel + " " +
mach + ")";
}
#endif
return operatingSystemString;
return operatingSystemString;
}

@ -25,11 +25,11 @@ class TQString;
class UiGuiSystemInfo
{
public:
static TQString getOperatingSystem();
public:
static TQString getOperatingSystem();
private:
UiGuiSystemInfo();
private:
UiGuiSystemInfo();
};
#endif // UIGUISYSTEMINFO_H

@ -23,39 +23,48 @@
#include <tntqstringlist.h>
#include <tqdate.h>
namespace UiGuiVersion {
/*!
\brief Returns the build date as a localized string, e.g. "9. Februar 2009". If
there was some kind of error, the returned string is empty.
*/
TQString getBuildDate() {
TQStringList monthNames;
TQString buildDateString = "";
monthNames << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun" << "Jul" << "Aug" << "Sep" << "Oct" << "Nov" << "Dez";
TQStringList buildDateStringList = TQString(__DATE__).simplified().split(' '); // __DATE__ returns eg "Feb 4 2009"
if ( buildDateStringList.count() == 3 ) {
TQDate buildDate(buildDateStringList.last().toInt(), monthNames.indexOf( buildDateStringList.first() )+1, buildDateStringList.at(1).toInt());
buildDateString = buildDate.toString("d. MMMM yyyy");
}
return buildDateString;
}
/*!
\brief Returns the revision number, that the current build is based on, as string. If
there was some kind of error, the returned string is empty.
*/
TQString getBuildRevision() {
TQString buildRevision = "";
TQStringList buildRevisionStringList = TQString(PROGRAM_REVISION).simplified().split(' ');
if ( buildRevisionStringList.count() == 3 ) {
buildRevision = buildRevisionStringList.at(1); // PROGRAM_REVISION is eg "$Revision: 907 $"
}
return buildRevision;
}
} // namespace UiGuiVersion
namespace UiGuiVersion
{
/*!
\brief Returns the build date as a localized string, e.g. "9. Februar 2009". If
there was some kind of error, the returned string is empty.
*/
TQString getBuildDate()
{
TQStringList monthNames;
TQString buildDateString = "";
monthNames << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun" << "Jul" << "Aug" << "Sep" <<
"Oct" << "Nov" << "Dez";
TQStringList buildDateStringList = TQString(__DATE__).simplified().split(' '); // __DATE__
// returns eg
// "Feb 4 2009"
if (buildDateStringList.count() == 3)
{
TQDate buildDate(buildDateStringList.last().toInt(),
monthNames.indexOf(buildDateStringList.first()) + 1,
buildDateStringList.at(1).toInt());
buildDateString = buildDate.toString("d. MMMM yyyy");
}
return buildDateString;
}
/*!
\brief Returns the revision number, that the current build is based on, as string. If
there was some kind of error, the returned string is empty.
*/
TQString getBuildRevision()
{
TQString buildRevision = "";
TQStringList buildRevisionStringList = TQString(PROGRAM_REVISION).simplified().split(' ');
if (buildRevisionStringList.count() == 3)
{
buildRevision = buildRevisionStringList.at(1); // PROGRAM_REVISION is eg "$Revision: 907 $"
}
return buildRevision;
}
} // namespace UiGuiVersion

@ -23,17 +23,16 @@
class TQString;
// Define the version number here. Update this as the last file before a release.
#define PROGRAM_VERSION 1.2.0
#define PROGRAM_VERSION_STRING "1.2.0"
#define RESOURCE_VERSION 1,2,0,0
#define PROGRAM_VERSION 1.2 .0
#define PROGRAM_VERSION_STRING "1.2.0"
#define RESOURCE_VERSION 1, 2, 0, 0
#define RESOURCE_VERSION_STRING "1,2,0,0\0"
#define PROGRAM_REVISION "$Revision: 1070 $"
namespace UiGuiVersion {
TQString getBuildDate();
TQString getBuildRevision();
#define PROGRAM_REVISION "$Revision: 1070 $"
namespace UiGuiVersion
{
TQString getBuildDate();
TQString getBuildRevision();
}
#endif // UIGUIVERSION_H
#endif // UIGUIVERSION_H

@ -44,87 +44,91 @@
/*!
\brief Initializes member variables and stores the version of UiGui and a pointer to the _settings object.
*/
UpdateCheckDialog::UpdateCheckDialog(TQSharedPointer<UiGuiSettings> settings, TQWidget *parent) : TQDialog(parent),
_manualUpdateRequested(false),
_currentNetworkReply(NULL),
_roleOfClickedButton(TQDialogButtonBox::InvalidRole)
UpdateCheckDialog::UpdateCheckDialog(TQSharedPointer<UiGuiSettings> settings, TQWidget *parent) :
TQDialog(parent), _manualUpdateRequested(false), _currentNetworkReply(NULL),
_roleOfClickedButton(TQDialogButtonBox::InvalidRole)
{
_updateCheckDialogForm = new Ui::UpdateCheckDialog();
_updateCheckDialogForm->setupUi(this);
_updateCheckDialogForm->setupUi(this);
// Create object for _networkAccessManager request and connect it with the request return handler.
_networkAccessManager = new TQNetworkAccessManager(this);
connect( _networkAccessManager, SIGNAL(finished(TQNetworkReply*)), this, SLOT(checkResultsOfFetchedPadXMLFile(TQNetworkReply*)) );
// Create object for _networkAccessManager request and connect it with the request return handler.
_networkAccessManager = new TQNetworkAccessManager(this);
connect(_networkAccessManager, SIGNAL(finished(TQNetworkReply*)), this,
SLOT(checkResultsOfFetchedPadXMLFile(TQNetworkReply*)));
// Create a timer object used for the progress bar.
_updateCheckProgressTimer = new TQTimer(this);
_updateCheckProgressTimer->setInterval(5);
connect( _updateCheckProgressTimer, SIGNAL(timeout()), this, SLOT(updateUpdateCheckProgressBar()) );
_updateCheckProgressCounter = 0;
// Create a timer object used for the progress bar.
_updateCheckProgressTimer = new TQTimer(this);
_updateCheckProgressTimer->setInterval(5);
connect(_updateCheckProgressTimer, SIGNAL(timeout()), this, SLOT(updateUpdateCheckProgressBar()));
_updateCheckProgressCounter = 0;
// Connect the dialogs buttonbox with a button click handler.
connect( _updateCheckDialogForm->buttonBox, SIGNAL(clicked(TQAbstractButton*)), this, SLOT(handleUpdateCheckDialogButtonClicked(TQAbstractButton*)) );
// Connect the dialogs buttonbox with a button click handler.
connect(_updateCheckDialogForm->buttonBox, SIGNAL(clicked(TQAbstractButton*)), this,
SLOT(handleUpdateCheckDialogButtonClicked(TQAbstractButton*)));
settings->registerObjectSlot(this, "initProxySettings()", "ProxyEnabled");
settings->registerObjectSlot(this, "initProxySettings()", "ProxyHostName");
settings->registerObjectSlot(this, "initProxySettings()", "ProxyPort");
settings->registerObjectSlot(this, "initProxySettings()", "ProxyUserName");
settings->registerObjectSlot(this, "initProxySettings()", "ProxyPassword");
settings->registerObjectSlot(this, "initProxySettings()", "ProxyEnabled");
settings->registerObjectSlot(this, "initProxySettings()", "ProxyHostName");
settings->registerObjectSlot(this, "initProxySettings()", "ProxyPort");
settings->registerObjectSlot(this, "initProxySettings()", "ProxyUserName");
settings->registerObjectSlot(this, "initProxySettings()", "ProxyPassword");
_settings = settings;
_settings = settings;
initProxySettings();
// This dialog is always modal.
setModal(true);
// This dialog is always modal.
setModal(true);
}
/*!
\brief On destroy cancels any currently running network request.
*/
UpdateCheckDialog::~UpdateCheckDialog() {
disconnect( _networkAccessManager, SIGNAL(finished(TQNetworkReply*)), this, SLOT(checkResultsOfFetchedPadXMLFile(TQNetworkReply*)) );
if (_currentNetworkReply != NULL)
_currentNetworkReply->abort();
UpdateCheckDialog::~UpdateCheckDialog()
{
disconnect(_networkAccessManager, SIGNAL(finished(TQNetworkReply*)), this,
SLOT(checkResultsOfFetchedPadXMLFile(TQNetworkReply*)));
if (_currentNetworkReply != NULL)
{
_currentNetworkReply->abort();
}
}
/*!
\brief This slot should be called, if an update check is manually invoked.
In difference to the automatic update check, during manual update check request
a modal progress indicator dialog will be shown.
*/
void UpdateCheckDialog::checkForUpdateAndShowDialog() {
_manualUpdateRequested = true;
getPadXMLFile();
showCheckingForUpdateDialog();
void UpdateCheckDialog::checkForUpdateAndShowDialog()
{
_manualUpdateRequested = true;
getPadXMLFile();
showCheckingForUpdateDialog();
}
/*!
\brief This slot should be called, if an update check is automatically invoked.
An automatic invoked update check should run in background, so the user
gets not interrupted by a dialog box.
*/
void UpdateCheckDialog::checkForUpdate() {
_manualUpdateRequested = false;
getPadXMLFile();
void UpdateCheckDialog::checkForUpdate()
{
_manualUpdateRequested = false;
getPadXMLFile();
}
/*!
\brief This function tries to download the UniversalIndentGui pad file from the SourceForge server.
*/
void UpdateCheckDialog::getPadXMLFile() {
//_networkAccessManager->setHost("universalindent.sourceforge.net");
//_networkAccessManager->get("/universalindentgui_pad.xml");
_currentNetworkReply = _networkAccessManager->get(TQNetworkRequest(TQUrl("http://universalindent.sourceforge.net/universalindentgui_pad.xml")));
void UpdateCheckDialog::getPadXMLFile()
{
//_networkAccessManager->setHost("universalindent.sourceforge.net");
//_networkAccessManager->get("/universalindentgui_pad.xml");
_currentNetworkReply = _networkAccessManager->get(TQNetworkRequest(TQUrl(
"http://universalindent.sourceforge.net/universalindentgui_pad.xml")));
}
/*!
\brief This slot is called after the update check has returned, either by successfully
retrieving the pad file, or on any kind of network error.
@ -133,59 +137,74 @@ void UpdateCheckDialog::getPadXMLFile() {
download page if a newer version exists. In case of an error during update
check, a message box with the error will be displayed.
*/
void UpdateCheckDialog::checkResultsOfFetchedPadXMLFile(TQNetworkReply *networkReply) {
Q_ASSERT(_currentNetworkReply == networkReply);
// Stop the progress bar timer.
_updateCheckProgressTimer->stop();
if ( networkReply->error() == TQNetworkReply::NoError ) {
// Try to find the version string.
TQString returnedString = networkReply->readAll();
int leftPosition = returnedString.indexOf("<Program_Version>");
int rightPosition = returnedString.indexOf("</Program_Version>");
// If the version string could be found in the returned string, show an update dialog and set last update check date.
if ( leftPosition != -1 && rightPosition != -1 ) {
// Get the pure version string from returned string.
returnedString = returnedString.mid( leftPosition+17, rightPosition-(leftPosition+17) );
// Create integer values from the version strings.
int versionOnServerInt = convertVersionStringToNumber( returnedString );
int currentVersionInt = convertVersionStringToNumber( PROGRAM_VERSION_STRING );
// Only show update dialog, if the current version number is lower than the one received from the server.
if ( versionOnServerInt > currentVersionInt && currentVersionInt >= 0 && versionOnServerInt >= 0 ) {
// Show message box whether to download the new version.
showNewVersionAvailableDialog(returnedString);
// If yes clicked, open the download url in the default browser.
if ( _roleOfClickedButton == TQDialogButtonBox::YesRole ) {
TQDesktopServices::openUrl( TQUrl("_networkAccessManager://sourceforge.net/project/showfiles.php?group_id=167482") );
}
}
else if ( _manualUpdateRequested ) {
showNoNewVersionAvailableDialog();
}
// Set last update check date.
_settings->setValueByName("LastUpdateCheck", TQDate::currentDate());
}
// In the returned string, the version string could not be found.
else {
TQMessageBox::warning(this, tr("Update check error"), tr("There was an error while trying to check for an update! The retrieved file did not contain expected content.") );
}
}
// If there was some error while trying to retrieve the update info from server and not cancel was pressed.
else if ( _roleOfClickedButton != TQDialogButtonBox::RejectRole ) {
TQMessageBox::warning(this, tr("Update check error"), tr("There was an error while trying to check for an update! Error was : %1").arg(networkReply->errorString()) );
void UpdateCheckDialog::checkResultsOfFetchedPadXMLFile(TQNetworkReply *networkReply)
{
Q_ASSERT(_currentNetworkReply == networkReply);
// Stop the progress bar timer.
_updateCheckProgressTimer->stop();
if (networkReply->error() == TQNetworkReply::NoError)
{
// Try to find the version string.
TQString returnedString = networkReply->readAll();
int leftPosition = returnedString.indexOf("<Program_Version>");
int rightPosition = returnedString.indexOf("</Program_Version>");
// If the version string could be found in the returned string, show an update dialog and set
// last update check date.
if (leftPosition != -1 && rightPosition != -1)
{
// Get the pure version string from returned string.
returnedString = returnedString.mid(leftPosition + 17, rightPosition - (leftPosition + 17));
// Create integer values from the version strings.
int versionOnServerInt = convertVersionStringToNumber(returnedString);
int currentVersionInt = convertVersionStringToNumber(PROGRAM_VERSION_STRING);
// Only show update dialog, if the current version number is lower than the one received from
// the server.
if (versionOnServerInt > currentVersionInt && currentVersionInt >= 0 &&
versionOnServerInt >= 0)
{
// Show message box whether to download the new version.
showNewVersionAvailableDialog(returnedString);
// If yes clicked, open the download url in the default browser.
if (_roleOfClickedButton == TQDialogButtonBox::YesRole)
{
TQDesktopServices::openUrl(TQUrl(
"_networkAccessManager://sourceforge.net/project/showfiles.php?group_id=167482"));
}
}
else if (_manualUpdateRequested)
{
showNoNewVersionAvailableDialog();
}
// Set last update check date.
_settings->setValueByName("LastUpdateCheck", TQDate::currentDate());
}
// In the returned string, the version string could not be found.
else
{
TQMessageBox::warning(this, tr("Update check error"), tr(
"There was an error while trying to check for an update! The retrieved file did not contain expected content."));
}
}
// If there was some error while trying to retrieve the update info from server and not cancel was
// pressed.
else if (_roleOfClickedButton != TQDialogButtonBox::RejectRole)
{
TQMessageBox::warning(this, tr("Update check error"),
tr("There was an error while trying to check for an update! Error was : %1").arg(
networkReply->errorString()));
hide();
}
_manualUpdateRequested = false;
networkReply->deleteLater();
_currentNetworkReply = NULL;
}
_manualUpdateRequested = false;
networkReply->deleteLater();
_currentNetworkReply = NULL;
}
/*!
\brief Displays the progress bar during update check.
@ -193,45 +212,49 @@ void UpdateCheckDialog::checkResultsOfFetchedPadXMLFile(TQNetworkReply *networkR
updated the progress bar. The user can press a cancel button to
stop the update check.
*/
void UpdateCheckDialog::showCheckingForUpdateDialog() {
// Reset the progress bar.
_updateCheckProgressCounter = 0;
_updateCheckDialogForm->progressBar->setValue(_updateCheckProgressCounter);
_updateCheckDialogForm->progressBar->setInvertedAppearance( false );
_updateCheckProgressTimer->start();
_updateCheckDialogForm->progressBar->show();
setWindowTitle( tr("Checking for update...") );
_updateCheckDialogForm->label->setText( tr("Checking whether a newer version is available") );
_updateCheckDialogForm->buttonBox->setStandardButtons(TQDialogButtonBox::Cancel);
show();
void UpdateCheckDialog::showCheckingForUpdateDialog()
{
// Reset the progress bar.
_updateCheckProgressCounter = 0;
_updateCheckDialogForm->progressBar->setValue(_updateCheckProgressCounter);
_updateCheckDialogForm->progressBar->setInvertedAppearance(false);
_updateCheckProgressTimer->start();
_updateCheckDialogForm->progressBar->show();
setWindowTitle(tr("Checking for update..."));
_updateCheckDialogForm->label->setText(tr("Checking whether a newer version is available"));
_updateCheckDialogForm->buttonBox->setStandardButtons(TQDialogButtonBox::Cancel);
show();
}
/*!
\brief Displays the dialog with info about the new available version.
*/
void UpdateCheckDialog::showNewVersionAvailableDialog(TQString newVersion) {
_updateCheckDialogForm->progressBar->hide();
setWindowTitle( tr("Update available") );
_updateCheckDialogForm->label->setText( tr("A newer version of UniversalIndentGUI is available.\nYour version is %1. New version is %2.\nDo you want to go to the download website?").arg(PROGRAM_VERSION_STRING).arg(newVersion) );
_updateCheckDialogForm->buttonBox->setStandardButtons(TQDialogButtonBox::No|TQDialogButtonBox::NoButton|TQDialogButtonBox::Yes);
exec();
void UpdateCheckDialog::showNewVersionAvailableDialog(TQString newVersion)
{
_updateCheckDialogForm->progressBar->hide();
setWindowTitle(tr("Update available"));
_updateCheckDialogForm->label->setText(tr(
"A newer version of UniversalIndentGUI is available.\nYour version is %1. New version is %2.\nDo you want to go to the download website?").arg(
PROGRAM_VERSION_STRING).arg(newVersion));
_updateCheckDialogForm->buttonBox->setStandardButtons(
TQDialogButtonBox::No | TQDialogButtonBox::NoButton | TQDialogButtonBox::Yes);
exec();
}
/*!
\brief Displays the dialog, that no new version is available.
*/
void UpdateCheckDialog::showNoNewVersionAvailableDialog() {
_updateCheckDialogForm->progressBar->hide();
setWindowTitle( tr("No new update available") );
_updateCheckDialogForm->label->setText( tr("You already have the latest version of UniversalIndentGUI.") );
_updateCheckDialogForm->buttonBox->setStandardButtons(TQDialogButtonBox::Ok);
exec();
void UpdateCheckDialog::showNoNewVersionAvailableDialog()
{
_updateCheckDialogForm->progressBar->hide();
setWindowTitle(tr("No new update available"));
_updateCheckDialogForm->label->setText(tr(
"You already have the latest version of UniversalIndentGUI."));
_updateCheckDialogForm->buttonBox->setStandardButtons(TQDialogButtonBox::Ok);
exec();
}
/*!
\brief This slot is called, when a button in the dialog is clicked.
@ -241,42 +264,47 @@ void UpdateCheckDialog::showNoNewVersionAvailableDialog() {
In any case if a button is clicked, the dialog box will be closed.
*/
void UpdateCheckDialog::handleUpdateCheckDialogButtonClicked(TQAbstractButton *clickedButton) {
_roleOfClickedButton = _updateCheckDialogForm->buttonBox->buttonRole(clickedButton);
void UpdateCheckDialog::handleUpdateCheckDialogButtonClicked(TQAbstractButton *clickedButton)
{
_roleOfClickedButton = _updateCheckDialogForm->buttonBox->buttonRole(clickedButton);
if ( _roleOfClickedButton == TQDialogButtonBox::RejectRole ) {
// Abort the _networkAccessManager request.
_currentNetworkReply->abort();
// Stop the progress bar timer.
_updateCheckProgressTimer->stop();
}
if (_roleOfClickedButton == TQDialogButtonBox::RejectRole)
{
// Abort the _networkAccessManager request.
_currentNetworkReply->abort();
// Stop the progress bar timer.
_updateCheckProgressTimer->stop();
}
accept();
accept();
}
/*!
\brief This slot is responsible for the animation of the update check progress bar.
*/
void UpdateCheckDialog::updateUpdateCheckProgressBar() {
// Depending on the progress bar direction, decrease or increase the progressbar value.
if ( _updateCheckDialogForm->progressBar->invertedAppearance() ) {
_updateCheckProgressCounter--;
}
else {
_updateCheckProgressCounter++;
}
// If the progress bar reaches 0 or 100 as value, swap the animation direction.
if ( _updateCheckProgressCounter == 0 || _updateCheckProgressCounter == 100 ) {
_updateCheckDialogForm->progressBar->setInvertedAppearance( !_updateCheckDialogForm->progressBar->invertedAppearance() );
}
// Update the progress bar value.
_updateCheckDialogForm->progressBar->setValue(_updateCheckProgressCounter);
void UpdateCheckDialog::updateUpdateCheckProgressBar()
{
// Depending on the progress bar direction, decrease or increase the progressbar value.
if (_updateCheckDialogForm->progressBar->invertedAppearance())
{
_updateCheckProgressCounter--;
}
else
{
_updateCheckProgressCounter++;
}
// If the progress bar reaches 0 or 100 as value, swap the animation direction.
if (_updateCheckProgressCounter == 0 || _updateCheckProgressCounter == 100)
{
_updateCheckDialogForm->progressBar->setInvertedAppearance(
!_updateCheckDialogForm->progressBar->invertedAppearance());
}
// Update the progress bar value.
_updateCheckDialogForm->progressBar->setValue(_updateCheckProgressCounter);
}
/*!
\brief Converts the as string given version \a versionString to an integer number.
@ -287,36 +315,42 @@ void UpdateCheckDialog::updateUpdateCheckProgressBar() {
Thus for example 12.5.170 will result in 12005170.
*/
int UpdateCheckDialog::convertVersionStringToNumber(TQString versionString) {
int versionInteger = 0;
int pos = 0;
TQRegExp regEx("\\d{1,3}.\\d{1,3}.\\d{1,3}");
TQRegExpValidator validator(regEx, NULL);
if ( validator.validate(versionString, pos) == TQValidator::Acceptable ) {
TQStringList versionNumberStringList = versionString.split(".");
versionInteger = versionNumberStringList.at(0).toInt() * 1000000;
versionInteger += versionNumberStringList.at(1).toInt() * 1000;
versionInteger += versionNumberStringList.at(2).toInt();
}
else {
versionInteger = -1;
}
return versionInteger;
int UpdateCheckDialog::convertVersionStringToNumber(TQString versionString)
{
int versionInteger = 0;
int pos = 0;
TQRegExp regEx("\\d{1,3}.\\d{1,3}.\\d{1,3}");
TQRegExpValidator validator(regEx, NULL);
if (validator.validate(versionString, pos) == TQValidator::Acceptable)
{
TQStringList versionNumberStringList = versionString.split(".");
versionInteger = versionNumberStringList.at(0).toInt() * 1000000;
versionInteger += versionNumberStringList.at(1).toInt() * 1000;
versionInteger += versionNumberStringList.at(2).toInt();
}
else
{
versionInteger = -1;
}
return versionInteger;
}
void UpdateCheckDialog::initProxySettings()
{
if ( _settings->getValueByName("ProxyEnabled") == true ) {
if (_settings->getValueByName("ProxyEnabled") == true)
{
TQString proxyHostName = _settings->getValueByName("ProxyHostName").toString();
int proxyPort = _settings->getValueByName("ProxyPort").toInt();
int proxyPort = _settings->getValueByName("ProxyPort").toInt();
TQString proxyUserName = _settings->getValueByName("ProxyUserName").toString();
TQString proxyPassword = _settings->getValueByName("ProxyPassword").toString();
_networkAccessManager->setProxy(TQNetworkProxy(TQNetworkProxy::Socks5Proxy, proxyHostName, proxyPort, proxyUserName, proxyPassword));
}
else {
_networkAccessManager->setProxy(TQNetworkProxy(TQNetworkProxy::Socks5Proxy, proxyHostName,
proxyPort, proxyUserName, proxyPassword));
}
else
{
_networkAccessManager->setProxy(TQNetworkProxy());
}
}
}

@ -24,7 +24,8 @@
#include <tqdialogbuttonbox.h>
class UiGuiSettings;
namespace Ui {
namespace Ui
{
class UpdateCheckDialog;
}
@ -36,38 +37,38 @@ class TQNetworkReply;
class UpdateCheckDialog : public TQDialog
{
Q_OBJECT
Q_OBJECT
public:
UpdateCheckDialog(TQSharedPointer<UiGuiSettings> settings, TQWidget *parent = NULL);
~UpdateCheckDialog();
public:
UpdateCheckDialog(TQSharedPointer<UiGuiSettings> settings, TQWidget *parent = NULL);
~UpdateCheckDialog();
public slots:
void checkForUpdateAndShowDialog();
void checkForUpdate();
public slots:
void checkForUpdateAndShowDialog();
void checkForUpdate();
private slots:
void checkResultsOfFetchedPadXMLFile(TQNetworkReply *networkReply);
void handleUpdateCheckDialogButtonClicked(TQAbstractButton *clickedButton);
void updateUpdateCheckProgressBar();
void initProxySettings();
private slots:
void checkResultsOfFetchedPadXMLFile(TQNetworkReply *networkReply);
void handleUpdateCheckDialogButtonClicked(TQAbstractButton *clickedButton);
void updateUpdateCheckProgressBar();
void initProxySettings();
private:
Ui::UpdateCheckDialog *_updateCheckDialogForm;
private:
Ui::UpdateCheckDialog *_updateCheckDialogForm;
void getPadXMLFile();
void showCheckingForUpdateDialog();
void showNewVersionAvailableDialog(TQString newVersion);
void showNoNewVersionAvailableDialog();
int convertVersionStringToNumber(TQString versionString);
void getPadXMLFile();
void showCheckingForUpdateDialog();
void showNewVersionAvailableDialog(TQString newVersion);
void showNoNewVersionAvailableDialog();
int convertVersionStringToNumber(TQString versionString);
TQSharedPointer<UiGuiSettings> _settings;
bool _manualUpdateRequested;
TQNetworkAccessManager *_networkAccessManager;
TQNetworkReply *_currentNetworkReply;
TQDialogButtonBox::ButtonRole _roleOfClickedButton;
TQTimer *_updateCheckProgressTimer;
int _updateCheckProgressCounter;
TQSharedPointer<UiGuiSettings> _settings;
bool _manualUpdateRequested;
TQNetworkAccessManager *_networkAccessManager;
TQNetworkReply *_currentNetworkReply;
TQDialogButtonBox::ButtonRole _roleOfClickedButton;
TQTimer *_updateCheckProgressTimer;
int _updateCheckProgressCounter;
};
#endif // UPDATECHECKDIALOG_H

@ -35,7 +35,7 @@
using namespace tschweitzer;
using namespace tschweitzer::debugging;
TSLogger* TSLogger::_instance = NULL;
TSLogger*TSLogger::_instance = NULL;
/*!
\class TSLogger
@ -52,200 +52,250 @@ TSLogger* TSLogger::_instance = NULL;
/*!
\brief Returns the only existing instance of TSLogger. If the instance doesn't exist, it will be created.
*/
TSLogger* TSLogger::getInstance(int verboseLevel) {
if ( _instance == NULL )
_instance = new TSLogger(verboseLevel);
return _instance;
TSLogger* TSLogger::getInstance(int verboseLevel)
{
if (_instance == NULL)
{
_instance = new TSLogger(verboseLevel);
}
return _instance;
}
/*!
\brief Returns the only existing instance of TSLogger. If the instance doesn't exist, it will be created.
*/
TSLogger* TSLogger::getInstance() {
TSLogger* TSLogger::getInstance()
{
#ifdef _DEBUG
return TSLogger::getInstance(TQtDebugMsg);
return TSLogger::getInstance(TQtDebugMsg);
#else
return TSLogger::getInstance(TQtWarningMsg);
return TSLogger::getInstance(TQtWarningMsg);
#endif
}
/*!
\brief Initializes the dialog and sets the path to the log file in the systems temporary directory.
Sets the default verbose level to warning level.
*/
TSLogger::TSLogger(int verboseLevel) : TQDialog() {
TSLogger::TSLogger(int verboseLevel) :
TQDialog()
{
_TSLoggerDialogForm = new Ui::TSLoggerDialog();
_TSLoggerDialogForm->setupUi(this);
_TSLoggerDialogForm->setupUi(this);
#ifdef _DEBUG
_verboseLevel = TQtDebugMsg;
_verboseLevel = TQtDebugMsg;
#else
_verboseLevel = TQtMsgType(verboseLevel);
_verboseLevel = TQtMsgType(verboseLevel);
#endif
_logFileInitState = NOTINITIALZED;
_logFileInitState = NOTINITIALZED;
connect( _TSLoggerDialogForm->openLogFileFolderToolButton, SIGNAL(clicked()), this, SLOT(openLogFileFolder()) );
connect(_TSLoggerDialogForm->openLogFileFolderToolButton, SIGNAL(clicked()), this,
SLOT(openLogFileFolder()));
// Make the main application not to wait for the logging window to close.
setAttribute(TQt::WA_QuitOnClose, false);
// Make the main application not to wait for the logging window to close.
setAttribute(TQt::WA_QuitOnClose, false);
}
/*!
\brief Logs all incoming messages \a msg to the dialogs text edit and to the log file.
Only messages whos \a type have a higher priority than the set verbose level are logged.
*/
void TSLogger::messageHandler(TQtMsgType type, const char *msg) {
if ( _instance == NULL )
_instance = TSLogger::getInstance();
/*
TQMessageBox messageBox;
TQString messageBoxText = TQString::fromUtf8( msg );
messageBox.setText( messageBoxText );
messageBox.setWindowModality( TQt::ApplicationModal );
messageBox.exec();
*/
// Only log messages that have a higher or equal priority than set with the verbose level.
if ( type < _instance->_verboseLevel )
return;
// Init log message with prepended date and time.
TQString message = TQDateTime::currentDateTime().toString();
// Depending on the TQtMsgType prepend a different colored Debug, Warning, Critical or Fatal.
switch (type) {
case TQtDebugMsg :
message += " <span style=\"font-weight:bold; color:black;\">Debug:</span> ";
break;
case TQtWarningMsg :
message += " <span style=\"font-weight:bold; color:gold;\">Warning:</span> ";
break;
case TQtCriticalMsg :
message += "<span style=\"font-weight:bold; color:red;\">Critical:</span> ";
break;
case TQtFatalMsg :
message += " <span style=\"font-weight:bold; color:#D60000;\">Fatal:</span> ";
// This one is no TQt message type, but can be used to send info messages to the log
// by calling TSLogger::messageHandler() directly.
case TSLoggerInfoMsg :
message += " <span style=\"font-weight:bold; color:darkgray;\">Info:</span> ";
break;
}
// Append the to UTF-8 back converted message parameter.
message += TQString::fromUtf8( msg ) + "<br/>\n";
// Write the message to the log windows text edit.
_instance->_TSLoggerDialogForm->logTextEdit->append( message );
// Write/append the log message to the log file.
_instance->writeToLogFile( message );
// In case of a fatal error abort the application.
if ( type == TQtFatalMsg )
abort();
void TSLogger::messageHandler(TQtMsgType type, const char *msg)
{
if (_instance == NULL)
{
_instance = TSLogger::getInstance();
}
/*
TQMessageBox messageBox;
TQString messageBoxText = TQString::fromUtf8( msg );
messageBox.setText( messageBoxText );
messageBox.setWindowModality( TQt::ApplicationModal );
messageBox.exec();
*/
// Only log messages that have a higher or equal priority than set with the verbose level.
if (type < _instance->_verboseLevel)
{
return;
}
// Init log message with prepended date and time.
TQString message = TQDateTime::currentDateTime().toString();
// Depending on the TQtMsgType prepend a different colored Debug, Warning, Critical or Fatal.
switch (type)
{
case TQtDebugMsg:
{
message += " <span style=\"font-weight:bold; color:black;\">Debug:</span> ";
break;
}
case TQtWarningMsg:
{
message += " <span style=\"font-weight:bold; color:gold;\">Warning:</span> ";
break;
}
case TQtCriticalMsg:
{
message += "<span style=\"font-weight:bold; color:red;\">Critical:</span> ";
break;
}
case TQtFatalMsg:
{
message += " <span style=\"font-weight:bold; color:#D60000;\">Fatal:</span> ";
}
// This one is no TQt message type, but can be used to send info messages to the log
// by calling TSLogger::messageHandler() directly.
case TSLoggerInfoMsg:
{
message += " <span style=\"font-weight:bold; color:darkgray;\">Info:</span> ";
break;
}
}
// Append the to UTF-8 back converted message parameter.
message += TQString::fromUtf8(msg) + "<br/>\n";
// Write the message to the log windows text edit.
_instance->_TSLoggerDialogForm->logTextEdit->append(message);
// Write/append the log message to the log file.
_instance->writeToLogFile(message);
// In case of a fatal error abort the application.
if (type == TQtFatalMsg)
{
abort();
}
}
/*!
\brief Calling this the verbose level can be set in a range from 0 to 3
which is equal to debug, warning, critical and fatal priority.
*/
void TSLogger::setVerboseLevel(int level) {
if ( level < 0 )
_verboseLevel = TQtDebugMsg;
if ( level > 3 )
_verboseLevel = TQtFatalMsg;
else
_verboseLevel = TQtMsgType(level);
void TSLogger::setVerboseLevel(int level)
{
if (level < 0)
{
_verboseLevel = TQtDebugMsg;
}
if (level > 3)
{
_verboseLevel = TQtFatalMsg;
}
else
{
_verboseLevel = TQtMsgType(level);
}
}
/*!
\brief Deletes the existing _instance of TSLogger.
*/
void TSLogger::deleteInstance() {
if ( _instance != NULL ) {
delete _instance;
_instance = NULL;
}
void TSLogger::deleteInstance()
{
if (_instance != NULL)
{
delete _instance;
_instance = NULL;
}
}
/*!
\brief Opens the folder that contains the created log file with the name "UiGUI_log.html".
*/
void TSLogger::openLogFileFolder() {
TQDesktopServices::openUrl( TQFileInfo( _logFile ).absolutePath() );
void TSLogger::openLogFileFolder()
{
TQDesktopServices::openUrl(TQFileInfo(_logFile).absolutePath());
}
/*!
\brief Writes the \a message to the used log file.
*/
void TSLogger::writeToLogFile(const TQString &message) {
// If the file where all logging messages should go to isn't initilized yet, do that now.
if ( _logFileInitState == NOTINITIALZED ) {
_logFileInitState = INITIALIZING;
// On different systems it may be that "TQDir::tempPath()" ends with a "/" or not. So check this.
// Remove any trailing slashes.
TQString tempPath = TQFileInfo( SettingsPaths::getTempPath() ).absolutePath();
while ( tempPath.right(1) == "/" ) {
tempPath.chop(1);
}
// To make the temporary log file invulnerable against file symbolic link hacks
// append the current date and time up to milliseconds to its name and a random character.
TQString logFileName = "UiGUI_log_" + TQDateTime::currentDateTime().toString("yyyyMMdd");
logFileName += "-" + TQDateTime::currentDateTime().toString("hhmmsszzz");
// By random decide whether to append a number or an upper or lower case character.
qsrand( time(NULL) );
unsigned char randomChar;
switch ( qrand() % 3 ) {
// Append a number from 0 to 9.
case 0 :
randomChar = qrand() % 10 + '0';
break;
// Append a upper case characer between A and Z.
case 1 :
randomChar = qrand() % 26 + 'A';
break;
// Append a lower case characer between a and z.
default :
randomChar = qrand() % 26 + 'a';
break;
}
logFileName += "_" + TQString(randomChar) + ".html";
_logFile.setFileName( tempPath + "/" + logFileName );
// Set the tooltip of the open log file folder button to show the unique name of the log file.
_TSLoggerDialogForm->openLogFileFolderToolButton->setToolTip( _TSLoggerDialogForm->openLogFileFolderToolButton->toolTip() + " (" + logFileName + ")" );
_logFileInitState = INITIALZED;
}
// Add the message to the message queue.
_messageQueue << message;
// If the logging file is initialzed, write all messages contained in the message queue into the file.
if ( _logFileInitState == INITIALZED ) {
// Write/append the log message to the log file.
if ( _logFile.open(TQIODevice::WriteOnly | TQIODevice::Text | TQIODevice::Append) ) {
TQTextStream out(&_logFile);
while ( !_messageQueue.isEmpty() ) {
out << _messageQueue.takeFirst() << "\n";
}
_logFile.close();
}
}
void TSLogger::writeToLogFile(const TQString &message)
{
// If the file where all logging messages should go to isn't initilized yet, do that now.
if (_logFileInitState == NOTINITIALZED)
{
_logFileInitState = INITIALIZING;
// On different systems it may be that "TQDir::tempPath()" ends with a "/" or not. So check
// this.
// Remove any trailing slashes.
TQString tempPath = TQFileInfo(SettingsPaths::getTempPath()).absolutePath();
while (tempPath.right(1) == "/")
{
tempPath.chop(1);
}
// To make the temporary log file invulnerable against file symbolic link hacks
// append the current date and time up to milliseconds to its name and a random character.
TQString logFileName = "UiGUI_log_" + TQDateTime::currentDateTime().toString("yyyyMMdd");
logFileName += "-" + TQDateTime::currentDateTime().toString("hhmmsszzz");
// By random decide whether to append a number or an upper or lower case character.
qsrand(time(NULL));
unsigned char randomChar;
switch (qrand() % 3)
{
// Append a number from 0 to 9.
case 0:
{
randomChar = qrand() % 10 + '0';
break;
}
// Append a upper case characer between A and Z.
case 1:
{
randomChar = qrand() % 26 + 'A';
break;
}
// Append a lower case characer between a and z.
default:
{
randomChar = qrand() % 26 + 'a';
break;
}
}
logFileName += "_" + TQString(randomChar) + ".html";
_logFile.setFileName(tempPath + "/" + logFileName);
// Set the tooltip of the open log file folder button to show the unique name of the log file.
_TSLoggerDialogForm->openLogFileFolderToolButton->setToolTip(
_TSLoggerDialogForm->openLogFileFolderToolButton->toolTip() + " (" + logFileName + ")");
_logFileInitState = INITIALZED;
}
// Add the message to the message queue.
_messageQueue << message;
// If the logging file is initialzed, write all messages contained in the message queue into the
// file.
if (_logFileInitState == INITIALZED)
{
// Write/append the log message to the log file.
if (_logFile.open(TQIODevice::WriteOnly | TQIODevice::Text | TQIODevice::Append))
{
TQTextStream out(&_logFile);
while (!_messageQueue.isEmpty())
{
out << _messageQueue.takeFirst() << "\n";
}
_logFile.close();
}
}
}

@ -23,41 +23,50 @@
#include <tntqdialog.h>
#include <tntqfile.h>
namespace Ui {
namespace Ui
{
class TSLoggerDialog;
}
namespace tschweitzer { namespace debugging {
namespace tschweitzer
{
namespace debugging
{
#define TSLoggerInfoMsg TQtMsgType(4)
class TSLogger : public TQDialog
{
Q_OBJECT
class TSLogger : public TQDialog
{
Q_OBJECT
public:
static TSLogger* getInstance(int verboseLevel);
static TSLogger* getInstance();
static void messageHandler(TQtMsgType type, const char *msg);
static void deleteInstance();
void setVerboseLevel(int level);
public:
static TSLogger* getInstance(int verboseLevel);
static TSLogger* getInstance();
static void messageHandler(TQtMsgType type, const char *msg);
static void deleteInstance();
void setVerboseLevel(int level);
private slots:
void openLogFileFolder();
private slots:
void openLogFileFolder();
private:
Ui::TSLoggerDialog *_TSLoggerDialogForm;
private:
Ui::TSLoggerDialog *_TSLoggerDialogForm;
enum LogFileInitState { NOTINITIALZED, INITIALIZING, INITIALZED } _logFileInitState;
TSLogger(int verboseLevel);
void writeToLogFile(const TQString &message);
enum LogFileInitState
{
NOTINITIALZED,
INITIALIZING,
INITIALZED
} _logFileInitState;
TSLogger(int verboseLevel);
static TSLogger* _instance;
TQtMsgType _verboseLevel;
TQFile _logFile;
TQStringList _messageQueue;
};
void writeToLogFile(const TQString &message);
}} // namespace tschweitzer::debugging
static TSLogger *_instance;
TQtMsgType _verboseLevel;
TQFile _logFile;
TQStringList _messageQueue;
};
}
} // namespace tschweitzer::debugging
#endif // TSLogger_H

@ -18,7 +18,7 @@
***************************************************************************/
// -- #include "MainWindow.h"
// --
// --
// -- #include "UiGuiIndentServer.h"
// -- #include "debugging/TSLogger.h"
// -- #include "UiGuiIniFileParser.h"
@ -27,7 +27,7 @@
// -- #include "UiGuiSystemInfo.h"
// -- #include "IndentHandler.h"
// -- #include "SettingsPaths.h"
// --
// --
// -- #include <tntqapplication.h>
// -- #include <tntqtextcodec.h>
// -- #include <tqdebug.h>
@ -54,118 +54,127 @@
int main(int argc, char *argv[])
{
return 0;
// -- TQString file2OpenOnStart = "";
// -- int verboseLevel = 1;
// -- bool startAsPlugin = false;
// -- bool startAsServer = false;
// -- bool tclapExitExceptionThrown = false;
// -- int returnValue = 0;
// --
// -- // Wrap everything in a try block. Do this every time,
// -- // because exceptions will be thrown for problems.
// -- try {
// -- // Define the command line object.
// -- TCLAP::CmdLine cmd("If -p and -s are set, -p will be used.\nGiving no parameters starts full gui without server.", ' ', "UiGUI version " PROGRAM_VERSION_STRING " " PROGRAM_REVISION);
// -- cmd.setExceptionHandling(false);
// --
// -- // Define a value argument and add it to the command line.
// -- TCLAP::UnlabeledValueArg<std::string> filenameArg("file", "Opens the by filename defined file on start" , false, "", "filename");
// -- cmd.add( filenameArg );
// --
// -- // Define a switch and add it to the command line.
// -- TCLAP::SwitchArg pluginSwitch("p", "plugin", "Run as plugin. Server will be started with a simplified gui", false);
// -- cmd.add( pluginSwitch );
// --
// -- // Define a switch and add it to the command line.
// -- TCLAP::SwitchArg serverSwitch("s", "server", "Run as server only without gui", false);
// -- cmd.add( serverSwitch );
// --
// -- // Define a value argument and add it to the command line.
// -- TCLAP::ValueArg<int> verboselevelArg("v", "verbose", "Sets how many info is written to the log. 0 means with debug info, 3 means critical messages only" , false, 1, "int");
// -- cmd.add( verboselevelArg );
// --
// -- // Parse the args.
// -- cmd.parse( argc, argv );
// --
// -- // Get the value parsed by each arg.
// -- file2OpenOnStart = filenameArg.getValue().c_str();
// -- startAsPlugin = pluginSwitch.getValue();
// -- startAsServer = serverSwitch.getValue();
// -- verboseLevel = verboselevelArg.getValue();
// -- }
// -- catch (TCLAP::ArgException &e) { // catch arg exceptions
// -- std::cerr << std::endl << "error: " << e.error() << ". " << e.argId() << std::endl;
// -- returnValue = 1;
// -- }
// -- catch (TCLAP::ExitException &e) { // catch exit exceptions
// -- tclapExitExceptionThrown = true;
// -- returnValue = e.getExitStatus();
// -- }
// -- catch (...) { // catch any exceptions
// -- std::cerr << std::endl << "There was an error! Maybe faulty command line arguments set. See --help." << std::endl;
// -- returnValue = 1;
// -- }
// --
// -- if ( returnValue != 0 || tclapExitExceptionThrown ) {
// -- return returnValue;
// -- }
// --
// -- TQApplication app(argc, argv);
// -- UiGuiIndentServer server;
// -- MainWindow *mainWindow = NULL;
// -- IndentHandler *indentHandler = NULL;
// --
// -- // Init and install the logger function.
// -- // Setting UTF-8 as default 8-Bit encoding to ensure that tqDebug does no false string conversion.
// -- TQTextCodec::setCodecForCStrings( TQTextCodec::codecForName("UTF-8") );
// -- TQTextCodec::setCodecForLocale( TQTextCodec::codecForName("UTF-8") );
// -- // Force creation of an TSLogger instance here, to avoid recursion with SettingsPaths init function.
// -- #ifdef _DEBUG
// -- TSLogger::getInstance(0);
// -- #else
// -- TSLogger::getInstance(verboseLevel);
// -- #endif
// -- qInstallMsgHandler( TSLogger::messageHandler );
// -- TSLogger::messageHandler( TSLoggerInfoMsg, TQString("Starting UiGUI Version %1 %2").arg(PROGRAM_VERSION_STRING).arg(PROGRAM_REVISION).toAscii() );
// -- TSLogger::messageHandler( TSLoggerInfoMsg, TQString("Running on %1").arg(UiGuiSystemInfo::getOperatingSystem()).toAscii() );
// --
// -- // Set default values for all by UniversalIndentGUI used settings objects.
// -- TQCoreApplication::setOrganizationName("UniversalIndentGUI");
// -- TQCoreApplication::setOrganizationDomain("universalindent.sf.net");
// -- TQCoreApplication::setApplicationName("UniversalIndentGUI");
// --
// -- // Start normal with full gui and without server.
// -- if ( !startAsPlugin && !startAsServer ) {
// -- mainWindow = new MainWindow(file2OpenOnStart);
// -- mainWindow->show();
// -- }
// -- // Start as plugin with server.
// -- else if ( startAsPlugin ) {
// -- server.startServer();
// -- indentHandler = new IndentHandler(0);
// -- indentHandler->show();
// -- }
// -- // Start as server only without any gui.
// -- else if ( startAsServer ) {
// -- server.startServer();
// -- }
// --
// -- try {
// -- returnValue = app.exec();
// -- }
// -- catch (std::exception &ex) {
// -- qCritical() << __LINE__ << " " << __FUNCTION__ << ": Something went terribly wrong:" << ex.what();
// -- }
// --
// -- if ( startAsPlugin || startAsServer )
// -- server.stopServer();
// --
// -- delete indentHandler;
// -- delete mainWindow;
// --
// -- SettingsPaths::cleanAndRemoveTempDir();
// -- TSLogger::deleteInstance();
// --
// -- return returnValue;
// -- TQString file2OpenOnStart = "";
// -- int verboseLevel = 1;
// -- bool startAsPlugin = false;
// -- bool startAsServer = false;
// -- bool tclapExitExceptionThrown = false;
// -- int returnValue = 0;
// --
// -- // Wrap everything in a try block. Do this every time,
// -- // because exceptions will be thrown for problems.
// -- try {
// -- // Define the command line object.
// -- TCLAP::CmdLine cmd("If -p and -s are set, -p will be used.\nGiving no parameters starts
// full gui without server.", ' ', "UiGUI version " PROGRAM_VERSION_STRING " " PROGRAM_REVISION);
// -- cmd.setExceptionHandling(false);
// --
// -- // Define a value argument and add it to the command line.
// -- TCLAP::UnlabeledValueArg<std::string> filenameArg("file", "Opens the by
// filename defined file on start" , false, "", "filename");
// -- cmd.add( filenameArg );
// --
// -- // Define a switch and add it to the command line.
// -- TCLAP::SwitchArg pluginSwitch("p", "plugin", "Run as plugin. Server will be started with
// a simplified gui", false);
// -- cmd.add( pluginSwitch );
// --
// -- // Define a switch and add it to the command line.
// -- TCLAP::SwitchArg serverSwitch("s", "server", "Run as server only without gui", false);
// -- cmd.add( serverSwitch );
// --
// -- // Define a value argument and add it to the command line.
// -- TCLAP::ValueArg<int> verboselevelArg("v", "verbose", "Sets how many info is written to
// the log. 0 means with debug info, 3 means critical messages only" , false, 1, "int");
// -- cmd.add( verboselevelArg );
// --
// -- // Parse the args.
// -- cmd.parse( argc, argv );
// --
// -- // Get the value parsed by each arg.
// -- file2OpenOnStart = filenameArg.getValue().c_str();
// -- startAsPlugin = pluginSwitch.getValue();
// -- startAsServer = serverSwitch.getValue();
// -- verboseLevel = verboselevelArg.getValue();
// -- }
// -- catch (TCLAP::ArgException &e) { // catch arg exceptions
// -- std::cerr << std::endl << "error: " << e.error() << ". " << e.argId() << std::endl;
// -- returnValue = 1;
// -- }
// -- catch (TCLAP::ExitException &e) { // catch exit exceptions
// -- tclapExitExceptionThrown = true;
// -- returnValue = e.getExitStatus();
// -- }
// -- catch (...) { // catch any exceptions
// -- std::cerr << std::endl << "There was an error! Maybe faulty command line arguments set.
// See --help." << std::endl;
// -- returnValue = 1;
// -- }
// --
// -- if ( returnValue != 0 || tclapExitExceptionThrown ) {
// -- return returnValue;
// -- }
// --
// -- TQApplication app(argc, argv);
// -- UiGuiIndentServer server;
// -- MainWindow *mainWindow = NULL;
// -- IndentHandler *indentHandler = NULL;
// --
// -- // Init and install the logger function.
// -- // Setting UTF-8 as default 8-Bit encoding to ensure that tqDebug does no false string
// conversion.
// -- TQTextCodec::setCodecForCStrings( TQTextCodec::codecForName("UTF-8") );
// -- TQTextCodec::setCodecForLocale( TQTextCodec::codecForName("UTF-8") );
// -- // Force creation of an TSLogger instance here, to avoid recursion with SettingsPaths
// init function.
// -- #ifdef _DEBUG
// -- TSLogger::getInstance(0);
// -- #else
// -- TSLogger::getInstance(verboseLevel);
// -- #endif
// -- qInstallMsgHandler( TSLogger::messageHandler );
// -- TSLogger::messageHandler( TSLoggerInfoMsg, TQString("Starting UiGUI Version %1
// %2").arg(PROGRAM_VERSION_STRING).arg(PROGRAM_REVISION).toAscii() );
// -- TSLogger::messageHandler( TSLoggerInfoMsg, TQString("Running on
// %1").arg(UiGuiSystemInfo::getOperatingSystem()).toAscii() );
// --
// -- // Set default values for all by UniversalIndentGUI used settings objects.
// -- TQCoreApplication::setOrganizationName("UniversalIndentGUI");
// -- TQCoreApplication::setOrganizationDomain("universalindent.sf.net");
// -- TQCoreApplication::setApplicationName("UniversalIndentGUI");
// --
// -- // Start normal with full gui and without server.
// -- if ( !startAsPlugin && !startAsServer ) {
// -- mainWindow = new MainWindow(file2OpenOnStart);
// -- mainWindow->show();
// -- }
// -- // Start as plugin with server.
// -- else if ( startAsPlugin ) {
// -- server.startServer();
// -- indentHandler = new IndentHandler(0);
// -- indentHandler->show();
// -- }
// -- // Start as server only without any gui.
// -- else if ( startAsServer ) {
// -- server.startServer();
// -- }
// --
// -- try {
// -- returnValue = app.exec();
// -- }
// -- catch (std::exception &ex) {
// -- qCritical() << __LINE__ << " " << __FUNCTION__ << ": Something went terribly wrong:"
// << ex.what();
// -- }
// --
// -- if ( startAsPlugin || startAsServer )
// -- server.stopServer();
// --
// -- delete indentHandler;
// -- delete mainWindow;
// --
// -- SettingsPaths::cleanAndRemoveTempDir();
// -- TSLogger::deleteInstance();
// --
// -- return returnValue;
}

File diff suppressed because it is too large Load Diff

@ -1,24 +1,24 @@
// -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*-
/******************************************************************************
*
/******************************************************************************
*
* file: ArgException.h
*
*
* Copyright (c) 2003, Michael E. Smoot .
* All rights reverved.
*
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* 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.
*
*****************************************************************************/
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef TCLAP_ARG_EXCEPTION_H
@ -27,174 +27,182 @@
#include <string>
#include <exception>
namespace TCLAP {
/**
* A simple class that defines and argument exception. Should be caught
* whenever a CmdLine is created and parsed.
*/
class ArgException : public std::exception
{
public:
/**
* Constructor.
* \param text - The text of the exception.
* \param id - The text identifying the argument source.
* \param td - Text describing the type of ArgException it is.
* of the exception.
*/
ArgException( const std::string& text = "undefined exception",
const std::string& id = "undefined",
const std::string& td = "Generic ArgException")
: std::exception(),
_errorText(text),
_argId( id ),
_typeDescription(td)
{ }
/**
* Destructor.
*/
virtual ~ArgException() throw() { }
/**
* Returns the error text.
*/
std::string error() const { return ( _errorText ); }
/**
* Returns the argument id.
*/
std::string argId() const
{
if ( _argId == "undefined" )
return " ";
else
return ( "Argument: " + _argId );
}
/**
* Returns the arg id and error text.
*/
const char* what() const throw()
{
static std::string ex;
ex = _argId + " -- " + _errorText;
return ex.c_str();
}
/**
* Returns the type of the exception. Used to explain and distinguish
* between different child exceptions.
*/
std::string typeDescription() const
{
return _typeDescription;
}
private:
/**
* The text of the exception message.
*/
std::string _errorText;
/**
* The argument related to this exception.
*/
std::string _argId;
/**
* Describes the type of the exception. Used to distinguish
* between different child exceptions.
*/
std::string _typeDescription;
};
/**
* Thrown from within the child Arg classes when it fails to properly
* parse the argument it has been passed.
*/
class ArgParseException : public ArgException
{
public:
/**
* Constructor.
* \param text - The text of the exception.
* \param id - The text identifying the argument source
* of the exception.
*/
ArgParseException( const std::string& text = "undefined exception",
const std::string& id = "undefined" )
: ArgException( text,
id,
std::string( "Exception found while parsing " ) +
std::string( "the value the Arg has been passed." ))
{ }
};
/**
* Thrown from CmdLine when the arguments on the command line are not
* properly specified, e.g. too many arguments, required argument missing, etc.
*/
class CmdLineParseException : public ArgException
{
public:
/**
* Constructor.
* \param text - The text of the exception.
* \param id - The text identifying the argument source
* of the exception.
*/
CmdLineParseException( const std::string& text = "undefined exception",
const std::string& id = "undefined" )
: ArgException( text,
id,
std::string( "Exception found when the values ") +
std::string( "on the command line do not meet ") +
std::string( "the requirements of the defined ") +
std::string( "Args." ))
{ }
};
/**
* Thrown from Arg and CmdLine when an Arg is improperly specified, e.g.
* same flag as another Arg, same name, etc.
*/
class SpecificationException : public ArgException
namespace TCLAP
{
public:
/**
* Constructor.
* \param text - The text of the exception.
* \param id - The text identifying the argument source
* of the exception.
*/
SpecificationException( const std::string& text = "undefined exception",
const std::string& id = "undefined" )
: ArgException( text,
id,
std::string("Exception found when an Arg object ")+
std::string("is improperly defined by the ") +
std::string("developer." ))
{ }
};
class ExitException {
public:
ExitException(int estat) : _estat(estat) {}
int getExitStatus() const { return _estat; }
private:
int _estat;
};
/**
* A simple class that defines and argument exception. Should be caught
* whenever a CmdLine is created and parsed.
*/
class ArgException : public std::exception
{
public:
/**
* Constructor.
* \param text - The text of the exception.
* \param id - The text identifying the argument source.
* \param td - Text describing the type of ArgException it is.
* of the exception.
*/
ArgException(const std::string &text = "undefined exception",
const std::string &id = "undefined",
const std::string &td = "Generic ArgException") :
std::exception(), _errorText(text), _argId(id), _typeDescription(td)
{
}
/**
* Destructor.
*/
virtual ~ArgException() throw ()
{
}
/**
* Returns the error text.
*/
std::string error() const
{
return _errorText;
}
/**
* Returns the argument id.
*/
std::string argId() const
{
if (_argId == "undefined")
{
return " ";
}
else
{
return "Argument: " + _argId;
}
}
/**
* Returns the arg id and error text.
*/
const char* what() const throw ()
{
static std::string ex;
ex = _argId + " -- " + _errorText;
return ex.c_str();
}
/**
* Returns the type of the exception. Used to explain and distinguish
* between different child exceptions.
*/
std::string typeDescription() const
{
return _typeDescription;
}
private:
/**
* The text of the exception message.
*/
std::string _errorText;
/**
* The argument related to this exception.
*/
std::string _argId;
/**
* Describes the type of the exception. Used to distinguish
* between different child exceptions.
*/
std::string _typeDescription;
};
/**
* Thrown from within the child Arg classes when it fails to properly
* parse the argument it has been passed.
*/
class ArgParseException : public ArgException
{
public:
/**
* Constructor.
* \param text - The text of the exception.
* \param id - The text identifying the argument source
* of the exception.
*/
ArgParseException(const std::string &text = "undefined exception",
const std::string &id = "undefined") :
ArgException(text,
id,
std::string("Exception found while parsing ") +
std::string("the value the Arg has been passed."))
{
}
};
/**
* Thrown from CmdLine when the arguments on the command line are not
* properly specified, e.g. too many arguments, required argument missing, etc.
*/
class CmdLineParseException : public ArgException
{
public:
/**
* Constructor.
* \param text - The text of the exception.
* \param id - The text identifying the argument source
* of the exception.
*/
CmdLineParseException(const std::string &text = "undefined exception",
const std::string &id = "undefined") :
ArgException(text,
id,
std::string("Exception found when the values ") +
std::string("on the command line do not meet ") +
std::string("the requirements of the defined ") + std::string("Args."))
{
}
};
/**
* Thrown from Arg and CmdLine when an Arg is improperly specified, e.g.
* same flag as another Arg, same name, etc.
*/
class SpecificationException : public ArgException
{
public:
/**
* Constructor.
* \param text - The text of the exception.
* \param id - The text identifying the argument source
* of the exception.
*/
SpecificationException(const std::string &text = "undefined exception",
const std::string &id = "undefined") :
ArgException(text,
id,
std::string("Exception found when an Arg object ") +
std::string("is improperly defined by the ") + std::string("developer."))
{
}
};
class ExitException
{
public:
ExitException(int estat) :
_estat(estat)
{
}
int getExitStatus() const
{
return _estat;
}
private:
int _estat;
};
} // namespace TCLAP
#endif

@ -24,58 +24,62 @@
// include this directly
#ifndef TCLAP_ARGTRAITS_H
#define TCLAP_ARGTRAITS_H
#define TCLAP_ARGTRAITS_H
namespace TCLAP {
namespace TCLAP
{
// We use two empty structs to get compile type specialization
// function to work
// We use two empty structs to get compile type specialization
// function to work
/**
* A value like argument value type is a value that can be set using
* operator>>. This is the default value type.
*/
struct ValueLike
{
typedef ValueLike ValueCategory;
};
/**
* A value like argument value type is a value that can be set using
* operator>>. This is the default value type.
*/
struct ValueLike {
typedef ValueLike ValueCategory;
};
/**
* A string like argument value type is a value that can be set using
* operator=(string). Usefull if the value type contains spaces which
* will be broken up into individual tokens by operator>>.
*/
struct StringLike
{};
/**
* A string like argument value type is a value that can be set using
* operator=(string). Usefull if the value type contains spaces which
* will be broken up into individual tokens by operator>>.
*/
struct StringLike {};
/**
* A class can inherit from this object to make it have string like
* traits. This is a compile time thing and does not add any overhead
* to the inherenting class.
*/
struct StringLikeTrait
{
typedef StringLike ValueCategory;
};
/**
* A class can inherit from this object to make it have string like
* traits. This is a compile time thing and does not add any overhead
* to the inherenting class.
*/
struct StringLikeTrait {
typedef StringLike ValueCategory;
};
/**
* A class can inherit from this object to make it have value like
* traits. This is a compile time thing and does not add any overhead
* to the inherenting class.
*/
struct ValueLikeTrait
{
typedef ValueLike ValueCategory;
};
/**
* A class can inherit from this object to make it have value like
* traits. This is a compile time thing and does not add any overhead
* to the inherenting class.
*/
struct ValueLikeTrait {
typedef ValueLike ValueCategory;
};
/**
* Arg traits are used to get compile type specialization when parsing
* argument values. Using an ArgTraits you can specify the way that
* values gets assigned to any particular type during parsing. The two
* supported types are string like and value like.
*/
template<typename T>
struct ArgTraits {
typedef typename T::ValueCategory ValueCategory;
//typedef ValueLike ValueCategory;
};
/**
* Arg traits are used to get compile type specialization when parsing
* argument values. Using an ArgTraits you can specify the way that
* values gets assigned to any particular type during parsing. The two
* supported types are string like and value like.
*/
template<typename T>
struct ArgTraits
{
typedef typename T::ValueCategory ValueCategory;
//typedef ValueLike ValueCategory;
};
#endif
} // namespace

File diff suppressed because it is too large Load Diff

@ -1,24 +1,23 @@
/******************************************************************************
*
/******************************************************************************
*
* file: CmdLineInterface.h
*
*
* Copyright (c) 2003, Michael E. Smoot .
* Copyright (c) 2004, Michael E. Smoot, Daniel Aarno.
* All rights reverved.
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* 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.
*
*****************************************************************************/
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef TCLAP_COMMANDLINE_INTERFACE_H
#define TCLAP_COMMANDLINE_INTERFACE_H
@ -30,121 +29,121 @@
#include <algorithm>
namespace TCLAP {
class Arg;
class CmdLineOutput;
class XorHandler;
/**
* The base class that manages the command line definition and passes
* along the parsing to the appropriate Arg classes.
*/
class CmdLineInterface
namespace TCLAP
{
public:
/**
* Destructor
*/
virtual ~CmdLineInterface() {}
/**
* Adds an argument to the list of arguments to be parsed.
* \param a - Argument to be added.
*/
virtual void add( Arg& a )=0;
/**
* An alternative add. Functionally identical.
* \param a - Argument to be added.
*/
virtual void add( Arg* a )=0;
/**
* Add two Args that will be xor'd.
* If this method is used, add does
* not need to be called.
* \param a - Argument to be added and xor'd.
* \param b - Argument to be added and xor'd.
*/
virtual void xorAdd( Arg& a, Arg& b )=0;
/**
* Add a list of Args that will be xor'd. If this method is used,
* add does not need to be called.
* \param xors - List of Args to be added and xor'd.
*/
virtual void xorAdd( std::vector<Arg*>& xors )=0;
/**
* Parses the command line.
* \param argc - Number of arguments.
* \param argv - Array of arguments.
*/
virtual void parse(int argc, const char * const * argv)=0;
/**
* Parses the command line.
* \param args - A vector of strings representing the args.
* args[0] is still the program name.
*/
void parse(std::vector<std::string>& args);
/**
* Returns the CmdLineOutput object.
*/
virtual CmdLineOutput* getOutput()=0;
/**
* \param co - CmdLineOutput object that we want to use instead.
*/
virtual void setOutput(CmdLineOutput* co)=0;
/**
* Returns the version string.
*/
virtual std::string& getVersion()=0;
/**
* Returns the program name string.
*/
virtual std::string& getProgramName()=0;
/**
* Returns the argList.
*/
virtual std::list<Arg*>& getArgList()=0;
/**
* Returns the XorHandler.
*/
virtual XorHandler& getXorHandler()=0;
/**
* Returns the delimiter string.
*/
virtual char getDelimiter()=0;
/**
* Returns the message string.
*/
virtual std::string& getMessage()=0;
/**
* Indicates whether or not the help and version switches were created
* automatically.
*/
virtual bool hasHelpAndVersion()=0;
/**
* Resets the instance as if it had just been constructed so that the
* instance can be reused.
*/
virtual void reset()=0;
};
class Arg;
class CmdLineOutput;
class XorHandler;
/**
* The base class that manages the command line definition and passes
* along the parsing to the appropriate Arg classes.
*/
class CmdLineInterface
{
public:
/**
* Destructor
*/
virtual ~CmdLineInterface()
{
}
/**
* Adds an argument to the list of arguments to be parsed.
* \param a - Argument to be added.
*/
virtual void add(Arg &a) = 0;
/**
* An alternative add. Functionally identical.
* \param a - Argument to be added.
*/
virtual void add(Arg *a) = 0;
/**
* Add two Args that will be xor'd.
* If this method is used, add does
* not need to be called.
* \param a - Argument to be added and xor'd.
* \param b - Argument to be added and xor'd.
*/
virtual void xorAdd(Arg &a, Arg &b) = 0;
/**
* Add a list of Args that will be xor'd. If this method is used,
* add does not need to be called.
* \param xors - List of Args to be added and xor'd.
*/
virtual void xorAdd(std::vector<Arg*> &xors) = 0;
/**
* Parses the command line.
* \param argc - Number of arguments.
* \param argv - Array of arguments.
*/
virtual void parse(int argc, const char*const *argv) = 0;
/**
* Parses the command line.
* \param args - A vector of strings representing the args.
* args[0] is still the program name.
*/
void parse(std::vector<std::string> &args);
/**
* Returns the CmdLineOutput object.
*/
virtual CmdLineOutput* getOutput() = 0;
/**
* \param co - CmdLineOutput object that we want to use instead.
*/
virtual void setOutput(CmdLineOutput *co) = 0;
/**
* Returns the version string.
*/
virtual std::string& getVersion() = 0;
/**
* Returns the program name string.
*/
virtual std::string& getProgramName() = 0;
/**
* Returns the argList.
*/
virtual std::list<Arg*>& getArgList() = 0;
/**
* Returns the XorHandler.
*/
virtual XorHandler& getXorHandler() = 0;
/**
* Returns the delimiter string.
*/
virtual char getDelimiter() = 0;
/**
* Returns the message string.
*/
virtual std::string& getMessage() = 0;
/**
* Indicates whether or not the help and version switches were created
* automatically.
*/
virtual bool hasHelpAndVersion() = 0;
/**
* Resets the instance as if it had just been constructed so that the
* instance can be reused.
*/
virtual void reset() = 0;
};
} //namespace
#endif
#endif

@ -1,24 +1,22 @@
/******************************************************************************
*
/******************************************************************************
*
* file: CmdLineOutput.h
*
*
* Copyright (c) 2004, Michael E. Smoot
* All rights reverved.
*
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* 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.
*
*****************************************************************************/
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef TCLAP_CMDLINEOUTPUT_H
#define TCLAP_CMDLINEOUTPUT_H
@ -30,45 +28,43 @@
#include <iomanip>
#include <algorithm>
namespace TCLAP {
class CmdLineInterface;
class ArgException;
/**
* The interface that any output object must implement.
*/
class CmdLineOutput
namespace TCLAP
{
class CmdLineInterface;
class ArgException;
public:
/**
* The interface that any output object must implement.
*/
class CmdLineOutput
{
public:
/**
* Virtual destructor.
*/
virtual ~CmdLineOutput()
{
}
/**
* Virtual destructor.
*/
virtual ~CmdLineOutput() {}
/**
* Generates some sort of output for the USAGE.
* \param c - The CmdLine object the output is generated for.
*/
virtual void usage(CmdLineInterface &c) = 0;
/**
* Generates some sort of output for the USAGE.
* \param c - The CmdLine object the output is generated for.
*/
virtual void usage(CmdLineInterface& c)=0;
/**
* Generates some sort of output for the version.
* \param c - The CmdLine object the output is generated for.
*/
virtual void version(CmdLineInterface& c)=0;
/**
* Generates some sort of output for a failure.
* \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure.
*/
virtual void failure( CmdLineInterface& c,
ArgException& e )=0;
};
/**
* Generates some sort of output for the version.
* \param c - The CmdLine object the output is generated for.
*/
virtual void version(CmdLineInterface &c) = 0;
/**
* Generates some sort of output for a failure.
* \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure.
*/
virtual void failure(CmdLineInterface &c, ArgException &e) = 0;
};
} //namespace TCLAP
#endif
#endif

@ -1,4 +1,3 @@
/******************************************************************************
*
* file: Constraint.h
@ -29,40 +28,41 @@
#include <iomanip>
#include <algorithm>
namespace TCLAP {
/**
* The interface that defines the interaction between the Arg and Constraint.
*/
template<class T>
class Constraint
namespace TCLAP
{
/**
* The interface that defines the interaction between the Arg and Constraint.
*/
template<class T>
class Constraint
{
public:
/**
* Returns a description of the Constraint.
*/
virtual std::string description() const = 0;
public:
/**
* Returns a description of the Constraint.
*/
virtual std::string description() const =0;
/**
* Returns the short ID for the Constraint.
*/
virtual std::string shortID() const =0;
/**
* Returns the short ID for the Constraint.
*/
virtual std::string shortID() const = 0;
/**
* The method used to verify that the value parsed from the command
* line meets the constraint.
* \param value - The value that will be checked.
*/
virtual bool check(const T& value) const =0;
/**
* Destructor.
* Silences warnings about Constraint being a base class with virtual
* functions but without a virtual destructor.
*/
virtual ~Constraint() { ; }
};
/**
* The method used to verify that the value parsed from the command
* line meets the constraint.
* \param value - The value that will be checked.
*/
virtual bool check(const T &value) const = 0;
/**
* Destructor.
* Silences warnings about Constraint being a base class with virtual
* functions but without a virtual destructor.
*/
virtual ~Constraint()
{
}
};
} //namespace TCLAP
#endif

@ -1,24 +1,24 @@
// -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*-
/******************************************************************************
*
/******************************************************************************
*
* file: DocBookOutput.h
*
*
* Copyright (c) 2004, Michael E. Smoot
* All rights reverved.
*
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* 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.
*
*****************************************************************************/
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef TCLAP_DOCBOOKOUTPUT_H
#define TCLAP_DOCBOOKOUTPUT_H
@ -34,266 +34,272 @@
#include <tclap/XorHandler.h>
#include <tclap/Arg.h>
namespace TCLAP {
/**
* A class that generates DocBook output for usage() method for the
* given CmdLine and its Args.
*/
class DocBookOutput : public CmdLineOutput
{
public:
/**
* Prints the usage to stdout. Can be overridden to
* produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void usage(CmdLineInterface& c);
/**
* Prints the version to stdout. Can be overridden
* to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void version(CmdLineInterface& c);
/**
* Prints (to stderr) an error message, short usage
* Can be overridden to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure.
*/
virtual void failure(CmdLineInterface& c,
ArgException& e );
protected:
/**
* Substitutes the char r for string x in string s.
* \param s - The string to operate on.
* \param r - The char to replace.
* \param x - What to replace r with.
*/
void substituteSpecialChars( std::string& s, char r, std::string& x );
void removeChar( std::string& s, char r);
void basename( std::string& s );
void printShortArg(Arg* it);
void printLongArg(Arg* it);
char theDelimiter;
};
inline void DocBookOutput::version(CmdLineInterface& _cmd)
{
std::cout << _cmd.getVersion() << std::endl;
}
inline void DocBookOutput::usage(CmdLineInterface& _cmd )
namespace TCLAP
{
std::list<Arg*> argList = _cmd.getArgList();
std::string progName = _cmd.getProgramName();
std::string version = _cmd.getVersion();
theDelimiter = _cmd.getDelimiter();
XorHandler xorHandler = _cmd.getXorHandler();
std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList();
basename(progName);
std::cout << "<?xml version='1.0'?>" << std::endl;
std::cout << "<!DOCTYPE refentry PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\"" << std::endl;
std::cout << "\t\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\">" << std::endl << std::endl;
std::cout << "<refentry>" << std::endl;
std::cout << "<refmeta>" << std::endl;
std::cout << "<refentrytitle>" << progName << "</refentrytitle>" << std::endl;
std::cout << "<manvolnum>1</manvolnum>" << std::endl;
std::cout << "</refmeta>" << std::endl;
std::cout << "<refnamediv>" << std::endl;
std::cout << "<refname>" << progName << "</refname>" << std::endl;
std::cout << "<refpurpose>" << _cmd.getMessage() << "</refpurpose>" << std::endl;
std::cout << "</refnamediv>" << std::endl;
std::cout << "<refsynopsisdiv>" << std::endl;
std::cout << "<cmdsynopsis>" << std::endl;
std::cout << "<command>" << progName << "</command>" << std::endl;
/**
* A class that generates DocBook output for usage() method for the
* given CmdLine and its Args.
*/
class DocBookOutput : public CmdLineOutput
{
public:
/**
* Prints the usage to stdout. Can be overridden to
* produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void usage(CmdLineInterface &c);
/**
* Prints the version to stdout. Can be overridden
* to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void version(CmdLineInterface &c);
/**
* Prints (to stderr) an error message, short usage
* Can be overridden to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure.
*/
virtual void failure(CmdLineInterface &c, ArgException &e);
protected:
/**
* Substitutes the char r for string x in string s.
* \param s - The string to operate on.
* \param r - The char to replace.
* \param x - What to replace r with.
*/
void substituteSpecialChars(std::string &s, char r, std::string &x);
void removeChar(std::string &s, char r);
void basename(std::string &s);
void printShortArg(Arg *it);
void printLongArg(Arg *it);
char theDelimiter;
};
inline void DocBookOutput::version(CmdLineInterface &_cmd)
{
std::cout << _cmd.getVersion() << std::endl;
}
// xor
for ( int i = 0; (unsigned int)i < xorList.size(); i++ )
inline void DocBookOutput::usage(CmdLineInterface &_cmd)
{
std::cout << "<group choice='req'>" << std::endl;
for ( ArgVectorIterator it = xorList[i].begin();
it != xorList[i].end(); it++ )
printShortArg((*it));
std::list<Arg*> argList = _cmd.getArgList();
std::string progName = _cmd.getProgramName();
std::string version = _cmd.getVersion();
theDelimiter = _cmd.getDelimiter();
XorHandler xorHandler = _cmd.getXorHandler();
std::vector<std::vector<Arg*>> xorList = xorHandler.getXorList();
basename(progName);
std::cout << "<?xml version='1.0'?>" << std::endl;
std::cout << "<!DOCTYPE refentry PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\"" << std::endl;
std::cout << "\t\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\">" << std::endl <<
std::endl;
std::cout << "<refentry>" << std::endl;
std::cout << "<refmeta>" << std::endl;
std::cout << "<refentrytitle>" << progName << "</refentrytitle>" << std::endl;
std::cout << "<manvolnum>1</manvolnum>" << std::endl;
std::cout << "</refmeta>" << std::endl;
std::cout << "<refnamediv>" << std::endl;
std::cout << "<refname>" << progName << "</refname>" << std::endl;
std::cout << "<refpurpose>" << _cmd.getMessage() << "</refpurpose>" << std::endl;
std::cout << "</refnamediv>" << std::endl;
std::cout << "<refsynopsisdiv>" << std::endl;
std::cout << "<cmdsynopsis>" << std::endl;
std::cout << "<command>" << progName << "</command>" << std::endl;
// xor
for (int i = 0; (unsigned int)i < xorList.size(); i++)
{
std::cout << "<group choice='req'>" << std::endl;
for (ArgVectorIterator it = xorList[i].begin();
it != xorList[i].end(); it++)
{
printShortArg((*it));
}
std::cout << "</group>" << std::endl;
}
// rest of args
for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
{
if (!xorHandler.contains((*it)))
{
printShortArg((*it));
}
}
std::cout << "</cmdsynopsis>" << std::endl;
std::cout << "</refsynopsisdiv>" << std::endl;
std::cout << "<refsect1>" << std::endl;
std::cout << "<title>Description</title>" << std::endl;
std::cout << "<para>" << std::endl;
std::cout << _cmd.getMessage() << std::endl;
std::cout << "</para>" << std::endl;
std::cout << "</refsect1>" << std::endl;
std::cout << "<refsect1>" << std::endl;
std::cout << "<title>Options</title>" << std::endl;
std::cout << "<variablelist>" << std::endl;
for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
{
printLongArg((*it));
}
std::cout << "</variablelist>" << std::endl;
std::cout << "</refsect1>" << std::endl;
std::cout << "<refsect1>" << std::endl;
std::cout << "<title>Version</title>" << std::endl;
std::cout << "<para>" << std::endl;
std::cout << version << std::endl;
std::cout << "</para>" << std::endl;
std::cout << "</refsect1>" << std::endl;
std::cout << "</refentry>" << std::endl;
}
std::cout << "</group>" << std::endl;
inline void DocBookOutput::failure(CmdLineInterface &_cmd, ArgException &e)
{
static_cast<void>(_cmd); // unused
std::cout << e.what() << std::endl;
throw ExitException(1);
}
// rest of args
for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
if ( !xorHandler.contains( (*it) ) )
printShortArg((*it));
std::cout << "</cmdsynopsis>" << std::endl;
std::cout << "</refsynopsisdiv>" << std::endl;
std::cout << "<refsect1>" << std::endl;
std::cout << "<title>Description</title>" << std::endl;
std::cout << "<para>" << std::endl;
std::cout << _cmd.getMessage() << std::endl;
std::cout << "</para>" << std::endl;
std::cout << "</refsect1>" << std::endl;
std::cout << "<refsect1>" << std::endl;
std::cout << "<title>Options</title>" << std::endl;
std::cout << "<variablelist>" << std::endl;
for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
printLongArg((*it));
std::cout << "</variablelist>" << std::endl;
std::cout << "</refsect1>" << std::endl;
std::cout << "<refsect1>" << std::endl;
std::cout << "<title>Version</title>" << std::endl;
std::cout << "<para>" << std::endl;
std::cout << version << std::endl;
std::cout << "</para>" << std::endl;
std::cout << "</refsect1>" << std::endl;
std::cout << "</refentry>" << std::endl;
}
inline void DocBookOutput::failure( CmdLineInterface& _cmd,
ArgException& e )
{
static_cast<void>(_cmd); // unused
std::cout << e.what() << std::endl;
throw ExitException(1);
}
inline void DocBookOutput::substituteSpecialChars( std::string& s,
char r,
std::string& x )
{
size_t p;
while ( (p = s.find_first_of(r)) != std::string::npos )
inline void DocBookOutput::substituteSpecialChars(std::string &s, char r, std::string &x)
{
s.erase(p,1);
s.insert(p,x);
size_t p;
while ((p = s.find_first_of(r)) != std::string::npos)
{
s.erase(p, 1);
s.insert(p, x);
}
}
}
inline void DocBookOutput::removeChar( std::string& s, char r)
{
size_t p;
while ( (p = s.find_first_of(r)) != std::string::npos )
inline void DocBookOutput::removeChar(std::string &s, char r)
{
s.erase(p,1);
size_t p;
while ((p = s.find_first_of(r)) != std::string::npos)
{
s.erase(p, 1);
}
}
}
inline void DocBookOutput::basename( std::string& s )
{
size_t p = s.find_last_of('/');
if ( p != std::string::npos )
inline void DocBookOutput::basename(std::string &s)
{
s.erase(0, p + 1);
size_t p = s.find_last_of('/');
if (p != std::string::npos)
{
s.erase(0, p + 1);
}
}
}
inline void DocBookOutput::printShortArg(Arg* a)
{
std::string lt = "&lt;";
std::string gt = "&gt;";
std::string id = a->shortID();
substituteSpecialChars(id,'<',lt);
substituteSpecialChars(id,'>',gt);
removeChar(id,'[');
removeChar(id,']');
std::string choice = "opt";
if ( a->isRequired() )
choice = "plain";
std::cout << "<arg choice='" << choice << '\'';
if ( a->acceptsMultipleValues() )
std::cout << " rep='repeat'";
std::cout << '>';
if ( !a->getFlag().empty() )
std::cout << a->flagStartChar() << a->getFlag();
else
std::cout << a->nameStartString() << a->getName();
if ( a->isValueRequired() )
inline void DocBookOutput::printShortArg(Arg *a)
{
std::string arg = a->shortID();
removeChar(arg,'[');
removeChar(arg,']');
removeChar(arg,'<');
removeChar(arg,'>');
arg.erase(0, arg.find_last_of(theDelimiter) + 1);
std::cout << theDelimiter;
std::cout << "<replaceable>" << arg << "</replaceable>";
std::string lt = "&lt;";
std::string gt = "&gt;";
std::string id = a->shortID();
substituteSpecialChars(id, '<', lt);
substituteSpecialChars(id, '>', gt);
removeChar(id, '[');
removeChar(id, ']');
std::string choice = "opt";
if (a->isRequired())
{
choice = "plain";
}
std::cout << "<arg choice='" << choice << '\'';
if (a->acceptsMultipleValues())
{
std::cout << " rep='repeat'";
}
std::cout << '>';
if (!a->getFlag().empty())
{
std::cout << a->flagStartChar() << a->getFlag();
}
else
{
std::cout << a->nameStartString() << a->getName();
}
if (a->isValueRequired())
{
std::string arg = a->shortID();
removeChar(arg, '[');
removeChar(arg, ']');
removeChar(arg, '<');
removeChar(arg, '>');
arg.erase(0, arg.find_last_of(theDelimiter) + 1);
std::cout << theDelimiter;
std::cout << "<replaceable>" << arg << "</replaceable>";
}
std::cout << "</arg>" << std::endl;
}
std::cout << "</arg>" << std::endl;
}
inline void DocBookOutput::printLongArg(Arg *a)
{
std::string lt = "&lt;";
std::string gt = "&gt;";
inline void DocBookOutput::printLongArg(Arg* a)
{
std::string lt = "&lt;";
std::string gt = "&gt;";
std::string desc = a->getDescription();
substituteSpecialChars(desc, '<', lt);
substituteSpecialChars(desc, '>', gt);
std::string desc = a->getDescription();
substituteSpecialChars(desc,'<',lt);
substituteSpecialChars(desc,'>',gt);
std::cout << "<varlistentry>" << std::endl;
std::cout << "<varlistentry>" << std::endl;
if (!a->getFlag().empty())
{
std::cout << "<term>" << std::endl;
std::cout << "<option>";
std::cout << a->flagStartChar() << a->getFlag();
std::cout << "</option>" << std::endl;
std::cout << "</term>" << std::endl;
}
if ( !a->getFlag().empty() )
{
std::cout << "<term>" << std::endl;
std::cout << "<option>";
std::cout << a->flagStartChar() << a->getFlag();
std::cout << a->nameStartString() << a->getName();
if (a->isValueRequired())
{
std::string arg = a->shortID();
removeChar(arg, '[');
removeChar(arg, ']');
removeChar(arg, '<');
removeChar(arg, '>');
arg.erase(0, arg.find_last_of(theDelimiter) + 1);
std::cout << theDelimiter;
std::cout << "<replaceable>" << arg << "</replaceable>";
}
std::cout << "</option>" << std::endl;
std::cout << "</term>" << std::endl;
}
std::cout << "<term>" << std::endl;
std::cout << "<option>";
std::cout << a->nameStartString() << a->getName();
if ( a->isValueRequired() )
{
std::string arg = a->shortID();
removeChar(arg,'[');
removeChar(arg,']');
removeChar(arg,'<');
removeChar(arg,'>');
arg.erase(0, arg.find_last_of(theDelimiter) + 1);
std::cout << theDelimiter;
std::cout << "<replaceable>" << arg << "</replaceable>";
}
std::cout << "</option>" << std::endl;
std::cout << "</term>" << std::endl;
std::cout << "<listitem>" << std::endl;
std::cout << "<para>" << std::endl;
std::cout << desc << std::endl;
std::cout << "</para>" << std::endl;
std::cout << "</listitem>" << std::endl;
std::cout << "</varlistentry>" << std::endl;
}
std::cout << "<listitem>" << std::endl;
std::cout << "<para>" << std::endl;
std::cout << desc << std::endl;
std::cout << "</para>" << std::endl;
std::cout << "</listitem>" << std::endl;
std::cout << "</varlistentry>" << std::endl;
}
} //namespace TCLAP
#endif
#endif

@ -1,23 +1,22 @@
/******************************************************************************
*
/******************************************************************************
*
* file: HelpVisitor.h
*
*
* Copyright (c) 2003, Michael E. Smoot .
* All rights reverved.
*
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* 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.
*
*****************************************************************************/
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef TCLAP_HELP_VISITOR_H
#define TCLAP_HELP_VISITOR_H
@ -26,44 +25,46 @@
#include <tclap/CmdLineOutput.h>
#include <tclap/Visitor.h>
namespace TCLAP {
/**
* A Visitor object that calls the usage method of the given CmdLineOutput
* object for the specified CmdLine object.
*/
class HelpVisitor: public Visitor
namespace TCLAP
{
protected:
/**
* The CmdLine the output will be generated for.
*/
CmdLineInterface* _cmd;
/**
* The output object.
*/
CmdLineOutput** _out;
public:
/**
* A Visitor object that calls the usage method of the given CmdLineOutput
* object for the specified CmdLine object.
*/
class HelpVisitor : public Visitor
{
protected:
/**
* The CmdLine the output will be generated for.
*/
CmdLineInterface *_cmd;
/**
* Constructor.
* \param cmd - The CmdLine the output will be generated for.
* \param out - The type of output.
*/
HelpVisitor(CmdLineInterface* cmd, CmdLineOutput** out)
: Visitor(), _cmd( cmd ), _out( out ) { }
/**
* The output object.
*/
CmdLineOutput **_out;
/**
* Calls the usage method of the CmdLineOutput for the
* specified CmdLine.
*/
void visit() { (*_out)->usage(*_cmd); throw ExitException(0); }
};
public:
/**
* Constructor.
* \param cmd - The CmdLine the output will be generated for.
* \param out - The type of output.
*/
HelpVisitor(CmdLineInterface *cmd, CmdLineOutput **out) :
Visitor(), _cmd(cmd), _out(out)
{
}
/**
* Calls the usage method of the CmdLineOutput for the
* specified CmdLine.
*/
void visit()
{
(*_out)->usage(*_cmd);
throw ExitException(0);
}
};
}
#endif

@ -1,23 +1,22 @@
/******************************************************************************
*
/******************************************************************************
*
* file: IgnoreRestVisitor.h
*
*
* Copyright (c) 2003, Michael E. Smoot .
* All rights reverved.
*
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* 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.
*
*****************************************************************************/
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef TCLAP_IGNORE_REST_VISITOR_H
@ -26,27 +25,31 @@
#include <tclap/Visitor.h>
#include <tclap/Arg.h>
namespace TCLAP {
/**
* A Vistor that tells the CmdLine to begin ignoring arguments after
* this one is parsed.
*/
class IgnoreRestVisitor: public Visitor
namespace TCLAP
{
public:
/**
* Constructor.
*/
IgnoreRestVisitor() : Visitor() {}
/**
* Sets Arg::_ignoreRest.
*/
void visit() { Arg::beginIgnoring(); }
};
/**
* A Vistor that tells the CmdLine to begin ignoring arguments after
* this one is parsed.
*/
class IgnoreRestVisitor : public Visitor
{
public:
/**
* Constructor.
*/
IgnoreRestVisitor() :
Visitor()
{
}
/**
* Sets Arg::_ignoreRest.
*/
void visit()
{
Arg::beginIgnoring();
}
};
}
#endif

@ -1,22 +1,22 @@
/******************************************************************************
*
/******************************************************************************
*
* file: MultiArg.h
*
*
* Copyright (c) 2003, Michael E. Smoot .
* Copyright (c) 2004, Michael E. Smoot, Daniel Aarno.
* All rights reverved.
*
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* 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.
*
*
* 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.
*
*****************************************************************************/
@ -29,394 +29,377 @@
#include <tclap/Arg.h>
#include <tclap/Constraint.h>
namespace TCLAP {
/**
* An argument that allows multiple values of type T to be specified. Very
* similar to a ValueArg, except a vector of values will be returned
* instead of just one.
*/
template<class T>
class MultiArg : public Arg
namespace TCLAP
{
public:
typedef std::vector<T> container_type;
typedef typename container_type::iterator iterator;
typedef typename container_type::const_iterator const_iterator;
protected:
/**
* The list of values parsed from the CmdLine.
* An argument that allows multiple values of type T to be specified. Very
* similar to a ValueArg, except a vector of values will be returned
* instead of just one.
*/
std::vector<T> _values;
template<class T>
class MultiArg : public Arg
{
public:
typedef std::vector<T> container_type;
typedef typename container_type::iterator iterator;
typedef typename container_type::const_iterator const_iterator;
protected:
/**
* The list of values parsed from the CmdLine.
*/
std::vector<T> _values;
/**
* The description of type T to be used in the usage.
*/
std::string _typeDesc;
/**
* A list of constraint on this Arg.
*/
Constraint<T> *_constraint;
/**
* Extracts the value from the string.
* Attempts to parse string as type T, if this fails an exception
* is thrown.
* \param val - The string to be read.
*/
void _extractValue(const std::string &val);
/**
* Used by XorHandler to decide whether to keep parsing for this arg.
*/
bool _allowMore;
public:
/**
* Constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiArg(const std::string &flag, const std::string &name, const std::string &desc, bool req,
const std::string &typeDesc, Visitor *v = NULL);
/**
* Constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param parser - A CmdLine parser object to add this Arg to
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiArg(const std::string &flag, const std::string &name, const std::string &desc, bool req,
const std::string &typeDesc, CmdLineInterface &parser, Visitor *v = NULL);
/**
* Constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiArg(const std::string &flag, const std::string &name, const std::string &desc, bool req,
Constraint<T> *constraint, Visitor *v = NULL);
/**
* Constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param parser - A CmdLine parser object to add this Arg to
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiArg(const std::string &flag, const std::string &name, const std::string &desc, bool req,
Constraint<T> *constraint, CmdLineInterface &parser, Visitor *v = NULL);
/**
* Handles the processing of the argument.
* This re-implements the Arg version of this method to set the
* _value of the argument appropriately. It knows the difference
* between labeled and unlabeled.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed from main().
*/
virtual bool processArg(int *i, std::vector<std::string> &args);
/**
* Returns a vector of type T containing the values parsed from
* the command line.
*/
const std::vector<T>& getValue();
/**
* Returns an iterator over the values parsed from the command
* line.
*/
const_iterator begin() const
{
return _values.begin();
}
/**
* Returns the end of the values parsed from the command
* line.
*/
const_iterator end() const
{
return _values.end();
}
/**
* Returns the a short id string. Used in the usage.
* \param val - value to be used.
*/
virtual std::string shortID(const std::string &val = "val") const;
/**
* Returns the a long id string. Used in the usage.
* \param val - value to be used.
*/
virtual std::string longID(const std::string &val = "val") const;
/**
* Once we've matched the first value, then the arg is no longer
* required.
*/
virtual bool isRequired() const;
virtual bool allowMore();
virtual void reset();
};
template<class T>
MultiArg<T>::MultiArg(const std::string &flag, const std::string &name, const std::string &desc,
bool req, const std::string &typeDesc, Visitor *v) :
Arg(flag, name, desc, req, true, v), _typeDesc(typeDesc), _constraint(NULL), _allowMore(false)
{
_acceptsMultipleValues = true;
}
/**
* The description of type T to be used in the usage.
*/
std::string _typeDesc;
template<class T>
MultiArg<T>::MultiArg(const std::string &flag, const std::string &name, const std::string &desc,
bool req, const std::string &typeDesc, CmdLineInterface &parser,
Visitor *v) :
Arg(flag, name, desc, req, true, v), _typeDesc(typeDesc), _constraint(NULL), _allowMore(false)
{
parser.add(this);
_acceptsMultipleValues = true;
}
/**
* A list of constraint on this Arg.
*
*/
Constraint<T>* _constraint;
template<class T>
MultiArg<T>::MultiArg(const std::string &flag, const std::string &name, const std::string &desc,
bool req, Constraint<T> *constraint, Visitor *v) :
Arg(flag, name, desc, req, true, v), _typeDesc(constraint->shortID()),
_constraint(constraint), _allowMore(false)
{
_acceptsMultipleValues = true;
}
/**
* Extracts the value from the string.
* Attempts to parse string as type T, if this fails an exception
* is thrown.
* \param val - The string to be read.
*/
void _extractValue( const std::string& val );
template<class T>
MultiArg<T>::MultiArg(const std::string &flag, const std::string &name, const std::string &desc,
bool req, Constraint<T> *constraint, CmdLineInterface &parser, Visitor *v) :
Arg(flag, name, desc, req, true, v), _typeDesc(constraint->shortID()),
_constraint(constraint), _allowMore(false)
{
parser.add(this);
_acceptsMultipleValues = true;
}
/**
* Used by XorHandler to decide whether to keep parsing for this arg.
*/
bool _allowMore;
template<class T>
const std::vector<T>& MultiArg<T>::getValue()
{
return _values;
}
public:
template<class T>
bool MultiArg<T>::processArg(int *i, std::vector<std::string> &args)
{
if (_ignoreable && Arg::ignoreRest())
{
return false;
}
/**
* Constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
Visitor* v = NULL);
if (_hasBlanks(args[*i]))
{
return false;
}
/**
* Constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param parser - A CmdLine parser object to add this Arg to
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
CmdLineInterface& parser,
Visitor* v = NULL );
std::string flag = args[*i];
std::string value = "";
/**
* Constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
Visitor* v = NULL );
/**
* Constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param parser - A CmdLine parser object to add this Arg to
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
CmdLineInterface& parser,
Visitor* v = NULL );
/**
* Handles the processing of the argument.
* This re-implements the Arg version of this method to set the
* _value of the argument appropriately. It knows the difference
* between labeled and unlabeled.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed from main().
*/
virtual bool processArg(int* i, std::vector<std::string>& args);
trimFlag(flag, value);
/**
* Returns a vector of type T containing the values parsed from
* the command line.
*/
const std::vector<T>& getValue();
if (argMatches(flag))
{
if (Arg::delimiter() != ' ' && value == "")
{
throw (ArgParseException(
"Couldn't find delimiter for this argument!", toString()));
}
// always take the first one, regardless of start string
if (value == "")
{
(*i)++;
if (static_cast<unsigned int>(*i) < args.size())
{
_extractValue(args[*i]);
}
else
{
throw (ArgParseException("Missing a value for this argument!", toString()));
}
}
else
{
_extractValue(value);
}
/**
* Returns an iterator over the values parsed from the command
* line.
*/
const_iterator begin() const { return _values.begin(); }
/*
// continuing taking the args until we hit one with a start string
while ( (unsigned int)(*i)+1 < args.size() &&
args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 &&
args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 )
_extractValue( args[++(*i)] );
*/
/**
* Returns the end of the values parsed from the command
* line.
*/
const_iterator end() const { return _values.end(); }
_alreadySet = true;
_checkWithVisitor();
return true;
}
else
{
return false;
}
}
/**
* Returns the a short id string. Used in the usage.
* \param val - value to be used.
*
*/
virtual std::string shortID(const std::string& val="val") const;
template<class T>
std::string MultiArg<T>::shortID(const std::string &val) const
{
static_cast<void>(val); // Ignore input, don't warn
return Arg::shortID(_typeDesc) + " ... ";
}
/**
* Returns the a long id string. Used in the usage.
* \param val - value to be used.
*
*/
virtual std::string longID(const std::string& val="val") const;
template<class T>
std::string MultiArg<T>::longID(const std::string &val) const
{
static_cast<void>(val); // Ignore input, don't warn
return Arg::longID(_typeDesc) + " (accepted multiple times)";
}
/**
* Once we've matched the first value, then the arg is no longer
* required.
*/
virtual bool isRequired() const;
virtual bool allowMore();
virtual void reset();
};
template<class T>
MultiArg<T>::MultiArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
Visitor* v)
: Arg( flag, name, desc, req, true, v ),
_typeDesc( typeDesc ),
_constraint( NULL ),
_allowMore(false)
{
_acceptsMultipleValues = true;
}
template<class T>
MultiArg<T>::MultiArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
CmdLineInterface& parser,
Visitor* v)
: Arg( flag, name, desc, req, true, v ),
_typeDesc( typeDesc ),
_constraint( NULL ),
_allowMore(false)
{
parser.add( this );
_acceptsMultipleValues = true;
}
/**
*
*/
template<class T>
MultiArg<T>::MultiArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
Visitor* v)
: Arg( flag, name, desc, req, true, v ),
_typeDesc( constraint->shortID() ),
_constraint( constraint ),
_allowMore(false)
{
_acceptsMultipleValues = true;
}
template<class T>
MultiArg<T>::MultiArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
CmdLineInterface& parser,
Visitor* v)
: Arg( flag, name, desc, req, true, v ),
_typeDesc( constraint->shortID() ),
_constraint( constraint ),
_allowMore(false)
{
parser.add( this );
_acceptsMultipleValues = true;
}
template<class T>
const std::vector<T>& MultiArg<T>::getValue() { return _values; }
template<class T>
bool MultiArg<T>::processArg(int *i, std::vector<std::string>& args)
{
if ( _ignoreable && Arg::ignoreRest() )
return false;
if ( _hasBlanks( args[*i] ) )
return false;
std::string flag = args[*i];
std::string value = "";
trimFlag( flag, value );
if ( argMatches( flag ) )
{
if ( Arg::delimiter() != ' ' && value == "" )
throw( ArgParseException(
"Couldn't find delimiter for this argument!",
toString() ) );
// always take the first one, regardless of start string
if ( value == "" )
template<class T>
bool MultiArg<T>::isRequired() const
{
if (_required)
{
(*i)++;
if ( static_cast<unsigned int>(*i) < args.size() )
_extractValue( args[*i] );
if (_values.size() > 1)
{
return false;
}
else
throw( ArgParseException("Missing a value for this argument!",
toString() ) );
}
{
return true;
}
}
else
_extractValue( value );
/*
// continuing taking the args until we hit one with a start string
while ( (unsigned int)(*i)+1 < args.size() &&
args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 &&
args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 )
_extractValue( args[++(*i)] );
*/
_alreadySet = true;
_checkWithVisitor();
return true;
{
return false;
}
}
else
return false;
}
/**
*
*/
template<class T>
std::string MultiArg<T>::shortID(const std::string& val) const
{
static_cast<void>(val); // Ignore input, don't warn
return Arg::shortID(_typeDesc) + " ... ";
}
/**
*
*/
template<class T>
std::string MultiArg<T>::longID(const std::string& val) const
{
static_cast<void>(val); // Ignore input, don't warn
return Arg::longID(_typeDesc) + " (accepted multiple times)";
}
/**
* Once we've matched the first value, then the arg is no longer
* required.
*/
template<class T>
bool MultiArg<T>::isRequired() const
{
if ( _required )
template<class T>
void MultiArg<T>::_extractValue(const std::string &val)
{
if ( _values.size() > 1 )
return false;
else
return true;
}
else
return false;
}
try
{
T tmp;
ExtractValue(tmp, val, typename ArgTraits<T>::ValueCategory());
_values.push_back(tmp);
}
catch (ArgParseException &e)
{
throw ArgParseException(e.error(), toString());
}
template<class T>
void MultiArg<T>::_extractValue( const std::string& val )
{
try {
T tmp;
ExtractValue(tmp, val, typename ArgTraits<T>::ValueCategory());
_values.push_back(tmp);
} catch( ArgParseException &e) {
throw ArgParseException(e.error(), toString());
}
if ( _constraint != NULL )
if ( ! _constraint->check( _values.back() ) )
throw( CmdLineParseException( "Value '" + val +
"' does not meet constraint: " +
_constraint->description(),
toString() ) );
}
template<class T>
bool MultiArg<T>::allowMore()
{
bool am = _allowMore;
_allowMore = true;
return am;
}
if (_constraint != NULL)
{
if (!_constraint->check(_values.back()))
{
throw (CmdLineParseException("Value '" + val + "' does not meet constraint: " +
_constraint->description(), toString()));
}
}
}
template<class T>
void MultiArg<T>::reset()
{
Arg::reset();
_values.clear();
}
template<class T>
bool MultiArg<T>::allowMore()
{
bool am = _allowMore;
_allowMore = true;
return am;
}
template<class T>
void MultiArg<T>::reset()
{
Arg::reset();
_values.clear();
}
} // namespace TCLAP
#endif

@ -1,5 +1,4 @@
/******************************************************************************
/******************************************************************************
*
* file: MultiSwitchArg.h
*
@ -30,187 +29,173 @@
#include <tclap/SwitchArg.h>
namespace TCLAP {
/**
* A multiple switch argument. If the switch is set on the command line, then
* the getValue method will return the number of times the switch appears.
*/
class MultiSwitchArg : public SwitchArg
namespace TCLAP
{
protected:
/**
* The value of the switch.
*/
int _value;
/**
* Used to support the reset() method so that ValueArg can be
* reset to their constructed value.
*/
int _default;
public:
/**
* MultiSwitchArg constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param init - Optional. The initial/default value of this Arg.
* Defaults to 0.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiSwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
int init = 0,
Visitor* v = NULL);
/**
* MultiSwitchArg constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param parser - A CmdLine parser object to add this Arg to
* \param init - Optional. The initial/default value of this Arg.
* Defaults to 0.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiSwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
CmdLineInterface& parser,
int init = 0,
Visitor* v = NULL);
/**
* Handles the processing of the argument.
* This re-implements the SwitchArg version of this method to set the
* _value of the argument appropriately.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed
* in from main().
*/
virtual bool processArg(int* i, std::vector<std::string>& args);
/**
* Returns int, the number of times the switch has been set.
*/
int getValue();
/**
* Returns the shortID for this Arg.
*/
std::string shortID(const std::string& val) const;
/**
* Returns the longID for this Arg.
*/
std::string longID(const std::string& val) const;
void reset();
};
//////////////////////////////////////////////////////////////////////
//BEGIN MultiSwitchArg.cpp
//////////////////////////////////////////////////////////////////////
inline MultiSwitchArg::MultiSwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
int init,
Visitor* v )
: SwitchArg(flag, name, desc, false, v),
_value( init ),
_default( init )
{ }
inline MultiSwitchArg::MultiSwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
CmdLineInterface& parser,
int init,
Visitor* v )
: SwitchArg(flag, name, desc, false, v),
_value( init ),
_default( init )
{
parser.add( this );
}
inline int MultiSwitchArg::getValue() { return _value; }
inline bool MultiSwitchArg::processArg(int *i, std::vector<std::string>& args)
{
if ( _ignoreable && Arg::ignoreRest() )
return false;
if ( argMatches( args[*i] ))
/**
* A multiple switch argument. If the switch is set on the command line, then
* the getValue method will return the number of times the switch appears.
*/
class MultiSwitchArg : public SwitchArg
{
// so the isSet() method will work
_alreadySet = true;
// Matched argument: increment value.
++_value;
protected:
/**
* The value of the switch.
*/
int _value;
/**
* Used to support the reset() method so that ValueArg can be
* reset to their constructed value.
*/
int _default;
public:
/**
* MultiSwitchArg constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param init - Optional. The initial/default value of this Arg.
* Defaults to 0.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiSwitchArg(const std::string &flag, const std::string &name, const std::string &desc,
int init = 0, Visitor *v = NULL);
/**
* MultiSwitchArg constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param parser - A CmdLine parser object to add this Arg to
* \param init - Optional. The initial/default value of this Arg.
* Defaults to 0.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiSwitchArg(const std::string &flag, const std::string &name, const std::string &desc,
CmdLineInterface &parser, int init = 0, Visitor *v = NULL);
/**
* Handles the processing of the argument.
* This re-implements the SwitchArg version of this method to set the
* _value of the argument appropriately.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed
* in from main().
*/
virtual bool processArg(int *i, std::vector<std::string> &args);
/**
* Returns int, the number of times the switch has been set.
*/
int getValue();
/**
* Returns the shortID for this Arg.
*/
std::string shortID(const std::string &val) const;
/**
* Returns the longID for this Arg.
*/
std::string longID(const std::string &val) const;
void reset();
};
//////////////////////////////////////////////////////////////////////
//BEGIN MultiSwitchArg.cpp
//////////////////////////////////////////////////////////////////////
inline MultiSwitchArg::MultiSwitchArg(const std::string &flag, const std::string &name,
const std::string &desc, int init, Visitor *v) :
SwitchArg(flag, name, desc, false, v), _value(init), _default(init)
{
}
_checkWithVisitor();
inline MultiSwitchArg::MultiSwitchArg(const std::string &flag, const std::string &name,
const std::string &desc, CmdLineInterface &parser, int init,
Visitor *v) :
SwitchArg(flag, name, desc, false, v), _value(init), _default(init)
{
parser.add(this);
}
return true;
inline int MultiSwitchArg::getValue()
{
return _value;
}
else if ( combinedSwitchesMatch( args[*i] ) )
inline bool MultiSwitchArg::processArg(int *i, std::vector<std::string> &args)
{
// so the isSet() method will work
_alreadySet = true;
if (_ignoreable && Arg::ignoreRest())
{
return false;
}
// Matched argument: increment value.
++_value;
if (argMatches(args[*i]))
{
// so the isSet() method will work
_alreadySet = true;
// Check for more in argument and increment value.
while ( combinedSwitchesMatch( args[*i] ) )
// Matched argument: increment value.
++_value;
_checkWithVisitor();
_checkWithVisitor();
return false;
}
else
return false;
}
return true;
}
else if (combinedSwitchesMatch(args[*i]))
{
// so the isSet() method will work
_alreadySet = true;
inline std::string
MultiSwitchArg::shortID(const std::string& val) const
{
return Arg::shortID(val) + " ... ";
}
// Matched argument: increment value.
++_value;
inline std::string
MultiSwitchArg::longID(const std::string& val) const
{
return Arg::longID(val) + " (accepted multiple times)";
}
// Check for more in argument and increment value.
while (combinedSwitchesMatch(args[*i]))
{
++_value;
}
inline void
MultiSwitchArg::reset()
{
MultiSwitchArg::_value = MultiSwitchArg::_default;
}
_checkWithVisitor();
//////////////////////////////////////////////////////////////////////
//END MultiSwitchArg.cpp
//////////////////////////////////////////////////////////////////////
return false;
}
else
{
return false;
}
}
inline std::string MultiSwitchArg::shortID(const std::string &val) const
{
return Arg::shortID(val) + " ... ";
}
inline std::string MultiSwitchArg::longID(const std::string &val) const
{
return Arg::longID(val) + " (accepted multiple times)";
}
inline void MultiSwitchArg::reset()
{
MultiSwitchArg::_value = MultiSwitchArg::_default;
}
//////////////////////////////////////////////////////////////////////
//END MultiSwitchArg.cpp
//////////////////////////////////////////////////////////////////////
} //namespace TCLAP
#endif

@ -1,24 +1,22 @@
/******************************************************************************
*
/******************************************************************************
*
* file: OptionalUnlabeledTracker.h
*
*
* Copyright (c) 2005, Michael E. Smoot .
* All rights reverved.
*
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* 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.
*
*****************************************************************************/
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef TCLAP_OPTIONAL_UNLABELED_TRACKER_H
@ -26,37 +24,45 @@
#include <string>
namespace TCLAP {
class OptionalUnlabeledTracker
{
public:
static void check( bool req, const std::string& argName );
static void gotOptional() { alreadyOptionalRef() = true; }
static bool& alreadyOptional() { return alreadyOptionalRef(); }
private:
static bool& alreadyOptionalRef() { static bool ct = false; return ct; }
};
inline void OptionalUnlabeledTracker::check( bool req, const std::string& argName )
namespace TCLAP
{
if ( OptionalUnlabeledTracker::alreadyOptional() )
throw( SpecificationException(
"You can't specify ANY Unlabeled Arg following an optional Unlabeled Arg",
argName ) );
if ( !req )
OptionalUnlabeledTracker::gotOptional();
}
class OptionalUnlabeledTracker
{
public:
static void check(bool req, const std::string &argName);
static void gotOptional()
{
alreadyOptionalRef() = true;
}
static bool& alreadyOptional()
{
return alreadyOptionalRef();
}
private:
static bool& alreadyOptionalRef()
{
static bool ct = false;
return ct;
}
};
inline void OptionalUnlabeledTracker::check(bool req, const std::string &argName)
{
if (OptionalUnlabeledTracker::alreadyOptional())
{
throw (SpecificationException(
"You can't specify ANY Unlabeled Arg following an optional Unlabeled Arg", argName));
}
if (!req)
{
OptionalUnlabeledTracker::gotOptional();
}
}
} // namespace TCLAP
#endif

@ -27,160 +27,174 @@
#define TCLAP_STANDARD_TRAITS_H
#ifdef HAVE_CONFIG_H
#include <config.h> // To check for long long
#include <config.h> // To check for long long
#endif
namespace TCLAP {
// ======================================================================
// Integer types
// ======================================================================
/**
* longs have value-like semantics.
*/
template<>
struct ArgTraits<long> {
typedef ValueLike ValueCategory;
};
/**
* ints have value-like semantics.
*/
template<>
struct ArgTraits<int> {
typedef ValueLike ValueCategory;
};
/**
* shorts have value-like semantics.
*/
template<>
struct ArgTraits<short> {
typedef ValueLike ValueCategory;
};
/**
* chars have value-like semantics.
*/
template<>
struct ArgTraits<char> {
typedef ValueLike ValueCategory;
};
namespace TCLAP
{
// ======================================================================
// Integer types
// ======================================================================
/**
* longs have value-like semantics.
*/
template<>
struct ArgTraits<long>
{
typedef ValueLike ValueCategory;
};
/**
* ints have value-like semantics.
*/
template<>
struct ArgTraits<int>
{
typedef ValueLike ValueCategory;
};
/**
* shorts have value-like semantics.
*/
template<>
struct ArgTraits<short>
{
typedef ValueLike ValueCategory;
};
/**
* chars have value-like semantics.
*/
template<>
struct ArgTraits<char>
{
typedef ValueLike ValueCategory;
};
#ifdef HAVE_LONG_LONG
/**
* long longs have value-like semantics.
*/
template<>
struct ArgTraits<long long> {
typedef ValueLike ValueCategory;
};
/**
* long longs have value-like semantics.
*/
template<>
struct ArgTraits<long long>
{
typedef ValueLike ValueCategory;
};
#endif
// ======================================================================
// Unsigned integer types
// ======================================================================
/**
* unsigned longs have value-like semantics.
*/
template<>
struct ArgTraits<unsigned long> {
typedef ValueLike ValueCategory;
};
/**
* unsigned ints have value-like semantics.
*/
template<>
struct ArgTraits<unsigned int> {
typedef ValueLike ValueCategory;
};
/**
* unsigned shorts have value-like semantics.
*/
template<>
struct ArgTraits<unsigned short> {
typedef ValueLike ValueCategory;
};
/**
* unsigned chars have value-like semantics.
*/
template<>
struct ArgTraits<unsigned char> {
typedef ValueLike ValueCategory;
};
// ======================================================================
// Unsigned integer types
// ======================================================================
/**
* unsigned longs have value-like semantics.
*/
template<>
struct ArgTraits<unsigned long>
{
typedef ValueLike ValueCategory;
};
/**
* unsigned ints have value-like semantics.
*/
template<>
struct ArgTraits<unsigned int>
{
typedef ValueLike ValueCategory;
};
/**
* unsigned shorts have value-like semantics.
*/
template<>
struct ArgTraits<unsigned short>
{
typedef ValueLike ValueCategory;
};
/**
* unsigned chars have value-like semantics.
*/
template<>
struct ArgTraits<unsigned char>
{
typedef ValueLike ValueCategory;
};
#ifdef HAVE_LONG_LONG
/**
* unsigned long longs have value-like semantics.
*/
template<>
struct ArgTraits<unsigned long long> {
typedef ValueLike ValueCategory;
};
#endif
/**
* unsigned long longs have value-like semantics.
*/
template<>
struct ArgTraits<unsigned long long>
{
typedef ValueLike ValueCategory;
};
// ======================================================================
// Float types
// ======================================================================
/**
* floats have value-like semantics.
*/
template<>
struct ArgTraits<float> {
typedef ValueLike ValueCategory;
};
/**
* doubles have value-like semantics.
*/
template<>
struct ArgTraits<double> {
typedef ValueLike ValueCategory;
};
// ======================================================================
// Other types
// ======================================================================
/**
* bools have value-like semantics.
*/
template<>
struct ArgTraits<bool> {
typedef ValueLike ValueCategory;
};
/**
* wchar_ts have value-like semantics.
*/
/*
template<>
struct ArgTraits<wchar_t> {
typedef ValueLike ValueCategory;
};
*/
/**
* Strings have string like argument traits.
*/
template<>
struct ArgTraits<std::string> {
typedef StringLike ValueCategory;
};
template<typename T>
void SetString(T &dst, const std::string &src)
{
dst = src;
}
#endif
// ======================================================================
// Float types
// ======================================================================
/**
* floats have value-like semantics.
*/
template<>
struct ArgTraits<float>
{
typedef ValueLike ValueCategory;
};
/**
* doubles have value-like semantics.
*/
template<>
struct ArgTraits<double>
{
typedef ValueLike ValueCategory;
};
// ======================================================================
// Other types
// ======================================================================
/**
* bools have value-like semantics.
*/
template<>
struct ArgTraits<bool>
{
typedef ValueLike ValueCategory;
};
/**
* wchar_ts have value-like semantics.
*/
/*
template<>
struct ArgTraits<wchar_t> {
typedef ValueLike ValueCategory;
};
*/
/**
* Strings have string like argument traits.
*/
template<>
struct ArgTraits<std::string>
{
typedef StringLike ValueCategory;
};
template<typename T>
void SetString(T &dst, const std::string &src)
{
dst = src;
}
} // namespace
#endif

@ -1,24 +1,24 @@
// -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*-
/******************************************************************************
*
/******************************************************************************
*
* file: StdOutput.h
*
*
* Copyright (c) 2004, Michael E. Smoot
* All rights reverved.
*
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* 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.
*
*****************************************************************************/
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef TCLAP_STDCMDLINEOUTPUT_H
#define TCLAP_STDCMDLINEOUTPUT_H
@ -34,265 +34,275 @@
#include <tclap/XorHandler.h>
#include <tclap/Arg.h>
namespace TCLAP {
/**
* A class that isolates any output from the CmdLine object so that it
* may be easily modified.
*/
class StdOutput : public CmdLineOutput
{
public:
/**
* Prints the usage to stdout. Can be overridden to
* produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void usage(CmdLineInterface& c);
/**
* Prints the version to stdout. Can be overridden
* to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void version(CmdLineInterface& c);
/**
* Prints (to stderr) an error message, short usage
* Can be overridden to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure.
*/
virtual void failure(CmdLineInterface& c,
ArgException& e );
protected:
/**
* Writes a brief usage message with short args.
* \param c - The CmdLine object the output is generated for.
* \param os - The stream to write the message to.
*/
void _shortUsage( CmdLineInterface& c, std::ostream& os ) const;
/**
* Writes a longer usage message with long and short args,
* provides descriptions and prints message.
* \param c - The CmdLine object the output is generated for.
* \param os - The stream to write the message to.
*/
void _longUsage( CmdLineInterface& c, std::ostream& os ) const;
/**
* This function inserts line breaks and indents long strings
* according the params input. It will only break lines at spaces,
* commas and pipes.
* \param os - The stream to be printed to.
* \param s - The string to be printed.
* \param maxWidth - The maxWidth allowed for the output line.
* \param indentSpaces - The number of spaces to indent the first line.
* \param secondLineOffset - The number of spaces to indent the second
* and all subsequent lines in addition to indentSpaces.
*/
void spacePrint( std::ostream& os,
const std::string& s,
int maxWidth,
int indentSpaces,
int secondLineOffset ) const;
};
inline void StdOutput::version(CmdLineInterface& _cmd)
{
std::string progName = _cmd.getProgramName();
std::string version = _cmd.getVersion();
std::cout << std::endl << progName << " version: "
<< version << std::endl << std::endl;
}
inline void StdOutput::usage(CmdLineInterface& _cmd )
namespace TCLAP
{
std::cout << std::endl << "USAGE: " << std::endl << std::endl;
_shortUsage( _cmd, std::cout );
std::cout << std::endl << std::endl << "Where: " << std::endl << std::endl;
_longUsage( _cmd, std::cout );
std::cout << std::endl;
}
inline void StdOutput::failure( CmdLineInterface& _cmd,
ArgException& e )
{
std::string progName = _cmd.getProgramName();
std::cerr << "PARSE ERROR: " << e.argId() << std::endl
<< " " << e.error() << std::endl << std::endl;
if ( _cmd.hasHelpAndVersion() )
/**
* A class that isolates any output from the CmdLine object so that it
* may be easily modified.
*/
class StdOutput : public CmdLineOutput
{
public:
/**
* Prints the usage to stdout. Can be overridden to
* produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void usage(CmdLineInterface &c);
/**
* Prints the version to stdout. Can be overridden
* to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void version(CmdLineInterface &c);
/**
* Prints (to stderr) an error message, short usage
* Can be overridden to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure.
*/
virtual void failure(CmdLineInterface &c, ArgException &e);
protected:
/**
* Writes a brief usage message with short args.
* \param c - The CmdLine object the output is generated for.
* \param os - The stream to write the message to.
*/
void _shortUsage(CmdLineInterface &c, std::ostream &os) const;
/**
* Writes a longer usage message with long and short args,
* provides descriptions and prints message.
* \param c - The CmdLine object the output is generated for.
* \param os - The stream to write the message to.
*/
void _longUsage(CmdLineInterface &c, std::ostream &os) const;
/**
* This function inserts line breaks and indents long strings
* according the params input. It will only break lines at spaces,
* commas and pipes.
* \param os - The stream to be printed to.
* \param s - The string to be printed.
* \param maxWidth - The maxWidth allowed for the output line.
* \param indentSpaces - The number of spaces to indent the first line.
* \param secondLineOffset - The number of spaces to indent the second
* and all subsequent lines in addition to indentSpaces.
*/
void spacePrint(std::ostream &os, const std::string &s, int maxWidth, int indentSpaces,
int secondLineOffset) const;
};
inline void StdOutput::version(CmdLineInterface &_cmd)
{
std::string progName = _cmd.getProgramName();
std::string version = _cmd.getVersion();
std::cout << std::endl << progName << " version: " << version << std::endl << std::endl;
}
inline void StdOutput::usage(CmdLineInterface &_cmd)
{
std::cout << std::endl << "USAGE: " << std::endl << std::endl;
_shortUsage(_cmd, std::cout);
std::cout << std::endl << std::endl << "Where: " << std::endl << std::endl;
_longUsage(_cmd, std::cout);
std::cout << std::endl;
}
inline void StdOutput::failure(CmdLineInterface &_cmd, ArgException &e)
{
std::string progName = _cmd.getProgramName();
std::cerr << "PARSE ERROR: " << e.argId() << std::endl << " " << e.error() <<
std::endl << std::endl;
if (_cmd.hasHelpAndVersion())
{
std::cerr << "Brief USAGE: " << std::endl;
_shortUsage( _cmd, std::cerr );
_shortUsage(_cmd, std::cerr);
std::cerr << std::endl << "For complete USAGE and HELP type: "
<< std::endl << " " << progName << " --help"
<< std::endl << std::endl;
std::cerr << std::endl << "For complete USAGE and HELP type: " << std::endl << " " <<
progName << " --help" << std::endl << std::endl;
}
else
{
usage(_cmd);
}
else
usage(_cmd);
throw ExitException(1);
}
throw ExitException(1);
}
inline void
StdOutput::_shortUsage( CmdLineInterface& _cmd,
std::ostream& os ) const
{
std::list<Arg*> argList = _cmd.getArgList();
std::string progName = _cmd.getProgramName();
XorHandler xorHandler = _cmd.getXorHandler();
std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList();
inline void StdOutput::_shortUsage(CmdLineInterface &_cmd, std::ostream &os) const
{
std::list<Arg*> argList = _cmd.getArgList();
std::string progName = _cmd.getProgramName();
XorHandler xorHandler = _cmd.getXorHandler();
std::vector<std::vector<Arg*>> xorList = xorHandler.getXorList();
std::string s = progName + " ";
std::string s = progName + " ";
// first the xor
for ( int i = 0; static_cast<unsigned int>(i) < xorList.size(); i++ )
// first the xor
for (int i = 0; static_cast<unsigned int>(i) < xorList.size(); i++)
{
s += " {";
for ( ArgVectorIterator it = xorList[i].begin();
it != xorList[i].end(); it++ )
for (ArgVectorIterator it = xorList[i].begin();
it != xorList[i].end(); it++)
{
s += (*it)->shortID() + "|";
}
s[s.length()-1] = '}';
s[s.length() - 1] = '}';
}
// then the rest
for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
if ( !xorHandler.contains( (*it) ) )
s += " " + (*it)->shortID();
// then the rest
for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
{
if (!xorHandler.contains((*it)))
{
s += " " + (*it)->shortID();
}
}
// if the program name is too long, then adjust the second line offset
int secondLineOffset = static_cast<int>(progName.length()) + 2;
if ( secondLineOffset > 75/2 )
secondLineOffset = static_cast<int>(75/2);
// if the program name is too long, then adjust the second line offset
int secondLineOffset = static_cast<int>(progName.length()) + 2;
if (secondLineOffset > 75 / 2)
{
secondLineOffset = static_cast<int>(75 / 2);
}
spacePrint( os, s, 75, 3, secondLineOffset );
}
spacePrint(os, s, 75, 3, secondLineOffset);
}
inline void
StdOutput::_longUsage( CmdLineInterface& _cmd,
std::ostream& os ) const
{
std::list<Arg*> argList = _cmd.getArgList();
std::string message = _cmd.getMessage();
XorHandler xorHandler = _cmd.getXorHandler();
std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList();
inline void StdOutput::_longUsage(CmdLineInterface &_cmd, std::ostream &os) const
{
std::list<Arg*> argList = _cmd.getArgList();
std::string message = _cmd.getMessage();
XorHandler xorHandler = _cmd.getXorHandler();
std::vector<std::vector<Arg*>> xorList = xorHandler.getXorList();
// first the xor
for ( int i = 0; static_cast<unsigned int>(i) < xorList.size(); i++ )
// first the xor
for (int i = 0; static_cast<unsigned int>(i) < xorList.size(); i++)
{
for ( ArgVectorIterator it = xorList[i].begin();
it != xorList[i].end();
it++ )
{
spacePrint( os, (*it)->longID(), 75, 3, 3 );
spacePrint( os, (*it)->getDescription(), 75, 5, 0 );
for (ArgVectorIterator it = xorList[i].begin();
it != xorList[i].end();
it++)
{
spacePrint(os, (*it)->longID(), 75, 3, 3);
spacePrint(os, (*it)->getDescription(), 75, 5, 0);
if ( it+1 != xorList[i].end() )
spacePrint(os, "-- OR --", 75, 9, 0);
if (it + 1 != xorList[i].end())
{
spacePrint(os, "-- OR --", 75, 9, 0);
}
}
os << std::endl << std::endl;
}
// then the rest
for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
if ( !xorHandler.contains( (*it) ) )
// then the rest
for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
{
if (!xorHandler.contains((*it)))
{
spacePrint( os, (*it)->longID(), 75, 3, 3 );
spacePrint( os, (*it)->getDescription(), 75, 5, 0 );
spacePrint(os, (*it)->longID(), 75, 3, 3);
spacePrint(os, (*it)->getDescription(), 75, 5, 0);
os << std::endl;
}
}
os << std::endl;
os << std::endl;
spacePrint( os, message, 75, 3, 0 );
}
spacePrint(os, message, 75, 3, 0);
}
inline void StdOutput::spacePrint( std::ostream& os,
const std::string& s,
int maxWidth,
int indentSpaces,
int secondLineOffset ) const
{
int len = static_cast<int>(s.length());
inline void StdOutput::spacePrint(std::ostream &os, const std::string &s, int maxWidth,
int indentSpaces, int secondLineOffset) const
{
int len = static_cast<int>(s.length());
if ( (len + indentSpaces > maxWidth) && maxWidth > 0 )
if ((len + indentSpaces > maxWidth) && maxWidth > 0)
{
int allowedLen = maxWidth - indentSpaces;
int start = 0;
while ( start < len )
int start = 0;
while (start < len)
{
// find the substring length
// int stringLen = std::min<int>( len - start, allowedLen );
// doing it this way to support a VisualC++ 2005 bug
using namespace std;
int stringLen = min<int>(len - start, allowedLen);
// trim the length so it doesn't end in middle of a word
if (stringLen == allowedLen)
{
while (stringLen >= 0 &&
s[stringLen + start] != ' ' &&
s[stringLen + start] != ',' &&
s[stringLen + start] != '|')
{
stringLen--;
}
}
// ok, the word is longer than the line, so just split
// wherever the line ends
if (stringLen <= 0)
{
stringLen = allowedLen;
}
// check for newlines
for (int i = 0; i < stringLen; i++)
{
if (s[start + i] == '\n')
{
stringLen = i + 1;
}
}
// print the indent
for (int i = 0; i < indentSpaces; i++)
{
// find the substring length
// int stringLen = std::min<int>( len - start, allowedLen );
// doing it this way to support a VisualC++ 2005 bug
using namespace std;
int stringLen = min<int>( len - start, allowedLen );
// trim the length so it doesn't end in middle of a word
if ( stringLen == allowedLen )
while ( stringLen >= 0 &&
s[stringLen+start] != ' ' &&
s[stringLen+start] != ',' &&
s[stringLen+start] != '|' )
stringLen--;
// ok, the word is longer than the line, so just split
// wherever the line ends
if ( stringLen <= 0 )
stringLen = allowedLen;
// check for newlines
for ( int i = 0; i < stringLen; i++ )
if ( s[start+i] == '\n' )
stringLen = i+1;
// print the indent
for ( int i = 0; i < indentSpaces; i++ )
os << " ";
if ( start == 0 )
{
// handle second line offsets
indentSpaces += secondLineOffset;
// adjust allowed len
allowedLen -= secondLineOffset;
}
os << s.substr(start,stringLen) << std::endl;
// so we don't start a line with a space
while ( s[stringLen+start] == ' ' && start < len )
start++;
start += stringLen;
os << " ";
}
if (start == 0)
{
// handle second line offsets
indentSpaces += secondLineOffset;
// adjust allowed len
allowedLen -= secondLineOffset;
}
os << s.substr(start, stringLen) << std::endl;
// so we don't start a line with a space
while (s[stringLen + start] == ' ' && start < len)
{
start++;
}
start += stringLen;
}
}
else
else
{
for ( int i = 0; i < indentSpaces; i++ )
for (int i = 0; i < indentSpaces; i++)
{
os << " ";
}
os << s << std::endl;
}
}
}
} //namespace TCLAP
#endif
#endif

@ -1,24 +1,23 @@
/******************************************************************************
*
/******************************************************************************
*
* file: SwitchArg.h
*
*
* Copyright (c) 2003, Michael E. Smoot .
* Copyright (c) 2004, Michael E. Smoot, Daniel Aarno.
* All rights reverved.
*
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* 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.
*
*****************************************************************************/
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef TCLAP_SWITCH_ARG_H
@ -29,200 +28,202 @@
#include <tclap/Arg.h>
namespace TCLAP {
/**
* A simple switch argument. If the switch is set on the command line, then
* the getValue method will return the opposite of the default value for the
* switch.
*/
class SwitchArg : public Arg
{
protected:
/**
* The value of the switch.
*/
bool _value;
/**
* Used to support the reset() method so that ValueArg can be
* reset to their constructed value.
*/
bool _default;
public:
/**
* SwitchArg constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param def - The default value for this Switch.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
SwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool def = false,
Visitor* v = NULL);
/**
* SwitchArg constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param parser - A CmdLine parser object to add this Arg to
* \param def - The default value for this Switch.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
SwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
CmdLineInterface& parser,
bool def = false,
Visitor* v = NULL);
/**
* Handles the processing of the argument.
* This re-implements the Arg version of this method to set the
* _value of the argument appropriately.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed
* in from main().
*/
virtual bool processArg(int* i, std::vector<std::string>& args);
/**
* Checks a string to see if any of the chars in the string
* match the flag for this Switch.
*/
bool combinedSwitchesMatch(std::string& combined);
/**
* Returns bool, whether or not the switch has been set.
*/
bool getValue();
virtual void reset();
};
//////////////////////////////////////////////////////////////////////
//BEGIN SwitchArg.cpp
//////////////////////////////////////////////////////////////////////
inline SwitchArg::SwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool default_val,
Visitor* v )
: Arg(flag, name, desc, false, false, v),
_value( default_val ),
_default( default_val )
{ }
inline SwitchArg::SwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
CmdLineInterface& parser,
bool default_val,
Visitor* v )
: Arg(flag, name, desc, false, false, v),
_value( default_val ),
_default(default_val)
{
parser.add( this );
}
inline bool SwitchArg::getValue() { return _value; }
inline bool SwitchArg::combinedSwitchesMatch(std::string& combinedSwitches )
namespace TCLAP
{
// make sure this is actually a combined switch
if ( combinedSwitches.length() > 0 &&
combinedSwitches[0] != Arg::flagStartString()[0] )
return false;
/**
* A simple switch argument. If the switch is set on the command line, then
* the getValue method will return the opposite of the default value for the
* switch.
*/
class SwitchArg : public Arg
{
protected:
/**
* The value of the switch.
*/
bool _value;
/**
* Used to support the reset() method so that ValueArg can be
* reset to their constructed value.
*/
bool _default;
public:
/**
* SwitchArg constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param def - The default value for this Switch.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
SwitchArg(const std::string &flag, const std::string &name, const std::string &desc,
bool def = false, Visitor *v = NULL);
/**
* SwitchArg constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param parser - A CmdLine parser object to add this Arg to
* \param def - The default value for this Switch.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
SwitchArg(const std::string &flag, const std::string &name, const std::string &desc,
CmdLineInterface &parser, bool def = false, Visitor *v = NULL);
/**
* Handles the processing of the argument.
* This re-implements the Arg version of this method to set the
* _value of the argument appropriately.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed
* in from main().
*/
virtual bool processArg(int *i, std::vector<std::string> &args);
/**
* Checks a string to see if any of the chars in the string
* match the flag for this Switch.
*/
bool combinedSwitchesMatch(std::string &combined);
/**
* Returns bool, whether or not the switch has been set.
*/
bool getValue();
virtual void reset();
};
//////////////////////////////////////////////////////////////////////
//BEGIN SwitchArg.cpp
//////////////////////////////////////////////////////////////////////
inline SwitchArg::SwitchArg(const std::string &flag, const std::string &name,
const std::string &desc, bool default_val, Visitor *v) :
Arg(flag, name, desc, false, false, v), _value(default_val), _default(default_val)
{
}
// make sure it isn't a long name
if ( combinedSwitches.substr( 0, Arg::nameStartString().length() ) ==
Arg::nameStartString() )
return false;
inline SwitchArg::SwitchArg(const std::string &flag, const std::string &name,
const std::string &desc, CmdLineInterface &parser, bool default_val,
Visitor *v) :
Arg(flag, name, desc, false, false, v), _value(default_val), _default(default_val)
{
parser.add(this);
}
// make sure the delimiter isn't in the string
if ( combinedSwitches.find_first_of( Arg::delimiter() ) != std::string::npos )
return false;
inline bool SwitchArg::getValue()
{
return _value;
}
// ok, we're not specifying a ValueArg, so we know that we have
// a combined switch list.
for ( unsigned int i = 1; i < combinedSwitches.length(); i++ )
if ( _flag.length() > 0 &&
combinedSwitches[i] == _flag[0] &&
_flag[0] != Arg::flagStartString()[0] )
inline bool SwitchArg::combinedSwitchesMatch(std::string &combinedSwitches)
{
// make sure this is actually a combined switch
if (combinedSwitches.length() > 0 &&
combinedSwitches[0] != Arg::flagStartString()[0])
{
// update the combined switches so this one is no longer present
// this is necessary so that no unlabeled args are matched
// later in the processing.
//combinedSwitches.erase(i,1);
combinedSwitches[i] = Arg::blankChar();
return true;
return false;
}
// none of the switches passed in the list match.
return false;
}
// make sure it isn't a long name
if (combinedSwitches.substr(0, Arg::nameStartString().length()) == Arg::nameStartString())
{
return false;
}
// make sure the delimiter isn't in the string
if (combinedSwitches.find_first_of(Arg::delimiter()) != std::string::npos)
{
return false;
}
inline bool SwitchArg::processArg(int *i, std::vector<std::string>& args)
{
if ( _ignoreable && Arg::ignoreRest() )
// ok, we're not specifying a ValueArg, so we know that we have
// a combined switch list.
for (unsigned int i = 1; i < combinedSwitches.length(); i++)
{
if (_flag.length() > 0 &&
combinedSwitches[i] == _flag[0] &&
_flag[0] != Arg::flagStartString()[0])
{
// update the combined switches so this one is no longer present
// this is necessary so that no unlabeled args are matched
// later in the processing.
//combinedSwitches.erase(i,1);
combinedSwitches[i] = Arg::blankChar();
return true;
}
}
// none of the switches passed in the list match.
return false;
}
if ( argMatches( args[*i] ) || combinedSwitchesMatch( args[*i] ) )
inline bool SwitchArg::processArg(int *i, std::vector<std::string> &args)
{
// If we match on a combined switch, then we want to return false
// so that other switches in the combination will also have a
// chance to match.
bool ret = false;
if ( argMatches( args[*i] ) )
ret = true;
if ( _alreadySet || ( !ret && combinedSwitchesMatch( args[*i] ) ) )
throw(CmdLineParseException("Argument already set!", toString()));
_alreadySet = true;
if (_ignoreable && Arg::ignoreRest())
{
return false;
}
if ( _value == true )
_value = false;
if (argMatches(args[*i]) || combinedSwitchesMatch(args[*i]))
{
// If we match on a combined switch, then we want to return false
// so that other switches in the combination will also have a
// chance to match.
bool ret = false;
if (argMatches(args[*i]))
{
ret = true;
}
if (_alreadySet || (!ret && combinedSwitchesMatch(args[*i])))
{
throw (CmdLineParseException("Argument already set!", toString()));
}
_alreadySet = true;
if (_value == true)
{
_value = false;
}
else
{
_value = true;
}
_checkWithVisitor();
return ret;
}
else
_value = true;
_checkWithVisitor();
return ret;
{
return false;
}
}
else
return false;
}
inline void SwitchArg::reset()
{
Arg::reset();
_value = _default;
}
//////////////////////////////////////////////////////////////////////
//End SwitchArg.cpp
//////////////////////////////////////////////////////////////////////
inline void SwitchArg::reset()
{
Arg::reset();
_value = _default;
}
//////////////////////////////////////////////////////////////////////
//End SwitchArg.cpp
//////////////////////////////////////////////////////////////////////
} //namespace TCLAP
#endif

@ -1,23 +1,22 @@
/******************************************************************************
*
/******************************************************************************
*
* file: UnlabeledMultiArg.h
*
*
* Copyright (c) 2003, Michael E. Smoot.
* All rights reverved.
*
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* 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.
*
*****************************************************************************/
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef TCLAP_MULTIPLE_UNLABELED_ARGUMENT_H
@ -29,273 +28,243 @@
#include <tclap/MultiArg.h>
#include <tclap/OptionalUnlabeledTracker.h>
namespace TCLAP {
/**
* Just like a MultiArg, except that the arguments are unlabeled. Basically,
* this Arg will slurp up everything that hasn't been matched to another
* Arg.
*/
template<class T>
class UnlabeledMultiArg : public MultiArg<T>
{
// If compiler has two stage name lookup (as gcc >= 3.4 does)
// this is requried to prevent undef. symbols
using MultiArg<T>::_ignoreable;
using MultiArg<T>::_hasBlanks;
using MultiArg<T>::_extractValue;
using MultiArg<T>::_typeDesc;
using MultiArg<T>::_name;
using MultiArg<T>::_description;
using MultiArg<T>::_alreadySet;
using MultiArg<T>::toString;
public:
/**
* Constructor.
* \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
UnlabeledMultiArg( const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
bool ignoreable = false,
Visitor* v = NULL );
/**
* Constructor.
* \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param parser - A CmdLine parser object to add this Arg to
* \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
UnlabeledMultiArg( const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
CmdLineInterface& parser,
bool ignoreable = false,
Visitor* v = NULL );
/**
* Constructor.
* \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
UnlabeledMultiArg( const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
bool ignoreable = false,
Visitor* v = NULL );
/**
* Constructor.
* \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param parser - A CmdLine parser object to add this Arg to
* \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
UnlabeledMultiArg( const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
CmdLineInterface& parser,
bool ignoreable = false,
Visitor* v = NULL );
/**
* Handles the processing of the argument.
* This re-implements the Arg version of this method to set the
* _value of the argument appropriately. It knows the difference
* between labeled and unlabeled.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed from main().
*/
virtual bool processArg(int* i, std::vector<std::string>& args);
/**
* Returns the a short id string. Used in the usage.
* \param val - value to be used.
*/
virtual std::string shortID(const std::string& val="val") const;
/**
* Returns the a long id string. Used in the usage.
* \param val - value to be used.
*/
virtual std::string longID(const std::string& val="val") const;
/**
* Opertor ==.
* \param a - The Arg to be compared to this.
*/
virtual bool operator==(const Arg& a) const;
/**
* Pushes this to back of list rather than front.
* \param argList - The list this should be added to.
*/
virtual void addToList( std::list<Arg*>& argList ) const;
};
template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
bool ignoreable,
Visitor* v)
: MultiArg<T>("", name, desc, req, typeDesc, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString());
}
template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
CmdLineInterface& parser,
bool ignoreable,
Visitor* v)
: MultiArg<T>("", name, desc, req, typeDesc, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString());
parser.add( this );
}
template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
bool ignoreable,
Visitor* v)
: MultiArg<T>("", name, desc, req, constraint, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString());
}
template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
CmdLineInterface& parser,
bool ignoreable,
Visitor* v)
: MultiArg<T>("", name, desc, req, constraint, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString());
parser.add( this );
}
template<class T>
bool UnlabeledMultiArg<T>::processArg(int *i, std::vector<std::string>& args)
namespace TCLAP
{
/**
* Just like a MultiArg, except that the arguments are unlabeled. Basically,
* this Arg will slurp up everything that hasn't been matched to another
* Arg.
*/
template<class T>
class UnlabeledMultiArg : public MultiArg<T>
{
// If compiler has two stage name lookup (as gcc >= 3.4 does)
// this is requried to prevent undef. symbols
using MultiArg<T>::_ignoreable;
using MultiArg<T>::_hasBlanks;
using MultiArg<T>::_extractValue;
using MultiArg<T>::_typeDesc;
using MultiArg<T>::_name;
using MultiArg<T>::_description;
using MultiArg<T>::_alreadySet;
using MultiArg<T>::toString;
public:
/**
* Constructor.
* \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
UnlabeledMultiArg(const std::string &name, const std::string &desc, bool req,
const std::string &typeDesc, bool ignoreable = false, Visitor *v = NULL);
/**
* Constructor.
* \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param parser - A CmdLine parser object to add this Arg to
* \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
UnlabeledMultiArg(const std::string &name, const std::string &desc, bool req,
const std::string &typeDesc, CmdLineInterface &parser,
bool ignoreable = false, Visitor *v = NULL);
/**
* Constructor.
* \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
UnlabeledMultiArg(const std::string &name, const std::string &desc, bool req,
Constraint<T> *constraint, bool ignoreable = false, Visitor *v = NULL);
/**
* Constructor.
* \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param parser - A CmdLine parser object to add this Arg to
* \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
UnlabeledMultiArg(const std::string &name, const std::string &desc, bool req,
Constraint<T> *constraint, CmdLineInterface &parser,
bool ignoreable = false, Visitor *v = NULL);
/**
* Handles the processing of the argument.
* This re-implements the Arg version of this method to set the
* _value of the argument appropriately. It knows the difference
* between labeled and unlabeled.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed from main().
*/
virtual bool processArg(int *i, std::vector<std::string> &args);
/**
* Returns the a short id string. Used in the usage.
* \param val - value to be used.
*/
virtual std::string shortID(const std::string &val = "val") const;
/**
* Returns the a long id string. Used in the usage.
* \param val - value to be used.
*/
virtual std::string longID(const std::string &val = "val") const;
/**
* Opertor ==.
* \param a - The Arg to be compared to this.
*/
virtual bool operator==(const Arg &a) const;
/**
* Pushes this to back of list rather than front.
* \param argList - The list this should be added to.
*/
virtual void addToList(std::list<Arg*> &argList) const;
};
template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string &name, const std::string &desc,
bool req, const std::string &typeDesc, bool ignoreable,
Visitor *v) :
MultiArg<T>("", name, desc, req, typeDesc, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString());
}
template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string &name, const std::string &desc,
bool req, const std::string &typeDesc,
CmdLineInterface &parser, bool ignoreable, Visitor *v) :
MultiArg<T>("", name, desc, req, typeDesc, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString());
parser.add(this);
}
template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string &name, const std::string &desc,
bool req, Constraint<T> *constraint, bool ignoreable,
Visitor *v) :
MultiArg<T>("", name, desc, req, constraint, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString());
}
template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string &name, const std::string &desc,
bool req, Constraint<T> *constraint,
CmdLineInterface &parser, bool ignoreable, Visitor *v) :
MultiArg<T>("", name, desc, req, constraint, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString());
parser.add(this);
}
template<class T>
bool UnlabeledMultiArg<T>::processArg(int *i, std::vector<std::string> &args)
{
if (_hasBlanks(args[*i]))
{
return false;
}
// never ignore an unlabeled multi arg
// always take the first value, regardless of the start string
_extractValue(args[(*i)]);
/*
// continue taking args until we hit the end or a start string
while ( (unsigned int)(*i)+1 < args.size() &&
args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 &&
args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 )
_extractValue( args[++(*i)] );
*/
_alreadySet = true;
if ( _hasBlanks( args[*i] ) )
return false;
// never ignore an unlabeled multi arg
// always take the first value, regardless of the start string
_extractValue( args[(*i)] );
/*
// continue taking args until we hit the end or a start string
while ( (unsigned int)(*i)+1 < args.size() &&
args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 &&
args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 )
_extractValue( args[++(*i)] );
*/
_alreadySet = true;
return true;
}
template<class T>
std::string UnlabeledMultiArg<T>::shortID(const std::string& val) const
{
static_cast<void>(val); // Ignore input, don't warn
return std::string("<") + _typeDesc + "> ...";
}
template<class T>
std::string UnlabeledMultiArg<T>::longID(const std::string& val) const
{
static_cast<void>(val); // Ignore input, don't warn
return std::string("<") + _typeDesc + "> (accepted multiple times)";
}
template<class T>
bool UnlabeledMultiArg<T>::operator==(const Arg& a) const
{
if ( _name == a.getName() || _description == a.getDescription() )
return true;
else
return false;
}
template<class T>
void UnlabeledMultiArg<T>::addToList( std::list<Arg*>& argList ) const
{
argList.push_back( const_cast<Arg*>(static_cast<const Arg* const>(this)) );
}
}
template<class T>
std::string UnlabeledMultiArg<T>::shortID(const std::string &val) const
{
static_cast<void>(val); // Ignore input, don't warn
return std::string("<") + _typeDesc + "> ...";
}
template<class T>
std::string UnlabeledMultiArg<T>::longID(const std::string &val) const
{
static_cast<void>(val); // Ignore input, don't warn
return std::string("<") + _typeDesc + "> (accepted multiple times)";
}
template<class T>
bool UnlabeledMultiArg<T>::operator==(const Arg &a) const
{
if (_name == a.getName() || _description == a.getDescription())
{
return true;
}
else
{
return false;
}
}
template<class T>
void UnlabeledMultiArg<T>::addToList(std::list<Arg*> &argList) const
{
argList.push_back(const_cast<Arg*>(static_cast<const Arg*const>(this)));
}
}
#endif

@ -1,24 +1,23 @@
/******************************************************************************
*
/******************************************************************************
*
* file: UnlabeledValueArg.h
*
*
* Copyright (c) 2003, Michael E. Smoot .
* Copyright (c) 2004, Michael E. Smoot, Daniel Aarno.
* All rights reverved.
*
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* 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.
*
*****************************************************************************/
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef TCLAP_UNLABELED_VALUE_ARGUMENT_H
@ -31,310 +30,275 @@
#include <tclap/OptionalUnlabeledTracker.h>
namespace TCLAP {
/**
* The basic unlabeled argument that parses a value.
* This is a template class, which means the type T defines the type
* that a given object will attempt to parse when an UnlabeledValueArg
* is reached in the list of args that the CmdLine iterates over.
*/
template<class T>
class UnlabeledValueArg : public ValueArg<T>
namespace TCLAP
{
// If compiler has two stage name lookup (as gcc >= 3.4 does)
// this is requried to prevent undef. symbols
using ValueArg<T>::_ignoreable;
using ValueArg<T>::_hasBlanks;
using ValueArg<T>::_extractValue;
using ValueArg<T>::_typeDesc;
using ValueArg<T>::_name;
using ValueArg<T>::_description;
using ValueArg<T>::_alreadySet;
using ValueArg<T>::toString;
public:
/**
* UnlabeledValueArg constructor.
* \param name - A one word name for the argument. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param ignoreable - Allows you to specify that this argument can be
* ignored if the '--' flag is set. This defaults to false (cannot
* be ignored) and should generally stay that way unless you have
* some special need for certain arguments to be ignored.
* \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason.
*/
UnlabeledValueArg( const std::string& name,
const std::string& desc,
bool req,
T value,
const std::string& typeDesc,
bool ignoreable = false,
Visitor* v = NULL);
/**
* UnlabeledValueArg constructor.
* \param name - A one word name for the argument. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param parser - A CmdLine parser object to add this Arg to
* \param ignoreable - Allows you to specify that this argument can be
* ignored if the '--' flag is set. This defaults to false (cannot
* be ignored) and should generally stay that way unless you have
* some special need for certain arguments to be ignored.
* \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason.
*/
UnlabeledValueArg( const std::string& name,
const std::string& desc,
bool req,
T value,
const std::string& typeDesc,
CmdLineInterface& parser,
bool ignoreable = false,
Visitor* v = NULL );
/**
* UnlabeledValueArg constructor.
* \param name - A one word name for the argument. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param ignoreable - Allows you to specify that this argument can be
* ignored if the '--' flag is set. This defaults to false (cannot
* be ignored) and should generally stay that way unless you have
* some special need for certain arguments to be ignored.
* \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason.
*/
UnlabeledValueArg( const std::string& name,
const std::string& desc,
bool req,
T value,
Constraint<T>* constraint,
bool ignoreable = false,
Visitor* v = NULL );
/**
* UnlabeledValueArg constructor.
* \param name - A one word name for the argument. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param parser - A CmdLine parser object to add this Arg to
* \param ignoreable - Allows you to specify that this argument can be
* ignored if the '--' flag is set. This defaults to false (cannot
* be ignored) and should generally stay that way unless you have
* some special need for certain arguments to be ignored.
* \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason.
*/
UnlabeledValueArg( const std::string& name,
const std::string& desc,
bool req,
T value,
Constraint<T>* constraint,
CmdLineInterface& parser,
bool ignoreable = false,
Visitor* v = NULL);
/**
* Handles the processing of the argument.
* This re-implements the Arg version of this method to set the
* _value of the argument appropriately. Handling specific to
* unlabled arguments.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings.
*/
virtual bool processArg(int* i, std::vector<std::string>& args);
/**
* Overrides shortID for specific behavior.
*/
virtual std::string shortID(const std::string& val="val") const;
/**
* Overrides longID for specific behavior.
*/
virtual std::string longID(const std::string& val="val") const;
/**
* Overrides operator== for specific behavior.
*/
virtual bool operator==(const Arg& a ) const;
/**
* Instead of pushing to the front of list, push to the back.
* \param argList - The list to add this to.
*/
virtual void addToList( std::list<Arg*>& argList ) const;
};
/**
* Constructor implemenation.
*/
template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name,
const std::string& desc,
bool req,
T val,
const std::string& typeDesc,
bool ignoreable,
Visitor* v)
: ValueArg<T>("", name, desc, req, val, typeDesc, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString());
}
template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name,
const std::string& desc,
bool req,
T val,
const std::string& typeDesc,
CmdLineInterface& parser,
bool ignoreable,
Visitor* v)
: ValueArg<T>("", name, desc, req, val, typeDesc, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString());
parser.add( this );
}
/**
* Constructor implemenation.
*/
template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name,
const std::string& desc,
bool req,
T val,
Constraint<T>* constraint,
bool ignoreable,
Visitor* v)
: ValueArg<T>("", name, desc, req, val, constraint, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString());
}
template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name,
const std::string& desc,
bool req,
T val,
Constraint<T>* constraint,
CmdLineInterface& parser,
bool ignoreable,
Visitor* v)
: ValueArg<T>("", name, desc, req, val, constraint, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString());
parser.add( this );
}
/**
* Implementation of processArg().
*/
template<class T>
bool UnlabeledValueArg<T>::processArg(int *i, std::vector<std::string>& args)
{
if ( _alreadySet )
return false;
if ( _hasBlanks( args[*i] ) )
return false;
// never ignore an unlabeled arg
_extractValue( args[*i] );
_alreadySet = true;
return true;
}
/**
* Overriding shortID for specific output.
*/
template<class T>
std::string UnlabeledValueArg<T>::shortID(const std::string& val) const
{
static_cast<void>(val); // Ignore input, don't warn
return std::string("<") + _typeDesc + ">";
}
/**
* Overriding longID for specific output.
*/
template<class T>
std::string UnlabeledValueArg<T>::longID(const std::string& val) const
{
static_cast<void>(val); // Ignore input, don't warn
// Ideally we would like to be able to use RTTI to return the name
// of the type required for this argument. However, g++ at least,
// doesn't appear to return terribly useful "names" of the types.
return std::string("<") + _typeDesc + ">";
}
/**
* Overriding operator== for specific behavior.
*/
template<class T>
bool UnlabeledValueArg<T>::operator==(const Arg& a ) const
{
if ( _name == a.getName() || _description == a.getDescription() )
/**
* The basic unlabeled argument that parses a value.
* This is a template class, which means the type T defines the type
* that a given object will attempt to parse when an UnlabeledValueArg
* is reached in the list of args that the CmdLine iterates over.
*/
template<class T>
class UnlabeledValueArg : public ValueArg<T>
{
// If compiler has two stage name lookup (as gcc >= 3.4 does)
// this is requried to prevent undef. symbols
using ValueArg<T>::_ignoreable;
using ValueArg<T>::_hasBlanks;
using ValueArg<T>::_extractValue;
using ValueArg<T>::_typeDesc;
using ValueArg<T>::_name;
using ValueArg<T>::_description;
using ValueArg<T>::_alreadySet;
using ValueArg<T>::toString;
public:
/**
* UnlabeledValueArg constructor.
* \param name - A one word name for the argument. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param ignoreable - Allows you to specify that this argument can be
* ignored if the '--' flag is set. This defaults to false (cannot
* be ignored) and should generally stay that way unless you have
* some special need for certain arguments to be ignored.
* \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason.
*/
UnlabeledValueArg(const std::string &name, const std::string &desc, bool req, T value,
const std::string &typeDesc, bool ignoreable = false, Visitor *v = NULL);
/**
* UnlabeledValueArg constructor.
* \param name - A one word name for the argument. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param parser - A CmdLine parser object to add this Arg to
* \param ignoreable - Allows you to specify that this argument can be
* ignored if the '--' flag is set. This defaults to false (cannot
* be ignored) and should generally stay that way unless you have
* some special need for certain arguments to be ignored.
* \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason.
*/
UnlabeledValueArg(const std::string &name, const std::string &desc, bool req, T value,
const std::string &typeDesc, CmdLineInterface &parser,
bool ignoreable = false, Visitor *v = NULL);
/**
* UnlabeledValueArg constructor.
* \param name - A one word name for the argument. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param ignoreable - Allows you to specify that this argument can be
* ignored if the '--' flag is set. This defaults to false (cannot
* be ignored) and should generally stay that way unless you have
* some special need for certain arguments to be ignored.
* \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason.
*/
UnlabeledValueArg(const std::string &name, const std::string &desc, bool req, T value,
Constraint<T> *constraint, bool ignoreable = false, Visitor *v = NULL);
/**
* UnlabeledValueArg constructor.
* \param name - A one word name for the argument. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param parser - A CmdLine parser object to add this Arg to
* \param ignoreable - Allows you to specify that this argument can be
* ignored if the '--' flag is set. This defaults to false (cannot
* be ignored) and should generally stay that way unless you have
* some special need for certain arguments to be ignored.
* \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason.
*/
UnlabeledValueArg(const std::string &name, const std::string &desc, bool req, T value,
Constraint<T> *constraint, CmdLineInterface &parser,
bool ignoreable = false, Visitor *v = NULL);
/**
* Handles the processing of the argument.
* This re-implements the Arg version of this method to set the
* _value of the argument appropriately. Handling specific to
* unlabled arguments.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings.
*/
virtual bool processArg(int *i, std::vector<std::string> &args);
/**
* Overrides shortID for specific behavior.
*/
virtual std::string shortID(const std::string &val = "val") const;
/**
* Overrides longID for specific behavior.
*/
virtual std::string longID(const std::string &val = "val") const;
/**
* Overrides operator== for specific behavior.
*/
virtual bool operator==(const Arg &a) const;
/**
* Instead of pushing to the front of list, push to the back.
* \param argList - The list to add this to.
*/
virtual void addToList(std::list<Arg*> &argList) const;
};
/**
* Constructor implemenation.
*/
template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string &name, const std::string &desc,
bool req, T val, const std::string &typeDesc,
bool ignoreable, Visitor *v) :
ValueArg<T>("", name, desc, req, val, typeDesc, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString());
}
template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string &name, const std::string &desc,
bool req, T val, const std::string &typeDesc,
CmdLineInterface &parser, bool ignoreable, Visitor *v) :
ValueArg<T>("", name, desc, req, val, typeDesc, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString());
parser.add(this);
}
/**
* Constructor implemenation.
*/
template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string &name, const std::string &desc,
bool req, T val, Constraint<T> *constraint,
bool ignoreable, Visitor *v) :
ValueArg<T>("", name, desc, req, val, constraint, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString());
}
template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string &name, const std::string &desc,
bool req, T val, Constraint<T> *constraint,
CmdLineInterface &parser, bool ignoreable, Visitor *v) :
ValueArg<T>("", name, desc, req, val, constraint, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString());
parser.add(this);
}
/**
* Implementation of processArg().
*/
template<class T>
bool UnlabeledValueArg<T>::processArg(int *i, std::vector<std::string> &args)
{
if (_alreadySet)
{
return false;
}
if (_hasBlanks(args[*i]))
{
return false;
}
// never ignore an unlabeled arg
_extractValue(args[*i]);
_alreadySet = true;
return true;
else
return false;
}
/**
* Overriding shortID for specific output.
*/
template<class T>
std::string UnlabeledValueArg<T>::shortID(const std::string &val) const
{
static_cast<void>(val); // Ignore input, don't warn
return std::string("<") + _typeDesc + ">";
}
/**
* Overriding longID for specific output.
*/
template<class T>
std::string UnlabeledValueArg<T>::longID(const std::string &val) const
{
static_cast<void>(val); // Ignore input, don't warn
// Ideally we would like to be able to use RTTI to return the name
// of the type required for this argument. However, g++ at least,
// doesn't appear to return terribly useful "names" of the types.
return std::string("<") + _typeDesc + ">";
}
/**
* Overriding operator== for specific behavior.
*/
template<class T>
bool UnlabeledValueArg<T>::operator==(const Arg &a) const
{
if (_name == a.getName() || _description == a.getDescription())
{
return true;
}
else
{
return false;
}
}
template<class T>
void UnlabeledValueArg<T>::addToList(std::list<Arg*> &argList) const
{
argList.push_back(const_cast<Arg*>(static_cast<const Arg*const>(this)));
}
}
template<class T>
void UnlabeledValueArg<T>::addToList( std::list<Arg*>& argList ) const
{
argList.push_back( const_cast<Arg*>(static_cast<const Arg* const>(this)) );
}
}
#endif

@ -1,23 +1,23 @@
/******************************************************************************
*
/******************************************************************************
*
* file: ValueArg.h
*
*
* Copyright (c) 2003, Michael E. Smoot .
* Copyright (c) 2004, Michael E. Smoot, Daniel Aarno.
* All rights reverved.
*
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* 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.
*
*****************************************************************************/
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef TCLAP_VALUE_ARGUMENT_H
@ -29,383 +29,348 @@
#include <tclap/Arg.h>
#include <tclap/Constraint.h>
namespace TCLAP {
/**
* The basic labeled argument that parses a value.
* This is a template class, which means the type T defines the type
* that a given object will attempt to parse when the flag/name is matched
* on the command line. While there is nothing stopping you from creating
* an unflagged ValueArg, it is unwise and would cause significant problems.
* Instead use an UnlabeledValueArg.
*/
template<class T>
class ValueArg : public Arg
namespace TCLAP
{
protected:
/**
* The value parsed from the command line.
* Can be of any type, as long as the >> operator for the type
* is defined.
*/
T _value;
/**
* Used to support the reset() method so that ValueArg can be
* reset to their constructed value.
*/
T _default;
/**
* A human readable description of the type to be parsed.
* This is a hack, plain and simple. Ideally we would use RTTI to
* return the name of type T, but until there is some sort of
* consistent support for human readable names, we are left to our
* own devices.
*/
std::string _typeDesc;
/**
* A Constraint this Arg must conform to.
*/
Constraint<T>* _constraint;
/**
* Extracts the value from the string.
* Attempts to parse string as type T, if this fails an exception
* is thrown.
* \param val - value to be parsed.
*/
void _extractValue( const std::string& val );
public:
/**
* Labeled ValueArg constructor.
* You could conceivably call this constructor with a blank flag,
* but that would make you a bad person. It would also cause
* an exception to be thrown. If you want an unlabeled argument,
* use the other constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
ValueArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
T value,
const std::string& typeDesc,
Visitor* v = NULL);
/**
* Labeled ValueArg constructor.
* You could conceivably call this constructor with a blank flag,
* but that would make you a bad person. It would also cause
* an exception to be thrown. If you want an unlabeled argument,
* use the other constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param parser - A CmdLine parser object to add this Arg to
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
ValueArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
T value,
const std::string& typeDesc,
CmdLineInterface& parser,
Visitor* v = NULL );
/**
* Labeled ValueArg constructor.
* You could conceivably call this constructor with a blank flag,
* but that would make you a bad person. It would also cause
* an exception to be thrown. If you want an unlabeled argument,
* use the other constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param parser - A CmdLine parser object to add this Arg to.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
ValueArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
T value,
Constraint<T>* constraint,
CmdLineInterface& parser,
Visitor* v = NULL );
/**
* Labeled ValueArg constructor.
* You could conceivably call this constructor with a blank flag,
* but that would make you a bad person. It would also cause
* an exception to be thrown. If you want an unlabeled argument,
* use the other constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
ValueArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
T value,
Constraint<T>* constraint,
Visitor* v = NULL );
/**
* Handles the processing of the argument.
* This re-implements the Arg version of this method to set the
* _value of the argument appropriately. It knows the difference
* between labeled and unlabeled.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed
* in from main().
*/
virtual bool processArg(int* i, std::vector<std::string>& args);
/**
* Returns the value of the argument.
*/
T& getValue() ;
/**
* Specialization of shortID.
* \param val - value to be used.
*/
virtual std::string shortID(const std::string& val = "val") const;
/**
* Specialization of longID.
* \param val - value to be used.
*/
virtual std::string longID(const std::string& val = "val") const;
virtual void reset() ;
};
/**
* Constructor implementation.
*/
template<class T>
ValueArg<T>::ValueArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
T val,
const std::string& typeDesc,
Visitor* v)
: Arg(flag, name, desc, req, true, v),
_value( val ),
_default( val ),
_typeDesc( typeDesc ),
_constraint( NULL )
{ }
template<class T>
ValueArg<T>::ValueArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
T val,
const std::string& typeDesc,
CmdLineInterface& parser,
Visitor* v)
: Arg(flag, name, desc, req, true, v),
_value( val ),
_default( val ),
_typeDesc( typeDesc ),
_constraint( NULL )
{
parser.add( this );
}
template<class T>
ValueArg<T>::ValueArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
T val,
Constraint<T>* constraint,
Visitor* v)
: Arg(flag, name, desc, req, true, v),
_value( val ),
_default( val ),
_typeDesc( constraint->shortID() ),
_constraint( constraint )
{ }
template<class T>
ValueArg<T>::ValueArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
T val,
Constraint<T>* constraint,
CmdLineInterface& parser,
Visitor* v)
: Arg(flag, name, desc, req, true, v),
_value( val ),
_default( val ),
_typeDesc( constraint->shortID() ),
_constraint( constraint )
{
parser.add( this );
}
/**
* Implementation of getValue().
*/
template<class T>
T& ValueArg<T>::getValue() { return _value; }
/**
* Implementation of processArg().
*/
template<class T>
bool ValueArg<T>::processArg(int *i, std::vector<std::string>& args)
{
if ( _ignoreable && Arg::ignoreRest() )
return false;
if ( _hasBlanks( args[*i] ) )
return false;
std::string flag = args[*i];
std::string value = "";
trimFlag( flag, value );
if ( argMatches( flag ) )
{
if ( _alreadySet )
throw( CmdLineParseException("Argument already set!", toString()) );
if ( Arg::delimiter() != ' ' && value == "" )
throw( ArgParseException(
"Couldn't find delimiter for this argument!",
toString() ) );
if ( value == "" )
{
(*i)++;
if ( static_cast<unsigned int>(*i) < args.size() )
_extractValue( args[*i] );
else
throw( ArgParseException("Missing a value for this argument!",
toString() ) );
}
else
_extractValue( value );
_alreadySet = true;
_checkWithVisitor();
return true;
}
else
return false;
}
/**
* Implementation of shortID.
*/
template<class T>
std::string ValueArg<T>::shortID(const std::string& val) const
{
static_cast<void>(val); // Ignore input, don't warn
return Arg::shortID( _typeDesc );
}
/**
* Implementation of longID.
*/
template<class T>
std::string ValueArg<T>::longID(const std::string& val) const
{
static_cast<void>(val); // Ignore input, don't warn
return Arg::longID( _typeDesc );
}
template<class T>
void ValueArg<T>::_extractValue( const std::string& val )
{
try {
ExtractValue(_value, val, typename ArgTraits<T>::ValueCategory());
} catch( ArgParseException &e) {
throw ArgParseException(e.error(), toString());
}
if ( _constraint != NULL )
if ( ! _constraint->check( _value ) )
throw( CmdLineParseException( "Value '" + val +
+ "' does not meet constraint: "
+ _constraint->description(),
toString() ) );
}
template<class T>
void ValueArg<T>::reset()
{
Arg::reset();
_value = _default;
}
/**
* The basic labeled argument that parses a value.
* This is a template class, which means the type T defines the type
* that a given object will attempt to parse when the flag/name is matched
* on the command line. While there is nothing stopping you from creating
* an unflagged ValueArg, it is unwise and would cause significant problems.
* Instead use an UnlabeledValueArg.
*/
template<class T>
class ValueArg : public Arg
{
protected:
/**
* The value parsed from the command line.
* Can be of any type, as long as the >> operator for the type
* is defined.
*/
T _value;
/**
* Used to support the reset() method so that ValueArg can be
* reset to their constructed value.
*/
T _default;
/**
* A human readable description of the type to be parsed.
* This is a hack, plain and simple. Ideally we would use RTTI to
* return the name of type T, but until there is some sort of
* consistent support for human readable names, we are left to our
* own devices.
*/
std::string _typeDesc;
/**
* A Constraint this Arg must conform to.
*/
Constraint<T> *_constraint;
/**
* Extracts the value from the string.
* Attempts to parse string as type T, if this fails an exception
* is thrown.
* \param val - value to be parsed.
*/
void _extractValue(const std::string &val);
public:
/**
* Labeled ValueArg constructor.
* You could conceivably call this constructor with a blank flag,
* but that would make you a bad person. It would also cause
* an exception to be thrown. If you want an unlabeled argument,
* use the other constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
ValueArg(const std::string &flag, const std::string &name, const std::string &desc, bool req,
T value, const std::string &typeDesc, Visitor *v = NULL);
/**
* Labeled ValueArg constructor.
* You could conceivably call this constructor with a blank flag,
* but that would make you a bad person. It would also cause
* an exception to be thrown. If you want an unlabeled argument,
* use the other constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param parser - A CmdLine parser object to add this Arg to
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
ValueArg(const std::string &flag, const std::string &name, const std::string &desc, bool req,
T value, const std::string &typeDesc, CmdLineInterface &parser, Visitor *v = NULL);
/**
* Labeled ValueArg constructor.
* You could conceivably call this constructor with a blank flag,
* but that would make you a bad person. It would also cause
* an exception to be thrown. If you want an unlabeled argument,
* use the other constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param parser - A CmdLine parser object to add this Arg to.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
ValueArg(const std::string &flag, const std::string &name, const std::string &desc, bool req,
T value, Constraint<T> *constraint, CmdLineInterface &parser, Visitor *v = NULL);
/**
* Labeled ValueArg constructor.
* You could conceivably call this constructor with a blank flag,
* but that would make you a bad person. It would also cause
* an exception to be thrown. If you want an unlabeled argument,
* use the other constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
ValueArg(const std::string &flag, const std::string &name, const std::string &desc, bool req,
T value, Constraint<T> *constraint, Visitor *v = NULL);
/**
* Handles the processing of the argument.
* This re-implements the Arg version of this method to set the
* _value of the argument appropriately. It knows the difference
* between labeled and unlabeled.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed
* in from main().
*/
virtual bool processArg(int *i, std::vector<std::string> &args);
/**
* Returns the value of the argument.
*/
T& getValue();
/**
* Specialization of shortID.
* \param val - value to be used.
*/
virtual std::string shortID(const std::string &val = "val") const;
/**
* Specialization of longID.
* \param val - value to be used.
*/
virtual std::string longID(const std::string &val = "val") const;
virtual void reset();
};
/**
* Constructor implementation.
*/
template<class T>
ValueArg<T>::ValueArg(const std::string &flag, const std::string &name, const std::string &desc,
bool req, T val, const std::string &typeDesc, Visitor *v) :
Arg(flag, name, desc, req, true, v), _value(val), _default(val), _typeDesc(typeDesc),
_constraint(NULL)
{
}
template<class T>
ValueArg<T>::ValueArg(const std::string &flag, const std::string &name, const std::string &desc,
bool req, T val, const std::string &typeDesc, CmdLineInterface &parser,
Visitor *v) :
Arg(flag, name, desc, req, true, v), _value(val), _default(val), _typeDesc(typeDesc),
_constraint(NULL)
{
parser.add(this);
}
template<class T>
ValueArg<T>::ValueArg(const std::string &flag, const std::string &name, const std::string &desc,
bool req, T val, Constraint<T> *constraint, Visitor *v) :
Arg(flag, name, desc, req, true, v), _value(val), _default(val), _typeDesc(
constraint->shortID()), _constraint(constraint)
{
}
template<class T>
ValueArg<T>::ValueArg(const std::string &flag, const std::string &name, const std::string &desc,
bool req, T val, Constraint<T> *constraint, CmdLineInterface &parser,
Visitor *v) :
Arg(flag, name, desc, req, true, v), _value(val), _default(val), _typeDesc(
constraint->shortID()), _constraint(constraint)
{
parser.add(this);
}
/**
* Implementation of getValue().
*/
template<class T>
T& ValueArg<T>::getValue()
{
return _value;
}
/**
* Implementation of processArg().
*/
template<class T>
bool ValueArg<T>::processArg(int *i, std::vector<std::string> &args)
{
if (_ignoreable && Arg::ignoreRest())
{
return false;
}
if (_hasBlanks(args[*i]))
{
return false;
}
std::string flag = args[*i];
std::string value = "";
trimFlag(flag, value);
if (argMatches(flag))
{
if (_alreadySet)
{
throw (CmdLineParseException("Argument already set!", toString()));
}
if (Arg::delimiter() != ' ' && value == "")
{
throw (ArgParseException(
"Couldn't find delimiter for this argument!", toString()));
}
if (value == "")
{
(*i)++;
if (static_cast<unsigned int>(*i) < args.size())
{
_extractValue(args[*i]);
}
else
{
throw (ArgParseException("Missing a value for this argument!", toString()));
}
}
else
{
_extractValue(value);
}
_alreadySet = true;
_checkWithVisitor();
return true;
}
else
{
return false;
}
}
/**
* Implementation of shortID.
*/
template<class T>
std::string ValueArg<T>::shortID(const std::string &val) const
{
static_cast<void>(val); // Ignore input, don't warn
return Arg::shortID(_typeDesc);
}
/**
* Implementation of longID.
*/
template<class T>
std::string ValueArg<T>::longID(const std::string &val) const
{
static_cast<void>(val); // Ignore input, don't warn
return Arg::longID(_typeDesc);
}
template<class T>
void ValueArg<T>::_extractValue(const std::string &val)
{
try
{
ExtractValue(_value, val, typename ArgTraits<T>::ValueCategory());
}
catch (ArgParseException &e)
{
throw ArgParseException(e.error(), toString());
}
if (_constraint != NULL)
{
if (!_constraint->check(_value))
{
throw (CmdLineParseException("Value '" + val + +"' does not meet constraint: " +
_constraint->description(), toString()));
}
}
}
template<class T>
void ValueArg<T>::reset()
{
Arg::reset();
_value = _default;
}
} // namespace TCLAP
#endif

@ -1,24 +1,22 @@
/******************************************************************************
*
/******************************************************************************
*
* file: ValuesConstraint.h
*
*
* Copyright (c) 2005, Michael E. Smoot
* All rights reverved.
*
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* 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.
*
*****************************************************************************/
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef TCLAP_VALUESCONSTRAINT_H
#define TCLAP_VALUESCONSTRAINT_H
@ -28,120 +26,122 @@
#include <tclap/Constraint.h>
#ifdef HAVE_CONFIG_H
#include <config.h>
#include <config.h>
#else
#define HAVE_SSTREAM
#define HAVE_SSTREAM
#endif
#if defined(HAVE_SSTREAM)
#include <sstream>
#elif defined(HAVE_STRSTREAM)
#include <strstream>
#if defined (HAVE_SSTREAM)
#include <sstream>
#elif defined (HAVE_STRSTREAM)
#include <strstream>
#else
#error "Need a stringstream (sstream or strstream) to compile!"
#error "Need a stringstream (sstream or strstream) to compile!"
#endif
namespace TCLAP {
/**
* A Constraint that constrains the Arg to only those values specified
* in the constraint.
*/
template<class T>
class ValuesConstraint : public Constraint<T>
namespace TCLAP
{
public:
/**
* Constructor.
* \param allowed - vector of allowed values.
*/
ValuesConstraint(std::vector<T>& allowed);
/**
* Virtual destructor.
*/
virtual ~ValuesConstraint() {}
/**
* Returns a description of the Constraint.
*/
virtual std::string description() const;
/**
* Returns the short ID for the Constraint.
*/
virtual std::string shortID() const;
/**
* The method used to verify that the value parsed from the command
* line meets the constraint.
* \param value - The value that will be checked.
*/
virtual bool check(const T& value) const;
protected:
/**
* The list of valid values.
*/
std::vector<T> _allowed;
/**
* The string used to describe the allowed values of this constraint.
*/
std::string _typeDesc;
};
template<class T>
ValuesConstraint<T>::ValuesConstraint(std::vector<T>& allowed)
: _allowed(allowed)
{
for ( unsigned int i = 0; i < _allowed.size(); i++ )
{
#if defined(HAVE_SSTREAM)
std::ostringstream os;
#elif defined(HAVE_STRSTREAM)
std::ostrstream os;
/**
* A Constraint that constrains the Arg to only those values specified
* in the constraint.
*/
template<class T>
class ValuesConstraint : public Constraint<T>
{
public:
/**
* Constructor.
* \param allowed - vector of allowed values.
*/
ValuesConstraint(std::vector<T> &allowed);
/**
* Virtual destructor.
*/
virtual ~ValuesConstraint()
{
}
/**
* Returns a description of the Constraint.
*/
virtual std::string description() const;
/**
* Returns the short ID for the Constraint.
*/
virtual std::string shortID() const;
/**
* The method used to verify that the value parsed from the command
* line meets the constraint.
* \param value - The value that will be checked.
*/
virtual bool check(const T &value) const;
protected:
/**
* The list of valid values.
*/
std::vector<T> _allowed;
/**
* The string used to describe the allowed values of this constraint.
*/
std::string _typeDesc;
};
template<class T>
ValuesConstraint<T>::ValuesConstraint(std::vector<T> &allowed) :
_allowed(allowed)
{
for (unsigned int i = 0; i < _allowed.size(); i++)
{
#if defined (HAVE_SSTREAM)
std::ostringstream os;
#elif defined (HAVE_STRSTREAM)
std::ostrstream os;
#else
#error "Need a stringstream (sstream or strstream) to compile!"
#error "Need a stringstream (sstream or strstream) to compile!"
#endif
os << _allowed[i];
std::string temp( os.str() );
if ( i > 0 )
_typeDesc += "|";
_typeDesc += temp;
}
}
template<class T>
bool ValuesConstraint<T>::check( const T& val ) const
{
if ( std::find(_allowed.begin(),_allowed.end(),val) == _allowed.end() )
return false;
else
return true;
}
template<class T>
std::string ValuesConstraint<T>::shortID() const
{
return _typeDesc;
}
template<class T>
std::string ValuesConstraint<T>::description() const
{
return _typeDesc;
}
os << _allowed[i];
std::string temp(os.str());
if (i > 0)
{
_typeDesc += "|";
}
_typeDesc += temp;
}
}
template<class T>
bool ValuesConstraint<T>::check(const T &val) const
{
if (std::find(_allowed.begin(), _allowed.end(), val) == _allowed.end())
{
return false;
}
else
{
return true;
}
}
template<class T>
std::string ValuesConstraint<T>::shortID() const
{
return _typeDesc;
}
template<class T>
std::string ValuesConstraint<T>::description() const
{
return _typeDesc;
}
} //namespace TCLAP
#endif
#endif

@ -1,24 +1,24 @@
// -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*-
/******************************************************************************
*
/******************************************************************************
*
* file: VersionVisitor.h
*
*
* Copyright (c) 2003, Michael E. Smoot .
* All rights reverved.
*
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* 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.
*
*****************************************************************************/
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef TCLAP_VERSION_VISITOR_H
@ -28,47 +28,46 @@
#include <tclap/CmdLineOutput.h>
#include <tclap/Visitor.h>
namespace TCLAP {
/**
* A Vistor that will call the version method of the given CmdLineOutput
* for the specified CmdLine object and then exit.
*/
class VersionVisitor: public Visitor
namespace TCLAP
{
protected:
/**
* The CmdLine of interest.
*/
CmdLineInterface* _cmd;
/**
* The output object.
*/
CmdLineOutput** _out;
public:
/**
* Constructor.
* \param cmd - The CmdLine the output is generated for.
* \param out - The type of output.
*/
VersionVisitor( CmdLineInterface* cmd, CmdLineOutput** out )
: Visitor(), _cmd( cmd ), _out( out ) { }
/**
* A Vistor that will call the version method of the given CmdLineOutput
* for the specified CmdLine object and then exit.
*/
class VersionVisitor : public Visitor
{
protected:
/**
* The CmdLine of interest.
*/
CmdLineInterface *_cmd;
/**
* Calls the version method of the output object using the
* specified CmdLine.
*/
void visit() {
(*_out)->version(*_cmd);
throw ExitException(0);
}
/**
* The output object.
*/
CmdLineOutput **_out;
};
public:
/**
* Constructor.
* \param cmd - The CmdLine the output is generated for.
* \param out - The type of output.
*/
VersionVisitor(CmdLineInterface *cmd, CmdLineOutput **out) :
Visitor(), _cmd(cmd), _out(out)
{
}
/**
* Calls the version method of the output object using the
* specified CmdLine.
*/
void visit()
{
(*_out)->version(*_cmd);
throw ExitException(0);
}
};
}
#endif

@ -1,53 +1,56 @@
/******************************************************************************
*
/******************************************************************************
*
* file: Visitor.h
*
*
* Copyright (c) 2003, Michael E. Smoot .
* All rights reverved.
*
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* 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.
*
*****************************************************************************/
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef TCLAP_VISITOR_H
#define TCLAP_VISITOR_H
namespace TCLAP {
/**
* A base class that defines the interface for visitors.
*/
class Visitor
namespace TCLAP
{
public:
/**
* Constructor. Does nothing.
*/
Visitor() { }
/**
* Destructor. Does nothing.
*/
virtual ~Visitor() { }
/**
* Does nothing. Should be overridden by child.
*/
virtual void visit() { }
};
/**
* A base class that defines the interface for visitors.
*/
class Visitor
{
public:
/**
* Constructor. Does nothing.
*/
Visitor()
{
}
/**
* Destructor. Does nothing.
*/
virtual ~Visitor()
{
}
/**
* Does nothing. Should be overridden by child.
*/
virtual void visit()
{
}
};
}
#endif

@ -1,24 +1,23 @@
/******************************************************************************
*
/******************************************************************************
*
* file: XorHandler.h
*
*
* Copyright (c) 2003, Michael E. Smoot .
* Copyright (c) 2004, Michael E. Smoot, Daniel Aarno.
* All rights reverved.
*
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* 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.
*
*****************************************************************************/
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#ifndef TCLAP_XORHANDLER_H
#define TCLAP_XORHANDLER_H
@ -29,128 +28,141 @@
#include <algorithm>
#include <iostream>
namespace TCLAP {
/**
* This class handles lists of Arg's that are to be XOR'd on the command
* line. This is used by CmdLine and you shouldn't ever use it.
*/
class XorHandler
namespace TCLAP
{
protected:
/**
* The list of of lists of Arg's to be or'd together.
*/
std::vector< std::vector<Arg*> > _orList;
public:
/**
* Constructor. Does nothing.
*/
XorHandler( ) {}
/**
* Add a list of Arg*'s that will be orred together.
* \param ors - list of Arg* that will be xor'd.
*/
void add( std::vector<Arg*>& ors );
/**
* Checks whether the specified Arg is in one of the xor lists and
* if it does match one, returns the size of the xor list that the
* Arg matched. If the Arg matches, then it also sets the rest of
* the Arg's in the list. You shouldn't use this.
* \param a - The Arg to be checked.
*/
int check( const Arg* a );
/**
* Returns the XOR specific short usage.
*/
std::string shortUsage();
/**
* Prints the XOR specific long usage.
* \param os - Stream to print to.
*/
void printLongUsage(std::ostream& os);
/**
* Simply checks whether the Arg is contained in one of the arg
* lists.
* \param a - The Arg to be checked.
*/
bool contains( const Arg* a );
std::vector< std::vector<Arg*> >& getXorList();
};
//////////////////////////////////////////////////////////////////////
//BEGIN XOR.cpp
//////////////////////////////////////////////////////////////////////
inline void XorHandler::add( std::vector<Arg*>& ors )
{
_orList.push_back( ors );
}
inline int XorHandler::check( const Arg* a )
{
// iterate over each XOR list
for ( int i = 0; static_cast<unsigned int>(i) < _orList.size(); i++ )
/**
* This class handles lists of Arg's that are to be XOR'd on the command
* line. This is used by CmdLine and you shouldn't ever use it.
*/
class XorHandler
{
// if the XOR list contains the arg..
ArgVectorIterator ait = std::find( _orList[i].begin(),
_orList[i].end(), a );
if ( ait != _orList[i].end() )
{
// go through and set each arg that is not a
for ( ArgVectorIterator it = _orList[i].begin();
it != _orList[i].end();
it++ )
if ( a != (*it) )
(*it)->xorSet();
// return the number of required args that have now been set
if ( (*ait)->allowMore() )
return 0;
else
return static_cast<int>(_orList[i].size());
}
protected:
/**
* The list of of lists of Arg's to be or'd together.
*/
std::vector<std::vector<Arg*>> _orList;
public:
/**
* Constructor. Does nothing.
*/
XorHandler()
{
}
/**
* Add a list of Arg*'s that will be orred together.
* \param ors - list of Arg* that will be xor'd.
*/
void add(std::vector<Arg*> &ors);
/**
* Checks whether the specified Arg is in one of the xor lists and
* if it does match one, returns the size of the xor list that the
* Arg matched. If the Arg matches, then it also sets the rest of
* the Arg's in the list. You shouldn't use this.
* \param a - The Arg to be checked.
*/
int check(const Arg *a);
/**
* Returns the XOR specific short usage.
*/
std::string shortUsage();
/**
* Prints the XOR specific long usage.
* \param os - Stream to print to.
*/
void printLongUsage(std::ostream &os);
/**
* Simply checks whether the Arg is contained in one of the arg
* lists.
* \param a - The Arg to be checked.
*/
bool contains(const Arg *a);
std::vector<std::vector<Arg*>>& getXorList();
};
//////////////////////////////////////////////////////////////////////
//BEGIN XOR.cpp
//////////////////////////////////////////////////////////////////////
inline void XorHandler::add(std::vector<Arg*> &ors)
{
_orList.push_back(ors);
}
if ( a->isRequired() )
return 1;
else
return 0;
}
inline bool XorHandler::contains( const Arg* a )
{
for ( int i = 0; static_cast<unsigned int>(i) < _orList.size(); i++ )
for ( ArgVectorIterator it = _orList[i].begin();
it != _orList[i].end();
it++ )
if ( a == (*it) )
return true;
return false;
}
inline int XorHandler::check(const Arg *a)
{
// iterate over each XOR list
for (int i = 0; static_cast<unsigned int>(i) < _orList.size(); i++)
{
// if the XOR list contains the arg..
ArgVectorIterator ait = std::find(_orList[i].begin(), _orList[i].end(), a);
if (ait != _orList[i].end())
{
// go through and set each arg that is not a
for (ArgVectorIterator it = _orList[i].begin();
it != _orList[i].end();
it++)
{
if (a != (*it))
{
(*it)->xorSet();
}
}
// return the number of required args that have now been set
if ((*ait)->allowMore())
{
return 0;
}
else
{
return static_cast<int>(_orList[i].size());
}
}
}
inline std::vector< std::vector<Arg*> >& XorHandler::getXorList()
{
return _orList;
}
if (a->isRequired())
{
return 1;
}
else
{
return 0;
}
}
inline bool XorHandler::contains(const Arg *a)
{
for (int i = 0; static_cast<unsigned int>(i) < _orList.size(); i++)
{
for (ArgVectorIterator it = _orList[i].begin();
it != _orList[i].end();
it++)
{
if (a == (*it))
{
return true;
}
}
}
return false;
}
//////////////////////////////////////////////////////////////////////
//END XOR.cpp
//////////////////////////////////////////////////////////////////////
inline std::vector<std::vector<Arg*>>& XorHandler::getXorList()
{
return _orList;
}
//////////////////////////////////////////////////////////////////////
//END XOR.cpp
//////////////////////////////////////////////////////////////////////
} //namespace TCLAP
#endif
#endif

@ -1,24 +1,24 @@
// -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*-
/******************************************************************************
*
/******************************************************************************
*
* file: ZshCompletionOutput.h
*
*
* Copyright (c) 2006, Oliver Kiddle
* All rights reverved.
*
*
* See the file COPYING in the top directory of this distribution for
* more information.
*
* 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
*
* THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
*
*****************************************************************************/
#ifndef TCLAP_ZSHCOMPLETIONOUTPUT_H
#define TCLAP_ZSHCOMPLETIONOUTPUT_H
@ -34,288 +34,309 @@
#include <tclap/XorHandler.h>
#include <tclap/Arg.h>
namespace TCLAP {
/**
* A class that generates a Zsh completion function as output from the usage()
* method for the given CmdLine and its Args.
*/
class ZshCompletionOutput : public CmdLineOutput
{
public:
ZshCompletionOutput();
/**
* Prints the usage to stdout. Can be overridden to
* produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void usage(CmdLineInterface& c);
/**
* Prints the version to stdout. Can be overridden
* to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void version(CmdLineInterface& c);
/**
* Prints (to stderr) an error message, short usage
* Can be overridden to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure.
*/
virtual void failure(CmdLineInterface& c,
ArgException& e );
protected:
void basename( std::string& s );
void quoteSpecialChars( std::string& s );
std::string getMutexList( CmdLineInterface& _cmd, Arg* a );
void printOption( Arg* it, std::string mutex );
void printArg( Arg* it );
std::map<std::string, std::string> common;
char theDelimiter;
};
ZshCompletionOutput::ZshCompletionOutput()
{
common["host"] = "_hosts";
common["hostname"] = "_hosts";
common["file"] = "_files";
common["filename"] = "_files";
common["user"] = "_users";
common["username"] = "_users";
common["directory"] = "_directories";
common["path"] = "_directories";
common["url"] = "_urls";
}
inline void ZshCompletionOutput::version(CmdLineInterface& _cmd)
{
std::cout << _cmd.getVersion() << std::endl;
}
inline void ZshCompletionOutput::usage(CmdLineInterface& _cmd )
namespace TCLAP
{
std::list<Arg*> argList = _cmd.getArgList();
std::string progName = _cmd.getProgramName();
std::string version = _cmd.getVersion();
theDelimiter = _cmd.getDelimiter();
basename(progName);
std::cout << "#compdef " << progName << std::endl << std::endl <<
"# " << progName << " version " << _cmd.getVersion() << std::endl << std::endl <<
"_arguments -s -S";
for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
/**
* A class that generates a Zsh completion function as output from the usage()
* method for the given CmdLine and its Args.
*/
class ZshCompletionOutput : public CmdLineOutput
{
if ( (*it)->shortID().at(0) == '<' )
printArg((*it));
else if ( (*it)->getFlag() != "-" )
printOption((*it), getMutexList(_cmd, *it));
}
std::cout << std::endl;
}
inline void ZshCompletionOutput::failure( CmdLineInterface& _cmd,
ArgException& e )
{
static_cast<void>(_cmd); // unused
std::cout << e.what() << std::endl;
}
inline void ZshCompletionOutput::quoteSpecialChars( std::string& s )
{
size_t idx = s.find_last_of(':');
while ( idx != std::string::npos )
public:
ZshCompletionOutput();
/**
* Prints the usage to stdout. Can be overridden to
* produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void usage(CmdLineInterface &c);
/**
* Prints the version to stdout. Can be overridden
* to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void version(CmdLineInterface &c);
/**
* Prints (to stderr) an error message, short usage
* Can be overridden to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure.
*/
virtual void failure(CmdLineInterface &c, ArgException &e);
protected:
void basename(std::string &s);
void quoteSpecialChars(std::string &s);
std::string getMutexList(CmdLineInterface &_cmd, Arg *a);
void printOption(Arg *it, std::string mutex);
void printArg(Arg *it);
std::map<std::string, std::string> common;
char theDelimiter;
};
ZshCompletionOutput::ZshCompletionOutput()
{
s.insert(idx, 1, '\\');
idx = s.find_last_of(':', idx);
common["host"] = "_hosts";
common["hostname"] = "_hosts";
common["file"] = "_files";
common["filename"] = "_files";
common["user"] = "_users";
common["username"] = "_users";
common["directory"] = "_directories";
common["path"] = "_directories";
common["url"] = "_urls";
}
idx = s.find_last_of('\'');
while ( idx != std::string::npos )
inline void ZshCompletionOutput::version(CmdLineInterface &_cmd)
{
s.insert(idx, "'\\'");
if (idx == 0)
idx = std::string::npos;
else
idx = s.find_last_of('\'', --idx);
std::cout << _cmd.getVersion() << std::endl;
}
}
inline void ZshCompletionOutput::basename( std::string& s )
{
size_t p = s.find_last_of('/');
if ( p != std::string::npos )
inline void ZshCompletionOutput::usage(CmdLineInterface &_cmd)
{
s.erase(0, p + 1);
}
}
std::list<Arg*> argList = _cmd.getArgList();
std::string progName = _cmd.getProgramName();
std::string version = _cmd.getVersion();
theDelimiter = _cmd.getDelimiter();
basename(progName);
inline void ZshCompletionOutput::printArg(Arg* a)
{
static int count = 1;
std::cout << " \\" << std::endl << " '";
if ( a->acceptsMultipleValues() )
std::cout << '*';
else
std::cout << count++;
std::cout << ':';
if ( !a->isRequired() )
std::cout << ':';
std::cout << "#compdef " << progName << std::endl << std::endl << "# " << progName <<
" version " << _cmd.getVersion() << std::endl << std::endl << "_arguments -s -S";
std::cout << a->getName() << ':';
std::map<std::string, std::string>::iterator compArg = common.find(a->getName());
if ( compArg != common.end() )
{
std::cout << compArg->second;
}
else
{
std::cout << "_guard \"^-*\" " << a->getName();
}
std::cout << '\'';
}
for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
{
if ((*it)->shortID().at(0) == '<')
{
printArg((*it));
}
else if ((*it)->getFlag() != "-")
{
printOption((*it), getMutexList(_cmd, *it));
}
}
inline void ZshCompletionOutput::printOption(Arg* a, std::string mutex)
{
std::string flag = a->flagStartChar() + a->getFlag();
std::string name = a->nameStartString() + a->getName();
std::string desc = a->getDescription();
std::cout << std::endl;
}
// remove full stop and capitalisation from description as
// this is the convention for zsh function
if (!desc.compare(0, 12, "(required) "))
inline void ZshCompletionOutput::failure(CmdLineInterface &_cmd, ArgException &e)
{
desc.erase(0, 12);
static_cast<void>(_cmd); // unused
std::cout << e.what() << std::endl;
}
if (!desc.compare(0, 15, "(OR required) "))
inline void ZshCompletionOutput::quoteSpecialChars(std::string &s)
{
desc.erase(0, 15);
size_t idx = s.find_last_of(':');
while (idx != std::string::npos)
{
s.insert(idx, 1, '\\');
idx = s.find_last_of(':', idx);
}
idx = s.find_last_of('\'');
while (idx != std::string::npos)
{
s.insert(idx, "'\\'");
if (idx == 0)
{
idx = std::string::npos;
}
else
{
idx = s.find_last_of('\'', --idx);
}
}
}
size_t len = desc.length();
if (len && desc.at(--len) == '.')
inline void ZshCompletionOutput::basename(std::string &s)
{
desc.erase(len);
size_t p = s.find_last_of('/');
if (p != std::string::npos)
{
s.erase(0, p + 1);
}
}
if (len)
inline void ZshCompletionOutput::printArg(Arg *a)
{
desc.replace(0, 1, 1, tolower(desc.at(0)));
}
static int count = 1;
std::cout << " \\" << std::endl << " '" << mutex;
std::cout << " \\" << std::endl << " '";
if (a->acceptsMultipleValues())
{
std::cout << '*';
}
else
{
std::cout << count++;
}
std::cout << ':';
if (!a->isRequired())
{
std::cout << ':';
}
if ( a->getFlag().empty() )
{
std::cout << name;
}
else
{
std::cout << "'{" << flag << ',' << name << "}'";
std::cout << a->getName() << ':';
std::map<std::string, std::string>::iterator compArg = common.find(a->getName());
if (compArg != common.end())
{
std::cout << compArg->second;
}
else
{
std::cout << "_guard \"^-*\" " << a->getName();
}
std::cout << '\'';
}
if ( theDelimiter == '=' && a->isValueRequired() )
std::cout << "=-";
quoteSpecialChars(desc);
std::cout << '[' << desc << ']';
if ( a->isValueRequired() )
inline void ZshCompletionOutput::printOption(Arg *a, std::string mutex)
{
std::string arg = a->shortID();
arg.erase(0, arg.find_last_of(theDelimiter) + 1);
if ( arg.at(arg.length()-1) == ']' )
arg.erase(arg.length()-1);
if ( arg.at(arg.length()-1) == ']' )
std::string flag = a->flagStartChar() + a->getFlag();
std::string name = a->nameStartString() + a->getName();
std::string desc = a->getDescription();
// remove full stop and capitalisation from description as
// this is the convention for zsh function
if (!desc.compare(0, 12, "(required) "))
{
arg.erase(arg.length()-1);
desc.erase(0, 12);
}
if ( arg.at(0) == '<' )
if (!desc.compare(0, 15, "(OR required) "))
{
arg.erase(arg.length()-1);
arg.erase(0, 1);
desc.erase(0, 15);
}
size_t p = arg.find('|');
if ( p != std::string::npos )
size_t len = desc.length();
if (len && desc.at(--len) == '.')
{
do
{
arg.replace(p, 1, 1, ' ');
}
while ( (p = arg.find_first_of('|', p)) != std::string::npos );
quoteSpecialChars(arg);
std::cout << ": :(" << arg << ')';
desc.erase(len);
}
if (len)
{
desc.replace(0, 1, 1, tolower(desc.at(0)));
}
std::cout << " \\" << std::endl << " '" << mutex;
if (a->getFlag().empty())
{
std::cout << name;
}
else
{
std::cout << ':' << arg;
std::map<std::string, std::string>::iterator compArg = common.find(arg);
if ( compArg != common.end() )
std::cout << "'{" << flag << ',' << name << "}'";
}
if (theDelimiter == '=' && a->isValueRequired())
{
std::cout << "=-";
}
quoteSpecialChars(desc);
std::cout << '[' << desc << ']';
if (a->isValueRequired())
{
std::string arg = a->shortID();
arg.erase(0, arg.find_last_of(theDelimiter) + 1);
if (arg.at(arg.length() - 1) == ']')
{
arg.erase(arg.length() - 1);
}
if (arg.at(arg.length() - 1) == ']')
{
arg.erase(arg.length() - 1);
}
if (arg.at(0) == '<')
{
arg.erase(arg.length() - 1);
arg.erase(0, 1);
}
size_t p = arg.find('|');
if (p != std::string::npos)
{
std::cout << ':' << compArg->second;
do
{
arg.replace(p, 1, 1, ' ');
}
while ((p = arg.find_first_of('|', p)) != std::string::npos);
quoteSpecialChars(arg);
std::cout << ": :(" << arg << ')';
}
else
{
std::cout << ':' << arg;
std::map<std::string, std::string>::iterator compArg = common.find(arg);
if (compArg != common.end())
{
std::cout << ':' << compArg->second;
}
}
}
}
std::cout << '\'';
}
inline std::string ZshCompletionOutput::getMutexList( CmdLineInterface& _cmd, Arg* a)
{
XorHandler xorHandler = _cmd.getXorHandler();
std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList();
if (a->getName() == "help" || a->getName() == "version")
{
return "(-)";
std::cout << '\'';
}
std::ostringstream list;
if ( a->acceptsMultipleValues() )
inline std::string ZshCompletionOutput::getMutexList(CmdLineInterface &_cmd, Arg *a)
{
list << '*';
}
XorHandler xorHandler = _cmd.getXorHandler();
std::vector<std::vector<Arg*>> xorList = xorHandler.getXorList();
for ( int i = 0; static_cast<unsigned int>(i) < xorList.size(); i++ )
{
for ( ArgVectorIterator it = xorList[i].begin();
it != xorList[i].end();
it++)
if ( a == (*it) )
if (a->getName() == "help" || a->getName() == "version")
{
return "(-)";
}
std::ostringstream list;
if (a->acceptsMultipleValues())
{
list << '*';
}
for (int i = 0; static_cast<unsigned int>(i) < xorList.size(); i++)
{
list << '(';
for ( ArgVectorIterator iu = xorList[i].begin();
iu != xorList[i].end();
iu++ )
for (ArgVectorIterator it = xorList[i].begin();
it != xorList[i].end();
it++)
{
bool notCur = (*iu) != a;
bool hasFlag = !(*iu)->getFlag().empty();
if ( iu != xorList[i].begin() && (notCur || hasFlag) )
list << ' ';
if (hasFlag)
list << (*iu)->flagStartChar() << (*iu)->getFlag() << ' ';
if ( notCur || hasFlag )
list << (*iu)->nameStartString() << (*iu)->getName();
if (a == (*it))
{
list << '(';
for (ArgVectorIterator iu = xorList[i].begin();
iu != xorList[i].end();
iu++)
{
bool notCur = (*iu) != a;
bool hasFlag = !(*iu)->getFlag().empty();
if (iu != xorList[i].begin() && (notCur || hasFlag))
{
list << ' ';
}
if (hasFlag)
{
list << (*iu)->flagStartChar() << (*iu)->getFlag() << ' ';
}
if (notCur || hasFlag)
{
list << (*iu)->nameStartString() << (*iu)->getName();
}
}
list << ')';
return list.str();
}
}
list << ')';
return list.str();
}
}
// wasn't found in xor list
if (!a->getFlag().empty()) {
list << "(" << a->flagStartChar() << a->getFlag() << ' ' <<
a->nameStartString() << a->getName() << ')';
}
return list.str();
}
// wasn't found in xor list
if (!a->getFlag().empty())
{
list << "(" << a->flagStartChar() << a->getFlag() << ' ' << a->nameStartString() <<
a->getName() << ')';
}
return list.str();
}
} //namespace TCLAP
#endif

Loading…
Cancel
Save