Format code using uncrustify

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

@ -37,9 +37,8 @@
\brief The constructor calls the setup function for the ui created by uic and adds \brief The constructor calls the setup function for the ui created by uic and adds
the GPL text to the text edit. the GPL text to the text edit.
*/ */
AboutDialog::AboutDialog(TQWidget *parent, TQt::WindowFlags flags) : TQDialog(parent, flags) AboutDialog::AboutDialog(TQWidget *parent, TQt::WindowFlags flags) :
, _dialogForm(NULL) TQDialog(parent, flags), _dialogForm(NULL), _timer(NULL)
, _timer(NULL)
{ {
_dialogForm = new Ui::AboutDialog(); _dialogForm = new Ui::AboutDialog();
_dialogForm->setupUi(this); _dialogForm->setupUi(this);
@ -48,7 +47,9 @@ AboutDialog::AboutDialog(TQWidget *parent, TQt::WindowFlags flags) : TQDialog(pa
_dialogForm->creditsTextBrowser->setOpenExternalLinks(true); _dialogForm->creditsTextBrowser->setOpenExternalLinks(true);
TQString versionString = _dialogForm->versionTextBrowser->toHtml(); TQString versionString = _dialogForm->versionTextBrowser->toHtml();
versionString = versionString.arg(PROGRAM_VERSION_STRING).arg( UiGuiVersion::getBuildRevision() ).arg( UiGuiVersion::getBuildDate() ); versionString =
versionString.arg(PROGRAM_VERSION_STRING).arg(UiGuiVersion::getBuildRevision()).arg(
UiGuiVersion::getBuildDate());
_dialogForm->versionTextBrowser->setHtml(versionString); _dialogForm->versionTextBrowser->setHtml(versionString);
_dialogForm->creditsTextBrowser->setHtml("<html><head></head><body>" _dialogForm->creditsTextBrowser->setHtml("<html><head></head><body>"
@ -98,50 +99,56 @@ AboutDialog::AboutDialog(TQWidget *parent, TQt::WindowFlags flags) : TQDialog(pa
connect(this, SIGNAL(accepted()), _timer, SLOT(stop())); connect(this, SIGNAL(accepted()), _timer, SLOT(stop()));
} }
/*! /*!
\brief Catches language change events and retranslates all needed widgets. \brief Catches language change events and retranslates all needed widgets.
*/ */
void AboutDialog::changeEvent(TQEvent *event) { void AboutDialog::changeEvent(TQEvent *event)
if (event->type() == TQEvent::LanguageChange) { {
if (event->type() == TQEvent::LanguageChange)
{
_dialogForm->retranslateUi(this); _dialogForm->retranslateUi(this);
TQString versionString = _dialogForm->versionTextBrowser->toHtml(); TQString versionString = _dialogForm->versionTextBrowser->toHtml();
versionString = versionString.arg(PROGRAM_VERSION_STRING).arg( UiGuiVersion::getBuildRevision() ).arg( UiGuiVersion::getBuildDate() ); versionString =
versionString.arg(PROGRAM_VERSION_STRING).arg(UiGuiVersion::getBuildRevision()).arg(
UiGuiVersion::getBuildDate());
_dialogForm->versionTextBrowser->setHtml(versionString); _dialogForm->versionTextBrowser->setHtml(versionString);
} }
else { else
{
TQWidget::changeEvent(event); TQWidget::changeEvent(event);
} }
} }
/*! /*!
\brief Reimplements the dialog execution function to init the credits scroller. \brief Reimplements the dialog execution function to init the credits scroller.
*/ */
int AboutDialog::exec() { int AboutDialog::exec()
{
//creditsTextBrowser->verticalScrollBar()->setValue(0); //creditsTextBrowser->verticalScrollBar()->setValue(0);
_timer->start(_scrollSpeed); _timer->start(_scrollSpeed);
return TQDialog::exec(); return TQDialog::exec();
} }
/*! /*!
\brief This slot is called each _timer timeout to scroll the credits textbrowser. \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. Also changes the scroll direction and speed when reaching the start or end.
*/ */
void AboutDialog::scroll() { void AboutDialog::scroll()
{
TQScrollBar *scrollBar = _dialogForm->creditsTextBrowser->verticalScrollBar(); TQScrollBar *scrollBar = _dialogForm->creditsTextBrowser->verticalScrollBar();
scrollBar->setValue(scrollBar->value() + _scrollDirection); scrollBar->setValue(scrollBar->value() + _scrollDirection);
if ( scrollBar->value() == scrollBar->maximum() ) { if (scrollBar->value() == scrollBar->maximum())
{
// Toggle scroll direction and change scroll speed; // Toggle scroll direction and change scroll speed;
_scrollDirection = -1; _scrollDirection = -1;
_scrollSpeed = 5; _scrollSpeed = 5;
_timer->stop(); _timer->stop();
_timer->start(_scrollSpeed); _timer->start(_scrollSpeed);
} }
else if ( scrollBar->value() == scrollBar->minimum() ) { else if (scrollBar->value() == scrollBar->minimum())
{
// Toggle scroll direction and change scroll speed; // Toggle scroll direction and change scroll speed;
_scrollDirection = 1; _scrollDirection = 1;
_scrollSpeed = 100; _scrollSpeed = 100;
@ -152,11 +159,11 @@ void AboutDialog::scroll() {
_dialogForm->creditsTextBrowser->update(); _dialogForm->creditsTextBrowser->update();
} }
/*! /*!
\brief Shows the about dialog and also starts the credits scroller. \brief Shows the about dialog and also starts the credits scroller.
*/ */
void AboutDialog::show() { void AboutDialog::show()
{
_timer->start(_scrollSpeed); _timer->start(_scrollSpeed);
TQDialog::show(); TQDialog::show();
} }

@ -22,7 +22,8 @@
#include <tntqdialog.h> #include <tntqdialog.h>
namespace Ui { namespace Ui
{
class AboutDialog; class AboutDialog;
} }

@ -39,21 +39,21 @@
/*! /*!
\brief The constructor initializes everything needed for the 3D animation. \brief The constructor initializes everything needed for the 3D animation.
*/ */
AboutDialogGraphicsView::AboutDialogGraphicsView(AboutDialog *aboutDialog, TQWidget *parentWindow) : TQGraphicsView(parentWindow) AboutDialogGraphicsView::AboutDialogGraphicsView(AboutDialog *aboutDialog, TQWidget *parentWindow) :
, _aboutDialog(NULL) TQGraphicsView(parentWindow), _aboutDialog(NULL), _graphicsProxyWidget(NULL),
, _graphicsProxyWidget(NULL) _parentWindow(NULL), _timeLine(NULL), _aboutDialogAsSplashScreen(NULL)
, _parentWindow(NULL)
, _timeLine(NULL)
, _aboutDialogAsSplashScreen(NULL)
{ {
_parentWindow = parentWindow; _parentWindow = parentWindow;
setWindowFlags(TQt::SplashScreen); setWindowFlags(TQt::SplashScreen);
#ifdef Q_OS_LINUX #ifdef Q_OS_LINUX
TQRect availableGeometry = TQApplication::desktop()->availableGeometry(); TQRect availableGeometry = TQApplication::desktop()->availableGeometry();
TQRect newGeometry = TQRect( availableGeometry.x(), availableGeometry.y(), availableGeometry.width(), availableGeometry.height() ); TQRect newGeometry = TQRect(availableGeometry.x(),
availableGeometry.y(), availableGeometry.width(), availableGeometry.height());
#else #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 #endif
setGeometry(newGeometry); setGeometry(newGeometry);
@ -89,30 +89,41 @@ AboutDialogGraphicsView::AboutDialogGraphicsView(AboutDialog *aboutDialog, TQWid
connect(_timeLine, SIGNAL(frameChanged(int)), this, SLOT(updateStep(int))); 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 \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. AboutDialog 3D animation is shown. Also grabs the content of the AboutDialog itself.
*/ */
void AboutDialogGraphicsView::show() { void AboutDialogGraphicsView::show()
// Because on X11 system the window decoration is only available after a widget has been shown once, {
// 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. // we can detect _windowTitleBarWidth here for the first time.
_windowTitleBarWidth = _parentWindow->geometry().y() - _parentWindow->y(); _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 the _windowTitleBarWidth could not be determined, try it a second way. Even the chances are
// low to get good results.
if (_windowTitleBarWidth == 0) if (_windowTitleBarWidth == 0)
_windowTitleBarWidth = _parentWindow->frameGeometry().height() - _parentWindow->geometry().height(); {
_windowTitleBarWidth = _parentWindow->frameGeometry().height() -
_parentWindow->geometry().height();
}
#ifdef Q_OS_LINUX #ifdef Q_OS_LINUX
if ( _windowTitleBarWidth == 0 ) { 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. {
//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; _windowPosOffset = 27;
_windowTitleBarWidth = 27; _windowTitleBarWidth = 27;
} }
#endif #endif
TQPixmap originalPixmap = TQPixmap::grabWindow(TQApplication::desktop()->winId(), TQApplication::desktop()->availableGeometry().x(), TQApplication::desktop()->availableGeometry().y(), geometry().width(), geometry().height() ); TQPixmap originalPixmap = TQPixmap::grabWindow(
TQApplication::desktop()->winId(),
TQApplication::desktop()->availableGeometry().x(),
TQApplication::desktop()->availableGeometry().y(), geometry().width(),
geometry().height());
TQBrush brush(originalPixmap); TQBrush brush(originalPixmap);
TQTransform transform; TQTransform transform;
transform.translate(0, TQApplication::desktop()->availableGeometry().y()); transform.translate(0, TQApplication::desktop()->availableGeometry().y());
@ -123,12 +134,13 @@ void AboutDialogGraphicsView::show() {
_aboutDialogAsSplashScreen->setPixmap(TQPixmap::grabWidget(_aboutDialog)); _aboutDialogAsSplashScreen->setPixmap(TQPixmap::grabWidget(_aboutDialog));
_graphicsProxyWidget->setGeometry(_aboutDialog->geometry()); _graphicsProxyWidget->setGeometry(_aboutDialog->geometry());
_aboutDialog->hide(); _aboutDialog->hide();
_graphicsProxyWidget->setPos( _parentWindow->geometry().x()+(_parentWindow->geometry().width()-_graphicsProxyWidget->geometry().width()) / 2, _parentWindow->y()+_windowTitleBarWidth-_windowPosOffset); _graphicsProxyWidget->setPos(_parentWindow->geometry().x() +
(_parentWindow->geometry().width() - _graphicsProxyWidget->geometry().width()) / 2,
_parentWindow->y() + _windowTitleBarWidth - _windowPosOffset);
TQRectF r = _graphicsProxyWidget->boundingRect(); TQRectF r = _graphicsProxyWidget->boundingRect();
_graphicsProxyWidget->setTransform(TQTransform() _graphicsProxyWidget->setTransform(TQTransform().translate(
.translate(r.width() / 2, -_windowTitleBarWidth) r.width() / 2, -_windowTitleBarWidth).rotate(270, TQt::XAxis)
.rotate(270, TQt::XAxis)
//.rotate(90, TQt::YAxis) //.rotate(90, TQt::YAxis)
//.rotate(5, TQt::ZAxis) //.rotate(5, TQt::ZAxis)
//.scale(1 + 1.5 * step, 1 + 1.5 * step) //.scale(1 + 1.5 * step, 1 + 1.5 * step)
@ -143,15 +155,14 @@ void AboutDialogGraphicsView::show() {
_timeLine->start(); _timeLine->start();
} }
/*! /*!
\brief Does the next calculation/transformation step. \brief Does the next calculation/transformation step.
*/ */
void AboutDialogGraphicsView::updateStep(int step) { void AboutDialogGraphicsView::updateStep(int step)
{
TQRectF r = _graphicsProxyWidget->boundingRect(); TQRectF r = _graphicsProxyWidget->boundingRect();
_graphicsProxyWidget->setTransform(TQTransform() _graphicsProxyWidget->setTransform(TQTransform().translate(
.translate(r.width() / 2, -_windowTitleBarWidth) r.width() / 2, -_windowTitleBarWidth).rotate(step, TQt::XAxis)
.rotate(step, TQt::XAxis)
//.rotate(step, TQt::YAxis) //.rotate(step, TQt::YAxis)
//.rotate(step * 5, TQt::ZAxis) //.rotate(step * 5, TQt::ZAxis)
//.scale(1 + 1.5 * step, 1 + 1.5 * step) //.scale(1 + 1.5 * step, 1 + 1.5 * step)
@ -159,28 +170,31 @@ void AboutDialogGraphicsView::updateStep(int step) {
//update(); //update();
} }
/*! /*!
\brief Stops the 3D animation, moves the AboutDialog to the correct place and really shows it. \brief Stops the 3D animation, moves the AboutDialog to the correct place and really shows it.
*/ */
void AboutDialogGraphicsView::showAboutDialog() { void AboutDialogGraphicsView::showAboutDialog()
{
//hide(); //hide();
disconnect(_timeLine, SIGNAL(finished()), this, SLOT(showAboutDialog())); 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->move(int(_parentWindow->geometry().x() +
(_parentWindow->geometry().width() - _graphicsProxyWidget->geometry().width()) / 2),
_parentWindow->y() + _windowTitleBarWidth - _windowPosOffset);
_aboutDialog->exec(); _aboutDialog->exec();
} }
/*! /*!
\brief Does not directly hide the AboutDialog but instead starts the "fade out" 3D animation. \brief Does not directly hide the AboutDialog but instead starts the "fade out" 3D animation.
*/ */
void AboutDialogGraphicsView::hide() { void AboutDialogGraphicsView::hide()
_graphicsProxyWidget->setPos( _parentWindow->geometry().x()+(_parentWindow->geometry().width()-_graphicsProxyWidget->geometry().width()) / 2, _parentWindow->y()+_windowTitleBarWidth-_windowPosOffset); {
_graphicsProxyWidget->setPos(_parentWindow->geometry().x() +
(_parentWindow->geometry().width() - _graphicsProxyWidget->geometry().width()) / 2,
_parentWindow->y() + _windowTitleBarWidth - _windowPosOffset);
TQRectF r = _graphicsProxyWidget->boundingRect(); TQRectF r = _graphicsProxyWidget->boundingRect();
_graphicsProxyWidget->setTransform(TQTransform() _graphicsProxyWidget->setTransform(TQTransform().translate(
.translate(r.width() / 2, -_windowTitleBarWidth) r.width() / 2, -_windowTitleBarWidth).rotate(0, TQt::XAxis)
.rotate(0, TQt::XAxis)
//.rotate(90, TQt::YAxis) //.rotate(90, TQt::YAxis)
//.rotate(5, TQt::ZAxis) //.rotate(5, TQt::ZAxis)
//.scale(1 + 1.5 * step, 1 + 1.5 * step) //.scale(1 + 1.5 * step, 1 + 1.5 * step)
@ -195,11 +209,11 @@ void AboutDialogGraphicsView::hide() {
_timeLine->start(); _timeLine->start();
} }
/*! /*!
\brief This slot really hides this AboutDialog container. \brief This slot really hides this AboutDialog container.
*/ */
void AboutDialogGraphicsView::hideReally() { void AboutDialogGraphicsView::hideReally()
{
disconnect(_timeLine, SIGNAL(finished()), this, SLOT(hideReally())); disconnect(_timeLine, SIGNAL(finished()), this, SLOT(hideReally()));
TQGraphicsView::hide(); TQGraphicsView::hide();
_parentWindow->activateWindow(); _parentWindow->activateWindow();

@ -30,6 +30,7 @@ class TQSplashScreen;
class AboutDialogGraphicsView : public TQGraphicsView class AboutDialogGraphicsView : public TQGraphicsView
{ {
Q_OBJECT Q_OBJECT
public: public:
AboutDialogGraphicsView(AboutDialog *aboutDialog, TQWidget *parentWindow = NULL); AboutDialogGraphicsView(AboutDialog *aboutDialog, TQWidget *parentWindow = NULL);
~AboutDialogGraphicsView(void); ~AboutDialogGraphicsView(void);

File diff suppressed because it is too large Load Diff

@ -89,44 +89,55 @@ private:
bool createIndenterCallString(); bool createIndenterCallString();
void initIndenterMenu(); void initIndenterMenu();
//! Holds a reference to all created pages of the parameter categories toolbox and the pages boxlayout //! Holds a reference to all created pages of the parameter categories toolbox and the pages
struct IndenterParameterCategoryPage { // boxlayout
struct IndenterParameterCategoryPage
{
TQWidget *widget; TQWidget *widget;
TQVBoxLayout *vboxLayout; TQVBoxLayout *vboxLayout;
}; };
TQVector<IndenterParameterCategoryPage> _indenterParameterCategoryPages; TQVector<IndenterParameterCategoryPage> _indenterParameterCategoryPages;
//! Holds a reference to all checkboxes needed for boolean parameter setting and the parameters name //! Holds a reference to all checkboxes needed for boolean parameter setting and the parameters
struct ParamBoolean { // name
struct ParamBoolean
{
TQString paramName; TQString paramName;
TQString trueString; TQString trueString;
TQString falseString; TQString falseString;
TQCheckBox *checkBox; TQCheckBox *checkBox;
}; };
TQVector<ParamBoolean> _paramBooleans; TQVector<ParamBoolean> _paramBooleans;
//! Holds a reference to all line edits needed for parameter setting and the parameters name //! Holds a reference to all line edits needed for parameter setting and the parameters name
struct ParamString { struct ParamString
{
TQString paramName; TQString paramName;
TQString paramCallName; TQString paramCallName;
TQCheckBox *valueEnabledChkBox; TQCheckBox *valueEnabledChkBox;
TQLineEdit *lineEdit; TQLineEdit *lineEdit;
TQLabel *label; TQLabel *label;
}; };
TQVector<ParamString> _paramStrings; TQVector<ParamString> _paramStrings;
//! Hold a reference to all spin boxes needed for parameter setting and the parameters name //! Hold a reference to all spin boxes needed for parameter setting and the parameters name
struct ParamNumeric { struct ParamNumeric
{
TQString paramName; TQString paramName;
TQString paramCallName; TQString paramCallName;
TQCheckBox *valueEnabledChkBox; TQCheckBox *valueEnabledChkBox;
TQSpinBox *spinBox; TQSpinBox *spinBox;
TQLabel *label; TQLabel *label;
}; };
TQVector<ParamNumeric> _paramNumerics; TQVector<ParamNumeric> _paramNumerics;
//! Hold a reference to all combo boxes needed for parameter setting and the parameters name //! Hold a reference to all combo boxes needed for parameter setting and the parameters name
struct ParamMultiple { struct ParamMultiple
{
TQString paramName; TQString paramName;
TQString paramCallName; TQString paramCallName;
TQCheckBox *valueEnabledChkBox; TQCheckBox *valueEnabledChkBox;
@ -134,6 +145,7 @@ private:
TQStringList choicesStrings; TQStringList choicesStrings;
TQStringList choicesStringsReadable; TQStringList choicesStringsReadable;
}; };
TQVector<ParamMultiple> _paramMultiples; TQVector<ParamMultiple> _paramMultiples;
TQComboBox *_indenterSelectionCombobox; TQComboBox *_indenterSelectionCombobox;

File diff suppressed because it is too large Load Diff

@ -30,7 +30,8 @@ class AboutDialogGraphicsView;
class UiGuiHighlighter; class UiGuiHighlighter;
class IndentHandler; class IndentHandler;
class UpdateCheckDialog; class UpdateCheckDialog;
namespace Ui { namespace Ui
{
class ToolBarWidget; class ToolBarWidget;
class MainWindowUi; class MainWindowUi;
} }
@ -50,7 +51,9 @@ class MainWindow : public TQMainWindow
public: public:
//! Constructor //! Constructor
MainWindow(TQString file2OpenOnStart = "", TQWidget *parent = NULL); MainWindow(TQString file2OpenOnStart = "", TQWidget *parent = NULL);
~MainWindow() {
~MainWindow()
{
_settings.clear(); _settings.clear();
} }

@ -45,7 +45,6 @@ TQString SettingsPaths::_indenterPath = "";
TQString SettingsPaths::_tempPath = ""; TQString SettingsPaths::_tempPath = "";
bool SettingsPaths::_portableMode = false; bool SettingsPaths::_portableMode = false;
/*! /*!
\brief Initializes all available information about the paths. \brief Initializes all available information about the paths.
@ -56,7 +55,8 @@ bool SettingsPaths::_portableMode = false;
Means also that the directory "indenters" has to be there. 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. In not portable mode (multiuser mode) only users home directory is used for writing config data.
*/ */
void SettingsPaths::init() { void SettingsPaths::init()
{
_alreadyInitialized = true; _alreadyInitialized = true;
tqDebug() << __LINE__ << " " << __FUNCTION__ << ": Initializing application paths."; tqDebug() << __LINE__ << " " << __FUNCTION__ << ": Initializing application paths.";
@ -64,7 +64,8 @@ void SettingsPaths::init() {
// Get the applications binary path, with respect to MacOSXs use of the .app folder. // Get the applications binary path, with respect to MacOSXs use of the .app folder.
_applicationBinaryPath = TQCoreApplication::applicationDirPath(); _applicationBinaryPath = TQCoreApplication::applicationDirPath();
// Remove any trailing slashes // Remove any trailing slashes
while ( _applicationBinaryPath.right(1) == "/" ) { while (_applicationBinaryPath.right(1) == "/")
{
_applicationBinaryPath.chop(1); _applicationBinaryPath.chop(1);
} }
@ -76,17 +77,21 @@ void SettingsPaths::init() {
// Because on Mac universal binaries are used, the binary path is not equal // Because on Mac universal binaries are used, the binary path is not equal
// to the applications (.app) path. So get the .apps path here. // to the applications (.app) path. So get the .apps path here.
int indexOfDotApp = _applicationBinaryPath.indexOf(".app"); int indexOfDotApp = _applicationBinaryPath.indexOf(".app");
if ( indexOfDotApp != -1 ) { if (indexOfDotApp != -1)
{
// Cut off after the dot of ".app". // Cut off after the dot of ".app".
_applicationBinaryPath = _applicationBinaryPath.left(indexOfDotApp - 1); _applicationBinaryPath = _applicationBinaryPath.left(indexOfDotApp - 1);
// Cut off after the first slash that was in front of ".app" (normally this is the word "UniversalIndentGUI") // Cut off after the first slash that was in front of ".app" (normally this is the word
// "UniversalIndentGUI")
_applicationBinaryPath = _applicationBinaryPath.left(_applicationBinaryPath.lastIndexOf("/")); _applicationBinaryPath = _applicationBinaryPath.left(_applicationBinaryPath.lastIndexOf("/"));
} }
#endif #endif
// If the "config" directory is a subdir of the applications binary path, use this one (portable mode) // If the "config" directory is a subdir of the applications binary path, use this one (portable
// mode)
_settingsPath = _applicationBinaryPath + "/config"; _settingsPath = _applicationBinaryPath + "/config";
if ( TQFile::exists( _settingsPath ) ) { if (TQFile::exists(_settingsPath))
{
_portableMode = true; _portableMode = true;
TQDir dirCreator; TQDir dirCreator;
_globalFilesPath = _applicationBinaryPath; _globalFilesPath = _applicationBinaryPath;
@ -97,24 +102,28 @@ void SettingsPaths::init() {
dirCreator.mkpath(_tempPath); dirCreator.mkpath(_tempPath);
} }
// ... otherwise use the system specific global application data path. // ... otherwise use the system specific global application data path.
else { else
{
_portableMode = false; _portableMode = false;
TQDir dirCreator; TQDir dirCreator;
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
// Get the local users application settings directory. // Get the local users application settings directory.
// Remove any trailing slashes. // Remove any trailing slashes.
_settingsPath = TQDir::fromNativeSeparators(qgetenv("APPDATA")); _settingsPath = TQDir::fromNativeSeparators(qgetenv("APPDATA"));
while ( _settingsPath.right(1) == "/" ) { while (_settingsPath.right(1) == "/")
{
_settingsPath.chop(1); _settingsPath.chop(1);
} }
_settingsPath = _settingsPath + "/UniversalIndentGUI"; _settingsPath = _settingsPath + "/UniversalIndentGUI";
// On windows systems the directories "indenters", "translations" are subdirs of the _applicationBinaryPath. // On windows systems the directories "indenters", "translations" are subdirs of the
// _applicationBinaryPath.
_globalFilesPath = _applicationBinaryPath; _globalFilesPath = _applicationBinaryPath;
#else #else
// Remove any trailing slashes. // Remove any trailing slashes.
_settingsPath = TQDir::homePath(); _settingsPath = TQDir::homePath();
while ( _settingsPath.right(1) == "/" ) { while (_settingsPath.right(1) == "/")
{
_settingsPath.chop(1); _settingsPath.chop(1);
} }
_settingsPath = _settingsPath + "/.universalindentgui"; _settingsPath = _settingsPath + "/.universalindentgui";
@ -123,15 +132,19 @@ void SettingsPaths::init() {
dirCreator.mkpath(_settingsPath); dirCreator.mkpath(_settingsPath);
// If a highlighter config file does not exist in the users home config dir // If a highlighter config file does not exist in the users home config dir
// copy the default config file over there. // copy the default config file over there.
if ( !TQFile::exists(_settingsPath+"/UiGuiSyntaxHighlightConfig.ini") ) { if (!TQFile::exists(_settingsPath + "/UiGuiSyntaxHighlightConfig.ini"))
TQFile::copy( _globalFilesPath+"/config/UiGuiSyntaxHighlightConfig.ini", _settingsPath+"/UiGuiSyntaxHighlightConfig.ini" ); {
TQFile::copy(_globalFilesPath + "/config/UiGuiSyntaxHighlightConfig.ini",
_settingsPath + "/UiGuiSyntaxHighlightConfig.ini");
} }
_indenterPath = _globalFilesPath + "/indenters"; _indenterPath = _globalFilesPath + "/indenters";
// On different systems it may be that "TQDir::tempPath()" ends with a "/" or not. So check this. // On different systems it may be that "TQDir::tempPath()" ends with a "/" or not. So check
// this.
// Remove any trailing slashes. // Remove any trailing slashes.
_tempPath = TQDir::tempPath(); _tempPath = TQDir::tempPath();
while ( _tempPath.right(1) == "/" ) { while (_tempPath.right(1) == "/")
{
_tempPath.chop(1); _tempPath.chop(1);
} }
_tempPath = _tempPath + "/UniversalIndentGUI"; _tempPath = _tempPath + "/UniversalIndentGUI";
@ -153,123 +166,144 @@ void SettingsPaths::init() {
} }
tqDebug() << __LINE__ << " " << __FUNCTION__ << ": Paths are:" \ tqDebug() << __LINE__ << " " << __FUNCTION__ << ": Paths are:" \
"<ul><li>_applicationBinaryPath=" << _applicationBinaryPath \ "<ul><li>_applicationBinaryPath=" <<
<< "</li><li>_settingsPath=" << _settingsPath \ _applicationBinaryPath << "</li><li>_settingsPath=" << _settingsPath <<
<< "</li><li>_globalFilesPath=" << _globalFilesPath \ "</li><li>_globalFilesPath=" << _globalFilesPath << "</li><li>_indenterPath=" <<
<< "</li><li>_indenterPath=" << _indenterPath \ _indenterPath << "</li><li>_tempPath=" << _tempPath <<
<< "</li><li>_tempPath=" << _tempPath \ "</li><li>Running in portable mode=" << _portableMode << "</li></ul>";
<< "</li><li>Running in portable mode=" << _portableMode << "</li></ul>";
} }
/*! /*!
\brief Returns the path of the applications executable. \brief Returns the path of the applications executable.
*/ */
const TQString SettingsPaths::getApplicationBinaryPath() { const TQString SettingsPaths::getApplicationBinaryPath()
if ( !_alreadyInitialized ) { {
if (!_alreadyInitialized)
{
SettingsPaths::init(); SettingsPaths::init();
} }
return _applicationBinaryPath; return _applicationBinaryPath;
} }
/*! /*!
\brief Returns the path where all settings are being/should be written to. \brief Returns the path where all settings are being/should be written to.
*/ */
const TQString SettingsPaths::getSettingsPath() { const TQString SettingsPaths::getSettingsPath()
if ( !_alreadyInitialized ) { {
if (!_alreadyInitialized)
{
SettingsPaths::init(); SettingsPaths::init();
} }
return _settingsPath; return _settingsPath;
} }
/*! /*!
\brief Returns the path where the files concerning all users reside. For example translations. \brief Returns the path where the files concerning all users reside. For example translations.
*/ */
const TQString SettingsPaths::getGlobalFilesPath() { const TQString SettingsPaths::getGlobalFilesPath()
if ( !_alreadyInitialized ) { {
if (!_alreadyInitialized)
{
SettingsPaths::init(); SettingsPaths::init();
} }
return _globalFilesPath; return _globalFilesPath;
} }
/*! /*!
\brief Returns the path where the indenter executables reside. \brief Returns the path where the indenter executables reside.
*/ */
const TQString SettingsPaths::getIndenterPath() { const TQString SettingsPaths::getIndenterPath()
if ( !_alreadyInitialized ) { {
if (!_alreadyInitialized)
{
SettingsPaths::init(); SettingsPaths::init();
} }
return _indenterPath; return _indenterPath;
} }
/*! /*!
\brief Returns the path where the where all temporary data should be written to. \brief Returns the path where the where all temporary data should be written to.
*/ */
const TQString SettingsPaths::getTempPath() { const TQString SettingsPaths::getTempPath()
if ( !_alreadyInitialized ) { {
if (!_alreadyInitialized)
{
SettingsPaths::init(); SettingsPaths::init();
} }
return _tempPath; return _tempPath;
} }
/*! /*!
\brief Returns true if portable mode shall be used. \brief Returns true if portable mode shall be used.
*/ */
bool SettingsPaths::getPortableMode() { bool SettingsPaths::getPortableMode()
if ( !_alreadyInitialized ) { {
if (!_alreadyInitialized)
{
SettingsPaths::init(); SettingsPaths::init();
} }
return _portableMode; return _portableMode;
} }
/*! /*!
\brief Completely deletes the created temporary directory with all of its content. \brief Completely deletes the created temporary directory with all of its content.
*/ */
void SettingsPaths::cleanAndRemoveTempDir() { void SettingsPaths::cleanAndRemoveTempDir()
{
TQDirIterator dirIterator(_tempPath, TQDirIterator::Subdirectories); TQDirIterator dirIterator(_tempPath, TQDirIterator::Subdirectories);
TQStack<TQString> directoryStack; TQStack<TQString> directoryStack;
bool noErrorsOccurred = true; bool noErrorsOccurred = true;
while ( dirIterator.hasNext() ) { while (dirIterator.hasNext())
{
TQString currentDirOrFile = dirIterator.next(); TQString currentDirOrFile = dirIterator.next();
// If this dummy call isn't done here, calling "dirIterator.fileInfo().isDir()" later somehow fails. // If this dummy call isn't done here, calling "dirIterator.fileInfo().isDir()" later somehow
// fails.
dirIterator.fileInfo(); dirIterator.fileInfo();
if ( !currentDirOrFile.isEmpty() && dirIterator.fileName() != "." && dirIterator.fileName() != ".." ) { if (!currentDirOrFile.isEmpty() && dirIterator.fileName() != "." &&
dirIterator.fileName() != "..")
{
// There is a path on the stack but the current path doesn't start with that path. // 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 // So we changed into another parent directory and the one on the stack can be deleted
// since it must be empty. // since it must be empty.
if ( !directoryStack.isEmpty() && !currentDirOrFile.startsWith(directoryStack.top()) ) { if (!directoryStack.isEmpty() && !currentDirOrFile.startsWith(directoryStack.top()))
{
TQString dirToBeRemoved = directoryStack.pop(); TQString dirToBeRemoved = directoryStack.pop();
bool couldRemoveDir = TQDir(dirToBeRemoved).rmdir(dirToBeRemoved); bool couldRemoveDir = TQDir(dirToBeRemoved).rmdir(dirToBeRemoved);
noErrorsOccurred &= couldRemoveDir; noErrorsOccurred &= couldRemoveDir;
if (couldRemoveDir == false) if (couldRemoveDir == false)
tqWarning() << __LINE__ << " " << __FUNCTION__ << "Could not remove the directory: " << dirToBeRemoved; {
tqWarning() << __LINE__ << " " << __FUNCTION__ << "Could not remove the directory: " <<
dirToBeRemoved;
}
//tqDebug() << "Removing Dir " << directoryStack.pop(); //tqDebug() << "Removing Dir " << directoryStack.pop();
} }
// If the iterator currently points to a directory push it onto the stack. // If the iterator currently points to a directory push it onto the stack.
if ( dirIterator.fileInfo().isDir() ) { if (dirIterator.fileInfo().isDir())
{
directoryStack.push(currentDirOrFile); directoryStack.push(currentDirOrFile);
//tqDebug() << "Pushing onto Stack " << currentDirOrFile; //tqDebug() << "Pushing onto Stack " << currentDirOrFile;
} }
// otherwise it must be a file, so delete it. // otherwise it must be a file, so delete it.
else { else
{
bool couldRemoveFile = TQFile::remove(currentDirOrFile); bool couldRemoveFile = TQFile::remove(currentDirOrFile);
noErrorsOccurred &= couldRemoveFile; noErrorsOccurred &= couldRemoveFile;
if (couldRemoveFile == false) if (couldRemoveFile == false)
tqWarning() << __LINE__ << " " << __FUNCTION__ << "Could not remove the file: " << currentDirOrFile; {
tqWarning() << __LINE__ << " " << __FUNCTION__ << "Could not remove the file: " <<
currentDirOrFile;
}
//tqDebug() << "Removing File " << currentDirOrFile; //tqDebug() << "Removing File " << currentDirOrFile;
} }
} }
} }
noErrorsOccurred &= TQDir(_tempPath).rmdir(_tempPath); noErrorsOccurred &= TQDir(_tempPath).rmdir(_tempPath);
if (noErrorsOccurred == false) if (noErrorsOccurred == false)
tqWarning() << __LINE__ << " " << __FUNCTION__ << "While cleaning up the temp dir an error occurred."; {
tqWarning() << __LINE__ << " " << __FUNCTION__ <<
"While cleaning up the temp dir an error occurred.";
}
} }

@ -33,7 +33,8 @@
"__INDENTERCALLSTRING2__" the call string for indenting only one file. "__INDENTERCALLSTRING2__" the call string for indenting only one file.
And "__INDENTERCALLSTRINGSCRIPTNAME__" which is only the shown name of the indenter. And "__INDENTERCALLSTRINGSCRIPTNAME__" which is only the shown name of the indenter.
*/ */
const char* TemplateBatchScript::getTemplateBatchScript() { const char* TemplateBatchScript::getTemplateBatchScript()
{
static const char *templateBatchScript = static const char *templateBatchScript =
#if defined (Q_OS_WIN32) #if defined (Q_OS_WIN32)
"@echo off\n" "@echo off\n"
@ -121,7 +122,6 @@ const char* TemplateBatchScript::getTemplateBatchScript() {
return templateBatchScript; return templateBatchScript;
} }
/* Here comes the original batch script without the c++ markup /* Here comes the original batch script without the c++ markup
@echo off @echo off

@ -24,6 +24,7 @@ class TemplateBatchScript
{ {
private: private:
TemplateBatchScript(); TemplateBatchScript();
public: public:
static const char* getTemplateBatchScript(); static const char* getTemplateBatchScript();
}; };

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

@ -32,6 +32,7 @@ class UiGuiErrorMessage : public TQErrorMessage
public: public:
UiGuiErrorMessage(TQWidget *parent = 0); UiGuiErrorMessage(TQWidget *parent = 0);
~UiGuiErrorMessage(void); ~UiGuiErrorMessage(void);
void showMessage(const TQString &message); void showMessage(const TQString &message);
void showMessage(const TQString &title, const TQString &message); void showMessage(const TQString &title, const TQString &message);

@ -85,18 +85,23 @@
/*! /*!
\brief The constructor initializes some regular expressions and keywords to identify cpp tokens \brief The constructor initializes some regular expressions and keywords to identify cpp tokens
*/ */
UiGuiHighlighter::UiGuiHighlighter(QsciScintilla *parent) : TQObject(parent) { UiGuiHighlighter::UiGuiHighlighter(QsciScintilla *parent) :
TQObject(parent)
{
_qsciEditorParent = parent; _qsciEditorParent = parent;
// Create the highlighter _settings object from the UiGuiSyntaxHighlightConfig.ini file. // Create the highlighter _settings object from the UiGuiSyntaxHighlightConfig.ini file.
_settings = new TQSettings(SettingsPaths::getSettingsPath() + "/UiGuiSyntaxHighlightConfig.ini", TQSettings::IniFormat, this); _settings = new TQSettings(
SettingsPaths::getSettingsPath() + "/UiGuiSyntaxHighlightConfig.ini", TQSettings::IniFormat,
this);
_highlightningIsOn = true; _highlightningIsOn = true;
_mapHighlighternameToExtension["Bash"] = TQStringList() << "sh"; _mapHighlighternameToExtension["Bash"] = TQStringList() << "sh";
_mapHighlighternameToExtension["Batch"] = TQStringList() << "bat"; _mapHighlighternameToExtension["Batch"] = TQStringList() << "bat";
_mapHighlighternameToExtension["CMake"] = TQStringList() << "cmake"; _mapHighlighternameToExtension["CMake"] = TQStringList() << "cmake";
_mapHighlighternameToExtension["C++"] = TQStringList() << "c" << "h" << "cpp" << "hpp" << "cxx" << "hxx"; _mapHighlighternameToExtension["C++"] = TQStringList() << "c" << "h" << "cpp" << "hpp" <<
"cxx" << "hxx";
_mapHighlighternameToExtension["C#"] = TQStringList() << "cs"; _mapHighlighternameToExtension["C#"] = TQStringList() << "cs";
_mapHighlighternameToExtension["CSS"] = TQStringList() << "css"; _mapHighlighternameToExtension["CSS"] = TQStringList() << "css";
_mapHighlighternameToExtension["D"] = TQStringList() << "d"; _mapHighlighternameToExtension["D"] = TQStringList() << "d";
@ -117,7 +122,8 @@ UiGuiHighlighter::UiGuiHighlighter(QsciScintilla *parent) : TQObject(parent) {
_mapHighlighternameToExtension["Perl"] = TQStringList() << "perl" << "pl" << "pm"; _mapHighlighternameToExtension["Perl"] = TQStringList() << "perl" << "pl" << "pm";
_mapHighlighternameToExtension["PHP"] = TQStringList() << "php"; _mapHighlighternameToExtension["PHP"] = TQStringList() << "php";
#if (TQSCINTILLA_VERSION >= 0x020300) #if (TQSCINTILLA_VERSION >= 0x020300)
_mapHighlighternameToExtension["PostScript"] = TQStringList() << "ps" << "eps" << "pdf" << "ai" << "fh"; _mapHighlighternameToExtension["PostScript"] = TQStringList() << "ps" << "eps" << "pdf" << "ai" <<
"fh";
#endif #endif
_mapHighlighternameToExtension["POV"] = TQStringList() << "pov"; _mapHighlighternameToExtension["POV"] = TQStringList() << "pov";
_mapHighlighternameToExtension["Ini"] = TQStringList() << "ini"; _mapHighlighternameToExtension["Ini"] = TQStringList() << "ini";
@ -153,33 +159,34 @@ UiGuiHighlighter::UiGuiHighlighter(QsciScintilla *parent) : TQObject(parent) {
setLexerForExtension("cpp"); setLexerForExtension("cpp");
} }
/*! /*!
\brief Returns the available highlighters as TQStringList. \brief Returns the available highlighters as TQStringList.
*/ */
TQStringList UiGuiHighlighter::getAvailableHighlighters() { TQStringList UiGuiHighlighter::getAvailableHighlighters()
{
return _mapHighlighternameToExtension.keys(); return _mapHighlighternameToExtension.keys();
} }
/*! /*!
\brief This slot handles signals coming from selecting another syntax highlighter. \brief This slot handles signals coming from selecting another syntax highlighter.
*/ */
void UiGuiHighlighter::setHighlighterByAction(TQAction* highlighterAction) { void UiGuiHighlighter::setHighlighterByAction(TQAction *highlighterAction)
{
TQString highlighterName = highlighterAction->text(); TQString highlighterName = highlighterAction->text();
setLexerForExtension(_mapHighlighternameToExtension[highlighterName].first()); setLexerForExtension(_mapHighlighternameToExtension[highlighterName].first());
//TODO: This is really no nice way. How do it better? //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. // Need to do this "text update" to update the syntax highlighting. Otherwise highlighting is
// wrong.
int scrollPos = _qsciEditorParent->verticalScrollBar()->value(); int scrollPos = _qsciEditorParent->verticalScrollBar()->value();
_qsciEditorParent->setText(_qsciEditorParent->text()); _qsciEditorParent->setText(_qsciEditorParent->text());
_qsciEditorParent->verticalScrollBar()->setValue(scrollPos); _qsciEditorParent->verticalScrollBar()->setValue(scrollPos);
} }
/*! /*!
\brief Turns the syntax parser on. \brief Turns the syntax parser on.
*/ */
void UiGuiHighlighter::turnHighlightOn() { void UiGuiHighlighter::turnHighlightOn()
{
_highlightningIsOn = true; _highlightningIsOn = true;
_qsciEditorParent->setLexer(_lexer); _qsciEditorParent->setLexer(_lexer);
readCurrentSettings(""); readCurrentSettings("");
@ -188,7 +195,8 @@ void UiGuiHighlighter::turnHighlightOn() {
/*! /*!
\brief Turns the syntax parser off. \brief Turns the syntax parser off.
*/ */
void UiGuiHighlighter::turnHighlightOff() { void UiGuiHighlighter::turnHighlightOff()
{
_highlightningIsOn = false; _highlightningIsOn = false;
_qsciEditorParent->setLexer(); _qsciEditorParent->setLexer();
#if defined (Q_OS_WIN) || defined (Q_OS_MAC) #if defined (Q_OS_WIN) || defined (Q_OS_MAC)
@ -200,12 +208,13 @@ void UiGuiHighlighter::turnHighlightOff() {
#endif #endif
} }
/*! /*!
\brief Read the settings for the current lexer from the settings file. \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. //TODO: Refactor this function so that the coding style and variable names suit better.
bool UiGuiHighlighter::readCurrentSettings( const char *prefix ) { bool UiGuiHighlighter::readCurrentSettings(const char *prefix)
{
bool ok, flag, rc = true; bool ok, flag, rc = true;
int num; int num;
TQString key; TQString key;
@ -215,10 +224,13 @@ bool UiGuiHighlighter::readCurrentSettings( const char *prefix ) {
_colorForStyles.clear(); _colorForStyles.clear();
// Read the styles. // Read the styles.
for (int i = 0; i < 128; ++i) { for (int i = 0; i < 128; ++i)
{
// Ignore invalid styles. // Ignore invalid styles.
if (_lexer->description(i).isEmpty()) if (_lexer->description(i).isEmpty())
{
continue; continue;
}
key.sprintf("%s/%s/style%d/", prefix, _lexer->language(), i); key.sprintf("%s/%s/style%d/", prefix, _lexer->language(), i);
key.replace("+", "p"); key.replace("+", "p");
@ -228,18 +240,26 @@ bool UiGuiHighlighter::readCurrentSettings( const char *prefix ) {
num = _settings->value(key + "color", 0).toInt(); num = _settings->value(key + "color", 0).toInt();
if (ok) if (ok)
{
setColor(TQColor((num >> 16) & 0xff, (num >> 8) & 0xff, num & 0xff), i); setColor(TQColor((num >> 16) & 0xff, (num >> 8) & 0xff, num & 0xff), i);
}
else else
{
rc = false; rc = false;
}
// Read the end-of-line fill. // Read the end-of-line fill.
ok = _settings->contains(key + "eolfill"); ok = _settings->contains(key + "eolfill");
flag = _settings->value(key + "eolfill", false).toBool(); flag = _settings->value(key + "eolfill", false).toBool();
if (ok) if (ok)
{
_lexer->setEolFill(flag, i); _lexer->setEolFill(flag, i);
}
else else
{
rc = false; rc = false;
}
// Read the font // Read the font
TQStringList fdesc; TQStringList fdesc;
@ -247,16 +267,21 @@ bool UiGuiHighlighter::readCurrentSettings( const char *prefix ) {
ok = _settings->contains(key + "font"); ok = _settings->contains(key + "font");
fdesc = _settings->value(key + "font").toStringList(); fdesc = _settings->value(key + "font").toStringList();
if (ok && fdesc.count() == 5) { if (ok && fdesc.count() == 5)
{
TQFont f; TQFont f;
#if defined (Q_OS_WIN) || defined (Q_OS_MAC) #if defined (Q_OS_WIN) || defined (Q_OS_MAC)
f.setFamily(fdesc[0]); f.setFamily(fdesc[0]);
#else #else
if (fdesc[0].contains("courier", TQt::CaseInsensitive)) if (fdesc[0].contains("courier", TQt::CaseInsensitive))
{
f.setFamily("Monospace"); f.setFamily("Monospace");
}
else else
{
f.setFamily(fdesc[0]); f.setFamily(fdesc[0]);
}
#endif #endif
f.setPointSize(fdesc[1].toInt()); f.setPointSize(fdesc[1].toInt());
f.setBold(fdesc[2].toInt()); f.setBold(fdesc[2].toInt());
@ -266,17 +291,23 @@ bool UiGuiHighlighter::readCurrentSettings( const char *prefix ) {
setFont(f, i); setFont(f, i);
} }
else else
{
rc = false; rc = false;
}
// Read the background color. // Read the background color.
ok = _settings->contains(key + "paper"); ok = _settings->contains(key + "paper");
num = _settings->value(key + "paper", 0).toInt(); num = _settings->value(key + "paper", 0).toInt();
if (ok) if (ok)
{
_lexer->setPaper(TQColor((num >> 16) & 0xff, (num >> 8) & 0xff, num & 0xff), i); _lexer->setPaper(TQColor((num >> 16) & 0xff, (num >> 8) & 0xff, num & 0xff), i);
}
else else
{
rc = false; rc = false;
} }
}
// Read the properties. // Read the properties.
key.sprintf("%s/%s/properties/", prefix, _lexer->language()); key.sprintf("%s/%s/properties/", prefix, _lexer->language());
@ -286,18 +317,21 @@ bool UiGuiHighlighter::readCurrentSettings( const char *prefix ) {
return rc; return rc;
} }
/*! /*!
\brief Write the settings for the current lexer to the settings file. \brief Write the settings for the current lexer to the settings file.
*/ */
void UiGuiHighlighter::writeCurrentSettings( const char *prefix ) { void UiGuiHighlighter::writeCurrentSettings(const char *prefix)
{
TQString key; TQString key;
// Write the styles. // Write the styles.
for (int i = 0; i < 128; ++i) { for (int i = 0; i < 128; ++i)
{
// Ignore invalid styles. // Ignore invalid styles.
if (_lexer->description(i).isEmpty()) if (_lexer->description(i).isEmpty())
{
continue; continue;
}
int num; int num;
TQColor c; TQColor c;
@ -309,10 +343,12 @@ void UiGuiHighlighter::writeCurrentSettings( const char *prefix ) {
_settings->setValue(key + "", _lexer->description(i)); _settings->setValue(key + "", _lexer->description(i));
// Write the foreground color. // Write the foreground color.
if ( _colorForStyles.contains(i) ) { if (_colorForStyles.contains(i))
{
c = _colorForStyles[i]; c = _colorForStyles[i];
} }
else { else
{
c = _lexer->color(i); c = _lexer->color(i);
} }
num = (c.red() << 16) | (c.green() << 8) | c.blue(); num = (c.red() << 16) | (c.green() << 8) | c.blue();
@ -327,10 +363,12 @@ void UiGuiHighlighter::writeCurrentSettings( const char *prefix ) {
TQString fmt("%1"); TQString fmt("%1");
TQFont f; TQFont f;
if ( _fontForStyles.contains(i) ) { if (_fontForStyles.contains(i))
{
f = _fontForStyles[i]; f = _fontForStyles[i];
} }
else { else
{
f = _lexer->font(i); f = _lexer->font(i);
} }
@ -352,148 +390,182 @@ void UiGuiHighlighter::writeCurrentSettings( const char *prefix ) {
} }
} }
/*! /*!
\brief Sets the \a color for the given \a style. \brief Sets the \a color for the given \a style.
*/ */
void UiGuiHighlighter::setColor(const TQColor &color, int style) { void UiGuiHighlighter::setColor(const TQColor &color, int style)
{
_colorForStyles[style] = color; _colorForStyles[style] = color;
_lexer->setColor(color, style); _lexer->setColor(color, style);
} }
/*! /*!
\brief Sets the \a font for the given \a style. \brief Sets the \a font for the given \a style.
*/ */
void UiGuiHighlighter::setFont(const TQFont &font, int style) { void UiGuiHighlighter::setFont(const TQFont &font, int style)
{
_fontForStyles[style] = font; _fontForStyles[style] = font;
_lexer->setFont(font, style); _lexer->setFont(font, style);
} }
/*! /*!
\brief Sets the to be used lexer by giving his name. \brief Sets the to be used lexer by giving his name.
*/ */
void UiGuiHighlighter::setLexerByName( TQString lexerName ) { void UiGuiHighlighter::setLexerByName(TQString lexerName)
{
setLexerForExtension(_mapHighlighternameToExtension[lexerName].first()); 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. \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 UiGuiHighlighter::setLexerForExtension(TQString extension)
{
int indexOfHighlighter = 0; int indexOfHighlighter = 0;
extension = extension.toLower(); extension = extension.toLower();
if ( _lexer != NULL ) { if (_lexer != NULL)
{
writeCurrentSettings(""); writeCurrentSettings("");
delete _lexer; delete _lexer;
} }
if ( extension == "cpp" || extension == "hpp" || extension == "c" || extension == "h" || extension == "cxx" || extension == "hxx" ) { if (extension == "cpp" || extension == "hpp" || extension == "c" || extension == "h" ||
extension == "cxx" || extension == "hxx")
{
_lexer = new QsciLexerCPP(); _lexer = new QsciLexerCPP();
} }
else if ( extension == "sh" ) { else if (extension == "sh")
{
_lexer = new QsciLexerBash(); _lexer = new QsciLexerBash();
} }
else if ( extension == "bat" ) { else if (extension == "bat")
{
_lexer = new QsciLexerBatch(); _lexer = new QsciLexerBatch();
} }
else if ( extension == "cmake" ) { else if (extension == "cmake")
{
_lexer = new QsciLexerCMake(); _lexer = new QsciLexerCMake();
} }
else if ( extension == "cs" ) { else if (extension == "cs")
{
_lexer = new QsciLexerCSharp(); _lexer = new QsciLexerCSharp();
} }
else if ( extension == "css" ) { else if (extension == "css")
{
_lexer = new QsciLexerCSS(); _lexer = new QsciLexerCSS();
} }
else if ( extension == "d" ) { else if (extension == "d")
{
_lexer = new QsciLexerD(); _lexer = new QsciLexerD();
} }
else if ( extension == "diff" ) { else if (extension == "diff")
{
_lexer = new QsciLexerDiff(); _lexer = new QsciLexerDiff();
} }
#if (TQSCINTILLA_VERSION >= 0x020300) #if (TQSCINTILLA_VERSION >= 0x020300)
else if ( extension == "f" || extension == "for" || extension == "f90" ) { else if (extension == "f" || extension == "for" || extension == "f90")
{
_lexer = new QsciLexerFortran(); _lexer = new QsciLexerFortran();
} }
else if ( extension == "f77" ) { else if (extension == "f77")
{
_lexer = new QsciLexerFortran77(); _lexer = new QsciLexerFortran77();
} }
#endif #endif
else if ( extension == "html" || extension == "htm" ) { else if (extension == "html" || extension == "htm")
{
_lexer = new QsciLexerHTML(); _lexer = new QsciLexerHTML();
} }
else if ( extension == "idl" ) { else if (extension == "idl")
{
_lexer = new QsciLexerIDL(); _lexer = new QsciLexerIDL();
} }
else if ( extension == "java" ) { else if (extension == "java")
{
_lexer = new QsciLexerJava(); _lexer = new QsciLexerJava();
} }
else if ( extension == "js" ) { else if (extension == "js")
{
_lexer = new QsciLexerJavaScript(); _lexer = new QsciLexerJavaScript();
} }
else if ( extension == "lua" ) { else if (extension == "lua")
{
_lexer = new QsciLexerLua(); _lexer = new QsciLexerLua();
} }
else if ( extension == "makefile" ) { else if (extension == "makefile")
{
_lexer = new QsciLexerMakefile(); _lexer = new QsciLexerMakefile();
} }
#if (TQSCINTILLA_VERSION >= 0x020300) #if (TQSCINTILLA_VERSION >= 0x020300)
else if ( extension == "pas" ) { else if (extension == "pas")
{
_lexer = new QsciLexerPascal(); _lexer = new QsciLexerPascal();
} }
#endif #endif
else if ( extension == "perl" || extension == "pl" || extension == "pm" ) { else if (extension == "perl" || extension == "pl" || extension == "pm")
{
_lexer = new QsciLexerPerl(); _lexer = new QsciLexerPerl();
} }
else if ( extension == "php" ) { else if (extension == "php")
{
_lexer = new QsciLexerHTML(); _lexer = new QsciLexerHTML();
} }
#if (TQSCINTILLA_VERSION >= 0x020300) #if (TQSCINTILLA_VERSION >= 0x020300)
else if ( extension == "ps" || extension == "eps" || extension == "pdf" || extension == "ai" || extension == "fh") { else if (extension == "ps" || extension == "eps" || extension == "pdf" || extension == "ai" ||
extension == "fh")
{
_lexer = new QsciLexerPostScript(); _lexer = new QsciLexerPostScript();
} }
#endif #endif
else if ( extension == "pov" ) { else if (extension == "pov")
{
_lexer = new QsciLexerPOV(); _lexer = new QsciLexerPOV();
} }
else if ( extension == "ini" ) { else if (extension == "ini")
{
_lexer = new QsciLexerProperties(); _lexer = new QsciLexerProperties();
} }
else if ( extension == "py" ) { else if (extension == "py")
{
_lexer = new QsciLexerPython(); _lexer = new QsciLexerPython();
} }
else if ( extension == "rub" || extension == "rb" ) { else if (extension == "rub" || extension == "rb")
{
_lexer = new QsciLexerRuby(); _lexer = new QsciLexerRuby();
} }
#if (TQSCINTILLA_VERSION >= 0x020400) #if (TQSCINTILLA_VERSION >= 0x020400)
else if ( extension == "spice?" ) { else if (extension == "spice?")
{
_lexer = new QsciLexerSpice(); _lexer = new QsciLexerSpice();
} }
#endif #endif
else if ( extension == "sql" ) { else if (extension == "sql")
{
_lexer = new QsciLexerSQL(); _lexer = new QsciLexerSQL();
} }
#if (TQSCINTILLA_VERSION >= 0x020300) #if (TQSCINTILLA_VERSION >= 0x020300)
else if ( extension == "tcl" ) { else if (extension == "tcl")
{
_lexer = new QsciLexerTCL(); _lexer = new QsciLexerTCL();
} }
#endif #endif
else if ( extension == "tex" ) { else if (extension == "tex")
{
_lexer = new QsciLexerTeX(); _lexer = new QsciLexerTeX();
} }
#if (TQSCINTILLA_VERSION >= 0x020400) #if (TQSCINTILLA_VERSION >= 0x020400)
else if ( extension == "vlog?" ) { else if (extension == "vlog?")
{
_lexer = new QsciLexerVerilog(); _lexer = new QsciLexerVerilog();
} }
#endif #endif
else if ( extension == "vhdl" ) { else if (extension == "vhdl")
{
_lexer = new QsciLexerVHDL(); _lexer = new QsciLexerVHDL();
} }
else if ( extension == "xml" ) { else if (extension == "xml")
{
#if (TQSCINTILLA_VERSION >= 0x020300) #if (TQSCINTILLA_VERSION >= 0x020300)
_lexer = new QsciLexerXML(); _lexer = new QsciLexerXML();
#else #else
@ -501,23 +573,27 @@ int UiGuiHighlighter::setLexerForExtension( TQString extension ) {
#endif #endif
} }
#if (TQSCINTILLA_VERSION >= 0x020300) #if (TQSCINTILLA_VERSION >= 0x020300)
else if ( extension == "yaml" ) { else if (extension == "yaml")
{
_lexer = new QsciLexerYAML(); _lexer = new QsciLexerYAML();
} }
#endif #endif
else { else
{
_lexer = new QsciLexerCPP(); _lexer = new QsciLexerCPP();
extension = "cpp"; extension = "cpp";
} }
// Find the index of the selected _lexer. // Find the index of the selected _lexer.
indexOfHighlighter = 0; indexOfHighlighter = 0;
while ( !_mapHighlighternameToExtension.values().at(indexOfHighlighter).contains(extension) ) { while (!_mapHighlighternameToExtension.values().at(indexOfHighlighter).contains(extension))
{
indexOfHighlighter++; indexOfHighlighter++;
} }
// Set the _lexer for the TQScintilla widget. // Set the _lexer for the TQScintilla widget.
if ( _highlightningIsOn ) { if (_highlightningIsOn)
{
_qsciEditorParent->setLexer(_lexer); _qsciEditorParent->setLexer(_lexer);
} }

@ -38,6 +38,7 @@ class UiGuiHighlighter : public TQObject
public: public:
UiGuiHighlighter(QsciScintilla *parent); UiGuiHighlighter(QsciScintilla *parent);
void turnHighlightOff(); void turnHighlightOff();
void turnHighlightOn(); void turnHighlightOn();

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

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

@ -35,6 +35,7 @@ public:
UiGuiIniFileParser(void); UiGuiIniFileParser(void);
UiGuiIniFileParser(const TQString &iniFileName); UiGuiIniFileParser(const TQString &iniFileName);
~UiGuiIniFileParser(void); ~UiGuiIniFileParser(void);
TQVariant value(const TQString &keyName, const TQString &defaultValue = ""); TQVariant value(const TQString &keyName, const TQString &defaultValue = "");
TQStringList childGroups(); TQStringList childGroups();

@ -48,22 +48,26 @@ TQWeakPointer<UiGuiSettings> UiGuiSettings::_instance;
/*! /*!
\brief The constructor for the settings. \brief The constructor for the settings.
*/ */
UiGuiSettings::UiGuiSettings() : TQObject() { UiGuiSettings::UiGuiSettings() :
TQObject()
{
// Create the main application settings object from the UniversalIndentGUI.ini file. // Create the main application settings object from the UniversalIndentGUI.ini file.
_qsettings = new TQSettings(SettingsPaths::getSettingsPath() + "/UniversalIndentGUI.ini", TQSettings::IniFormat, this); _qsettings = new TQSettings(
SettingsPaths::getSettingsPath() + "/UniversalIndentGUI.ini", TQSettings::IniFormat, this);
_indenterDirctoryStr = SettingsPaths::getGlobalFilesPath() + "/indenters"; _indenterDirctoryStr = SettingsPaths::getGlobalFilesPath() + "/indenters";
readAvailableTranslations(); readAvailableTranslations();
initSettings(); initSettings();
} }
/*! /*!
\brief Returns the instance of the settings class. If no instance exists, ONE will be created. \brief Returns the instance of the settings class. If no instance exists, ONE will be created.
*/ */
TQSharedPointer<UiGuiSettings> UiGuiSettings::getInstance() { TQSharedPointer<UiGuiSettings> UiGuiSettings::getInstance()
{
TQSharedPointer<UiGuiSettings> sharedInstance = _instance.toStrongRef(); TQSharedPointer<UiGuiSettings> sharedInstance = _instance.toStrongRef();
if ( sharedInstance.isNull() ) { if (sharedInstance.isNull())
{
// Create the settings object, which loads all UiGui settings from a file. // Create the settings object, which loads all UiGui settings from a file.
sharedInstance = TQSharedPointer<UiGuiSettings>(new UiGuiSettings()); sharedInstance = TQSharedPointer<UiGuiSettings>(new UiGuiSettings());
_instance = sharedInstance.toWeakRef(); _instance = sharedInstance.toWeakRef();
@ -72,29 +76,32 @@ TQSharedPointer<UiGuiSettings> UiGuiSettings::getInstance() {
return sharedInstance; return sharedInstance;
} }
/*! /*!
\brief The destructor saves the settings to a file. \brief The destructor saves the settings to a file.
*/ */
UiGuiSettings::~UiGuiSettings() { UiGuiSettings::~UiGuiSettings()
{
// Convert the language setting from an integer index to a string. // Convert the language setting from an integer index to a string.
int index = _qsettings->value("UniversalIndentGUI/language", 0).toInt(); int index = _qsettings->value("UniversalIndentGUI/language", 0).toInt();
if (index < 0 || index >= _availableTranslations.size()) if (index < 0 || index >= _availableTranslations.size())
{
index = 0; index = 0;
}
_qsettings->setValue("UniversalIndentGUI/language", _availableTranslations.at(index)); _qsettings->setValue("UniversalIndentGUI/language", _availableTranslations.at(index));
} }
/*! /*!
\brief Scans the translations directory for available translation files and \brief Scans the translations directory for available translation files and
stores them in the TQList \a _availableTranslations. stores them in the TQList \a _availableTranslations.
*/ */
void UiGuiSettings::readAvailableTranslations() { void UiGuiSettings::readAvailableTranslations()
{
TQString languageShort; TQString languageShort;
TQStringList languageFileList; TQStringList languageFileList;
// English is the default language. A translation file does not exist but to have a menu entry, added here. // English is the default language. A translation file does not exist but to have a menu entry,
// added here.
languageFileList << "universalindent_en.qm"; languageFileList << "universalindent_en.qm";
// Find all translation files in the "translations" directory. // Find all translation files in the "translations" directory.
@ -102,7 +109,8 @@ void UiGuiSettings::readAvailableTranslations() {
languageFileList << translationDirectory.entryList(TQStringList("universalindent_*.qm")); languageFileList << translationDirectory.entryList(TQStringList("universalindent_*.qm"));
// Loop for each found translation file // Loop for each found translation file
foreach ( languageShort, languageFileList ) { foreach(languageShort, languageFileList)
{
// Remove the leading string "universalindent_" from the filename. // Remove the leading string "universalindent_" from the filename.
languageShort.remove(0, 16); languageShort.remove(0, 16);
// Remove trailing file extension ".qm". // Remove trailing file extension ".qm".
@ -112,25 +120,24 @@ void UiGuiSettings::readAvailableTranslations() {
} }
} }
/*! /*!
\brief Returns a list of the mnemonics of the available translations. \brief Returns a list of the mnemonics of the available translations.
*/ */
TQStringList UiGuiSettings::getAvailableTranslations() { TQStringList UiGuiSettings::getAvailableTranslations()
{
return _availableTranslations; return _availableTranslations;
} }
/*! /*!
\brief Returns the value of the by \a settingsName defined setting as TQVariant. \brief Returns the value of the by \a settingsName defined setting as TQVariant.
If the named setting does not exist, 0 is being returned. If the named setting does not exist, 0 is being returned.
*/ */
TQVariant UiGuiSettings::getValueByName(TQString settingName) { TQVariant UiGuiSettings::getValueByName(TQString settingName)
{
return _qsettings->value("UniversalIndentGUI/" + settingName); return _qsettings->value("UniversalIndentGUI/" + settingName);
} }
/*! /*!
\brief Loads the settings for the main application. \brief Loads the settings for the main application.
@ -139,103 +146,136 @@ TQVariant UiGuiSettings::getValueByName(TQString settingName) {
bool UiGuiSettings::initSettings() bool UiGuiSettings::initSettings()
{ {
// Read the version string saved in the settings file. // Read the version string saved in the settings file.
_qsettings->setValue( "UniversalIndentGUI/version", _qsettings->value("UniversalIndentGUI/version", "") ); _qsettings->setValue("UniversalIndentGUI/version",
_qsettings->value("UniversalIndentGUI/version", ""));
// Read windows last size and position from the settings file. // Read windows last size and position from the settings file.
_qsettings->setValue( "UniversalIndentGUI/maximized", _qsettings->value("UniversalIndentGUI/maximized", false) ); _qsettings->setValue("UniversalIndentGUI/maximized",
_qsettings->setValue( "UniversalIndentGUI/position", _qsettings->value("UniversalIndentGUI/position", TQPoint(50, 50)) ); _qsettings->value("UniversalIndentGUI/maximized", false));
_qsettings->setValue( "UniversalIndentGUI/size", _qsettings->value("UniversalIndentGUI/size", TQSize(800, 600)) ); _qsettings->setValue("UniversalIndentGUI/position",
_qsettings->value("UniversalIndentGUI/position", TQPoint(50, 50)));
_qsettings->setValue("UniversalIndentGUI/size",
_qsettings->value("UniversalIndentGUI/size", TQSize(800, 600)));
// Read last selected encoding for the opened source code file. // Read last selected encoding for the opened source code file.
_qsettings->setValue( "UniversalIndentGUI/encoding", _qsettings->value("UniversalIndentGUI/encoding", "UTF-8") ); _qsettings->setValue("UniversalIndentGUI/encoding",
_qsettings->value("UniversalIndentGUI/encoding", "UTF-8"));
// Read maximum length of list for recently opened files. // Read maximum length of list for recently opened files.
_qsettings->setValue( "UniversalIndentGUI/recentlyOpenedListSize", _qsettings->value("UniversalIndentGUI/recentlyOpenedListSize", 5) ); _qsettings->setValue("UniversalIndentGUI/recentlyOpenedListSize",
_qsettings->value("UniversalIndentGUI/recentlyOpenedListSize", 5));
// Read if last opened source code file should be loaded on startup. // Read if last opened source code file should be loaded on startup.
_qsettings->setValue( "UniversalIndentGUI/loadLastSourceCodeFileOnStartup", _qsettings->value("UniversalIndentGUI/loadLastSourceCodeFileOnStartup", true) ); _qsettings->setValue("UniversalIndentGUI/loadLastSourceCodeFileOnStartup",
_qsettings->value("UniversalIndentGUI/loadLastSourceCodeFileOnStartup", true));
// Read last opened source code file from the settings file. // Read last opened source code file from the settings file.
_qsettings->setValue( "UniversalIndentGUI/lastSourceCodeFile", _qsettings->value("UniversalIndentGUI/lastSourceCodeFile", _indenterDirctoryStr+"/example.cpp") ); _qsettings->setValue("UniversalIndentGUI/lastSourceCodeFile",
_qsettings->value("UniversalIndentGUI/lastSourceCodeFile",
_indenterDirctoryStr + "/example.cpp"));
// Read last selected indenter from the settings file. // Read last selected indenter from the settings file.
int selectedIndenter = _qsettings->value("UniversalIndentGUI/selectedIndenter", 0).toInt(); int selectedIndenter = _qsettings->value("UniversalIndentGUI/selectedIndenter", 0).toInt();
if ( selectedIndenter < 0 ) { if (selectedIndenter < 0)
{
selectedIndenter = 0; selectedIndenter = 0;
} }
_qsettings->setValue("UniversalIndentGUI/selectedIndenter", selectedIndenter); _qsettings->setValue("UniversalIndentGUI/selectedIndenter", selectedIndenter);
// Read if syntax highlighting is enabled. // Read if syntax highlighting is enabled.
_qsettings->setValue( "UniversalIndentGUI/SyntaxHighlightingEnabled", _qsettings->value("UniversalIndentGUI/SyntaxHighlightingEnabled", true) ); _qsettings->setValue("UniversalIndentGUI/SyntaxHighlightingEnabled",
_qsettings->value("UniversalIndentGUI/SyntaxHighlightingEnabled", true));
// Read if white space characters should be displayed. // Read if white space characters should be displayed.
_qsettings->setValue( "UniversalIndentGUI/whiteSpaceIsVisible", _qsettings->value("UniversalIndentGUI/whiteSpaceIsVisible", false) ); _qsettings->setValue("UniversalIndentGUI/whiteSpaceIsVisible",
_qsettings->value("UniversalIndentGUI/whiteSpaceIsVisible", false));
// Read if indenter parameter tool tips are enabled. // Read if indenter parameter tool tips are enabled.
_qsettings->setValue( "UniversalIndentGUI/indenterParameterTooltipsEnabled", _qsettings->value("UniversalIndentGUI/indenterParameterTooltipsEnabled", true) ); _qsettings->setValue("UniversalIndentGUI/indenterParameterTooltipsEnabled",
_qsettings->value("UniversalIndentGUI/indenterParameterTooltipsEnabled", true));
// Read the tab width from the settings file. // Read the tab width from the settings file.
_qsettings->setValue( "UniversalIndentGUI/tabWidth", _qsettings->value("UniversalIndentGUI/tabWidth", 4) ); _qsettings->setValue("UniversalIndentGUI/tabWidth",
_qsettings->value("UniversalIndentGUI/tabWidth", 4));
// Read the last selected language and stores the index it has in the list of available translations. // Read the last selected language and stores the index it has in the list of available
_qsettings->setValue( "UniversalIndentGUI/language", _availableTranslations.indexOf( _qsettings->value("UniversalIndentGUI/language", "").toString() ) ); // translations.
_qsettings->setValue("UniversalIndentGUI/language",
_availableTranslations.indexOf(_qsettings->value("UniversalIndentGUI/language",
"").toString()));
// Read the update check settings from the settings file. // Read the update check settings from the settings file.
_qsettings->setValue( "UniversalIndentGUI/CheckForUpdate", _qsettings->value("UniversalIndentGUI/CheckForUpdate", false) ); _qsettings->setValue("UniversalIndentGUI/CheckForUpdate",
_qsettings->setValue( "UniversalIndentGUI/LastUpdateCheck", _qsettings->value("UniversalIndentGUI/LastUpdateCheck", TQDate(1900,1,1)) ); _qsettings->value("UniversalIndentGUI/CheckForUpdate", false));
_qsettings->setValue("UniversalIndentGUI/LastUpdateCheck",
_qsettings->value("UniversalIndentGUI/LastUpdateCheck", TQDate(1900, 1, 1)));
// Read the main window state. // Read the main window state.
_qsettings->setValue( "UniversalIndentGUI/MainWindowState", _qsettings->value("UniversalIndentGUI/MainWindowState", TQByteArray()) ); _qsettings->setValue("UniversalIndentGUI/MainWindowState",
_qsettings->value("UniversalIndentGUI/MainWindowState", TQByteArray()));
return true; return true;
} }
/*! /*!
\brief Register the by \a propertyName defined property of \a obj to be connected to the setting defined by \a settingName. \brief Register the by \a propertyName defined property of \a obj to be connected to the setting defined by \a settingName.
The \a propertyName must be one of those that are listed in the TQt "Properties" documentation section of a TQt Object. The \a propertyName must be one of those that are listed in the TQt "Properties" documentation section of a TQt Object.
All further needed info is retrieved via the \a obj's MetaObject, like the to the property bound signal. All further needed info is retrieved via the \a obj's MetaObject, like the to the property bound signal.
*/ */
bool UiGuiSettings::registerObjectProperty( TQObject *obj, const TQString &propertyName, const TQString &settingName ) bool UiGuiSettings::registerObjectProperty(TQObject *obj, const TQString &propertyName,
const TQString &settingName)
{ {
const TQMetaObject *metaObject = obj->metaObject(); const TQMetaObject *metaObject = obj->metaObject();
bool connectSuccess = false; bool connectSuccess = false;
// Connect to the objects destroyed signal, so that it will be correctly unregistered. // Connect to the objects destroyed signal, so that it will be correctly unregistered.
connectSuccess = connect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectProperty(TQObject*))); connectSuccess =
connect(obj, SIGNAL(destroyed(TQObject*)), this,
SLOT(unregisterObjectProperty(TQObject*)));
int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName)); int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName));
if ( connectSuccess && indexOfProp > -1 ) { if (connectSuccess && indexOfProp > -1)
{
TQMetaProperty mProp = metaObject->property(indexOfProp); TQMetaProperty mProp = metaObject->property(indexOfProp);
// Connect to the property's value changed signal. // Connect to the property's value changed signal.
if ( mProp.hasNotifySignal() ) { if (mProp.hasNotifySignal())
{
TQMetaMethod signal = mProp.notifySignal(); TQMetaMethod signal = mProp.notifySignal();
//TQString teststr = qPrintable(SIGNAL() + TQString(signal.signature())); //TQString teststr = qPrintable(SIGNAL() + TQString(signal.signature()));
// The command "SIGNAL() + TQString(signal.signature())" assembles the signal methods signature to a valid TQt SIGNAL. // The command "SIGNAL() + TQString(signal.signature())" assembles the signal methods
connectSuccess = connect(obj, qPrintable(SIGNAL() + TQString(signal.signature())), this, SLOT(handleObjectPropertyChange())); // signature to a valid TQt SIGNAL.
connectSuccess =
connect(obj, qPrintable(SIGNAL() + TQString(signal.signature())), this,
SLOT(handleObjectPropertyChange()));
} }
if ( connectSuccess ) { if (connectSuccess)
{
_registeredObjectProperties[obj] = TQStringList() << propertyName << settingName; _registeredObjectProperties[obj] = TQStringList() << propertyName << settingName;
} }
else { else
{
//TODO: Write a debug warning to the log. //TODO: Write a debug warning to the log.
disconnect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectProperty(TQObject*))); disconnect(obj, SIGNAL(destroyed(TQObject*)), this,
SLOT(unregisterObjectProperty(TQObject*)));
return false; return false;
} }
// If setting already exists, set the objects property to the setting value. // If setting already exists, set the objects property to the setting value.
if ( _qsettings->contains("UniversalIndentGUI/" + settingName) ) { if (_qsettings->contains("UniversalIndentGUI/" + settingName))
{
mProp.write(obj, _qsettings->value("UniversalIndentGUI/" + settingName)); mProp.write(obj, _qsettings->value("UniversalIndentGUI/" + settingName));
} }
// Otherwise add the setting and set it to the value of the objects property. // Otherwise add the setting and set it to the value of the objects property.
else { else
{
_qsettings->setValue("UniversalIndentGUI/" + settingName, mProp.read(obj)); _qsettings->setValue("UniversalIndentGUI/" + settingName, mProp.read(obj));
} }
} }
else { else
{
//TODO: Write a debug warning to the log. //TODO: Write a debug warning to the log.
disconnect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectProperty(TQObject*))); disconnect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectProperty(TQObject*)));
return false; return false;
@ -244,7 +284,6 @@ bool UiGuiSettings::registerObjectProperty( TQObject *obj, const TQString &prope
return true; return true;
} }
/*! /*!
\brief Searches the child TQObjects of \a obj for a property name and setting name definition within \brief Searches the child TQObjects of \a obj for a property name and setting name definition within
their custom properties and registers this property name to that setting name if both were found. their custom properties and registers this property name to that setting name if both were found.
@ -257,36 +296,41 @@ bool UiGuiSettings::registerObjectProperty( TQObject *obj, const TQString &prope
Returns true, if all found property and setting definitions could be successfully registered. Returns true, if all found property and setting definitions could be successfully registered.
Returns false, if any of those registrations fails. Returns false, if any of those registrations fails.
*/ */
bool UiGuiSettings::registerObjectPropertyRecursive(TQObject *obj) { bool UiGuiSettings::registerObjectPropertyRecursive(TQObject *obj)
{
return checkCustomPropertiesAndCallFunction(obj, &UiGuiSettings::registerObjectProperty); return checkCustomPropertiesAndCallFunction(obj, &UiGuiSettings::registerObjectProperty);
} }
/*! /*!
\brief Assigns the by \a settingName defined setting value to the by \a propertyName defined property of \a obj. \brief Assigns the by \a settingName defined setting value to the by \a propertyName defined property of \a obj.
Returns true, if the value could be assigned, otherwise returns false, which is the case if settingName doesn't exist Returns true, if the value could be assigned, otherwise returns false, which is the case if settingName doesn't exist
within the settings or if the mentioned propertyName wasn't found for the \a obj. within the settings or if the mentioned propertyName wasn't found for the \a obj.
*/ */
bool UiGuiSettings::setObjectPropertyToSettingValue( TQObject *obj, const TQString &propertyName, const TQString &settingName ) bool UiGuiSettings::setObjectPropertyToSettingValue(TQObject *obj, const TQString &propertyName,
const TQString &settingName)
{ {
const TQMetaObject *metaObject = obj->metaObject(); const TQMetaObject *metaObject = obj->metaObject();
int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName)); int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName));
if ( indexOfProp > -1 ) { if (indexOfProp > -1)
{
TQMetaProperty mProp = metaObject->property(indexOfProp); TQMetaProperty mProp = metaObject->property(indexOfProp);
// If setting already exists, set the objects property to the setting value. // If setting already exists, set the objects property to the setting value.
if ( _qsettings->contains("UniversalIndentGUI/" + settingName) ) { if (_qsettings->contains("UniversalIndentGUI/" + settingName))
{
mProp.write(obj, _qsettings->value("UniversalIndentGUI/" + settingName)); mProp.write(obj, _qsettings->value("UniversalIndentGUI/" + settingName));
} }
// The setting didn't exist so return that setting the objects property failed. // The setting didn't exist so return that setting the objects property failed.
else { else
{
//TODO: Write a debug warning to the log. //TODO: Write a debug warning to the log.
return false; return false;
} }
} }
else { else
{
//TODO: Write a debug warning to the log. //TODO: Write a debug warning to the log.
return false; return false;
} }
@ -294,7 +338,6 @@ bool UiGuiSettings::setObjectPropertyToSettingValue( TQObject *obj, const TQStri
return true; return true;
} }
/*! /*!
\brief Searches the child TQObjects of \a obj for a property name and setting name definition within \brief Searches the child TQObjects of \a obj for a property name and setting name definition within
their custom properties and sets each property to settings value. their custom properties and sets each property to settings value.
@ -306,11 +349,11 @@ bool UiGuiSettings::setObjectPropertyToSettingValue( TQObject *obj, const TQStri
Returns true, if all found property and setting definitions could be successfully registered. Returns true, if all found property and setting definitions could be successfully registered.
Returns false, if any of those registrations fails. Returns false, if any of those registrations fails.
*/ */
bool UiGuiSettings::setObjectPropertyToSettingValueRecursive(TQObject *obj) { bool UiGuiSettings::setObjectPropertyToSettingValueRecursive(TQObject *obj)
{
return checkCustomPropertiesAndCallFunction(obj, &UiGuiSettings::setObjectPropertyToSettingValue); return checkCustomPropertiesAndCallFunction(obj, &UiGuiSettings::setObjectPropertyToSettingValue);
} }
/*! /*!
\brief Assigns the by \a propertyName defined property's value of \a obj to the by \a settingName defined setting. \brief Assigns the by \a propertyName defined property's value of \a obj to the by \a settingName defined setting.
@ -319,17 +362,20 @@ bool UiGuiSettings::setObjectPropertyToSettingValueRecursive(TQObject *obj) {
Returns true, if the value could be assigned, otherwise returns false, which is the case if the mentioned Returns true, if the value could be assigned, otherwise returns false, which is the case if the mentioned
propertyName wasn't found for the \a obj. propertyName wasn't found for the \a obj.
*/ */
bool UiGuiSettings::setSettingToObjectPropertyValue( TQObject *obj, const TQString &propertyName, const TQString &settingName ) bool UiGuiSettings::setSettingToObjectPropertyValue(TQObject *obj, const TQString &propertyName,
const TQString &settingName)
{ {
const TQMetaObject *metaObject = obj->metaObject(); const TQMetaObject *metaObject = obj->metaObject();
int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName)); int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName));
if ( indexOfProp > -1 ) { if (indexOfProp > -1)
{
TQMetaProperty mProp = metaObject->property(indexOfProp); TQMetaProperty mProp = metaObject->property(indexOfProp);
setValueByName(settingName, mProp.read(obj)); setValueByName(settingName, mProp.read(obj));
} }
else { else
{
//TODO: Write a debug warning to the log. //TODO: Write a debug warning to the log.
return false; return false;
} }
@ -337,7 +383,6 @@ bool UiGuiSettings::setSettingToObjectPropertyValue( TQObject *obj, const TQStri
return true; return true;
} }
/*! /*!
\brief Searches the child TQObjects of \a obj for a property name and setting name definition within \brief Searches the child TQObjects of \a obj for a property name and setting name definition within
their custom properties and sets each setting to the property value. their custom properties and sets each setting to the property value.
@ -350,27 +395,32 @@ bool UiGuiSettings::setSettingToObjectPropertyValue( TQObject *obj, const TQStri
Returns true, if all found property and setting definitions could be successfully registered. Returns true, if all found property and setting definitions could be successfully registered.
Returns false, if any of those registrations fails. Returns false, if any of those registrations fails.
*/ */
bool UiGuiSettings::setSettingToObjectPropertyValueRecursive(TQObject *obj) { bool UiGuiSettings::setSettingToObjectPropertyValueRecursive(TQObject *obj)
{
return checkCustomPropertiesAndCallFunction(obj, &UiGuiSettings::setSettingToObjectPropertyValue); return checkCustomPropertiesAndCallFunction(obj, &UiGuiSettings::setSettingToObjectPropertyValue);
} }
/*! /*!
\brief Iterates over all \a objs child TQObjects and checks whether they have the custom properties \brief Iterates over all \a objs child TQObjects and checks whether they have the custom properties
"connectedPropertyName" and "connectedSettingName" set. If both are set, it invokes the \a callBackFunc "connectedPropertyName" and "connectedSettingName" set. If both are set, it invokes the \a callBackFunc
with both. with both.
*/ */
bool UiGuiSettings::checkCustomPropertiesAndCallFunction(TQObject *obj, bool (UiGuiSettings::*callBackFunc)(TQObject *obj, const TQString &propertyName, const TQString &settingName)) { bool UiGuiSettings::checkCustomPropertiesAndCallFunction(TQObject *obj, bool (UiGuiSettings::*callBackFunc)(
TQObject *obj, const TQString &propertyName,
const TQString &settingName))
{
bool success = true; bool success = true;
// Find all widgets that have PropertyName and SettingName defined in their style sheet. // Find all widgets that have PropertyName and SettingName defined in their style sheet.
TQList<TQObject*> allObjects = obj->findChildren<TQObject*>(); TQList<TQObject*> allObjects = obj->findChildren<TQObject*>();
foreach (TQObject *object, allObjects) { foreach(TQObject * object, allObjects)
{
TQString propertyName = object->property("connectedPropertyName").toString(); TQString propertyName = object->property("connectedPropertyName").toString();
TQString settingName = object->property("connectedSettingName").toString(); TQString settingName = object->property("connectedSettingName").toString();
// If property and setting name were found, register that widget with the settings. // If property and setting name were found, register that widget with the settings.
if ( !propertyName.isEmpty() && !settingName.isEmpty() ) { if (!propertyName.isEmpty() && !settingName.isEmpty())
{
success &= (this->*callBackFunc)(object, propertyName, settingName); success &= (this->*callBackFunc)(object, propertyName, settingName);
} }
} }
@ -378,33 +428,37 @@ bool UiGuiSettings::checkCustomPropertiesAndCallFunction(TQObject *obj, bool (Ui
return success; return success;
} }
/*! /*!
\brief The with a certain property registered \a obj gets unregistered. \brief The with a certain property registered \a obj gets unregistered.
*/ */
void UiGuiSettings::unregisterObjectProperty(TQObject *obj) { void UiGuiSettings::unregisterObjectProperty(TQObject *obj)
if ( _registeredObjectProperties.contains(obj) ) { {
if (_registeredObjectProperties.contains(obj))
{
const TQMetaObject *metaObject = obj->metaObject(); const TQMetaObject *metaObject = obj->metaObject();
TQString propertyName = _registeredObjectProperties[obj].first(); TQString propertyName = _registeredObjectProperties[obj].first();
TQString settingName = _registeredObjectProperties[obj].last(); TQString settingName = _registeredObjectProperties[obj].last();
bool connectSuccess = false; bool connectSuccess = false;
int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName)); int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName));
if ( indexOfProp > -1 ) { if (indexOfProp > -1)
{
TQMetaProperty mProp = metaObject->property(indexOfProp); TQMetaProperty mProp = metaObject->property(indexOfProp);
// Disconnect to the property's value changed signal. // Disconnect to the property's value changed signal.
if ( mProp.hasNotifySignal() ) { if (mProp.hasNotifySignal())
{
TQMetaMethod signal = mProp.notifySignal(); TQMetaMethod signal = mProp.notifySignal();
// The command "SIGNAL() + TQString(signal.signature())" assembles the signal methods signature to a valid TQt SIGNAL. // The command "SIGNAL() + TQString(signal.signature())" assembles the signal methods
connectSuccess = disconnect(obj, qPrintable(SIGNAL() + TQString(signal.signature())), this, SLOT(handleObjectPropertyChange())); // signature to a valid TQt SIGNAL.
connectSuccess = disconnect(obj, qPrintable(SIGNAL() + TQString(
signal.signature())), this, SLOT(handleObjectPropertyChange()));
} }
} }
_registeredObjectProperties.remove(obj); _registeredObjectProperties.remove(obj);
} }
} }
/*! /*!
\brief Registers a slot form the \a obj by its \a slotName to be invoked, if the by \a settingName defined \brief Registers a slot form the \a obj by its \a slotName to be invoked, if the by \a settingName defined
setting changes. setting changes.
@ -413,33 +467,39 @@ void UiGuiSettings::unregisterObjectProperty(TQObject *obj) {
\a settingName changes the slot gets tried to be invoked with the settings value as parameter. This only works, \a settingName changes the slot gets tried to be invoked with the settings value as parameter. This only works,
if the slot parameter is of the same type as the setting. if the slot parameter is of the same type as the setting.
*/ */
bool UiGuiSettings::registerObjectSlot(TQObject *obj, const TQString &slotName, const TQString &settingName) { bool UiGuiSettings::registerObjectSlot(TQObject *obj, const TQString &slotName,
const TQString &settingName)
{
const TQMetaObject *metaObject = obj->metaObject(); const TQMetaObject *metaObject = obj->metaObject();
bool connectSuccess = false; bool connectSuccess = false;
// Connect to the objects destroyed signal, so that it will be correctly unregistered. // Connect to the objects destroyed signal, so that it will be correctly unregistered.
connectSuccess = connect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectSlot(TQObject*))); connectSuccess =
connect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectSlot(TQObject*)));
TQString normalizedSlotName = TQMetaObject::normalizedSignature(qPrintable(slotName)); TQString normalizedSlotName = TQMetaObject::normalizedSignature(qPrintable(slotName));
int indexOfMethod = metaObject->indexOfMethod(qPrintable(normalizedSlotName)); int indexOfMethod = metaObject->indexOfMethod(qPrintable(normalizedSlotName));
if ( connectSuccess && indexOfMethod > -1 ) { if (connectSuccess && indexOfMethod > -1)
{
TQMetaMethod mMethod = metaObject->method(indexOfMethod); TQMetaMethod mMethod = metaObject->method(indexOfMethod);
//TQMetaMethod::Access access = mMethod.access(); //TQMetaMethod::Access access = mMethod.access();
//TQMetaMethod::MethodType methType = mMethod.methodType(); //TQMetaMethod::MethodType methType = mMethod.methodType();
// Since the method can at maximum be invoked with the setting value as argument, // Since the method can at maximum be invoked with the setting value as argument,
// only methods taking max one argument are allowed. // only methods taking max one argument are allowed.
if ( mMethod.parameterTypes().size() <= 1 ) { if (mMethod.parameterTypes().size() <= 1)
{
_registeredObjectSlots.insert(obj, TQStringList() << normalizedSlotName << settingName); _registeredObjectSlots.insert(obj, TQStringList() << normalizedSlotName << settingName);
} }
else { else
{
//TODO: Write a debug warning to the log. //TODO: Write a debug warning to the log.
disconnect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectSlot(TQObject*))); disconnect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectSlot(TQObject*)));
return false; return false;
} }
} }
else { else
{
//TODO: Write a debug warning to the log. //TODO: Write a debug warning to the log.
disconnect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectSlot(TQObject*))); disconnect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectSlot(TQObject*)));
return false; return false;
@ -448,30 +508,36 @@ bool UiGuiSettings::registerObjectSlot(TQObject *obj, const TQString &slotName,
return true; return true;
} }
/*! /*!
\brief If \a obj, \a slotName and \a settingName are given, that certain connection is unregistered. \brief If \a obj, \a slotName and \a settingName are given, that certain connection is unregistered.
If only \a obj is given, all to this object registered slot-setting connections are unregistered. If only \a obj is given, all to this object registered slot-setting connections are unregistered.
*/ */
void UiGuiSettings::unregisterObjectSlot(TQObject *obj, const TQString &slotName, const TQString &settingName) { void UiGuiSettings::unregisterObjectSlot(TQObject *obj, const TQString &slotName,
const TQString &settingName)
{
//const TQMetaObject *metaObject = obj->metaObject(); //const TQMetaObject *metaObject = obj->metaObject();
TQString normalizedSlotName = TQMetaObject::normalizedSignature(qPrintable(slotName)); TQString normalizedSlotName = TQMetaObject::normalizedSignature(qPrintable(slotName));
TQMutableMapIterator<TQObject*, TQStringList> it(_registeredObjectSlots); TQMutableMapIterator<TQObject*, TQStringList> it(_registeredObjectSlots);
while (it.hasNext()) { while (it.hasNext())
{
it.next(); it.next();
if (it.key() == obj && slotName.isEmpty() && settingName.isEmpty()) if (it.key() == obj && slotName.isEmpty() && settingName.isEmpty())
{
it.remove(); it.remove();
}
else if (it.key() == obj && it.value().first() == slotName && it.value().last() == settingName) else if (it.key() == obj && it.value().first() == slotName && it.value().last() == settingName)
{
it.remove(); it.remove();
} }
} }
}
/*! /*!
\brief This private slot gets invoked whenever a registered objects property changes \brief This private slot gets invoked whenever a registered objects property changes
and distributes the new value to all other to the same settingName registered objects. and distributes the new value to all other to the same settingName registered objects.
*/ */
void UiGuiSettings::handleObjectPropertyChange() { void UiGuiSettings::handleObjectPropertyChange()
{
TQObject *obj = TQObject::sender(); TQObject *obj = TQObject::sender();
TQString className = obj->metaObject()->className(); TQString className = obj->metaObject()->className();
const TQMetaObject *metaObject = obj->metaObject(); const TQMetaObject *metaObject = obj->metaObject();
@ -479,13 +545,13 @@ void UiGuiSettings::handleObjectPropertyChange() {
TQString settingName = _registeredObjectProperties[obj].last(); TQString settingName = _registeredObjectProperties[obj].last();
int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName)); int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName));
if ( indexOfProp > -1 ) { if (indexOfProp > -1)
{
TQMetaProperty mProp = metaObject->property(indexOfProp); TQMetaProperty mProp = metaObject->property(indexOfProp);
setValueByName(settingName, mProp.read(obj)); setValueByName(settingName, mProp.read(obj));
} }
} }
/*! /*!
\brief Sets the setting defined by \a settingName to \a value. \brief Sets the setting defined by \a settingName to \a value.
@ -493,20 +559,26 @@ void UiGuiSettings::handleObjectPropertyChange() {
the changed value set too. the changed value set too.
If the \a settingName didn't exist yet, it will be created. If the \a settingName didn't exist yet, it will be created.
*/ */
void UiGuiSettings::setValueByName(const TQString &settingName, const TQVariant &value) { void UiGuiSettings::setValueByName(const TQString &settingName, const TQVariant &value)
{
// Do the updating only, if the setting was really changed. // Do the updating only, if the setting was really changed.
if ( _qsettings->value("UniversalIndentGUI/" + settingName) != value ) { if (_qsettings->value("UniversalIndentGUI/" + settingName) != value)
{
_qsettings->setValue("UniversalIndentGUI/" + settingName, value); _qsettings->setValue("UniversalIndentGUI/" + settingName, value);
// Set the new value for all registered object properties for settingName. // Set the new value for all registered object properties for settingName.
for ( TQMap<TQObject*, TQStringList>::ConstIterator it = _registeredObjectProperties.begin(); it != _registeredObjectProperties.end(); ++it ) { for (TQMap<TQObject*, TQStringList>::ConstIterator it = _registeredObjectProperties.begin();
if ( it.value().last() == settingName ) { it != _registeredObjectProperties.end(); ++it)
{
if (it.value().last() == settingName)
{
TQObject *obj = it.key(); TQObject *obj = it.key();
const TQMetaObject *metaObject = obj->metaObject(); const TQMetaObject *metaObject = obj->metaObject();
TQString propertyName = it.value().first(); TQString propertyName = it.value().first();
int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName)); int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName));
if ( indexOfProp > -1 ) { if (indexOfProp > -1)
{
TQMetaProperty mProp = metaObject->property(indexOfProp); TQMetaProperty mProp = metaObject->property(indexOfProp);
mProp.write(obj, value); mProp.write(obj, value);
} }
@ -514,14 +586,18 @@ void UiGuiSettings::setValueByName(const TQString &settingName, const TQVariant
} }
// Invoke all registered object methods for settingName. // Invoke all registered object methods for settingName.
for ( TQMap<TQObject*, TQStringList>::ConstIterator it = _registeredObjectSlots.begin(); it != _registeredObjectSlots.end(); ++it ) { for (TQMap<TQObject*, TQStringList>::ConstIterator it = _registeredObjectSlots.begin();
if ( it.value().last() == settingName ) { it != _registeredObjectSlots.end(); ++it)
{
if (it.value().last() == settingName)
{
TQObject *obj = it.key(); TQObject *obj = it.key();
const TQMetaObject *metaObject = obj->metaObject(); const TQMetaObject *metaObject = obj->metaObject();
TQString slotName = it.value().first(); TQString slotName = it.value().first();
int indexOfMethod = metaObject->indexOfMethod(qPrintable(slotName)); int indexOfMethod = metaObject->indexOfMethod(qPrintable(slotName));
if ( indexOfMethod > -1 ) { if (indexOfMethod > -1)
{
TQMetaMethod mMethod = metaObject->method(indexOfMethod); TQMetaMethod mMethod = metaObject->method(indexOfMethod);
//TQMetaMethod::Access access = mMethod.access(); //TQMetaMethod::Access access = mMethod.access();
//TQMetaMethod::MethodType methType = mMethod.methodType(); //TQMetaMethod::MethodType methType = mMethod.methodType();
@ -529,17 +605,21 @@ void UiGuiSettings::setValueByName(const TQString &settingName, const TQVariant
bool success = false; bool success = false;
// Handle registered slots taking one parameter. // Handle registered slots taking one parameter.
if ( mMethod.parameterTypes().size() == 1 ) { if (mMethod.parameterTypes().size() == 1)
if ( mMethod.parameterTypes().first() == value.typeName() ) { {
if (mMethod.parameterTypes().first() == value.typeName())
{
success = invokeMethodWithValue(obj, mMethod, value); success = invokeMethodWithValue(obj, mMethod, value);
} }
} }
// Handle registered slots taking zero parameters. // Handle registered slots taking zero parameters.
else { else
{
success = mMethod.invoke(obj, TQt::DirectConnection); success = mMethod.invoke(obj, TQt::DirectConnection);
} }
if ( success == false ) { if (success == false)
{
// TODO: Write a warning to the log if no success. // TODO: Write a warning to the log if no success.
} }
} }
@ -548,7 +628,6 @@ void UiGuiSettings::setValueByName(const TQString &settingName, const TQVariant
} }
} }
#include <tntqbitarray.h> #include <tntqbitarray.h>
#include <tntqbitmap.h> #include <tntqbitmap.h>
#include <tntqbrush.h> #include <tntqbrush.h>
@ -571,118 +650,284 @@ void UiGuiSettings::setValueByName(const TQString &settingName, const TQVariant
bool UiGuiSettings::invokeMethodWithValue(TQObject *obj, TQMetaMethod mMethod, TQVariant value) bool UiGuiSettings::invokeMethodWithValue(TQObject *obj, TQMetaMethod mMethod, TQVariant value)
{ {
switch (value.type()) { switch (value.type())
{
case TQVariant::BitArray: case TQVariant::BitArray:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQBitArray, value.toBitArray())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQBitArray, value.toBitArray()));
}
case TQVariant::Bitmap: case TQVariant::Bitmap:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQBitmap, value.value<TQBitmap>())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQBitmap, value.value<TQBitmap>()));
}
case TQVariant::Bool: case TQVariant::Bool:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(bool, value.toBool())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(bool, value.toBool()));
}
case TQVariant::Brush: case TQVariant::Brush:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQBrush, value.value<TQBrush>())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQBrush, value.value<TQBrush>()));
}
case TQVariant::ByteArray: case TQVariant::ByteArray:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQByteArray, value.toByteArray())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQByteArray, value.toByteArray()));
}
case TQVariant::Char: case TQVariant::Char:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQChar, value.toChar())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQChar, value.toChar()));
}
case TQVariant::Color: case TQVariant::Color:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQColor, value.value<TQColor>())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQColor, value.value<TQColor>()));
}
case TQVariant::Cursor: case TQVariant::Cursor:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQCursor, value.value<TQCursor>())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQCursor, value.value<TQCursor>()));
}
case TQVariant::Date: case TQVariant::Date:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQDate, value.toDate())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQDate, value.toDate()));
}
case TQVariant::DateTime: case TQVariant::DateTime:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQDateTime, value.toDateTime())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQDateTime, value.toDateTime()));
}
case TQVariant::Double: case TQVariant::Double:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(double, value.toDouble())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(double, value.toDouble()));
}
case TQVariant::Font: case TQVariant::Font:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQFont, value.value<TQFont>())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQFont, value.value<TQFont>()));
}
case TQVariant::Hash: case TQVariant::Hash:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQVariantHash, value.toHash())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQVariantHash, value.toHash()));
}
case TQVariant::Icon: case TQVariant::Icon:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQIcon, value.value<TQIcon>())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQIcon, value.value<TQIcon>()));
}
case TQVariant::Image: case TQVariant::Image:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQImage, value.value<TQImage>())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQImage, value.value<TQImage>()));
}
case TQVariant::Int: case TQVariant::Int:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(int, value.toInt())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(int, value.toInt()));
}
case TQVariant::KeySequence: case TQVariant::KeySequence:
return mMethod.invoke( obj, TQt::DirectConnection, Q_ARG(TQKeySequence, value.value<TQKeySequence>()) ); {
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQKeySequence,
value.value<TQKeySequence>()));
}
case TQVariant::Line: case TQVariant::Line:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQLine, value.toLine())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQLine, value.toLine()));
}
case TQVariant::LineF: case TQVariant::LineF:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQLineF, value.toLineF())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQLineF, value.toLineF()));
}
case TQVariant::List: case TQVariant::List:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQVariantList, value.toList())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQVariantList, value.toList()));
}
case TQVariant::Locale: case TQVariant::Locale:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQLocale, value.toLocale())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQLocale, value.toLocale()));
}
case TQVariant::LongLong: case TQVariant::LongLong:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(qlonglong, value.toLongLong())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(qlonglong, value.toLongLong()));
}
case TQVariant::Map: case TQVariant::Map:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQVariantMap, value.toMap())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQVariantMap, value.toMap()));
}
case TQVariant::Matrix: case TQVariant::Matrix:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQMatrix, value.value<TQMatrix>())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQMatrix, value.value<TQMatrix>()));
}
case TQVariant::Transform: case TQVariant::Transform:
return mMethod.invoke( obj, TQt::DirectConnection, Q_ARG(TQTransform, value.value<TQTransform>()) ); {
return mMethod.invoke(obj, TQt::DirectConnection,
Q_ARG(TQTransform, value.value<TQTransform>()));
}
#if TQT_VERSION >= 0x040600 #if TQT_VERSION >= 0x040600
case TQVariant::Matrix4x4: case TQVariant::Matrix4x4:
return mMethod.invoke( obj, TQt::DirectConnection, Q_ARG(TQMatrix4x4, value.value<TQMatrix4x4>()) ); {
return mMethod.invoke(obj, TQt::DirectConnection,
Q_ARG(TQMatrix4x4, value.value<TQMatrix4x4>()));
}
#endif #endif
case TQVariant::Palette: case TQVariant::Palette:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPalette, value.value<TQPalette>())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPalette, value.value<TQPalette>()));
}
case TQVariant::Pen: case TQVariant::Pen:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPen, value.value<TQPen>())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPen, value.value<TQPen>()));
}
case TQVariant::Pixmap: case TQVariant::Pixmap:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPixmap, value.value<TQPixmap>())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPixmap, value.value<TQPixmap>()));
}
case TQVariant::Point: case TQVariant::Point:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPoint, value.toPoint())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPoint, value.toPoint()));
}
// case TQVariant::PointArray : // case TQVariant::PointArray :
// return Q_ARG(TQPointArray, value.value<TQPointArray>()) ); // return Q_ARG(TQPointArray, value.value<TQPointArray>()) );
case TQVariant::PointF: case TQVariant::PointF:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPointF, value.toPointF())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPointF, value.toPointF()));
}
case TQVariant::Polygon: case TQVariant::Polygon:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPolygon, value.value<TQPolygon>())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPolygon, value.value<TQPolygon>()));
}
#if TQT_VERSION >= 0x040600 #if TQT_VERSION >= 0x040600
case TQVariant::Quaternion: case TQVariant::Quaternion:
return mMethod.invoke( obj, TQt::DirectConnection, Q_ARG(TQQuaternion, value.value<TQQuaternion>()) ); {
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQQuaternion,
value.value<TQQuaternion>()));
}
#endif #endif
case TQVariant::Rect: case TQVariant::Rect:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQRect, value.toRect())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQRect, value.toRect()));
}
case TQVariant::RectF: case TQVariant::RectF:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQRectF, value.toRectF())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQRectF, value.toRectF()));
}
case TQVariant::RegExp: case TQVariant::RegExp:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQRegExp, value.toRegExp())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQRegExp, value.toRegExp()));
}
case TQVariant::Region: case TQVariant::Region:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQRegion, value.value<TQRegion>())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQRegion, value.value<TQRegion>()));
}
case TQVariant::Size: case TQVariant::Size:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQSize, value.toSize())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQSize, value.toSize()));
}
case TQVariant::SizeF: case TQVariant::SizeF:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQSizeF, value.toSizeF())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQSizeF, value.toSizeF()));
}
case TQVariant::SizePolicy: case TQVariant::SizePolicy:
return mMethod.invoke( obj, TQt::DirectConnection, Q_ARG(TQSizePolicy, value.value<TQSizePolicy>()) ); {
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQSizePolicy,
value.value<TQSizePolicy>()));
}
case TQVariant::String: case TQVariant::String:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQString, value.toString())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQString, value.toString()));
}
case TQVariant::StringList: case TQVariant::StringList:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQStringList, value.toStringList())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQStringList, value.toStringList()));
}
case TQVariant::TextFormat: case TQVariant::TextFormat:
return mMethod.invoke( obj, TQt::DirectConnection, Q_ARG(TQTextFormat, value.value<TQTextFormat>()) ); {
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQTextFormat,
value.value<TQTextFormat>()));
}
case TQVariant::TextLength: case TQVariant::TextLength:
return mMethod.invoke( obj, TQt::DirectConnection, Q_ARG(TQTextLength, value.value<TQTextLength>()) ); {
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQTextLength,
value.value<TQTextLength>()));
}
case TQVariant::Time: case TQVariant::Time:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQTime, value.toTime())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQTime, value.toTime()));
}
case TQVariant::UInt: case TQVariant::UInt:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(uint, value.toUInt())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(uint, value.toUInt()));
}
case TQVariant::ULongLong: case TQVariant::ULongLong:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(qulonglong, value.toULongLong())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(qulonglong, value.toULongLong()));
}
case TQVariant::Url: case TQVariant::Url:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQUrl, value.toUrl())); return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQUrl, value.toUrl()));
}
#if TQT_VERSION >= 0x040600 #if TQT_VERSION >= 0x040600
case TQVariant::Vector2D: case TQVariant::Vector2D:
return mMethod.invoke( obj, TQt::DirectConnection, Q_ARG(TQVector2D, value.value<TQVector2D>()) ); {
return mMethod.invoke(obj, TQt::DirectConnection,
Q_ARG(TQVector2D, value.value<TQVector2D>()));
}
case TQVariant::Vector3D: case TQVariant::Vector3D:
return mMethod.invoke( obj, TQt::DirectConnection, Q_ARG(TQVector3D, value.value<TQVector3D>()) ); {
return mMethod.invoke(obj, TQt::DirectConnection,
Q_ARG(TQVector3D, value.value<TQVector3D>()));
}
case TQVariant::Vector4D: case TQVariant::Vector4D:
return mMethod.invoke( obj, TQt::DirectConnection, Q_ARG(TQVector4D, value.value<TQVector4D>()) ); {
return mMethod.invoke(obj, TQt::DirectConnection,
Q_ARG(TQVector4D, value.value<TQVector4D>()));
}
#endif #endif
default: default:
{
return false; return false;
} }
} }
}

@ -31,33 +31,44 @@ class TQSettings;
class UiGuiSettings : public TQObject class UiGuiSettings : public TQObject
{ {
Q_OBJECT Q_OBJECT
private: private:
UiGuiSettings(); UiGuiSettings();
static TQWeakPointer<UiGuiSettings> _instance; static TQWeakPointer<UiGuiSettings> _instance;
public: public:
static TQSharedPointer<UiGuiSettings> getInstance(); static TQSharedPointer<UiGuiSettings> getInstance();
~UiGuiSettings(); ~UiGuiSettings();
bool registerObjectProperty(TQObject *obj, const TQString &propertyName, const TQString &settingName); bool registerObjectProperty(TQObject *obj, const TQString &propertyName,
const TQString &settingName);
bool registerObjectPropertyRecursive(TQObject *obj); bool registerObjectPropertyRecursive(TQObject *obj);
bool setObjectPropertyToSettingValue(TQObject *obj, const TQString &propertyName, const TQString &settingName); bool setObjectPropertyToSettingValue(TQObject *obj, const TQString &propertyName,
const TQString &settingName);
bool setObjectPropertyToSettingValueRecursive(TQObject *obj); bool setObjectPropertyToSettingValueRecursive(TQObject *obj);
bool setSettingToObjectPropertyValue(TQObject *obj, const TQString &propertyName, const TQString &settingName); bool setSettingToObjectPropertyValue(TQObject *obj, const TQString &propertyName,
const TQString &settingName);
bool setSettingToObjectPropertyValueRecursive(TQObject *obj); bool setSettingToObjectPropertyValueRecursive(TQObject *obj);
bool registerObjectSlot(TQObject *obj, const TQString &slotName, const TQString &settingName); bool registerObjectSlot(TQObject *obj, const TQString &slotName,
const TQString &settingName);
TQVariant getValueByName(TQString settingName); TQVariant getValueByName(TQString settingName);
TQStringList getAvailableTranslations(); TQStringList getAvailableTranslations();
public slots: public slots:
void setValueByName(const TQString &settingName, const TQVariant &value); void setValueByName(const TQString &settingName, const TQVariant &value);
void unregisterObjectProperty(TQObject *obj); void unregisterObjectProperty(TQObject *obj);
void unregisterObjectSlot(TQObject *obj, const TQString &slotName = "", const TQString &settingName = ""); void unregisterObjectSlot(TQObject *obj, const TQString &slotName = "",
const TQString &settingName = "");
protected: protected:
bool initSettings(); bool initSettings();
bool invokeMethodWithValue(TQObject *obj, TQMetaMethod mMethod, TQVariant value); bool invokeMethodWithValue(TQObject *obj, TQMetaMethod mMethod, TQVariant value);
bool checkCustomPropertiesAndCallFunction(TQObject *obj, bool (UiGuiSettings::*callBackFunc)(TQObject *obj, const TQString &propertyName, const TQString &settingName));
bool checkCustomPropertiesAndCallFunction(TQObject * obj,
bool (UiGuiSettings::*callBackFunc)(TQObject *obj, const TQString &propertyName,
const TQString &settingName));
private slots: private slots:
void handleObjectPropertyChange(); void handleObjectPropertyChange();
@ -71,7 +82,8 @@ private:
//! The settings file. //! The settings file.
TQSettings *_qsettings; TQSettings *_qsettings;
//! Maps an TQObject to a string list containing the property name and the associated setting name. //! Maps an TQObject to a string list containing the property name and the associated setting
// name.
TQMap<TQObject*, TQStringList> _registeredObjectProperties; TQMap<TQObject*, TQStringList> _registeredObjectProperties;
//! Maps TQObjects to a string list containing the method name and the associated setting name. //! Maps TQObjects to a string list containing the method name and the associated setting name.

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

@ -24,7 +24,8 @@
#include "UiGuiSettings.h" #include "UiGuiSettings.h"
namespace Ui { namespace Ui
{
class SettingsDialog; class SettingsDialog;
} }

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

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

@ -29,11 +29,10 @@ class TQString;
#define RESOURCE_VERSION_STRING "1,2,0,0\0" #define RESOURCE_VERSION_STRING "1,2,0,0\0"
#define PROGRAM_REVISION "$Revision: 1070 $" #define PROGRAM_REVISION "$Revision: 1070 $"
namespace UiGuiVersion { namespace UiGuiVersion
{
TQString getBuildDate(); TQString getBuildDate();
TQString getBuildRevision(); TQString getBuildRevision();
} }
#endif // UIGUIVERSION_H #endif // UIGUIVERSION_H

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

@ -24,7 +24,8 @@
#include <tqdialogbuttonbox.h> #include <tqdialogbuttonbox.h>
class UiGuiSettings; class UiGuiSettings;
namespace Ui { namespace Ui
{
class UpdateCheckDialog; class UpdateCheckDialog;
} }

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

@ -23,12 +23,15 @@
#include <tntqdialog.h> #include <tntqdialog.h>
#include <tntqfile.h> #include <tntqfile.h>
namespace Ui { namespace Ui
{
class TSLoggerDialog; class TSLoggerDialog;
} }
namespace tschweitzer { namespace debugging { namespace tschweitzer
{
namespace debugging
{
#define TSLoggerInfoMsg TQtMsgType(4) #define TSLoggerInfoMsg TQtMsgType(4)
class TSLogger : public TQDialog class TSLogger : public TQDialog
@ -48,8 +51,14 @@ private slots:
private: private:
Ui::TSLoggerDialog *_TSLoggerDialogForm; Ui::TSLoggerDialog *_TSLoggerDialogForm;
enum LogFileInitState { NOTINITIALZED, INITIALIZING, INITIALZED } _logFileInitState; enum LogFileInitState
{
NOTINITIALZED,
INITIALIZING,
INITIALZED
} _logFileInitState;
TSLogger(int verboseLevel); TSLogger(int verboseLevel);
void writeToLogFile(const TQString &message); void writeToLogFile(const TQString &message);
static TSLogger *_instance; static TSLogger *_instance;
@ -57,7 +66,7 @@ private:
TQFile _logFile; TQFile _logFile;
TQStringList _messageQueue; TQStringList _messageQueue;
}; };
}
}} // namespace tschweitzer::debugging } // namespace tschweitzer::debugging
#endif // TSLogger_H #endif // TSLogger_H

@ -65,15 +65,18 @@ int main(int argc, char *argv[])
// -- // because exceptions will be thrown for problems. // -- // because exceptions will be thrown for problems.
// -- try { // -- try {
// -- // Define the command line object. // -- // 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); // -- 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); // -- cmd.setExceptionHandling(false);
// -- // --
// -- // Define a value argument and add it to the command line. // -- // 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"); // -- TCLAP::UnlabeledValueArg<std::string> filenameArg("file", "Opens the by
// filename defined file on start" , false, "", "filename");
// -- cmd.add( filenameArg ); // -- cmd.add( filenameArg );
// -- // --
// -- // Define a switch and add it to the command line. // -- // 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); // -- TCLAP::SwitchArg pluginSwitch("p", "plugin", "Run as plugin. Server will be started with
// a simplified gui", false);
// -- cmd.add( pluginSwitch ); // -- cmd.add( pluginSwitch );
// -- // --
// -- // Define a switch and add it to the command line. // -- // Define a switch and add it to the command line.
@ -81,7 +84,8 @@ int main(int argc, char *argv[])
// -- cmd.add( serverSwitch ); // -- cmd.add( serverSwitch );
// -- // --
// -- // Define a value argument and add it to the command line. // -- // 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"); // -- 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 ); // -- cmd.add( verboselevelArg );
// -- // --
// -- // Parse the args. // -- // Parse the args.
@ -102,7 +106,8 @@ int main(int argc, char *argv[])
// -- returnValue = e.getExitStatus(); // -- returnValue = e.getExitStatus();
// -- } // -- }
// -- catch (...) { // catch any exceptions // -- catch (...) { // catch any exceptions
// -- std::cerr << std::endl << "There was an error! Maybe faulty command line arguments set. See --help." << std::endl; // -- std::cerr << std::endl << "There was an error! Maybe faulty command line arguments set.
// See --help." << std::endl;
// -- returnValue = 1; // -- returnValue = 1;
// -- } // -- }
// -- // --
@ -116,18 +121,22 @@ int main(int argc, char *argv[])
// -- IndentHandler *indentHandler = NULL; // -- IndentHandler *indentHandler = NULL;
// -- // --
// -- // Init and install the logger function. // -- // Init and install the logger function.
// -- // Setting UTF-8 as default 8-Bit encoding to ensure that tqDebug does no false string conversion. // -- // Setting UTF-8 as default 8-Bit encoding to ensure that tqDebug does no false string
// conversion.
// -- TQTextCodec::setCodecForCStrings( TQTextCodec::codecForName("UTF-8") ); // -- TQTextCodec::setCodecForCStrings( TQTextCodec::codecForName("UTF-8") );
// -- TQTextCodec::setCodecForLocale( TQTextCodec::codecForName("UTF-8") ); // -- TQTextCodec::setCodecForLocale( TQTextCodec::codecForName("UTF-8") );
// -- // Force creation of an TSLogger instance here, to avoid recursion with SettingsPaths init function. // -- // Force creation of an TSLogger instance here, to avoid recursion with SettingsPaths
// init function.
// -- #ifdef _DEBUG // -- #ifdef _DEBUG
// -- TSLogger::getInstance(0); // -- TSLogger::getInstance(0);
// -- #else // -- #else
// -- TSLogger::getInstance(verboseLevel); // -- TSLogger::getInstance(verboseLevel);
// -- #endif // -- #endif
// -- qInstallMsgHandler( TSLogger::messageHandler ); // -- qInstallMsgHandler( TSLogger::messageHandler );
// -- TSLogger::messageHandler( TSLoggerInfoMsg, TQString("Starting UiGUI Version %1 %2").arg(PROGRAM_VERSION_STRING).arg(PROGRAM_REVISION).toAscii() ); // -- TSLogger::messageHandler( TSLoggerInfoMsg, TQString("Starting UiGUI Version %1
// -- TSLogger::messageHandler( TSLoggerInfoMsg, TQString("Running on %1").arg(UiGuiSystemInfo::getOperatingSystem()).toAscii() ); // %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. // -- // Set default values for all by UniversalIndentGUI used settings objects.
// -- TQCoreApplication::setOrganizationName("UniversalIndentGUI"); // -- TQCoreApplication::setOrganizationName("UniversalIndentGUI");
@ -154,7 +163,8 @@ int main(int argc, char *argv[])
// -- returnValue = app.exec(); // -- returnValue = app.exec();
// -- } // -- }
// -- catch (std::exception &ex) { // -- catch (std::exception &ex) {
// -- qCritical() << __LINE__ << " " << __FUNCTION__ << ": Something went terribly wrong:" << ex.what(); // -- qCritical() << __LINE__ << " " << __FUNCTION__ << ": Something went terribly wrong:"
// << ex.what();
// -- } // -- }
// -- // --
// -- if ( startAsPlugin || startAsServer ) // -- if ( startAsPlugin || startAsServer )
@ -167,5 +177,4 @@ int main(int argc, char *argv[])
// -- TSLogger::deleteInstance(); // -- TSLogger::deleteInstance();
// -- // --
// -- return returnValue; // -- return returnValue;
} }

@ -54,8 +54,8 @@ typedef std::istrstream istringstream;
#include <tclap/ArgTraits.h> #include <tclap/ArgTraits.h>
#include <tclap/StandardTraits.h> #include <tclap/StandardTraits.h>
namespace TCLAP { namespace TCLAP
{
/** /**
* A virtual base class that defines the essential data for all arguments. * A virtual base class that defines the essential data for all arguments.
* This class, or one of its existing children, must be subclassed to do * This class, or one of its existing children, must be subclassed to do
@ -68,16 +68,23 @@ class Arg
/** /**
* Indicates whether the rest of the arguments should be ignored. * Indicates whether the rest of the arguments should be ignored.
*/ */
static bool& ignoreRestRef() { static bool ign = false; return ign; } static bool& ignoreRestRef()
{
static bool ign = false;
return ign;
}
/** /**
* The delimiter that separates an argument flag/name from the * The delimiter that separates an argument flag/name from the
* value. * value.
*/ */
static char& delimiterRef() { static char delim = ' '; return delim; } static char& delimiterRef()
{
static char delim = ' ';
return delim;
}
protected: protected:
/** /**
* The single char flag used to identify the argument. * The single char flag used to identify the argument.
* This value (preceded by a dash {-}), can be used to identify * This value (preceded by a dash {-}), can be used to identify
@ -166,12 +173,8 @@ class Arg
* \param valreq - Whether the a value is required for the argument. * \param valreq - Whether the a value is required for the argument.
* \param v - The visitor checked by the argument. Defaults to NULL. * \param v - The visitor checked by the argument. Defaults to NULL.
*/ */
Arg( const std::string& flag, Arg(const std::string &flag, const std::string &name, const std::string &desc, bool req,
const std::string& name, bool valreq, Visitor *v = NULL);
const std::string& desc,
bool req,
bool valreq,
Visitor* v = NULL );
public: public:
/** /**
@ -188,52 +191,79 @@ class Arg
/** /**
* Begin ignoring arguments since the "--" argument was specified. * Begin ignoring arguments since the "--" argument was specified.
*/ */
static void beginIgnoring() { ignoreRestRef() = true; } static void beginIgnoring()
{
ignoreRestRef() = true;
}
/** /**
* Whether to ignore the rest. * Whether to ignore the rest.
*/ */
static bool ignoreRest() { return ignoreRestRef(); } static bool ignoreRest()
{
return ignoreRestRef();
}
/** /**
* The delimiter that separates an argument flag/name from the * The delimiter that separates an argument flag/name from the
* value. * value.
*/ */
static char delimiter() { return delimiterRef(); } static char delimiter()
{
return delimiterRef();
}
/** /**
* The char used as a place holder when SwitchArgs are combined. * The char used as a place holder when SwitchArgs are combined.
* Currently set to the bell char (ASCII 7). * Currently set to the bell char (ASCII 7).
*/ */
static char blankChar() { return (char)7; } static char blankChar()
{
return (char)7;
}
/** /**
* The char that indicates the beginning of a flag. Currently '-'. * The char that indicates the beginning of a flag. Currently '-'.
*/ */
static char flagStartChar() { return '-'; } static char flagStartChar()
{
return '-';
}
/** /**
* The sting that indicates the beginning of a flag. Currently "-". * The sting that indicates the beginning of a flag. Currently "-".
* Should be identical to flagStartChar. * Should be identical to flagStartChar.
*/ */
static const std::string flagStartString() { return "-"; } static const std::string flagStartString()
{
return "-";
}
/** /**
* The sting that indicates the beginning of a name. Currently "--". * The sting that indicates the beginning of a name. Currently "--".
* Should be flagStartChar twice. * Should be flagStartChar twice.
*/ */
static const std::string nameStartString() { return "--"; } static const std::string nameStartString()
{
return "--";
}
/** /**
* The name used to identify the ignore rest argument. * The name used to identify the ignore rest argument.
*/ */
static const std::string ignoreNameString() { return "ignore_rest"; } static const std::string ignoreNameString()
{
return "ignore_rest";
}
/** /**
* Sets the delimiter for all arguments. * Sets the delimiter for all arguments.
* \param c - The character that delimits flags/names from values. * \param c - The character that delimits flags/names from values.
*/ */
static void setDelimiter( char c ) { delimiterRef() = c; } static void setDelimiter(char c)
{
delimiterRef() = c;
}
/** /**
* Pure virtual method meant to handle the parsing and value assignment * Pure virtual method meant to handle the parsing and value assignment
@ -391,35 +421,44 @@ typedef std::list<Visitor*>::iterator VisitorListIterator;
* specialization of ExtractValue depending on the value traits of T. * specialization of ExtractValue depending on the value traits of T.
* ValueLike traits use operator>> to assign the value from strVal. * ValueLike traits use operator>> to assign the value from strVal.
*/ */
template<typename T> void template<typename T>
ExtractValue(T &destVal, const std::string& strVal, ValueLike vl) void ExtractValue(T &destVal, const std::string &strVal, ValueLike vl)
{ {
static_cast<void>(vl); // Avoid warning about unused vl static_cast<void>(vl); // Avoid warning about unused vl
std::istringstream is(strVal); std::istringstream is(strVal);
int valuesRead = 0; int valuesRead = 0;
while ( is.good() ) { while (is.good())
{
if (is.peek() != EOF) if (is.peek() != EOF)
#ifdef TCLAP_SETBASE_ZERO #ifdef TCLAP_SETBASE_ZERO
{
is >> std::setbase(0) >> destVal; is >> std::setbase(0) >> destVal;
}
#else #else
{
is >> destVal; is >> destVal;
}
#endif #endif
else else
{
break; break;
}
valuesRead++; valuesRead++;
} }
if (is.fail()) if (is.fail())
{
throw (ArgParseException("Couldn't read argument value " throw (ArgParseException("Couldn't read argument value "
"from string '" + strVal + "'")); "from string '" + strVal + "'"));
}
if (valuesRead > 1) if (valuesRead > 1)
{
throw (ArgParseException("More than one valid value parsed from " throw (ArgParseException("More than one valid value parsed from "
"string '" + strVal + "'")); "string '" + strVal + "'"));
}
} }
/* /*
@ -428,8 +467,8 @@ ExtractValue(T &destVal, const std::string& strVal, ValueLike vl)
* specialization of ExtractValue depending on the value traits of T. * specialization of ExtractValue depending on the value traits of T.
* StringLike uses assignment (operator=) to assign from strVal. * StringLike uses assignment (operator=) to assign from strVal.
*/ */
template<typename T> void template<typename T>
ExtractValue(T &destVal, const std::string& strVal, StringLike sl) void ExtractValue(T &destVal, const std::string &strVal, StringLike sl)
{ {
static_cast<void>(sl); // Avoid warning about unused sl static_cast<void>(sl); // Avoid warning about unused sl
SetString(destVal, strVal); SetString(destVal, strVal);
@ -439,63 +478,62 @@ ExtractValue(T &destVal, const std::string& strVal, StringLike sl)
//BEGIN Arg.cpp //BEGIN Arg.cpp
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
inline Arg::Arg(const std::string& flag, inline Arg::Arg(const std::string &flag, const std::string &name, const std::string &desc,
const std::string& name, bool req, bool valreq, Visitor *v) :
const std::string& desc, _flag(flag), _name(name), _description(desc), _required(req), _requireLabel("required"),
bool req, _valueRequired(valreq), _alreadySet(false), _visitor(v), _ignoreable(true),
bool valreq, _xorSet(false), _acceptsMultipleValues(false)
Visitor* v) :
_flag(flag),
_name(name),
_description(desc),
_required(req),
_requireLabel("required"),
_valueRequired(valreq),
_alreadySet(false),
_visitor( v ),
_ignoreable(true),
_xorSet(false),
_acceptsMultipleValues(false)
{ {
if (_flag.length() > 1) if (_flag.length() > 1)
{
throw (SpecificationException( throw (SpecificationException(
"Argument flag can only be one character long", toString())); "Argument flag can only be one character long", toString()));
}
if (_name != ignoreNameString() && if (_name != ignoreNameString() &&
(_flag == Arg::flagStartString() || (_flag == Arg::flagStartString() ||
_flag == Arg::nameStartString() || _flag == Arg::nameStartString() ||
_flag == " ")) _flag == " "))
throw(SpecificationException("Argument flag cannot be either '" + {
Arg::flagStartString() + "' or '" + throw (SpecificationException("Argument flag cannot be either '" + Arg::flagStartString() +
Arg::nameStartString() + "' or a space.", "' or '" + Arg::nameStartString() + "' or a space.", toString()));
toString() ) ); }
if ((_name.substr(0, Arg::flagStartString().length()) == Arg::flagStartString()) || if ((_name.substr(0, Arg::flagStartString().length()) == Arg::flagStartString()) ||
(_name.substr(0, Arg::nameStartString().length()) == Arg::nameStartString()) || (_name.substr(0, Arg::nameStartString().length()) == Arg::nameStartString()) ||
(_name.find(" ", 0) != std::string::npos)) (_name.find(" ", 0) != std::string::npos))
throw(SpecificationException("Argument name begin with either '" + {
Arg::flagStartString() + "' or '" + throw (SpecificationException("Argument name begin with either '" + Arg::flagStartString() +
Arg::nameStartString() + "' or space.", "' or '" + Arg::nameStartString() + "' or space.", toString()));
toString() ) ); }
} }
inline Arg::~Arg() { } inline Arg::~Arg()
{
}
inline std::string Arg::shortID(const std::string &valueId) const inline std::string Arg::shortID(const std::string &valueId) const
{ {
std::string id = ""; std::string id = "";
if (_flag != "") if (_flag != "")
{
id = Arg::flagStartString() + _flag; id = Arg::flagStartString() + _flag;
}
else else
{
id = Arg::nameStartString() + _name; id = Arg::nameStartString() + _name;
}
if (_valueRequired) if (_valueRequired)
{
id += std::string(1, Arg::delimiter()) + "<" + valueId + ">"; id += std::string(1, Arg::delimiter()) + "<" + valueId + ">";
}
if (!_required) if (!_required)
{
id = "[" + id + "]"; id = "[" + id + "]";
}
return id; return id;
} }
@ -509,7 +547,9 @@ inline std::string Arg::longID( const std::string& valueId ) const
id += Arg::flagStartString() + _flag; id += Arg::flagStartString() + _flag;
if (_valueRequired) if (_valueRequired)
{
id += std::string(1, Arg::delimiter()) + "<" + valueId + ">"; id += std::string(1, Arg::delimiter()) + "<" + valueId + ">";
}
id += ", "; id += ", ";
} }
@ -517,25 +557,32 @@ inline std::string Arg::longID( const std::string& valueId ) const
id += Arg::nameStartString() + _name; id += Arg::nameStartString() + _name;
if (_valueRequired) if (_valueRequired)
{
id += std::string(1, Arg::delimiter()) + "<" + valueId + ">"; id += std::string(1, Arg::delimiter()) + "<" + valueId + ">";
}
return id; return id;
} }
inline bool Arg::operator==(const Arg &a) const inline bool Arg::operator==(const Arg &a) const
{ {
if ((_flag != "" && _flag == a._flag) || _name == a._name) if ((_flag != "" && _flag == a._flag) || _name == a._name)
{
return true; return true;
}
else else
{
return false; return false;
} }
}
inline std::string Arg::getDescription() const inline std::string Arg::getDescription() const
{ {
std::string desc = ""; std::string desc = "";
if (_required) if (_required)
{
desc = "(" + _requireLabel + ") "; desc = "(" + _requireLabel + ") ";
}
// if ( _valueRequired ) // if ( _valueRequired )
// desc += "(value required) "; // desc += "(value required) ";
@ -544,23 +591,42 @@ inline std::string Arg::getDescription() const
return desc; return desc;
} }
inline const std::string& Arg::getFlag() const { return _flag; } inline const std::string& Arg::getFlag() const
{
return _flag;
}
inline const std::string& Arg::getName() const { return _name; } inline const std::string& Arg::getName() const
{
return _name;
}
inline bool Arg::isRequired() const { return _required; } inline bool Arg::isRequired() const
{
return _required;
}
inline bool Arg::isValueRequired() const { return _valueRequired; } inline bool Arg::isValueRequired() const
{
return _valueRequired;
}
inline bool Arg::isSet() const inline bool Arg::isSet() const
{ {
if (_alreadySet && !_xorSet) if (_alreadySet && !_xorSet)
{
return true; return true;
}
else else
{
return false; return false;
} }
}
inline bool Arg::isIgnoreable() const { return _ignoreable; } inline bool Arg::isIgnoreable() const
{
return _ignoreable;
}
inline void Arg::setRequireLabel(const std::string &s) inline void Arg::setRequireLabel(const std::string &s)
{ {
@ -571,17 +637,23 @@ inline bool Arg::argMatches( const std::string& argFlag ) const
{ {
if ((argFlag == Arg::flagStartString() + _flag && _flag != "") || if ((argFlag == Arg::flagStartString() + _flag && _flag != "") ||
argFlag == Arg::nameStartString() + _name) argFlag == Arg::nameStartString() + _name)
{
return true; return true;
}
else else
{
return false; return false;
} }
}
inline std::string Arg::toString() const inline std::string Arg::toString() const
{ {
std::string s = ""; std::string s = "";
if (_flag != "") if (_flag != "")
{
s += Arg::flagStartString() + _flag + " "; s += Arg::flagStartString() + _flag + " ";
}
s += "(" + Arg::nameStartString() + _name + ")"; s += "(" + Arg::nameStartString() + _name + ")";
@ -591,8 +663,10 @@ inline std::string Arg::toString() const
inline void Arg::_checkWithVisitor() const inline void Arg::_checkWithVisitor() const
{ {
if (_visitor != NULL) if (_visitor != NULL)
{
_visitor->visit(); _visitor->visit();
} }
}
/** /**
* Implementation of trimFlag. * Implementation of trimFlag.
@ -601,18 +675,19 @@ inline void Arg::trimFlag(std::string& flag, std::string& value) const
{ {
int stop = 0; int stop = 0;
for (int i = 0; static_cast<unsigned int>(i) < flag.length(); i++) for (int i = 0; static_cast<unsigned int>(i) < flag.length(); i++)
{
if (flag[i] == Arg::delimiter()) if (flag[i] == Arg::delimiter())
{ {
stop = i; stop = i;
break; break;
} }
}
if (stop > 1) if (stop > 1)
{ {
value = flag.substr(stop + 1); value = flag.substr(stop + 1);
flag = flag.substr(0, stop); flag = flag.substr(0, stop);
} }
} }
/** /**
@ -621,8 +696,12 @@ inline void Arg::trimFlag(std::string& flag, std::string& value) const
inline bool Arg::_hasBlanks(const std::string &s) const inline bool Arg::_hasBlanks(const std::string &s) const
{ {
for (int i = 1; static_cast<unsigned int>(i) < s.length(); i++) for (int i = 1; static_cast<unsigned int>(i) < s.length(); i++)
{
if (s[i] == Arg::blankChar()) if (s[i] == Arg::blankChar())
{
return true; return true;
}
}
return false; return false;
} }
@ -665,8 +744,6 @@ inline void Arg::reset()
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
//END Arg.cpp //END Arg.cpp
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
} //namespace TCLAP } //namespace TCLAP
#endif #endif

@ -27,8 +27,8 @@
#include <string> #include <string>
#include <exception> #include <exception>
namespace TCLAP { namespace TCLAP
{
/** /**
* A simple class that defines and argument exception. Should be caught * A simple class that defines and argument exception. Should be caught
* whenever a CmdLine is created and parsed. * whenever a CmdLine is created and parsed.
@ -36,7 +36,6 @@ namespace TCLAP {
class ArgException : public std::exception class ArgException : public std::exception
{ {
public: public:
/** /**
* Constructor. * Constructor.
* \param text - The text of the exception. * \param text - The text of the exception.
@ -46,22 +45,25 @@ class ArgException : public std::exception
*/ */
ArgException(const std::string &text = "undefined exception", ArgException(const std::string &text = "undefined exception",
const std::string &id = "undefined", const std::string &id = "undefined",
const std::string& td = "Generic ArgException") const std::string &td = "Generic ArgException") :
: std::exception(), std::exception(), _errorText(text), _argId(id), _typeDescription(td)
_errorText(text), {
_argId( id ), }
_typeDescription(td)
{ }
/** /**
* Destructor. * Destructor.
*/ */
virtual ~ArgException() throw() { } virtual ~ArgException() throw ()
{
}
/** /**
* Returns the error text. * Returns the error text.
*/ */
std::string error() const { return ( _errorText ); } std::string error() const
{
return _errorText;
}
/** /**
* Returns the argument id. * Returns the argument id.
@ -69,9 +71,13 @@ class ArgException : public std::exception
std::string argId() const std::string argId() const
{ {
if (_argId == "undefined") if (_argId == "undefined")
{
return " "; return " ";
}
else else
return ( "Argument: " + _argId ); {
return "Argument: " + _argId;
}
} }
/** /**
@ -93,9 +99,7 @@ class ArgException : public std::exception
return _typeDescription; return _typeDescription;
} }
private: private:
/** /**
* The text of the exception message. * The text of the exception message.
*/ */
@ -111,7 +115,6 @@ class ArgException : public std::exception
* between different child exceptions. * between different child exceptions.
*/ */
std::string _typeDescription; std::string _typeDescription;
}; };
/** /**
@ -128,12 +131,13 @@ class ArgParseException : public ArgException
* of the exception. * of the exception.
*/ */
ArgParseException(const std::string &text = "undefined exception", ArgParseException(const std::string &text = "undefined exception",
const std::string& id = "undefined" ) const std::string &id = "undefined") :
: ArgException( text, ArgException(text,
id, id,
std::string("Exception found while parsing ") + std::string("Exception found while parsing ") +
std::string("the value the Arg has been passed.")) std::string("the value the Arg has been passed."))
{ } {
}
}; };
/** /**
@ -150,14 +154,14 @@ class CmdLineParseException : public ArgException
* of the exception. * of the exception.
*/ */
CmdLineParseException(const std::string &text = "undefined exception", CmdLineParseException(const std::string &text = "undefined exception",
const std::string& id = "undefined" ) const std::string &id = "undefined") :
: ArgException( text, ArgException(text,
id, id,
std::string("Exception found when the values ") + std::string("Exception found when the values ") +
std::string("on the command line do not meet ") + std::string("on the command line do not meet ") +
std::string( "the requirements of the defined ") + std::string("the requirements of the defined ") + std::string("Args."))
std::string( "Args." )) {
{ } }
}; };
/** /**
@ -174,27 +178,31 @@ class SpecificationException : public ArgException
* of the exception. * of the exception.
*/ */
SpecificationException(const std::string &text = "undefined exception", SpecificationException(const std::string &text = "undefined exception",
const std::string& id = "undefined" ) const std::string &id = "undefined") :
: ArgException( text, ArgException(text,
id, id,
std::string("Exception found when an Arg object ") + std::string("Exception found when an Arg object ") +
std::string("is improperly defined by the ") + std::string("is improperly defined by the ") + std::string("developer."))
std::string("developer." )) {
{ } }
}; };
class ExitException { class ExitException
{
public: public:
ExitException(int estat) : _estat(estat) {} ExitException(int estat) :
_estat(estat)
{
}
int getExitStatus() const { return _estat; } int getExitStatus() const
{
return _estat;
}
private: private:
int _estat; int _estat;
}; };
} // namespace TCLAP } // namespace TCLAP
#endif #endif

@ -26,8 +26,8 @@
#ifndef TCLAP_ARGTRAITS_H #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 // We use two empty structs to get compile type specialization
// function to work // function to work
@ -35,7 +35,8 @@ namespace TCLAP {
* A value like argument value type is a value that can be set using * A value like argument value type is a value that can be set using
* operator>>. This is the default value type. * operator>>. This is the default value type.
*/ */
struct ValueLike { struct ValueLike
{
typedef ValueLike ValueCategory; typedef ValueLike ValueCategory;
}; };
@ -44,14 +45,16 @@ struct ValueLike {
* operator=(string). Usefull if the value type contains spaces which * operator=(string). Usefull if the value type contains spaces which
* will be broken up into individual tokens by operator>>. * will be broken up into individual tokens by operator>>.
*/ */
struct StringLike {}; struct StringLike
{};
/** /**
* A class can inherit from this object to make it have string like * 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 * traits. This is a compile time thing and does not add any overhead
* to the inherenting class. * to the inherenting class.
*/ */
struct StringLikeTrait { struct StringLikeTrait
{
typedef StringLike ValueCategory; typedef StringLike ValueCategory;
}; };
@ -60,7 +63,8 @@ struct StringLikeTrait {
* traits. This is a compile time thing and does not add any overhead * traits. This is a compile time thing and does not add any overhead
* to the inherenting class. * to the inherenting class.
*/ */
struct ValueLikeTrait { struct ValueLikeTrait
{
typedef ValueLike ValueCategory; typedef ValueLike ValueCategory;
}; };
@ -71,11 +75,11 @@ struct ValueLikeTrait {
* supported types are string like and value like. * supported types are string like and value like.
*/ */
template<typename T> template<typename T>
struct ArgTraits { struct ArgTraits
{
typedef typename T::ValueCategory ValueCategory; typedef typename T::ValueCategory ValueCategory;
//typedef ValueLike ValueCategory; //typedef ValueLike ValueCategory;
}; };
#endif #endif
} // namespace } // namespace

@ -48,21 +48,22 @@
#include <algorithm> #include <algorithm>
#include <stdlib.h> // Needed for exit(), which isn't defined in some envs. #include <stdlib.h> // Needed for exit(), which isn't defined in some envs.
namespace TCLAP { namespace TCLAP
{
template<typename T> void DelPtr(T ptr) template<typename T>
void DelPtr(T ptr)
{ {
delete ptr; delete ptr;
} }
template<typename C> void ClearContainer(C &c) template<typename C>
void ClearContainer(C &c)
{ {
typedef typename C::value_type value_type; typedef typename C::value_type value_type;
std::for_each(c.begin(), c.end(), DelPtr<value_type>); std::for_each(c.begin(), c.end(), DelPtr<value_type>);
c.clear(); c.clear();
} }
/** /**
* The base class that manages the command line definition and passes * The base class that manages the command line definition and passes
* along the parsing to the appropriate Arg classes. * along the parsing to the appropriate Arg classes.
@ -70,7 +71,6 @@ template<typename C> void ClearContainer(C &c)
class CmdLine : public CmdLineInterface class CmdLine : public CmdLineInterface
{ {
protected: protected:
/** /**
* The list of arguments that will be tested against the * The list of arguments that will be tested against the
* command line. * command line.
@ -158,7 +158,6 @@ class CmdLine : public CmdLineInterface
void deleteOnExit(Visitor *ptr); void deleteOnExit(Visitor *ptr);
private: private:
/** /**
* Encapsulates the code common to the constructors * Encapsulates the code common to the constructors
* (which is all of it). * (which is all of it).
@ -178,7 +177,6 @@ private:
bool _helpAndVersion; bool _helpAndVersion;
public: public:
/** /**
* Command line constructor. Defines how the arguments will be * Command line constructor. Defines how the arguments will be
* parsed. * parsed.
@ -191,10 +189,8 @@ private:
* \param helpAndVersion - Whether or not to create the Help and * \param helpAndVersion - Whether or not to create the Help and
* Version switches. Defaults to true. * Version switches. Defaults to true.
*/ */
CmdLine(const std::string& message, CmdLine(const std::string &message, const char delimiter = ' ',
const char delimiter = ' ', const std::string &version = "none", bool helpAndVersion = true);
const std::string& version = "none",
bool helpAndVersion = true);
/** /**
* Deletes any resources allocated by a CmdLine object. * Deletes any resources allocated by a CmdLine object.
@ -306,7 +302,6 @@ private:
* Allows the CmdLine object to be reused. * Allows the CmdLine object to be reused.
*/ */
void reset(); void reset();
}; };
@ -314,18 +309,9 @@ private:
//Begin CmdLine.cpp //Begin CmdLine.cpp
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
inline CmdLine::CmdLine(const std::string& m, inline CmdLine::CmdLine(const std::string &m, char delim, const std::string &v, bool help) :
char delim, _progName("not_set_yet"), _message(m), _version(v), _numRequired(0), _delimiter(delim),
const std::string& v, _handleExceptions(true), _userSetOutput(false), _helpAndVersion(help)
bool help )
: _progName("not_set_yet"),
_message(m),
_version(v),
_numRequired(0),
_delimiter(delim),
_handleExceptions(true),
_userSetOutput(false),
_helpAndVersion(help)
{ {
_constructor(); _constructor();
} }
@ -335,7 +321,8 @@ inline CmdLine::~CmdLine()
ClearContainer(_argDeleteOnExitList); ClearContainer(_argDeleteOnExitList);
ClearContainer(_visitorDeleteOnExitList); ClearContainer(_visitorDeleteOnExitList);
if ( !_userSetOutput ) { if (!_userSetOutput)
{
delete _output; delete _output;
_output = 0; _output = 0;
} }
@ -352,16 +339,14 @@ inline void CmdLine::_constructor()
if (_helpAndVersion) if (_helpAndVersion)
{ {
v = new HelpVisitor(this, &_output); v = new HelpVisitor(this, &_output);
SwitchArg* help = new SwitchArg("h","help", SwitchArg *help =
"Displays usage information and exits.", new SwitchArg("h", "help", "Displays usage information and exits.", false, v);
false, v);
add(help); add(help);
deleteOnExit(help); deleteOnExit(help);
deleteOnExit(v); deleteOnExit(v);
v = new VersionVisitor(this, &_output); v = new VersionVisitor(this, &_output);
SwitchArg* vers = new SwitchArg("","version", SwitchArg *vers = new SwitchArg("", "version", "Displays version information and exits.",
"Displays version information and exits.",
false, v); false, v);
add(vers); add(vers);
deleteOnExit(vers); deleteOnExit(vers);
@ -370,9 +355,8 @@ inline void CmdLine::_constructor()
v = new IgnoreRestVisitor(); v = new IgnoreRestVisitor();
SwitchArg *ignore = new SwitchArg(Arg::flagStartString(), SwitchArg *ignore = new SwitchArg(Arg::flagStartString(),
Arg::ignoreNameString(), Arg::ignoreNameString(), "Ignores the rest of the labeled arguments following this flag.", false,
"Ignores the rest of the labeled arguments following this flag.", v);
false, v);
add(ignore); add(ignore);
deleteOnExit(ignore); deleteOnExit(ignore);
deleteOnExit(v); deleteOnExit(v);
@ -407,17 +391,21 @@ inline void CmdLine::add( Arg& a )
inline void CmdLine::add(Arg *a) inline void CmdLine::add(Arg *a)
{ {
for (ArgListIterator it = _argList.begin(); it != _argList.end(); it++) for (ArgListIterator it = _argList.begin(); it != _argList.end(); it++)
{
if (*a == *(*it)) if (*a == *(*it))
{
throw (SpecificationException( throw (SpecificationException(
"Argument with same flag/name already exists!", "Argument with same flag/name already exists!", a->longID()));
a->longID() ) ); }
}
a->addToList(_argList); a->addToList(_argList);
if (a->isRequired()) if (a->isRequired())
{
_numRequired++; _numRequired++;
} }
}
inline void CmdLine::parse(int argc, const char*const *argv) inline void CmdLine::parse(int argc, const char*const *argv)
{ {
@ -425,7 +413,9 @@ inline void CmdLine::parse(int argc, const char * const * argv)
// mutable strings. // mutable strings.
std::vector<std::string> args; std::vector<std::string> args;
for (int i = 0; i < argc; i++) for (int i = 0; i < argc; i++)
{
args.push_back(argv[i]); args.push_back(argv[i]);
}
parse(args); parse(args);
} }
@ -435,16 +425,19 @@ inline void CmdLine::parse(std::vector<std::string>& args)
bool shouldExit = false; bool shouldExit = false;
int estat = 0; int estat = 0;
try { try
{
_progName = args.front(); _progName = args.front();
args.erase(args.begin()); args.erase(args.begin());
int requiredCount = 0; int requiredCount = 0;
for (int i = 0; static_cast<unsigned int>(i) < args.size(); i++) { for (int i = 0; static_cast<unsigned int>(i) < args.size(); i++)
{
bool matched = false; bool matched = false;
for (ArgListIterator it = _argList.begin(); for (ArgListIterator it = _argList.begin();
it != _argList.end(); it++) { it != _argList.end(); it++)
{
if ((*it)->processArg(&i, args)) if ((*it)->processArg(&i, args))
{ {
requiredCount += _xorHandler.check(*it); requiredCount += _xorHandler.check(*it);
@ -456,35 +449,50 @@ inline void CmdLine::parse(std::vector<std::string>& args)
// checks to see if the argument is an empty combined // checks to see if the argument is an empty combined
// switch and if so, then we've actually matched it // switch and if so, then we've actually matched it
if (!matched && _emptyCombined(args[i])) if (!matched && _emptyCombined(args[i]))
{
matched = true; matched = true;
}
if (!matched && !Arg::ignoreRest()) if (!matched && !Arg::ignoreRest())
{
throw (CmdLineParseException("Couldn't find match " throw (CmdLineParseException("Couldn't find match "
"for argument", "for argument", args[i]));
args[i])); }
} }
if (requiredCount < _numRequired) if (requiredCount < _numRequired)
{
missingArgsException(); missingArgsException();
}
if (requiredCount > _numRequired) if (requiredCount > _numRequired)
{
throw (CmdLineParseException("Too many arguments!")); throw (CmdLineParseException("Too many arguments!"));
}
} catch ( ArgException& e ) { }
catch (ArgException &e)
{
// If we're not handling the exceptions, rethrow. // If we're not handling the exceptions, rethrow.
if ( !_handleExceptions) { if (!_handleExceptions)
{
throw; throw;
} }
try { try
{
_output->failure(*this, e); _output->failure(*this, e);
} catch ( ExitException &ee ) { }
catch (ExitException &ee)
{
estat = ee.getExitStatus(); estat = ee.getExitStatus();
shouldExit = true; shouldExit = true;
} }
} catch (ExitException &ee) { }
catch (ExitException &ee)
{
// If we're not handling the exceptions, rethrow. // If we're not handling the exceptions, rethrow.
if ( !_handleExceptions) { if (!_handleExceptions)
{
throw; throw;
} }
@ -493,17 +501,25 @@ inline void CmdLine::parse(std::vector<std::string>& args)
} }
if (shouldExit) if (shouldExit)
{
exit(estat); exit(estat);
} }
}
inline bool CmdLine::_emptyCombined(const std::string &s) inline bool CmdLine::_emptyCombined(const std::string &s)
{ {
if (s.length() > 0 && s[0] != Arg::flagStartChar()) if (s.length() > 0 && s[0] != Arg::flagStartChar())
{
return false; return false;
}
for (int i = 1; static_cast<unsigned int>(i) < s.length(); i++) for (int i = 1; static_cast<unsigned int>(i) < s.length(); i++)
{
if (s[i] != Arg::blankChar()) if (s[i] != Arg::blankChar())
{
return false; return false;
}
}
return true; return true;
} }
@ -526,9 +542,13 @@ inline void CmdLine::missingArgsException()
std::string msg; std::string msg;
if (count > 1) if (count > 1)
{
msg = "Required arguments missing: "; msg = "Required arguments missing: ";
}
else else
{
msg = "Required argument missing: "; msg = "Required argument missing: ";
}
msg += missingArgList; msg += missingArgList;
@ -614,8 +634,6 @@ inline void CmdLine::reset()
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
//End CmdLine.cpp //End CmdLine.cpp
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
} //namespace TCLAP } //namespace TCLAP
#endif #endif

@ -1,4 +1,3 @@
/****************************************************************************** /******************************************************************************
* *
* file: CmdLineInterface.h * file: CmdLineInterface.h
@ -30,8 +29,8 @@
#include <algorithm> #include <algorithm>
namespace TCLAP { namespace TCLAP
{
class Arg; class Arg;
class CmdLineOutput; class CmdLineOutput;
class XorHandler; class XorHandler;
@ -43,11 +42,12 @@ class XorHandler;
class CmdLineInterface class CmdLineInterface
{ {
public: public:
/** /**
* Destructor * Destructor
*/ */
virtual ~CmdLineInterface() {} virtual ~CmdLineInterface()
{
}
/** /**
* Adds an argument to the list of arguments to be parsed. * Adds an argument to the list of arguments to be parsed.
@ -143,7 +143,6 @@ class CmdLineInterface
*/ */
virtual void reset() = 0; virtual void reset() = 0;
}; };
} //namespace } //namespace

@ -1,5 +1,3 @@
/****************************************************************************** /******************************************************************************
* *
* file: CmdLineOutput.h * file: CmdLineOutput.h
@ -30,8 +28,8 @@
#include <iomanip> #include <iomanip>
#include <algorithm> #include <algorithm>
namespace TCLAP { namespace TCLAP
{
class CmdLineInterface; class CmdLineInterface;
class ArgException; class ArgException;
@ -40,13 +38,13 @@ class ArgException;
*/ */
class CmdLineOutput class CmdLineOutput
{ {
public: public:
/** /**
* Virtual destructor. * Virtual destructor.
*/ */
virtual ~CmdLineOutput() {} virtual ~CmdLineOutput()
{
}
/** /**
* Generates some sort of output for the USAGE. * Generates some sort of output for the USAGE.
@ -65,10 +63,8 @@ class CmdLineOutput
* \param c - The CmdLine object the output is generated for. * \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure. * \param e - The ArgException that caused the failure.
*/ */
virtual void failure( CmdLineInterface& c, virtual void failure(CmdLineInterface &c, ArgException &e) = 0;
ArgException& e )=0;
}; };
} //namespace TCLAP } //namespace TCLAP
#endif #endif

@ -1,4 +1,3 @@
/****************************************************************************** /******************************************************************************
* *
* file: Constraint.h * file: Constraint.h
@ -29,15 +28,14 @@
#include <iomanip> #include <iomanip>
#include <algorithm> #include <algorithm>
namespace TCLAP { namespace TCLAP
{
/** /**
* The interface that defines the interaction between the Arg and Constraint. * The interface that defines the interaction between the Arg and Constraint.
*/ */
template<class T> template<class T>
class Constraint class Constraint
{ {
public: public:
/** /**
* Returns a description of the Constraint. * Returns a description of the Constraint.
@ -61,8 +59,10 @@ class Constraint
* Silences warnings about Constraint being a base class with virtual * Silences warnings about Constraint being a base class with virtual
* functions but without a virtual destructor. * functions but without a virtual destructor.
*/ */
virtual ~Constraint() { ; } virtual ~Constraint()
{
}
}; };
} //namespace TCLAP } //namespace TCLAP
#endif #endif

@ -34,17 +34,15 @@
#include <tclap/XorHandler.h> #include <tclap/XorHandler.h>
#include <tclap/Arg.h> #include <tclap/Arg.h>
namespace TCLAP { namespace TCLAP
{
/** /**
* A class that generates DocBook output for usage() method for the * A class that generates DocBook output for usage() method for the
* given CmdLine and its Args. * given CmdLine and its Args.
*/ */
class DocBookOutput : public CmdLineOutput class DocBookOutput : public CmdLineOutput
{ {
public: public:
/** /**
* Prints the usage to stdout. Can be overridden to * Prints the usage to stdout. Can be overridden to
* produce alternative behavior. * produce alternative behavior.
@ -65,11 +63,9 @@ class DocBookOutput : public CmdLineOutput
* \param c - The CmdLine object the output is generated for. * \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure. * \param e - The ArgException that caused the failure.
*/ */
virtual void failure(CmdLineInterface& c, virtual void failure(CmdLineInterface &c, ArgException &e);
ArgException& e );
protected: protected:
/** /**
* Substitutes the char r for string x in string s. * Substitutes the char r for string x in string s.
* \param s - The string to operate on. * \param s - The string to operate on.
@ -86,7 +82,6 @@ class DocBookOutput : public CmdLineOutput
char theDelimiter; char theDelimiter;
}; };
inline void DocBookOutput::version(CmdLineInterface &_cmd) inline void DocBookOutput::version(CmdLineInterface &_cmd)
{ {
std::cout << _cmd.getVersion() << std::endl; std::cout << _cmd.getVersion() << std::endl;
@ -104,7 +99,8 @@ inline void DocBookOutput::usage(CmdLineInterface& _cmd )
std::cout << "<?xml version='1.0'?>" << std::endl; std::cout << "<?xml version='1.0'?>" << std::endl;
std::cout << "<!DOCTYPE refentry PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\"" << 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 << "\t\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\">" << std::endl <<
std::endl;
std::cout << "<refentry>" << std::endl; std::cout << "<refentry>" << std::endl;
@ -129,15 +125,21 @@ inline void DocBookOutput::usage(CmdLineInterface& _cmd )
std::cout << "<group choice='req'>" << std::endl; std::cout << "<group choice='req'>" << std::endl;
for (ArgVectorIterator it = xorList[i].begin(); for (ArgVectorIterator it = xorList[i].begin();
it != xorList[i].end(); it++) it != xorList[i].end(); it++)
{
printShortArg((*it)); printShortArg((*it));
}
std::cout << "</group>" << std::endl; std::cout << "</group>" << std::endl;
} }
// rest of args // rest of args
for (ArgListIterator it = argList.begin(); it != argList.end(); it++) for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
{
if (!xorHandler.contains((*it))) if (!xorHandler.contains((*it)))
{
printShortArg((*it)); printShortArg((*it));
}
}
std::cout << "</cmdsynopsis>" << std::endl; std::cout << "</cmdsynopsis>" << std::endl;
std::cout << "</refsynopsisdiv>" << std::endl; std::cout << "</refsynopsisdiv>" << std::endl;
@ -155,7 +157,9 @@ inline void DocBookOutput::usage(CmdLineInterface& _cmd )
std::cout << "<variablelist>" << std::endl; std::cout << "<variablelist>" << std::endl;
for (ArgListIterator it = argList.begin(); it != argList.end(); it++) for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
{
printLongArg((*it)); printLongArg((*it));
}
std::cout << "</variablelist>" << std::endl; std::cout << "</variablelist>" << std::endl;
std::cout << "</refsect1>" << std::endl; std::cout << "</refsect1>" << std::endl;
@ -168,20 +172,16 @@ inline void DocBookOutput::usage(CmdLineInterface& _cmd )
std::cout << "</refsect1>" << std::endl; std::cout << "</refsect1>" << std::endl;
std::cout << "</refentry>" << std::endl; std::cout << "</refentry>" << std::endl;
} }
inline void DocBookOutput::failure( CmdLineInterface& _cmd, inline void DocBookOutput::failure(CmdLineInterface &_cmd, ArgException &e)
ArgException& e )
{ {
static_cast<void>(_cmd); // unused static_cast<void>(_cmd); // unused
std::cout << e.what() << std::endl; std::cout << e.what() << std::endl;
throw ExitException(1); throw ExitException(1);
} }
inline void DocBookOutput::substituteSpecialChars( std::string& s, inline void DocBookOutput::substituteSpecialChars(std::string &s, char r, std::string &x)
char r,
std::string& x )
{ {
size_t p; size_t p;
while ((p = s.find_first_of(r)) != std::string::npos) while ((p = s.find_first_of(r)) != std::string::npos)
@ -222,18 +222,25 @@ inline void DocBookOutput::printShortArg(Arg* a)
std::string choice = "opt"; std::string choice = "opt";
if (a->isRequired()) if (a->isRequired())
{
choice = "plain"; choice = "plain";
}
std::cout << "<arg choice='" << choice << '\''; std::cout << "<arg choice='" << choice << '\'';
if (a->acceptsMultipleValues()) if (a->acceptsMultipleValues())
{
std::cout << " rep='repeat'"; std::cout << " rep='repeat'";
}
std::cout << '>'; std::cout << '>';
if (!a->getFlag().empty()) if (!a->getFlag().empty())
{
std::cout << a->flagStartChar() << a->getFlag(); std::cout << a->flagStartChar() << a->getFlag();
}
else else
{
std::cout << a->nameStartString() << a->getName(); std::cout << a->nameStartString() << a->getName();
}
if (a->isValueRequired()) if (a->isValueRequired())
{ {
std::string arg = a->shortID(); std::string arg = a->shortID();
@ -246,7 +253,6 @@ inline void DocBookOutput::printShortArg(Arg* a)
std::cout << "<replaceable>" << arg << "</replaceable>"; std::cout << "<replaceable>" << arg << "</replaceable>";
} }
std::cout << "</arg>" << std::endl; std::cout << "</arg>" << std::endl;
} }
inline void DocBookOutput::printLongArg(Arg *a) inline void DocBookOutput::printLongArg(Arg *a)
@ -294,6 +300,6 @@ inline void DocBookOutput::printLongArg(Arg* a)
std::cout << "</varlistentry>" << std::endl; std::cout << "</varlistentry>" << std::endl;
} }
} //namespace TCLAP } //namespace TCLAP
#endif #endif

@ -1,4 +1,3 @@
/****************************************************************************** /******************************************************************************
* *
* file: HelpVisitor.h * file: HelpVisitor.h
@ -26,8 +25,8 @@
#include <tclap/CmdLineOutput.h> #include <tclap/CmdLineOutput.h>
#include <tclap/Visitor.h> #include <tclap/Visitor.h>
namespace TCLAP { namespace TCLAP
{
/** /**
* A Visitor object that calls the usage method of the given CmdLineOutput * A Visitor object that calls the usage method of the given CmdLineOutput
* object for the specified CmdLine object. * object for the specified CmdLine object.
@ -35,7 +34,6 @@ namespace TCLAP {
class HelpVisitor : public Visitor class HelpVisitor : public Visitor
{ {
protected: protected:
/** /**
* The CmdLine the output will be generated for. * The CmdLine the output will be generated for.
*/ */
@ -47,23 +45,26 @@ class HelpVisitor: public Visitor
CmdLineOutput **_out; CmdLineOutput **_out;
public: public:
/** /**
* Constructor. * Constructor.
* \param cmd - The CmdLine the output will be generated for. * \param cmd - The CmdLine the output will be generated for.
* \param out - The type of output. * \param out - The type of output.
*/ */
HelpVisitor(CmdLineInterface* cmd, CmdLineOutput** out) HelpVisitor(CmdLineInterface *cmd, CmdLineOutput **out) :
: Visitor(), _cmd( cmd ), _out( out ) { } Visitor(), _cmd(cmd), _out(out)
{
}
/** /**
* Calls the usage method of the CmdLineOutput for the * Calls the usage method of the CmdLineOutput for the
* specified CmdLine. * specified CmdLine.
*/ */
void visit() { (*_out)->usage(*_cmd); throw ExitException(0); } void visit()
{
(*_out)->usage(*_cmd);
throw ExitException(0);
}
}; };
} }
#endif #endif

@ -1,4 +1,3 @@
/****************************************************************************** /******************************************************************************
* *
* file: IgnoreRestVisitor.h * file: IgnoreRestVisitor.h
@ -26,8 +25,8 @@
#include <tclap/Visitor.h> #include <tclap/Visitor.h>
#include <tclap/Arg.h> #include <tclap/Arg.h>
namespace TCLAP { namespace TCLAP
{
/** /**
* A Vistor that tells the CmdLine to begin ignoring arguments after * A Vistor that tells the CmdLine to begin ignoring arguments after
* this one is parsed. * this one is parsed.
@ -35,18 +34,22 @@ namespace TCLAP {
class IgnoreRestVisitor : public Visitor class IgnoreRestVisitor : public Visitor
{ {
public: public:
/** /**
* Constructor. * Constructor.
*/ */
IgnoreRestVisitor() : Visitor() {} IgnoreRestVisitor() :
Visitor()
{
}
/** /**
* Sets Arg::_ignoreRest. * Sets Arg::_ignoreRest.
*/ */
void visit() { Arg::beginIgnoring(); } void visit()
{
Arg::beginIgnoring();
}
}; };
} }
#endif #endif

@ -29,7 +29,8 @@
#include <tclap/Arg.h> #include <tclap/Arg.h>
#include <tclap/Constraint.h> #include <tclap/Constraint.h>
namespace TCLAP { namespace TCLAP
{
/** /**
* An argument that allows multiple values of type T to be specified. Very * 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 * similar to a ValueArg, except a vector of values will be returned
@ -44,7 +45,6 @@ public:
typedef typename container_type::const_iterator const_iterator; typedef typename container_type::const_iterator const_iterator;
protected: protected:
/** /**
* The list of values parsed from the CmdLine. * The list of values parsed from the CmdLine.
*/ */
@ -74,7 +74,6 @@ protected:
bool _allowMore; bool _allowMore;
public: public:
/** /**
* Constructor. * Constructor.
* \param flag - The one character flag that identifies this * \param flag - The one character flag that identifies this
@ -92,12 +91,8 @@ public:
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
MultiArg( const std::string& flag, MultiArg(const std::string &flag, const std::string &name, const std::string &desc, bool req,
const std::string& name, const std::string &typeDesc, Visitor *v = NULL);
const std::string& desc,
bool req,
const std::string& typeDesc,
Visitor* v = NULL);
/** /**
* Constructor. * Constructor.
@ -117,13 +112,8 @@ public:
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
MultiArg( const std::string& flag, MultiArg(const std::string &flag, const std::string &name, const std::string &desc, bool req,
const std::string& name, const std::string &typeDesc, CmdLineInterface &parser, Visitor *v = NULL);
const std::string& desc,
bool req,
const std::string& typeDesc,
CmdLineInterface& parser,
Visitor* v = NULL );
/** /**
* Constructor. * Constructor.
@ -140,12 +130,8 @@ public:
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
MultiArg( const std::string& flag, MultiArg(const std::string &flag, const std::string &name, const std::string &desc, bool req,
const std::string& name, Constraint<T> *constraint, Visitor *v = NULL);
const std::string& desc,
bool req,
Constraint<T>* constraint,
Visitor* v = NULL );
/** /**
* Constructor. * Constructor.
@ -163,13 +149,8 @@ public:
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
MultiArg( const std::string& flag, MultiArg(const std::string &flag, const std::string &name, const std::string &desc, bool req,
const std::string& name, Constraint<T> *constraint, CmdLineInterface &parser, Visitor *v = NULL);
const std::string& desc,
bool req,
Constraint<T>* constraint,
CmdLineInterface& parser,
Visitor* v = NULL );
/** /**
* Handles the processing of the argument. * Handles the processing of the argument.
@ -191,13 +172,19 @@ public:
* Returns an iterator over the values parsed from the command * Returns an iterator over the values parsed from the command
* line. * line.
*/ */
const_iterator begin() const { return _values.begin(); } const_iterator begin() const
{
return _values.begin();
}
/** /**
* Returns the end of the values parsed from the command * Returns the end of the values parsed from the command
* line. * line.
*/ */
const_iterator end() const { return _values.end(); } const_iterator end() const
{
return _values.end();
}
/** /**
* Returns the a short id string. Used in the usage. * Returns the a short id string. Used in the usage.
@ -220,36 +207,21 @@ public:
virtual bool allowMore(); virtual bool allowMore();
virtual void reset(); virtual void reset();
}; };
template<class T> template<class T>
MultiArg<T>::MultiArg(const std::string& flag, MultiArg<T>::MultiArg(const std::string &flag, const std::string &name, const std::string &desc,
const std::string& name, bool req, const std::string &typeDesc, Visitor *v) :
const std::string& desc, Arg(flag, name, desc, req, true, v), _typeDesc(typeDesc), _constraint(NULL), _allowMore(false)
bool req,
const std::string& typeDesc,
Visitor* v)
: Arg( flag, name, desc, req, true, v ),
_typeDesc( typeDesc ),
_constraint( NULL ),
_allowMore(false)
{ {
_acceptsMultipleValues = true; _acceptsMultipleValues = true;
} }
template<class T> template<class T>
MultiArg<T>::MultiArg(const std::string& flag, MultiArg<T>::MultiArg(const std::string &flag, const std::string &name, const std::string &desc,
const std::string& name, bool req, const std::string &typeDesc, CmdLineInterface &parser,
const std::string& desc, Visitor *v) :
bool req, Arg(flag, name, desc, req, true, v), _typeDesc(typeDesc), _constraint(NULL), _allowMore(false)
const std::string& typeDesc,
CmdLineInterface& parser,
Visitor* v)
: Arg( flag, name, desc, req, true, v ),
_typeDesc( typeDesc ),
_constraint( NULL ),
_allowMore(false)
{ {
parser.add(this); parser.add(this);
_acceptsMultipleValues = true; _acceptsMultipleValues = true;
@ -259,48 +231,42 @@ MultiArg<T>::MultiArg(const std::string& flag,
* *
*/ */
template<class T> template<class T>
MultiArg<T>::MultiArg(const std::string& flag, MultiArg<T>::MultiArg(const std::string &flag, const std::string &name, const std::string &desc,
const std::string& name, bool req, Constraint<T> *constraint, Visitor *v) :
const std::string& desc, Arg(flag, name, desc, req, true, v), _typeDesc(constraint->shortID()),
bool req, _constraint(constraint), _allowMore(false)
Constraint<T>* constraint,
Visitor* v)
: Arg( flag, name, desc, req, true, v ),
_typeDesc( constraint->shortID() ),
_constraint( constraint ),
_allowMore(false)
{ {
_acceptsMultipleValues = true; _acceptsMultipleValues = true;
} }
template<class T> template<class T>
MultiArg<T>::MultiArg(const std::string& flag, MultiArg<T>::MultiArg(const std::string &flag, const std::string &name, const std::string &desc,
const std::string& name, bool req, Constraint<T> *constraint, CmdLineInterface &parser, Visitor *v) :
const std::string& desc, Arg(flag, name, desc, req, true, v), _typeDesc(constraint->shortID()),
bool req, _constraint(constraint), _allowMore(false)
Constraint<T>* constraint,
CmdLineInterface& parser,
Visitor* v)
: Arg( flag, name, desc, req, true, v ),
_typeDesc( constraint->shortID() ),
_constraint( constraint ),
_allowMore(false)
{ {
parser.add(this); parser.add(this);
_acceptsMultipleValues = true; _acceptsMultipleValues = true;
} }
template<class T> template<class T>
const std::vector<T>& MultiArg<T>::getValue() { return _values; } const std::vector<T>& MultiArg<T>::getValue()
{
return _values;
}
template<class T> template<class T>
bool MultiArg<T>::processArg(int *i, std::vector<std::string> &args) bool MultiArg<T>::processArg(int *i, std::vector<std::string> &args)
{ {
if (_ignoreable && Arg::ignoreRest()) if (_ignoreable && Arg::ignoreRest())
{
return false; return false;
}
if (_hasBlanks(args[*i])) if (_hasBlanks(args[*i]))
{
return false; return false;
}
std::string flag = args[*i]; std::string flag = args[*i];
std::string value = ""; std::string value = "";
@ -310,22 +276,28 @@ bool MultiArg<T>::processArg(int *i, std::vector<std::string>& args)
if (argMatches(flag)) if (argMatches(flag))
{ {
if (Arg::delimiter() != ' ' && value == "") if (Arg::delimiter() != ' ' && value == "")
{
throw (ArgParseException( throw (ArgParseException(
"Couldn't find delimiter for this argument!", "Couldn't find delimiter for this argument!", toString()));
toString() ) ); }
// always take the first one, regardless of start string // always take the first one, regardless of start string
if (value == "") if (value == "")
{ {
(*i)++; (*i)++;
if (static_cast<unsigned int>(*i) < args.size()) if (static_cast<unsigned int>(*i) < args.size())
{
_extractValue(args[*i]); _extractValue(args[*i]);
}
else else
throw( ArgParseException("Missing a value for this argument!", {
toString() ) ); throw (ArgParseException("Missing a value for this argument!", toString()));
}
} }
else else
{
_extractValue(value); _extractValue(value);
}
/* /*
// continuing taking the args until we hit one with a start string // continuing taking the args until we hit one with a start string
@ -341,8 +313,10 @@ bool MultiArg<T>::processArg(int *i, std::vector<std::string>& args)
return true; return true;
} }
else else
{
return false; return false;
} }
}
/** /**
* *
@ -374,32 +348,42 @@ bool MultiArg<T>::isRequired() const
if (_required) if (_required)
{ {
if (_values.size() > 1) if (_values.size() > 1)
{
return false; return false;
}
else else
{
return true; return true;
} }
}
else else
{
return false; return false;
}
} }
template<class T> template<class T>
void MultiArg<T>::_extractValue(const std::string &val) void MultiArg<T>::_extractValue(const std::string &val)
{ {
try { try
{
T tmp; T tmp;
ExtractValue(tmp, val, typename ArgTraits<T>::ValueCategory()); ExtractValue(tmp, val, typename ArgTraits<T>::ValueCategory());
_values.push_back(tmp); _values.push_back(tmp);
} catch( ArgParseException &e) { }
catch (ArgParseException &e)
{
throw ArgParseException(e.error(), toString()); throw ArgParseException(e.error(), toString());
} }
if (_constraint != NULL) if (_constraint != NULL)
{
if (!_constraint->check(_values.back())) if (!_constraint->check(_values.back()))
throw( CmdLineParseException( "Value '" + val + {
"' does not meet constraint: " + throw (CmdLineParseException("Value '" + val + "' does not meet constraint: " +
_constraint->description(), _constraint->description(), toString()));
toString() ) ); }
}
} }
template<class T> template<class T>
@ -416,7 +400,6 @@ void MultiArg<T>::reset()
Arg::reset(); Arg::reset();
_values.clear(); _values.clear();
} }
} // namespace TCLAP } // namespace TCLAP
#endif #endif

@ -1,4 +1,3 @@
/****************************************************************************** /******************************************************************************
* *
* file: MultiSwitchArg.h * file: MultiSwitchArg.h
@ -30,8 +29,8 @@
#include <tclap/SwitchArg.h> #include <tclap/SwitchArg.h>
namespace TCLAP { namespace TCLAP
{
/** /**
* A multiple switch argument. If the switch is set on the command line, then * 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. * the getValue method will return the number of times the switch appears.
@ -39,7 +38,6 @@ namespace TCLAP {
class MultiSwitchArg : public SwitchArg class MultiSwitchArg : public SwitchArg
{ {
protected: protected:
/** /**
* The value of the switch. * The value of the switch.
*/ */
@ -52,7 +50,6 @@ class MultiSwitchArg : public SwitchArg
int _default; int _default;
public: public:
/** /**
* MultiSwitchArg constructor. * MultiSwitchArg constructor.
* \param flag - The one character flag that identifies this * \param flag - The one character flag that identifies this
@ -66,11 +63,8 @@ class MultiSwitchArg : public SwitchArg
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
MultiSwitchArg(const std::string& flag, MultiSwitchArg(const std::string &flag, const std::string &name, const std::string &desc,
const std::string& name, int init = 0, Visitor *v = NULL);
const std::string& desc,
int init = 0,
Visitor* v = NULL);
/** /**
@ -87,12 +81,8 @@ class MultiSwitchArg : public SwitchArg
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
MultiSwitchArg(const std::string& flag, MultiSwitchArg(const std::string &flag, const std::string &name, const std::string &desc,
const std::string& name, CmdLineInterface &parser, int init = 0, Visitor *v = NULL);
const std::string& desc,
CmdLineInterface& parser,
int init = 0,
Visitor* v = NULL);
/** /**
@ -121,41 +111,36 @@ class MultiSwitchArg : public SwitchArg
std::string longID(const std::string &val) const; std::string longID(const std::string &val) const;
void reset(); void reset();
}; };
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
//BEGIN MultiSwitchArg.cpp //BEGIN MultiSwitchArg.cpp
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
inline MultiSwitchArg::MultiSwitchArg(const std::string& flag, inline MultiSwitchArg::MultiSwitchArg(const std::string &flag, const std::string &name,
const std::string& name, const std::string &desc, int init, Visitor *v) :
const std::string& desc, SwitchArg(flag, name, desc, false, v), _value(init), _default(init)
int init, {
Visitor* v ) }
: SwitchArg(flag, name, desc, false, v),
_value( init ), inline MultiSwitchArg::MultiSwitchArg(const std::string &flag, const std::string &name,
_default( init ) const std::string &desc, CmdLineInterface &parser, 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); parser.add(this);
} }
inline int MultiSwitchArg::getValue() { return _value; } inline int MultiSwitchArg::getValue()
{
return _value;
}
inline bool MultiSwitchArg::processArg(int *i, std::vector<std::string> &args) inline bool MultiSwitchArg::processArg(int *i, std::vector<std::string> &args)
{ {
if (_ignoreable && Arg::ignoreRest()) if (_ignoreable && Arg::ignoreRest())
{
return false; return false;
}
if (argMatches(args[*i])) if (argMatches(args[*i]))
{ {
@ -179,30 +164,31 @@ inline bool MultiSwitchArg::processArg(int *i, std::vector<std::string>& args)
// Check for more in argument and increment value. // Check for more in argument and increment value.
while (combinedSwitchesMatch(args[*i])) while (combinedSwitchesMatch(args[*i]))
{
++_value; ++_value;
}
_checkWithVisitor(); _checkWithVisitor();
return false; return false;
} }
else else
{
return false; return false;
} }
}
inline std::string inline std::string MultiSwitchArg::shortID(const std::string &val) const
MultiSwitchArg::shortID(const std::string& val) const
{ {
return Arg::shortID(val) + " ... "; return Arg::shortID(val) + " ... ";
} }
inline std::string inline std::string MultiSwitchArg::longID(const std::string &val) const
MultiSwitchArg::longID(const std::string& val) const
{ {
return Arg::longID(val) + " (accepted multiple times)"; return Arg::longID(val) + " (accepted multiple times)";
} }
inline void inline void MultiSwitchArg::reset()
MultiSwitchArg::reset()
{ {
MultiSwitchArg::_value = MultiSwitchArg::_default; MultiSwitchArg::_value = MultiSwitchArg::_default;
} }
@ -210,7 +196,6 @@ MultiSwitchArg::reset()
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
//END MultiSwitchArg.cpp //END MultiSwitchArg.cpp
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
} //namespace TCLAP } //namespace TCLAP
#endif #endif

@ -1,5 +1,3 @@
/****************************************************************************** /******************************************************************************
* *
* file: OptionalUnlabeledTracker.h * file: OptionalUnlabeledTracker.h
@ -26,37 +24,45 @@
#include <string> #include <string>
namespace TCLAP { namespace TCLAP
{
class OptionalUnlabeledTracker class OptionalUnlabeledTracker
{ {
public: public:
static void check(bool req, const std::string &argName); static void check(bool req, const std::string &argName);
static void gotOptional() { alreadyOptionalRef() = true; } static void gotOptional()
{
alreadyOptionalRef() = true;
}
static bool& alreadyOptional() { return alreadyOptionalRef(); } static bool& alreadyOptional()
{
return alreadyOptionalRef();
}
private: private:
static bool& alreadyOptionalRef()
static bool& alreadyOptionalRef() { static bool ct = false; return ct; } {
static bool ct = false;
return ct;
}
}; };
inline void OptionalUnlabeledTracker::check(bool req, const std::string &argName) inline void OptionalUnlabeledTracker::check(bool req, const std::string &argName)
{ {
if (OptionalUnlabeledTracker::alreadyOptional()) if (OptionalUnlabeledTracker::alreadyOptional())
{
throw (SpecificationException( throw (SpecificationException(
"You can't specify ANY Unlabeled Arg following an optional Unlabeled Arg", "You can't specify ANY Unlabeled Arg following an optional Unlabeled Arg", argName));
argName ) ); }
if (!req) if (!req)
{
OptionalUnlabeledTracker::gotOptional(); OptionalUnlabeledTracker::gotOptional();
} }
}
} // namespace TCLAP } // namespace TCLAP
#endif #endif

@ -30,8 +30,8 @@
#include <config.h> // To check for long long #include <config.h> // To check for long long
#endif #endif
namespace TCLAP { namespace TCLAP
{
// ====================================================================== // ======================================================================
// Integer types // Integer types
// ====================================================================== // ======================================================================
@ -40,7 +40,8 @@ namespace TCLAP {
* longs have value-like semantics. * longs have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<long> { struct ArgTraits<long>
{
typedef ValueLike ValueCategory; typedef ValueLike ValueCategory;
}; };
@ -48,7 +49,8 @@ struct ArgTraits<long> {
* ints have value-like semantics. * ints have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<int> { struct ArgTraits<int>
{
typedef ValueLike ValueCategory; typedef ValueLike ValueCategory;
}; };
@ -56,7 +58,8 @@ struct ArgTraits<int> {
* shorts have value-like semantics. * shorts have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<short> { struct ArgTraits<short>
{
typedef ValueLike ValueCategory; typedef ValueLike ValueCategory;
}; };
@ -64,7 +67,8 @@ struct ArgTraits<short> {
* chars have value-like semantics. * chars have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<char> { struct ArgTraits<char>
{
typedef ValueLike ValueCategory; typedef ValueLike ValueCategory;
}; };
@ -73,9 +77,11 @@ struct ArgTraits<char> {
* long longs have value-like semantics. * long longs have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<long long> { struct ArgTraits<long long>
{
typedef ValueLike ValueCategory; typedef ValueLike ValueCategory;
}; };
#endif #endif
// ====================================================================== // ======================================================================
@ -86,7 +92,8 @@ struct ArgTraits<long long> {
* unsigned longs have value-like semantics. * unsigned longs have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<unsigned long> { struct ArgTraits<unsigned long>
{
typedef ValueLike ValueCategory; typedef ValueLike ValueCategory;
}; };
@ -94,7 +101,8 @@ struct ArgTraits<unsigned long> {
* unsigned ints have value-like semantics. * unsigned ints have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<unsigned int> { struct ArgTraits<unsigned int>
{
typedef ValueLike ValueCategory; typedef ValueLike ValueCategory;
}; };
@ -102,7 +110,8 @@ struct ArgTraits<unsigned int> {
* unsigned shorts have value-like semantics. * unsigned shorts have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<unsigned short> { struct ArgTraits<unsigned short>
{
typedef ValueLike ValueCategory; typedef ValueLike ValueCategory;
}; };
@ -110,7 +119,8 @@ struct ArgTraits<unsigned short> {
* unsigned chars have value-like semantics. * unsigned chars have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<unsigned char> { struct ArgTraits<unsigned char>
{
typedef ValueLike ValueCategory; typedef ValueLike ValueCategory;
}; };
@ -119,9 +129,11 @@ struct ArgTraits<unsigned char> {
* unsigned long longs have value-like semantics. * unsigned long longs have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<unsigned long long> { struct ArgTraits<unsigned long long>
{
typedef ValueLike ValueCategory; typedef ValueLike ValueCategory;
}; };
#endif #endif
// ====================================================================== // ======================================================================
@ -132,7 +144,8 @@ struct ArgTraits<unsigned long long> {
* floats have value-like semantics. * floats have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<float> { struct ArgTraits<float>
{
typedef ValueLike ValueCategory; typedef ValueLike ValueCategory;
}; };
@ -140,7 +153,8 @@ struct ArgTraits<float> {
* doubles have value-like semantics. * doubles have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<double> { struct ArgTraits<double>
{
typedef ValueLike ValueCategory; typedef ValueLike ValueCategory;
}; };
@ -152,7 +166,8 @@ struct ArgTraits<double> {
* bools have value-like semantics. * bools have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<bool> { struct ArgTraits<bool>
{
typedef ValueLike ValueCategory; typedef ValueLike ValueCategory;
}; };
@ -170,7 +185,8 @@ struct ArgTraits<wchar_t> {
* Strings have string like argument traits. * Strings have string like argument traits.
*/ */
template<> template<>
struct ArgTraits<std::string> { struct ArgTraits<std::string>
{
typedef StringLike ValueCategory; typedef StringLike ValueCategory;
}; };
@ -179,8 +195,6 @@ void SetString(T &dst, const std::string &src)
{ {
dst = src; dst = src;
} }
} // namespace } // namespace
#endif #endif

@ -34,17 +34,15 @@
#include <tclap/XorHandler.h> #include <tclap/XorHandler.h>
#include <tclap/Arg.h> #include <tclap/Arg.h>
namespace TCLAP { namespace TCLAP
{
/** /**
* A class that isolates any output from the CmdLine object so that it * A class that isolates any output from the CmdLine object so that it
* may be easily modified. * may be easily modified.
*/ */
class StdOutput : public CmdLineOutput class StdOutput : public CmdLineOutput
{ {
public: public:
/** /**
* Prints the usage to stdout. Can be overridden to * Prints the usage to stdout. Can be overridden to
* produce alternative behavior. * produce alternative behavior.
@ -65,11 +63,9 @@ class StdOutput : public CmdLineOutput
* \param c - The CmdLine object the output is generated for. * \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure. * \param e - The ArgException that caused the failure.
*/ */
virtual void failure(CmdLineInterface& c, virtual void failure(CmdLineInterface &c, ArgException &e);
ArgException& e );
protected: protected:
/** /**
* Writes a brief usage message with short args. * Writes a brief usage message with short args.
* \param c - The CmdLine object the output is generated for. * \param c - The CmdLine object the output is generated for.
@ -96,22 +92,16 @@ class StdOutput : public CmdLineOutput
* \param secondLineOffset - The number of spaces to indent the second * \param secondLineOffset - The number of spaces to indent the second
* and all subsequent lines in addition to indentSpaces. * and all subsequent lines in addition to indentSpaces.
*/ */
void spacePrint( std::ostream& os, void spacePrint(std::ostream &os, const std::string &s, int maxWidth, int indentSpaces,
const std::string& s,
int maxWidth,
int indentSpaces,
int secondLineOffset) const; int secondLineOffset) const;
}; };
inline void StdOutput::version(CmdLineInterface &_cmd) inline void StdOutput::version(CmdLineInterface &_cmd)
{ {
std::string progName = _cmd.getProgramName(); std::string progName = _cmd.getProgramName();
std::string version = _cmd.getVersion(); std::string version = _cmd.getVersion();
std::cout << std::endl << progName << " version: " std::cout << std::endl << progName << " version: " << version << std::endl << std::endl;
<< version << std::endl << std::endl;
} }
inline void StdOutput::usage(CmdLineInterface &_cmd) inline void StdOutput::usage(CmdLineInterface &_cmd)
@ -125,16 +115,14 @@ inline void StdOutput::usage(CmdLineInterface& _cmd )
_longUsage(_cmd, std::cout); _longUsage(_cmd, std::cout);
std::cout << std::endl; std::cout << std::endl;
} }
inline void StdOutput::failure( CmdLineInterface& _cmd, inline void StdOutput::failure(CmdLineInterface &_cmd, ArgException &e)
ArgException& e )
{ {
std::string progName = _cmd.getProgramName(); std::string progName = _cmd.getProgramName();
std::cerr << "PARSE ERROR: " << e.argId() << std::endl std::cerr << "PARSE ERROR: " << e.argId() << std::endl << " " << e.error() <<
<< " " << e.error() << std::endl << std::endl; std::endl << std::endl;
if (_cmd.hasHelpAndVersion()) if (_cmd.hasHelpAndVersion())
{ {
@ -142,19 +130,18 @@ inline void StdOutput::failure( CmdLineInterface& _cmd,
_shortUsage(_cmd, std::cerr); _shortUsage(_cmd, std::cerr);
std::cerr << std::endl << "For complete USAGE and HELP type: " std::cerr << std::endl << "For complete USAGE and HELP type: " << std::endl << " " <<
<< std::endl << " " << progName << " --help" progName << " --help" << std::endl << std::endl;
<< std::endl << std::endl;
} }
else else
{
usage(_cmd); usage(_cmd);
}
throw ExitException(1); throw ExitException(1);
} }
inline void inline void StdOutput::_shortUsage(CmdLineInterface &_cmd, std::ostream &os) const
StdOutput::_shortUsage( CmdLineInterface& _cmd,
std::ostream& os ) const
{ {
std::list<Arg*> argList = _cmd.getArgList(); std::list<Arg*> argList = _cmd.getArgList();
std::string progName = _cmd.getProgramName(); std::string progName = _cmd.getProgramName();
@ -169,27 +156,33 @@ StdOutput::_shortUsage( CmdLineInterface& _cmd,
s += " {"; s += " {";
for (ArgVectorIterator it = xorList[i].begin(); for (ArgVectorIterator it = xorList[i].begin();
it != xorList[i].end(); it++) it != xorList[i].end(); it++)
{
s += (*it)->shortID() + "|"; s += (*it)->shortID() + "|";
}
s[s.length() - 1] = '}'; s[s.length() - 1] = '}';
} }
// then the rest // then the rest
for (ArgListIterator it = argList.begin(); it != argList.end(); it++) for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
{
if (!xorHandler.contains((*it))) if (!xorHandler.contains((*it)))
{
s += " " + (*it)->shortID(); s += " " + (*it)->shortID();
}
}
// if the program name is too long, then adjust the second line offset // if the program name is too long, then adjust the second line offset
int secondLineOffset = static_cast<int>(progName.length()) + 2; int secondLineOffset = static_cast<int>(progName.length()) + 2;
if (secondLineOffset > 75 / 2) if (secondLineOffset > 75 / 2)
{
secondLineOffset = static_cast<int>(75 / 2); secondLineOffset = static_cast<int>(75 / 2);
}
spacePrint(os, s, 75, 3, secondLineOffset); spacePrint(os, s, 75, 3, secondLineOffset);
} }
inline void inline void StdOutput::_longUsage(CmdLineInterface &_cmd, std::ostream &os) const
StdOutput::_longUsage( CmdLineInterface& _cmd,
std::ostream& os ) const
{ {
std::list<Arg*> argList = _cmd.getArgList(); std::list<Arg*> argList = _cmd.getArgList();
std::string message = _cmd.getMessage(); std::string message = _cmd.getMessage();
@ -207,30 +200,31 @@ StdOutput::_longUsage( CmdLineInterface& _cmd,
spacePrint(os, (*it)->getDescription(), 75, 5, 0); spacePrint(os, (*it)->getDescription(), 75, 5, 0);
if (it + 1 != xorList[i].end()) if (it + 1 != xorList[i].end())
{
spacePrint(os, "-- OR --", 75, 9, 0); spacePrint(os, "-- OR --", 75, 9, 0);
} }
}
os << std::endl << std::endl; os << std::endl << std::endl;
} }
// then the rest // then the rest
for (ArgListIterator it = argList.begin(); it != argList.end(); it++) for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
{
if (!xorHandler.contains((*it))) if (!xorHandler.contains((*it)))
{ {
spacePrint(os, (*it)->longID(), 75, 3, 3); spacePrint(os, (*it)->longID(), 75, 3, 3);
spacePrint(os, (*it)->getDescription(), 75, 5, 0); spacePrint(os, (*it)->getDescription(), 75, 5, 0);
os << std::endl; 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, inline void StdOutput::spacePrint(std::ostream &os, const std::string &s, int maxWidth,
const std::string& s, int indentSpaces, int secondLineOffset) const
int maxWidth,
int indentSpaces,
int secondLineOffset ) const
{ {
int len = static_cast<int>(s.length()); int len = static_cast<int>(s.length());
@ -248,25 +242,37 @@ inline void StdOutput::spacePrint( std::ostream& os,
// trim the length so it doesn't end in middle of a word // trim the length so it doesn't end in middle of a word
if (stringLen == allowedLen) if (stringLen == allowedLen)
{
while (stringLen >= 0 && while (stringLen >= 0 &&
s[stringLen + start] != ' ' && s[stringLen + start] != ' ' &&
s[stringLen + start] != ',' && s[stringLen + start] != ',' &&
s[stringLen + start] != '|') s[stringLen + start] != '|')
{
stringLen--; stringLen--;
}
}
// ok, the word is longer than the line, so just split // ok, the word is longer than the line, so just split
// wherever the line ends // wherever the line ends
if (stringLen <= 0) if (stringLen <= 0)
{
stringLen = allowedLen; stringLen = allowedLen;
}
// check for newlines // check for newlines
for (int i = 0; i < stringLen; i++) for (int i = 0; i < stringLen; i++)
{
if (s[start + i] == '\n') if (s[start + i] == '\n')
{
stringLen = i + 1; stringLen = i + 1;
}
}
// print the indent // print the indent
for (int i = 0; i < indentSpaces; i++) for (int i = 0; i < indentSpaces; i++)
{
os << " "; os << " ";
}
if (start == 0) if (start == 0)
{ {
@ -281,7 +287,9 @@ inline void StdOutput::spacePrint( std::ostream& os,
// so we don't start a line with a space // so we don't start a line with a space
while (s[stringLen + start] == ' ' && start < len) while (s[stringLen + start] == ' ' && start < len)
{
start++; start++;
}
start += stringLen; start += stringLen;
} }
@ -289,10 +297,12 @@ inline void StdOutput::spacePrint( std::ostream& os,
else else
{ {
for (int i = 0; i < indentSpaces; i++) for (int i = 0; i < indentSpaces; i++)
{
os << " "; os << " ";
}
os << s << std::endl; os << s << std::endl;
} }
} }
} //namespace TCLAP } //namespace TCLAP
#endif #endif

@ -1,4 +1,3 @@
/****************************************************************************** /******************************************************************************
* *
* file: SwitchArg.h * file: SwitchArg.h
@ -29,8 +28,8 @@
#include <tclap/Arg.h> #include <tclap/Arg.h>
namespace TCLAP { namespace TCLAP
{
/** /**
* A simple switch argument. If the switch is set on the command line, then * 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 * the getValue method will return the opposite of the default value for the
@ -39,7 +38,6 @@ namespace TCLAP {
class SwitchArg : public Arg class SwitchArg : public Arg
{ {
protected: protected:
/** /**
* The value of the switch. * The value of the switch.
*/ */
@ -52,7 +50,6 @@ class SwitchArg : public Arg
bool _default; bool _default;
public: public:
/** /**
* SwitchArg constructor. * SwitchArg constructor.
* \param flag - The one character flag that identifies this * \param flag - The one character flag that identifies this
@ -65,11 +62,8 @@ class SwitchArg : public Arg
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
SwitchArg(const std::string& flag, SwitchArg(const std::string &flag, const std::string &name, const std::string &desc,
const std::string& name, bool def = false, Visitor *v = NULL);
const std::string& desc,
bool def = false,
Visitor* v = NULL);
/** /**
@ -85,12 +79,8 @@ class SwitchArg : public Arg
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
SwitchArg(const std::string& flag, SwitchArg(const std::string &flag, const std::string &name, const std::string &desc,
const std::string& name, CmdLineInterface &parser, bool def = false, Visitor *v = NULL);
const std::string& desc,
CmdLineInterface& parser,
bool def = false,
Visitor* v = NULL);
/** /**
@ -115,56 +105,55 @@ class SwitchArg : public Arg
bool getValue(); bool getValue();
virtual void reset(); virtual void reset();
}; };
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
//BEGIN SwitchArg.cpp //BEGIN SwitchArg.cpp
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
inline SwitchArg::SwitchArg(const std::string& flag, inline SwitchArg::SwitchArg(const std::string &flag, const std::string &name,
const std::string& name, const std::string &desc, bool default_val, Visitor *v) :
const std::string& desc, Arg(flag, name, desc, false, false, v), _value(default_val), _default(default_val)
bool default_val, {
Visitor* v ) }
: Arg(flag, name, desc, false, false, v),
_value( default_val ), inline SwitchArg::SwitchArg(const std::string &flag, const std::string &name,
_default( default_val ) const std::string &desc, CmdLineInterface &parser, 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); parser.add(this);
} }
inline bool SwitchArg::getValue() { return _value; } inline bool SwitchArg::getValue()
{
return _value;
}
inline bool SwitchArg::combinedSwitchesMatch(std::string &combinedSwitches) inline bool SwitchArg::combinedSwitchesMatch(std::string &combinedSwitches)
{ {
// make sure this is actually a combined switch // make sure this is actually a combined switch
if (combinedSwitches.length() > 0 && if (combinedSwitches.length() > 0 &&
combinedSwitches[0] != Arg::flagStartString()[0]) combinedSwitches[0] != Arg::flagStartString()[0])
{
return false; return false;
}
// make sure it isn't a long name // make sure it isn't a long name
if ( combinedSwitches.substr( 0, Arg::nameStartString().length() ) == if (combinedSwitches.substr(0, Arg::nameStartString().length()) == Arg::nameStartString())
Arg::nameStartString() ) {
return false; return false;
}
// make sure the delimiter isn't in the string // make sure the delimiter isn't in the string
if (combinedSwitches.find_first_of(Arg::delimiter()) != std::string::npos) if (combinedSwitches.find_first_of(Arg::delimiter()) != std::string::npos)
{
return false; return false;
}
// ok, we're not specifying a ValueArg, so we know that we have // ok, we're not specifying a ValueArg, so we know that we have
// a combined switch list. // a combined switch list.
for (unsigned int i = 1; i < combinedSwitches.length(); i++) for (unsigned int i = 1; i < combinedSwitches.length(); i++)
{
if (_flag.length() > 0 && if (_flag.length() > 0 &&
combinedSwitches[i] == _flag[0] && combinedSwitches[i] == _flag[0] &&
_flag[0] != Arg::flagStartString()[0]) _flag[0] != Arg::flagStartString()[0])
@ -176,16 +165,18 @@ inline bool SwitchArg::combinedSwitchesMatch(std::string& combinedSwitches )
combinedSwitches[i] = Arg::blankChar(); combinedSwitches[i] = Arg::blankChar();
return true; return true;
} }
}
// none of the switches passed in the list match. // none of the switches passed in the list match.
return false; return false;
} }
inline bool SwitchArg::processArg(int *i, std::vector<std::string> &args) inline bool SwitchArg::processArg(int *i, std::vector<std::string> &args)
{ {
if (_ignoreable && Arg::ignoreRest()) if (_ignoreable && Arg::ignoreRest())
{
return false; return false;
}
if (argMatches(args[*i]) || combinedSwitchesMatch(args[*i])) if (argMatches(args[*i]) || combinedSwitchesMatch(args[*i]))
{ {
@ -194,35 +185,45 @@ inline bool SwitchArg::processArg(int *i, std::vector<std::string>& args)
// chance to match. // chance to match.
bool ret = false; bool ret = false;
if (argMatches(args[*i])) if (argMatches(args[*i]))
{
ret = true; ret = true;
}
if (_alreadySet || (!ret && combinedSwitchesMatch(args[*i]))) if (_alreadySet || (!ret && combinedSwitchesMatch(args[*i])))
{
throw (CmdLineParseException("Argument already set!", toString())); throw (CmdLineParseException("Argument already set!", toString()));
}
_alreadySet = true; _alreadySet = true;
if (_value == true) if (_value == true)
{
_value = false; _value = false;
}
else else
{
_value = true; _value = true;
}
_checkWithVisitor(); _checkWithVisitor();
return ret; return ret;
} }
else else
{
return false; return false;
} }
}
inline void SwitchArg::reset() inline void SwitchArg::reset()
{ {
Arg::reset(); Arg::reset();
_value = _default; _value = _default;
} }
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
//End SwitchArg.cpp //End SwitchArg.cpp
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
} //namespace TCLAP } //namespace TCLAP
#endif #endif

@ -1,4 +1,3 @@
/****************************************************************************** /******************************************************************************
* *
* file: UnlabeledMultiArg.h * file: UnlabeledMultiArg.h
@ -29,8 +28,8 @@
#include <tclap/MultiArg.h> #include <tclap/MultiArg.h>
#include <tclap/OptionalUnlabeledTracker.h> #include <tclap/OptionalUnlabeledTracker.h>
namespace TCLAP { namespace TCLAP
{
/** /**
* Just like a MultiArg, except that the arguments are unlabeled. Basically, * Just like a MultiArg, except that the arguments are unlabeled. Basically,
* this Arg will slurp up everything that hasn't been matched to another * this Arg will slurp up everything that hasn't been matched to another
@ -39,7 +38,6 @@ namespace TCLAP {
template<class T> template<class T>
class UnlabeledMultiArg : public MultiArg<T> class UnlabeledMultiArg : public MultiArg<T>
{ {
// If compiler has two stage name lookup (as gcc >= 3.4 does) // If compiler has two stage name lookup (as gcc >= 3.4 does)
// this is requried to prevent undef. symbols // this is requried to prevent undef. symbols
using MultiArg<T>::_ignoreable; using MultiArg<T>::_ignoreable;
@ -52,7 +50,6 @@ class UnlabeledMultiArg : public MultiArg<T>
using MultiArg<T>::toString; using MultiArg<T>::toString;
public: public:
/** /**
* Constructor. * Constructor.
* \param name - The name of the Arg. Note that this is used for * \param name - The name of the Arg. Note that this is used for
@ -70,12 +67,9 @@ class UnlabeledMultiArg : public MultiArg<T>
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
UnlabeledMultiArg( const std::string& name, UnlabeledMultiArg(const std::string &name, const std::string &desc, bool req,
const std::string& desc, const std::string &typeDesc, bool ignoreable = false, Visitor *v = NULL);
bool req,
const std::string& typeDesc,
bool ignoreable = false,
Visitor* v = NULL );
/** /**
* Constructor. * Constructor.
* \param name - The name of the Arg. Note that this is used for * \param name - The name of the Arg. Note that this is used for
@ -94,13 +88,9 @@ class UnlabeledMultiArg : public MultiArg<T>
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
UnlabeledMultiArg( const std::string& name, UnlabeledMultiArg(const std::string &name, const std::string &desc, bool req,
const std::string& desc, const std::string &typeDesc, CmdLineInterface &parser,
bool req, bool ignoreable = false, Visitor *v = NULL);
const std::string& typeDesc,
CmdLineInterface& parser,
bool ignoreable = false,
Visitor* v = NULL );
/** /**
* Constructor. * Constructor.
@ -117,12 +107,8 @@ class UnlabeledMultiArg : public MultiArg<T>
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
UnlabeledMultiArg( const std::string& name, UnlabeledMultiArg(const std::string &name, const std::string &desc, bool req,
const std::string& desc, Constraint<T> *constraint, bool ignoreable = false, Visitor *v = NULL);
bool req,
Constraint<T>* constraint,
bool ignoreable = false,
Visitor* v = NULL );
/** /**
* Constructor. * Constructor.
@ -140,13 +126,9 @@ class UnlabeledMultiArg : public MultiArg<T>
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
UnlabeledMultiArg( const std::string& name, UnlabeledMultiArg(const std::string &name, const std::string &desc, bool req,
const std::string& desc, Constraint<T> *constraint, CmdLineInterface &parser,
bool req, bool ignoreable = false, Visitor *v = NULL);
Constraint<T>* constraint,
CmdLineInterface& parser,
bool ignoreable = false,
Visitor* v = NULL );
/** /**
* Handles the processing of the argument. * Handles the processing of the argument.
@ -184,73 +166,57 @@ class UnlabeledMultiArg : public MultiArg<T>
}; };
template<class T> template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name, UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string &name, const std::string &desc,
const std::string& desc, bool req, const std::string &typeDesc, bool ignoreable,
bool req, Visitor *v) :
const std::string& typeDesc, MultiArg<T>("", name, desc, req, typeDesc, v)
bool ignoreable,
Visitor* v)
: MultiArg<T>("", name, desc, req, typeDesc, v)
{ {
_ignoreable = ignoreable; _ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString()); OptionalUnlabeledTracker::check(true, toString());
} }
template<class T> template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name, UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string &name, const std::string &desc,
const std::string& desc, bool req, const std::string &typeDesc,
bool req, CmdLineInterface &parser, bool ignoreable, Visitor *v) :
const std::string& typeDesc, MultiArg<T>("", name, desc, req, typeDesc, v)
CmdLineInterface& parser,
bool ignoreable,
Visitor* v)
: MultiArg<T>("", name, desc, req, typeDesc, v)
{ {
_ignoreable = ignoreable; _ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString()); OptionalUnlabeledTracker::check(true, toString());
parser.add(this); parser.add(this);
} }
template<class T> template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name, UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string &name, const std::string &desc,
const std::string& desc, bool req, Constraint<T> *constraint, bool ignoreable,
bool req, Visitor *v) :
Constraint<T>* constraint, MultiArg<T>("", name, desc, req, constraint, v)
bool ignoreable,
Visitor* v)
: MultiArg<T>("", name, desc, req, constraint, v)
{ {
_ignoreable = ignoreable; _ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString()); OptionalUnlabeledTracker::check(true, toString());
} }
template<class T> template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name, UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string &name, const std::string &desc,
const std::string& desc, bool req, Constraint<T> *constraint,
bool req, CmdLineInterface &parser, bool ignoreable, Visitor *v) :
Constraint<T>* constraint, MultiArg<T>("", name, desc, req, constraint, v)
CmdLineInterface& parser,
bool ignoreable,
Visitor* v)
: MultiArg<T>("", name, desc, req, constraint, v)
{ {
_ignoreable = ignoreable; _ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString()); OptionalUnlabeledTracker::check(true, toString());
parser.add(this); parser.add(this);
} }
template<class T> template<class T>
bool UnlabeledMultiArg<T>::processArg(int *i, std::vector<std::string> &args) bool UnlabeledMultiArg<T>::processArg(int *i, std::vector<std::string> &args)
{ {
if (_hasBlanks(args[*i])) if (_hasBlanks(args[*i]))
{
return false; return false;
}
// never ignore an unlabeled multi arg // never ignore an unlabeled multi arg
// always take the first value, regardless of the start string // always take the first value, regardless of the start string
_extractValue(args[(*i)]); _extractValue(args[(*i)]);
@ -285,17 +251,20 @@ template<class T>
bool UnlabeledMultiArg<T>::operator==(const Arg &a) const bool UnlabeledMultiArg<T>::operator==(const Arg &a) const
{ {
if (_name == a.getName() || _description == a.getDescription()) if (_name == a.getName() || _description == a.getDescription())
{
return true; return true;
}
else else
{
return false; return false;
} }
}
template<class T> template<class T>
void UnlabeledMultiArg<T>::addToList(std::list<Arg*> &argList) const void UnlabeledMultiArg<T>::addToList(std::list<Arg*> &argList) const
{ {
argList.push_back(const_cast<Arg*>(static_cast<const Arg*const>(this))); argList.push_back(const_cast<Arg*>(static_cast<const Arg*const>(this)));
} }
} }
#endif #endif

@ -1,4 +1,3 @@
/****************************************************************************** /******************************************************************************
* *
* file: UnlabeledValueArg.h * file: UnlabeledValueArg.h
@ -31,8 +30,8 @@
#include <tclap/OptionalUnlabeledTracker.h> #include <tclap/OptionalUnlabeledTracker.h>
namespace TCLAP { namespace TCLAP
{
/** /**
* The basic unlabeled argument that parses a value. * The basic unlabeled argument that parses a value.
* This is a template class, which means the type T defines the type * This is a template class, which means the type T defines the type
@ -42,7 +41,6 @@ namespace TCLAP {
template<class T> template<class T>
class UnlabeledValueArg : public ValueArg<T> class UnlabeledValueArg : public ValueArg<T>
{ {
// If compiler has two stage name lookup (as gcc >= 3.4 does) // If compiler has two stage name lookup (as gcc >= 3.4 does)
// this is requried to prevent undef. symbols // this is requried to prevent undef. symbols
using ValueArg<T>::_ignoreable; using ValueArg<T>::_ignoreable;
@ -55,7 +53,6 @@ class UnlabeledValueArg : public ValueArg<T>
using ValueArg<T>::toString; using ValueArg<T>::toString;
public: public:
/** /**
* UnlabeledValueArg constructor. * UnlabeledValueArg constructor.
* \param name - A one word name for the argument. Note that this is used for * \param name - A one word name for the argument. Note that this is used for
@ -77,13 +74,8 @@ class UnlabeledValueArg : public ValueArg<T>
* \param v - Optional Vistor. You should leave this blank unless * \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason. * you have a very good reason.
*/ */
UnlabeledValueArg( const std::string& name, UnlabeledValueArg(const std::string &name, const std::string &desc, bool req, T value,
const std::string& desc, const std::string &typeDesc, bool ignoreable = false, Visitor *v = NULL);
bool req,
T value,
const std::string& typeDesc,
bool ignoreable = false,
Visitor* v = NULL);
/** /**
* UnlabeledValueArg constructor. * UnlabeledValueArg constructor.
@ -107,14 +99,9 @@ class UnlabeledValueArg : public ValueArg<T>
* \param v - Optional Vistor. You should leave this blank unless * \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason. * you have a very good reason.
*/ */
UnlabeledValueArg( const std::string& name, UnlabeledValueArg(const std::string &name, const std::string &desc, bool req, T value,
const std::string& desc, const std::string &typeDesc, CmdLineInterface &parser,
bool req, bool ignoreable = false, Visitor *v = NULL);
T value,
const std::string& typeDesc,
CmdLineInterface& parser,
bool ignoreable = false,
Visitor* v = NULL );
/** /**
* UnlabeledValueArg constructor. * UnlabeledValueArg constructor.
@ -135,13 +122,8 @@ class UnlabeledValueArg : public ValueArg<T>
* \param v - Optional Vistor. You should leave this blank unless * \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason. * you have a very good reason.
*/ */
UnlabeledValueArg( const std::string& name, UnlabeledValueArg(const std::string &name, const std::string &desc, bool req, T value,
const std::string& desc, Constraint<T> *constraint, bool ignoreable = false, Visitor *v = NULL);
bool req,
T value,
Constraint<T>* constraint,
bool ignoreable = false,
Visitor* v = NULL );
/** /**
@ -164,14 +146,9 @@ class UnlabeledValueArg : public ValueArg<T>
* \param v - Optional Vistor. You should leave this blank unless * \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason. * you have a very good reason.
*/ */
UnlabeledValueArg( const std::string& name, UnlabeledValueArg(const std::string &name, const std::string &desc, bool req, T value,
const std::string& desc, Constraint<T> *constraint, CmdLineInterface &parser,
bool req, bool ignoreable = false, Visitor *v = NULL);
T value,
Constraint<T>* constraint,
CmdLineInterface& parser,
bool ignoreable = false,
Visitor* v = NULL);
/** /**
* Handles the processing of the argument. * Handles the processing of the argument.
@ -203,38 +180,27 @@ class UnlabeledValueArg : public ValueArg<T>
* \param argList - The list to add this to. * \param argList - The list to add this to.
*/ */
virtual void addToList(std::list<Arg*> &argList) const; virtual void addToList(std::list<Arg*> &argList) const;
}; };
/** /**
* Constructor implemenation. * Constructor implemenation.
*/ */
template<class T> template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name, UnlabeledValueArg<T>::UnlabeledValueArg(const std::string &name, const std::string &desc,
const std::string& desc, bool req, T val, const std::string &typeDesc,
bool req, bool ignoreable, Visitor *v) :
T val, ValueArg<T>("", name, desc, req, val, typeDesc, v)
const std::string& typeDesc,
bool ignoreable,
Visitor* v)
: ValueArg<T>("", name, desc, req, val, typeDesc, v)
{ {
_ignoreable = ignoreable; _ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString()); OptionalUnlabeledTracker::check(req, toString());
} }
template<class T> template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name, UnlabeledValueArg<T>::UnlabeledValueArg(const std::string &name, const std::string &desc,
const std::string& desc, bool req, T val, const std::string &typeDesc,
bool req, CmdLineInterface &parser, bool ignoreable, Visitor *v) :
T val, ValueArg<T>("", name, desc, req, val, typeDesc, v)
const std::string& typeDesc,
CmdLineInterface& parser,
bool ignoreable,
Visitor* v)
: ValueArg<T>("", name, desc, req, val, typeDesc, v)
{ {
_ignoreable = ignoreable; _ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString()); OptionalUnlabeledTracker::check(req, toString());
@ -245,29 +211,20 @@ UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name,
* Constructor implemenation. * Constructor implemenation.
*/ */
template<class T> template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name, UnlabeledValueArg<T>::UnlabeledValueArg(const std::string &name, const std::string &desc,
const std::string& desc, bool req, T val, Constraint<T> *constraint,
bool req, bool ignoreable, Visitor *v) :
T val, ValueArg<T>("", name, desc, req, val, constraint, v)
Constraint<T>* constraint,
bool ignoreable,
Visitor* v)
: ValueArg<T>("", name, desc, req, val, constraint, v)
{ {
_ignoreable = ignoreable; _ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString()); OptionalUnlabeledTracker::check(req, toString());
} }
template<class T> template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name, UnlabeledValueArg<T>::UnlabeledValueArg(const std::string &name, const std::string &desc,
const std::string& desc, bool req, T val, Constraint<T> *constraint,
bool req, CmdLineInterface &parser, bool ignoreable, Visitor *v) :
T val, ValueArg<T>("", name, desc, req, val, constraint, v)
Constraint<T>* constraint,
CmdLineInterface& parser,
bool ignoreable,
Visitor* v)
: ValueArg<T>("", name, desc, req, val, constraint, v)
{ {
_ignoreable = ignoreable; _ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString()); OptionalUnlabeledTracker::check(req, toString());
@ -280,12 +237,15 @@ UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name,
template<class T> template<class T>
bool UnlabeledValueArg<T>::processArg(int *i, std::vector<std::string> &args) bool UnlabeledValueArg<T>::processArg(int *i, std::vector<std::string> &args)
{ {
if (_alreadySet) if (_alreadySet)
{
return false; return false;
}
if (_hasBlanks(args[*i])) if (_hasBlanks(args[*i]))
{
return false; return false;
}
// never ignore an unlabeled arg // never ignore an unlabeled arg
@ -325,16 +285,20 @@ template<class T>
bool UnlabeledValueArg<T>::operator==(const Arg &a) const bool UnlabeledValueArg<T>::operator==(const Arg &a) const
{ {
if (_name == a.getName() || _description == a.getDescription()) if (_name == a.getName() || _description == a.getDescription())
{
return true; return true;
}
else else
{
return false; return false;
} }
}
template<class T> template<class T>
void UnlabeledValueArg<T>::addToList(std::list<Arg*> &argList) const void UnlabeledValueArg<T>::addToList(std::list<Arg*> &argList) const
{ {
argList.push_back(const_cast<Arg*>(static_cast<const Arg*const>(this))); argList.push_back(const_cast<Arg*>(static_cast<const Arg*const>(this)));
} }
} }
#endif #endif

@ -29,8 +29,8 @@
#include <tclap/Arg.h> #include <tclap/Arg.h>
#include <tclap/Constraint.h> #include <tclap/Constraint.h>
namespace TCLAP { namespace TCLAP
{
/** /**
* The basic labeled argument that parses a value. * The basic labeled argument that parses a value.
* This is a template class, which means the type T defines the type * This is a template class, which means the type T defines the type
@ -43,7 +43,6 @@ template<class T>
class ValueArg : public Arg class ValueArg : public Arg
{ {
protected: protected:
/** /**
* The value parsed from the command line. * The value parsed from the command line.
* Can be of any type, as long as the >> operator for the type * Can be of any type, as long as the >> operator for the type
@ -80,7 +79,6 @@ class ValueArg : public Arg
void _extractValue(const std::string &val); void _extractValue(const std::string &val);
public: public:
/** /**
* Labeled ValueArg constructor. * Labeled ValueArg constructor.
* You could conceivably call this constructor with a blank flag, * You could conceivably call this constructor with a blank flag,
@ -104,13 +102,8 @@ class ValueArg : public Arg
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
ValueArg( const std::string& flag, ValueArg(const std::string &flag, const std::string &name, const std::string &desc, bool req,
const std::string& name, T value, const std::string &typeDesc, Visitor *v = NULL);
const std::string& desc,
bool req,
T value,
const std::string& typeDesc,
Visitor* v = NULL);
/** /**
@ -137,14 +130,8 @@ class ValueArg : public Arg
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
ValueArg( const std::string& flag, ValueArg(const std::string &flag, const std::string &name, const std::string &desc, bool req,
const std::string& name, T value, const std::string &typeDesc, CmdLineInterface &parser, Visitor *v = NULL);
const std::string& desc,
bool req,
T value,
const std::string& typeDesc,
CmdLineInterface& parser,
Visitor* v = NULL );
/** /**
* Labeled ValueArg constructor. * Labeled ValueArg constructor.
@ -168,14 +155,8 @@ class ValueArg : public Arg
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
ValueArg( const std::string& flag, ValueArg(const std::string &flag, const std::string &name, const std::string &desc, bool req,
const std::string& name, T value, Constraint<T> *constraint, CmdLineInterface &parser, Visitor *v = NULL);
const std::string& desc,
bool req,
T value,
Constraint<T>* constraint,
CmdLineInterface& parser,
Visitor* v = NULL );
/** /**
* Labeled ValueArg constructor. * Labeled ValueArg constructor.
@ -198,13 +179,8 @@ class ValueArg : public Arg
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
ValueArg( const std::string& flag, ValueArg(const std::string &flag, const std::string &name, const std::string &desc, bool req,
const std::string& name, T value, Constraint<T> *constraint, Visitor *v = NULL);
const std::string& desc,
bool req,
T value,
Constraint<T>* constraint,
Visitor* v = NULL );
/** /**
* Handles the processing of the argument. * Handles the processing of the argument.
@ -235,7 +211,6 @@ class ValueArg : public Arg
virtual std::string longID(const std::string &val = "val") const; virtual std::string longID(const std::string &val = "val") const;
virtual void reset(); virtual void reset();
}; };
@ -243,77 +218,49 @@ class ValueArg : public Arg
* Constructor implementation. * Constructor implementation.
*/ */
template<class T> template<class T>
ValueArg<T>::ValueArg(const std::string& flag, ValueArg<T>::ValueArg(const std::string &flag, const std::string &name, const std::string &desc,
const std::string& name, bool req, T val, const std::string &typeDesc, Visitor *v) :
const std::string& desc, Arg(flag, name, desc, req, true, v), _value(val), _default(val), _typeDesc(typeDesc),
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) _constraint(NULL)
{ } {
}
template<class T> template<class T>
ValueArg<T>::ValueArg(const std::string& flag, ValueArg<T>::ValueArg(const std::string &flag, const std::string &name, const std::string &desc,
const std::string& name, bool req, T val, const std::string &typeDesc, CmdLineInterface &parser,
const std::string& desc, Visitor *v) :
bool req, Arg(flag, name, desc, req, true, v), _value(val), _default(val), _typeDesc(typeDesc),
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) _constraint(NULL)
{ {
parser.add(this); parser.add(this);
} }
template<class T> template<class T>
ValueArg<T>::ValueArg(const std::string& flag, ValueArg<T>::ValueArg(const std::string &flag, const std::string &name, const std::string &desc,
const std::string& name, bool req, T val, Constraint<T> *constraint, Visitor *v) :
const std::string& desc, Arg(flag, name, desc, req, true, v), _value(val), _default(val), _typeDesc(
bool req, constraint->shortID()), _constraint(constraint)
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> template<class T>
ValueArg<T>::ValueArg(const std::string& flag, ValueArg<T>::ValueArg(const std::string &flag, const std::string &name, const std::string &desc,
const std::string& name, bool req, T val, Constraint<T> *constraint, CmdLineInterface &parser,
const std::string& desc, Visitor *v) :
bool req, Arg(flag, name, desc, req, true, v), _value(val), _default(val), _typeDesc(
T val, constraint->shortID()), _constraint(constraint)
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); parser.add(this);
} }
/** /**
* Implementation of getValue(). * Implementation of getValue().
*/ */
template<class T> template<class T>
T& ValueArg<T>::getValue() { return _value; } T& ValueArg<T>::getValue()
{
return _value;
}
/** /**
* Implementation of processArg(). * Implementation of processArg().
@ -322,10 +269,14 @@ template<class T>
bool ValueArg<T>::processArg(int *i, std::vector<std::string> &args) bool ValueArg<T>::processArg(int *i, std::vector<std::string> &args)
{ {
if (_ignoreable && Arg::ignoreRest()) if (_ignoreable && Arg::ignoreRest())
{
return false; return false;
}
if (_hasBlanks(args[*i])) if (_hasBlanks(args[*i]))
{
return false; return false;
}
std::string flag = args[*i]; std::string flag = args[*i];
@ -335,32 +286,42 @@ bool ValueArg<T>::processArg(int *i, std::vector<std::string>& args)
if (argMatches(flag)) if (argMatches(flag))
{ {
if (_alreadySet) if (_alreadySet)
{
throw (CmdLineParseException("Argument already set!", toString())); throw (CmdLineParseException("Argument already set!", toString()));
}
if (Arg::delimiter() != ' ' && value == "") if (Arg::delimiter() != ' ' && value == "")
{
throw (ArgParseException( throw (ArgParseException(
"Couldn't find delimiter for this argument!", "Couldn't find delimiter for this argument!", toString()));
toString() ) ); }
if (value == "") if (value == "")
{ {
(*i)++; (*i)++;
if (static_cast<unsigned int>(*i) < args.size()) if (static_cast<unsigned int>(*i) < args.size())
{
_extractValue(args[*i]); _extractValue(args[*i]);
}
else else
throw( ArgParseException("Missing a value for this argument!", {
toString() ) ); throw (ArgParseException("Missing a value for this argument!", toString()));
}
} }
else else
{
_extractValue(value); _extractValue(value);
}
_alreadySet = true; _alreadySet = true;
_checkWithVisitor(); _checkWithVisitor();
return true; return true;
} }
else else
{
return false; return false;
} }
}
/** /**
* Implementation of shortID. * Implementation of shortID.
@ -385,18 +346,23 @@ std::string ValueArg<T>::longID(const std::string& val) const
template<class T> template<class T>
void ValueArg<T>::_extractValue(const std::string &val) void ValueArg<T>::_extractValue(const std::string &val)
{ {
try { try
{
ExtractValue(_value, val, typename ArgTraits<T>::ValueCategory()); ExtractValue(_value, val, typename ArgTraits<T>::ValueCategory());
} catch( ArgParseException &e) { }
catch (ArgParseException &e)
{
throw ArgParseException(e.error(), toString()); throw ArgParseException(e.error(), toString());
} }
if (_constraint != NULL) if (_constraint != NULL)
{
if (!_constraint->check(_value)) if (!_constraint->check(_value))
throw( CmdLineParseException( "Value '" + val + {
+ "' does not meet constraint: " throw (CmdLineParseException("Value '" + val + +"' does not meet constraint: " +
+ _constraint->description(), _constraint->description(), toString()));
toString() ) ); }
}
} }
template<class T> template<class T>
@ -405,7 +371,6 @@ void ValueArg<T>::reset()
Arg::reset(); Arg::reset();
_value = _default; _value = _default;
} }
} // namespace TCLAP } // namespace TCLAP
#endif #endif

@ -1,5 +1,3 @@
/****************************************************************************** /******************************************************************************
* *
* file: ValuesConstraint.h * file: ValuesConstraint.h
@ -41,7 +39,8 @@
#error "Need a stringstream (sstream or strstream) to compile!" #error "Need a stringstream (sstream or strstream) to compile!"
#endif #endif
namespace TCLAP { namespace TCLAP
{
/** /**
* A Constraint that constrains the Arg to only those values specified * A Constraint that constrains the Arg to only those values specified
@ -50,9 +49,7 @@ namespace TCLAP {
template<class T> template<class T>
class ValuesConstraint : public Constraint<T> class ValuesConstraint : public Constraint<T>
{ {
public: public:
/** /**
* Constructor. * Constructor.
* \param allowed - vector of allowed values. * \param allowed - vector of allowed values.
@ -62,7 +59,9 @@ class ValuesConstraint : public Constraint<T>
/** /**
* Virtual destructor. * Virtual destructor.
*/ */
virtual ~ValuesConstraint() {} virtual ~ValuesConstraint()
{
}
/** /**
* Returns a description of the Constraint. * Returns a description of the Constraint.
@ -82,7 +81,6 @@ class ValuesConstraint : public Constraint<T>
virtual bool check(const T &value) const; virtual bool check(const T &value) const;
protected: protected:
/** /**
* The list of valid values. * The list of valid values.
*/ */
@ -92,16 +90,14 @@ class ValuesConstraint : public Constraint<T>
* The string used to describe the allowed values of this constraint. * The string used to describe the allowed values of this constraint.
*/ */
std::string _typeDesc; std::string _typeDesc;
}; };
template<class T> template<class T>
ValuesConstraint<T>::ValuesConstraint(std::vector<T>& allowed) ValuesConstraint<T>::ValuesConstraint(std::vector<T> &allowed) :
: _allowed(allowed) _allowed(allowed)
{ {
for (unsigned int i = 0; i < _allowed.size(); i++) for (unsigned int i = 0; i < _allowed.size(); i++)
{ {
#if defined (HAVE_SSTREAM) #if defined (HAVE_SSTREAM)
std::ostringstream os; std::ostringstream os;
#elif defined (HAVE_STRSTREAM) #elif defined (HAVE_STRSTREAM)
@ -115,7 +111,9 @@ ValuesConstraint<T>::ValuesConstraint(std::vector<T>& allowed)
std::string temp(os.str()); std::string temp(os.str());
if (i > 0) if (i > 0)
{
_typeDesc += "|"; _typeDesc += "|";
}
_typeDesc += temp; _typeDesc += temp;
} }
} }
@ -124,10 +122,14 @@ template<class T>
bool ValuesConstraint<T>::check(const T &val) const bool ValuesConstraint<T>::check(const T &val) const
{ {
if (std::find(_allowed.begin(), _allowed.end(), val) == _allowed.end()) if (std::find(_allowed.begin(), _allowed.end(), val) == _allowed.end())
{
return false; return false;
}
else else
{
return true; return true;
} }
}
template<class T> template<class T>
std::string ValuesConstraint<T>::shortID() const std::string ValuesConstraint<T>::shortID() const
@ -140,8 +142,6 @@ std::string ValuesConstraint<T>::description() const
{ {
return _typeDesc; return _typeDesc;
} }
} //namespace TCLAP } //namespace TCLAP
#endif
#endif

@ -28,8 +28,8 @@
#include <tclap/CmdLineOutput.h> #include <tclap/CmdLineOutput.h>
#include <tclap/Visitor.h> #include <tclap/Visitor.h>
namespace TCLAP { namespace TCLAP
{
/** /**
* A Vistor that will call the version method of the given CmdLineOutput * A Vistor that will call the version method of the given CmdLineOutput
* for the specified CmdLine object and then exit. * for the specified CmdLine object and then exit.
@ -37,7 +37,6 @@ namespace TCLAP {
class VersionVisitor : public Visitor class VersionVisitor : public Visitor
{ {
protected: protected:
/** /**
* The CmdLine of interest. * The CmdLine of interest.
*/ */
@ -49,26 +48,26 @@ class VersionVisitor: public Visitor
CmdLineOutput **_out; CmdLineOutput **_out;
public: public:
/** /**
* Constructor. * Constructor.
* \param cmd - The CmdLine the output is generated for. * \param cmd - The CmdLine the output is generated for.
* \param out - The type of output. * \param out - The type of output.
*/ */
VersionVisitor( CmdLineInterface* cmd, CmdLineOutput** out ) VersionVisitor(CmdLineInterface *cmd, CmdLineOutput **out) :
: Visitor(), _cmd( cmd ), _out( out ) { } Visitor(), _cmd(cmd), _out(out)
{
}
/** /**
* Calls the version method of the output object using the * Calls the version method of the output object using the
* specified CmdLine. * specified CmdLine.
*/ */
void visit() { void visit()
{
(*_out)->version(*_cmd); (*_out)->version(*_cmd);
throw ExitException(0); throw ExitException(0);
} }
}; };
} }
#endif #endif

@ -1,4 +1,3 @@
/****************************************************************************** /******************************************************************************
* *
* file: Visitor.h * file: Visitor.h
@ -23,31 +22,35 @@
#ifndef TCLAP_VISITOR_H #ifndef TCLAP_VISITOR_H
#define TCLAP_VISITOR_H #define TCLAP_VISITOR_H
namespace TCLAP { namespace TCLAP
{
/** /**
* A base class that defines the interface for visitors. * A base class that defines the interface for visitors.
*/ */
class Visitor class Visitor
{ {
public: public:
/** /**
* Constructor. Does nothing. * Constructor. Does nothing.
*/ */
Visitor() { } Visitor()
{
}
/** /**
* Destructor. Does nothing. * Destructor. Does nothing.
*/ */
virtual ~Visitor() { } virtual ~Visitor()
{
}
/** /**
* Does nothing. Should be overridden by child. * Does nothing. Should be overridden by child.
*/ */
virtual void visit() { } virtual void visit()
{
}
}; };
} }
#endif #endif

@ -1,4 +1,3 @@
/****************************************************************************** /******************************************************************************
* *
* file: XorHandler.h * file: XorHandler.h
@ -29,7 +28,8 @@
#include <algorithm> #include <algorithm>
#include <iostream> #include <iostream>
namespace TCLAP { namespace TCLAP
{
/** /**
* This class handles lists of Arg's that are to be XOR'd on the command * This class handles lists of Arg's that are to be XOR'd on the command
@ -38,18 +38,18 @@ namespace TCLAP {
class XorHandler class XorHandler
{ {
protected: protected:
/** /**
* The list of of lists of Arg's to be or'd together. * The list of of lists of Arg's to be or'd together.
*/ */
std::vector<std::vector<Arg*>> _orList; std::vector<std::vector<Arg*>> _orList;
public: public:
/** /**
* Constructor. Does nothing. * Constructor. Does nothing.
*/ */
XorHandler( ) {} XorHandler()
{
}
/** /**
* Add a list of Arg*'s that will be orred together. * Add a list of Arg*'s that will be orred together.
@ -85,10 +85,8 @@ class XorHandler
bool contains(const Arg *a); bool contains(const Arg *a);
std::vector<std::vector<Arg*>>& getXorList(); std::vector<std::vector<Arg*>>& getXorList();
}; };
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
//BEGIN XOR.cpp //BEGIN XOR.cpp
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -103,39 +101,56 @@ inline int XorHandler::check( const Arg* a )
for (int i = 0; static_cast<unsigned int>(i) < _orList.size(); i++) for (int i = 0; static_cast<unsigned int>(i) < _orList.size(); i++)
{ {
// if the XOR list contains the arg.. // if the XOR list contains the arg..
ArgVectorIterator ait = std::find( _orList[i].begin(), ArgVectorIterator ait = std::find(_orList[i].begin(), _orList[i].end(), a);
_orList[i].end(), a );
if (ait != _orList[i].end()) if (ait != _orList[i].end())
{ {
// go through and set each arg that is not a // go through and set each arg that is not a
for (ArgVectorIterator it = _orList[i].begin(); for (ArgVectorIterator it = _orList[i].begin();
it != _orList[i].end(); it != _orList[i].end();
it++) it++)
{
if (a != (*it)) if (a != (*it))
{
(*it)->xorSet(); (*it)->xorSet();
}
}
// return the number of required args that have now been set // return the number of required args that have now been set
if ((*ait)->allowMore()) if ((*ait)->allowMore())
{
return 0; return 0;
}
else else
{
return static_cast<int>(_orList[i].size()); return static_cast<int>(_orList[i].size());
} }
} }
}
if (a->isRequired()) if (a->isRequired())
{
return 1; return 1;
}
else else
{
return 0; return 0;
} }
}
inline bool XorHandler::contains(const Arg *a) inline bool XorHandler::contains(const Arg *a)
{ {
for (int i = 0; static_cast<unsigned int>(i) < _orList.size(); i++) for (int i = 0; static_cast<unsigned int>(i) < _orList.size(); i++)
{
for (ArgVectorIterator it = _orList[i].begin(); for (ArgVectorIterator it = _orList[i].begin();
it != _orList[i].end(); it != _orList[i].end();
it++) it++)
{
if (a == (*it)) if (a == (*it))
{
return true; return true;
}
}
}
return false; return false;
} }
@ -145,12 +160,9 @@ inline std::vector< std::vector<Arg*> >& XorHandler::getXorList()
return _orList; return _orList;
} }
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
//END XOR.cpp //END XOR.cpp
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
} //namespace TCLAP } //namespace TCLAP
#endif #endif

@ -34,17 +34,15 @@
#include <tclap/XorHandler.h> #include <tclap/XorHandler.h>
#include <tclap/Arg.h> #include <tclap/Arg.h>
namespace TCLAP { namespace TCLAP
{
/** /**
* A class that generates a Zsh completion function as output from the usage() * A class that generates a Zsh completion function as output from the usage()
* method for the given CmdLine and its Args. * method for the given CmdLine and its Args.
*/ */
class ZshCompletionOutput : public CmdLineOutput class ZshCompletionOutput : public CmdLineOutput
{ {
public: public:
ZshCompletionOutput(); ZshCompletionOutput();
/** /**
@ -67,11 +65,9 @@ class ZshCompletionOutput : public CmdLineOutput
* \param c - The CmdLine object the output is generated for. * \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure. * \param e - The ArgException that caused the failure.
*/ */
virtual void failure(CmdLineInterface& c, virtual void failure(CmdLineInterface &c, ArgException &e);
ArgException& e );
protected: protected:
void basename(std::string &s); void basename(std::string &s);
void quoteSpecialChars(std::string &s); void quoteSpecialChars(std::string &s);
@ -109,23 +105,25 @@ inline void ZshCompletionOutput::usage(CmdLineInterface& _cmd )
theDelimiter = _cmd.getDelimiter(); theDelimiter = _cmd.getDelimiter();
basename(progName); basename(progName);
std::cout << "#compdef " << progName << std::endl << std::endl << std::cout << "#compdef " << progName << std::endl << std::endl << "# " << progName <<
"# " << progName << " version " << _cmd.getVersion() << std::endl << std::endl << " version " << _cmd.getVersion() << std::endl << std::endl << "_arguments -s -S";
"_arguments -s -S";
for (ArgListIterator it = argList.begin(); it != argList.end(); it++) for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
{ {
if ((*it)->shortID().at(0) == '<') if ((*it)->shortID().at(0) == '<')
{
printArg((*it)); printArg((*it));
}
else if ((*it)->getFlag() != "-") else if ((*it)->getFlag() != "-")
{
printOption((*it), getMutexList(_cmd, *it)); printOption((*it), getMutexList(_cmd, *it));
} }
}
std::cout << std::endl; std::cout << std::endl;
} }
inline void ZshCompletionOutput::failure( CmdLineInterface& _cmd, inline void ZshCompletionOutput::failure(CmdLineInterface &_cmd, ArgException &e)
ArgException& e )
{ {
static_cast<void>(_cmd); // unused static_cast<void>(_cmd); // unused
std::cout << e.what() << std::endl; std::cout << e.what() << std::endl;
@ -144,11 +142,15 @@ inline void ZshCompletionOutput::quoteSpecialChars( std::string& s )
{ {
s.insert(idx, "'\\'"); s.insert(idx, "'\\'");
if (idx == 0) if (idx == 0)
{
idx = std::string::npos; idx = std::string::npos;
}
else else
{
idx = s.find_last_of('\'', --idx); idx = s.find_last_of('\'', --idx);
} }
} }
}
inline void ZshCompletionOutput::basename(std::string &s) inline void ZshCompletionOutput::basename(std::string &s)
{ {
@ -165,12 +167,18 @@ inline void ZshCompletionOutput::printArg(Arg* a)
std::cout << " \\" << std::endl << " '"; std::cout << " \\" << std::endl << " '";
if (a->acceptsMultipleValues()) if (a->acceptsMultipleValues())
{
std::cout << '*'; std::cout << '*';
}
else else
{
std::cout << count++; std::cout << count++;
}
std::cout << ':'; std::cout << ':';
if (!a->isRequired()) if (!a->isRequired())
{
std::cout << ':'; std::cout << ':';
}
std::cout << a->getName() << ':'; std::cout << a->getName() << ':';
std::map<std::string, std::string>::iterator compArg = common.find(a->getName()); std::map<std::string, std::string>::iterator compArg = common.find(a->getName());
@ -222,7 +230,9 @@ inline void ZshCompletionOutput::printOption(Arg* a, std::string mutex)
std::cout << "'{" << flag << ',' << name << "}'"; std::cout << "'{" << flag << ',' << name << "}'";
} }
if (theDelimiter == '=' && a->isValueRequired()) if (theDelimiter == '=' && a->isValueRequired())
{
std::cout << "=-"; std::cout << "=-";
}
quoteSpecialChars(desc); quoteSpecialChars(desc);
std::cout << '[' << desc << ']'; std::cout << '[' << desc << ']';
@ -231,7 +241,9 @@ inline void ZshCompletionOutput::printOption(Arg* a, std::string mutex)
std::string arg = a->shortID(); std::string arg = a->shortID();
arg.erase(0, arg.find_last_of(theDelimiter) + 1); arg.erase(0, arg.find_last_of(theDelimiter) + 1);
if (arg.at(arg.length() - 1) == ']') if (arg.at(arg.length() - 1) == ']')
{
arg.erase(arg.length() - 1); arg.erase(arg.length() - 1);
}
if (arg.at(arg.length() - 1) == ']') if (arg.at(arg.length() - 1) == ']')
{ {
arg.erase(arg.length() - 1); arg.erase(arg.length() - 1);
@ -287,6 +299,7 @@ inline std::string ZshCompletionOutput::getMutexList( CmdLineInterface& _cmd, Ar
for (ArgVectorIterator it = xorList[i].begin(); for (ArgVectorIterator it = xorList[i].begin();
it != xorList[i].end(); it != xorList[i].end();
it++) it++)
{
if (a == (*it)) if (a == (*it))
{ {
list << '('; list << '(';
@ -297,25 +310,33 @@ inline std::string ZshCompletionOutput::getMutexList( CmdLineInterface& _cmd, Ar
bool notCur = (*iu) != a; bool notCur = (*iu) != a;
bool hasFlag = !(*iu)->getFlag().empty(); bool hasFlag = !(*iu)->getFlag().empty();
if (iu != xorList[i].begin() && (notCur || hasFlag)) if (iu != xorList[i].begin() && (notCur || hasFlag))
{
list << ' '; list << ' ';
}
if (hasFlag) if (hasFlag)
{
list << (*iu)->flagStartChar() << (*iu)->getFlag() << ' '; list << (*iu)->flagStartChar() << (*iu)->getFlag() << ' ';
}
if (notCur || hasFlag) if (notCur || hasFlag)
{
list << (*iu)->nameStartString() << (*iu)->getName(); list << (*iu)->nameStartString() << (*iu)->getName();
} }
}
list << ')'; list << ')';
return list.str(); return list.str();
} }
} }
}
// wasn't found in xor list // wasn't found in xor list
if (!a->getFlag().empty()) { if (!a->getFlag().empty())
list << "(" << a->flagStartChar() << a->getFlag() << ' ' << {
a->nameStartString() << a->getName() << ')'; list << "(" << a->flagStartChar() << a->getFlag() << ' ' << a->nameStartString() <<
a->getName() << ')';
} }
return list.str(); return list.str();
} }
} //namespace TCLAP } //namespace TCLAP
#endif #endif

Loading…
Cancel
Save