Format code using uncrustify

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

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

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

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

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

File diff suppressed because it is too large Load Diff

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

File diff suppressed because it is too large Load Diff

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

@ -45,7 +45,6 @@ TQString SettingsPaths::_indenterPath = "";
TQString SettingsPaths::_tempPath = "";
bool SettingsPaths::_portableMode = false;
/*!
\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.
In not portable mode (multiuser mode) only users home directory is used for writing config data.
*/
void SettingsPaths::init() {
void SettingsPaths::init()
{
_alreadyInitialized = true;
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.
_applicationBinaryPath = TQCoreApplication::applicationDirPath();
// Remove any trailing slashes
while ( _applicationBinaryPath.right(1) == "/" ) {
while (_applicationBinaryPath.right(1) == "/")
{
_applicationBinaryPath.chop(1);
}
@ -76,17 +77,21 @@ void SettingsPaths::init() {
// Because on Mac universal binaries are used, the binary path is not equal
// to the applications (.app) path. So get the .apps path here.
int indexOfDotApp = _applicationBinaryPath.indexOf(".app");
if ( indexOfDotApp != -1 ) {
if (indexOfDotApp != -1)
{
// Cut off after the dot of ".app".
_applicationBinaryPath = _applicationBinaryPath.left(indexOfDotApp - 1);
// Cut off after the first slash that was in front of ".app" (normally this is the word "UniversalIndentGUI")
// Cut off after the first slash that was in front of ".app" (normally this is the word
// "UniversalIndentGUI")
_applicationBinaryPath = _applicationBinaryPath.left(_applicationBinaryPath.lastIndexOf("/"));
}
#endif
// If the "config" directory is a subdir of the applications binary path, use this one (portable mode)
// If the "config" directory is a subdir of the applications binary path, use this one (portable
// mode)
_settingsPath = _applicationBinaryPath + "/config";
if ( TQFile::exists( _settingsPath ) ) {
if (TQFile::exists(_settingsPath))
{
_portableMode = true;
TQDir dirCreator;
_globalFilesPath = _applicationBinaryPath;
@ -97,24 +102,28 @@ void SettingsPaths::init() {
dirCreator.mkpath(_tempPath);
}
// ... otherwise use the system specific global application data path.
else {
else
{
_portableMode = false;
TQDir dirCreator;
#ifdef Q_OS_WIN
// Get the local users application settings directory.
// Remove any trailing slashes.
_settingsPath = TQDir::fromNativeSeparators(qgetenv("APPDATA"));
while ( _settingsPath.right(1) == "/" ) {
while (_settingsPath.right(1) == "/")
{
_settingsPath.chop(1);
}
_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;
#else
// Remove any trailing slashes.
_settingsPath = TQDir::homePath();
while ( _settingsPath.right(1) == "/" ) {
while (_settingsPath.right(1) == "/")
{
_settingsPath.chop(1);
}
_settingsPath = _settingsPath + "/.universalindentgui";
@ -123,15 +132,19 @@ void SettingsPaths::init() {
dirCreator.mkpath(_settingsPath);
// If a highlighter config file does not exist in the users home config dir
// copy the default config file over there.
if ( !TQFile::exists(_settingsPath+"/UiGuiSyntaxHighlightConfig.ini") ) {
TQFile::copy( _globalFilesPath+"/config/UiGuiSyntaxHighlightConfig.ini", _settingsPath+"/UiGuiSyntaxHighlightConfig.ini" );
if (!TQFile::exists(_settingsPath + "/UiGuiSyntaxHighlightConfig.ini"))
{
TQFile::copy(_globalFilesPath + "/config/UiGuiSyntaxHighlightConfig.ini",
_settingsPath + "/UiGuiSyntaxHighlightConfig.ini");
}
_indenterPath = _globalFilesPath + "/indenters";
// On different systems it may be that "TQDir::tempPath()" ends with a "/" or not. So check this.
// On different systems it may be that "TQDir::tempPath()" ends with a "/" or not. So check
// this.
// Remove any trailing slashes.
_tempPath = TQDir::tempPath();
while ( _tempPath.right(1) == "/" ) {
while (_tempPath.right(1) == "/")
{
_tempPath.chop(1);
}
_tempPath = _tempPath + "/UniversalIndentGUI";
@ -153,123 +166,144 @@ void SettingsPaths::init() {
}
tqDebug() << __LINE__ << " " << __FUNCTION__ << ": Paths are:" \
"<ul><li>_applicationBinaryPath=" << _applicationBinaryPath \
<< "</li><li>_settingsPath=" << _settingsPath \
<< "</li><li>_globalFilesPath=" << _globalFilesPath \
<< "</li><li>_indenterPath=" << _indenterPath \
<< "</li><li>_tempPath=" << _tempPath \
<< "</li><li>Running in portable mode=" << _portableMode << "</li></ul>";
"<ul><li>_applicationBinaryPath=" <<
_applicationBinaryPath << "</li><li>_settingsPath=" << _settingsPath <<
"</li><li>_globalFilesPath=" << _globalFilesPath << "</li><li>_indenterPath=" <<
_indenterPath << "</li><li>_tempPath=" << _tempPath <<
"</li><li>Running in portable mode=" << _portableMode << "</li></ul>";
}
/*!
\brief Returns the path of the applications executable.
*/
const TQString SettingsPaths::getApplicationBinaryPath() {
if ( !_alreadyInitialized ) {
const TQString SettingsPaths::getApplicationBinaryPath()
{
if (!_alreadyInitialized)
{
SettingsPaths::init();
}
return _applicationBinaryPath;
}
/*!
\brief Returns the path where all settings are being/should be written to.
*/
const TQString SettingsPaths::getSettingsPath() {
if ( !_alreadyInitialized ) {
const TQString SettingsPaths::getSettingsPath()
{
if (!_alreadyInitialized)
{
SettingsPaths::init();
}
return _settingsPath;
}
/*!
\brief Returns the path where the files concerning all users reside. For example translations.
*/
const TQString SettingsPaths::getGlobalFilesPath() {
if ( !_alreadyInitialized ) {
const TQString SettingsPaths::getGlobalFilesPath()
{
if (!_alreadyInitialized)
{
SettingsPaths::init();
}
return _globalFilesPath;
}
/*!
\brief Returns the path where the indenter executables reside.
*/
const TQString SettingsPaths::getIndenterPath() {
if ( !_alreadyInitialized ) {
const TQString SettingsPaths::getIndenterPath()
{
if (!_alreadyInitialized)
{
SettingsPaths::init();
}
return _indenterPath;
}
/*!
\brief Returns the path where the where all temporary data should be written to.
*/
const TQString SettingsPaths::getTempPath() {
if ( !_alreadyInitialized ) {
const TQString SettingsPaths::getTempPath()
{
if (!_alreadyInitialized)
{
SettingsPaths::init();
}
return _tempPath;
}
/*!
\brief Returns true if portable mode shall be used.
*/
bool SettingsPaths::getPortableMode() {
if ( !_alreadyInitialized ) {
bool SettingsPaths::getPortableMode()
{
if (!_alreadyInitialized)
{
SettingsPaths::init();
}
return _portableMode;
}
/*!
\brief Completely deletes the created temporary directory with all of its content.
*/
void SettingsPaths::cleanAndRemoveTempDir() {
void SettingsPaths::cleanAndRemoveTempDir()
{
TQDirIterator dirIterator(_tempPath, TQDirIterator::Subdirectories);
TQStack<TQString> directoryStack;
bool noErrorsOccurred = true;
while ( dirIterator.hasNext() ) {
while (dirIterator.hasNext())
{
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();
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.
// So we changed into another parent directory and the one on the stack can be deleted
// since it must be empty.
if ( !directoryStack.isEmpty() && !currentDirOrFile.startsWith(directoryStack.top()) ) {
if (!directoryStack.isEmpty() && !currentDirOrFile.startsWith(directoryStack.top()))
{
TQString dirToBeRemoved = directoryStack.pop();
bool couldRemoveDir = TQDir(dirToBeRemoved).rmdir(dirToBeRemoved);
noErrorsOccurred &= couldRemoveDir;
if (couldRemoveDir == false)
tqWarning() << __LINE__ << " " << __FUNCTION__ << "Could not remove the directory: " << dirToBeRemoved;
{
tqWarning() << __LINE__ << " " << __FUNCTION__ << "Could not remove the directory: " <<
dirToBeRemoved;
}
//tqDebug() << "Removing Dir " << directoryStack.pop();
}
// If the iterator currently points to a directory push it onto the stack.
if ( dirIterator.fileInfo().isDir() ) {
if (dirIterator.fileInfo().isDir())
{
directoryStack.push(currentDirOrFile);
//tqDebug() << "Pushing onto Stack " << currentDirOrFile;
}
// otherwise it must be a file, so delete it.
else {
else
{
bool couldRemoveFile = TQFile::remove(currentDirOrFile);
noErrorsOccurred &= couldRemoveFile;
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;
}
}
}
noErrorsOccurred &= TQDir(_tempPath).rmdir(_tempPath);
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.
And "__INDENTERCALLSTRINGSCRIPTNAME__" which is only the shown name of the indenter.
*/
const char* TemplateBatchScript::getTemplateBatchScript() {
const char* TemplateBatchScript::getTemplateBatchScript()
{
static const char *templateBatchScript =
#if defined (Q_OS_WIN32)
"@echo off\n"
@ -121,7 +122,6 @@ const char* TemplateBatchScript::getTemplateBatchScript() {
return templateBatchScript;
}
/* Here comes the original batch script without the c++ markup
@echo off

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

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

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

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

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

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

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

@ -48,22 +48,26 @@ TQWeakPointer<UiGuiSettings> UiGuiSettings::_instance;
/*!
\brief The constructor for the settings.
*/
UiGuiSettings::UiGuiSettings() : TQObject() {
UiGuiSettings::UiGuiSettings() :
TQObject()
{
// 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";
readAvailableTranslations();
initSettings();
}
/*!
\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();
if ( sharedInstance.isNull() ) {
if (sharedInstance.isNull())
{
// Create the settings object, which loads all UiGui settings from a file.
sharedInstance = TQSharedPointer<UiGuiSettings>(new UiGuiSettings());
_instance = sharedInstance.toWeakRef();
@ -72,29 +76,32 @@ TQSharedPointer<UiGuiSettings> UiGuiSettings::getInstance() {
return sharedInstance;
}
/*!
\brief The destructor saves the settings to a file.
*/
UiGuiSettings::~UiGuiSettings() {
UiGuiSettings::~UiGuiSettings()
{
// Convert the language setting from an integer index to a string.
int index = _qsettings->value("UniversalIndentGUI/language", 0).toInt();
if (index < 0 || index >= _availableTranslations.size())
{
index = 0;
}
_qsettings->setValue("UniversalIndentGUI/language", _availableTranslations.at(index));
}
/*!
\brief Scans the translations directory for available translation files and
stores them in the TQList \a _availableTranslations.
*/
void UiGuiSettings::readAvailableTranslations() {
void UiGuiSettings::readAvailableTranslations()
{
TQString languageShort;
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";
// Find all translation files in the "translations" directory.
@ -102,7 +109,8 @@ void UiGuiSettings::readAvailableTranslations() {
languageFileList << translationDirectory.entryList(TQStringList("universalindent_*.qm"));
// Loop for each found translation file
foreach ( languageShort, languageFileList ) {
foreach(languageShort, languageFileList)
{
// Remove the leading string "universalindent_" from the filename.
languageShort.remove(0, 16);
// Remove trailing file extension ".qm".
@ -112,25 +120,24 @@ void UiGuiSettings::readAvailableTranslations() {
}
}
/*!
\brief Returns a list of the mnemonics of the available translations.
*/
TQStringList UiGuiSettings::getAvailableTranslations() {
TQStringList UiGuiSettings::getAvailableTranslations()
{
return _availableTranslations;
}
/*!
\brief Returns the value of the by \a settingsName defined setting as TQVariant.
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);
}
/*!
\brief Loads the settings for the main application.
@ -139,103 +146,136 @@ TQVariant UiGuiSettings::getValueByName(TQString settingName) {
bool UiGuiSettings::initSettings()
{
// 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.
_qsettings->setValue( "UniversalIndentGUI/maximized", _qsettings->value("UniversalIndentGUI/maximized", false) );
_qsettings->setValue( "UniversalIndentGUI/position", _qsettings->value("UniversalIndentGUI/position", TQPoint(50, 50)) );
_qsettings->setValue( "UniversalIndentGUI/size", _qsettings->value("UniversalIndentGUI/size", TQSize(800, 600)) );
_qsettings->setValue("UniversalIndentGUI/maximized",
_qsettings->value("UniversalIndentGUI/maximized", false));
_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.
_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.
_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.
_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.
_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.
int selectedIndenter = _qsettings->value("UniversalIndentGUI/selectedIndenter", 0).toInt();
if ( selectedIndenter < 0 ) {
if (selectedIndenter < 0)
{
selectedIndenter = 0;
}
_qsettings->setValue("UniversalIndentGUI/selectedIndenter", selectedIndenter);
// 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.
_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.
_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.
_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.
_qsettings->setValue( "UniversalIndentGUI/language", _availableTranslations.indexOf( _qsettings->value("UniversalIndentGUI/language", "").toString() ) );
// Read the last selected language and stores the index it has in the list of available
// translations.
_qsettings->setValue("UniversalIndentGUI/language",
_availableTranslations.indexOf(_qsettings->value("UniversalIndentGUI/language",
"").toString()));
// Read the update check settings from the settings file.
_qsettings->setValue( "UniversalIndentGUI/CheckForUpdate", _qsettings->value("UniversalIndentGUI/CheckForUpdate", false) );
_qsettings->setValue( "UniversalIndentGUI/LastUpdateCheck", _qsettings->value("UniversalIndentGUI/LastUpdateCheck", TQDate(1900,1,1)) );
_qsettings->setValue("UniversalIndentGUI/CheckForUpdate",
_qsettings->value("UniversalIndentGUI/CheckForUpdate", false));
_qsettings->setValue("UniversalIndentGUI/LastUpdateCheck",
_qsettings->value("UniversalIndentGUI/LastUpdateCheck", TQDate(1900, 1, 1)));
// 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;
}
/*!
\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.
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();
bool connectSuccess = false;
// 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));
if ( connectSuccess && indexOfProp > -1 ) {
if (connectSuccess && indexOfProp > -1)
{
TQMetaProperty mProp = metaObject->property(indexOfProp);
// Connect to the property's value changed signal.
if ( mProp.hasNotifySignal() ) {
if (mProp.hasNotifySignal())
{
TQMetaMethod signal = mProp.notifySignal();
//TQString teststr = qPrintable(SIGNAL() + TQString(signal.signature()));
// The command "SIGNAL() + TQString(signal.signature())" assembles the signal methods signature to a valid TQt SIGNAL.
connectSuccess = connect(obj, qPrintable(SIGNAL() + TQString(signal.signature())), this, SLOT(handleObjectPropertyChange()));
// The command "SIGNAL() + TQString(signal.signature())" assembles the signal methods
// 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;
}
else {
else
{
//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;
}
// 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));
}
// Otherwise add the setting and set it to the value of the objects property.
else {
else
{
_qsettings->setValue("UniversalIndentGUI/" + settingName, mProp.read(obj));
}
}
else {
else
{
//TODO: Write a debug warning to the log.
disconnect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectProperty(TQObject*)));
return false;
@ -244,7 +284,6 @@ bool UiGuiSettings::registerObjectProperty( TQObject *obj, const TQString &prope
return true;
}
/*!
\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.
@ -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 false, if any of those registrations fails.
*/
bool UiGuiSettings::registerObjectPropertyRecursive(TQObject *obj) {
bool UiGuiSettings::registerObjectPropertyRecursive(TQObject *obj)
{
return checkCustomPropertiesAndCallFunction(obj, &UiGuiSettings::registerObjectProperty);
}
/*!
\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
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();
int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName));
if ( indexOfProp > -1 ) {
if (indexOfProp > -1)
{
TQMetaProperty mProp = metaObject->property(indexOfProp);
// 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));
}
// The setting didn't exist so return that setting the objects property failed.
else {
else
{
//TODO: Write a debug warning to the log.
return false;
}
}
else {
else
{
//TODO: Write a debug warning to the log.
return false;
}
@ -294,7 +338,6 @@ bool UiGuiSettings::setObjectPropertyToSettingValue( TQObject *obj, const TQStri
return true;
}
/*!
\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.
@ -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 false, if any of those registrations fails.
*/
bool UiGuiSettings::setObjectPropertyToSettingValueRecursive(TQObject *obj) {
bool UiGuiSettings::setObjectPropertyToSettingValueRecursive(TQObject *obj)
{
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.
@ -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
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();
int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName));
if ( indexOfProp > -1 ) {
if (indexOfProp > -1)
{
TQMetaProperty mProp = metaObject->property(indexOfProp);
setValueByName(settingName, mProp.read(obj));
}
else {
else
{
//TODO: Write a debug warning to the log.
return false;
}
@ -337,7 +383,6 @@ bool UiGuiSettings::setSettingToObjectPropertyValue( TQObject *obj, const TQStri
return true;
}
/*!
\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.
@ -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 false, if any of those registrations fails.
*/
bool UiGuiSettings::setSettingToObjectPropertyValueRecursive(TQObject *obj) {
bool UiGuiSettings::setSettingToObjectPropertyValueRecursive(TQObject *obj)
{
return checkCustomPropertiesAndCallFunction(obj, &UiGuiSettings::setSettingToObjectPropertyValue);
}
/*!
\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
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;
// Find all widgets that have PropertyName and SettingName defined in their style sheet.
TQList<TQObject*> allObjects = obj->findChildren<TQObject*>();
foreach (TQObject *object, allObjects) {
foreach(TQObject * object, allObjects)
{
TQString propertyName = object->property("connectedPropertyName").toString();
TQString settingName = object->property("connectedSettingName").toString();
// 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);
}
}
@ -378,33 +428,37 @@ bool UiGuiSettings::checkCustomPropertiesAndCallFunction(TQObject *obj, bool (Ui
return success;
}
/*!
\brief The with a certain property registered \a obj gets unregistered.
*/
void UiGuiSettings::unregisterObjectProperty(TQObject *obj) {
if ( _registeredObjectProperties.contains(obj) ) {
void UiGuiSettings::unregisterObjectProperty(TQObject *obj)
{
if (_registeredObjectProperties.contains(obj))
{
const TQMetaObject *metaObject = obj->metaObject();
TQString propertyName = _registeredObjectProperties[obj].first();
TQString settingName = _registeredObjectProperties[obj].last();
bool connectSuccess = false;
int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName));
if ( indexOfProp > -1 ) {
if (indexOfProp > -1)
{
TQMetaProperty mProp = metaObject->property(indexOfProp);
// Disconnect to the property's value changed signal.
if ( mProp.hasNotifySignal() ) {
if (mProp.hasNotifySignal())
{
TQMetaMethod signal = mProp.notifySignal();
// The command "SIGNAL() + TQString(signal.signature())" assembles the signal methods signature to a valid TQt SIGNAL.
connectSuccess = disconnect(obj, qPrintable(SIGNAL() + TQString(signal.signature())), this, SLOT(handleObjectPropertyChange()));
// The command "SIGNAL() + TQString(signal.signature())" assembles the signal methods
// signature to a valid TQt SIGNAL.
connectSuccess = disconnect(obj, qPrintable(SIGNAL() + TQString(
signal.signature())), this, SLOT(handleObjectPropertyChange()));
}
}
_registeredObjectProperties.remove(obj);
}
}
/*!
\brief Registers a slot form the \a obj by its \a slotName to be invoked, if the by \a settingName defined
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,
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();
bool connectSuccess = false;
// 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));
int indexOfMethod = metaObject->indexOfMethod(qPrintable(normalizedSlotName));
if ( connectSuccess && indexOfMethod > -1 ) {
if (connectSuccess && indexOfMethod > -1)
{
TQMetaMethod mMethod = metaObject->method(indexOfMethod);
//TQMetaMethod::Access access = mMethod.access();
//TQMetaMethod::MethodType methType = mMethod.methodType();
// Since the method can at maximum be invoked with the setting value as argument,
// only methods taking max one argument are allowed.
if ( mMethod.parameterTypes().size() <= 1 ) {
if (mMethod.parameterTypes().size() <= 1)
{
_registeredObjectSlots.insert(obj, TQStringList() << normalizedSlotName << settingName);
}
else {
else
{
//TODO: Write a debug warning to the log.
disconnect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectSlot(TQObject*)));
return false;
}
}
else {
else
{
//TODO: Write a debug warning to the log.
disconnect(obj, SIGNAL(destroyed(TQObject*)), this, SLOT(unregisterObjectSlot(TQObject*)));
return false;
@ -448,30 +508,36 @@ bool UiGuiSettings::registerObjectSlot(TQObject *obj, const TQString &slotName,
return true;
}
/*!
\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.
*/
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();
TQString normalizedSlotName = TQMetaObject::normalizedSignature(qPrintable(slotName));
TQMutableMapIterator<TQObject*, TQStringList> it(_registeredObjectSlots);
while (it.hasNext()) {
while (it.hasNext())
{
it.next();
if (it.key() == obj && slotName.isEmpty() && settingName.isEmpty())
{
it.remove();
}
else if (it.key() == obj && it.value().first() == slotName && it.value().last() == settingName)
{
it.remove();
}
}
}
/*!
\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.
*/
void UiGuiSettings::handleObjectPropertyChange() {
void UiGuiSettings::handleObjectPropertyChange()
{
TQObject *obj = TQObject::sender();
TQString className = obj->metaObject()->className();
const TQMetaObject *metaObject = obj->metaObject();
@ -479,13 +545,13 @@ void UiGuiSettings::handleObjectPropertyChange() {
TQString settingName = _registeredObjectProperties[obj].last();
int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName));
if ( indexOfProp > -1 ) {
if (indexOfProp > -1)
{
TQMetaProperty mProp = metaObject->property(indexOfProp);
setValueByName(settingName, mProp.read(obj));
}
}
/*!
\brief Sets the setting defined by \a settingName to \a value.
@ -493,20 +559,26 @@ void UiGuiSettings::handleObjectPropertyChange() {
the changed value set too.
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.
if ( _qsettings->value("UniversalIndentGUI/" + settingName) != value ) {
if (_qsettings->value("UniversalIndentGUI/" + settingName) != value)
{
_qsettings->setValue("UniversalIndentGUI/" + settingName, value);
// Set the new value for all registered object properties for settingName.
for ( TQMap<TQObject*, TQStringList>::ConstIterator it = _registeredObjectProperties.begin(); it != _registeredObjectProperties.end(); ++it ) {
if ( it.value().last() == settingName ) {
for (TQMap<TQObject*, TQStringList>::ConstIterator it = _registeredObjectProperties.begin();
it != _registeredObjectProperties.end(); ++it)
{
if (it.value().last() == settingName)
{
TQObject *obj = it.key();
const TQMetaObject *metaObject = obj->metaObject();
TQString propertyName = it.value().first();
int indexOfProp = metaObject->indexOfProperty(qPrintable(propertyName));
if ( indexOfProp > -1 ) {
if (indexOfProp > -1)
{
TQMetaProperty mProp = metaObject->property(indexOfProp);
mProp.write(obj, value);
}
@ -514,14 +586,18 @@ void UiGuiSettings::setValueByName(const TQString &settingName, const TQVariant
}
// Invoke all registered object methods for settingName.
for ( TQMap<TQObject*, TQStringList>::ConstIterator it = _registeredObjectSlots.begin(); it != _registeredObjectSlots.end(); ++it ) {
if ( it.value().last() == settingName ) {
for (TQMap<TQObject*, TQStringList>::ConstIterator it = _registeredObjectSlots.begin();
it != _registeredObjectSlots.end(); ++it)
{
if (it.value().last() == settingName)
{
TQObject *obj = it.key();
const TQMetaObject *metaObject = obj->metaObject();
TQString slotName = it.value().first();
int indexOfMethod = metaObject->indexOfMethod(qPrintable(slotName));
if ( indexOfMethod > -1 ) {
if (indexOfMethod > -1)
{
TQMetaMethod mMethod = metaObject->method(indexOfMethod);
//TQMetaMethod::Access access = mMethod.access();
//TQMetaMethod::MethodType methType = mMethod.methodType();
@ -529,17 +605,21 @@ void UiGuiSettings::setValueByName(const TQString &settingName, const TQVariant
bool success = false;
// Handle registered slots taking one parameter.
if ( mMethod.parameterTypes().size() == 1 ) {
if ( mMethod.parameterTypes().first() == value.typeName() ) {
if (mMethod.parameterTypes().size() == 1)
{
if (mMethod.parameterTypes().first() == value.typeName())
{
success = invokeMethodWithValue(obj, mMethod, value);
}
}
// Handle registered slots taking zero parameters.
else {
else
{
success = mMethod.invoke(obj, TQt::DirectConnection);
}
if ( success == false ) {
if (success == false)
{
// 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 <tntqbitmap.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)
{
switch (value.type()) {
switch (value.type())
{
case TQVariant::BitArray:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQBitArray, value.toBitArray()));
}
case TQVariant::Bitmap:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQBitmap, value.value<TQBitmap>()));
}
case TQVariant::Bool:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(bool, value.toBool()));
}
case TQVariant::Brush:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQBrush, value.value<TQBrush>()));
}
case TQVariant::ByteArray:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQByteArray, value.toByteArray()));
}
case TQVariant::Char:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQChar, value.toChar()));
}
case TQVariant::Color:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQColor, value.value<TQColor>()));
}
case TQVariant::Cursor:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQCursor, value.value<TQCursor>()));
}
case TQVariant::Date:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQDate, value.toDate()));
}
case TQVariant::DateTime:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQDateTime, value.toDateTime()));
}
case TQVariant::Double:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(double, value.toDouble()));
}
case TQVariant::Font:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQFont, value.value<TQFont>()));
}
case TQVariant::Hash:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQVariantHash, value.toHash()));
}
case TQVariant::Icon:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQIcon, value.value<TQIcon>()));
}
case TQVariant::Image:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQImage, value.value<TQImage>()));
}
case TQVariant::Int:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(int, value.toInt()));
}
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:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQLine, value.toLine()));
}
case TQVariant::LineF:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQLineF, value.toLineF()));
}
case TQVariant::List:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQVariantList, value.toList()));
}
case TQVariant::Locale:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQLocale, value.toLocale()));
}
case TQVariant::LongLong:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(qlonglong, value.toLongLong()));
}
case TQVariant::Map:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQVariantMap, value.toMap()));
}
case TQVariant::Matrix:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQMatrix, value.value<TQMatrix>()));
}
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
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
case TQVariant::Palette:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPalette, value.value<TQPalette>()));
}
case TQVariant::Pen:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPen, value.value<TQPen>()));
}
case TQVariant::Pixmap:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPixmap, value.value<TQPixmap>()));
}
case TQVariant::Point:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPoint, value.toPoint()));
}
// case TQVariant::PointArray :
// return Q_ARG(TQPointArray, value.value<TQPointArray>()) );
case TQVariant::PointF:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPointF, value.toPointF()));
}
case TQVariant::Polygon:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQPolygon, value.value<TQPolygon>()));
}
#if TQT_VERSION >= 0x040600
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
case TQVariant::Rect:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQRect, value.toRect()));
}
case TQVariant::RectF:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQRectF, value.toRectF()));
}
case TQVariant::RegExp:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQRegExp, value.toRegExp()));
}
case TQVariant::Region:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQRegion, value.value<TQRegion>()));
}
case TQVariant::Size:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQSize, value.toSize()));
}
case TQVariant::SizeF:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQSizeF, value.toSizeF()));
}
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:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQString, value.toString()));
}
case TQVariant::StringList:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQStringList, value.toStringList()));
}
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:
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:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQTime, value.toTime()));
}
case TQVariant::UInt:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(uint, value.toUInt()));
}
case TQVariant::ULongLong:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(qulonglong, value.toULongLong()));
}
case TQVariant::Url:
{
return mMethod.invoke(obj, TQt::DirectConnection, Q_ARG(TQUrl, value.toUrl()));
}
#if TQT_VERSION >= 0x040600
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:
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:
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
default:
{
return false;
}
}
}

@ -31,33 +31,44 @@ class TQSettings;
class UiGuiSettings : public TQObject
{
Q_OBJECT
private:
UiGuiSettings();
static TQWeakPointer<UiGuiSettings> _instance;
public:
static TQSharedPointer<UiGuiSettings> getInstance();
~UiGuiSettings();
bool registerObjectProperty(TQObject *obj, const TQString &propertyName, const TQString &settingName);
bool registerObjectProperty(TQObject *obj, const TQString &propertyName,
const TQString &settingName);
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 setSettingToObjectPropertyValue(TQObject *obj, const TQString &propertyName, const TQString &settingName);
bool setSettingToObjectPropertyValue(TQObject *obj, const TQString &propertyName,
const TQString &settingName);
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);
TQStringList getAvailableTranslations();
public slots:
void setValueByName(const TQString &settingName, const TQVariant &value);
void unregisterObjectProperty(TQObject *obj);
void unregisterObjectSlot(TQObject *obj, const TQString &slotName = "", const TQString &settingName = "");
void unregisterObjectSlot(TQObject *obj, const TQString &slotName = "",
const TQString &settingName = "");
protected:
bool initSettings();
bool invokeMethodWithValue(TQObject *obj, TQMetaMethod mMethod, TQVariant value);
bool checkCustomPropertiesAndCallFunction(TQObject *obj, bool (UiGuiSettings::*callBackFunc)(TQObject *obj, const TQString &propertyName, const TQString &settingName));
bool checkCustomPropertiesAndCallFunction(TQObject * obj,
bool (UiGuiSettings::*callBackFunc)(TQObject *obj, const TQString &propertyName,
const TQString &settingName));
private slots:
void handleObjectPropertyChange();
@ -71,7 +82,8 @@ private:
//! The settings file.
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;
//! 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.
*/
UiGuiSettingsDialog::UiGuiSettingsDialog(TQWidget* parent, TQSharedPointer<UiGuiSettings> settings) : TQDialog(parent) {
UiGuiSettingsDialog::UiGuiSettingsDialog(TQWidget *parent,
TQSharedPointer<UiGuiSettings> settings) :
TQDialog(parent)
{
// Remember pointer to the UiGuiSettings object.
_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
// 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(this, SIGNAL(accepted()), this, SLOT(writeWidgetValuesToSettings()));
@ -50,55 +55,71 @@ UiGuiSettingsDialog::UiGuiSettingsDialog(TQWidget* parent, TQSharedPointer<UiGui
initTranslationSelection();
}
/*!
\brief By calling this function the combobox for selecting the application language will
be initialized.
Also the translation itself will be reinitialized.
*/
void UiGuiSettingsDialog::initTranslationSelection() {
void UiGuiSettingsDialog::initTranslationSelection()
{
// First empty the combo box.
_settingsDialogForm->languageSelectionComboBox->clear();
// Now add an entry into the box for every language short.
foreach (TQString languageShort, _settings->getAvailableTranslations() ) {
foreach(TQString languageShort, _settings->getAvailableTranslations())
{
// Identify the language mnemonic and set the full name.
if ( languageShort == "en" ) {
_settingsDialogForm->languageSelectionComboBox->addItem( TQIcon(TQString(":/language/language-"+languageShort+".png")), tr("English") );
if (languageShort == "en")
{
_settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-"
+ languageShort + ".png")), tr("English"));
}
else if ( languageShort == "fr" ) {
_settingsDialogForm->languageSelectionComboBox->addItem( TQIcon(TQString(":/language/language-"+languageShort+".png")), tr("French") );
else if (languageShort == "fr")
{
_settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-"
+ languageShort + ".png")), tr("French"));
}
else if ( languageShort == "de" ) {
_settingsDialogForm->languageSelectionComboBox->addItem( TQIcon(TQString(":/language/language-"+languageShort+".png")), tr("German") );
else if (languageShort == "de")
{
_settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-"
+ languageShort + ".png")), tr("German"));
}
else if ( languageShort == "zh_TW" ) {
_settingsDialogForm->languageSelectionComboBox->addItem( TQIcon(TQString(":/language/language-"+languageShort+".png")), tr("Chinese (Taiwan)") );
else if (languageShort == "zh_TW")
{
_settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-"
+ languageShort + ".png")), tr("Chinese (Taiwan)"));
}
else if ( languageShort == "ja" ) {
_settingsDialogForm->languageSelectionComboBox->addItem( TQIcon(TQString(":/language/language-"+languageShort+".png")), tr("Japanese") );
else if (languageShort == "ja")
{
_settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-"
+ languageShort + ".png")), tr("Japanese"));
}
else if ( languageShort == "ru" ) {
_settingsDialogForm->languageSelectionComboBox->addItem( TQIcon(TQString(":/language/language-"+languageShort+".png")), tr("Russian") );
else if (languageShort == "ru")
{
_settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-"
+ languageShort + ".png")), tr("Russian"));
}
else if ( languageShort == "uk" ) {
_settingsDialogForm->languageSelectionComboBox->addItem( TQIcon(TQString(":/language/language-"+languageShort+".png")), tr("Ukrainian") );
else if (languageShort == "uk")
{
_settingsDialogForm->languageSelectionComboBox->addItem(TQIcon(TQString(":/language/language-"
+ languageShort + ".png")), tr("Ukrainian"));
}
else {
_settingsDialogForm->languageSelectionComboBox->addItem( tr("Unknown language mnemonic ") + languageShort );
else
{
_settingsDialogForm->languageSelectionComboBox->addItem(tr(
"Unknown language mnemonic ") + languageShort);
}
}
}
/*!
\brief Displays the dialog by calling the dialogs exec function.
Before it gets all the values needed from the UiGuiSettings object.
*/
int UiGuiSettingsDialog::showDialog() {
int UiGuiSettingsDialog::showDialog()
{
// Init all settings dialog objects with values from settings.
_settings->setObjectPropertyToSettingValueRecursive(this);
@ -106,64 +127,79 @@ int UiGuiSettingsDialog::showDialog() {
return exec();
}
/*!
\brief This slot is called when the dialog box is closed by pressing the Ok button.
Writes all settings to the UiGuiSettings object.
*/
void UiGuiSettingsDialog::writeWidgetValuesToSettings() {
void UiGuiSettingsDialog::writeWidgetValuesToSettings()
{
// Write settings dialog object values to settings.
_settings->setSettingToObjectPropertyValueRecursive(this);
}
/*!
\brief Catches language change events and retranslates all needed widgets.
*/
void UiGuiSettingsDialog::changeEvent(TQEvent *event) {
if (event->type() == TQEvent::LanguageChange) {
void UiGuiSettingsDialog::changeEvent(TQEvent *event)
{
if (event->type() == TQEvent::LanguageChange)
{
_settingsDialogForm->retranslateUi(this);
// If this is not explicit set here, TQt < 4.3.0 does not translate the buttons.
_settingsDialogForm->buttonBox->setStandardButtons(TQDialogButtonBox::Cancel | TQDialogButtonBox::NoButton|TQDialogButtonBox::Ok);
_settingsDialogForm->buttonBox->setStandardButtons(
TQDialogButtonBox::Cancel | TQDialogButtonBox::NoButton | TQDialogButtonBox::Ok);
//TODO: This has to be removed when the properties for the highlighters can be set.
_settingsDialogForm->groupBoxSyntaxHighlighterProperties->setToolTip( "(Will be implemented soon)" + _settingsDialogForm->groupBoxSyntaxHighlighterProperties->toolTip() );
_settingsDialogForm->groupBoxSyntaxHighlighterProperties->setToolTip(
"(Will be implemented soon)" +
_settingsDialogForm->groupBoxSyntaxHighlighterProperties->toolTip());
TQStringList languageShortList = _settings->getAvailableTranslations();
// Now retranslate every entry in the language selection box.
for (int i = 0; i < languageShortList.size(); i++ ) {
for (int i = 0; i < languageShortList.size(); i++)
{
TQString languageShort = languageShortList.at(i);
// Identify the language mnemonic and set the full name.
if ( languageShort == "en" ) {
if (languageShort == "en")
{
_settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("English"));
}
else if ( languageShort == "fr" ) {
else if (languageShort == "fr")
{
_settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("French"));
}
else if ( languageShort == "de" ) {
else if (languageShort == "de")
{
_settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("German"));
}
else if ( languageShort == "zh_TW" ) {
else if (languageShort == "zh_TW")
{
_settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("Chinese (Taiwan)"));
}
else if ( languageShort == "ja" ) {
else if (languageShort == "ja")
{
_settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("Japanese"));
}
else if ( languageShort == "ru" ) {
else if (languageShort == "ru")
{
_settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("Russian"));
}
else if ( languageShort == "uk" ) {
else if (languageShort == "uk")
{
_settingsDialogForm->languageSelectionComboBox->setItemText(i, tr("Ukrainian"));
}
else {
_settingsDialogForm->languageSelectionComboBox->setItemText( i, tr("Unknown language mnemonic ") + languageShort );
else
{
_settingsDialogForm->languageSelectionComboBox->setItemText(i,
tr("Unknown language mnemonic ") + languageShort);
}
}
}
else {
else
{
TQWidget::changeEvent(event);
}
}

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

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

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

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

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

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

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

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

@ -54,8 +54,8 @@ typedef std::istrstream istringstream;
#include <tclap/ArgTraits.h>
#include <tclap/StandardTraits.h>
namespace TCLAP {
namespace TCLAP
{
/**
* 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
@ -68,16 +68,23 @@ class Arg
/**
* 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
* value.
*/
static char& delimiterRef() { static char delim = ' '; return delim; }
static char& delimiterRef()
{
static char delim = ' ';
return delim;
}
protected:
/**
* The single char flag used to identify the argument.
* 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 v - The visitor checked by the argument. Defaults to NULL.
*/
Arg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
bool valreq,
Visitor* v = NULL );
Arg(const std::string &flag, const std::string &name, const std::string &desc, bool req,
bool valreq, Visitor *v = NULL);
public:
/**
@ -188,52 +191,79 @@ class Arg
/**
* Begin ignoring arguments since the "--" argument was specified.
*/
static void beginIgnoring() { ignoreRestRef() = true; }
static void beginIgnoring()
{
ignoreRestRef() = true;
}
/**
* 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
* value.
*/
static char delimiter() { return delimiterRef(); }
static char delimiter()
{
return delimiterRef();
}
/**
* The char used as a place holder when SwitchArgs are combined.
* 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 '-'.
*/
static char flagStartChar() { return '-'; }
static char flagStartChar()
{
return '-';
}
/**
* The sting that indicates the beginning of a flag. Currently "-".
* 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 "--".
* 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.
*/
static const std::string ignoreNameString() { return "ignore_rest"; }
static const std::string ignoreNameString()
{
return "ignore_rest";
}
/**
* Sets the delimiter for all arguments.
* \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
@ -391,35 +421,44 @@ typedef std::list<Visitor*>::iterator VisitorListIterator;
* specialization of ExtractValue depending on the value traits of T.
* ValueLike traits use operator>> to assign the value from strVal.
*/
template<typename T> void
ExtractValue(T &destVal, const std::string& strVal, ValueLike vl)
template<typename T>
void ExtractValue(T &destVal, const std::string &strVal, ValueLike vl)
{
static_cast<void>(vl); // Avoid warning about unused vl
std::istringstream is(strVal);
int valuesRead = 0;
while ( is.good() ) {
while (is.good())
{
if (is.peek() != EOF)
#ifdef TCLAP_SETBASE_ZERO
{
is >> std::setbase(0) >> destVal;
}
#else
{
is >> destVal;
}
#endif
else
{
break;
}
valuesRead++;
}
if (is.fail())
{
throw (ArgParseException("Couldn't read argument value "
"from string '" + strVal + "'"));
}
if (valuesRead > 1)
{
throw (ArgParseException("More than one valid value parsed from "
"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.
* StringLike uses assignment (operator=) to assign from strVal.
*/
template<typename T> void
ExtractValue(T &destVal, const std::string& strVal, StringLike sl)
template<typename T>
void ExtractValue(T &destVal, const std::string &strVal, StringLike sl)
{
static_cast<void>(sl); // Avoid warning about unused sl
SetString(destVal, strVal);
@ -439,63 +478,62 @@ ExtractValue(T &destVal, const std::string& strVal, StringLike sl)
//BEGIN Arg.cpp
//////////////////////////////////////////////////////////////////////
inline Arg::Arg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
bool valreq,
Visitor* v) :
_flag(flag),
_name(name),
_description(desc),
_required(req),
_requireLabel("required"),
_valueRequired(valreq),
_alreadySet(false),
_visitor( v ),
_ignoreable(true),
_xorSet(false),
_acceptsMultipleValues(false)
inline Arg::Arg(const std::string &flag, const std::string &name, const std::string &desc,
bool req, bool valreq, 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)
{
throw (SpecificationException(
"Argument flag can only be one character long", toString()));
}
if (_name != ignoreNameString() &&
(_flag == Arg::flagStartString() ||
_flag == Arg::nameStartString() ||
_flag == " "))
throw(SpecificationException("Argument flag cannot be either '" +
Arg::flagStartString() + "' or '" +
Arg::nameStartString() + "' or a space.",
toString() ) );
{
throw (SpecificationException("Argument flag cannot be either '" + Arg::flagStartString() +
"' or '" + Arg::nameStartString() + "' or a space.", toString()));
}
if ((_name.substr(0, Arg::flagStartString().length()) == Arg::flagStartString()) ||
(_name.substr(0, Arg::nameStartString().length()) == Arg::nameStartString()) ||
(_name.find(" ", 0) != std::string::npos))
throw(SpecificationException("Argument name begin with either '" +
Arg::flagStartString() + "' or '" +
Arg::nameStartString() + "' or space.",
toString() ) );
{
throw (SpecificationException("Argument name begin with either '" + Arg::flagStartString() +
"' or '" + Arg::nameStartString() + "' or space.", toString()));
}
}
inline Arg::~Arg() { }
inline Arg::~Arg()
{
}
inline std::string Arg::shortID(const std::string &valueId) const
{
std::string id = "";
if (_flag != "")
{
id = Arg::flagStartString() + _flag;
}
else
{
id = Arg::nameStartString() + _name;
}
if (_valueRequired)
{
id += std::string(1, Arg::delimiter()) + "<" + valueId + ">";
}
if (!_required)
{
id = "[" + id + "]";
}
return id;
}
@ -509,7 +547,9 @@ inline std::string Arg::longID( const std::string& valueId ) const
id += Arg::flagStartString() + _flag;
if (_valueRequired)
{
id += std::string(1, Arg::delimiter()) + "<" + valueId + ">";
}
id += ", ";
}
@ -517,25 +557,32 @@ inline std::string Arg::longID( const std::string& valueId ) const
id += Arg::nameStartString() + _name;
if (_valueRequired)
{
id += std::string(1, Arg::delimiter()) + "<" + valueId + ">";
}
return id;
}
inline bool Arg::operator==(const Arg &a) const
{
if ((_flag != "" && _flag == a._flag) || _name == a._name)
{
return true;
}
else
{
return false;
}
}
inline std::string Arg::getDescription() const
{
std::string desc = "";
if (_required)
{
desc = "(" + _requireLabel + ") ";
}
// if ( _valueRequired )
// desc += "(value required) ";
@ -544,23 +591,42 @@ inline std::string Arg::getDescription() const
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
{
if (_alreadySet && !_xorSet)
{
return true;
}
else
{
return false;
}
}
inline bool Arg::isIgnoreable() const { return _ignoreable; }
inline bool Arg::isIgnoreable() const
{
return _ignoreable;
}
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 != "") ||
argFlag == Arg::nameStartString() + _name)
{
return true;
}
else
{
return false;
}
}
inline std::string Arg::toString() const
{
std::string s = "";
if (_flag != "")
{
s += Arg::flagStartString() + _flag + " ";
}
s += "(" + Arg::nameStartString() + _name + ")";
@ -591,8 +663,10 @@ inline std::string Arg::toString() const
inline void Arg::_checkWithVisitor() const
{
if (_visitor != NULL)
{
_visitor->visit();
}
}
/**
* Implementation of trimFlag.
@ -601,18 +675,19 @@ inline void Arg::trimFlag(std::string& flag, std::string& value) const
{
int stop = 0;
for (int i = 0; static_cast<unsigned int>(i) < flag.length(); i++)
{
if (flag[i] == Arg::delimiter())
{
stop = i;
break;
}
}
if (stop > 1)
{
value = flag.substr(stop + 1);
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
{
for (int i = 1; static_cast<unsigned int>(i) < s.length(); i++)
{
if (s[i] == Arg::blankChar())
{
return true;
}
}
return false;
}
@ -665,8 +744,6 @@ inline void Arg::reset()
//////////////////////////////////////////////////////////////////////
//END Arg.cpp
//////////////////////////////////////////////////////////////////////
} //namespace TCLAP
#endif

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

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

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

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

@ -1,5 +1,3 @@
/******************************************************************************
*
* file: CmdLineOutput.h
@ -30,8 +28,8 @@
#include <iomanip>
#include <algorithm>
namespace TCLAP {
namespace TCLAP
{
class CmdLineInterface;
class ArgException;
@ -40,13 +38,13 @@ class ArgException;
*/
class CmdLineOutput
{
public:
/**
* Virtual destructor.
*/
virtual ~CmdLineOutput() {}
virtual ~CmdLineOutput()
{
}
/**
* 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 e - The ArgException that caused the failure.
*/
virtual void failure( CmdLineInterface& c,
ArgException& e )=0;
virtual void failure(CmdLineInterface &c, ArgException &e) = 0;
};
} //namespace TCLAP
#endif

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading…
Cancel
Save